Testing
Writing tests that find bugs: a small test harness with #line, choosing cases at the edges, testing errors, test-driven development, random property tests, fakes for dependencies, tracing, and Swift Testing.
- CS61A
- Software Testing · Software Tracing
- Swift book
- Functions
- Documentation
- Swift Testing
Every lab in this tutorial ended its solutions with assert lines, and every
project came with a test runner. You have been reading tests since Lesson 1.
This lesson is about writing them: what to test, how to make a failure easy
to understand, and a few techniques that find bugs no hand-picked example
would.
A caution from Edsger Dijkstra is worth keeping in mind throughout: testing can show that bugs are present, never that they are absent. A passing test suite means only that the cases you thought of work. Good tests are the ones that think of the cases you did not.
What a test is
A test has three parts: an input, the expected result, and a check that compares them.
func clamp(_ value: Int, _ low: Int, _ high: Int) -> Int {
min(max(value, low), high)
}
assert(clamp(5, 0, 10) == 5) // inside the range
assert(clamp(-3, 0, 10) == 0) // below
assert(clamp(42, 0, 10) == 10) // above
assert(clamp(10, 0, 10) == 10) // exactly on the edge
assert is a fine start, but it has two weaknesses. It stops the program at
the first failure, so one broken case hides every other result. And its
message says only that the assertion failed, not what the value actually
was.
A test harness in a few lines
A better check keeps going, counts results, and shows both values. The projects’ runners are built like this:
var passed = 0
var failed = 0
func expect<T: Equatable>(_ actual: T, _ expected: T, line: Int = #line) {
if actual == expected {
passed += 1
} else {
failed += 1
print("✗ line \(line): expected \(expected), got \(actual)")
}
}
func reversedWords(_ text: String) -> String {
text.split(separator: " ").reversed().joined(separator: " ")
}
expect(reversedWords("hello big world"), "world big hello")
expect(reversedWords(""), "")
expect(reversedWords(" two spaces "), "spaces two")
print("\(passed) passed, \(failed) failed")
This prints:
✗ line 19: expected spaces two, got spaces two
2 passed, 1 failed
#line as a default argument is the trick. A default argument is
evaluated where the function is called, so #line becomes the line of
the expect call, not a line inside expect. Each failure points at the
test that failed. #file and #function work the same way.
And the harness found something. split drops empty pieces, so the double
space in the input is lost. Whether that is a bug depends on what
reversedWords is supposed to do; the test made us decide.
What would Swift print?
func whereAmI(line: Int = #line) -> Int {
line
}
let a = whereAmI()
let b = whereAmI()
print(a, b)Show answer and explanation
Answer4 5
Each call’s #line is the line of the call itself: lines 4 and 5 of this
program. If the default were the line inside the function, both would be 2.
Choosing test cases
The inputs that find bugs are rarely the typical ones. For each function, think in categories:
- Typical cases, one or two, to show it works at all.
- Edges: the empty array, the empty string, zero, one element, the largest and smallest values.
- Boundaries, just below, at, and just above every point where the behavior changes. Off-by-one errors live here.
- Special cases in the specification, each rule and each exception to a rule.
- Invalid input, and whether the function rejects it the way it should.
Leap years show why the specification matters. A year is a leap year if it is divisible by 4, except years divisible by 100, except years divisible by 400. Each rule needs a test, and so does each exception:
func isLeapYear(_ year: Int) -> Bool {
year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
}
assert(isLeapYear(2024)) // divisible by 4
assert(!isLeapYear(2023)) // not divisible by 4
assert(!isLeapYear(1900)) // divisible by 100, not by 400
assert(isLeapYear(2000)) // divisible by 400
Leave out the 1900 test and a version without the 100 rule passes. Leave
out 2000 and a version without the 400 rule passes. Four tests, one per
rule, is the minimum that can tell a correct function from the plausible
wrong ones.
Testing errors
A function that throws should be tested for the errors too. The check is whether calling it throws, and which error:
enum AgeError: Error, Equatable {
case notANumber
case negative
}
func parseAge(_ text: String) throws(AgeError) -> Int {
guard let age = Int(text) else { throw .notANumber }
guard age >= 0 else { throw .negative }
return age
}
func expectError<E: Error & Equatable, T>(_ expected: E, line: Int = #line, _ body: () throws -> T) {
do {
let value = try body()
print("✗ line \(line): expected \(expected), but got the value \(value)")
} catch let error as E where error == expected {
// the right error: the test passes
} catch {
print("✗ line \(line): expected \(expected), got \(error)")
}
}
expectError(AgeError.notANumber) { try parseAge("ten") }
expectError(AgeError.negative) { try parseAge("-4") }
expectError(AgeError.negative) { try parseAge("30") }
// ✗ line 25: expected negative, but got the value 30
The last check is deliberately wrong, to show what a failure looks like.
catch let error as E where error == expected is a pattern with a
condition, as in Lesson 19: it matches only the expected error, and anything
else falls through to the final catch. Not throwing at all is a failure too, which is exactly what assert(false, …)
after the call was doing by hand in Lesson 21.
Test-driven development
Tests do not have to come last. In test-driven development, you write a failing test for the next small piece of behavior, then the simplest code that passes it, then clean up, and repeat. Writing the test first forces you to decide what the function should do before deciding how, and every piece of the finished code exists because a test needed it.
Suppose we want plural(_:_:), which writes counts like “1 cat” and “3
cats”. Start with the tests, in order of difficulty:
assert(plural(1, "cat") == "1 cat")
assert(plural(3, "cat") == "3 cats")
assert(plural(0, "cat") == "0 cats")
assert(plural(2, "box") == "2 boxes")
The first passes with "\(count) \(word)". The second needs an s when the
count is not 1. The third checks that the rule is “not 1” rather than “more
than 1”. The fourth needs a new rule for words ending in x:
func plural(_ count: Int, _ word: String) -> String {
if count == 1 {
return "1 \(word)"
}
let suffix = word.hasSuffix("x") || word.hasSuffix("s") ? "es" : "s"
return "\(count) \(word)\(suffix)"
}
assert(plural(1, "cat") == "1 cat")
assert(plural(3, "cat") == "3 cats")
assert(plural(0, "cat") == "0 cats")
assert(plural(2, "box") == "2 boxes")
assert(plural(2, "bus") == "2 buses")
The s rule came in without a test that asked for it, so a new test was
added for it right away. If the code does something, a test should say so.
Property-based testing
Hand-picked tests check the cases you thought of. Property-based testing checks a rule that must hold for every input, on hundreds of random inputs. For a sorting function, three properties together pin the answer down:
- the result is in order;
- it has the same number of elements as the input;
- it has the same elements (counting repeats).
Here is a sort with a subtle bug, tested with random arrays. The random numbers come from a seeded generator, so a failure can be reproduced exactly:
struct SeededGenerator: RandomNumberGenerator {
var state: UInt64
mutating func next() -> UInt64 { // SplitMix64
state &+= 0x9E3779B97F4A7C15
var z = state
z = (z ^ (z >> 30)) &* 0xBF58476D1CE4E5B9
z = (z ^ (z >> 27)) &* 0x94D049BB133111EB
return z ^ (z >> 31)
}
}
// Selection sort by moving each smallest value into a new array.
func buggySort(_ values: [Int]) -> [Int] {
var remaining = values
var result: [Int] = []
while let smallest = remaining.min() {
result.append(smallest)
remaining.removeAll { $0 == smallest } // the bug
}
return result
}
var random = SeededGenerator(state: 61)
for trial in 1...100 {
let input = (0..<Int.random(in: 0...6, using: &random)).map { _ in Int.random(in: 0...9, using: &random) }
let output = buggySort(input)
let inOrder = zip(output, output.dropFirst()).allSatisfy { $0 <= $1 }
if !inOrder || output.count != input.count {
print("trial \(trial) fails for \(input): got \(output)")
break
}
}
Within a few trials it finds an input with a repeated value: removeAll
removes every copy of the smallest value, so duplicates vanish. A test
suite of distinct numbers, which is what most people write by hand, would
never have caught it.
Good properties to look for:
- Round trips: parsing what you printed gives back the original, like
Lesson 20’s
showandparse. - Invariants: a binary search tree stays sorted after any insertion.
- Comparison with a simple version: a fast, clever function returns the same as a slow, obviously correct one. Lesson 18’s memoized functions can be checked against the plain recursive versions this way.
Testing code that depends on the world
A function that reads the clock, the network, or a random number cannot be
tested with fixed expectations, since its answer changes. The fix is to pass
the dependency in, so that a test can pass a fake one. Cats did this with
the upload function in reportProgress. A protocol works too:
protocol Clock {
var hour: Int { get }
}
struct FixedClock: Clock {
let hour: Int
}
func greeting(_ clock: some Clock) -> String {
switch clock.hour {
case 5..<12: "Good morning"
case 12..<18: "Good afternoon"
default: "Good evening"
}
}
assert(greeting(FixedClock(hour: 9)) == "Good morning")
assert(greeting(FixedClock(hour: 12)) == "Good afternoon")
assert(greeting(FixedClock(hour: 23)) == "Good evening")
assert(greeting(FixedClock(hour: 4)) == "Good evening")
The real program passes a clock that reads the system time; the tests pass
FixedClock, a test double, and can check midnight without waiting for
it. Designing for tests like this tends to improve the design anyway: the
function’s dependencies are now listed in its signature.
Tracing
CS61A’s tracing lecture shows how to watch a recursive function run. Printing each call and each return, indented by depth, turns a call tree you had to imagine into one you can read:
var depth = 0
func factorial(_ n: Int) -> Int {
let indent = String(repeating: " ", count: depth)
print("\(indent)factorial(\(n))")
depth += 1
defer {
depth -= 1
}
let result = n <= 1 ? 1 : n * factorial(n - 1)
print("\(indent)→ \(result)")
return result
}
_ = factorial(3)
// factorial(3)
// factorial(2)
// factorial(1)
// → 1
// → 2
// → 6
Lesson 21’s defer makes sure the depth goes back down whichever way the
function returns. When a recursive function gives a wrong answer, a trace of
a small input shows which call first returned something wrong, and the
bug is in that call.
Swift Testing
For real projects, Swift comes with a testing library, Swift Testing.
Tests live in a package’s Tests folder, which Lesson 24 sets up, and run
with swift test. A test is a function marked @Test, and #expect is the
check:
import Testing
@testable import Calculator
@Test func addition() {
#expect(run("(+ 1 2)") == "3")
}
@Test func divisionByZeroIsAnError() {
#expect(run("(/ 1 0)") == "Error: division by zero")
}
@Test(arguments: [("(- 5)", "-5"), ("(* 2 3 4)", "24"), ("(+)", "0")])
func examples(input: String, expected: String) {
#expect(run(input) == expected)
}
#expect is a macro, so when it fails it can show the whole expression and
the value of each part, like our expect but more thoroughly. Tests keep
running after a failure, and each argument of a parameterized test is
reported separately. #expect(throws: SomeError.self) { … } checks that
code throws, and try #require(…) stops a test early when a value it needs
is missing. Older projects use XCTest, with XCTAssertEqual instead of
#expect; the ideas are the same.
Put the lines in order
Put the lines in order so the program prints 1 failed.
func expect(_ actual: Int, _ expected: Int) {}print(failed, "failed")}expect(-7 / 2, -4)failed += 1if actual != expected {var failed = 0
Show the correct program
var failed = 0
func expect(_ actual: Int, _ expected: Int) {
if actual != expected {
failed += 1
}
}
expect(-7 / 2, -4)
print(failed, "failed")Lab 22: Testing
Q0: What would Swift print?
What would Swift print?
func isEven(_ n: Int) -> Bool {
n % 2 == 0
}
var failures = 0
for n in [-2, -1, 0, 1, 2] {
let expected = [-2, 0, 2].contains(n)
if isEven(n) != expected {
failures += 1
}
}
print(failures)Show answer and explanation
Answer0
-1 % 2 is -1 in Swift, not 1, but isEven only compares with 0, so it
is still right. A version that tested n % 2 == 1 for odd numbers would fail
for −1: exactly the kind of case worth testing.
What would Swift print?
let values = [3, 1, 2]
let twice = values.reversed().reversed()
let sortedTwice = values.sorted().sorted()
print(Array(twice) == values, sortedTwice == values.sorted())Show answer and explanation
Answertrue true
Two properties that hold for any array: reversing twice gives back the original, and sorting is idempotent, so sorting a sorted array changes nothing. Both make good property tests.
Q1: The missing test
This isLeapYear passes all three tests, but it is wrong. Add the one test
that fails for it, then fix the function.
func isLeapYear(_ year: Int) -> Bool {
year % 4 == 0 && year % 100 != 0
}
assert(isLeapYear(2024))
assert(!isLeapYear(2023))
assert(!isLeapYear(1900))
Show solution
func isLeapYear(_ year: Int) -> Bool {
year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
}
assert(isLeapYear(2024))
assert(!isLeapYear(2023))
assert(!isLeapYear(1900))
assert(isLeapYear(2000)) // the missing test: divisible by 400The buggy version says 2000 was not a leap year. Each rule in the specification needs a test that only a correct implementation of that rule can pass.
Q2: A test runner
Write a TestRun structure with a mutating method expect(_:_:_:) taking
the actual value, the expected value, and a name. It records failures and
counts, and its summary property is "3 passed" when everything passed,
or "2 passed, 1 failed: name" listing the names of failures, separated by
commas.
Show solution
struct TestRun {
private var passed = 0
private var failures: [String] = []
mutating func expect<T: Equatable>(_ actual: T, _ expected: T, _ name: String) {
if actual == expected {
passed += 1
} else {
failures.append(name)
}
}
var summary: String {
if failures.isEmpty {
return "\(passed) passed"
}
return "\(passed) passed, \(failures.count) failed: " + failures.joined(separator: ", ")
}
}
var good = TestRun()
good.expect(1 + 1, 2, "addition")
good.expect("ab" + "c", "abc", "strings")
assert(good.summary == "2 passed")
var bad = TestRun()
bad.expect(7 / 2, 3, "integer division")
bad.expect([1, 2].count, 3, "count")
bad.expect(-7 % 3, 2, "remainder")
assert(bad.summary == "1 passed, 2 failed: count, remainder")The last test is a real surprise to many programmers: -7 % 3 is -1 in
Swift, because the remainder takes the sign of the dividend. A test runner
that keeps going is useful exactly because one wrong expectation does not
hide the others.
Q3: Tests first
Here are the tests for roman(_:), which writes numbers from 1 to 3999 as
Roman numerals. Write the function to pass them. (Hint: go through the
values 1000, 900, 500, 400, …, 1 from largest to smallest, subtracting each
as many times as it fits.)
assert(roman(1) == "I")
assert(roman(4) == "IV")
assert(roman(9) == "IX")
assert(roman(14) == "XIV")
assert(roman(40) == "XL")
assert(roman(1994) == "MCMXCIV")
assert(roman(2026) == "MMXXVI")
assert(roman(3999) == "MMMCMXCIX")
Show solution
func roman(_ number: Int) -> String {
precondition((1...3999).contains(number), "Roman numerals go from 1 to 3999")
let 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")]
var remaining = number
var result = ""
for (value, letters) in values {
while remaining >= value {
result += letters
remaining -= value
}
}
return result
}
assert(roman(1) == "I")
assert(roman(4) == "IV")
assert(roman(9) == "IX")
assert(roman(14) == "XIV")
assert(roman(40) == "XL")
assert(roman(1994) == "MCMXCIV")
assert(roman(2026) == "MMXXVI")
assert(roman(3999) == "MMMCMXCIX")Putting the subtractive pairs like CM and IV into the table turns every
special case into an ordinary step. The tests for 4, 9, and 40 are the ones
that forced that idea: 1, 14, and 2026 pass without it.
Q4: Checking a property
Write findCounterexample(trials:seed:property:), which generates random
arrays of 0 to 8 numbers from 0 to 9, and returns the first array for which
property is false, or nil. Use it to find a bug in this function, which
should remove repeated values while keeping the first occurrence of each, in
order.
func removeDuplicates(_ values: [Int]) -> [Int] {
Array(Set(values)).sorted()
}
Show solution
struct SeededGenerator: RandomNumberGenerator {
var state: UInt64
mutating func next() -> UInt64 {
state &+= 0x9E3779B97F4A7C15
var z = state
z = (z ^ (z >> 30)) &* 0xBF58476D1CE4E5B9
z = (z ^ (z >> 27)) &* 0x94D049BB133111EB
return z ^ (z >> 31)
}
}
func findCounterexample(trials: Int, seed: UInt64, property: ([Int]) -> Bool) -> [Int]? {
var random = SeededGenerator(state: seed)
for _ in 0..<trials {
let count = Int.random(in: 0...8, using: &random)
let input = (0..<count).map { _ in Int.random(in: 0...9, using: &random) }
if !property(input) {
return input
}
}
return nil
}
func removeDuplicates(_ values: [Int]) -> [Int] {
Array(Set(values)).sorted()
}
// A simple, obviously correct version to compare against.
func removeDuplicatesSlowly(_ values: [Int]) -> [Int] {
var result: [Int] = []
for value in values where !result.contains(value) {
result.append(value)
}
return result
}
let bad = findCounterexample(trials: 100, seed: 1) { removeDuplicates($0) == removeDuplicatesSlowly($0) }
assert(bad != nil) // for example, [3, 1] comes back as [1, 3]
assert(findCounterexample(trials: 500, seed: 1) { removeDuplicatesSlowly($0) == removeDuplicatesSlowly(removeDuplicatesSlowly($0)) } == nil)The buggy version loses the original order, because a Set has none and
sorted() puts back a different one. Any input that is not already sorted
shows it. The property used is comparison with a simple version; the
second check is idempotence: removing duplicates twice changes nothing.
Q5: A fake sensor
A thermostat turns the heating on below 18 degrees, off above 21, and
otherwise leaves it as it was, so it does not flick on and off around a single
temperature. Write Thermostat.update() using a sensor passed in as a
protocol, then test it with a fake sensor whose temperature the test controls.
protocol TemperatureSensor {
var celsius: Int { get }
}
Show solution
protocol TemperatureSensor {
var celsius: Int { get }
}
final class FakeSensor: TemperatureSensor {
var celsius = 20
}
struct Thermostat {
let sensor: any TemperatureSensor
private(set) var heating = false
init(sensor: any TemperatureSensor) {
self.sensor = sensor
}
mutating func update() {
if sensor.celsius < 18 {
heating = true
} else if sensor.celsius > 21 {
heating = false
}
}
}
let sensor = FakeSensor()
var thermostat = Thermostat(sensor: sensor)
var history: [Bool] = []
for temperature in [20, 17, 19, 21, 22, 20] {
sensor.celsius = temperature
thermostat.update()
history.append(thermostat.heating)
}
assert(history == [false, true, true, true, false, false])FakeSensor is a class so that the test and the thermostat share it: the
test changes the temperature, and the thermostat sees it (Lesson 14’s
reference semantics, used on purpose). The sequence checks both thresholds
and, with 19 and 20, that the heating keeps its state between them.
Q6 (optional): Shrinking
A random counterexample is often longer than it needs to be. Write
shrink(_:property:), which takes a failing input and repeatedly tries
removing one element; whenever the smaller array still fails, keep it and
start again. Return an array that fails but from which no single element can
be removed without passing.
Show solution
func shrink(_ input: [Int], property: ([Int]) -> Bool) -> [Int] {
precondition(!property(input), "shrink needs a failing input")
var current = input
var changed = true
while changed {
changed = false
for index in current.indices {
var smaller = current
smaller.remove(at: index)
if !property(smaller) {
current = smaller
changed = true
break
}
}
}
return current
}
func buggySort(_ values: [Int]) -> [Int] {
var remaining = values
var result: [Int] = []
while let smallest = remaining.min() {
result.append(smallest)
remaining.removeAll { $0 == smallest }
}
return result
}
let keepsCount: ([Int]) -> Bool = { buggySort($0).count == $0.count }
assert(shrink([5, 3, 9, 3, 1, 7], property: keepsCount) == [3, 3])The smallest failing input, two equal numbers, is also the clearest explanation of the bug. Real property-testing libraries shrink the same way, and also try smaller values, not just fewer of them.
What’s next
The tests in this lesson lived next to the code they tested. The last lesson of the tutorial separates them properly: a Swift package with a library, a command-line program, and a test suite, ready for other people to use.