Lesson 6 of 9 · 24m
Testing FastAPI Services Like Production Code
A practical test pyramid for FastAPI: contract tests at the HTTP boundary, focused service tests, dependency overrides, and the mistakes that make suites lie.
A FastAPI test suite can look green while proving almost nothing. The reason is usually wrong altitude: tests either exercise Pydantic instead of your logic, or they spin up the whole application for every tiny rule. Good suites test behavior at the layer where behavior lives.
Test through HTTP for contracts
FastAPI's test client is valuable because it exercises routing, validation, serialization, dependencies, middleware, and status codes together:
from fastapi.testclient import TestClient
def test_rejects_short_password(client):
response = client.post("/users", json={
"email": "sam@example.com",
"password": "short",
})
assert response.status_code == 422These are contract tests: they prove what a real client experiences. Keep them few enough to stay fast, but broad enough to catch integration drift.
Override infrastructure, not behavior
dependency_overrides is the seam for replacing databases, clocks, external services, and queue clients:
app.dependency_overrides[get_db] = override_get_db
app.dependency_overrides[send_email] = FakeEmailSender()If the override reimplements the endpoint's business decision, the test is no longer testing the decision. A fake should simulate infrastructure faithfully — failure included — not grant wishes.
Service-layer tests carry most business logic
Put domain rules in functions that do not know about HTTP. Then test those directly:
def test_cannot_close_paid_invoice_twice(db_session):
invoice = create_paid_invoice(db_session)
with pytest.raises(ConflictError):
close_invoice(db_session, invoice.id)This keeps the pyramid healthy: many fast service tests, fewer HTTP contract tests, and a handful of true end-to-end tests against containers or staging.
Async tests need the real concurrency model
Use pytest-asyncio or AnyIO when the path under test is genuinely async. A common lie is testing async code by forcing it into a synchronous helper that never hits concurrent behavior. Another is using async endpoints around blocking database drivers and then wondering why tests pass but production stalls.
Test failure modes, not only happy paths
Every integration should answer: what happens on timeout, malformed response, duplicate job, expired token, conflicting state, and partial failure? These tests are where senior engineering shows up. The happy path is necessary; the failure path is what pages you at 3 a.m.
Database fixtures decide whether tests can be trusted
Use isolated transactions or fresh schemas. Shared mutable test data creates order dependence and phantom failures. If your test needs ten lines of unrelated setup, build factories that encode only what matters.
Field notes
- A 200 assertion alone is weak; assert status, body shape, side effects, and security-relevant omissions.
- Reset
dependency_overridesafter each test or leakage becomes cross-test contamination. - Contract tests should include auth failure cases, not just authenticated success.
- Use time providers instead of
datetime.now()deep in logic; otherwise expiry tests become flaky.
Was this lesson helpful?