Testing data pipelines and migrations
A migration runs once and cannot be undone by a code review. A pipeline runs every night on data nobody chose. Test both against data you built to be awkward.
The migration has run and the column is NOT NULL with a default of 'web'. A checkout server that still runs the old code (it never mentions channel) places an order with the idempotency key pos-20. What does the row's channel contain?
Two kinds of change that tests rarely see
A unit test checks code. Two things in a system are not code and still decide whether it works: the shape of the data (tables, columns, constraints) and the content of the data (the rows). Code reads both, so when either changes, code that was correct becomes wrong without a line of it being edited.
Two jobs change them on purpose:
- A migration changes the shape, and usually rewrites content to fit. It runs once per environment. If it goes wrong on production there is no second run to learn from; the best case is a restore.
- A pipeline moves content from one place to another on a schedule, here the nightly order export to the warehouse. It runs a thousand times, on data that has changed since the last run, and a bad night is quiet because the output still looks like data.
Both are code, so both can be tested like code. What makes them hard is that the interesting inputs are rows in a database, the interesting failures are about order and repetition (what if this runs twice, what if it runs in the middle of a deploy), and the output is another database that nobody reads closely. This chapter builds the tests on the lab’s own pieces, a real SQLite file from Integration tests with a real database, and uses the fresh-world-per-test habit from Test data and fixtures.
What the lab gives you
labs/testing/migrations/ holds two numbered files, applied in name order by scripts/migrate.py:
| File | What it does |
|---|---|
001_add_orders_channel.sql |
ALTER TABLE orders ADD COLUMN channel TEXT; (nullable), then one UPDATE that sets pos where idempotency_key LIKE 'pos-%' and web otherwise |
002_orders_channel_not_null.sql |
Rebuilds orders with channel TEXT NOT NULL DEFAULT 'web' CHECK (channel IN ('web', 'pos')), copies rows with COALESCE(channel, 'web'), drops the old table, renames the new one, recreates the orders_key index |
The second file is a rebuild because SQLite cannot add a constraint to an existing column. The SQLite documentation (read 2026-11-24) gives the same recipe, create a new table, copy, drop, rename, as the way to make “arbitrary changes to the schema design”, and says to do it inside one transaction. The shape is common beyond SQLite: expand the schema in a way old code tolerates, move the data, then tighten.
scripts/migrate.py records each applied file in a table, schema_migrations, and runs each file in its own transaction. Its two public behaviours are migrate(path), which returns the names of the files it applied, and the command line scripts/migrate.py DB [--status].
scripts/export_orders.py writes order_id,created_at,status,total_kobo,lines for orders in a window of two Lagos dates, --from inclusive and --to exclusive. Lagos is UTC+1 all year, so the Lagos day of 22 November runs from 23:00 UTC on the 21st up to, but not including, 23:00 UTC on the 22nd. Amounts are integer kobo.
Testing a migration: five questions
Write one test for each question. A migration that passes all five is not proved correct, but the five cover the failures that actually reach production.
1. Does it apply, in order, and does it remember? Build a database the way the old app left it, run migrate, and assert the two names came back in order and sit in schema_migrations. This is the cheapest test and catches a misnamed file, a file the glob misses and a recorded-twice bug.
2. Is every row still there, unchanged? Before the migration, take a snapshot: the row count, and a checksum over the columns that existed before. After, take the same snapshot and compare. The checksum matters because a table rebuild that copies the wrong column order, truncates a string or rounds an integer keeps the count and loses the data. Hash the old columns only; the new column is checked separately. Order the rows (ORDER BY id) or the hash will change for no reason.
def snapshot(path):
with closing(sqlite3.connect(path)) as conn:
rows = conn.execute(
"SELECT id, idempotency_key, status, total_kobo, charge_id, created_at FROM orders ORDER BY id"
).fetchall()
return len(rows), hashlib.sha256(repr(rows).encode()).hexdigest()
3. Is the backfill right for the awkward rows? A backfill is a rule, and a rule is tested at its edges like the boundaries in Choosing cases. The lab’s rule is LIKE 'pos-%'. Build keys on both sides of every edge: web-1, pos-17, posh-19 (starts with pos but is not a tablet key) and POS-18 (upper case). The last one is a finding: SQLite’s LIKE ignores case for ASCII letters, so the migration labels POS-18 as pos. Whether that is right is a business question, but a test should make the answer visible, so the test pins it with a comment.
4. Does a second run change nothing? Run migrate twice. The second call must return an empty list and the snapshot, and the channels, must be identical. Add a harsher version: run the file’s SQL by hand a second time, skipping schema_migrations. It fails with duplicate column name, which is the right thing to happen, and the test asserts the database is unchanged afterwards. Idempotent here means the tool refuses to repeat the work, not that the SQL could be repeated safely; the lesson Idempotency and exactly-once shows why that distinction matters whenever something retries.
5. Does a failure leave the database as it was? Write a second migration directory with a copy of 001 and a deliberately broken 002: its first statement adds a column and its second updates a table that does not exist. Point migrate.MIGRATIONS at it with monkeypatch, expect OperationalError, and then assert that 001 committed, the new column from 002 is absent (its first statement was rolled back) and only 001 is recorded. SQLite runs DDL inside transactions, so this works. Not every database does: on engines where a schema change commits at once, a half-applied migration is possible and this test needs to look different. Write it for the engine you run.
The deploy window: old code on new schema, new code on old schema
A migration test that stops at the database proves the database. A deploy has a middle, when old and new code run against one schema, and the two bad pairings fail differently.
| Pairing | What happens in the lab | How it fails |
|---|---|---|
| New code, old schema | A query that selects channel before the migration has run raises no such column: channel |
Loudly, on the first request. Safe in the sense that someone notices. Fixed by the rule: migrate first, then deploy |
| Old code, new schema | place_order never mentions channel; the insert succeeds because of the default; every order is labelled web |
Silently. The data is wrong and nothing crashes |
Test both. The first is one assertion with pytest.raises. The second is the test that matters: run place_order from the real checkout code on a migrated database with the key pos-20 and read the channel back. It is web. The backfill rule lives in 001’s UPDATE and nowhere else.
There is a third pairing in the middle of the migration itself. If 001 has run and 002 has not, the column is nullable with no default, and old code writes NULL. Then 002 runs with COALESCE(channel, 'web'), and a tablet order written in that gap becomes web for good. The test builds it by applying only 001 (a directory with only that file), placing a pos-21 order with old code, restoring the full directory, migrating again, and reading the channel.
These tests do not say the migration is wrong. They say what a team must decide before shipping: either the checkout code sends channel itself in the same release (so the rule is not in the database), or a follow-up backfill runs after the last old server is gone, or the team accepts a window of mislabelled rows and records its size. The professional name for the cure is expand and contract: add the column (expand), ship code that writes it, backfill what is left, and only then add the constraint (contract). The Legacy Migrations course covers it in full; its chapter on expand, backfill and contract is planned, so the title is plain text for now. Sadalage and Fowler’s Evolutionary Database Design in the reading is the classic account.
A test only sees the data you built
The fixture for these tests, old_db, is five orders with chosen keys and times, on a fresh file from tmp_path. That is its strength: every row is there for a reason. It is also the limit. Real production has rows nobody imagined, and a table of 40 million rows can take a lock that a table of five never does. A test on five rows proves the logic. It does not prove the migration runs in an hour on production, so rehearse the real thing on a copy of production-shaped data (anonymised) and record how long it took and the row counts before and after. Treat that run as the last test, not as a substitute for the first five.
Testing a pipeline: a function of the database
The nightly export reads orders and writes a file. The test-friendly way to see it is as a function from database state and a window to a file. Give it a database you built, call it, parse the CSV, assert. No clock, no network, no schedule. export_orders(db_path, out, start, end) already has that shape, with an io.StringIO standing in for stdout.
What to put in the database is the whole craft. Each row type below is a bug someone has shipped.
- An empty window. The right output is the header and nothing else. A wrong time zone or a broken filter also produces zero rows, and the test makes zero a deliberate answer.
- The edges of the Lagos day. Orders at 22:59:59 UTC and 23:00:00 UTC on the evening before, and the same pair at the end. The first is the previous Lagos day, the second is the first second of this one. The window is a half-open interval, so the end is excluded; this is the same boundary reasoning as the ₦10,000 discount tier.
- A row with nothing underneath. Every column of
ordersisNOT NULL, so a true null cannot be stored. The nearest real case is an order with noorder_linesrows. The export reportslinesas zero. The test pins that, and the data-quality check below names it. - A duplicate.
orders_keyis a plain index, not aUNIQUEone (the database chapter records it and the concurrency chapter closes it), so two orders can carry the same idempotency key. The export writes both. The test says so, so nobody is surprised when the warehouse counts two sales. - A late order. An order whose
created_atis inside yesterday’s window but which was committed after the export ran, for example a slow payment retry that finishes at 00:03. The first night’s file never contained it, and tomorrow’s window does not cover it. - A stamp in another offset.
created_atis stored as text and the export filters by comparing text. Text compares character by character, so2026-11-22T23:30:00+01:00(which is 22:30 UTC, inside the day) sorts after2026-11-22T22:59:59+00:00and is cut off. The lab’s checkout code always writes UTC, so this cannot happen from the app today. The test is markedxfail(strict=True): it records a real weakness (anything that writes another offset will lose rows) without failing the build, and turns red the day someone fixes it so the marker comes off. That is the same technique the database chapter used for the unique key.
Make the load safe to repeat
Late rows and corrections mean the same day gets exported again. The question then moves to the other end of the pipe. A loader that appends will double count; a loader that upserts by order id will not. The lab chapter adds a 30-line scripts/warehouse_load.py with an INSERT ... ON CONFLICT (order_id) DO UPDATE, and three tests:
- Load the same file twice: one row per order.
- Export a day, load it, add a late order, load the same day’s export again: the late order is there and the earlier row is not duplicated. The fix for lateness is not a cleverer export but an export of overlapping windows and a loader that does not mind.
- Change a total in the source, export and load again: the warehouse holds the corrected value, once.
Two data-quality checks
A test runs your code on rows you chose. A data-quality check runs on the real rows each night and says whether they are fit to ship. The tools the industry uses for this, dbt’s unique and not_null tests and Great Expectations, are in the reading; the idea fits in a function. The lab chapter adds scripts/order_quality.py with two:
duplicate_keys: idempotency keys on more than one order in the window. It would have caught the double orders from the race the starter code has, hours after they happened rather than weeks.orders_without_lines: orders with no lines, found with aLEFT JOIN ... WHERE l.order_id IS NULL.
Each returns a list of problems; an empty list means pass. Test each on bad data (it names the offender) and on clean data (it returns nothing). The second kind of test is easy to forget, and it is the one that catches a check that always cries wolf. Decide in advance what a failure does. A check that only logs is ignored by week three. For a count of duplicates above zero the safe default is to stop the load and page the owner; for a softer rule, such as a sudden fall in rows, hold the file for a person to release.
What the tests cannot tell you
Your tests ran on SQLite. If the warehouse is another engine, it will have its own types, time zones and upsert syntax, and a green test does not prove the load there. The answer is the same as for any integration test: a thin test of the real loader against the real engine, plus the nightly checks. The tests here prove the logic. The checks watch the data.
You will migrate a database the way the app left it, write the tests above, add a warehouse loader and two quality checks, and watch the old-code-on-new-schema gap appear as a failing assertion you can read. Work from labs/testing. The migrations and the two scripts (migrate.py, export_orders.py) are already there; you write the rest. The tests build their databases in tmp_path. Steps 1 and 7 use data/pipeline.sqlite, a scratch file you delete at the end.
1. Migrate a copy by hand.
cd labs/testing
mkdir -p data && rm -f data/pipeline.sqlite
.venv/bin/python - <<'EOF'
from datetime import datetime
from checkout.db import Database
db = Database("data/pipeline.sqlite")
db.seed()
lines = [{"product_id": 2, "qty": 1, "unit_price_kobo": 350_000}]
for key, at in [("web-1", "2026-11-22T08:00:00+00:00"), ("pos-17", "2026-11-22T10:30:00+00:00"),
("web-2", "2026-11-22T23:30:00+00:00")]:
db.save_order(key, 376_250, "ch_x", datetime.fromisoformat(at), lines)
EOF
.venv/bin/python scripts/migrate.py data/pipeline.sqlite --status
.venv/bin/python scripts/migrate.py data/pipeline.sqlite
.venv/bin/python scripts/migrate.py data/pipeline.sqlite
.venv/bin/python scripts/migrate.py data/pipeline.sqlite --statusThe first --status lists 001_add_orders_channel.sql and 002_orders_channel_not_null.sql. The first run prints applied: 001_add_orders_channel.sql, 002_orders_channel_not_null.sql. The second prints applied: nothing, and the last --status prints up to date. The tool refuses to repeat work it has recorded.
2. The migration tests: apply, rows, backfill, repeat.
Create tests/integration/test_migrations.py. The imports at the top are used by later steps; if you run ruff before step 3 it will warn that shutil is unused.
"""Migration tests: a real sqlite file, migrated by scripts/migrate.py."""
import hashlib
import shutil
import sqlite3
import sys
from contextlib import closing
from datetime import datetime, timezone
from pathlib import Path
import pytest
SCRIPTS = Path(__file__).resolve().parents[2] / "scripts"
sys.path.insert(0, str(SCRIPTS))
import migrate # noqa: E402
from checkout.db import Database # noqa: E402
from checkout.orders import place_order # noqa: E402
LINES = [{"product_id": 2, "qty": 1, "unit_price_kobo": 350_000}]
OLD_COLUMNS = "id, idempotency_key, status, total_kobo, charge_id, created_at"
def utc(text):
return datetime.fromisoformat(text).astimezone(timezone.utc)
@pytest.fixture
def old_db(tmp_path):
"""A database as the app made it before the migrations, with five orders."""
db = Database(str(tmp_path / "old.sqlite"))
db.seed()
for key, at in [
("web-1", "2026-11-22T08:00:00+00:00"),
("pos-17", "2026-11-22T10:30:00+00:00"),
("POS-18", "2026-11-22T11:00:00+00:00"),
("posh-19", "2026-11-22T12:00:00+00:00"),
("web-2", "2026-11-22T23:30:00+00:00"),
]:
db.save_order(key, 376_250, "ch_x", utc(at), LINES)
return db
def snapshot(path):
"""Row count and a checksum over the columns that existed before the migration."""
with closing(sqlite3.connect(path)) as conn:
rows = conn.execute(f"SELECT {OLD_COLUMNS} FROM orders ORDER BY id").fetchall()
return len(rows), hashlib.sha256(repr(rows).encode()).hexdigest()
def channels(path):
with closing(sqlite3.connect(path)) as conn:
return dict(conn.execute("SELECT idempotency_key, channel FROM orders"))
def test_migrations_apply_in_order_and_are_recorded(old_db):
assert migrate.migrate(old_db.path) == ["001_add_orders_channel.sql", "002_orders_channel_not_null.sql"]
with closing(sqlite3.connect(old_db.path)) as conn:
done = [r[0] for r in conn.execute("SELECT version FROM schema_migrations ORDER BY version")]
assert done == ["001_add_orders_channel.sql", "002_orders_channel_not_null.sql"]
def test_no_row_is_lost_or_changed(old_db):
before = snapshot(old_db.path)
migrate.migrate(old_db.path)
assert snapshot(old_db.path) == before
def test_the_backfill_reads_the_key_prefix(old_db):
migrate.migrate(old_db.path)
assert channels(old_db.path) == {
"web-1": "web",
"pos-17": "pos",
"POS-18": "pos", # LIKE ignores ASCII case: the migration treats POS- as pos-
"posh-19": "web",
"web-2": "web",
}
def test_running_twice_changes_nothing(old_db):
migrate.migrate(old_db.path)
once = snapshot(old_db.path), channels(old_db.path)
assert migrate.migrate(old_db.path) == []
assert (snapshot(old_db.path), channels(old_db.path)) == once.venv/bin/pytest tests/integration/test_migrations.py -q -p no:randomly4 passed. Each test built its own five-order file. The POS-18 line is the one to read twice: the test passes because it pins what the migration does, which is not necessarily what the business wants.3. Hand-run SQL, a failing migration, and the constraint.
Append:
def test_a_file_run_by_hand_a_second_time_fails_and_changes_nothing(old_db):
migrate.migrate(old_db.path)
before = snapshot(old_db.path)
first = migrate.MIGRATIONS + "/001_add_orders_channel.sql"
with closing(sqlite3.connect(old_db.path)) as conn:
with pytest.raises(sqlite3.OperationalError, match="duplicate column name"):
conn.executescript(open(first).read())
assert snapshot(old_db.path) == before
def test_a_failing_migration_leaves_the_database_as_it_was(old_db, tmp_path, monkeypatch):
folder = tmp_path / "migrations"
folder.mkdir()
shutil.copy(migrate.MIGRATIONS + "/001_add_orders_channel.sql", folder)
(folder / "002_broken.sql").write_text(
"ALTER TABLE orders ADD COLUMN region TEXT;\nUPDATE no_such_table SET x = 1;\n"
)
monkeypatch.setattr(migrate, "MIGRATIONS", str(folder))
with pytest.raises(sqlite3.OperationalError, match="no such table"):
migrate.migrate(old_db.path)
with closing(sqlite3.connect(old_db.path)) as conn:
columns = [r[1] for r in conn.execute("PRAGMA table_info(orders)")]
done = [r[0] for r in conn.execute("SELECT version FROM schema_migrations")]
assert "channel" in columns # 001 committed on its own
assert "region" not in columns # 002's first statement was rolled back
assert done == ["001_add_orders_channel.sql"]
def test_the_new_schema_refuses_an_unknown_channel(old_db):
migrate.migrate(old_db.path)
with closing(sqlite3.connect(old_db.path)) as conn:
with pytest.raises(sqlite3.IntegrityError, match="CHECK constraint failed"):
conn.execute("UPDATE orders SET channel = 'phone' WHERE idempotency_key = 'web-1'").venv/bin/pytest tests/integration/test_migrations.py -q -p no:randomly7 passed. The broken migration raised and left channel in place (001 committed in its own transaction) and region out (002’s first statement was undone). That is the guarantee migrate.py states in its docstring, now checked.4. Old code and new code, either side of the migration.
Append:
def test_new_code_on_the_old_schema_fails_loudly(old_db):
with closing(sqlite3.connect(old_db.path)) as conn:
with pytest.raises(sqlite3.OperationalError, match="no such column: channel"):
conn.execute("SELECT channel FROM orders")
def test_old_code_on_the_new_schema_still_places_orders(old_db, payments, clock):
migrate.migrate(old_db.path)
order, created = place_order(old_db, payments, clock, [{"product_id": 2, "qty": 1}], "web-3")
assert created
assert channels(old_db.path)["web-3"] == "web"
def test_old_code_on_the_new_schema_labels_a_till_order_web(old_db, payments, clock):
migrate.migrate(old_db.path)
place_order(old_db, payments, clock, [{"product_id": 2, "qty": 1}], "pos-20")
# place_order sends no channel, so the default applies. The backfill rule is not applied to new rows.
assert channels(old_db.path)["pos-20"] == "web"
def test_a_row_written_between_the_two_migrations_is_labelled_web(old_db, tmp_path, monkeypatch, payments, clock):
folder = tmp_path / "only_001"
folder.mkdir()
shutil.copy(migrate.MIGRATIONS + "/001_add_orders_channel.sql", folder)
monkeypatch.setattr(migrate, "MIGRATIONS", str(folder))
migrate.migrate(old_db.path) # channel exists, nullable, no default
place_order(old_db, payments, clock, [{"product_id": 2, "qty": 1}], "pos-21")
assert channels(old_db.path)["pos-21"] is None
monkeypatch.undo()
migrate.migrate(old_db.path) # 002 runs: COALESCE(channel, 'web')
assert channels(old_db.path)["pos-21"] == "web".venv/bin/pytest tests/integration/test_migrations.py -q -p no:randomly11 passed. Two of those tests assert a behaviour you may not want: a tablet order labelled web, twice. They pass because they describe the gap. Write down in a sentence what you would change in the checkout code, or in the rollout order, to close it.5. Add the loader and the two checks.
Create scripts/warehouse_load.py:
"""Load an orders CSV (from export_orders.py) into a warehouse table, safe to repeat.
.venv/bin/python scripts/warehouse_load.py warehouse.sqlite orders.csv
"""
import csv
import sqlite3
import sys
from typing import IO
CREATE = """
CREATE TABLE IF NOT EXISTS warehouse_orders (
order_id TEXT PRIMARY KEY,
created_at TEXT NOT NULL,
status TEXT NOT NULL,
total_kobo INTEGER NOT NULL,
lines INTEGER NOT NULL
)
"""
UPSERT = """
INSERT INTO warehouse_orders (order_id, created_at, status, total_kobo, lines)
VALUES (:order_id, :created_at, :status, :total_kobo, :lines)
ON CONFLICT (order_id) DO UPDATE SET
created_at = excluded.created_at, status = excluded.status,
total_kobo = excluded.total_kobo, lines = excluded.lines
"""
def load_orders(conn: sqlite3.Connection, source: IO[str]) -> int:
"""Upsert every row by order_id. Returns the number of rows read."""
conn.execute(CREATE)
rows = list(csv.DictReader(source))
with conn:
conn.executemany(UPSERT, rows)
return len(rows)
if __name__ == "__main__":
with sqlite3.connect(sys.argv[1]) as connection, open(sys.argv[2], newline="") as handle:
print(f"{load_orders(connection, handle)} rows loaded")Create scripts/order_quality.py:
"""Two data-quality checks on the orders a nightly export would send.
Each returns a list of problems; an empty list means the check passed.
"""
import sqlite3
from contextlib import closing
from datetime import date
from typing import List
from export_orders import lagos_midnight_utc
def _window(start: date, end: date) -> tuple:
return lagos_midnight_utc(start), lagos_midnight_utc(end)
def duplicate_keys(db_path: str, start: date, end: date) -> List[str]:
"""Idempotency keys that appear on more than one order in the window."""
lo, hi = _window(start, end)
with closing(sqlite3.connect(db_path)) as conn:
rows = conn.execute(
"SELECT idempotency_key, COUNT(*) FROM orders WHERE created_at >= ? AND created_at < ?"
" GROUP BY idempotency_key HAVING COUNT(*) > 1 ORDER BY idempotency_key",
(lo, hi),
).fetchall()
return [f"key {key} on {n} orders" for key, n in rows]
def orders_without_lines(db_path: str, start: date, end: date) -> List[str]:
"""Orders in the window that have no order_lines rows."""
lo, hi = _window(start, end)
with closing(sqlite3.connect(db_path)) as conn:
rows = conn.execute(
"SELECT o.id FROM orders o LEFT JOIN order_lines l ON l.order_id = o.id"
" WHERE o.created_at >= ? AND o.created_at < ? AND l.order_id IS NULL ORDER BY o.id",
(lo, hi),
).fetchall()
return [f"order {row[0]} has no lines" for row in rows].venv/bin/python -c "import sys; sys.path.insert(0, 'scripts'); import warehouse_load, order_quality; print('ok')"ok. Both modules import; order_quality reuses lagos_midnight_utc from the export so the checks and the export cannot disagree about where a Lagos day starts.6. Test the export, the load and the checks.
Create tests/integration/test_order_export.py:
"""The nightly export, the warehouse load and two data-quality checks."""
import csv
import io
import sqlite3
import sys
from contextlib import closing
from datetime import date, datetime
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts"))
import export_orders # noqa: E402
import order_quality # noqa: E402
import warehouse_load # noqa: E402
LINES = [{"product_id": 2, "qty": 1, "unit_price_kobo": 350_000}]
DAY, NEXT_DAY = date(2026, 11, 22), date(2026, 11, 23) # the Lagos day 22 November
def at(text):
return datetime.fromisoformat(text)
def export(db, start=DAY, end=NEXT_DAY):
out = io.StringIO()
export_orders.export_orders(db.path, out, start, end)
return out.getvalue()
def rows_of(text):
return list(csv.DictReader(io.StringIO(text)))
def test_an_empty_window_is_a_header_and_nothing_else(db):
assert export(db) == "order_id,created_at,status,total_kobo,lines\n"
def test_the_lagos_day_starts_at_2300_utc_and_ends_one_second_before_the_next(db):
for key, when in [
("before", "2026-11-21T22:59:59+00:00"),
("first", "2026-11-21T23:00:00+00:00"),
("last", "2026-11-22T22:59:59+00:00"),
("after", "2026-11-22T23:00:00+00:00"),
]:
db.save_order(key, 1_000, "ch_1", at(when), LINES)
got = [r["created_at"] for r in rows_of(export(db))]
assert got == ["2026-11-21T23:00:00+00:00", "2026-11-22T22:59:59+00:00"]
def test_rows_come_out_in_time_order_with_a_line_count(db):
db.save_order("k2", 2_000, "ch_2", at("2026-11-22T12:00:00+00:00"), LINES + LINES)
db.save_order("k1", 1_000, "ch_1", at("2026-11-22T08:00:00+00:00"), LINES)
rows = rows_of(export(db))
assert [(r["total_kobo"], r["lines"]) for r in rows] == [("1000", "1"), ("2000", "2")]
def test_an_order_with_no_lines_exports_with_zero_lines(db):
db.save_order("k1", 1_000, "ch_1", at("2026-11-22T08:00:00+00:00"), [])
assert rows_of(export(db))[0]["lines"] == "0"
@pytest.mark.xfail(strict=True, reason="created_at is compared as text; a +01:00 stamp sorts after a +00:00 one")
def test_a_stamp_written_with_a_local_offset_lands_in_the_right_day(db):
# 23:30 on 22 November at +01:00 is 22:30 UTC: inside the Lagos day 22 November.
db.save_order("k1", 1_000, "ch_1", at("2026-11-22T23:30:00+01:00"), LINES)
assert len(rows_of(export(db))) == 1
def test_a_duplicate_key_exports_two_rows_and_the_check_names_the_key(db):
db.save_order("same", 1_000, "ch_1", at("2026-11-22T08:00:00+00:00"), LINES)
db.save_order("same", 1_000, "ch_1", at("2026-11-22T08:00:01+00:00"), LINES)
assert len(rows_of(export(db))) == 2
assert order_quality.duplicate_keys(db.path, DAY, NEXT_DAY) == ["key same on 2 orders"]
def test_the_check_for_missing_lines_names_the_order(db):
order = db.save_order("k1", 1_000, "ch_1", at("2026-11-22T08:00:00+00:00"), [])
assert order_quality.orders_without_lines(db.path, DAY, NEXT_DAY) == [f"order {order['id']} has no lines"]
def test_clean_data_passes_both_checks(db):
db.save_order("k1", 1_000, "ch_1", at("2026-11-22T08:00:00+00:00"), LINES)
assert order_quality.duplicate_keys(db.path, DAY, NEXT_DAY) == []
assert order_quality.orders_without_lines(db.path, DAY, NEXT_DAY) == []
@pytest.fixture
def warehouse():
with closing(sqlite3.connect(":memory:")) as conn:
yield conn
def stored(conn):
return conn.execute("SELECT order_id, total_kobo FROM warehouse_orders ORDER BY order_id").fetchall()
def test_loading_the_same_file_twice_leaves_one_copy_of_each_row(db, warehouse):
db.save_order("k1", 1_000, "ch_1", at("2026-11-22T08:00:00+00:00"), LINES)
text = export(db)
warehouse_load.load_orders(warehouse, io.StringIO(text))
warehouse_load.load_orders(warehouse, io.StringIO(text))
assert len(stored(warehouse)) == 1
def test_a_late_order_arrives_when_the_day_is_exported_again(db, warehouse):
db.save_order("k1", 1_000, "ch_1", at("2026-11-22T08:00:00+00:00"), LINES)
warehouse_load.load_orders(warehouse, io.StringIO(export(db))) # the 00:00 run
late = db.save_order("k2", 2_000, "ch_2", at("2026-11-22T22:58:00+00:00"), LINES) # saved after it
assert len(stored(warehouse)) == 1
warehouse_load.load_orders(warehouse, io.StringIO(export(db))) # the next run covers the day again
assert late["id"] in [row[0] for row in stored(warehouse)]
assert len(stored(warehouse)) == 2
def test_a_corrected_row_replaces_the_old_one(db, warehouse):
order = db.save_order("k1", 1_000, "ch_1", at("2026-11-22T08:00:00+00:00"), LINES)
warehouse_load.load_orders(warehouse, io.StringIO(export(db)))
with closing(sqlite3.connect(db.path)) as conn, conn:
conn.execute("UPDATE orders SET total_kobo = 1500 WHERE id = ?", (order["id"],))
warehouse_load.load_orders(warehouse, io.StringIO(export(db)))
assert stored(warehouse) == [(order["id"], 1_500)].venv/bin/pytest tests/integration/test_order_export.py -q10 passed, 1 xfailed, with an XFAIL line for the local-offset test carrying its reason. This run uses random order (pytest-randomly is on), and it passes in any order because each test has its own db file and the warehouse fixture is a fresh in-memory database.
7. Run the real pipeline twice.
.venv/bin/python scripts/export_orders.py data/pipeline.sqlite --from 2026-11-22 --to 2026-11-23 > data/orders.csv
cat data/orders.csv
.venv/bin/python scripts/warehouse_load.py data/warehouse.sqlite data/orders.csv
.venv/bin/python scripts/warehouse_load.py data/warehouse.sqlite data/orders.csvThe export prints 2 orders on standard error. The CSV has a header and two rows, for web-1 at 08:00 UTC and pos-17 at 10:30 UTC, each with total_kobo 376250 and lines 1. The third order, web-2 at 23:30 UTC, is not there: 23:30 UTC on 22 November is 00:30 on 23 November in Lagos, so it belongs to the next day’s file. Both loads print 2 rows loaded, and the warehouse still holds two rows.
8. The whole suite.
.venv/bin/pytest -q
.venv/bin/python scripts/migrate.py data/pipeline.sqlite --status
rm -f data/pipeline.sqlite data/warehouse.sqlite data/orders.csvxfailed. On the lab machine, with the starter suite and the two files above, the line read 44 passed, 1 skipped, 1 deselected, 1 xfailed; your total depends on what you added in earlier chapters. The --status line prints up to date, and the last command removes the scratch files.Break the backfill and watch the test catch it. In migrations/001_add_orders_channel.sql change LIKE 'pos-%' to LIKE 'pos%' and run .venv/bin/pytest tests/integration/test_migrations.py -q -p no:randomly.
On the lab machine one test failed, test_the_backfill_reads_the_key_prefix, with {'posh-19': 'pos'} != {'posh-19': 'web'}, and the other ten passed. The row-count and checksum test could not see the fault, because the old columns were untouched. Only the test with an awkward key did. Put pos-% back and rerun to see all eleven pass.
9. Put the lab back, after the break below. Later chapters count tests from the starter state. Once you have restored migrations/001_add_orders_channel.sql (git checkout migrations/ does it), remove what you added:
git checkout migrations/
rm -rf tests/integration/test_migrations.py tests/integration/test_order_export.py scripts/warehouse_load.py scripts/order_quality.py data/pipeline.sqlite data/warehouse.sqlite data/orders.csv .hypothesis
.venv/bin/pytest -q23 passed, 1 skipped, 1 deselected, the starter state.Anele's nightly export sends one Lagos day to the warehouse at 00:30. Orders are sometimes committed after midnight with a created_at inside the day that has ended: slow payment retries, tablets that sync late. About 40 a night (illustrative) are missing from their day's file and appear nowhere. Siya's channel report is wrong by that much every morning. Anele must choose a fix.
- POST Evolutionary Database Design Pramod Sadalage and Martin Fowler, 2016
The standard account of treating every schema change as a small, versioned migration, with transition phases so old and new code can coexist. Read the sections on migrations and on transition phases; skip the team-process sections on a first read.
- POST Online migrations at scale Jacqueline Xu (Stripe), 2017
A four-step pattern for moving data under live traffic: dual write, backfill, switch reads, switch writes and remove the old data. The test you would write for each step is the chapter's list of five questions at larger scale. Read all of it; it is short.
- POST Scientist: Measure Twice, Cut Over Once GitHub Engineering, 2016
Runs the old and the new code on the same production input and records any difference while still returning the old answer. It is how you test a migration or an export rewrite on data you did not imagine. Read for the idea; the library is Ruby.
- DOC Data tests dbt Labs
The four built-in generic tests (unique, not_null, accepted_values, relationships) and singular tests written as a query that returns the failing rows. Compare them with the two checks in the lab. Read the first two sections; skip the configuration reference. Page read 2026-11-24.
- DOC Great Expectations documentation Great Expectations
The Python library for declaring expectations about data and validating a batch against them. Read the introduction to see what a check framework adds to a hand-written function (a vocabulary, reports, scheduling) and decide whether you need it. Page read 2026-11-24; its API changes between releases.
- DOC ALTER TABLE SQLite project
Section 8, 'Making Other Kinds Of Table Schema Changes', gives the create, copy, drop, rename recipe that migration 002 follows, including the transaction and the foreign-key steps. Read it before writing a SQLite migration of your own; skip the rest.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.