Lab: A Disposable PostgreSQL for Every Test Run
Spin up a disposable PostgreSQL container in pytest, apply Alembic migrations once per test session, and isolate each test with automatic transaction rollbacks.
Contentsand lesson path
On this page
- Why it matters
- Before you start
- Step 1: create the project and check Docker
- Step 2: the API under test
- Step 3: the schema as an Alembic migration
- Step 4: one container for the whole test run
- Step 5: a rolled-back transaction for every test
- Step 6: break the isolation on purpose
- Check your understanding
- Apply it
- Review prompt
Lessons of API Integration & Contract Testing
- Why Mocks Lie About Databases Concept · 15 min
- Lab: A Disposable PostgreSQL for Every Test Run Lab · 30 min
- End-to-End API Tests with Factories Worked example · 25 min
- Contract Tests Generated from an OpenAPI Document Worked example · 25 min
- Fast, Deterministic, Not Flaky Concept · 15 min
- Check: Diagnose the Failing Suite Knowledge check · 8 questions
What you will learn
- Run integration tests against a disposable PostgreSQL instance with migrations applied and per-test isolation through transaction rollback or truncation.
Prerequisites: Software Testing Fundamentals, Data Access with SQLAlchemy
01. Why it matters
A shared development database makes integration tests unreliable. One test changes a user's email, a later test expects the old value, and the suite passes or fails depending on the order in which tests run. Teams then add cleanup scripts that delete rows by hand, and those scripts fall out of date as the schema grows.
In this lab every test run gets its own PostgreSQL. pytest starts a throwaway container with Testcontainers, builds the schema with your real Alembic migrations, and wraps each test in a transaction that is rolled back at the end. You will build a small reading-list API, prove that tests cannot see each other's rows, and then break the isolation on purpose so you recognise that failure later. The next lesson builds on the same project.
02. Before you start
You need Python 3.12 or newer, uv (or python -m venv and pip), and a running Docker engine. The lab was run with fastapi 0.163.1, SQLAlchemy 2.1.9, Alembic 1.20.1, psycopg 3.3.9, testcontainers 4.15.0, pytest 9.2.0 and postgres:17-alpine. FastAPI's TestClient comes from Starlette, which now builds it on httpx2; plain httpx still works but prints a deprecation warning (Starlette test client docs). The finished project has three parts:
app/:models.py,security.py,deps.pyandmain.py, the API under test.alembic.iniandmigrations/:env.pyand one revision inversions/, the schema.tests/:conftest.py,test_schema.pyandtest_api.py, the suite.
03. Step 1: create the project and check Docker
Create the folders, install the packages into a virtual environment, and ask the Postgres image for its version. The last command proves two things: Docker answers, and the image is already on your machine, so the first test run does not stall on a download.
mkdir -p readinglist/app readinglist/migrations/versions readinglist/tests
cd readinglist
touch app/__init__.py tests/__init__.py
uv venv --python 3.12
source .venv/bin/activate
uv pip install fastapi httpx2 sqlalchemy "psycopg[binary]" alembic \
argon2-cffi pytest testcontainers
docker run --rm postgres:17-alpine postgres --versionpostgres (PostgreSQL) 17.1104. Step 2: the API under test
The app is deliberately small: people sign up and receive an API token, then create and read their own books. The models describe two tables. Note the unique constraint on (owner_id, slug): one person cannot add the same title twice, and you will test that rule against the real database.
from sqlalchemy import ForeignKey, String, UniqueConstraint
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
class Base(DeclarativeBase):
pass
class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(primary_key=True)
email: Mapped[str] = mapped_column(String(254), unique=True)
password_hash: Mapped[str]
token_hash: Mapped[str] = mapped_column(String(64), unique=True)
class Book(Base):
__tablename__ = "books"
__table_args__ = (UniqueConstraint("owner_id", "slug"),)
id: Mapped[int] = mapped_column(primary_key=True)
owner_id: Mapped[int] = mapped_column(ForeignKey("users.id"))
title: Mapped[str] = mapped_column(String(200))
slug: Mapped[str] = mapped_column(String(200))
year: Mapped[int]Passwords and tokens are stored only as hashes. A password is short and guessable, so it gets Argon2id, a deliberately slow hash, through argon2-cffi. A token is 32 random bytes, so a fast SHA-256 is enough to find it without storing the token itself.
import hashlib
import secrets
from argon2 import PasswordHasher
_hasher = PasswordHasher() # Argon2id with the library's default cost
def new_token() -> str:
return secrets.token_urlsafe(32)
def hash_token(token: str) -> str:
"""Tokens are long and random, so a fast SHA-256 lookup hash is enough."""
return hashlib.sha256(token.encode()).hexdigest()
def hash_password(password: str) -> str:
"""Passwords are guessable, so they need a slow, salted hash."""
return _hasher.hash(password)deps.py is the seam the tests will use. Every route receives its database session from get_session, so a test can replace that one function and send all database work into its own transaction.
import os
from collections.abc import Iterator
from sqlalchemy import create_engine
from sqlalchemy.orm import Session, sessionmaker
# create_engine() does not connect yet, so importing this module is safe in tests.
engine = create_engine(os.environ.get(
"DATABASE_URL", "postgresql+psycopg://app:app@localhost:5432/readinglist"))
SessionLocal = sessionmaker(bind=engine, expire_on_commit=False)
def get_session() -> Iterator[Session]:
with SessionLocal() as session:
yield sessionimport re
from typing import Annotated
from fastapi import Depends, FastAPI, Header, HTTPException
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from app.deps import get_session
from app.models import Book, User
from app.security import hash_password, hash_token, new_token
app = FastAPI()
DB = Annotated[Session, Depends(get_session)]
class SignUp(BaseModel):
email: str
password: str
class BookIn(BaseModel):
title: str
year: intdef make_slug(title: str) -> str:
return re.sub(r"[^a-z0-9]+", "-", title.lower()).strip("-")
def current_user(db: DB, authorization: str = Header("")) -> User:
token = authorization.removeprefix("Bearer ")
user = db.scalar(select(User).where(User.token_hash == hash_token(token)))
if user is None:
raise HTTPException(401, "missing or invalid token")
return user
def save(db: Session, row: User | Book, conflict: str) -> None:
db.add(row)
try:
db.commit()
except IntegrityError:
db.rollback()
raise HTTPException(409, conflict)@app.post("/users", status_code=201)
def sign_up(body: SignUp, db: DB) -> dict:
token = new_token()
user = User(email=body.email, password_hash=hash_password(body.password),
token_hash=hash_token(token))
save(db, user, "email already registered")
return {"id": user.id, "email": user.email, "token": token}
@app.post("/books", status_code=201)
def create_book(body: BookIn, db: DB,
user: Annotated[User, Depends(current_user)]) -> dict:
book = Book(owner_id=user.id, title=body.title,
slug=make_slug(body.title), year=body.year)
save(db, book, "you already have a book with this title")
return {"id": book.id, "title": book.title, "year": book.year}
@app.get("/books")
def list_books(db: DB, user: Annotated[User, Depends(current_user)]) -> list[dict]:
books = db.scalars(select(Book).where(Book.owner_id == user.id)
.order_by(Book.id))
return [{"id": b.id, "title": b.title, "year": b.year} for b in books]
@app.get("/books/{book_id}")
def read_book(book_id: int, db: DB,
user: Annotated[User, Depends(current_user)]) -> dict:
book = db.get(Book, book_id)
if book is None or book.owner_id != user.id:
raise HTTPException(404, "book not found")
return {"id": book.id, "title": book.title, "year": book.year}save() turns a unique-constraint violation into 409 Conflict. It calls db.rollback() first, because a SQLAlchemy session whose flush failed refuses further work until it is rolled back. Check that the app imports and exposes its three paths:
python -c 'from app.main import app; print(list(app.openapi()["paths"]))'['/users', '/books', '/books/{book_id}']05. Step 3: the schema as an Alembic migration
Production databases are built by migrations, so the tests build theirs the same way. Alembic needs a config file naming the migrations folder, an env.py that connects and runs the scripts, and one script per schema change. In a real project alembic init migrations generates these files; minimal versions are enough here.
[alembic]
script_location = migrationsimport os
from alembic import context
from sqlalchemy import create_engine
# Tests set sqlalchemy.url; the alembic CLI falls back to DATABASE_URL.
url = context.config.get_main_option("sqlalchemy.url") or os.environ["DATABASE_URL"]
with create_engine(url).connect() as connection:
context.configure(connection=connection)
with context.begin_transaction():
context.run_migrations()"""Create users and books."""
import sqlalchemy as sa
from alembic import op
revision = "0001"
down_revision = None
def upgrade() -> None:
op.create_table(
"users",
sa.Column("id", sa.Integer, primary_key=True),
sa.Column("email", sa.String(254), nullable=False, unique=True),
sa.Column("password_hash", sa.String, nullable=False),
sa.Column("token_hash", sa.String(64), nullable=False, unique=True),
)
op.create_table(
"books",
sa.Column("id", sa.Integer, primary_key=True),
sa.Column("owner_id", sa.Integer, sa.ForeignKey("users.id"), nullable=False),
sa.Column("title", sa.String(200), nullable=False),
sa.Column("slug", sa.String(200), nullable=False),
sa.Column("year", sa.Integer, nullable=False),
sa.UniqueConstraint("owner_id", "slug"),
)
def downgrade() -> None:
op.drop_table("books")
op.drop_table("users")The migration repeats what the models say, and that is on purpose: if the two ever disagree, the tests are where you find out. Ask Alembic which revisions it can see:
alembic history<base> -> 0001 (head), Create users and books.06. Step 4: one container for the whole test run
Now the first half of tests/conftest.py. The database_url fixture starts the container, and scope="session" tells pytest to build it once per run instead of once per test, which would repeat the start-up wait every time. PostgresContainer maps port 5432 to a random free port, so it does not clash with a Postgres you already run, and leaving the with block stops and removes the container.
from collections.abc import Iterator
from pathlib import Path
import pytest
from alembic import command
from alembic.config import Config
from fastapi.testclient import TestClient
from sqlalchemy import Connection, Engine, create_engine
from sqlalchemy.orm import Session, sessionmaker
from testcontainers.community.postgres import PostgresContainer
from app.deps import get_session
from app.main import app
ROOT = Path(__file__).resolve().parents[1] # the folder that holds alembic.ini
@pytest.fixture(scope="session")
def database_url() -> Iterator[str]:
"""One PostgreSQL container for the whole run; removed when the block exits."""
pg = PostgresContainer("postgres:17-alpine", driver="psycopg")
pg.with_tmpfs_mount("/var/lib/postgresql/data") # data lives in memory only
with pg:
yield pg.get_connection_url()
@pytest.fixture(scope="session")
def engine(database_url: str) -> Iterator[Engine]:
"""Build the schema the way production does: by running every migration."""
cfg = Config(str(ROOT / "alembic.ini"))
cfg.set_main_option("sqlalchemy.url", database_url)
command.upgrade(cfg, "head")
engine = create_engine(database_url)
yield engine
engine.dispose()Two choices here are worth copying. with_tmpfs_mount keeps the database files in memory, so nothing outlives the container. And the engine fixture runs command.upgrade(cfg, "head") instead of Base.metadata.create_all(), which builds tables straight from the models and would hide a migration that fails, forgets an index or disagrees with the models.
Testcontainers also starts Ryuk, a helper container that removes the run's containers even if pytest is killed; leave it on unless your CI cleans up by itself (TESTCONTAINERS_RYUK_DISABLED=true). Add a first test that checks the migrated schema, and run it:
from sqlalchemy import Engine, inspect
def test_migrations_build_the_schema(engine: Engine) -> None:
tables = sorted(inspect(engine).get_table_names())
assert tables == ["alembic_version", "books", "users"]pytest -v --no-header tests/test_schema.py============================= test session starts ==============================
collecting ... collected 1 item
tests/test_schema.py::test_migrations_build_the_schema PASSED [100%]
============================== 1 passed in 0.55s ===============================07. Step 5: a rolled-back transaction for every test
All tests share the one migrated database, so each must start from the same empty state. TRUNCATE after each test works (Step 6 shows when you need it), but it must name every table. The approach here costs one rollback per test instead.
Each test gets its own connection with an outer transaction already open. The app's session joins that connection with join_transaction_mode="create_savepoint", the pattern in SQLAlchemy's guide to joining an external transaction. When a route calls session.commit(), SQLAlchemy releases a SAVEPOINT, a named mark inside a transaction that can be rolled back to, instead of committing. When the test ends, the fixture rolls back the outer transaction and everything the test wrote disappears. Rollback is cheap in PostgreSQL: it marks the transaction as aborted, and VACUUM reclaims the dead rows later.
@pytest.fixture
def connection(engine: Engine) -> Iterator[Connection]:
"""Each test runs inside one outer transaction that is rolled back at the end."""
with engine.connect() as conn:
outer = conn.begin()
yield conn
outer.rollback()
@pytest.fixture
def session(connection: Connection) -> Iterator[Session]:
"""A session on the test connection: its commit() only releases a savepoint."""
factory = sessionmaker(
bind=connection,
join_transaction_mode="create_savepoint",
expire_on_commit=False,
)
with factory() as session:
yield session
@pytest.fixture
def client(session: Session) -> Iterator[TestClient]:
"""Every route that asks for get_session receives the test session instead."""
def override() -> Iterator[Session]:
yield session
app.dependency_overrides[get_session] = override
with TestClient(app) as test_client:
yield test_client
app.dependency_overrides.clear()In the client fixture, app.dependency_overrides[get_session] = override makes FastAPI call override wherever a route asks for get_session (FastAPI: testing dependencies), so every request uses the test's session and connection. Now the tests. The third is a negative test: a missing or forged token must be refused.
from fastapi.testclient import TestClient
from sqlalchemy import func, select
from sqlalchemy.orm import Session
from app.models import User
SAM = {"email": "[email protected]", "password": "correct horse battery"}
def sign_up(client: TestClient) -> dict[str, str]:
token = client.post("/users", json=SAM).json()["token"]
return {"Authorization": f"Bearer {token}"}
def test_sign_up_creates_a_user(client: TestClient) -> None:
response = client.post("/users", json=SAM)
assert response.status_code == 201
assert response.json()["email"] == "[email protected]"
def test_created_book_can_be_read_back(client: TestClient) -> None:
auth = sign_up(client)
created = client.post("/books", json={"title": "Dune", "year": 1965},
headers=auth)
assert created.status_code == 201
read = client.get(f"/books/{created.json()['id']}", headers=auth)
assert read.json() == {"id": created.json()["id"], "title": "Dune",
"year": 1965}def test_books_without_a_valid_token_answer_401(client: TestClient) -> None:
sign_up(client)
forged = {"Authorization": "Bearer not-a-real-token"}
assert client.get("/books").status_code == 401
assert client.get("/books", headers=forged).status_code == 401
def test_duplicate_title_answers_409(client: TestClient) -> None:
auth = sign_up(client)
book = {"title": "Dune", "year": 1965}
assert client.post("/books", json=book, headers=auth).status_code == 201
again = client.post("/books", json=book, headers=auth)
assert again.status_code == 409
# The failed insert rolled back only its savepoint; the session still works.
assert len(client.get("/books", headers=auth).json()) == 1
def test_every_test_starts_from_an_empty_database(session: Session) -> None:
# Four tests above created users; each outer transaction was rolled back.
users = session.scalar(select(func.count(User.id)))
assert users == 0The order matters for the last test: pytest runs the tests of a file from top to bottom, so by the time it counts users, four earlier tests have each signed Sam up. Run the file:
pytest -v --no-header tests/test_api.py============================= test session starts ==============================
collecting ... collected 5 items
tests/test_api.py::test_sign_up_creates_a_user PASSED [ 20%]
tests/test_api.py::test_created_book_can_be_read_back PASSED [ 40%]
tests/test_api.py::test_books_without_a_valid_token_answer_401 PASSED [ 60%]
tests/test_api.py::test_duplicate_title_answers_409 PASSED [ 80%]
tests/test_api.py::test_every_test_starts_from_an_empty_database PASSED [100%]
============================== 5 passed in 1.20s ===============================Sam signed up four times with the same email, and the unique email column never complained, because each sign-up vanished with its test's transaction. The duplicate-title test also shows the savepoint at work: the failed insert rolled back only its own savepoint, so the same test could keep using the session and still list one book.
08. Step 6: break the isolation on purpose
Rollback isolation covers only work done through the test's connection. Code that opens its own connection, such as a background job, a second engine or a script called from a route, commits for real and leaks into later tests. See it happen: add this test to tests/test_api.py directly above test_every_test_starts_from_an_empty_database, and change the import line to from sqlalchemy import Engine, func, insert, select.
def test_report_job_commits_on_its_own_connection(engine: Engine) -> None:
# Like a background job: it opens its own connection and really commits.
with engine.begin() as conn:
conn.execute(insert(User).values(
email="[email protected]", password_hash="-", token_hash="-"))pytest -q --no-header --tb=short tests/test_api.py.....F [100%]
=================================== FAILURES ===================================
________________ test_every_test_starts_from_an_empty_database _________________
tests/test_api.py:58: in test_every_test_starts_from_an_empty_database
assert users == 0
E assert 1 == 0
=========================== short test summary info ============================
FAILED tests/test_api.py::test_every_test_starts_from_an_empty_database - ass...
1 failed, 5 passed in 10.60sThe job's row was committed on a separate connection, so the outer rollback never touched it. Delete the temporary test, restore the import line and rerun: all five pass, because the leaked row lived only in that run's container. Within one run nothing resets it, so code that commits on its own connection needs a fixture that truncates the affected tables afterwards.
Two more limits:
- Sequences are not rolled back. Identity values keep growing across tests, so never assert that a new row has id 1.
- Anything that depends on a real
COMMITis not exercised. Deferred constraints, commit-time triggers and visibility from other connections need a separate test that truly commits and then truncates.
09. Check your understanding
10. Apply it
Turn the Step 6 leak into a passing test. Write a truncate_tables fixture that runs TRUNCATE users, books RESTART IDENTITY CASCADE on its own connection after the test, use it only for the job test, and confirm that the rollback-based tests still pass next to it. Then run pytest --durations=5 and compare the set-up time of database_url with the time of a single test, so you know what the session scope saves you. Keep the project: in the next lesson you add data factories and end-to-end flows on top of it.
11. Review prompt
Without looking back: trace one test from the moment pytest calls it to the end of teardown, and explain how engine.connect(), conn.begin(), join_transaction_mode="create_savepoint" and outer.rollback() cooperate to keep it isolated. Say why the fixtures run the Alembic migrations instead of create_all(), which kinds of code escape the rollback, and what you would use for them instead.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.