BEGINNERPROJECTCHAPTER 07

Project: put a legacy function under test and find its bug

Pin what the old code does, ask what must always be true, and let a property find the input you would never have tried

90 MINSOFTWARE TESTING AND QUALITYUPDATED 2026-11-23

You are Jomo. The lab is labs/testing, the service you have used since the start of the module. The function is make_schedule(total, n, y, m, d). It splits total kobo into n monthly instalments starting on the year, month and day you give it, and returns a list of ("YYYY-MM-DD", kobo) pairs. The first instalments carry any extra kobo, and a day after the 28th is capped at 28.

You are not told what is wrong with it. Finding out is the project.

What you do, in order

  1. Read it without running it. Write down what you expect it to return for five inputs, and which inputs you cannot predict from the code.
  2. Characterise it. Pick twenty inputs on purpose, run the function once, and write what it returns into tests that fail if it ever changes. You judge nothing yet. You are making the code safe to touch.
  3. Find the seam. Decide how a test gets hold of the function. Here it is easy, and saying why teaches you what to look for in code where it is not.
  4. State what must always be true. Write invariants over every plan, not examples, and let Hypothesis search.
  5. Shrink, report, fix. Take the smallest failing input, write the bug report, make the smallest fix, and watch which tests change.

Characterise before you judge

You cannot fix what you cannot see, and you cannot see what you have not pinned. A characterisation test says: for this input the code returned this output on this day. Michael Feathers calls the practice getting code under test before you change it, in Working Effectively with Legacy Code. The rule is to write down what the code does, not what you think it should do. If you pin your belief instead, a wrong belief fails the test and you start to “fix” correct behaviour.

Choose the inputs with the edges of the rules in mind, as in the boundary values lesson: a total that divides exactly, one that leaves a remainder of 1 and of 2, a total smaller than the number of instalments, a day at 28, 29, 30 and 31, the longest plan, a plan that ends in December. Add one that is plain nonsense, such as day 0, because the old code accepts it and someone may rely on that. And add one a real customer would send: a plan that starts in the autumn.

Two things follow. First, the pinned outputs include whatever the code gets wrong. You do not read them for rightness yet, but you keep them under review, because step 5 will change one. Second, coverage will look excellent. Twenty well-chosen inputs run every line and every branch of a 24-line function, and the report says 100%. The coverage lesson is about exactly this: coverage says the lines ran, and it says nothing about whether anyone read what they returned.

The seam is the argument list

Feathers’ seam is a place where you can change behaviour without editing the code there. In most legacy code you hunt for one: a database call you cannot run in a test, a clock you cannot set, a global you cannot reset. Martin Fowler’s note on the idea is worth reading when you meet such code.

This function has none of those. It takes numbers and returns a list. Nothing is read from outside and nothing is written. The seam is its signature, and a test calls it like any pure function. That is the best case, and it is rare. Say it out loud in the lab, because the next legacy function you meet will not be this kind, and the skill you need then is the one you are skipping now: finding where to cut.

What must always be true

A pinned example checks one input. An invariant checks every input of a kind. For an instalment plan you can write down, before you look at any output, what any correct schedule must satisfy:

Invariant In words
The parts add up to the whole The amounts sum to total exactly, to the kobo
One per instalment The list has n entries
Nobody is short-changed No amount differs from another by more than 1 kobo
Real dates, one month apart Every date is a real calendar date, and each is the month after the one before, starting at the month you asked for

Hypothesis, from the property-based testing lesson, turns each into a test over plans it generates. When a property fails it also shrinks: it tries simpler and simpler inputs that still fail, and reports the smallest. That is the smallest case you need for a bug report. You do not have to guess which of a million plans to try, which is the whole advantage over writing examples by hand.

Choose the ranges honestly. If you allow only plans of up to 12 instalments, say so in a comment, because you have decided not to test longer ones. A property is as wide as its generator.

Where it goes wrong

Pinning what you believe. You write the expected value from your head, the test fails, and you change the code to match your head. The code was the evidence. Record its output first.

Regenerating the pins. After the fix, one pinned test fails. The quick move is to run the generator again and overwrite them all. That also accepts any other change the fix made. Edit the one row you checked by hand.

A fix that passes your own tests. The smallest change that turns the failing property green may pass only because your generator never reaches the case it does not cover. The break at the end of the lab shows it.

Stopping at the first green. The sum invariant passes at once, and it should: it is a good test. It does not mean the function is right. It means the amounts are right.

LAB Put make_schedule under test, and find what is wrong with it ~90 MIN
YOU NEEDlabs/testing set up as in its README (Python 3.9 or later, `.venv` installed)A terminal in labs/testingHypothesis 6.141.1, installed by requirements.txt

You work from labs/testing with .venv in place. Nothing here starts a server or touches data/. You add one folder, tests/legacy/, and one scratch script.

1. Read it, and guess.

Open checkout/legacy.py and read it top to bottom. Do not run it. On paper, write what you expect for these five calls, and mark any you cannot predict from the code alone:

make_schedule(3000, 3, 2026, 3, 15)
make_schedule(1001, 3, 2026, 3, 15)
make_schedule(1_000_000, 4, 2026, 1, 31)
make_schedule(1000, 0, 2026, 3, 15)
make_schedule(1_000_000, 3, 2026, 3, 0)

Then check the starter suite is green before you add anything:

.venv/bin/pytest -q
The file is 24 lines. Your page holds five guesses and a list of the ones you could not be sure of (the day-31 and day-0 calls are the usual ones). The suite prints 23 passed, 1 skipped, 1 deselected. Nothing in tests/ imports checkout.legacy, which is why nobody noticed anything.

2. Pin twenty inputs.

Create tests/legacy/__init__.py (empty) and the script pin_legacy.py in labs/testing:

"""Run make_schedule on 19 chosen inputs and write what it returns into a test file."""
from checkout.legacy import make_schedule

CASES = [
    (3000, 3, 2026, 3, 15),        # divides exactly
    (1000, 1, 2026, 3, 15),        # one instalment
    (1000, 3, 2026, 3, 15),        # remainder 1
    (1001, 3, 2026, 3, 15),        # remainder 2
    (1002, 3, 2026, 3, 15),        # remainder 0 again
    (2, 3, 2026, 3, 15),           # fewer kobo than instalments
    (0, 3, 2026, 3, 15),           # nothing to pay
    (1_000_000, 4, 2026, 1, 1),    # first of January
    (1_000_000, 4, 2026, 2, 28),   # day 28 stays 28
    (1_000_000, 4, 2026, 2, 29),   # day 29 is capped
    (1_000_000, 4, 2026, 1, 31),   # day 31 is capped
    (1_000_000, 4, 2026, 1, 30),   # day 30 is capped
    (1_000_000, 4, 2026, 9, 5),    # single-digit day, ends in December
    (1_000_000, 12, 2026, 1, 10),  # the longest plan, January to December
    (1_000_000, 6, 2026, 7, 10),   # a plan that ends in December
    (1_000_000, 4, 2026, 10, 31),  # a real customer: October, four instalments
    (1_000_000, 3, 2026, 3, 0),    # garbage in: day zero
    (999_999_999, 7, 2028, 2, 29), # a big total in a leap year
    (1_000_000, 2, 2026, 11, 1),   # November and December
]

lines = [
    "import pytest",
    "",
    "from checkout.legacy import make_schedule",
    "",
    "# Characterisation: each row is what make_schedule returned on the day we pinned it.",
    "# It says what the code does, not what it should do.",
    "PINNED = [",
]
for args in CASES:
    lines.append(f"    ({args!r}, {make_schedule(*args)!r}),")
lines += [
    "]",
    "",
    "",
    '@pytest.mark.parametrize("args, expected", PINNED, ids=["-".join(str(x) for x in a) for a, _ in PINNED])',
    "def test_pinned(args, expected):",
    "    assert make_schedule(*args) == expected",
    "",
    "",
    "def test_zero_instalments_raises():",
    "    with pytest.raises(ZeroDivisionError):",
    "        make_schedule(1000, 0, 2026, 3, 15)",
    "",
]
open("tests/legacy/test_legacy_pinned.py", "w").write("\n".join(lines))
print(len(CASES), "cases written")

Run it, then run the new tests:

.venv/bin/python pin_legacy.py
.venv/bin/pytest tests/legacy -q
19 cases written, then 20 passed: nineteen pinned plans and the zero-instalments test. Open tests/legacy/test_legacy_pinned.py and read each row against the code. Do not judge yet. Notice which rows surprise you, and write their input down. Day 0 comes back as 2026-03-00, and a day of 29, 30 or 31 comes back as 28. Those are pinned too: you do not know if anyone relies on them.

3. Measure what that bought you.

.venv/bin/pytest tests/legacy -q -p no:randomly --cov=checkout.legacy --cov-branch --cov-report=term-missing
Name                 Stmts   Miss Branch BrPart  Cover   Missing
----------------------------------------------------------------
checkout/legacy.py      20      0      8      0   100%

Every statement and every branch ran. You still have not asked whether any answer is right. Write that down: 100% coverage here means twenty inputs reached every line, not that the function is correct.

4. Find the seam, then state what must be true.

Write the seam down in one sentence in your notes: where does a test get hold of this function, and what would you have needed if it read the date from the system clock? Then create tests/legacy/test_legacy_invariants.py with the first invariant only:

from datetime import date

from hypothesis import given, strategies as st

from checkout.legacy import make_schedule

plans = st.tuples(
    st.integers(min_value=0, max_value=1_000_000_000),  # total, kobo
    st.integers(min_value=1, max_value=12),             # instalments
    st.integers(min_value=2020, max_value=2035),        # year
    st.integers(min_value=1, max_value=12),             # month
    st.integers(min_value=1, max_value=31),             # day
)

@given(plans)
def test_instalments_add_up_to_the_total(plan):
    schedule = make_schedule(*plan)
    assert sum(amount for _, amount in schedule) == plan[0]
.venv/bin/pytest tests/legacy/test_legacy_invariants.py -q
1 passed. Hypothesis tried a hundred plans (its default) and the amounts add up on every one. That is finance’s first suspicion, and it is wrong: the amounts are not the problem. Keep the test, it will guard the amounts when someone changes them. Hypothesis writes a .hypothesis/ folder here; it is git-ignored.

5. Add the other three invariants and run them.

Append to tests/legacy/test_legacy_invariants.py:

@given(plans)
def test_one_instalment_each_and_no_amount_is_out_of_line(plan):
    n = plan[1]
    amounts = [amount for _, amount in make_schedule(*plan)]
    assert len(amounts) == n
    assert max(amounts) - min(amounts) <= 1

@given(plans)
def test_dates_are_real_and_one_month_apart(plan):
    _, n, y, m, _ = plan
    dates = [date.fromisoformat(d) for d, _ in make_schedule(*plan)]   # a bad date, or a year that never advances
    months = [d.year * 12 + d.month for d in dates]
    assert months == list(range(y * 12 + m, y * 12 + m + n))
.venv/bin/pytest tests/legacy/test_legacy_invariants.py -q -p no:randomly

1 failed, 2 passed. The count-and-spread test passes. The last one fails, and Hypothesis reports a shrunk example, trimmed here:

E       assert [24252, 24241] == [24252, 24253]
E       Falsifying example: test_dates_are_real_and_one_month_apart(
E           plan=(0, 2, 2020, 12, 1),
E       )

The numbers are year times 12 plus month. The second instalment is eleven months before the first. Hypothesis started from a random plan and reduced it to a total of 0, two instalments, December 2020, day 1. It also prints a line pointing at line 17 of checkout/legacy.py.

6. Shrink it yourself, and read the cause.

Reproduce the smallest case by hand, then try to make it smaller:

.venv/bin/python -c "from checkout.legacy import make_schedule as m; print(m(2, 2, 2020, 12, 1))"
.venv/bin/python -c "from checkout.legacy import make_schedule as m; print(m(2, 2, 2020, 11, 1))"

Now read lines 14 to 18 of checkout/legacy.py, the lines Hypothesis pointed at, and say in one sentence what the code does when the month goes past 12. Then work out which plans in your twenty pinned cases it affects.

The first call prints [('2020-12-01', 1), ('2020-01-01', 1)]: the second instalment is in January of the same year, eleven months earlier. The second call prints [('2020-11-01', 1), ('2020-12-01', 1)], which is fine. So the smallest failing plan starts in December and has two instalments, and nothing shorter fails. When the month passes 12 the code subtracts 12 from it and leaves the year alone. Exactly one of your nineteen pinned rows crosses a year end: the October plan, whose fourth date reads 2026-01-28. You pinned it on step 2 and it looked unremarkable.

7. Write the bug report.

Save this in legacy-bug-report.md in labs/testing, filled in with your own words. It goes to Hassan and into the ticket:

Title:     <one line: what is wrong, when>
Impact:    <who is affected, and since when, in plain words>
Smallest:  make_schedule(...) returns ..., it should return ...
Cause:     <one or two sentences, and the line>
Not the problem: <what you checked and ruled out>
Fix:       <what you will change, and what you will not>
Evidence:  <the test that fails, and the pinned test that will change>
A report short enough to read in a minute. “Not the problem” says the amounts add up and are spread within one kobo, which the first two invariants show. “Impact” names every plan that starts late enough in the year for a date to pass December, and says that the amounts finance sees are correct but the dates are not. Do not write more than the evidence supports: you know the year does not advance, and you have not looked at what the billing system does with a date in the past.

8. Fix it, then see which tests change.

Replace the month and year arithmetic with whole-month arithmetic. In checkout/legacy.py, replace lines 14 to 17 (mm = m + i down to mm = mm - 12) with:

        months = (m - 1) + i
        yy = y + months // 12
        mm = months % 12 + 1

Run everything you wrote, then the whole suite:

.venv/bin/pytest tests/legacy -q -p no:randomly
.venv/bin/pytest -q
The invariants pass: 3 passed in the invariants file. In the pinned file exactly one test fails, test_pinned[1000000-4-2026-10-31], with At index 3 diff: ('2027-01-28', 250000) != ('2026-01-28', 250000). The other 19 pinned tests still pass: your fix changed what you meant it to change and nothing else. The whole-suite run shows that one failure and the starter tests green.

Check by hand that January 2027 is right for an October start with four instalments. Then change that one row in tests/legacy/test_legacy_pinned.py: edit '2026-01-28' to '2027-01-28' in the row for (1_000_000, 4, 2026, 10, 31). Add a comment above it that says why. Do not run pin_legacy.py again.

.venv/bin/pytest -q
46 passed, 1 skipped, 1 deselected (the 23 starter tests, your 20 pinned tests and 3 invariants). Your commit has the fix, the one changed pin and the invariants together, and the message says why the pin changed. Delete pin_legacy.py or leave it out of the commit: it was scaffolding.

Break it differently. Put the original checkout/legacy.py back (revert your fix), and make the smallest fix you can think of: add yy = yy + 1 on the line after mm = mm - 12. Run the tests. Then in test_legacy_invariants.py change the generator’s instalments from max_value=12 to max_value=36 and run the invariants again. The first version passes everything you wrote. The second one fails with ValueError: month must be in 1..12 and a shrunk plan of (0, 14, 2020, 12, 1): the code subtracts 12 once, so a plan more than a year long reaches month 13 or higher. Put the proper fix back and run the wider property: it passes. A fix is only as good as the widest input you tested it on.

READING
  1. BOOK
    Working Effectively with Legacy Code Michael Feathers, 2004

    The source of the method this project follows: get the code under test before you change it, and pin what it does, not what you think it should do. Read the two chapters named; the rest is a catalogue of dependency-breaking techniques to dip into when you meet code with no easy seam. Read: the chapters on seams and on characterisation tests; the publisher page has the table of contents.

  2. POST
    Legacy Seam Martin Fowler, 2024

    A short note that defines a seam (a place to change behaviour without editing there), names the enabling point, and works through a price calculation with a TypeScript example. Read all of it; it is the clearest account of what step 4 asks you to say aloud.

  3. DOC
    Hypothesis documentation

    The reference for the library that finds and shrinks the failing plan in steps 4 to 6. Read the quickstart and the page on strategies; skip the sections on stateful testing and the Django extras for now.

  4. DOC
    Coverage.py documentation

    Explains the report you read in step 3 and what its percentages count. Read the quick start and the branch coverage page, so you can say what 100% on legacy.py does and does not tell you.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: The shape of a suite: pyramid, trophy and what fits your system →