python
runtime_error
ai_generated
true
值错误:依赖项'get_db'已被覆盖
ValueError: Dependency 'get_db' has already been overridden
ID: python/fastapi-dependency-override-error
80%修复率
81%置信度
0证据数
2024-06-30首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
在测试中多次覆盖同一个FastAPI依赖项
English
在测试中多次覆盖同一个FastAPI依赖项
解决方案
-
90% 成功率 使用context manager管理依赖项覆盖
with TestClient(app) as client: app.dependency_overrides[get_db] = override_get_db response = client.get('/') -
85% 成功率 在测试fixture中清理覆盖
@pytest.fixture def client(): app.dependency_overrides = {} yield TestClient(app)
无效尝试
常见但无效的做法:
-
尝试使用不同的依赖项名称
60% 失败
原始依赖项仍被覆盖,新名称不匹配
-
在每次测试前重置依赖项
40% 失败
app.dependency_overrides是全局状态,重置可能导致测试间污染