14. Testing with pytest — Mini-project
The data team receives a new raw sales export every month. Before anyone cleans it, they want a report of what is wrong with it: how many rows have a missing region, a misspelled region, a broken date or a revenue that does not match price × quantity × (1 − discount). If a new kind of problem appears, they want to know before the dashboards are wrong.
Build salescheck: a small project with one module, validate.py, and a pytest suite that proves it right. The validator does not change any data. It only counts problems. The suite is the main deliverable: it must be fast, readable and strict enough that the team can change the validator without fear.
The project uses every part of module 14: test functions, fixtures in conftest.py (including fixtures that return functions), parametrize with IDs, tmp_path, capsys, pytest.raises, a marker for a slow test, a [tool.pytest] configuration and a coverage gate.
Dataset
Section titled “Dataset”data/sales_raw.csv: 1,200 rows with 13 columns (order_id, order_date, customer_id, store_id, region, channel, product_id, product, category, unit_price, quantity, discount, revenue). The data dictionary lists the injected problems, counted in the file:
| Problem | Count |
|---|---|
| exact duplicate rows | 36 |
| region in wrong case or with spaces | 259 |
missing region ("", N/A, -) |
17 |
| missing customer_id | 23 |
| missing channel | 17 |
| missing discount | 24 |
| missing unit_price | 10 |
| product with stray spaces | 95 |
| negative or absurd quantity | 10 |
dates in three formats (ISO, DD/MM/YYYY, Month D, YYYY) |
all valid |
These counts are your oracle: an independent source of the right answer. A slow integration test compares your validator with them.
Requirements
Section titled “Requirements”Your project must have this layout, inside your course folder next to data/:
salescheck/├── pyproject.toml├── validate.py└── tests/ ├── conftest.py ├── test_validate_row.py └── test_validate_file.pyvalidate.py must provide:
validate_row(row: dict[str, str]) -> list[str]: the problems of one row, in a fixed order, as short labels:missing <field>forcustomer_id,region,channel,unit_priceanddiscount;bad date;region needs cleaning(it becomes valid afterstrip()andtitle());unknown region;product needs cleaning;bad quantity(outside 1–100);bad price(present but not a number);revenue mismatch(more than 0.01 away from price × quantity × (1 − discount), checked only when price and discount are present). A clean row gives[].validate_file(path) -> Counter[str]: the number ofrows, the number of exactduplicatesand the count of every problem label.print_report(counts):rowsandduplicatesfirst, then the problems from most to least common (ties in alphabetical order), aligned in columns.main(argv=None) -> int: the command linepython validate.py PATH. A missing file exits with code 2 andfile not foundon stderr.
The test suite must:
- Have at least 40 tests, all passing, in under one second without the slow test.
- Define shared fixtures in
tests/conftest.py: a clean row, and two factory fixtures (fixtures that return a function): one that builds a row with some fields changed, one that writes rows to a CSV intmp_path. - Use parametrize with readable IDs for every rule that has more than one example.
- Test the error path of
main()withpytest.raises(SystemExit)andcapsys. - Mark the test on the full file with
@pytest.mark.slow, register the marker and setstrict = true. - Reach at least 95% total coverage of
validate.pywith branch measurement on (theCovercolumn combines statements and branches), checked withcoverage report --fail-under=95.
Step plan
Section titled “Step plan”-
Configure the project. Write
pyproject.tomlwith a[tool.pytest]table (testpaths,pythonpath = ["."],strict,markers) and a[tool.coverage.run]table withbranch = true. -
Start with one clean row. Copy a real clean line of
data/sales_raw.csv(for example O000004) into aclean_rowfixture. Writetest_clean_row_has_no_problemsand avalidate_rowthat returns[]. Green. -
Add one rule at a time, test first. For each rule: write a parametrized test, watch it fail (red), implement the rule (green). Start with the missing tokens; parametrize over the field names and the three tokens at once by stacking two
@pytest.mark.parametrizedecorators. -
Write the
make_rowfactory fixture when you notice that every test copies the clean row and changes one field:make_row(region="north"). -
Test the file level. Write
write_csv, a factory fixture that writes rows totmp_path. Test thatvalidate_filecounts rows and duplicates on a three-row file. -
Test the report and the CLI with
capsysandpytest.raises(SystemExit). -
Add the slow test that runs
validate_fileondata/sales_raw.csvand compares with the data dictionary. Build the path fromPath(__file__), so it works from any folder. -
Measure coverage with
pytest --cov=validate --cov-report=andcoverage report. Add tests for every missing branch until the gate passes. -
Run the validator on the real file:
python validate.py ../data/sales_raw.csv.
A skeleton for the first test file:
import pytest
from validate import REQUIRED, validate_row
def test_clean_row_has_no_problems(clean_row): assert validate_row(clean_row) == []
# TODO: test_missing_tokens: parametrize over REQUIRED and ["", "N/A", "-"]# TODO: test_region_problems, test_bad_dates, test_product_needs_cleaning# TODO: test_bad_quantity, test_bad_price, test_revenue_mismatchRubric
Section titled “Rubric”| Criterion | Points | Full points when |
|---|---|---|
| Correct validator | 3 | python validate.py ../data/sales_raw.csv prints the counts of the data dictionary |
| Suite passes and is fast | 2 | pytest -q -m "not slow" passes in under one second |
| Fixtures | 3 | conftest.py holds the clean row and two factory fixtures; no test builds a full row by hand |
| Parametrize | 2 | every multi-example rule is parametrized, with readable IDs where the values are unclear |
| Error paths | 2 | pytest.raises with match= or exit-code checks for every error the code raises |
| Output tests | 1 | the report order and the CLI are tested with capsys |
| Slow test and markers | 2 | the full-file test is marked, the marker is registered, strict = true |
| Coverage gate | 2 | coverage report --fail-under=95 exits with 0 |
| Readability | 1 | each test name states one rule |
| Total | 18 | 15 or more: you are ready for module 15 |
Stretch goals
Section titled “Stretch goals”- Add a
bad storerule:store_idmust beS01..S12. Write the tests first. - Report the line numbers of the first three rows with each problem, and test the new output with
capsys. - Accept several files on the command line and print one report per file. Test it with two files in
tmp_path. - Add a
--fail-on PROBLEMoption that exits with code 1 when that problem appears, so a CI job can block a bad export. Test both exit codes. - Write a property-based test with random rows from
np.random.default_rng(42): a row built only from valid values must always give[].
Reference solution
Section titled “Reference solution”Try the project yourself first. Then compare. Your labels and layout can differ; the counts on the real file must not.
Reference solution
[project]name = "salescheck"version = "0.1.0"description = "Validate a raw sales file and report every problem."requires-python = ">=3.12"dependencies = []
[dependency-groups]dev = ["pytest>=9.2", "pytest-cov>=7.1"]
[tool.pytest]testpaths = ["tests"]pythonpath = ["."]strict = truemarkers = ["slow: reads the full raw data file"]
[tool.coverage.run]branch = true
[tool.coverage.report]show_missing = trueexclude_also = ['if __name__ == "__main__":']exclude_also tells coverage to skip the if __name__ == "__main__": block. The tests call main() directly, so that one line never runs under pytest.
"""Validate the rows of a raw sales file and count every problem.
Usage: python validate.py data/sales_raw.csv"""
import argparseimport csvfrom collections import Counterfrom datetime import 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")REQUIRED = ("customer_id", "region", "channel", "unit_price", "discount")
def is_missing(text: str) -> bool: return text.strip() in MISSING_TOKENS
def is_date(text: str) -> bool: """True when text matches one of the three date formats of the file.""" for fmt in DATE_FORMATS: try: datetime.strptime(text.strip(), fmt) except ValueError: continue return True return False
def region_problem(text: str) -> str | None: if text in REGIONS: return None if text.strip().title() in REGIONS: return "region needs cleaning" return "unknown region"
def to_price(text: str) -> float | None: try: return float(text.strip().removeprefix("$").replace(",", "")) except ValueError: return None
def validate_row(row: dict[str, str]) -> list[str]: """Return the problems of one row; an empty list means the row is clean.""" problems = [f"missing {name}" for name in REQUIRED if is_missing(row[name])] if not is_date(row["order_date"]): problems.append("bad date") if not is_missing(row["region"]) and (issue := region_problem(row["region"])): problems.append(issue) if row["product"] != " ".join(row["product"].split()): problems.append("product needs cleaning") quantity = int(row["quantity"]) if not 1 <= quantity <= 100: problems.append("bad quantity") price = None if is_missing(row["unit_price"]) else to_price(row["unit_price"]) if not is_missing(row["unit_price"]) and price is None: problems.append("bad price") if price is not None and not is_missing(row["discount"]): expected = price * quantity * (1 - float(row["discount"])) if abs(expected - float(row["revenue"])) > 0.01: problems.append("revenue mismatch") return problems
def validate_file(path: Path) -> Counter[str]: """Count the rows, the exact duplicates and every problem in a raw file.""" with path.open(newline="", encoding="utf-8") as file: rows = list(csv.DictReader(file)) counts: Counter[str] = Counter(rows=len(rows)) counts["duplicates"] = len(rows) - len({tuple(row.values()) for row in rows}) for row in rows: counts.update(validate_row(row)) return counts
def print_report(counts: Counter[str]) -> None: """Print rows and duplicates first, then the problems, most common first.""" print(f"{'rows':<24}{counts['rows']:>6,}") print(f"{'duplicates':<24}{counts['duplicates']:>6,}") problems = [(n, c) for n, c in counts.items() if n not in ("rows", "duplicates")] for name, count in sorted(problems, key=lambda item: (-item[1], item[0])): print(f"{name:<24}{count:>6,}")
def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description="Validate a raw sales CSV file.") parser.add_argument("path", type=Path, help="the raw CSV file") args = parser.parse_args(argv) if not args.path.is_file(): parser.error(f"file not found: {args.path}") print_report(validate_file(args.path)) return 0
if __name__ == "__main__": raise SystemExit(main())import csvfrom collections.abc import Callablefrom pathlib import Path
import pytest
@pytest.fixturedef clean_row() -> dict[str, str]: """A real line of data/sales_raw.csv that has no problems.""" return { "order_id": "O000004", "order_date": "2023-01-01", "customer_id": "C01087", "store_id": "S11", "region": "West", "channel": "store", "product_id": "P002", "product": "Noise-Cancelling Headphones", "category": "Electronics", "unit_price": "$249.00", "quantity": "1", "discount": "0.1", "revenue": "224.1", }
@pytest.fixturedef make_row(clean_row: dict[str, str]) -> Callable[..., dict[str, str]]: """Return a function that builds a row: the clean row plus some changes."""
def _make_row(**changes: str) -> dict[str, str]: return clean_row | changes
return _make_row
@pytest.fixturedef write_csv(tmp_path: Path) -> Callable[[list[dict[str, str]]], Path]: """Return a function that writes rows to a CSV file in tmp_path."""
def _write_csv(rows: list[dict[str, str]]) -> Path: path = tmp_path / "raw.csv" with path.open("w", newline="", encoding="utf-8") as file: writer = csv.DictWriter(file, fieldnames=list(rows[0])) writer.writeheader() writer.writerows(rows) return path
return _write_csvimport pytest
from validate import REQUIRED, validate_row
def test_clean_row_has_no_problems(clean_row): assert validate_row(clean_row) == []
@pytest.mark.parametrize("token", ["", "N/A", "-"], ids=["empty", "n/a", "dash"])@pytest.mark.parametrize("field", REQUIRED)def test_missing_tokens(make_row, field, token): assert f"missing {field}" in validate_row(make_row(**{field: token}))
@pytest.mark.parametrize( ("region", "problem"), [ ("north", "region needs cleaning"), (" West ", "region needs cleaning"), ("SOUTH", "region needs cleaning"), ("Mars", "unknown region"), ],)def test_region_problems(make_row, region, problem): assert validate_row(make_row(region=region)) == [problem]
@pytest.mark.parametrize( "text", ["07/01/2023", "January 7, 2023", " 2023-01-07 "], ids=str.strip)def test_accepted_date_formats(make_row, text): assert validate_row(make_row(order_date=text)) == []
@pytest.mark.parametrize("text", ["2023-13-01", "01-07-2023", "Jan 7, 2023"])def test_bad_dates(make_row, text): assert validate_row(make_row(order_date=text)) == ["bad date"]
@pytest.mark.parametrize("name", [" Air Purifier", "Air Purifier ", "Air Purifier"])def test_product_needs_cleaning(make_row, name): assert validate_row(make_row(product=name)) == ["product needs cleaning"]
@pytest.mark.parametrize("quantity", ["0", "-2", "101", "999"])def test_bad_quantity(make_row, quantity): assert "bad quantity" in validate_row(make_row(quantity=quantity))
def test_bad_price(make_row): assert validate_row(make_row(unit_price="$12.x0")) == ["bad price"]
def test_thousands_separator_is_a_valid_price(make_row): row = make_row(unit_price="$1,299.00", revenue="1169.1") assert validate_row(row) == []
def test_revenue_mismatch(make_row): assert validate_row(make_row(revenue="249.0")) == ["revenue mismatch"]
def test_no_revenue_check_without_a_discount(make_row): assert validate_row(make_row(discount="N/A", revenue="1.0")) == ["missing discount"]
def test_problems_come_in_a_fixed_order(make_row): row = make_row(customer_id="N/A", region="north", quantity="0") assert validate_row(row) == [ "missing customer_id", "region needs cleaning", "bad quantity", "revenue mismatch", ]from pathlib import Path
import pytest
from validate import main, print_report, validate_file
# The course folder holds both salescheck/ and data/.RAW = Path(__file__).resolve().parents[2] / "data" / "sales_raw.csv"
def test_counts_rows_duplicates_and_problems(write_csv, clean_row, make_row): path = write_csv([clean_row, clean_row, make_row(region="north")]) counts = validate_file(path) assert counts == {"rows": 3, "duplicates": 1, "region needs cleaning": 1}
def test_clean_file_has_no_problems(write_csv, clean_row): assert validate_file(write_csv([clean_row])) == {"rows": 1, "duplicates": 0}
def test_values_with_commas_survive_the_file(write_csv, make_row): row = make_row( order_date="January 1, 2023", unit_price="$1,299.00", revenue="1169.1" ) assert validate_file(write_csv([row])) == {"rows": 1, "duplicates": 0}
def test_report_order(capsys): counts = {"rows": 5, "duplicates": 1, "bad date": 2, "missing region": 3} print_report(counts) assert capsys.readouterr().out.splitlines() == [ "rows 5", "duplicates 1", "missing region 3", "bad date 2", ]
def test_main_prints_the_report(write_csv, clean_row, capsys): assert main([str(write_csv([clean_row]))]) == 0 assert capsys.readouterr().out.startswith("rows")
def test_main_rejects_a_missing_file(tmp_path, capsys): with pytest.raises(SystemExit) as excinfo: main([str(tmp_path / "missing.csv")]) assert excinfo.value.code == 2 assert "file not found" in capsys.readouterr().err
@pytest.mark.slowdef test_real_file_matches_the_data_dictionary(): assert validate_file(RAW) == { "rows": 1200, "duplicates": 36, "region needs cleaning": 259, "product needs cleaning": 95, "missing discount": 24, "missing customer_id": 23, "missing channel": 17, "missing region": 17, "bad quantity": 10, "missing unit_price": 10, "revenue mismatch": 10, }Run the fast suite, then everything with coverage and the gate:
cd salescheckpytest -q -m "not slow"pytest -q --cov=validate --cov-report=coverage report --fail-under=95echo "exit code: $?"............................................ [100%]44 passed, 1 deselected in 0.03s............................................. [100%]45 passed in 0.08sName Stmts Miss Branch BrPart Cover Missing---------------------------------------------------------validate.py 71 0 26 0 100%---------------------------------------------------------TOTAL 71 0 26 0 100%exit code: 0Run the validator on the real file:
cd salescheckpython validate.py ../data/sales_raw.csvrows 1,200duplicates 36region needs cleaning 259product needs cleaning 95missing discount 24missing customer_id 23missing channel 17missing region 17bad quantity 10missing unit_price 10revenue mismatch 10The counts match the data dictionary. The 10 revenue mismatches are the 10 rows with a bad quantity: their revenue is the original value, so it no longer equals price × quantity × (1 − discount).
The IDs of the stacked parametrize test show how pytest combines the two lists:
cd salescheckpytest --collect-only -q -k "missing_tokens and region"tests/test_validate_row.py::test_missing_tokens[region-empty]tests/test_validate_row.py::test_missing_tokens[region-n/a]tests/test_validate_row.py::test_missing_tokens[region-dash]
3/45 tests collected (42 deselected) in 0.01sHow it works:
- One rule, one test. Each test name states a rule, and each parametrized list holds the examples of that rule. When a test fails, its name and ID tell you which rule broke on which input.
- Factory fixtures.
make_row(**changes)returns the clean row merged with the changes (clean_row | changesbuilds a new dict, so the fixture’s row stays clean).write_csv(rows)writes any rows totmp_pathwithcsv.DictWriter, which quotes values that contain commas, such as$1,299.00andJanuary 1, 2023;test_values_with_commas_survive_the_filechecks that. Tests state only what differs from a clean row, which keeps them short and readable. - Exact problem lists. Most tests compare the whole list,
== ["bad date"], not justin. That also proves that the rule does not trigger other problems by accident.test_problems_come_in_a_fixed_orderpins the order of several problems at once. - Edge cases.
" 2023-01-07 "and"$1,299.00"are valid inputs that a careless rule would flag. Testing them protects against false alarms, which matter as much as missed problems. - The oracle test. The slow test compares the whole
Counterwith the counts that the data dictionary documents, in one==. A new problem label, or a missing one, also fails it. It found nothing new here, which is the point: when next month’s export has a new problem, this is the test that changes. - Coverage. With branch coverage and the
__main__line excluded, the suite runs every line and both directions of everyif. The gate turns that into a check that CI can enforce.
Alternative: pandas can do the same counts in a few vectorized lines, for example raw["region"].str.strip().str.title().isin(REGIONS). A pandas version is faster on large files; the row-by-row version is easier to test one rule at a time. If you switch, keep the test suite: test_real_file_matches_the_data_dictionary tells you whether the new version gives the same answer. Module 26 cleans this file with pandas.