pytest: writing and running tests
Data Quality Automation with Python · 7 questions
Short notes
Key idea
pytest runs automated tests: functions named test_* in files named test_*.py, using plain assert. It shows both sides of a failed assert, and returns an exit code (0 = all passed, 1 = failures) that CI and pipelines use to stop on bad data or code.
Syntax
# test_dw_orders.py
import pandas as pd
import pytest
dw_orders = pd.read_csv("data/dw_orders.csv")
def test_no_duplicate_order_ids():
dups = dw_orders.loc[dw_orders["order_id"].duplicated(), "order_id"].tolist()
assert dups == [], f"duplicated order ids: {dups}"
def test_unknown_status_is_rejected():
with pytest.raises(ValueError, match="unknown status"):
status_group("on_hold")
pytest -v | -q | -k "name expr" | -x | --lf | file.py::test_name
Example
assert status_group("returned") == "lost" fails with assert 'fulfilled' == 'lost', which is the warehouse's mapping bug. The data tests fail with "duplicated order ids: [46, 47]" and "orders missing from dw_orders: [57, 75]".
Traps
- Names without the
test_prefix are silently skipped. assert (cond, "msg")is a tuple: always true.- Put failing keys in assert messages.
- Exit code 5 (no tests collected) is not a pass.
Want the full lesson with step-by-step examples, a project and a certificate? Data Quality Automation with Python course, ₹120 →
- Question 1easy
What does this print?
passed = 0 for x in [5, 0, -3, 12]: try: assert x > 0 passed += 1 except AssertionError: pass print(passed) - Question 2easy
Which test will pytest run by default?
- Question 3medium
A failure shows
E AssertionError: assert 'fulfilled' == 'lost'for the lineassert status_group("returned") == "lost". What happened? - Question 4hard
Why does
assert (len(dups) == 0, "duplicates found")never fail? - Question 5easy
You only want to run tests whose names contain
duplicate. Which command?
pytest: writing and running tests
pytest: writing and running tests
pytest: writing and running tests
pytest: writing and running tests
pytest: writing and running tests
2 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.