Skip to content

Lesson 49 of 59Testing

Testing FastAPI

Test FastAPI with TestClient and async clients, override the database and auth, test lifespan and uploads, and snapshot the OpenAPI schema.

24 min read0/8 questions

Tests are what let you change a backend on a Friday without fear. They catch the 422 you introduced by renaming a field, the route that forgot to check ownership, the migration that broke a query. Take-home assignments and interviews for backend roles nearly always look at your tests, and FastAPI makes them pleasant to write because the whole app can be called in-process, without a running server. This lesson assumes the pytest basics from Testing with pytest in the Python course: test functions, fixtures, parametrize and mocking.

TestClient: call the app directly

TestClient wraps your ASGI app in an httpx client. Requests go straight into the app object, through middleware, dependencies and validation, exactly like real traffic, but no port, no Uvicorn and no network are involved.

tests/test_health.py
from fastapi.testclient import TestClient
 
from app.main import app
 
client = TestClient(app)
 
 
def test_health():
    response = client.get("/health")
    assert response.status_code == 200
    assert response.json() == {"status": "ok"}
 
 
def test_create_todo_validates_title():
    response = client.post("/todos", json={"title": ""})
    assert response.status_code == 422
    assert response.json()["detail"][0]["loc"] == ["body", "title"]

Run them with pytest, which finds files named test_*.py and functions named test_*, and reports any failing assert with the values involved:

uv add --dev pytestuv run pytest -q# ..                                                    [100%]# 2 passed in 0.31s

Every test follows the same shape: arrange the data, act by making one request, assert on the status code and body. Assert on both: a test that only checks status_code == 200 will happily pass while the body is wrong.

Quick check
Do you need to start Uvicorn before running tests that use TestClient(app)?
Need a nudge? A hint rules out a wrong answer.

httpx, httpx2 and the client under TestClient

TestClient is Starlette's, re-exported by FastAPI, and it is built on an HTTP client library. For years that library was httpx. In current Starlette (1.9, which FastAPI 0.161 uses) it is httpx2, and if only httpx is installed you get this on import:

StarletteDeprecationWarning: Using `httpx` with `starlette.testclient` is deprecated; install `httpx2` instead.

Starlette now tries import httpx2 first and falls back to httpx with that warning. The fix is one line:

uv add --dev httpx2

The test API you write does not change: client.get(...), json=, files=, headers= and response.json() all behave the same. fastapi[standard] currently pulls in both packages. If your pytest config turns warnings into errors (filterwarnings = ["error"], a good habit), this warning fails the whole suite after an upgrade, which is exactly how most teams find out. Because the httpx ecosystem is in transition, check the Starlette release notes before pinning, and use the same package for the async client below.

Fixtures and a test database

You do not want tests writing to your development database, and you want every test to start from a clean state. A pytest fixture is a function that prepares something for a test; tests receive it by naming it as a parameter. Fixtures with yield clean up afterwards, just like yield dependencies.

Put shared fixtures in tests/conftest.py. This one gives each test a fresh in-memory SQLite database and points the app at it with a dependency override:

tests/conftest.py
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
 
from app.db.session import get_db
from app.main import app
from app.models import Base
 
 
@pytest.fixture
def db():
    engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
    Base.metadata.create_all(engine)
    TestingSession = sessionmaker(bind=engine, expire_on_commit=False)
    with TestingSession() as session:
        yield session
    engine.dispose()
 
 
@pytest.fixture
def client(db):
    def override_get_db():
        yield db
 
    app.dependency_overrides[get_db] = override_get_db
    with TestClient(app) as test_client:
        yield test_client
    app.dependency_overrides.clear()
tests/test_todos.py
def test_create_then_read(client):
    created = client.post("/todos", json={"title": "Buy milk"})
    assert created.status_code == 201
    todo_id = created.json()["id"]
 
    fetched = client.get(f"/todos/{todo_id}")
    assert fetched.json() == {"id": todo_id, "title": "Buy milk", "done": False}
 
 
def test_missing_todo_is_404(client):
    assert client.get("/todos/999").status_code == 404

Each test asks for client, pytest sees that client needs db, builds both, and tears them down in reverse. That is dependency injection again, pytest style.

SQLite or a real PostgreSQL for tests?

In-memory SQLite is fast and needs no setup, but it is not PostgreSQL: it ignores some constraints, lacks types like JSONB and arrays, and handles concurrency differently. Many teams run tests against a real PostgreSQL started by docker compose or the testcontainers library, and keep them fast by wrapping each test in a transaction that is rolled back at the end instead of recreating tables. Use the same database engine in CI as in production for anything beyond a toy app.

Put it in order5 steps

Order what pytest does for test_create_then_read(client).

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Testing lifespan startup and shutdown

Look again at the client fixture: it uses with TestClient(app) as test_client. The with is not decoration. Only the with form runs your lifespan. Entering the block sends the ASGI lifespan.startup event, so your lifespan function runs up to its yield; leaving it sends lifespan.shutdown, so the code after yield runs.

app/main.py
@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.ready = True            # open pools, warm caches, load a model
    yield
    await close_pools()               # runs on shutdown
 
 
@app.get("/ready")
def ready(request: Request):
    return {"ready": getattr(request.app.state, "ready", False)}

Tested on FastAPI 0.161: TestClient(app).get("/ready") without with returned {"ready": false}, and the startup code never ran. Inside with TestClient(app) as c:, it returned {"ready": true}, and shutdown ran when the block ended. That gap explains a classic confusing failure: a test passes locally because a module-level client happened to work, then fails with AttributeError: 'State' object has no attribute 'pool' once someone moves pool creation into lifespan.

So you get two kinds of test for free:

  • Startup works. A test that only does with TestClient(app): pass proves the app boots: settings load, migrations are at head, connections open. A broken startup then fails one clear test instead of every test.
  • Shutdown cleans up. Pass a fake pool in through a dependency or app state, exit the with block, and assert that close was called. Leaked connections at shutdown are what make rolling deploys slow.

If lifespan connects to real services, tests that use it need those services, or overrides for them. Keep lifespan thin (create clients, store them on app.state or yield them as lifespan state) so tests can replace what it creates.

Quick check
Your lifespan creates app.state.pool. A test does client = TestClient(app) at module level and calls client.get('/orders'). What happens?
Need a nudge? A hint rules out a wrong answer.

Testing protected routes

Most routes need a logged-in user. You have two good options:

  • Override the auth dependency for tests about business logic. Fast and direct.
  • Log in for real through /token in a few tests that check the auth flow itself.
tests/conftest.py
from app.api.deps import get_current_user
 
 
@pytest.fixture
def as_user(client, db):
    user = make_user(db, email="ada@example.com")
    app.dependency_overrides[get_current_user] = lambda: user
    return user
 
 
def test_cannot_read_someone_elses_todo(client, db, as_user):
    other = make_user(db, email="sam@example.com")
    todo = make_todo(db, owner=other)
    assert client.get(f"/todos/{todo.id}").status_code == 404
 
 
def test_requires_token(client):
    assert client.get("/todos").status_code == 401   # no override, no header

That first test is the one people forget. "Logged-in user can read their own todo" is easy to get right; "logged-in user cannot read another user's todo" is where real security bugs hide.

Quick check
Which test is most likely to catch a real security bug?
Need a nudge? A hint rules out a wrong answer.

Testing uploads and auth overrides together

Real endpoints need several overrides at once. An avatar upload needs a user, a storage backend and a multipart body. File Uploads and Object Storage covered what to test about the file itself (magic bytes, size limits); here is how the pieces fit in one test.

tests/test_avatars.py
from app.api.deps import get_current_user, get_storage
from app.main import app
 
 
class FakeStorage:
    def __init__(self):
        self.objects: dict[str, bytes] = {}
 
    def put(self, key: str, data: bytes) -> None:
        self.objects[key] = data
 
 
def test_upload_stores_under_the_users_key(client, db):
    user = make_user(db)
    storage = FakeStorage()
    app.dependency_overrides[get_current_user] = lambda: user
    app.dependency_overrides[get_storage] = lambda: storage
 
    png = b"\x89PNG\r\n\x1a\n" + b"0" * 100
    r = client.post("/avatars", files={"file": ("me.png", png, "image/png")})
 
    assert r.status_code == 201
    assert list(storage.objects) == [f"avatars/{user.id}"]
    assert storage.objects[f"avatars/{user.id}"] == png
 
 
def test_upload_needs_a_token(client):
    files = {"file": ("me.png", b"\x89PNG\r\n\x1a\n", "image/png")}
    assert client.post("/avatars", files=files).status_code == 401

A few rules make overrides predictable:

  • The key is the function object. dependency_overrides[get_current_user] only works if the route depends on that exact function. If one route uses Depends(get_current_user) and another uses a wrapper get_active_user that calls it through Depends, overriding get_current_user also covers the wrapper, because FastAPI resolves sub-dependencies through the same table. Overriding the wrapper does not cover routes that use get_current_user directly.
  • Override at the lowest useful level. To test that get_active_user rejects disabled users, override get_current_user with a disabled user and let the real get_active_user run. You test your logic, not your fake.
  • No override means real auth. With no override and no header, OAuth2PasswordBearer itself answers 401, which is what test_upload_needs_a_token relies on. Tested on FastAPI 0.161, this route returned 201 with both overrides and 401 once the user override was removed.
  • Always clear. dependency_overrides is a plain dict on a global app. An override leaked from one test makes later tests pass for the wrong reason. Clear it in fixture teardown, as the client fixture does, never at the end of a test body where a failed assert would skip it.

Uploads need the python-multipart package installed, or FastAPI refuses to start routes with UploadFile or Form parameters. It is part of fastapi[standard].

Quick check
A test sets app.dependency_overrides[get_current_user] = lambda: admin and clears the dict as its last line. Its assert fails. What is the risk?
Need a nudge? A hint rules out a wrong answer.

The same ideas, runnable

Here are fixtures, overrides and fakes with nothing but plain Python. The service depends on a mailer; the test passes a fake that records emails instead of sending them.

Pythonfakes.py
class FakeMailer: def __init__(self): self.sent = [] def send(self, to, subject): self.sent.append({"to": to, "subject": subject}) def signup(email, users, mailer): email = email.strip().lower() if email in users: raise ValueError("email taken") users.add(email) mailer.send(email, "Welcome!") return {"email": email} def run_test(test): try: test() print("PASS", test.__name__) except AssertionError as err: print("FAIL", test.__name__, "-", err) def test_signup_sends_welcome(): users, mailer = set(), FakeMailer() # arrange signup(" Ada@Example.com ", users, mailer) # act assert mailer.sent == [{"to": "ada@example.com", "subject": "Welcome!"}] # assert def test_duplicate_email_rejected(): users, mailer = {"ada@example.com"}, FakeMailer() try: signup("ada@example.com", users, mailer) assert False, "expected ValueError" except ValueError: pass assert mailer.sent == [], "no email for a failed signup" run_test(test_signup_sends_welcome)run_test(test_duplicate_email_rejected)
Output
Press Run (⌘ Enter) to see what happens.

A fake is a working lightweight implementation (an in-memory mailer, an in-memory repository). A mock is an object that records calls so you can assert on them (unittest.mock.Mock). Prefer fakes for your own interfaces and mocks or HTTP stubs (like respx for httpx) for third-party services.

Factories for test data

Tests need data, and building full objects by hand in every test gets long and brittle. A factory creates a valid object with sensible defaults, and each test overrides only what matters to it.

Pythonfactories.py
import itertools _ids = itertools.count(1) def make_user(**overrides): n = next(_ids) user = {"id": n, "email": f"user{n}@example.com", "name": f"User {n}", "is_admin": False} user.update(overrides) return user print(make_user())print(make_user(is_admin=True))print(make_user(email="ada@example.com")["email"])
Output
Press Run (⌘ Enter) to see what happens.

The counter gives each object unique values, so tests never collide on a unique email. Libraries like factory_boy and polyfactory (which builds Pydantic models and dataclasses automatically) add database saving, related objects and random realistic values.

Predict the outputPython

Continuing right after the code above, what does this print?

u = make_user(name="Sam")
print(u["id"], u["email"], u["name"])
Need a nudge? Hints walk you through it.

Async tests with AsyncClient

pytest in Depth showed how to run async def tests with the anyio or pytest-asyncio plugin and an AsyncClient over ASGITransport. With the httpx2 move, the imports follow:

tests/test_async_orders.py
import httpx2
import pytest
 
from app.main import app
 
 
@pytest.mark.anyio
async def test_list_orders(seeded_orders):
    transport = httpx2.ASGITransport(app=app)
    async with httpx2.AsyncClient(transport=transport, base_url="http://test") as client:
        response = await client.get("/orders")
    assert response.status_code == 200

When do you need this over TestClient? TestClient runs your app on an event loop in a separate thread, through an anyio portal. That is fine until your test itself owns async resources: an async SQLAlchemy session from an async fixture, an asyncpg pool, an async Redis client. Those objects belong to the event loop that created them, and using them from the other loop fails with errors like Future attached to a different loop or another operation is in progress. With AsyncClient, the test, its fixtures and the app all run on one loop, so they can share those resources.

The catch: ASGITransport does not send lifespan events. Tested with httpx2 2.16, the same /ready endpoint returned {"ready": false} through AsyncClient because startup never ran. If your app needs lifespan, wrap it with LifespanManager from the asgi-lifespan package:

tests/conftest.py
import httpx2
import pytest
from asgi_lifespan import LifespanManager
 
from app.main import app
 
 
@pytest.fixture
async def client():
    async with LifespanManager(app) as manager:
        transport = httpx2.ASGITransport(app=manager.app)
        async with httpx2.AsyncClient(transport=transport, base_url="http://test") as c:
            yield c

Pass manager.app, not app: if your lifespan yields a state dict (yield {"pool": pool}), only the wrapped app injects it into each request's request.state. With app itself, that state is missing. The fixture needs an async-capable plugin configured, as pytest in Depth explains, and the same override and teardown rules as before.

Why TestClient can call async routes from a sync test

TestClient starts a blocking portal: a background thread running an event loop. Each request is submitted to that loop with portal.call(...), and the calling thread waits for the result. That is why a plain def test_... can drive async def routes. It is also why objects created on the test's own loop cannot cross over: the app is running on the portal's loop, not yours.

Snapshot-testing the OpenAPI schema

Frontend teams and other services generate clients from your /openapi.json. A renamed field, a type changed from int to str, or a status code dropped from a route changes that contract, and nothing in your route tests notices. A snapshot test does: it saves the schema to a committed file once, and fails whenever the generated schema differs.

tests/test_openapi_snapshot.py
import json
import os
from pathlib import Path
 
from app.main import app
 
SNAPSHOT = Path(__file__).parent / "snapshots" / "openapi.json"
 
 
def test_openapi_schema_matches_snapshot():
    current = json.dumps(app.openapi(), indent=2, sort_keys=True) + "\n"
    if os.environ.get("UPDATE_SNAPSHOTS") == "1":
        SNAPSHOT.parent.mkdir(exist_ok=True)
        SNAPSHOT.write_text(current)
    assert SNAPSHOT.read_text() == current, "API schema changed: review it, then rerun with UPDATE_SNAPSHOTS=1"

sort_keys=True makes the file stable, so the diff in review shows only real changes. The point is not to stop change. It is to make every contract change visible in the pull request, where a reviewer can ask "is this breaking?" Here is the mechanism in miniature:

Pythonsnapshot.py
import difflibimport json def render(schema): return json.dumps(schema, indent=2, sort_keys=True).splitlines() snapshot = {"paths": {"/orders/{id}": {"get": {"responses": {"200": {}, "404": {}}}}}, "components": {"Order": {"properties": {"id": {"type": "integer"}, "total": {"type": "number"}}}}} # Someone "tidies up" the model: total becomes a string, 404 is no longer documented.current = json.loads(json.dumps(snapshot))current["components"]["Order"]["properties"]["total"]["type"] = "string"del current["paths"]["/orders/{id}"]["get"]["responses"]["404"] diff = list(difflib.unified_diff(render(snapshot), render(current), "snapshot", "current", lineterm="", n=0))print("schema unchanged" if not diff else "\n".join(diff))
Output
Press Run (⌘ Enter) to see what happens.

Each - and + line is something a client could depend on. Snapshots answer "did it change?"; they do not answer "is the change breaking?". For that, OpenAPI, Generated Clients and Contract-First APIs runs oasdiff in CI against the main branch, and Testing with Real Databases uses Schemathesis to check the server actually honours the schema. A snapshot test is the cheap first step that needs no extra tools. Libraries like syrupy add an update flag and nicer diffs if you snapshot more than one thing.

Predict the outputPython

Using the code above, how many lines in the diff start with a single - (not counting the --- snapshot header)?

removed = [l for l in diff if l.startswith("-") and not l.startswith("---")]
print(len(removed))
Need a nudge? Hints walk you through it.
What to test, and how much
  1. End-to-endA few: real browser or client against a deployed stack
  2. API integrationMany: TestClient + test database, one route per test
  3. UnitMost: services, validators, pure helpers, no I/O

Unit tests are milliseconds each. Business rules in services and pure functions belong here.

1/3
Match the pairs0/5 matched

Match each tool to its job in a FastAPI test suite.

Choose an item, then its match on the other side.

Practice

ChallengeEasy

A test data factory

Write a factory for test users, the kind you would keep in tests/factories.py.

  • make_user(**overrides) -> dict returns a valid user. The nth user made (counting from 1) has these defaults:
{"id": n, "email": f"user{n}@example.com", "name": f"User {n}", "is_admin": False, "is_active": True}

Any keyword overrides replace the defaults. An override for a key that is not one of those five raises TypeError (so a typo like is_amdin=True fails loudly instead of being ignored). The sequence advances on every call, overridden or not.

  • make_users(count, **overrides) -> list[dict] makes count users with the same overrides.
  • reset_sequence() starts numbering from 1 again (tests call it so they do not depend on each other).
reset_sequence()
make_user()                  # {"id": 1, "email": "user1@example.com", "name": "User 1", ...}
make_user(is_admin=True)     # id 2, is_admin True
Python
def make_user(**overrides) -> dict: pass def make_users(count: int, **overrides) -> list[dict]: pass def reset_sequence() -> None: pass
ChallengeEasy

Test a service with a fake

Write a signup service and the fake that tests it.

FakeMailer stands in for a real email client:

  • sent: a list, empty at first.
  • send(to, subject, body) appends {"to": to, "subject": subject, "body": body}.
  • outbox(to) returns the messages sent to that address, in order.

signup(email, users, mailer) -> dict, where users is a set of registered emails and mailer is anything with a send method:

  • Normalise the email: strip spaces and lowercase it.
  • If it is already in users, raise ValueError and send nothing.
  • Otherwise add it to users and send one email with subject "Welcome!" and body f"Hi {email}, thanks for signing up." (normalised email).
  • Return {"email": email, "welcome_sent": True}. If mailer.send raises any exception, the signup still succeeds: return {"email": email, "welcome_sent": False}. A flaky email provider must never block account creation.
Python
class FakeMailer: def __init__(self): pass def send(self, to: str, subject: str, body: str) -> None: pass def outbox(self, to: str) -> list[dict]: pass def signup(email: str, users: set, mailer) -> dict: pass
Key terms
TestClient
An httpx-based client that calls a FastAPI app in-process, with no server needed.
fixture
A pytest function that prepares something for tests; tests request it by parameter name. yield adds cleanup.
dependency override
Replacing a dependency in app.dependency_overrides so tests use a test database or fake user.
fake
A simple working stand-in for a real collaborator, like an in-memory mailer that records sent emails.
factory
A helper that builds valid test objects with defaults and unique values, overriding only what a test needs.
lifespan in tests
Startup and shutdown run only inside with TestClient(app), or with LifespanManager around an async client.
ASGITransport
An httpx2 (formerly httpx) transport that sends requests straight into an ASGI app on the current event loop.
snapshot test
A test that compares output, such as the OpenAPI schema, to a committed file so every change shows up in review.