14. Testing with pytest
Data code fails quietly. A price parser that drops the thousands separator does not crash; it turns 1,299.00 USD into 1.299 USD, and every report after it is wrong. In this module you write tests: small programs that run your code on known inputs and check the results. You test the cleaning functions for data/sales_raw.csv, a pandas report, a churn model and a small package, and you run every test with pytest, the standard test tool for Python.
What you will learn
Section titled “What you will learn”- Write test functions with plain
assertand run them with pytest; read the dots, the summary and the exit code. - Read a failure report: which test failed, which values differed and on which line.
- Share setup code with fixtures and
conftest.py, and run one test over many inputs with@pytest.mark.parametrize. - Test files, floats, exceptions, printed output and environment variables with
tmp_path,pytest.approx,pytest.raises,capsysandmonkeypatch. - Test pandas and NumPy results, and smoke-test a machine learning model.
- Lay out a project with
src/andtests/, select tests with-k,-xand markers, and measure coverage with pytest-cov.
Prerequisites
Section titled “Prerequisites”- Functions, return values and docstrings: 05. Functions.
assert, exceptions andraise: 06. Errors and debugging.pathliband thecsvmodule: 07. Files and data formats.- Imports, packages, the src layout and
pyproject.toml: 08. Modules, packages and environments. withand generator functions withyield: 11. Decorators and context managers.
pytest and pytest-cov are in the course environment. In your own project, add them with uv add --dev pytest pytest-cov. Examples 5 and 6 use a little pandas and scikit-learn; modules 24 and 34 teach them, so here you only read the test logic.
Concepts
Section titled “Concepts”Why automated tests
Section titled “Why automated tests”Until now you checked your code by eye: you ran it, looked at the output and decided that it was right. That works once. It does not work after the tenth change, at 2 a.m., on code that a colleague changed.
An automated test (or just test) is code that runs a piece of your program on a known input and checks the result without a person. A test suite is the set of all tests of a project. You run the suite after every change. If a change breaks something that worked before, the suite tells you at once. Such a break is a regression, and a test that guards against it is a regression test.
| Check by eye | Automated test | |
|---|---|---|
| Who decides “correct” | you, each time | the test, written once |
| Cost of a rerun | minutes of attention | about a second |
| Catches a regression | only if you look at the right line | every time the suite runs |
| Documents the rules | no | yes: each test is an example of correct use |
Tests come in three sizes:
- A unit test checks one small unit, usually one function, in isolation:
parse_price("$1,299.00")returns1299.0. - An integration test checks that several parts work together:
clean_file()reads a CSV, cleans each row, drops duplicates and writes the result. - An end-to-end test runs the whole program as a user would:
python clean.py data/sales_raw.csv out.csv, then checks the output file.
| Level | Share of a healthy suite | Speed | Example in this module |
|---|---|---|---|
| Unit | most tests | milliseconds | parse_date("07/01/2023") returns 7 January 2023 |
| Integration | fewer | up to a second | clean_file() on a six-row CSV |
| End-to-end | fewest | seconds | python x05_cli.py data/sales_raw.csv clean.csv |
Most tests in a healthy suite are unit tests: they are fast and they point to the exact function that broke. This module tests the cleaning functions in cleaning.py. They turn the raw text of one cell of data/sales_raw.csv into a clean value:
| Function | Raw input | Result |
|---|---|---|
parse_price |
"$1,299.00", "N/A" |
1299.0, None |
parse_discount |
"0.05", "-" |
0.05, 0.0 |
normalize_region |
" north " |
"North" |
clean_product |
"Espresso Machine" |
"Espresso Machine" |
parse_date |
"07/01/2023", "January 7, 2023" |
date(2023, 1, 7) |
clean_file |
a raw CSV path | a clean CSV and a dict of counts |
Here is the module. Read it once; the tests below refer to it.
"""Clean the messy columns of data/sales_raw.csv.
Each parse_* function takes the raw text of one cell and returns a clean value."""
import csvfrom datetime import date, datetimefrom pathlib import Path
MISSING_TOKENS = frozenset({"", "N/A", "-"})REGIONS = frozenset({"North", "South", "East", "West"})DATE_FORMATS = ("%Y-%m-%d", "%d/%m/%Y", "%B %d, %Y")MAX_QUANTITY = 100CLEAN_COLUMNS = [ "order_id", "order_date", "region", "product", "unit_price", "quantity", "discount",]
def is_missing(text: str) -> bool: """Return True for the tokens that mean "no value" in the raw file.""" return text.strip() in MISSING_TOKENS
def parse_price(text: str) -> float | None: """Turn '$1,299.00' into 1299.0. Return None for a missing token.""" if is_missing(text): return None return float(text.strip().removeprefix("$").replace(",", ""))
def parse_discount(text: str) -> float: """Turn '0.05' into 0.05. A missing discount means no discount: 0.0.""" if is_missing(text): return 0.0 value = float(text) if not 0 <= value < 1: raise ValueError(f"discount out of range: {text!r}") return value
def normalize_region(text: str) -> str | None: """Turn ' north ' into 'North'. Return None for a missing token.""" if is_missing(text): return None region = text.strip().title() if region not in REGIONS: raise ValueError(f"unknown region: {text!r}") return region
def clean_product(name: str) -> str: """Remove leading, trailing and repeated inner spaces.""" return " ".join(name.split())
def parse_date(text: str) -> date: """Parse the three date formats of the raw file.""" for fmt in DATE_FORMATS: try: return datetime.strptime(text.strip(), fmt).date() except ValueError: pass raise ValueError(f"unknown date format: {text!r}")
def is_valid_quantity(quantity: int) -> bool: """A sales line sells 1 to MAX_QUANTITY units.""" return 1 <= quantity <= MAX_QUANTITY
def line_revenue(unit_price: float, quantity: int, discount: float = 0.0) -> float: """Revenue of one sales line, rounded to cents.""" return round(unit_price * quantity * (1 - discount), 2)
def clean_row(row: dict[str, str]) -> dict[str, object]: """Clean one raw row, as csv.DictReader returns it.""" return { "order_id": row["order_id"], "order_date": parse_date(row["order_date"]), "region": normalize_region(row["region"]), "product": clean_product(row["product"]), "unit_price": parse_price(row["unit_price"]), "quantity": int(row["quantity"]), "discount": parse_discount(row["discount"]), }
def clean_file(src: Path, dst: Path) -> dict[str, int]: """Clean a raw sales file, drop duplicates and bad quantities, write dst.""" with src.open(newline="", encoding="utf-8") as file: rows = list(csv.DictReader(file)) counts = {"read": len(rows), "duplicates": 0, "bad_quantity": 0, "written": 0} seen: set[tuple[str, ...]] = set() kept = [] for row in rows: key = tuple(row.values()) if key in seen: counts["duplicates"] += 1 continue seen.add(key) if not is_valid_quantity(int(row["quantity"])): counts["bad_quantity"] += 1 continue kept.append(clean_row(row)) with dst.open("w", newline="", encoding="utf-8") as file: writer = csv.DictWriter(file, fieldnames=CLEAN_COLUMNS) writer.writeheader() writer.writerows(kept) counts["written"] = len(kept) return countsA test is a function with an assert
Section titled “A test is a function with an assert”A test has three parts. This pattern is called Arrange–Act–Assert (AAA):
- Arrange: build the input.
- Act: call the code under test once.
- Assert: check the result with
assert.
Module 06 introduced assert condition: it does nothing when the condition is true and raises AssertionError when it is false. A test function is an ordinary function whose name starts with test_ and that contains asserts. You can call it yourself:
from cleaning import parse_price
def test_parse_price_thousands_separator(): raw = "$1,299.00" # arrange price = parse_price(raw) # act assert price == 1299.0 # assert
test_parse_price_thousands_separator()print("test passed")test passedThe call returned without an error, so the assert held. When the assert is false, plain Python tells you very little:
def test_parse_price_cents(): assert parse_price("$79.99") == 79.90
test_parse_price_cents()AssertionErrorThe message is empty. You do not know which value parse_price returned. pytest fixes this, and it finds and runs all test functions for you.
Run tests with pytest
Section titled “Run tests with pytest”pytest is a test runner: a program that finds tests, runs them and reports the results. Its test discovery rules are simple:
| pytest collects | Default rule | Example |
|---|---|---|
| files | name matches test_*.py or *_test.py |
test_prices.py |
| functions | name starts with test |
def test_plain_price(): |
| methods | name starts with test, inside a class whose name starts with Test (and that has no __init__) |
class TestPrices: … def test_plain(self): |
Put the test from above into a file next to cleaning.py:
from cleaning import parse_price
def test_parse_price_plain(): assert parse_price("$79.99") == 79.99
def test_parse_price_thousands_separator(): assert parse_price("$1,299.00") == 1299.0The file has no call at the bottom. pytest imports the file, finds the two test_ functions and calls each one:
pytest -q test_first.py.. [100%]2 passed in 0.00s-q (quiet) prints one character per test: . for a pass, F for a failure, E for an error outside the test body (for example in a fixture) and s for a skip. [100%] is the progress. The last line counts the results and gives the run time. Your time differs; that is normal.
Without -q, pytest prints a header with your platform and folder. -v (verbose) prints one line per test, with the test’s node ID: the file name, :: and the test name. --no-header drops the header:
pytest -v --no-header test_first.py======================================= test session starts ========================================collecting ... collected 2 items
test_first.py::test_parse_price_plain PASSED [ 50%]test_first.py::test_parse_price_thousands_separator PASSED [100%]
======================================== 2 passed in 0.00s =========================================pytest also returns an exit code (module 08): 0 when all tests pass, 1 when a test fails, 2 when you interrupt it, 4 for a usage error and 5 when it collected no tests. A CI service (module 08) uses the exit code to block a change that breaks a test.
Read a failure report
Section titled “Read a failure report”A test failure is information. Learn to read the report fast. Here is a first draft of two cleaning functions, with bugs on purpose:
"""A first draft of two cleaning functions. It has bugs on purpose."""
def parse_price(text: str) -> float: return float(text.strip("$"))
def normalize_regions(values: list[str]) -> list[str]: return [value.title() for value in values]from draft_cleaning import normalize_regions, parse_price
def test_price_plain(): assert parse_price("$79.99") == 79.99
def test_price_thousands_separator(): assert parse_price("$1,299.00") == 1299.0
def test_regions_case_and_spaces(): raw = ["north", " East "] assert normalize_regions(raw) == ["North", "East"]
def test_price_count(): prices = [parse_price(text) for text in ["$14.99", "$59.99", "$249.00"]] assert len(prices) == 3--tb=short keeps each traceback short (tb is short for traceback):
pytest -q --tb=short test_broken.py.FF. [100%]============================================= FAILURES =============================================__________________________________ test_price_thousands_separator __________________________________test_broken.py:9: in test_price_thousands_separator assert parse_price("$1,299.00") == 1299.0 ^^^^^^^^^^^^^^^^^^^^^^^^draft_cleaning.py:5: in parse_price return float(text.strip("$")) ^^^^^^^^^^^^^^^^^^^^^^E ValueError: could not convert string to float: '1,299.00'___________________________________ test_regions_case_and_spaces ___________________________________test_broken.py:14: in test_regions_case_and_spaces assert normalize_regions(raw) == ["North", "East"]E AssertionError: assert ['North', ' East '] == ['North', 'East']EE At index 1 diff: ' East ' != 'East'E Use -v to get more diff===================================== short test summary info ======================================FAILED test_broken.py::test_price_thousands_separator - ValueError: could not convert string to f...FAILED test_broken.py::test_regions_case_and_spaces - AssertionError: assert ['North', ' East '] ...2 failed, 2 passed in 0.01sRead it in this order:
- The last line. 2 failed, 2 passed. The progress line
.FF.shows which: the second and third tests. - The short test summary. One line per failure: the node ID and the last line of the error.
- Each FAILURES section. It starts with the test name. The lines show the call chain, from the test down to the line that raised. Lines that start with
Eare the error. - The values. The second failure shows both sides of
==: the list on the left holds' East 'with spaces, the expected list holds'East'. pytest even names the first differing index.
The first failure is an error inside the code under test: float() cannot read '1,299.00', because strip("$") leaves the comma. The second failure is a wrong result: .title() keeps the spaces. Both are real bugs in the draft.
How does pytest know the two lists? It rewrites every assert statement in a test file before it runs it. This assertion rewriting records the value of each part of the expression, so a failure can show them. That is why plain assert is all you need: no assertEqual, no special methods.
Without --tb=short, pytest shows the full source of each failing test (--tb=long, the default). --tb=no shows only the summary, and --tb=line one line per failure.
Select which tests run
Section titled “Select which tests run”A real suite has hundreds of tests. These options run only part of it:
| Option | Runs | Example |
|---|---|---|
| a file or folder | the tests in it | pytest tests/test_dates.py |
| a node ID | one test | pytest "test_dates.py::test_parse_date[iso]" |
-k EXPR |
tests whose name matches the expression | -k price, -k "price and not plain" |
-m EXPR |
tests with a marker | -m "not slow" |
-x |
stop at the first failure | pytest -x |
--lf |
only the tests that failed last time | pytest --lf |
--ff |
the last failures first, then the rest | pytest --ff |
-k matches substrings of test names, with and, or and not:
pytest -q --tb=no -k "price and not count" test_broken.py.F [100%]===================================== short test summary info ======================================FAILED test_broken.py::test_price_thousands_separator - ValueError: could not convert string to f...1 failed, 1 passed, 2 deselected in 0.01sThree tests have price in their name, and not count removes one of them. So two tests run and two are deselected: collected but not run. -x stops at the first failure, which saves time when one broken import makes every test fail:
pytest -q --tb=no -x test_broken.pyecho "exit code: $?".F===================================== short test summary info ======================================FAILED test_broken.py::test_price_thousands_separator - ValueError: could not convert string to f...!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! stopping after 1 failures !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1 failed, 1 passed in 0.00sexit code: 1$? is the shell variable that holds the exit code of the last command: 1, because a test failed.
Fixtures: reusable test setup
Section titled “Fixtures: reusable test setup”Many tests need the same input: a raw row, a small CSV file, a database connection. Copying the setup into every test is long and error-prone. A fixture is a function that prepares a resource for tests. You mark it with @pytest.fixture. A test asks for a fixture by naming it as a parameter; pytest calls the fixture and passes its return value in. This is a form of dependency injection: the test declares what it needs, and pytest provides it.
Fixtures that several test files share live in a file called conftest.py. pytest loads it automatically; you never import it. This conftest.py defines two fixtures: raw_row (one messy row) and raw_csv (a small raw file):
"""Fixtures shared by every test file in this folder."""
from pathlib import Path
import pytest
# Six rows modeled on real lines of data/sales_raw.csv: one of each problem.RAW_SAMPLE = """\order_id,order_date,region,product,unit_price,quantity,discountO000133,2023-01-10, North ,Wireless Earbuds,$79.99,1,0.0O000145,2023-01-11,West,55-inch 4K Smart TV,"$1,299.00",2,0.0O001806,2023-05-11,,Wireless Earbuds,$79.99,1,-O002118,27/05/2023,South,Mineral Sunscreen SPF 50,$15.99,999,0.05O002353,"June 9, 2023",North,Electric Toothbrush ,$59.99,2,0.0O002353,"June 9, 2023",North,Electric Toothbrush ,$59.99,2,0.0"""
@pytest.fixturedef raw_row() -> dict[str, str]: """One messy row, as csv.DictReader returns it.""" return { "order_id": "O000096", "order_date": "January 7, 2023", "region": " North ", "product": "Chef's Knife Set ", "unit_price": "$129.95", "quantity": "1", "discount": "N/A", }
@pytest.fixturedef raw_csv(tmp_path: Path) -> Path: """Write RAW_SAMPLE to a fresh temporary folder and return its path.""" path = tmp_path / "sales_raw.csv" path.write_text(RAW_SAMPLE, encoding="utf-8") return pathThree tests use raw_row:
from datetime import date
from cleaning import clean_row
def test_clean_row(raw_row): clean = clean_row(raw_row) assert clean["order_date"] == date(2023, 1, 7) assert clean["region"] == "North" assert clean["product"] == "Chef's Knife Set" assert clean["unit_price"] == 129.95 assert clean["discount"] == 0.0
def test_changes_stay_inside_one_test(raw_row): raw_row["region"] = "garbage" assert raw_row["region"] == "garbage"
def test_each_test_gets_a_fresh_row(raw_row): assert raw_row["region"] == " North "pytest -q test_fixtures.py... [100%]3 passed in 0.01sThe second test damages its row, and the third still gets the original. By default pytest calls a fixture again for every test that uses it, so tests cannot leak changes into each other. Tests that do not depend on each other are isolated: you can run them alone, in any order.
Fixture scope sets how often pytest calls the fixture:
| Scope | Created | Use for |
|---|---|---|
"function" (default) |
once per test | anything a test may change |
"class" |
once per test class | shared state of a Test... class |
"module" |
once per test file | a dataset loaded from disk, a trained model |
"session" |
once per pytest run | an expensive resource that no test changes |
A wider scope is faster but shares one object between tests. Use it only for objects that no test changes. Example 6 trains a model once per file with scope="module".
A fixture can also clean up. Write yield instead of return: the code before yield is the setup, the test runs at the yield, and the code after it is the teardown. It runs even when the test fails. This is the same idea as @contextmanager in module 11. A fixture with yield is a generator function, so its type hint is an iterator of the value it yields: -> Iterator[sqlite3.Connection], with Iterator from collections.abc (module 12).
import sqlite3from collections.abc import Iterator
import pytest
@pytest.fixturedef sales_db() -> Iterator[sqlite3.Connection]: conn = sqlite3.connect(":memory:") conn.execute("CREATE TABLE sales (region TEXT, revenue REAL)") conn.executemany( "INSERT INTO sales VALUES (?, ?)", [("North", 224.1), ("North", 79.99), ("West", 2598.0)], ) yield conn # the test runs here conn.close() # teardown: runs after the test, even if it failed
def test_row_count(sales_db): (count,) = sales_db.execute("SELECT COUNT(*) FROM sales").fetchone() assert count == 3
def test_north_revenue(sales_db): query = "SELECT SUM(revenue) FROM sales WHERE region = 'North'" (total,) = sales_db.execute(query).fetchone() assert total == pytest.approx(304.09)--setup-show prints each fixture’s setup and teardown. F means function scope:
pytest -q --setup-show test_db_fixture.py SETUP F sales_db test_db_fixture.py::test_row_count (fixtures used: sales_db) . TEARDOWN F sales_db SETUP F sales_db test_db_fixture.py::test_north_revenue (fixtures used: sales_db) . TEARDOWN F sales_db2 passed in 0.01sEach test got its own in-memory database and pytest closed it after the test. pytest also has built-in fixtures that you request by name: tmp_path, capsys, monkeypatch and others. The next sections use them.
Parametrize: one test, many inputs
Section titled “Parametrize: one test, many inputs”Data has many spellings of the same value. One test per spelling is a lot of copy-paste. @pytest.mark.parametrize runs one test function once per set of arguments. Give it the argument names and a list of values:
import pytest
from cleaning import clean_product
@pytest.mark.parametrize( ("raw", "expected"), [ ("Wireless Earbuds", "Wireless Earbuds"), (" Air Purifier", "Air Purifier"), ("Fitness Tracker ", "Fitness Tracker"), ("Espresso Machine", "Espresso Machine"), ],)def test_clean_product(raw, expected): assert clean_product(raw) == expectedpytest -v --no-header test_products.py======================================= test session starts ========================================collecting ... collected 4 items
test_products.py::test_clean_product[Wireless Earbuds-Wireless Earbuds] PASSED [ 25%]test_products.py::test_clean_product[ Air Purifier-Air Purifier] PASSED [ 50%]test_products.py::test_clean_product[Fitness Tracker -Fitness Tracker] PASSED [ 75%]test_products.py::test_clean_product[Espresso Machine-Espresso Machine] PASSED [100%]
======================================== 4 passed in 0.01s =========================================pytest made four tests. Each one has a test ID in square brackets, built from the argument values. If one case fails, the other three still run and report, unlike a for loop inside one test, which stops at the first failing case. Example 4 gives the cases readable IDs with pytest.param(..., id="...").
tmp_path: a fresh folder for each test
Section titled “tmp_path: a fresh folder for each test”A test that writes files must not write into your project or into data/. tmp_path is a built-in fixture: a pathlib.Path to a new, empty folder, unique to each test. pytest keeps the folders of the last three runs and deletes older ones.
import csv
def test_write_and_read_back(tmp_path): path = tmp_path / "regions.csv" with path.open("w", newline="", encoding="utf-8") as file: csv.writer(file).writerows([["region", "lines"], ["North", "291"]]) with path.open(newline="", encoding="utf-8") as file: rows = list(csv.DictReader(file)) assert rows == [{"region": "North", "lines": "291"}] assert [p.name for p in tmp_path.iterdir()] == ["regions.csv"]pytest -q test_tmp.py. [100%]1 passed in 0.01sThe last assert proves that the folder started empty. The raw_csv fixture in conftest.py builds on tmp_path: a fixture can request other fixtures, just like a test. A fixture can also return a function instead of a value. Such a factory fixture lets each test build its own variant, for example make_row(region="north"); the mini-project uses two. For a folder shared by many tests, use the session-scoped tmp_path_factory fixture and call tmp_path_factory.mktemp("name").
pytest.approx: compare floats
Section titled “pytest.approx: compare floats”Floats are approximate (module 01): 0.1 + 0.2 == 0.3 is False. pytest.approx(expected) makes a value that compares equal to anything close enough:
import pytest
print(0.1 + 0.2 == 0.3, 0.1 + 0.2 == pytest.approx(0.3))print(pytest.approx(672.3))print([0.1 + 0.2, 0.7] == pytest.approx([0.3, 0.7]))print({"mean": 177.61000001} == pytest.approx({"mean": 177.61}))False True672.3 ± 6.7e-04TrueTrueapprox works with numbers, lists, tuples, dicts and NumPy arrays. Its repr shows the tolerance. The check is:
The defaults are rel=1e-6 (a relative tolerance: one part in a million of the expected value) and abs=1e-12 (an absolute tolerance, which matters only near 0). Pass your own when the default is wrong for the data:
print(1201 == pytest.approx(1200, rel=0.01), 1213 == pytest.approx(1200, rel=0.01))print(1e-13 == pytest.approx(0.0))True FalseTrueA 1% tolerance accepts 1201 rows but not 1213. Keep approx on the right-hand side of ==. pytest then shows the tolerance in a failure report.
pytest.raises: test the error path
Section titled “pytest.raises: test the error path”Good cleaning code rejects bad input loudly. A test of that rule must check that the error happens. pytest.raises is a context manager. The with block passes only if its code raises the given exception type. match= is a regular expression that re.search must find in the error message:
from cleaning import parse_discount
with pytest.raises(ValueError, match="out of range") as excinfo: parse_discount("15")print(type(excinfo.value).__name__, excinfo.value)ValueError discount out of range: '15'excinfo.value is the exception object, for more checks after the block. When the code does not raise, pytest.raises fails the test:
with pytest.raises(ValueError): parse_discount("0.05")Failed: DID NOT RAISE ValueErrorFailed is pytest’s own exception for a failed test. Two rules keep error tests honest:
- Put only the one call that should raise inside the
withblock. Otherwise an earlier line may raise the error and the test passes for the wrong reason. - Always add
match=.ValueErroralone also passes when the code fails with a differentValueError, for example fromfloat().
capsys and monkeypatch
Section titled “capsys and monkeypatch”Two more built-in fixtures cover code that talks to the outside world:
capsyscaptures what the code prints.capsys.readouterr()returns an object with.out(standard output) and.err(standard error), and empties the buffers.monkeypatchchanges the environment for one test and undoes the change afterwards:setenvanddelenvfor environment variables,setattrto replace an attribute or a function,chdirto change the folder.
The report.py module has a function that prints counts and one that reads the data folder from an environment variable:
"""Summaries of cleaned sales data."""
import osfrom pathlib import Path
import pandas as pd
def revenue_by_region(sales: pd.DataFrame) -> pd.DataFrame: """Total revenue and number of lines per region, largest revenue first.""" return ( sales.groupby("region", as_index=False) .agg(revenue=("revenue", "sum"), lines=("revenue", "size")) .sort_values("revenue", ascending=False, ignore_index=True) )
def print_summary(counts: dict[str, int]) -> None: """Print the counts that clean_file returns, one per line.""" for name, value in counts.items(): print(f"{name:<13}{value:>6,}")
def data_dir() -> Path: """The data folder: $SALES_DATA_DIR if it is set, else ./data.""" return Path(os.environ.get("SALES_DATA_DIR", "data"))from pathlib import Path
from report import data_dir, print_summary
def test_print_summary(capsys): print_summary({"read": 1200, "duplicates": 36}) captured = capsys.readouterr() assert captured.out == "read 1,200\nduplicates 36\n" assert captured.err == ""
def test_data_dir_default(monkeypatch): monkeypatch.delenv("SALES_DATA_DIR", raising=False) assert data_dir() == Path("data")
def test_data_dir_from_environment(monkeypatch, tmp_path): monkeypatch.setenv("SALES_DATA_DIR", str(tmp_path)) assert data_dir() == tmp_pathpytest -q test_report_output.py... [100%]3 passed in 0.28sdelenv(..., raising=False) removes the variable if it exists, so the default test passes even on a machine where someone set SALES_DATA_DIR. After each test, monkeypatch restores the environment. A replacement object that stands in for a real one during a test is a test double (a fake, a stub or a mock). monkeypatch.setattr is the simplest way to install one; the standard library also has unittest.mock. Use doubles sparingly: a test full of fakes tests the fakes.
Testing pandas and NumPy results
Section titled “Testing pandas and NumPy results”== on two DataFrames compares cell by cell and returns another DataFrame, not one True or False, so assert df1 == df2 raises an error. pandas and NumPy ship their own assert functions:
| Check | Use |
|---|---|
| two DataFrames are equal (values, dtypes, index, column names) | pd.testing.assert_frame_equal(result, expected) |
| two Series are equal | pd.testing.assert_series_equal(result, expected) |
| two arrays are equal, element by element | np.testing.assert_array_equal(result, expected) |
| two float arrays are close | np.testing.assert_allclose(result, expected, rtol=1e-7) |
They raise AssertionError with a precise message. A wrong dtype is a typical failure, for example a count column that is float64 because of a missing value:
import numpy as npimport pandas as pd
result = pd.DataFrame({"region": ["West", "North"], "lines": [1, 2]})expected = pd.DataFrame({"region": ["West", "North"], "lines": [1.0, 2.0]})try: pd.testing.assert_frame_equal(result, expected)except AssertionError as err: print(err)Attributes of DataFrame.iloc[:, 1] (column name="lines") are different
Attribute "dtype" are different[left]: int64[right]: float64assert_frame_equal compares floats with a relative tolerance of 1e-5 by default (check_exact=False), so 304.09000000000003 equals 304.09. Pass check_dtype=False only when the dtype truly does not matter. np.testing.assert_allclose reports the worst element:
try: np.testing.assert_allclose([0.5, 1.0, 1.4999], [0.5, 1.0, 1.5])except AssertionError as err: print(err)Not equal to tolerance rtol=1e-07, atol=0
Mismatched elements: 1 / 3 (33.3%)Mismatch at index: [2]: 1.4999 (ACTUAL), 1.5 (DESIRED)Max absolute difference among violations: 1.e-04Max relative difference among violations: 6.66666667e-05 ACTUAL: array([0.5 , 1. , 1.4999]) DESIRED: array([0.5, 1. , 1.5])The message names the mismatched element (index 2) and the largest differences. Its default rtol=1e-7 is strict; pass rtol=1e-3 for a looser check.
Test layout: src/ and tests/
Section titled “Test layout: src/ and tests/”A small script can keep test_cleaning.py next to cleaning.py. A project keeps the package and the tests apart. Module 08 introduced the src layout; tests go into a tests/ folder next to src/:
salesclean/├── pyproject.toml├── src/│ └── salesclean/│ ├── __init__.py│ └── prices.py└── tests/ ├── test_prices.py ├── test_errors.py └── test_real_data.py- Mirror the package:
src/salesclean/prices.pyhastests/test_prices.py. - Shared fixtures go into
tests/conftest.py. Aconftest.pyapplies to its folder and all folders below it. - The tests import the package by its name,
from salesclean.prices import parse_price, exactly as a user would. pyproject.tomlholds the pytest settings in a[tool.pytest]table, so a barepytestin the project folder does the right thing.
[tool.pytest]testpaths = ["tests"] # where a bare `pytest` looks for testspythonpath = ["src"] # add src/ to sys.path for the testsstrict = true # strict markers, config, xfail and parametrize IDsmarkers = ["slow: reads the full raw data file"]pytest 9 reads [tool.pytest] with native TOML types (lists, booleans). Older projects use [tool.pytest.ini_options] with the same keys; one file must not have both. A marker is a label on a test, such as @pytest.mark.slow. pytest also has built-in markers: skip, skipif and xfail, which marks a test that is expected to fail. strict = true turns on four checks at once: a marker that is not listed under markers is an error (so a typo such as @pytest.mark.slwo cannot silently disable a filter), a typo in the configuration is an error, every xfail is strict (an unexpected pass becomes a failure) and duplicate parametrize IDs are an error. Example 7 builds this project.
Coverage: which lines did the tests run?
Section titled “Coverage: which lines did the tests run?”Code coverage measures which parts of your code ran during the tests. Line coverage (also called statement coverage) counts the lines that ran. Branch coverage also checks that each if went both ways: true and false. The pytest-cov plugin measures it with the coverage package.
How much of cleaning.py do the two tests in test_first.py run?
pytest -q --cov=cleaning --cov-report= test_first.pycoverage report -m.. [100%]2 passed in 0.01sName Stmts Miss Cover Missing-------------------------------------------cleaning.py 65 44 32% 33, 39-44, 49-54, 59, 64-69, 74, 79, 84, 97-117-------------------------------------------TOTAL 65 44 32%--cov=cleaning measures the module cleaning and saves the data to a file called .coverage. --cov-report= (empty) turns off pytest-cov’s own report, and coverage report -m prints the table from that file. Stmts counts statements, Miss the statements that never ran, and Missing lists their line numbers. The two tests ran only 32% of the module: no test touches the dates, the regions or the file cleaner.
Coverage answers one question: which code did no test run? It does not tell you if the tests check the right things. A test without asserts runs lines and catches nothing. Use coverage to find untested branches, not as a score to maximize. Many teams fail the build below a threshold, such as 90%, with coverage report --fail-under=90.
Red, green, refactor
Section titled “Red, green, refactor”Test-driven development (TDD) writes the test before the code. It works in short cycles called red-green-refactor:
flowchart LR
R["Red: write a test that fails"] --> G["Green: write the least code that passes"]
G --> F["Refactor: clean up, tests stay green"]
F --> R
The red step proves the test can fail; a test that has never failed may test nothing. The same cycle fixes bugs: first write a test that reproduces the bug (red), then fix the code (green). The test stays in the suite as a regression test. Example 2 does exactly this.
For old code with unclear behavior, write characterization tests first: tests that record what the code does today, right or wrong. Then you can change the code and see each behavior that changes.
Worked examples
Section titled “Worked examples”Example 1 — Test the price parser on real messy values
Section titled “Example 1 — Test the price parser on real messy values”Goal: data/sales_raw.csv stores prices as text such as $79.99. Find every shape of price text in the file and write one test for each shape.
Step 1 — Find the shapes of the raw prices
Section titled “Step 1 — Find the shapes of the raw prices”import csvimport refrom collections import Counter
with open("data/sales_raw.csv", newline="", encoding="utf-8") as file: prices = [row["unit_price"] for row in csv.DictReader(file)]
shapes = Counter(re.sub(r"\d", "9", text) for text in prices)for shape, count in shapes.most_common(): print(f"{shape!r:<14}{count:>5}")'$99.99' 768'$999.99' 375'$9,999.99' 47'' 6'N/A' 2'-' 2re.sub(r"\d", "9", text) replaces every digit with 9, so all prices with the same shape look alike. The file has six shapes: prices with two or three digits before the point, prices with a thousands separator, and three missing tokens. Each shape is a test case.
Step 2 — Write one test per shape
Section titled “Step 2 — Write one test per shape”import pytest
from cleaning import parse_discount, parse_price
def test_plain_price(): assert parse_price("$79.99") == 79.99
def test_thousands_separator(): assert parse_price("$1,299.00") == 1299.0
def test_surrounding_spaces(): assert parse_price(" $14.99 ") == 14.99
def test_missing_tokens_give_none(): assert parse_price("") is None assert parse_price("N/A") is None assert parse_price("-") is None
def test_garbage_is_rejected(): with pytest.raises(ValueError, match="could not convert"): parse_price("$12.x0")
def test_missing_discount_means_no_discount(): assert parse_discount("N/A") == 0.0
def test_discount_must_be_a_fraction(): with pytest.raises(ValueError, match="out of range"): parse_discount("15")Each test name says the rule it checks. When test_thousands_separator fails, you know the problem before you read the report. The file also tests two shapes that the data does not have yet, spaces and garbage, because the next export may have them. The "could not convert" text comes from float()’s own error message.
Step 3 — Run the tests
Section titled “Step 3 — Run the tests”pytest -q test_prices.py....... [100%]7 passed in 0.01sAll seven pass. The suite now documents what parse_price accepts, and it fails the day someone breaks one of those rules.
Step 4 — Run only the tests about missing values
Section titled “Step 4 — Run only the tests about missing values”pytest -q -k missing test_prices.py.. [100%]2 passed, 5 deselected in 0.01s-k missing selects the two tests with missing in their name. Good names make -k useful.
Common mistakes:
- Testing only the happy path, the normal input that works. The bugs live in the edge cases: an edge case is an input at the border of what the code handles, such as an empty string, a missing token or a thousands separator.
- Comparing
parse_price("N/A") == None. Useis None, as in all Python code. - Writing one test for three unrelated rules, such as the price format, the missing tokens and the discount range. When the first assert fails, the others never run. Several asserts are fine when they check one behavior, as
test_clean_rowchecks the cleaning of one full row; unrelated rules get their own tests.
Example 2 — Fix a region bug with a regression test
Section titled “Example 2 — Fix a region bug with a regression test”Goal: A cleaning run on data/sales_raw.csv stops with ValueError: unknown region: ' North '. Reproduce the bug in a test, fix it, and keep the test so the bug never comes back.
Step 1 — Read the code that has the bug
Section titled “Step 1 — Read the code that has the bug”"""Normalize the region column of data/sales_raw.csv."""
REGIONS = frozenset({"North", "South", "East", "West"})
def normalize_region(text: str) -> str: """Turn 'north' or 'NORTH' into 'North'.""" region = text.title() if region not in REGIONS: raise ValueError(f"unknown region: {text!r}") return regionThe data dictionary lists four kinds of bad region text: lowercase (north), uppercase (NORTH), surrounding spaces (North) and trailing spaces (North ). The function handles only the first two.
Step 2 — Write the test first (red)
Section titled “Step 2 — Write the test first (red)”import pytest
from regions import normalize_region
@pytest.mark.parametrize("raw", ["North", "north", "NORTH", " North ", "North "])def test_north_variants(raw): assert normalize_region(raw) == "North"
def test_unknown_region_is_rejected(): with pytest.raises(ValueError, match="unknown region"): normalize_region("Nort")cd regression/beforepytest -q --tb=no test_regions.py...FF. [100%]===================================== short test summary info ======================================FAILED test_regions.py::test_north_variants[ North ] - ValueError: unknown region: ' North 'FAILED test_regions.py::test_north_variants[North ] - ValueError: unknown region: 'North '2 failed, 4 passed in 0.00sRed: the two spellings with spaces fail, with the same error as the real run. The test reproduces the bug in about a second instead of a full cleaning run. --tb=no is enough here, because the summary lines already show the error.
Step 3 — Fix the code (green)
Section titled “Step 3 — Fix the code (green)”"""Normalize the region column of data/sales_raw.csv."""
REGIONS = frozenset({"North", "South", "East", "West"})
def normalize_region(text: str) -> str: """Turn 'north', 'NORTH' or ' North ' into 'North'.""" region = text.strip().title() if region not in REGIONS: raise ValueError(f"unknown region: {text!r}") return regionThe regression/after/ folder holds the fixed module and the same test file:
cd regression/afterpytest -q test_regions.py...... [100%]6 passed in 0.00sGreen: all six pass. .strip() removes the spaces before .title().
Step 4 — Keep the test
Section titled “Step 4 — Keep the test”The test now protects the fix. If someone “simplifies” the function and drops .strip(), the suite fails with the exact spelling that broke. This is how cleaning.normalize_region got its strip(). The refactor step of the cycle is empty here; the code is already short.
Common mistakes:
- Fixing the bug first and writing the test afterwards. You never see the test fail, so you do not know that it would catch the bug.
- Testing only the one value from the bug report (
" North "). Add its neighbors too:"North "failed for the same reason. - Deleting a regression test because “that bug is fixed”. The test exists for the day the bug returns.
Example 3 — Test the file cleaner with fixtures and tmp_path
Section titled “Example 3 — Test the file cleaner with fixtures and tmp_path”Goal: clean_file() reads a raw CSV, drops duplicates and bad quantities and writes a clean CSV. Test it on a small file with one row for each problem, without touching data/.
Step 1 — Use the raw_csv fixture
Section titled “Step 1 — Use the raw_csv fixture”The raw_csv fixture in conftest.py (see Fixtures) writes six rows to tmp_path: two rows that only need value cleaning (spaces around the region, a thousands separator in the price), one with a missing region, one with a quantity of 999 and one row twice. You can predict the result by hand: 6 read, 1 duplicate, 1 bad quantity, 4 written. A test whose expected value you can work out by hand is a trustworthy test.
Step 2 — Write the tests
Section titled “Step 2 — Write the tests”import csv
from cleaning import clean_file
def test_counts(raw_csv, tmp_path): counts = clean_file(raw_csv, tmp_path / "clean.csv") assert counts == {"read": 6, "duplicates": 1, "bad_quantity": 1, "written": 4}
def test_written_rows(raw_csv, tmp_path): out = tmp_path / "clean.csv" clean_file(raw_csv, out) with out.open(newline="", encoding="utf-8") as file: rows = list(csv.DictReader(file)) assert [row["order_id"] for row in rows] == [ "O000133", "O000145", "O001806", "O002353", ] assert rows[0]["region"] == "North" assert rows[1]["unit_price"] == "1299.0" assert rows[2]["region"] == "" # None is written as an empty cell assert rows[3]["order_date"] == "2023-06-09" assert rows[3]["product"] == "Electric Toothbrush"
def test_input_file_is_unchanged(raw_csv, tmp_path): before = raw_csv.read_text(encoding="utf-8") clean_file(raw_csv, tmp_path / "clean.csv") assert raw_csv.read_text(encoding="utf-8") == beforeEach test asks for raw_csv and tmp_path. Within one test, both get the same temporary folder, so the clean file lands next to the raw one. The third test checks a rule that is easy to forget: a cleaner must never change its input.
Step 3 — Run the tests
Section titled “Step 3 — Run the tests”pytest -q test_clean_file.py... [100%]3 passed in 0.01sThese are integration tests: each one runs the CSV reader, the duplicate check, all the parse functions and the writer together.
Step 4 — Check the real file
Section titled “Step 4 — Check the real file”from pathlib import Path
from cleaning import clean_file
Path("output").mkdir(exist_ok=True)counts = clean_file(Path("data/sales_raw.csv"), Path("output/sales_clean.csv"))print(counts)dropped = counts["duplicates"] + counts["bad_quantity"]print(counts["read"] == dropped + counts["written"]){'read': 1200, 'duplicates': 36, 'bad_quantity': 10, 'written': 1154}TrueThe real file agrees with the data dictionary: 36 duplicates and 10 bad quantities (6 negative, 4 absurd). The data dictionary is a test oracle here: an independent source of the right answer. The second line is an invariant: every row read is either dropped or written. The challenge exercises turn checks like these into a test that runs on the full file.
Common mistakes:
- Writing test files into the project folder or into
data/. A failed run leaves junk behind, and two tests that use the same file name can break each other. Usetmp_path. - Loading
data/sales_raw.csvin every unit test. The real file is slow and can change. Use a small fixture with one row per problem; test the real file in a few integration tests. - Forgetting
newline=""when you read or write CSV files (module 07).
Example 4 — Parametrize the date parser over three formats
Section titled “Example 4 — Parametrize the date parser over three formats”Goal: The order_date column mixes three formats: 2023-01-07, 07/01/2023 (day first) and January 7, 2023. Test every format and every kind of invalid date with two parametrized tests and readable IDs.
Step 1 — Write the parametrized tests
Section titled “Step 1 — Write the parametrized tests”from datetime import date
import pytest
from cleaning import parse_date
@pytest.mark.parametrize( ("text", "expected"), [ pytest.param("2023-01-07", date(2023, 1, 7), id="iso"), pytest.param("07/01/2023", date(2023, 1, 7), id="day-first"), pytest.param("January 7, 2023", date(2023, 1, 7), id="month-name"), pytest.param(" 2023-01-07 ", date(2023, 1, 7), id="spaces"), pytest.param("29/02/2024", date(2024, 2, 29), id="leap-day"), ],)def test_parse_date(text, expected): assert parse_date(text) == expected
@pytest.mark.parametrize( "text", ["2023-13-01", "31/04/2023", "01-07-2023", "", "Jan 7, 2023"], ids=["month-13", "april-31", "dashes", "empty", "short-month"],)def test_parse_date_rejects(text): with pytest.raises(ValueError, match="unknown date format"): parse_date(text)pytest.param(..., id="iso") gives one case a name. The ids= argument names all cases at once. The automatic ID of date(2023, 1, 7) would be expected0, which tells you nothing. The leap-day and april-31 cases test the calendar: 29 February exists in 2024, 31 April never does.
Step 2 — Run them verbosely
Section titled “Step 2 — Run them verbosely”pytest -v --no-header test_dates.py======================================= test session starts ========================================collecting ... collected 10 items
test_dates.py::test_parse_date[iso] PASSED [ 10%]test_dates.py::test_parse_date[day-first] PASSED [ 20%]test_dates.py::test_parse_date[month-name] PASSED [ 30%]test_dates.py::test_parse_date[spaces] PASSED [ 40%]test_dates.py::test_parse_date[leap-day] PASSED [ 50%]test_dates.py::test_parse_date_rejects[month-13] PASSED [ 60%]test_dates.py::test_parse_date_rejects[april-31] PASSED [ 70%]test_dates.py::test_parse_date_rejects[dashes] PASSED [ 80%]test_dates.py::test_parse_date_rejects[empty] PASSED [ 90%]test_dates.py::test_parse_date_rejects[short-month] PASSED [100%]
======================================== 10 passed in 0.01s ========================================Two functions, ten tests. Each line names the case, so a failure such as test_parse_date[day-first] tells you at once which format broke.
Step 3 — Select cases by ID
Section titled “Step 3 — Select cases by ID”pytest -q -k "iso or leap" test_dates.pypytest -q "test_dates.py::test_parse_date[iso]".. [100%]2 passed, 8 deselected in 0.01s. [100%]1 passed in 0.01s-k also matches the IDs: iso and leap-day, one case for each side of or. A node ID with brackets selects one case; put it in quotes, because the shell treats [ specially.
Common mistakes:
- Parametrizing over “07/01/2023” without deciding what it means. In the US it is 1 July; this file puts the day first. Write the decision down as a test.
- Using one parametrized test for valid and invalid inputs with an
ifinside the test. Two tests, one per behavior, are easier to read. - Long, unreadable automatic IDs for objects such as dates or DataFrames. Add
id=orids=.
Example 5 — Test a pandas report function
Section titled “Example 5 — Test a pandas report function”Goal: revenue_by_region() in report.py sums revenue per region. Test it with a four-row DataFrame whose answer you can compute by hand.
Step 1 — Try the function on the real data
Section titled “Step 1 — Try the function on the real data”import pandas as pd
from report import revenue_by_region
pd.set_option("display.width", 100)pd.set_option("display.precision", 2)
sales = pd.read_csv("data/sales.csv")print(revenue_by_region(sales)) region revenue lines0 East 993683.72 53961 South 891766.07 51442 North 888229.47 49663 West 822844.57 4722This is the real answer, but you cannot check it by hand. A test needs a small input with a known answer.
Step 2 — Write the tests with a small fixture
Section titled “Step 2 — Write the tests with a small fixture”import pandas as pdimport pytest
from report import revenue_by_region
@pytest.fixturedef sales() -> pd.DataFrame: return pd.DataFrame( { "region": ["North", "West", "North", "South"], "revenue": [224.1, 2598.0, 79.99, 29.99], } )
def test_revenue_by_region(sales): expected = pd.DataFrame( { "region": ["West", "North", "South"], "revenue": [2598.0, 304.09, 29.99], "lines": [1, 2, 1], } ) pd.testing.assert_frame_equal(revenue_by_region(sales), expected)
def test_total_revenue_is_kept(sales): result = revenue_by_region(sales) assert result["revenue"].sum() == pytest.approx(sales["revenue"].sum())
def test_input_is_not_changed(sales): before = sales.copy() revenue_by_region(sales) pd.testing.assert_frame_equal(sales, before)
def test_empty_input_gives_empty_report(): empty = pd.DataFrame( {"region": pd.Series([], dtype="str"), "revenue": pd.Series([], dtype=float)} ) result = revenue_by_region(empty) assert result.empty assert list(result.columns) == ["region", "revenue", "lines"]Four tests, four kinds of check:
- Exact result: North is 224.1 + 79.99 = 304.09, and West comes first.
assert_frame_equalalso checks the column order, the dtypes and the index (0, 1, 2 afterignore_index=True). - Invariant: grouping must not lose or invent revenue.
- No side effects: the function must not change its input (module 05).
- Edge case: an empty frame gives an empty report with the right columns, not a crash.
Step 3 — Run the tests
Section titled “Step 3 — Run the tests”pytest -q test_report.py.... [100%]4 passed in 0.19sAll four pass. The sum 224.1 + 79.99 is really 304.09000000000003, and assert_frame_equal accepts it, because it compares floats with a tolerance by default.
Common mistakes:
- Writing
assert result == expectedfor DataFrames. It raisesValueError: The truth value of a DataFrame is ambiguous. Usepd.testing.assert_frame_equal. - Building the expected frame from the function’s own output (“it printed this, so it must be right”). Compute the expected values by hand from a small input.
- Forgetting the index. A result with index
[1, 0, 2]after a sort does not equal a frame with index[0, 1, 2].
Example 6 — Smoke-test a churn model
Section titled “Example 6 — Smoke-test a churn model”Goal: model.py trains a logistic regression that predicts churn from data/customers.csv. You cannot assert an exact accuracy, but you can test the properties every good model has: it beats a naive baseline, gives valid probabilities and trains the same way twice.
Step 1 — Read the training function
Section titled “Step 1 — Read the training function”"""Train a small churn model on data/customers.csv."""
import pandas as pdfrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import train_test_splitfrom sklearn.pipeline import Pipeline, make_pipelinefrom sklearn.preprocessing import StandardScaler
FEATURES = [ "tenure_months", "monthly_charges", "support_tickets", "logins_last_30d", "has_autopay",]TARGET = "churned"
def train_churn_model( customers: pd.DataFrame, seed: int = 42) -> tuple[Pipeline, pd.DataFrame, pd.Series]: """Fit a scaled logistic regression; return it with the held-out test set.""" X_train, X_test, y_train, y_test = train_test_split( customers[FEATURES], customers[TARGET], test_size=0.25, random_state=seed, stratify=customers[TARGET], ) model = make_pipeline(StandardScaler(), LogisticRegression()) model.fit(X_train, y_train) return model, X_test, y_testThe function holds back 25% of the customers as a test set, scales the features and fits the model. A smoke test is a quick test that checks the basics work, like switching on a machine to see if smoke comes out. For a model, the basics are the properties below. A test that checks a general rule rather than one exact value is a property test; a property-based test checks such a rule on many generated inputs (exercise M14-X04). A model test can also guard against data leakage, information from the test set that reaches the model during training (exercise M14-X03).
Step 2 — Write property tests with module-scoped fixtures
Section titled “Step 2 — Write property tests with module-scoped fixtures”import numpy as npimport pandas as pdimport pytestfrom sklearn.metrics import roc_auc_scorefrom sklearn.pipeline import Pipeline
from model import train_churn_model
@pytest.fixture(scope="module")def customers() -> pd.DataFrame: return pd.read_csv("data/customers.csv")
@pytest.fixture(scope="module")def trained(customers: pd.DataFrame) -> tuple[Pipeline, pd.DataFrame, pd.Series]: return train_churn_model(customers)
def test_beats_majority_baseline(trained): model, X_test, y_test = trained baseline = max(y_test.mean(), 1 - y_test.mean()) assert model.score(X_test, y_test) > baseline
def test_ranks_churners_well(trained): model, X_test, y_test = trained auc = roc_auc_score(y_test, model.predict_proba(X_test)[:, 1]) assert auc > 0.75
def test_probabilities_are_valid(trained): model, X_test, _ = trained proba = model.predict_proba(X_test) assert proba.shape == (len(X_test), 2) assert ((proba >= 0) & (proba <= 1)).all() np.testing.assert_allclose(proba.sum(axis=1), 1.0)
def test_same_seed_same_model(customers): first, _, _ = train_churn_model(customers, seed=42) second, _, _ = train_churn_model(customers, seed=42) np.testing.assert_array_equal(first[-1].coef_, second[-1].coef_)
def test_missing_feature_fails_loudly(customers): with pytest.raises(KeyError, match="logins_last_30d"): train_churn_model(customers.drop(columns="logins_last_30d"))About 81% of customers did not churn, so a “model” that always says “no churn” is 81% accurate. The first test demands more than that. The second uses ROC AUC (module 36), a score where 0.5 is random and 1.0 is perfect ranking. The threshold 0.75 sits a margin below the real value, so the test does not break from tiny changes:
from sklearn.metrics import roc_auc_score
from model import train_churn_model
model, X_test, y_test = train_churn_model(pd.read_csv("data/customers.csv"))auc = roc_auc_score(y_test, model.predict_proba(X_test)[:, 1])accuracy = model.score(X_test, y_test)print(f"accuracy {accuracy:.3f} (baseline {1 - y_test.mean():.3f}), AUC {auc:.3f}")accuracy 0.832 (baseline 0.807), AUC 0.783The accuracy beats the baseline by about 2.5 points and the AUC sits about 0.03 above the threshold. The other tests check the probabilities, the reproducibility with a fixed seed (first[-1] is the last step of the pipeline, the logistic regression) and a clear error for a missing column.
Step 3 — Run the tests and show the fixtures
Section titled “Step 3 — Run the tests and show the fixtures”pytest -q --setup-show test_model.py SETUP M customers SETUP M trained (fixtures used: customers) test_model.py::test_beats_majority_baseline (fixtures used: customers, trained) . test_model.py::test_ranks_churners_well (fixtures used: customers, trained) . test_model.py::test_probabilities_are_valid (fixtures used: customers, trained) . test_model.py::test_same_seed_same_model (fixtures used: customers) . test_model.py::test_missing_feature_fails_loudly (fixtures used: customers) . TEARDOWN M trained TEARDOWN M customers5 passed in 0.98sM means module scope: pytest loaded the CSV once and trained the model once for the three tests that use trained, then tore both down at the end of the file. With function scope, it would train three times.
Common mistakes:
- Asserting an exact score, such as
accuracy == 0.832. A new library version or a new data row changes the last digits. Assert a threshold with a margin, or compare with a baseline. - Testing a model without a fixed
random_state. The test then passes or fails by chance. A test with random outcomes is a flaky test, and a flaky suite teaches people to ignore failures. - Training a large model in a function-scoped fixture. Use
scope="module"or"session"for expensive objects that no test changes.
Example 7 — Lay out a tested package and measure coverage
Section titled “Example 7 — Lay out a tested package and measure coverage”Goal: Build salesclean, a small package in the src layout with a tests/ folder, run it with a bare pytest, skip a slow test with a marker and use coverage to find the untested lines.
Step 1 — Configure the project
Section titled “Step 1 — Configure the project”[project]name = "salesclean"version = "0.1.0"description = "Parse the messy columns of a raw sales file."requires-python = ">=3.12"dependencies = []
[dependency-groups]dev = ["pytest>=9.2", "pytest-cov>=7.1"]
[tool.pytest]testpaths = ["tests"]pythonpath = ["src"]strict = truemarkers = ["slow: reads the full raw data file"]
[build-system]requires = ["hatchling>=1.27"]build-backend = "hatchling.build"The dev dependency group holds the test tools (module 08). The [tool.pytest] table makes a bare pytest look in tests/, import from src/ and reject unknown markers.
Step 2 — Write the package module
Section titled “Step 2 — Write the package module”"""Parse the price and discount columns and compute line revenue."""
MISSING_TOKENS = frozenset({"", "N/A", "-"})
def parse_price(text: str) -> float | None: """Turn '$1,299.00' into 1299.0. Return None for a missing token.""" if text.strip() in MISSING_TOKENS: return None return float(text.strip().removeprefix("$").replace(",", ""))
def parse_discount(text: str) -> float: """Turn '0.05' into 0.05. A missing discount means no discount: 0.0.""" if text.strip() in MISSING_TOKENS: return 0.0 value = float(text) if not 0 <= value < 1: raise ValueError(f"discount out of range: {text!r}") return value
def line_revenue(unit_price: float, quantity: int, discount: float = 0.0) -> float: """Revenue of one sales line, rounded to cents.""" if quantity < 1: raise ValueError(f"quantity must be at least 1, got {quantity}") return round(unit_price * quantity * (1 - discount), 2)src/salesclean/__init__.py holds only a docstring and __version__ = "0.1.0".
Step 3 — Write the tests: happy paths, errors and one slow test
Section titled “Step 3 — Write the tests: happy paths, errors and one slow test”import pytest
from salesclean.prices import line_revenue, parse_discount, parse_price
@pytest.mark.parametrize( ("text", "expected"), [("$79.99", 79.99), ("$1,299.00", 1299.0)])def test_parse_price(text, expected): assert parse_price(text) == expected
def test_parse_discount(): assert parse_discount("0.05") == 0.05
def test_line_revenue(): assert line_revenue(249.0, 3, 0.1) == pytest.approx(672.3)import pytest
from salesclean.prices import line_revenue, parse_discount, parse_price
@pytest.mark.parametrize("token", ["", "N/A", "-"])def test_missing_tokens(token): assert parse_price(token) is None assert parse_discount(token) == 0.0
@pytest.mark.parametrize("text", ["1.5", "-0.1"])def test_discount_out_of_range(text): with pytest.raises(ValueError, match="out of range"): parse_discount(text)
def test_zero_quantity_is_rejected(): with pytest.raises(ValueError, match="at least 1"): line_revenue(79.99, 0)import csvfrom pathlib import Path
import pytest
from salesclean.prices import parse_discount, parse_price
# The course folder holds both salesclean/ and data/.RAW = Path(__file__).resolve().parents[2] / "data" / "sales_raw.csv"
@pytest.mark.slowdef test_every_price_and_discount_parses(): with RAW.open(newline="", encoding="utf-8") as file: rows = list(csv.DictReader(file)) prices = [parse_price(row["unit_price"]) for row in rows] discounts = [parse_discount(row["discount"]) for row in rows] assert len(rows) == 1200 assert sum(price is None for price in prices) == 10 assert all(price > 0 for price in prices if price is not None) assert all(0 <= discount < 1 for discount in discounts)The slow test builds its path from __file__, the path of the test file itself. parents[2] goes up from tests/ to salesclean/ to the course folder. So the test finds the data from any working folder.
Step 4 — Run the suite, then skip the slow test
Section titled “Step 4 — Run the suite, then skip the slow test”cd salescleanpytest -qpytest -q -m "not slow"........... [100%]11 passed in 0.01s.......... [100%]10 passed, 1 deselected in 0.01sA bare pytest found all 11 tests through testpaths. -m "not slow" deselects the marked test. Developers run the fast set while they work and the full set before they share a change.
Step 5 — Measure coverage of the happy-path tests only
Section titled “Step 5 — Measure coverage of the happy-path tests only”cd salescleanpytest -q --cov=salesclean --cov-branch --cov-report= tests/test_prices.pycoverage report -m.... [100%]4 passed in 0.01sName Stmts Miss Branch BrPart Cover Missing------------------------------------------------------------------------src/salesclean/__init__.py 1 0 0 0 100%src/salesclean/prices.py 16 4 8 4 67% 9, 16, 19, 26------------------------------------------------------------------------TOTAL 17 4 8 4 68%--cov-branch adds the Branch and BrPart (partial branches) columns. Lines 9, 16, 19 and 26 never ran: the return None, the return 0.0 and the two raise lines. Each of the 4 if statements went only one way. Happy-path tests leave every error path untested, and the error paths are where bad data goes.
Step 6 — Measure the whole suite
Section titled “Step 6 — Measure the whole suite”cd salescleanpytest -q --cov=salesclean --cov-branch --cov-report=coverage report -m........... [100%]11 passed in 0.02sName Stmts Miss Branch BrPart Cover Missing------------------------------------------------------------------------src/salesclean/__init__.py 1 0 0 0 100%src/salesclean/prices.py 16 0 8 0 100%------------------------------------------------------------------------TOTAL 17 0 8 0 100%With test_errors.py, every line and every branch ran. 100% does not prove the code correct; it proves that no line is untested.
Common mistakes:
- Putting
tests/insidesrc/salesclean/. The tests then ship to your users. Keep them next tosrc/. - Giving two test files the same name in different folders (
tests/a/test_utils.py,tests/b/test_utils.py) without__init__.pyfiles. pytest stops with an “import file mismatch” error. Use unique names. - Chasing 100% coverage with asserts-free tests. Coverage shows which lines ran, not which behaviors are checked.
Pitfalls
Section titled “Pitfalls”| Mistake | Symptom | Fix |
|---|---|---|
File named prices_test_data.py or function named check_price |
no tests ran, exit code 5, or a test silently missing |
Name files test_*.py and functions test_* |
assert result == expected on DataFrames |
ValueError: The truth value of a DataFrame is ambiguous |
pd.testing.assert_frame_equal(result, expected) |
assert total == 304.09 on a float sum |
Fails with 304.09000000000003 |
assert total == pytest.approx(304.09) |
pytest.raises(ValueError) around several lines |
Passes even though the wrong line raised | One call inside the block, plus match= |
Tests write into data/ or the project folder |
Leftover files; tests break each other | Use tmp_path |
| A test changes a module-scoped fixture | Later tests fail only when run together | Use function scope, or never mutate shared fixtures |
A model test asserts accuracy == 0.832 |
Fails after a library or data update | Assert a threshold with a margin or beat a baseline |
| Tests depend on the order they run in | Pass in the suite, fail with -k or alone |
Each test builds its own input with fixtures |
import cleaning works in Python, fails in pytest |
ModuleNotFoundError during collection |
Run python -m pytest, set pythonpath, or install the package |
@pytest.mark.slwo (typo) |
The marker is ignored, -m "not slow" runs the test |
strict = true and list markers in the config |
pytest --cov output differs on another machine |
The header shows the platform and Python version | Compare the coverage report table, not the header |
| A test without an assert | Always passes, raises coverage, checks nothing | Every test asserts the behavior it names |
Where this is used beyond data science
Section titled “Where this is used beyond data science”- Web development: web frameworks such as FastAPI and Django test their endpoints with pytest and a test client. Module 44 tests a prediction API with FastAPI’s
TestClient. - Libraries: pandas, NumPy and scikit-learn each run tens of thousands of pytest tests on every change, on several operating systems, before a release.
- Automation and CI: GitHub Actions and GitLab CI run
pyteston every pull request and block the merge when the exit code is not 0. - Command-line tools:
capsys,tmp_pathandmonkeypatchtest a CLI’s output, files and settings without a real terminal; the challenge exercises do this for a cleaning CLI.
Summary
Section titled “Summary”- A test is a function named
test_*that calls your code and checks the result withassert. pytest findstest_*.pyfiles and runs every test in them. pytest -qprints one character per test and a summary line; the exit code is 0 only when every test passes.- A failure report shows the failing line and, thanks to assertion rewriting, the values on both sides of the comparison. Read the summary first, then each
Eline. - Fixtures prepare inputs and resources; request them by parameter name. Shared fixtures live in
conftest.py.yieldadds teardown;scopecontrols how often a fixture runs. @pytest.mark.parametrizeruns one test over many cases; give them readable IDs.tmp_pathgives each test an empty folder,pytest.approxcompares floats,pytest.raises(..., match=...)checks errors,capsyscaptures output andmonkeypatchchanges the environment for one test.- Test DataFrames with
pd.testing.assert_frame_equaland arrays withnp.testing.assert_allclose. Test models by properties and thresholds, not exact scores. - Keep tests in
tests/next tosrc/, configure pytest in[tool.pytest], and select tests with paths, node IDs,-k,-m,-xand--lf. - Coverage shows which lines and branches no test ran. Use it to find gaps, not as a goal in itself.
- Fix a bug by writing a failing test first (red), then the fix (green). Keep the test as a regression test.
Self-check questions
Section titled “Self-check questions”Q1. Which of these does pytest collect by default: the file prices_tests.py, the function test_price() in test_prices.py, the function check_price() in test_prices.py?
Answer
Only test_price() in test_prices.py. A file must match test_*.py or *_test.py; prices_tests.py matches neither (it ends in _tests, not _test). A function must start with test, so check_price is ignored.
Q2. Why does pytest show the values of both sides of a failing assert a == b, while plain Python shows only AssertionError?
Answer
pytest rewrites the assert statements of test files before it runs them (assertion rewriting). The rewritten code records the value of each part of the expression and puts them into the failure report. Plain Python evaluates the condition and only knows that it is false.
Q3. Two tests use a fixture raw_row that returns a dict. The first test changes the dict. Does the second test see the change? What if the fixture had scope="module"?
Answer
With the default function scope, no: pytest calls the fixture again for each test and the second test gets a new dict. With scope="module", yes: both tests in the file share the same dict object, so the change leaks into the second test. That is why wide scopes are only for objects that no test changes.
Q4. What does 0.1 + 0.2 == pytest.approx(0.3) check, and what are the default tolerances?
Answer
It checks that |0.30000000000000004 - 0.3| <= max(rel * 0.3, abs). The defaults are rel=1e-6 (relative tolerance) and abs=1e-12 (absolute tolerance). The difference is about 5.6e-17, so the comparison is True.
Q5. This test passes. Why is it weak, and how do you fix it?
def test_bad_discount(): with pytest.raises(ValueError): value = parse_discount("abc") assert value == 0.0Answer
float("abc") raises ValueError: could not convert string to float, not the range error. The test passes for any ValueError, and the assert inside the block never runs. Put only the call in the block and add match=: with pytest.raises(ValueError, match="could not convert"): parse_discount("abc"). Test the range rule separately with match="out of range".
Q6. A test function writes a report file. Which built-in fixture should it use, and why not a fixed path such as output/report.csv?
Answer
tmp_path: a fresh, empty folder per test. A fixed path leaves files behind after a failure, can contain a stale file from an earlier run (so the test passes without writing anything), and breaks when two tests or two developers’ runs use the same file.
Q7. What is the difference between pytest -k price and pytest -m slow?
Answer
-k price selects tests whose name (or parametrize ID, or file or class name) contains price. -m slow selects tests that carry the marker @pytest.mark.slow. -k depends on naming; -m depends on labels you put on tests on purpose.
Q8. Coverage reports 100% for a module. Can the module still have bugs?
Answer
Yes. 100% coverage only means that every line (and with --cov-branch, every branch) ran at least once during the tests. A test can run a line without checking its result, and no test may cover an input that triggers a bug, such as a thousands separator. Coverage finds untested code; asserts and good test cases find bugs.
Q9. Why does the churn model test assert auc > 0.75 and not auc == 0.7826?
Answer
The exact AUC changes with small, harmless changes: a new scikit-learn version, a new row in the data or a different seed. A test with an exact value would fail for reasons that are not bugs. A threshold with a margin checks the property that matters: the model ranks churners clearly better than chance (0.5).
Q10. What are the three steps of red-green-refactor, and why must you see the test fail first?
Answer
Red: write a test that fails. Green: write the least code that makes it pass. Refactor: clean up the code while the tests stay green. You must see the red step because a test that has never failed might not test anything, for example because it calls the wrong function or its assert is always true.
Q11. Where do you put a fixture that tests/test_prices.py and tests/test_dates.py both need?
Answer
In tests/conftest.py. pytest loads every conftest.py automatically and makes its fixtures available to all tests in that folder and its subfolders. You never import conftest.py.
Track your progress
Section titled “Track your progress”Next steps
Section titled “Next steps”- Exercises: 28 exercises on asserts, fixtures, parametrize, approx, raises, capsys, monkeypatch, pandas tests, coverage and TDD.
- Mini-project: build a validator for
data/sales_raw.csvwith a full pytest suite and a coverage gate. - Cheat sheet: pytest commands, fixtures, markers, assert helpers and configuration on one page.
- Next module: 15. Performance and concurrency measures speed with
timeitandcProfileand runs work in parallel. Your tests make sure that the fast version still gives the same answer.