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.

These exercises practice what the Module 13 reading explained. They aren’t graded. Work in a terminal, in a folder m13 inside py101, as in the reading: save each module and its test file there, and run python -m pytest with your environment’s Python. Write your answer or your prediction first, then run the tests to check it. The answers are in the collapsed blocks; open one only after you have an answer of your own.

Worked example: cases for a function that can refuse its input

A quiz app stores scores as text, such as "12/20". This function, saved as scores.py, turns one into a percentage, and refuses text that isn’t a valid score:

"""Scores on quizzes."""


def score_percent(text):
    """Return a score such as "12/20" as a percentage; raise ValueError for a bad score."""
    parts = text.split("/")
    if len(parts) != 2:
        raise ValueError(f"expected a score such as 12/20, got {text!r}")
    points, total = int(parts[0]), int(parts[1])
    if total <= 0:
        raise ValueError(f"the total must be positive: {text!r}")
    if not 0 <= points <= total:
        raise ValueError(f"points must be from 0 to the total: {text!r}")
    return points / total * 100

To choose the cases, go through the docstring and the code, and write down what each part promises:

The good cases share one test, and so do the errors, because each group checks the same thing in the same way. match uses the start of each message, so a test fails if the wrong raise runs:

import pytest

from scores import score_percent


@pytest.mark.parametrize(
    "text, percent",
    [
        ("12/20", 60),
        ("1/3", 33.333),
        ("0/20", 0),
        ("20/20", 100),
    ],
)
def test_score_percent(text, percent):
    assert score_percent(text) == pytest.approx(percent, abs=0.001)


@pytest.mark.parametrize(
    "text, message",
    [
        ("12", "expected a score"),
        ("12/20/30", "expected a score"),
        ("5/0", "total must be positive"),
        ("21/20", "points must be from 0"),
        ("-1/20", "points must be from 0"),
    ],
)
def test_bad_score_raises(text, message):
    with pytest.raises(ValueError, match=message):
        score_percent(text)

Saved as test_scores.py, the run ends:

============================== 9 passed in 0.02s ===============================

abs=0.001 suits every case: the expected values are written to three decimal places, and the rest are whole numbers.

Exercise 13.1 (LO-13.1, ★, about 10 minutes)

Save this as test_predict.py, next to scores.py. Before you run it, predict the last line of pytest’s report, and say which test passes without testing anything.

import pytest

from scores import score_percent


def test_half():
    assert score_percent("10/20") == 50


def test_eleven_of_twenty():
    assert score_percent("11/20") == 55


def check_full():
    assert score_percent("20/20") == 100


def test_nothing_scored():
    score_percent("0/5") == 0


def test_zero_total():
    with pytest.raises(ValueError):
        score_percent("5/0")
Hint

Go through the tests one at a time, and ask three questions of each: does pytest collect it, does it check anything, and is it comparing a calculated float with ==?

Answer
python -m pytest test_predict.py
test_predict.py .F..                                                     [100%]

=================================== FAILURES ===================================
____________________________ test_eleven_of_twenty _____________________________

    def test_eleven_of_twenty():
>       assert score_percent("11/20") == 55
E       AssertionError: assert 55.00000000000001 == 55
E        +  where 55.00000000000001 = score_percent('11/20')

test_predict.py:11: AssertionError
=========================== short test summary info ============================
FAILED test_predict.py::test_eleven_of_twenty - AssertionError: assert 55.000...
========================= 1 failed, 3 passed in 0.03s ==========================

pytest collects four tests, not five: check_full doesn’t start with test, so it never runs. test_eleven_of_twenty fails because 11 / 20 * 100 is 55.00000000000001 as a float; test_half passes only because 10 / 20 * 100 happens to come out exact. Both should use pytest.approx. test_nothing_scored passes without testing anything: it has no assert, so it throws the comparison away. test_zero_total is a real test, and passes.

Exercise 13.2 (LO-13.1, ★★, about 10 minutes)

A science museum charges by age in whole years: under 5 is free, 5 to 17 is 6.50,18to64is6.50, 18 to 64 is12.00, and 65 and over is $7.00. A negative age is a mistake. Save this as tickets.py:

"""Ticket prices at the science museum."""


def ticket_price(age):
    """Return the price of a ticket in dollars for a visitor's age in whole years."""
    if age < 0:
        raise ValueError(f"age can't be negative: {age}")
    if age < 5:
        return 0
    if age < 18:
        return 6.50
    if age < 65:
        return 12.00
    return 7.00

Finish these tests, in test_tickets.py: add a case on each side of each boundary, and write the error test.

import pytest

from tickets import ticket_price


@pytest.mark.parametrize(
    "age, price",
    [
        (2, 0),
        (30, 12.00),
        # Add the cases at each boundary here.
    ],
)
def test_ticket_price(age, price):
    assert ticket_price(age) == price


def test_negative_age_raises():
    ...
Answer
import pytest

from tickets import ticket_price


@pytest.mark.parametrize(
    "age, price",
    [
        (2, 0),
        (30, 12.00),
        (0, 0),
        (4, 0),
        (5, 6.50),
        (17, 6.50),
        (18, 12.00),
        (64, 12.00),
        (65, 7.00),
        (90, 7.00),
    ],
)
def test_ticket_price(age, price):
    assert ticket_price(age) == price


def test_negative_age_raises():
    with pytest.raises(ValueError, match="negative"):
        ticket_price(-1)
============================== 11 passed in 0.01s ===============================

Ages are whole numbers, so the boundaries fall between 4 and 5, 17 and 18, and 64 and 65, and each pair catches a < written as <=. Age 0 is the lowest valid age. The prices are returned as written, not calculated, and 6.5, 12.0, and 7.0 are stored exactly as floats, so == is safe here.

Fixtures and files

Exercise 13.3 (LO-13.2, ★★, about 15 minutes)

Module 11’s Exercise 11.7 wrote save_scores(path, scores) and load_scores(path), which save a game’s high scores, a dictionary such as {1: [120, 95], 2: [80]}, as JSON, and load them back. Save its answer as highscores.py, with import json and from pathlib import Path at the top. Then write three tests in test_highscores.py, each with its own tmp_path:

  1. Loading gives back the dictionary that was saved.

  2. Loading a file that doesn’t exist gives {}.

  3. The saved file is JSON with the levels as strings: read it with json.loads.

Then check that the first test can fail: in load_scores, return saved without converting the keys, run the tests, and put the conversion back.

Answer
import json

from highscores import load_scores, save_scores


def test_load_gives_back_what_was_saved(tmp_path):
    path = tmp_path / "scores.json"
    scores = {1: [120, 95], 2: [80]}
    save_scores(path, scores)
    assert load_scores(path) == scores


def test_load_of_missing_file_is_empty(tmp_path):
    assert load_scores(tmp_path / "no-such-file.json") == {}


def test_saved_file_is_json(tmp_path):
    path = tmp_path / "scores.json"
    save_scores(path, {1: [120, 95]})
    assert json.loads(path.read_text(encoding="utf-8")) == {"1": [120, 95]}

All three pass. Without the conversion, the first fails, and pytest shows how the two dictionaries differ:

>       assert load_scores(path) == scores
E       AssertionError: assert {'1': [120, 95], '2': [80]} == {1: [120, 95], 2: [80]}
E         
E         Left contains 2 more items:
E         {'1': [120, 95], '2': [80]}
E         Right contains 2 more items:
E         {1: [120, 95], 2: [80]}
E         Use -v to get more diff

The keys look alike in print, but '1' and 1 are different keys, so the two dictionaries share none. The second test uses a path in tmp_path that nothing ever wrote, so the file is sure not to exist; a name in your own folder might, one day. The third test pins down the file’s format, which matters once other programs read the file too.

Exercise 13.4 (LO-13.2, ★★, about 10 minutes)

A fixture can ask for another fixture, such as tmp_path, the same way a test does: by naming it as a parameter. Module 11’s Exercise 11.4 wrote coldest(path), which returns the row of a CSV file with the lowest temp_c, as a dictionary with the temperature as a float, and the first such row if two tie. Save its answer as coldness.py, with import csv at the top.

In test_coldness.py, write a fixture temps_file(tmp_path) that writes Exercise 11.4’s four rows to a CSV file in tmp_path and returns its path. Then write two tests that use it: one for the row that coldest returns, and one that checks the temperature is a float. Add a third test, without the fixture, for a file that has only a header row, for which coldest returns None. Which of your tests fails if < becomes <= in coldest?

Answer
import pytest

from coldness import coldest


@pytest.fixture
def temps_file(tmp_path):
    """A CSV file of four readings, two of which tie for the coldest."""
    path = tmp_path / "temps.csv"
    path.write_text(
        "station,date,temp_c\n"
        "Harbor,2026-11-02,4.5\n"
        "Hilltop,2026-11-02,-1.5\n"
        "Harbor,2026-11-03,-0.5\n"
        "Hilltop,2026-11-03,-1.5\n",
        encoding="utf-8",
    )
    return path


def test_coldest_gives_the_first_of_a_tie(temps_file):
    assert coldest(temps_file) == {"station": "Hilltop", "date": "2026-11-02", "temp_c": -1.5}


def test_coldest_temperature_is_a_float(temps_file):
    assert isinstance(coldest(temps_file)["temp_c"], float)


def test_coldest_of_a_file_without_readings_is_none(tmp_path):
    path = tmp_path / "empty.csv"
    path.write_text("station,date,temp_c\n", encoding="utf-8")
    assert coldest(path) is None

All three pass. With <=, test_coldest_gives_the_first_of_a_tie fails, because coldest then returns the second Hilltop row, from November 3. Without the conversion to float, both tests that use the fixture fail. Each test gets its own tmp_path, and so its own copy of the file.

Testing first, and testing bugs

Exercise 13.5 (LO-13.3, ★★, about 15 minutes)

A timetable shows durations in hours and minutes: 45 minutes is "45 min", 60 is "1 h", 90 is "1 h 30 min", and 0 is "0 min". A negative duration is a mistake. Write the tests for format_duration(minutes) first, in test_durations.py, importing it from durations, and run them to see them fail. Then write durations.py, and run the tests until they pass.

Hint

The boundaries are at whole hours: test 59, 60, and 61 minutes. minutes // 60 gives the hours, and minutes % 60 the minutes left over.

Answer
import pytest

from durations import format_duration


@pytest.mark.parametrize(
    "minutes, text",
    [
        (0, "0 min"),
        (45, "45 min"),
        (59, "59 min"),
        (60, "1 h"),
        (61, "1 h 1 min"),
        (90, "1 h 30 min"),
        (125, "2 h 5 min"),
    ],
)
def test_format_duration(minutes, text):
    assert format_duration(minutes) == text


def test_negative_duration_raises():
    with pytest.raises(ValueError, match="negative"):
        format_duration(-5)

Before durations.py exists, the run stops while collecting, with ModuleNotFoundError: No module named 'durations'. Then:

"""Durations for a timetable."""


def format_duration(minutes):
    """Return a whole number of minutes as hours and minutes, such as 1 h 30 min."""
    if minutes < 0:
        raise ValueError(f"a duration can't be negative: {minutes}")
    hours = minutes // 60
    rest = minutes % 60
    if hours == 0:
        return f"{rest} min"
    if rest == 0:
        return f"{hours} h"
    return f"{hours} h {rest} min"
============================== 8 passed in 0.03s ===============================

Writing the tests first settles the questions the description left open, such as whether 60 is "1 h" or "1 h 0 min" and whether 125 is "2 h 5 min", before any code depends on the answer.

Exercise 13.6 (LO-13.3, ★★, about 10 minutes)

Module 12’s Exercise 12.8 fixed capitalize_words(text), which stopped with IndexError on text with two spaces in a row, but the fix came with no test. Save the version with the bug as words.py:

"""Text helpers."""


def capitalize_words(text):
    """Return text with the first letter of each word in capitals."""
    words = text.split(" ")
    result = []
    for word in words:
        result.append(word[0].upper() + word[1:])
    return " ".join(result)

Write one parametrized test, in test_words.py, that captures the bug: a typical case that passes, and the two smallest inputs that fail. Run it, and check that it fails for the right reason. Then fix the function, as Module 12 did, and run the test again.

Answer
import pytest

from words import capitalize_words


@pytest.mark.parametrize(
    "text, expected",
    [
        ("rain later today", "Rain Later Today"),
        ("west  by evening", "West  By Evening"),
        ("", ""),
    ],
)
def test_capitalize_words(text, expected):
    assert capitalize_words(text) == expected
=========================== short test summary info ============================
FAILED test_words.py::test_capitalize_words[west  by evening-West  By Evening]
FAILED test_words.py::test_capitalize_words[-] - IndexError: string index out...
========================= 2 failed, 1 passed in 0.08s ==========================

Both failures are the IndexError from the bug report, which is the right reason. (A string makes its own ID, so the empty string gives the odd-looking [-].) With word[:1].upper() in place of word[0].upper(), all three pass. The typical case matters too: it shows that the fix didn’t break the text the function already handled.

Continuous integration

Exercise 13.7 (LO-13.4, ★★, about 10 minutes)

This workflow has four mistakes. Find each one, say what would go wrong on GitHub, and fix it:

name: "Tests"

on: [push]

jobs:
  test:
    steps:
      - name: "Set up Python"
        uses: actions/setup-python@v7
        with:
          python-version: 3.10
      - name: "Run the tests"
        run: python -m pytest
      - name: "Install the requirements"
        run: python -m pip install -r requirements.txt
Answer
  1. The job has no runs-on, so it doesn’t say which kind of runner to start.

  2. Nothing checks out the repository, so the runner has none of your files: no tests, and no requirements.txt.

  3. 3.10 without quotes is the number 3.1 to YAML, so setup-python looks for Python 3.1 instead of 3.10.

  4. The tests run before the requirements are installed, so they run without the packages in requirements.txt.

name: "Tests"

on: [push]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - name: "Check out the repository"
        uses: actions/checkout@v7
      - name: "Set up Python"
        uses: actions/setup-python@v7
        with:
          python-version: "3.10"
      - name: "Install the requirements"
        run: python -m pip install -r requirements.txt
      - name: "Run the tests"
        run: python -m pytest

The course uses Python 3.12; “3.10” is kept here to show the quotes at work.

Exercise 13.8 (LO-13.1, LO-13.4, ★★, about 20 minutes)

Your Project 1 game has a check script, check_<game>.py, that tests its rule functions with assert. Turn it into a pytest test file, test_<game>.py, with one test function for each thing it checks and parametrize wherever several checks differ only in their values. Run it with python -m pytest. Then add requirements.txt and the reading’s workflow to the game’s repository, commit, push, and find the run on the Actions tab. Last, add the run’s status to your README in a sentence, so a visitor knows the game is tested.

Answer

Answers differ with each game. Check yours against these points:

  • python -m pytest collects every test you meant to write: count them in the collected line.

  • Each test’s name says what it checks, and no test holds more than one idea.

  • The run on GitHub has a green check mark, and expanding Run the tests shows the same number of tests as on your computer.

  • To prove the workflow can fail, make a branch (Module 10), break one rule function on it, and push the branch with git push -u origin and the branch’s name. Watch its run fail, then switch back to main and delete the branch without merging it, with git branch -D and its name: -D deletes a branch that was never merged, which -d refuses to do.

Keep check_<game>.py only if your README tells readers to run it; otherwise delete it, so the project has one set of tests.