Testing data structures
Working the way CS61B does: a package for the unit’s data structures, Swift Testing suites and parameterized tests, test-driven selection sort, randomized comparison against a trusted reference, testing interfaces rather than implementations, and git.
- CS61B
- Testing · Packages · Textbook Ch. 4
- Swift book
- Access Control
- Documentation
- Swift Testing · Swift Package Manager · Xcode
A data structure has many operations that can be called in any order, and a bug may show up only after a particular sequence of a hundred of them. The examples that come to mind first, adding three things and removing them, almost never find it. CS61B treats testing as part of building a data structure, not something done afterwards, and so will we. This lesson extends Lesson 23 with the tools the rest of the unit needs.
A package for the unit
The data structures of this unit will live in one package, growing lesson by lesson:
mkdir DataStructures
cd DataStructures
swift package init --type library --name DataStructures
Library code goes in Sources/DataStructures, tests in
Tests/DataStructuresTests. swift test runs all of them;
swift test --filter SelectionSortTests runs only the tests whose names
match. This package has no user interface, so it builds and tests on any
system Swift supports.
Swift Testing, in more depth
Lesson 23 introduced @Test and #expect. Real test files group their tests
and share setup, and a few more tools make failures easier to read.
import Testing
@testable import DataStructures
@Suite("Selection sort")
struct SelectionSortTests {
@Test func sortsAnArray() {
#expect(selectionSort([4, 1, 3, 2]) == [1, 2, 3, 4])
}
@Test(arguments: [[], [7], [2, 2, 1], [-1, -5, 0]])
func matchesTheStandardLibrary(input: [Int]) {
#expect(selectionSort(input) == input.sorted())
}
@Test func findsTheSmallest() throws {
let values = [5, 3, 9, 3]
#expect(indexOfSmallest(in: values, from: 0) == 1)
#expect(indexOfSmallest(in: values, from: 2) == 3)
let first = try #require(values.first)
#expect(first == 4) // wrong on purpose
}
}
@Suitegroups tests in a type. A suite can be a structure with properties set up in itsinit; Swift Testing creates a fresh instance for every test, so tests cannot affect one another.- Parameterized tests take
arguments:, and each argument runs and is reported as a separate case. Four edge cases cost one test function. #requireis#expectthat stops the test when it fails. It also unwraps optionals:try #require(values.first)gives the first element, or ends the test right there if there is none, so later lines never run with a meaningless value.@testable importlets tests useinternalhelpers likeindexOfSmallest, which users of the library cannot see.
When an expectation fails, swift test shows the expression and the value of
each part of it:
✘ Test findsTheSmallest() recorded an issue at DataStructuresTests.swift:20:9:
Expectation failed: first == 4
first == 4 → false
first → 5
✘ Test run with 3 tests in 1 suite failed after 0.001 seconds with 1 issue.
(The exact symbols at the start of each line depend on your terminal.) The
message says which line, what was expected, and what first actually was:
everything needed to start fixing it, without adding a single print.
Test-driven selection sort
CS61B’s testing lecture builds selection sort test first, and it is a good model for how to grow a data structure. Selection sort finds the smallest item, swaps it to the front, and repeats on the rest.
Start with a test of the whole thing, which fails because nothing exists yet. Then notice that the algorithm has a piece that can be tested alone, finding the smallest item from some position on, and write that piece with its own test first:
func indexOfSmallest(in values: [Int], from start: Int) -> Int {
var best = start
for i in start..<values.count where values[i] < values[best] {
best = i
}
return best
}
func selectionSort(_ values: [Int]) -> [Int] {
var result = values
for i in result.indices {
result.swapAt(i, indexOfSmallest(in: result, from: i))
}
return result
}
// Tests for the helper, then for the whole sort.
assert(indexOfSmallest(in: [5, 3, 9, 3], from: 0) == 1)
assert(indexOfSmallest(in: [5, 3, 9, 3], from: 2) == 3)
assert(indexOfSmallest(in: [8], from: 0) == 0)
assert(selectionSort([4, 1, 3, 2]) == [1, 2, 3, 4])
assert(selectionSort([]) == [])
assert(selectionSort([2, 2, 1]) == [1, 2, 2])
print("all passed")
Testing the helper separately is a unit test: it checks one small piece,
so when it fails, the bug can only be in a few lines. The test of
selectionSort is closer to an integration test: it checks pieces
working together. Both are needed. A sort that is wrong because of the helper
fails both tests, and the helper’s failure says where to look.
What would Swift print?
func indexOfSmallest(in values: [Int], from start: Int) -> Int {
var best = start
for i in start..<values.count where values[i] <= values[best] {
best = i
}
return best
}
print(indexOfSmallest(in: [5, 3, 9, 3], from: 0))Show answer and explanation
Answer3
With <=, a later equal value replaces the current best, so the last
smallest element wins. The sort would still be correct, but the test
expecting 1 fails, and that is right: a test pins down the exact behavior you
promised, and changing it should be a deliberate decision.
Comparing against a trusted reference
Hand-written tests check the sequences you thought of. For a data structure, a stronger technique is randomized comparison testing, which CS61B uses for its deque projects: perform a long random sequence of operations on your structure and on a simple structure you trust, and check after every step that they agree. When they do not, the list of operations so far is an exact recipe for the bug.
Here is a queue stored in a ring buffer: an array used in a circle, where the front can be anywhere and the back wraps around to the start. It has a bug. The queue works for many inputs, and the bug is in the one place that is hard to think about.
struct RingQueue {
private var items = [Int?](repeating: nil, count: 2)
private var head = 0
private(set) var count = 0
mutating func enqueue(_ value: Int) {
if count == items.count {
grow()
}
items[(head + count) % items.count] = value
count += 1
}
mutating func dequeue() -> Int? {
guard count > 0 else {
return nil
}
let value = items[head]
items[head] = nil
head = (head + 1) % items.count
count -= 1
return value
}
private mutating func grow() {
var bigger = [Int?](repeating: nil, count: items.count * 2)
for i in 0..<count {
bigger[i] = items[i] // the bug
}
items = bigger
head = 0
}
}
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)
}
}
var random = SeededGenerator(state: 61)
var queue = RingQueue()
var reference: [Int] = [] // an array is the queue we trust
var log: [String] = []
for n in 1...1000 {
if Bool.random(using: &random) {
queue.enqueue(n)
reference.append(n)
log.append("enqueue(\(n))")
} else {
let actual = queue.dequeue()
let expected = reference.isEmpty ? nil : reference.removeFirst()
log.append("dequeue()")
if actual != expected {
print("operation \(log.count): expected \(expected.map(String.init) ?? "nil"), got \(actual.map(String.init) ?? "nil")")
break
}
}
}
Running it prints:
operation 127: expected 115, got 118
The queue gave the wrong answer at the 127th operation, and log holds
every operation that led there. That is too long to follow by hand, but it
is a complete, repeatable recipe, and it can be shortened: Q5 in the lab
does it mechanically. Thinking about what could go wrong, the shortest
possible failure has six operations:
enqueue(1), dequeue(), enqueue(2), enqueue(3), enqueue(4), dequeue()
expected 2, got 3
Now the story is visible. After one enqueue and one dequeue, the front of
the queue is at position 1. Enqueuing 2 and 3 fills the array, with 3
wrapped around into position 0. Enqueuing 4 makes the array grow, and the
items must be copied starting from head, wrapping around. grow
copies from position 0 instead, putting 3 before 2. The fix is
bigger[i] = items[(head + i) % items.count].
Three details make this technique work:
- A seeded generator (Lesson 23) makes every run the same, so a failure can be reproduced, debugged, and turned into a permanent test.
- Checking after every operation means the failure is reported at the first wrong step, not a thousand steps later.
- The log is the bug report. If it is long, Lesson 23’s shrinking, removing operations while the test still fails, makes it short.
Test the interface, not the implementation
The next four lessons build the same abstract type, a deque (a queue you can add to and remove from at both ends), twice: once as a linked list and once as an array. If the tests use only the operations every deque supports, the same tests check both. In Swift, that means writing tests against a protocol:
protocol IntStack {
init()
var isEmpty: Bool { get }
mutating func push(_ value: Int)
mutating func pop() -> Int?
}
struct ArrayStack: IntStack {
private var items: [Int] = []
var isEmpty: Bool { items.isEmpty }
mutating func push(_ value: Int) { items.append(value) }
mutating func pop() -> Int? { items.popLast() }
}
final class LinkedStack: IntStack {
private final class Node {
let value: Int
let next: Node?
init(_ value: Int, _ next: Node?) {
self.value = value
self.next = next
}
}
private var top: Node?
init() {}
var isEmpty: Bool { top == nil }
func push(_ value: Int) { top = Node(value, top) }
func pop() -> Int? {
defer { top = top?.next }
return top?.value
}
}
func checkStack<S: IntStack>(_ type: S.Type) -> Bool {
var stack = S()
guard stack.isEmpty, stack.pop() == nil else { return false }
for n in 1...3 {
stack.push(n)
}
return stack.pop() == 3 && stack.pop() == 2 && !stack.isEmpty && stack.pop() == 1 && stack.isEmpty
}
print(checkStack(ArrayStack.self), checkStack(LinkedStack.self)) // true true
checkStack is generic, and takes the type to test, ArrayStack.self,
so it can create fresh instances with the init() the protocol requires. A
class can conform to a protocol with mutating requirements using ordinary
methods, as Lesson 25’s lab showed. With Swift Testing, the same idea is a
parameterized test whose arguments are the types.
Tests written against the interface are also the ones that survive a rewrite: when an implementation changes completely, as the deque will in Lesson 30, tests that only use the interface keep working and prove that nothing visible changed.
Saving your work with git
CS61B asks students to commit often, and to push every assignment through git. The habit is worth more than any single test: a commit is a checkpoint you can always go back to.
git init
git add Package.swift Sources Tests
git commit -m "Add selection sort with tests"
git log --oneline # the history
git diff # what changed since the last commit
git restore Sources # throw away uncommitted changes in Sources
A good rhythm is to commit each time a new test passes. When an edit breaks
something and you cannot see why, git diff shows exactly what you changed
since everything last worked. Swift packages come with a .gitignore that
keeps the .build folder of compiled files out of the repository.
Put the lines in order
Put the lines in order so the program prints 3 1.
var stack: [Int] = []reference.append(n)stack.append(n)var reference: [Int] = []let top = stack.popLast()!print(top, reference.first!)}for n in 1...3 {
Show the correct program
var reference: [Int] = []
var stack: [Int] = []
for n in 1...3 {
stack.append(n)
reference.append(n)
}
let top = stack.popLast()!
print(top, reference.first!)Lab 26: Testing
The labs in this unit run as single files, with assert for tests, so they
work anywhere. Q4 moves tests into a package with Swift Testing.
Q0: What would Swift print?
What would Swift print?
var failures: [String] = []
func expect(_ ok: Bool, _ name: String) {
if !ok {
failures.append(name)
}
}
let sorted = [3, 1, 2].sorted()
expect(sorted.count == 3, "count")
expect(sorted.first == 1, "first")
expect(sorted == [3, 2, 1], "order")
expect(sorted.last == 2, "last")
print(failures)Show answer and explanation
Answer["order", "last"]
A harness that collects failures reports every one, not just the first. Two
wrong expectations in the test itself, not in sorted(), are also a normal
part of testing: when a test fails, check the test too.
What would Swift print?
var ring = [Int?](repeating: nil, count: 4)
var head = 3
for (i, value) in [10, 20, 30].enumerated() {
ring[(head + i) % ring.count] = value
}
print(ring.map { $0 ?? 0 })Show answer and explanation
Answer[20, 30, 0, 10]
Starting at position 3, the next positions wrap around to 0 and 1. The front
of a ring buffer can be anywhere, which is why every index is computed with
% count.
Q1: Which test finds the bug?
This selection sort has a bug. Without running it, decide which of these
tests fail, then check: [], [1], [2, 1], [3, 1, 2], [1, 2, 3].
func selectionSort(_ values: [Int]) -> [Int] {
var result = values
for i in 0..<(result.count - 1) {
result.swapAt(i, indexOfSmallest(in: result, from: i + 1))
}
return result
}
Show solution
There are two bugs. 0..<(result.count - 1) crashes for the empty array,
since 0..<-1 is not a valid range. And searching from i + 1 means the
item at i is always swapped away, even when it was already the smallest:
[]crashes.[1]passes: the loop runs zero times.[2, 1]passes: 1 is swapped to the front.[3, 1, 2]passes by luck: 1 is swapped to the front, giving[1, 3, 2], then 2 is swapped with 3.[1, 2, 3]fails: 1 is swapped with 2, giving[2, 1, 3], then 1 with 3, giving[2, 3, 1].
The already-sorted input, which many people would not bother testing, is the one that finds the second bug.
func indexOfSmallest(in values: [Int], from start: Int) -> Int {
var best = start
for i in start..<values.count where values[i] < values[best] {
best = i
}
return best
}
func selectionSort(_ values: [Int]) -> [Int] {
var result = values
for i in result.indices {
result.swapAt(i, indexOfSmallest(in: result, from: i))
}
return result
}
for input in [[], [1], [2, 1], [3, 1, 2], [1, 2, 3]] {
assert(selectionSort(input) == input.sorted())
}Q2: Fix the ring buffer
Fix RingQueue.grow(), then run the randomized comparison from this lesson
with 20 different seeds and 10,000 operations each, and make sure every run
passes. Add a peek() method that returns the front item without removing
it, and include it in the random operations.
Show solution
struct RingQueue {
private var items = [Int?](repeating: nil, count: 2)
private var head = 0
private(set) var count = 0
mutating func enqueue(_ value: Int) {
if count == items.count {
grow()
}
items[(head + count) % items.count] = value
count += 1
}
mutating func dequeue() -> Int? {
guard count > 0 else {
return nil
}
let value = items[head]
items[head] = nil
head = (head + 1) % items.count
count -= 1
return value
}
func peek() -> Int? {
count > 0 ? items[head] : nil
}
private mutating func grow() {
var bigger = [Int?](repeating: nil, count: items.count * 2)
for i in 0..<count {
bigger[i] = items[(head + i) % items.count]
}
items = bigger
head = 0
}
}
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)
}
}
for seed in 1...20 as ClosedRange<UInt64> {
var random = SeededGenerator(state: seed)
var queue = RingQueue()
var reference: [Int] = []
for n in 1...10_000 {
switch Int.random(in: 0..<3, using: &random) {
case 0:
queue.enqueue(n)
reference.append(n)
case 1:
assert(queue.dequeue() == (reference.isEmpty ? nil : reference.removeFirst()), "seed \(seed), step \(n)")
default:
assert(queue.peek() == reference.first, "seed \(seed), step \(n)")
}
assert(queue.count == reference.count)
}
}Choosing among three operations equally often makes the queue grow slowly
over the run, since enqueues outnumber dequeues, so both wrapping and
growing are exercised many times. Checking count at every step too costs
nothing and catches a different family of bugs.
Q3: One test for two stacks
Add a third implementation of IntStack that stores its items in an array
in reverse order (pushing inserts at index 0), and extend checkStack
with a randomized comparison against [Int], so that one function tests all
three implementations thoroughly.
Show solution
protocol IntStack {
init()
var isEmpty: Bool { get }
mutating func push(_ value: Int)
mutating func pop() -> Int?
}
struct ArrayStack: IntStack {
private var items: [Int] = []
var isEmpty: Bool { items.isEmpty }
mutating func push(_ value: Int) { items.append(value) }
mutating func pop() -> Int? { items.popLast() }
}
struct ReversedStack: IntStack {
private var items: [Int] = []
var isEmpty: Bool { items.isEmpty }
mutating func push(_ value: Int) { items.insert(value, at: 0) }
mutating func pop() -> Int? { items.isEmpty ? nil : items.removeFirst() }
}
final class LinkedStack: IntStack {
private final class Node {
let value: Int
let next: Node?
init(_ value: Int, _ next: Node?) {
self.value = value
self.next = next
}
}
private var top: Node?
init() {}
var isEmpty: Bool { top == nil }
func push(_ value: Int) { top = Node(value, top) }
func pop() -> Int? {
defer { top = top?.next }
return top?.value
}
}
func checkStack<S: IntStack>(_ type: S.Type, operations: Int = 5_000) -> Bool {
var random = SystemRandomNumberGenerator()
var stack = S()
var reference: [Int] = []
for n in 0..<operations {
if Bool.random(using: &random) {
stack.push(n)
reference.append(n)
} else if stack.pop() != reference.popLast() {
return false
}
if stack.isEmpty != reference.isEmpty {
return false
}
}
return true
}
assert(checkStack(ArrayStack.self))
assert(checkStack(ReversedStack.self))
assert(checkStack(LinkedStack.self))ReversedStack is correct but slow: inserting at index 0 moves every item,
which Lesson 30 will measure. Correctness and speed are separate questions,
and the same interface test answers the first for all three.
Q4: Into the package
Create the DataStructures package from this lesson. Put selectionSort and
indexOfSmallest in the library, and write a Swift Testing suite with at
least one parameterized test and one test that uses #require. Make one
test fail on purpose, read the output, and fix it.
Show solution
The suite in “Swift Testing, in more depth” is a complete answer; remove the
line marked “wrong on purpose” once you have seen the failure. Keep
indexOfSmallest internal: it is a detail of the sort, and
@testable import is what lets the tests reach it.
swift test
swift test --filter SelectionSortTestsQ5: A minimal failing sequence
Write shrinkLog(_:fails:), which takes a list of operations that makes a
test fail and removes operations one at a time, as in Lesson 23, keeping
each removal that still fails. Use it on the buggy RingQueue, representing
operations as nil for a dequeue and a number for an enqueue.
Show solution
struct RingQueue {
private var items = [Int?](repeating: nil, count: 2)
private var head = 0
private(set) var count = 0
mutating func enqueue(_ value: Int) {
if count == items.count {
grow()
}
items[(head + count) % items.count] = value
count += 1
}
mutating func dequeue() -> Int? {
guard count > 0 else {
return nil
}
let value = items[head]
items[head] = nil
head = (head + 1) % items.count
count -= 1
return value
}
private mutating func grow() {
var bigger = [Int?](repeating: nil, count: items.count * 2)
for i in 0..<count {
bigger[i] = items[i] // still the bug
}
items = bigger
head = 0
}
}
/// Whether running these operations ever disagrees with an array.
func disagrees(_ operations: [Int?]) -> Bool {
var queue = RingQueue()
var reference: [Int] = []
for operation in operations {
if let value = operation {
queue.enqueue(value)
reference.append(value)
} else if queue.dequeue() != (reference.isEmpty ? nil : reference.removeFirst()) {
return true
}
}
return false
}
func shrinkLog(_ operations: [Int?], fails: ([Int?]) -> Bool) -> [Int?] {
var current = operations
var changed = true
while changed {
changed = false
for index in current.indices {
var smaller = current
smaller.remove(at: index)
if fails(smaller) {
current = smaller
changed = true
break
}
}
}
return current
}
let long: [Int?] = [7, 1, nil, 8, nil, 2, nil, 3, 9, nil, 4, 5, nil, nil, nil]
assert(disagrees(long))
let short = shrinkLog(long, fails: disagrees)
assert(disagrees(short))
assert(short.indices.allSatisfy { i in
var smaller = short
smaller.remove(at: i)
return !disagrees(smaller) // no single operation can be removed
})
print(short.map { $0.map(String.init) ?? "dequeue" })
// ["8", "2", "3", "9", "dequeue", "4", "5", "dequeue"]Fifteen operations shrink to eight. Following them by hand: 8 and 2 fill the
first array, 3 makes it grow (correctly, since head is still 0), 9 fills
the new array, a dequeue moves head to 1, 4 wraps around into position 0,
and 5 makes the array grow while head is 1, which is the bug.
Eight is not the shortest failing sequence: the lesson found one with six. Removing one operation at a time stops at a local minimum, a sequence from which no single operation can be removed, even when removing two at once would still fail. Property-testing libraries try larger steps too for this reason. A short, readable failure is the goal, and eight operations already is one.
Q6 (optional): A test for every sort
Write checkSort(_:), which takes any sorting function ([Int]) -> [Int]
and checks it on 500 random arrays of random lengths (including empty
ones), with values from a small range so that duplicates are common. It
should return the first input that the sort gets wrong, or nil. Try it on
selectionSort, on sorted(), and on a “sort” that removes duplicates.
Show solution
func selectionSort(_ values: [Int]) -> [Int] {
var result = values
for i in result.indices {
var best = i
for j in i..<result.count where result[j] < result[best] {
best = j
}
result.swapAt(i, best)
}
return result
}
func checkSort(_ sort: ([Int]) -> [Int]) -> [Int]? {
var random = SystemRandomNumberGenerator()
for _ in 0..<500 {
let input = (0..<Int.random(in: 0...12, using: &random)).map { _ in Int.random(in: 0...5, using: &random) }
if sort(input) != input.sorted() {
return input
}
}
return nil
}
assert(checkSort(selectionSort) == nil)
assert(checkSort { $0.sorted() } == nil)
assert(checkSort { Array(Set($0)).sorted() } != nil)Comparing with sorted() checks every property of a correct sort at once:
the order, the length, and the same elements. A range of only six values
makes duplicates appear in almost every array, which is what exposes the
duplicate-dropping version.
What’s next
With tests ready, the first data structure: a list built from linked nodes,
the way CS61B builds IntList and then SLList.