计算机科学 · 第 2 册 · 10–12 年级

High School Computer Science

本书暂未推出简体中文版。现有版本: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 20242024 (leap), on 20232023 (not leap) and on 20002000 (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 19001900 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.

The contract of a function. The caller’s duty comes first, the function’s duty after.
The contract of a function. The caller’s duty comes first, the function’s duty after.

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 15821582. Its rule is that a year is a leap year when it is divisible by 44, except the century years (17001700, 18001800, 19001900, …), which are leap years only when they are divisible by 400400. 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
Listing 1.1. Sam’s function, with its specification. code/grade-10/01-specifications-and-tests/listings/leap.py

The precondition (15831583 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
Output 1.1. Four calls. The last line breaks the postcondition: 19001900 is divisible by 100100 and not by 400400.

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 19001900, 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)

  1. Name each parameter and say what kind of value it holds (a whole number, a list of numbers, a string).
  2. Write the precondition: every restriction on the arguments (“not empty”, “from 1 to 12”).
  3. Write the postcondition in terms of the arguments: what the result is, not how it is found.
  4. 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
Listing 1.2. The body of the corrected function (its docstring is the same). code/grade-10/01-specifications-and-tests/listings/leap_fixed.py

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([]))
Listing 1.3. A precondition checked by an assertion. The last line breaks it on purpose. code/grade-10/01-specifications-and-tests/listings/average.py
$ 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]
Output 1.2. The first call keeps the contract; the second stops with the message of the assertion. The error report is read from the bottom: the last line says what went wrong, the lines above say where.

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))
Listing 1.4. A function that announces each evaluation. code/grade-10/01-specifications-and-tests/listings/short_circuit.py
$ python short_circuit.py
False and loud(True):
False
True and loud(False):
  evaluating loud(False)
False
True or loud(False):
True
Output 1.3. 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))
Listing 1.5. A guard on the left of 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]
Output 1.4. The guarded function answers 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 400400, such as 19001900, 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.

The four kinds of year in the specification of 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.
The four kinds of year in the specification of 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)

  1. Split the allowed inputs into the kinds that the specification treats differently.
  2. Take one ordinary input of each kind.
  3. Add the boundary cases: the inputs where one kind meets the next (a mark of exactly 1010 when 1010 or more passes), and the edges of the precondition (the smallest allowed year, a list of one element).
  4. 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.
  5. 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: 20232023, 20242024, 19001900, 20002000; the edge of the precondition: 15831583, which is not a leap year. Sam’s original function fails exactly one of these five tests, the one for 19001900. 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.

The paths through the corrected function. The five tests reach every return; the last one in both of its outcomes.
The paths through the corrected function. The five tests reach every 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 TT be any finite set of test cases that f passes. There is a function that also passes every test of TT and breaks the specification.

Proof. Choose an allowed input xx that is not in TT (there is one, since TT is finite). Let g return what f returns, except on xx, where it returns a value that the postcondition forbids. On every input of TT, g returns what f returns, so it passes TT; on xx 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)
Listing 1.6. The five test cases of the example, as a test suite. code/grade-10/01-specifications-and-tests/listings/leap_tests.py

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
Output 1.5. A failing test is a bug report: it names the test, the line, and what came back instead of what was expected.

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)
Listing 1.7. Examples in a docstring are also tests. code/grade-10/01-specifications-and-tests/listings/mean.py
$ 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.
Output 1.6. 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)
Listing 1.8. The specification promises a result, not a change to t. code/grade-10/01-specifications-and-tests/listings/side_effect.py
$ python side_effect.py
[18, 15, 12]
[18, 15, 12, 9, 7]
Output 1.7. The result is right, but the caller’s list of scores has been reordered.

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))
Listing 1.9. Three branches, and a mark that falls between them. code/grade-10/01-specifications-and-tests/listings/missing_branch.py
$ python missing_branch.py
8 fail
12 pass
15 None
17 merit
Output 1.8. A function that reaches its end without return returns None.

The boundary case 1515 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:

  1. a value of the wrong type: a number read with input is a string, and "10" < "9" is true because strings compare letter by letter;
  2. an unexpected side effect: a list argument changed in place;
  3. an index out of range: t[len(t)], t[0] on an empty list, a loop one step too long;
  4. a non-exhaustive if: a case that no branch handles;
  5. the wrong inequality: < where the specification says “at most” (<=);
  6. equality between decimal numbers: computed decimals are rarely exact, so == between two of them is a trap (chapter 4 explains why);
  7. a misleading name: a variable called total that 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 00. Postcondition: the result is an element of t, it is greater than 00, and no element of t that is greater than 00 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 1818 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 00 is removed, -2 moves to position 00 and the loop goes on at position 11, 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 15831583 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 3131 days, the four of 3030, 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 20252025 (3131), April 20252025 (3030), February in 20252025 (2828), 20242024 (2929), 19001900 (2828) and 20002000 (2929). 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 1≤61 \le 6, 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 22 to 10001000, 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 22 to 10001000 (10091009 is not among them) and is wrong, since 10091009 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 00 and 100100) 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 1010; a child under 1212 pays half, and on Tuesdays everyone has 22 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: 2×2=42 \times 2 = 4 paths. (b) One test makes every line run: a child on a Tuesday (10→5→310 \to 5 \to 3). (c) Four tests follow every path: an adult on a Monday (1010), an adult on a Tuesday (88), a child on a Monday (55), a child on a Tuesday (33). 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 1≤n≤39991 \le n \le 3999, 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 39993999 numerals are all different.

Exercise 1.14 ★★★

This loop should count the steps of 0.10.1 from 00 to 11: 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 1010 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: 0.10.1 is not stored exactly, so after ten additions x is very close to 11 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 1010 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 20242024 and 20002000, 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, 20002000 still returns True there and 20242024 is not a century. (b) survives: neither 20242024 nor 20002000 reaches the line return False. (c) is killed: 20242024 then gives 2024 % 400 == 0, false. (d) is killed: 20242024 gives 24 != 0, true, so the mutant returns False. Adding 19001900 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 15831583 and 24002400.

Part I — The specification.

  1. State the precondition of leap_year, and explain why it starts at 15831583.
  2. Name the four kinds of year that the postcondition treats differently, and say for each whether it is a leap year.
  3. How many years from 15831583 to 24002400 (both included) are century years? How many of them are leap years?
  4. What fraction of the years from 15831583 to 24002400 belong to the kind that Sam’s first version got wrong?

Part II — A suite from the specification.

  1. Give the smallest suite with one year of each kind, using 20232023, 20242024, 19001900 and 20002000, with the expected results.
  2. Show that no suite of three years can contain one year of each kind.
  3. 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?
  4. Why is 15831583 a boundary case, and what is the expected result for it?

Part III — Mutants.

  1. The teacher’s program changes the body of the corrected function (its lines 88 to 1212) in one place, by these rules: each == becomes !=; each True becomes False and each False becomes True; the number 400 becomes 100 or 4; 100 becomes 400 or 4; 4 becomes 100 or 400; each 0 on the right of an == becomes 1. Count the mutants by hand.
  2. Write out the mutant where year % 100 == 0 becomes year % 100 != 0, and find one year of the four-year suite on which it fails.
  3. Write out the mutant where year % 400 becomes year % 4. Which kind of year does it get wrong?
  4. Run the program exercises/mutants.py of this chapter’s code. How many mutants does the four-year suite kill?
  5. Explain without running it why the mutant “the first True becomes False” is killed by the four-year suite.

Part IV — A hundred random years.

  1. Using the answer to question 3, how many century years would you expect among 100100 years drawn at random from 15831583 to 24002400, as a rough frequency?
  2. The random suite of the program kills only 77 mutants. List the seven survivors that the program prints and find what they have in common.
  3. How many century years does the program’s random suite contain? Explain the survivors with this number.
  4. Which single year added to the random suite would kill the most survivors? Does any one year kill all seven?
  5. Find the smallest set of years that, added to the random suite, kills all seven survivors.
  6. 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, 15831583 or later: the rule belongs to a calendar instituted in 15821582, and asking about earlier years makes no sense for it.

2. Not divisible by 44: not leap. Divisible by 44 but not by 100100: leap. Divisible by 100100 but not by 400400: not leap. Divisible by 400400: leap.

3. The century years are 1600,1700,…,24001600, 1700, \dots, 2400: 99 of them. The leap ones are 16001600, 20002000 and 24002400: 33.

4. Sam’s version is wrong exactly on the 9−3=69 - 3 = 6 centuries that are not leap. From 15831583 to 24002400 there are 2400−1583+1=8182400 - 1583 + 1 = 818 years, so the fraction is 6/8186/818, about 0.7 %0.7\,\%.

5. The suite of four test cases: 20232023 gives False, 20242024 gives True, 19001900 gives False, 20002000 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 19001900. To let the bug through, a suite must contain no year of the third kind (divisible by 100100 and not by 400400).

8. 15831583 is the smallest year the precondition allows, the edge of the allowed inputs; it is not divisible by 44, so the expected result is False.

9. Three == (lines 88, 1010, 1212): 33; one True and one False: 22; 400, 100 and 4 have two replacements each: 66; three 0 on the right of ==: 33. In all 3+2+6+3=143 + 2 + 6 + 3 = 14 mutants.

10. The mutant reads if year % 100 != 0: return False. On 20242024 the condition is true (2024 % 100 is 2424), so it returns False instead of True; the test of 20242024 fails.

11. The first line becomes if year % 4 == 0: return True: every year divisible by 44 is leap, so it gets the third kind wrong, exactly like Sam’s version (19001900 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 400400; the suite contains 20002000, whose expected result is True, so that test fails.

14. 99 century years among 818818 is a frequency of about 9/818≈0.0119/818 \approx 0.011, so about one century among 100100 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 100100, so the lines about centuries never decide its results, and a change to them is invisible.

17. A century that is not leap (19001900, 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 19001900 leap. A multiple of 400400 (20002000) 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 100100 and not by 400400, the second a year divisible by 400400.

18. By question 17, two years are needed and two suffice: 19001900 and 20002000.

19. The four years chosen from the specification kill all 1414 mutants; the 100100 random years kill only 77. 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.

本章定义的术语

在术语表中查看全部 1050 个术语