pytest Fixtures Explained: Scope, Teardown and conftest

How pytest fixtures work: defining and using them, yield teardown, scopes, conftest.py sharing, parametrized fixtures, and the built-in ones worth knowing.

A pytest fixture is a function that prepares something your tests need, and a test requests it just by naming it as an argument. Fixtures replace the setUp and tearDown methods of unittest with something more flexible and reusable.

The basics

import pytest

@pytest.fixture
def user():
    return {"name": "Ada", "active": True}

def test_user_is_active(user):
    assert user["active"]

pytest sees that test_user_is_active has an argument called user, finds the fixture with that name, runs it and passes the return value in. There is no import, no registration and no class.

Teardown with yield

Use yield when the fixture needs cleanup:

import sqlite3
import pytest

@pytest.fixture
def db():
    conn = sqlite3.connect(":memory:")
    conn.execute("CREATE TABLE items (name TEXT)")
    yield conn
    conn.close()

Everything before yield is setup, the yielded value goes to the test, and everything after runs afterwards, even when the test fails. In a run with a test that failed on purpose, the teardown code still ran.

Scope

By default a fixture runs once per test. Widen the scope to share an expensive resource:

@pytest.fixture(scope="session")
def api_client():
    ...
Scope Created
function Once per test (default)
class Once per test class
module Once per test file
package Once per package, including its sub-packages and sub-directories
session Once per test run

Wider scopes are faster but share state, so tests that modify the object can influence each other. Share read-only or reset-able resources, and keep mutable things at function scope. Over two tests, a session-scoped fixture was created once and a function-scoped one twice.

Every example below was run on pytest 9.2.0 and Python 3.13.

Sharing fixtures with conftest.py

Put fixtures used by many files in a conftest.py. pytest finds it automatically, and the fixtures are available to tests in that directory and its subdirectories without imports.

tests/
├── conftest.py        # shared fixtures
├── test_users.py
└── api/
    ├── conftest.py    # fixtures for api tests only
    └── test_routes.py

Fixtures that use fixtures

A fixture can request other fixtures the same way a test does:

@pytest.fixture
def admin(user):
    return {**user, "role": "admin"}

Parametrized fixtures

Give params to run every test that uses the fixture once per value:

@pytest.fixture(params=["sqlite", "postgres"])
def backend(request):
    return request.param

Run with -v, each test using this fixture appeared twice, as test_backend[sqlite] and test_backend[postgres]. For parametrizing a single test, use @pytest.mark.parametrize.

Built-in fixtures worth knowing

  • tmp_path: a temporary directory as a pathlib.Path. See pathlib vs os.path.
  • monkeypatch: set attributes, dictionary items and environment variables for one test, undone automatically.
  • capsys: capture what the code prints.
  • caplog: capture log records; see Loguru vs logging.

autouse

@pytest.fixture(autouse=True) applies a fixture to every test in its scope without being requested. Use it sparingly, for things like resetting global state, because invisible setup makes tests harder to read.

Where to go next

pytest is in our resources. For the wider tool landscape see the best Python testing tools compared, and for testing an API specifically, the best Python IDE for FastAPI includes a TestClient example.

Frequently Asked Questions

What is a pytest fixture?

A fixture is a function decorated with @pytest.fixture that provides setup data or resources to tests. A test asks for a fixture by naming it as an argument, and pytest runs the fixture and passes in the result.

How do I do teardown in a pytest fixture?

Use yield instead of return. Code before the yield is setup, the yielded value goes to the test, and code after the yield runs as teardown even if the test fails.

What are pytest fixture scopes?

function (the default, once per test), class, module, package and session. A wider scope creates the fixture once and shares it, which is faster but means tests can affect each other if they change it.

What is conftest.py?

A special file where you put fixtures that several test files share. pytest discovers conftest.py automatically, and fixtures defined there are available to tests in that directory and below without importing them.

What built-in pytest fixtures should I know?

tmp_path for a temporary directory, monkeypatch for changing attributes and environment variables safely, capsys for capturing printed output, and caplog for capturing log records.