Pytest Conftest Files That Don't Become a Mess With AI Agents
Every pytest project starts with one conftest.py, a handful of fixtures and good intentions. Some time later the same file is enormous, nobody is sure which fixtures are still used, and adding one feels risky. I've seen this on teams of every size, and the cause is nearly always the same: conftest files grow by accretion rather than by design.
Coding agents speed that up. An agent that needs a fixture and can't quickly find the existing one will write a new one, usually in the nearest or the root conftest. Repeat that across many agent tasks and you get near-duplicate fixtures with slightly different behaviour, and tests that pass or fail depending on which one they picked up.
Pytest's fixture system gives you what you need to prevent this: layered conftest files, scopes and factory fixtures. None of it works automatically. In this article I'll cover where fixtures should live, how to choose scope, when to split a conftest, and how to make the structure obvious enough that an agent follows it instead of working around it.
Learn Node.js, Cucumber, GitHub Copilot, APIs, CI/CD, and modern automation by building a complete framework.
Layer conftest files instead of piling everything at the root
Pytest collects conftest.py files from the directories above each test, so a test sees the fixtures in its own folder's conftest and every conftest above it. That lets you put each fixture exactly where it's needed:
tests/
conftest.py # settings, base URL, shared session: what every test needs
api/
conftest.py # auth clients, API helpers
test_orders.py
test_products.py
integration/
conftest.py # database connections, seed data
test_checkout.py
A fixture in tests/api/conftest.py isn't visible to tests/integration/. That isolation is a feature. The mistake I see most is dumping API clients, seed helpers, mock servers and environment loading into the root conftest "in case they're needed anywhere". Most are only used in one folder. Move them down, and promote one later if another folder genuinely needs it.
My rule of thumb: a fixture belongs at the lowest level where it's shared, not the highest level where it might theoretically be useful.
Scope is a contract
Most conftest debt comes from scope. Too broad and tests share state they shouldn't. Too narrow and you pay setup costs on every test for no reason.
scope="session"for things that are expensive to build and that no test can change: settings loaded from the environment, a configured HTTP client, a read-only reference file. If two tests could corrupt it by running in sequence, it doesn't belong here.scope="module"for setup shared by one test file, such as a stub server for one endpoint family. It's needed less often than people think.scope="function", the default, for anything that creates, writes or mutates. Each test gets its own copy, and teardown runs before the next test.
The classic mistake is making a fixture session-scoped because it feels expensive, then discovering it holds mutable state. My check: if the tests ran in a different order, or in parallel, would this fixture behave identically? "Probably" isn't good enough.
Pytest enforces one direction for you. A function-scoped fixture can depend on a session-scoped one, but a session-scoped fixture that requests a function-scoped one fails with a ScopeMismatch error. That error is telling you something real about the design, so fix the structure rather than downgrading scopes until it goes away.
Split by moving fixtures into plain modules
Line count isn't the real signal. Cohesion is. When one conftest holds HTTP clients, database connections, stub servers, data factories and environment bootstrapping, it's a utility module wearing a conftest name. Move the implementations into normal modules and register them from the root conftest:
# tests/fixtures/api_clients.py
import pytest
import requests
@pytest.fixture(scope="session")
def api_session(settings):
"""Session-scoped. One authenticated session per run. Do not mutate headers in tests."""
with requests.Session() as session:
session.headers["Authorization"] = f"Bearer {settings.api_token}"
yield session
# tests/conftest.py
pytest_plugins = [
"fixtures.api_clients",
"fixtures.factories",
]
pytest_plugins is meant for the root conftest, and the module path must be importable from where pytest runs, so adjust it to your layout. Importing fixtures directly into conftest also works, but linters flag those imports as unused and someone eventually deletes them.
Two more habits keep things small:
- Factory fixtures over one fixture per variant. A
make_order(status="pending")factory beats separatepending_order,confirmed_orderandshipped_orderfixtures. I go further in pytest fixtures for API testing beyond the basics. - Audit what's actually used.
pytest --fixtureslists the fixtures available, with their docstrings, andpytest --fixtures-per-testshows which fixtures each test uses. Anything in the first list that never appears in the second is a candidate for deletion.
Docstrings pay off twice: they show up in pytest --fixtures, and they tell a reader the scope and the rule ("do not mutate") right where it matters.
Making the structure obvious to agents
An agent can only reuse a fixture it knows exists. Three things make a big difference.
Give it the inventory. Before asking an agent to write tests, I have it run pytest --fixtures tests/api or paste the output into the prompt. Good docstrings turn that list into a usable catalogue. Without it, the agent guesses and writes its own.
Write the rules down. In .github/copilot-instructions.md, or your agent's equivalent:
## Pytest fixtures
- Check `pytest --fixtures` before adding a fixture; reuse or extend an existing one.
- Put new fixtures in the conftest of the lowest folder that needs them, not tests/conftest.py.
- Anything that creates or changes data is function-scoped and cleans up after itself.
- Never widen a fixture's scope to speed tests up without asking.
Review conftest changes separately. In an agent's PR, the conftest diff is where shared behaviour changes, so I look at it before the tests. A new session-scoped fixture that yields something mutable, or a near-copy of an existing fixture, is the thing to catch.
The same structure helps when you test features that call a model. I keep a generate fixture that returns a function from prompt to text. Most tests get a deterministic stub; tests marked to use the real model get the real client and run in a scheduled job, judged on pass rate across several runs. Because the fixture is injected, test code doesn't change between the two, and nobody has to hunt for where the model client gets built.
# tests/conftest.py
import pytest
@pytest.fixture
def generate(request, settings):
"""Prompt -> text. Stubbed unless the test is marked real_model."""
if request.node.get_closest_marker("real_model"):
return settings.model_client.generate
return lambda prompt: '{"status": "ok"}'
Here settings.model_client stands in for however your project builds its model client; the point is that one fixture owns that decision. Register real_model in pytest.ini so it can be selected or excluded with -m.
Every fixture should have an obvious home
The goal isn't a minimal conftest. It's one where every fixture clearly belongs at its level. If you can explain in one sentence why each root fixture lives at the root, you're in good shape, and so is any agent working in the repo. Where your tests then run is the next question, which I cover in where API tests belong in a CI/CD pipeline. My API testing courses build a pytest or Behave suite with this structure using VS Code and GitHub Copilot.