Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Lab · 25 min · revision 2

Lab: Unit Tests for Transformation Logic

Write a dbt unit test with hand-made input rows and expected output at the boundaries of a pricing rule, and a pytest suite for a Python transformation; watch both catch real bugs, fix them, then run the same commands as a GitHub Actions CI workflow.

Contentsand lesson path

What you will learn

  • Unit-test transformation logic with fixed input and expected-output fixtures and run all checks in CI.

01. Goal and setup

The checks in the previous lab are data tests: they look at whatever data has arrived and catch bad input. They cannot tell you whether your own logic is right, because the data you happen to have may never reach the case where the logic breaks. A unit test fixes the input instead. You write a few rows by hand, called a fixture, run one transformation on them, and compare the result with an expected output that you also wrote by hand. If the logic changes the result, the test fails, whatever the production data looks like that day.

In this lab you unit-test a SQL model with dbt and a Python function with pytest. Both contain a bug that is easy to write and hard to see, and both tests catch it. Then you run every check with the same commands that a CI (continuous integration) job runs on each pull request.

The lab was tested with Python 3.12, dbt Core 1.12.7, dbt-duckdb 1.11.1, DuckDB 1.5.6 and pytest 9.2.0. dbt unit tests need dbt 1.8 or later.

Text · requirements.txt
dbt-core==1.12.7
dbt-duckdb==1.11.1
duckdb==1.5.6
pytest==9.2.0
Terminal
mkdir dq-unit && cd dq-unit
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
mkdir -p models tests pipeline .github/workflows
Folder layout at the end of the lab
dq-unit/
├── requirements.txt, load_raw.py, results.py, pytest.ini
├── dbt_project.yml, profiles.yml
├── models/    sources.yml, stg_orders.sql, order_charges.sql, order_charges.yml
├── pipeline/  latest.py
├── tests/     test_latest.py
└── .github/workflows/data-ci.yml

02. Step 1: Create the dbt project

load_raw.py stands in for ingestion with three raw orders; dbt needs real upstream tables to exist, even for unit tests. The profile has a dev target for your work and a ci target that builds into its own schema, as a CI job would.

Python · load_raw.py
"""Stand-in for ingestion: a few raw orders, enough for dbt to build the models."""
import duckdb

con = duckdb.connect("warehouse.duckdb")
con.execute("CREATE SCHEMA IF NOT EXISTS raw")
con.execute("""
CREATE OR REPLACE TABLE raw.orders AS SELECT * FROM (VALUES
  (1, 'GB', 32.00, NULL),
  (2, 'FR', 64.50, 10),
  (3, 'GB', 50.00, NULL)
) AS t(order_id, country, subtotal, coupon_pct)""")
print(con.execute("SELECT count(*) FROM raw.orders").fetchone()[0], "raw orders")
YAML · dbt_project.yml
name: shop_logic
version: "1.0.0"
profile: shop_logic

models:
  shop_logic:
    +materialized: table
YAML · profiles.yml
shop_logic:
  target: dev
  outputs:
    dev:
      type: duckdb
      path: warehouse.duckdb
      schema: dev
      threads: 1
    ci:
      type: duckdb
      path: warehouse.duckdb
      schema: ci
      threads: 1
YAML · models/sources.yml
sources:
  - name: raw
    schema: raw
    tables:
      - name: orders
SQL · models/stg_orders.sql
select
    order_id,
    country,
    cast(subtotal as decimal(9, 2)) as subtotal,
    coupon_pct
from {{ source('raw', 'orders') }}
Python · results.py
"""Print status, failure count and name of each node of a dbt result file."""
import json
import sys

path = sys.argv[1] if len(sys.argv) > 1 else "target/run_results.json"
with open(path) as f:
    run = json.load(f)
for result in run["results"]:
    parts = result["unique_id"].split(".")
    kind = parts[0]
    name = "::".join(parts[2:4]) if kind == "unit_test" else parts[2]
    failures = result.get("failures")
    count = "" if failures is None else str(failures)
    print(f"{result['status']:<7} {kind:<9} {count:>3}  {name}")
Terminal
python load_raw.py
Expected output
3 raw orders

03. Step 2: Write the model and its unit test

The business rule: shipping costs 4.95 and is free for a subtotal of 50.00 or more, and a coupon takes coupon_pct percent off the subtotal. Here is a first version of order_charges. Read it and look for the bugs before you run anything.

SQL · models/order_charges.sql
-- Shipping is free from 50.00; a coupon takes coupon_pct percent off the subtotal.
with charges as (
    select
        order_id,
        subtotal,
        case when subtotal > 50 then 0.00 else 4.95 end as shipping_fee,
        round(subtotal * coupon_pct / 100, 2) as discount
    from {{ ref('stg_orders') }}
)

select
    order_id,
    subtotal,
    shipping_fee,
    discount,
    subtotal + shipping_fee - discount as total
from charges

Good fixture rows sit on and next to the edges of the rule, not in the comfortable middle: 49.99 and 50.00 test the threshold from both sides, and a NULL coupon tests the case where a value is missing. The expected values are worked out by hand from the rule, never copied from the model's output, otherwise the test would only confirm what the code already does.

A dbt unit test lives in a YAML file under models/. given replaces each ref() or source() of the model with fixture rows, and expect lists the rows the model must return. You only list the columns that matter for the test; dbt fills the others with NULL. The same file also declares two ordinary data tests on the model's key.

YAML · models/order_charges.yml
unit_tests:
  - name: shipping_and_discount_at_the_edges
    description: Free shipping starts at exactly 50.00; no coupon means no discount.
    model: order_charges
    given:
      - input: ref('stg_orders')
        rows:
          - {order_id: 1, subtotal: 49.99, coupon_pct: null}
          - {order_id: 2, subtotal: 50.00, coupon_pct: null}
          - {order_id: 3, subtotal: 80.00, coupon_pct: 25}
    expect:
      rows:
        - {order_id: 1, shipping_fee: 4.95, discount: 0.00, total: 54.94}
        - {order_id: 2, shipping_fee: 0.00, discount: 0.00, total: 50.00}
        - {order_id: 3, shipping_fee: 0.00, discount: 20.00, total: 60.00}

models:
  - name: order_charges
    columns:
      - name: order_id
        data_tests: [unique, not_null]

dbt build runs a model's unit tests before it builds the model, then the model, then its data tests. dbt prints the difference between the actual and the expected rows; the other log lines carry clock times, so the command below keeps only the difference.

Terminal
dbt build --quiet --no-use-colors > build.log
echo "exit code: $?"
sed -n '/actual differs/,$p' build.log
Expected output
exit code: 1
actual differs from expected:

@@,order_id,shipping_fee,discount,total
→ ,1       ,4.95        ,0.0→NULL,54.94→NULL
→ ,2       ,0.00→4.95   ,0.0→NULL,50.0→NULL
  ,3       ,0.00        ,20.0    ,60.0

Rows marked → differ, and each changed cell shows expected→actual. Order 2, with a subtotal of exactly 50.00, was charged 4.95 shipping: > 50 should be >= 50. Orders 1 and 2 have a NULL discount and therefore a NULL total, because arithmetic with NULL gives NULL; a missing coupon should mean no discount. Order 3, in the middle of both rules, was right, which is why a test with only typical values would have passed.

04. Step 3: Fix the model and rerun

Replace order_charges.sql with the version below: >= at the threshold and coalesce(coupon_pct, 0) for a missing coupon. Then build again.

SQL · models/order_charges.sql
-- Shipping is free from 50.00; a coupon takes coupon_pct percent off the subtotal.
with charges as (
    select
        order_id,
        subtotal,
        case when subtotal >= 50 then 0.00 else 4.95 end as shipping_fee,
        round(subtotal * coalesce(coupon_pct, 0) / 100, 2) as discount
    from {{ ref('stg_orders') }}
)

select
    order_id,
    subtotal,
    shipping_fee,
    discount,
    subtotal + shipping_fee - discount as total
from charges
Terminal
dbt build --quiet
python results.py
Expected output
success model          stg_orders
pass    unit_test   0  order_charges::shipping_and_discount_at_the_edges
success model          order_charges
pass    test        0  not_null_order_charges_order_id
pass    test        0  unique_order_charges_order_id

The unit test runs after stg_orders, because the model it tests depends on it, and before order_charges itself. Had it failed, dbt would have skipped the model and kept the wrong logic out of the warehouse.

05. Step 4: Unit-test a Python transformation

Not all logic lives in SQL. latest_per_customer reads a change feed, where the same customer can appear several times, and keeps the newest version of each customer. Save this first version as pipeline/latest.py:

Python · pipeline/latest.py
"""Keep the newest version of each customer from a change feed."""


def latest_per_customer(records):
    """Return one record per customer_id: the one with the latest updated_at."""
    latest = {}
    for record in records:
        key = record["customer_id"]
        if key not in latest or record["updated_at"] > latest[key]["updated_at"]:
            latest[key] = record
    return sorted(latest.values(), key=lambda r: r["customer_id"])

The tests build their fixtures with a small helper, rec, so each case stays readable. The second test is the boundary case for this function: two timestamps written with different UTC offsets. pytest.mark.parametrize runs one test function once per input, here for an empty feed and a feed with a single record. pytest.ini puts the project folder on the import path so that the tests can import pipeline.

Python · tests/test_latest.py
import pytest

from pipeline.latest import latest_per_customer


def rec(customer_id, email, updated_at):
    return {"customer_id": customer_id, "email": email, "updated_at": updated_at}


def emails(records):
    return [(r["customer_id"], r["email"]) for r in records]


def test_keeps_the_newest_record_per_customer():
    records = [
        rec(1, "[email protected]", "2026-11-02T08:00:00+00:00"),
        rec(1, "[email protected]", "2026-11-02T09:00:00+00:00"),
        rec(2, "[email protected]", "2026-11-01T12:00:00+00:00"),
    ]
    assert emails(latest_per_customer(records)) == [
        (1, "[email protected]"), (2, "[email protected]")]


def test_compares_instants_not_text_when_offsets_differ():
    # 09:00 in Paris (+01:00) is 08:00 UTC, so the UTC record is newer.
    records = [
        rec(1, "[email protected]", "2026-11-02T09:00:00+01:00"),
        rec(1, "[email protected]", "2026-11-02T08:30:00+00:00"),
    ]
    assert emails(latest_per_customer(records)) == [(1, "[email protected]")]


@pytest.mark.parametrize("records", [[], [rec(7, "[email protected]",
                                                "2026-11-02T08:00:00+00:00")]])
def test_empty_and_single_inputs(records):
    assert latest_per_customer(records) == records
INI · pytest.ini
[pytest]
testpaths = tests
pythonpath = .

sed removes the run time from pytest's last line, so that your output matches.

Terminal
pytest -q | sed -E 's/ in [0-9.]+s$//'
Expected output
.F..                                                                     [100%]
=================================== FAILURES ===================================
_____________ test_compares_instants_not_text_when_offsets_differ ______________

    def test_compares_instants_not_text_when_offsets_differ():
        # 09:00 in Paris (+01:00) is 08:00 UTC, so the UTC record is newer.
        records = [
            rec(1, "[email protected]", "2026-11-02T09:00:00+01:00"),
            rec(1, "[email protected]", "2026-11-02T08:30:00+00:00"),
        ]
>       assert emails(latest_per_customer(records)) == [(1, "[email protected]")]
E       AssertionError: assert [(1, '[email protected]')] == [(1, '[email protected]')]
E         
E         At index 0 diff: (1, '[email protected]') != (1, '[email protected]')
E         Use -v to get more diff

tests/test_latest.py:30: AssertionError
=========================== short test summary info ============================
FAILED tests/test_latest.py::test_compares_instants_not_text_when_offsets_differ
1 failed, 3 passed

The function compared updated_at as text. "2026-11-02T09:00:00+01:00" sorts after "2026-11-02T08:30:00+00:00", but it is 08:00 UTC, the earlier instant. The bug only shows when a feed mixes offsets, which a sample of production data may not contain on the day you look. Fix it by parsing the timestamps before comparing them:

Python · pipeline/latest.py
"""Keep the newest version of each customer from a change feed."""
from datetime import datetime


def latest_per_customer(records):
    """Return one record per customer_id: the one with the latest updated_at."""
    latest = {}
    for record in records:
        key = record["customer_id"]
        when = datetime.fromisoformat(record["updated_at"])   # compare instants
        if key not in latest or when > latest[key][0]:
            latest[key] = (when, record)
    return [record for _, record in sorted(latest.values(),
                                           key=lambda pair: pair[1]["customer_id"])]
Terminal
pytest -q | sed -E 's/ in [0-9.]+s$//'
Expected output
....                                                                     [100%]
4 passed

06. Step 5: Run every check the way CI will

A CI job starts from a clean machine, installs the pinned tools and runs a fixed list of commands; any command that exits with a non-zero code fails the job. Run that list yourself first. The output goes to log files here, and the exit codes are what CI looks at.

Terminal
pytest -q > pytest.log; echo "pytest: exit $?"
python load_raw.py
dbt build --target ci > dbt.log; echo "dbt build: exit $?"
python results.py
Expected output
pytest: exit 0
3 raw orders
dbt build: exit 0
success model          stg_orders
pass    unit_test   0  order_charges::shipping_and_discount_at_the_edges
success model          order_charges
pass    test        0  not_null_order_charges_order_id
pass    test        0  unique_order_charges_order_id

Unit tests use fixed inputs, so running them again in production adds nothing but time. dbt recommends running them in development and CI only, and excluding them from production builds:

Terminal
dbt build --exclude-resource-type unit_test --quiet
python results.py
Expected output
success model          stg_orders
success model          order_charges
pass    test        0  not_null_order_charges_order_id
pass    test        0  unique_order_charges_order_id

07. Step 6: The CI workflow

The workflow below runs on every pull request to main, with exactly the commands of step 5. Each action is pinned to a full commit SHA with its release tag as a comment, because a tag can be moved to other code. permissions: contents: read gives the job no write access. After you push it, make the check required in the branch protection rules, so a red check blocks the merge. We checked the file with actionlint but did not run it on GitHub; the commands themselves are the ones you just ran.

YAML · .github/workflows/data-ci.yml
name: data CI

on:
  pull_request:
    branches: [main]

permissions:
  contents: read

jobs:
  test:
    runs-on: ubuntu-24.04
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          persist-credentials: false
      - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
        with:
          python-version: "3.12"
      - name: Install the pinned tools
        run: pip install -r requirements.txt
      - name: Unit-test the Python transformations
        run: pytest -q
      - name: Load the sample raw data
        run: python load_raw.py
      - name: Run dbt unit tests, models and data tests in the ci schema
        run: dbt build --target ci

With a cloud warehouse, the ci target would point at a schema of its own for each pull request, and the job would read credentials from repository secrets. For large projects, the dbt CI lab shows how to build only the changed models with state:modified+ and --defer.

08. Check your understanding

Practice check · 3 questions

Unit tests and fixtures

Each question is about the lab's model, function or workflow.

Q1. A colleague writes the `expect` rows of a new unit test by running the model once and pasting its output. What is the problem?
Q2. The fixture for `stg_orders` lists only `order_id`, `subtotal` and `coupon_pct`. What does dbt put in the `country` column of the fixture rows?
Q3. You run `dbt build` on the fixed project, but `stg_orders` now fails to build because a raw column was renamed. What happens to the unit test of `order_charges`?
Practice only: not graded, not saved, not evidence.

09. Apply it

The skill practice asks for two unit tests on your own pipeline. Choose the two rules most likely to be wrong, such as a threshold, a date boundary, a NULL or a duplicate:

  • For each rule, write the fixture rows on and next to the edge, and work out the expected output by hand before you run anything.
  • Make each test fail once on purpose, by breaking the logic, to prove that it can fail.
  • Add the workflow from step 6 to your repository, with your own commands, and make it a required check.

10. Review prompt

Without looking back, explain the difference between a data test and a unit test, how you choose fixture rows and expected values, in which order dbt build runs unit tests, models and data tests, and why unit tests run in CI but not in production.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check