Part 03 / Stage 1
Testing and code quality
Goal: Write code the customer can trust after you leave: tested against their messy data, safe to re-run, and clean enough to review. Time: ~3 hours · Needs: Python 3.14+, the course venv (pytest is installed)
What you will learn
- pytest: assertions, fixtures, parametrised tests
- Testing messy real-world inputs from actual customer data
- Testing failure paths: exceptions, timeouts, bad responses
- Idempotency: designing and testing jobs that are safe to re-run
- Linting, formatting and type checks
- Code review in a customer repository
Topics in this part
Practice
Work in the course venv. Check each answer by running it; compare with solutions/ only after trying.
Exercise 1: Parametrise the status parser
Write parse_status(text) that maps Acme's raw status values (Delivered, DELIVERED, delivered, in transit, Delayed…) to one of delivered | in_transit | delayed, raising ValueError on anything else. Test it with @pytest.mark.parametrize over at least six raw values from the export, plus one garbage case with pytest.raises. Run the tests from the script the way the lesson's example does.
Show the solution to Exercise 1
# Exercise 1: status parser, tested over the export's real values
import pathlib, re, subprocess, sys, tempfile, textwrap
code = textwrap.dedent('''
import pytest
def parse_status(text):
norm = text.strip().lower().replace(" ", "_")
if norm in {"delivered", "in_transit", "delayed"}:
return norm
raise ValueError(f"unknown status: {text!r}")
@pytest.mark.parametrize("raw, expected", [
("Delivered", "delivered"), ("DELIVERED", "delivered"), ("delivered", "delivered"),
("in transit", "in_transit"), ("Delayed", "delayed"), (" delivered ", "delivered"),
])
def test_statuses(raw, expected):
assert parse_status(raw) == expected
def test_rejects_garbage():
with pytest.raises(ValueError):
parse_status("lost in a lake")
''')
folder = pathlib.Path(tempfile.mkdtemp())
(folder / "test_status.py").write_text(code)
r = subprocess.run([sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", str(folder)],
capture_output=True, text=True)
print(re.sub(r" in \d+\.\d+s", "", r.stdout.strip().splitlines()[-1]))
Exercise 2: A fixture for the export
Write a pytest fixture export_path(tmp_path) that writes fdelab.SHIPMENTS_CSV to a file and returns the path, and a test that reads it with csv.DictReader and asserts it has 8 rows and that exactly one row has an empty weight.
Show the solution to Exercise 2
# Exercise 2: a fixture that provides the export file
import pathlib, re, subprocess, sys, tempfile, textwrap
code = textwrap.dedent('''
import csv
import pytest
from fdelab import SHIPMENTS_CSV
@pytest.fixture
def export_path(tmp_path):
path = tmp_path / "shipments.csv"
path.write_text(SHIPMENTS_CSV, encoding="utf-8")
return path
def test_export_shape(export_path):
with export_path.open(encoding="utf-8") as f:
rows = list(csv.DictReader(f))
assert len(rows) == 8
assert sum(1 for r in rows if not r["weight"].strip()) == 1
''')
folder = pathlib.Path(tempfile.mkdtemp())
(folder / "test_export.py").write_text(code)
env_tools = str(pathlib.Path(__file__).resolve().parents[3] / "tools")
import os
env = dict(os.environ, PYTHONPATH=env_tools)
r = subprocess.run([sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", str(folder)],
capture_output=True, text=True, env=env)
print(re.sub(r" in \d+\.\d+s", "", r.stdout.strip().splitlines()[-1]))
Exercise 3: Prove a load is idempotent
Write load(records, table) as a keyed upsert and a test test_run_twice_equals_run_once that loads a 3-record batch twice and asserts the result equals a single run. Add a second test proving an append-only version fails the same assertion.
Show the solution to Exercise 3
# Exercise 3: run-twice == run-once, and the append version fails it
import pathlib, re, subprocess, sys, tempfile, textwrap
code = textwrap.dedent('''
def load(records, table):
for r in records:
table[r["id"]] = r
return table
BATCH = [{"id": "S-1001"}, {"id": "S-1002"}, {"id": "S-1003"}]
def test_run_twice_equals_run_once():
once = load(BATCH, {})
twice = load(BATCH, load(BATCH, {}))
assert once == twice and len(twice) == 3
def test_append_only_is_not_idempotent():
appended = []
for _ in range(2):
appended.extend(BATCH)
assert len(appended) != len(BATCH) # duplicates after a re-run
''')
folder = pathlib.Path(tempfile.mkdtemp())
(folder / "test_idempotent.py").write_text(code)
r = subprocess.run([sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", str(folder)],
capture_output=True, text=True)
print(re.sub(r" in \d+\.\d+s", "", r.stdout.strip().splitlines()[-1]))
Exercise 4: Date parser with failure paths
Write parse_date(text) accepting 2025-03-01, 03/02/2025 (US order, month first) and 2025/03/05, returning ISO YYYY-MM-DD, raising ValueError otherwise. Tests: the three good formats, and pytest.raises for yesterday.
Show the solution to Exercise 4
# Exercise 4: a date parser for the export's three formats, failure path tested
import pathlib, re, subprocess, sys, tempfile, textwrap
code = textwrap.dedent('''
from datetime import datetime
import pytest
FORMATS = ["%Y-%m-%d", "%m/%d/%Y", "%Y/%m/%d"]
def parse_date(text):
for fmt in FORMATS:
try:
return datetime.strptime(text.strip(), fmt).date().isoformat()
except ValueError:
continue
raise ValueError(f"unrecognised date: {text!r}")
@pytest.mark.parametrize("raw, expected", [
("2025-03-01", "2025-03-01"),
("03/02/2025", "2025-03-02"),
("2025/03/05", "2025-03-05"),
])
def test_formats(raw, expected):
assert parse_date(raw) == expected
def test_rejects_garbage():
with pytest.raises(ValueError):
parse_date("yesterday")
''')
folder = pathlib.Path(tempfile.mkdtemp())
(folder / "test_dates.py").write_text(code)
r = subprocess.run([sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", str(folder)],
capture_output=True, text=True)
print(re.sub(r" in \d+\.\d+s", "", r.stdout.strip().splitlines()[-1]))
Mini-project: Parser test suite
Put the three parsers (weight from the lesson, status and date from the exercises) in one module and write a test suite covering every messy case in the real export — run it and show the pass summary.
A solution is in solutions/mini_parser_test_suite.py.
Stretch: run the tests, a linter and a type checker in CI on every push (GitHub Actions: pytest, ruff check, mypy).
Common mistakes
| Mistake | Why it hurts | Fix |
|---|---|---|
| Testing only invented, clean inputs | Production data breaks the parser in week one | Harvest test cases from the customer's real data |
| No failure-path tests | The first 503 reveals untested error handling | pytest.raises, mock timeouts and bad responses |
| Append-only loads | Every retry duplicates rows | Keyed upserts; test run-twice == run-once |
| Style debates in review | Burns goodwill and days | Formatter + linter + type checker in CI |
| Giant pull requests | Unreviewable; stalls for weeks | One concern per PR |
Quick recap
- pytest tests are plain asserts; fixtures handle setup, and parametrize turns a table of cases into individual tests.
- Test cases come from the customer's data, not from imagination.
- Failure paths get tests too, with
pytest.raisesand simulated timeouts and errors. - Idempotent means running twice gives the same result — and the test is exactly that: run it twice and compare.
- Automate style — formatting, linting, types — so review time goes to logic.
- Small PRs with context are how outsiders earn commit rights.
Checklist
- I wrote a parametrised test covering five messy inputs.
- I asserted an exception with
pytest.raises. - I can explain idempotency in one sentence and test it in three lines.
- I know which three tools remove style from code review.
- I ran both examples and my output matched the lesson.
Read more: pytest: how to use fixtures · pytest: parametrize