Sub topic 9
Sharing fixtures through conftest.py
This chapter assumes you can write a basic fixture with @pytest.fixture and use yield for cleanup. It also assumes you know how pytest discovers test files. Here you will move fixtures out of individual test modules so that many files can use them without importing anything.
Why conftest.py exists
A fixture defined inside test_users.py is visible only to tests in that file. When a second file needs the same database, you could copy the fixture, but then every change has to be made in two places. Importing the fixture function from the first test module also works, but it ties test files to each other. Linters will flag the import as unused or redefined, and the pattern is easy to break.
pytest solves this with a special file named conftest.py. Fixtures defined in it are available to every test in the same directory and in all subdirectories below it. You do not import them. pytest loads conftest.py files itself, before it collects the tests next to them.
A first shared fixture
Start with this layout:
project/
├── pyproject.toml
└── tests/
├── conftest.py
├── test_users.py
└── test_reports.pyMove the db fixture into tests/conftest.py:
# tests/conftest.py
import sqlite3
import pytest
@pytest.fixture
def db():
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users (name TEXT)")
yield conn
conn.close()Both test files can now request db by naming it as a parameter:
# tests/test_users.py
def test_insert_user(db):
db.execute("INSERT INTO users VALUES ('ada')")
count = db.execute("SELECT COUNT(*) FROM users").fetchone()[0]
assert count == 1# tests/test_reports.py
def test_new_database_has_no_users(db):
count = db.execute("SELECT COUNT(*) FROM users").fetchone()[0]
assert count == 0Neither file imports db. Each test still gets its own fresh in-memory connection, because the fixture keeps its default function scope. The second test would fail if the first test's row leaked into it, so it also checks that isolation holds.
How pytest finds a fixture
When a test requests a fixture, pytest searches from the most specific place outward. It looks first in the test module, then in the conftest.py in the same directory, then in each parent directory's conftest.py up to the root. Plugins and pytest's built-in fixtures come last.
The first match wins. This order is what makes overriding possible.
Overriding a fixture closer to the test
A fixture with the same name in a deeper directory hides the one above it. The deeper version can also request the parent fixture by using its own name as a parameter. This lets you extend a shared fixture for one area of the project without changing it for everyone else.
# tests/api/conftest.py
import pytest
@pytest.fixture
def db(db):
db.execute("INSERT INTO users VALUES ('grace')")
return db# tests/api/test_seeded.py
def test_api_database_starts_with_one_user(db):
count = db.execute("SELECT COUNT(*) FROM users").fetchone()[0]
assert count == 1Tests in tests/api/ get a database with one seeded row. Tests elsewhere under tests/ still get the empty one. A test module can override in the same way: a db fixture defined in the module itself wins over every conftest.py.
Seeing where a fixture comes from
When a suite grows, it is easy to lose track of which definition a test is using. pytest can tell you:
pytest --fixtures
pytest --fixtures-per-test tests/api/test_seeded.pyThe first command lists every fixture available from the current directory, grouped by the file that defines it. Fixtures that start with an underscore are hidden unless you add -v. The second shows, for each test, the fixtures it uses and the file and line of the definition that was picked. Use it first whenever a test behaves as if it has the wrong fixture.
What belongs in conftest.py
Good candidates are fixtures needed by several test files: database connections, temporary project layouts, sample data builders, and configured clients. Put a fixture in the narrowest conftest.py that covers every test using it. A fixture used only under tests/api/ belongs in tests/api/conftest.py, not in the top-level file.
Keep these points in mind:
- Scope still applies. A session-scoped fixture in
conftest.pyis created once per test run, as it would be anywhere else. Where you define a fixture decides which tests can see it. Thescopeargument decides how long it lives. - Autouse is wider than it looks. A fixture marked
autouse=Trueintests/conftest.pyruns for every test undertests/, including tests whose authors never see the file. Use it sparingly and keep it cheap. - Fixtures can depend on each other across files. A fixture in
tests/api/conftest.pycan request a fixture fromtests/conftest.pyby name, exactly as the override above does. - Hooks and markers live here too.
conftest.pycan also contain pytest hook functions such aspytest_configure. Hooks are a plugin mechanism and are beyond this chapter. Fixtures are the most common use.
# tests/conftest.py (addition)
import pytest
@pytest.fixture(autouse=True)
def fixed_timezone(monkeypatch):
monkeypatch.setenv("TZ", "UTC")With this in place, every test under tests/ sees TZ=UTC without asking for it, and monkeypatch restores the environment afterwards.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `fixture 'db' not found` | The fixture is in a `conftest.py` that is not in the test's directory or one of its parents. | Move it up to a common parent, or check the path with `pytest --fixtures`. |
| A test gets the wrong data | A deeper `conftest.py` or the test module overrides the fixture name. | Run `pytest --fixtures-per-test` on that test. |
| `ImportError` after `from conftest import db` | Test files should not import from `conftest.py`. Module names can clash when several directories have one. | Delete the import and request the fixture by parameter name. |
| Fixture changes have no effect | pytest is running a different checkout or a stale copy of the file. | Check the path in the report header and the `rootdir` line. |
| Helper function in conftest is collected as a test | The function name starts with `test_`. | Rename it, or make it a fixture that returns the helper. |
Do not put plain helper functions in conftest.py and import them elsewhere. If tests need a shared helper, expose it through a fixture that returns it, or place it in a regular module such as tests/helpers.py.
Exercise
Exercise
Your project has tests/conftest.py defining a fixture named client that returns a basic test client. Tests in tests/admin/ need a client that is already logged in as an administrator, but tests elsewhere must keep the basic client. Where do you put the new fixture, what do you name it, and how does it reuse the basic one?
Show answer
Create tests/admin/conftest.py and define a fixture also named client there, with client as its own parameter: def client(client): and log in as the administrator on the received object before returning it. Because the closest conftest.py wins, tests under tests/admin/ get the logged-in client. The parent fixture is still used underneath, and tests outside tests/admin/ are unaffected.