Sub topic 8
Fixture scope and cleanup with yield
This chapter assumes you can write a basic fixture and request it by argument name in a test. It covers how long a fixture lives (its scope) and how to run cleanup code when it ends.
Scope controls how often a fixture runs
By default, pytest creates a fixture once per test function and discards it afterward. The scope argument to @pytest.fixture changes that. A wider scope runs setup less often, which helps when setup is slow, such as opening a database connection or starting a server.
| Scope | Fixture is created | Fixture is torn down |
|---|---|---|
| `function` (default) | Once per test | After that test |
| `class` | Once per test class | After the last test in the class |
| `module` | Once per test file | After the last test in the file |
| `package` | Once per package | After the last test in the package |
| `session` | Once per pytest run | At the end of the run |
Cleanup with yield
A fixture that uses yield instead of return hands its value to the test at the yield line. pytest resumes the function after the test finishes, and the remaining lines act as teardown. Teardown runs whether the test passed or failed.
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 users(conn):
yield conn
conn.execute("DELETE FROM users")
def test_insert_user(users):
users.execute("INSERT INTO users VALUES ('ada')")
count = users.execute("SELECT COUNT(*) FROM users").fetchone()[0]
assert count == 1
def test_table_starts_empty(users):
count = users.execute("SELECT COUNT(*) FROM users").fetchone()[0]
assert count == 0The conn fixture is expensive, so it lives for the whole module. The users fixture is function-scoped and empties the table after each test. Each test starts from a clean state, but the connection is opened and closed only once.
Rules and common errors
- Scope mismatch. A fixture can depend only on fixtures with the same or a wider scope. A
modulefixture that requests a function-scoped fixture fails withScopeMismatch. The example above is valid because the dependency points the other way. - Shared state leaks. With a wider scope, tests share one object. If a test changes it, later tests see the change. Reset the state in a narrower fixture, as
usersdoes. - Setup failure skips teardown. If an exception happens before the
yield, the code after it never runs. If setup acquires several resources, wrap them intry/finally, or register each cleanup right after its resource is created withrequest.addfinalizer. - One yield only. A fixture must yield exactly once.
Exercise
A module-scoped fixture named config requests a function-scoped fixture named tmp_path. What happens when a test uses config, and how do you fix it?
Show answer
pytest raises ScopeMismatch, because a wider-scoped fixture cannot depend on a narrower one. Fix it by using the session-scoped tmp_path_factory fixture inside config, or by making config function-scoped.