Testing transformations

Part of the free LogicWiz Data Engineering course, Module 7: Data quality and testing. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 8:15 on Wednesday. Tess's dashboard says Tuesday's revenue is up 12%, and every data check is green. Yesterday you merged a faster version of the daily revenue query. One changed line now counts returned orders as revenue. Nora reads the diff and says: "Five made-up orders would have caught this before it shipped."

You'll learn to

  • Tell a unit test from a data test, and when each runs
  • Build a small fixture and test a transformation in Python and SQL
  • Alert on late tables and odd row counts without false alarms
  • Use lineage to see who a broken table affects

Learn

Green checks, wrong revenue

Every check from Lessons 7.1 to 7.4 ran last night, and every one passed. They had nothing to complain about: the revenue numbers were not null, not duplicated, fresh and normal in size. They were just wrong.

Those checks are data tests. They look at the real data every time the pipeline runs, and they catch bad data flowing through good code.

What broke was the code. That needs a unit test: run the logic on a few rows you wrote by hand, and compare the result with the rows it must give. Those hand-written inputs are called a fixture. A unit test runs in seconds in CI, the automatic checks on every pull request, before any real data is involved.

Where each kind of test runs

A flow from a pull request through unit tests on fixtures, then deploy, then data tests on the nightly run, then monitors and lineage after every run.

Read it left to right: the green step is the only one that runs before your change reaches real data, which is why it is the only one that could have stopped Tuesday.

Five orders that cover every rule

Start with the rule, in words: daily revenue adds up qty × unit_price for the lines of orders that are not cancelled or returned.

A good fixture is the smallest input that tests each part of that rule. One normal order with two lines and a quantity above 1. One cancelled order. One returned order. One order with no lines at all. And two different days, so the grouping by day is tested too.

That makes five orders, five lines and two expected rows. Work out the expected rows by hand, from the rule. Never copy what the code returns today: if the code is wrong, the copy is wrong too.

The fixture, and what it should give

OrderDayStatusLines (qty x price)Counts?
11 Junedelivered1 x 10.00, 2 x 5.00yes: 20.00
21 Junecancelled1 x 99.00no
31 Junereturned1 x 50.00no
42 Juneshipped2 x 7.50yes: 15.00
52 Juneplaced(no lines)adds nothing
Expected1 June: 20.00; 2 June: 15.00

Each order is there for one part of the rule, and the last row was worked out on paper, not by running the code.

Give every risky case a row

Five orders are enough for this rule. Other rules hide other bugs, and most of them sit in a short list of cases. Give each one a row in a fixture:

  • NULLs in every column the logic touches;
  • duplicate keys, such as the retry file;
  • empty input (no rows today);
  • boundaries: the first and last second of a day;
  • every branch of a CASE or filter, such as each status;
  • late or out-of-order rows when the logic picks "the latest". Put the newer version first, so code that keeps the last row it saw fails.

Write one test per rule and name it after the rule, test_returned_orders_excluded, so a failure explains itself.

The rewrite meets the fixture

Five fixture orders, then the expected rows worked out by hand, then the old code matching them, then the rewrite returning 70 dollars for 1 June so the test reports a missing row and an unexpected row.

  1. The fixture. Five orders on two days, each one there for one part of the rule. Nothing has run yet.

  2. The expected rows, by hand. Orders 2 and 3 drop out, and order 5 adds nothing. So 1 June is $20.00 and 2 June is $15.00, written down before any code runs.

  3. Run the old code. It returns the same two rows. Nothing is missing and nothing is unexpected, so the test passes.

  4. Run the rewrite. It skips only cancelled orders, so order 3's $50.00 comes back in and 1 June says $70.00. The test reports one expected row missing and one row unexpected, and the pull request goes red.

Compare the Expected and Actual boxes at each step: the test is that comparison, and every red row is a failure that names its own reason.

Remember: a unit test is three things written by hand: the fixture, the expected rows, and a name that says the rule. If you have never seen it go red, you do not know that it can.

Unit tests in plain Python

def daily_revenue(orders, lines):
    """Revenue per day: qty * unit_price of lines whose order is not cancelled or returned."""
    info = {o['order_id']: (o['day'], o['status']) for o in orders}
    out = {}
    for line in lines:
        day, status = info[line['order_id']]
        if status in ('cancelled', 'returned'):
            continue
        out[day] = round(out.get(day, 0) + line['qty'] * line['unit_price'], 2)
    return out

ORDERS = [
    {'order_id': 1, 'day': '2025-06-01', 'status': 'delivered'},
    {'order_id': 2, 'day': '2025-06-01', 'status': 'cancelled'},
    {'order_id': 3, 'day': '2025-06-01', 'status': 'returned'},
    {'order_id': 4, 'day': '2025-06-02', 'status': 'shipped'},
    {'order_id': 5, 'day': '2025-06-02', 'status': 'placed'},
]
LINES = [
    {'order_id': 1, 'qty': 1, 'unit_price': 10.0},
    {'order_id': 1, 'qty': 2, 'unit_price': 5.0},
    {'order_id': 2, 'qty': 1, 'unit_price': 99.0},
    {'order_id': 3, 'qty': 1, 'unit_price': 50.0},
    {'order_id': 4, 'qty': 2, 'unit_price': 7.5},
]

def test_revenue_by_day():
    assert daily_revenue(ORDERS, LINES) == {'2025-06-01': 20.0, '2025-06-02': 15.0}

def test_no_input_no_revenue():
    assert daily_revenue([], []) == {}

for test in [test_revenue_by_day, test_no_input_no_revenue]:
    test()
    print('pass', test.__name__)

def faster_revenue(orders, lines):             # the "faster" rewrite
    info = {o['order_id']: (o['day'], o['status']) for o in orders}
    out = {}
    for line in lines:
        day, status = info[line['order_id']]
        if status != 'cancelled':
            out[day] = round(out.get(day, 0) + line['qty'] * line['unit_price'], 2)
    return out

try:
    assert faster_revenue(ORDERS, LINES) == {'2025-06-01': 20.0, '2025-06-02': 15.0}
except AssertionError:
    print('FAIL: the rewrite counts returned orders:', faster_revenue(ORDERS, LINES))

Each test is a function whose name says the rule; a test runner such as pytest finds and runs every test_ function for you. The rewrite fails the first test with 70.0 for 1 June: caught in a second, not on a dashboard.

The same test in SQL

Most of SwiftKart's transformations are SQL, so the test can be SQL too. The idea does not change: fixture rows in, expected rows written down, then compare.

Put the fixture in CTEs, run the model's query on them, and write the expected rows as VALUES. Then ask two questions with EXCEPT. Which expected rows are missing from the result? Which result rows are unexpected? Zero rows back means the test passes. Any row back says exactly what broke.

The card runs on the empty database, so the fixture is the only data. In a dbt project the same test is a few lines of YAML.

Fixtures in, EXCEPT out

WITH orders_fx (order_id, order_ts, status) AS (
  VALUES (1, TIMESTAMP '2025-06-01 09:00', 'delivered'),
         (2, TIMESTAMP '2025-06-01 10:00', 'cancelled'),
         (3, TIMESTAMP '2025-06-01 11:00', 'returned'),
         (4, TIMESTAMP '2025-06-02 09:00', 'shipped'),
         (5, TIMESTAMP '2025-06-02 10:00', 'placed')
),
lines_fx (order_id, qty, unit_price) AS (
  VALUES (1, 1, 10.00), (1, 2, 5.00), (2, 1, 99.00), (3, 1, 50.00), (4, 2, 7.50)
),
actual AS (
  -- the model under test
  SELECT o.order_ts::DATE AS day, SUM(l.qty * l.unit_price) AS revenue
  FROM orders_fx AS o
  JOIN lines_fx AS l ON l.order_id = o.order_id
  WHERE o.status NOT IN ('cancelled', 'returned')
  GROUP BY o.order_ts::DATE
),
expected (day, revenue) AS (
  VALUES (DATE '2025-06-01', 20.00), (DATE '2025-06-02', 15.00)
)
SELECT 'missing' AS problem, * FROM (SELECT * FROM expected EXCEPT SELECT * FROM actual) AS m
UNION ALL
SELECT 'unexpected', * FROM (SELECT * FROM actual EXCEPT SELECT * FROM expected) AS u;

Zero rows means the test passes. Change NOT IN ('cancelled', 'returned') to <> 'cancelled' and run it again: one "missing" row and one "unexpected" row show exactly what broke.

The trap: a test that cannot fail. Watch for asserts like assert len(result) >= 0, expected values copied from the code's own output (they only prove the code does what it does), and fixtures without the edge case the rule is about. Break the code on purpose once (skip only cancelled, not returned) and make sure a test goes red.

A dbt unit test (dbt 1.8 and later)

Runs with dbt:

unit_tests:
  - name: test_returned_orders_excluded
    model: daily_revenue
    given:
      - input: ref('stg_orders')
        rows:
          - {order_id: 1, order_date: 2025-06-01, status: delivered}
          - {order_id: 3, order_date: 2025-06-01, status: returned}
      - input: ref('stg_order_items')
        rows:
          - {order_id: 1, qty: 1, unit_price: 10.00}
          - {order_id: 3, qty: 1, unit_price: 50.00}
    expect:
      rows:
        - {order_date: 2025-06-01, revenue: 10.00}
$ dbt test --select "daily_revenue,test_type:unit"
...
1 of 1 PASS daily_revenue::test_returned_orders_excluded ......... [PASS in 0.41s]

Done. PASS=1 WARN=0 ERROR=0 SKIP=0 TOTAL=1

dbt replaces the model's inputs with the given rows, runs the model and compares its output with expect: the SQL card above, managed for you.

Someone has to hear it fail

The rewrite is fixed and its test is green. But the pipeline runs every night on real data, and the next problems come from outside your code: a feed stops, a file lands late, half the rows go missing.

Checks only help if someone hears when they fail. Agree a freshness target for each table with the people who use it: "daily_revenue is complete for yesterday by 07:00 UTC". A promise to others is often called an SLA, your internal target an SLO.

Alert on what users feel, not on every hiccup. A good alert says what is wrong, since when, which table, who owns it and where the failing rows are.

Freshness against targets

WITH newest AS (
  SELECT 'orders' AS table_name, MAX(updated_at) AS newest, INTERVAL '12 hours' AS target FROM orders
  UNION ALL
  SELECT 'payments', MAX(paid_ts), INTERVAL '12 hours' FROM payments
  UNION ALL
  SELECT 'customers', MAX(updated_at), INTERVAL '7 days' FROM customers
  UNION ALL
  SELECT 'events', MAX(event_ts), INTERVAL '1 day' FROM events
)
SELECT table_name, newest,
  TIMESTAMP '2025-06-16 07:00:00' - newest AS age,
  CASE WHEN TIMESTAMP '2025-06-16 07:00:00' - newest > target THEN 'LATE' ELSE 'ok' END AS status
FROM newest
ORDER BY table_name;

At the 07:00 run on 16 June, orders and customers are within target. Payments are 18 hours old against 12. The events feed stopped on 3 June: twelve days without anyone noticing is what happens when nobody checks freshness.

Is today's count normal?

Freshness asks "did it arrive?". Volume asks "did all of it arrive?". A fixed range, "800 to 1,200 orders a day", breaks as soon as the business grows or has a quiet day of the week.

The usual next step is a z-score: how far today is from the average of the last 28 days, counted in standard deviations. z = (today - mean) / sd, with an alert at |z| > 3. It fails in two ways. Past incidents sit in the history: one outage day with 120 orders inflates the standard deviation and hides the next incident. And weekly seasonality (Sundays are always low) widens the band further.

A sturdier monitor uses the middle value instead of the average. See what four monitors say about two days.

Four weeks of orders, two days, four monitors

MonitorWednesday: 780 (a partner file missing)Sunday: 600 (normal)Verdict
Fixed range 800 to 1,200ALERTALERTNoisy: fires every Sunday
z over 28 days, alert at abs(z) 3-0.41: missed-1.23Blind: sd is 219 because of weekends and the outage
Robust z (MAD) over 28 days-12.67: ALERT-23.23: ALERTIgnores the outage, not the weekly cycle
Robust z, same weekday only-21.1: ALERT-0.14Right on both

History: weekdays near 1,000, Saturdays near 700, Sundays near 600, and one Tuesday with 120 orders. The Python card below computes every number.

The robust monitor makes two changes. It swaps the average for the median (the middle value), and the standard deviation for the median absolute deviation, or MAD (the middle distance from the median). Then M = 0.6745 × (today - median) / MAD, and a day is an outlier when |M| > 3.5. One outage barely moves a median.

It also compares each day only with the same weekday in earlier weeks, which takes the weekly cycle out.

Freshness gets the same treatment. Record each partition's arrival delay: when it landed, minus the end of the period it covers. Alert when today's delay passes the weekday's median plus a few MADs, or the agreed target, whichever comes first.

Wednesdays only: the drop stands out

Bars show the orders on the last four Wednesdays, all close to one thousand, and today's Wednesday at 780, far below them.

Compare the red bar with the four blue ones: median 999, absolute deviations 11, 14, 3 and 3, so MAD = 7, and 0.6745 x (780 - 999) / 7 = -21.1, far past 3.5.

Compute the four monitors

import statistics as st

# Orders per day, Monday first; week 2 had a half-day outage on Tuesday
weeks = [
    [1012, 1003, 1010,  991, 1015, 702, 605],
    [ 990,  120,  985, 1004, 1008, 688, 590],
    [1005,  998, 1002, 1000,  996, 715, 612],
    [ 995, 1010,  996, 1007, 1001, 694, 598],
]
history = [n for week in weeks for n in week]

def z(x, hist):
    return (x - st.mean(hist)) / st.stdev(hist)

def robust_z(x, hist):
    med = st.median(hist)
    mad = st.median([abs(h - med) for h in hist])
    return 0.6745 * (x - med) / mad

print('mean', round(st.mean(history), 1), '| sd', round(st.stdev(history), 1))
for name, today, weekday in [('Wednesday', 780, 2), ('Sunday', 600, 6)]:
    same_day = [week[weekday] for week in weeks]
    print(name, today,
          '| fixed:', 'ok' if 800 <= today <= 1200 else 'ALERT',
          '| z:', round(z(today, history), 2),
          '| robust 28 days:', round(robust_z(today, history), 2),
          '| robust same weekday:', round(robust_z(today, same_day), 2))

Real monitors store one metric row per table, partition and day, and compute this in SQL with percentile_cont(0.5) or in the observability tool. Keep at least four to eight weeks of the same weekday, and exclude days already marked as incidents from the history.

Who reads the broken table?

Freshness, volume, schema changes (Lesson 7.4) and per-column distributions are what data observability tools watch on every table. One more signal answers the first question of every incident: when a table breaks, who reads it? The map of which table feeds which is called lineage.

OpenLineage is an open standard that reports lineage as events. Every job run sends a RunEvent: an eventType (START, COMPLETE, FAIL and a few more), a run with a runId, a job with a namespace and name, and the job's inputs and outputs datasets. Each input-to-output pair is one edge of the graph.

You rarely write events by hand: Airflow, Spark and dbt send them, and Marquez is the reference backend. Because every tool reports to one place, the graph crosses tools.

The COMPLETE event dbt-ol sends for daily_revenue (trimmed)

Runs with dbt:

{
  "eventType": "COMPLETE",
  "eventTime": "2025-06-16T06:42:10.120Z",
  "run": { "runId": "3f2b9c1e-6a7d-4f0e-9b8a-1c2d3e4f5a6b" },
  "job": { "namespace": "swiftkart-dbt", "name": "swiftkart.marts.daily_revenue" },
  "inputs": [
    { "namespace": "postgres://warehouse:5432", "name": "swiftkart.staging.orders" },
    { "namespace": "postgres://warehouse:5432", "name": "swiftkart.staging.order_items" }
  ],
  "outputs": [
    { "namespace": "postgres://warehouse:5432", "name": "swiftkart.marts.daily_revenue",
      "facets": { "schema": { "fields": [
        { "name": "order_date", "type": "date" },
        { "name": "revenue", "type": "numeric" } ] } } }
  ],
  "producer": "https://github.com/OpenLineage/OpenLineage/tree/main/integration/dbt",
  "schemaURL": "https://openlineage.io/spec/2-0-2/OpenLineage.json#/definitions/RunEvent"
}

Two inputs and one output make two edges: staging.orders to daily_revenue and staging.order_items to daily_revenue. Real facets also carry _producer and _schemaURL fields, and a START event with the same runId comes first.

Lineage from the run events: what staging.orders breaks

A lineage graph from raw tables through staging tables to marts and their consumers; staging.orders failed a check, so everything downstream of it is marked as affected.

Read it from the red failure outwards: everything to its right is suspect (flag it and tell its users first), everything to its left is where to look for the cause, and staging.order_items is fine although it feeds the same marts.

Numbers to remember

WhatSetting or ruleGood to know
pytestruns every test function it findsPython unit tests in CI on every pull request
dbt unit testsdbt 1.8 and latergiven rows in, expect rows out; run with dbt test --select "dailyrevenue,testtype:unit"
dbt source freshnesswarnafter, errorafter on a sourceChecked by dbt source freshness; alerts go to Slack or PagerDuty from the orchestrator
z-scorealert at abs(z) 3, over 28 daysOutages and the weekly cycle inflate the standard deviation
Robust z0.6745 x (x - median) / MAD, outlier above 3.5The Iglewicz and Hoaglin rule in NIST's statistics handbook
History to keep4 to 8 weeks of the same weekdayLeave out days already marked as incidents
Column distributionsnull rate, distinct count (HyperLogLog), min, maxStored per table and partition, against a history, like volume
OpenLineage eventTypeSTART, RUNNING, COMPLETE, ABORT, FAIL, OTHERDatasets carry facets such as schema, dataSource and columnLineage
OpenLineage sendersAirflow: apache-airflow-providers-openlineage; Spark: spark.extraListeners=io.openlineage.spark.agent.OpenLineageSparkListener; dbt: dbt-ol runLineage also comes from dbt docs and Databricks Unity Catalog

What changed at SwiftKart

The rewrite is back, still faster and now right. Its pull request carries test_returned_orders_excluded, and you broke the code once on purpose to watch the test go red. Tuesday's revenue is back to its true number.

Every night the pipeline now checks its own pulse: freshness against agreed targets, a same-weekday volume monitor, and a lineage graph that says who to warn when a table breaks.

Module 7 is done. You can catch bad data and bad code. One thing is still done by hand: deciding which transformation runs before which. Module 8 starts there, with "Models and ref()", where each transformation says what it depends on.

In one line

Unit tests check your logic on a few hand-made rows before it ships; freshness and volume monitors and lineage watch the real data after.

Interview corner

How do you unit-test a SQL transformation?

Feed the model a small fixture that covers each rule and edge case (NULLs, duplicates, each status, an empty input), and compare its output with an expected result worked out by hand, for example with EXCEPT both ways or a dbt unit test. It runs in CI on every pull request, so logic bugs are caught before they touch production data.

How would you detect that a table's daily volume is abnormal, without hand-tuning a threshold for every table?

Store one metric row per table, partition and day, then compare each new value with the same weekday over the last four to eight weeks using the median and the median absolute deviation, flagging a modified z-score beyond about 3.5. A plain mean and standard deviation fail because past incidents and weekly seasonality inflate the spread: in a typical case a 22% drop scores -0.4 there and -21 with the robust weekday method. I exclude incident days from the history, apply the same idea to arrival delay for freshness, and route alerts by lineage to the owners of the affected tables.

What is OpenLineage, and what does it give you over lineage inside one tool?

An open standard where every job run emits events (START, COMPLETE, FAIL and so on) naming the job and its input and output datasets, with facets such as schema and column lineage. Integrations exist for Airflow, Spark and dbt, so the graph spans tools instead of stopping at the edge of dbt docs or one catalog, and it is built from what actually ran, not from what the code says. During an incident I can walk from a failed dataset to everything downstream and notify those owners; Marquez is the reference backend.

A table feeding the finance dashboard failed its checks. What do you do first?

Use lineage to see everything downstream, stop or flag those tables so nobody acts on wrong numbers, and tell their users. Then find the cause upstream, fix it, rerun the affected partitions (the loads are idempotent, so that is safe), and add a test that would have caught it earlier.