pytest fixtures explained: scope, yield, conftest.py and factories
How pytest fixtures work: requesting them, scopes, yield teardown, conftest.py, parametrized and autouse fixtures, and factory fixtures, with real examples.
Almost every test needs some setup: a cart with products in it, a customer, a database row, a temporary file. Write that setup into each test and it gets copied twenty times, and changed in nineteen. Fixtures are pytest's answer, and they're the feature that makes pytest suites scale.
A fixture is a function that prepares something
import pytest
from shop import Catalog
@pytest.fixture
def catalog():
c = Catalog()
c.add("HOSE-25", "Garden hose", 2499, stock=4)
c.add("POT-2", "Clay pot", 899, stock=0)
return c
def test_out_of_stock(catalog):
assert catalog.in_stock("POT-2") is FalseThe test asks for catalog by naming it as a parameter. Before the test runs, pytest finds
the fixture with that name, calls it, and passes in what it returned. This is dependency
injection: the test declares what it needs, pytest provides it. Never call a fixture yourself:
catalog() inside a test is an error.
By default the fixture runs once for every test that uses it, so every test gets its own fresh catalogue. One test reserving stock can't affect another.
Scope: how long a fixture lives
Some setup is expensive. scope controls how often it runs:
| Scope | Created |
|---|---|
"function" (default) | once per test |
"class" | once per test class |
"module" | once per test file |
"package" | once per package |
"session" | once for the whole run |
The usual pattern combines two fixtures: a wide-scoped one for the expensive, shared resource, and a narrow one that gives each test its own piece of it.
@pytest.fixture(scope="module")
def db():
return connect() # once per file
@pytest.fixture
def basket(db):
return db.new_basket() # fresh for every testA fixture can only use fixtures of the same or wider scope. A module-scoped fixture that asks
for the function-scoped tmp_path gets a ScopeMismatch error; use tmp_path_factory (session
scoped) there instead.
Setup and teardown with yield
When something must be cleaned up, use yield instead of return:
@pytest.fixture
def printer():
p = LabelPrinter()
p.connect() # setup
yield p # the test runs here
p.close() # teardown, even if the test failedpytest runs the code after yield when the test finishes, whatever its outcome. With several
fixtures, teardown runs in reverse order of setup. If setup itself fails, the test is reported as
an error and the teardown is skipped, because nothing was opened.
Fixtures that use fixtures
Fixtures can ask for other fixtures, so test data can be built in layers:
@pytest.fixture
def member():
return make_customer("Ada", member=True)
@pytest.fixture
def member_cart(member):
return make_cart(member)A test asking for member_cart gets the whole chain, and if it also asks for member it gets
the same object that's inside the cart.
Sharing fixtures with conftest.py
Fixtures defined in a test file are only visible there. Put shared ones in a file called
conftest.py:
tests/
├── conftest.py <- fixtures here
├── test_search.py <- are available here
└── test_basket.py <- and here, without importing anythingpytest loads every conftest.py automatically. Deeper ones add fixtures for their folder, and a
fixture with the same name in a deeper conftest.py (or in the test file) overrides the outer
one.
Parametrized fixtures
A fixture with params runs once per value, and every test using it runs once per value too:
@pytest.fixture(params=["card", "ideal", "paypal"])
def method(request):
return request.param
def test_fee_is_never_negative(method):
assert payment_fee(method, 2000) >= 0 # runs three timesUse it when many tests should run against every variant of something.
autouse fixtures
autouse=True runs a fixture for every test in its scope without being asked for. Keep it for
housekeeping, like resetting global state:
@pytest.fixture(autouse=True)
def clean_audit_log():
fees.AUDIT.clear()
yield
fees.AUDIT.clear()Factory fixtures
When tests need several objects, or each needs a slightly different one, return a function:
@pytest.fixture
def make_order():
def _make(*, items=None, member=False, region="mainland"):
return {"items": items or [item(6000)], "member": member, "region": region}
return _make
def test_remote_regions_dont_ship_free(make_order):
assert free_shipping(make_order(region="remote")) is FalseEach test mentions only the detail it's about; the defaults describe a normal case.
Common fixture mistakes
- Sharing mutable state: a module-level object instead of a fixture makes tests depend on their order. Create objects in function-scoped fixtures.
- Too wide a scope: a session-scoped list that tests append to leaks between them.
- One giant fixture that builds everything for everyone: compose small, named fixtures instead.
- Fixture not found: a typo, or a fixture in a file the test can't see. The error lists every available fixture.
Practise it
The Mastering pytest course has a whole module on fixtures, where
your fixtures are checked for real: a module-scoped "database" must connect exactly once, and a
yield fixture must leave no printer connection open.
Questions and answers
- What is a fixture in pytest?
- A function decorated with @pytest.fixture that prepares something a test needs: an object, test data, a temporary file, a connection. A test asks for it by naming it as a parameter, and pytest runs the fixture and passes in its result.
- What's the difference between fixture scopes?
- Scope sets how long a fixture's result lives: function (the default) creates it for every test, class once per test class, module once per file, package once per folder and session once per run. Wider scopes are faster but shared between tests.
- When should I use yield in a fixture?
- When something must be cleaned up after the test: closing a connection, deleting a file, resetting global state. Code before yield is setup, code after it is teardown, and pytest runs the teardown even when the test fails.
- Where do I put fixtures shared by several test files?
- In a conftest.py file in the same folder or a parent folder. pytest loads it automatically, and its fixtures are available to every test below it without an import.
Practise it
Read next
- Testing with pytest: run, read and write Python tests
How to run pytest, read a failing test, select tests with markers and -k, share setup with fixtures, cover many cases with parametrize, and test exceptions.
- Mocking in pytest: Mock, patch and monkeypatch explained
Test code that calls payment providers, email, the clock or randomness: Mock, MagicMock, side_effect, where to patch, monkeypatch, and when not to mock.
- Learn pytest by catching real bugs: a hands-on course
Learn pytest from your first assert to fixtures, mocking and a full shop test suite. Real pytest runs in your browser, and your tests must catch planted bugs.