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
80%修复率
87%置信度
0证据数
2025-06-15首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 0.100.x | active | — | — | — |
| 0.110.x | active | — | — | — |
根因分析
app.dependency_overrides 使用的键与路由中实际使用的函数对象不同(例如模块被重新导入或依赖被包装)。
English
app.dependency_overrides keyed on a different function object than the one used in the route (e.g., re-imported module or wrapped dependency).
解决方案
-
95% 成功率
from app.deps import get_db app.dependency_overrides[get_db] = lambda: test_session client = TestClient(app)
-
90% 成功率
Use `app.dependency_overrides.clear()` in teardown to avoid leakage between tests.
无效尝试
常见但无效的做法:
-
95% 失败
FastAPI requires the callable object, not its name.
-
85% 失败
TestClient uses the app passed to it; overrides elsewhere are ignored.