Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

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 in scratch/lab13 on the test files you name, as python -m pytest -v would 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 in broken, 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 in scratch/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.

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.

Exercise L13.1 (LO-13.1, ★, about 10 minutes)

From the report above, give:

  1. r1: how many tests pytest collected, as a number.

  2. r2: the name of the test that failed, as a string.

  3. r3: the value the function returned in that test, and r4: the line of test_speed.py that failed, as numbers.

  4. 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.

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 raises ValueError, with match set 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.

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:

  1. 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.

  2. 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, match the start of the message, so that a different ValueError doesn’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 "".

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:

  1. Save [2.4, 0.0, 12.0], and check the file’s exact text, newlines included, with path.read_text(encoding="utf-8").

  2. Save twice to the same path, and check that the second save replaced the first.

  3. Check that read_rain reads back the total of what save_rain saved.

  4. Write a file that has a blank line yourself, with path.write_text(...), and check that read_rain skips it.

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.

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)

  1. Before you write the function, write its tests in test_comfort.py: one parametrized test of classify(temp), imported from comfort, with a case on each side of each of the three boundaries, at least six cases in all.

  2. Run the cell after it, which runs your tests against a comfort.py whose classify raises NotImplementedError, because it isn’t written yet. Every test should fail.

  3. Then write classify in comfort.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.

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.

Exercise L13.7 (LO-13.3, ★★, about 15 minutes)

  1. In test_stats.py, write a test that captures the bug: it should fail on this stats.py with an AssertionError, and pass once the bug is fixed. Add a second case where the value falls, such as from 80 to 60, which is −25%.

  2. Run the check after the cell, which runs your tests on the buggy version.

  3. Then fix percent_change in the cell after that, which saves stats.py again, and run the last check, which runs your tests on your fix.

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.

Exercise L13.9 (LO-13.4, ★, about 5 minutes)

Answer each question with a letter, as a string.

  1. w1: The tests pass on your computer, but the run on GitHub fails in Run the tests with ModuleNotFoundError: No module named 'dice'. The likeliest cause: A. pytest isn’t installed on the runner. B. dice.py was never committed. C. The runner has the wrong version of Python.

  2. 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.

  3. w3: When does a workflow with on: [push] run? A. Once a day. B. After every push, to any branch. C. Only after a push to main.

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 parametrize for many cases, tmp_path for 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.