pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories
Fixtures are how pytest prepares what a test needs and cleans up afterwards. Learn how they are found, how scope changes when they run, and the patterns that keep a growing suite fast and isolated.
- A fixture is a function marked with
@pytest.fixturethat a test requests by naming it as a parameter. - Code after
yieldis teardown, and it runs even when the test fails. - Scope controls reuse: function (default), class, module, package or session.
- Put shared fixtures in
conftest.py, and use--setup-showto see exactly when each one runs.
Every test needs some setup: a database connection, a logged-in user, a temporary folder. Copying that setup into each test makes a suite long and fragile. pytest fixtures solve this with a simple idea. You write the setup once as a function, and any test that names it as a parameter receives the result.
We built a small suite and ran it with pytest 9.2 on Python 3.13. All outputs below come from that run. If pytest itself is new to you, start with our pytest tutorial.
What is a fixture?
A fixture provides a known, consistent starting point for a test. In pytest, it is a function decorated with @pytest.fixture. When pytest sees a test with a parameter called db, it looks for a fixture with that name, runs it, and passes in the value. This is a form of dependency injection, and fixtures can themselves request other fixtures.
Your first fixture
import pytest, sqlite3
@pytest.fixture
def db():
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users (name TEXT)")
return conn
def test_isolated(db):
assert db.execute("SELECT COUNT(*) FROM users").fetchone()[0] == 0
The test never calls db() itself. pytest does that, and by default it creates a fresh value for every test function, so one test’s data cannot leak into another.
Teardown with yield
Most resources need cleaning up. Replace return with yield, and everything after it becomes teardown:
@pytest.fixture
def db(db_engine):
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users (name TEXT)")
print("[setup] fresh db")
yield conn
conn.close()
print("[teardown] closed db")
We added a test that fails on purpose, assert 1 == 2, and ran the suite with -s to show the prints. The output for that test was:
[setup] fresh db
F
[teardown] closed db
The connection was closed even though the test failed. That guarantee is why yield fixtures are better than putting cleanup at the end of the test body, where a failing assert would skip it. If setup raises an exception before reaching yield, the teardown does not run, so keep setup steps small or nest fixtures so each one cleans up its own resource.
Fixture scope
Some setup is expensive, such as starting a browser, creating a database schema or launching a container. Scope lets pytest reuse one fixture value across many tests:
| Scope | Created once per | Typical use |
|---|---|---|
function (default) |
Test | Anything tests might change |
class |
Test class | Shared state within a class |
module |
Test file | A file’s worth of related tests |
package |
Test package | A folder of tests |
session |
Whole test run | Expensive, read-only resources |
@pytest.fixture(scope="session")
def db_engine():
print("[setup] session engine")
yield "engine"
print("[teardown] session engine")
In our run, “session engine” was set up once at the start and torn down once at the very end, while the function-scoped db was created and closed around each test. One rule applies: a fixture can only request fixtures of the same or a wider scope. A session fixture cannot use a function fixture, because the function fixture would be gone before the session ends.
Tip: Wide scopes make suites faster but risk shared state. If a session-scoped object can be changed by tests, one test can break another, and failures will depend on test order. That is a common cause of flaky tests. Keep wide-scoped fixtures read-only, or reset them between tests.
Watching fixtures run
The --setup-show option prints each fixture’s setup and teardown. For two of our tests it showed:
SETUP S db_engine
SETUP F db (fixtures used: db_engine)
SETUP F make_user (fixtures used: db)
tests/test_users.py::test_add_user (fixtures used: db, db_engine, make_user) .
TEARDOWN F make_user
TEARDOWN F db
SETUP F db (fixtures used: db_engine)
tests/test_users.py::test_isolated (fixtures used: db, db_engine) .
TEARDOWN F db
TEARDOWN S db_engine
S marks session scope and F marks function scope. You can see the dependency chain, the reverse order of teardown, and the fresh db for each test. When a suite behaves strangely, this is the first view to check.
Sharing fixtures with conftest.py
Fixtures defined in a test file are available only in that file. Move them into a file named conftest.py, and every test in that folder and its subfolders can use them without importing anything. pytest discovers the file automatically.
tests/
conftest.py # db_engine, db, make_user
test_users.py
api/
conftest.py # fixtures only for API tests
test_orders.py
A nested conftest.py can add fixtures for its folder or override a parent fixture with the same name. Run pytest --fixtures to list every fixture available and where it is defined. In our project it listed db, db_engine and make_user from tests\conftest.py, alongside the built-ins.
Factory fixtures
Sometimes a test needs several users, or users with different data. Instead of one fixture per variation, return a function:
@pytest.fixture
def make_user(db):
def _make(name="Asha"):
db.execute("INSERT INTO users VALUES (?)", (name,))
return name
return _make
def test_add_user(db, make_user):
make_user("Ben")
assert db.execute("SELECT COUNT(*) FROM users").fetchone()[0] == 1
The test decides how many records it needs and with what values, while the fixture still owns the details of creating them. Factories keep test data next to the test that depends on it, which makes failures easier to understand.
Parametrized fixtures
@pytest.fixture(params=["sqlite", "postgres"])
def backend(request):
return request.param
def test_backend(backend):
assert backend in {"sqlite", "postgres"}
Every test that uses backend runs once per parameter, so this one test counted as two passes in our results. In a real suite, the fixture would create a connection for each database, letting the same tests check both. Use @pytest.mark.parametrize on the test instead when only the input data changes.
Built-in fixtures
| Fixture | What it gives you |
|---|---|
tmp_path |
A unique temporary folder as a pathlib.Path |
monkeypatch |
Safe, auto-undone changes to environment variables, attributes and dicts |
capsys |
Captured stdout and stderr |
caplog |
Captured log records |
request |
Information about the requesting test, including parameters |
def test_tmp_path(tmp_path):
f = tmp_path / "report.txt"
f.write_text("ok")
assert f.read_text() == "ok"
def test_env(monkeypatch):
monkeypatch.setenv("APP_MODE", "test")
assert os.environ["APP_MODE"] == "test"
Both passed, and pytest cleaned up the folder and restored the environment afterwards. monkeypatch pairs well with our guides to environment variables and mocking in Python.
Errors and debugging
A misspelt fixture name is reported as an error at setup, not a test failure:
def test_typo(dbb):
pass
E fixture 'dbb' not found
> available fixtures: backend, capfd, ..., db, db_engine, ..., make_user, monkeypatch, ...
pytest helpfully lists every available name. Our final summary read 1 failed, 6 passed, 1 error: the deliberate assertion failure, six passing tests (including both backend runs), and the missing-fixture error.
Best practices
- Name fixtures after what they provide, such as
admin_userorempty_cart, notsetup1. - Keep each fixture small and compose them, rather than one giant fixture that sets up everything.
- Default to function scope and widen only for measured, expensive setup.
- Always clean up with
yield, even for things you think are harmless. - Use
autouse=Truesparingly. Fixtures that run invisibly make tests harder to understand. - Avoid hidden data. If a test’s assertion depends on a value, it should be visible in the test or passed to a factory.
Fixtures vs setUp and tearDown methods
If you come from unittest, JUnit or NUnit, you know setup and teardown methods that run around every test in a class. pytest still supports that style, but fixtures have clear advantages:
| setUp / tearDown | pytest fixtures | |
|---|---|---|
| What runs | Everything in setUp, for every test | Only the fixtures a test asks for |
| Sharing | Through class inheritance | By name, through conftest.py |
| Reuse across scopes | Separate class-level methods | One scope argument |
| Composition | Hard to mix and match | Fixtures request other fixtures |
| Visibility | Hidden in the class | Listed in the test’s parameters |
The biggest win is explicitness. Reading def test_checkout(logged_in_user, cart_with_items) tells you exactly what state the test starts from. With a setUp method, you have to scroll up and read it to find out, and every test pays for every step, even ones it does not need.
Two smaller tools are worth knowing. @pytest.mark.usefixtures("clean_cache") applies a fixture to a test or class when the test does not need its return value. And request.addfinalizer(func) registers cleanup from inside a fixture, which is useful when a fixture creates several resources and needs to register cleanup for each one as it goes.
Final thoughts
Fixtures turn repeated setup into small, named, reusable building blocks. Start with function-scoped yield fixtures in conftest.py, add factories when tests need varied data, and widen scope only where speed demands it. When in doubt, run --setup-show and watch what really happens.
Frequently asked questions
What is a fixture in pytest?
A fixture is a function decorated with @pytest.fixture that prepares something a test needs. A test requests it by using the fixture’s name as a parameter.
What is the default fixture scope?
Function scope. A new value is created for each test. Other scopes are class, module, package and session.
Does teardown run if a test fails?
Yes. Code after yield in a fixture runs even when the test fails. In our run, the database was closed after a failing test.
What is conftest.py used for?
It holds fixtures and hooks shared by all tests in its folder and subfolders. pytest loads it automatically, so no import is needed.
How do I see which fixtures a test uses?
Run pytest with –setup-show to see setup and teardown order, or pytest –fixtures to list all available fixtures.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.