Lab: End-to-End Pipeline Tests with Disposable Databases
Test a PostgreSQL-to-warehouse pipeline end to end with pytest and Testcontainers: start throwaway source and target databases, seed known rows, run the pipeline, assert the exact output and tear everything down. Then smoke-test a deployment on one recent day, watch it catch a time-zone bug that CI missed, and publish only after the fix.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: The pipeline
- Step 2: Disposable databases as pytest fixtures
- Step 3: Assert on exact outputs
- Step 4: Deploy and smoke-test before publishing
- Step 5: Reproduce the bug in a test, fix it, publish
- Check your understanding
- Apply it
- Review prompt
Lessons of Data Quality & Testing
- From Quality Dimensions to Concrete Checks Concept · 20 min
- Lab: Declarative Checks on Raw and Modeled Data Lab · 30 min
- Lab: Unit Tests for Transformation Logic Lab · 25 min
- Write-Audit-Publish and Quarantine Patterns Worked example · 25 min
- Lab: End-to-End Pipeline Tests with Disposable Databases Lab · 25 min
- Check: Triage a Failing Quality Suite Knowledge check · 10 questions
What you will learn
- Test a pipeline end to end against disposable containerized source and target databases with seeded data, assert on its outputs, and smoke-test each deployment before its data is published.
01. Goal and setup
A unit test checks one piece of logic on hand-made rows. An end-to-end test runs the whole pipeline as it will run in production: it connects to a real source database, reads, transforms, writes to a real target, and then checks what landed. That is where the faults hide that unit tests cannot see: SQL that a mock would accept, a type that changes on the way, a transaction that does not commit.
Each test run needs databases in a known state, and shared test databases are not: someone else's data changes underneath you, and two runs at once disturb each other. Testcontainers is a library that starts a fresh database in a Docker container for your tests and removes it afterwards. Every run gets the same empty engine, of the same kind and version as production.
You need Docker and Python 3.10 or later. The lab was tested with Python 3.12, PostgreSQL 17 (postgres:17-alpine), testcontainers 4.15.0, psycopg 3.3.9 and pytest 9.2.0. Testcontainers pulls the image the first time if it is not already on your machine. LAB is a prefix for container names, so that you can find and remove them.
psycopg[binary]==3.3.9
pytest==9.2.0
testcontainers==4.15.0mkdir dq-e2e && cd dq-e2e
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
mkdir -p tests
export LAB=dq-labTestcontainers normally also starts a small helper container, Ryuk, that removes your test containers even if the test process crashes. Keep it on. We ran this lab with TESTCONTAINERS_RYUK_DISABLED=true because our test machine was not allowed to download images; the output is the same either way.
02. Step 1: The pipeline
The pipeline reads one day of orders from the shop's database, excludes cancelled orders, sums revenue per country, and writes the result to analytics.daily_revenue in the warehouse. The write deletes the day's rows and inserts the new ones inside one transaction (psycopg commits when the with block ends), so a rerun replaces the day instead of adding to it. It looks correct. Keep it in mind; it has a bug that the first tests will not find.
"""Load one day of shop orders into the warehouse table daily_revenue."""
import sys
import psycopg
DAY_ROWS = """
SELECT ordered_at::date AS day, country, count(*) AS orders,
round(sum(amount_cents) / 100.0, 2) AS revenue
FROM shop.orders
WHERE ordered_at::date = %s AND status <> 'cancelled'
GROUP BY 1, 2 ORDER BY 2"""
def run(source_dsn, target_dsn, day, schema="analytics"):
with psycopg.connect(source_dsn) as src:
rows = src.execute(DAY_ROWS, [day]).fetchall()
with psycopg.connect(target_dsn) as tgt: # one transaction, committed at the end
tgt.execute(f"CREATE SCHEMA IF NOT EXISTS {schema}")
tgt.execute(f"""CREATE TABLE IF NOT EXISTS {schema}.daily_revenue (
day date, country text, orders int, revenue numeric(12, 2),
PRIMARY KEY (day, country))""")
tgt.execute(f"DELETE FROM {schema}.daily_revenue WHERE day = %s", [day])
with tgt.cursor() as cur:
cur.executemany(
f"INSERT INTO {schema}.daily_revenue VALUES (%s, %s, %s, %s)", rows)
return len(rows)
if __name__ == "__main__":
source, target, day = sys.argv[1:4]
print(f"loaded {run(source, target, day)} rows for {day}")03. Step 2: Disposable databases as pytest fixtures
A pytest fixture is a function that prepares something a test needs; a test asks for it by naming it as an argument. source_url and target_url each start a PostgreSQL container. Their scope is session, so each container starts once for the whole test run, not once per test, which keeps the suite fast. The with statement stops and removes the container when the session ends, even if tests fail. driver=None makes get_connection_url() return a plain postgresql:// URL that psycopg accepts.
seeded runs before every test: it recreates the source table with five known orders and empties the warehouse, so each test starts from the same state and no test depends on another. In testcontainers 4.15 the PostgreSQL module lives in testcontainers.community.postgres; the older testcontainers.postgres still works but prints a deprecation warning.
import os
import psycopg
import pytest
from testcontainers.community.postgres import PostgresContainer
PREFIX = os.environ.get("LAB", "dq-lab")
SEED = """
DROP SCHEMA IF EXISTS shop CASCADE;
CREATE SCHEMA shop;
CREATE TABLE shop.orders (order_id int PRIMARY KEY, ordered_at timestamptz,
country text, status text, amount_cents int);
INSERT INTO shop.orders VALUES
(1, '2026-11-01 23:50+00', 'GB', 'paid', 1000),
(2, '2026-11-02 09:15+00', 'GB', 'paid', 2500),
(3, '2026-11-02 12:40+00', 'GB', 'paid', 1999),
(4, '2026-11-02 18:05+00', 'FR', 'cancelled', 4000),
(5, '2026-11-02 20:30+00', 'FR', 'paid', 3550);
"""
def postgres(role):
"""A throwaway PostgreSQL 17 server, named so that you can spot it in docker ps."""
return PostgresContainer("postgres:17-alpine", driver=None).with_name(
f"{PREFIX}-{role}-{os.getpid()}")
@pytest.fixture(scope="session")
def source_url():
with postgres("source") as pg: # started once per test session ...
yield pg.get_connection_url() # ... and removed when the session ends
@pytest.fixture(scope="session")
def target_url():
with postgres("target") as pg:
yield pg.get_connection_url()
@pytest.fixture
def seeded(source_url, target_url):
"""Give every test the same known source data and an empty warehouse."""
with psycopg.connect(source_url) as con:
con.execute(SEED)
with psycopg.connect(target_url) as con:
con.execute("DROP SCHEMA IF EXISTS analytics CASCADE")
return source_url, target_url[pytest]
testpaths = tests
pythonpath = .04. Step 3: Assert on exact outputs
Because the seed is known, the result is known too, so the tests assert the exact rows: 2 November has one paid order in France and two in Great Britain. Order 4 is cancelled, and order 1 belongs to 1 November. A weaker assertion, such as "the table is not empty" or "the run exited with 0", would pass even if the pipeline dropped or double-counted rows. Two more tests cover a rerun of the same day and a day with no orders.
from decimal import Decimal
import psycopg
import pipeline
def published(target_url):
with psycopg.connect(target_url) as con:
return con.execute("SELECT day::text, country, orders, revenue FROM"
" analytics.daily_revenue ORDER BY day, country").fetchall()
def test_one_day_gives_exact_rows(seeded):
source_url, target_url = seeded
assert pipeline.run(source_url, target_url, "2026-11-02") == 2
assert published(target_url) == [
("2026-11-02", "FR", 1, Decimal("35.50")), # order 4 is cancelled
("2026-11-02", "GB", 2, Decimal("44.99")), # order 1 belongs to 1 November
]
def test_rerun_replaces_instead_of_duplicating(seeded):
source_url, target_url = seeded
pipeline.run(source_url, target_url, "2026-11-02")
pipeline.run(source_url, target_url, "2026-11-02")
assert sum(orders for _, _, orders, _ in published(target_url)) == 3
def test_a_day_without_orders_loads_nothing(seeded):
source_url, target_url = seeded
assert pipeline.run(source_url, target_url, "2026-11-05") == 0
assert published(target_url) == []pytest's full output, with timings, goes to e2e.log; grep shows one line per test. The last command counts the lab's containers after the run.
pytest -v --no-header > e2e.log; echo "pytest exit code: $?"
grep "::" e2e.log
docker ps -a --filter "name=$LAB" --format '{{.Names}}' | wc -lpytest exit code: 0
tests/test_pipeline_e2e.py::test_one_day_gives_exact_rows PASSED [ 33%]
tests/test_pipeline_e2e.py::test_rerun_replaces_instead_of_duplicating PASSED [ 66%]
tests/test_pipeline_e2e.py::test_a_day_without_orders_loads_nothing PASSED [100%]
0All three tests pass, and no container is left: the fixtures removed both databases at the end of the session. On our machine the whole run took about ten seconds, most of it spent starting the two containers. In CI the same command works on any runner that has Docker, such as GitHub's ubuntu-24.04 runners.
05. Step 4: Deploy and smoke-test before publishing
The tests are green, so the pipeline is deployed. But CI only proved the code on seeded data in containers with default settings. Production has its own configuration, credentials and data. A smoke test is a short check that a deployment works in its real environment: here, run the new version on one recent day, write the result to a separate smoke schema, compare it with what the source says, and publish to analytics only if everything agrees.
start_prod.sh starts a long-lived container that stands in for production. Like many real servers in Europe, it is configured with timezone=Europe/Berlin. -p 127.0.0.1::5432 lets Docker pick a free port, and the script exports the two connection URLs. Source it, so that the variables stay in your shell. seed_prod.py creates the shop and warehouse databases and 300 orders.
# A long-lived "production" server, configured like the real one: Europe/Berlin time.
# Run it with "source start_prod.sh" so that the exported variables stay in your shell.
docker run -d --name "$LAB-prod" -e POSTGRES_PASSWORD=lab -p 127.0.0.1::5432 \
postgres:17-alpine -c timezone=Europe/Berlin > /dev/null || return 1
until docker exec "$LAB-prod" pg_isready -h 127.0.0.1 -U postgres > /dev/null 2>&1; do
sleep 1
done
PORT=$(docker port "$LAB-prod" 5432/tcp | head -n 1 | cut -d: -f2)
export PROD_SOURCE="postgresql://postgres:[email protected]:$PORT/shop"
export PROD_TARGET="postgresql://postgres:[email protected]:$PORT/warehouse"
echo "production server is up""""Stand-in for production: a shop database and an empty warehouse on one server."""
import os
import random
from datetime import datetime, timedelta, timezone
import psycopg
admin = os.environ["PROD_SOURCE"].rsplit("/", 1)[0] + "/postgres"
with psycopg.connect(admin, autocommit=True) as con:
for db in ["shop", "warehouse"]:
con.execute(f"DROP DATABASE IF EXISTS {db}")
con.execute(f"CREATE DATABASE {db}")
rng = random.Random(3)
start = datetime(2026, 11, 2, tzinfo=timezone.utc)
rows = [(i, start + timedelta(minutes=rng.randint(0, 3 * 24 * 60 - 1)),
rng.choice(["GB", "FR", "DE"]), rng.choice(["paid"] * 9 + ["cancelled"]),
rng.randint(500, 9000)) for i in range(1, 301)]
with psycopg.connect(os.environ["PROD_SOURCE"]) as con:
con.execute("""CREATE SCHEMA shop;
CREATE TABLE shop.orders (order_id int PRIMARY KEY, ordered_at timestamptz,
country text, status text, amount_cents int)""")
with con.cursor() as cur:
cur.executemany("INSERT INTO shop.orders VALUES (%s, %s, %s, %s, %s)", rows)
tz = con.execute("SHOW timezone").fetchone()[0]
print(f"shop.orders: {len(rows)} rows from 2 to 4 November; server time zone {tz}")smoke.py computes the expected count and revenue for the day straight from the source, with the day's start and end written explicitly in UTC, and compares them with what the pipeline wrote.
"""Smoke-test a deployment on one recent day; publish only if every check passes."""
import os
import sys
import psycopg
import pipeline
SOURCE, TARGET = os.environ["PROD_SOURCE"], os.environ["PROD_TARGET"]
day = sys.argv[1]
loaded = pipeline.run(SOURCE, TARGET, day, schema="smoke") # one day, off to the side
with psycopg.connect(SOURCE) as con: # what the day holds, with explicit UTC bounds
want = con.execute("""
SELECT count(*), round(sum(amount_cents) / 100.0, 2) FROM shop.orders
WHERE ordered_at >= %(day)s::timestamp AT TIME ZONE 'UTC'
AND ordered_at < (%(day)s::timestamp + interval '1 day') AT TIME ZONE 'UTC'
AND status <> 'cancelled'""", {"day": day}).fetchone()
with psycopg.connect(TARGET) as con:
got = con.execute("SELECT sum(orders), sum(revenue) FROM smoke.daily_revenue"
" WHERE day = %s", [day]).fetchone()
checks = [("the pipeline wrote rows", loaded > 0),
(f"order count {got[0]} = source {want[0]}", got[0] == want[0]),
(f"revenue {got[1]} = source {want[1]}", got[1] == want[1])]
for name, ok in checks:
print(f"{'pass' if ok else 'FAIL'} {name}")
if not all(ok for _, ok in checks):
print(f"NOT PUBLISHED: analytics.daily_revenue for {day} is unchanged")
sys.exit(1)
pipeline.run(SOURCE, TARGET, day) # the real publish
print(f"PUBLISHED: {day}")source start_prod.sh
python seed_prod.py
python smoke.py 2026-11-04; echo "exit code: $?"production server is up
shop.orders: 300 rows from 2 to 4 November; server time zone Europe/Berlin
pass the pipeline wrote rows
FAIL order count 108 = source 106
FAIL revenue 4800.20 = source 4665.33
NOT PUBLISHED: analytics.daily_revenue for 2026-11-04 is unchanged
exit code: 1The pipeline wrote rows, so a check of "the job succeeded" would have passed. The numbers are wrong, though, and nothing was published: analytics.daily_revenue does not exist yet in the warehouse, and the exit code 1 stops the deployment. The cause is ordered_at::date. Casting a timestamptz to a date uses the session's time zone, which here is Berlin's, one hour ahead of UTC in November. The pipeline's "4 November" therefore starts at 23:00 UTC on 3 November. The test containers run on UTC, so the tests could not see it.
06. Step 5: Reproduce the bug in a test, fix it, publish
First turn the production fault into a test, so it cannot come back. libpq, the client library under psycopg, accepts an options parameter in the URL; -c TimeZone=Europe/Berlin makes the session behave like production without starting another container.
from decimal import Decimal
import psycopg
import pipeline
# libpq passes "options" to the server: this session runs on Berlin time, like prod.
BERLIN = "?options=-c%20TimeZone%3DEurope%2FBerlin"
def test_day_boundaries_ignore_the_session_time_zone(seeded):
source_url, target_url = seeded
pipeline.run(source_url + BERLIN, target_url, "2026-11-02")
with psycopg.connect(target_url) as con:
rows = con.execute("SELECT country, orders, revenue"
" FROM analytics.daily_revenue").fetchall()
by_country = {country: (orders, revenue) for country, orders, revenue in rows}
assert by_country["FR"] == (1, Decimal("35.50"))
assert by_country["GB"] == (2, Decimal("44.99")) # order 1 is still 1 Novemberpytest -q --tb=short tests/test_time_zone.py | sed -E 's/ in [0-9.]+s$//'F [100%]
=================================== FAILURES ===================================
_______________ test_day_boundaries_ignore_the_session_time_zone _______________
tests/test_time_zone.py:19: in test_day_boundaries_ignore_the_session_time_zone
assert by_country["GB"] == (2, Decimal("44.99")) # order 1 is still 1 November
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
E AssertionError: assert (3, Decimal('54.99')) == (2, Decimal('44.99'))
E
E At index 0 diff: 3 != 2
E Use -v to get more diff
=========================== short test summary info ============================
FAILED tests/test_time_zone.py::test_day_boundaries_ignore_the_session_time_zone
1 failedOrder 1, at 23:50 UTC on 1 November, was counted on 2 November because it is 00:50 in Berlin. Fix the pipeline by converting to UTC before taking the date: ordered_at AT TIME ZONE 'UTC' gives the UTC wall-clock time, whatever the session's setting. Replace pipeline.py with this version, rerun every test, then repeat the smoke test.
"""Load one day of shop orders into the warehouse table daily_revenue."""
import sys
import psycopg
DAY_ROWS = """
SELECT (ordered_at AT TIME ZONE 'UTC')::date AS day, country, count(*) AS orders,
round(sum(amount_cents) / 100.0, 2) AS revenue
FROM shop.orders
WHERE (ordered_at AT TIME ZONE 'UTC')::date = %s AND status <> 'cancelled'
GROUP BY 1, 2 ORDER BY 2"""
def run(source_dsn, target_dsn, day, schema="analytics"):
with psycopg.connect(source_dsn) as src:
rows = src.execute(DAY_ROWS, [day]).fetchall()
with psycopg.connect(target_dsn) as tgt: # one transaction, committed at the end
tgt.execute(f"CREATE SCHEMA IF NOT EXISTS {schema}")
tgt.execute(f"""CREATE TABLE IF NOT EXISTS {schema}.daily_revenue (
day date, country text, orders int, revenue numeric(12, 2),
PRIMARY KEY (day, country))""")
tgt.execute(f"DELETE FROM {schema}.daily_revenue WHERE day = %s", [day])
with tgt.cursor() as cur:
cur.executemany(
f"INSERT INTO {schema}.daily_revenue VALUES (%s, %s, %s, %s)", rows)
return len(rows)
if __name__ == "__main__":
source, target, day = sys.argv[1:4]
print(f"loaded {run(source, target, day)} rows for {day}")pytest -q | sed -E 's/ in [0-9.]+s$//'
python smoke.py 2026-11-04; echo "exit code: $?".... [100%]
4 passed
pass the pipeline wrote rows
pass order count 106 = source 106
pass revenue 4665.33 = source 4665.33
PUBLISHED: 2026-11-04
exit code: 0Only now does the deployment write to analytics. In a real pipeline the smoke test runs as the first job after every deployment, on a slice small enough to be quick and recent enough to contain real data, and the orchestrator runs the normal schedule only after it passes. When you have finished, remove the production stand-in:
docker rm -f -v "$LAB-prod" > /dev/null
docker ps -a --filter "name=$LAB" --format '{{.Names}}' | wc -l007. Check your understanding
08. Apply it
The skill practice asks for one end-to-end test that runs your pipeline against containerised databases in CI:
- Start the same database engines and major versions that you use in production, seed a small fixed dataset with edge cases such as a row near midnight, and assert the exact output.
- Run the tests in the CI workflow from lesson 3; GitHub's Ubuntu runners have Docker installed.
- Add a smoke test that runs after each deployment on one recent day and blocks publishing when its totals disagree with the source.
09. Review prompt
Without looking back, explain why end-to-end tests use disposable databases instead of a shared test database, how session-scoped fixtures and a per-test seed fixture work together, why the assertions compare exact rows, and what a smoke test after deployment can catch that CI cannot.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.