Sub topic 7
Fixtures: reusable setup and teardown
This chapter assumes you can write and run pytest test functions, use plain assert, and read pytest's output. It also assumes you know what a Python generator is.
What a fixture is
A fixture is a function that prepares something a test needs, such as a database connection, a temporary file, or a configured object. You mark it with @pytest.fixture. A test asks for it by naming it as a parameter. pytest sees the name, runs the fixture, and passes the result into the test.
This replaces copied setup lines at the top of every test. It also keeps setup and cleanup in one place.
A fixture with teardown
import sqlite3
import pytest
@pytest.fixture
def db():
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users (name TEXT)")
yield conn
conn.close()
def test_insert_user(db):
db.execute("INSERT INTO users VALUES ('ada')")
count = db.execute("SELECT COUNT(*) FROM users").fetchone()[0]
assert count == 1The code before yield is setup. The value after yield is what the test receives. The code after yield is teardown, and it runs once the test finishes. If the test fails, teardown still runs. Each test that requests db gets its own fresh in-memory database, so tests cannot affect each other.
If a fixture does not need cleanup, use return instead of yield.
How pytest runs it
Fixtures can use other fixtures
A fixture can request another fixture the same way a test does. This lets you build setup in layers.
import sqlite3
import pytest
@pytest.fixture
def db():
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users (name TEXT)")
yield conn
conn.close()
@pytest.fixture
def db_with_ada(db):
db.execute("INSERT INTO users VALUES ('ada')")
return db
def test_ada_exists(db_with_ada):
row = db_with_ada.execute("SELECT name FROM users").fetchone()
assert row == ("ada",)pytest sets up db first, then db_with_ada. Teardown runs in the reverse order.
Common errors
- Calling a fixture directly. Writing
db()in a test raises an error. Request it as a parameter instead. - Forgetting the decorator. Without
@pytest.fixture, pytest treats the name as an ordinary missing argument and reportsfixture 'db' not found. - Code after
yieldthat depends on a failed setup. If setup raises beforeyield, teardown does not run. Keep setup short, or register cleanup early. - Shared mutable state. By default a fixture runs once per test, which avoids this. Widening that lifetime is covered in the next chapter.
Exercise
Exercise
A test named test_save uses the fixture db. The test fails with an assertion error. Does the code after yield in db still run, and why does that matter?
Show answer
Yes. pytest resumes the fixture after the test whether it passed or failed, so the connection is still closed. This matters because a failing test cannot leak open resources or leave state behind that breaks later tests.
Exercise
Write a fixture named numbers that returns the list [1, 2, 3], and a test that checks its sum is 6.
Show answer
import pytest @pytest.fixture def numbers(): return [1, 2, 3] def test_sum(numbers): assert sum(numbers) == 6