What is conftest.py?
conftest.py is a special file where pytest looks for fixtures, hooks, and configuration. It is the standard way to share fixtures across multiple test files without importing them.
Sharing Fixtures
Define fixtures in conftest.py and they become available to all test files in that directory:
# conftest.py
import pytest
@pytest.fixture
def sample_data():
return {"name": "Alice", "age": 30}
@pytest.fixture
def temp_dir(tmp_path):
return tmp_path / "test_output"
# test_one.py - no import needed!
def test_with_data(sample_data):
assert sample_data["name"] == "Alice"
# test_two.py - also works without import
def test_with_data(sample_data):
assert sample_data["age"] == 30
Hierarchical conftest.py
pytest collects conftest.py files at every directory level. A fixture defined in a parent directory is available to all subdirectories:
project/
โโโ conftest.py # Available everywhere
โโโ tests/
โ โโโ conftest.py # Available to tests/ and subdirs
โ โโโ test_api.py
โ โโโ unit/
โ โโโ conftest.py # Available only to unit/
โ โโโ test_math.py
conftest.py is NOT Imported
You never import from conftest.py. pytest loads it automatically. This is different from regular Python modules:
# WRONG - do not do this
from conftest import sample_data
# RIGHT - pytest handles it automatically
def test_something(sample_data):
pass