Tests and docs
Part of the free LogicWiz Data Engineering course, Module 8: Transformation as code: dbt. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 9:05 on Thursday. Tess opens finance's "new customers in June" report and finds Maya Chen in it three times. Maya signed up with the same email on three accounts. Every model built, every job was green, and nothing warned anyone.
You'll learn to
- Attach the four generic tests and say what each checks
- Read the query dbt runs for a test
- Predict what dbt build does when a test fails or warns
- Pick singular tests, unit tests or contracts for the right job
Learn
Every job was green
Green only means the SQL ran. Nobody asked whether the rows were right.
Nora's question: "Which query would have shown you Maya three times?" That query is the whole idea.
In dbt, a test is a SELECT that returns the rows that should not exist. Zero rows means pass. Any rows mean fail, and the number of rows says how badly.
Think of a spell-checker. It does not show you the correct words. It lists only the wrong ones, and an empty list means the page is clean.
The picture runs one test: no customer may be missing an email.
One test, start to finish
Four steps: the model stg_customers, a test query that selects rows with no email, the one row it returns for customer 7, and the result FAIL 1.
Read it left to right. dbt only counts the rows that come back: here one, so the test reports FAIL 1.
Four tests, one line of YAML each
You rarely write those queries yourself. dbt ships four generic tests. You attach one to a column with a line of YAML, and dbt turns it into a query against the built model and runs it.
not_null: no value is missing.unique: no value appears twice.accepted_values: every value is on your list.relationships: every key has a match in another model.
The YAML file sits next to the models. It also holds a description for each model and column, and dbt docs generate turns those into a website of every model, every column and the lineage graph.
Tests and docs live next to the models
Runs with dbt:
# models/staging/_staging.yml
version: 2
models:
- name: stg_customers
description: One row per customer account in the shop.
columns:
- name: customer_id
description: The shop's id for the account.
data_tests: [not_null, unique]
- name: email
data_tests: [not_null, unique]
- name: stg_orders
columns:
- name: order_id
data_tests: [not_null, unique]
- name: status
data_tests:
- accepted_values:
values: [placed, shipped, delivered, cancelled, returned]
- name: customer_id
data_tests:
- relationships:
to: ref('stg_customers')
field: customer_id
Read the line under email: data_tests: [not_null, unique] would have caught Maya. Older projects write tests: instead of data_tests:; both work.
The four generic tests and the query each runs
| Test | Fails when | The query dbt runs (simplified) |
|---|---|---|
| notnull | a value is missing | select from m where col is null |
| unique | a value appears twice | select col, count() from m where col is not null group by col having count() 1 |
| acceptedvalues | a value is not on the list | select col from m where col not in (...) group by col |
| relationships | a key has no match in the other model | select child.col from m child left join other parent on ... where parent.key is null |
Every query returns bad rows only. Look closely at unique: it groups by the value before it counts.
A failing test stops what depends on it
Finding the duplicate is half the job. The other half is keeping it out of the marts.
dbt build does both. It builds a model, runs that model's tests straight away, and only then moves on to the models that read it. If a test fails, every model that depends on it is skipped. Models that do not depend on it carry on.
Skipping is the protection. Yesterday's good table stays in place, instead of being replaced by one that has the same person in it three times.
Run the build, then step through what happened.
Build with tests
import minidbt
models = {
'stg_customers': "select customer_id, name, email, country from {{ source('shop', 'customers') }}",
'stg_orders': "select order_id, customer_id, status from {{ source('shop', 'orders') }}",
}
models['dim_customers'] = "{{ config(materialized='table') }} select * from {{ ref('stg_customers') }}"
models['fct_orders'] = "{{ config(materialized='table') }} select * from {{ ref('stg_orders') }}"
tests = {
'stg_customers': {
'customer_id': ['not_null', 'unique'],
'email': ['not_null', 'unique'],
},
'stg_orders': {
'order_id': ['not_null', 'unique'],
'status': [{'accepted_values': ['placed', 'shipped', 'delivered', 'cancelled', 'returned']}],
'customer_id': [{'relationships': {'to': 'stg_customers', 'field': 'customer_id'}}],
},
}
results = minidbt.Project(models=models, tests=tests).build()
The tests dictionary is the YAML above written as Python. Read the log from the top: each test runs right after the model it checks, two tests on stg_customers fail, and dim_customers is marked SKIP.
dbt build, with tests in the way
Two rows of a graph: stg_customers, its tests and dim_customers; stg_orders, its tests and fct_orders. The customer tests fail, so dim_customers is skipped, while the orders row builds to the end.
Build stg_customers.
dbt buildcreates the view. Nothing else has run yet.Test it at once. Four tests run on the new view. Two pass.
not_nullfinds customer 7 with no email.uniquefinds[email protected], used by customers 2, 12 and 29.Skip what reads it.
dim_customersreads a model with a failing test, so dbt does not build it. Yesterday's gooddim_customersstays in place.Carry on elsewhere.
stg_ordersdoes not depend on customers. dbt builds it, and its four tests pass: ids unique, statuses known, every customer exists.Build fct_orders. Its parent passed every test, so the mart is built. The run ends with
PASS=9 WARN=0 ERROR=2 SKIP=1.
Follow each row from left to right. The red tests sit between stg_customers and dim_customers, so nothing bad gets past them. The other row has no failure and builds to the end.
Try it: make a test fail
A dbt graph where a test on a staging model fails, and every model downstream of it is marked as skipped while unrelated models still build.
Make a test fail in the picture and watch which models turn grey.
Remember: dbt build tests a model before it builds the models that read it. A failed test skips them.
What dbt runs for one test
Now open the hood on that unique test.
A generic test is a macro: a reusable piece of SQL with blanks for the model and the column. Filled in for stg_customers.email, it becomes a query that returns one row per duplicated email.
dbt does not fetch those rows. It wraps the query in a second one and asks the warehouse for three numbers at once:
failures: how many bad rows came back.should_warn: is that enough to warn?should_error: is that enough to fail?
The next card is the real file dbt writes for Maya's test.
The compiled unique test
Runs with dbt:
select
count(*) as failures,
count(*) != 0 as should_warn,
count(*) != 0 as should_error
from (
select
email as unique_field,
count(*) as n_records
from analytics.stg_customers
where email is not null
group by email
having count(*) > 1
) dbt_internal_test
failures | should_warn | should_error
----------+-------------+--------------
1 | true | true
dbt saves this under target/run/ as unique_stg_customers_email.sql. One duplicated email, so failures is 1 and both flags are true: FAIL 1. With error_if: ">100" the last column would be count(*) > 100, false here, and the test would only warn.
From a YAML line to PASS, WARN or FAIL
Five steps: a test named in YAML, the test macro rendering a query of bad rows, the wrapper counting them, the severity rules choosing a result, and the status that decides whether the children are built.
Read it left to right. The first three boxes are the query in the card above. The last two decide between PASS, WARN and FAIL, and the next section is about them.
Stop the build, or only warn
Two settings in that picture decide how strict a test is.
The severity. error, the default, fails the run and skips what depends on the model. warn only reports the problem and carries on. Use warn for a known issue you are tracking, never to silence a test you do not want to fix.
The thresholds. warn_if and error_if are both !=0 by default: one bad row is enough. Set warn_if: ">10" and error_if: ">100", and the test passes with a few bad rows, warns past 10 and fails past 100.
The command matters too. The older habit, dbt run then dbt test, builds every model first, so bad rows have already reached the marts before any test complains. Prefer dbt build.
A broken key, and a warning
import minidbt
project = minidbt.Project(
models={
'stg_products': "select product_id, name from {{ source('shop', 'products') }}",
'stg_order_items': "select order_id, line_no, product_id, qty from {{ source('shop', 'order_items') }}",
'stg_payments': "select payment_id, status from {{ source('shop', 'payments') }}",
},
tests={
'stg_order_items': {'product_id': [{'relationships': {'to': 'stg_products', 'field': 'product_id'}}]},
'stg_payments': {'status': [{'accepted_values': ['captured', 'failed'], 'severity': 'warn'}]},
},
# read order lines from the 2 June landing file, which has a line for product 999
sources={'shop': {'order_items': 'landing/order_items/2025-06-02.csv'}},
)
project.build()
Two tests, two outcomes. The relationships test fails: one order line points at product 999, which does not exist. The payments test only warns about refunded, a real status nobody listed. The fix is to add it to the list, which is exactly what a warning is for.
NULLs pass unique and accepted_values. Both tests skip missing values, so a column full of NULLs passes them happily. Pair them with not_null whenever a value is required. And test where it counts: a key tested in staging can still be duplicated by a careless join in a mart, so test the mart's grain too.
Any rule you can write as SQL
The four generic tests cover keys and codes. Business rules need more. Take this one: an order's captured payments must add up to its total.
No generic test says that. So you write the query yourself: a .sql file in the tests/ folder that returns the rows that break the rule. dbt calls it a singular test. Same idea as before: zero rows pass, any rows fail.
It is the reconciliation idea from Module 7, now run on every build.
A singular test for a business rule
import duckdb
import minidbt
project = minidbt.Project('models') # reads models/*.sql, and tests/*.sql as singular tests
project.build()
# Look at the failing rows yourself
sql = open('tests/assert_captured_matches_total.sql').read()
duckdb.sql(project.compile(sql)).show()
The test fails, and the last lines print the row it found: order 1033, charged twice. Open tests/assert_captured_matches_total.sql under the code to read the rule.
Test the logic, promise the shape
Every test so far checks data: today's rows. Two more tools check other things.
A unit test checks the logic. You give the model two or three made-up rows and the output you expect. dbt runs the model's SQL on your rows and compares. A bug in a filter fails the test, even on a day when the real data happens to look fine.
A contract is a promise about shape. It fixes the model's column names and types in YAML. Before building, dbt compares the query's columns with the contract. If they differ, the build stops, before anyone who reads the model breaks.
A contract and a unit test (dbt 1.8 and later)
Runs with dbt:
models:
- name: fct_daily_revenue
config:
contract:
enforced: true
columns:
- name: order_date
data_type: date
constraints:
- type: not_null
- name: orders
data_type: bigint
- name: revenue
data_type: numeric(12,2)
unit_tests:
- name: cancelled_orders_are_not_revenue
model: fct_daily_revenue
given:
- input: ref('int_order_totals')
rows:
- {order_id: 1, order_date: 2025-06-01, status: delivered, order_total: 10.00}
- {order_id: 2, order_date: 2025-06-01, status: cancelled, order_total: 99.00}
expect:
rows:
- {order_date: 2025-06-01, orders: 1, revenue: 10.00}
Top half: the contract for fct_daily_revenue, three columns with their types. Bottom half: a unit test that feeds the model one delivered order of $10 and one cancelled order of $99, and expects one order and $10.00 of revenue.
A unit test, start to finish
Four steps: two made-up rows are swapped in for the model's input, the model's SQL runs on them, the output is one order with revenue 10.00, and it matches the expected row, so the test passes.
Read it left to right. No real data is touched: only your rows go in, so the test checks the logic and nothing else.
A contract stops the build
Runs with dbt:
$ dbt build --select fct_daily_revenue
This model has an enforced contract that failed.
Please ensure the name, data_type, and number of columns in your contract match the columns in your model's definition.
| column_name | definition_type | contract_type | mismatch_reason |
| ----------- | --------------- | ------------- | ------------------ |
| revenue | DOUBLE | NUMERIC | data type mismatch |
The contract says revenue is numeric(12,2). The model returns round(sum(line_amount), 2) over a double column, so its type is DOUBLE. Nothing was built and nothing after it ran. The fix is in the model: cast(... as numeric(12,2)).
Numbers to remember
| Name | What to remember |
|---|---|
| severity | error by default; with warn, dbt skips errorif, so the test can only warn |
| warnif, errorif | both !=0 by default; with severity error, dbt checks errorif first, then warnif |
| storefailures: true | saves the failing rows to a table named after the test, in the schema <targetschemadbttestaudit, replaced on every run |
| datatests: | called tests: before dbt 1.8; both work. From dbt 1.10.5 a test's settings can sit under arguments: |
| Unit tests | dbt 1.8 and later. Only the columns you name matter. Direct parents must exist but may be empty: dbt run --select stgcustomers --empty |
| Unit tests, more | overrides: {macros: {isincremental: true}} tests an incremental branch. Fixtures never change, so dbt Labs recommends running unit tests in development and CI only |
| Contracts | dbt also writes the types and constraints into the CREATE TABLE statement. notnull is enforced almost everywhere; primary and foreign keys usually are not (Postgres enforces them) |
| Versions | versions: [{v: 1}, {v: 2}] builds dimcustomersv1 and dimcustomersv2; ref('dimcustomers', v=1) pins a reader; latestversion sets what a plain ref means |
| In CI | dbt build --select state:modified+ runs only the changed models and what depends on them |
| More tests | the packages dbtutils and dbt-expectations add tests; tools such as Elementary track test results over time |
Versions are how a contracted model makes a breaking change safely: readers move from v1 to v2 when they are ready.
What changed at SwiftKart
stg_customers.email now carries not_null and unique. The next dbt build fails on Maya's three accounts, dim_customers is skipped, and finance keeps yesterday's good numbers until the duplicate is fixed. Tess hears about it from the build, not from her report.
Every key has the same pair of tests. A singular test reconciles payments with order totals, and fct_daily_revenue has a contract and a unit test.
One thing still hurts. fct_orders is rebuilt from scratch on every run, and the run gets longer every month. Lesson 8.4 builds only what changed.
In one line
A dbt test is a SELECT that returns the bad rows: put unique and not_null on every key, write singular tests for business rules, and run dbt build so a failure stops bad data before it reaches a mart.
Interview corner
What kinds of tests does dbt support?
Generic data tests attached in YAML (not_null, unique, accepted_values, relationships, plus more from packages), singular tests (a SQL file that returns bad rows), unit tests since dbt 1.8 (mock input rows and expected output, to test logic), source freshness checks, and model contracts that enforce column names and types at build time.
A unique test fails in production at 6 am. What happens and what do you do?
With dbt build, models downstream of the failing model are skipped, so the marts keep yesterday's good data and the job alerts. I would query the failing rows (dbt can store them with store_failures), find whether the source sent duplicates or a join fanned out, fix the cause (dedup in staging, fix the join key), and rerun the failed model and its children with dbt build --select model+.
Why can a column pass unique and accepted_values and still be wrong?
Both tests ignore NULLs, so a column of missing values passes them. They also say nothing about whether the values are correct, only that they are distinct or on a list. Add not_null where a value is required, and reconciliation or unit tests for correctness.
Thirty teams read your dim_customers. How do you stop a breaking column change from reaching them?
I put an enforced contract on the model, so a change that removes or retypes a column fails the build, and CI selecting state:modified against production raises a contract error for the breaking change before merge. When the change is intended, I add a new version: dim_customers_v2 is built next to v1, consumers pin ref('dim_customers', v=1) until they migrate, and a deprecation_date on v1 sets the deadline. Unit tests cover the logic, and data tests on the grain cover the data.