Test FastAPI routes with dependency overrides
Test routes, tenant boundaries, lifespan and database integration with pytest, fakes and dependency overrides.
By Invicly Tech, , in FastAPI with Python for AI Backends. About 12 minutes to read.
In short
FastAPI routes get their database sessions, current user and model client through dependencies, so tests can swap any of them for a fake with app.dependency_overrides. Fast unit-style tests use fakes and TestClient; slower integration tests run the real lifespan against a real PostgreSQL database. Together they prove the contract, the validation and the tenant boundary without calling a paid model.
Think of it like this: Dependency overrides are like a stunt double: the scene, script and camera stay the same, only the risky part is played by someone safe.
Explained simply
A test is a small program that calls your code and checks the result. For a FastAPI service, the most useful tests send a real HTTP request to a route and look at the status code and JSON that come back. You do not need to start a server for this. FastAPI's TestClient calls the app directly inside the test process.
Most routes need things from outside: a database session, the signed-in user and a model client. FastAPI hands these to the route through dependencies. In a test you can swap any dependency for a fake by putting it in app.dependency_overrides. The route code stays the same; only what it receives changes.
Good tests also try to break the route. Send a missing field, a negative page number or a file that is too big, and check for a clear 422 or 413 error. Sign in as a user from one tenant and ask for another tenant's document. The service must answer as if the document does not exist.
Fakes are fast but they can lie. A fake database will never reject bad SQL. So keep a smaller group of integration tests that start the real app lifespan and talk to a real PostgreSQL database running in Docker. Run the fast tests all the time and the slow ones before you merge.
Press Play on a diagram to walk through it one step at a time.
- 1Set override
app.dependency_overrides[get_model] = fake
- 2Send request
TestClient or HTTPX AsyncClient
- 3Route runs
Validation, auth, handler, serializer
- 4Assert
Status code, JSON body, calls on the fake
- 5Clear override
Reset so the next test starts clean
- Milliseconds per test
- Fake model, fake user, in-memory store
- Cover validation and status codes
- Run on every save
- Seconds per test
- Real PostgreSQL and real lifespan
- Cover SQL, migrations and tenant filters
- Run before merge and in CI
- 1A few end-to-end checks
Compose stack, real worker, fake model
- 2Integration tests
Real PostgreSQL, real lifespan, migrations applied
- 3Route tests with overrides
Fake user, fake model, validation and tenant rules
- 4Unit tests
Pure functions: chunking, scoring, prompt building
In depth
How dependency_overrides works
When FastAPI resolves a route, it reads the Depends(...) markers in the route signature. Before calling each dependency function, it checks app.dependency_overrides, a plain dictionary whose keys are the original functions and whose values are replacements. If a key matches, FastAPI calls the replacement instead, and it still resolves the replacement's own parameters, so a fake can depend on other dependencies too.
The key must be the exact function object used in Depends. If your route uses Depends(get_session) imported from app.db, override app.db.get_session, not a copy defined somewhere else. Overrides also apply to sub-dependencies: overriding get_session replaces it everywhere in the graph, including inside get_current_user if that uses a session.
Because the dictionary lives on the app object, it is shared by every test. Put overrides in a pytest fixture that clears them after the test with a yield.
- Key: the original dependency function
- Value: any callable, including a lambda or a class
- Applies to nested dependencies as well
- Clear with app.dependency_overrides.clear()
TestClient, HTTPX and the lifespan
TestClient is synchronous, so tests stay plain def functions even when routes are async. It is built on HTTPX, so the request and response objects feel familiar. If you use it in a with block, it runs the app lifespan: startup code before the block, shutdown code after it. That matters when the lifespan creates the HTTP client, database pool or settings your routes read from app.state.
Sometimes you need async tests, for example to await a database query inside the test itself. Then use httpx.AsyncClient with transport=httpx.ASGITransport(app=app) and a base_url such as http://test, and mark the test with @pytest.mark.anyio as the FastAPI docs show. ASGITransport does not send lifespan events. If startup must run, wrap the app in LifespanManager from the asgi-lifespan package, or create the resources in a fixture yourself.
- Sync test functions
- Runs lifespan in a with block
- Simplest choice for route tests
- Cannot await inside the test
- Async test functions with anyio
- No lifespan unless you add a manager
- Can await DB checks in the test
- Good for async fixtures
Testing invalid input and tenant boundaries
Write one test per rule in your contract. Validation tests send bad payloads and check the error shape your clients depend on: status 422, the field location and your error code if you wrap validation errors. Size tests send a body just over the limit and check for 413.
Tenant tests need two tenants in the fixtures, for example contoso and fabrikam, each with its own user and document. Then check every route that takes an ID: read, update, delete and list. A fabrikam user who asks for a contoso document ID should get 404, the same as for an ID that never existed. A list call should return only fabrikam rows. These tests are cheap to write and catch the most damaging bug a multi-tenant API can have.
- Parametrize over routes so each new route gets the check
- Assert on the error code, not the English message
- Test list endpoints, not only single reads
- Seed IDs that look valid, not obviously fake ones
Integration tests with a real database
Start PostgreSQL in Docker, either from your Compose file or with a library such as testcontainers. Run alembic upgrade head once per test session so the schema matches production, including pgvector if you use it. Then give each test a clean state. A common pattern opens a connection, begins a transaction, binds the test session to it and rolls everything back at the end, which is fast and leaves no data behind. If your code commits on its own, truncate the tables between tests instead.
Override get_session so routes use the test session. Keep the fake model and fake identity provider; the goal is to test your SQL and tenant filters, not a remote service. Mark these tests, for example with @pytest.mark.integration, so you can run them separately in CI.
Learn it in 5 short steps
About 50m each. Track them with a timer in your plan.
- 1Use TestClient or async HTTPX~50m
- 2Override dependencies with fakes~50m
- 3Test invalid input and tenant boundaries~50m
- 4Run lifespan in tests~50m
- 5Use a real database in integration tests~50m
Key points
- Override the dependency function itself, using the same function object the route declared with Depends.
- Use TestClient as a context manager, or an explicit lifespan manager with HTTPX, when startup code must run.
- Test unhappy paths on purpose: missing fields, wrong types, oversized input and another tenant's IDs.
- A cross-tenant read should return 404, not 403, so the response does not reveal that the record exists.
- Keep at least a few tests against real PostgreSQL; fakes cannot catch SQL or migration bugs.
Key terms
Tap a card to flip it. 0/6 known
Examples
from fastapi.testclient import TestClient
from app.main import app
from app.deps import get_current_user
def as_user(tenant: str):
return lambda: {"id": "u1", "tenant_id": tenant}
def test_other_tenant_gets_404():
app.dependency_overrides[get_current_user] = as_user("fabrikam")
with TestClient(app) as client:
r = client.get("/documents/doc-contoso-1")
app.dependency_overrides.clear()
assert r.status_code == 404A user from fabrikam asks for a contoso document and must not see it.
A reusable fixture for fake dependencies
Step 1: write a FakeModel whose complete method returns a fixed answer and records the prompts it received. Step 2: in conftest.py, add a fixture that sets overrides for the model and the current user, yields a TestClient in a with block, then clears the overrides. Step 3: tests ask for the client fixture and stay short. Expected evidence: pytest shows the tests passing in well under a second, and fake.prompts lets you assert that the tenant's documents, and only those, went into the prompt.
import pytest
from fastapi.testclient import TestClient
from app.main import app
from app.deps import get_current_user, get_model
class FakeModel:
def __init__(self): self.prompts: list[str] = []
async def complete(self, prompt: str) -> str:
self.prompts.append(prompt); return "Refunds are accepted within 30 days."
@pytest.fixture
def client():
fake = FakeModel()
app.dependency_overrides.update({get_model: lambda: fake, get_current_user: lambda: {"id": "u1", "tenant_id": "contoso"}})
with TestClient(app) as c:
yield c, fake
app.dependency_overrides.clear()Checking every ID route for cross-tenant access
Step 1: seed one contoso document with ID doc-c1. Step 2: override the user so the caller belongs to fabrikam. Step 3: parametrize a test over the methods and paths that take a document ID. Step 4: assert 404 for each. Expected evidence: one passing test case per route in the pytest output. If someone adds a new route and forgets the tenant filter, adding it to the list makes the gap fail at once.
import pytest
ROUTES = [("GET", "/documents/doc-c1"), ("DELETE", "/documents/doc-c1"), ("GET", "/documents/doc-c1/chunks")]
@pytest.mark.parametrize("method,path", ROUTES)
def test_fabrikam_cannot_reach_contoso(fabrikam_client, method, path):
r = fabrikam_client.request(method, path)
assert r.status_code == 404Quick reference
- app.dependency_overrides[original_fn] = fake_fn replaces a dependency for every route.
- app.dependency_overrides.clear() after each test, ideally in a yield fixture.
- with TestClient(app) as client: runs startup and shutdown from the lifespan.
- AsyncClient(transport=ASGITransport(app=app), base_url="http://test") for async tests.
- ASGITransport skips lifespan events; use asgi-lifespan's LifespanManager if you need them.
- Cross-tenant reads return 404 so the response does not confirm the record exists.
- Run alembic upgrade head once per session against the test database.
- pytest -m "not integration" for the fast loop; pytest -m integration before merge.
Common mistakes
- Forgetting to clear dependency_overrides, so a fake leaks into later tests and hides real failures.
- Overriding a different function than the one passed to Depends, so the override silently does nothing.
- Using an HTTPX AsyncClient and expecting the lifespan to run; it does not unless you start it yourself.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write a test for GET /health that uses TestClient and asserts status 200 and the body {"status": "ok"}.
- Exercise 2medium
POST /chat requires a non-empty question of at most 2,000 characters. Write two tests: an empty question and a 2,001-character question both return 422.
- Exercise 3hard
Write an async integration test that uploads a document as contoso through the API, then checks directly in PostgreSQL that the new row has tenant_id contoso.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should I use TestClient or HTTPX AsyncClient?
- Start with TestClient; it is simpler and runs the lifespan. Switch to AsyncClient when the test itself needs to await something, such as an async database query.
- Do I need to mock the database for route tests?
- For fast route tests, overriding the session or repository with a fake is fine. Keep separate integration tests against a real PostgreSQL so SQL and migrations are covered too.
- Why does my async test say there is no event loop or skip itself?
- Async tests need a pytest plugin, such as the one that ships with anyio or pytest-asyncio, and the matching marker. The FastAPI docs use @pytest.mark.anyio.
- How many tenant tests are enough?
- At least one per route that takes an ID or returns a list. Parametrize over routes so new routes are easy to add.