How to Run a Method Before All Tests in All Classes?

Better Stack Team
Updated on July 18, 2024

In pytest, fixtures run setup code before tests across multiple classes or the entire test suite. They help provide reusable test data, manage resources like database connections, and set up test environments.

Fixtures can be scoped to different levels:

  • function: Run once per test function (default)
  • class: Run once per test class
  • module: Run once per module
  • package: Run once per package
  • session: Run once per test session

To run a method before all tests in all classes across the entire test suite, use a session scoped fixture.

Here's an example using SQLite with a session-scoped fixture for database connection:

 
import sqlite3
import pytest


@pytest.fixture(scope="session")
def db_connection():
    # Connect to an in-memory SQLite database
    conn = sqlite3.connect(":memory:")

    # Create a test table
    conn.execute(
        """CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)"""
    )

    # Yield the connection for tests to use
    yield conn

    # Close the connection after all tests are done
    conn.close()


@pytest.fixture(autouse=True)
def reset_table(db_connection):
    # This fixture runs automatically before each test
    db_connection.execute("DELETE FROM users")
    db_connection.commit()


def test_insert_user(db_connection):
    ...

def test_insert_multiple_users(db_connection):
    ...

def test_update_user(db_connection):
    ...

This code uses pytest fixtures to manage an SQLite database connection for testing. The db_connection fixture, scoped to the entire test session, sets up an in-memory database, creates a users table, and then tears it down after all tests are complete.

The reset_table fixture, with autouse=True, runs automatically before each test to ensure a clean state by deleting all entries in the users table. The test functions (test_insert_user, test_insert_multiple_users, and test_update_user) demonstrate basic database operations such as inserting and updating user records and verifying the results.

For a more thorough guide on using fixtures, see the fixtures guide.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github