Hand-written checks test the cases you thought of. Bugs live in the cases you did not: a cancel after a restock after a failed order, say. Random input finds those, if you have a way to tell right from wrong without working out every expected answer. An invariant is such a way. It is a rule that must hold after every step, whatever the steps were. For the ledger: for each item, the stock on the shelf plus the stock held by open orders must equal everything ever stocked. Units cannot appear or vanish.
To be useful in a check, random input must be repeatable. math/rand/v2 with an explicit seed, such as rand.New(rand.NewPCG(7, 11)), produces the same sequence on every run and every machine, so a failure can be replayed and debugged.
Predict and run
The same seed is used twice. Do the two sequences match?
package main
import (
"fmt"
"math/rand/v2"
)
func main() {
for range 2 {
random := rand.New(rand.NewPCG(7, 11))
var picks []int
for range 6 {
picks = append(picks, random.IntN(10))
}
fmt.Println(picks)
}
}Check your prediction
[2 3 5 1 3 2]
[2 3 5 1 3 2]Both lines are identical, and they will be identical tomorrow and on another computer, because the PCG generator is a fixed algorithm and the seed fixes its starting point. You could not have predicted the numbers themselves, and you do not need to. Change one seed number and run again: the sequence changes, but still repeats on every run.
Check the rule after every step
The program below drives a tiny ledger with 300 random commands and checks conservation after each one. Its Cancel has a bug: it returns stock even for an order that is already cancelled. A handful of hand-written checks might never cancel twice. The random run does, and the invariant names the step where the units went wrong.
package main
import (
"fmt"
"math/rand/v2"
)
type Ledger struct {
stock int
orders map[int]int
cancelled map[int]bool
}
func (l *Ledger) Order(id, n int) {
if _, exists := l.orders[id]; !exists && n <= l.stock {
l.stock -= n
l.orders[id] = n
}
}
func (l *Ledger) Cancel(id int) {
if n, exists := l.orders[id]; exists { // bug: no check of l.cancelled
l.stock += n
l.cancelled[id] = true
}
}
func main() {
random := rand.New(rand.NewPCG(7, 11))
l := &Ledger{stock: 50, orders: map[int]int{}, cancelled: map[int]bool{}}
for step := 1; step <= 300; step++ {
id := random.IntN(5)
if random.IntN(2) == 0 {
l.Order(id, 1+random.IntN(5))
} else {
l.Cancel(id)
}
held := 0
for id, n := range l.orders {
if !l.cancelled[id] {
held += n
}
}
if l.stock+held != 50 {
fmt.Printf("step %d: shelf %d + held %d is not 50\n", step, l.stock, held)
return
}
}
fmt.Println("invariant held for 300 steps")
}step 16: shelf 48 + held 3 is not 50Because the seed is fixed, the failure happens at the same step on every run, so you can add prints around step 16 and watch it happen: an order is cancelled a second time, and its units are counted on the shelf twice. Fix Cancel by changing the condition to exists && !l.cancelled[id], and run again: the invariant now holds for all 300 steps.
Invariants, models and examples
An invariant checks a property, not exact answers, so it is cheap to write and catches whole families of bugs. It cannot catch everything: a ledger that rejected every order would conserve units perfectly. That is why the project combines three kinds of check. Examples such as checkOrders pin down exact behavior at the edges. checkConservation runs 400 random commands against the conservation rule. And the snapshot and transcript checks compare complete outputs. Each covers what the others miss.
A reference model
A stronger form of random testing compares the real code with a reference model: a second implementation, written as simply as possible and never optimized. After each random step, both must agree on every observable result. It costs more to write than an invariant, and finds more. Rust Advanced uses one for its stock ledger, if you want to see the idea at full size.
Practice
Your turn
The starter's Seats type books and releases seats by ID. Drive it with 200 random commands from rand.NewPCG(3, 5), booking or releasing a random ID from 0 to 5 with 1 to 3 seats. After each step, check that the number of taken seats equals the sum of the open bookings' sizes, and that it never exceeds 10. Print the result.
The output should be:
invariant held for 200 steps; most seats taken at once: 10package main
type Seats struct {
free int
bookings map[int]int
}
func (s *Seats) Book(id, n int) {
if _, exists := s.bookings[id]; !exists && n <= s.free {
s.free -= n
s.bookings[id] = n
}
}
func (s *Seats) Release(id int) {
if n, exists := s.bookings[id]; exists {
s.free += n
delete(s.bookings, id)
}
}
func main() {
s := &Seats{free: 10, bookings: map[int]int{}}
_ = s
// Drive s with random commands and check the invariant.
}Hint 1: the idea
Taken seats are 10 - s.free. Compute the same number a second way, from the bookings, and compare.
Hint 2: a first step
Loop with for step := 1; step <= 200; step++, pick id := random.IntN(6), and choose between Book and Release with random.IntN(2).
Worked solution
package main
import (
"fmt"
"math/rand/v2"
)
type Seats struct {
free int
bookings map[int]int
}
func (s *Seats) Book(id, n int) {
if _, exists := s.bookings[id]; !exists && n <= s.free {
s.free -= n
s.bookings[id] = n
}
}
func (s *Seats) Release(id int) {
if n, exists := s.bookings[id]; exists {
s.free += n
delete(s.bookings, id)
}
}
func main() {
random := rand.New(rand.NewPCG(3, 5))
s := &Seats{free: 10, bookings: map[int]int{}}
most := 0
for step := 1; step <= 200; step++ {
id := random.IntN(6)
if random.IntN(2) == 0 {
s.Book(id, 1+random.IntN(3))
} else {
s.Release(id)
}
held := 0
for _, n := range s.bookings {
held += n
}
taken := 10 - s.free
if taken != held || taken > 10 {
panic(fmt.Sprintf("step %d: taken %d, held %d", step, taken, held))
}
most = max(most, taken)
}
fmt.Println("invariant held for 200 steps; most seats taken at once:", most)
}invariant held for 200 steps; most seats taken at once: 10Printing the most seats taken at once shows the random run really reached the limit, where bugs tend to hide. A run that never filled the room would pass while testing very little. Break Release by removing the delete, and the check fails at a fixed step.
Going further: Go's testing and fuzzing tools (optional)
The browser runs a single main package, so this course writes its checks as functions that return an error, such as checkConservation() error, and calls them from main. On your own computer, Go's testing package is the standard home for the same checks, and it adds a tool built for exactly this lesson's idea: native fuzzing, random input generated and shrunk by go test itself. The project's download already uses the first part: its ledger_test.go is a test function that calls checkLedger and fails with its error. This section needs a local Go install.
In an empty folder, run go mod init quantity and save a parseQuantity that accepts 1 to 1000 in quantity.go, with package main and a small main:
var errQuantity = errors.New("quantity must be 1-1000")
func parseQuantity(text string) (int, error) {
n, err := strconv.Atoi(text)
if err != nil || n < 1 || n > 1000 {
return 0, fmt.Errorf("%q: %w", text, errQuantity)
}
return n, nil
}Then save this as quantity_test.go beside it:
package main
import (
"errors"
"testing"
)
func TestParseQuantity(t *testing.T) {
cases := []struct {
text string
want int
wantErr bool
}{
{"1", 1, false},
{"1000", 1000, false},
{"0", 0, true},
{"1001", 0, true},
{"two", 0, true},
}
for _, c := range cases {
t.Run(c.text, func(t *testing.T) {
got, err := parseQuantity(c.text)
if got != c.want || (err != nil) != c.wantErr {
t.Errorf("parseQuantity(%q) = %d, %v", c.text, got, err)
}
if err != nil && !errors.Is(err, errQuantity) {
t.Errorf("error %v does not wrap errQuantity", err)
}
})
}
}
func FuzzParseQuantity(f *testing.F) {
f.Add("12")
f.Add("1000")
f.Fuzz(func(t *testing.T, text string) {
n, err := parseQuantity(text)
if err != nil {
return
}
if n < 1 || n > 1000 {
t.Errorf("parseQuantity(%q) accepted %d", text, n)
}
})
}TestParseQuantityis a table test. Each row runs as a named subtest throught.Run, andt.Errorfrecords a failure and carries on, so one run reports every broken row.go test -vlists them, andgo test -run 'TestParseQuantity/1001'runs one.FuzzParseQuantitychecks an invariant, not examples: whatever text comes in, an accepted quantity is between 1 and 1000.f.Addgives seed inputs. A plaingo testruns only the seeds, so the fuzz test costs nothing in a normal test run.go test -run=FuzzParseQuantity -fuzz=FuzzParseQuantity -fuzztime=30sgenerates new inputs from the seeds for up to 30 seconds, guided by which code paths they reach.
To see it work, delete n < 1 || from parseQuantity and run the fuzz command. It stops almost at once with parseQuantity("0") accepted 0, writes the input to testdata/fuzz/FuzzParseQuantity/, and from then on every plain go test replays that file, so the bug can't come back unnoticed. (The table test catches this bug too. A fuzzer earns its keep on the inputs nobody thought to put in a table.)
How the styles fit together: a checkX() error function works anywhere, including the browser, and a test function can call it, as ledger_test.go does. A seeded generator, as in this lesson, gives a long random run that repeats exactly. A fuzz test explores far more inputs than any fixed seed, shrinks a failure to a small example and saves it. Real projects usually have all three.
Completion is saved in this browser only. It does not measure mastery.