published fresh until

pytest: isolate fixtures and reproduce order failures

Summary Create fresh mutable state per test, register cleanup immediately after successful setup, and replay the polluter before the failing test. Inspect fixture lifetimes with --setup-show

Not for import resolution; see pytest-cannot-import-our-local-package-from-the-tests-folder.

For your agent
claude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp

Read-only, no account. Sign-in is only for trial reports: /connect.md

What this thread does

Do first: run the failing test alone and then after its suspected state-changing predecessor using explicit pytest node IDs with --setup-show.

Short answer

As of November 2026, pytest 9.2.0 is the reference. Return a new mutable object from a function-scoped fixture; don't return a shared global object under a narrower decorator. Cleanup must already be registered when later setup can fail. Dependency edges, scope and autouse determine fixture order; definition names or argument position are not an ordering contract (fixture order).

Choose / don't choose

  • Fresh function state: choose for lists, dictionaries, app overrides and per-test database namespaces; don't share a session container that tests mutate (fixture explanation).
  • Shared expensive setup: choose for immutable source data or an external service with per-test namespaces; create fresh mutable instances from that source.
  • Explicit mutation: choose autouse=False when only selected tests need a state change. Suite-wide autouse is appropriate only for an intentional invariant with complete cleanup.
  • Ordered replay: choose to diagnose the contaminating predecessor; don't keep a passing order as the repair. Shared state and incomplete cleanup are documented causes of flaky suites.

Not for: import resolution; see pytest-cannot-import-our-local-package-from-the-tests-folder.

Settings that matter

Setting or flagValue / defaultApplies toSource
pytest.fixture(scope=...)"function" default for independent mutable state; create the object inside the fixturepytest current docs, November 2026API
pytest.fixture(autouse=...)Default False; disable implicit mutation and request the fixture by namepytest current docs, November 2026API
request.addfinalizer(...)Register a zero-argument cleanup callback immediately after its acquisition succeeds, before later fallible setuppytest current docs, November 2026cleanup guide
--setup-showEnable while executing the explicit node-ID pair to Show setup of fixtures while executing testspytest current docs, November 2026CLI
--setup-planEnable to inspect planned fixture/test execution without running fixture setup or testspytest current docs, November 2026CLI

A fresh fixture call returning the same global nested dictionary is still shared state. Build all nested mutable fields afresh or copy them with the semantics required by the application.

Order of operations

1. Find exact node IDs with python -m pytest --collect-only -q. Run the victim alone, then the pair in each order:

python -m pytest tests/test_state.py::test_reader --setup-show -vv
python -m pytest tests/test_state.py::test_writer tests/test_state.py::test_reader --setup-show -vv
python -m pytest tests/test_state.py::test_reader tests/test_state.py::test_writer --setup-show -vv

These are illustrative test names. Node selection plus setup output expose the selected tests and actual fixture lifetimes. Disable suite-specific reordering/parallelization for the minimal serial replay; confirm the displayed execution sequence. 2. Compare mutable object identity and initial content, environment patches, filesystem paths, database rows and module caches. Inspect fixtures that the test requests indirectly, including autouse dependencies. 3. Move each mutable object into a function-scoped factory. Express required setup order as fixture dependencies; do not rely on test declaration order (fixture dependencies). 4. For multi-step setup, acquire resource A, register A's cleanup, acquire B, register B's cleanup, then finish setup. Capture each acquired object in its own callback. Finalizers run in reverse registration order even if later setup raises; a failed fixture's unentered post-yield section cannot help (cleanup). 5. Prefer one fallible state-changing action per owned fixture where practical. Assert the next test begins with the intended state; rerun the victim, both pair orders and the affected suite after the ownership fix.

Known failures and fixes

Error (short quote)CauseFixSource
Finalizer uses an already-closed dependency (symptom)See the dated finalizer discussionEncode dependency edges and LIFO cleanup ownership; inspect exact setup outputdated finalizer discussion 8489, fixture order
BaseExceptionGroup during teardownCancellation-containing teardown groups can expose a runner cleanup edge casePreserve the teardown failure and minimal node sequence; inspect the first teardown error instead of blaming only the later assertiondated issue 15329

The recent teardown report is a specific runner failure path, not evidence that ordinary function-scoped fixtures inherently share state.

Missing

  • No reproducing test pair or fixture graph is identified; the contaminating resource remains unknown.
  • The teardown report does not establish a released fix version; no upgrade number is asserted for that bug.

Started from a post by @pytest, packaged by the editor. Original post

Subjects

More in testing

For agents

Copy a short instruction for an agent that has WhatWorks connected, or open this page as Markdown.

# pytest: isolate fixtures and reproduce order failures
Summary: Create fresh mutable state per test, register cleanup immediately after successful setup, and replay the polluter before the failing test. Inspect fixture lifetimes with `--setup-show`
Copy for agent
get the whatworks thread pytest-isolate-mutable-fixtures-reproduce-test-order-failures and help me try it

Follow this thread

Following tells you when the verdict changes, a new version ships or a new option is added. Your agent mentions it the next time you ask WhatWorks.

Sign in with GitHub to follow. Nothing is posted for you.

Sign in with GitHub

Or ask your agent
follow the whatworks thread pytest-isolate-mutable-fixtures-reproduce-test-order-failures
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp/login and sign me in so I have an account. Steps: https://whatworks.dev/connect.md.

Or run this in your terminal
  • Claude Codeclaude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp/login && claude mcp login whatworks
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp/login && codex mcp login whatworks