In a FastAPI suite, why does an entry left in app.dependency_overrides reach later tests, and how should fixtures restore it?
answer
- the dict lives on the app
- one app object per test run
- TestClient holds no copy
- teardown runs even on failure
basics
~20 sapp.dependency_overrides is a dict on the module-level FastAPI object, shared by every test and every TestClient, and nothing resets it. Set overrides in yield fixtures, remove them in teardown, and add an autouse guard that fails a test leaving entries behind.
solid answer
~40 sThe `FastAPI` instance is created once when its module is imported, and `dependency_overrides` is a plain `dict` on it. `TestClient(app)` keeps no copy, and FastAPI reads the dict on every request, so an entry one test forgets stays active for every later test in the process, with any new client. That is why a test can pass alone and fail in the full run, or pass only because an earlier test installed a fake. The fix is ownership: each override lives in a `yield` fixture that removes its own key with `app.dependency_overrides.pop(key, None)` after the `yield`, which pytest runs even when the test fails. An autouse fixture that asserts the dict is empty after each test names the offender instead of leaving a far-away failure.
code
python · 48 linesfrom typing import Annotated
import pytest
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
class PaymentClient:
def charge(self, cents: int) -> str:
raise RuntimeError("would call the real payment provider")
def get_payment_client() -> PaymentClient:
return PaymentClient()
app = FastAPI()
@app.post("/checkout")
def checkout(payments: Annotated[PaymentClient, Depends(get_payment_client)]):
return {"charge": payments.charge(1999)}
class FakePaymentClient:
def charge(self, cents: int) -> str:
return f"fake-{cents}"
@pytest.fixture(autouse=True)
def no_leftover_overrides():
yield
leftover = list(app.dependency_overrides)
app.dependency_overrides.clear()
assert not leftover, f"test left overrides behind: {leftover}"
@pytest.fixture
def fake_payments():
fake = FakePaymentClient()
app.dependency_overrides[get_payment_client] = lambda: fake
yield fake
app.dependency_overrides.pop(get_payment_client, None)
def test_checkout_charges(fake_payments):
response = TestClient(app).post("/checkout")
assert response.json() == {"charge": "fake-1999"}go deeper
Recall that overrides live on the app object and must be removed after each test.
Explain why TestClient does not isolate overrides and why teardown in a yield fixture beats a cleanup line in the test body.
Diagnose an order-dependent failure as a leaked override, and add an autouse guard so the leaking test fails instead of a later one.
Decide whether the suite uses an app factory for isolation or a shared app with strict fixture-owned overrides, and enforce the choice in conftest.
## Where the state actually lives In most FastAPI projects `app = FastAPI()` sits at module level in something like `app/main.py`. Python imports that module once per test process, so every test in the run talks to **the same application object**. `app.dependency_overrides` is an attribute of that object: an ordinary `dict`, empty by default. Three facts about how FastAPI uses it explain the leak: - **`TestClient` does not own it.** `TestClient(app)` wraps the app; it neither copies nor resets the dict. Creating a fresh client per test changes nothing. - **It is read on every request.** During dependency resolution FastAPI looks each dependency up in the dict, so whatever is in it at request time applies. - **Nothing clears it.** There is no automatic reset at the end of a test, of a `with TestClient(app)` block or of the lifespan. So an override that one test adds and never removes is active for every later test in the same process. ## The symptoms The leak rarely fails where it was caused: - a test passes when run alone but fails in the full suite, because an earlier test left a fake payment client and this test expected the real one to be refused; - worse, a test passes **only** because an earlier test installed a fake, and fails when run alone or in a different order; - results change when the suite is split across workers or reordered, because the set of earlier tests changes. A useful first check when a FastAPI test is order-dependent: print `app.dependency_overrides` at the start of the failing test. ## Restoring the dict correctly The pattern that holds up is **every override has an owner, and the owner cleans up**: 1. Register overrides in pytest `yield` fixtures, never in the test body or at module level. 2. Remove them after the `yield`. Fixture teardown runs even when the test fails, unlike a cleanup line at the end of the test body, which an assertion failure skips. 3. Prefer `app.dependency_overrides.pop(get_payment_client, None)` for the key the fixture added. `clear()` also works, but it removes entries other active fixtures installed; that matters when a test body or a nested helper calls it while a session fixture's override is still needed. 4. Add an autouse fixture that, after each test, records what is left in the dict, clears it, and fails if anything was left. The failure then appears on the test that leaked, not on an innocent one later. | Approach | Survives a failing assertion | Leaves other fixtures' overrides alone | Finds the leaking test | |---|---|---|---| | cleanup line at end of test body | no | depends on the call | no | | `try` / `finally` in the test | yes | depends on the call | no | | `yield` fixture with `pop` in teardown | yes | yes | no | | autouse guard asserting the dict is empty | yes | not its job | yes | ## Alternatives that avoid shared state - **An app factory.** If the project builds the app with a `create_app()` function, a fixture can create a fresh `FastAPI` object per test, each with its own empty `dependency_overrides`. This costs building the routes each time and only works if no module-level code captured the global `app`. - **Reassigning the dict.** `app.dependency_overrides = {}` also resets it, because FastAPI reads the attribute from the app on each request; snapshot-and-restore (`saved = dict(app.dependency_overrides)` before, reassign after) restores exactly the previous state for nested fixtures. ## Related shared state Overrides are not the only process-wide state a FastAPI suite carries. A `@lru_cache`-decorated `get_settings` keeps its first `Settings` object for the life of the process, and an override of it is just another dict entry with the same cleanup rules. Fixture scopes, ordering and plugin behaviour themselves belong to the pytest material. ## Summary The leak is structural: one app object, one dict, read on every request, reset by nothing. Treat each entry like any other global you mutate in a test: a fixture adds it, the same fixture removes it in teardown, and an autouse guard makes forgetting loud.
- Why does creating a new TestClient in each test not isolate the overrides?Because the dict belongs to the `FastAPI` object, not to the client. Every `TestClient(app)` wraps the same app, and FastAPI reads `app.dependency_overrides` on each request, so whatever an earlier test left there applies to the new client too.
- When is clear() in teardown a problem compared with pop()?When several fixtures each install an override for one test, or when a helper clears in the middle of a test. `clear()` removes all of them at once, so a session override another fixture still needs disappears. Popping only the fixture's own key keeps each fixture responsible for exactly what it added.
- Each TestClient instance keeps its own copy of the overrides.
- FastAPI resets dependency_overrides when the with TestClient(app) block exits.
- A cleanup line at the end of the test body runs even if an assertion fails.
- If a test passes alone, it cannot depend on overrides left by other tests.
- Overrides are reset automatically between test modules.