Direct answer
Design fixtures that give every test a fresh boundary and name who cleans up. Pytest identifies uncontrolled system state and thread-safety issues as possible causes of flaky tests (F022), and it documents fixtures as the reusable setup mechanism (F023). The practice here is to inventory shared state, define the smallest fresh fixture per test, declare setup dependencies explicitly, clean up in reverse order, and vary test order before raising parallelism. Fresh fixtures reduce state leakage between cases; they do not eliminate every cause of flakiness.
Ask Claude Code to trace which fixtures a failing test reads and writes, then make the ownership visible in code. A test that cannot describe what it owns cannot reliably isolate it, and the failure usually appears only after a parallel run or a reorder.
Why shared fixture state produces order bugs
A fixture that mutates module-level state, a shared database row, a temp directory, or a singleton leaves the suite order-dependent. Test A writes a value. Test B reads it and passes. Reorder the two and B fails with no code change. The failure is real, but the cause sits in setup rather than in the behavior under test.
Three costs follow. The suite becomes impossible to run in parallel because each worker races for the same mutable state. Debugging a single failure requires reproducing the entire preceding sequence. New engineers learn to fear the suite instead of trusting it, which is how intermittent failures survive for quarters.
| Hidden shared state | Symptom in the suite | Isolation move |
|---|---|---|
| Module-level mutable object | A test passes alone and fails in the full run | Fresh instance per test |
| Shared database row | Order-dependent assertion on counts | Transaction rollback or unique rows per test |
| Temp directory reused by name | File-not-found only under parallel workers | Unique directory per test |
| Singleton service client | Connection reset after another test closes it | Fresh client in setup, closed in teardown |
| Environment variable set in one test | Downstream tests read a leaked value | Save and restore in the fixture |
None of these are exotic. They are the ordinary accidents of a suite that grew faster than its setup discipline.
Inventory shared fixture state
Before changing fixtures, list what is actually shared. Ask Claude Code to scan a named test directory for module-level mutable variables, fixtures that write without restoring, and resources opened without a matching teardown. Review the list for consequence rather than style.
| Fixture | Mutable fields | Creator | Consumers | Cleanup owner |
|---|---|---|---|---|
db_session |
Open transaction, inserted rows | Session factory | Most integration tests | Fixture teardown, rollback |
app_client |
Auth token, cached config | Test setup | API tests | Fixture teardown, close |
tmp_workspace |
Files written during the test | Fixture | Importer tests | Fixture teardown, delete tree |
feature_flags |
Overridden flag values | Individual tests | Behavior tests | Fixture teardown, restore |
clock |
Frozen time value | Time fixture | Scheduling tests | Fixture teardown, unfreeze |
The inventory itself is the deliverable. A team that can name its shared state can reason about parallelism; a team that cannot will discover the shared state from failures.
For each row, record whether the mutable field is intentional or accidental. An intentional shared cache with documented synchronization is a design decision. An accidental shared transaction is a bug in the fixture.
Keep the inventory in the repository next to the fixtures it describes. An inventory that lives only in a design document drifts out of date within weeks, and a stale inventory is worse than none because it creates false confidence. Update it when a fixture changes scope, when a new shared resource appears, or when a leak is found and fixed.
When the suite is large, split the inventory by area rather than producing one long table nobody reads. A billing inventory, an auth inventory, and an importer inventory are each short enough to review, and each one names the fixtures that area actually shares.
Define the smallest fresh fixture
The smallest fresh fixture gives one test exactly the resources that test needs and nothing else. Prefer creating a resource inside the fixture and tearing it down in the same place over reaching for a session-scoped shared object. Pytest documents fixtures as reusable setup (F023), and the reuse is valuable when the setup is deterministic and the teardown is explicit.
A fresh fixture has three properties. It creates its own state, so no test inherits another test’s writes. It names its cleanup, so teardown is not an afterthought. It declares its dependencies, so the setup order is visible in the fixture signature rather than hidden in import order.
Consider the difference:
- Leaky: a module-level
clientcreated at import and reused across every test. - Fresh: an
app_clientfixture that builds a client, yields it, and closes it after the test.
The fresh version costs slightly more per test in setup time. It removes the entire class of cross-test leakage, which is usually a trade worth making once the suite is run in parallel. The one exception is an expensive resource that is genuinely read-only for the whole run, such as a large compiled artifact; recreating it per test adds cost without adding isolation.
| Fixture type | Scope | Isolation | Cost |
|---|---|---|---|
| Function-scoped fresh | One test | Full | Highest setup time |
| Module-scoped shared | One file | Partial, order-dependent within file | Medium |
| Session-scoped shared | Whole run | Lowest, leaks across files | Lowest setup time |
| Worker-scoped | One parallel worker | Isolates workers, not tests within a worker | Medium |
Choose the widest scope only when the resource is genuinely immutable for the whole run and the test asserts nothing about its lifecycle.
Declare setup dependencies
Setup that depends on another fixture should say so in its signature. Hidden dependencies appear when a fixture reaches for a global that another fixture happens to initialize first. Those fixtures pass until the order changes.
| Setup dependency | Failure mode when broken | Isolation change | Verification run |
|---|---|---|---|
db_session requires a migrated schema |
Tables missing on a fresh database | Schema fixture declared first | Run against an empty database |
app_client requires db_session |
Client cannot reach the database | Dependency in the signature | Run the client test alone |
feature_flags requires saved originals |
Flags stay overridden after the test | Save originals before override | Run the same test twice in one session |
clock requires a deterministic seed |
Timing assertions fail on reorder | Seed declared, not global | Run with randomized order |
Claude Code can map these dependencies from the fixture signatures and report any fixture that reads a global another fixture writes. That report is the input to the next step, which is cleanup.
Clean up resources in reverse order
Cleanup belongs in the fixture that created the resource, and it runs in reverse order of setup. A fixture that opens a file, starts a server, and inserts rows should close the server, remove the file, and roll back the rows when the test ends.
Assume the test can fail at any point. A cleanup hook that only runs on success is not cleanup. Frameworks differ in what runs after a failure, so verify the teardown actually executes for a failing test rather than assuming it (F024).
| Resource | Created in | Cleanup action | Verified after a failure |
|---|---|---|---|
| Database transaction | db_session |
Rollback | Yes, row count unchanged |
| HTTP client | app_client |
Close connections | Yes, no open handles |
| Temp directory | tmp_workspace |
Delete tree | Yes, directory absent |
| Frozen clock | clock |
Restore real time | Yes, later tests see real time |
| Feature flag override | feature_flags |
Restore saved value | Yes, later tests see defaults |
Record cleanup ownership in the fixture name or docstring. A reader should be able to tell who closes a resource without reading the whole test file.
Separate mutable and immutable data
Immutable test data can be shared safely across the whole run. A constant list of product codes, a static JSON payload, or a fixed date string does not need a fresh copy per test. Mutable data cannot be shared the same way, because one test’s write becomes another test’s starting condition.
| Data kind | Example | Sharing | Risk |
|---|---|---|---|
| Immutable constant | List of country codes | Session-scoped | None if never mutated |
| Read-only payload | Fixed request body | Session-scoped | Leak if a test mutates it |
| Mutable record | Customer row | Function-scoped fresh | Cross-test writes if shared |
| Mutable aggregate | Cart total | Function-scoped fresh | Order-dependent assertions |
The discipline is to mark intent at the definition. An immutable fixture that a test mutates is a bug, and the mutation should be caught by treating the fixture output as read-only or by copying before mutation. Reviewers should look for the specific pattern of a test assigning into a fixture result, because that assignment is the moment a shared fixture becomes a leak.
Parametrization interacts with this directly. Pytest’s parametrize example shows the same test running over multiple inputs (F023), and each parametrized case should receive its own mutable fixture so one case’s state never reaches another.
Test order and parallel variations
Isolation is a property you verify, not one you assume. Run the suite in a randomized order and in parallel with several workers. If the result changes, a fixture leaks, and the order variation has identified which one.
Increase parallelism only after the randomized-order run is clean. Adding workers before checking isolation converts a latent leak into a hard failure across the suite, and the failure report is harder to read than the leak was. A leak that appears only under parallelism also costs more to diagnose, because the interleaving that produced it is not recorded anywhere.
| Verification run | What it exposes | Pass condition |
|---|---|---|
| Single test alone | Missing setup that the full run hid | Passes without the preceding sequence |
| Randomized order | Cross-test state leakage | Same result for any order |
| Two workers | Shared resources raced by workers | Same result as single-worker |
| Repeated run in one session | Teardown that does not restore state | Second run matches the first |
Varying order is cheaper than debugging a parallel-only failure later. The flaky test triage guide covers the classification step once a failure is found.
Ask Claude Code to trace fixture ownership
Give Claude Code a specific investigation rather than a general request. A useful prompt names the failing test, the symptom, and the question: which fixtures does this test read, which does it write, and which mutable state survives after teardown.
Official Claude Code best practices recommends precise prompts with file names and symptoms. Applied here, the prompt produces a map of fixture ownership that a reviewer can check against the inventory from the earlier step. Discrepancies are the interesting findings: a fixture that writes but does not restore, or a test that reads a global no fixture claims.
Ask for the map before proposing a fix. A fix proposed from an incomplete ownership map usually moves the leak rather than removing it.
| Question to Claude Code | Answer that indicates a leak | Follow-up |
|---|---|---|
| Which globals does this test read? | A global written by another test’s fixture | Make the dependency explicit |
| Which fixtures restore their state? | A fixture that overrides without restoring | Add teardown |
| What survives after teardown? | Rows, files, or flag values | Name the cleanup owner |
| Which fixtures share a resource? | Two fixtures writing one row | Split or scope down |
Document intentional shared state
Some shared state is a deliberate design choice. A read-only reference dataset, a cached build artifact, or a compiled fixture that is expensive to recreate can be shared across the run. The requirement is documentation and synchronization, not elimination.
| Intentional shared state | Reason | Synchronization rule | Risk |
|---|---|---|---|
| Reference country list | Large, never mutated | No test writes to it | Leak if a test mutates |
| Compiled parser fixture | Expensive to build | Read-only after setup | Stale if the grammar changes |
| Shared read-only database | Realistic volume | Only SELECT in tests | Cross-test writes corrupt it |
| Worker-scoped temp root | Reduces directory churn | Unique subdir per test | Collision if names are not unique |
Document the rule that protects the sharing. A shared fixture with no stated rule is an accident waiting for a new test to violate it. Write the rule where the fixture is defined so a reader encounters it before writing the test that breaks it.
Worked example: a leaked feature flag
Suppose a behavior test overrides a feature flag by assigning directly to a module-level dictionary and never restores it. The test passes alone. It also passes in the full suite until another test that asserts the default flag value runs after it, at which point that test fails with no code change.
The inventory step identifies the override as mutable shared state with no cleanup owner. The fix is a fixture that saves the original value, applies the override, yields to the test, and restores the original in teardown.
After the fix, run the same test twice in one session and then the full suite in randomized order. Both runs pass, and the flag returns to its default after every test. Record the cleanup owner in the fixture name so the next engineer does not reintroduce the direct assignment.
Two verification runs are worth adding for this specific leak. The first runs the offending test twice in a single session, which catches a teardown that does not restore. The second runs the full suite in randomized order, which catches the ordering assumption directly. Either run would have found the leak before parallelism exposed it in a harder-to-read failure report.
The concrete win is a suite that produces the same result in any order, which is the precondition for running it in parallel. The concrete loss is that the fresh fixture cannot remove flakiness caused by real timing, network, or thread-safety issues (F022). The practical implication is to make setup explicit and cleanup owned before increasing parallelism, because parallelism amplifies whatever isolation discipline already exists.
Connect the method to the rest of the batch
Isolation is one half of a trustworthy suite. The other half is assertions that check behavior, which is covered by mutation testing for weak assertions. Where a fixture feeds a boundary value, property tests for edge cases generate the inputs automatically.
When a fixture failure reveals a real bug rather than a setup problem, produce a minimal case with the minimal repro method. Record the investigation with the debug log that separates facts from hypotheses, including the order variation that exposed the leak. Concurrency-related failures need a different tool, covered by deterministic scheduling for async races. A fixture that is expensive because of duplicated setup logic points at the structural cause covered by duplication and reuse independence.
Where shared state is a cache or an allocation, comparing allocation snapshots covers the resource-growth angle. For the commit that introduced a hidden global, git bisect for regression hunts finds it.
For the surrounding test strategy, selecting tests for changed code keeps the fixture-heavy suite fast enough to run on every change, contract tests for API expectations covers the interface fixtures that integration tests share, and snapshot review addresses approvals that hide fixture drift. When randomized order surfaces a timing dependency rather than a state leak, deterministic handling of time and randomness is the matching guide. If the fixtures grew alongside sprawling test files, commit messages that record change intent help later readers understand why a fixture has the scope it does.
Structure and review benefit from adjacent disciplines: refactoring complexity hotspots covers the code that fixtures struggle to set up, duplication and reuse independence covers copy-pasted setup, and dead code removal removes fixtures nothing uses anymore. For an investigation that spans many files, auditing the context already loaded keeps the fixture trace focused on the failing test.
Release hygiene depends on the suite being trustworthy. Atomic commits keep fixture changes reviewable, merge protection and checks gate merges on a clean run, and the release checklist decides whether a flaky suite blocks a candidate. Where a leaked fixture causes intermittent failures in the merge queue, the merge queue guide covers the group-retry behavior that can mask the leak. If a fixture fix lands alongside a behavior change in one commit, splitting it keeps the isolation fix revertible on its own.
Data gap and future update
The fact pack contains no measured flake-reduction percentage for fresh fixtures, no benchmark comparing fixture scopes across frameworks, and no evidence that Claude Code consistently identifies fixture leaks faster than manual review. No such number is claimed here.
Pytest documentation identifies uncontrolled state and thread-safety as flake causes (F022) and documents fixtures as reusable setup (F023). The workflow for naming cleanup ownership and varying order before increasing parallelism is a derived practice (F024), not an official procedure with measured outcomes. Jest and Vitest configuration pages were used for the general lifecycle contrast, and lifecycle details differ between frameworks, so verify against the documentation for the framework in use.
A future update should add a reproducible case study with fixture inventory counts, randomized-order results before and after, and the parallel-worker outcome. Framework lifecycle behavior changes over time; recheck the cited pages before publishing.
One AI API Key option for OpenAI-format agents
Claude Code uses an Anthropic-format route, so the One AI free model IDs are not a Claude Code model source. The packet records Claude IDs as unavailable on 2026-11-27.
For a separate OpenAI-format agent, One AI API Key provides https://api.oneaiapikey.com/v1, one key, and 46 live free IDs. That option concerns a different client and request format, not a workaround for Claude Code authentication or quota. Review the free model list and eligibility details before choosing an agent route.
FAQ
Do fresh fixtures make a suite slower?
Fresh function-scoped fixtures cost more setup time than session-scoped shared ones. The trade is isolation against setup cost. Widen the scope only for resources that are genuinely immutable for the whole run and that no test asserts on the lifecycle of.
Does cleaning up fixtures remove all flakiness?
No. Pytest lists uncontrolled system state and thread-safety issues among flake causes (F022), and fixture design is only one control point. Timing, network, and concurrency causes need their own treatments.
Should cleanup run in reverse order?
Setup that acquires several resources should release them in reverse order, so a resource that depends on an earlier one is released before it. Verify the teardown actually runs after a failure rather than assuming the framework guarantees it (F024).
Can Claude Code find fixture leaks automatically?
It can trace which fixtures a test reads and writes and report mismatches against the inventory. That report is a lead for review, not a proof of correctness. A fixture that leaks through a framework lifecycle detail may still require manual confirmation.
When is shared state acceptable?
When the state is immutable for the whole run, no test asserts on its lifecycle, and the rule protecting it is documented. A shared read-only reference dataset is a reasonable choice; a shared mutable customer row is not.
More Claude Code troubleshooting
- Claude Code Static Analysis: Baseline the Noise
- Claude Code Git Stash: Recover Work Without Dropping It
- Claude Code Git Rebase: Choose a Branch Policy
- Claude Code Merge Conflicts: Resolve Behavior, Not Lines
- Claude Code SemVer: Decide Major, Minor, or Patch
- Claude Code Release Tags: Use Annotated Markers
- Claude Code Hotfix Backports: Cherry-Pick Carefully
- Claude Code Rollback: Plan a Revert Before Release
- Claude Code Changelog: Write Consumer-Facing Changes
Sources
- Official: Pytest fixtures, documenting fixtures as reusable setup (F023).
- Official: Pytest flaky tests, listing uncontrolled state and thread-safety as flake causes (F022).
- Official: Pytest parametrization, supporting per-case isolation for parametrized inputs.
- Official: Jest configuration, supporting the framework lifecycle contrast.
- Official: Vitest configuration, supporting the framework lifecycle contrast.
- Official: Claude Code best practices, supporting precise investigation prompts with named files.