Skip to content

pytest Fixtures: Setup, Teardown and Scope

  • How pytest finds a fixture by parameter name, runs its setup, and runs the code after yield as teardown.
  • How scopes (function, class, module, package, session) decide how often a fixture is built, and in what order setup and teardown happen.
  • How conftest.py, autouse=True and fixture overriding control where a fixture is visible.
  • Factory fixtures, parametrized fixtures (params=), and the built-ins you use every day: tmp_path, tmp_path_factory, monkeypatch, request.
  • How to keep tests isolated when a fixture is shared, using a database rollback as the example.

A fixture is a function decorated with @pytest.fixture. A test (or another fixture) requests it by naming it as a parameter; pytest calls the fixture, injects its return or yield value, and after the test runs any code that follows the yield. The scope argument controls how long the value is cached and shared. Fixtures are pytest’s dependency injection system and are current in pytest 9.2.0 (the latest release at the time of writing).

Without fixtures, setup is copied into each test and cleanup sits at the end of the test body, where a failed assertion skips it. The samples on this page are pytest modules: install pytest into a virtual environment, save the files in one folder and run pytest -v. They were run with pytest 9.2.0 on CPython 3.14.6; header lines and absolute paths are trimmed from the output.

OrdersPortal’s order repository is a thin wrapper over sqlite3:

orders_repo.py
import os
import sqlite3
class OrderRepository:
def __init__(self, conn: sqlite3.Connection):
self.conn = conn
def create_schema(self) -> None:
self.conn.execute(
"CREATE TABLE orders (id TEXT PRIMARY KEY, customer_id TEXT NOT NULL,"
" total_cents INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'pending')"
)
def add(self, order_id: str, customer_id: str, total_cents: int, status: str = "pending") -> None:
self.conn.execute(
"INSERT INTO orders (id, customer_id, total_cents, status) VALUES (?, ?, ?, ?)",
(order_id, customer_id, total_cents, status),
)
def status(self, order_id: str) -> str:
return self.conn.execute("SELECT status FROM orders WHERE id = ?", (order_id,)).fetchone()[0]
def paid_total(self, customer_id: str) -> int:
row = self.conn.execute(
"SELECT COALESCE(SUM(total_cents), 0) FROM orders WHERE customer_id = ? AND status = 'paid'",
(customer_id,),
).fetchone()
return row[0]
def count(self) -> int:
return self.conn.execute("SELECT COUNT(*) FROM orders").fetchone()[0]
def format_cents(cents: int) -> str:
currency = os.environ.get("ORDERSPORTAL_CURRENCY", "USD")
return f"{cents / 100:.2f} {currency}"
test_before.py
import os
import sqlite3
from orders_repo import OrderRepository
DB_FILE = "orders-test.db"
def test_paid_total():
conn = sqlite3.connect(DB_FILE) # setup, copied into every test
repo = OrderRepository(conn)
repo.create_schema()
repo.add("ORD-1", "C-7", 1500, status="paid")
repo.add("ORD-2", "C-7", 999)
assert repo.paid_total("C-7") == 2499 # wrong expectation: the test fails here...
conn.close() # ...so this cleanup never runs
os.remove(DB_FILE)

Running it twice:

--- run 1
E AssertionError: assert 1500 == 2499
1 failed in 0.01s
--- run 2
E sqlite3.OperationalError: table orders already exists
1 failed in 0.00s

The second run fails for a different reason: the database file leaked by run 1 breaks setup. Every later run now depends on what earlier tests left behind. Fixtures move setup into one place and guarantee teardown.

  • Request by name. def test_x(repo): asks for the fixture named repo. pytest resolves it before the test runs; a missing name is an error listing the available fixtures (pytest --fixtures prints them too). Fixtures are not meant to be called directly; doing so raises an error.
  • Return or yield. A fixture that returns a value has no teardown. With yield, everything after the yield runs after the test, whether it passed or failed. If the fixture raises before its yield, its teardown does not run. request.addfinalizer(fn) is the older alternative that registers teardown callbacks.
  • Fixtures request fixtures. Dependencies form a graph; each fixture is set up once per scope and torn down in reverse order (last set up, first torn down).
  • Scope sets the cache lifetime: function (default, one per test), class, module, package (the package where the fixture is defined, including sub-packages) and session (once per run). A fixture can only request fixtures of the same or a wider scope. scope= also accepts a callable for dynamic scope.
  • Order. Within one test, higher-scoped fixtures are set up first, then autouse fixtures within each scope, then the requested fixtures in dependency order.
  • Visibility. Fixtures defined in a test module are visible there; fixtures in a conftest.py are visible to every test in that directory and below, without imports. A fixture with the same name closer to the test overrides the outer one, and can request the outer one by that same name to extend it.
  • autouse=True applies the fixture to every test that can see it, without being requested.

--setup-show prints the lifecycle:

test_lifecycle.py
import pytest
@pytest.fixture(scope="module")
def catalog():
# Built once for the whole module, torn down after its last test.
yield {"SKU-1": 9.50, "SKU-2": 20.00}
@pytest.fixture
def cart(catalog): # a fixture can request other fixtures
items = []
yield items
items.clear() # teardown: runs after each test, pass or fail
@pytest.fixture(autouse=True)
def audit_log(): # used by every test in this module without being requested
events = []
yield events
def test_add_item(cart, catalog):
cart.append("SKU-1")
assert sum(catalog[sku] for sku in cart) == 9.50
def test_empty_cart(cart):
assert cart == []
$ pytest --setup-show test_lifecycle.py
test_lifecycle.py
SETUP M catalog
SETUP F audit_log
SETUP F cart (fixtures used: catalog)
test_lifecycle.py::test_add_item (fixtures used: audit_log, cart, catalog) .
TEARDOWN F cart
TEARDOWN F audit_log
SETUP F audit_log
SETUP F cart (fixtures used: catalog)
test_lifecycle.py::test_empty_cart (fixtures used: audit_log, cart, catalog) .
TEARDOWN F cart
TEARDOWN F audit_log
TEARDOWN M catalog
============================== 2 passed in 0.01s ===============================

M and F mark module and function scope: catalog is built once and outlives both tests, while cart and audit_log are rebuilt per test.

OrdersPortal’s test suite puts its fixtures in conftest.py. The schema is created once per run in a pytest-managed temporary directory; each test gets its own connection and its writes are rolled back; a factory fixture creates exactly the orders a test needs; and a parametrized fixture runs currency-dependent tests once per currency.

conftest.py
import itertools
import sqlite3
import pytest
from orders_repo import OrderRepository
@pytest.fixture(scope="session")
def db_path(tmp_path_factory):
"""Create the schema once per test run in a pytest-managed temp directory."""
path = tmp_path_factory.mktemp("orders") / "orders.db"
conn = sqlite3.connect(path)
OrderRepository(conn).create_schema()
conn.commit()
conn.close()
return path
@pytest.fixture
def repo(db_path):
"""One connection per test; everything the test writes is rolled back."""
conn = sqlite3.connect(db_path)
yield OrderRepository(conn)
conn.rollback()
conn.close()
@pytest.fixture
def make_order(repo):
"""Factory fixture: tests create exactly the rows they need."""
ids = itertools.count(1)
def _make(customer_id="C-1", total_cents=1000, status="pending"):
order_id = f"ORD-{next(ids):04d}"
repo.add(order_id, customer_id, total_cents, status)
return order_id
return _make
@pytest.fixture(params=["USD", "EUR"])
def currency(request, monkeypatch):
"""Parametrized fixture: every test that uses it runs once per currency."""
monkeypatch.setenv("ORDERSPORTAL_CURRENCY", request.param)
return request.param
test_orders.py
from orders_repo import format_cents
def test_new_orders_start_pending(repo, make_order):
order_id = make_order()
assert repo.status(order_id) == "pending"
def test_paid_total_ignores_unpaid_and_other_customers(repo, make_order):
make_order("C-7", 1500, status="paid")
make_order("C-7", 999)
make_order("C-8", 5000, status="paid")
assert repo.paid_total("C-7") == 1500
def test_each_test_starts_empty(repo):
assert repo.count() == 0 # rows from earlier tests were rolled back
def test_format_cents(currency):
assert format_cents(1999) == f"19.99 {currency}"
$ pytest -v
test_orders.py::test_new_orders_start_pending PASSED [ 20%]
test_orders.py::test_paid_total_ignores_unpaid_and_other_customers PASSED [ 40%]
test_orders.py::test_each_test_starts_empty PASSED [ 60%]
test_orders.py::test_format_cents[USD] PASSED [ 80%]
test_orders.py::test_format_cents[EUR] PASSED [100%]
============================== 5 passed in 0.04s ===============================

The design choices:

  • Expensive, immutable setup is session-scoped; mutable state is function-scoped. The schema is shared, but every test gets a fresh connection and a rollback, which is why test_each_test_starts_empty passes regardless of order. sqlite3 opens a transaction implicitly before the INSERTs, so rollback() discards them.
  • tmp_path_factory is the session-scoped sibling of tmp_path; pytest keeps the directories of the last 3 runs by default.
  • The factory fixture returns a function, so a test creates the orders it needs while the fixture owns the connection and ID scheme.
  • monkeypatch.setenv changes the environment only for that test and restores it at teardown. For replacing functions and objects, see unittest.mock.patch, which compares the two.
  • params= multiplies every test that requests currency. To pass values from a single test into a fixture instead, use indirect=True on pytest parametrize.
  • Mutable state in a wide scope. A session-scoped list or connection that tests write to makes results depend on test order. Share only what is read-only, or reset it per test with a function-scoped wrapper.
  • Teardown that needs setup to succeed. If a fixture raises before yield, its teardown is skipped. Acquire one resource per fixture so each has its own teardown.
  • Calling a fixture function directly. db_path() in a test raises an error; request it as a parameter.
  • Hidden behavior through autouse. An autouse fixture in a top-level conftest.py silently affects every test. Reserve it for cross-cutting needs such as blocking network access.
  • Scope mismatch. A session-scoped fixture cannot request the function-scoped monkeypatch or tmp_path; pytest reports a ScopeMismatch error. Use tmp_path_factory or pytest.MonkeyPatch.context() instead.
  • Fixtures as instance methods in a class. Since pytest 9.1 a class-scoped fixture defined as an instance method warns (9.2 extends this to module, package and session scope), because it sets attributes on a different instance than the tests use. Use @classmethod or a module-level fixture.
Need Use
Setup and cleanup shared by several tests A yield fixture
Expensive read-only resource (schema, compiled config, test server) scope="module" or "session"
Tests need several objects with different data Factory fixture returning a function
Run every dependent test against each variant @pytest.fixture(params=[...])
Temporary files, environment variables, output capture Built-ins: tmp_path, monkeypatch, capsys, caplog
A one-off value used by one test A local variable; a fixture adds indirection for nothing
Inputs and expected outputs for one behavior @pytest.mark.parametrize, not a fixture per case

Fixtures, yield teardown, conftest.py and the five scopes are long-standing pytest features and current in 9.2.0. Recent changes: pytest 9.1 deprecated class-scoped fixtures defined as instance methods and calling request.getfixturevalue() during teardown for a fixture not already requested; pytest 9.2 extended the instance-method deprecation to wider scopes and scheduled the old yield_fixture decorator for removal. pytest 9 requires Python 3.10 or later.

1. What happens to a yield fixture’s teardown when the test fails? And when the fixture itself fails before yield? When the test fails, teardown still runs, like a finally block. When the fixture raises before yield, there is nothing to tear down from pytest’s point of view and the code after yield is skipped, so partial setup must clean up after itself or be split into separate fixtures.

2. Why can a function-scoped fixture use a session-scoped one, but not the other way round? A wider-scoped value outlives the narrower one. If a session fixture held a function-scoped value, it would keep using it after that value’s teardown. pytest rejects this with a ScopeMismatch error.

3. How does pytest decide which db fixture a test gets when several are defined? It searches outward from the test: the test class, the test module, then conftest.py files from the test’s directory up to the root, then plugins. The closest definition wins, and an overriding fixture may request the outer one by the same name to extend it.

4. Senior scenario: OrdersPortal’s integration suite takes 25 minutes because every test creates a PostgreSQL schema, and tests became flaky when someone made the schema fixture session-scoped. How do you make it fast and reliable? Separate what is expensive and immutable from what each test mutates. Create the database and run migrations once in a session-scoped fixture (one database per pytest-xdist worker if you run in parallel). Give each test a function-scoped connection inside a transaction, or a savepoint, that is rolled back at teardown, and make the application code under test use that connection. Data comes from factory fixtures, never from rows another test left behind. Run the suite in random order in CI to prove isolation, and keep a small number of tests that really commit for code paths that depend on commit behavior.

  • Tests request fixtures by parameter name; pytest builds the dependency graph and runs teardown in reverse order.
  • Put cleanup after yield; it runs even when the test fails, but not when the fixture fails before yield.
  • Choose the narrowest scope that is fast enough; share only read-only state across tests.
  • conftest.py shares fixtures by directory; closer definitions override outer ones.
  • Factory fixtures, params=, tmp_path and monkeypatch cover most real setup needs.