Objectives: LO-13.1, LO-13.2, LO-13.3, LO-13.4
Prerequisites: the Module 13 reading and
Lab 12
Time: about 2 hours
In this lab you read pytest’s report of a failed test, write tests for a weather module, and then find out whether your tests are good enough: each check runs them against versions of the module with a bug planted in them, and your tests must catch every one. Then you write tests before the code, capture a bug in a test before fixing it, and write a workflow that would run your tests on GitHub.
You write each test file in a notebook cell that starts with %%writefile and a file name.
Running the cell saves the rest of the cell to that file, in scratch/lab13, instead of running
it. Each exercise has its own test file.
Setup¶
Run the next cell first. It writes the module you will test, weather.py, into
scratch/lab13, and defines three helpers:
show_pytest(*names)runs pytest inscratch/lab13on the test files you name, aspython -m pytest -vwould in a terminal, and prints its report.check_tests(test_file, module_file, good, broken)is what the checks use. It copies your test file into a new, empty folder with one version of the module at a time: the correct one,good, and then each version inbroken, which has a bug planted in it. Your tests pass the check when they pass on the correct version and fail on every broken one.load(name)imports a module you wrote inscratch/lab13, afresh each time you call it.
The broken versions are in the cell, so you can read what each one gets wrong. Each check also says which bug your tests missed.
import importlib.util
import re
import subprocess
import sys
import tempfile
from pathlib import Path
import pytest
import yaml
print("Python", sys.version.split()[0])
print("pytest", pytest.__version__)
print("PyYAML", yaml.__version__)
LAB = Path("scratch") / "lab13"
LAB.mkdir(parents=True, exist_ok=True)
WEATHER = '''"""Weather helpers for Lab 13."""
def c_to_f(celsius):
"""Return a Celsius temperature in degrees Fahrenheit."""
return celsius * 9 / 5 + 32
def mean(values):
"""Return the mean of a list of numbers; raise ValueError for an empty list."""
if not values:
raise ValueError("mean of an empty list")
return sum(values) / len(values)
def parse_reading(line):
"""Return (station, date, temperature) from a line such as 'Harbor,2026-11-02,8.5'."""
fields = line.strip().split(",")
if len(fields) != 3:
raise ValueError(f"expected 3 fields, found {len(fields)}: {line!r}")
station, date, text = fields
return station, date, float(text)
def save_rain(path, values):
"""Write daily rain readings in mm to a text file, one per line, replacing the file."""
with open(path, "w", encoding="utf-8") as file:
for value in values:
file.write(f"{value}\\n")
def read_rain(path):
"""Return the total of a file of daily rain readings in mm; skip blank lines."""
total = 0
with open(path, encoding="utf-8") as file:
for line in file:
if line.strip():
total = total + float(line)
return total
def station_means(lines):
"""Return a dictionary of each station's mean temperature, from lines of readings."""
temperatures = {}
for line in lines:
station, date, temperature = parse_reading(line)
temperatures.setdefault(station, []).append(temperature)
means = {}
for station, values in temperatures.items():
means[station] = mean(values)
return means
def warmest(lines):
"""Return the station with the highest mean temperature, from lines of readings."""
means = station_means(lines)
return max(means, key=means.get)
'''
(LAB / "weather.py").write_text(WEATHER, encoding="utf-8")
def planted(old, new):
"""Return a copy of weather.py with one piece of code replaced, to plant a bug."""
assert old in WEATHER, old
return WEATHER.replace(old, new)
BROKEN_BASICS = {
"multiplies by 5 / 9 instead of 9 / 5 (0 °C still gives 32)":
planted("celsius * 9 / 5 + 32", "celsius * 5 / 9 + 32"),
"divides with // (0, 100, and -40 °C still give the right answers)":
planted("celsius * 9 / 5 + 32", "celsius * 9 // 5 + 32"),
"returns 0 for an empty list":
planted('raise ValueError("mean of an empty list")', "return 0"),
"has no check for an empty list, so it divides by zero":
planted(' if not values:\n raise ValueError("mean of an empty list")\n', ""),
"divides with // (a list whose mean is a whole number still gives the right answer)":
planted("return sum(values) / len(values)", "return sum(values) // len(values)"),
}
BROKEN_PARSE = {
"returns the temperature as a string":
planted("return station, date, float(text)", "return station, date, text"),
"returns the date first and the station second":
planted("return station, date, float(text)", "return date, station, float(text)"),
"rejects negative temperatures, because it checks the text with isdigit":
planted(" return station, date, float(text)",
' if not text.replace(".", "").isdigit():\n'
' raise ValueError(f"not a number: {text!r}")\n'
" return station, date, float(text)"),
"has no check of the number of fields (unpacking raises another ValueError)":
planted(' if len(fields) != 3:\n'
' raise ValueError(f"expected 3 fields, found {len(fields)}: {line!r}")\n',
""),
"ignores any fields after the third":
planted("if len(fields) != 3:", "if len(fields) < 3:")
.replace("station, date, text = fields", "station, date, text = fields[:3]"),
}
BROKEN_RAIN = {
"writes to rain.txt in the current folder instead of to path":
planted('open(path, "w", encoding="utf-8")', 'open("rain.txt", "w", encoding="utf-8")'),
"adds to the end of the file instead of replacing it":
planted('with open(path, "w", encoding="utf-8")', 'with open(path, "a", encoding="utf-8")'),
"leaves out the newline after the last reading":
planted(' for value in values:\n file.write(f"{value}\\n")',
' file.write("\\n".join(str(value) for value in values))'),
"stops with ValueError at a blank line":
planted(" if line.strip():\n total = total + float(line)",
" total = total + float(line)"),
}
WARMEST = " means = station_means(lines)\n return max(means, key=means.get)"
BROKEN_MEANS = {
"gives each station's total instead of its mean":
planted("means[station] = mean(values)", "means[station] = sum(values)"),
"gives the station with the lowest mean":
planted("return max(means, key=means.get)", "return min(means, key=means.get)"),
"gives the station with the highest single reading":
planted(WARMEST, " readings = [parse_reading(line) for line in lines]\n"
" return max(readings, key=lambda reading: reading[2])[0]"),
"gives the station with the highest total":
planted(WARMEST, " totals = {}\n"
" for line in lines:\n"
" station, date, temperature = parse_reading(line)\n"
" totals[station] = totals.get(station, 0) + temperature\n"
" return max(totals, key=totals.get)"),
}
def run_tests(files):
"""Run pytest in a new, empty folder holding files, a dictionary of names and texts."""
with tempfile.TemporaryDirectory() as folder:
for name, text in files.items():
Path(folder, name).write_text(text, encoding="utf-8")
result = subprocess.run(
[sys.executable, "-B", "-m", "pytest", "-q", "-p", "no:cacheprovider"],
cwd=folder, capture_output=True, text=True,
)
return result.returncode, result.stdout + result.stderr
def counts(output):
"""Return the numbers of passed and failed tests in pytest's last line."""
last = output.strip().splitlines()[-1] if output.strip() else ""
passed = re.search(r"(\d+) passed", last)
failed = re.search(r"(\d+) failed", last)
return int(passed.group(1)) if passed else 0, int(failed.group(1)) if failed else 0
def check_tests(test_file, module_file, good, broken, hint="Add a test that fails on it."):
"""Check that the tests in test_file pass on good and fail on every version in broken."""
tests = (LAB / test_file).read_text(encoding="utf-8")
status, output = run_tests({test_file: tests, module_file: good})
if status != 0:
print(output)
assert status != 5, f"pytest found no tests in {test_file}: name each one test_..."
assert status == 0, (
f"Your tests fail on the correct {module_file}. Read pytest's report above: is the "
"test wrong, or did you compare a calculated float with ==?"
)
for what, source in broken.items():
status, output = run_tests({test_file: tests, module_file: source})
assert status == 1, (
f"Your tests pass on a {module_file} that {what}. {hint}"
)
print(f"{test_file}: passes on the correct {module_file}, and fails on all {len(broken)} "
"broken versions.")
def show_pytest(*names):
"""Run pytest -v in LAB on the named test files, and print its report."""
result = subprocess.run(
[sys.executable, "-B", "-m", "pytest", "-v", "-p", "no:cacheprovider", *names],
cwd=LAB, capture_output=True, text=True,
)
print(result.stdout + result.stderr, end="")
def load(name):
"""Import LAB/name.py afresh, and return the module."""
spec = importlib.util.spec_from_file_location(name, LAB / f"{name}.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
(LAB / "speed.py").write_text('''"""Wind speeds."""
def kmh_to_ms(kmh):
"""Return a speed in kilometers per hour in meters per second."""
return kmh / 3.6
def is_gale(kmh):
"""Return True for a wind of 62 km/h or more."""
return kmh >= 62
''', encoding="utf-8")
(LAB / "test_speed.py").write_text('''import pytest
from speed import is_gale, kmh_to_ms
def test_kmh_to_ms_of_zero():
assert kmh_to_ms(0) == 0
def test_kmh_to_ms_of_a_breeze():
assert kmh_to_ms(18) == pytest.approx(5)
def test_kmh_to_ms_of_a_strong_wind():
assert kmh_to_ms(54) == pytest.approx(16)
def test_gale_starts_at_62():
assert is_gale(62)
assert not is_gale(61.9)
''', encoding="utf-8")
print("Ready.")1. Reading pytest’s report¶
Setup also wrote a small module, speed.py, and its tests, test_speed.py. Run the next cell
to run them.
show_pytest("test_speed.py")Exercise L13.1 (LO-13.1, ★, about 10 minutes)¶
From the report above, give:
r1: how many tests pytest collected, as a number.r2: the name of the test that failed, as a string.r3: the value the function returned in that test, andr4: the line oftest_speed.pythat failed, as numbers.r5: which is wrong,"code"or"test"? Work out 54 km/h in m/s yourself: there are 1,000 m in a kilometer and 3,600 s in an hour.
r1 = 0
r2 = "..."
r3 = 0
r4 = 0
r5 = "..."assert r1 == 4, "r1: the line 'collected ... items' gives the count."
assert r2 == "test_kmh_to_ms_of_a_strong_wind", "r2: the FAILED line names the test after ::."
assert r3 == pytest.approx(15), "r3: the E line shows the returned value on the left of ==."
assert r4 == 15, "r4: the line after the E lines gives test_speed.py and the line number."
assert r5 == "test", (
"r5: 54 km/h is 54,000 m in 3,600 s, which is 15 m/s, so kmh_to_ms is right and the test "
"expects the wrong value."
)
print("passed")2. Typical cases, edge cases, and errors¶
Exercise L13.2 (LO-13.1, ★★, about 20 minutes)¶
Write tests for c_to_f and mean from weather.py in the next cell, which saves them as
test_basics.py. Include:
for
c_to_f, at least two typical cases, one of which doesn’t give a whole number of degrees Fahrenheit;for
mean, a typical case whose mean isn’t a whole number, an edge case or two, and a test that the empty list raisesValueError, withmatchset to a word or two of its message.
Compare calculated floats with pytest.approx. Run the cell, then the one after it to see
pytest’s report, and fix your tests until they pass; then run the check. The check runs your
tests against five broken versions of weather.py, listed in BROKEN_BASICS in the setup cell,
and tells you which one they miss.
%%writefile scratch/lab13/test_basics.py
import pytest
from weather import c_to_f, mean
# Write your tests here.show_pytest("test_basics.py")check_tests("test_basics.py", "weather.py", WEATHER, BROKEN_BASICS)3. Many cases with parametrize¶
parse_reading(line) turns a line of a readings file, such as "Harbor,2026-11-02,8.5", into
a tuple, ("Harbor", "2026-11-02", 8.5). A line without exactly three fields raises
ValueError with a message that starts expected 3 fields, and a temperature that isn’t a
number raises the ValueError that float raises.
Exercise L13.3 (LO-13.2, ★★, about 15 minutes)¶
Write tests for parse_reading in test_parse.py:
One parametrized test for lines it should accept, with at least three cases: a typical line, a negative temperature, and a line that ends with a newline (
"\n"), as lines read from a file do.One parametrized test for lines it should refuse, with at least three cases: too few fields, too many fields, and a temperature that isn’t a number. Use
pytest.raises(ValueError). For the field counts,matchthe start of the message, so that a differentValueErrordoesn’t pass the test.
Hint
A parametrized test for errors can take the line and the pattern as its two parameters, as in ("Harbor,2026-11-02", "expected 3 fields"). For the temperature that isn’t a number, look at the message float gives, or use a pattern that every ValueError message matches, such as "".
%%writefile scratch/lab13/test_parse.py
import pytest
from weather import parse_reading
# Write your tests here.show_pytest("test_parse.py")tests = (LAB / "test_parse.py").read_text(encoding="utf-8")
assert tests.count("@pytest.mark.parametrize") >= 2, "Write two parametrized tests."
check_tests("test_parse.py", "weather.py", WEATHER, BROKEN_PARSE)4. Files with tmp_path¶
save_rain(path, values) writes a list of daily rain readings in millimeters to a text file,
one per line, and read_rain(path) reads such a file back and returns the total, skipping
blank lines.
Exercise L13.4 (LO-13.2, ★★, about 15 minutes)¶
Write tests in test_rain.py, each with its own file in tmp_path:
Save
[2.4, 0.0, 12.0], and check the file’s exact text, newlines included, withpath.read_text(encoding="utf-8").Save twice to the same path, and check that the second save replaced the first.
Check that
read_rainreads back the total of whatsave_rainsaved.Write a file that has a blank line yourself, with
path.write_text(...), and check thatread_rainskips it.
%%writefile scratch/lab13/test_rain.py
import pytest
from weather import read_rain, save_rain
# Write your tests here.show_pytest("test_rain.py")tests = (LAB / "test_rain.py").read_text(encoding="utf-8")
assert "tmp_path" in tests, "Give each test its own folder with the tmp_path fixture."
check_tests("test_rain.py", "weather.py", WEATHER, BROKEN_RAIN)5. A fixture of your own¶
station_means(lines) returns a dictionary of each station’s mean temperature, from lines of
readings such as "Harbor,2026-11-02,8.5", and warmest(lines) returns the station whose mean
is highest.
Exercise L13.5 (LO-13.2, ★, about 10 minutes)¶
In test_means.py, write a fixture named readings that returns a list of at least four lines
for at least two stations. Then write two tests that ask for it: one that checks
station_means, and one that checks warmest. Choose readings where the warmest station by
mean isn’t the one with the single highest reading, or the one with the highest total.
%%writefile scratch/lab13/test_means.py
import pytest
from weather import station_means, warmest
# Write the fixture and your tests here.show_pytest("test_means.py")tests = (LAB / "test_means.py").read_text(encoding="utf-8")
assert "@pytest.fixture" in tests and "def readings(" in tests, (
"Write a fixture named readings, marked @pytest.fixture."
)
assert tests.count("(readings)") >= 2, "Write two tests that ask for readings as a parameter."
check_tests("test_means.py", "weather.py", WEATHER, BROKEN_MEANS, hint=(
"Add a test that fails on it, with readings where the station with the highest mean has "
"neither the highest single reading nor the highest total."
))6. Test first¶
A thermostat’s display labels each temperature: "freezing" below 0 °C, "cold" from 0 °C to
below 10 °C, "mild" from 10 °C to below 20 °C, and "warm" from 20 °C.
Exercise L13.6 (LO-13.3, ★★, about 15 minutes)¶
Before you write the function, write its tests in
test_comfort.py: one parametrized test ofclassify(temp), imported fromcomfort, with a case on each side of each of the three boundaries, at least six cases in all.Run the cell after it, which runs your tests against a
comfort.pywhoseclassifyraisesNotImplementedError, because it isn’t written yet. Every test should fail.Then write
classifyincomfort.py, two cells down, and run the check, which runs your tests against your function and against four versions of it with a mistake at a boundary.
%%writefile scratch/lab13/test_comfort.py
import pytest
from comfort import classify
# Write your tests here.STUB = '''def classify(temp):
raise NotImplementedError("classify isn't written yet")
'''
tests = (LAB / "test_comfort.py").read_text(encoding="utf-8")
status, output = run_tests({"test_comfort.py": tests, "comfort.py": STUB})
print(output.strip().splitlines()[-1])
passed, failed = counts(output)
assert passed == 0 and failed >= 6, "Write at least six cases, and see every one of them fail."
print("passed: every test fails before the code exists")%%writefile scratch/lab13/comfort.py
"""Labels for a thermostat's display."""
def classify(temp):
"""Return freezing, cold, mild, or warm for a temperature in degrees Celsius."""
...comfort = load("comfort")
for temp, label in [(-12.5, "freezing"), (-0.1, "freezing"), (0, "cold"), (9.9, "cold"),
(10, "mild"), (19.99, "mild"), (20, "warm"), (31.5, "warm")]:
assert comfort.classify(temp) == label, f"classify({temp}) should be {label!r}."
CODE = (LAB / "comfort.py").read_text(encoding="utf-8")
GOOD_COMFORT = '''def classify(temp):
if temp < 0:
return "freezing"
if temp < 10:
return "cold"
if temp < 20:
return "mild"
return "warm"
'''
BROKEN_COMFORT = {
"calls 0 °C freezing": GOOD_COMFORT.replace("temp < 0", "temp <= 0"),
"calls 10 °C cold": GOOD_COMFORT.replace("temp < 10", "temp <= 10"),
"calls 20 °C mild": GOOD_COMFORT.replace("temp < 20", "temp <= 20"),
"calls every temperature below 10 °C cold":
GOOD_COMFORT.replace("temp < 0", "temp < -273.15"),
}
check_tests("test_comfort.py", "comfort.py", CODE, BROKEN_COMFORT)7. Capture a bug in a test before you fix it¶
Setup didn’t write this module yet. Run the next cell: it writes stats.py, whose
percent_change(old, new) returns how much a value changed, as a percentage of the old value.
A user reports a bug: a price that went from 50 to 75 rose by 50%, but
percent_change(50, 75) gives 33.3.
BUGGY_STATS = '''"""Statistics for the weather station's reports."""
def percent_change(old, new):
"""Return the change from old to new as a percentage of old, which must not be 0."""
return (new - old) / new * 100
'''
(LAB / "stats.py").write_text(BUGGY_STATS, encoding="utf-8")
print(load("stats").percent_change(50, 75))Exercise L13.7 (LO-13.3, ★★, about 15 minutes)¶
In
test_stats.py, write a test that captures the bug: it should fail on thisstats.pywith anAssertionError, and pass once the bug is fixed. Add a second case where the value falls, such as from 80 to 60, which is −25%.Run the check after the cell, which runs your tests on the buggy version.
Then fix
percent_changein the cell after that, which savesstats.pyagain, and run the last check, which runs your tests on your fix.
%%writefile scratch/lab13/test_stats.py
import pytest
from stats import percent_change
# Write your tests here.tests = (LAB / "test_stats.py").read_text(encoding="utf-8")
status, output = run_tests({"test_stats.py": tests, "stats.py": BUGGY_STATS})
print(output)
passed, failed = counts(output)
assert status == 1 and failed >= 1, "Your tests should fail on the buggy percent_change."
assert "AssertionError" in output, "Fail with an assert, not with another exception."
print("passed: your tests catch the bug")%%writefile scratch/lab13/stats.py
"""Statistics for the weather station's reports."""
def percent_change(old, new):
"""Return the change from old to new as a percentage of old, which must not be 0."""
return (new - old) / new * 100stats = load("stats")
for old, new, change in [(50, 75, 50), (80, 60, -25), (4, 5, 25), (7, 7, 0)]:
assert stats.percent_change(old, new) == pytest.approx(change), (
f"percent_change({old}, {new}) should be {change}."
)
tests = (LAB / "test_stats.py").read_text(encoding="utf-8")
fixed = (LAB / "stats.py").read_text(encoding="utf-8")
status, output = run_tests({"test_stats.py": tests, "stats.py": fixed})
print(output)
assert status == 0, "Your tests should pass on the fixed percent_change."
print("passed: the bug is fixed, and your tests will catch it if it comes back")8. A workflow for GitHub Actions¶
Exercise L13.8 (LO-13.4, ★★, about 15 minutes)¶
Write a workflow in tests.yml that runs a project’s tests on every push, as in the reading.
It should have one job on ubuntu-latest, whose steps check out the repository, set up
Python 3.12, install the packages in requirements.txt, and run pytest, in that order. You
can’t run it here, so the check reads the file with PyYAML, a YAML reader for Python that came
with JupyterLab.
%%writefile scratch/lab13/tests.yml
# Write the workflow here, in place of this line.workflow = yaml.safe_load((LAB / "tests.yml").read_text(encoding="utf-8"))
assert isinstance(workflow, dict), "tests.yml should hold keys such as name, on, and jobs."
# PyYAML follows an older version of YAML that reads the key on as True. GitHub reads it as on.
events = workflow.get("on", workflow.get(True))
assert events is not None, "Say when the workflow runs, with on."
assert "push" in events, "Run the workflow on every push: on: [push]."
jobs = workflow.get("jobs")
assert isinstance(jobs, dict) and len(jobs) == 1, "Give jobs exactly one job, such as test."
job = list(jobs.values())[0]
assert job.get("runs-on") == "ubuntu-latest", "Run the job on ubuntu-latest, with runs-on."
steps = job.get("steps")
assert isinstance(steps, list) and len(steps) >= 4, "Give the job a list of at least four steps."
uses = [str(step.get("uses", "")) for step in steps]
runs = [str(step.get("run", "")) for step in steps]
assert uses[0].startswith("actions/checkout@"), "Check out the repository in the first step."
python = [n for n, name in enumerate(uses) if name.startswith("actions/setup-python@")]
assert python, "Set up Python with actions/setup-python."
version = (steps[python[0]].get("with") or {}).get("python-version")
assert not isinstance(version, float), (
f'python-version is the number {version}: write "3.12", in quotes, so that YAML reads it as '
"text."
)
assert version == "3.12", f'python-version is {version!r}: set it to "3.12".'
install = [n for n, command in enumerate(runs) if "pip install -r requirements.txt" in command]
test = [n for n, command in enumerate(runs) if "pytest" in command]
assert install, "Install the requirements: python -m pip install -r requirements.txt."
assert test, "Run the tests: python -m pytest."
assert python[0] < install[0] < test[0], "Set up Python, then install, then run the tests."
print("passed")Exercise L13.9 (LO-13.4, ★, about 5 minutes)¶
Answer each question with a letter, as a string.
w1: The tests pass on your computer, but the run on GitHub fails in Run the tests withModuleNotFoundError: No module named 'dice'. The likeliest cause: A. pytest isn’t installed on the runner. B.dice.pywas never committed. C. The runner has the wrong version of Python.w2: The Install the requirements step fails. What happens to Run the tests? A. It runs anyway. B. It’s skipped. C. It runs with the packages of the last run that passed.w3: When does a workflow withon: [push]run? A. Once a day. B. After every push, to any branch. C. Only after a push tomain.
w1 = "..."
w2 = "..."
w3 = "..."assert w1 == "B", (
"w1: without pytest the error would name pytest; the runner has only what was committed."
)
assert w2 == "B", "w2: a failed step stops the job, and the steps after it are skipped."
assert w3 == "B", "w3: push means every push, to any branch, unless the workflow says otherwise."
print("passed")Summary¶
In this lab you:
read pytest’s report of a failure, and decided that the test, not the code, was wrong;
wrote tests of typical cases, edge cases, and errors that caught planted bugs, some of which only a well-chosen case could catch;
used
parametrizefor many cases,tmp_pathfor code that writes files, and a fixture of your own for shared data;wrote tests before the code, saw them fail, and then made them pass;
captured a bug in a failing test before fixing it; and
wrote a workflow that runs a project’s tests on GitHub on every push.
Next, the Module 13 practice has more exercises, in the terminal, with your own test files.