Sub topic 7
Fixtures: reusable setup and teardown
This chapter assumes you can write and run pytest test functions, use plain assert, and read generators (functions that use yield). Fixtures are how pytest shares setup code between tests without copying it.
The problem fixtures solve
Many tests need the same starting state: a list of sample data, a database connection, or a temporary directory. Without a shared mechanism, each test repeats the setup lines, and each one has to remember to clean up. When the setup changes, you edit every test.
A fixture is a function that pytest runs to prepare something a test needs. The test asks for it by name, and pytest passes in the result. Fixtures can also run cleanup after the test finishes.
Defining and requesting a fixture
Decorate a function with @pytest.fixture. To use it, add a parameter with the same name to your test function.
import pytest
from cart import total
@pytest.fixture
def prices():
return [10, 20, 30]
def test_total_of_sample_prices(prices):
assert total(prices) == 60
def test_total_with_tax_of_sample_prices(prices):
assert total(prices, tax_rate=0.5) == pytest.approx(90.0)Pytest does not call test_total_of_sample_prices with a value you supply. It inspects the parameter names, finds a fixture called prices, calls it, and passes the return value as the argument. The test never calls the fixture function itself.
Each test gets its own value
By default, pytest runs a fixture once for every test that requests it. The result is not shared between tests. This is what keeps tests independent.
import pytest
@pytest.fixture
def basket():
return []
def test_add_one_item(basket):
basket.append("apple")
assert basket == ["apple"]
def test_basket_starts_empty(basket):
assert basket == []Both tests pass in any order, because the second test receives a new empty list. If the fixture instead returned a module-level list, the first test would leak state into the second. Wider sharing is possible through fixture scope, which the next chapter covers.
Fixtures that use other fixtures
A fixture can request other fixtures with the same parameter-name rule. Pytest builds the chain of dependencies and runs them in order. This lets you assemble complex state from small pieces.
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_users(db):
db.executemany("INSERT INTO users VALUES (?)", [("ada",), ("grace",)])
return db
def test_two_users_are_loaded(db_with_users):
count = db_with_users.execute("SELECT COUNT(*) FROM users").fetchone()[0]
assert count == 2The test requests only db_with_users. Pytest sees that this fixture needs db, runs db first, and then runs db_with_users. Both receive the same connection object within this one test. A test that only needs an empty table can request db and skip the inserts.
Teardown with yield
Some setup needs cleanup: closing a connection, deleting a file, stopping a server. Write the fixture as a generator. Pytest runs the code up to yield, hands the yielded value to the test, and runs the rest of the function after the test ends.
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 == 1Points about teardown to keep in mind:
- The code after
yieldruns whether the test passed or failed. - A fixture should yield exactly once. A second
yieldis an error. - Teardown runs in reverse order of setup. In the previous example,
db_with_usersis torn down beforedb. - If the code before
yieldraises an exception, the code afteryielddoes not run. Resources you created earlier in that fixture stay open.
For the last case, protect multi-step setup with try and finally, or split it into several smaller fixtures. Each small fixture then cleans up independently.
import pytest
@pytest.fixture
def log_file(tmp_path):
path = tmp_path / "app.log"
handle = path.open("w")
try:
handle.write("start\n")
yield handle
finally:
handle.close()
def test_log_file_is_writable(log_file):
log_file.write("event\n")
log_file.flush()
assert not log_file.closedThis example also requests tmp_path, a built-in fixture that gives each test its own temporary directory. Built-in fixtures are covered in a later chapter. They work exactly like the ones you write.
Returning a value versus yielding one
Choose based on whether cleanup is needed.
| Situation | Use | Example |
|---|---|---|
| Plain data, nothing to release | `return` | A list of sample prices |
| Resource that must be closed or removed | `yield` | A database connection |
| Setup that builds on another fixture | `return` or `yield`, with the other fixture as a parameter | `db_with_users` |
Common errors
| What you see | Likely cause | Fix |
|---|---|---|
| `fixture 'prices' not found` | The parameter name is misspelled, or the fixture is defined in a file the test cannot see | Match the names exactly. Move shared fixtures to a place visible to the test (see the `conftest.py` chapter) |
| `Fixture "prices" called directly` | Test code called `prices()` like a normal function | Request it as a parameter instead |
| The test receives a function object or fails with an odd attribute error | The `@pytest.fixture` decorator is missing, so pytest treats the parameter as unknown | Add the decorator |
| Cleanup never runs | Setup raised before `yield`, or the process was killed | Use `try`/`finally`, or split the fixture |
| Tests pass alone but fail together | A fixture returns a shared mutable object, such as a module-level list | Create the object inside the fixture function |
Seeing which fixtures a test uses
Run pytest --fixtures to list every fixture pytest can see, including built-in ones, with the first line of each docstring. Run pytest --setup-show to print the setup and teardown of each fixture as tests run. The second command is the quickest way to confirm that teardown happens and in what order.
pytest --setup-show test_db.pyA line such as SETUP F db means a function-scoped fixture started, and TEARDOWN F db shows when it finished.
Naming and design tips
- Name a fixture after the thing it provides (
db,prices), not the action (setup_db). Tests then read as a description of what they need. - Keep fixtures small. Prefer several focused fixtures over one that builds everything.
- Put assertions in tests, not in fixtures. A failing assertion in a fixture is reported as an error, not a failure, which makes the report harder to read.
- Do not hide the important input of a test inside a fixture. If the value matters to the assertion, show it in the test body.
Exercise
A fixture opens a temporary connection, yields it, and then closes it. A test using the fixture fails on an assertion. Is the connection closed? Now suppose the fixture raises an exception before reaching yield. Is the code after yield run? How would you make sure an earlier resource still gets released?
Show answer
When the test fails, the connection is still closed, because pytest resumes the fixture after the test regardless of its outcome. When the fixture raises before yield, the code after yield does not run, so anything opened earlier leaks. To prevent this, wrap the setup and yield in try/finally, with the cleanup in finally, or split the work into separate fixtures so each one cleans up its own resource.
Exercise
Write a fixture empty_db that yields an in-memory SQLite connection with a users table, and a second fixture ada_db that depends on it and inserts one row named ada. Which fixture does a test request to get a database containing ada, and why do you not need to request both?
Show answer
The test requests ada_db. Pytest sees that ada_db has a parameter named empty_db, so it runs empty_db first and passes its connection in. The test receives the connection that ada_db returns, and empty_db is torn down after the test ends. For example: @pytest.fixture / def empty_db(): create the connection and table, yield conn, then conn.close(). Then @pytest.fixture / def ada_db(empty_db): run empty_db.execute("INSERT INTO users VALUES ('ada')") and return empty_db.