Pytest conftest.py Explained: Shared Fixtures, Hooks and Overrides
A pytest conftest.py file shares fixtures, hooks and custom options with every test in its directory, with no imports. Learn how discovery works, fixture scope and teardown, overriding fixtures per folder, autouse fixtures, custom command-line options and markers, and how to keep conftest files tidy, with a suite we ran.
- A pytest conftest file makes its fixtures and hooks available to every test in the same directory and below, with no import statement.
- Nested
conftest.pyfiles can override a parent fixture by defining the same name; the closest one wins. - Hooks such as
pytest_addoptionandpytest_configureadd command-line options and markers for the whole suite. - Our 6-test suite ran in 0.02 s, and
--setup-showconfirmed the session database opened once and closed once.
As a test suite grows, the same setup appears in many files: a database connection, a logged-in API client, a temporary directory, test users. Copying it is fragile, and importing fixtures between test modules gets messy. A pytest conftest file solves that: it is a plugin local to a directory, and pytest loads it automatically.
We built a small suite and ran it with Python 3.13.6 and pytest 9.2.0; every output below is from those runs. If fixtures themselves are new, read our pytest fixtures guide first.
What is conftest.py in pytest?
conftest.py is a special file name. When pytest collects tests, it loads every conftest.py on the path from the root directory down to each test file, before importing the tests. Everything defined there, fixtures, hooks and plugin registrations, applies to that directory and all subdirectories. There can be one per directory, and they stack.
Our project layout
tests/
conftest.py # shared: env option, db, clean_db, base_url, user, marker
unit/
test_users.py
api/
conftest.py # API-only: overrides user, adds autouse api_headers
test_orders.py
Running the whole suite:
pytest -q tests
6 passed in 0.02s
Sharing fixtures across files
# tests/conftest.py
import pytest, sqlite3
@pytest.fixture
def user():
return {"name": "asha", "role": "viewer"}
# tests/unit/test_users.py
def test_user_role(user):
assert user["role"] == "viewer"
The test file has no import, yet user is available. pytest matches the argument name with a fixture it found in a visible conftest.py. That keeps test files focused on behaviour and puts setup in one place.
Scope and teardown with yield
@pytest.fixture(scope="session")
def db():
print("\n[session] open db")
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE users(name TEXT)")
yield con
print("\n[session] close db")
con.close()
Code before yield is setup; code after is teardown, which runs even if tests fail. With scope="session" the database is created once for the whole run. --setup-show made the lifetimes visible:
SETUP S db
SETUP F clean_db (fixtures used: db)
TEARDOWN F clean_db
SETUP F clean_db (fixtures used: db)
TEARDOWN F clean_db
SETUP F user
TEARDOWN F user
TEARDOWN S db
S marks session scope and F function scope. The expensive connection was opened once, while the cheap per-test fixtures were recreated for each test. Other scopes are class, module and package. Under parallel runs with pytest-xdist, “session” means once per worker.
Fixtures that use other fixtures
@pytest.fixture
def clean_db(db):
db.execute("DELETE FROM users")
return db
def test_insert(clean_db):
clean_db.execute("INSERT INTO users VALUES ('asha')")
assert clean_db.execute("SELECT COUNT(*) FROM users").fetchone()[0] == 1
def test_isolated(clean_db):
assert clean_db.execute("SELECT COUNT(*) FROM users").fetchone()[0] == 0
A function-scoped fixture can depend on a session-scoped one. Here every test shares one connection but starts with an empty table, so test_isolated passes regardless of what test_insert did. This is the standard pattern for fast yet independent database tests. The reverse is not allowed: a session fixture cannot request a function fixture, and pytest reports a ScopeMismatch error.
Overriding fixtures per folder
# tests/api/conftest.py
@pytest.fixture
def user():
return {"name": "api-bot", "role": "admin"}
# tests/api/test_orders.py
def test_override(user):
assert user["role"] == "admin"
Both conftest files define user. Tests under tests/api receive the admin version, while tests/unit still gets the viewer; both tests passed. pytest searches from the test file outwards and uses the closest definition. Use this to swap behaviour for one area, for example a different base URL or a mocked service for integration tests, without touching the rest of the suite.
Autouse fixtures
# tests/api/conftest.py
@pytest.fixture(autouse=True)
def api_headers(request):
request.node.headers = {"Accept": "application/json"}
autouse=True runs the fixture for every test in scope without anyone requesting it. Here every API test got default headers, which test_slow_report asserted. Autouse is ideal for global guards, such as blocking real network calls with monkeypatch or resetting a cache, but keep autouse fixtures few and cheap, because they run everywhere and are invisible in test signatures.
Tip: put autouse fixtures in the most specific conftest that needs them. An autouse fixture in the root conftest affects every single test.
Adding custom command-line options
# tests/conftest.py
def pytest_addoption(parser):
parser.addoption("--env", default="local", help="target environment")
@pytest.fixture(scope="session")
def env(request):
return request.config.getoption("--env")
@pytest.fixture
def base_url(env):
return {"local": "http://localhost:8000",
"staging": "https://staging.example.com"}[env]
pytest -q tests --env staging -k base_url
1 passed, 5 deselected in 0.09s
pytest_addoption is a hook: pytest calls it at start-up so you can add options. A fixture then reads the value, and every test that needs a URL just asks for base_url. The same suite can now run against local, staging or a review app from CI. Note that option hooks belong in the root conftest, or a plugin, so they load before command-line parsing; values like these often come from environment variables too.
Registering custom markers
def pytest_configure(config):
config.addinivalue_line("markers", "slow: marks tests as slow")
@pytest.mark.slow
def test_slow_report(base_url, request):
assert request.node.headers["Accept"] == "application/json"
pytest -q tests -m "not slow"
5 passed, 1 deselected in 0.02s
Registering markers in pytest_configure documents them and avoids “unknown marker” warnings; with --strict-markers, unregistered markers become errors, which catches typos. Our pytest markers guide covers selection expressions in depth.
Other useful conftest hooks
| Hook | Use it to |
|---|---|
pytest_addoption |
Add command-line options |
pytest_configure |
Register markers, set up global state |
pytest_collection_modifyitems |
Reorder, skip or mark collected tests |
pytest_runtest_makereport |
Attach screenshots or logs to failures |
pytest_sessionfinish |
Write summaries or clean up after the run |
pytest_generate_tests |
Parametrize tests dynamically |
Only the first two were run in our suite; the rest are documented hooks you will often see in larger projects. Dynamic parametrization is an alternative to pytest.mark.parametrize when values come from files or options.
Finding where a fixture comes from
pytest tests --fixtures
------------------- fixtures defined from conftest -------------------
db [session scope] -- tests\conftest.py:13
clean_db -- tests\conftest.py:22
base_url -- tests\conftest.py:27
user -- tests\conftest.py:31
env [session scope] -- tests\conftest.py:9
user -- tests\api\conftest.py:3
api_headers -- tests\api\conftest.py:7
--fixtures lists every available fixture with its file, line and scope, including both versions of user. Add -v to see private fixtures too. When a test receives an unexpected value, this is the fastest way to find which conftest supplied it.
Do not import from conftest.py
In our run, from conftest import user inside a test file actually worked, because pytest had put the tests directory on sys.path. It is still a bad idea: it depends on import mode and directory layout, it imports the fixture function rather than letting pytest manage it, and with several conftest.py files the name is ambiguous. If you need shared helper functions, put them in a normal module, such as tests/helpers.py, and import that.
Organising conftest files
- Keep the root conftest for truly global things: options, markers, core fixtures.
- Put area-specific fixtures in that area’s conftest, such as
tests/api/conftest.py. - Keep narrow fixtures that one module uses in that test module.
- When a conftest grows large, move fixtures into modules and load them with
pytest_plugins = ["tests.fixtures.db"]in the root conftest. - Give fixtures descriptive names and docstrings;
--fixturesshows the docstrings.
Common conftest mistakes
- A misspelled file name such as
conftests.py, which pytest silently ignores. - Expensive work in function-scoped fixtures that should be session-scoped.
- Session fixtures that keep mutable state between tests without a reset step.
- Too many autouse fixtures, making tests slow and hard to understand.
- Defining
pytest_addoptionin a nested conftest, where it may load too late. - Turning conftest into a dumping ground for unrelated helpers.
Final thoughts
A pytest conftest file is the backbone of a maintainable test suite. It shares fixtures without imports, controls their lifetime with scopes and yield teardown, lets subfolders override behaviour, and hosts hooks for options and markers. Keep each conftest focused on its directory, check sources with --fixtures and --setup-show, and your tests stay short while the setup stays in one place. For API suites built on these ideas, see API testing with Python.
Frequently asked questions
What is conftest.py used for in pytest?
It holds fixtures, hooks and plugin settings that pytest loads automatically for every test in the same directory and its subdirectories, so tests can use them without imports.
Can I have multiple conftest.py files?
Yes. Each directory can have its own conftest.py. They stack from the root down, and a fixture defined closer to a test overrides one with the same name defined higher up.
Do I need to import fixtures from conftest.py?
No. pytest discovers conftest fixtures automatically by name. Importing them is discouraged; put shared helper functions in a normal module instead.
Where should conftest.py be located?
Put shared fixtures in the root of your tests directory and area specific fixtures in a conftest.py inside that subfolder. Command line option hooks belong in the root conftest.
How do I add a custom command line option to pytest?
Define the pytest_addoption hook in the root conftest.py and call parser.addoption, then read the value in a fixture with request.config.getoption.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.