How Much Test Data Isolation Is Enough When Agents Run Tests
Test data isolation is one of those topics where teams swing between two extremes. Either every test provisions its own universe of data and the suite crawls, or everything shares one seeded database and you lose afternoons to failures that only happen in a particular order. Neither is right, and "it depends" isn't an architecture decision.
The question has got sharper now that coding agents write and run a lot of tests. An agent working in its own branch runs the suite repeatedly, sometimes several agent sessions at once against the same staging API, alongside CI and the humans on the team. Agent-written tests also have habits: they love asserting exact counts and they assume the data they just saw will be there next time. Weak isolation that a single developer could live with turns into noise nobody can trust.
In this article I'll give you the rule I use to decide how much isolation a test needs, where the scope boundaries belong in pytest and Behave, how to make the suite safe for many concurrent runners, and the signals that tell you you've drawn the line in the wrong place.
Learn Node.js, Cucumber, GitHub Copilot, APIs, CI/CD, and modern automation by building a complete framework.
Draw the line at mutation
Over-isolation means every test creates and deletes all of its own records. It sounds ideal and produces slow suites with fixtures so complex they have bugs of their own. When a test fails, the first question becomes "is the fixture broken or the system?", and you never want to be asking that.
Under-isolation is the opposite. Tests share records with no ownership rules, and eventually two collide. A GET /users test that asserts an exact count breaks when a create test runs at the same time. A test expecting an order in "pending" fails because another test already moved it to "shipped".
The rule I use is one question per test: does this test change shared state? If it only reads, it can share data with other readers. If it writes, it owns its data. Everything else is implementation detail. I like the fixture names to carry that contract:
# conftest.py
import uuid
import pytest
@pytest.fixture(scope="session")
def run_id():
return uuid.uuid4().hex[:8]
@pytest.fixture(scope="session")
def reference_user(api_client, run_id):
"""Created once per run, never modified. Safe to share between readers."""
resp = api_client.post("/users", json={"name": f"ref-{run_id}", "role": "viewer"})
user = resp.json()
yield user
api_client.delete(f"/users/{user['id']}")
@pytest.fixture
def owned_user(api_client, run_id):
"""Fresh per test. Use whenever the test will change the user."""
resp = api_client.post("/users", json={"name": f"owned-{run_id}", "role": "editor"})
user = resp.json()
yield user
api_client.delete(f"/users/{user['id']}")
Anyone reading a test, including an agent asked to extend it, can see from the fixture name what kind of data they're touching. That explicitness is worth more than clever scoping. If teardown is giving you trouble, I cover the details in structuring API test teardown so it actually runs.
Where the scope boundaries belong
Most suites have three natural boundaries, and each fits a kind of data:
- Function scope for anything the test writes, deletes or moves through a workflow. An order going from created to paid to shipped belongs to one test.
- Module, class or feature scope for data a group of related tests reads but never changes, such as a product catalogue that several read-endpoint tests query.
- Session scope for reference data the system treats as fixed: roles, lookup tables, configuration. Creating it once per run isn't a compromise. It's the right call.
In Behave, the same split maps onto hooks, and a tag makes the contract visible in the feature file rather than buried in code:
# features/environment.py
def before_feature(context, feature):
context.catalog = context.api.post("/products/bulk", json=CATALOG_SEED).json()
def after_feature(context, feature):
for product in context.catalog:
context.api.delete(f"/products/{product['id']}")
def before_scenario(context, scenario):
if "mutates_data" in scenario.tags:
context.order = context.api.post("/orders", json=NEW_ORDER).json()
def after_scenario(context, scenario):
if "mutates_data" in scenario.tags:
context.api.delete(f"/orders/{context.order['id']}")
Behave's scenario.tags holds tag names without the @, so @mutates_data in the feature file shows up as "mutates_data". When a scenario fails, the tag tells you straight away whether to look at shared or owned state. Dumping everything onto the top-level context is the under-isolation trap in disguise; sharing test data across a Behave suite safely goes deeper on that.
Isolation for many runners at once
A suite written for one developer on one machine assumes it's alone. With CI, pytest-xdist workers and agents all running against the same environment, it isn't. The two patterns that make the biggest difference:
- Namespace every record you create. The
run_idfixture above prefixes names, so two runs never fight over the same record and leftovers can be traced to the run that made them. For per-worker uniqueness under xdist, include theworker_idfixture that pytest-xdist provides. - Assert on what you own, not on totals. "The list contains the user I created" survives concurrent runs. "The list has 12 users" doesn't. Filter by your prefix, then assert.
The second pattern is the one agents break most. Ask an agent to test a list endpoint and it will often run the request, see the current count and assert it. That passes today and fails the moment anyone else touches the environment. I write the rule down where the agent will read it, such as .github/copilot-instructions.md for Copilot or your agent's instruction file:
## Test data
- Tests that create, update or delete data use owned_* fixtures, never reference_* ones.
- Prefix every created record with the run_id fixture.
- Never assert on total counts or list positions in shared environments; assert on records the test created.
Then I check for it in review. An instruction file is guidance, not a guarantee.
Three signals your isolation level is wrong
Order-dependent failures. If running tests in a different order changes the result, something mutates shared data without owning it. The pytest-randomly plugin shuffles test order on each run and prints the seed it used, so you can replay a bad order with pytest --randomly-seed=<seed>. Run it a few times and look for the test that always breaks when it runs after a particular neighbour. That neighbour is your mutator; give it owned data.
Setup dominates run time. If fixtures take longer than the tests, you've probably over-isolated. Run pytest --durations=20 to see the slowest setup, call and teardown phases, then check which function-scoped fixtures are never actually changed by the tests that use them. Those can usually move up a scope. Measure rather than guess.
CI failures you can't reproduce locally. This erodes trust faster than anything else. The cause is almost always a hidden dependency on state that exists in one environment but not the other, often created by an earlier test. The fix is to make every test's data needs explicit in its own setup, so it can run alone and pass.
Agents give you a useful extra check here: ask one to run a single failing test in isolation, then in random order, and report the difference. That's tedious for a person and exactly the kind of repetitive investigation an agent does well, as long as you read its conclusion rather than accept a "fix".
Enough, and no more
The honest answer to "how much isolation is enough" is: enough that each test can be understood, run and debugged on its own, by a person or an agent, while other runs are happening. Every layer beyond that is complexity you pay interest on. Draw the line at mutation, namespace what you create, and assert on what you own. For the broader design picture, see testing best practices from design onward, and if you want to build fixtures like these into a full API suite, my API testing courses walk through it step by step.