TECHNOLOGIESTieInn Technologies

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 →

Questions

Open in Code Lab5 free questions
5 questions

    pytest: writing and running tests

  1. 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)
  2. pytest: writing and running tests

  3. Question 2easy

    Which test will pytest run by default?

  4. pytest: writing and running tests

  5. Question 3medium

    A failure shows E AssertionError: assert 'fulfilled' == 'lost' for the line assert status_group("returned") == "lost". What happened?

  6. pytest: writing and running tests

  7. Question 4hard

    Why does assert (len(dups) == 0, "duplicates found") never fail?

  8. pytest: writing and running tests

  9. Question 5easy

    You only want to run tests whose names contain duplicate. Which command?

2 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.