Start here
A test is a small piece of code that checks your code. You give it an input and the answer you expect.
A pipeline runs again and again. Tomorrow it reads new data. Next month a teammate changes it.
A test tells you right away when the answer changes.
Here is the shop from the earlier chapters. The function paid_total adds up the amounts of paid orders. The test uses assert.
The word assert means: this must be true. If it is false, Python stops with an AssertionError and shows your message.
| order_id | customer_id | status | amount | order_date |
|---|---|---|---|---|
| 101 | 1 | paid | 40.0 | 2026-01-03 |
| 102 | 1 | paid | 25.0 | 2026-01-10 |
| 103 | 2 | refunded | 60.0 | 2026-01-11 |
| 104 | 3 | paid | 15.5 | 2026-01-15 |
| 105 | 3 | pending | None | 2026-01-20 |
| 106 | 4 | paid | 80.0 | 2026-01-21 |
orders = [
{"order_id": 101, "customer_id": 1, "status": "paid",
"amount": 40.0, "order_date": "2026-01-03"},
{"order_id": 102, "customer_id": 1, "status": "paid",
"amount": 25.0, "order_date": "2026-01-10"},
{"order_id": 103, "customer_id": 2, "status": "refunded",
"amount": 60.0, "order_date": "2026-01-11"},
{"order_id": 104, "customer_id": 3, "status": "paid",
"amount": 15.5, "order_date": "2026-01-15"},
{"order_id": 105, "customer_id": 3, "status": "pending",
"amount": None, "order_date": "2026-01-20"},
{"order_id": 106, "customer_id": 4, "status": "paid",
"amount": 80.0, "order_date": "2026-01-21"},
]
def paid_total(orders):
total = 0
for order in orders:
if order["status"] == "paid":
total += order["amount"]
return total
def test_paid_total():
total = paid_total(orders)
assert total == 160.5, f"expected 160.5, got {total}"
test_paid_total()
print("test passed")| output |
|---|
| test passed |
Now a teammate wants to “simplify” the filter. They write != "pending" instead of == "paid". Run the same test again:
| order_id | customer_id | status | amount | order_date |
|---|---|---|---|---|
| 101 | 1 | paid | 40.0 | 2026-01-03 |
| 102 | 1 | paid | 25.0 | 2026-01-10 |
| 103 | 2 | refunded | 60.0 | 2026-01-11 |
| 104 | 3 | paid | 15.5 | 2026-01-15 |
| 105 | 3 | pending | None | 2026-01-20 |
| 106 | 4 | paid | 80.0 | 2026-01-21 |
def paid_total(orders):
total = 0
for order in orders:
if order["status"] != "pending":
total += order["amount"]
return total
test_paid_total()| output |
|---|
| AssertionError: expected 160.5, got 220.5 |
Without the test, the job runs with no error and the report is wrong.
What you will learn
- How to test a function, including odd inputs.
- How to run tests with a tool called pytest, and how to fake a clock or an API.
- How to find a bug: read an error message, and stop a program to look inside.
- How to write counts to a log, and keep secrets out of it.
- How to check that row counts add up.
