Testing FastAPI: TestClient, Fixtures, Database Fixtures, Dependency Overrides, Mocking HTTP Clients
"Thanks to Starlette, testing FastAPI applications is easy and enjoyable. It is based on HTTPX, which in turn is designed based on Requests, so it's very familiar and intuitive. With it, you can use pytest directly with FastAPI." — FastAPI documentation, "Testing", fastapi.tiangolo.com/tutorial/testing
Summary: A FastAPI test suite is pytest plus three FastAPI-specific seams. TestClient (an httpx.Client whose transport calls the ASGI app in-process) or httpx.AsyncClient with ASGITransport sends real HTTP requests through routing, validation, dependencies and serialisation without a socket or a server. app.dependency_overrides swaps any dependency (the session, the current user, the payment client) for the duration of a test. And the database fixture decides isolation: either one schema per run with a transaction per test (BEGIN in the fixture, the app's commit() turned into RELEASE SAVEPOINT, ROLLBACK at teardown), or a fresh schema per test. Around those seams sit the ordinary pytest tools: fixtures with scopes and conftest.py layering, parametrize and markers, respx or pytest-httpx for outbound HTTP, freezegun or time-machine for the clock, factory_boy and polyfactory for data, coverage.py with branch coverage, an OpenAPI snapshot, and testcontainers for PostgreSQL in CI. Focus: pytest basics (test discovery, assert rewriting, arrange act assert, pytest.ini vs pyproject [tool.pytest.ini_options]), fixtures (fixture scope, yield fixture, autouse, conftest.py layering and overriding), parametrize and markers, TestClient and the lifespan in tests, httpx.AsyncClient + ASGITransport under anyio and pytest-asyncio (asyncio_mode), testing routes and validation errors (the exact 422 body), database fixtures (SQLite in-memory, StaticPool, check_same_thread, transaction rollback per test, nested transaction and savepoint, the sqlite3 driver trap, create_all per test, schema recreate vs rollback with measured timings), app.dependency_overrides (override get_session, a fake current user, a test token), mocking an external API (respx, pytest-httpx, unittest.mock, monkeypatch), time (freezegun, time-machine, flaky tests, the retries anti-pattern), BackgroundTasks testing, a WebSocket test, an OpenAPI snapshot and a contract test, coverage.py and pytest-cov with branch coverage, testcontainers and PostgreSQL in CI, test speed, and the Laravel (RefreshDatabase, Http::fake, actingAs, Pest) and Go (httptest, table-driven tests, testify) comparisons. Learning goal: Build a test suite for a FastAPI service where every test is isolated (no leaked rows, no leaked overrides, no network, no real clock), every layer is tested at the cheapest level that can prove it, the database fixture is fast and provably correct, and a failing test explains itself.
This page owns the FastAPI and pytest mechanics of testing. The theory of test layers, test doubles, TDD and flaky-test policy is owned by Testing Strategy & TDD, and the Go twin of this page is Testing & Benchmarking with Mocking with Interfaces, Dependency Injection for Testability: those are linked, not re-taught. How Depends and app.dependency_overrides work inside FastAPI is in Dependency Injection with Depends. Engines, sessions and the Room/Booking models are in SQLAlchemy 2 & SQLModel, migrations in Alembic Migrations. Real JWTs are in Authentication in FastAPI; this page uses a small signed token instead. Calling external APIs with retries and caching is in Background Tasks, Caching & External APIs, event loops in Async Python, and the project tooling (uv, venvs, pyproject.toml) in Python Project Tooling. Testing brokers and consumers is in Testing Messaging Systems, and the pipeline that runs the suite is in CI/CD Pipelines.
Facts below were checked against the FastAPI docs (testing, testing dependencies, async tests, testing events, testing WebSockets, settings, SQL databases, release notes), the pytest docs (getting started, fixtures, parametrize, marks, monkeypatch, assertions, good practices, customize, flaky tests, history, changelog), the Starlette TestClient page and release notes, the HTTPX async and transports pages, the AnyIO testing page, the pytest-asyncio concepts, configuration and changelog, the SQLAlchemy 2.0 docs (session transactions, "Joining a Session into an External Transaction", pooling, the SQLite dialect), the SQLModel FastAPI tests tutorial, the respx guide, the pytest-httpx README, factory_boy, polyfactory, Faker, freezegun, time-machine, coverage.py, pytest-cov, testcontainers-python, unittest.mock, Laravel 13 (testing, database testing, HTTP tests, HTTP client, mocking), Pest, Go's net/http/httptest source, testify's README, Martin Fowler's articles on the test pyramid, contract tests and non-determinism, and PyPI release data, all fetched on 2026-11-29. The page is written for Python 3.12+ and current releases (FastAPI 0.165.0, pytest 9.2.0, pytest-asyncio 1.5.0, time-machine 3.6.0). The snippets ran on the only interpreter on the build machine, CPython 3.9.6, with the newest releases that still install there: FastAPI 0.128.8, Starlette 0.49.3, Pydantic 2.13.5, SQLAlchemy 2.0.58, SQLModel 0.0.34, httpx 0.28.1, pytest 8.4.2, pytest-asyncio 1.2.0, anyio 4.12.1, respx 0.23.1, pytest-httpx 0.35.0, freezegun 1.5.5, time-machine 2.19.0, factory_boy 3.3.3, Faker 37.12.0, polyfactory 3.5.0, coverage 7.10.7, pytest-cov 7.1.0 and asgi-lifespan 2.1.0, with SQLite 3.54.0. Every count, status code, body, SQL statement and timing quoted as "real" is what that run printed. PostgreSQL with testcontainers and Python 3.12 were not run (no Docker, no 3.12 interpreter) and are marked "expected, not run".
Page map
| If you are looking for | Go to |
|---|---|
| The tables to memorise | Everything in one minute |
| Why tests need their own seams | Why it exists |
| py.test 2004 to pytest 9, requests to httpx2 | Where it comes from |
| A fragile suite and the fixed one | Python |
| Test discovery, assert rewriting, AAA | pytest basics |
pytest.ini, [tool.pytest.ini_options], [tool.pytest] | Configuration |
| Fixtures, scope, yield, autouse | Fixtures |
conftest.py layering and overriding a fixture | conftest.py layering |
@pytest.mark.parametrize, ids | Parametrize |
slow, --strict-markers, -m | Markers |
TestClient, with, the lifespan | TestClient and the lifespan |
AsyncClient, ASGITransport, anyio, pytest-asyncio | Async tests |
| The exact 422 body | Testing routes and validation errors |
app.dependency_overrides, override get_session | Dependency overrides |
StaticPool, check_same_thread | SQLite in-memory for tests |
| BEGIN, SAVEPOINT, ROLLBACK per test | Transaction rollback per test |
| The sqlite3 savepoint trap | The sqlite3 driver trap |
create_all per test, timings | Schema recreate vs rollback |
| factory_boy, polyfactory, Faker | Factories |
| Test token, fake current user | Testing auth-protected routes |
| respx, pytest-httpx | Mocking an external API |
monkeypatch, unittest.mock, autospec | monkeypatch and unittest.mock |
| freezegun, time-machine, flaky tests, retries | Time and flaky tests |
BackgroundTasks, WebSockets | Background tasks and WebSockets |
| OpenAPI snapshot, contract test | Snapshots and contracts |
| coverage.py, pytest-cov, branch coverage | Coverage |
| testcontainers, PostgreSQL in CI | PostgreSQL in CI |
| Unit vs integration vs e2e | Test layers |
| What happens inside one test | Mechanics |
| Bugs and fixes | Solving the classic problems |
| Which tool for which job | Choosing |
| Monolith to distributed | In architecture |
| Run it yourself | Lab |
RefreshDatabase, Http::fake, actingAs, Pest | For PHP/Laravel developers |
httptest, table-driven tests, testify | The Go angle |
Everything in one minute
The vocabulary. Each row is unpacked in the concept catalogue.
| Term | What it is | Plain words | In the snippet |
|---|---|---|---|
| Test discovery | pytest collects test_*.py files, test_ functions, Test classes | "Name it right and it runs" | testpaths = ["tests"] |
| Assert rewriting | pytest rewrites assert in test modules to explain failures | "Plain assert, rich report" | assert 503 == 201 with where lines |
| Fixture | A function that provides a value (and cleanup) to tests that name it | "Arrange, reusable" | engine, db_session, client |
| Fixture scope | How long one fixture value lives: function to session | "Built once per ..." | engine is scope="session" |
conftest.py | A file of fixtures for its directory and below | "Shared setup by folder" | root, tests/api/, tests/speed/ |
TestClient | httpx.Client that calls the ASGI app in-process | "HTTP without a server" | with TestClient(app) as c |
ASGITransport | httpx transport that calls an ASGI app from async code | "Same, inside async def" | tests/api/test_async_client.py |
| Dependency override | app.dependency_overrides[dep] = replacement | "Swap one seam" | get_session, get_current_user, get_payments |
| Savepoint | A nested transaction inside a transaction | "An undo point" | the app's commit() in tests |
| respx / pytest-httpx | Replace httpx's transport with canned responses | "A fake internet" | payments_api autouse fixture |
| freezegun / time-machine | Replace the clock | "Stop or move time" | token expiry, "check_in in the past" |
| Snapshot test | Compare an output with a stored copy | "Diff the API" | snapshots/openapi.json |
Which isolation you get from which fixture. Measured on this machine, 100 tests per row, same bodies (real, runs/speed.txt).
| Strategy | What happens per test | DB-only body, 100 tests | Through the API, 100 tests | Trap |
|---|---|---|---|---|
| Transaction rollback per test | BEGIN, savepoints for the app's commits, ROLLBACK | 0.21 s | 1.59-1.67 s | The sqlite3 driver needs SQLAlchemy's BEGIN hook |
| Schema recreate, in-memory | New engine, create_all, drop_all | 0.38-0.41 s | 2.00-2.05 s | None; commits are real COMMITs |
| Schema recreate, SQLite file | New file, create_all, drop_all | 0.43-0.45 s | 1.96-2.31 s | Disk; temp dir cleanup |
| No isolation (the Before suite) | One database for the module | — | — | Order-dependent tests |
Where each piece of a request comes from in a test.
| Piece | Production | In this suite | How |
|---|---|---|---|
| HTTP server | Uvicorn | none | TestClient / ASGITransport call the app directly |
| Lifespan | Uvicorn sends startup/shutdown | with TestClient(app) or LifespanManager(app) | Without them app.state is empty |
| Database session | get_session on the app's engine | The test's db_session (one connection, outer transaction) | app.dependency_overrides[get_session] |
| Current user | Token check against the users table | Real test token, or a fake user | auth_headers fixture, or override get_current_user |
| Payment provider | httpx.Client to the provider | respx canned responses, or an autospec mock | autouse payments_api, or override get_payments |
| Clock | time.time(), date.today() | Frozen or moved | freeze_time, time_machine.travel |
| Environment | Process env | Set per test, undone after | monkeypatch.setenv + get_settings.cache_clear() |
The suite of this chapter (real counts).
| Directory | Tests | What they prove | Runs by default |
|---|---|---|---|
tests/unit | 29 | Pricing, model validation, tokens, the payments client, settings | Yes |
tests/api | 30 | Routes, 401/403/404/409/422/402/503, overrides, async client, lifespan, WebSocket | Yes |
tests/db | 7 | Isolation, the savepoint trace, the sqlite3 trap, the recreate variant | Yes |
tests/contract | 5 | OpenAPI snapshot, provider samples | Yes |
tests/speed | 600 | Timing comparison (2 bodies x 3 strategies x 100) | Only with -m speed |
tests/postgres | 1 | Rollback recipe on PostgreSQL via testcontainers | Only with -m postgres (expected, not run) |
before/ | 3 | What goes wrong without fixtures | Only when named |
Why it exists
A web service is mostly glue: routing, validation, auth, a database, other services, the clock. Tests that call the service through HTTP are the only ones that check the glue, but the naive version of such a test is slow, flaky and order-dependent. It starts a real server, shares one database across tests, calls the real payment provider, and depends on today's date. FastAPI and pytest give you a seam for each of those problems. TestClient removes the server. Fixtures give each test its own arranged world and clean it up. app.dependency_overrides replaces exactly the parts that are not under test. A transaction per test gives each test an empty database at the cost of one ROLLBACK. Transport mocks remove the network, and clock mocks remove time. What is left is a test that runs the real code path in a millisecond or two and fails only when the code is wrong.
| Without the seams (the Before suite) | With them (the After suite) |
|---|---|
| One module-scoped client and database: tests share rows | Fresh app per test; outer transaction rolled back after each test |
test_list_rooms passes only after test_create_room (real: assert 0 == 1 when run alone) | Each test arranges its own rows with factories |
| A real HTTP call to the payment provider: DNS failure, 503, 2.31 s for the file (real) | respx autouse fixture; unmatched requests raise |
"2026-12-01" hard-coded: fails from that date on | freeze_time / time_machine.travel; dates relative to date.today() |
Setup by reaching into app.state.engine | make_user, RoomFactory through the test session |
| A token minted at import from the default secret | auth_headers(user) with the test secret, or an override |
| No coverage, no snapshot | 97.93 % line+branch coverage, OpenAPI snapshot |
An everyday picture. A flight simulator. Pilots train on the real cockpit (the real app, routes and validation), but the simulator replaces the parts that are expensive, dangerous or uncontrollable: the sky is a projection (respx instead of the payment provider), the weather is chosen by the instructor (freezegun instead of the clock), and the passengers are mannequins (factories). Before every exercise, the instructor resets the simulator to the same starting state (the fixture's BEGIN); after it, every switch the pilot flipped is reset (ROLLBACK), so the next pilot does not inherit a half-lowered landing gear. A good instructor can swap any one instrument for a fake (one dependency override) and leave the rest real. And no one trains in the real aircraft until the simulator passes, which is the job of the slow, few end-to-end tests.
Three common misunderstandings, up front
- "
TestClientstarts the app like Uvicorn does." It runs the lifespan only insidewith TestClient(app). Withoutwith, routes that needapp.statefail withAttributeError: 'State' object has no attribute 'payments'(real).httpx.AsyncClientwithASGITransportnever sends lifespan events. - "Rolling back a transaction per test always isolates tests." On the sqlite3 driver's legacy transaction control (still its default), a
SAVEPOINTdoes not join the outer transaction, so the app'scommit()really commits. In the real run, removing SQLAlchemy's BEGIN hook leaked rows into later tests: 18 errors and 1 failure,UNIQUE constraint failed: user.email. - "Mocking HTTP means patching my client." respx and pytest-httpx replace httpx's transport. Your client's real code (URL, JSON, headers, status handling) still runs, and
TestClient's own requests are not intercepted.
Where it comes from
pytest grew out of PyPy. Its own history page dates the first pytest-like runner to Europython 2004, when Holger Krekel's "std" project argued: "forget about limited 'assertXYZ APIs' and use the real thing, e.g.: assert x == y", and "std.utest (magic!) actually reinterprets the assertion expression and offers detailed information about underlying values". Around September/October 2004 "std.utest became py.test". py 1.0.0 (August 2009) introduced "funcargs/fixtures", a plugin architecture and monkeypatch. pytest 2.0.0 (November 2010) was released "as a package separate from py (but still called py.test)", and pytest 3.0.0 (August 2016) made pytest the recommended command. pytest 6 added pyproject.toml support under [tool.pytest.ini_options] "in an 'INI compatibility mode'". pytest 8.4.2 (2025-09-03) is the last release for Python 3.9. pytest 9.0.0 (2025-11-05) dropped 3.9 ("Support for Python 3.9 is dropped following its end of life"), added native TOML configuration under [tool.pytest], and merged subtests into the core.
The HTTP side moved with it. Starlette 0.21.0 (September 26, 2022) "replaces the underlying HTTP client used on the TestClient", from requests to httpx, and warns that "your test suite will likely break". Starlette 1.2.0 (May 28, 2026) added "Support httpx2 in the test client", and the current TestClient page says "The TestClient is built on httpx2. Plain httpx is still supported, but deprecated". The snippet pin (Starlette 0.49.3) still uses httpx. On the async side, pytest-asyncio 0.17.0 (2022-01-13) "Added the plugin modes: strict, auto, and legacy". 1.0.0 (2025-05-26) removed "The deprecated event_loop fixture", and 1.3.0 (2025-11-10) removed Python 3.9. For time, freezegun's first PyPI release was 0.0.1 (2012-12-11) and time-machine's 1.0.0 (2020-05-29); time-machine describes freezegun as "a popular solution" whose "main drawback is its slow implementation". For databases, SQLAlchemy 2.0's "join into an external transaction" recipe "is newly improved again in 2.0; event handlers to 'reset' the nested transaction are no longer required", and the SQLAlchemy docs note that the sqlite3 driver's legacy transaction mode "will no longer be the default in a future Python version (3.16 as of this writing)".
1 2004-06/07 Europython 2004: "std" project, plain assert reinterpreted (pytest's own dating)
2 2004-09/10 std.utest renamed py.test
3 2009-08 py 1.0.0: funcargs/fixtures, plugin architecture, monkeypatch
4 2010-11 pytest 2.0.0 separate from py; 2016-08 pytest 3.0.0: `pytest` command
5 2012-12 freezegun 0.0.1 (first PyPI release)
6 2020-05 time-machine 1.0.0; 2020-01 respx 0.10.0 (first PyPI release)
7 2022-01 pytest-asyncio 0.17.0: strict / auto / legacy modes
8 2022-09 Starlette 0.21.0: TestClient requests -> httpx
9 2022-10 SQLAlchemy 2.0 series (first beta): create_savepoint join recipe without reset events
10 2025-05 pytest-asyncio 1.0.0 removes the event_loop fixture
11 2025-09 pytest 8.4.2 (last for Python 3.9, the snippet pin)
12 2025-11 pytest 9.0.0: drops 3.9, native [tool.pytest] TOML, subtests in core
13 2026-05 Starlette 1.2.0: httpx2 in the TestClient
14 2026-11 FastAPI 0.165.0, pytest 9.2.0 current at the time of writingRow 9 is the first 2.0 release on SQLAlchemy's release table (a beta, 2022-10-13); the recipe text is from the 2.0.58 documentation, and 2.1.9 (2026-11-16) is the current series.
Python
Before
The application under test is the same throughout: a rooms and bookings API with users, an admin-only room creation, a booking flow that checks overlaps, charges an external payment provider through httpx, saves the booking and sends a confirmation in a background task, and a WebSocket that reports availability. The Before suite tests it the way many first suites do. One module-scoped client shares one database. One test depends on another. Setup reaches into app.state.engine. The token is minted at import. The booking test calls the real provider and hard-codes a date.
"""The Before suite: tests that pass on the author's laptop and are wrong anyway.
Not in testpaths. Run it on purpose: pytest before/
Problems, one per test: shared state between tests (module-scoped client + module-level token),
order dependence, a real network call to the payment provider, a hard-coded calendar date,
setup through the app's internals instead of fixtures.
"""
import pytest
from fastapi.testclient import TestClient
from sqlmodel import Session
from app.main import app # the module-level app: real settings, real lifespan
from app.models import User
from app.security import issue_token
from app.settings import get_settings
TOKEN = {"Authorization": f"Bearer {issue_token(1, get_settings().token_secret, 900)}"}
@pytest.fixture(scope="module")
def client():
with TestClient(app) as c: # one database for the whole module: tests share rows
yield c
def test_create_room(client):
with Session(app.state.engine) as s: # setup by reaching into the app
s.add(User(email="admin@example.com", is_admin=True))
s.commit()
r = client.post("/rooms", json={"name": "Garden", "capacity": 2, "price_per_night": 12000}, headers=TOKEN)
assert r.status_code == 201
def test_list_rooms(client):
assert len(client.get("/rooms").json()) == 1 # true only if test_create_room ran first
def test_book_room(client):
# a real HTTP call to https://payments.example.test, and a date that will be in the past soon
r = client.post("/bookings", json={"room_id": 1, "check_in": "2026-12-01", "check_out": "2026-12-03"}, headers=TOKEN)
assert r.status_code == 201Run as a file it "mostly works". The booking test fails after 2.31 s of DNS resolution for payments.example.test, and run alone, the list test fails because the row it expects came from another test (real, runs/before-suite.txt):
$ pytest before/
> assert r.status_code == 201
E assert 503 == 201
E + where 503 = <Response [503 Service Unavailable]>.status_code
FAILED before/test_before.py::test_book_room - assert 503 == 201
========================= 1 failed, 2 passed in 2.31s ==========================
$ pytest before/test_before.py::test_list_rooms
FAILED before/test_before.py::test_list_rooms - AssertionError: assert 0 == 1
============================== 1 failed in 0.27s ===============================After
The application. Settings come from the environment once per process; the engine factory applies the SQLite recipe this chapter depends on:
"""Settings read from the environment once per process.
Tests either build a Settings object and pass it to create_app(), or set the
environment with monkeypatch and clear the cache of get_settings().
"""
import os
from dataclasses import dataclass
from functools import lru_cache
@dataclass(frozen=True)
class Settings:
database_url: str = "sqlite://"
payments_url: str = "https://payments.example.test"
payments_timeout_s: float = 2.0
token_secret: str = "dev-secret-change-me"
token_ttl_s: int = 900
def load_settings() -> Settings:
env = os.environ
return Settings(
database_url=env.get("BOOKINGS_DATABASE_URL", "sqlite://"),
payments_url=env.get("BOOKINGS_PAYMENTS_URL", "https://payments.example.test"),
payments_timeout_s=float(env.get("BOOKINGS_PAYMENTS_TIMEOUT_S", "2.0")),
token_secret=env.get("BOOKINGS_TOKEN_SECRET", "dev-secret-change-me"),
token_ttl_s=int(env.get("BOOKINGS_TOKEN_TTL_S", "900")),
)
@lru_cache
def get_settings() -> Settings:
"""Process-wide settings; tests call get_settings.cache_clear() after changing env."""
return load_settings()"""Engine factory and the per-request session dependency."""
from typing import Annotated, Any, Dict, Iterator
from fastapi import Depends, Request
from sqlalchemy import event
from sqlalchemy.engine import Engine
from sqlalchemy.pool import StaticPool
from sqlmodel import Session, SQLModel, create_engine
def make_engine(url: str = "sqlite://", *, echo: bool = False, sqlalchemy_begin: bool = True) -> Engine:
"""One engine per process.
In-memory SQLite needs StaticPool (one shared connection; the default SingletonThreadPool
gives every thread its own empty database) and check_same_thread=False (FastAPI runs
`def` routes and TestClient runs the app on other threads).
sqlalchemy_begin=True applies the SQLAlchemy recipe for the sqlite3 driver's legacy
transaction control: switch the driver's own BEGIN off and let SQLAlchemy emit it.
Without it, SAVEPOINT does not join the enclosing transaction (see tests/db).
"""
kwargs: Dict[str, Any] = {"echo": echo}
if url.startswith("sqlite"):
kwargs["connect_args"] = {"check_same_thread": False}
if url in ("sqlite://", "sqlite:///:memory:"):
kwargs["poolclass"] = StaticPool
engine = create_engine(url, **kwargs)
if url.startswith("sqlite"):
@event.listens_for(engine, "connect")
def _on_connect(dbapi_connection: Any, connection_record: Any) -> None:
if sqlalchemy_begin:
dbapi_connection.isolation_level = None # driver stops emitting BEGIN itself
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA foreign_keys=ON")
cursor.close()
if sqlalchemy_begin:
@event.listens_for(engine, "begin")
def _on_begin(conn: Any) -> None:
conn.exec_driver_sql("BEGIN")
return engine
def create_db_and_tables(engine: Engine) -> None:
"""Fine for tests and demos; production schemas belong to Alembic migrations."""
SQLModel.metadata.create_all(engine)
def get_engine(request: Request) -> Engine:
return request.app.state.engine
def get_session(engine: Annotated[Engine, Depends(get_engine)]) -> Iterator[Session]:
"""One Session per request; rolled back on error, always closed. Tests override this."""
with Session(engine) as session:
try:
yield session
except Exception:
session.rollback()
raise
SessionDep = Annotated[Session, Depends(get_session)]The models, the pure pricing rule, the token, the payment client and the outbox:
"""Rooms, bookings and users: one table model plus Create/Public data models per resource.
No `from __future__ import annotations`: FastAPI and SQLModel read these annotations at runtime.
"""
import datetime as dt
from typing import Optional
from pydantic import model_validator
from sqlmodel import Field, SQLModel
class User(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
email: str = Field(index=True, unique=True, max_length=254)
is_admin: bool = False
class RoomBase(SQLModel):
name: str = Field(min_length=1, max_length=60, unique=True)
capacity: int = Field(ge=1, le=12)
price_per_night: int = Field(gt=0, description="Price in cents")
class Room(RoomBase, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
class RoomCreate(RoomBase):
pass
class RoomPublic(RoomBase):
id: int
class BookingBase(SQLModel):
room_id: int
check_in: dt.date
check_out: dt.date
class BookingCreate(BookingBase):
@model_validator(mode="after")
def check_dates(self) -> "BookingCreate":
if self.check_out <= self.check_in:
raise ValueError("check_out must be after check_in")
if (self.check_out - self.check_in).days > 30:
raise ValueError("stays are limited to 30 nights")
return self
class Booking(BookingBase, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
room_id: int = Field(foreign_key="room.id", index=True)
user_id: int = Field(foreign_key="user.id", index=True)
total_cents: int
payment_id: str
created_at: dt.datetime
class BookingPublic(BookingBase):
id: int
user_id: int
total_cents: int
payment_id: str
created_at: dt.datetime"""Pure pricing rules: the cheapest thing to test (no app, no database, no network)."""
WEEKLY_DISCOUNT_PCT = 10
def quote(nights: int, price_per_night: int) -> int:
"""Total in cents. Stays of 7 nights or more get the weekly discount, rounded down."""
if nights < 1:
raise ValueError("nights must be >= 1")
if price_per_night <= 0:
raise ValueError("price_per_night must be > 0")
total = nights * price_per_night
if nights >= 7:
total = total * (100 - WEEKLY_DISCOUNT_PCT) // 100
return total"""A tiny signed, expiring token: user id + expiry + HMAC-SHA256.
Stand-in for the JWT of the authentication chapter; it reads the clock through
time.time(), which is exactly what freezegun and time-machine replace.
"""
import hashlib
import hmac
import time
from typing import Optional
class InvalidToken(Exception):
pass
class ExpiredToken(InvalidToken):
pass
def _sign(payload: str, secret: str) -> str:
return hmac.new(secret.encode(), payload.encode(), hashlib.sha256).hexdigest()
def issue_token(user_id: int, secret: str, ttl_s: int, now: Optional[float] = None) -> str:
issued = time.time() if now is None else now
payload = f"{user_id}.{int(issued) + ttl_s}"
return f"{payload}.{_sign(payload, secret)}"
def verify_token(token: str, secret: str) -> int:
"""Return the user id, or raise InvalidToken / ExpiredToken."""
try:
user_id, exp, sig = token.split(".")
payload = f"{user_id}.{exp}"
expires_at = int(exp)
uid = int(user_id)
except ValueError as exc:
raise InvalidToken("malformed token") from exc
if not hmac.compare_digest(sig, _sign(payload, secret)):
raise InvalidToken("bad signature")
if time.time() >= expires_at:
raise ExpiredToken("token expired")
return uid"""Client for the external payment provider (an HTTP API we do not control).
The app creates one httpx.Client in the lifespan; tests never reach the real host:
respx or pytest-httpx intercept the transport, or the whole client is overridden.
"""
import httpx
from pydantic import BaseModel
class ChargeResponse(BaseModel):
"""The part of the provider's response we rely on: the consumer side of the contract."""
id: str
status: str
amount_cents: int
class PaymentError(Exception):
pass
class PaymentDeclined(PaymentError):
pass
class PaymentUnavailable(PaymentError):
pass
class PaymentsClient:
def __init__(self, http: httpx.Client) -> None:
self._http = http
def charge(self, *, amount_cents: int, reference: str, idempotency_key: str) -> str:
"""Charge and return the provider's charge id."""
try:
response = self._http.post(
"/v1/charges",
json={"amount_cents": amount_cents, "currency": "EUR", "reference": reference},
headers={"Idempotency-Key": idempotency_key},
)
except httpx.TimeoutException as exc:
raise PaymentUnavailable("payment provider timed out") from exc
except httpx.TransportError as exc:
raise PaymentUnavailable(f"payment provider unreachable: {exc}") from exc
if response.status_code == 402:
raise PaymentDeclined(response.json().get("reason", "declined"))
if response.status_code >= 500:
raise PaymentUnavailable(f"payment provider answered {response.status_code}")
response.raise_for_status()
return ChargeResponse.model_validate(response.json()).id"""Confirmation 'emails'. A real app would call an email API; here they land in an outbox list."""
from typing import Dict, List
def send_confirmation(outbox: List[Dict[str, object]], booking_id: int, email: str) -> None:
outbox.append({"to": email, "subject": f"Booking {booking_id} confirmed", "booking_id": booking_id})Every dependency is a seam a test can replace:
"""Dependencies the routes declare; every one of them is a seam a test can override."""
from typing import Annotated, Dict, List
from fastapi import Depends, HTTPException, Request, status
from fastapi.security import OAuth2PasswordBearer
from app.db import SessionDep
from app.models import User
from app.payments import PaymentsClient
from app.security import ExpiredToken, InvalidToken, verify_token
from app.settings import Settings
def get_settings_dep(request: Request) -> Settings:
return request.app.state.settings
SettingsDep = Annotated[Settings, Depends(get_settings_dep)]
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
def get_current_user(
token: Annotated[str, Depends(oauth2_scheme)], session: SessionDep, settings: SettingsDep
) -> User:
try:
user_id = verify_token(token, settings.token_secret)
except ExpiredToken:
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Token expired", {"WWW-Authenticate": "Bearer"})
except InvalidToken:
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Invalid token", {"WWW-Authenticate": "Bearer"})
user = session.get(User, user_id)
if user is None:
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Unknown user", {"WWW-Authenticate": "Bearer"})
return user
CurrentUser = Annotated[User, Depends(get_current_user)]
def require_admin(user: CurrentUser) -> User:
if not user.is_admin:
raise HTTPException(status.HTTP_403_FORBIDDEN, "Admins only")
return user
AdminUser = Annotated[User, Depends(require_admin)]
def get_payments(request: Request) -> PaymentsClient:
return request.app.state.payments
PaymentsDep = Annotated[PaymentsClient, Depends(get_payments)]
def get_outbox(request: Request) -> List[Dict[str, object]]:
return request.app.state.outbox
OutboxDep = Annotated[List[Dict[str, object]], Depends(get_outbox)]"""Rooms & bookings API: the application under test."""
import datetime as dt
from contextlib import asynccontextmanager
from typing import AsyncIterator, List, Optional
import httpx
from fastapi import BackgroundTasks, FastAPI, HTTPException, Query, WebSocket, WebSocketDisconnect, status
from sqlalchemy.exc import IntegrityError
from sqlmodel import Session, col, func, select
from app import pricing
from app.db import SessionDep, create_db_and_tables, make_engine
from app.deps import AdminUser, CurrentUser, OutboxDep, PaymentsDep
from app.models import Booking, BookingCreate, BookingPublic, Room, RoomCreate, RoomPublic, User
from app.notifications import send_confirmation
from app.payments import PaymentDeclined, PaymentsClient, PaymentUnavailable
from app.settings import Settings, get_settings
def overlapping_bookings(session: Session, room_id: int, check_in: dt.date, check_out: dt.date) -> int:
"""Two stays overlap when each one starts before the other ends."""
stmt = (
select(func.count())
.select_from(Booking)
.where(Booking.room_id == room_id, col(Booking.check_in) < check_out, col(Booking.check_out) > check_in)
)
return session.exec(stmt).one()
def create_app(settings: Optional[Settings] = None) -> FastAPI:
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
cfg: Settings = app.state.settings
app.state.engine = make_engine(cfg.database_url)
create_db_and_tables(app.state.engine) # Alembic owns this in production
app.state.http = httpx.Client(base_url=cfg.payments_url, timeout=cfg.payments_timeout_s)
app.state.payments = PaymentsClient(app.state.http)
app.state.outbox = []
yield
app.state.http.close()
app.state.engine.dispose()
app = FastAPI(title="Rooms & Bookings", version="1.0.0", lifespan=lifespan)
app.state.settings = settings or get_settings()
@app.get("/health")
def health() -> dict:
return {"status": "ok"}
@app.get("/me", response_model=User)
def me(user: CurrentUser) -> User:
return user
@app.post("/rooms", response_model=RoomPublic, status_code=status.HTTP_201_CREATED)
def create_room(room_in: RoomCreate, session: SessionDep, admin: AdminUser) -> Room:
room = Room.model_validate(room_in)
session.add(room)
try:
session.commit()
except IntegrityError:
session.rollback()
raise HTTPException(status.HTTP_409_CONFLICT, "Room name already exists")
session.refresh(room)
return room
@app.get("/rooms", response_model=List[RoomPublic])
def list_rooms(
session: SessionDep, limit: int = Query(20, ge=1, le=100), offset: int = Query(0, ge=0)
) -> List[Room]:
return list(session.exec(select(Room).order_by(Room.id).offset(offset).limit(limit)).all())
@app.get("/rooms/{room_id}", response_model=RoomPublic)
def get_room(room_id: int, session: SessionDep) -> Room:
room = session.get(Room, room_id)
if room is None:
raise HTTPException(status.HTTP_404_NOT_FOUND, "Room not found")
return room
@app.post("/bookings", response_model=BookingPublic, status_code=status.HTTP_201_CREATED)
def create_booking(
booking_in: BookingCreate,
session: SessionDep,
user: CurrentUser,
payments: PaymentsDep,
outbox: OutboxDep,
background_tasks: BackgroundTasks,
) -> Booking:
if booking_in.check_in < dt.date.today():
raise HTTPException(status.HTTP_422_UNPROCESSABLE_CONTENT, "check_in is in the past")
room = session.get(Room, booking_in.room_id)
if room is None:
raise HTTPException(status.HTTP_404_NOT_FOUND, "Room not found")
if overlapping_bookings(session, room.id, booking_in.check_in, booking_in.check_out):
raise HTTPException(status.HTTP_409_CONFLICT, "Room already booked for these dates")
nights = (booking_in.check_out - booking_in.check_in).days
total = pricing.quote(nights, room.price_per_night)
key = f"u{user.id}-r{room.id}-{booking_in.check_in.isoformat()}"
try:
payment_id = payments.charge(amount_cents=total, reference=f"room-{room.id}", idempotency_key=key)
except PaymentDeclined as exc:
raise HTTPException(status.HTTP_402_PAYMENT_REQUIRED, f"Payment declined: {exc}")
except PaymentUnavailable:
raise HTTPException(status.HTTP_503_SERVICE_UNAVAILABLE, "Payment provider unavailable, try again")
booking = Booking.model_validate(
booking_in,
update={
"user_id": user.id,
"total_cents": total,
"payment_id": payment_id,
"created_at": dt.datetime.now(dt.timezone.utc).replace(tzinfo=None),
},
)
session.add(booking)
session.commit()
session.refresh(booking)
background_tasks.add_task(send_confirmation, outbox, booking.id, user.email)
return booking
@app.get("/bookings/me", response_model=List[BookingPublic])
def my_bookings(session: SessionDep, user: CurrentUser) -> List[Booking]:
stmt = select(Booking).where(Booking.user_id == user.id).order_by(Booking.check_in)
return list(session.exec(stmt).all())
@app.websocket("/ws/rooms/{room_id}/availability")
async def availability(websocket: WebSocket, room_id: int, session: SessionDep) -> None:
await websocket.accept()
try:
while True:
msg = await websocket.receive_json()
check_in = dt.date.fromisoformat(msg["check_in"])
check_out = dt.date.fromisoformat(msg["check_out"])
taken = overlapping_bookings(session, room_id, check_in, check_out)
await websocket.send_json({"room_id": room_id, "available": taken == 0})
except WebSocketDisconnect:
pass
return app
app = create_app()The project file pins the stack and configures pytest (markers, addopts, asyncio_mode, warnings as errors) and coverage (branch, fail_under):
[project]
name = "testing-fastapi-pytest"
version = "0.1.0"
description = "Snippets for the Testing FastAPI chapter: a rooms & bookings app and its layered pytest suite"
# The page targets Python 3.12+; the pins below are the newest releases that still install on 3.9,
# the only interpreter on the build machine (FastAPI 0.129.0 and SQLModel 0.0.35 dropped 3.9).
requires-python = ">=3.9"
dependencies = [
"fastapi==0.128.8",
"starlette==0.49.3",
"pydantic==2.13.5",
"sqlalchemy==2.0.58",
"sqlmodel==0.0.34",
"httpx==0.28.1",
"uvicorn==0.39.0",
# Lets Pydantic evaluate `X | None` annotations on Python 3.9; not needed on 3.10+.
"eval-type-backport==0.4.0; python_version < '3.10'",
]
[project.optional-dependencies]
test = [
"pytest==8.4.2",
"pytest-asyncio==1.2.0", # last release for Python 3.9
"anyio==4.12.1", # ships the `anyio` pytest plugin
"asgi-lifespan==2.1.0", # runs the lifespan around httpx.AsyncClient + ASGITransport
"respx==0.23.1",
"pytest-httpx==0.35.0",
"freezegun==1.5.5",
"time-machine==2.19.0",
"factory-boy==3.3.3",
"Faker==37.12.0",
"polyfactory==3.5.0",
"coverage==7.10.7",
"pytest-cov==7.1.0",
]
[build-system]
requires = ["setuptools>=61"]
build-backend = "setuptools.build_meta"
[tool.setuptools]
packages = ["app"]
[tool.pytest.ini_options]
minversion = "8.0"
testpaths = ["tests"]
pythonpath = ["."]
# -ra: summary of skips/xfails; strict markers: a typo in a marker name is an error, not a new marker.
# The speed comparison and the PostgreSQL suite only run when selected with -m.
addopts = "-ra --strict-markers -p no:cacheprovider -m 'not speed and not postgres'"
markers = [
"slow: slower tests (schema recreated per test)",
"speed: fixture timing comparison, run with -m speed",
"postgres: needs Docker + testcontainers, run with -m postgres",
"contract: OpenAPI snapshot and provider contract checks",
]
asyncio_mode = "strict" # only @pytest.mark.asyncio tests go to pytest-asyncio
asyncio_default_fixture_loop_scope = "function"
filterwarnings = ["error"] # a new deprecation warning fails the suite
[tool.coverage.run]
branch = true
source = ["app"]
[tool.coverage.report]
show_missing = true
skip_covered = false
fail_under = 90The root conftest.py: one engine per run, one connection and outer transaction per test, a session joined with create_savepoint, a fresh app per test with get_session overridden, the client inside with, users and real test tokens:
"""Root fixtures, shared by every test directory below.
Layering: tests/conftest.py (this file: database, app, client, users, tokens)
tests/api/conftest.py (autouse: the payment provider is mocked for every API test)
A fixture defined in a deeper conftest.py with the same name overrides this one for that directory.
"""
from typing import Callable, Dict, Iterator
import factory.random
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from sqlalchemy.engine import Connection, Engine
from sqlmodel import Session, SQLModel
from app.db import get_session, make_engine
from app.main import create_app
from app.models import User
from app.security import issue_token
from app.settings import Settings
from tests import factories
factory.random.reseed_random(1234) # Faker values are the same on every run
TEST_SETTINGS = Settings(
database_url="sqlite://", # the lifespan's own engine; the tests replace get_session anyway
payments_url="https://payments.example.test",
token_secret="test-secret",
token_ttl_s=900,
)
# --- database: one schema per session, one transaction per test -------------------------------
@pytest.fixture(scope="session")
def engine() -> Iterator[Engine]:
"""Created once for the whole run: in-memory SQLite, StaticPool, SQLAlchemy-emitted BEGIN."""
engine = make_engine("sqlite://")
SQLModel.metadata.create_all(engine)
yield engine
engine.dispose()
@pytest.fixture
def connection(engine: Engine) -> Iterator[Connection]:
"""BEGIN at the start of every test, ROLLBACK at the end: nothing a test writes survives it."""
conn = engine.connect()
outer = conn.begin()
try:
yield conn
finally:
outer.rollback()
conn.close()
@pytest.fixture
def db_session(connection: Connection) -> Iterator[Session]:
"""A Session joined to the outer transaction. commit() and rollback() inside the app
become RELEASE SAVEPOINT / ROLLBACK TO SAVEPOINT, so the route code runs unchanged."""
session = Session(bind=connection, join_transaction_mode="create_savepoint")
factories.bind(session)
try:
yield session
finally:
session.close()
# --- application ---------------------------------------------------------------------------------
@pytest.fixture
def settings() -> Settings:
return TEST_SETTINGS
@pytest.fixture
def app(settings: Settings, db_session: Session) -> Iterator[FastAPI]:
"""A fresh app per test with get_session overridden to the test session."""
app = create_app(settings)
def override_get_session() -> Iterator[Session]:
yield db_session # no close here: the fixture owns the session's lifetime
app.dependency_overrides[get_session] = override_get_session
yield app
app.dependency_overrides.clear()
@pytest.fixture
def client(app: FastAPI) -> Iterator[TestClient]:
"""`with` runs the lifespan (http client, outbox); without it app.state stays empty."""
with TestClient(app) as c:
yield c
# --- users and tokens ----------------------------------------------------------------------------
@pytest.fixture
def make_user(db_session: Session) -> Callable[..., User]:
def _make(**kwargs: object) -> User:
return factories.UserFactory(**kwargs)
return _make
@pytest.fixture
def user(make_user: Callable[..., User]) -> User:
return make_user(email="guest@example.com")
@pytest.fixture
def admin(make_user: Callable[..., User]) -> User:
return make_user(email="admin@example.com", is_admin=True)
@pytest.fixture
def auth_headers(settings: Settings) -> Callable[[User], Dict[str, str]]:
"""A real test token signed with the test secret: the whole auth path runs."""
def _headers(u: User) -> Dict[str, str]:
return {"Authorization": f"Bearer {issue_token(u.id, settings.token_secret, settings.token_ttl_s)}"}
return _headersThe factories: factory_boy for rows, polyfactory for payloads:
"""Test data builders.
factory_boy builds *rows* (table models saved through the test session);
polyfactory builds *payloads* (Pydantic/SQLModel data models) from the type hints.
"""
import datetime as dt
import factory
from polyfactory import PostGenerated, Use
from polyfactory.factories.pydantic_factory import ModelFactory
from sqlmodel import Session
from app.models import BookingCreate, Room, User
def bind(session: Session) -> None:
"""Point every SQLAlchemy factory at the current test's session."""
for f in (UserFactory, RoomFactory):
f._meta.sqlalchemy_session = session
class UserFactory(factory.alchemy.SQLAlchemyModelFactory):
class Meta:
model = User
sqlalchemy_session_persistence = "flush" # INSERT now, inside the test transaction
email = factory.Sequence(lambda n: f"user{n}@example.com")
is_admin = False
class RoomFactory(factory.alchemy.SQLAlchemyModelFactory):
class Meta:
model = Room
sqlalchemy_session_persistence = "flush"
name = factory.Sequence(lambda n: f"Room {n}")
capacity = factory.Faker("pyint", min_value=1, max_value=4)
price_per_night = factory.Faker("pyint", min_value=5_000, max_value=20_000, step=500)
class BookingCreateFactory(ModelFactory[BookingCreate]):
"""Valid booking payloads: check_in 1-60 days ahead, a 3-night stay."""
__model__ = BookingCreate
__random_seed__ = 1234
room_id = Use(lambda: 1)
check_in = Use(lambda: dt.date.today() + dt.timedelta(days=BookingCreateFactory.__random__.randint(1, 60)))
check_out = PostGenerated(lambda name, values: values["check_in"] + dt.timedelta(days=3))The API directory's conftest.py adds one autouse fixture, so no API test can reach the network:
"""API-level fixtures. autouse: every test in tests/api gets a mocked payment provider,
so no API test can reach the network by accident (respx raises on unmatched requests)."""
import json
from pathlib import Path
from typing import Any, Dict, Iterator
import httpx
import pytest
import respx
SAMPLES: Dict[str, Any] = json.loads((Path(__file__).parent.parent / "contract" / "payments_samples.json").read_text())
@pytest.fixture(autouse=True)
def payments_api() -> Iterator[respx.MockRouter]:
with respx.mock(base_url="https://payments.example.test", assert_all_called=False) as router:
router.post("/v1/charges", name="charge").mock(
return_value=httpx.Response(201, json=SAMPLES["charge_succeeded"])
)
yield router{
"charge_succeeded": {"id": "ch_test_123", "status": "succeeded", "amount_cents": 36000, "currency": "EUR"},
"charge_declined": {"error": "card_declined", "reason": "insufficient funds"}
}Unit tests: a table-driven pure function, model validation, tokens under a frozen and a moving clock, the HTTP client against respx and pytest-httpx, settings with monkeypatch:
"""Unit tests: a pure function, no fixtures, table-driven with parametrize."""
import pytest
from app.pricing import quote
@pytest.mark.parametrize(
("nights", "price", "expected"),
[
pytest.param(1, 10_000, 10_000, id="one-night"),
pytest.param(6, 10_000, 60_000, id="six-nights-no-discount"),
pytest.param(7, 10_000, 63_000, id="weekly-discount-starts-at-7"),
pytest.param(10, 9_999, 89_991, id="discount-rounds-down"), # 99_990 * 0.9 = 89_991
],
)
def test_quote(nights: int, price: int, expected: int) -> None:
# Arrange is the parameter table; Act and Assert are one line each.
total = quote(nights, price)
assert total == expected
@pytest.mark.parametrize(("nights", "price"), [(0, 10_000), (-1, 10_000), (3, 0)])
def test_quote_rejects_nonsense(nights: int, price: int) -> None:
with pytest.raises(ValueError, match="must be"):
quote(nights, price)"""Validation rules tested on the model itself, without HTTP."""
import datetime as dt
import pytest
from pydantic import ValidationError
from app.models import BookingCreate
from tests.factories import BookingCreateFactory
def test_factory_builds_valid_payloads() -> None:
for payload in BookingCreateFactory.batch(size=20):
assert payload.check_out - payload.check_in == dt.timedelta(days=3)
@pytest.mark.parametrize(
("check_in", "check_out", "message"),
[
("2030-01-10", "2030-01-10", "check_out must be after check_in"),
("2030-01-10", "2030-01-09", "check_out must be after check_in"),
("2030-01-01", "2030-03-01", "stays are limited to 30 nights"),
],
)
def test_booking_dates_are_validated(check_in: str, check_out: str, message: str) -> None:
with pytest.raises(ValidationError) as exc_info:
BookingCreate.model_validate({"room_id": 1, "check_in": check_in, "check_out": check_out})
error = exc_info.value.errors()[0]
assert error["type"] == "value_error"
assert message in error["msg"]"""Time-dependent code: freeze or move the clock instead of sleeping."""
import time
import pytest
import time_machine
from freezegun import freeze_time
from app.security import ExpiredToken, InvalidToken, issue_token, verify_token
SECRET = "unit-secret"
@freeze_time("2026-11-29 12:00:00")
def test_token_valid_until_its_expiry_freezegun() -> None:
token = issue_token(7, SECRET, ttl_s=900)
assert verify_token(token, SECRET) == 7
with freeze_time("2026-11-29 12:14:59"):
assert verify_token(token, SECRET) == 7
with freeze_time("2026-11-29 12:15:00"):
with pytest.raises(ExpiredToken):
verify_token(token, SECRET)
def test_token_expiry_time_machine() -> None:
with time_machine.travel("2026-11-29 12:00:00+00:00", tick=False) as traveller:
token = issue_token(7, SECRET, ttl_s=900)
traveller.shift(899)
assert verify_token(token, SECRET) == 7
traveller.shift(1)
with pytest.raises(ExpiredToken):
verify_token(token, SECRET)
def test_frozen_clock_does_not_move() -> None:
with freeze_time("2026-11-29 12:00:00"):
before = time.time()
sum(range(100_000))
assert time.time() == before
@pytest.mark.parametrize("token", ["", "abc", "1.2", "1.notanint.sig", "x.1.sig"])
def test_malformed_tokens(token: str) -> None:
with pytest.raises(InvalidToken):
verify_token(token, SECRET)
def test_tampered_signature() -> None:
token = issue_token(7, SECRET, ttl_s=900)
user_id, exp, sig = token.split(".")
with pytest.raises(InvalidToken, match="bad signature"):
verify_token(f"8.{exp}.{sig}", SECRET)"""The outbound HTTP client, tested against a mocked transport.
respx and pytest-httpx both replace httpx's transport, so the real PaymentsClient code
(serialisation, headers, status handling) runs; only the network is fake.
"""
import json
from pathlib import Path
from unittest import mock
import httpx
import pytest
import respx
from pytest_httpx import HTTPXMock
from app.payments import PaymentDeclined, PaymentsClient, PaymentUnavailable
BASE = "https://payments.example.test"
SAMPLES = json.loads((Path(__file__).parent.parent / "contract" / "payments_samples.json").read_text())
@pytest.fixture
def client() -> PaymentsClient:
return PaymentsClient(httpx.Client(base_url=BASE, timeout=2.0))
@respx.mock(base_url=BASE)
def test_charge_sends_amount_and_idempotency_key(respx_mock: respx.MockRouter, client: PaymentsClient) -> None:
route = respx_mock.post("/v1/charges").mock(return_value=httpx.Response(201, json=SAMPLES["charge_succeeded"]))
charge_id = client.charge(amount_cents=36_000, reference="room-1", idempotency_key="k-1")
assert charge_id == "ch_test_123"
assert route.call_count == 1
sent = route.calls.last.request
assert sent.headers["Idempotency-Key"] == "k-1"
assert json.loads(sent.content) == {"amount_cents": 36_000, "currency": "EUR", "reference": "room-1"}
@respx.mock(base_url=BASE)
def test_declined_is_a_domain_error(respx_mock: respx.MockRouter, client: PaymentsClient) -> None:
respx_mock.post("/v1/charges").respond(402, json=SAMPLES["charge_declined"])
with pytest.raises(PaymentDeclined, match="insufficient funds"):
client.charge(amount_cents=1, reference="r", idempotency_key="k")
@respx.mock(base_url=BASE)
def test_timeout_becomes_unavailable(respx_mock: respx.MockRouter, client: PaymentsClient) -> None:
respx_mock.post("/v1/charges").mock(side_effect=httpx.ConnectTimeout("connect timed out"))
with pytest.raises(PaymentUnavailable, match="timed out"):
client.charge(amount_cents=1, reference="r", idempotency_key="k")
@respx.mock(base_url=BASE, assert_all_called=False) # default True: an unused route fails the test
def test_unmatched_request_is_an_error_not_a_network_call(respx_mock: respx.MockRouter) -> None:
respx_mock.post("/v1/charges").respond(201, json=SAMPLES["charge_succeeded"])
http = httpx.Client(base_url=BASE)
with pytest.raises(respx.models.AllMockedAssertionError):
http.get("/v1/refunds")
def test_server_error_with_pytest_httpx(httpx_mock: HTTPXMock, client: PaymentsClient) -> None:
httpx_mock.add_response(method="POST", url=f"{BASE}/v1/charges", status_code=503)
with pytest.raises(PaymentUnavailable, match="answered 503"):
client.charge(amount_cents=1, reference="r", idempotency_key="k")
request = httpx_mock.get_request()
assert request is not None and request.headers["Idempotency-Key"] == "k"
def test_unittest_mock_replaces_the_whole_client() -> None:
"""A Mock with spec= fails on misspelled methods; it checks call shape, not HTTP."""
fake = mock.create_autospec(PaymentsClient, instance=True)
fake.charge.return_value = "ch_mock"
assert fake.charge(amount_cents=1, reference="r", idempotency_key="k") == "ch_mock"
fake.charge.assert_called_once_with(amount_cents=1, reference="r", idempotency_key="k")
with pytest.raises(AttributeError):
fake.refund # not on the real class, so not on the autospec either"""Environment-driven settings: monkeypatch sets and restores env vars; clear the cache around it."""
from typing import Iterator
import pytest
from app.settings import get_settings
@pytest.fixture(autouse=True)
def fresh_settings_cache() -> Iterator[None]:
get_settings.cache_clear()
yield
get_settings.cache_clear() # never leak test settings into the next test
def test_defaults() -> None:
assert get_settings().payments_url == "https://payments.example.test"
def test_env_override(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("BOOKINGS_PAYMENTS_URL", "http://localhost:9999")
monkeypatch.setenv("BOOKINGS_TOKEN_TTL_S", "60")
settings = get_settings()
assert (settings.payments_url, settings.token_ttl_s) == ("http://localhost:9999", 60)
def test_cache_hides_later_env_changes(monkeypatch: pytest.MonkeyPatch) -> None:
first = get_settings()
monkeypatch.setenv("BOOKINGS_TOKEN_TTL_S", "5")
assert get_settings() is first and first.token_ttl_s == 900 # lru_cache: env read onceAPI tests through TestClient: rooms (201, 409 with the savepoint still usable, the exact 422 list, 401 before 422, 403, pagination, 404), auth three ways, the booking flow with the mocked provider and the background task, the lifespan, the one test without overrides, and the WebSocket:
"""Route tests through TestClient: status codes, bodies, validation errors, auth."""
from typing import Callable, Dict
from fastapi.testclient import TestClient
from app.models import User
from tests.factories import RoomFactory
ROOM = {"name": "Garden", "capacity": 2, "price_per_night": 12_000}
def test_health(client: TestClient) -> None:
response = client.get("/health")
assert response.status_code == 200
assert response.json() == {"status": "ok"}
def test_admin_creates_room(client: TestClient, admin: User, auth_headers: Callable[[User], Dict[str, str]]) -> None:
response = client.post("/rooms", json=ROOM, headers=auth_headers(admin))
assert response.status_code == 201, response.text
body = response.json()
assert body["name"] == "Garden" and isinstance(body["id"], int)
def test_duplicate_room_is_409_and_session_still_usable(
client: TestClient, admin: User, auth_headers: Callable[[User], Dict[str, str]]
) -> None:
headers = auth_headers(admin)
assert client.post("/rooms", json=ROOM, headers=headers).status_code == 201
second = client.post("/rooms", json=ROOM, headers=headers)
assert second.status_code == 409
assert second.json() == {"detail": "Room name already exists"}
# the route's session.rollback() only rolled back to the savepoint: the first room survived
assert [r["name"] for r in client.get("/rooms").json()] == ["Garden"]
def test_validation_error_body_is_exact(
client: TestClient, admin: User, auth_headers: Callable[[User], Dict[str, str]]
) -> None:
response = client.post("/rooms", json={"name": "", "capacity": 0}, headers=auth_headers(admin))
assert response.status_code == 422
errors = response.json()["detail"]
assert [(e["loc"], e["type"]) for e in errors] == [
(["body", "name"], "string_too_short"),
(["body", "capacity"], "greater_than_equal"),
(["body", "price_per_night"], "missing"),
]
assert errors[1]["msg"] == "Input should be greater than or equal to 1"
def test_auth_runs_before_body_validation(client: TestClient) -> None:
# no token and an invalid body: the 401 from the dependency wins, the 422 never happens
response = client.post("/rooms", json={})
assert response.status_code == 401
assert response.headers["www-authenticate"] == "Bearer"
def test_non_admin_gets_403(client: TestClient, user: User, auth_headers: Callable[[User], Dict[str, str]]) -> None:
response = client.post("/rooms", json=ROOM, headers=auth_headers(user))
assert response.status_code == 403
assert response.json() == {"detail": "Admins only"}
def test_pagination_with_factory_rows(client: TestClient) -> None:
RoomFactory.create_batch(5)
page = client.get("/rooms", params={"limit": 2, "offset": 2}).json()
assert len(page) == 2
assert client.get("/rooms", params={"limit": 0}).status_code == 422
def test_unknown_room_is_404(client: TestClient) -> None:
assert client.get("/rooms/999").json() == {"detail": "Room not found"}"""Auth-protected routes three ways: the real token path, an expired token, a fake current user."""
from typing import Callable, Dict
import time_machine
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.deps import get_current_user
from app.models import User
from app.security import issue_token
from app.settings import Settings
def test_no_token_is_401(client: TestClient) -> None:
response = client.get("/me")
assert response.status_code == 401
assert response.json() == {"detail": "Not authenticated"}
def test_real_test_token(client: TestClient, user: User, auth_headers: Callable[[User], Dict[str, str]]) -> None:
response = client.get("/me", headers=auth_headers(user))
assert response.status_code == 200
assert response.json() == {"id": user.id, "email": "guest@example.com", "is_admin": False}
def test_token_signed_with_another_secret(client: TestClient, user: User) -> None:
token = issue_token(user.id, "not-the-test-secret", 900)
response = client.get("/me", headers={"Authorization": f"Bearer {token}"})
assert response.json() == {"detail": "Invalid token"}
def test_expired_token(client: TestClient, user: User, settings: Settings) -> None:
with time_machine.travel("2026-11-29 12:00:00+00:00", tick=False) as traveller:
token = issue_token(user.id, settings.token_secret, settings.token_ttl_s)
traveller.shift(settings.token_ttl_s) # exactly at expiry
response = client.get("/me", headers={"Authorization": f"Bearer {token}"})
assert response.status_code == 401
assert response.json() == {"detail": "Token expired"}
def test_fake_current_user(app: FastAPI, client: TestClient) -> None:
"""Override the whole auth dependency: no header, no token, no users table read."""
app.dependency_overrides[get_current_user] = lambda: User(id=42, email="fake@example.com", is_admin=True)
response = client.get("/me")
assert response.json() == {"id": 42, "email": "fake@example.com", "is_admin": True}"""The booking flow end to end inside the process: DB, auth, mocked payment API, background task."""
import datetime as dt
import json
from typing import Callable, Dict
from unittest import mock
import httpx
import pytest
import respx
from fastapi import FastAPI
from fastapi.testclient import TestClient
from freezegun import freeze_time
from app import main
from app.deps import get_payments
from app.models import Room, User
from app.payments import PaymentsClient, PaymentUnavailable
from tests.factories import RoomFactory
Headers = Callable[[User], Dict[str, str]]
@pytest.fixture
def room() -> Room:
return RoomFactory(name="Sea View", price_per_night=12_000)
def stay(days_ahead: int = 10, nights: int = 3, room_id: int = 1) -> Dict[str, object]:
start = dt.date.today() + dt.timedelta(days=days_ahead)
return {"room_id": room_id, "check_in": start.isoformat(), "check_out": (start + dt.timedelta(days=nights)).isoformat()}
def test_booking_charges_and_sends_confirmation(
app: FastAPI, client: TestClient, room: Room, user: User, auth_headers: Headers, payments_api: respx.MockRouter
) -> None:
response = client.post("/bookings", json=stay(room_id=room.id), headers=auth_headers(user))
assert response.status_code == 201, response.text
body = response.json()
assert body["total_cents"] == 36_000 and body["payment_id"] == "ch_test_123"
charge = payments_api["charge"].calls.last.request
assert json.loads(charge.content)["amount_cents"] == 36_000
assert charge.headers["Idempotency-Key"].startswith(f"u{user.id}-r{room.id}-")
# TestClient runs background tasks before it returns the response
assert app.state.outbox == [
{"to": "guest@example.com", "subject": f"Booking {body['id']} confirmed", "booking_id": body["id"]}
]
def test_overlap_is_409(client: TestClient, room: Room, user: User, auth_headers: Headers) -> None:
headers = auth_headers(user)
assert client.post("/bookings", json=stay(10, 3, room.id), headers=headers).status_code == 201
clash = client.post("/bookings", json=stay(12, 3, room.id), headers=headers)
assert clash.status_code == 409
back_to_back = client.post("/bookings", json=stay(13, 2, room.id), headers=headers)
assert back_to_back.status_code == 201 # check_out day == next check_in day is allowed
def test_declined_payment_is_402_and_nothing_saved(
client: TestClient, room: Room, user: User, auth_headers: Headers, payments_api: respx.MockRouter
) -> None:
payments_api["charge"].respond(402, json={"error": "card_declined", "reason": "insufficient funds"})
response = client.post("/bookings", json=stay(room_id=room.id), headers=auth_headers(user))
assert response.status_code == 402
assert response.json() == {"detail": "Payment declined: insufficient funds"}
assert client.get("/bookings/me", headers=auth_headers(user)).json() == []
def test_provider_timeout_is_503(
client: TestClient, room: Room, user: User, auth_headers: Headers, payments_api: respx.MockRouter
) -> None:
payments_api["charge"].mock(side_effect=httpx.ReadTimeout("read timed out"))
response = client.post("/bookings", json=stay(room_id=room.id), headers=auth_headers(user))
assert response.status_code == 503
@freeze_time("2026-12-24")
def test_past_check_in_is_rejected(client: TestClient, room: Room, user: User, auth_headers: Headers) -> None:
payload = {"room_id": room.id, "check_in": "2026-12-23", "check_out": "2026-12-26"}
response = client.post("/bookings", json=payload, headers=auth_headers(user))
assert response.status_code == 422
assert response.json() == {"detail": "check_in is in the past"}
def test_invalid_dates_give_a_422_body(client: TestClient, user: User, auth_headers: Headers) -> None:
payload = {"room_id": 1, "check_in": "2030-01-10", "check_out": "2030-01-09"}
detail = client.post("/bookings", json=payload, headers=auth_headers(user)).json()["detail"]
assert detail[0]["type"] == "value_error"
assert detail[0]["loc"] == ["body"]
assert detail[0]["msg"] == "Value error, check_out must be after check_in"
def test_payments_dependency_overridden_with_a_mock(
app: FastAPI, client: TestClient, room: Room, user: User, auth_headers: Headers
) -> None:
fake = mock.create_autospec(PaymentsClient, instance=True)
fake.charge.side_effect = PaymentUnavailable("down")
app.dependency_overrides[get_payments] = lambda: fake
response = client.post("/bookings", json=stay(room_id=room.id), headers=auth_headers(user))
assert response.status_code == 503
fake.charge.assert_called_once()
def test_background_task_function_patched(client: TestClient, room: Room, user: User, auth_headers: Headers) -> None:
with mock.patch.object(main, "send_confirmation") as sent:
response = client.post("/bookings", json=stay(room_id=room.id), headers=auth_headers(user))
sent.assert_called_once_with(mock.ANY, response.json()["id"], "guest@example.com")"""TestClient runs the lifespan only inside `with`."""
from typing import Callable, Dict
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.models import User
def test_with_block_runs_startup_and_shutdown(app: FastAPI) -> None:
assert not hasattr(app.state, "outbox")
with TestClient(app) as client:
assert client.get("/health").status_code == 200
assert app.state.outbox == [] # startup ran
http = app.state.http
assert http.is_closed # shutdown ran
def test_without_with_no_lifespan(app: FastAPI, user: User, auth_headers: Callable[[User], Dict[str, str]]) -> None:
client = TestClient(app)
assert client.get("/health").status_code == 200 # routes that need no state still work
with pytest.raises(AttributeError, match="'State' object has no attribute 'payments'"):
payload = {"room_id": 1, "check_in": "2030-01-10", "check_out": "2030-01-12"}
client.post("/bookings", json=payload, headers=auth_headers(user))"""One smoke test with NO overrides: the real get_session, the lifespan's engine, a real commit.
Every other API test replaces get_session, so without this file the production wiring
(app/db.py's get_session and get_engine) would never run under test; coverage shows it.
"""
from fastapi.testclient import TestClient
from sqlmodel import Session
from app.main import create_app
from app.models import User
from app.security import issue_token
from tests.conftest import TEST_SETTINGS
def test_real_session_dependency_end_to_end() -> None:
app = create_app(TEST_SETTINGS)
with TestClient(app) as client:
with Session(app.state.engine) as s:
s.add(User(email="real@example.com", is_admin=True))
s.commit()
headers = {"Authorization": f"Bearer {issue_token(1, TEST_SETTINGS.token_secret, 60)}"}
created = client.post("/rooms", json={"name": "Real", "capacity": 1, "price_per_night": 100}, headers=headers)
assert created.status_code == 201
assert client.get(f"/rooms/{created.json()['id']}").json()["name"] == "Real"
# the yield dependency rolls back and re-raises when the route fails
assert client.post("/rooms", json={"name": "Real", "capacity": 1, "price_per_night": 100}, headers=headers).status_code == 409
def test_token_for_deleted_user_is_401(client: TestClient, settings) -> None: # type: ignore[no-untyped-def]
token = issue_token(9999, settings.token_secret, 60)
response = client.get("/me", headers={"Authorization": f"Bearer {token}"})
assert response.json() == {"detail": "Unknown user"}"""WebSocket routes go through the same TestClient, with websocket_connect()."""
import datetime as dt
from typing import Callable, Dict
from fastapi.testclient import TestClient
from app.models import User
from tests.factories import RoomFactory
def test_availability_over_websocket(client: TestClient, user: User, auth_headers: Callable[[User], Dict[str, str]]) -> None:
room = RoomFactory()
start = dt.date.today() + dt.timedelta(days=5)
stay = {"check_in": start.isoformat(), "check_out": (start + dt.timedelta(days=2)).isoformat()}
with client.websocket_connect(f"/ws/rooms/{room.id}/availability") as ws:
ws.send_json(stay)
assert ws.receive_json() == {"room_id": room.id, "available": True}
booked = client.post("/bookings", json={"room_id": room.id, **stay}, headers=auth_headers(user))
assert booked.status_code == 201
ws.send_json(stay)
assert ws.receive_json() == {"room_id": room.id, "available": False}Async tests with httpx.AsyncClient and ASGITransport, under the anyio plugin and under pytest-asyncio:
"""Async tests: httpx.AsyncClient + ASGITransport, under the anyio plugin and under pytest-asyncio.
ASGITransport sends requests straight into the ASGI app; it does NOT send lifespan events.
asgi-lifespan's LifespanManager does that part.
"""
from typing import AsyncIterator, Callable, Dict
import pytest
from asgi_lifespan import LifespanManager
from fastapi import FastAPI
from httpx import ASGITransport, AsyncClient
from app.models import User
from tests.factories import RoomFactory
Headers = Callable[[User], Dict[str, str]]
@pytest.fixture
def anyio_backend() -> str:
return "asyncio" # the anyio plugin can also run each test on "trio"
@pytest.mark.anyio
async def test_health_with_anyio(app: FastAPI) -> None:
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as ac:
response = await ac.get("/health")
assert response.status_code == 200
@pytest.mark.anyio
async def test_without_lifespan_app_state_is_empty(app: FastAPI, user: User, auth_headers: Headers) -> None:
RoomFactory()
payload = {"room_id": 1, "check_in": "2030-01-10", "check_out": "2030-01-12"}
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as ac:
with pytest.raises(AttributeError, match="'State' object has no attribute 'payments'"):
await ac.post("/bookings", json=payload, headers=auth_headers(user))
@pytest.fixture
async def lifespan_client(app: FastAPI) -> AsyncIterator[AsyncClient]:
async with LifespanManager(app) as manager:
async with AsyncClient(transport=ASGITransport(app=manager.app), base_url="http://test") as ac:
yield ac
@pytest.mark.anyio
async def test_booking_with_lifespan_manager(lifespan_client: AsyncClient, user: User, auth_headers: Headers) -> None:
room = RoomFactory()
payload = {"room_id": room.id, "check_in": "2030-01-10", "check_out": "2030-01-12"}
response = await lifespan_client.post("/bookings", json=payload, headers=auth_headers(user))
assert response.status_code == 201, response.text
@pytest.mark.asyncio
async def test_health_with_pytest_asyncio(app: FastAPI) -> None:
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as ac:
assert (await ac.get("/health")).json() == {"status": "ok"}Database tests: isolation proved across two tests, the SQL a commit becomes, the negative control for the sqlite3 trap, and the schema recreate variant overriding db_session for one module:
"""Proof that the per-test transaction really isolates tests (run in file order)."""
from typing import Callable, Dict, List
from fastapi.testclient import TestClient
from sqlalchemy import event, text
from sqlalchemy.engine import Connection, Engine
from sqlmodel import Session, select
from app.models import Room, User
Headers = Callable[[User], Dict[str, str]]
def test_1_route_commits_inside_the_test(client: TestClient, admin: User, auth_headers: Headers, db_session: Session) -> None:
response = client.post("/rooms", json={"name": "Isolation", "capacity": 1, "price_per_night": 100}, headers=auth_headers(admin))
assert response.status_code == 201
assert db_session.exec(select(Room).where(Room.name == "Isolation")).one().id == response.json()["id"]
def test_2_the_commit_did_not_survive_the_test(engine: Engine) -> None:
with engine.connect() as conn: # a plain connection, outside any test transaction
assert conn.execute(text("SELECT count(*) FROM room")).scalar() == 0
assert conn.execute(text("SELECT count(*) FROM user")).scalar() == 0
def test_route_commit_becomes_release_savepoint(
client: TestClient, admin: User, auth_headers: Headers, connection: Connection
) -> None:
statements: List[str] = []
@event.listens_for(connection, "before_cursor_execute")
def record(conn, cursor, statement, parameters, context, executemany): # type: ignore[no-untyped-def]
statements.append(statement.split(" (")[0])
client.post("/rooms", json={"name": "Traced", "capacity": 1, "price_per_night": 100}, headers=auth_headers(admin))
event.remove(connection, "before_cursor_execute", record)
# The savepoint opened when the fixture flushed `admin` (sa_savepoint_1). The route's
# commit() releases it; refresh() then opens the next one. No COMMIT reaches SQLite.
assert statements[:3] == ["INSERT INTO room", "RELEASE SAVEPOINT sa_savepoint_1", "SAVEPOINT sa_savepoint_2"]
assert statements[3].startswith("SELECT room.name")
assert "COMMIT" not in statements"""Negative control: the same recipe without SQLAlchemy's BEGIN hook on the sqlite3 driver.
In the driver's legacy transaction control (the default before Python 3.16), SAVEPOINT does
not join the enclosing transaction, so a released savepoint survives the outer ROLLBACK.
This test pins that behaviour so nobody 'simplifies' make_engine() and loses isolation silently.
"""
from sqlalchemy import text
from sqlmodel import Session, SQLModel
from app.db import make_engine
from app.models import Room
def leaked_rows(sqlalchemy_begin: bool) -> int:
engine = make_engine("sqlite://", sqlalchemy_begin=sqlalchemy_begin)
SQLModel.metadata.create_all(engine)
conn = engine.connect()
outer = conn.begin()
session = Session(bind=conn, join_transaction_mode="create_savepoint")
session.add(Room(name="Leak", capacity=1, price_per_night=1))
session.commit() # SAVEPOINT ... RELEASE SAVEPOINT
session.close()
outer.rollback() # should undo everything
conn.close()
with engine.connect() as check:
count = check.execute(text("SELECT count(*) FROM room")).scalar()
engine.dispose()
return count
def test_with_sqlalchemy_begin_the_rollback_undoes_the_commit() -> None:
assert leaked_rows(sqlalchemy_begin=True) == 0
def test_driver_legacy_mode_leaks_the_released_savepoint() -> None:
assert leaked_rows(sqlalchemy_begin=False) == 1"""The other isolation strategy: a brand-new database and schema for every test.
This is what the SQLModel tutorial does (create_all per test with an in-memory engine).
The module-level `db_session` fixture overrides the root conftest's one for this file only.
"""
from typing import Callable, Dict, Iterator, List
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import event
from sqlalchemy.engine import Engine
from sqlmodel import Session, SQLModel, func, select
from app.db import make_engine
from app.models import Room, User
from tests import factories
pytestmark = pytest.mark.slow
@pytest.fixture
def db_session() -> Iterator[Session]:
engine = make_engine("sqlite://") # a new in-memory database: nothing to roll back
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
factories.bind(session)
yield session
SQLModel.metadata.drop_all(engine)
engine.dispose()
def test_route_commit_is_a_real_commit_here(
client: TestClient, admin: User, auth_headers: Callable[[User], Dict[str, str]], db_session: Session
) -> None:
engine = db_session.get_bind()
assert isinstance(engine, Engine) # the root fixture binds a Connection inside an outer transaction
commits: List[int] = []
event.listen(engine, "commit", lambda conn: commits.append(1))
response = client.post("/rooms", json={"name": "Fresh", "capacity": 1, "price_per_night": 100}, headers=auth_headers(admin))
assert response.status_code == 201
assert commits == [1] # a real COMMIT; under the root fixture this list stays empty (RELEASE SAVEPOINT)
def test_previous_commit_is_gone_because_the_database_is_new(db_session: Session) -> None:
assert db_session.exec(select(func.count()).select_from(Room)).one() == 0Contract tests: the OpenAPI snapshot and the provider samples:
"""OpenAPI snapshot: any change to the public API shape shows up as a failing diff in review.
Update deliberately with: UPDATE_SNAPSHOTS=1 pytest tests/contract
"""
import json
import os
from pathlib import Path
import pytest
from app.main import create_app
from app.settings import Settings
pytestmark = pytest.mark.contract
SNAPSHOT = Path(__file__).parent / "snapshots" / "openapi.json"
def current_schema() -> str:
schema = create_app(Settings()).openapi() # building the schema needs no lifespan and no DB
return json.dumps(schema, indent=2, sort_keys=True) + "\n"
def test_openapi_matches_snapshot() -> None:
actual = current_schema()
if os.environ.get("UPDATE_SNAPSHOTS") == "1" or not SNAPSHOT.exists():
SNAPSHOT.write_text(actual)
pytest.skip("snapshot written; review and commit it")
assert actual == SNAPSHOT.read_text(), "public API changed: review the diff, then UPDATE_SNAPSHOTS=1"
def test_breaking_change_is_caught() -> None:
"""What a removed field looks like to the snapshot test."""
schema = json.loads(SNAPSHOT.read_text())
props = schema["components"]["schemas"]["RoomPublic"]["properties"]
assert set(props) == {"id", "name", "capacity", "price_per_night"}
assert schema["components"]["schemas"]["RoomPublic"]["required"] == ["name", "capacity", "price_per_night", "id"]"""Consumer-side contract: the samples our mocks return must match what we parse.
The same JSON file feeds the respx mocks (tests/api/conftest.py) and this test, so a mock
cannot drift away from the model the client validates. A provider-side check (the provider
runs our expectations against its real API, e.g. with Pact) is the other half: not run here.
"""
import json
from pathlib import Path
import pytest
from pydantic import ValidationError
from app.payments import ChargeResponse
pytestmark = pytest.mark.contract
SAMPLES = json.loads((Path(__file__).parent / "payments_samples.json").read_text())
def test_success_sample_satisfies_the_model() -> None:
charge = ChargeResponse.model_validate(SAMPLES["charge_succeeded"])
assert charge.id.startswith("ch_")
def test_provider_renaming_a_field_breaks_the_contract() -> None:
renamed = dict(SAMPLES["charge_succeeded"])
renamed["charge_id"] = renamed.pop("id")
with pytest.raises(ValidationError, match="id\n Field required"):
ChargeResponse.model_validate(renamed)
def test_declined_sample_has_the_reason_we_show() -> None:
assert "reason" in SAMPLES["charge_declined"]The speed comparison, whose conftest.py overrides db_session with a parametrized fixture, and the PostgreSQL suite for CI:
"""Overrides the root `db_session` for this directory: every speed test runs once per strategy.
rollback one schema for the run; BEGIN ... ROLLBACK around each test (root conftest)
recreate-memory new in-memory engine + create_all/drop_all per test (the SQLModel tutorial)
recreate-file new SQLite file + create_all per test (closer to a server database's DDL cost)
"""
from pathlib import Path
from typing import Iterator
import pytest
from sqlalchemy.engine import Engine
from sqlmodel import Session, SQLModel
from app.db import make_engine
from tests import factories
@pytest.fixture(params=["rollback", "recreate-memory", "recreate-file"])
def db_session(request: pytest.FixtureRequest, engine: Engine, tmp_path: Path) -> Iterator[Session]:
if request.param == "rollback":
conn = engine.connect()
outer = conn.begin()
session = Session(bind=conn, join_transaction_mode="create_savepoint")
factories.bind(session)
yield session
session.close()
outer.rollback()
conn.close()
return
url = "sqlite://" if request.param == "recreate-memory" else f"sqlite:///{tmp_path / 'test.db'}"
fresh = make_engine(url)
SQLModel.metadata.create_all(fresh)
session = Session(fresh)
factories.bind(session)
yield session
session.close()
SQLModel.metadata.drop_all(fresh)
fresh.dispose()"""Same test bodies under each DB strategy. Not part of the default run:
pytest -m speed -k rollback pytest -m speed -k recreate-memory pytest -m speed -k recreate-file
Compare the wall times; never assert on timings (they depend on the machine).
"""
from typing import Callable, Dict
import pytest
from fastapi.testclient import TestClient
from sqlmodel import Session, func, select
from app.models import Room, User
from tests.factories import RoomFactory
pytestmark = pytest.mark.speed
N = range(100)
@pytest.mark.parametrize("i", N)
def test_db_only(db_session: Session, i: int) -> None:
RoomFactory.create_batch(3)
assert db_session.exec(select(func.count()).select_from(Room)).one() == 3
@pytest.mark.parametrize("i", N)
def test_through_api(client: TestClient, admin: User, auth_headers: Callable[[User], Dict[str, str]], i: int) -> None:
response = client.post("/rooms", json={"name": f"R{i}", "capacity": 2, "price_per_night": 100}, headers=auth_headers(admin))
assert response.status_code == 201
assert len(client.get("/rooms").json()) == 1"""The same rollback-per-test recipe against a real PostgreSQL in a throwaway container.
Expected, not run on the build machine (no Docker). In CI:
pip install "testcontainers[postgres]" "psycopg[binary]"
pytest -m postgres
"""
from typing import Iterator
import pytest
from sqlalchemy import create_engine, text
from sqlalchemy.engine import Engine
from sqlmodel import Session, SQLModel
from app.models import Room
pytestmark = pytest.mark.postgres
postgres = pytest.importorskip("testcontainers.postgres", reason="testcontainers not installed")
@pytest.fixture(scope="session")
def pg_engine() -> Iterator[Engine]:
with postgres.PostgresContainer("postgres:17", driver="psycopg") as pg:
engine = create_engine(pg.get_connection_url())
SQLModel.metadata.create_all(engine) # in a real project: run the Alembic migrations here
yield engine
engine.dispose()
@pytest.fixture
def pg_session(pg_engine: Engine) -> Iterator[Session]:
conn = pg_engine.connect()
outer = conn.begin()
session = Session(bind=conn, join_transaction_mode="create_savepoint")
yield session
session.close()
outer.rollback()
conn.close()
def test_insert_is_rolled_back(pg_session: Session) -> None:
pg_session.add(Room(name="PG", capacity=1, price_per_night=1))
pg_session.commit()
assert pg_session.exec(text("SELECT count(*) FROM room")).scalar() == 1The Python angle
Most of what looks like magic here is plain Python. A fixture is a function, and pytest calls it because a test names it as a parameter. That is the same idea as FastAPI's Depends, which is why the SQLModel tutorial says "pytest fixtures work in a very similar way to FastAPI dependencies". A yield fixture is a generator: code before yield is setup, code after it is teardown, and pytest runs teardowns in reverse order. Assert rewriting is an import hook. pytest rewrites the bytecode of test modules (and of conftest.py and plugins) as it imports them, so assert response.status_code == 201 reports assert 503 == 201 with where 503 = <Response ...>.status_code. Helper modules that are not test modules are not rewritten. Clock mocking is module patching. freezegun replaces datetime, time.time and friends wherever they were imported, which is why its cost grows with the number of loaded modules (the slowest test of the run is the frozen-time one, 0.03 s setup plus 0.02 s call, runs/durations.txt). time-machine patches the C-level functions once. unittest.mock.create_autospec builds a mock from the real class signature, so fake.refund raises AttributeError and a wrong keyword argument fails. Two 3.9-specific details shape the snippets. They use Optional[X] and no from __future__ import annotations in app modules, because FastAPI and SQLModel read annotations at runtime. And SQLite's driver (sqlite3) has no autocommit attribute before Python 3.12, so the engine uses SQLAlchemy's BEGIN hook. On 3.12+ the SQLAlchemy docs also offer connect_args={"autocommit": False}.
The concept catalogue
pytest basics: test discovery, assert rewriting, arrange act assert Must-know
In plain words: pytest finds tests by name, runs each one, and when a plain assert fails it shows the values on both sides. A good test reads in three steps: arrange the world, act once, assert the outcome.
Common misunderstanding: "I need self.assertEqual or a special assert library for useful messages." pytest's docs: "Reporting details about a failing assertion is achieved by rewriting assert statements before they are run." The other misreading is that every module gets this. "pytest only rewrites test modules directly discovered by its test collection process", plus conftest.py and plugins, so "asserts in supporting modules which are not themselves test modules will not be rewritten". An assert inside app/ code or a plain helper module gives a bare AssertionError.
Definition: Test discovery per the good-practices page: starting from testpaths or the arguments, pytest recurses into directories, and "In those directories, search for test_*.py or *_test.py files". Inside them it collects "test prefixed test functions or methods outside of class" and "test prefixed test functions or methods inside Test prefixed test classes (without an __init__ method)". Arrange, act, assert is the shape the pytest docs' "Anatomy of a test" page describes, in four steps: arrange, act, assert, cleanup. A fixture is the reusable "arrange" and its teardown the "cleanup".
pytest (rootdir = folder with pyproject.toml; testpaths = ["tests"])
1 collect: tests/**/test_*.py -> modules imported with assert rewriting
2 collect: test_* functions, Test* classes, parametrize expands ids
3 deselect: -m 'not speed and not postgres' (from addopts) -> 600 deselected
4 per test: set up requested fixtures (scope order), call test, tear down in reverse
5 report: "71 passed, 1 skipped, 600 deselected in 0.70s" (real; 0.63-0.70 s across runs)Real scenario: the Before suite's failure reads assert 503 == 201 / where 503 = <Response [503 Service Unavailable]>.status_code, which already says "the payment call failed" without a debugger; a 422 test asserts on the (loc, type) pairs, so the failure shows exactly which field changed.
| Piece | Rule | In the snippet |
|---|---|---|
| File names | test_*.py or *_test.py | tests/unit/test_pricing.py |
| Functions | test_ prefix | test_quote |
| Classes | Test prefix, no __init__ | not used; functions are enough |
__init__.py in test dirs | Package-style import names; avoids basename clashes | every tests/* directory |
| Assert rewriting | Test modules, conftest.py, plugins | tests/** |
| Arrange / act / assert | Fixtures arrange; one action; plain asserts | test_quote: table, quote(...), assert |
Fix / how to use it: name files and functions by the convention; keep one action per test; assert on whole structures (assert body == {...}) where the shape matters, on chosen fields where it does not; put shared helpers in conftest.py (rewritten) rather than in a plain module if they assert.
Configuration: pytest.ini, pyproject [tool.pytest.ini_options], [tool.pytest] Important
In plain words: pytest reads its settings from one file at the project root: the test folders, default options, markers and plugin settings. In a pyproject.toml project that file is pyproject.toml.
Common misunderstanding: "[tool.pytest.ini_options] is TOML, so lists and numbers are typed." The pytest 9.0.0 changelog: pytest "since version 6, supports configuration in pyproject.toml files under [tool.pytest.ini_options], it does so in an 'INI compatibility mode', where all configuration values are treated as strings or list of strings". Native TOML is the new [tool.pytest] table in pytest 9.0+, and "both tables cannot be used at the same time". The snippet uses [tool.pytest.ini_options] because pytest 8.4.2 is the 3.9 pin.
Definition: The customize page: pytest determines the common ancestor of the arguments and looks upwards for "pytest.toml, .pytest.toml, pytest.ini, .pytest.ini, pyproject.toml, tox.ini, and setup.cfg"; "pytest.ini files take precedence over other files (except pytest.toml and .pytest.toml), even when empty". The file found sets the rootdir and configfile, which "are printed as part of the pytest header during startup" (real: configfile: pyproject.toml). Note that "rootdir is NOT used to modify sys.path/PYTHONPATH", which is why the snippet sets pythonpath = ["."].
# pyproject.toml (pytest 8.x and 9.x; the snippet's table)
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-ra --strict-markers -p no:cacheprovider -m 'not speed and not postgres'"
markers = ["slow: ...", "speed: ...", "postgres: ...", "contract: ..."]
asyncio_mode = "strict"
filterwarnings = ["error"]
# pytest 9.0+ only, native types (cannot coexist with the table above)
[tool.pytest]
addopts = ["-ra", "-q"]Real scenario: filterwarnings = ["error"] turns any new DeprecationWarning from FastAPI, Pydantic or SQLAlchemy into a test failure on upgrade day, not in production months later; --strict-markers makes a typo like @pytest.mark.slwo an error.
| Setting | Effect | Snippet value |
|---|---|---|
testpaths | Where to look when no path is given | ["tests"] (so before/ runs only on request) |
pythonpath | Prepended to sys.path | ["."] (import app without installing) |
addopts | Default command-line options | -ra --strict-markers -p no:cacheprovider -m ... |
markers | Registered marker names | slow, speed, postgres, contract |
asyncio_mode | pytest-asyncio discovery mode | strict |
filterwarnings | Warning filters for the run | error |
minversion | Refuse older pytest | 8.0 |
Fix / how to use it: one config table in pyproject.toml; --strict-markers and filterwarnings = ["error"] from day one; move to [tool.pytest] when the project requires pytest 9.
Fixtures: fixture scope, yield fixture, autouse Must-know
In plain words: A fixture is a function that builds something a test needs. The test asks for it by naming a parameter. With yield, the code after yield is the cleanup. The scope says how often it is rebuilt.
Common misunderstanding: "A session-scoped fixture is the fast default." A wider scope shares state: a session-scoped database session would carry one test's rows into the next. Only things that are expensive and immutable for the run (the engine and schema) get a wide scope; anything a test can change stays function-scoped. Also: fixtures are not called in file order. pytest builds the graph from the requested names; the fixtures reference: "Higher-scoped fixtures are executed first" and "Autouse fixtures are executed first within their scope".
Definition: The scopes, verbatim from the fixture docs: "function: the default scope, the fixture is destroyed at the end of the test"; "class: the fixture is destroyed during teardown of the last test in the class"; "module: the fixture is destroyed during teardown of the last test in the module"; "package: ... the last test in the package where the fixture is defined, including sub-packages and sub-directories within it"; "session: the fixture is destroyed at the end of the test session". autouse=True makes a fixture apply to every test in its scope without being requested ("Autouse fixtures (fixtures you don't have to request)").
the snippet's graph for one API test (real order of SQL from runs/sql-trace.txt)
1 engine scope=session make_engine + create_all, once per run
2 connection function engine.connect(); conn.begin() -> BEGIN
3 db_session function Session(bind=conn, join_transaction_mode="create_savepoint")
4 app function create_app(settings); overrides[get_session] = yield db_session
5 client function with TestClient(app): lifespan startup
6 admin function UserFactory flush -> SAVEPOINT sa_savepoint_1; INSERT
7 test body ...
8 teardown reverse: client (shutdown), app (overrides.clear), db_session.close, outer.rollback -> ROLLBACKReal scenario: every API test asks for client and gets, without asking, a mocked payment provider (payments_api, autouse in tests/api/conftest.py) and a fresh database view (the chain above). The settings test's autouse fixture clears get_settings's lru_cache before and after each test.
| Fixture | Scope | Yield? | Why that scope |
|---|---|---|---|
engine | session | yes (dispose) | Schema creation is the expensive, immutable part |
connection | function | yes (rollback, close) | One outer transaction per test |
db_session | function | yes (close) | Identity map must not leak |
app | function | yes (clear overrides) | Overrides and app.state must not leak |
client | function | yes (lifespan shutdown) | One lifespan per app |
payments_api | function, autouse | yes (respx stop) | Routes and call history per test |
user, admin, make_user | function | no | Rows live in the test transaction |
anyio_backend | function (anyio's built-in one is function-scoped too) | no | Picks asyncio for @pytest.mark.anyio |
Fix / how to use it: widen scope only for immutable, expensive things; use yield for cleanup (it runs even when the test fails); give factories as fixtures (make_user) rather than global rows; make "always on" safety nets autouse (no network, cache clearing).
conftest.py layering and overriding a fixture Important
In plain words: A conftest.py holds fixtures for its folder and everything below it. A deeper file (or the test module itself) can define a fixture with the same name and win for its part of the tree.
Common misunderstanding: "Import fixtures from conftest.py." You never import them: pytest loads every conftest.py on the path to a test and offers its fixtures by name. Importing a fixture function into a test module creates a second definition. The other trap is defining all fixtures in the root file, so slow or risky ones (a network mock, a parametrized DB strategy) apply where they should not.
Definition: The fixtures docs describe how to "Override a fixture on a directory (conftest) level", "on a test module level" and "with direct test parametrization", and pytest picks the closest definition: test module, then the nearest conftest.py, then parent conftest.py files, then plugins. A fixture can also request the fixture it overrides by the same name to extend it.
tests/conftest.py engine, connection, db_session, settings, app, client, users, auth_headers
1 tests/api/conftest.py + payments_api (autouse): every API test is offline
2 tests/db/test_schema_recreate.py module-level db_session: new engine + create_all per test (overrides root)
3 tests/speed/conftest.py db_session(params=[rollback, recreate-memory, recreate-file]) (overrides root)
4 app and client are NOT redefined: they pick up whichever db_session is closest -> same API tests, three strategiesReal scenario: the schema-recreate module proves the override: its session is bound to an Engine and the route's commit() fires the engine's commit event once, a real COMMIT. With the module fixture removed in a scratch copy, the root fixture applies and the test fails with isinstance(<sqlalchemy.engine.base.Connection ...>, Engine) is False (real, runs/recreate-override-check.txt). Do not use "ids restart at 1" as the proof: SQLite reuses rowids after a rollback, so ids start at 1 under the rollback fixture too.
| Level | File | Affects | Snippet use |
|---|---|---|---|
| Plugin | installed package | Whole run | respx_mock, httpx_mock, monkeypatch, tmp_path |
| Root | tests/conftest.py | All tests | DB, app, client, users |
| Directory | tests/api/conftest.py | tests/api/** | autouse payments_api |
| Directory | tests/speed/conftest.py | tests/speed/** | parametrized db_session |
| Module | the test file | That file | db_session in test_schema_recreate.py |
Fix / how to use it: keep the root conftest.py for what every test needs; push specialised fixtures down to the directory that needs them; override by name instead of adding flags to a fixture.
Parametrize: one test body, many cases Must-know
In plain words: Write the test once and give pytest a table of inputs and expected outputs; each row becomes its own test with its own name and its own pass or fail.
Common misunderstanding: "A loop inside one test is the same." A loop stops at the first failing case and reports one test; parametrize reports every case and lets you run one (-k weekly-discount). The other misreading is that ids are cosmetic: readable ids (pytest.param(..., id="weekly-discount-starts-at-7")) are what you see in CI and select with -k.
Definition: @pytest.mark.parametrize(argnames, argvalues, ids=...) generates one test per value set; stacking two decorators produces the cross product. pytest.param(..., id=..., marks=...) sets an id or marks for one row. A fixture can also be parametrized with @pytest.fixture(params=[...]), which is how tests/speed/conftest.py runs every speed test under three DB strategies.
@pytest.mark.parametrize(
("nights", "price", "expected"),
[
pytest.param(1, 10_000, 10_000, id="one-night"),
pytest.param(6, 10_000, 60_000, id="six-nights-no-discount"),
pytest.param(7, 10_000, 63_000, id="weekly-discount-starts-at-7"),
pytest.param(10, 9_999, 89_991, id="discount-rounds-down"), # 99_990 * 0.9 = 89_991
],
)
def test_quote(nights: int, price: int, expected: int) -> None:Real scenario: boundary tables (6 vs 7 nights for a discount), invalid inputs (empty, zero, negative), every malformed token shape ("", "abc", "1.2", "1.notanint.sig", "x.1.sig"), and the speed comparison (2 bodies x 3 strategies x 100 = 600 generated tests, real).
| Form | Generates | Snippet |
|---|---|---|
parametrize("a,b", [...]) | One test per row | test_quote_rejects_nonsense (3) |
pytest.param(..., id=...) | Named rows | test_quote (4) |
| Two stacked decorators | Cross product | not needed here |
@pytest.fixture(params=[...]) | Every test using the fixture, per param | db_session in tests/speed (3) |
range(100) as values | Repetition for timing | test_db_only[rollback-0..99] |
Fix / how to use it: table-drive pure logic and validation; name rows; keep each row's expectation in the row (not computed in the test); use fixture params to run the same tests under different infrastructure.
Markers: slow, contract, postgres, --strict-markers, -m Important
In plain words: A marker is a label on a test. You use labels to skip, expect failure, or choose which group of tests to run.
Common misunderstanding: "An unregistered marker just works." Without --strict-markers it does, with a warning, and with a typo it silently never selects anything. With --strict-markers (the snippet) an unknown marker is a collection error.
Definition: Built-in marks include skip, skipif, xfail, parametrize, usefixtures and filterwarnings. Custom marks are registered under markers in the config. -m 'expr' selects by marker expression, and pytestmark = pytest.mark.x at module level marks every test in the module. pytest.importorskip("testcontainers.postgres") skips a module when an optional dependency is missing (real: SKIPPED [1] tests/postgres/test_postgres.py:19: testcontainers not installed).
the snippet's selection (addopts has -m 'not speed and not postgres'; a later -m wins)
1 pytest -> 71 passed, 1 skipped, 600 deselected
2 pytest -m speed -k rollback -> 200 passed, 1 skipped, 471 deselected (both bodies, one strategy)
3 pytest -m contract -> 5 passed, 1 skipped, 666 deselected
4 pytest -m postgres -> 1 skipped, 671 deselected (no testcontainers here); CI with Docker runs itReal scenario: a fast default run for every save (well under a second here), a -m speed benchmark you run when changing fixtures, and a -m postgres job in CI that has Docker.
| Marker | Registered | Meaning in the snippet |
|---|---|---|
slow | yes | Schema recreated per test |
speed | yes | Timing comparison, excluded by default |
postgres | yes | Needs Docker + testcontainers |
contract | yes | OpenAPI snapshot and provider samples |
anyio | by the anyio plugin | Run this async def test on an event loop |
asyncio | by pytest-asyncio | Same, via pytest-asyncio (strict mode) |
skip/xfail | built in | Not used; prefer fixing or deleting |
Fix / how to use it: register every marker; keep the default run fast with addopts = -m 'not ...'; run the excluded groups in dedicated CI jobs.
TestClient and the lifespan in tests Must-know
In plain words: TestClient is an HTTP client that, instead of opening a socket, hands each request straight to your app object. Your tests are normal def functions, and the full request path (routing, validation, dependencies, serialisation, exception handlers) runs for real.
Common misunderstanding: "TestClient(app) runs startup." Only with TestClient(app) as client: does. The testing-events page: "When you need lifespan to run in your tests, you can use the TestClient with a with statement". Real run: without with, GET /health works but POST /bookings raises AttributeError: 'State' object has no attribute 'payments', because the lifespan never put the client on app.state. And raise_server_exceptions=True (the default) means an unhandled exception in the app is re-raised in the test instead of becoming a 500; pass False to assert on the 500.
Definition: Starlette's TestClient takes raise_server_exceptions: bool = True and backend: Literal["asyncio", "trio"] = "asyncio"; the backend options "are passed to anyio.start_blocking_portal()". FastAPI re-exports it: "You could also use from starlette.testclient import TestClient". The tutorial's tip: "Notice that the testing functions are normal def, not async def." The current Starlette docs (1.x) say it "is built on httpx2. Plain httpx is still supported, but deprecated"; the pin (0.49.3) uses httpx 0.28.1.
with TestClient(app) as client: (test thread)
1 portal = anyio.start_blocking_portal() event loop in a second thread
2 lifespan startup: engine, httpx.Client, PaymentsClient, outbox on app.state
3 client.post("/bookings", json=..., headers=...) -> ASGI scope/receive/send via the portal
4 route + dependencies run; `def` route in the thread pool; background tasks run
5 response returned to the test thread (TestClient waits for background tasks)
6 block exit: lifespan shutdown -> app.state.http.close(), engine.dispose() (real: http.is_closed)Real scenario: test_with_block_runs_startup_and_shutdown asserts app.state.outbox == [] inside the block and http.is_closed after it; test_booking_charges_and_sends_confirmation asserts the background task's outbox entry right after client.post.
| You want | Use | Note |
|---|---|---|
Normal def tests | TestClient | The default |
| Lifespan to run | with TestClient(app) as c | Once per with |
| Assert on a 500 | TestClient(app, raise_server_exceptions=False) | Default re-raises |
| Trio backend | TestClient(app, backend="trio") | Needs trio |
| WebSockets | client.websocket_connect(path) | See Background tasks and WebSockets |
| Base URL | http://testserver | Default host for relative paths |
| Call async code in the test too | AsyncClient + ASGITransport | See Async tests |
Fix / how to use it: a client fixture that yields inside with TestClient(app); a fresh app per test from an app factory; never a module-level client = TestClient(app) shared by every test.
Async tests: httpx.AsyncClient, ASGITransport, anyio, pytest-asyncio, asyncio_mode Must-know
In plain words: If the test itself must await something (an async repository, an async client), the test is async def, a plugin runs it on an event loop, and the app is called through httpx.AsyncClient with ASGITransport instead of TestClient.
Common misunderstanding: "ASGITransport behaves like TestClient." It does not run the lifespan. The FastAPI async-tests page: "If your application relies on lifespan events, the AsyncClient won't trigger these events. To ensure they are triggered, use LifespanManager from florimondmanca/asgi-lifespan." Real run: the same booking request raises AttributeError: 'State' object has no attribute 'payments' without it and returns 201 with it. Second trap: without a plugin marker, pytest refuses the coroutine (real, strict mode, marker removed): "async def functions are not natively supported."
Definition: The FastAPI page explains why: "The TestClient does some magic inside to call the asynchronous FastAPI application in your normal def test functions ... But that magic doesn't work anymore when we're using it inside asynchronous functions." anyio's plugin runs tests marked @pytest.mark.anyio on the backend chosen by the anyio_backend fixture. pytest-asyncio's modes: "In strict mode pytest-asyncio will only run tests that have the asyncio marker and will only evaluate async fixtures decorated with @pytest_asyncio.fixture"; auto mode handles every async def test and fixture.
@pytest.fixture
async def lifespan_client(app: FastAPI) -> AsyncIterator[AsyncClient]:
async with LifespanManager(app) as manager:
async with AsyncClient(transport=ASGITransport(app=manager.app), base_url="http://test") as ac:
yield acReal scenario: an async repository that must be awaited in the test, an app whose routes are async def and use an async SQLAlchemy session, or a check that several concurrent requests interleave. With both plugins installed in strict mode, @pytest.mark.anyio and @pytest.mark.asyncio tests coexist; with -o asyncio_mode=auto the four async tests still passed on this pin (real, runs/asyncio-modes.txt).
| Need | Tool | Snippet |
|---|---|---|
async def test, any backend | @pytest.mark.anyio + anyio_backend | test_health_with_anyio |
async def test, asyncio only | @pytest.mark.asyncio (strict) | test_health_with_pytest_asyncio |
| Async fixture under anyio | plain @pytest.fixture on async def | lifespan_client |
| Async fixture under strict pytest-asyncio | @pytest_asyncio.fixture | not needed here |
| HTTP into the app from async code | AsyncClient(transport=ASGITransport(app=app)) | all four tests |
| Lifespan around it | asgi_lifespan.LifespanManager | lifespan_client |
| Event loop per test | asyncio_default_fixture_loop_scope = "function" | pyproject.toml |
Fix / how to use it: prefer TestClient and def tests; switch to AsyncClient only when the test must await; pick one async plugin per project and strict mode; wrap the app in LifespanManager whenever the lifespan matters.
Testing routes and validation errors: the 422 body Must-know
In plain words: A route test sends a request and checks the status and the JSON. Testing validation errors is the same with bad input: FastAPI answers 422 with a list of errors, each saying where (loc), what kind (type) and a human message (msg); tests should pin that list down.
Common misunderstanding: "Assert status_code == 422 and move on." Any typo in the payload also gives 422, so the test passes for the wrong reason. Assert the (loc, type) pairs. And dependency failures come first: in the real run, POST /rooms with no token and an invalid body returns 401, not 422, because get_current_user raised before the body errors were reported.
Definition: FastAPI's handling-errors page: when a request contains invalid data, FastAPI raises RequestValidationError and responds 422 with the errors in detail. Each error is a Pydantic v2 error dict: type, loc (prefixed with body, query, path, header or cookie), msg, input, and ctx when the constraint has parameters. A model_validator error has loc: ["body"] and the message prefixed with Value error, . The real bodies:
POST /rooms {"name": "", "capacity": 0} (real, runs/error-texts.txt)
422 {"detail":[{"type":"string_too_short","loc":["body","name"],"msg":"String should have at least 1 character","input":"","ctx":{"min_length":1}},
{"type":"greater_than_equal","loc":["body","capacity"],"msg":"Input should be greater than or equal to 1","input":0,"ctx":{"ge":1}},
{"type":"missing","loc":["body","price_per_night"],"msg":"Field required","input":{"name":"","capacity":0}}]}
POST /bookings check_out before check_in
422 {"detail":[{"type":"value_error","loc":["body"],"msg":"Value error, check_out must be after check_in","input":{...},"ctx":{"error":{}}}]}
GET /rooms?limit=0
422 {"detail":[{"type":"greater_than_equal","loc":["query","limit"],"msg":"Input should be greater than or equal to 1","input":"0","ctx":{"ge":1}}]}Real scenario: a client team depends on loc to highlight form fields; a Pydantic upgrade that changes a type string must fail a test before it reaches them. The snippet also tests a domain 422 raised by the route ("check_in is in the past"), which has a plain string detail, a different shape that clients must handle.
| Error source | loc | Shape of detail | Snippet test |
|---|---|---|---|
| Field constraint | ["body", "name"] | list of error dicts | test_validation_error_body_is_exact |
| Missing field | ["body", "price_per_night"] | list, type: "missing" | same |
| Model validator | ["body"] | list, type: "value_error" | test_invalid_dates_give_a_422_body |
| Query parameter | ["query", "limit"] | list; input is the raw string "0" | test_pagination_with_factory_rows |
Route HTTPException(422) | — | string | test_past_check_in_is_rejected |
| Dependency raised first | — | 401 string, no 422 | test_auth_runs_before_body_validation |
Fix / how to use it: assert the list of (loc, type) pairs and one msg; keep domain errors in a documented shape; test that auth wins over validation if your clients rely on it.
Dependency overrides: app.dependency_overrides, override get_session Must-know
In plain words: In a test you can tell FastAPI "whenever a route asks for this dependency, call this other function instead". That is how the tests give every route the test's database session, a fake user or a fake payment client, without touching the app's code.
Common misunderstanding: "Override get_engine and the session follows." It would, but each request would open its own session on a pool, outside the test's transaction. Override get_session itself, with a generator that yields the test's db_session and does not close it: the fixture owns its lifetime. Second trap: overrides live on the app object, so a module-level app keeps them across tests unless cleared. The FastAPI docs reset with app.dependency_overrides = {}; the snippet builds a fresh app per test and still clears.
Definition: The testing-dependencies page: "There are some scenarios where you might want to override a dependency during testing." and "You probably want to test the external provider once, but not necessarily call it for every test that runs." The key is the original callable object; the value is any callable whose parameters FastAPI resolves like a dependency's. How the lookup works per node is in Dependency Injection with Depends.
@pytest.fixture
def app(settings: Settings, db_session: Session) -> Iterator[FastAPI]:
app = create_app(settings)
def override_get_session() -> Iterator[Session]:
yield db_session # no close here: the fixture owns the session's lifetime
app.dependency_overrides[get_session] = override_get_session
yield app
app.dependency_overrides.clear()Real scenario: get_session for every test; get_current_user with lambda: User(id=42, ...) for "fake current user" (no header sent, the 200 comes back with id 42, real); get_payments with a create_autospec(PaymentsClient) whose charge raises PaymentUnavailable (503, real). And one test with no override at all (test_real_wiring.py), because coverage showed get_session and get_engine were otherwise never executed.
| Override | Replaces | Keeps real | Snippet test |
|---|---|---|---|
get_session | Engine, pool, session lifetime | SQL, constraints, commits (as savepoints) | every API test |
get_current_user | Token parsing, user lookup | Route, admin check | test_fake_current_user |
get_payments | The whole client | Route's error mapping | test_payments_dependency_overridden_with_a_mock |
| none (respx instead) | Only the network | Client code, JSON, headers | test_booking_charges_and_sends_confirmation |
| none at all | nothing | everything except external hosts | test_real_session_dependency_end_to_end |
Fix / how to use it: override at the narrowest seam that removes the slow or external part; key by the exact object used in Depends; clear in fixture teardown; keep one smoke test that runs the real wiring.
SQLite in-memory for tests: StaticPool and check_same_thread Must-know
In plain words: An in-memory SQLite database exists only inside one connection. To make every part of a test (fixtures, the app, TestClient's other thread) see the same database, the engine must hand out that one connection every time and allow it to be used from other threads.
Common misunderstanding: "sqlite:// is one database for the engine." The SQLAlchemy docs: for a :memory: database "the dialect by default will use SingletonThreadPool. This pool maintains a single connection per thread, so that all access to the engine within the current thread use the same :memory: database - other threads would access a different :memory: database." Tables created on the test thread are missing on TestClient's portal thread or a thread-pool worker (no such table). The other misreading is that StaticPool makes SQLite safe for concurrency; the SQLAlchemy docs warn it "does not support any form of concurrency and is only useful when all access to the engine is fully serialized, such as in single-threaded test suites".
Definition: The SQLAlchemy recipe: create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool). And the warning: "Because StaticPool maintains a single DBAPI connection, all Session or Connection objects that use this engine share that one underlying connection and its single SQLite transaction state. A ROLLBACK issued by one session (e.g. during error handling) will also roll back uncommitted work from any other session". The SQLModel tutorial: "we need to also tell SQLAlchemy that we want to be able to use the same in-memory database object from different threads. We tell it that with the poolclass=StaticPool parameter." check_same_thread=False is needed because def routes run in the thread pool and TestClient runs the app in a portal thread.
why each setting is there (the snippet's make_engine for "sqlite://")
1 poolclass=StaticPool every checkout -> the same DBAPI connection -> the same in-memory DB
2 check_same_thread=False fixture thread, portal thread, thread-pool worker all use it
3 connect: isolation_level=None driver stops emitting its own BEGIN (see the trap below)
4 begin event: "BEGIN" SQLAlchemy emits BEGIN, so SAVEPOINTs nest inside it
5 connect: PRAGMA foreign_keys=ON SQLite ships with foreign keys off per connectionReal scenario: the root engine fixture builds this once; every test's connection checks out the one shared connection. The lifespan's own engine is a separate in-memory database the tests never read (routes get the overridden session), so its create_all and dispose cannot disturb the test transaction.
| Setting | Without it | With it |
|---|---|---|
StaticPool | Default SingletonThreadPool: one DB per thread | One DB per engine |
check_same_thread=False | ProgrammingError from the other thread | Shared across threads (serialised) |
| BEGIN hook | Savepoints escape the outer transaction | Rollback per test isolates |
PRAGMA foreign_keys=ON | FK violations silently accepted | Same errors as PostgreSQL |
| File DB instead | Survives the process; leftover files | No leftovers |
Fix / how to use it: one session-scoped engine with all four settings; route all test DB access through the one bound connection; run the same suite against PostgreSQL in CI for anything SQLite does differently.
Transaction rollback per test: nested transaction and savepoint Must-know
In plain words: The fixture opens a transaction before the test and rolls it back after, so nothing the test wrote survives. Because the app calls commit() and sometimes rollback(), the session turns those into savepoint operations inside the fixture's transaction.
Common misunderstanding: "If the app calls commit(), the data is committed and the rollback cannot undo it." With join_transaction_mode="create_savepoint", the session's commit() releases a savepoint and its rollback() rolls back to one, so the outer transaction stays open (real trace: no COMMIT reaches SQLite during a test, asserted in test_route_commit_becomes_release_savepoint). The reverse misunderstanding: "the route's session.rollback() after an IntegrityError throws away the test's earlier rows." It only rolls back to the current savepoint: in test_duplicate_room_is_409_and_session_still_usable the first room survives the 409.
Definition: SQLAlchemy, "Joining a Session into an External Transaction (such as for test suites)": "a Session can be made to participate within that transaction by just binding the Session to that Connection. The usual rationale for this is a test suite that allows ORM code to work freely with a Session, including the ability to call Session.commit(), where afterwards the entire database interaction is rolled back." The create_savepoint mode "indicates that new SAVEPOINTs should be created in order to implement BEGIN/COMMIT/ROLLBACK for the Session, which will leave the external transaction in the same state in which it was passed." And: "The above recipe is part of SQLAlchemy's own CI".
one test, real SQL (runs/sql-trace.txt)
1 BEGIN connection fixture
2 SAVEPOINT sa_savepoint_1 first ORM statement in the session
3 INSERT INTO user ... admin fixture (factory flush)
4 INSERT INTO room ... route: session.add + commit() ->
5 RELEASE SAVEPOINT sa_savepoint_1 ... commit() is a RELEASE
6 SAVEPOINT sa_savepoint_2 route: session.refresh(room)
7 SELECT room.name, ... WHERE room.id = ?
8 ROLLBACK TO SAVEPOINT sa_savepoint_2 db_session.close()
9 ROLLBACK connection fixture teardown: every row goneReal scenario: test_1_route_commits_inside_the_test creates a room through the API and finds it with db_session; the next test, test_2_the_commit_did_not_survive_the_test, opens a plain connection and counts 0 rooms and 0 users (real). Laravel's RefreshDatabase does the same thing: "it will only execute the test within a database transaction".
| Session call in the app | SQL inside a test | SQL in production |
|---|---|---|
| first statement | SAVEPOINT sa_savepoint_N | BEGIN |
commit() | RELEASE SAVEPOINT sa_savepoint_N | COMMIT |
rollback() | ROLLBACK TO SAVEPOINT sa_savepoint_N | ROLLBACK |
close() | ROLLBACK TO SAVEPOINT (if open) | ROLLBACK (if open) |
| fixture teardown | ROLLBACK | — |
begin_nested() in app code | a nested savepoint inside the test's | SAVEPOINT |
Fix / how to use it: the three fixtures of the root conftest.py (engine session-scoped, connection with begin()/rollback(), db_session with join_transaction_mode="create_savepoint"); bind factories to db_session; prove isolation with a pair of tests like test_1/test_2.
The sqlite3 driver trap: SAVEPOINT outside the transaction Important
In plain words: Python's built-in SQLite driver decides on its own when to send BEGIN, and it does not send one before a SAVEPOINT. Then a savepoint is not nested inside your test transaction at all, and "releasing" it is a real commit.
Common misunderstanding: "The rollback recipe passes, so it works." It can pass test by test and still leak: in the probe, the same recipe without SQLAlchemy's BEGIN hook left 1 row after the outer ROLLBACK, and in the full suite the leaked users produced 18 errors and 1 failure (UNIQUE constraint failed: user.email in later fixtures, assert 1 == 0 in the isolation check). Real, runs/savepoint-probe.txt and runs/lab-no-begin-hook.txt.
Definition: The SQLAlchemy SQLite dialect page: "Incorrect behavior for SAVEPOINT - as the SAVEPOINT statement does not imply a BEGIN, a new SAVEPOINT emitted before a BEGIN will function on its own but fails to participate in the enclosing transaction, meaning a ROLLBACK of the transaction will not rollback elements that were part of a released savepoint." The documented fix for all Python versions: a connect listener setting dbapi_connection.isolation_level = None and a begin listener running conn.exec_driver_sql("BEGIN"). On Python 3.12+ the alternative is connect_args={"autocommit": False}. The legacy mode "will no longer be the default in a future Python version (3.16 as of this writing)".
same recipe, two engines (real echo, runs/savepoint-probe.txt)
sqlalchemy_begin=True sqlalchemy_begin=False (driver legacy mode)
1 BEGIN (implicit) / BEGIN BEGIN (implicit) <- logged by SQLAlchemy, not sent by the driver
2 SAVEPOINT sa_savepoint_1 SAVEPOINT sa_savepoint_1 <- starts SQLite's transaction
3 INSERT INTO room ... INSERT INTO room ...
4 RELEASE SAVEPOINT sa_savepoint_1 RELEASE SAVEPOINT sa_savepoint_1 <- commits it
5 ROLLBACK ROLLBACK <- nothing left to undo
6 rooms after outer ROLLBACK: 0 rooms after outer ROLLBACK: 1Real scenario: a team copies the SQLAlchemy recipe, which is written against PostgreSQL, onto an in-memory SQLite test database on Python 3.11, and gets intermittent "duplicate email" errors depending on test order. tests/db/test_savepoint_trap.py pins both behaviours so the hook cannot be "simplified" away.
| Driver / setting | SAVEPOINT nests? | Rollback per test isolates? |
|---|---|---|
| sqlite3, legacy (default), no hook | No | No (1 leaked row) |
sqlite3 + isolation_level=None + BEGIN hook | Yes | Yes (0 rows) |
sqlite3, Python 3.12+, autocommit=False | Yes (per docs) | Expected yes, not run |
aiosqlite + the same hooks on engine.sync_engine | Yes (per docs) | Expected yes, not run |
| psycopg / asyncpg (PostgreSQL) | Yes | Yes (expected, not run) |
Fix / how to use it: put the BEGIN hook in the engine factory (the snippet's make_engine(..., sqlalchemy_begin=True) default); keep the negative-control test; never trust an isolation scheme without a test that proves a commit does not survive.
Schema recreate vs rollback: create_all per test and test speed Important
In plain words: The other way to isolate tests is to throw the whole database away after each one: new engine, create_all, test, drop_all. It is simpler and has no savepoint subtleties, but it pays the schema cost every time.
Common misunderstanding: "Recreating the schema is always much slower." For three tables on in-memory SQLite the measured difference is under 2 ms per test for the DB-only body and about 4 ms through the API. The cost grows with the schema (dozens of tables, indexes, extensions) and the database (PostgreSQL DDL, migrations instead of create_all). The opposite mistake: "Rollback is free, so always use it." It needs the BEGIN hook on SQLite and cannot test code that relies on real commits (two sessions, a second connection, AUTOCOMMIT DDL).
Definition: The SQLModel tutorial's fixture is the recreate style: an in-memory engine with StaticPool, SQLModel.metadata.create_all(engine), a Session, and app.dependency_overrides.clear() in teardown. The rollback style is the SQLAlchemy recipe above. The measurement uses the same two test bodies under three strategies (tests/speed/conftest.py), 100 tests each, three runs each (real, runs/speed.txt, SQLite 3.54.0, this machine; never asserted on):
pytest -m speed -k "<body> and <strategy>" -q (100 tests per line; 3 runs)
1 test_db_only rollback 0.22s 0.21s 0.21s
2 test_db_only recreate-memory 0.39s 0.38s 0.41s
3 test_db_only recreate-file 0.43s 0.45s 0.45s
4 test_through_api rollback 1.67s 1.59s 1.61s
5 test_through_api recreate-memory 2.02s 2.05s 2.00s
6 test_through_api recreate-file 1.98s 1.96s 2.31sReal scenario: per test, the DB-only body costs about 2.1 ms with rollback and 3.8-4.5 ms with recreate; through the API it is about 16 ms vs 20 ms, because each test also builds an app and runs a lifespan (whose own throwaway engine runs create_all too). On PostgreSQL with a real schema the gap widens (expected, not run); Laravel's docs make the same call: DatabaseMigrations and DatabaseTruncation are "significantly slower than the RefreshDatabase trait".
| Strategy | Isolation | Cost driver | When |
|---|---|---|---|
| Rollback per test | Outer transaction | One BEGIN/ROLLBACK | Default for most API tests |
| Recreate per test (memory) | New database | create_all per test | Tiny schemas, code that commits on several connections |
| Recreate per test (file/server) | New database | DDL on disk or server | Rarely; migration tests |
| Truncate tables after test | Empty tables | DELETE/TRUNCATE per table | Code that needs real commits on PostgreSQL |
| Template database (PostgreSQL) | Clone per worker | CREATE DATABASE ... TEMPLATE | Parallel workers (expected, not run) |
Fix / how to use it: rollback by default; a module-level db_session override with recreate for the few tests that need real commits; measure on your own schema with a parametrized fixture before deciding.
Factories: factory_boy, polyfactory, Faker Important
In plain words: A factory builds a valid object with sensible defaults, so a test only spells out the fields it cares about. factory_boy builds and saves database rows; polyfactory builds payloads from type hints; Faker supplies realistic fake values.
Common misunderstanding: "Random data finds more bugs, so let Faker pick everything." Unseeded random data makes failures unreproducible. The snippet seeds both (factory.random.reseed_random(1234), __random_seed__ = 1234) and writes the values that matter explicitly (RoomFactory(name="Sea View", price_per_night=12_000)). The other trap: a factory with its own session commits outside the test transaction; the snippet binds every factory to the test's db_session with sqlalchemy_session_persistence = "flush".
Definition: factory_boy's SQLAlchemyModelFactory uses Meta.sqlalchemy_session and sqlalchemy_session_persistence (None, "flush" or "commit"); factory.Sequence gives unique values; factory.Faker("pyint", ...) draws from Faker. polyfactory's ModelFactory[BookingCreate] generates instances from the model's fields; Use(...) sets a callable for one field and PostGenerated(...) computes a field from the already generated ones.
class BookingCreateFactory(ModelFactory[BookingCreate]):
"""Valid booking payloads: check_in 1-60 days ahead, a 3-night stay."""
__model__ = BookingCreate
__random_seed__ = 1234
room_id = Use(lambda: 1)
check_in = Use(lambda: dt.date.today() + dt.timedelta(days=BookingCreateFactory.__random__.randint(1, 60)))
check_out = PostGenerated(lambda name, values: values["check_in"] + dt.timedelta(days=3))Real scenario: RoomFactory.create_batch(5) for a pagination test; make_user(is_admin=True) for an admin; BookingCreateFactory.batch(size=20) asserted to always produce a valid 3-night stay (real). Laravel's model factories (User::factory()->create()) are the same idea.
| Tool | Builds | Persists | Snippet |
|---|---|---|---|
factory_boy SQLAlchemyModelFactory | Table rows | Through the bound session (flush) | UserFactory, RoomFactory |
polyfactory ModelFactory | Pydantic/SQLModel data models | No | BookingCreateFactory |
| Faker | Values (names, ints, emails) | No | factory.Faker("pyint", step=500) |
| A fixture returning a builder | Anything | Your choice | make_user |
| Hand-written dicts | Request JSON | No | ROOM, stay(...) |
Fix / how to use it: one factory per model with valid defaults; bind to the test session; seed randomness; spell out the fields the assertion depends on.
Testing auth-protected routes: test token, fake current user Must-know
In plain words: Testing auth routes has two honest options: send a real token the app will accept (the whole auth path runs), or replace the "who is the user" dependency with a fake user (the route runs, auth does not). Use the first for the auth rules and the second for everything else.
Common misunderstanding: "Override auth everywhere, it is faster." Then no test proves that a missing or expired token is rejected. The snippet keeps both: auth_headers(user) mints a real test token with the test secret, and only test_fake_current_user overrides get_current_user. The other trap is a hard-coded token in a module constant, built from the production default secret (the Before suite does exactly that).
Definition: OAuth2PasswordBearer only extracts the bearer token and answers 401 Not authenticated with WWW-Authenticate: Bearer when it is missing; get_current_user verifies it. The test token is the app's own issue_token(user.id, settings.token_secret, ttl), with settings from a fixture. Expiry is tested by moving the clock rather than waiting. Real responses:
GET /me (real)
1 no Authorization header -> 401 {"detail":"Not authenticated"} www-authenticate: Bearer
2 Bearer 1.2.3 (bad signature) -> 401 {"detail":"Invalid token"}
3 token signed with another secret -> 401 {"detail":"Invalid token"}
4 valid token, clock moved by ttl -> 401 {"detail":"Token expired"}
5 valid token, user id 9999 -> 401 {"detail":"Unknown user"}
6 override get_current_user -> 200 {"id":42,"email":"fake@example.com","is_admin":true}Real scenario: POST /rooms is admin-only: a guest's real token gets 403 Admins only; an admin's gets 201. The JWT version with refresh tokens is in Authentication in FastAPI, and the token theory in JWT Deep Dive. Laravel's actingAs($user) is the "fake current user" style.
| Approach | Runs auth code | Speed | Use for |
|---|---|---|---|
Real test token (auth_headers) | Yes | Same | 401/403 rules, expiry, roles |
Override get_current_user | No | Same | Business routes where auth is not the subject |
Override require_admin only | Partly | Same | Role checks in isolation |
| Real login endpoint per test | Yes, plus hashing | Slower (hashing) | One login test |
| Token from production secret | Yes | Same | Never |
Fix / how to use it: a test secret in test settings; a fixture that mints tokens for fixture users; auth-rule tests with real tokens; dependency_overrides[get_current_user] elsewhere when it makes tests clearer.
Mocking an external API: respx and pytest-httpx Must-know
In plain words: The app calls a payment provider over HTTP. In tests you install a fake at httpx's transport layer that answers with canned responses, so the real client code runs and no packet leaves the machine.
Common misunderstanding: "If I mock the provider, TestClient's requests get mocked too." respx patches the httpcore-based transports, and TestClient uses its own transport into the app, so the autouse respx fixture in tests/api/conftest.py intercepts only the outbound provider call (real: every API test passes with it active). Second: "an unmatched request falls through to the network". By default respx asserts "that all sent and captured HTTPX requests are routed and mocked" (real: AllMockedAssertionError: RESPX: <Request('GET', 'https://payments.example.test/v1/refunds')> not mocked!), and it also asserts all routes were called (real: AssertionError: RESPX: some routes were not called!, hence assert_all_called=False in the shared fixture).
Definition: respx: "RESPX is a simple, yet powerful, utility for mocking out the HTTPX, and HTTP Core, libraries." Routes match on method, host, path and more, return httpx.Response(...) or raise via side_effect, and record calls (route.calls.last.request). pytest-httpx provides the httpx_mock fixture; "By default, pytest-httpx will ensure that every response was requested during test execution", and unregistered requests fail unless assert_all_requests_were_expected=False.
@respx.mock(base_url=BASE)
def test_charge_sends_amount_and_idempotency_key(respx_mock: respx.MockRouter, client: PaymentsClient) -> None:
route = respx_mock.post("/v1/charges").mock(return_value=httpx.Response(201, json=SAMPLES["charge_succeeded"]))
charge_id = client.charge(amount_cents=36_000, reference="room-1", idempotency_key="k-1")
assert charge_id == "ch_test_123"
assert route.call_count == 1Real scenario: the provider's success (201 → booking saved), decline (402 → Payment declined: insufficient funds, nothing saved), timeout (httpx.ReadTimeout → 503) and server error (503 → PaymentUnavailable) are all tested without the provider. The retry and circuit-breaker policies around such calls belong to Background Tasks, Caching & External APIs.
| Tool | Level | Strength | Snippet |
|---|---|---|---|
| respx | httpx/httpcore transport | Rich route patterns, side_effect, call history | autouse payments_api, unit tests |
| pytest-httpx | httpx transport | Strict by default, simple fixture | test_server_error_with_pytest_httpx |
httpx.MockTransport | Your client's transport | No dependency, explicit injection | not used |
Override get_payments | Dependency | No HTTP at all | test_payments_dependency_overridden_with_a_mock |
| A fake HTTP server | Socket | Language-neutral | Contract tests against a stub (not run) |
| The real sandbox | Network | Real behaviour | A few tagged tests, outside the default run |
Fix / how to use it: an autouse mock that blocks the network for API tests; one route per external endpoint; assert on what was sent (body, headers, idempotency key); test timeouts with side_effect; keep the sample responses in one file shared with the contract test.
monkeypatch and unittest.mock Important
In plain words: monkeypatch changes an environment variable, an attribute or a dict for one test and puts it back afterwards. unittest.mock builds stand-in objects that record how they were called.
Common misunderstanding: "mock.patch('app.notifications.send_confirmation') patches the function everywhere." patch replaces a name where it is looked up. app.main imported send_confirmation into its own namespace, so the snippet patches main.send_confirmation (mock.patch.object(main, "send_confirmation")). The other trap: a bare Mock() accepts any attribute and any arguments, so a renamed method still "passes"; create_autospec(PaymentsClient, instance=True) raises AttributeError for fake.refund (real).
Definition: pytest's monkeypatch provides setattr, delattr, setitem, delitem, setenv, delenv, syspath_prepend and chdir, and "All modifications will be undone after the requesting test function or fixture has finished." The standard library: "Auto-speccing can be done through the autospec argument to patch, or the create_autospec() function. Auto-speccing creates mock objects that have the same attributes and methods as the objects they are replacing".
settings + monkeypatch + lru_cache (tests/unit/test_settings.py, real)
1 autouse fixture: get_settings.cache_clear()
2 monkeypatch.setenv("BOOKINGS_PAYMENTS_URL", "http://localhost:9999")
3 get_settings() -> reads env -> payments_url == "http://localhost:9999"
4 test_cache_hides_later_env_changes: setenv after the first call -> still 900 (cached)
5 teardown: env restored by monkeypatch; cache cleared againReal scenario: settings from the environment, a feature flag, a module-level function a route calls (the confirmation sender), a client replaced by an autospec that raises. FastAPI's settings page recommends a get_settings dependency with lru_cache and overriding it in tests, which the snippet does through create_app(settings).
| Tool | Replaces | Restored | Snippet |
|---|---|---|---|
monkeypatch.setenv | Env var | After the test | test_env_override |
monkeypatch.setattr | Attribute or function | After the test | not needed |
mock.patch.object(module, name) | A name in one module | On context exit | test_background_task_function_patched |
create_autospec(cls, instance=True) | An object with the real signature | n/a | test_unittest_mock_replaces_the_whole_client |
mock.ANY | "Any value" in call assertions | n/a | assert_called_once_with(mock.ANY, ...) |
dependency_overrides | A FastAPI dependency | When cleared | preferred for app seams |
Fix / how to use it: prefer a dependency override for anything the app injects; monkeypatch for env and globals; create_autospec over bare Mock; patch where the name is used.
Time and flaky tests: freezegun, time-machine, the retries anti-pattern Must-know
In plain words: Code that reads the clock gives different answers on different days. Tests should set the clock instead of sleeping or hoping, and a test that sometimes fails should be fixed, not retried until green.
Common misunderstanding: "Rerun failed tests in CI and the flakiness goes away." The pytest flaky-tests page lists rerun plugins ("Rerunning any failed tests can mitigate the negative effects of flaky tests"), and that is exactly the anti-pattern: a retry hides a real race or a time bomb. Fowler: "non-deterministic tests can completely destroy the value of an automated regression suite". Quarantine and fix. The Before suite's "2026-12-01" is such a time bomb: it passes today (2026-11-29) and fails from December 1 on.
Definition: freezegun: "Once the decorator or context manager have been invoked, all calls to datetime.datetime.now(), datetime.datetime.utcnow(), datetime.date.today(), time.time(), time.localtime(), time.gmtime(), and time.strftime() will return the time that has been frozen." time-machine's travel(dest, tick=False) returns a traveller with .shift(seconds) and .move_to(...). Its comparison page on freezegun: "It essentially does a find-and-replace mock of all the places that the datetime and time modules have been imported ... the time it takes to do the mocking is proportional to the number of loaded modules."
token expiry under a controlled clock (tests/unit/test_security.py, real)
1 travel("2026-11-29 12:00:00+00:00", tick=False) issue_token(ttl_s=900) -> exp = 12:15:00
2 shift(899) -> 12:14:59 verify -> 7
3 shift(1) -> 12:15:00 verify -> ExpiredToken
4 freeze_time("2026-12-24") + POST /bookings check_in 2026-12-23 -> 422 "check_in is in the past"Real scenario: token expiry, "no bookings in the past", a nightly job that runs "at midnight", rate-limit windows. Both libraries worked through TestClient here (the frozen clock did not stall the portal thread). The frozen-time booking test was the slowest of the run, 0.03 s setup plus 0.02 s call in the saved --durations=5 output (0.04 s call in an earlier run).
| Source of flakiness | Symptom | Fix |
|---|---|---|
| Wall clock | Fails near midnight or after a date | freezegun / time-machine; relative dates |
| Shared DB rows | Fails in a different order | Rollback per test; factories |
| Real network | Timeouts, DNS (Before: 2.31 s, 503) | respx / pytest-httpx |
sleep for async work | Slow and still racy | Await the result; TestClient waits for background tasks |
| Unseeded randomness | Fails once in N runs | Seed Faker and polyfactory |
| Leaked overrides or settings cache | Fails after another test | Fresh app; clear caches in fixtures |
Retries (--reruns) | Hides all of the above | Quarantine and fix the cause |
Fix / how to use it: never read the real clock in a test; time-machine for speed and coverage of C extensions, freezegun when the project already uses it; make dates relative to "today" in fixtures; treat a rerun-to-pass as a bug report.
Background tasks and WebSockets Important
In plain words: BackgroundTasks testing is easy because of one property: a background task runs after the response is sent, but with TestClient it has already run when your client.post(...) returns, so you can assert on its effect right away. A WebSocket test opens a connection with client.websocket_connect(...) and sends and receives messages like a browser would.
Common misunderstanding: "Background tasks need a sleep in the test." Not with TestClient: the real test asserts the outbox entry on the next line. The other misreading is testing a background task only through HTTP. The task function is plain Python; test it directly, and test through HTTP only that it was scheduled with the right arguments (mock.patch.object(main, "send_confirmation") + assert_called_once_with(mock.ANY, booking_id, "guest@example.com"), real).
Definition: FastAPI's background-tasks tutorial: tasks added with background_tasks.add_task(fn, *args) run after the response. The testing-websockets page: "You can use the same TestClient to test WebSockets. For this, you use the TestClient in a with statement, connecting to the WebSocket". The websocket_connect session has send_json, receive_json, send_text, receive_text and close.
tests/api/test_websocket.py (real)
1 with client.websocket_connect("/ws/rooms/1/availability") as ws:
2 ws.send_json({"check_in": d, "check_out": d+2}) -> {"room_id": 1, "available": true}
3 client.post("/bookings", ...) -> 201 (same client, same test transaction)
4 ws.send_json(same dates) -> {"room_id": 1, "available": false}Real scenario: confirmation emails, audit logs, cache invalidation after a write; a live availability or chat channel. Heavy or retried work belongs in a queue, which is tested as in Testing Messaging Systems.
| What | How in the snippet | Assertion |
|---|---|---|
| Task effect | app.state.outbox after client.post | Exact outbox entry |
| Task scheduling | mock.patch.object(main, "send_confirmation") | Called once with id and email |
| Task logic | Call send_confirmation(outbox, 1, "x") directly | Unit test (trivial here) |
| WebSocket happy path | websocket_connect + send_json/receive_json | Availability flips after a booking |
| WebSocket with auth | Headers or query on websocket_connect | Not in this app |
Fix / how to use it: keep task functions pure and parameterised (pass ids, not sessions); assert effects after TestClient returns; test WebSockets through the same client so they share the overridden session.
Snapshots and contracts: OpenAPI snapshot, contract test Important
In plain words: A snapshot test stores the app's OpenAPI document in a file and fails when it changes, so every API change shows up as a diff in code review. A contract test checks that both sides of an HTTP boundary agree on the message shapes.
Common misunderstanding: "Snapshot tests are just 'update and commit'." If updating is automatic, the test protects nothing. The snippet writes the snapshot only with UPDATE_SNAPSHOTS=1 (or when the file is missing, then skips with "snapshot written; review and commit it"), and the lab shows a real failure from tightening capacity from le=12 to le=10: - aximum": 12.0, / + aximum": 10.0,. The other misreading: "my respx mock is the contract". A mock can drift from the provider; the shared samples file plus a model check is the consumer half, and only a provider-side verification (Pact and similar) closes the loop.
Definition: app.openapi() builds the schema without a lifespan or a database, so the snapshot test needs no fixtures. Fowler's contract tests: "These check that all the calls against your test doubles return the same results as a call to the external service would." The consumer side here is ChargeResponse.model_validate(sample); renaming id to charge_id in a sample fails with id\n Field required (real).
snapshot workflow
1 pytest tests/contract -> fails on any schema change (diff in the message)
2 review: intended? breaking for clients? -> discuss in the PR
3 UPDATE_SNAPSHOTS=1 pytest tests/contract -> writes snapshots/openapi.json, skips
4 commit the new snapshot with the change -> reviewers see the JSON diffReal scenario: a refactor renames a response field; the snapshot fails in CI before the mobile app breaks. Schema-driven fuzzing (Schemathesis reads the OpenAPI document and generates requests) is a further step, not run here.
| Check | Catches | Snippet |
|---|---|---|
| OpenAPI snapshot | Any change to paths, models, constraints | test_openapi_matches_snapshot |
| Explicit schema assertions | Removal of a named field | test_breaking_change_is_caught |
| Consumer contract (samples + model) | Mocks drifting from what the client parses | test_payments_contract.py |
| Provider verification (Pact) | Provider changing the real API | not run |
| Schema-based fuzzing | Crashes on unexpected input | not run |
Fix / how to use it: snapshot the OpenAPI JSON with sorted keys; update only on purpose; feed mocks and contract tests from one samples file; ask providers for a sandbox or a published contract.
Coverage: coverage.py, pytest-cov, branch coverage Important
In plain words: Coverage reports which lines (and which branches of each if) ran during the tests. It cannot tell you the tests are good, but it shows clearly what was never executed.
Common misunderstanding: "98 % coverage means the code is tested." It means 98 % of lines ran. Before test_real_wiring.py existed, every API test overrode get_session, so the real get_session and get_engine never ran (real: app/db.py 79%, Missing 54, 59-64). The remaining report still shows app/main.py ... Missing 93: no test books an unknown room. Line coverage alone would also miss an if that is never false; branch coverage reports it as a partial branch.
Definition: coverage.py: "Where a line in your program could jump to more than one next line, coverage.py tracks which of those destinations are actually visited, and flags lines that haven't visited all of their possible destinations." pytest-cov runs coverage.py inside pytest (--cov, --cov-report=term-missing, --cov-branch) and handles subprocesses and xdist workers. The snippet sets branch = true, source = ["app"] and fail_under = 90 in [tool.coverage.*], and keeps the data file outside the repo with COVERAGE_FILE.
$ pytest -q --cov --cov-report=term-missing (real, runs/coverage.txt)
Name Stmts Miss Branch BrPart Cover Missing
app/db.py 38 0 10 3 94% 24->28, 26->28, 29->45
app/main.py 98 1 8 1 98% 93
app/payments.py 28 2 4 0 94% 45-46
TOTAL 298 3 40 4 98%
Required test coverage of 90.0% reached. Total coverage: 97.93%Real scenario: the partial branches in app/db.py are the non-SQLite and file-database paths, which only the PostgreSQL CI job would exercise; payments.py 45-46 is the non-timeout transport error branch. Both are honest gaps the report makes visible.
| Setting | Effect | Snippet |
|---|---|---|
branch = true | Report partial branches (24->28) | yes |
source = ["app"] | Measure only the app, not tests or libraries | yes |
fail_under = 90 | Fail the run below 90 % | yes |
show_missing = true | Line numbers in the terminal report | yes |
--cov-report=html | Browsable report | not committed |
COVERAGE_FILE | Where .coverage goes | scratch dir |
Fix / how to use it: turn on branch coverage; read the "Missing" column, not the total; add a test without overrides for the real wiring; set a floor that ratchets up, not a target that invites junk tests.
PostgreSQL in CI: testcontainers Good to know
In plain words: SQLite is a fast stand-in, but production runs PostgreSQL. In CI, start a real PostgreSQL in a throwaway Docker container for the test session and run the same rollback-per-test fixtures against it.
Common misunderstanding: "SQLite tests prove the PostgreSQL queries." They miss everything SQLite does differently: types and CHECK behaviour, ILIKE, JSONB, row locks (FOR UPDATE), exclusion constraints, transactional DDL rules, isolation levels. The other misreading is "testcontainers replaces the fixtures": it only provides the server; the transaction-per-test recipe is the same (and needs no BEGIN hook on psycopg).
Definition: testcontainers-python "facilitates the use of Docker containers for functional and integration testing". Its PostgresContainer(image='postgres:latest', port=5432, username=None, password=None, dbname=None, driver='psycopg2', **kwargs) starts a container and get_connection_url() returns a SQLAlchemy URL ("To get a URL without a driver, pass in driver=None"). The snippet's tests/postgres/test_postgres.py uses a session-scoped container and the same connection/savepoint fixtures; it is skipped here (testcontainers not installed) and expected, not run.
CI job "postgres" (expected, not run)
1 services: Docker available on the runner
2 pip install "testcontainers[postgres]" "psycopg[binary]"
3 pytest -m postgres
4 session start: PostgresContainer("postgres:17", driver="psycopg") -> container up, URL
5 create_all (or: alembic upgrade head) once; per test BEGIN ... SAVEPOINT ... ROLLBACK
6 session end: container removedReal scenario: a booking-overlap rule moved into a PostgreSQL exclusion constraint, a SELECT ... FOR UPDATE in the checkout, or JSONB filters: none of those can be tested on SQLite. The pipeline mechanics (service containers, caching, matrix jobs) are in CI/CD Pipelines.
| Database in tests | Speed | Fidelity | Where |
|---|---|---|---|
| SQLite in-memory + rollback | Fastest | Lowest | Every save, every PR |
| SQLite file | Fast | Low | Rarely |
| PostgreSQL via testcontainers | Seconds to start, then fast with rollback | High | CI job, -m postgres |
| PostgreSQL service container in CI | No start cost in the test | High | CI with services: |
| Shared staging database | Slow, shared | High but polluted | Avoid for automated tests |
Fix / how to use it: keep the fixtures database-agnostic; run the full suite on PostgreSQL in CI; run migrations (not create_all) in that job so schema drift is caught.
Test layers: unit vs integration vs e2e, and the test pyramid link Good to know
In plain words: Some tests check one function with everything around it faked (unit), some check the app with real routing and a real (test) database (integration), and a few check the deployed system end to end (e2e). Most tests should be the cheap kind; a few should be the real kind.
Common misunderstanding: "TestClient tests are end-to-end tests." They run in one process, with no server, no network and usually a fake provider. They are integration tests of the app. An e2e test starts Uvicorn (or the deployed service), a real database and a real or stub provider. This page does not re-teach the pyramid: Testing Strategy & TDD owns pyramid vs trophy and test doubles, and Testing & Benchmarking shows the Go side.
Definition: Fowler's summary of Cohn's pyramid: "Write lots of small and fast unit tests. Write some more coarse-grained tests and very few high-level tests that test your application from end to end." In this suite: 29 unit tests, 37 integration tests (30 API, 7 DB), 5 contract tests, 1 e2e-style PostgreSQL test (skipped here), and 600 opt-in speed tests.
where a booking rule is tested, cheapest first
1 unit quote(7, 10_000) == 63_000 (no app) tests/unit
2 unit BookingCreate(check_out <= check_in) -> ValidationError tests/unit
3 integration POST /bookings overlap -> 409 (TestClient, test DB) tests/api
4 contract provider sample still parses as ChargeResponse tests/contract
5 e2e Uvicorn + PostgreSQL + provider sandbox (few, slow) expected, not runReal scenario: the weekly discount boundary is tested 4 ways in a millisecond as a unit test; "a booking with a declined card saves nothing" needs the route, the database and the mocked provider, so it is an integration test.
| Layer | Fakes | Real | Count here | Typical time |
|---|---|---|---|---|
| Unit | Everything around one function | The function | 29 | well under 1 ms |
| Integration (API) | Network, clock, sometimes user | Routing, validation, dependencies, SQL | 30 | ~2-16 ms |
| Integration (DB) | — | SQLite transactions | 7 | ~1-5 ms |
| Contract | The other side | Message shapes | 5 | ~1 ms |
| E2E | Little or nothing | Server, DB, network | 1 (skipped) | seconds |
Fix / how to use it: test each rule at the lowest layer that can show it; keep integration tests for wiring and failure mapping; keep a handful of e2e tests for deploy-level confidence.
Mechanics
What happens inside one API test Important
test_booking_charges_and_sends_confirmation, from collection to teardown. Fixture setup follows the dependency graph (higher scopes first), the request crosses one thread boundary, and teardown runs in reverse.
pytest tests/api/test_bookings.py::test_booking_charges_and_sends_confirmation
1 collect: module imported with assert rewriting; conftest.py files of tests/ and tests/api/ loaded
2 setup engine (session, already built) -> connection: BEGIN -> db_session (create_savepoint)
3 setup payments_api (autouse): respx router started, route "charge" -> 201 sample
4 setup settings -> app = create_app(TEST_SETTINGS); overrides[get_session] -> yields db_session
5 setup client: with TestClient(app) -> portal thread, lifespan startup (httpx.Client, outbox)
6 setup room (RoomFactory flush), user (UserFactory flush), auth_headers -> real test token
7 act client.post("/bookings") -> portal -> Starlette -> FastAPI solves deps:
get_session (override) -> db_session; get_current_user -> verify token, session.get(User)
get_payments -> app.state.payments; body -> BookingCreate (model_validator)
8 def route in thread pool: overlap COUNT(*) -> quote() -> payments.charge -> httpx -> respx 201
9 session.add; commit() = RELEASE SAVEPOINT; refresh() = new SAVEPOINT; background task queued
10 response 201 sent; background task appends to app.state.outbox; TestClient returns
11 assert body, respx call (JSON, Idempotency-Key), outbox entry
12 teardown (reverse): client -> lifespan shutdown; app -> overrides.clear(); respx stop (assert_all_called=False)
13 teardown db_session.close() -> ROLLBACK TO SAVEPOINT; connection -> ROLLBACK; closeThe test schema and the SQL of one test Good to know
The schema the engine fixture creates once per run, and the statements one API test produces under the rollback recipe, taken from SQLAlchemy's echo (real, runs/sql-trace.txt). Edited for reading: PRAGMA checks and the separate parameter lines dropped, the parameters written inline, semicolons and comments added. The statements and their order are as logged:
-- once per run: SQLModel.metadata.create_all(engine)
CREATE TABLE user (
id INTEGER NOT NULL,
email VARCHAR(254) NOT NULL,
is_admin BOOLEAN NOT NULL,
PRIMARY KEY (id)
);
CREATE UNIQUE INDEX ix_user_email ON user (email);
CREATE TABLE room (
name VARCHAR(60) NOT NULL,
capacity INTEGER NOT NULL,
price_per_night INTEGER NOT NULL,
id INTEGER NOT NULL,
PRIMARY KEY (id),
UNIQUE (name)
);
CREATE TABLE booking (
check_in DATE NOT NULL,
check_out DATE NOT NULL,
id INTEGER NOT NULL,
room_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
total_cents INTEGER NOT NULL,
payment_id VARCHAR NOT NULL,
created_at DATETIME NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY(room_id) REFERENCES room (id),
FOREIGN KEY(user_id) REFERENCES user (id)
);
CREATE INDEX ix_booking_user_id ON booking (user_id);
CREATE INDEX ix_booking_room_id ON booking (room_id);
COMMIT;
-- one test: fixture BEGIN, factory flush, POST /rooms, fixture ROLLBACK
BEGIN; -- connection fixture (SQLAlchemy's begin hook)
SAVEPOINT sa_savepoint_1; -- first statement of db_session
INSERT INTO user (email, is_admin) VALUES ('admin@example.com', 1);
INSERT INTO room (name, capacity, price_per_night) VALUES ('Garden', 2, 12000);
RELEASE SAVEPOINT sa_savepoint_1; -- the route's session.commit()
SAVEPOINT sa_savepoint_2; -- session.refresh(room)
SELECT room.name, room.capacity, room.price_per_night, room.id
FROM room
WHERE room.id = 1;
ROLLBACK TO SAVEPOINT sa_savepoint_2; -- db_session.close()
ROLLBACK; -- connection fixture teardownTwo details from the trace. The auth dependency's session.get(User, id) emitted no SQL, because the admin row was already in the session's identity map from the fixture; in production that lookup is a SELECT. And the overlap query the booking tests assert on is SELECT count(*) FROM booking WHERE booking.room_id = ? AND booking.check_in < ? AND booking.check_out > ? (overlapping_bookings in app/main.py): test_overlap_is_409 proves the half-open interval (a stay may start on the day another ends).
Exact errors, warnings and outputs Must-know
Every line below was printed by the snippet run (FastAPI 0.128.8, Starlette 0.49.3, Pydantic 2.13.5, SQLAlchemy 2.0.58, pytest 8.4.2, respx 0.23.1).
| Trigger | Status / outcome | Exact output |
|---|---|---|
No Authorization header | 401 | {"detail":"Not authenticated"}, www-authenticate: Bearer |
| Bad signature / other secret | 401 | {"detail":"Invalid token"} |
| Clock moved past expiry | 401 | {"detail":"Token expired"} |
| Guest on an admin route | 403 | {"detail":"Admins only"} |
?limit=0 | 422 | {"type":"greater_than_equal","loc":["query","limit"],"msg":"Input should be greater than or equal to 1","input":"0","ctx":{"ge":1}} |
check_out before check_in | 422 | "msg":"Value error, check_out must be after check_in", "loc":["body"] |
Frozen clock after check_in | 422 | {"detail":"check_in is in the past"} |
| Duplicate room name | 409 | {"detail":"Room name already exists"} |
| Overlapping stay | 409 | {"detail":"Room already booked for these dates"} |
| Provider answers 402 | 402 | {"detail":"Payment declined: insufficient funds"} |
Provider timeout (side_effect) | 503 | {"detail":"Payment provider unavailable, try again"} |
| Unmatched respx request | exception | respx.models.AllMockedAssertionError: RESPX: <Request('GET', 'https://payments.example.test/v1/refunds')> not mocked! |
| respx route never called | teardown failure | AssertionError: RESPX: some routes were not called! |
No with / ASGITransport without LifespanManager | exception | AttributeError: 'State' object has no attribute 'payments' |
async def test without a marker (strict) | failed | async def functions are not natively supported. |
| Missing testcontainers | skipped | SKIPPED [1] tests/postgres/test_postgres.py:19: testcontainers not installed |
| Engine without the BEGIN hook | 18 errors, 1 failed | sqlite3.IntegrityError: UNIQUE constraint failed: user.email |
| Snapshot after a schema change | failed | AssertionError: public API changed: review the diff, then UPDATE_SNAPSHOTS=1 |
| Before suite, real provider | failed after 2.31 s | assert 503 == 201 / where 503 = <Response [503 Service Unavailable]>.status_code |
| Before suite, one test alone | failed | AssertionError: assert 0 == 1 |
Solving the classic problems
| Bug | Symptom | Fix | Cost |
|---|---|---|---|
| Shared database between tests | Order-dependent passes and failures | Transaction per test (or recreate) | Three fixtures |
| SAVEPOINT on the legacy sqlite3 driver | Rows leak despite the rollback | BEGIN hook in the engine factory | 8 lines |
| Override not cleared | A later test sees a fake user | Fresh app per test; overrides.clear() in teardown | Fixture |
TestClient without with | AttributeError on app.state | with TestClient(app) in the fixture | One line |
ASGITransport and a lifespan | Same AttributeError | LifespanManager(app) | Fixture |
| Real HTTP in tests | Slow, flaky, 503 (2.31 s in the Before suite) | autouse respx fixture; strict mocks | Fixture |
| Mock drifts from the provider | Tests pass, production fails | Shared samples + contract test | One file |
| Hard-coded dates | Time bombs | freeze_time / time_machine.travel; relative dates | Small |
| Retrying flaky tests | Hidden races | Quarantine, find the cause | Discipline |
| Only overridden wiring is tested | Real get_session never runs (coverage 79 % for db.py) | One no-override smoke test | One test |
assert status_code == 422 only | Passes for any typo | Assert (loc, type) pairs | Small |
| Unseeded factories | Irreproducible failures | Seed Faker and polyfactory | One line each |
| Snapshot auto-updates | Protects nothing | Update only with UPDATE_SNAPSHOTS=1 | None |
Isolation that is proved, not assumed
The pair test_1_route_commits_inside_the_test / test_2_the_commit_did_not_survive_the_test costs two tests and turns "we roll back after each test" from a belief into a check. The negative control in test_savepoint_trap.py pins the driver behaviour that would otherwise break it silently. Lab step 4 shows the failure mode: 18 errors and 1 failure, every one of them in a test that did nothing wrong.
Offline by construction
An autouse respx fixture in tests/api/conftest.py means a new API test cannot reach the network even if its author forgets: any unmatched request raises. The provider's responses live in payments_samples.json, which the contract test also reads, so changing a mock means changing the contract file under review.
One seam per concern
Every external concern has exactly one seam: the session (get_session), the user (get_current_user), the payment client (get_payments, or respx at the transport), the clock (freezegun/time-machine at the time/datetime level), settings (create_app(settings) or monkeypatch plus cache_clear). A test that needs to change two of them changes two lines, and a reader sees exactly what is fake.
Fast default, complete in CI
addopts keeps the default run to the 71 tests that finish in 0.63-0.70 s here. Speed comparisons and PostgreSQL run only with -m, so CI can run pytest, pytest -m postgres and a coverage job as separate steps.
Choosing
| Situation | Use | Extra technique | Reason |
|---|---|---|---|
| Test a pure rule | Plain function test + parametrize | ids per row | Fastest, clearest failure |
| Test a route | TestClient in a fixture | Fresh app per test | Real routing and validation |
Test must await | AsyncClient + ASGITransport | LifespanManager, anyio marker | TestClient cannot be used inside async def |
| Database for most tests | Transaction per test, savepoints | BEGIN hook on SQLite | ~2 ms per test |
| Code that needs real commits | Schema recreate (module override) | create_all per test | No savepoint semantics |
| PostgreSQL-specific SQL | testcontainers job | Same fixtures, -m postgres | Fidelity |
| Replace an app collaborator | app.dependency_overrides | Key by the exact object | No patching of imports |
| Replace outbound HTTP but keep the client code | respx or pytest-httpx | Strict defaults | Tests the client too |
| Replace env/settings | create_app(settings) or monkeypatch.setenv | cache_clear() | Restored automatically |
| Replace the clock | time-machine (or freezegun) | tick=False, shift | No sleeps |
| Build rows | factory_boy bound to the test session | flush persistence | Inside the test transaction |
| Build payloads | polyfactory | Use, PostGenerated, seed | Valid by construction |
| Guard the public API | OpenAPI snapshot | Explicit update switch | Reviewable diffs |
| Find untested code | coverage.py + pytest-cov, branch | fail_under floor | Shows wiring gaps |
respx vs pytest-httpx vs dependency override
| Question | respx | pytest-httpx | dependency_overrides[get_payments] |
|---|---|---|---|
| Runs the real client code | Yes | Yes | No |
| Default for unmatched requests | Raise (assert_all_mocked=True) | Fail the test | n/a |
| Default for unused routes | Fail at exit (assert_all_called=True) | Fail at teardown | n/a |
| Route patterns | Method, host, path, params, JSON, regex, combinators | URL, method, headers, content, JSON | n/a |
| Request history | route.calls, .last.request | httpx_mock.get_request() | Mock's call_args |
| Python support of the newest release | 3.8+ (0.23.1) | 3.10+ (0.36.2) | n/a |
| Best for | Shared autouse mocks, rich matching | Simple strict tests | Testing the route's error mapping only |
In architecture: from a single process to a distributed system
Monolith: one process, one database
One FastAPI app, one tests/ tree with the layering of this chapter: unit tests for rules, API tests through TestClient with the transaction-per-test database, one autouse network block, one OpenAPI snapshot. A typical shop backend tests checkout this way: the cart, prices and discounts as unit tests; POST /orders through TestClient with the payment provider mocked by respx and the stock check on the test database; the order-confirmation email as a background task asserted from the outbox. The whole suite runs in seconds on every commit, and a nightly PostgreSQL job adds fidelity.
Modular monolith and multiple databases
Each module (catalog, orders, billing) gets its own tests/<module>/conftest.py with its own fixtures, on top of a shared root conftest.py for the app and the database. Tests of one module override the other modules' public dependencies (the orders tests get a fake BillingService), which enforces the module boundary in tests just as imports enforce it in code. With two databases, the root conftest has two engines and two connection fixtures, and each session dependency is overridden to its own test session. Each is rolled back independently, since there is no distributed transaction across the two.
Microservices
Inside each service, everything above applies. Between services, the "external API" is another team's service, so the mocks must stay honest: consumer tests record their expectations (respx samples or Pact contracts), the provider verifies them in its own CI, and the contract test is where the two meet. A service's suite never calls a real neighbour. A small set of end-to-end tests against a deployed environment checks the wiring (auth between services, network policies) and nothing else. Message-driven interactions (outbox, queues, consumers) are tested as in Testing Messaging Systems.
Distributed data: replicas, caches, sharded databases, multi-region
Read replicas and caches add behaviour a single-database test cannot see: replication lag, stale cache entries, a write to one shard and a read from another. Unit-test the routing decision (which engine for which tenant or shard) with plain functions. Test the "read your own writes" rule with a fake replica session that deliberately returns stale data. Test cache invalidation by asserting on a fake cache's calls after a write. Real Redis, PostgreSQL replicas or multi-region behaviour belong in a few testcontainers or staging tests, not in the default run. Isolation-level effects (lost updates, write skew) need a real database and two concurrent connections, which the rollback-per-test fixture cannot provide; write those tests on a dedicated PostgreSQL with real commits, as described in Isolation Levels.
Scaling path: 1×, 10×, 100×
| Suite size | What hurts | Practice |
|---|---|---|
| 1× (hundreds of tests) | Nothing yet | Rollback per test, TestClient, autouse network block, snapshot, coverage floor |
| 10× (thousands, several teams) | Wall time, flaky tests, fixture sprawl | pytest-xdist with one database (or schema) per worker; directory-level conftests; quarantine flaky tests; --durations in CI |
| 100× (many services) | Cross-service drift, slow e2e | Consumer contracts verified by providers; e2e only for critical paths; per-service suites in parallel CI jobs; template databases or container reuse for PostgreSQL |
Lab
All commands run from docs/snippets/python/testing-fastapi-pytest/. Outputs marked "real" were produced on CPython 3.9.6 (macOS) with the pins in pyproject.toml, in a venv outside the repository, with PYTHONDONTWRITEBYTECODE=1 and COVERAGE_FILE pointing outside the repository. Python 3.12 with current releases was not run: expect different version numbers in the headers, and on pytest 9 the configuration may move to [tool.pytest].
1. Install and run the suite (real)
python3 -m venv ~/venvs/tfp # keep venvs, .coverage and caches out of the repo
~/venvs/tfp/bin/pip install --upgrade pip
~/venvs/tfp/bin/pip install '.[test]' # uv venv + uv pip install '.[test]' should work too (not exercised here)
PYTHONDONTWRITEBYTECODE=1 ~/venvs/tfp/bin/python -m pytest
# platform darwin -- Python 3.9.6, pytest-8.4.2, pluggy-1.6.0
# configfile: pyproject.toml
# plugins: anyio-4.12.1, time-machine-2.19.0, asyncio-1.2.0, cov-7.1.0, httpx-0.35.0, Faker-37.12.0, respx-0.23.1
# asyncio: mode=strict, debug=False, asyncio_default_fixture_loop_scope=function, asyncio_default_test_loop_scope=function
# collected 671 items / 600 deselected / 1 skipped / 71 selected
# tests/api/test_async_client.py .... [ 5%]
# tests/api/test_bookings.py ........ [ 23%]
# tests/db/test_isolation.py ... [ 53%]
# tests/unit/test_security.py ......... [ 95%]
# SKIPPED [1] tests/postgres/test_postgres.py:19: testcontainers not installed
# ================ 71 passed, 1 skipped, 600 deselected in 0.70s =================A second fresh venv installed from the same pyproject.toml produced the same pip freeze as the first (requirements.lock).
2. Coverage and the slowest tests (real)
COVERAGE_FILE=/tmp/tfp.coverage python -m pytest -q --cov --cov-report=term-missing
# app/db.py 38 0 10 3 94% 24->28, 26->28, 29->45
# app/main.py 98 1 8 1 98% 93
# TOTAL 298 3 40 4 98%
# Required test coverage of 90.0% reached. Total coverage: 97.93%
python -m pytest -q --durations=5
# 0.03s setup tests/api/test_bookings.py::test_past_check_in_is_rejected <- freezegun
# 0.02s call tests/api/test_bookings.py::test_past_check_in_is_rejectedDelete tests/api/test_real_wiring.py in a scratch copy and app/db.py drops to 79 % with lines 54 and 59-64 missing: the real get_engine and get_session (real, runs/coverage-without-real-wiring.txt).
3. Run the Before suite (real)
python -m pytest before/ # 1 failed, 2 passed in 2.31s (assert 503 == 201)
python -m pytest before/test_before.py::test_list_rooms # 1 failed: AssertionError: assert 0 == 14. Break isolation on purpose (real)
In a scratch copy, change the engine fixture to make_engine("sqlite://", sqlalchemy_begin=False):
python -m pytest -q
# ERROR tests/api/test_rooms.py::test_non_admin_gets_403 - sqlalchemy.exc.Integ...
# ERROR tests/db/test_isolation.py::test_1_route_commits_inside_the_test - sqla...
# FAILED tests/db/test_isolation.py::test_2_the_commit_did_not_survive_the_test
# 1 failed, 52 passed, 1 skipped, 600 deselected, 18 errors in 3.85sThe probe behind it (runs/savepoint-probe.py) prints rooms after outer ROLLBACK: 0 with the hook and 1 without.
5. Break the OpenAPI snapshot (real)
In a scratch copy, change capacity: int = Field(ge=1, le=12) to le=10 in app/models.py:
python -m pytest tests/contract -q
# E AssertionError: public API changed: review the diff, then UPDATE_SNAPSHOTS=1
# E - aximum": 12.0,
# E + aximum": 10.0,
# 1 failed, 4 passed in 0.05s
UPDATE_SNAPSHOTS=1 python -m pytest tests/contract -q # writes the new snapshot and skips; commit it6. Measure the database strategies (real)
for s in rollback recreate-memory recreate-file; do python -m pytest -m speed -k "test_db_only and $s" -q | tail -1; done
# 100 passed, 1 skipped, 571 deselected in 0.21s
# 100 passed, 1 skipped, 571 deselected in 0.38s
# 100 passed, 1 skipped, 571 deselected in 0.45sThree runs of every combination are in runs/speed.txt. Repeat with your own schema before you choose; the gap here is three small tables on in-memory SQLite.
7. Async plugins and modes (real)
python -m pytest tests/api/test_async_client.py -v -o asyncio_mode=auto # 4 passed
# scratch copy, @pytest.mark.asyncio removed, strict mode:
# async def functions are not natively supported.
# FAILED tests/api/test_async_client.py::test_health_with_pytest_asyncio8. PostgreSQL with testcontainers (expected, not run)
pip install "testcontainers[postgres]" "psycopg[binary]" # needs Docker running
python -m pytest -m postgres -v
# expected: tests/postgres/test_postgres.py::test_insert_is_rolled_back PASSED
# (container started once per session; BEGIN / SAVEPOINT / ROLLBACK per test)For PHP/Laravel developers
Laravel's testing toolkit maps onto this chapter almost one to one, with one difference in shape: Laravel's helpers live on the test case ($this->...) or on facades (Http::fake()), while pytest builds everything from fixtures you request by name. RefreshDatabase is the transaction-per-test strategy: the docs say it "does not migrate your database if your schema is up to date. Instead, it will only execute the test within a database transaction", and that DatabaseMigrations and DatabaseTruncation are "significantly slower than the RefreshDatabase trait", the same trade-off as schema recreate vs rollback. actingAs($user) is the "fake current user": "the actingAs helper method provides a simple way to authenticate a given user as the current user". Http::fake([...]) with Http::response(...) is respx, and Http::preventStrayRequests() is respx's assert_all_mocked: "any requests that do not have a corresponding fake response will throw an exception rather than making the actual HTTP request". $this->travel(5)->minutes(), travelTo and freezeTime are time-machine. Model factories are factory_boy. postJson(...)->assertUnprocessable()->assertJsonValidationErrors([...]) is the 422 test. Pest's test('...', function () { expect($x)->toBe(3); }) reads like a pytest function with plain asserts, and pest()->use(RefreshDatabase::class) applies a trait to a directory the way a conftest.py applies fixtures to one.
<?php
// tests/Feature/BookingTest.php (Pest on Laravel 13): the snippet's booking tests in Laravel terms
use App\Models\Room;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
pest()->use(RefreshDatabase::class); // transaction per test (like the db_session fixture)
beforeEach(function () {
Http::preventStrayRequests(); // like respx assert_all_mocked: no real network
Http::fake([
'payments.example.test/v1/charges' => Http::response(['id' => 'ch_test_123', 'status' => 'succeeded'], 201),
]);
});
test('a guest books a room and the provider is charged', function () {
$user = User::factory()->create(); // factory_boy UserFactory
$room = Room::factory()->create(['price_per_night' => 12000]);
$this->actingAs($user) // dependency_overrides[get_current_user]
->postJson('/api/bookings', ['room_id' => $room->id, 'check_in' => now()->addDays(10)->toDateString(),
'check_out' => now()->addDays(13)->toDateString()])
->assertCreated()
->assertJsonPath('total_cents', 36000);
Http::assertSent(fn ($request) => $request->hasHeader('Idempotency-Key')); // route.calls.last.request
$this->assertDatabaseCount('bookings', 1);
});
test('a booking in the past is rejected', function () {
$this->travelTo(now()->setDate(2026, 12, 24)); // freeze_time("2026-12-24")
$this->actingAs(User::factory()->create())
->postJson('/api/bookings', ['room_id' => 1, 'check_in' => '2026-12-23', 'check_out' => '2026-12-26'])
->assertUnprocessable();
});| Laravel / Pest | FastAPI / pytest |
|---|---|
RefreshDatabase | Transaction per test: connection + db_session (create_savepoint) |
DatabaseMigrations, DatabaseTruncation | Schema recreate per test, truncation |
actingAs($user) | app.dependency_overrides[get_current_user], or a real test token |
Http::fake([...]), Http::response(...) | respx routes, pytest-httpx add_response |
Http::preventStrayRequests() | respx assert_all_mocked=True (default) |
Http::assertSent(...) | route.calls.last.request assertions |
$this->travel(...), travelTo, freezeTime | time-machine travel(...).shift(...), freezegun |
Model factories, User::factory()->create() | factory_boy SQLAlchemyModelFactory |
postJson()->assertJsonValidationErrors([...]) | Assert the 422 (loc, type) pairs |
$this->mock(Service::class) | create_autospec + dependency_overrides |
Feature tests (tests/Feature) | tests/api with TestClient |
Unit tests (tests/Unit) | tests/unit |
phpunit.xml / Pest.php | pyproject.toml [tool.pytest.ini_options], conftest.py |
php artisan test --coverage | pytest --cov --cov-branch |
Pest datasets (->with([...])) | @pytest.mark.parametrize |
The Go angle
Go's standard library covers the same ground without a framework. net/http/httptest has two tools: httptest.NewRecorder(), a ResponseRecorder ("an implementation of [http.ResponseWriter] that records its mutations for later inspection in tests"), which is the in-process TestClient equivalent for a single handler, and httptest.NewServer, "an HTTP server for use in end-to-end HTTP tests" listening on a real loopback port, which Go tests also use to fake an external API (where Python uses respx). Table-driven tests are the idiomatic form of parametrize: a slice of cases and a t.Run(tc.name, ...) subtest per case. testify adds assert (continue on failure), require (stop on failure; its README: "These functions must be called from the goroutine running the test", so not inside a fake server's handler) and mock. Dependency injection is constructor arguments, so "override a dependency" means passing a fake that implements the interface. The full treatment is in Testing & Benchmarking and Mocking with Interfaces, Dependency Injection for Testability.
// Go: the booking handler tested with httptest, a table-driven test and testify
func TestCreateBooking(t *testing.T) {
payments := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "/v1/charges", r.URL.Path) // fake external API (respx's job); not require: other goroutine
w.WriteHeader(http.StatusCreated)
_, _ = w.Write([]byte(`{"id":"ch_test_123","status":"succeeded","amount_cents":36000}`))
}))
defer payments.Close()
tests := []struct { // table-driven: the parametrize table
name string
body string
wantCode int
}{
{"valid stay", `{"room_id":1,"check_in":"2030-01-10","check_out":"2030-01-13"}`, http.StatusCreated},
{"check_out before check_in", `{"room_id":1,"check_in":"2030-01-10","check_out":"2030-01-09"}`, http.StatusUnprocessableEntity},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
tx := beginTestTx(t) // BEGIN; t.Cleanup(ROLLBACK): the db_session fixture
h := NewBookingHandler(NewStore(tx), NewPaymentsClient(payments.URL), fakeUser{ID: 1})
req := httptest.NewRequest(http.MethodPost, "/bookings", strings.NewReader(tc.body))
rec := httptest.NewRecorder() // in-process, like TestClient
h.ServeHTTP(rec, req)
assert.Equal(t, tc.wantCode, rec.Code)
})
}
}| Concern | FastAPI / pytest | Go |
|---|---|---|
| In-process request | TestClient, ASGITransport | httptest.NewRecorder + handler.ServeHTTP |
| Fake external API | respx, pytest-httpx | httptest.NewServer with a handler |
| Case tables | @pytest.mark.parametrize | Table-driven tests + t.Run subtests |
| Setup/cleanup | Fixtures with yield | Helpers + t.Cleanup |
| Shared setup per package | conftest.py | TestMain, helper files |
| Assertions | Plain assert (rewritten) | if got != want { t.Errorf }, testify assert/require |
| Replace a collaborator | app.dependency_overrides | Pass a fake implementing the interface |
| Mocks | unittest.mock, autospec | testify mock, hand-written fakes |
| Coverage | coverage.py + pytest-cov | go test -cover, -coverprofile |
| Time | freezegun, time-machine | Inject a clock interface |
Common misconceptions
| Belief | Reality |
|---|---|
TestClient(app) runs startup | Only inside with TestClient(app); otherwise app.state is empty (real AttributeError) |
ASGITransport runs the lifespan | It never sends lifespan events; use LifespanManager |
TestClient tests are end-to-end tests | They are in-process integration tests: no server, no network |
| Rollback per test always isolates | Not on the legacy sqlite3 driver without the BEGIN hook (real: 1 leaked row, 18 errors) |
The app's commit() defeats the test transaction | With create_savepoint it is a RELEASE SAVEPOINT |
The app's rollback() wipes the test's rows | It rolls back to the current savepoint only |
sqlite:// is one database per engine | One per connection, unless StaticPool |
StaticPool makes SQLite concurrent | It serialises everything on one connection; tests only |
| Schema recreate is always much slower | Here about 2 ms (DB only) to 4 ms (API) per test; the gap depends on schema and database |
respx also intercepts TestClient | It patches httpcore transports; TestClient uses its own |
| An unmatched mocked request goes to the network | respx raises by default, pytest-httpx fails the test |
mock.patch replaces a function everywhere | It replaces a name where it is looked up |
A bare Mock() is a safe stand-in | It accepts any attribute; use create_autospec |
| Retrying flaky tests fixes them | It hides races and time bombs |
assert status_code == 422 is a validation test | Assert the (loc, type) pairs |
[tool.pytest.ini_options] values are typed TOML | INI compatibility mode: strings; [tool.pytest] (pytest 9) is native |
| High coverage means well tested | It means lines ran; overrides can hide untested wiring |
async def tests just work | They need anyio or pytest-asyncio and a marker in strict mode |
Cheat sheet
| Topic | Remember |
|---|---|
| Discovery | test_*.py, test_ functions, Test classes; testpaths |
| Asserts | Plain assert; rewritten in test modules and conftest.py only |
| Config | pyproject.toml [tool.pytest.ini_options] (pytest 6+); [tool.pytest] native (9+) |
| Safety flags | --strict-markers, filterwarnings = ["error"], -ra |
| Fixtures | Request by name; yield for teardown; widen scope only for immutable things |
| Layering | Closest definition wins: module > directory conftest.py > parent > plugin |
| Parametrize | pytest.param(..., id=...); @pytest.fixture(params=...) for infrastructure |
| TestClient | with TestClient(app) as c: runs the lifespan; background tasks done on return |
| Async | AsyncClient(transport=ASGITransport(app=app)) + LifespanManager; @pytest.mark.anyio |
| Overrides | app.dependency_overrides[get_session] = gen; fresh app per test; clear |
| SQLite | sqlite:// + StaticPool + check_same_thread=False + BEGIN hook + FK pragma |
| Rollback recipe | conn.begin() -> Session(bind=conn, join_transaction_mode="create_savepoint") -> rollback() |
| Prove isolation | A test that commits, then a test that counts 0 rows |
| 422 | Assert (loc, type) pairs; dependencies (401) win over body errors |
| Auth | Real test token for auth rules; override get_current_user elsewhere |
| HTTP mocks | Autouse respx with strict defaults; shared samples file |
| Time | time_machine.travel(..., tick=False) + shift; freeze_time |
| Coverage | branch = true, fail_under, read "Missing"; one no-override test |
| CI | Default run fast; -m postgres with testcontainers; snapshot updates by hand |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What does with TestClient(app) as client: do that client = TestClient(app) does not, and how do you see the difference in a test? Must-know
Answer
Answer: The with block starts an anyio portal and runs the app's lifespan: startup on entry, shutdown on exit. Without it, no lifespan runs, so anything the lifespan puts on app.state is missing. In the snippet, GET /health still works, but POST /bookings raises AttributeError: 'State' object has no attribute 'payments' (real). test_with_block_runs_startup_and_shutdown sees app.state.outbox == [] inside the block and http.is_closed after it. See TestClient and the lifespan.
2 — How does the transaction-per-test fixture survive the route calling session.commit()? Must-know
Answer
Answer: The connection fixture opens an outer transaction (BEGIN), and db_session is bound to that connection with join_transaction_mode="create_savepoint". The session then implements its own begin, commit and rollback with savepoints: commit() becomes RELEASE SAVEPOINT, rollback() becomes ROLLBACK TO SAVEPOINT, and the outer transaction stays open until the fixture's ROLLBACK. The real trace shows no COMMIT during the test. See Transaction rollback per test.
3 — Why does the snippet's engine set isolation_level = None and emit its own BEGIN, and what happens without it? Must-know
Answer
Answer: The sqlite3 driver's legacy transaction control does not emit BEGIN before a SAVEPOINT, so the savepoint starts its own transaction and RELEASE SAVEPOINT commits it; the outer ROLLBACK has nothing to undo. SQLAlchemy's documented fix is to switch the driver's BEGIN off (isolation_level = None on connect) and emit BEGIN from the begin event. Without it the real probe leaves 1 row after the rollback, and the full suite gets 18 errors and 1 failure from leaked users. On Python 3.12+ connect_args={"autocommit": False} is the alternative. See The sqlite3 driver trap.
4 — How do you test a route that needs a logged-in user, and when do you override get_current_user instead? Must-know
Answer
Answer: For the auth rules themselves (missing token 401, bad signature, expiry, 403 for non-admins), send a real test token minted with the test settings' secret (auth_headers(user)), so the whole dependency chain runs. For routes where auth is not the subject, app.dependency_overrides[get_current_user] = lambda: User(...) gives a fake current user without a header (real: 200 with id 42). Keep at least the rule tests on real tokens, or nothing proves a missing token is rejected. See Testing auth-protected routes.
5 — Your booking route calls a payment API with httpx. How do you test success, decline and timeout without the network, and what proves no test reaches it? Must-know
Answer
Answer: Mock the transport with respx (or pytest-httpx): a route for POST /v1/charges that returns the success sample, .respond(402, json=...) for a decline, and side_effect=httpx.ReadTimeout(...) for a timeout. The real client code still runs, so you can assert on the JSON and the Idempotency-Key header it sent. An autouse fixture in tests/api/conftest.py applies the mock to every API test, and respx's default assert_all_mocked=True raises for any unmatched request (real AllMockedAssertionError). See Mocking an external API.
6 — Rollback per test or schema recreate per test: what did you measure, and when would you pick recreate? Important
Answer
Answer: With the same bodies, 100 tests each, three runs: DB-only 0.21 s with rollback vs 0.38-0.41 s (in-memory recreate) and 0.43-0.45 s (file recreate); through the API 1.59-1.67 s vs about 2.0 s. That is a small gap for three tables on SQLite, and it grows with schema size and on PostgreSQL. Pick recreate (or truncation) for tests whose code needs real commits, such as two sessions or connections, AUTOCOMMIT DDL, or concurrency, and keep rollback as the default. See Schema recreate vs rollback.
7 — When must you use httpx.AsyncClient with ASGITransport instead of TestClient, and what extra step does the lifespan need? Important
Answer
Answer: When the test itself is async def because it awaits other async code. FastAPI's docs: the TestClient's magic "doesn't work anymore when we're using it inside asynchronous functions". ASGITransport sends no lifespan events, so wrap the app in asgi_lifespan.LifespanManager(app) and pass manager.app to the transport. The test needs @pytest.mark.anyio (anyio plugin) or @pytest.mark.asyncio (pytest-asyncio in strict mode); without a marker pytest reports "async def functions are not natively supported." See Async tests.
8 — How do conftest.py files combine, and how does the snippet run the same API tests under three database strategies? Important
Answer
Answer: pytest loads every conftest.py from the rootdir down to the test's directory and resolves each fixture name to the closest definition: the test module, then the nearest conftest.py, then parents, then plugins. tests/speed/conftest.py defines a db_session with params=["rollback", "recreate-memory", "recreate-file"]; app and client from the root conftest request db_session by name, so they pick up the overriding one and every speed test runs three times. tests/db/test_schema_recreate.py does the same at module level. See conftest.py layering.
9 — A test fails only when run after another test. List the usual causes in a FastAPI suite and the fix for each. Important
Answer
Answer: Shared database rows (fix: rollback per test, factories); an override left on a shared app (fix: fresh app per test, overrides.clear()); a cached settings object or other lru_cache (fix: cache_clear() in an autouse fixture); module-scoped fixtures with mutable state (fix: function scope); a real clock or unseeded randomness (fix: time-machine, seeds); a leaked savepoint on the sqlite3 driver (fix: the BEGIN hook). Retrying the test hides all of them. See Time and flaky tests.
10 — Why assert on the (loc, type) pairs of a 422, and why did POST /rooms with no token and an invalid body return 401? Important
Answer
Answer: A bare status_code == 422 passes for any malformed payload, including a typo in the test itself; loc and type pin which field failed and why, and they are what clients use to show errors. The 401 comes first because FastAPI solves dependencies before it reports body errors, and get_current_user (via OAuth2PasswordBearer) raised HTTPException(401) during that solve. The real test test_auth_runs_before_body_validation pins it. See Testing routes and validation errors.
11 — What does an OpenAPI snapshot test protect, and what makes it useless? Good to know
Answer
Answer: It turns every change in paths, models and constraints into a reviewable diff in the PR. The lab's le=12 to le=10 change failed with - aximum": 12.0 / + aximum": 10.0. It becomes useless when updating is automatic. The snippet writes the snapshot only with UPDATE_SNAPSHOTS=1 (or when it is missing), and reviewers see the JSON diff. A provider contract (shared samples plus a model check, or Pact) covers the other direction: mocks drifting from a real API. See Snapshots and contracts.
12 — How do Laravel's RefreshDatabase, actingAs and Http::fake and Go's httptest map to this chapter? Good to know
Answer
Answer: RefreshDatabase runs each test inside a database transaction when the schema is current, like the connection/db_session fixtures. actingAs($user) is overriding get_current_user. Http::fake plus Http::preventStrayRequests() is respx with assert_all_mocked. In Go, httptest.NewRecorder plus ServeHTTP is the in-process TestClient, httptest.NewServer fakes the external API, table-driven tests with t.Run are parametrize, and testify's assert/require add helpers to plain comparisons. See For PHP/Laravel developers and The Go angle.
Glossary
| Term | Meaning |
|---|---|
| pytest | Python test runner: discovery, fixtures, plain asserts, plugins |
| Test discovery | Collecting test_*.py files, test_ functions and Test classes from testpaths |
| Assert rewriting | pytest's import hook that rewrites assert in test modules to report values |
| Arrange act assert | The three (plus cleanup) steps of a test |
| Fixture | A function providing a value and optional teardown to tests that name it |
| Fixture scope | Lifetime of a fixture value: function, class, module, package, session |
| Yield fixture | Fixture whose code after yield is teardown |
| Autouse | A fixture applied to every test in its scope without being requested |
conftest.py | File of fixtures and hooks for its directory and below |
| Fixture override | Redefining a fixture name closer to the test (module or directory) |
| Parametrize | Generating one test per set of arguments |
| Marker | A label on a test (slow, skip, xfail, anyio) used for selection or behaviour |
--strict-markers | Makes unregistered markers an error |
pytest.ini / [tool.pytest.ini_options] | INI-style pytest configuration; the TOML table is INI compatibility mode |
[tool.pytest] | pytest 9's native TOML configuration table |
| rootdir | Directory pytest anchors node ids and config to |
TestClient | Starlette/FastAPI client that calls the ASGI app in-process |
httpx.AsyncClient | httpx's async client |
ASGITransport | httpx transport that sends requests to an ASGI app directly |
LifespanManager | asgi-lifespan helper that sends startup/shutdown to an ASGI app |
| anyio plugin | pytest plugin shipped with anyio; runs @pytest.mark.anyio tests |
| pytest-asyncio | pytest plugin that runs asyncio tests; asyncio_mode strict or auto |
asyncio_mode | pytest-asyncio setting: strict (marker required) or auto (all async tests) |
| Lifespan in tests | Running the app's startup/shutdown around tests that need app.state |
app.dependency_overrides | FastAPI dict mapping an original dependency to its test replacement |
Override get_session | Replacing the session dependency with one bound to the test transaction |
| Fake current user | Overriding the user dependency with a fixed user object |
| Test token | A real token minted with test settings for auth tests |
| SQLite in-memory | sqlite://: a database that lives inside one connection |
StaticPool | SQLAlchemy pool that always returns the same single connection |
check_same_thread | sqlite3 flag; False allows use from other threads |
| Transaction rollback per test | Isolation by an outer transaction rolled back after each test |
| Nested transaction | A transaction inside a transaction, implemented with savepoints |
| Savepoint | SAVEPOINT / RELEASE / ROLLBACK TO: an undo point inside a transaction |
join_transaction_mode="create_savepoint" | Session mode that maps its commit/rollback onto savepoints of an external transaction |
| Legacy transaction control | sqlite3's default mode that skips BEGIN for SAVEPOINT and DDL |
create_all per test | Schema recreate strategy: new schema for every test |
| Schema recreate vs rollback | The two isolation strategies; measured at 0.38-0.45 s vs 0.21 s per 100 DB tests here |
| factory_boy | Library of model factories; SQLAlchemyModelFactory saves rows through a session |
| polyfactory | Library that builds Pydantic/dataclass instances from type hints |
| Faker | Library of realistic fake values |
| respx | httpx mocking library with routes and side effects |
| pytest-httpx | pytest plugin with an httpx_mock fixture |
| Mock external API | Replacing an outbound HTTP dependency with canned responses |
monkeypatch | pytest fixture that changes env, attributes or dicts and restores them |
unittest.mock | Standard library mocks: Mock, patch, create_autospec, ANY |
| Autospec | A mock built from a real object's signature |
| freezegun | Library that freezes datetime/time by patching modules |
| time-machine | Library that moves the clock by patching C-level time functions |
| Flaky test | A test that passes and fails without code changes |
| Retries anti-pattern | Rerunning failed tests until they pass instead of fixing the cause |
BackgroundTasks testing | Asserting a background task's effect after TestClient returns |
| WebSocket test | client.websocket_connect(...) with send_json/receive_json |
| OpenAPI snapshot | Stored openapi.json compared on every run |
| Contract test | A test that checks both sides of an interface agree on messages |
| coverage.py | Python coverage measurement tool |
| pytest-cov | pytest plugin that runs coverage.py (--cov) |
| Branch coverage | Coverage of each possible jump, reporting partial branches |
| testcontainers | Library that starts throwaway Docker containers (PostgreSQL) for tests |
| PostgreSQL in CI | Running the suite against a real PostgreSQL in the pipeline |
| Test speed | Wall time per test and per suite; driven mostly by fixtures |
| Test pyramid | Many unit tests, fewer integration tests, very few e2e tests |
| Unit vs integration vs e2e | One function, the app with test infrastructure, the deployed system |
RefreshDatabase | Laravel trait running each test in a transaction |
Http::fake | Laravel HTTP client fake |
actingAs | Laravel helper that authenticates a user for a test |
| Pest | PHP testing framework on PHPUnit with test()/expect() |
httptest | Go package with ResponseRecorder and a test Server |
| Table-driven tests | Go idiom: a slice of cases run as subtests |
| testify | Go assertion (assert, require) and mock library |
References
- FastAPI, "Testing": https://fastapi.tiangolo.com/tutorial/testing/
- FastAPI, "Testing Dependencies with Overrides": https://fastapi.tiangolo.com/advanced/testing-dependencies/
- FastAPI, "Async Tests": https://fastapi.tiangolo.com/advanced/async-tests/
- FastAPI, "Testing Events: lifespan and startup - shutdown": https://fastapi.tiangolo.com/advanced/testing-events/
- FastAPI, "Testing WebSockets": https://fastapi.tiangolo.com/advanced/testing-websockets/
- FastAPI, "Settings and Environment Variables": https://fastapi.tiangolo.com/advanced/settings/
- FastAPI, "Background Tasks": https://fastapi.tiangolo.com/tutorial/background-tasks/
- FastAPI, "SQL (Relational) Databases": https://fastapi.tiangolo.com/tutorial/sql-databases/
- FastAPI, "Handling Errors": https://fastapi.tiangolo.com/tutorial/handling-errors/
- FastAPI, "Lifespan Events": https://fastapi.tiangolo.com/advanced/events/
- FastAPI, "Test Client - TestClient" (reference): https://fastapi.tiangolo.com/reference/testclient/
- FastAPI, "Release Notes": https://fastapi.tiangolo.com/release-notes/
- SQLModel, "Test Applications with FastAPI and SQLModel": https://sqlmodel.tiangolo.com/tutorial/fastapi/tests/
- Starlette, "Test Client": https://www.starlette.dev/testclient/
- Starlette, "Release Notes" (0.21.0 httpx, 1.2.0 httpx2): https://www.starlette.dev/release-notes/
- Starlette, "WebSockets": https://www.starlette.dev/websockets/
- HTTPX, "Async Support": https://www.python-httpx.org/async/
- HTTPX, "Transports" (
ASGITransport,MockTransport): https://www.python-httpx.org/advanced/transports/ - asgi-lifespan, README: https://raw.githubusercontent.com/florimondmanca/asgi-lifespan/master/README.md
- AnyIO, "Testing with AnyIO": https://anyio.readthedocs.io/en/stable/testing.html
- pytest-asyncio, "Concepts" (modes): https://pytest-asyncio.readthedocs.io/en/stable/concepts.html
- pytest-asyncio, "Configuration": https://pytest-asyncio.readthedocs.io/en/stable/reference/configuration.html
- pytest-asyncio, "Changelog": https://pytest-asyncio.readthedocs.io/en/stable/reference/changelog.html
- pytest, "Get Started": https://docs.pytest.org/en/stable/getting-started.html
- pytest, "How to use fixtures": https://docs.pytest.org/en/stable/how-to/fixtures.html
- pytest, "About fixtures": https://docs.pytest.org/en/stable/explanation/fixtures.html
- pytest, "Fixtures reference": https://docs.pytest.org/en/stable/reference/fixtures.html
- pytest, "How to parametrize fixtures and test functions": https://docs.pytest.org/en/stable/how-to/parametrize.html
- pytest, "How to mark test functions with attributes": https://docs.pytest.org/en/stable/how-to/mark.html
- pytest, "How to use skip and xfail": https://docs.pytest.org/en/stable/how-to/skipping.html
- pytest, "How to monkeypatch/mock modules and environments": https://docs.pytest.org/en/stable/how-to/monkeypatch.html
- pytest, "How to write and report assertions in tests": https://docs.pytest.org/en/stable/how-to/assert.html
- pytest, "Anatomy of a test": https://docs.pytest.org/en/stable/explanation/anatomy.html
- pytest, "Good Integration Practices": https://docs.pytest.org/en/stable/explanation/goodpractices.html
- pytest, "Configuration" (rootdir, config files): https://docs.pytest.org/en/stable/reference/customize.html
- pytest, "Flaky tests": https://docs.pytest.org/en/stable/explanation/flaky.html
- pytest, "How to re-run failed tests and maintain state between test runs": https://docs.pytest.org/en/stable/how-to/cache.html
- pytest, "Writing plugins": https://docs.pytest.org/en/stable/how-to/writing_plugins.html
- pytest, "API Reference": https://docs.pytest.org/en/stable/reference/reference.html
- pytest, "History": https://docs.pytest.org/en/stable/history.html
- pytest, "Changelog" (8.4.2, 9.0.0): https://docs.pytest.org/en/stable/changelog.html
- SQLAlchemy 2.0, "Transactions and Connection Management" (joining an external transaction): https://docs.sqlalchemy.org/en/20/orm/session_transaction.html
- SQLAlchemy 2.0, "Connection Pooling" (
StaticPool): https://docs.sqlalchemy.org/en/20/core/pooling.html - SQLAlchemy 2.0, "SQLite" (legacy transaction control, savepoints,
StaticPool): https://docs.sqlalchemy.org/en/20/dialects/sqlite.html - SQLAlchemy 2.0, "Session Basics": https://docs.sqlalchemy.org/en/20/orm/session_basics.html
- SQLAlchemy, "Download" (release table): https://www.sqlalchemy.org/download.html
- respx, "User Guide": https://lundberg.github.io/respx/guide/
- respx, "API Reference": https://lundberg.github.io/respx/api/
- pytest-httpx, README: https://raw.githubusercontent.com/Colin-b/pytest_httpx/develop/README.md
- factory_boy, documentation: https://factoryboy.readthedocs.io/en/stable/
- factory_boy, "Using factory_boy with ORMs": https://factoryboy.readthedocs.io/en/stable/orms.html
- polyfactory, "Declaring factories": https://polyfactory.litestar.dev/latest/usage/declaring_factories.html
- polyfactory, Pydantic factory reference: https://polyfactory.litestar.dev/latest/reference/factories/pydantic_factory.html
- Faker, documentation: https://faker.readthedocs.io/en/master/
- freezegun, README: https://raw.githubusercontent.com/spulec/freezegun/master/README.rst
- time-machine, "Usage": https://time-machine.readthedocs.io/en/latest/usage.html
- time-machine, "Comparison": https://time-machine.readthedocs.io/en/latest/comparison.html
- coverage.py, documentation: https://coverage.readthedocs.io/en/latest/
- coverage.py, "Branch coverage measurement": https://coverage.readthedocs.io/en/latest/branch.html
- coverage.py, "Configuration reference": https://coverage.readthedocs.io/en/latest/config.html
- pytest-cov, documentation: https://pytest-cov.readthedocs.io/en/latest/
- pytest-cov, "Reporting": https://pytest-cov.readthedocs.io/en/latest/reporting.html
- testcontainers-python, documentation: https://testcontainers-python.readthedocs.io/en/latest/
- testcontainers-python,
PostgresContainer: https://testcontainers-python.readthedocs.io/en/latest/modules/postgres/README.html - Python,
unittest.mock: https://docs.python.org/3/library/unittest.mock.html - Python, "unittest.mock — getting started": https://docs.python.org/3/library/unittest.mock-examples.html
- Schemathesis, documentation: https://schemathesis.readthedocs.io/en/stable/
- Pact, documentation: https://docs.pact.io/
- Laravel 13, "Testing: Getting Started": https://laravel.com/docs/13.x/testing
- Laravel 13, "Database Testing": https://laravel.com/docs/13.x/database-testing
- Laravel 13, "HTTP Tests": https://laravel.com/docs/13.x/http-tests
- Laravel 13, "HTTP Client" (faking, stray requests): https://laravel.com/docs/13.x/http-client
- Laravel 13, "Mocking" (time travel): https://laravel.com/docs/13.x/mocking
- Pest, "Writing Tests": https://pestphp.com/docs/writing-tests
- Pest, "Mocking": https://pestphp.com/docs/mocking
- Pest, "Hooks" (
beforeEach): https://pestphp.com/docs/hooks - Go source,
net/http/httptest/server.go: https://go.dev/src/net/http/httptest/server.go - Go source,
net/http/httptest/recorder.go: https://go.dev/src/net/http/httptest/recorder.go - Go wiki, "TableDrivenTests": https://go.dev/wiki/TableDrivenTests
- testify, README: https://github.com/stretchr/testify
- Martin Fowler, "The Practical Test Pyramid": https://martinfowler.com/articles/practical-test-pyramid.html
- Martin Fowler, "TestPyramid": https://martinfowler.com/bliki/TestPyramid.html
- Martin Fowler, "ContractTest": https://martinfowler.com/bliki/ContractTest.html
- Martin Fowler, "Eradicating Non-Determinism in Tests": https://martinfowler.com/articles/nonDeterminism.html
- PyPI release data: https://pypi.org/project/pytest/ , https://pypi.org/project/pytest-asyncio/ , https://pypi.org/project/time-machine/ , https://pypi.org/project/fastapi/ , https://pypi.org/project/starlette/