Why data code resists conventional testing
Application code fails loudly: an exception is raised, a status is 500, a test asserts on a return value. Data code fails by producing a plausible number that is wrong, and the difference changes what testing has to mean. There is no stack trace for a join that dropped forty percent of its rows because a key arrived with trailing whitespace; the only evidence is a downstream total that nobody notices until quarter close.
The second obstacle is environmental. A transformation is only interesting when it runs against a schema, an engine, and real distributional properties, yet pulling a warehouse into every test run is slow and expensive. The resolution is layering: test the pure logic thousands of times against synthetic frames in milliseconds, test engine-specific behaviour against a local containerised database on a schedule, and reserve the full pipeline for a small number of high-value checks.
After this lesson you should be able to decompose a pipeline into units worth isolating, write a transformation test that would actually catch a regression, and decide which layer a given bug belongs in.
A pyramid built for data
The pyramid applies, but the layers are defined by what they exercise rather than by how many of them exist. At the base sit pure unit tests over in-memory frames: fast, deterministic, and safe to run on every commit. The middle holds integration tests that execute against a real engine â SQLite or DuckDB in CI, a containerised Postgres for scheduling tests â because SQL dialects, null semantics, and type coercion are exactly where assumptions break. Above that sit contract tests validating external schemas, and at the top a handful of end-to-end runs plus regression checks against known-good outputs.
| Layer | Exercises | Runtime | Runs on | Catches |
|---|---|---|---|---|
| Unit | Pure transformation logic | Milliseconds | Every commit | Logic and null-handling bugs |
| SQL unit | Statements against SQLite or DuckDB | Seconds | Every commit | Syntax, dialect, semantics |
| Integration | Real engine with container fixture | Minutes | Nightly or PR-labelled | Type coercion, window behaviour |
| Contract | Source schema and freshness | Minutes | Every ingestion | Upstream drift |
| Regression | Output versus pinned snapshot | Minutes | Nightly | Silent semantic change |
| End to end | Whole pipeline on a sample | Tens of minutes | Release | Wiring and orchestration bugs |
The distribution matters more than the shape. Most teams have almost exclusively end-to-end tests, which are slow, flaky, and point at the pipeline rather than the defect. Moving the bulk of coverage down to units converts a twenty-minute investigation into a three-second failure with a file and line number.
Unit-testing a transformation you can trust
The precondition for unit testing is a function with no I/O. A transformation that reads a table, mutates a global, and writes a table cannot be tested in isolation; the same logic expressed as a function taking a frame and returning a frame can. That refactor is the single highest-leverage testing decision in a data pipeline.
import pandas as pd
import pytest
from transforms.orders import build_customer_lifetime_value, deduplicate_orders
@pytest.fixture
def orders():
return pd.DataFrame({
"order_id": [1, 2, 2, 3, 4],
"customer_id": ["A", "A", "A", "B", None],
"amount": [100.0, 50.0, 50.0, -5.0, 20.0],
"status": ["paid", "paid", "paid", "cancelled", "paid"],
"ordered_at": pd.to_datetime([
"2026-01-01", "2026-01-02", "2026-01-02", "2026-01-03", "2026-01-04"
]),
})
def test_duplicate_order_ids_collapse_to_first_occurrence():
df = pd.DataFrame({
"order_id": [1, 1],
"amount": [10.0, 99.0],
"ordered_at": pd.to_datetime(["2026-01-01", "2026-01-01"]),
})
out = deduplicate_orders(df)
assert len(out) == 1
assert out.iloc[0]["amount"] == 10.0
def test_ltv_excludes_cancelled_and_negative_amounts(orders):
ltv = build_customer_lifetime_value(orders)
assert "B" not in ltv.index # cancelled and negative
assert ltv["A"] == pytest.approx(150.0)
def test_null_customer_id_is_quarantined_not_dropped(orders):
out = build_customer_lifetime_value(orders, quarantine_null_keys=True)
assert out.attrs["quarantined"] == 1
def test_ltv_is_idempotent_under_replay(orders):
once = build_customer_lifetime_value(orders)
twice = build_customer_lifetime_value(deduplicate_orders(orders))
pd.testing.assert_series_equal(once, twice)
Notice which assertions are chosen. Testing that the function returns a DataFrame proves nothing; testing the boundary cases â duplicates, negative amounts, null keys, replay idempotence â proves the behaviours that actually break in production. The idempotence test is the most valuable of the four, because it encodes the promise that a re-run of yesterday's load converges to the same result.
Integration tests against a real engine
Dialect and type behaviour are not covered by pandas. Window frame defaults, integer division, implicit casts, NULL ordering, and string collation all differ between engines, and a query that passes against a mock will fail against the warehouse. A containerised database gives you the real semantics without the bill.
import duckdb
import pytest
from transforms.sql import revenue_by_region_sql
@pytest.fixture(scope="session")
def con():
c = duckdb.connect()
c.execute("CREATE TABLE orders AS SELECT * FROM read_csv_auto('tests/fixtures/orders.csv')")
c.execute("CREATE TABLE regions AS SELECT * FROM read_csv_auto('tests/fixtures/regions.csv')")
yield c
c.close()
def test_revenue_excludes_cancelled_and_joins_null_regions(con):
result = con.execute(revenue_by_region_sql).fetchdf()
assert set(result.columns) == {"region", "revenue", "orders"}
assert (result["revenue"] >= 0).all()
assert result["region"].isna().sum() == 0 # left join defaulted correctly
def test_revenue_matches_hand_computed_fixture(con):
result = con.execute(revenue_by_region_sql).fetchdf()
expected = {"EMEA": 1500.0, "AMER": 900.0}
actual = dict(zip(result["region"], result["revenue"]))
for region, value in expected.items():
assert actual[region] == pytest.approx(value)
def test_query_handles_empty_source(con):
con.execute("DELETE FROM orders")
result = con.execute(revenue_by_region_sql).fetchdf()
assert len(result) == 0 # no rows, but no crash either
The empty-source case is the one most often skipped and most often broken. A query that divides by a count, or a window that assumes at least one row, fails only when volume drops to zero â which is precisely when an incident is already in progress.
Contract and regression tests
Contract tests validate the outside world: the source schema, column types, nullability, and a freshness bound. They are cheap and run at ingestion time, and their value is turning an upstream change into a failure on the producer's schedule rather than a silent corruption on yours.
Regression tests protect semantics that unit tests cannot see. Pin a small fixture dataset, run the full transformation, and compare against a committed snapshot. When a change deliberately alters the output, the diff in review is the specification of the change; when it alters the output accidentally, the same diff is the bug report. Snapshot tests need a narrow, stable fixture â anything with timestamps or random ids produces noise until you normalise them.
Wiring tests into CI
CI should fail fast and cheap. Run units and SQL tests on every pull request in under a minute, run integration tests when the pull request touches SQL or schema files, and run the nightly suite with the containerised engine and the regression snapshots. Mark slow tests explicitly rather than skipping them silently, and keep fixtures in the repository so a new clone can run the suite without credentials.
Measuring coverage is useful only if you read it by module. A pipeline with ninety percent line coverage can still have zero assertions on output values, because lines executed is not the same as behaviour verified. Pair coverage with a mutation check occasionally: deliberately break a filter and confirm a test fails. If nothing fails, you had coverage without tests.
Test data management is the unglamorous half of a reliable suite. Fixtures should be committed, small enough to reason about by hand, and shaped to include the awkward cases deliberately: a duplicate key, a null in a required column, a boundary amount, an empty set, and one row that violates each rule you claim to enforce. Generate larger synthetic data with a fixed seed when you need volume, and normalise timestamps and identifiers before snapshot comparison so a test fails on semantics rather than on the clock. Keep production samples out of the repository entirely; if you need realism, derive it with a script at runtime so no sensitive value is ever committed.
đĄThe five-minute rule
If a test takes longer than five minutes or needs credentials, it does not belong on the commit path. Move it to a scheduled suite, keep it reliable, and never let the fast suite depend on it.
Common Mistakes
Testing only through the orchestrator, so every failure points at the whole pipeline
Fix: Extract pure functions and unit test them; reserve orchestrator tests for wiring
Asserting on shape and column names but never on values
Fix: Pin expected totals and edge rows so a semantic regression fails the suite
Skipping the empty and single-row cases
Fix: Add fixtures for zero rows and one row; those are when windows and divides break
Ignoring flaky tests by re-running CI
Fix: Quarantine a flaky test immediately, because a red suite people rerun is a suite nobody reads
Best Practices
- Refactor transformations into pure functions before writing tests
- Run the same assertions against a real engine so dialect and null semantics are covered
- Keep fixtures small, committed, and free of unseeded randomness
- Snapshot-test regression against a pinned dataset and review diffs as specifications
- Measure mutation survival occasionally to confirm assertions can actually fail
Interview Questions
Q1: Why unit test data transformations at all, when the warehouse can validate output?
Warehouse validation catches that something is wrong; unit tests tell you which function and which line, in seconds rather than minutes.
Q2: What belongs in an integration test rather than a unit test?
Anything dependent on engine semantics: type coercion, window frames, null ordering, collation, and dialect-specific syntax.
Q3: How do you test that a pipeline is idempotent?
Run the transformation twice over the same input, or replay through deduplication, and assert the outputs are equal.
Q4: What is a contract test in this context?
A check that the source still provides the agreed schema, types, and freshness before ingestion proceeds.
Key Takeaways
- Data bugs fail silently, so tests must assert values rather than successful execution
- Layer tests by cost: pure units on every commit, engine integration on change, end-to-end rarely
- Pure functions with no I/O are the precondition for meaningful unit tests
- Contract and regression tests cover the two places units cannot: upstream drift and semantic change
- A fast suite that people trust beats a comprehensive suite people rerun