13. Catch Orphaned and Invalid Payments
Difficulty: Medium · Topic: Data tests
Write models/schema.yml tests for payments (payment_id, order_id, method, amount). The orders model (order_id, status) is also in the project.
payment_idis unique and never missing.- Every payment belongs to an order:
order_idis never missing and always exists inorders. methodis one ofcard,upi,bank_transfer,gift_card.amountis greater than zero (refunds live in another model).
Clean datasets must pass every test; broken ones must make at least one test fail. dbt_utils is installed: dbt_utils.accepted_range and dbt_utils.expression_is_true are available.
Your schema.yml tests run on 8 datasets, including hidden ones: clean datasets must pass every test, broken ones must make a test fail.
Clean data (clean)
{{ ref('payments') }}
| payment_id | order_id | method | amount |
|---|---|---|---|
| 100 | 1 | card | 25 |
| 101 | 2 | upi | 40 |
| 102 | 2 | card | 5 |
{{ ref('orders') }}
| order_id | status |
|---|---|
| 1 | paid |
| 2 | paid |
| 3 | pending |
A payment for an unknown order (broken)
Order 9 was never loaded.
{{ ref('payments') }}
| payment_id | order_id | method | amount |
|---|---|---|---|
| 100 | 1 | card | 25 |
| 103 | 9 | upi | 12 |
{{ ref('orders') }}
| order_id | status |
|---|---|
| 1 | paid |
| 2 | paid |
Hints
Hint 1
relationships checks a foreign key: - relationships: {arguments: {to: "ref('orders')", field: order_id}}.Hint 2
Like most tests,relationships skips nulls: a payment with no order passes it. "Never missing" needs not_null as well.Hint 3
"Greater than zero" excludes zero:dbt_utils.accepted_range with min_value: 0 and inclusive: false, or dbt_utils.expression_is_true with expression: "> 0" on the column.Learn the concepts
- Data tests · 5 min read. unique, not_null, accepted_values and relationships, singular tests, and how a test fails: it returns rows.