Chapter 20 — Moby's Test Lab#
Round-trip budgets, index assertions and SQL shape checks that run in CI.
pool.trace()tr.rttsassert_uses_index()compile()to_svg_erd()examples/078_testing_your_app.pyLaunch Day, 18:00. Down in the test lab, Moby the Whale floats happily beside a single PostgreSQL container serving four parallel pytest workers.
Moby: One container, one fresh t_<hex> schema per test! Real COMMITs, real SAVEPOINTs, real connection pools — and zero tests stepping on each other.
Panda: Why test against real PostgreSQL? Just mock the database driver — or swap in SQLite for tests!
Maya: SQLite doesn't have WITHOUT OVERLAPS, MERGE … RETURNING, SKIP LOCKED, or EXPLAIN index plans. Moby gives us the real Elephant in under a second.
The mission#
Mocking your database hides every bug that matters: missing indexes, N+1 round trips, broken constraints, and drifted SQL shapes. In the final shift, Maya locks down four production invariants in CI against a live PostgreSQL:
- Static SQL shape & tags: assert
= ANY($1)and trailing/* op:... */comments viapool.compile(...)with zero DB cost, - Hard RTT budgets: assert
tr.rtts == 1across a 3-query pipeline withpool.trace(), - Planner index proofs: assert
plan.assert_no_seq_scan()andplan.assert_uses_index("idx_guest_directory")viapool.explain(..., disable_seqscan=True), - Always-fresh ERDs: generate deterministic pure-Rust SVG diagrams straight from your Python tables with
pg.to_svg_erd(...).
The Panda's plan
Mock pool.all() to return fake dicts, or run tests against an in-memory toy database. Every test stays green while someone deletes idx_guest_directory, introduces a 40-RTT loop, or breaks a PostgreSQL CHECK constraint — and you find out from users at 03:00.
1. Per-test schema isolation in one container#
Instead of mocking PostgreSQL or rolling back giant outer transactions (which breaks COMMIT visibility, LISTEN/NOTIFY, and multi-connection pools), every test runs in its own isolated t_<hex> schema inside a single shared PostgreSQL container.
2. Four invariants every production app should assert#
async def verify_app_invariants(pool: pg.Pool, dorm_id: int) -> None:
# 1. Static SQL shape & pg_stat_statements operation tag check (no DB needed).
lookup_q = (
pg.select(Guest)
.where(Guest.email.in_any(["[email protected]", "[email protected]"]))
.order_by(Guest.last_name.asc(), Guest.guest_id.asc())
.tag("desk.lookup_herd")
)
compiled = pool.compile(lookup_q)
assert "ANY($1)" in compiled.sql
assert compiled.sql.endswith("/* op:desk.lookup_herd */")
print(f"SQL tag verified: {compiled.op_tag}")
# => SQL tag verified: desk.lookup_herd
# 2. Enforce strict 1-RTT budgets in CI with pool.trace().
async with pool.trace() as tr, pool.pipeline() as pipe:
h_dorm = pipe.add(pg.select(Dormitory).where(Dormitory.dormitory_id == dorm_id))
h_rooms = pipe.add(pg.select(Room).where(Room.dormitory_id == dorm_id))
h_guests = pipe.add(lookup_q)
assert tr.rtts == 1
assert h_dorm.one().code == "LIS"
assert len(h_rooms.all()) == 12
assert len(h_guests.all()) == 2
print(f"pipeline budget verified: {tr.statement_count} statements in {tr.rtts} RTT")
# => pipeline budget verified: 3 statements in 1 RTT
# 3. Verify PostgreSQL chooses your index (disable_seqscan=True catches silent Seq Scans).
dir_q = (
pg.select(Guest)
.where(pg.tuple_(Guest.last_name, Guest.guest_id) > ("Kalahari", 0))
.order_by(Guest.last_name.asc(), Guest.guest_id.asc())
.limit(5)
)
dir_idx = next(
i.name for i in Guest.__pg_resolved_indexes__ if i.columns == ("last_name", "guest_id")
)
plan = await pool.explain(dir_q, disable_seqscan=True)
plan.assert_no_seq_scan()
plan.assert_uses_index(dir_idx)
print(f"planner index verified: {dir_idx in plan.summary()}")
# => planner index verified: True
# 4. Generate a deterministic pure-Rust SVG ERD straight from your Python models.
svg = pg.to_svg_erd(*ACT1_TABLES)
assert svg.startswith("<svg") and "guest" in svg
print(f"ERD generated from {len(ACT1_TABLES)} tables (valid_svg={svg.startswith('<svg')})")
# => ERD generated from 7 tables (valid_svg=True)
What just happened
pool.compile(lookup_q)compiles the query locally in Rust — proving constant-shape= ANY($1)(one prepared statement regardless of list length) and the exact trailing/* op:desk.lookup_herd */tag.async with pool.trace() as tr:measures the live wire traffic and proves all 3 pipelined statements finished in 1 RTT (assert tr.rtts == 1). If a future refactor accidentally breaks the pipeline into 3 sequentialawaits, CI fails loudly on that exact line.pool.explain(dir_q, disable_seqscan=True)proves PostgreSQL can satisfy the directory query viaidx_guest_directory(with zero sequential scans even on a 3-row test table; as Chapter 9 notes, production plan choice still depends on live table statistics).pg.to_svg_erd(*ACT1_TABLES)generates a deterministic SVG entity-relationship diagram directly from your models in Rust — zero Graphviz installation needed, and zero stale hand-drawn diagrams.
Ferris' basement: explicit assertions over hidden snapshots
Snapshotting SQL strings is great for catching unexpected query changes, but never hide your performance invariants only inside a snapshot file! Always keep explicit assert tr.rtts == 1 and plan.assert_uses_index(...) assertions right in your test bodies so a reviewer sees immediately what cannot regress.
What PostgreSQL actually received#
🔭 What PostgreSQL received: 8 statements in 5 round trips (captured live on PostgreSQL)
-- ⚙ schema setup (create_all): 19 statements omitted · full transcript in examples/__wire__/testing_your_app.sql
-- ── round trip 1 · 2 statements pipelined ──
BEGIN;
INSERT INTO "dormitory" ("region_id", "code", "name", "city", "country", "timezone", "check_in", "check_out", "city_tax", "opened_on")
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
RETURNING "dormitory_id", "region_id", "code", "name", "city", "country", "timezone", "check_in", "check_out", "city_tax", "opened_on";
-- → 1 row
-- ── round trip 2 ──
INSERT INTO "room" ("dormitory_id", "number", "floor", "category", "max_weight_kg", "max_guests", "amenities", "out_of_service")
VALUES
($1, $2, $3, $4, $5, $6, $7, $8),
($9, $10, $11, $12, $13, $14, $15, $16),
($17, $18, $19, $20, $21, $22, $23, $24),
($25, $26, $27, $28, $29, $30, $31, $32),
($33, $34, $35, $36, $37, $38, $39, $40),
($41, $42, $43, $44, $45, $46, $47, $48),
($49, $50, $51, $52, $53, $54, $55, $56),
($57, $58, $59, $60, $61, $62, $63, $64),
($65, $66, $67, $68, $69, $70, $71, $72),
($73, $74, $75, $76, $77, $78, $79, $80),
($81, $82, $83, $84, $85, $86, $87, $88),
($89, $90, $91, $92, $93, $94, $95, $96)
RETURNING "room_id", "dormitory_id", "number", "floor", "category", "max_weight_kg", "max_guests", "amenities", "out_of_service";
-- → 12 rows
-- ── round trip 3 ──
INSERT INTO "guest" ("email", "first_name", "last_name", "species", "phone", "country", "birth_date", "loyalty_tier", "peanut_points", "preferences", "marketing_opt_in")
SELECT u.c0, u.c1, u.c2, u.c3, u.c4, u.c5, u.c6, u.c7, u.c8, u.c9, u.c10
FROM unnest($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) WITH ORDINALITY AS u(c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, ord)
ORDER BY u.ord
RETURNING "guest_id", "public_id", "email", "first_name", "last_name", "full_name", "species", "phone", "country", "birth_date", "loyalty_tier", "peanut_points", "preferences", "marketing_opt_in", "created_at";
-- → 3 rows
-- ── round trip 4 ──
COMMIT;
-- ── round trip 5 · 3 statements pipelined ──
SELECT
"dormitory_id",
"region_id",
"code",
"name",
"city",
"country",
"timezone",
"check_in",
"check_out",
"city_tax",
"opened_on"
FROM "dormitory"
WHERE "dormitory_id" = $1;
-- → 1 row
SELECT
"room_id",
"dormitory_id",
"number",
"floor",
"category",
"max_weight_kg",
"max_guests",
"amenities",
"out_of_service"
FROM "room"
WHERE "dormitory_id" = $1;
-- → 12 rows
SELECT
"guest_id",
"public_id",
"email",
"first_name",
"last_name",
"full_name",
"species",
"phone",
"country",
"birth_date",
"loyalty_tier",
"peanut_points",
"preferences",
"marketing_opt_in",
"created_at"
FROM "guest"
WHERE "email" = ANY($1)
ORDER BY "last_name" ASC, "guest_id" ASC
/* op:desk.lookup_herd */;
-- → 2 rows
Shift report
- Verified
= ANY($1)and/* op:... */tags statically withpool.compile() - Enforced a 1-RTT pipeline budget with
pool.trace() - Proved index usage and ruled out sequential scans with
pool.explain() - Generated a deterministic SVG schema diagram in pure Rust with
pg.to_svg_erd()
Try it yourself
Run the entire book's test suite right now against live PostgreSQL:
uv run --no-sync pytest tests/docs/test_examples.py -v
Every single chapter from 1 to 20 executes, verifies its # => outputs, and compares every wire SQL statement against examples/__wire__/.
Go deeper: tests/integration/plans/test_plans.py · tests/README.md (live PostgreSQL test suites & snapshots)
Note
Also in pgdorm: Reuse pgdorm.testing (postgres_container, TestDB, assert_compiles) in your own pytest conftest.py — see the Library Authors Guide and Typing & Testing Reference.
Sticky note from Management
"You made it to sunrise. Every room is booked, zero double bookings, 1-RTT pipelines, and CI is green. Go get a pastel de nata — you earned it."
← PreviousChapter 19 · Renovating While OpenChapter 19 · Lock-Safe Online Migrations