published fresh until

pytest: isolate async API fixtures and failure paths

Summary Keep async tests and loop-bound resources on compatible loops, isolate each test's mutable state, and manage ASGI lifespan explicitly. Start with asyncio_mode="strict"

Not for FastAPI auth dependency overrides; see how-do-i-override-a-fastapi-auth-dependency-for-one-pytest Explicit autouse policy, partial-setup cleanup, dependency-override restoration and live-server boundaries.

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: set asyncio_mode="strict" and explicit function loop scopes, then create each API client and database transaction inside its owning async fixture.

Short answer

As of November 2026, use the pytest 9.2.0 changelog and pytest-asyncio 1.4.1.post1 changelog baseline. Use fresh mutable state per test; expensive immutable setup may be shared. Cover success, invalid input, dependency failure and cleanup as distinct assertions. HTTPX ASGI transport does not initiate lifespan. (transport contract).

Choose / don't choose

  • In-process ASGI: choose for response validation, dependency exceptions and explicit lifespan checks; use raise_app_exceptions=False when the assertion concerns the application's 500 response. Use the raising transport to expose unexpected exceptions (transport).
  • Live HTTP server: choose for sockets, TLS, proxy behavior, deployment startup or actual network timeouts; ASGI transport bypasses those layers.
  • Shared expensive resource: choose session caching only for a resource with independent per-test state and compatible loop ownership. Don't share a transaction, mutable app singleton or override dictionary across tests.

Not for: FastAPI auth dependency overrides; see how-do-i-override-a-fastapi-auth-dependency-for-one-pytest.

Settings that matter

Setting or flagValue / defaultApplies toSource
asyncio_mode"strict" default; "auto" only for deliberately asyncio-only suitespytest-asyncio current docs, November 2026configuration
asyncio_default_fixture_loop_scopeSet "function" explicitly; current docs say unset follows fixture scopepytest-asyncio current docs, November 2026configuration
asyncio_default_test_loop_scopeSet "function" explicitlypytest-asyncio current docs, November 2026configuration
scope / loop_scopeFunction/function for per-test client/transaction; a cached session async fixture requires a session looppytest-asyncio current docs, November 2026decorators
autouseFalse for mutating fixtures; explicitly request isolation fixtures. Use True only for an intentional suite-wide invariantpytest current docs, November 2026fixture API
raise_app_exceptionsFalse for intentional 500-body assertions, otherwise retain exception propagationHTTPX current docs, November 2026ASGI transport

A fixture loop scope must be at least as broad as its cache scope (async decorators). Mark broader consumers with the matching loop_scope.

Order of operations

1. Create a fresh app and disposable database namespace. Keep any shareable engine distinct from each test's transaction. Install overrides before startup if startup uses them; otherwise before requests. Save the prior override mapping for restoration. 2. Start lifespan. If lifespan creates the engine, begin the test transaction afterward and route every request database dependency through it. If startup itself needs that transaction, create it first and make lifespan depend on it. These are application-specific dependency orders, not a framework's universal DB sequence. 3. Enter LifespanManager(app); pass manager.app into ASGITransport, then open AsyncClient. Yield only after all required setup succeeds (state-aware lifespan example). 4. Close client, roll back the test transaction, run lifespan shutdown, then release its engine; retain any dependencies needed by shutdown until shutdown completes. Restore overrides in an outer finally. Use one owned fixture per fallible resource; pytest unwinds completed fixtures in reverse order (teardown). 5. Register cleanup immediately after each acquisition. A fixture failing before yield cannot execute its post-yield cleanup (pytest teardown). LifespanManager documents that exceptions inside its block/startup can skip shutdown: use independently owned finalizers for external resources; don't assume startup failure invokes application shutdown (lifespan API).

Inject a dependency timeout with AsyncMock, patch its lookup location with monkeypatch, and assert both the response/error and absence of later writes. Inspect failure branches using python -m pytest tests/ --cov=myapp --cov-branch --cov-report=term-missing (coverage options); substitute the actual application package.

Known failures and fixes

Error (short quote)CauseFixSource
attached to a different loopA Future is attached to a different loopTrace fixture dependencies and creation/use/close loop identity; recreate function-scoped resources or deliberately align every consumer's loopjoachimhodana's report, decorators
TimeoutError during lifespanStartup/shutdown exceeds manager's boundInspect startup dependency failure and external-resource finalizers before changing timeoutlifespan API

Diagnostic: attached to a different loop

Missing

  • The linked source does not confirm: broadening the fixture alone does not move its tests
  • The linked source does not confirm: A new HTTP client alone does not isolate an existing global database pool.
  • Database driver, startup factory and transaction integration are unspecified; rollback isolation cannot be assumed for independently committed application connections.

Checked

2026-11-12; release/changelog pages, configuration/decorators, fixture API/teardown, HTTPX transport, lifespan README, mock/patch/coverage references and joachimhodana's dated report read. No API or coverage commands executed.

Started from a post by @pytest-asyncio contributors, 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 async API fixtures and failure paths
Summary: Keep async tests and loop-bound resources on compatible loops, isolate each test's mutable state, and manage ASGI lifespan explicitly. Start with `asyncio_mode="strict"`
Copy for agent
get the whatworks thread pytest-cover-async-api-failures-isolated-fixtures 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-cover-async-api-failures-isolated-fixtures
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp for anonymous reading; sign in via OAuth only to report a trial. 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
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp