Lesson 8 of 9 · 28m
Testing Database Code Honestly
Test real SQL behavior against real databases, isolate transactions cleanly, and reserve SQLite shortcuts for code that genuinely shares semantics.
Database tests are where fake confidence goes to thrive. SQLite accepts syntax PostgreSQL rejects, constraints differ, transaction behavior differs, and yet teams call it "close enough." Sometimes it is. Often it is not. The rule is simple: test against the same database engine whose behavior production depends on.
Prefer real Postgres in a disposable container
For a PostgreSQL application, use Docker Compose or Testcontainers-style setup:
services:
postgres-test:
image: postgres:16
environment:
POSTGRES_PASSWORD: postgres
POSTGRES_DB: app_test
ports:
- "5433:5432"Then point tests at it:
DATABASE_URL=postgresql://postgres:postgres@127.0.0.1:5433/app_test pytest tests/dbYes, it is heavier than SQLite. That is the price of testing constraints, indexes, isolation levels, JSON operators, and SQL errors that actually exist in production.
Roll back around each test
The clean pattern is a transaction per test:
import pytest
@pytest.fixture
def db_session(engine):
connection = engine.connect()
transaction = connection.begin()
session = Session(bind=connection)
yield session
session.close()
transaction.rollback()
connection.close()Each test starts with the same schema and seeded baseline, then rolls back its writes. Tests become order-independent without rebuilding the database every time. Do not share committed rows across tests unless the test explicitly verifies cross-transaction behavior.
Apply migrations before tests
Schema drift ruins suites. Run real migrations in test setup:
alembic upgrade headIf migration setup is too slow for every test, run it once per session in a fixture, then isolate data per test with rollback. Never maintain a parallel hand-written schema for tests; it will lie eventually.
What belongs in database tests
- Constraints: duplicate emails rejected, foreign keys enforced.
- Query shape: filters, ordering, pagination boundaries.
- Transactions: rollback leaves no partial writes.
- Concurrency invariants: unique creation under parallel attempts.
- Serialization behavior: JSON columns, time zones, decimal precision.
Do not use database tests to re-test ORM basics. Test your queries and invariants, not the vendor's
SELECTimplementation.
SQLite is sometimes legitimate
SQLite is acceptable when production also uses SQLite, or when the tested layer deliberately restricts itself to portable SQL. Even then, document the boundary. A repository test on SQLite is evidence about portable query logic, not evidence about PostgreSQL locking behavior.
Field notes
- Use random test database names when running parallel CI workers so they do not fight each other.
- Truncation is slower and more error-prone than rollback; use it only when transaction wrapping is impossible.
- Keep seed data minimal and explicit; giant fixtures make every test pay for setup it does not use.
- Record slow queries with database logs in integration environments, not by guessing from Python timing alone.
- If a test requires committed data visible to another connection, say so in its name and structure — it is a concurrency test, not a normal repository test.
Was this lesson helpful?