Sub topic 8
Fixture scope and cleanup with yield
This chapter assumes you can write a basic fixture and request it by naming it as a test argument. It also assumes you can run pytest from a terminal. It covers how long a fixture's value lives, how to share an expensive resource across tests, and how to release resources reliably.
Why scope matters
By default pytest builds a fixture again for every test that requests it. That isolates tests well, but it is wasteful when setup is slow, for example when it starts a database server or loads a large file. The scope argument of @pytest.fixture controls how many tests share one instance.
| Scope | Created once per | Typical use |
|---|---|---|
| `function` (default) | test function | Fresh data, temporary state |
| `class` | test class | Setup shared by methods of one class |
| `module` | test file | A connection or parsed file used by one file |
| `package` | package directory | Resources shared by a test sub-package |
| `session` | whole pytest run | Servers, compiled assets, expensive clients |
A fixture is created lazily, the first time a test asks for it. It is torn down when the last test in its scope has finished. A module-scoped fixture that no test in a file requests is never built for that file.
Choosing a scope
Prefer the narrowest scope that keeps the suite fast enough. Each step wider trades isolation for speed. A shared fixture is only safe if tests cannot change it in a way that other tests notice.
import sqlite3
import pytest
@pytest.fixture(scope="module")
def conn():
connection = sqlite3.connect(":memory:")
connection.execute("CREATE TABLE users (name TEXT)")
yield connection
connection.close()
def test_insert_first(conn):
conn.execute("INSERT INTO users VALUES ('ada')")
assert conn.execute("SELECT COUNT(*) FROM users").fetchone()[0] == 1
def test_insert_second(conn):
conn.execute("INSERT INTO users VALUES ('grace')")
assert conn.execute("SELECT COUNT(*) FROM users").fetchone()[0] == 1The second test fails. It sees two rows, because the connection and its table survive from the first test. The failure also depends on test order. If you run only test_insert_second, it passes.
This is the main hazard of wide scopes: state leaks between tests. Two fixes work. Keep the shared resource immutable, or share only the expensive part and reset the mutable part per test, as described next.
Layering a cheap fixture on an expensive one
Share the connection at module scope. Add a function-scoped fixture that empties the table after each test.
import sqlite3
import pytest
@pytest.fixture(scope="module")
def conn():
connection = sqlite3.connect(":memory:")
connection.execute("CREATE TABLE users (name TEXT)")
yield connection
connection.close()
@pytest.fixture
def db(conn):
yield conn
conn.execute("DELETE FROM users")
def test_insert_first(db):
db.execute("INSERT INTO users VALUES ('ada')")
assert db.execute("SELECT COUNT(*) FROM users").fetchone()[0] == 1
def test_insert_second(db):
db.execute("INSERT INTO users VALUES ('grace')")
assert db.execute("SELECT COUNT(*) FROM users").fetchone()[0] == 1Both tests now pass in any order. The table is created once, and the rows are cleared after every test.
The scope rule
A fixture can only depend on fixtures with the same scope or a wider one. A wide fixture that depended on a narrow one would outlive its dependency. pytest rejects this with an error.
import pytest
@pytest.fixture
def user_name():
return "ada"
@pytest.fixture(scope="module")
def greeting(user_name):
return f"hello {user_name}"
def test_greeting(greeting):
assert greeting == "hello ada"This test errors with ScopeMismatch, because the module-scoped greeting requested the function-scoped user_name. Either widen user_name to module scope or narrow greeting.
Cleanup with yield
A fixture that contains yield is a generator fixture. pytest runs the code before yield as setup and passes the yielded value to the test. After the test finishes, it resumes the generator and runs the code after yield as teardown.
- Teardown runs whether the test passed, failed, or raised an exception.
- If you do not need to pass a value, a bare
yieldis fine. - Write exactly one
yield. - The teardown runs at the end of the fixture's scope, not at the end of each test that used it.
Teardown order
Teardown runs in the reverse order of setup. If second depends on first, then second is torn down before first. This is the order you need, because second may still use first while cleaning up.
import pytest
events = []
@pytest.fixture
def first():
events.append("setup first")
yield
events.append("teardown first")
@pytest.fixture
def second(first):
events.append("setup second")
yield
events.append("teardown second")
def test_order(second):
events.append("test")
def test_events_recorded():
assert events == [
"setup first",
"setup second",
"test",
"teardown second",
"teardown first",
]The second test relies on file order, which is acceptable for a demonstration but not for real tests.
When setup itself fails
If code before the yield raises, the generator never reaches the yield. Its own teardown code does not run, and the test errors. Fixtures that were already set up successfully are still torn down.
This matters when one fixture acquires several resources. If the second acquisition fails, the first leaks. Wrap the acquisitions so each is released:
import pytest
@pytest.fixture
def two_files(tmp_path):
first = open(tmp_path / "a.txt", "w")
try:
second = open(tmp_path / "b.txt", "w")
except OSError:
first.close()
raise
yield first, second
second.close()
first.close()
def test_write_both(two_files):
first, second = two_files
first.write("a")
second.write("b")
assert not first.closedAn alternative is request.addfinalizer. It registers a cleanup function immediately after each resource is acquired. A finalizer registered before a later failure still runs.
import pytest
@pytest.fixture
def resource(request):
log = []
log.append("acquired")
request.addfinalizer(lambda: log.append("released"))
return log
def test_resource_is_acquired(resource):
assert resource == ["acquired"]Use yield for the common single-resource case. Reach for addfinalizer when several steps each need their own cleanup.
Seeing what pytest does
Run pytest --setup-show to print every fixture setup and teardown with its scope letter. The letter is F for function, C for class, M for module, P for package, and S for session.
pytest --setup-show test_db.pyThe output lists lines such as SETUP M conn and TEARDOWN F db. Use it when a resource lives longer or shorter than you expected.
Common mistakes
- Expecting teardown after each test from a module-scoped fixture. It runs once, at the end of the module.
- Putting cleanup after an
assertinside the test body. A failed assertion skips it. Put cleanup in the fixture instead. - Using
returnin a fixture that needs cleanup. Code afterreturnnever runs, so useyield. - Requesting a narrow fixture from a wide one, which raises
ScopeMismatch.
Exercise
A fixture server has scope="session" and starts a local test server. A fixture client has the default scope and requests server. A third fixture settings has scope="session" and requests client. What happens when a test uses settings, and how would you fix it?
Show answer
pytest raises ScopeMismatch. The session-scoped settings cannot depend on the function-scoped client, because client would be destroyed before settings is. The fix is to give client session scope too, or to make settings function scoped. A session-scoped server requested by a function-scoped client is fine, since a narrow fixture may depend on a wider one.
Exercise
A module-scoped fixture conn yields a database connection, and teardown after the yield closes it. A test in the module fails with an assertion error. Does the connection still get closed, and when?
Show answer
Yes. Teardown after yield runs even when a test fails. It runs once, after the last test in the module has finished, not right after the failing test.