本书暂未推出简体中文版。现有版本:English。
High School Computer Science · 10–12 年级
1Specifications, Assertions and Tests
Sam writes a function that tells whether a year is a leap year, the kind of year with a 29th of February. She tries it on (leap), on (not leap) and on (leap): three right answers. She shares it with her class. A week later a friend who is building a calendar of the twentieth century finds that her function gives a 29th of February, a day that never existed.
Was the function wrong? It depends on what it promised. This chapter is about writing down that promise, the specification, so that “right” and “wrong” have a meaning; about making the program check the promise while it runs, with assertions; and about choosing the inputs that are most likely to break a function, the tests, and running them automatically every time the code changes.
You already know
A function has a name, parameters and a body; return sends a value back to the caller (Book 1, grade 7). A program can fail in three ways: it does not start, it stops with an error message, or it gives a wrong answer; a trace table follows its variables step by step (Book 1, grade 7). A comparison such as x < 10 has a Boolean value, True or False, and and, or, not combine such values (Book 1, grade 6).
1.1 What a function promises
A function is written once and called many times, often by people who never read its body. They need to know two things: what they must give it, and what they get back.
Definition 1.1 (Specification)
The specification of a function states, without describing how the function works, what it computes: its name and parameters, the values its parameters may take, and the result it returns or the change it makes for each of those values.
A specification is usually split into two parts: what the caller must guarantee, and what the function guarantees in return.
Definition 1.2 (Precondition, postcondition)
A precondition of a function is a condition on its arguments that the caller must make true before the call. A postcondition is a condition on the result (and on the arguments) that the function makes true when it returns, provided the precondition held.
The two form a contract. If the caller keeps its side, the function must keep its own; if the caller breaks the precondition, the function promises nothing at all.
In Python the specification lives inside the function, as its first line of text.
Definition 1.3 (Docstring)
A docstring (documentation string) is a string written as the first statement of a function’s body. Python keeps it with the function, and help(f) prints it. In this book a docstring states the function’s specification.
The calendar in use almost everywhere today was instituted in . Its rule is that a year is a leap year when it is divisible by , except the century years (, , , …), which are leap years only when they are divisible by . Here is Sam’s function, with a docstring that says so.
def leap_year(year):
"""Return True if year is a leap year of the Gregorian calendar.
Precondition: year is a whole number, 1583 or later.
Postcondition: the result is True exactly when year is divisible
by 4 and not by 100, or divisible by 400.
"""
return year % 4 == 0
The precondition ( or later) is there because the rule means nothing before the calendar existed. The postcondition says exactly which years must give True. With it, the run below is not a matter of opinion.
$ python leap_demo.py
2024 True
2023 False
2000 True
1900 True
The body tests only the first part of the rule. The specification has turned “my friend’s calendar looks odd” into a precise statement: for , the postcondition requires False and the function returns True. That is what a bug is: a call whose precondition holds and whose postcondition fails.
Method 1.4 (Writing a specification)
- Name each parameter and say what kind of value it holds (a whole number, a list of numbers, a string).
- Write the precondition: every restriction on the arguments (“not empty”, “from 1 to 12”).
- Write the postcondition in terms of the arguments: what the result is, not how it is found.
- Check it on two or three examples worked by hand, including one at an edge.
Example 1.5 (The specification of a maximum)
For a function largest(t): the precondition is “t is a non-empty list of numbers”; the postcondition is “the result is an element of t, and no element of t is larger”. The empty list is excluded because it has no largest element: the specification forces the author to decide this case instead of leaving it to chance.
The corrected version tests the exceptions first, from the rarest case to the commonest.
if year % 400 == 0:
return True
if year % 100 == 0:
return False
return year % 4 == 0
1.2 Assertions
A specification written in a docstring is read by people. An assertion is read by the machine.
Definition 1.6 (Assertion)
An assertion is a statement assert condition, message that evaluates the condition. If it is true, the program goes on; if it is false, the program stops with an AssertionError that carries the message.
An assertion at the top of a function checks its precondition: a caller who breaks the contract is stopped at once, with a message that names the problem, instead of receiving a strange result much later.
def average(t):
"""Return the mean of the numbers in the list t.
Precondition: t is a non-empty list of numbers.
"""
assert len(t) > 0, "average of an empty list"
total = 0
for x in t:
total = total + x
return total / len(t)
print(average([12, 15, 9]))
print(average([]))
$ python average.py
12.0
Traceback (most recent call last):
File "average.py", line 14, in <module>
print(average([]))
^^^^^^^^^^^
File "average.py", line 6, in average
assert len(t) > 0, "average of an empty list"
AssertionError: average of an empty list
[exit status 1]
Without the assertion, average([]) would stop too, but with ZeroDivisionError on the line total / len(t): a message about division, not about the caller’s mistake.
Remark 1.7 (What assertions are for)
An assertion catches the programmer’s mistakes: a call that breaks a contract, a value that “cannot” happen. It is not the way to handle a user who types a wrong value: a program answers a user with a message and asks again. One reason is that assertions can be switched off.
Python removes every assert statement when it is started with the option -O, so a program must never rely on an assertion to do its work.
Assertions often guard an expression that would crash: “the list is not empty, and its first element is 3”. This works because Python evaluates such a condition from left to right and stops as soon as the answer is known.
Definition 1.8 (Short-circuit evaluation)
Python evaluates a and b by evaluating a first; if a is false, the result is false and b is not evaluated at all. It evaluates a or b by evaluating a first; if a is true, the result is true and b is not evaluated. This is short-circuit evaluation.
The function loud below prints a line each time it is evaluated, so the output shows which operands Python actually computes.
def loud(value):
print(" evaluating loud(" + str(value) + ")")
return value
print("False and loud(True):")
print(False and loud(True))
print("True and loud(False):")
print(True and loud(False))
print("True or loud(False):")
print(True or loud(False))
$ python short_circuit.py
False and loud(True):
False
True and loud(False):
evaluating loud(False)
False
True or loud(False):
True
loud runs only in the middle case, where the left operand does not settle the answer.The order of the operands therefore matters. The guarded version below tests the length before it reads t[0]; the unguarded version reads t[0] on an empty list.
def starts_with(t, x):
"""Return True if the list t is not empty and its first element is x."""
return len(t) > 0 and t[0] == x
def starts_with_unguarded(t, x):
return t[0] == x
print(starts_with([3, 1, 4], 3))
print(starts_with([], 3))
print(starts_with_unguarded([], 3))
and. code/grade-10/01-specifications-and-tests/listings/guard.py$ python guard.py
True
False
Traceback (most recent call last):
File "guard.py", line 12, in <module>
print(starts_with_unguarded([], 3))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "guard.py", line 7, in starts_with_unguarded
return t[0] == x
~^^^
IndexError: list index out of range
[exit status 1]
False for the empty list; the unguarded one stops.Written t[0] == x and len(t) > 0, the guard would come too late: the crash happens while evaluating the left operand.
1.3 Choosing test cases
Sam’s three tries were not careless; they were badly chosen. None of them was a century year that is not a multiple of , such as , the only kind her function gets wrong. Choosing tests is a skill with a method.
Definition 1.9 (Test case, boundary case)
A test case is an input for which the expected result is known in advance, from the specification, together with that expected result. A test case passes when the function returns the expected result and fails otherwise. A boundary case is a test case at the edge between two kinds of input that the specification treats differently.
The specification of leap_year splits the years into four kinds, nested inside each other, as the figure shows.
leap_year, with one test year in each. Sam’s three tries came from the two outer kinds and from the innermost one, never from the third.Method 1.10 (Choosing test cases from a specification)
- Split the allowed inputs into the kinds that the specification treats differently.
- Take one ordinary input of each kind.
- Add the boundary cases: the inputs where one kind meets the next (a mark of exactly when or more passes), and the edges of the precondition (the smallest allowed year, a list of one element).
- If the specification says what happens to invalid inputs (an error, a special value), add one invalid input; if it says nothing, invalid inputs are not test cases.
- Write the expected result of each case from the specification, before running the function.
Example 1.11 (Tests for leap_year)
One year of each kind: , , , ; the edge of the precondition: , which is not a leap year. Sam’s original function fails exactly one of these five tests, the one for . Any set of tests that misses the third kind misses her bug, however many years it contains.
A set of tests should also make every line of the function run at least once. The corrected leap_year has three return lines; the decision diagram below shows which test reaches which.
return; the last one in both of its outcomes.However well chosen, a set of tests tries finitely many inputs.
Proposition 1.12 (Tests do not prove correctness)
Let f be a function whose precondition allows infinitely many inputs, and let be any finite set of test cases that f passes. There is a function that also passes every test of and breaks the specification.
Proof. Choose an allowed input that is not in (there is one, since is finite). Let g return what f returns, except on , where it returns a value that the postcondition forbids. On every input of , g returns what f returns, so it passes ; on it breaks the specification. ∎
Tests find bugs; they cannot show that none is left. Showing that a function is correct for every input needs a proof, which is the subject of a chapter next year. Tests remain the everyday tool: cheap, automatic, and very good at catching the mistakes that people actually make.
1.4 Tests that run themselves
Tests typed by hand at the prompt are lost when the window closes. Written in a file, they can be run again after every change, in a second, by anyone.
Definition 1.13 (Test suite)
A test suite is a program that runs a set of test cases on a function, compares each result with the expected one, and reports which tests pass and which fail.
Python’s standard library includes unittest for this. Each test is a function whose name starts with test, inside a class (the word class is explained in grade 12; here it only groups the tests). assertTrue(x) checks that x is true, assertFalse(x) that it is false, and assertEqual(a, b) that a == b. The first lines choose which version of leap_year to test.
import sys
import unittest
if len(sys.argv) > 1 and sys.argv[1] == "fixed":
from leap_fixed import leap_year
else:
from leap import leap_year
class LeapYearTests(unittest.TestCase):
def test_ordinary_leap(self):
self.assertTrue(leap_year(2024))
def test_ordinary_common(self):
self.assertFalse(leap_year(2023))
def test_century_common(self):
self.assertFalse(leap_year(1900))
def test_four_hundred(self):
self.assertTrue(leap_year(2000))
def test_first_year(self):
self.assertFalse(leap_year(1583))
unittest.main(argv=sys.argv[:1], verbosity=2)
The session below runs the suite on Sam’s version, then on the corrected one. (The runner also prints a line with the time the tests took, which changes from run to run; grep -v removes it, so that the printed output can be checked exactly. Commands like this one are explained next year.)
$ python leap_tests.py 2>&1 | grep -v '^Ran '
test_century_common (__main__.LeapYearTests.test_century_common) ... FAIL
test_first_year (__main__.LeapYearTests.test_first_year) ... ok
test_four_hundred (__main__.LeapYearTests.test_four_hundred) ... ok
test_ordinary_common (__main__.LeapYearTests.test_ordinary_common) ... ok
test_ordinary_leap (__main__.LeapYearTests.test_ordinary_leap) ... ok
======================================================================
FAIL: test_century_common (__main__.LeapYearTests.test_century_common)
----------------------------------------------------------------------
Traceback (most recent call last):
File "~/session/leap_tests.py", line 18, in test_century_common
self.assertFalse(leap_year(1900))
AssertionError: True is not false
----------------------------------------------------------------------
FAILED (failures=1)
$ python leap_tests.py fixed 2>&1 | grep -v '^Ran '
test_century_common (__main__.LeapYearTests.test_century_common) ... ok
test_first_year (__main__.LeapYearTests.test_first_year) ... ok
test_four_hundred (__main__.LeapYearTests.test_four_hundred) ... ok
test_ordinary_common (__main__.LeapYearTests.test_ordinary_common) ... ok
test_ordinary_leap (__main__.LeapYearTests.test_ordinary_leap) ... ok
----------------------------------------------------------------------
OK
A smaller tool, doctest, reads examples written in the docstring itself, in the form of a session at the prompt (>>> then the expected answer), and checks them.
def mean(t):
"""Return the mean of the non-empty list of numbers t.
>>> mean([2, 4, 9])
5.0
>>> mean([7])
7.0
>>> mean([0.5, 0.25])
0.375
"""
return sum(t) / len(t)
$ python -m doctest -v mean.py
Trying:
mean([2, 4, 9])
Expecting:
5.0
ok
Trying:
mean([7])
Expecting:
7.0
ok
Trying:
mean([0.5, 0.25])
Expecting:
0.375
ok
1 items had no tests:
mean
1 items passed all tests:
3 tests in mean.mean
3 tests in 2 items.
3 passed and 0 failed.
Test passed.
python -m doctest -v runs each example and compares what is printed.In practice — Tests in a software project
Professional projects keep thousands of tests and run all of them on every change, often with a tool such as pytest, which finds the test functions by their names. A change is accepted only when every test passes. When a bug is reported, the first step is to write a test that fails because of it; the bug is fixed when that test passes, and the test stays in the suite so that the bug cannot come back unnoticed.
1.5 Where bugs come from
Most bugs belong to a handful of families. Knowing them tells you where to look first. One family deserves a name.
Definition 1.14 (Side effect)
A side effect of a function is any change it makes that outlives the call, apart from the value it returns: a change to a list it received as an argument, to a variable outside the function, to a file, or text printed on the screen.
A side effect is not a mistake in itself (print exists for its side effect). It becomes a bug when the specification does not mention it and the caller does not expect it.
def largest_three(t):
"""Return the three largest numbers of the list t, largest first."""
t.sort(reverse=True)
return t[:3]
scores = [12, 18, 7, 15, 9]
print(largest_three(scores))
print(scores)
t. code/grade-10/01-specifications-and-tests/listings/side_effect.py$ python side_effect.py
[18, 15, 12]
[18, 15, 12, 9, 7]
The method sort changes the list it is applied to, and t is the caller’s list itself, not a copy (the next chapter, 2, explains why). The fix is sorted(t, reverse=True)[:3], which builds a new list.
A second family is the if that forgets a case.
def grade(mark):
"""Return "fail", "pass" or "merit" for a mark from 0 to 20."""
if mark < 10:
return "fail"
elif mark < 15:
return "pass"
elif mark > 15:
return "merit"
for mark in [8, 12, 15, 17]:
print(mark, grade(mark))
$ python missing_branch.py
8 fail
12 pass
15 None
17 merit
return returns None.The boundary case falls through all three tests. Writing the last branch as else makes the if exhaustive, and the boundary test of the method above would have caught it.
Method 1.15 (A checklist of common causes)
When a test fails, or before trusting a function, look for:
- a value of the wrong type: a number read with
inputis a string, and"10" < "9"is true because strings compare letter by letter; - an unexpected side effect: a list argument changed in place;
- an index out of range:
t[len(t)],t[0]on an empty list, a loop one step too long; - a non-exhaustive
if: a case that no branch handles; - the wrong inequality:
<where the specification says “at most” (<=); - equality between decimal numbers: computed decimals are rarely exact, so
==between two of them is a trap (chapter 4 explains why); - a misleading name: a variable called
totalthat holds an average invites the next mistake.
1.6 Exercises
Exercise 1.1 ★
The docstring of a function half(n) holds the two examples >>> half(10) with the expected answer 5 and >>> half(7) with the expected answer 3. The body is return n / 2. What does python -m doctest report for each example, and why?
Solution
Solution of Exercise 1.1.
Both examples fail. doctest compares the text that the call prints with the expected text: half(10) prints 5.0 (the operator / always gives a decimal number), not 5; half(7) prints 3.5, not 3. Either the examples are wrong (the expected answers should be 5.0 and 3.5) or the body is (n // 2 gives 5 and 3); the specification must decide which.
Exercise 1.2 ★
With the function loud of the listing on short-circuit evaluation, what do these two lines print? print(3 > 5 and loud(1)) and print(3 < 5 or loud(2)). Then the same for print(loud(0) or loud(4)).
Solution
Solution of Exercise 1.2.
3 > 5 is false, so loud(1) is not evaluated: the line prints False. 3 < 5 is true, so loud(2) is not evaluated: True. For loud(0) or loud(4): loud(0) prints evaluating loud(0) and returns 0, which counts as false, so loud(4) is evaluated too and prints evaluating loud(4); the result of or is its last evaluated operand, so the line prints 4.
Exercise 1.3 ★
Write the docstring of a function smallest_positive(t) that returns the smallest strictly positive number of a list t. State a precondition and a postcondition, and decide what the precondition must say for the function to always have an answer.
Solution
Solution of Exercise 1.3.
“Return the smallest strictly positive number of t. Precondition: t is a list of numbers that contains at least one number greater than . Postcondition: the result is an element of t, it is greater than , and no element of t that is greater than is smaller than it.” Asking only for a non-empty list is not enough: [-3, 0] is not empty and has no positive element.
Exercise 1.4 ★
The function clamp(x, lo, hi) has the precondition lo <= hi and returns lo if x < lo, hi if x > hi, and x otherwise. List the kinds of input its specification treats differently and the boundary cases between them, and give one test case (input and expected result) for each.
Solution
Solution of Exercise 1.4.
Three kinds: x < lo, lo <= x <= hi, x > hi; boundaries x = lo and x = hi; and the edge of the precondition lo = hi. Tests (with lo = 0, hi = 10 unless stated): clamp(-5, 0, 10) gives 0; clamp(0, 0, 10) gives 0; clamp(4, 0, 10) gives 4; clamp(10, 0, 10) gives 10; clamp(12, 0, 10) gives 10; clamp(7, 3, 3) gives 3.
Exercise 1.5 ★
The specification of is_adult(age) says: “return True when age is or more”. The body is return age > 18. Which test case reveals the bug? Correct the body.
Solution
Solution of Exercise 1.5.
The boundary case is_adult(18): the expected result is True, the function returns False. The body must be return age >= 18 (item 5 of the checklist, the wrong inequality).
Exercise 1.6 ★★
The function below should return the non-negative numbers of a list. def remove_negatives(t): then for x in t: if x < 0: t.remove(x) and finally return t. Called on [-1, -2, 3] it returns [-2, 3]. Explain the result, name the two bugs (one is a side effect), and write a version that builds a new list.
Solution
Solution of Exercise 1.6.
Removing an element while the loop walks through the same list shifts the elements that follow it: after -1 at position is removed, -2 moves to position and the loop goes on at position , so -2 is never examined. The two bugs: the loop skips elements, and the function changes the caller’s list (a side effect the specification does not announce). The fix, in exercises/remove_negatives.py: result = [], then for x in t: if x >= 0: result.append(x), and return result. On [-1, -2, 3] it returns [3] and leaves the argument unchanged (checked by the chapter’s tests).
Exercise 1.7 ★★
The function days_in_month(month, year) returns the number of days of a month (1 to 12) of a year from on. Write a unittest test suite for it with every kind of input and every boundary case you can find, then a body that passes it (you may call the corrected leap_year).
Solution
Solution of Exercise 1.7.
Kinds: the seven months of days, the four of , and February, which splits into the four kinds of year. Boundaries: month 1 and month 12. The suite in exercises/days_in_month.py has seven tests: January and December (), April (), February in (), (), () and (). The body: if month == 2: return 29 if leap_year(year) else 28; then if month in (4, 6, 9, 11): return 30; else return 31. The chapter’s tests compare it with Python’s calendar module on every month of fifty-four years.
Exercise 1.8 ★★
A function is_sorted(t) should return True when the list t is in increasing order. Its body is return len(t) < 2 or t[0] <= t[-1]. For each test case below, say whether it passes or fails: [], [4], [1, 2, 3], [3, 2, 1], [1, 5, 2, 6]. Which kind of input did the author forget?
Solution
Solution of Exercise 1.8.
[] passes (True), [4] passes (True), [1, 2, 3] passes (True), [3, 2, 1] passes (False, as expected), [1, 5, 2, 6] fails: the function returns True because , but the list is not sorted. The author forgot lists that go down somewhere inside while their ends are in order; the fix compares every pair of neighbours.
Exercise 1.9 ★★
A friend says: “my function is_prime(n) passes my tests for every n from to , so it is correct”. Using the proposition of this chapter, build a function that passes the same tests and is wrong. What would it take to know that is_prime is correct?
Solution
Solution of Exercise 1.9.
Take a function bad_is_prime(n) that returns False when n == 1009 and is_prime(n) otherwise. It passes every test from to ( is not among them) and is wrong, since is prime. That is the proof of the proposition on an example: passing tests says nothing about the inputs that were not tried. To know that is_prime is correct for every n, one needs a proof that its body implements the definition of a prime, the kind of argument studied in grade 11.
Exercise 1.10 ★★
The function sign(x) should return -1, 0 or 1 according to the sign of the number x. Its body is if x > 0: return 1 followed by elif x < 0: return -1. What does sign(0) return? Which item of the checklist is this? Correct it.
Solution
Solution of Exercise 1.10.
sign(0) reaches the end of the function without a return and returns None: item 4, the non-exhaustive if. Adding else: return 0 (exercises/sign.py) makes the three branches cover every number.
Exercise 1.11 ★★
Write a function percent(part, whole) that returns part as a percentage of whole. Its preconditions are whole > 0 and 0 <= part <= whole; check them with assertions with clear messages, and check the postcondition (the result lies between and ) with a third assertion.
Solution
Solution of Exercise 1.11.
In exercises/percent.py, three assertions surround the computation result = 100 * part / whole: before it, assert whole > 0 with the message “whole must be positive” and assert 0 <= part <= whole with the message “part must lie between 0 and whole”; after it, assert 0 <= result <= 100; then return result. The tests check percent(1, 4) == 25 and that (1, 0), (-1, 4) and (5, 4) each raise AssertionError.
Exercise 1.12 ★★★
A ticket costs ; a child under pays half, and on Tuesdays everyone has off (after the child reduction). The function has two if statements one after the other, one for each rule. (a) How many different paths through the function are there? (b) What is the smallest number of tests that makes every line run? (c) What is the smallest number that follows every path? Give such tests with their expected prices.
Solution
Solution of Exercise 1.12.
(a) Each if is taken or not, independently: paths. (b) One test makes every line run: a child on a Tuesday (). (c) Four tests follow every path: an adult on a Monday (), an adult on a Tuesday (), a child on a Monday (), a child on a Tuesday (). Running every line is weaker than following every path: the single test of (b) would not notice a bug that only shows for an adult on a Tuesday.
Exercise 1.13 ★★★
Write roman(n) for , which returns the Roman numeral of n (4 is IV, 9 is IX, 1994 is MCMXCIV), with its specification, an assertion on its precondition and a test suite that includes the subtractive forms, the smallest and the largest allowed values, and two invalid inputs.
Solution
Solution of Exercise 1.13.
In exercises/roman.py: a table of the thirteen values 1000 M, 900 CM, 500 D, 400 CD, 100 C, 90 XC, 50 L, 40 XL, 10 X, 9 IX, 5 V, 4 IV, 1 I, from the largest down; for each value, while n >= value, append its letters and subtract it. The precondition is checked by assert 1 <= n <= 3999. The suite tests roman(1), 4, 9, 40, 900, 2026 (MMXXVI), 3999 (MMMCMXCIX), and that 0 and 4000 raise AssertionError; the chapter’s tests also check that the numerals are all different.
Exercise 1.14 ★★★
This loop should count the steps of from to : x = 0.0, steps = 0, then while x != 1.0: with the body x = x + 0.1 and steps = steps + 1. Run in your head with exact decimals, it stops after steps; run by Python, it never stops. Which item of the checklist explains it? Fix the loop in two ways: with a counter that does not depend on x, and with math.isclose(x, 1.0) as the test.
Solution
Solution of Exercise 1.14.
Item 6, equality between decimal numbers: is not stored exactly, so after ten additions x is very close to but not equal to 1.0, and the condition x != 1.0 stays true for ever. First fix: for steps in range(1, 11): x = x + 0.1, a loop that counts its steps instead of testing x. Second fix (exercises/count_up.py): while not math.isclose(x, 1.0), which stops after steps (checked by the chapter’s tests).
Exercise 1.15 ★★★
A mutant of a function is a copy with one small change, such as one number or one operator replaced. A test suite kills a mutant when at least one of its tests fails on it. For the corrected leap_year and the suite of the two years and , say which of these mutants survive: (a) 400 replaced by 100; (b) return False replaced by return True; (c) the last line’s 4 replaced by 400; (d) year % 100 == 0 replaced by year % 100 != 0. Which single year added to the suite kills every survivor?
Solution
Solution of Exercise 1.15.
(a) survives: with 100 in the first test, still returns True there and is not a century. (b) survives: neither nor reaches the line return False. (c) is killed: then gives 2024 % 400 == 0, false. (d) is killed: gives 24 != 0, true, so the mutant returns False. Adding kills both survivors: mutant (a) returns True for it at the first test, mutant (b) returns True at the second.
1.7 Problem: The Mutants of the Leap Year
Problem 1.1
Weekend problem — how good is a test suite?
Sam’s teacher grades test suites, not programs. Her method: she makes many mutants of a correct function (see Exercise 1.15) and counts how many of them a suite kills. A suite that kills every mutant would have caught all those mistakes. This problem compares two suites for the corrected leap_year: four years chosen with the method of this chapter, and a hundred years drawn at random between and .
Part I — The specification.
- State the precondition of
leap_year, and explain why it starts at . - Name the four kinds of year that the postcondition treats differently, and say for each whether it is a leap year.
- How many years from to (both included) are century years? How many of them are leap years?
- What fraction of the years from to belong to the kind that Sam’s first version got wrong?
Part II — A suite from the specification.
- Give the smallest suite with one year of each kind, using , , and , with the expected results.
- Show that no suite of three years can contain one year of each kind.
- Which test of this suite does Sam’s first version fail, and which of the four kinds would a suite need to miss to let her bug through?
- Why is a boundary case, and what is the expected result for it?
Part III — Mutants.
- The teacher’s program changes the body of the corrected function (its lines to ) in one place, by these rules: each
==becomes!=; eachTruebecomesFalseand eachFalsebecomesTrue; the number400becomes100or4;100becomes400or4;4becomes100or400; each0on the right of an==becomes1. Count the mutants by hand. - Write out the mutant where
year % 100 == 0becomesyear % 100 != 0, and find one year of the four-year suite on which it fails. - Write out the mutant where
year % 400becomesyear % 4. Which kind of year does it get wrong? - Run the program
exercises/mutants.pyof this chapter’s code. How many mutants does the four-year suite kill? - Explain without running it why the mutant “the first
TruebecomesFalse” is killed by the four-year suite.
Part IV — A hundred random years.
- Using the answer to question 3, how many century years would you expect among years drawn at random from to , as a rough frequency?
- The random suite of the program kills only mutants. List the seven survivors that the program prints and find what they have in common.
- How many century years does the program’s random suite contain? Explain the survivors with this number.
- Which single year added to the random suite would kill the most survivors? Does any one year kill all seven?
- Find the smallest set of years that, added to the random suite, kills all seven survivors.
- State the result of the comparison: how many mutants does each suite kill, and with how many tests?
Solution
Solution of Problem 1.1.
1. year is a whole number, or later: the rule belongs to a calendar instituted in , and asking about earlier years makes no sense for it.
2. Not divisible by : not leap. Divisible by but not by : leap. Divisible by but not by : not leap. Divisible by : leap.
3. The century years are : of them. The leap ones are , and : .
4. Sam’s version is wrong exactly on the centuries that are not leap. From to there are years, so the fraction is , about .
5. The suite of four test cases: gives False, gives True, gives False, gives True.
6. Each year belongs to exactly one of the four kinds, so three years can cover at most three kinds.
7. It fails the test of . To let the bug through, a suite must contain no year of the third kind (divisible by and not by ).
8. is the smallest year the precondition allows, the edge of the allowed inputs; it is not divisible by , so the expected result is False.
9. Three == (lines , , ): ; one True and one False: ; 400, 100 and 4 have two replacements each: ; three 0 on the right of ==: . In all mutants.
10. The mutant reads if year % 100 != 0: return False. On the condition is true (2024 % 100 is ), so it returns False instead of True; the test of fails.
11. The first line becomes if year % 4 == 0: return True: every year divisible by is leap, so it gets the third kind wrong, exactly like Sam’s version ( gives True).
12. The program prints boundary suite (4 years) kills 14: all fourteen.
13. The mutant returns False at the first test for every multiple of ; the suite contains , whose expected result is True, so that test fails.
14. century years among is a frequency of about , so about one century among random years (and quite possibly none).
15. The survivors are: line 9 True to False; line 11 False to True; line 8 400 to 100 and 400 to 4; line 10 100 to 400; the 0 of line 8 and of line 10 changed to 1. All seven change only what happens on the first two tests, the ones about centuries; every year that is not a century reaches the last line, which is intact in all seven.
16. None: the seeded random suite contains no year divisible by , so the lines about centuries never decide its results, and a change to them is invisible.
17. A century that is not leap (, say) kills five survivors: those of line 11, the two changes of 400, the change of 100 and the 0 of line 10; each makes leap. A multiple of () kills the other two (line 9, and the 0 of line 8). No single year kills all seven: the first group needs a year divisible by and not by , the second a year divisible by .
18. By question 17, two years are needed and two suffice: and .
19. The four years chosen from the specification kill all mutants; the random years kill only . Four well-chosen tests beat a hundred random ones, because the random ones never land on the rare kinds of input where the specification changes its answer.