Sub topic 16
Organizing tests in a growing project
This chapter assumes you can already write fixtures and put them in conftest.py. It also assumes you know how to configure pytest in pyproject.toml. Here you will use both to keep a suite manageable as the number of tests grows from dozens to thousands.
Why layout matters
A single test_cart.py next to cart.py works for a tutorial. In a real project, three problems show up:
- Tests are hard to find, because nothing links a test file to the code it checks.
- Slow tests mix with fast ones, so the quick feedback loop disappears.
- Test files import the code in inconsistent ways, which causes errors that only appear on some machines.
A deliberate layout and a few configuration lines prevent all three.
A layout that scales
Most projects keep tests in a top-level tests/ directory, separate from the package. The package itself lives under src/:
myshop/
├── pyproject.toml
├── src/
│ └── myshop/
│ ├── __init__.py
│ ├── cart.py
│ └── billing.py
└── tests/
├── conftest.py
├── unit/
│ ├── test_cart.py
│ └── test_billing.py
└── integration/
├── conftest.py
└── test_checkout_flow.pyThe rules behind this layout:
- Mirror the package.
src/myshop/cart.pyis tested bytests/unit/test_cart.py. A reader can find the tests without searching. - Split by speed and dependencies, not only by module. Unit tests touch no network, disk, or real database. Integration tests do. Keeping them in separate directories lets you run only the fast ones with
pytest tests/unit. - Keep shared helpers in
conftest.py, not in test files. Importing one test module from another couples them and breaks when you run a single file.
The src/ layout has one benefit. Your tests cannot accidentally import the package from the current directory. They must import the installed version, so packaging mistakes show up in tests instead of in production.
Making imports work
With the src/ layout, import myshop fails unless the package is installed or pytest is told where to look. There are two common fixes.
- Install the project in editable mode with
pip install -e .. This is the most realistic option, because tests run against the same install mechanism users get. - Add
pythonpath = ["src"]to the pytest configuration. This is simpler and needs no install step.
Here is a configuration that uses the second approach:
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]
addopts = "-ra --strict-markers --import-mode=importlib"
markers = [
"integration: tests that need a database or network",
"slow: marks tests as slow (deselect with -m 'not slow')",
]Three of these settings matter for organization:
testpathslimits discovery totests/, so pytest does not walk intobuild/or virtual environments.--strict-markersturns a misspelled marker such as@pytest.mark.integratoninto an error. Without it, pytest only warns, and the test silently escapes your-mfilters.--import-mode=importlibis explained in the next section.
Duplicate file names and import modes
By default, pytest uses prepend import mode. It inserts each test file's directory into sys.path and imports the file by its base name. If two directories both contain a test_cart.py and neither has an __init__.py, pytest cannot tell them apart. You get an error like this:
import file mismatch:
imported module 'test_cart' has this __file__ attribute: ...
which is not the same as the test file we want to collect: ...There are two ways out. The traditional one is to add an __init__.py to every test directory, which makes each file part of a package with a unique dotted name. The modern one is --import-mode=importlib, which imports files without changing sys.path and allows the same base name in different directories. The pytest documentation recommends importlib for new projects. One trade-off applies: with importlib, test files cannot import each other as modules, which is a good habit to avoid anyway.
Layered conftest.py files
A conftest.py applies to the directory it lives in and everything below it. A project can therefore have layers:
tests/conftest.pyholds fixtures every test might need.tests/integration/conftest.pyholds fixtures that only integration tests need, such as a database connection.
A fixture defined closer to the test overrides one with the same name defined higher up. This lets the integration layer replace a cheap default with a real resource:
# tests/conftest.py
import pytest
@pytest.fixture
def db_url():
return "sqlite:///:memory:"# tests/integration/conftest.py
import pytest
@pytest.fixture
def db_url():
return "sqlite:///integration_test.db"A test in tests/unit/ that requests db_url gets the in-memory URL. A test in tests/integration/ gets the file-based one. The test code is identical in both places. Only the location decides which fixture it receives.
Use the diagram below to see how lookup works.
Marking a whole directory
You can put @pytest.mark.integration on every test, but people forget. A hook in the directory's conftest.py can apply the marker automatically:
# tests/integration/conftest.py
from pathlib import Path
import pytest
HERE = Path(__file__).parent
def pytest_collection_modifyitems(items):
for item in items:
if HERE in item.path.parents:
item.add_marker(pytest.mark.integration)Now pytest -m "not integration" skips the whole directory, and pytest -m integration runs only it.
The if check is required. pytest_collection_modifyitems receives every collected test in the session, even when the hook lives in a subdirectory's conftest.py. Without the path check, every test in the project would get the marker. item.path is available in pytest 7.0 and later.
Choosing a split
| Split by | Good for | Cost |
|---|---|---|
| Directory (`unit/`, `integration/`) | Running a whole layer, applying markers and fixtures to it | A test can sit in the wrong folder |
| Marker (`slow`, `integration`) | Cutting across directories, such as one slow test in a unit module | Needs `--strict-markers` and discipline |
| Module mirror (`test_cart.py`) | Finding the tests for a given source file | Large modules produce large test files |
These do not compete. A typical project mirrors modules inside each directory and uses markers for exceptions.
Common errors
ModuleNotFoundError: No module named 'myshop'. The package is not installed andpythonpathis not set. Fix it withpip install -e .or by addingpythonpath = ["src"].- Fixture not found. The fixture is in a
conftest.pyin a sibling directory. Fixtures only flow downward, so move it up to the nearest common parent. - Tests not collected. The file or function name does not match the discovery patterns (
test_*.pyandtest_*), or it sits outsidetestpaths. - A test passes alone but fails in the full run. Tests are sharing state, such as a module-level list or a file on disk. Use function-scoped fixtures and
tmp_pathso each test starts clean. - Marker filter selects nothing. The marker name has a typo. Add
--strict-markersso this fails loudly.
Exercise
Your project has tests/unit/test_utils.py and tests/integration/test_utils.py, with no __init__.py files. Running pytest fails with "import file mismatch". Name two fixes. Then say which conftest.py location makes a fixture available to both directories.
Show answer
Fix one: add an __init__.py to each test directory so the modules get unique package-qualified names. Fix two: run with --import-mode=importlib, for example by adding it to addopts. A fixture shared by both directories belongs in tests/conftest.py, because a conftest applies to its own directory and everything below it.
Exercise
You add pytest_collection_modifyitems to tests/integration/conftest.py to mark integration tests, but now every test in the project is marked integration. What is the cause and the fix?
Show answer
The hook receives all collected items in the session, not only those in its own directory. Fix it by checking each item's location, for example if HERE in item.path.parents: where HERE = Path(__file__).parent, and adding the marker only when it is true.