Skip to content

14. Testing with pytest — Exercises

These exercises practice every idea of the testing with pytest lesson. They test the cleaning functions of cleaning.py and report.py from the lesson, on rows of data/sales_raw.csv and the other course datasets.

How to work:

  1. Work in your course folder, the one that holds data/. Put cleaning.py, report.py and conftest.py from the lesson next to it.
  2. Save each test file under the name in its block title, in the same folder, and run the command in the solution, for example pytest -q test_w07_regions.py. Exercises with their own folder (M14-C03) name the folder in the titles.
  3. Exercises without a test file are plain scripts: copy the starter into exercise.py and run python exercise.py.
  4. Stuck? Open one hint at a time. Open the solution only after a real attempt.

Each solution ends with assert checks. pytest prints the run time on its last line, for example 5 passed in 0.02s. The time differs on every run; compare the counts and ignore the time. The predict-the-output exercises (M14-W02, M14-C10) give acceptance criteria instead of an expected output, so the answer stays hidden until you open the solution.

Warm-up

A colleague checks clean_product by eye: the script prints the cleaned name, and they read it. Turn the check into a test function test_clean_product_spaces with one assert. Call the function at the end of the script and print a confirmation.

Expected output
test_clean_product_spaces passed
Starter
from cleaning import clean_product
print(clean_product(" Wireless Earbuds ")) # looks right?
# TODO: write test_clean_product_spaces() with an assert
# TODO: call it, then print "test_clean_product_spaces passed"
Hint 1

A test is a function whose name starts with test_. Inside it, compare the result with the exact expected string.

Hint 2

assert clean_product(" Wireless Earbuds ") == "Wireless Earbuds".

Solution
from cleaning import clean_product
def test_clean_product_spaces():
raw = " Wireless Earbuds "
result = clean_product(raw)
assert result == "Wireless Earbuds"
test_clean_product_spaces()
print("test_clean_product_spaces passed")
Output
test_clean_product_spaces passed

How it works:

  1. The test arranges the raw name, acts by calling clean_product once and asserts the exact result.
  2. If the assert were false, the call would raise AssertionError and the print would never run.
  3. In a file named test_*.py, pytest calls the function for you, so you would delete the last two lines.

Alternative: save the function alone in test_products_w01.py and run pytest -q test_products_w01.py. pytest then reports 1 passed and, on a failure, shows both strings.

M14-W02 · Predict which tests pytest collects

Section titled “M14-W02 · Predict which tests pytest collects”
Warm-up

Predict the output: this file has five functions and methods with asserts. Which ones does pytest collect? Write down the node IDs that pytest --collect-only -q test_w02_collect.py prints, then run it. --collect-only lists the tests without running them.

Acceptance criteria:

  • Write your list of node IDs before you run the command.
  • Your list matches the Output in the solution, and you can name the discovery rule behind each function that pytest skips.
Starter
from cleaning import clean_product, parse_price
def test_price():
assert parse_price("$59.99") == 59.99
def check_product():
assert clean_product(" Air Purifier ") == "Air Purifier"
def testing_spaces():
assert clean_product("Non-Slip Yoga Mat ") == "Non-Slip Yoga Mat"
class TestPrices:
def test_thousands(self):
assert parse_price("$1,149.00") == 1149.0
def sample_text(self):
return "$14.99"
class PriceChecks:
def test_missing(self):
assert parse_price("N/A") is None
Hint 1

Functions must start with test. Not test_: just the four letters.

Hint 2

Methods count only inside a class whose name starts with Test.

Solution
test_w02_collect.py
from cleaning import clean_product, parse_price
def test_price():
assert parse_price("$59.99") == 59.99
def check_product():
assert clean_product(" Air Purifier ") == "Air Purifier"
def testing_spaces():
assert clean_product("Non-Slip Yoga Mat ") == "Non-Slip Yoga Mat"
class TestPrices:
def test_thousands(self):
assert parse_price("$1,149.00") == 1149.0
def sample_text(self):
return "$14.99"
class PriceChecks:
def test_missing(self):
assert parse_price("N/A") is None
Terminal
pytest --collect-only -q test_w02_collect.py
Output
test_w02_collect.py::test_price
test_w02_collect.py::testing_spaces
test_w02_collect.py::TestPrices::test_thousands
3 tests collected in 0.00s

How it works:

  1. test_price starts with test: collected.
  2. check_product does not: skipped, even though it has an assert.
  3. testing_spaces starts with the four letters test: collected. The default rule is a prefix, not a word.
  4. TestPrices.test_thousands is a test method in a Test class: collected. sample_text is a helper method: skipped.
  5. PriceChecks does not start with Test, so none of its methods count.

Alternative: change the rules in the configuration, for example python_functions = ["test_*", "check_*"] in [tool.pytest]. Most projects keep the defaults, because every Python developer knows them.

M14-W03 · Compare floats with pytest.approx

Section titled “M14-W03 · Compare floats with pytest.approx”
Warm-up

Fix the bug: this check of the total discount fails, although the code is correct. Fix the comparison, not the data. Print the total and the result of the fixed comparison.

Expected output
total = 0.30000000000000004, close to 0.3: True
Starter
discounts = [0.1, 0.2] # two order lines of data/sales_raw.csv
total = sum(discounts)
assert total == 0.3 # AssertionError
# TODO: fix the comparison and print the line shown above
Hint 1

Print total. It is not exactly 0.3.

Hint 2

import pytest, then compare with pytest.approx(0.3) on the right-hand side.

Solution
import pytest
discounts = [0.1, 0.2]
total = sum(discounts)
close = total == pytest.approx(0.3)
print(f"total = {total!r}, close to 0.3: {close}")
assert total == pytest.approx(0.3)
Output
total = 0.30000000000000004, close to 0.3: True

How it works:

  1. 0.1 and 0.2 have no exact binary form, so their sum is 0.30000000000000004.
  2. pytest.approx(0.3) compares with a relative tolerance of one part in a million. The tiny error is far below it.
  3. !r in the f-string shows the full float, so you can see the error.

Alternative: math.isclose(total, 0.3) from module 01 gives the same answer. Inside tests, prefer approx: it also works on lists and dicts, and its failure message shows the tolerance.

M14-W04 · Check an error with pytest.raises

Section titled “M14-W04 · Check an error with pytest.raises”
Warm-up

parse_date("31/04/2023") must fail, because April has 30 days. Write the check with pytest.raises and a match= pattern for the text unknown date format. After the block, print the error message.

Expected output
unknown date format: '31/04/2023'
Starter
import pytest
from cleaning import parse_date
# TODO: check that parse_date("31/04/2023") raises ValueError
# with "unknown date format" in the message
# TODO: print the message
Hint 1

with pytest.raises(ValueError, match="...") as excinfo: and the call inside the block.

Hint 2

The exception object is excinfo.value. print(excinfo.value) shows its message.

Solution
import pytest
from cleaning import parse_date
with pytest.raises(ValueError, match="unknown date format") as excinfo:
parse_date("31/04/2023")
print(excinfo.value)
assert "31/04/2023" in str(excinfo.value)
Output
unknown date format: '31/04/2023'

How it works:

  1. parse_date tries all three formats. %d/%m/%Y fails for 31 April, so the loop ends and the function raises its own error.
  2. pytest.raises catches the ValueError and checks the message with re.search.
  3. The last assert checks that the message names the bad input, which helps whoever reads the log.

Alternative: pytest.raises also accepts a tuple of types, (ValueError, TypeError). Use a single type whenever you can; it states the rule more precisely.

M14-W05 · Refactor a test into Arrange, Act, Assert

Section titled “M14-W05 · Refactor a test into Arrange, Act, Assert”
Warm-up

Refactor: this test works, but it builds the row twice, cleans it twice and has a name that says nothing. Rewrite it as test_missing_region_becomes_none in the Arrange–Act–Assert pattern, with one call of clean_row. Call it and print test passed.

Expected output
test passed
Starter
from cleaning import clean_row
def test_it():
assert clean_row({"order_id": "O000173", "order_date": "January 13, 2023", "region": "N/A", "product": "Trail Running Shoes", "unit_price": "$129.99", "quantity": "4", "discount": "0.05"})["region"] is None and clean_row({"order_id": "O000173", "order_date": "January 13, 2023", "region": "N/A", "product": "Trail Running Shoes", "unit_price": "$129.99", "quantity": "4", "discount": "0.05"})["unit_price"] == 129.99
# TODO: rewrite as test_missing_region_becomes_none (arrange, act, assert)
Hint 1

Arrange: store the dict in a variable raw. Act: clean = clean_row(raw).

Hint 2

Write two asserts instead of one and. pytest then tells you which of the two failed.

Solution
from cleaning import clean_row
def test_missing_region_becomes_none():
raw = {
"order_id": "O000173",
"order_date": "January 13, 2023",
"region": "N/A",
"product": "Trail Running Shoes",
"unit_price": "$129.99",
"quantity": "4",
"discount": "0.05",
}
clean = clean_row(raw)
assert clean["region"] is None
assert clean["unit_price"] == 129.99
test_missing_region_becomes_none()
print("test passed")
Output
test passed

How it works:

  1. The name says the rule. A failure report that names test_missing_region_becomes_none explains itself.
  2. Blank lines separate the three parts, so the reader sees input, action and checks at a glance.
  3. One call of clean_row means the test checks one behavior on one input.

Alternative: if many tests need this row, move the dict into a fixture in conftest.py, as the lesson’s raw_row fixture does.

Warm-up

Write a fixture tv_row that returns the raw row of order O000145 (a 55-inch TV in the West region, $1,299.00, quantity 2, discount 0.0, date 2023-01-11). Then write two tests that use it: the cleaned price is 1299.0, and the cleaned quantity is the int 2.

Acceptance criteria:

  • pytest -q test_w06_fixture.py reports 2 passed.
  • Neither test builds the row itself.
Starter
import pytest
from cleaning import clean_row
# TODO: @pytest.fixture def tv_row(): return the raw row as a dict of str
# TODO: test_tv_price(tv_row)
# TODO: test_tv_quantity_is_an_int(tv_row)
Hint 1

clean_row needs the keys order_id, order_date, region, product, unit_price, quantity and discount. All values are strings, as csv.DictReader gives them.

Hint 2

A test receives the fixture by naming it as a parameter: def test_tv_price(tv_row):.

Solution
test_w06_fixture.py
import pytest
from cleaning import clean_row
@pytest.fixture
def tv_row():
return {
"order_id": "O000145",
"order_date": "2023-01-11",
"region": "West",
"product": "55-inch 4K Smart TV",
"unit_price": "$1,299.00",
"quantity": "2",
"discount": "0.0",
}
def test_tv_price(tv_row):
assert clean_row(tv_row)["unit_price"] == 1299.0
def test_tv_quantity_is_an_int(tv_row):
quantity = clean_row(tv_row)["quantity"]
assert isinstance(quantity, int)
assert quantity == 2
Terminal
pytest -q test_w06_fixture.py
Output
.. [100%]
2 passed in 0.01s

How it works:

  1. @pytest.fixture registers tv_row. pytest calls it once for each test that names it.
  2. Each test gets a fresh dict, so neither test can damage the other’s input.
  3. == 2 alone also passes for 2.0, so the quantity test first checks the type with isinstance. The test name promises an int, and the asserts deliver it.

Alternative: if other files need the row too, move the fixture into conftest.py. The tests stay the same; pytest finds the fixture there.

M14-W07 · Parametrize three copy-paste tests

Section titled “M14-W07 · Parametrize three copy-paste tests”
Warm-up

Refactor: these tests differ only in their data. Replace them with one parametrized test that also covers "West " → "West" and the missing token "N/A" → None.

The file must have one test function. pytest -q test_w07_regions.py prints:

Expected output
..... [100%]
5 passed in 0.01s
Starter
from cleaning import normalize_region
def test_lowercase():
assert normalize_region("north") == "North"
def test_uppercase():
assert normalize_region("SOUTH") == "South"
def test_spaces():
assert normalize_region(" East ") == "East"
# TODO: one @pytest.mark.parametrize test with five cases
Hint 1

@pytest.mark.parametrize(("raw", "expected"), [...]) with a list of (raw, expected) tuples.

Hint 2

None == None is True, so assert normalize_region(raw) == expected works for the missing token too.

Solution
test_w07_regions.py
import pytest
from cleaning import normalize_region
@pytest.mark.parametrize(
("raw", "expected"),
[
("north", "North"),
("SOUTH", "South"),
(" East ", "East"),
("West ", "West"),
("N/A", None),
],
)
def test_normalize_region(raw, expected):
assert normalize_region(raw) == expected
Terminal
pytest -q test_w07_regions.py
Output
..... [100%]
5 passed in 0.01s

How it works:

  1. The decorator lists the argument names once and one tuple per case.
  2. pytest creates five tests. A failing case does not stop the others.
  3. A new spelling in next month’s export is one new line in the list.

Alternative: split valid spellings and missing tokens into two parametrized tests, so expected is never None in the first one and the second can assert is None. That is stricter, and the lesson’s Example 2 does it for regions.

M14-W08 · Use raw_csv and tmp_path together

Section titled “M14-W08 · Use raw_csv and tmp_path together”
Warm-up

Write a test that cleans the raw_csv fixture file (from the lesson’s conftest.py) into tmp_path / "clean.csv" and checks two things: the first line of the output is the header built from CLEAN_COLUMNS, and the temporary folder now holds exactly clean.csv and sales_raw.csv.

Acceptance criteria:

  • pytest -q test_w08_header.py reports 1 passed.
  • The test writes nothing outside tmp_path.
Starter
from cleaning import CLEAN_COLUMNS, clean_file
def test_output_starts_with_header(raw_csv, tmp_path):
out = tmp_path / "clean.csv"
# TODO: clean raw_csv into out
# TODO: assert the first line equals ",".join(CLEAN_COLUMNS)
# TODO: assert the folder holds exactly the two files
Hint 1

out.read_text(encoding="utf-8").splitlines()[0] is the first line.

Hint 2

sorted(p.name for p in tmp_path.iterdir()) lists the file names in a fixed order.

Solution
test_w08_header.py
from cleaning import CLEAN_COLUMNS, clean_file
def test_output_starts_with_header(raw_csv, tmp_path):
out = tmp_path / "clean.csv"
clean_file(raw_csv, out)
first_line = out.read_text(encoding="utf-8").splitlines()[0]
assert first_line == ",".join(CLEAN_COLUMNS)
assert sorted(p.name for p in tmp_path.iterdir()) == ["clean.csv", "sales_raw.csv"]
Terminal
pytest -q test_w08_header.py
Output
. [100%]
1 passed in 0.01s

How it works:

  1. raw_csv itself requests tmp_path. In one test, every request of tmp_path returns the same folder, so the raw file and the clean file sit side by side.
  2. Building the expected header from CLEAN_COLUMNS keeps the test right when someone adds a column.
  3. sorted matters: iterdir() returns files in an order that depends on the file system.

Alternative: read the header with csv.reader and compare it with CLEAN_COLUMNS as a list. That also handles quoted column names.

Core

Write a test file for parse_discount with four groups of cases: valid fractions ("0.0", "0.05", " 0.2 "), the three missing tokens (which mean 0.0), out-of-range values ("1", "1.5", "-0.1", "15") and text that is not a number ("ten percent"). Use parametrize for the first three groups and pytest.raises with match= for both error groups.

Each error test uses match=, with a different pattern for the range error and for the conversion error. pytest -q test_c01_discounts.py prints:

Expected output
........... [100%]
11 passed in 0.01s
Starter
import pytest
from cleaning import parse_discount
# TODO: test_valid_discounts (parametrize text, expected)
# TODO: test_missing_means_no_discount (parametrize token)
# TODO: test_out_of_range (parametrize text, pytest.raises)
# TODO: test_text_is_rejected
Hint 1

Read parse_discount in the lesson. Which message does it raise itself, and which comes from float()?

Hint 2

The range error contains out of range. float("ten percent") raises could not convert string to float: 'ten percent'.

Hint 3

"1" is out of range because the rule is 0 <= value < 1: a 100% discount is not a valid sales line.

Solution
test_c01_discounts.py
import pytest
from cleaning import parse_discount
@pytest.mark.parametrize(
("text", "expected"), [("0.0", 0.0), ("0.05", 0.05), (" 0.2 ", 0.2)]
)
def test_valid_discounts(text, expected):
assert parse_discount(text) == expected
@pytest.mark.parametrize("token", ["", "N/A", "-"])
def test_missing_means_no_discount(token):
assert parse_discount(token) == 0.0
@pytest.mark.parametrize("text", ["1", "1.5", "-0.1", "15"])
def test_out_of_range(text):
with pytest.raises(ValueError, match="out of range"):
parse_discount(text)
def test_text_is_rejected():
with pytest.raises(ValueError, match="could not convert"):
parse_discount("ten percent")
Terminal
pytest -q test_c01_discounts.py
Output
........... [100%]
11 passed in 0.01s

How it works:

  1. 3 + 3 + 4 + 1 = 11 tests. Each group tests one rule.
  2. " 0.2 " passes because float() ignores surrounding spaces. The test documents that.
  3. Two different match= patterns prove that each bad input fails for the right reason. Without them, "15" could fail in float() and the range check would be untested.
  4. "1" and "-0.1" sit just outside the borders of 0 <= value < 1. Testing at the borders catches off-by-one mistakes such as <= instead of <.

Alternative: combine all invalid inputs into one parametrized test with two arguments, (text, pattern), and pass match=pattern. That is shorter, but the two rules then share one test name.

Core

Interpret the result: a teammate wrote c02_revenue.py and two tests. One test fails:

c02_revenue.py
"""Revenue of one sales line. This version has a bug."""
def line_revenue(unit_price: float, quantity: int, discount: float = 0.0) -> float:
return round(unit_price * quantity * (1 - discount / 100), 2)
test_c02_revenue.py
import pytest
from c02_revenue import line_revenue
def test_no_discount():
assert line_revenue(79.99, 3) == pytest.approx(239.97)
def test_ten_percent_discount():
assert line_revenue(249.0, 3, 0.1) == pytest.approx(672.3)
Terminal
pytest -q --tb=short test_c02_revenue.py
Output
.F [100%]
============================================= FAILURES =============================================
____________________________________ test_ten_percent_discount _____________________________________
test_c02_revenue.py:11: in test_ten_percent_discount
assert line_revenue(249.0, 3, 0.1) == pytest.approx(672.3)
E assert 746.25 == 672.3 ± 6.7e-04
E
E comparison failed
E Obtained: 746.25
E Expected: 672.3 ± 6.7e-04
===================================== short test summary info ======================================
FAILED test_c02_revenue.py::test_ten_percent_discount - assert 746.25 == 672.3 ± 6.7e-04
1 failed, 1 passed in 0.01s

Answer three questions: which test failed, what did the function return, and which line is wrong? Then write the fixed function in a script and check both cases with asserts. Print both revenues.

Expected output
239.97 672.3
Starter
import pytest
def line_revenue(unit_price: float, quantity: int, discount: float = 0.0) -> float:
# TODO: fix the formula; discount is a fraction such as 0.1
return round(unit_price * quantity * (1 - discount / 100), 2)
# TODO: print both revenues and assert them with pytest.approx
Hint 1

Read the line E assert 746.25 == 672.3 ± 6.7e-04. The left side is what the function returned.

Hint 2

3 × 249.0 is 747.0. 746.25 is 747.0 × 0.999. Which part of the formula turned 0.1 into 0.001?

Solution
import pytest
def line_revenue(unit_price: float, quantity: int, discount: float = 0.0) -> float:
return round(unit_price * quantity * (1 - discount), 2)
no_discount = line_revenue(79.99, 3)
ten_percent = line_revenue(249.0, 3, 0.1)
print(no_discount, ten_percent)
assert no_discount == pytest.approx(239.97)
assert ten_percent == pytest.approx(672.3)
Output
239.97 672.3

How it works:

  1. Which test: test_ten_percent_discount (the F is second in .F; the summary line names it).
  2. What it returned: 746.25, against the expected 672.3. approx shows its tolerance: ± 6.7e-04.
  3. The bug: discount / 100 treats the discount as a percentage. The data stores fractions (0.1 means 10%), so the formula subtracted only 0.1%. The test without a discount passed, because 0 / 100 is 0: a test with the default argument alone never finds this bug.
  4. The fix removes / 100. Both asserts now hold.

Alternative: if the business really wants percentages, keep / 100 and change the callers and the tests. Either way, decide once and write the decision in the docstring and in a test.

M14-C03 · Share a fixture with conftest.py

Section titled “M14-C03 · Share a fixture with conftest.py”
Core

Two test files, exercises/c03/test_totals.py and exercises/c03/test_counts.py, both need the same four orders. Put an orders fixture into exercises/c03/conftest.py and write two tests in each file: total revenue (454.59) and West revenue (424.6) in the first; lines per region and unique order ids in the second. Neither test file may import the fixture.

The orders: O000004 West 224.1, O000005 East 29.99, O000009 West 179.0, O000062 West 21.5.

orders must be defined only in conftest.py. pytest -q exercises/c03 prints:

Expected output
.... [100%]
4 passed in 0.01s
Starter
# exercises/c03/conftest.py
import pytest
# TODO: @pytest.fixture def orders(): return a list of 4 dicts
# with the keys order_id, region and revenue
# exercises/c03/test_totals.py
# TODO: test_total_revenue(orders), test_west_revenue(orders)
# exercises/c03/test_counts.py
# TODO: test_lines_per_region(orders), test_order_ids_are_unique(orders)
Hint 1

pytest loads conftest.py by itself. A test only needs the parameter name orders.

Hint 2

collections.Counter(order["region"] for order in orders) counts the regions. A Counter compares equal to a plain dict with the same counts.

Solution
exercises/c03/conftest.py
import pytest
@pytest.fixture
def orders():
return [
{"order_id": "O000004", "region": "West", "revenue": 224.1},
{"order_id": "O000005", "region": "East", "revenue": 29.99},
{"order_id": "O000009", "region": "West", "revenue": 179.0},
{"order_id": "O000062", "region": "West", "revenue": 21.5},
]
exercises/c03/test_totals.py
import pytest
def test_total_revenue(orders):
assert sum(order["revenue"] for order in orders) == pytest.approx(454.59)
def test_west_revenue(orders):
west = [order["revenue"] for order in orders if order["region"] == "West"]
assert sum(west) == pytest.approx(424.6)
exercises/c03/test_counts.py
from collections import Counter
def test_lines_per_region(orders):
counts = Counter(order["region"] for order in orders)
assert counts == {"West": 3, "East": 1}
def test_order_ids_are_unique(orders):
ids = [order["order_id"] for order in orders]
assert len(ids) == len(set(ids))
Terminal
pytest -q exercises/c03
Output
.... [100%]
4 passed in 0.01s

How it works:

  1. Passing a folder to pytest collects every test_*.py file in it.
  2. pytest loads exercises/c03/conftest.py before it imports the test files, so orders is available in both.
  3. The totals use approx: 224.1 + 29.99 + 179.0 + 21.5 is not exactly 454.59 in floating point.

Alternative: a conftest.py in a parent folder shares fixtures with every subfolder. Projects often have one tests/conftest.py for common fixtures and smaller ones in subfolders for local fixtures.

M14-C04 · A fixture with teardown, used by another fixture

Section titled “M14-C04 · A fixture with teardown, used by another fixture”
Core

c04_queries.py has one SQL function, revenue_by_region(conn). Test it with two fixtures: empty_db creates an in-memory SQLite database with a sales (order_id, region, revenue) table, yields the connection and closes it afterwards. sales_db uses empty_db and inserts three rows: O000004 West 224.1, O000005 East 29.99, O000009 West 179.0. Write one test for the filled table and one for the empty table.

c04_queries.py
"""SQL queries on a sales table."""
import sqlite3
def revenue_by_region(conn: sqlite3.Connection) -> list[tuple[str, float]]:
"""Total revenue per region, largest first."""
query = """
SELECT region, ROUND(SUM(revenue), 2) AS revenue
FROM sales
GROUP BY region
ORDER BY revenue DESC
"""
return conn.execute(query).fetchall()

Acceptance criteria:

  • pytest -q test_c04_sql.py reports 2 passed.
  • The connection is closed in the teardown of empty_db, after yield.
Starter
import sqlite3
import pytest
from c04_queries import revenue_by_region
@pytest.fixture
def empty_db():
# TODO: connect to ":memory:", create the table, yield, close
...
@pytest.fixture
def sales_db(empty_db):
# TODO: insert three rows, return the connection
...
# TODO: test_revenue_by_region(sales_db)
# TODO: test_empty_table_gives_no_rows(empty_db)
Hint 1

conn.executemany("INSERT INTO sales VALUES (?, ?, ?)", rows) inserts a list of tuples.

Hint 2

West is 224.1 + 179.0 = 403.1. The query rounds to 2 decimals, so an exact == on the list is safe here.

Solution
test_c04_sql.py
import sqlite3
from collections.abc import Iterator
import pytest
from c04_queries import revenue_by_region
@pytest.fixture
def empty_db() -> Iterator[sqlite3.Connection]:
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE sales (order_id TEXT, region TEXT, revenue REAL)")
yield conn
conn.close()
@pytest.fixture
def sales_db(empty_db: sqlite3.Connection) -> sqlite3.Connection:
rows = [
("O000004", "West", 224.1),
("O000005", "East", 29.99),
("O000009", "West", 179.0),
]
empty_db.executemany("INSERT INTO sales VALUES (?, ?, ?)", rows)
return empty_db
def test_revenue_by_region(sales_db):
assert revenue_by_region(sales_db) == [("West", 403.1), ("East", 29.99)]
def test_empty_table_gives_no_rows(empty_db):
assert revenue_by_region(empty_db) == []
Terminal
pytest -q --setup-show test_c04_sql.py
Output
SETUP F empty_db
SETUP F sales_db (fixtures used: empty_db)
test_c04_sql.py::test_revenue_by_region (fixtures used: empty_db, sales_db) .
TEARDOWN F sales_db
TEARDOWN F empty_db
SETUP F empty_db
test_c04_sql.py::test_empty_table_gives_no_rows (fixtures used: empty_db) .
TEARDOWN F empty_db
2 passed in 0.01s

How it works:

  1. --setup-show shows the order: pytest sets up empty_db first, because sales_db requests it. Teardown runs in reverse order.
  2. sales_db returns the same connection that empty_db yielded, now with rows. The close after yield still runs once, at the end of the test.
  3. The empty-table test is an edge case: GROUP BY on no rows returns no rows, not [(None, None)].

Alternative: copy data/shop.db into tmp_path and connect to the copy. That tests against the real schema, at the cost of a slower, bigger fixture.

M14-C05 · Test printed output with capsys

Section titled “M14-C05 · Test printed output with capsys”
Core

report.print_summary(counts) prints one aligned line per count. Test it with the real counts of data/sales_raw.csv (1,200 read, 36 duplicates, 10 bad quantities, 1,154 written). Compare the printed lines as a list.

Acceptance criteria:

  • pytest -q test_c05_summary.py reports 1 passed.
  • The test checks every line, including the thousands separator in 1,200.
Starter
from report import print_summary
def test_print_summary_of_the_real_file(capsys):
counts = {"read": 1200, "duplicates": 36, "bad_quantity": 10, "written": 1154}
# TODO: call print_summary, read the output with capsys
# TODO: assert the list of lines
Hint 1

capsys.readouterr().out.splitlines() gives the printed lines without the line breaks.

Hint 2

The format is f"{name:<13}{value:>6,}": the name left-aligned in 13 characters, the number right-aligned in 6 with a comma.

Solution
test_c05_summary.py
from report import print_summary
def test_print_summary_of_the_real_file(capsys):
counts = {"read": 1200, "duplicates": 36, "bad_quantity": 10, "written": 1154}
print_summary(counts)
lines = capsys.readouterr().out.splitlines()
assert lines == [
"read 1,200",
"duplicates 36",
"bad_quantity 10",
"written 1,154",
]
Terminal
pytest -q test_c05_summary.py
Output
. [100%]
1 passed in 0.18s

How it works:

  1. While a test runs, pytest captures standard output. capsys gives the test access to it.
  2. splitlines() makes the comparison readable and drops the last line break.
  3. A failure would show the two lists and the first differing line, for example a missing comma.

Alternative: make the function return the text (format_summary(counts) -> str) and print it in one place. A function that returns a string is easier to test than one that prints, and needs no capsys.

M14-C06 · Change settings with monkeypatch

Section titled “M14-C06 · Change settings with monkeypatch”
Core

cleaning.is_valid_quantity reads the module constant MAX_QUANTITY (100) each time it runs. Write three tests: one that lowers the limit to 10 with monkeypatch.setattr and checks that 50 is no longer valid; one that checks the limit is back to 100 in the next test; one that sets SALES_DATA_DIR to /srv/sales and checks report.data_dir().

Acceptance criteria:

  • pytest -q test_c06_monkeypatch.py reports 3 passed.
  • You can explain why the second test passes although the first test changed the constant.
Starter
from pathlib import Path
import cleaning
from report import data_dir
# TODO: test_quantity_limit_can_change(monkeypatch)
# TODO: test_limit_is_back_to_normal()
# TODO: test_data_dir_follows_the_environment(monkeypatch)
Hint 1

monkeypatch.setattr(cleaning, "MAX_QUANTITY", 10) replaces the attribute of the module object.

Hint 2

Import the module (import cleaning), not the name (from cleaning import MAX_QUANTITY). A copied name would not see the patch.

Solution
test_c06_monkeypatch.py
from pathlib import Path
import cleaning
from report import data_dir
def test_quantity_limit_can_change(monkeypatch):
assert cleaning.is_valid_quantity(50)
monkeypatch.setattr(cleaning, "MAX_QUANTITY", 10)
assert not cleaning.is_valid_quantity(50)
def test_limit_is_back_to_normal():
assert cleaning.MAX_QUANTITY == 100
def test_data_dir_follows_the_environment(monkeypatch):
monkeypatch.setenv("SALES_DATA_DIR", "/srv/sales")
assert data_dir() == Path("/srv/sales")
Terminal
pytest -q test_c06_monkeypatch.py
Output
... [100%]
3 passed in 0.18s

How it works:

  1. is_valid_quantity looks up MAX_QUANTITY in the module’s namespace at call time, so the patched value takes effect at once.
  2. At the end of the first test, monkeypatch restores the old value. The second test sees 100 again. Without monkeypatch, a plain cleaning.MAX_QUANTITY = 10 would leak into every later test.
  3. setenv changes os.environ for one test only. The path is never created; data_dir() only builds a Path.

Alternative: give the function a parameter, is_valid_quantity(quantity, high=MAX_QUANTITY), and pass high=10 in the test. A parameter is easier to test than a global setting, as parse_quantity in M14-X02 shows.

M14-C07 · Test a pandas function with assert_frame_equal

Section titled “M14-C07 · Test a pandas function with assert_frame_equal”
Core

Write add_net_revenue(sales): it returns a copy of the DataFrame with a new column net = unit_price × quantity × (1 − discount), rounded to 2 decimals. Test it on three hand-made lines with pd.testing.assert_frame_equal, and check that the input frame has no net column afterwards. Print a confirmation.

Expected output
add_net_revenue: frame matches, input unchanged
Starter
import pandas as pd
def add_net_revenue(sales: pd.DataFrame) -> pd.DataFrame:
# TODO: copy, add the net column, return the copy
...
sales = pd.DataFrame(
{"unit_price": [249.0, 79.99, 29.99], "quantity": [3, 1, 2], "discount": [0.1, 0.0, 0.05]}
)
# TODO: build the expected frame by hand and compare
Hint 1

sales.assign(net=...) returns a new frame and leaves sales unchanged.

Hint 2

By hand: 249.0 × 3 × 0.9 = 672.3, 79.99 × 1 × 1.0 = 79.99, 29.99 × 2 × 0.95 = 56.98 (56.981 rounded).

Solution
import pandas as pd
def add_net_revenue(sales: pd.DataFrame) -> pd.DataFrame:
net = sales["unit_price"] * sales["quantity"] * (1 - sales["discount"])
return sales.assign(net=net.round(2))
sales = pd.DataFrame(
{
"unit_price": [249.0, 79.99, 29.99],
"quantity": [3, 1, 2],
"discount": [0.1, 0.0, 0.05],
}
)
expected = sales.copy()
expected["net"] = [672.3, 79.99, 56.98]
result = add_net_revenue(sales)
pd.testing.assert_frame_equal(result, expected)
assert "net" not in sales.columns
print("add_net_revenue: frame matches, input unchanged")
Output
add_net_revenue: frame matches, input unchanged

How it works:

  1. assign returns a new DataFrame; the original keeps its three columns. The last assert checks that.
  2. The expected frame starts as a copy of the input, so the three input columns match by construction; only net is typed by hand.
  3. assert_frame_equal checks the values (with a float tolerance), the dtypes, the column order and the index.

Alternative: compare only the new column: pd.testing.assert_series_equal(result["net"], pd.Series([672.3, 79.99, 56.98], name="net")). That is shorter and focuses on the behavior under test.

M14-C08 · Test a z-score function with NumPy asserts

Section titled “M14-C08 · Test a z-score function with NumPy asserts”
Core

Write zscore(values): (value − mean) / standard deviation, with the population standard deviation (np.std, ddof=0). Test it in two ways. First, a known answer: for [1.0, 2.0, 3.0] the mean is 2 and the population standard deviation is √(2/3) ≈ 0.8165, so the z-scores are about [-1.2247, 0, 1.2247] (check with np.testing.assert_allclose). Second, two properties on the monthly charges of the first 200 customers in data/customers.csv: the result has mean 0 and standard deviation 1 (check with pytest.approx). Print the known-answer result and the first three real z-scores, rounded to 3 decimals.

Expected output
[-1.225 0. 1.225]
[ 1.264 -0.133 2.375]
Starter
import numpy as np
import pandas as pd
import pytest
def zscore(values: np.ndarray) -> np.ndarray:
# TODO
...
charges = pd.read_csv("data/customers.csv")["monthly_charges"].to_numpy()[:200]
# TODO: the known-answer check, the two property checks, then print
Hint 1

Work out the known answer by hand, not with the function: (1 − 2) / 0.8165 ≈ −1.2247. A check that reuses the function’s own formula cannot catch a wrong formula.

Hint 2

The mean of the z-scores is about 1e-16, not exactly 0. pytest.approx(0.0) already accepts it, because its default absolute tolerance is 1e-12.

Solution
import numpy as np
import pandas as pd
import pytest
def zscore(values: np.ndarray) -> np.ndarray:
return (values - values.mean()) / values.std()
known = zscore(np.array([1.0, 2.0, 3.0]))
np.testing.assert_allclose(known, [-1.224745, 0.0, 1.224745], rtol=1e-6)
charges = pd.read_csv("data/customers.csv")["monthly_charges"].to_numpy()[:200]
z = zscore(charges)
assert z.mean() == pytest.approx(0.0)
assert z.std() == pytest.approx(1.0)
print(np.round(known, 3))
print(np.round(z[:3], 3))
Output
[-1.225 0. 1.225]
[ 1.264 -0.133 2.375]

How it works:

  1. The known answer comes from arithmetic on three small numbers, not from the function, so it catches a wrong formula. With ddof=1 (the sample standard deviation, 1.0 here), the result would be [-1, 0, 1] and assert_allclose would fail and name the worst element.
  2. The mean of the real z-scores is 0 in theory and about 1e-16 in floating point. approx(0.0) uses the default absolute tolerance 1e-12, which covers it; a relative tolerance alone would mean nothing near 0.
  3. The standard deviation is 1 within one part in a million. The two properties hold for any input, so they also check the real data.

Alternative: compare with scipy.stats.zscore(charges), a trusted reference implementation that also uses ddof=0 by default. Testing against an independent reference is a good habit when one exists.

Core

Fix the bug: a teammate saved two checks in prices_check.py and ran pytest on it. pytest says it ran nothing:

prices_check.py
from cleaning import parse_price
def check_plain_price():
assert parse_price("$79.99") == 79.99
def check_missing_price():
assert parse_price("N/A") is None
Terminal
pytest -q prices_check.py
echo "exit code: $?"
Output
no tests ran in 0.00s
exit code: 5

Fix the names so that pytest finds both tests, also when you run a bare pytest in the folder. Save the result as test_c09_prices.py.

Acceptance criteria:

  • pytest -q test_c09_prices.py reports 2 passed and exit code 0.
  • You can name both naming problems of the original file.
Starter
from cleaning import parse_price
# TODO: rename the functions so that pytest collects them
Hint 1

Exit code 5 means “no tests collected”. pytest read the file (you named it on the command line) but found no test functions in it.

Hint 2

A bare pytest also skips the whole file, because its name does not match test_*.py.

Solution
test_c09_prices.py
from cleaning import parse_price
def test_plain_price():
assert parse_price("$79.99") == 79.99
def test_missing_price():
assert parse_price("N/A") is None
Terminal
pytest -q test_c09_prices.py
echo "exit code: $?"
Output
.. [100%]
2 passed in 0.00s
exit code: 0

How it works:

  1. Problem one: the functions start with check_, so pytest does not collect them.
  2. Problem two: the file name prices_check.py does not match test_*.py. When you name a file on the command line, pytest reads it anyway; a bare pytest or a CI run never looks at it. The checks then never run, and nobody notices.
  3. Exit code 5 is a useful alarm: a CI job that runs zero tests should fail, and with pytest it does.

Alternative: keep the names and configure python_files = ["test_*.py", "*_check.py"] and python_functions = ["test", "check"] under [tool.pytest]. Only do this for a real convention in your team; the defaults are what everyone expects.

Core

Predict the output: write down the five node IDs that pytest --collect-only -q test_c10_ids.py prints for this file. Watch the strings with spaces, the None and the date object.

Acceptance criteria:

  • Write all five IDs before you run the command.
  • Your IDs match the Output in the solution, and you can explain where expected0 comes from.
Starter
from datetime import date
import pytest
from cleaning import normalize_region, parse_date, parse_price
@pytest.mark.parametrize(("text", "expected"), [("$79.99", 79.99), ("N/A", None)])
def test_price(text, expected):
assert parse_price(text) == expected
@pytest.mark.parametrize("raw", ["north", " East "])
def test_region(raw):
assert normalize_region(raw) in {"North", "East"}
@pytest.mark.parametrize(("text", "expected"), [("2023-01-07", date(2023, 1, 7))])
def test_date(text, expected):
assert parse_date(text) == expected
Hint 1

For strings, numbers, None and booleans, pytest uses the value itself. Several arguments are joined with -.

Hint 2

For other objects, such as a date, pytest uses the argument name and the case number, counted from 0.

Solution
test_c10_ids.py
from datetime import date
import pytest
from cleaning import normalize_region, parse_date, parse_price
@pytest.mark.parametrize(("text", "expected"), [("$79.99", 79.99), ("N/A", None)])
def test_price(text, expected):
assert parse_price(text) == expected
@pytest.mark.parametrize("raw", ["north", " East "])
def test_region(raw):
assert normalize_region(raw) in {"North", "East"}
@pytest.mark.parametrize(("text", "expected"), [("2023-01-07", date(2023, 1, 7))])
def test_date(text, expected):
assert parse_date(text) == expected
Terminal
pytest --collect-only -q test_c10_ids.py
Output
test_c10_ids.py::test_price[$79.99-79.99]
test_c10_ids.py::test_price[N/A-None]
test_c10_ids.py::test_region[north]
test_c10_ids.py::test_region[ East ]
test_c10_ids.py::test_date[2023-01-07-expected0]
5 tests collected in 0.01s

How it works:

  1. $79.99-79.99: the string and the float, joined with -.
  2. N/A-None: None becomes the text None.
  3. East: the spaces stay in the ID, which makes it hard to type with -k or as a node ID.
  4. 2023-01-07-expected0: pytest has no short text for a date, so it uses the argument name expected and the index 0.

Alternative: add ids= or pytest.param(..., id="...") whenever the automatic IDs are unclear, as the lesson’s Example 4 does. ids also accepts a function, for example ids=str.strip.

M14-C11 · Refactor a loop test into parametrize

Section titled “M14-C11 · Refactor a loop test into parametrize”
Core

Refactor: this test checks four dates in a loop. When the first case fails, the loop stops and the other three never run, and the report does not say which format broke. Rewrite it as a parametrized test with the IDs iso, day-first, month-name and year-end.

The test body must have no loop. pytest -v --no-header test_c11_dates.py prints:

Expected output
======================================= test session starts ========================================
collecting ... collected 4 items
test_c11_dates.py::test_parse_date[iso] PASSED [ 25%]
test_c11_dates.py::test_parse_date[day-first] PASSED [ 50%]
test_c11_dates.py::test_parse_date[month-name] PASSED [ 75%]
test_c11_dates.py::test_parse_date[year-end] PASSED [100%]
======================================== 4 passed in 0.01s =========================================
Starter
from datetime import date
from cleaning import parse_date
def test_dates():
cases = [
("2023-01-07", date(2023, 1, 7)),
("07/01/2023", date(2023, 1, 7)),
("January 7, 2023", date(2023, 1, 7)),
("31/12/2024", date(2024, 12, 31)),
]
for text, expected in cases:
assert parse_date(text) == expected
# TODO: replace with @pytest.mark.parametrize and pytest.param(..., id=...)
Hint 1

Move the cases list into the decorator. Wrap each tuple in pytest.param(text, expected, id="...").

Hint 2

A module constant such as JAN_7 = date(2023, 1, 7) shortens the repeated date.

Solution
test_c11_dates.py
from datetime import date
import pytest
from cleaning import parse_date
JAN_7 = date(2023, 1, 7)
@pytest.mark.parametrize(
("text", "expected"),
[
pytest.param("2023-01-07", JAN_7, id="iso"),
pytest.param("07/01/2023", JAN_7, id="day-first"),
pytest.param("January 7, 2023", JAN_7, id="month-name"),
pytest.param("31/12/2024", date(2024, 12, 31), id="year-end"),
],
)
def test_parse_date(text, expected):
assert parse_date(text) == expected
Terminal
pytest -v --no-header test_c11_dates.py
Output
======================================= test session starts ========================================
collecting ... collected 4 items
test_c11_dates.py::test_parse_date[iso] PASSED [ 25%]
test_c11_dates.py::test_parse_date[day-first] PASSED [ 50%]
test_c11_dates.py::test_parse_date[month-name] PASSED [ 75%]
test_c11_dates.py::test_parse_date[year-end] PASSED [100%]
======================================== 4 passed in 0.01s =========================================

How it works:

  1. pytest makes one test per pytest.param. Each passes or fails alone.
  2. A failure now reads test_parse_date[day-first], which names the broken format.
  3. -k day runs one case while you debug it.

Alternative: the subtests fixture (built into pytest 9) keeps a loop but reports each case separately: with subtests.test(text=text): assert .... Parametrize is still the usual choice when the cases are known in advance.

M14-C12 · Characterization tests for a legacy function

Section titled “M14-C12 · Characterization tests for a legacy function”
Core

An old reporting script has a function size_band(units) with no docstring and no tests. Before anyone changes it, record what it does today. Print the band for the quantities -1, 0, 1, 2, 9, 10, 100 and 101, then pin every result with an assert.

Expected output
-1 invalid
0 invalid
1 single
2 multi
9 multi
10 large
100 large
101 bulk
Starter
def size_band(units):
if units > 100:
return "bulk"
elif units >= 10:
return "large"
elif units > 1:
return "multi"
elif units == 1:
return "single"
else:
return "invalid"
# TODO: print each quantity and its band, then assert each result
Hint 1

Run the function first and read the results. A characterization test records behavior; it does not judge it.

Hint 2

Test both sides of every border: 1 and 2, 9 and 10, 100 and 101.

Solution
def size_band(units):
if units > 100:
return "bulk"
elif units >= 10:
return "large"
elif units > 1:
return "multi"
elif units == 1:
return "single"
else:
return "invalid"
quantities = [-1, 0, 1, 2, 9, 10, 100, 101]
bands = {units: size_band(units) for units in quantities}
for units, band in bands.items():
print(f"{units:>4} {band}")
assert bands == {
-1: "invalid",
0: "invalid",
1: "single",
2: "multi",
9: "multi",
10: "large",
100: "large",
101: "bulk",
}
Output
-1 invalid
0 invalid
1 single
2 multi
9 multi
10 large
100 large
101 bulk

How it works:

  1. The quantities sit on both sides of every border in the if chain.
  2. The results expose a surprise: 100 is large, not bulk, because the first test is > 100. Whether that is a bug is a business question. The test makes the behavior visible and stops it from changing by accident.
  3. In a test file, write one parametrized test with these eight pairs. Then refactor size_band, for example into a loop over thresholds, and the tests tell you if anything changed.

Alternative: record the outputs for many inputs in a file once (a “golden file”) and compare future runs with it. That scales to functions with complex outputs, such as a whole report.

M14-C13 · Read a coverage report and close the gaps

Section titled “M14-C13 · Read a coverage report and close the gaps”
Core

Interpret the result: c13_shipping.py computes shipping costs. Its two tests pass, but the coverage report shows gaps:

c13_shipping.py
"""Shipping cost of an online order, in USD."""
def shipping_cost(order_total: float, region: str, express: bool = False) -> float:
"""Free from 100 USD; the West pays a surcharge; express doubles it plus 5."""
if order_total < 0:
raise ValueError("order_total must not be negative")
if order_total >= 100:
cost = 0.0
else:
cost = 4.99
if region == "West":
cost += 2.0
if express:
cost = cost * 2 + 5
return round(cost, 2)
test_c13_shipping.py
from c13_shipping import shipping_cost
def test_small_order_pays_standard_rate():
assert shipping_cost(59.99, "East") == 4.99
def test_large_order_ships_free():
assert shipping_cost(249.0, "North") == 0.0
Terminal
pytest -q --cov=c13_shipping --cov-branch --cov-report= test_c13_shipping.py
coverage report -m
Output
.. [100%]
2 passed in 0.01s
Name Stmts Miss Branch BrPart Cover Missing
-------------------------------------------------------------
c13_shipping.py 11 3 8 3 68% 7, 13, 15
-------------------------------------------------------------
TOTAL 11 3 8 3 68%

Name the behavior behind each missing line. Then write test_c13_more.py with one test per gap, plus a test for express shipping on a free order. Run both files with coverage.

Each new test name states the rule it checks. The coverage run over both files prints:

Expected output
...... [100%]
6 passed in 0.02s
Name Stmts Miss Branch BrPart Cover Missing
-------------------------------------------------------------
c13_shipping.py 11 0 8 0 100%
-------------------------------------------------------------
TOTAL 11 0 8 0 100%
Starter
import pytest
from c13_shipping import shipping_cost
# TODO: test the negative total (line 7)
# TODO: test the West surcharge (line 13)
# TODO: test express shipping (line 15), on a paid and on a free order
Hint 1

Line 7 is the raise, line 13 the surcharge and line 15 the express formula.

Hint 2

Express on 59.99 to the East: 4.99 × 2 + 5 = 14.98. Express on a free order: 0 × 2 + 5 = 5.0.

Solution
test_c13_more.py
import pytest
from c13_shipping import shipping_cost
def test_negative_total_is_rejected():
with pytest.raises(ValueError, match="negative"):
shipping_cost(-1.0, "East")
def test_west_pays_a_surcharge():
assert shipping_cost(59.99, "West") == 6.99
def test_express_doubles_and_adds_five():
assert shipping_cost(59.99, "East", express=True) == 14.98
def test_express_on_a_free_order_costs_five():
assert shipping_cost(249.0, "North", express=True) == 5.0
Terminal
pytest -q --cov=c13_shipping --cov-branch --cov-report= test_c13_shipping.py test_c13_more.py
coverage report -m
Output
...... [100%]
6 passed in 0.02s
Name Stmts Miss Branch BrPart Cover Missing
-------------------------------------------------------------
c13_shipping.py 11 0 8 0 100%
-------------------------------------------------------------
TOTAL 11 0 8 0 100%

How it works:

  1. Line 7: no test passed a negative total. Line 13: no test shipped to the West. Line 15: no test used express. BrPart 3 means three if statements went only one way.
  2. Each new test targets one gap. The free-order express test adds no coverage, but it checks a rule worth knowing: express is never free.
  3. shipping_cost returns rounded values, so exact == is safe here. 4.99 + 2.0 rounds to 6.99.

Alternative: write the four new cases plus the two old ones as one parametrized table of (total, region, express, expected). A table makes it easy to see which combinations you test.

Core

Choose a method and justify it: for each check below, pick ==, pytest.approx, np.testing.assert_allclose or pd.testing.assert_frame_equal, and write the check. (a) The number of rows in data/sales_raw.csv is 1,200. (b) The mean unit price in data/products.csv is 177.61, as the data dictionary says (2 decimals). (c) Min-max scaling of [19.5, 21.2, 20.1] gives [0, 1, 0.3529…]. (d) A groupby sum of three revenue lines (West 224.1, East 29.99, West 179.0) equals a hand-typed table. Print one line per check.

Expected output
(a) rows: ==
(b) mean price 177.6090: approx(abs=0.005)
(c) scaled readings: assert_allclose
(d) table: assert_frame_equal
Starter
import numpy as np
import pandas as pd
import pytest
products = pd.read_csv("data/products.csv")
raw = pd.read_csv("data/sales_raw.csv")
# TODO: (a) row count, (b) mean price, (c) scaled readings, (d) a small table
Hint 1

Counts are integers: exact. Floats from arithmetic: a tolerance.

Hint 2

A value shown to 2 decimals is only accurate to ±0.005. Use abs=0.005, not the default relative tolerance.

Solution
import numpy as np
import pandas as pd
import pytest
products = pd.read_csv("data/products.csv")
raw = pd.read_csv("data/sales_raw.csv")
# (a) an integer count: exact equality
assert len(raw) == 1200
print("(a) rows: ==")
# (b) a float rounded in the documentation: approx with an absolute tolerance
mean_price = products["unit_price"].mean()
assert mean_price == pytest.approx(177.61, abs=0.005)
print(f"(b) mean price {mean_price:.4f}: approx(abs=0.005)")
# (c) a float array: assert_allclose
readings = np.array([19.5, 21.2, 20.1])
scaled = (readings - readings.min()) / (readings.max() - readings.min())
np.testing.assert_allclose(scaled, [0.0, 1.0, 0.6 / 1.7])
print("(c) scaled readings: assert_allclose")
# (d) a whole table: assert_frame_equal
lines = pd.DataFrame(
{"region": ["West", "East", "West"], "revenue": [224.1, 29.99, 179.0]}
)
table = lines.groupby("region", as_index=False)["revenue"].sum()
expected = pd.DataFrame({"region": ["East", "West"], "revenue": [29.99, 403.1]})
pd.testing.assert_frame_equal(table, expected)
print("(d) table: assert_frame_equal")
Output
(a) rows: ==
(b) mean price 177.6090: approx(abs=0.005)
(c) scaled readings: assert_allclose
(d) table: assert_frame_equal

How it works:

  1. (a) A count has no rounding error. A tolerance would hide a lost row.
  2. (b) The documented 177.61 is rounded, so the true mean may be up to 0.005 away. A relative tolerance of 1e-6 would be 0.00018: too strict for a rounded number.
  3. (c) Arrays need an element-wise comparison; == on arrays returns an array, and assert on it raises ValueError. assert_allclose also reports the worst element.
  4. (d) DataFrames carry dtypes, an index and column names. assert_frame_equal checks them all. The expected table is typed by hand (West 224.1 + 179.0 = 403.1; groupby sorts the regions), so the check can fail if the grouping is wrong.

Alternative: pytest.approx also accepts NumPy arrays: assert scaled == pytest.approx([0.0, 1.0, 0.6 / 1.7]). assert_allclose gives a better report for large arrays.

Core

Write three edge-case tests for clean_file, each with its own file in tmp_path: a file with only the header line (all counts 0, the output has only the header), a file with one row three times (2 duplicates, 1 written) and a file with the region Mars (the run stops with ValueError: unknown region: 'Mars'). Write a small helper write_raw(folder, lines) that builds the files.

No two tests may share a file. pytest -q test_c15_edges.py prints:

Expected output
... [100%]
3 passed in 0.01s
Starter
import pytest
from cleaning import clean_file
HEADER = "order_id,order_date,region,product,unit_price,quantity,discount\n"
ROW = "O000005,2023-01-01,East,Weeknight Kitchen Cookbook,$29.99,1,0.0\n"
def write_raw(folder, lines):
# TODO: write HEADER + lines to folder / "raw.csv" and return the path
...
# TODO: test_header_only_file, test_three_copies_of_one_row,
# test_unknown_region_stops_the_run
Hint 1

[ROW] * 3 is a list with the same line three times.

Hint 2

ROW.replace("East", "Mars") makes the bad row. In match=, the quotes around Mars are ordinary characters.

Solution
test_c15_edges.py
from pathlib import Path
import pytest
from cleaning import clean_file
HEADER = "order_id,order_date,region,product,unit_price,quantity,discount\n"
ROW = "O000005,2023-01-01,East,Weeknight Kitchen Cookbook,$29.99,1,0.0\n"
def write_raw(folder: Path, lines: list[str]) -> Path:
path = folder / "raw.csv"
path.write_text(HEADER + "".join(lines), encoding="utf-8")
return path
def test_header_only_file(tmp_path):
out = tmp_path / "clean.csv"
counts = clean_file(write_raw(tmp_path, []), out)
assert counts == {"read": 0, "duplicates": 0, "bad_quantity": 0, "written": 0}
assert len(out.read_text(encoding="utf-8").splitlines()) == 1
def test_three_copies_of_one_row(tmp_path):
counts = clean_file(write_raw(tmp_path, [ROW] * 3), tmp_path / "clean.csv")
assert counts["duplicates"] == 2
assert counts["written"] == 1
def test_unknown_region_stops_the_run(tmp_path):
bad = ROW.replace("East", "Mars")
with pytest.raises(ValueError, match="unknown region: 'Mars'"):
clean_file(write_raw(tmp_path, [bad]), tmp_path / "clean.csv")
Terminal
pytest -q test_c15_edges.py
Output
... [100%]
3 passed in 0.01s

How it works:

  1. Each test has its own tmp_path, so the three raw.csv files never meet.
  2. The empty file proves that the cleaner handles “no data” without a crash and still writes a valid header.
  3. The third test documents a design decision: an unknown region stops the run (fail fast) instead of being written silently.

Alternative: make write_raw a fixture that returns a function (a “factory fixture”), as the mini-project’s write_csv does. Then any test can request it by name.

M14-X01 · An integration test suite for the full raw file

Section titled “M14-X01 · An integration test suite for the full raw file”
Challenge

Write test_x01_real_file.py: a session-scoped fixture cleaned cleans data/sales_raw.csv once into a folder from tmp_path_factory and returns the counts and the clean rows. Six tests check: the counts add up, the counts equal the data dictionary (1,200 / 36 / 10 / 1,154), no clean row appears twice, all dates lie in 2023–2024, every region is one of the four or empty, and every quantity is 1–100 with every present price above 0.

pytest -q --setup-show test_x01_real_file.py must show SETUP S cleaned exactly once. pytest -q test_x01_real_file.py prints:

Expected output
...... [100%]
6 passed in 0.02s
Starter
import csv
from datetime import date
from pathlib import Path
import pytest
from cleaning import REGIONS, clean_file
@pytest.fixture(scope="session")
def cleaned(tmp_path_factory):
# TODO: mktemp a folder, clean the real file into it, read the rows back
...
# TODO: six tests
Hint 1

tmp_path is function-scoped, so a session fixture cannot use it. tmp_path_factory.mktemp("clean") makes a folder that lives for the whole session.

Hint 2

Return a tuple (counts, rows). Each test unpacks the part it needs: counts, _ = cleaned.

Hint 3

The clean file stores dates as ISO text. date.fromisoformat(row["order_date"]) turns them back into dates.

Solution
test_x01_real_file.py
import csv
from datetime import date
from pathlib import Path
import pytest
from cleaning import REGIONS, clean_file
@pytest.fixture(scope="session")
def cleaned(tmp_path_factory):
out = tmp_path_factory.mktemp("clean") / "sales_clean.csv"
counts = clean_file(Path("data/sales_raw.csv"), out)
with out.open(newline="", encoding="utf-8") as file:
rows = list(csv.DictReader(file))
return counts, rows
def test_counts_add_up(cleaned):
counts, rows = cleaned
dropped = counts["duplicates"] + counts["bad_quantity"]
assert counts["read"] == dropped + counts["written"]
assert counts["written"] == len(rows)
def test_known_counts(cleaned):
counts, _ = cleaned
assert counts == {
"read": 1200,
"duplicates": 36,
"bad_quantity": 10,
"written": 1154,
}
def test_no_duplicate_rows(cleaned):
_, rows = cleaned
keys = [tuple(row.values()) for row in rows]
assert len(keys) == len(set(keys))
def test_dates_inside_the_sales_period(cleaned):
_, rows = cleaned
dates = [date.fromisoformat(row["order_date"]) for row in rows]
assert min(dates) >= date(2023, 1, 1)
assert max(dates) <= date(2024, 12, 31)
def test_regions_are_clean(cleaned):
_, rows = cleaned
assert {row["region"] for row in rows} <= REGIONS | {""}
def test_quantities_and_prices(cleaned):
_, rows = cleaned
assert all(1 <= int(row["quantity"]) <= 100 for row in rows)
prices = [float(row["unit_price"]) for row in rows if row["unit_price"]]
assert min(prices) > 0
Terminal
pytest -q test_x01_real_file.py
Output
...... [100%]
6 passed in 0.02s

How it works:

  1. The session fixture cleans the 1,200 rows once; six tests reuse the result. No test changes counts or rows, so sharing is safe.
  2. Two kinds of checks work together. Invariants (counts add up, no duplicates, valid ranges) hold for any input file. Known values (1,154 written) pin this particular file and catch a change in either the data or the code.
  3. <= between sets means “is a subset of”: every region in the output is a known region or empty.
  4. An integration test like this is slower than a unit test. Mark it @pytest.mark.slow in a real project, as the lesson’s Example 7 does.

Alternative: schema libraries such as pandera describe these checks declaratively (column types, allowed values, ranges) and run them on every new file, not just in tests. Module 26 covers validation checks on DataFrames.

Challenge

Red-green-refactor: the tests come first. They describe parse_quantity(text, low=1, high=100) in x02_quantity.py, which does not exist yet. Write the module so that every test passes. Then check two calls in a script.

test_x02_quantity.py
import pytest
from x02_quantity import parse_quantity
@pytest.mark.parametrize(("text", "expected"), [("1", 1), (" 3 ", 3), ("100", 100)])
def test_valid_quantities(text, expected):
assert parse_quantity(text) == expected
@pytest.mark.parametrize("text", ["0", "-2", "101", "999"])
def test_out_of_range(text):
with pytest.raises(ValueError, match="out of range"):
parse_quantity(text)
@pytest.mark.parametrize("text", ["2.5", "two", ""])
def test_not_a_whole_number(text):
with pytest.raises(ValueError, match="not a whole number"):
parse_quantity(text)
def test_custom_limits():
assert parse_quantity("500", high=1000) == 500
Expected output
3 999
Starter
def parse_quantity(text: str, low: int = 1, high: int = 100) -> int:
# TODO: red first: run the tests and watch them fail
# TODO: green: convert, check the range, raise the two messages
...
Hint 1

Before you write any code, run pytest -q test_x02_quantity.py. It fails at collection with ModuleNotFoundError: No module named 'x02_quantity'. That is your red step.

Hint 2

int("2.5") and int("") raise ValueError with Python’s own message. Catch it and raise your own message, with from None to hide the first traceback.

Hint 3

int(" 3 ") is 3: int() ignores surrounding spaces, so you need no strip().

Solution
x02_quantity.py
"""Parse the quantity column of the raw sales file."""
def parse_quantity(text: str, low: int = 1, high: int = 100) -> int:
"""Turn ' 3 ' into 3. Reject text that is not a whole number in [low, high]."""
try:
quantity = int(text)
except ValueError:
raise ValueError(f"not a whole number: {text!r}") from None
if not low <= quantity <= high:
raise ValueError(f"quantity out of range: {quantity}")
return quantity
Terminal
pytest -q test_x02_quantity.py
Output
........... [100%]
11 passed in 0.01s
from x02_quantity import parse_quantity
print(parse_quantity(" 3 "), parse_quantity("999", high=1000))
assert parse_quantity("1") == 1
Output
3 999

How it works:

  1. Red: the import fails, then each test fails until its rule is implemented. Implement one rule at a time and rerun.
  2. Green: int() handles spaces and rejects "2.5", "two" and "". The except turns its message into the one the tests expect. from None drops the original exception from the traceback.
  3. The range check uses the parameters, so test_custom_limits passes without extra code.
  4. Refactor: with 11 green tests, you can safely rewrite the body, for example with str.isdigit(). Try it: " 3 ".isdigit() is False, and the tests catch the regression at once.

Alternative: return None for invalid text instead of raising, like parse_price does for missing tokens. That suits optional fields. A quantity is required, so failing loudly is the better design here.

M14-X03 · A test that catches data leakage

Section titled “M14-X03 · A test that catches data leakage”
Challenge

Data leakage means that information from the test set reaches the model during training, so the test score looks better than real performance (module 33). A common leak: fitting a scaler on train and test data together. Write scale_train_test(train, test) that fits a StandardScaler on train only. Then write a check that passes for your function and fails for the leaky version below. Use tenure_months and monthly_charges of data/customers.csv, with the first 3,750 rows as train and the rest as test.

Leaky version
def scale_leaky(train, test):
scaler = StandardScaler().fit(np.vstack([train, test])) # leak!
return scaler.transform(train), scaler.transform(test)
Expected output
correct version passes: True
leaky version passes: False
test means after scaling: [-1.385 -0.058]
Starter
import numpy as np
import pandas as pd
import pytest
from sklearn.preprocessing import StandardScaler
customers = pd.read_csv("data/customers.csv")
X = customers[["tenure_months", "monthly_charges"]].to_numpy()
train, test = X[:3750], X[3750:]
def scale_train_test(train, test):
# TODO: fit on train only
...
def check_no_leak(scale):
# TODO: return True when the scaler was fitted on train only
...
Hint 1

After a correct fit, the scaled train columns have mean 0 and standard deviation 1. After the leaky fit, they do not, because the mean came from all rows.

Hint 2

A stronger check: the scaled test data must equal (test - train.mean(axis=0)) / train.std(axis=0). Use np.allclose to return a bool.

Solution
from collections.abc import Callable
import numpy as np
import pandas as pd
import pytest
from sklearn.preprocessing import StandardScaler
customers = pd.read_csv("data/customers.csv")
X = customers[["tenure_months", "monthly_charges"]].to_numpy()
train, test = X[:3750], X[3750:]
def scale_train_test(
train: np.ndarray, test: np.ndarray
) -> tuple[np.ndarray, np.ndarray]:
scaler = StandardScaler().fit(train)
return scaler.transform(train), scaler.transform(test)
def scale_leaky(
train: np.ndarray, test: np.ndarray
) -> tuple[np.ndarray, np.ndarray]:
scaler = StandardScaler().fit(np.vstack([train, test])) # leak!
return scaler.transform(train), scaler.transform(test)
Scaler = Callable[[np.ndarray, np.ndarray], tuple[np.ndarray, np.ndarray]]
def check_no_leak(scale: Scaler) -> bool:
train_scaled, test_scaled = scale(train.copy(), test.copy())
by_hand = (test - train.mean(axis=0)) / train.std(axis=0)
centered = train_scaled.mean(axis=0) == pytest.approx([0.0, 0.0], abs=1e-9)
return bool(centered and np.allclose(test_scaled, by_hand))
print("correct version passes:", check_no_leak(scale_train_test))
print("leaky version passes: ", check_no_leak(scale_leaky))
test_means = scale_train_test(train, test)[1].mean(axis=0)
print("test means after scaling:", np.round(test_means, 3))
assert check_no_leak(scale_train_test)
assert not check_no_leak(scale_leaky)
Output
correct version passes: True
leaky version passes: False
test means after scaling: [-1.385 -0.058]

How it works:

  1. The check recomputes the scaling by hand from the train statistics only and compares. Any other fit gives other numbers.
  2. The leaky version fails both parts: its train means are not 0, and its test values differ from the hand computation.
  3. The scaled test means are not 0. That is correct: newer customers (the last rows) have shorter tenure. A test set never has exactly the train statistics.
  4. The function receives copies, so the check also cannot be fooled by a function that changes its input.

Alternative: in a pytest file, parametrize one test over both functions with pytest.param(scale_leaky, marks=pytest.mark.xfail(strict=True)). xfail marks a test that must fail; with strict=True, an unexpected pass becomes a failure.

M14-X04 · Property checks with random inputs

Section titled “M14-X04 · Property checks with random inputs”
Challenge

Hand-picked cases miss inputs you did not think of. A property-based test checks a rule on many generated inputs instead. Generate 1,000 random sales lines with np.random.default_rng(42): prices from 14.99 to 1,299.00, quantities 1–10 and discounts from [0.0, 0.05, 0.1, 0.2]. Check three properties of cleaning.line_revenue: the revenue lies between 0 and price × quantity; with no discount it equals round(price × quantity, 2); a bigger discount never gives a bigger revenue. Print how many lines you checked and the largest revenue.

Expected output
checked 1000 random lines; largest revenue 12,973.90
Starter
import numpy as np
from cleaning import line_revenue
rng = np.random.default_rng(42)
prices = rng.uniform(14.99, 1299.00, size=1000).round(2)
quantities = rng.integers(1, 11, size=1000)
# TODO: discounts with rng.choice
# TODO: check the three properties for every line
Hint 1

Convert NumPy scalars with float() and int() before you call line_revenue, so the results are plain Python floats.

Hint 2

For the third property, compute the revenue of each line under all four discounts and check that the list never goes up: all(a >= b for a, b in zip(revs, revs[1:])).

Solution
import numpy as np
from cleaning import line_revenue
DISCOUNTS = [0.0, 0.05, 0.1, 0.2]
rng = np.random.default_rng(42)
prices = rng.uniform(14.99, 1299.00, size=1000).round(2)
quantities = rng.integers(1, 11, size=1000)
discounts = rng.choice(DISCOUNTS, size=1000)
largest = 0.0
for price, qty, disc in zip(prices, quantities, discounts, strict=True):
price, qty, disc = float(price), int(qty), float(disc)
revenue = line_revenue(price, qty, disc)
assert 0 <= revenue <= price * qty + 0.005
assert line_revenue(price, qty) == round(price * qty, 2)
revs = [line_revenue(price, qty, d) for d in DISCOUNTS]
assert all(a >= b for a, b in zip(revs, revs[1:]))
largest = max(largest, revenue)
print(f"checked {len(prices)} random lines; largest revenue {largest:,.2f}")
Output
checked 1000 random lines; largest revenue 12,973.90

How it works:

  1. A fixed seed makes the 1,000 inputs the same on every run, so a failure can be reproduced.
  2. The upper bound has + 0.005: rounding to cents can push the result up by up to half a cent. Without it, 31 of the 1,000 lines fail: 167.73 × 6 is 1006.3799999999999 in floating point, and rounding gives 1006.38. A hand-picked test would rarely find this detail.
  3. Properties describe rules, not values. They fit functions where many inputs are valid and the exact answer is tedious to compute by hand.

Alternative: the Hypothesis library (uv add --dev hypothesis) generates inputs for you with @given(st.floats(...)), and when a property fails it shrinks the input to the smallest failing example. It runs inside pytest.

Challenge

x05_cli.py wraps the cleaner in a command-line interface: python x05_cli.py RAW CLEAN cleans the file and prints the summary, and a missing input file exits with code 2. Write test_x05_cli.py with three tests that call main() with a list of arguments: a successful run on the raw_csv fixture (exit value 0, the clean file exists, the last printed line is written 4), a missing file (SystemExit with code 2 and file not found on stderr) and no arguments (SystemExit and a usage line on stderr). These in-process calls are integration tests. Finally, run the tool for real from the terminal on data/sales_raw.csv: that is the end-to-end check.

x05_cli.py
"""Command-line tool: clean a raw sales file and print a summary."""
import argparse
from pathlib import Path
from cleaning import clean_file
from report import print_summary
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="Clean a raw sales CSV file.")
parser.add_argument("src", type=Path, help="the raw CSV file")
parser.add_argument("dst", type=Path, help="where to write the clean CSV file")
args = parser.parse_args(argv)
if not args.src.is_file():
parser.error(f"file not found: {args.src}")
print_summary(clean_file(args.src, args.dst))
return 0
if __name__ == "__main__":
raise SystemExit(main())

The solution’s terminal block runs the tests, then the tool on the full file and on a missing file. It prints:

Expected output
... [100%]
3 passed in 0.18s
read 1,200
duplicates 36
bad_quantity 10
written 1,154
usage: x05_cli.py [-h] src dst
x05_cli.py: error: file not found: data/missing.csv
exit code: 2
Starter
import pytest
from x05_cli import main
def test_cleans_a_file(raw_csv, tmp_path, capsys):
# TODO
...
def test_missing_file_exits_with_code_2(tmp_path, capsys):
# TODO: pytest.raises(SystemExit) as excinfo; check excinfo.value.code
...
def test_no_arguments_prints_usage(capsys):
# TODO
...
Hint 1

main() takes argv as a list of strings, the way module 08 tested argparse. Convert paths with str().

Hint 2

parser.error() prints to stderr and raises SystemExit(2). The exit code is excinfo.value.code.

Hint 3

Call capsys.readouterr() once per test and keep the result: each call empties the buffers.

Solution
test_x05_cli.py
import pytest
from x05_cli import main
def test_cleans_a_file(raw_csv, tmp_path, capsys):
out = tmp_path / "clean.csv"
assert main([str(raw_csv), str(out)]) == 0
assert out.is_file()
assert capsys.readouterr().out.splitlines()[-1] == "written 4"
def test_missing_file_exits_with_code_2(tmp_path, capsys):
with pytest.raises(SystemExit) as excinfo:
main([str(tmp_path / "missing.csv"), str(tmp_path / "clean.csv")])
assert excinfo.value.code == 2
assert "file not found" in capsys.readouterr().err
def test_no_arguments_prints_usage(capsys):
with pytest.raises(SystemExit):
main([])
assert capsys.readouterr().err.startswith("usage:")
Terminal
pytest -q test_x05_cli.py
python x05_cli.py data/sales_raw.csv sales_clean.csv
python x05_cli.py data/missing.csv sales_clean.csv 2>&1
echo "exit code: $?"
Output
... [100%]
3 passed in 0.20s
read 1,200
duplicates 36
bad_quantity 10
written 1,154
usage: x05_cli.py [-h] src dst
x05_cli.py: error: file not found: data/missing.csv
exit code: 2

How it works:

  1. main(argv) takes the arguments as a parameter, so a test can call it like a function. The if __name__ == "__main__": line passes nothing, and argparse then reads sys.argv.
  2. The first test is an integration test of the whole chain inside one Python process: argument parsing, file cleaning and printing. It uses three fixtures at once. The terminal run after the tests is the end-to-end check, because it starts the program exactly as a user does.
  3. argparse signals errors with SystemExit, not a return value. pytest.raises(SystemExit) catches it, and excinfo.value.code holds the exit code.
  4. The real run shows the same behavior from a terminal, including the usage line and exit code 2. 2>&1 sends the error text to standard output, so it appears in order before the echo line.

Alternative: run the tool in a subprocess from the test, subprocess.run([sys.executable, "x05_cli.py", ...], capture_output=True, text=True), and check returncode and stdout. That tests exactly what a user runs, but it is slower and harder to debug.