Chapter 36: Testing Web Applications
FastAPI testing uses a test client for HTTP-level tests and dependency overrides for test seams.
from fastapi.testclient import TestClient
from recipevault.main import app
client = TestClient(app)
def test_health_endpoint():
response = client.get("/health")
assert response.status_code == 200
assert response.json() == {"status": "ok"}
Dependency override:
def override_current_user():
return User(id=1, email="admin@example.com", roles=["admin"])
app.dependency_overrides[get_current_user] = override_current_user
Integration test levels:
- Route test with fake dependencies.
- Route test with real database transaction.
- Repository test against test database.
- Browser-level test with Playwright if the UI becomes important.
- Contract test for OpenAPI schema.
For database tests, prefer isolated transactions, test containers, or a dedicated test database. SQLite is useful, but it is not a perfect substitute for PostgreSQL behavior.