python config_error ai_generated true

AssertionError: Dependency override for <function get_db at 0x...> was not applied; test used real database connection.

ID: python/fastapi-dependency-overrides-not-applied

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2025-06-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
0.100.x active — — —
0.110.x active — — —

Root Cause

app.dependency_overrides keyed on a different function object than the one used in the route (e.g., re-imported module or wrapped dependency).

generic

中文

app.dependency_overrides 使用的键与路由中实际使用的函数对象不同(例如模块被重新导入或依赖被包装)。

Workarounds

  1. 95% success
    from app.deps import get_db
    app.dependency_overrides[get_db] = lambda: test_session
    client = TestClient(app)
  2. 90% success
    Use `app.dependency_overrides.clear()` in teardown to avoid leakage between tests.

Dead Ends

Common approaches that don't work:

  1. 95% fail

    FastAPI requires the callable object, not its name.

  2. 85% fail

    TestClient uses the app passed to it; overrides elsewhere are ignored.