python
runtime_error
ai_generated
true
ValueError: Dependency 'get_db' has already been overridden
ID: python/fastapi-dependency-override-error
80%Fix Rate
81%Confidence
0Evidence
2024-06-30First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
在测试中多次覆盖同一个FastAPI依赖项
generic中文
在测试中多次覆盖同一个FastAPI依赖项
Workarounds
-
90% success 使用context manager管理依赖项覆盖
with TestClient(app) as client: app.dependency_overrides[get_db] = override_get_db response = client.get('/') -
85% success 在测试fixture中清理覆盖
@pytest.fixture def client(): app.dependency_overrides = {} yield TestClient(app)
Dead Ends
Common approaches that don't work:
-
尝试使用不同的依赖项名称
60% fail
原始依赖项仍被覆盖,新名称不匹配
-
在每次测试前重置依赖项
40% fail
app.dependency_overrides是全局状态,重置可能导致测试间污染