As a suite grows, fixtures must live in one place and be visible exactly where they're needed.
A `conftest.py` file holds fixtures (and hooks) shared by all tests in its directory and subdirectories. You never import it: pytest loads it automatically during collection, and fixtures defined there become available by name.
Conftest files are hierarchical. A typical layout:
tests/conftest.py: project-wide fixtures likeapp,client,db.tests/api/conftest.py: fixtures only API tests need.tests/unit/...: tests that don't see the API fixtures.
When two levels define a fixture with the same name, the one closest to the test wins. That allows a subdirectory to override a general fixture, for example replacing user with an admin user for admin tests. An overriding fixture can even request the fixture it overrides by the same name to extend it.
Guidelines:
- Don't put tests in conftest.py, and don't import from it; if you need shared helper functions, put them in a regular module or expose them as fixtures.
- Keep the root conftest small; big setup belongs near the tests that use it.
- Use
pytest --fixtures-per-test pathto see which fixture a test actually got.
For layout, prefer a src/ package layout with tests outside the package, installed with pip install -e ., so tests import your code the way users do.
Example
# tests/conftest.py (visible to every test under tests/)
import pytest
@pytest.fixture
def user():
return {"name": "ada", "role": "member"}
# tests/admin/conftest.py (overrides user for tests/admin/ only)
import pytest
@pytest.fixture
def user(user): # extends the parent fixture
return {**user, "role": "admin"}
# tests/admin/test_panel.py
def test_admin_sees_panel(user):
assert user["role"] == "admin"
# tests/test_profile.py
def test_member_profile(user):
assert user["role"] == "member"Remember
- conftest.py fixtures are available to tests in its directory tree
- Never import conftest; pytest loads it
- The closest definition of a fixture name wins
- An override can request the parent fixture by the same name
Watch out for
- Importing fixtures from conftest.py with
from conftest import ....