The project's checks use three kinds of evidence: examples at the edges, an invariant over random commands, and a snapshot of the final state. This checkpoint asks you to write all three for a small tool register, and then to show that together they catch a bug that each alone might miss.
What you will use
- The starter's
Register. It lends tools by ID and takes them back. It has a bug you will find. - Example checks. Lending an available tool, lending it again, returning it, and returning it again.
- An invariant. After every random step, the number of tools on loan equals the number of IDs recorded as borrowed, and no tool is on loan twice.
- A snapshot. The final state encoded as JSON with sorted keys, compared with an expected string.
Plan before you type
- Read
Registerand write the example checks first. Run them. - Add a random run of 300 steps with
rand.NewPCG(1, 2), checking the invariant after each step. - When a check fails, read the message, find the bug in
Return, and fix it. - Encode a final snapshot of a short, known sequence of commands and compare it with the expected JSON.
- Print one line per kind of check.
Let the failure guide you
Do not read Return for the bug first. Write the checks, let one of them fail, and use its message to find the problem. That is how the checks will be used on real code, where you do not already know there is a bug.
Mistakes worth checking for
- The random run never lends a tool twice, so it misses the bug: use few tool IDs, such as 0 to 3, so collisions are common.
- The invariant is computed from the same map it checks, so it can never fail: count loans from one structure and compare with the other.
- The snapshot includes the unexported fields: only exported fields with JSON tags appear.
- The random check passes on one seed and you stop: also print how many loans and returns actually happened.
Your turn
Write the three kinds of check for the starter's Register, find and fix the bug, and print one line per check. For the snapshot, lend tools 1 and 3, return tool 1, then compare with {"onLoan":[3],"loans":2}.
The output should be:
examples passed
invariant held: 78 loans, 77 returns
snapshot matched: {"onLoan":[3],"loans":2}package main
type Register struct {
onLoan map[int]bool
loans int
}
func (r *Register) Lend(tool int) bool {
if r.onLoan[tool] {
return false
}
r.onLoan[tool] = true
r.loans++
return true
}
func (r *Register) Return(tool int) bool {
r.onLoan[tool] = false
return true
}
func main() {
r := &Register{onLoan: map[int]bool{}}
_ = r
// Write example, invariant and snapshot checks.
}Hint 1: the idea
Each kind of check asks a different question. An example check asks what one operation should do in an edge case the random run may rarely reach. The invariant asks what must stay true of the whole register after every step. Think about which edge cases of lending and returning a tool deserve an example.
Hint 2: a first step
Write the example checks first, including returning a tool that isn't on loan, and run them before touching Return. Let the failing message tell you what to fix, then add the random run and confirm the invariant passes too. Build the snapshot last, from sorted keys, so its JSON is the same on every run.
Worked solution
package main
import (
"encoding/json"
"fmt"
"maps"
"math/rand/v2"
"slices"
)
type Register struct {
onLoan map[int]bool
loans int
}
func (r *Register) Lend(tool int) bool {
if r.onLoan[tool] {
return false
}
r.onLoan[tool] = true
r.loans++
return true
}
func (r *Register) Return(tool int) bool {
if !r.onLoan[tool] {
return false
}
delete(r.onLoan, tool)
return true
}
type Snapshot struct {
OnLoan []int `json:"onLoan"`
Loans int `json:"loans"`
}
func (r *Register) Snapshot() Snapshot {
return Snapshot{OnLoan: slices.Sorted(maps.Keys(r.onLoan)), Loans: r.loans}
}
func main() {
r := &Register{onLoan: map[int]bool{}}
for _, step := range []struct {
lend bool
tool int
want bool
}{{true, 1, true}, {true, 1, false}, {false, 1, true}, {false, 1, false}, {false, 9, false}} {
var got bool
if step.lend {
got = r.Lend(step.tool)
} else {
got = r.Return(step.tool)
}
if got != step.want {
panic(fmt.Sprintf("lend=%t tool %d: got %t", step.lend, step.tool, got))
}
}
fmt.Println("examples passed")
random := rand.New(rand.NewPCG(1, 2))
r = &Register{onLoan: map[int]bool{}}
lent, returned := 0, 0
for step := 1; step <= 300; step++ {
tool := random.IntN(4)
if random.IntN(2) == 0 {
if r.Lend(tool) {
lent++
}
} else if r.Return(tool) {
returned++
}
if len(r.onLoan) != lent-returned {
panic(fmt.Sprintf("step %d: %d on loan, expected %d", step, len(r.onLoan), lent-returned))
}
}
fmt.Printf("invariant held: %d loans, %d returns\n", lent, returned)
r = &Register{onLoan: map[int]bool{}}
r.Lend(1)
r.Lend(3)
r.Return(1)
data, err := json.Marshal(r.Snapshot())
if want := `{"onLoan":[3],"loans":2}`; err != nil || string(data) != want {
panic(fmt.Sprintf("snapshot:\n got %s\n want %s", data, want))
}
fmt.Println("snapshot matched:", string(data))
}examples passed
invariant held: 78 loans, 77 returns
snapshot matched: {"onLoan":[3],"loans":2}With the original Return, the fourth example fails, because returning tool 1 twice succeeds. The invariant fails too, because entries set to false still count toward len(r.onLoan). And the snapshot would list tool 1 as on loan. The counts on the second line show the random run did real work, with dozens of loans and returns.
Completion is saved in this browser only. It does not measure mastery.