Meet Thistlewick Pantry
Thistlewick Pantry is an invented online grocer. It has a small web shop where customers fill a basket, choose a delivery slot and pay, and a Python service behind it that works out delivery charges, keeps orders and talks to the warehouse. The company and its people are invented. The numbers are not: each one was produced by running the code shown, with Python 3.14.2, and the seeds used for random choices are stated next to them.
Two people carry the story. Ishaan writes the service. Meera joined this month as the first person at the company whose whole job is testing. Over eight chapters they will grow a set of tests for the shop, from one small function to a test that drives a browser. Along the way the chapters ask one question again and again: what did this test actually show?
A function and three tests
The shop is about to import its customers' old orders from a previous system. Some of those orders were made on 29 February 2000, so the importer must decide whether a date such as 29 February in a given year is real. Ishaan writes the rule from memory: a year is a leap year when it divides by four, except for years that divide by one hundred.
def is_leap(year):
return year % 4 == 0 and year % 100 != 0
tests = [("2024 is a leap year", 2024, True),
("2023 is not a leap year", 2023, False),
("1900 is not a leap year", 1900, False)]
for name, year, expected in tests:
print(name, "->", "pass" if is_leap(year) == expected else "FAIL")
# 2024 is a leap year -> pass
# 2023 is not a leap year -> pass
# 1900 is not a leap year -> pass
All three pass. Ishaan chose them with care: an ordinary leap year, an ordinary year, and a century that is not a leap year, which is the case people forget. A reviewer glancing at these tests would see the right three names and move on, and the function would ship.
The function is wrong. The next sections show how wrong, how that can be found, and why three good-looking examples could not find it.
What the three tests showed
A test runs the code with chosen inputs and compares the result with an expected value. When it passes, it shows exactly one thing: for those inputs, the result equals that expected value. It says nothing about any other input. The set of inputs a test uses is a sample of everything the function could be given, and a passing test is a report about the sample.
For a function of a whole number, the full set is large. Years from 1 to 9999 are 9,999 inputs, and real functions take pairs and lists and text, where the set cannot be counted. Nobody tests all of it. A test suite is always a sample, which means the question that matters is how the sample was chosen, and how likely it is to contain an input that the code gets wrong.
Three passing tests therefore support a narrow claim: the function is right for 2024, 2023 and 1900. They do not support the broad claim that the function is right. Treating the narrow claim as the broad one is a very common mistake, and one reason it is so common is that a green result feels the same in both cases.
An independent answer to compare with
To find out how wrong the function is, you need something to compare it with that does not share its mistake. In this case Python itself provides one: the standard library has calendar.isleap, written and tested by other people. A source of correct answers that is independent of the code under test is called an oracle.
import calendar
bad = [y for y in range(1, 10000) if is_leap(y) != calendar.isleap(y)]
print("years from 1 to 9999 where the function and the oracle disagree:", len(bad))
print("the first five:", bad[:5], "and the last two:", bad[-2:])
print("every one is a multiple of 400:", all(y % 400 == 0 for y in bad))
# years from 1 to 9999 where the function and the oracle disagree: 24
# the first five: [400, 800, 1200, 1600, 2000] and the last two: [9200, 9600]
# every one is a multiple of 400: True
The function is wrong for 24 years out of 9,999. They are the multiples of 400: 400, 800, 1200, 1600, 2000, and so on up to 9600. A year such as 2000 divides by one hundred, so Ishaan's rule says it is not a leap year; the real rule has a second exception to the exception, and years that divide by 400 are leap years after all.
Notice what had to be true for this check to work. A trusted second answer had to exist. Often it does not. For a delivery charge, a discount, a stock count or a report, nobody has written a library function that gives the right number; the only description of right is the requirement, in words, and the person writing the test has to turn it into expected values by hand. That difficulty is called the oracle problem, and it recurs in every chapter. Where no oracle exists, the tests rely on cases whose answers a person has worked out.
How often a random sample finds it
Suppose nobody had thought of the century case, and Ishaan had simply tried years at random. How many would it take? The program below draws a sample of years from 1 to 9999 and checks whether any year in it exposes the bug. It repeats that 1,000 times for each sample size, with random.seed(7) set before each size.
import random
def trials(size, count=1000, seed=7):
random.seed(seed)
found = 0
for _ in range(count):
sample = random.sample(range(1, 10000), size)
if any(is_leap(y) != calendar.isleap(y) for y in sample):
found += 1
return found
for size in (5, 20, 100, 500):
print("sample of", size, "random years: bug found in", trials(size), "of 1000 trials")
# sample of 5 random years: bug found in 17 of 1000 trials
# sample of 20 random years: bug found in 44 of 1000 trials
# sample of 100 random years: bug found in 193 of 1000 trials
# sample of 500 random years: bug found in 693 of 1000 trials
A sample of 5 random years finds the bug in 17 trials out of 1,000. A sample of 20 finds it in 44. Even 100 random years miss it in four trials out of five (it is found in 193), and 500 years still miss it in about three out of ten (693 found). The reason is arithmetic: only 24 of the 9,999 years are bad, so each random year has a chance of about 0.24 percent of being one, and the chance that at least one appears grows slowly with the sample.
Counts from random draws vary from one seed to the next, so it helps to compare them with what the arithmetic predicts. random.sample never repeats a year within one sample, so the chance that a sample of a given size holds at least one of the 24 bad years is 1 minus the number of ways to pick that many years from the 9,975 good ones, divided by the number of ways to pick them from all 9,999. Multiplied by 1,000 trials that is the expected count, and the usual spread of such a count is the square root of 1,000 times the chance times one minus the chance.
from math import comb, sqrt
for size in (5, 20, 100, 500):
chance = 1 - comb(9999 - 24, size) / comb(9999, size)
spread = sqrt(1000 * chance * (1 - chance))
print("sample of", size, "years: expected", round(1000 * chance, 1), "of 1000 trials, usual spread", round(spread, 1))
# sample of 5 years: expected 11.9 of 1000 trials, usual spread 3.4
# sample of 20 years: expected 47.0 of 1000 trials, usual spread 6.7
# sample of 100 years: expected 214.6 of 1000 trials, usual spread 13.0
# sample of 500 years: expected 708.5 of 1000 trials, usual spread 14.4
The observed counts, 17, 44, 193 and 693, sit near the expected ones, 11.9, 47.0, 214.6 and 708.5. The largest gap is 1.7 usual spreads (the sample of 100), and the 44 for 20 years is less than half a spread below 47.0.
The numbers say something uncomfortable. Writing more examples of the same kind does not reliably find a bug that lives in a narrow part of the input space. A suite of 500 random years still misses it about three times in ten. What finds the bug reliably is knowing where to look.
Choosing cases from the rule
The rule for leap years has structure, and the structure tells you where the cases are. In words: a year divisible by 4 is a leap year; but if it is divisible by 100 it is not; but if it is also divisible by 400 it is. That statement divides all years into four groups, and each group has a different right answer.
| Group | Example | Expected |
|---|---|---|
| not divisible by 4 | 2023 | not a leap year |
| divisible by 4, not by 100 | 2024 | leap year |
| divisible by 100, not by 400 | 1900 | not a leap year |
| divisible by 400 | 2000 | leap year |
Choosing one year from each group, and taking the cases from the written rule rather than from the code, gives four tests where Ishaan had three. The fourth is the one that matters.
four = [("not divisible by 4", 2023, False),
("divisible by 4, not by 100", 2024, True),
("divisible by 100, not by 400", 1900, False),
("divisible by 400", 2000, True)]
for group, year, expected in four:
print(group, year, "->", "pass" if is_leap(year) == expected else "FAIL")
# not divisible by 4 2023 -> pass
# divisible by 4, not by 100 2024 -> pass
# divisible by 100, not by 400 1900 -> pass
# divisible by 400 2000 -> FAIL
One of the four fails, and it is 2000, the first case that Ishaan's three examples left out. Now the corrected function, and a comparison with the oracle over every year from 1 to 9999, together with two other plausible-looking mistakes.
def is_leap_fixed(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def is_leap_no_century(year):
return year % 4 == 0
def is_leap_wrong_exception(year):
return year % 4 == 0 and year % 400 != 0
for f in (is_leap, is_leap_fixed, is_leap_no_century, is_leap_wrong_exception):
four_ok = sum(f(y) == want for _, y, want in four)
disagree = sum(f(y) != calendar.isleap(y) for y in range(1, 10000))
print(f.__name__, "- four group cases passed:", four_ok, "- years that disagree with the oracle:", disagree)
# is_leap - four group cases passed: 3 - years that disagree with the oracle: 24
# is_leap_fixed - four group cases passed: 4 - years that disagree with the oracle: 0
# is_leap_no_century - four group cases passed: 3 - years that disagree with the oracle: 75
# is_leap_wrong_exception - four group cases passed: 2 - years that disagree with the oracle: 99
The corrected function passes all four cases and agrees with the oracle for every year. The version that forgets the century rule entirely fails one case (1900) and is wrong for 75 years. The version that treats every multiple of 400 as an exception, the century rule turned the wrong way round, fails two cases (1900 and 2000) and is wrong for 99 years. Four cases, one from each group, separated three wrong versions from the right one. Twenty random years usually did not: they found even the first wrong version in only 44 of 1,000 trials.
That is the idea chapter 3 develops under the names equivalence classes and boundaries: cut the inputs into groups where the code should behave alike, and test each group, and the edges between groups. Here it is enough to see the effect. Four chosen cases did what hundreds of random ones often did not, because the choice used knowledge of the rule.
A test that borrows the code's rule
There is a tempting shortcut when the expected value is hard to work out: let the test calculate it. If Ishaan writes expected = year % 4 == 0 and year % 100 != 0 inside the test, the test needs no list of examples and can run over any range of years.
def test_by_rule(year):
expected = year % 4 == 0 and year % 100 != 0
return is_leap(year) == expected
failures = [y for y in range(1, 10000) if not test_by_rule(y)]
print("years where this test fails:", len(failures))
# years where this test fails: 0
It never fails, for any of the 9,999 years, including the 24 where the function is wrong. The expected value came from the same rule as the code, so the test can only confirm that the code does what the code does. This is a common way for a test to end up agreeing with the bug. The expected value must come from somewhere the code did not: the requirement, a worked example done by hand, an independent implementation, or a reference list.
A related habit has the same effect. If you run the code, look at the output, and paste the output into the test as the expected value, the test records what the code did, not what it should do. That is sometimes useful, as a guard against future change, and it is honest to call such a test a snapshot. It is not evidence of correctness.
What the bug did in the shop
The importer needs to know how many days a month has, so it can reject a date such as 31 June.
def days_in_month(year, month):
if month == 2:
return 29 if is_leap(year) else 28
return 30 if month in (4, 6, 9, 11) else 31
def is_valid_date(year, month, day):
return 1 <= month <= 12 and 1 <= day <= days_in_month(year, month)
import datetime
print("importer accepts 29 February 2000:", is_valid_date(2000, 2, 29))
print("the standard library accepts it:", datetime.date(2000, 2, 29).isoformat())
# importer accepts 29 February 2000: False
# the standard library accepts it: 2000-02-29
The importer rejects a date that exists. Every order from 29 February 2000 would be refused or sent to a list of problem records. The bug is real and the damage is real, but notice its shape: it is rare. Years that are multiples of 400 do not come up often, and a team could run the shop for years before anyone met one. Rare bugs of this shape are the reason a passing run is weak evidence. They do not appear in casual use, so the casual tests, written from casual use, do not include them.
A routine for the first tests of a new function
Meera and Ishaan write down what they would do next time, before running anything.
- Write the rule in words, from the requirement, not from the code.
- Split the inputs into groups where the rule says the answer changes kind. Count them.
- For each group choose at least one example, and for each edge between groups choose a case on each side.
- Work out the expected value of each case from the requirement. If an oracle exists, use it to check the whole range as well.
- Run the cases against the code. When one fails, decide whether the code or the case is wrong before changing either.
- When a bug is found, keep the failing case as a permanent test.
- Ask what kind of mistake would still pass these cases, and add a case for it.
Step 7 is the one beginners skip. After four tests pass, the useful question is not "are we done" but "what could be wrong that these four would not notice?". In the leap rule the answer is not "nothing". One example per group is the minimum, and a plausible wrong version slips past it: a rule written with 200 where 400 belongs.
def is_leap_200(year):
return year % 4 == 0 and (year % 100 != 0 or year % 200 == 0)
print("passes the four group cases:", all(is_leap_200(y) == want for _, y, want in four))
wrong = [y for y in range(1, 10000) if is_leap_200(y) != calendar.isleap(y)]
print("years where it is wrong:", len(wrong), "- the first five:", wrong[:5])
print("two more years from the group 'divisible by 100, not by 400':", [(y, is_leap_200(y), calendar.isleap(y)) for y in (2100, 2200)])
# passes the four group cases: True
# years where it is wrong: 25 - the first five: [200, 600, 1000, 1400, 1800]
# two more years from the group 'divisible by 100, not by 400': [(2100, False, False), (2200, True, False)]
The year 2200 divides by 200 but not by 400, and it is where this version goes wrong; 2100 does not show it. A second example from the group "divisible by 100, not by 400" catches the version, and nothing in the four cases could have told Meera to choose it. That is why step 7 is a question asked after the cases pass: it has no fixed answer, and for a function with rules that interact there is almost always something.
Mistakes that recur
- Reading "all tests pass" as "the code is correct". The result describes the sample.
- Choosing examples from what the code already does well, so every test passes on the first run and none was able to fail.
- Taking expected values from the code under test, or from a copy of its logic, so the test agrees with the bug.
- Counting tests instead of counting kinds of case. Twenty tests that all use years like 2023 add little over one.
- Believing that many random inputs replace chosen ones. In this chapter 500 random years missed the bug in about three runs out of ten.
- Fixing the code and not keeping the failing case, so the same bug can return unnoticed.