Buku ini belum tersedia dalam Bahasa Indonesia. Edisi: English.
University Computer Science — Year 3 · Sarjana Tahun 3
30Software Engineering: Design, Testing and Maintenance
A program written once and thrown away needs only to work. A program that a town library runs for ten years, that three people change every month and that must keep working after each change, needs more: a design that keeps each change small, tests that say at once when a change broke something, and habits that keep both in good order. This chapter follows one such program, the library’s loan system, from its requirements to its design, its tests, the measurement of those tests, and the checks that run before every commit. Each claim about the tests is measured by tools built in the chapter: a coverage tool on the interpreter’s own monitoring events, and a mutation tester that rewrites the program’s syntax tree.
You already know
A specification states what a program must do; an assertion states a property that must hold at a point of the program (grade 10 volume). A module hides its implementation behind an interface (grade 11 volume). A unit test checks one function or module; statement, branch and path coverage measure which parts of a program the tests run; a test oracle decides whether an output is correct; an end-to-end test runs the whole program as a user would (Year 1 volume). Git records the history of a project, commit by commit (Year 1 volume). Classes, interfaces and exceptions come from the Year 2 volume.
30.1 From requirements to design
Definition 30.1 (Requirement, use case)
A requirement is a statement of something the system must do or a property it must have, written so that a test or an inspection can decide whether it holds. A use case describes one interaction between a user, called an actor, and the system that reaches a goal of the actor: its main sequence of steps, and what happens when a step fails.
The library’s requirements, as the librarians gave them, read “readers may borrow books for a while, with fines if late”. Rewritten as testable statements, they become:
- R1. A loan lasts 21 days from the day of borrowing.
- R2. A book on loan cannot be borrowed again until it is given back.
- R3. A reader may hold at most 5 loans at a time.
- R4. A loan that is not late may be renewed by 1 to 4 weeks; a late loan may not.
- R5. A book given back late costs 20 cents per day late.
Each one names a number or a condition that a test can check, and each will have its test. The use case “borrow a book” has the reader as actor: the reader hands the book and the card to the desk; the system checks the book is not on loan (R2) and the reader holds fewer than 5 loans (R3); it records the loan with its due date (R1) and prints it. Two failure branches: the book is already on loan, or the reader has too many loans; each ends with a refusal that says why.
Definition 30.2 (UML class diagram, sequence diagram)
A UML class diagram shows the classes of a design as boxes listing their attributes and operations, and the relations between them as lines: association, with its multiplicities, and dependency, drawn dashed. A sequence diagram shows one scenario as objects side by side, each with a vertical lifeline, and the messages between them as arrows in time order, from top to bottom.
UML, the Unified Modeling Language, became a standard of the Object Management Group in 1997. The two diagrams below are the design of the loan system; the rest of the chapter is its code.
30.2 Modularity, coupling and cohesion
Definition 30.3 (Modularity, coupling, cohesion, information hiding, dependency inversion)
Modularity is the division of a program into modules that can be written, understood, tested and changed separately. Coupling is the degree to which one module depends on the details of another; cohesion is the degree to which the parts of one module serve a single purpose. Information hiding is the choice of module boundaries so that each module hides a design decision likely to change, behind an interface that does not reveal it. Dependency inversion makes a high-level module and a low-level one both depend on an interface owned by the high-level side, instead of the high-level module depending on the low-level one.
Parnas stated the criterion of information hiding in 1972: decompose a system by the decisions that may change, each hidden in one module, rather than by the steps of its processing. In the loan system, the decision “loans are kept in SQLite” is likely to change; it is hidden in SqliteLoans. The service sees only four operations, and receives its repository, its clock, its fine policy and its listeners from outside.
def __init__(self, repo, clock, fine=flat_fine, listeners=()):
self.repo, self.clock, self.fine = repo, clock, fine
self.listeners = list(listeners)
def _tell(self, event, loan):
for listener in self.listeners:
listener(event, loan)
def borrow(self, reader, book):
if self.repo.open_loan_of(book.isbn) is not None:
raise LoanError(f"{book.title} is already on loan")
if len(self.repo.open_loans_of(reader.card)) >= MAX_LOANS:
raise LoanError(f"{reader.name} already has {MAX_LOANS} loans")
today = self.clock()
loan = Loan(book, reader, today, today + timedelta(days=LOAN_DAYS))
self.repo.add(loan)
self._tell("borrowed", loan)
return loan
Low coupling and high cohesion are the two sides of the same aim. The service is cohesive, since it holds the rules of the use cases and nothing else; it is loosely coupled to storage, since a test can hand it any object with the four operations, and to time, since the clock is a function it is given. A version that opened the database itself and read date.today() would be simpler to write and much harder to test: every test would need a database file and would depend on the day it ran.
Robert C. Martin collected five such design principles in 2000, later named SOLID. Each has its instance in the loan system:
- single responsibility:
Loancomputes days late, the service applies the rules, the repository stores; a change to the fine rule touches one place; - open–closed: a new fine policy is added as a new function, without changing the service;
- Liskov substitution: any object with the four operations of
LoanRepository, honouring their meaning, can replaceSqliteLoans; - interface segregation: the service’s listeners are given only an event name and a loan, not the whole service;
- dependency inversion: the arrangement of the figure above.
Definition 30.4 (Design pattern, strategy pattern, observer pattern, adapter pattern, model–view–controller)
A design pattern is a named, reusable solution to a design problem that recurs in a context, described by its problem, its structure and its consequences. The strategy pattern puts each variant of an algorithm behind one interface, so that the variant can be chosen at run time. The observer pattern lets objects register with a subject, which notifies each of them of its changes without knowing what they are. The adapter pattern wraps an object so that it offers the interface that a client expects. Model–view–controller (MVC) divides an interactive program into the model, which holds the data and the rules, the view, which presents them, and the controller, which turns the user’s input into operations on the model.
The book by Gamma, Helm, Johnson and Vlissides, Design Patterns, published in 1994, catalogued 23 of them. In the loan system the fine policies flat_fine and capped_fine are strategies, the listeners are observers, and the repository interface is itself a pattern, the repository, which hides storage behind a collection-like interface. The town’s old catalogue gives each book as a line of text separated by bars; an adapter gives it the interface the loan system wants.
class TownCatalogue: # the existing interface: one record as a "|"-separated line
def fetch_record(self, code):
return RECORDS.get(code, "")
class CatalogueAdapter: # the interface the loan system wants
def __init__(self, catalogue):
self.catalogue = catalogue
def book(self, isbn):
record = self.catalogue.fetch_record(isbn)
if not record:
raise KeyError(isbn)
code, title, _shelf = record.split("|")
return Book(code, title)
MVC was created by Trygve Reenskaug for Smalltalk at Xerox PARC in the late 1970s. The toy web app of Chapter 29 can be read through it: its sessions and comments are the model, the function that builds the HTML page is the view, and the request handler that reads the form and calls the model is the controller. Its escaping, which Chapter 29 placed at the point where text enters HTML, belongs in the view.
A pattern pays when the variation it allows is real. A strategy for a fine policy that has had three versions in ten years earns its keep; an observer with one listener that will never have a second only adds an indirection to read through.
30.3 Tests
Definition 30.5 (Integration test, test double, metamorphic testing)
An integration test checks several modules working together, with their real collaborators, such as a service with its database. A test double is an object that stands in for a collaborator of the code under test: a stub returns fixed answers, a spy also records how it was called, a fake is a working but simplified implementation. Metamorphic testing checks a relation between the outputs for related inputs, such as “sorting a permutation of a list gives the same result”, when no test oracle for a single output is available.
Meszaros’s classification of test doubles, from 2007, distinguishes the stub, the spy, the mock, the fake and the dummy. The loan system’s tests use two: a stub clock that the test sets, and a spy listener that records the events.
class Clock: # a stub: the test sets the date
def __init__(self, today):
self.today = today
def __call__(self):
return self.today
def make_service(repo=None, fine=flat_fine):
events = [] # a spy: the listener records what it was told
clock = Clock(DAY)
service = LoanService(
repo or SqliteLoans(),
clock,
fine,
[lambda event, loan: events.append((event, loan.book.isbn))],
)
return service, clock, events
def test_days_late_is_zero_until_due(): # a unit test: one class, no collaborator
loan = Loan(DUNE, ADA, DAY, DAY + timedelta(days=21))
assert loan.days_late(DAY + timedelta(days=21)) == 0
assert loan.days_late(DAY + timedelta(days=24)) == 3
def test_late_return_is_fined(): # an integration test: service and SQLite together
service, clock, events = make_service()
service.borrow(ADA, DUNE)
clock.today = DAY + timedelta(days=21 + 4)
assert service.give_back(DUNE.isbn) == 80
assert events == [("borrowed", DUNE.isbn), ("returned", DUNE.isbn)]
Loan alone, and an integration test of the service with SQLite, which moves the clock 25 days on and expects R5’s fine. code/bachelor-3/30-software-engineering/tests/test_loans.pyThe end-to-end test runs the desk program as a user would, with a session of seven commands on its standard input, and compares what it prints.
$ python desk.py
2026-03-02 Ada borrows Crime and Punishment, due 2026-03-23
2026-03-02 refused: Crime and Punishment is already on loan
2026-03-16 Crime and Punishment renewed, due 2026-04-06
2026-04-06 returned, fine 0.00 euros
2026-04-06 Grace borrows Introduction to Algorithms, due 2026-04-27
2026-05-04 refused: a late loan cannot be renewed
2026-05-08 returned, fine 2.20 euros
The three levels trade speed against realism. A unit test runs in microseconds and points at one function, but it trusts every assumption the function makes about its collaborators; an end-to-end test checks that the whole program fits together, but it is slow and, when it fails, says little about where. A suite has many unit tests, fewer integration tests and a few end-to-end tests.
Definition 30.6 (Property-based test, shrinking)
A property-based test states a property that must hold for all inputs of a kind, and checks it on many inputs generated at random. Shrinking is the search, after a failing input is found, for a smaller input that still fails, so that the reported counterexample is as simple as possible.
Claessen and Hughes introduced the idea with QuickCheck, for Haskell, in 2000; the Python library hypothesis follows it, and its setting derandomize makes every run test the same inputs, which keeps a printed result reproducible. An older version of the town’s date library counted every fourth year as a leap year. A property against Python’s own calendar, used as the oracle, finds the error.
def old_day_number(year, month, day): # the bug: no exception for years like 1900
y = year - 1
n = 365 * y + y // 4
for m in range(1, month):
n += 29 if m == 2 and year % 4 == 0 else MONTH_DAYS[m - 1]
return n + day
dates = st.builds(date, st.integers(1, 9999), st.integers(1, 12), st.integers(1, 28))
tried = []
def same_as_the_calendar(a, b): # the property: the oracle is Python's own calendar
tried.append((a, b))
found = old_day_number(b.year, b.month, b.day) - old_day_number(
a.year, a.month, a.day
)
assert found == (b - a).days
$ python prop_demo.py
as found a = 0199-01-01, b = 0001-01-01, after 3 examples
after shrinking a = 0001-01-01, b = 0101-01-01, after 211 examples
When a single output has no oracle, a relation between outputs may still be checkable. Metamorphic testing was proposed by Chen and his colleagues in 1998: a search that is narrowed must return a subset of its results; a shortest path cannot get longer when an edge is added; a sorted list does not change when its input is permuted. Exercise 30.10 finds a bug in a sort that way, without ever stating what the sorted list should be.
30.4 Coverage and its limits
Statement and branch coverage, defined in the Year 1 volume, say which parts of the code a test suite runs. Python 3.12 added sys.monitoring, which calls a registered tool at chosen events: a LINE event when a new line starts, a BRANCH event when a conditional jump is taken or not. A tool may answer DISABLE to stop being told about a place. That is all a coverage tool needs.
def _line(self, code, line):
if self._ours(code):
self.lines.add(line)
return mon.DISABLE # a line counts once: stop telling us about it
def _branch(self, code, offset, destination):
if self._ours(code):
self.arcs.add((code.co_qualname, offset, destination))
def __enter__(self):
mon.use_tool_id(TOOL, "book-coverage")
mon.register_callback(TOOL, mon.events.LINE, self._line)
mon.register_callback(TOOL, mon.events.BRANCH, self._branch)
mon.set_events(TOOL, mon.events.LINE | mon.events.BRANCH)
return self
def __exit__(self, *exc):
mon.set_events(TOOL, mon.events.NO_EVENTS)
mon.free_tool_id(TOOL)
mon.restart_events() # re-enable what DISABLE switched off, for the next run
The tool finds the statements of the file by compiling it, and the branches by listing the conditional jumps of its bytecode with dis, two destinations each. It is run on the service with the first two tests, then with the whole suite.
$ python coverage_demo.py
the first two tests: all pass
statements (21, 36)
missed lines [14, 28, 30, 40, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57]
branches (5, 16)
missed branches at lines [27, 29, 39, 47, 47, 47, 47, 50, 50, 52, 52]
the whole suite: all pass
statements (36, 36)
missed lines []
branches (15, 16)
missed branches at lines [47]
loans/service.py. The whole suite runs every statement and 15 of the 16 branches; the one never taken is the way out of 1 <= weeks when it is false, for a renewal of 0 weeks or fewer.Full coverage is necessary for confidence, not sufficient. A suite can run every statement and take every branch while checking nothing: a test with no useful assertion covers as much as a good one (Exercise 30.5). And it can miss the one input where the code is wrong: the date library’s first suite, in the weekend problem, runs every statement, yet never asks about the year 1900, and a leap rule that forgot the centuries would pass it with the same coverage (Exercise 30.7). Coverage says what the tests did not run; it does not say that what they ran was checked.
Definition 30.7 (Mutation testing, mutant, mutation score, equivalent mutant)
Mutation testing evaluates a test suite by making many small changes to the program under test, one at a time, and running the suite on each. Each changed program is a mutant; the suite kills a mutant if at least one test fails on it. The mutation score is the number of killed mutants divided by the number of mutants. An equivalent mutant is one that behaves exactly as the original program on every input, so that no test can kill it.
Mutation testing was proposed by Lipton in 1971 and published by DeMillo, Lipton and Sayward in 1978. The mutator of the chapter parses a module with ast, finds every operator and every integer constant, and makes one mutant per site: + becomes -, < becomes <=, and becomes or, a constant becomes , and so on, from a fixed table.
def mutants(source):
"""Yield (line, before, after, mutant syntax tree), one per site."""
count = len(sites(ast.parse(source)))
for k in range(count):
tree = ast.parse(source) # a fresh tree for each mutant
node, field, i, new = sites(tree)[k]
before = ast.unparse(node)
if i is None:
setattr(node, field, new)
else:
node.ops[i] = new
yield node.lineno, before, ast.unparse(node), tree
Each mutant is compiled and installed in sys.modules under the module’s name, the test module is imported afresh so that it sees the mutant, and its tests are run. The end-to-end test is left out, since it runs the program in another process, which would load the real module.
$ python mutation_demo.py
16 mutants, 15 killed, mutation score 94%
survived, line 47: 1 <= weeks <= 4 -> 1 <= weeks < 4
The survivor shows what coverage could not: line 47 was run, and both its comparisons evaluated, but no test looked at the boundary. One test, a renewal of 4 weeks that must succeed, kills it. Equivalent mutants are the method’s cost: they survive every suite, and deciding whether a survivor is equivalent is in general undecidable, since it is the equivalence of two programs; in practice it is a short argument for each, as the weekend problem shows.
30.5 Continuous integration, review and refactoring
Definition 30.8 (Continuous integration, code review, refactoring, characterisation test, technical debt)
Continuous integration (CI) merges every change into the shared main line often, at least daily, and builds and tests the result automatically at each change. A code review is the reading of a change by someone other than its author before it is merged. Refactoring is a change to the structure of code that does not change its behaviour, made in small steps, each checked by the tests. A characterisation test records what existing code actually does, right or wrong, so that a change that alters it is detected. Technical debt is the future cost of changes that a quick solution makes harder, paid for as long as the solution stays.
Booch named continuous integration in 1991; Cunningham coined “technical debt” in 1992. The smallest form of CI runs on the developer’s own machine. Before every commit, Git runs the script .git/hooks/pre-commit, if it is there and executable, and refuses the commit if the script fails. The date library’s hook runs the linter, then a gate that runs the tests under the coverage tool and refuses any failure, or coverage below 100 % of statements.
$ git init -q -b main
$ printf '#!/bin/sh\nruff check -q . && python gate.py towndate.py date_tests 100\n' > .git/hooks/pre-commit
$ chmod +x .git/hooks/pre-commit
$ git add . && git commit -q -m "Town date library with its tests" && echo committed
gate: 0 failed: -; statements 16/16, branches 17/18
committed
$ sed -i 's/year % 100 != 0 or year % 400 == 0/True/' towndate.py
$ git commit -q -am "Simplify is_leap" || echo "commit refused"
gate: 1 failed: test_new_against_datetime; statements 16/16, branches 15/16
gate: refused
commit refused
$ sed -i 's/(True)/(year % 100 != 0 or year % 400 == 0)/' towndate.py
$ printf 'def test_new_1700():\n assert not is_leap(1700)\n' >> date_tests.py
$ git commit -q -am "Test the year 1700" && echo committed
gate: 0 failed: -; statements 16/16, branches 17/18
committed
$ git log --oneline
7fe6539 Test the year 1700
274a8c2 Town date library with its tests
--no-verify or a missing file is still caught.A review reads what the checks cannot: whether the change does what its message says, whether the requirement it serves is right, whether a test checks the right object (Exercise 30.5 is such a test), whether names say what things are, whether the change leaves the design easier or harder to change next time. It reads the tests first: they say what the author thought the change does.
Fowler’s Refactoring, in 1999, set out the method: tests first, then small steps, each leaving the tests green. The desk’s fines report is one long function with six parameters.
def fines_report(loans, today, rate, cap, grace, currency):
lines = []
total = 0
for title, reader, due in loans:
late = (today - due).days - grace
if late > 0:
fine = late * rate
if cap is not None and fine > cap:
fine = cap
total += fine
lines.append(
f"{reader:6} {title:24} {late:3} days {fine / 100:6.2f} {currency}"
)
lines.sort()
lines.append(f"{'total':40} {total / 100:6.2f} {currency}")
return "\n".join(lines)
Three steps make it clearer: extract the computation of a fine into a function, extract the formatting of a line, then introduce a parameter object, FinePolicy, for the four parameters that always travel together. After each step the same tests pass.
@dataclass(frozen=True)
class FinePolicy:
rate: int = 20 # cents a day
cap: int | None = None # at most this many cents, if set
grace: int = 0 # days before a fine starts
currency: str = "EUR"
def fine(self, late):
fine = late * self.rate
return fine if self.cap is None else min(fine, self.cap)
def line(reader, title, late, cents, currency):
return f"{reader:6} {title:24} {late:3} days {cents / 100:6.2f} {currency}"
def fines_report(loans, today, policy):
lines, total = [], 0
for title, reader, due in loans:
late = (today - due).days - policy.grace
if late > 0:
total += policy.fine(late)
lines.append(line(reader, title, late, policy.fine(late), policy.currency))
lines.sort()
lines.append(f"{'total':40} {total / 100:6.2f} {policy.currency}")
return "\n".join(lines)
The tests that protect such a change are characterisation tests, a term of Feathers: they record the old output, whatever it is, and require the new code to print it exactly. The old report prints “1 days”; the refactoring must keep it, since some reader of the report may depend on it, and correcting it is a separate change with its own test.
$ python refactor_check.py
Ada Dune 19 days 3.80 EUR
Ada Middlemarch 75 days 5.00 EUR
Alan Ulysses 1 days 0.20 EUR
Grace Emma 40 days 5.00 EUR
total 14.00 EUR
rate 20, cap 500, grace 2: same
rate 20, cap None, grace 0: same
rate 35, cap 300, grace 7: same
rate 10, cap 0, grace 0: same
30.6 Exercises
Exercise 30.1 ★
Rank these three designs of the fines report from the most to the least coupled to the database, and say what a test of each needs: (a) the report runs its own SQL query; (b) the report receives a repository and asks it for the open loans; (c) the report receives a list of loans.
Solution
Solution of Exercise 30.1.
From the most coupled to the least: (a), then (b), then (c). Design (a) knows the database, its table and its columns: a test needs a database with the right schema and rows, and a change of storage changes the report. Design (b) knows only the repository’s interface: a test hands it a fake repository holding a few loans. Design (c) knows nothing but loans: a test passes a list, and the report can be used on loans from anywhere. Design (c) is the most reusable and the easiest to test; (b) is right when the report must choose which loans to ask for.
Exercise 30.2 ★
Say whether each test is a unit, an integration or an end-to-end test: (a) test_days_late_is_zero_until_due; (b) test_late_return_is_fined; (c) test_desk_end_to_end; (d) the contract test of Exercise 30.6 run against SqliteLoans; (e) a test of flat_fine alone.
Solution
Solution of Exercise 30.2.
(a) Unit: one class, no collaborator. (b) Integration: the service with the real SQLite repository and a stub clock. (c) End-to-end: the whole program through its command line, in another process. (d) Integration: the contract exercises the real database. (e) Unit.
Exercise 30.3 ★
For days_in_month of the town’s date library and the tests days_in_month(2024, 2) and days_in_month(2026, 1), which statements and which branches are covered? Add the fewest tests that reach 100 % of branches of this function alone.
Solution
Solution of Exercise 30.3.
The two calls run the three statements of the function: (2024, 2) takes the if and returns 29, (2026, 1) falls through to the table. Of the branches, the test month == 2 goes both ways, but is_leap(year) is only seen true. One more test, days_in_month(2026, 2) == 28, takes it false and reaches every branch of this function. A test checks it with the coverage tool.
Exercise 30.4 ★
The mutator makes three mutants of return min(20 * days_late, 500). List them, and predict which ones the single test capped_fine(30) == 500 kills.
Solution
Solution of Exercise 30.4.
The three mutants are
min(20 + days_late, 500), min(21 * days_late, 500), min(20 * days_late, 501).
With 30 days late: the first gives 50, killed; the second gives , which survives, since the cap hides the rate; the third gives 501, killed. A test of the uncapped part, such as capped_fine(1) == 20, kills the survivor. A test computes the three mutants and checks the prediction.
Exercise 30.5 ★★
In exercises/ex5_wrong_object.py, test_fine_always_passes returns a book four days late and checks the result. Find why it can never fail, show it by mutation testing of the service, and fix it.
Solution
Solution of Exercise 30.5.
The test asserts on the loan returned by borrow, whose days late at day 25 are 4 whatever give_back computes: it never looks at the fine. Mutation testing shows it: the two mutants of flat_fine, 20 + days_late and 21 * days_late, survive it, while they change the fine from 80 to 24 and 84. The fixed test asserts fine == 80 and kills both: the score of the test alone rises from 3 to 5 of the 16 mutants of the service. The rest survive because a single test exercises a single path, which is what the whole suite is for.
Exercise 30.6 ★★
Write MemoryLoans, a fake repository keeping loans in a list, and one contract test that both repositories must pass: a loan added is found open, a change to the caller’s object does not change what is stored, a loan saved as returned is no longer open, and another reader’s loan is untouched.
Solution
Solution of Exercise 30.6.
exercises/ex6_memory_repo.py keeps a list of loans and stores and returns copies, made with dataclasses.replace, so that a caller who changes an object does not change the store, as with SQLite, which stores values. open_loan_of and open_loans_of filter on returned is None; save replaces the open loan of the same book. The contract test adds two loans of two readers, changes the caller’s copy, finds the stored due date unchanged, saves the first loan as returned and checks that it is no longer open and that the other reader’s loan is still there. It is one function, called with each repository: a fake that passes the same contract as the real implementation can stand in for it in every other test.
Exercise 30.7 ★★
Show that 100 % branch coverage need not reveal a bug: give a version of is_leap with an error, and a test suite that takes every branch of it, passes, and misses the error.
Solution
Solution of Exercise 30.7.
Facts used: a branch is covered when each way of each conditional jump is taken. Take is_leap(year) = year % 4 == 0 and year % 100 != 0, which forgets that years divisible by 400 are leap. The suite is_leap(2024) true, is_leap(2026) false and is_leap(1900) false passes, since these are the right answers, and takes both ways of each comparison: 2026 makes the first false, 2024 makes both true, 1900 makes the second false. So it covers every statement and every branch, and the function is wrong on 2000. A test measures the coverage with the chapter’s tool and checks the three answers.
Exercise 30.8 ★★
How many mutants does the chapter’s mutator make of an expression with operators of its table and integer constants? Check on a + b * c < d - 1. How many would a mutator make that replaces each comparison by each of the five others?
Solution
Solution of Exercise 30.8.
One mutant per operator of the table and one per integer constant: , since each operator in the table has exactly one replacement and each constant becomes . For a + b * c < d - 1: the operators +, *, < and -, and the constant 1, so 5, as a test checks. A mutator that replaces each comparison by each of the five others makes mutants per comparison instead of 1: with comparisons, other operators and constants, .
Exercise 30.9 ★★
Write the two intermediate states of the refactoring of the fines report, after the first and the second step, and check with a property-based test that all four versions print the same report for every rate, cap, grace period and day.
Solution
Solution of Exercise 30.9.
exercises/ex9_steps.py holds report_step1, with the fine computed by an extracted function fine(late, rate, cap), and report_step2, with the line formatted by an extracted line. Each step changes one thing, so that if the tests fail, the cause is that step. The property test draws 200 combinations of rate (0 to 100 cents), cap (none, or 0 to 1,000), grace (0 to 30 days) and day (up to 120 days after 5 January) and checks that the four versions print the same report on the same four loans. Introducing the parameter object, the third step, changes the signature: every caller must change with it, which is why it comes last, once the body is simple.
Exercise 30.10 ★★★
merge_sort in exercises/ex10_metamorphic.py has an injected bug. Without looking for it, write three metamorphic relations for a sort: permuting the input, doubling it, adding a constant to every element. Run them on random lists; which relation finds the bug, and what is it?
Solution
Solution of Exercise 30.10.
On 500 random lists of 1 to 8 numbers from 0 to 9, the permutation and the shift relations always hold, and the doubling relation fails on every list: sorting xs + xs must give each element of the sorted list twice, and the sort returns fewer. The bug is in the merge: when the two heads are equal, it takes one and advances both sides, so it drops one copy of every equal pair it meets. Permuting or shifting the input does not change which values are equal, so those relations see the same wrong output on both sides; doubling guarantees duplicates. The sorted builtin satisfies all three, as a test checks. A good set of relations varies what the bug is likely to depend on: here, repeated values.
Exercise 30.11 ★★★
Let be a class of mutation operators and a correct program on which a test suite passes. Prove that if kills every mutant of by that is not equivalent to , then fails on every program that differs from by one change of class and computes something else. Why does running the mutator on the program under test, rather than on the correct program nobody has, still give evidence of this?
Solution
Solution of Exercise 30.11.
Facts used: a test suite fails on a program if at least one of its tests fails. Let differ from by one change of class and compute a different function from . Then is, by definition, a mutant of by , and it is not equivalent to . By hypothesis kills it: at least one test of fails on . So every such single fault is detected. The hypothesis is about mutants of the correct program, which nobody has. What the mutator runs on is the program under test, ; if contains one fault of class and the class contains the inverse of each of its changes, then itself is a mutant of , and a suite that kills every non-equivalent mutant of while passing on fails on : its tests agree with the faulty program, not the correct one. That is why survivors, and not the score alone, are read: each survivor is a change that the tests cannot see, and either it is equivalent, or the tests have a gap at that place. The claim that real faults are close to such changes is a hypothesis about programmers, not a theorem.
Exercise 30.12 ★★★
Extend the coverage tool into LineCounts, which counts how many times each line runs. Test it on day_number(2026, 3, 1), whose counts you can compute by hand, and explain the count of the for line.
Solution
Solution of Exercise 30.12.
exercises/ex12_counts.py overrides _line to add one to a counter at each event and not to return DISABLE, so that the interpreter keeps reporting the line. For day_number(2026, 3, 1): the first two lines run once, the body of the loop twice (months 1 and 2), the call to days_in_month inside it runs its if and its table lookup twice, and the return once; is_leap’s line runs once, for February, through month == 2 and is_leap(year). The for line runs 3 times: once for each of the two turns and once more for the exit, when range is exhausted. A test checks all eight counts. Without DISABLE the tool slows the program much more: every line of every run calls back into Python.
30.7 Weekend problem
Problem 30.1
Weekend problem — Mutation testing the town’s date library
The town hall’s date library, towndate.py, has five tests, and its maintainer says that it is “fully tested: 100 % coverage”. The problem measures what the tests check, finds what they miss, and closes the gaps.
def is_leap(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def days_in_month(year, month):
if month == 2 and is_leap(year):
return 29
return MONTH_DAYS[month - 1]
def is_valid(year, month, day):
return 1 <= month <= 12 and 1 <= day <= days_in_month(year, month)
def day_number(year, month, day):
"""Days since 31 December of year 0: 1 January of year 1 is day 1."""
y = year - 1
n = 365 * y + y // 4 - y // 100 + y // 400
for m in range(1, month):
n += days_in_month(year, m)
return n + day
def days_between(a, b):
"""The number of days between dates a and b, in either order."""
n = day_number(*b) - day_number(*a)
return n if n >= 0 else -n
def weekday(date):
return WEEKDAYS[(day_number(*date) - 1) % 7] # 1 January of year 1 was a Monday
MONTH_DAYS, the lengths of the twelve months of a common year, and lines 5 to 13 the names of the days, from Monday. code/bachelor-3/30-software-engineering/listings/towndate.py$ python date_mutation.py
first suite, coverage:
statements (16, 16)
missed lines []
branches (15, 18)
missed branches at lines [17, 27, 27]
first suite: 46 of 62 mutants killed
survived, line 4: 30 -> 31
survived, line 4: 31 -> 32
survived, line 17: year % 100 -> year // 100
survived, line 17: 100 -> 101
survived, line 17: 0 -> 1
survived, line 17: year % 400 == 0 -> year % 400 != 0
survived, line 17: year % 400 -> year // 400
survived, line 17: 400 -> 401
survived, line 17: 0 -> 1
survived, line 27: 1 <= month <= 12 -> 1 <= month < 12
survived, line 27: 1 <= day <= days_in_month(year, month) -> 1 < day <= days_in_month(year, month)
survived, line 27: 1 -> 2
survived, line 33: 100 -> 101
survived, line 33: 400 -> 401
survived, line 42: n >= 0 -> n > 0
survived, line 42: 0 -> 1
with the new tests: 60 of 62 mutants killed
survived, line 42: n >= 0 -> n > 0
survived, line 42: 0 -> 1
Part I — The library and its tests.
- State the leap-year rule that line 17 implements, and the requirement each of the five first tests checks.
- Why does
day_numberaddy // 4 - y // 100 + y // 400to ? - Check by hand that
days_between((2026, 1, 1), (2026, 3, 1))is 59. - Which of the first tests is an oracle test against a known value, and which checks a relation?
- Why does
days_betweenreturn the absolute value? - What does
weekdayassume about the year 1, and why can that be checked against Python’sdatetime?
Part II — Coverage.
- What fraction of statements does the first suite run?
- Which three branches does it never take? Say which inputs would take each.
- Why does the test of 2024 never evaluate
year % 400 == 0? - Is the maintainer’s claim true? What does it prove about the leap rule?
- Give a wrong leap rule that the first suite passes with the same coverage.
- Which survivors of Part III fall on lines whose branches are fully covered?
Part III — Mutation analysis.
- How many mutants are made, and how many does the first suite kill? Give the score.
- Why do the mutants of the month table on line 4 survive, and which months are they?
- Why do 7 mutants of line 17 survive?
- Why do the mutants
y // 100toy // 101andy // 400toy // 401on line 33 survive, althoughweekdayuses the absolute day number? - Which survivors of line 27 point to missing boundary tests?
- Classify the 16 survivors by the requirement they show untested.
Part IV — New tests and equivalent mutants.
- What do the two new tests check, and which oracle does the first one use?
- Which of the two new tests kills each survivor of lines 4, 17, 27 and 33, and why does comparing
day_numberwith the calendar on the first of each month of eight chosen years suffice for most of them? - How many mutants survive the new suite?
- Prove that the two survivors are equivalent to the original.
- What is the score over the non-equivalent mutants?
- Sum up: what statement coverage does the first suite reach, how many of the mutants does it kill, how many do the two new tests raise it to, and how many survivors are equivalent?
Solution
Solution of Problem 30.1.
1. A year is leap if it is divisible by 4, except that a year divisible by 100 is not, unless it is divisible by 400. The first tests check that 2024 is leap and 2026 is not; the lengths of February in both years and of January; the validity of 31 January and the invalidity of 30 February and of month 13; the 59 days from 1 January to 1 March 2026, in both orders; and that 20 November 2026 is a Friday.
2. counts the days of the complete years if none were leap; is the number of leap years among : the multiples of 4, minus the multiples of 100, plus back the multiples of 400.
3. Both dates are in 2026, so the year terms cancel: .
4. All five compare with values known in advance; the test in both orders also checks a relation, the symmetry of days_between.
5. Its specification says “in either order”; the absolute value makes it symmetric.
6. That 1 January of year 1 was a Monday in the proleptic Gregorian calendar, day number 1. Python’s datetime.date uses the same calendar and the same day numbers, through toordinal, so its weekday is an oracle.
7. All of them: 16 of 16.
8. At line 17, year % 100 != 0 is never false, so the way out of its jump that goes on to year % 400 == 0 is never taken (that last comparison has no jump of its own: its value is returned); at line 27, 1 <= month is never false (month 0) and 1 <= day is never false (day 0). The inputs is_leap(1900) and is_leap(2000), is_valid(2026, 0, 1) and is_valid(2026, 1, 0) take them.
9. Because 2024 is not divisible by 100: year % 100 != 0 is true, and or stops there.
10. True for statements, not for branches (15 of 18). It proves nothing about the century rule: no test has a year divisible by 100.
11. year % 4 == 0, alone: it gives the same answers on 2024 and 2026, and runs the same statements.
12. Lines 4 and 33 have no branch and line 42’s two are both taken, yet 6 mutants survive there: 2 on each line.
13. 62 mutants, 46 killed: a score of .
14. The first tests use the lengths of January and February directly, and the weekday of 20 November sums those of January to October; the lengths of November (30) and December (31) are never used. They are the two survivors.
15. The only years tested are 2024 and 2026: 2026 stops at year % 4; for 2024, year % 100 != 0 stays true when % becomes // (), when 100 becomes 101 () and when 0 becomes 1 (), and the 400 part, with its four mutants, is never evaluated. Only the mutants of year % 4 == 0 and of and, or and != are seen.
16. For 20 November 2026, , and , : on that one date the mutants give the same day number. The other tests compare two dates of the same year, where the year terms cancel.
17. 1 <= month <= 12 to 1 <= month < 12: December is never checked valid. 1 <= day to 1 < day, and the constant 1 of 1 <= day to 2: the first day of a month is never checked valid.
18. The month table, November and December (2); the leap rule for centuries (7 on line 17, 2 on line 33); the boundaries of validity, December and day 1 (3); and the 2 mutants of line 42, which Part IV shows are no gap.
19. The first compares day_number with date.toordinal, the calendar’s own day number, on the first of each month of the years 1, 100, 101, 400, 401, 1900, 2000 and 2026; the second checks that 1 January and 31 December are valid and that day 0, 32 December and 29 February 2026 are not.
20. The first test kills every survivor of lines 17 and 33 and November’s: the years 1900 and 2000 test the century rule on 1 March, the years 100, 101, 400 and 401 make and , and and , differ, and 1 December sums November. The second kills the boundary mutants of line 27 and December’s length, which no day number uses, through 32 December.
21. 2 of 62: both on line 42.
22. Facts used: for an integer , . The original returns n if n >= 0 else -n; the mutants test n > 0 and n >= 1, which are the same condition on integers. They differ from the original only at , where the original returns and the mutants return . So the three functions are equal on every integer input, and the mutants are equivalent.
23. 60 killed of non-equivalent mutants: 100 %.
24. The first suite runs 100 % of statements yet kills only 46 of the 62 mutants; the two new tests raise the score to 60 of 62, and the 2 survivors are proved equivalent.
Istilah yang didefinisikan dalam bab ini
- Continuous integration, code review, refactoring, characterisation test, technical debt
- Design pattern, strategy pattern, observer pattern, adapter pattern, model–view–controller
- Integration test, test double, metamorphic testing
- Modularity, coupling, cohesion, information hiding, dependency inversion
- Mutation testing, mutant, mutation score, equivalent mutant
- Property-based test, shrinking
- Requirement, use case
- UML class diagram, sequence diagram