Skip to content

Fixtures Scope and autouse

Scope of Fixtures

By default, a fixture is created and destroyed for every test function that uses it. However, for expensive operations (like spinning up a Docker container or connecting to a database), you can change the scope to cache the fixture instance.

Available Scopes:

  • function (Default): Run once per test function.
  • class: Run once per test class.
  • module: Run once per .py file.
  • package: Run once per directory (Since pytest 7+, __init__.py is not required).
  • session: Run once per the entire test run.
python
# This will only run once for the entire test suite
@pytest.fixture(scope="session")
def expensive_resource():
    resource = start_server()
    yield resource
    resource.shutdown()

autouse

If you want a fixture to run automatically without explicitly requesting it in every test (or decorating every test), set autouse=True.

This is best used for global setup/teardown logic, such as configuring logging or clearing temporary files.

python
@pytest.fixture(autouse=True)
def clean_logs():
    print("Cleaning logs before test...")
    yield
    print("Archiving logs after test...")

def test_something():
    # clean_logs runs automatically here
    assert True