Recipes#

Short, runnable answers to "how do I use this with ...". Each page that shows output was produced by running the code on it, and says with which versions.

Page What it covers
FastAPI TestClient and httpx.AsyncClient with dependency-overridden sessions
Flask-SQLAlchemy The test client and db.session
SQLModel Session.exec() and relationships
Litestar TestClient with an overridden session dependency
pytest-asyncio Configuration pitfalls for async tests and fixtures
Budgets for hot endpoints max_queries and max_db_time on the endpoints that matter
The query count must not grow with N The same call with 1, 10 and 50 rows and the same count, for SQLAlchemy and Django
From a Sentry N+1 issue to a test A test that fails on the loop Sentry reported and passes after the fix
A session per request in a test transaction Per-request sessions that join the test's rolled-back transaction, instead of one shared Session
GraphQL resolvers Per-object resolvers: a batch loader or selectinload
Background tasks in tests Tasks run in the test body, with their own session
Factory Boy and seeding Seeding rows in the test body: fixtures, or ignoring write loops in tests
Adopting on a legacy codebase Warn mode, a baseline, then fail
CI GitHub Actions, GitLab CI, and pre-commit for the static check

The versions used for the output on these pages: Python 3.12, pytest 9.1.1, SQLAlchemy 2.1.4, pytest-queryguard 0.4.0. Messages from older SQLAlchemy releases differ in small ways, for example column aliases in the SQL. Before Python 3.12 a list comprehension is a frame of its own, so a finding raised inside one says in <listcomp> instead of the name of the function.

Edit this page on GitHub