Skip to main content

Web frameworks · Intermediate · 24 min

Test a FastAPI app with pytest, TestClient and dependency overrides

By Padding · Updated 18 Nov 2026
python:3.15-slim · Python 3.15 · FastAPI 0.165 · SQLModel 0.0.50 · pytest 9.2 · pytest-cov 7.1

You will build a pytest suite for a FastAPI and SQLModel API that gives every test its own in-memory database, swaps the signed-in user with a dependency override, checks validation errors field by field and reports 100 per cent coverage in well under a second.

On this page

A FastAPI route rarely works alone. It asks for a database session, a signed-in user, maybe a settings object, and FastAPI hands those over through Depends. That design is what makes FastAPI apps pleasant to test: in a test you can tell the app "when a route asks for get_session, give it this one instead". The mechanism is a plain dictionary on the app, app.dependency_overrides.

In this tutorial you write a small library API with SQLModel and then build a test suite around it. Each test gets a brand-new SQLite database that lives only in memory, so tests never share rows and never touch the file your app uses. A protected route is tested twice: once with the sign-in swapped out entirely, and once through the real token check. Validation errors are checked by field and error type, not only by status code, and pytest-cov tells you which lines no test reaches. The whole suite runs in a fraction of a second.

The app follows the same pattern as connect FastAPI to a database with SQLModel, squeezed into one file, with one route that needs a signed-in user. If you have your own FastAPI project, every technique here carries over unchanged.

Step 1 · Create the project and the app under test

Make a throwaway project folder and add FastAPI and SQLModel. The ranges allow patch releases and nothing newer:

Bash
mkdir -p ~/library-tests-demo
cd ~/library-tests-demo
uv init --no-package
uv add "fastapi>=0.165,<0.166" "sqlmodel>=0.0.50,<0.0.51"

uv init creates a placeholder main.py. Replace it with the app. It has three book routes and a health check. Two dependencies matter for testing: get_session opens a database session per request, and get_current_user reads a bearer token and compares it with the API_TOKEN environment variable. In a production app that second function would decode a JWT, as in add JWT authentication to FastAPI. The tests do not care how it decides, only what it returns.

Bash
cat > main.py <<'PY'
import os
from contextlib import asynccontextmanager
from secrets import compare_digest
from typing import Annotated

from fastapi import Depends, FastAPI, HTTPException, Query, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from pydantic import BaseModel
from sqlmodel import Field, Session, SQLModel, create_engine, select

DATABASE_URL = os.environ.get("DATABASE_URL", "sqlite:///books.db")
connect_args = {"check_same_thread": False} if DATABASE_URL.startswith("sqlite") else {}
engine = create_engine(DATABASE_URL, connect_args=connect_args)


class BookBase(SQLModel):
    title: str = Field(min_length=1, max_length=200)
    author: str = Field(min_length=1, max_length=100)
    year: int = Field(ge=1450, le=2100)


class Book(BookBase, table=True):
    id: int | None = Field(default=None, primary_key=True)
    added_by: str


class BookCreate(BookBase):
    pass


class BookRead(BookBase):
    id: int
    added_by: str


class User(BaseModel):
    username: str


def get_session():
    with Session(engine) as session:
        yield session


bearer = HTTPBearer(auto_error=False)


def get_current_user(
    creds: Annotated[HTTPAuthorizationCredentials | None, Depends(bearer)],
) -> User:
    expected = os.environ.get("API_TOKEN", "")
    if creds is None or not expected or not compare_digest(
        creds.credentials.encode(), expected.encode()
    ):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Not authenticated",
            headers={"WWW-Authenticate": "Bearer"},
        )
    return User(username="librarian")


SessionDep = Annotated[Session, Depends(get_session)]
UserDep = Annotated[User, Depends(get_current_user)]


@asynccontextmanager
async def lifespan(app: FastAPI):
    SQLModel.metadata.create_all(engine)
    yield


app = FastAPI(title="Library API", lifespan=lifespan)


@app.get("/health")
def health() -> dict[str, str]:
    return {"status": "ok"}


@app.get("/books", response_model=list[BookRead])
def list_books(
    session: SessionDep,
    offset: Annotated[int, Query(ge=0)] = 0,
    limit: Annotated[int, Query(ge=1, le=100)] = 20,
):
    return session.exec(select(Book).order_by(Book.id).offset(offset).limit(limit)).all()


@app.get("/books/{book_id}", response_model=BookRead)
def read_book(book_id: int, session: SessionDep):
    book = session.get(Book, book_id)
    if book is None:
        raise HTTPException(status_code=404, detail="Book not found")
    return book


@app.post("/books", response_model=BookRead, status_code=201)
def create_book(book_in: BookCreate, session: SessionDep, user: UserDep):
    book = Book.model_validate(book_in, update={"added_by": user.username})
    session.add(book)
    session.commit()
    session.refresh(book)
    return book
PY

Two details are worth testing later. BookCreate has no id or added_by, so a client cannot choose either: the server sets added_by from whoever is signed in. And the Field limits on title, author and year are what FastAPI turns into 422 responses.

Check it worked

Bash
uv run python -c "from main import app; print(sorted({r.path for r in app.routes if r.path.startswith(('/books', '/health'))}))"

The output is ['/books', '/books/{book_id}', '/health'].

Step 2 · Add pytest and write a first test with TestClient

Add the test tools as development dependencies, so they never ship with the app:

Bash
uv add --dev "pytest>=9.2,<9.3" "httpx2>=2.16,<2.17"

TestClient comes from Starlette, the toolkit FastAPI is built on, and it sends requests through an HTTP client library. FastAPI's own testing page still says to install httpx. That works, but Starlette 1.10, which FastAPI 0.165 depends on, now looks for its successor httpx2 first and prints a deprecation warning on every run if it only finds httpx. Installing httpx2 keeps the output clean. The client methods are the same.

Tell pytest where the tests live, and that the project folder belongs on the import path so from main import app works from inside tests/. Appending keeps whatever uv already wrote:

Bash
cat >> pyproject.toml <<'TOML'

[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["."]
TOML
mkdir -p tests

Now the first test. TestClient(app) calls your app in-process: there is no server, no port and no network, which is why tests stay fast.

Bash
cat > tests/test_health.py <<'PY'
from fastapi.testclient import TestClient

from main import app


def test_health():
    client = TestClient(app)
    response = client.get("/health")
    assert response.status_code == 200
    assert response.json() == {"status": "ok"}
PY
uv run pytest -q

Check it worked

The last line reads 1 passed in 0.0Xs, with no warnings summary above it. If you see a StarletteDeprecationWarning about httpx, the httpx2 install did not land in this project: run the uv add --dev line again from the project folder.

Step 3 · Give every test a fresh in-memory database

Calling /books the same way would hit books.db, the app's real database file. Tests should not do that: they would depend on whatever rows happen to be there and leave their own behind. Instead, build a new in-memory database for each test and point the app at it with an override.

Fixtures that several test files share go in tests/conftest.py, which pytest loads on its own:

Bash
cat > tests/conftest.py <<'PY'
import pytest
from fastapi.testclient import TestClient
from sqlalchemy.pool import StaticPool
from sqlmodel import Session, SQLModel, create_engine

from main import User, app, get_current_user, get_session


@pytest.fixture
def session():
    engine = create_engine(
        "sqlite://",
        connect_args={"check_same_thread": False},
        poolclass=StaticPool,
    )
    SQLModel.metadata.create_all(engine)
    with Session(engine) as session:
        yield session
    engine.dispose()


@pytest.fixture
def client(session):
    app.dependency_overrides[get_session] = lambda: session
    yield TestClient(app)
    app.dependency_overrides.clear()
PY

Each line earns its place:

  • sqlite:// with no file name is an in-memory database. It exists only while its connection is open, and every new connection would get a different, empty one. StaticPool makes the engine reuse a single connection, so the tables create_all makes are the tables the session sees.
  • check_same_thread=False is needed because TestClient runs your route in a worker thread, not the thread that opened the connection.
  • The session fixture is function-scoped, the pytest default, so each test gets a new engine and an empty database.
  • app.dependency_overrides[get_session] = lambda: session means every route that asks for get_session receives the test's session. The key is the original function itself, not its name.
  • dependency_overrides lives on the app object, which is shared by every test in the run. The clear() after yield runs even when a test fails, so one test's override never leaks into the next.
  • The client is created without a with block on purpose. Inside with TestClient(app), FastAPI runs the lifespan handler, and this one calls create_all on the real engine, which would create books.db. You will test the lifespan separately in the coverage step.

User and get_current_user are imported now for the next step. Write the first database tests. Asking for the session fixture as well as client lets a test put rows straight into the database before it calls the API:

Bash
cat > tests/test_books.py <<'PY'
from main import Book


def test_missing_book_is_404(client):
    response = client.get("/books/999")
    assert response.status_code == 404
    assert response.json() == {"detail": "Book not found"}


def test_offset_and_limit(client, session):
    for n in range(1, 6):
        session.add(Book(title=f"Book {n}", author="Test Author", year=2000 + n, added_by="seed"))
    session.commit()

    response = client.get("/books", params={"offset": 1, "limit": 2})

    assert response.status_code == 200
    assert [book["title"] for book in response.json()] == ["Book 2", "Book 3"]


def test_list_starts_empty(client):
    response = client.get("/books")
    assert response.status_code == 200
    assert response.json() == []
PY
uv run pytest -q

Check it worked

The last line reads 4 passed. pytest runs the tests in file order, so test_list_starts_empty runs straight after test_offset_and_limit has added five books. It still sees an empty list, which shows each test really does get its own database. Then confirm the suite never touched the app's own database:

Bash
test ! -e books.db && echo "no books.db"

It prints no books.db.

Step 4 · Swap the signed-in user with an override

POST /books needs a user. You could mint real tokens in every test, but most tests are about books, not about tokens. Override get_current_user so the route receives a known user straight away. Add a fixture that does this on top of client, so its overrides are cleared by the same clear():

Bash
cat >> tests/conftest.py <<'PY'


@pytest.fixture
def signed_in(client):
    app.dependency_overrides[get_current_user] = lambda: User(username="test-librarian")
    return client
PY

Tests that ask for client are anonymous; tests that ask for signed_in act as test-librarian. Keep at least one test that goes through the real get_current_user, so the override cannot hide a broken token check. monkeypatch sets or removes the environment variable for one test only and restores it afterwards. The token value is a throwaway string that exists only inside the test:

Bash
cat > tests/test_auth.py <<'PY'
from main import Book

BOOK = {"title": "Things Fall Apart", "author": "Chinua Achebe", "year": 1958}


def test_create_needs_a_user(client, monkeypatch):
    monkeypatch.delenv("API_TOKEN", raising=False)
    response = client.post("/books", json=BOOK)
    assert response.status_code == 401
    assert response.headers["www-authenticate"] == "Bearer"


def test_create_and_read_back(signed_in, session):
    response = signed_in.post("/books", json=BOOK)

    assert response.status_code == 201
    book = response.json()
    assert book["added_by"] == "test-librarian"
    assert signed_in.get(f"/books/{book['id']}").json()["title"] == "Things Fall Apart"
    assert session.get(Book, book["id"]) is not None


def test_client_cannot_set_id_or_owner(signed_in):
    response = signed_in.post("/books", json=BOOK | {"id": 999, "added_by": "someone-else"})

    assert response.status_code == 201
    assert response.json()["id"] != 999
    assert response.json()["added_by"] == "test-librarian"


def test_title_with_tone_marks_round_trips(signed_in):
    title = "Ògbójú Ọdẹ nínú Igbó Irúnmọlẹ̀"
    response = signed_in.post("/books", json=BOOK | {"title": title})
    assert response.json()["title"] == title


def test_real_token_check(client, monkeypatch):
    monkeypatch.setenv("API_TOKEN", "test-only-token")
    wrong = client.post("/books", json=BOOK, headers={"Authorization": "Bearer nope"})
    right = client.post("/books", json=BOOK, headers={"Authorization": "Bearer test-only-token"})
    assert wrong.status_code == 401
    assert right.status_code == 201
    assert right.json()["added_by"] == "librarian"
PY
uv run pytest -q

test_client_cannot_set_id_or_owner protects the separate input model: if someone later lets BookCreate accept added_by, this test fails. The tone-mark test uses D. O. Fagunwa's Yoruba title to check that accented and combining characters survive the trip through JSON and SQLite unchanged. If your users write in Yoruba, Igbo, Hausa, Amharic or any language with diacritics, a test like this catches encoding mistakes long before a reader in Ibadan sees a garbled title.

Check it worked

The last line reads 9 passed. Remove the signed_in fixture from one test's arguments, for example change test_create_and_read_back(signed_in, session) to use client, and run again: that test now fails with assert 401 == 201, which shows the override was doing the work. Put it back before you continue.

Step 5 · Test validation errors with parametrize

When a request body breaks the model's rules, FastAPI answers 422 with a detail list. Each entry has a loc (where the problem is, such as ["body", "year"]), a msg for humans and a type that Pydantic keeps stable across releases. Assert on loc and type, not on msg, whose wording can change.

One parametrised test covers many bad inputs. Each case changes a single field of a valid book, so exactly one error is expected, and the [error] = ... unpacking fails the test if there are more:

Bash
cat > tests/test_validation.py <<'PY'
import pytest

GOOD = {"title": "Half of a Yellow Sun", "author": "Chimamanda Ngozi Adichie", "year": 2006}


@pytest.mark.parametrize(
    ("change", "field", "error_type"),
    [
        ({"title": None}, "title", "string_type"),
        ({"title": ""}, "title", "string_too_short"),
        ({"author": "x" * 101}, "author", "string_too_long"),
        ({"year": "soon"}, "year", "int_parsing"),
        ({"year": 1200}, "year", "greater_than_equal"),
    ],
    ids=["title-null", "title-empty", "author-too-long", "year-not-a-number", "year-too-early"],
)
def test_bad_book_is_rejected(signed_in, change, field, error_type):
    response = signed_in.post("/books", json=GOOD | change)

    assert response.status_code == 422
    [error] = response.json()["detail"]
    assert error["loc"] == ["body", field]
    assert error["type"] == error_type


def test_missing_fields_are_all_reported(signed_in):
    response = signed_in.post("/books", json={"title": "No author"})

    assert response.status_code == 422
    missing = {tuple(e["loc"]) for e in response.json()["detail"] if e["type"] == "missing"}
    assert missing == {("body", "author"), ("body", "year")}


@pytest.mark.parametrize("limit", [0, 101, "all"])
def test_bad_limit_is_rejected(client, limit):
    response = client.get("/books", params={"limit": limit})
    assert response.status_code == 422
    assert response.json()["detail"][0]["loc"] == ["query", "limit"]
PY
uv run pytest tests/test_validation.py -v

The validation tests use signed_in because FastAPI resolves the user dependency as well as the body: without a user, an anonymous request could come back 401 and hide the 422 you meant to test. The ids give each case a readable name in the output.

Check it worked

The verbose output lists nine passing tests with names such as test_bad_book_is_rejected[year-too-early] and test_bad_limit_is_rejected[all]. Change "greater_than_equal" to "less_than_equal" in the file and run it again: only the year-too-early case fails, and pytest shows the actual type next to the expected one. Change it back.

Step 6 · Measure coverage with pytest-cov

Coverage tells you which lines of your app no test runs. Add pytest-cov, and keep its data file out of Git:

Bash
uv add --dev "pytest-cov>=7.1,<7.2"
echo ".coverage" >> .gitignore
uv run pytest -q --cov=main --cov-report=term-missing

--cov=main measures the main module, and term-missing lists the line numbers no test reached.

The report shows main.py at about 93 per cent, with something like 41-42, 69-70 under Missing. Those are the body of get_session and the body of lifespan: the overrides replaced the first, and the client never ran the second. That is correct, but it means a mistake in either would slip through. One more test closes the gap. It swaps the module's engine for an in-memory one with monkeypatch.setattr, then uses TestClient in a with block, which runs the lifespan, and calls /books with no session override, which runs the real get_session:

Bash
cat > tests/test_startup.py <<'PY'
from fastapi.testclient import TestClient
from sqlalchemy import inspect
from sqlalchemy.pool import StaticPool
from sqlmodel import create_engine

import main


def test_startup_creates_tables(monkeypatch):
    engine = create_engine(
        "sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool
    )
    monkeypatch.setattr(main, "engine", engine)

    with TestClient(main.app) as client:
        assert inspect(engine).has_table("book")
        assert client.get("/books").json() == []
    engine.dispose()
PY
uv run pytest -q --cov=main --cov-report=term-missing --cov-fail-under=100

This works because lifespan and get_session look up the module-level name engine each time they run, and monkeypatch puts the original back after the test.

--cov-fail-under=100 makes the run fail if coverage drops, which is what you want in CI. A hundred per cent is realistic for a file this size. On a larger app, set the floor at today's figure and raise it as you add tests. Full coverage means every line ran, not that every case is checked: the validation tests in the previous step matter more than the percentage.

Check it worked

The table shows main.py with 0 under Miss and 100% under Cover, followed by Required test coverage of 100% reached and 19 passed. books.db still does not exist.

Step 7 · Keep the suite fast

A test suite that runs in seconds gets run after every change; one that takes minutes gets skipped. Ask pytest which tests are slowest:

Bash
uv run pytest -q --durations=5

Every test here builds a new database, and the whole run still takes about a tenth of a second on a laptop, a bit more on a small cloud server. That speed comes from three choices you made: no server or network (TestClient calls the app directly), no disk (in-memory SQLite) and no real authentication in most tests (the override). On a low-end machine or a shared CI runner, these choices matter even more.

As the suite grows, these habits keep it quick:

  • Run one file or one test while you work: uv run pytest tests/test_auth.py or uv run pytest -k tone_marks.
  • Stop at the first failure with -x, and rerun only the failures from last time with --lf.
  • Keep slow, real-database checks (PostgreSQL in CI, for example) in a separate file you run less often, rather than slowing every test.

Check it worked

The output ends with 19 passed in and a time well under one second. Above it, pytest lists the slowest calls, each around 0.01s, and notes how many were too quick to show.

Step 8 · Clean up

Remove the demo project. Python and uv stay installed:

Bash
cd ~
rm -rf ~/library-tests-demo

Check it worked

ls ~/library-tests-demo reports No such file or directory.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.