Good Code
The good version replaces the auth dependency with a test implementation and resets overrides after the assertion.
Lesson 09
Override dependencies in tests instead of calling external services or patching internals.
from fastapi.testclient import TestClient
from app.main import app
from app.auth import current_user
def fake_current_user():
return {"id": 1, "role": "reviewer"}
def test_approve_review():
# Replace real auth with a fake user for this test.
app.dependency_overrides[current_user] = fake_current_user
client = TestClient(app)
response = client.post("/reviews/10/approve")
# Clear overrides so later tests do not inherit this setup.
app.dependency_overrides = {}
assert response.status_code == 200from fastapi.testclient import TestClient
from app.main import app
client = TestClient(app)
def test_approve_review():
response = client.post(
"/reviews/10/approve",
# Production-like tokens make the test depend on real auth behavior.
headers={"Authorization": "Bearer production-token"},
)
assert response.status_code == 200The good version replaces the auth dependency with a test implementation and resets overrides after the assertion.
The bad version depends on a production-like token and whatever auth service is behind it. Tests become slow, flaky, and hard to reason about.