Performance: Overriding dependencies in tests
MEDIUM IMPACT
This affects the speed and reliability of test execution by controlling dependency injection without impacting the main app runtime performance.
from fastapi.testclient import TestClient with TestClient(app) as client: app.dependency_overrides[get_db] = override_get_db response = client.get('/items/1') assert response.status_code == 200 app.dependency_overrides.clear() # Clean up after test
app.dependency_overrides = {}
def test_read_item():
# Directly patching global dependencies without cleanup
app.dependency_overrides[get_db] = override_get_db
response = client.get('/items/1')
assert response.status_code == 200
# No cleanup leads to side effects in other tests| Pattern | App Context Rebuilds | Test Isolation | Resource Usage | Verdict |
|---|---|---|---|---|
| Global overrides without cleanup | Multiple per test suite | Poor - side effects possible | High - memory leaks risk | [X] Bad |
| Scoped overrides with cleanup | Single per test | Good - isolated tests | Low - efficient resource use | [OK] Good |