---
title: "Specifications, Assertions and Tests"
book: "High School Computer Science"
subject: computer-science
language: en
chapter: 1
exercises: 15
source: https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 1 — Specifications, 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 $2024$ (leap), on $2023$ (not leap) and on $2000$ (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 $1900$ 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](#def-g10-specifications-and-tests-specification)*, so that “right” and “wrong” have a meaning; about making the program check the promise while it runs, with *[assertions](#def-g10-specifications-and-tests-assertion)*; 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](#def-g10-specifications-and-tests-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](#def-g10-specifications-and-tests-pre-post), the function promises nothing at all.

![The contract of a function. The caller’s duty comes first, the function’s duty after.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-specifications-and-tests/fig-99ecd382dff5.svg)

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

In Python the [specification](#def-g10-specifications-and-tests-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](#def-g10-specifications-and-tests-specification).

The calendar in use almost everywhere today was instituted in $1582$. Its rule is that a year is a leap year when it is divisible by $4$, except the century years ($1700$, $1800$, $1900$, …), which are leap years only when they are divisible by $400$. Here is Sam’s function, with a [docstring](#def-g10-specifications-and-tests-docstring) that says so.

```python
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](#def-g10-specifications-and-tests-specification). code/grade-10/01-specifications-and-tests/listings/leap.py*

The [precondition](#def-g10-specifications-and-tests-pre-post) ($1583$ or later) is there because the rule means nothing before the calendar existed. The [postcondition](#def-g10-specifications-and-tests-pre-post) 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](#def-g10-specifications-and-tests-pre-post): $1900$ is divisible by $100$ and not by $400$.*

The body tests only the first part of the rule. The [specification](#def-g10-specifications-and-tests-specification) has turned “my friend’s calendar looks odd” into a precise statement: for $1900$, the [postcondition](#def-g10-specifications-and-tests-pre-post) requires `False` and the function returns `True`. That is what a bug is: a call whose [precondition](#def-g10-specifications-and-tests-pre-post) holds and whose [postcondition](#def-g10-specifications-and-tests-pre-post) 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](#def-g10-specifications-and-tests-pre-post) : every restriction on the arguments (“not empty”, “from 1 to 12”).
3. Write the [postcondition](#def-g10-specifications-and-tests-pre-post) 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](#def-g10-specifications-and-tests-pre-post) is “`t` is a non-empty list of numbers”; the [postcondition](#def-g10-specifications-and-tests-pre-post) 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](#def-g10-specifications-and-tests-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.

```python
    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](#def-g10-specifications-and-tests-docstring) is the same). code/grade-10/01-specifications-and-tests/listings/leap_fixed.py*

## 1.2 Assertions

A [specification](#def-g10-specifications-and-tests-specification) written in a [docstring](#def-g10-specifications-and-tests-docstring) is read by people. An [assertion](#def-g10-specifications-and-tests-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](#def-g10-specifications-and-tests-assertion) at the top of a function checks its [precondition](#def-g10-specifications-and-tests-pre-post): 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.

```python
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](#def-g10-specifications-and-tests-pre-post) checked by an [assertion](#def-g10-specifications-and-tests-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](#def-g10-specifications-and-tests-assertion). The error report is read from the bottom: the last line says what went wrong, the lines above say where.*

Without the [assertion](#def-g10-specifications-and-tests-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](#def-g10-specifications-and-tests-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](#def-g10-specifications-and-tests-assertion) 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](#def-g10-specifications-and-tests-assertion) to do its work.

[Assertions](#def-g10-specifications-and-tests-assertion) 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.

```python
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.

```python
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 $400$, such as $1900$, 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](#def-g10-specifications-and-tests-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](#def-g10-specifications-and-tests-specification) treats differently.

The [specification](#def-g10-specifications-and-tests-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.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-specifications-and-tests/fig-3db807723739.svg)

*The four kinds of year in the [specification](#def-g10-specifications-and-tests-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](#def-g10-specifications-and-tests-specification) treats differently.
2. Take one ordinary input of each kind.
3. Add the [boundary cases](#def-g10-specifications-and-tests-test-case) : the inputs where one kind meets the next (a mark of exactly $10$ when $10$ or more passes), and the edges of the [precondition](#def-g10-specifications-and-tests-pre-post) (the smallest allowed year, a list of one element).
4. If the [specification](#def-g10-specifications-and-tests-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](#def-g10-specifications-and-tests-test-case) .
5. Write the expected result of each case from the [specification](#def-g10-specifications-and-tests-specification) , *before* running the function.

**Example 1.11 (Tests for leap_year).**

One year of each kind: $2023$, $2024$, $1900$, $2000$; the edge of the [precondition](#def-g10-specifications-and-tests-pre-post): $1583$, which is not a leap year. Sam’s original function fails exactly one of these five tests, the one for $1900$. 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.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-specifications-and-tests/fig-b2972f1f761c.svg)

*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](#def-g10-specifications-and-tests-pre-post) allows infinitely many inputs, and let $T$ be any finite set of [test cases](#def-g10-specifications-and-tests-test-case) that `f` passes. There is a function that also passes every test of $T$ and breaks the [specification](#def-g10-specifications-and-tests-specification).

**Proof.** Choose an allowed input $x$ that is not in $T$ (there is one, since $T$ is finite). Let `g` return what `f` returns, except on $x$, where it returns a value that the [postcondition](#def-g10-specifications-and-tests-pre-post) forbids. On every input of $T$, `g` returns what `f` returns, so it passes $T$; on $x$ it breaks the [specification](#def-g10-specifications-and-tests-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](#def-g10-specifications-and-tests-test-case) 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.

```python
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](#def-g10-specifications-and-tests-test-case) of the example, as a [test suite](#def-g10-specifications-and-tests-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](#def-g10-specifications-and-tests-docstring) itself, in the form of a session at the prompt (`>>>` then the expected answer), and checks them.

```python
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](#def-g10-specifications-and-tests-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](#def-g10-specifications-and-tests-side-effect) is not a mistake in itself (`print` exists for its [side effect](#def-g10-specifications-and-tests-side-effect)). It becomes a bug when the [specification](#def-g10-specifications-and-tests-specification) does not mention it and the caller does not expect it.

```python
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](#def-g10-specifications-and-tests-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](https://one-course.com/books/computer-science/2/en/chapter/2-tuples-sets-and-comprehensions#ch-g10-tuples-sets-comprehensions), 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.

```python
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](#def-g10-specifications-and-tests-test-case) $15$ 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](#def-g10-specifications-and-tests-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](#def-g10-specifications-and-tests-specification) says “at most” ( `<=` );
6. *equality between decimal numbers* : computed decimals are rarely exact, so `==` between two of them is a trap (chapter [4](https://one-course.com/books/computer-science/2/en/chapter/4-floating-point-numbers#ch-g10-floating-point) 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](#def-g10-specifications-and-tests-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 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](#def-g10-specifications-and-tests-specification) must decide which.

**Exercise 1.2 ★.**

With the function `loud` of the listing on [short-circuit evaluation](#def-g10-specifications-and-tests-short-circuit), 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 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](#def-g10-specifications-and-tests-docstring) of a function `smallest_positive(t)` that returns the smallest strictly positive number of a list `t`. State a [precondition](#def-g10-specifications-and-tests-pre-post) and a [postcondition](#def-g10-specifications-and-tests-pre-post), and decide what the [precondition](#def-g10-specifications-and-tests-pre-post) must say for the function to always have an answer.

**Solution of Exercise 1.3.**

“Return the smallest strictly positive number of `t`. [Precondition](#def-g10-specifications-and-tests-pre-post): `t` is a list of numbers that contains at least one number greater than $0$. [Postcondition](#def-g10-specifications-and-tests-pre-post): the result is an element of `t`, it is greater than $0$, and no element of `t` that is greater than $0$ 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](#def-g10-specifications-and-tests-pre-post) `lo <= hi` and returns `lo` if `x < lo`, `hi` if `x > hi`, and `x` otherwise. List the kinds of input its [specification](#def-g10-specifications-and-tests-specification) treats differently and the [boundary cases](#def-g10-specifications-and-tests-test-case) between them, and give one [test case](#def-g10-specifications-and-tests-test-case) (input and expected result) for each.

**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](#def-g10-specifications-and-tests-pre-post) `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](#def-g10-specifications-and-tests-specification) of `is_adult(age)` says: “return `True` when `age` is $18$ or more”. The body is `return age > 18`. Which [test case](#def-g10-specifications-and-tests-test-case) reveals the bug? Correct the body.

**Solution of Exercise 1.5.**

The [boundary case](#def-g10-specifications-and-tests-test-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](#def-g10-specifications-and-tests-side-effect)), and write a version that builds a new list.

**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 $0$ is removed, `-2` moves to position $0$ and the loop goes on at position $1$, so `-2` is never examined. The two bugs: the loop skips elements, and the function changes the caller’s list (a [side effect](#def-g10-specifications-and-tests-side-effect) the [specification](#def-g10-specifications-and-tests-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 $1583$ on. Write a `unittest` [test suite](#def-g10-specifications-and-tests-test-suite) for it with every kind of input and every [boundary case](#def-g10-specifications-and-tests-test-case) you can find, then a body that passes it (you may call the corrected `leap_year`).

**Solution of Exercise 1.7.**

Kinds: the seven months of $31$ days, the four of $30$, 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 $2025$ ($31$), April $2025$ ($30$), February in $2025$ ($28$), $2024$ ($29$), $1900$ ($28$) and $2000$ ($29$). 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](#def-g10-specifications-and-tests-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 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 \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 $2$ to $1000$, 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 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 $2$ to $1000$ ($1009$ is not among them) and is wrong, since $1009$ 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 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](#def-g10-specifications-and-tests-pre-post) are `whole > 0` and `0 <= part <= whole`; check them with [assertions](#def-g10-specifications-and-tests-assertion) with clear messages, and check the [postcondition](#def-g10-specifications-and-tests-pre-post) (the result lies between $0$ and $100$) with a third [assertion](#def-g10-specifications-and-tests-assertion).

**Solution of Exercise 1.11.**

In `exercises/percent.py`, three [assertions](#def-g10-specifications-and-tests-assertion) 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 $10$; a child under $12$ pays half, and on Tuesdays everyone has $2$ 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 of Exercise 1.12.**

*(a)* Each `if` is taken or not, independently: $2 \times 2 = 4$ paths. *(b)* One test makes every line run: a child on a Tuesday ($10 \to 5 \to 3$). *(c)* Four tests follow every path: an adult on a Monday ($10$), an adult on a Tuesday ($8$), a child on a Monday ($5$), a child on a Tuesday ($3$). 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 \le n \le 3999$, which returns the Roman numeral of `n` (`4` is `IV`, `9` is `IX`, `1994` is `MCMXCIV`), with its [specification](#def-g10-specifications-and-tests-specification), an [assertion](#def-g10-specifications-and-tests-assertion) on its [precondition](#def-g10-specifications-and-tests-pre-post) and a [test suite](#def-g10-specifications-and-tests-test-suite) that includes the subtractive forms, the smallest and the largest allowed values, and two invalid inputs.

**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](#def-g10-specifications-and-tests-pre-post) 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 $3999$ numerals are all different.

**Exercise 1.14 ★★★.**

This loop should count the steps of $0.1$ from $0$ to $1$: `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 $10$ 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 of Exercise 1.14.**

Item 6, equality between decimal numbers: $0.1$ is not stored exactly, so after ten additions `x` is very close to $1$ 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 $10$ 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](#def-g10-specifications-and-tests-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 $2024$ and $2000$, 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 of Exercise 1.15.**

*(a)* survives: with `100` in the first test, $2000$ still returns `True` there and $2024$ is not a century. *(b)* survives: neither $2024$ nor $2000$ reaches the line `return False`. *(c)* is killed: $2024$ then gives `2024 % 400 == 0`, false. *(d)* is killed: $2024$ gives `24 != 0`, true, so the mutant returns `False`. Adding $1900$ 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](#def-g10-specifications-and-tests-test-suite), not programs. Her method: she makes many mutants of a correct function (see [Exercise 1.15](#exo-g10-specifications-and-tests-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 $1583$ and $2400$.

**Part I — The specification.**

1. State the [precondition](#def-g10-specifications-and-tests-pre-post) of `leap_year` , and explain why it starts at $1583$ .
2. Name the four kinds of year that the [postcondition](#def-g10-specifications-and-tests-pre-post) treats differently, and say for each whether it is a leap year.
3. How many years from $1583$ to $2400$ (both included) are century years? How many of them are leap years?
4. What fraction of the years from $1583$ to $2400$ belong to the kind that Sam’s first version got wrong?

**Part II — A suite from the specification.**

5. Give the smallest suite with one year of each kind, using $2023$ , $2024$ , $1900$ and $2000$ , with the expected results.
6. Show that no suite of three years can contain one year of each kind.
7. 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?
8. Why is $1583$ a [boundary case](#def-g10-specifications-and-tests-test-case) , and what is the expected result for it?

**Part III — Mutants.**

9. The teacher’s program changes the body of the corrected function (its lines $8$ to $12$ ) 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.
10. 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.
11. Write out the mutant where `year % 400` becomes `year % 4` . Which kind of year does it get wrong?
12. Run the program `exercises/mutants.py` of this chapter’s code. How many mutants does the four-year suite kill?
13. 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.**

14. Using the answer to question 3, how many century years would you expect among $100$ years drawn at random from $1583$ to $2400$ , as a rough frequency?
15. The random suite of the program kills only $7$ mutants. List the seven survivors that the program prints and find what they have in common.
16. How many century years does the program’s random suite contain? Explain the survivors with this number.
17. Which single year added to the random suite would kill the most survivors? Does any one year kill all seven?
18. Find the smallest set of years that, added to the random suite, kills all seven survivors.
19. State the result of the comparison: how many mutants does each suite kill, and with how many tests?

**Solution of Problem 1.1.**

**1.** `year` is a whole number, $1583$ or later: the rule belongs to a calendar instituted in $1582$, and asking about earlier years makes no sense for it.

**2.** Not divisible by $4$: not leap. Divisible by $4$ but not by $100$: leap. Divisible by $100$ but not by $400$: not leap. Divisible by $400$: leap.

**3.** The century years are $1600, 1700, \dots, 2400$: $9$ of them. The leap ones are $1600$, $2000$ and $2400$: $3$.

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

**5.** The suite of four [test cases](#def-g10-specifications-and-tests-test-case): $2023$ gives `False`, $2024$ gives `True`, $1900$ gives `False`, $2000$ 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 $1900$. To let the bug through, a suite must contain no year of the third kind (divisible by $100$ and not by $400$).

**8.** $1583$ is the smallest year the [precondition](#def-g10-specifications-and-tests-pre-post) allows, the edge of the allowed inputs; it is not divisible by $4$, so the expected result is `False`.

**9.** Three `==` (lines $8$, $10$, $12$): $3$; one `True` and one `False`: $2$; `400`, `100` and `4` have two replacements each: $6$; three `0` on the right of `==`: $3$. In all $3 + 2 + 6 + 3 = 14$ mutants.

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

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

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

**17.** A century that is not leap ($1900$, 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 $1900$ leap. A multiple of $400$ ($2000$) 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 $100$ and not by $400$, the second a year divisible by $400$.

**18.** By question 17, two years are needed and two suffice: $1900$ and $2000$.

**19.** The four years chosen from the [specification](#def-g10-specifications-and-tests-specification) kill all $14$ mutants; the $100$ random years kill only $7$. Four well-chosen tests beat a hundred random ones, because the random ones never land on the rare kinds of input where the [specification](#def-g10-specifications-and-tests-specification) changes its answer.
