Full answer
Goals: tests that are isolated, fast and use the same database engine as production behaviour requires (PostgreSQL in CI, SQLite only for simple cases).
Layering of fixtures:
engine(scope="session"): create the engine,Base.metadata.create_all()(or run Alembic migrations to test them too).db_session(function scope):
connection = engine.connect()
outer = connection.begin()
session = Session(bind=connection, join_transaction_mode="create_savepoint")
yield session
session.close()
outer.rollback()
connection.close()With create_savepoint, an application session.commit() releases a SAVEPOINT instead of committing the outer transaction, so the final rollback undoes everything. This is the SQLAlchemy 2.0 replacement for the older "nested transaction plus event listener" recipe.
3. client: override the dependency and yield a TestClient:
app.dependency_overrides[get_db] = lambda: session
with TestClient(app) as c: yield c
app.dependency_overrides.clear()Practical points:
- Factories or small helper fixtures create data (
make_student(name="Asha")) so tests state only what they need. - SQLite via
pysqliteneeds a known workaround for savepoints to work (setisolation_level = Noneon connect and emitBEGINin abeginevent, as in the snippet); PostgreSQL needs nothing special. - If code under test uses threads (sync endpoints run in a thread pool), the session and connection are shared across threads: use a driver and pool that allow it (SQLite needs
check_same_thread=FalsewithStaticPool; PostgreSQL connections are fine when used sequentially). - Behaviour that depends on real commits (triggers on commit,
on_commithooks, isolation levels, concurrent transactions) needs separate tests with real commits and cleanup. - Seed static reference data once per session, not per test.
- Use pytest markers for slow database tests and run them in parallel with
pytest-xdistusing one database per worker. - Keep a few end-to-end tests that run migrations on a clean database to catch drift between models and migrations.
import contextlib
import io
import sys
import tempfile
import textwrap
from pathlib import Path
import pytest
work = Path(tempfile.mkdtemp())
(work / "app_under_test.py").write_text(textwrap.dedent("""
from typing import Annotated
from fastapi import Depends, FastAPI
from pydantic import BaseModel
from sqlalchemy import create_engine, event, select
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column, sessionmaker
from sqlalchemy.pool import StaticPool
class Base(DeclarativeBase):
pass
class Student(Base):
__tablename__ = "student"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
@event.listens_for(engine, "connect")
def no_implicit_begin(dbapi_connection, record):
dbapi_connection.isolation_level = None # pysqlite recipe: stop the driver from managing BEGIN
@event.listens_for(engine, "begin")
def emit_begin(conn):
conn.exec_driver_sql("BEGIN") # so SAVEPOINT and ROLLBACK behave properly
SessionLocal = sessionmaker(engine)
def get_db():
with SessionLocal() as db:
yield db
app = FastAPI()
class StudentIn(BaseModel):
name: str
@app.post("/students", status_code=201)
def create(s: StudentIn, db: Annotated[Session, Depends(get_db)]):
row = Student(name=s.name)
db.add(row)
db.commit() # the endpoint commits for real
return {"id": row.id, "name": row.name}
@app.get("/students")
def listing(db: Annotated[Session, Depends(get_db)]):
return [r.name for r in db.scalars(select(Student).order_by(Student.id))]
"""))
(work / "conftest.py").write_text(textwrap.dedent("""
import pytest
from fastapi.testclient import TestClient
from sqlalchemy.orm import Session
from app_under_test import Base, app, engine, get_db
@pytest.fixture(scope="session", autouse=True)
def schema():
Base.metadata.create_all(engine)
@pytest.fixture
def db_session():
connection = engine.connect()
outer = connection.begin()
session = Session(bind=connection, join_transaction_mode="create_savepoint")
yield session
session.close()
outer.rollback()
connection.close()
@pytest.fixture
def client(db_session):
app.dependency_overrides[get_db] = lambda: db_session
with TestClient(app) as c:
yield c
app.dependency_overrides.clear()
"""))
(work / "test_students.py").write_text(textwrap.dedent("""
def test_create_and_list(client):
assert client.post("/students", json={"name": "Asha"}).status_code == 201
assert client.get("/students").json() == ["Asha"]
def test_starts_empty_again(client):
assert client.get("/students").json() == []
def test_commit_inside_endpoint_is_rolled_back(client):
client.post("/students", json={"name": "Ravi"})
client.post("/students", json={"name": "Kiran"})
assert client.get("/students").json() == ["Ravi", "Kiran"]
def test_still_empty(client):
assert client.get("/students").json() == []
"""))
class Counter:
def __init__(self):
self.outcomes = []
def pytest_runtest_logreport(self, report):
if report.when == "call":
self.outcomes.append((report.nodeid.split("::")[1], report.outcome))
sys.path.insert(0, str(work))
counter = Counter()
with contextlib.redirect_stdout(io.StringIO()): # hide pytest timing line so the output is stable
code = pytest.main(["-q", "-p", "no:cacheprovider", "--rootdir", str(work), str(work)], plugins=[counter])
print("exit code:", int(code))
for name, outcome in counter.outcomes:
print(f"{name}: {outcome}")
Standalone script. Run it with `python file.py`; it writes a small test project to a temporary folder and runs pytest on it. Requires `pip install pytest sqlalchemy`. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0, pytest 9.2.0): exit code: 0 test_create_and_list: passed test_starts_empty_again: passed test_commit_inside_endpoint_is_rolled_back: passed test_still_empty: passed
Key points
- Session-scoped engine; function-scoped rolled-back transaction
- join_transaction_mode='create_savepoint' turns commit() into a savepoint release
- Override get_db to yield the test session
- Behaviour tied to real commits needs separate tests
- Use one database per xdist worker
Common mistakes
- Truncating tables between tests, which is slow and order-dependent
- Using a different database engine in tests than in production for behaviour that differs
- Forgetting to clear dependency overrides
- Testing commit-dependent behaviour inside a rolled-back transaction
- Leaking data between tests through session-scoped fixtures
Follow-ups
- How do you run these tests in parallel?
- How do you test code that depends on real commits, such as on_commit hooks?
- How would you run Alembic migrations as part of the fixtures?
Tips
- Describe the outer transaction and savepoint
- Show the dependency override
- Mention limits