Lesson 07 · 55 minutes
Test your code and let a fuzzer attack it
- Write table-driven tests, including one for an error path
- Run `go vet` and the race detector on your code
- Find a real bug with a fuzz test
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
A colleague wrote a small package that reads the prefix length of a network (24 or /24). Your team will use it in a scanner. Before it ships, your lead says: "Show me that it is right, and show me what breaks it." The package passes a quick look. You will learn to write table tests and a fuzz test on the port parser of the course. Then you attack your colleague's package in the same way.
Recall
Lesson 6 showed a data race on `count++`. Which tool found it, and which option turned it on?
The race detector found it. go run -race . (or go test -race) turns it on.
In lesson 3 you moved `Parse` into a package. Why does the name `Parse` start with a capital letter?
A name with a capital letter is exported: code in other packages can call it. A name with a small letter stays private to its package.
The idea
A test is a function in a _test.go file of the same package. Its name starts with Test, and it takes a *testing.T, a pointer (lesson 4, step 4) to the record of the test. go test runs them.
| Tool | Job |
|---|---|
go test | Runs the tests of a package. |
| Table-driven test | One loop over a slice of cases. A new case is one new line. |
go vet | Looks for code that compiles but is probably wrong, such as a wrong Printf verb. |
-race | The race detector from lesson 6, applied to tests. |
| Fuzzing | The tool makes up thousands of inputs and reports one that breaks a rule you set. |
- Write a test → Run go test: it states what must be true
- Run go test → Fix the code: it fails with a message
- Fix the code → Write a test: add the next case
Each pass ends in a new test for the next case. A test that failed once stays in the code for good, so the bug cannot come back.
Worked example
1. Make a package to test
mkdir -p ~/krlab/go/safe/portspec
cd ~/krlab/go/safe
go mod init krlab/safego mod init writes this go.mod. The lab zip holds it with go 1.22, so that it builds on every Go from 1.22:
go.mod
module krlab/safe
go 1.22Write portspec/portspec.go. ParseRange reads "80" or "20-25" and returns the first port, the last port and an error. A comment above a name documents it (lesson 3).
safe/portspec/portspec.go
package portspec
import (
"errors"
"fmt"
"strconv"
"strings"
)
// ErrRange means a port is outside 1 to 65535.
var ErrRange = errors.New("port out of range")
// Parse converts text such as "443" to a port number.
func Parse(s string) (int, error) {
n, err := strconv.Atoi(s)
if err != nil {
return 0, fmt.Errorf("parse port %q: %w", s, err)
}
if n < 1 || n > 65535 {
return 0, fmt.Errorf("parse port %q: %w", s, ErrRange)
}
return n, nil
}
// ParseRange converts "80" or "20-25" to the first and the last port.
func ParseRange(s string) (int, int, error) {
first, last, found := strings.Cut(s, "-")
lo, err := Parse(first)
if err != nil {
return 0, 0, err
}
if !found {
return lo, lo, nil
}
hi, err := Parse(last)
if err != nil {
return 0, 0, err
}
if hi < lo {
return 0, 0, fmt.Errorf("parse range %q: end before start", s)
}
return lo, hi, nil
}2. Write a table-driven test
Write portspec/portspec_test.go. The file name must end in _test.go, and the function name must start with Test. The value t of type *testing.T is how a test reports. t.Run names each case, so a failure points at it. t.Fatalf stops the case, and t.Errorf reports and goes on. The slice of anonymous structs is the "table".
safe/portspec/portspec_test.go
package portspec
import "testing"
func TestParseRange(t *testing.T) {
tests := []struct {
in string
lo, hi int
}{
{"80", 80, 80},
{"20-25", 20, 25},
{"1-65535", 1, 65535},
{"443-443", 443, 443},
}
for _, tc := range tests {
t.Run(tc.in, func(t *testing.T) {
lo, hi, err := ParseRange(tc.in)
if err != nil {
t.Fatalf("ParseRange(%q) error: %v", tc.in, err)
}
if lo != tc.lo || hi != tc.hi {
t.Errorf("ParseRange(%q) = %d, %d; want %d, %d", tc.in, lo, hi, tc.lo, tc.hi)
}
})
}
}go test ./... runs the tests of every package under the current folder (... means "and all below").
go test ./...ok krlab/safe/portspec 0.004sTo see a failure, change {"20-25", 20, 25} to {"20-25", 20, 26} and run again. The message names the case. Then change it back.
3. Test the error path
Many bugs hide in the bad-input paths. Add this function to the test file, and "errors" to its imports. A nil in wantErr means "any error will do".
func TestParseRangeErrors(t *testing.T) {
tests := []struct {
in string
wantErr error
}{
{"0", ErrRange},
{"70000", ErrRange},
{"20-70000", ErrRange},
{"25-20", nil},
{"http", nil},
{"", nil},
}
for _, tc := range tests {
t.Run(tc.in, func(t *testing.T) {
_, _, err := ParseRange(tc.in)
if err == nil {
t.Fatalf("ParseRange(%q): want an error, got none", tc.in)
}
if tc.wantErr != nil && !errors.Is(err, tc.wantErr) {
t.Errorf("ParseRange(%q) error = %v; want %v", tc.in, err, tc.wantErr)
}
})
}
}go test -count=1 ./...ok krlab/safe/portspec 0.004s-count=1 skips the cache of earlier results.
4. Run vet and the race detector
go vet reads your code and warns about mistakes that still compile. Make a throwaway folder with a mistake: %s for a number. Run mkdir vetdemo, and save this text as vetdemo/main.go. It is not a file of the lab zip.
package main
import "fmt"
func main() {
fmt.Printf("port %s\n", 80)
}go vet ./...vetdemo/main.go:6:19: fmt.Printf format %s has arg 80 of wrong type intDelete the folder with rm -r vetdemo. Then run the tests with the detector.
go vet ./... && go test -race ./...ok krlab/safe/portspec 1.023s5. Test against a server that the test owns
A test must not depend on a server that someone else runs. The package net/http/httptest starts a real server for the test. httptest.NewServer(handler) listens on a free port of 127.0.0.1 and gives its address in srv.URL, and srv.Close() stops it. http.HandlerFunc turns a function into a handler. For files, t.TempDir() works the same way: it gives a new folder that the test deletes at its end, and filepath.Join(dir, "a.txt") builds a path in it. You use both below. First write probe/probe.go, a function that returns the status of a URL.
- TestStatus → probe.Status: Status(ctx, srv.URL + "/broken")
- probe.Status → httptest server: GET to a free port on 127.0.0.1
- httptest server → probe.Status: the handler answers 500
- probe.Status → TestStatus: returns 500 and a nil error
safe/probe/probe.go
// Package probe asks a URL for its status.
package probe
import (
"context"
"net/http"
"time"
)
var client = &http.Client{Timeout: 2 * time.Second}
// Status sends a GET request and returns the status code of the answer.
func Status(ctx context.Context, url string) (int, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return 0, err
}
resp, err := client.Do(req)
if err != nil {
return 0, err
}
resp.Body.Close()
return resp.StatusCode, nil
}Then write probe/probe_test.go. The handler answers 500 for /broken and 200 for any other path.
safe/probe/probe_test.go
package probe
import (
"context"
"net/http"
"net/http/httptest"
"testing"
)
func TestStatus(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/broken" {
http.Error(w, "no", http.StatusInternalServerError)
}
}))
defer srv.Close()
tests := []struct {
path string
want int
}{{"/ok", 200}, {"/broken", 500}}
for _, tc := range tests {
t.Run(tc.path, func(t *testing.T) {
got, err := Status(context.Background(), srv.URL+tc.path)
if err != nil || got != tc.want {
t.Errorf("Status(%q) = %d, %v; want %d", tc.path, got, err, tc.want)
}
})
}
}Then write probe/tempdir_test.go. It has nothing to do with probe: it only shows t.TempDir(). It writes a file in a folder that the test owns, and reads it back. os.ReadFile reads a whole file, and t.Fatal(err) stops the test with the error.
safe/probe/tempdir_test.go
package probe
import (
"os"
"path/filepath"
"testing"
)
func TestTempDir(t *testing.T) {
path := filepath.Join(t.TempDir(), "a.txt")
if err := os.WriteFile(path, []byte("ok\n"), 0o600); err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(path)
if err != nil || string(data) != "ok\n" {
t.Errorf("read back %q, %v", data, err)
}
}go test -race ./probeok krlab/safe/probe 1.021s6. Let a fuzzer attack Parse
A fuzz test (a function that starts with Fuzz) states a rule that must hold for every input. f.Add gives the fuzzer a first input to start from, and f.Fuzz takes the function that checks the rule. strconv.Itoa turns a number into text, the opposite of Atoi. This rule: if Parse accepts a text, printing the number back gives the same text. Write portspec/fuzz_test.go.
safe/portspec/fuzz_test.go
package portspec
import (
"strconv"
"testing"
)
func FuzzParse(f *testing.F) {
f.Add("80")
f.Add("65535")
f.Fuzz(func(t *testing.T, s string) {
n, err := Parse(s)
if err != nil {
return
}
if strconv.Itoa(n) != s {
t.Errorf("Parse(%q) = %d, but %q is not the plain form of %d", s, n, s, n)
}
})
}go test -fuzz=FuzzParse -fuzztime=5s ./portspecfuzz: elapsed: 0s, gathering baseline coverage: 2/2 completed
fuzz: minimizing 29-byte failing input file
--- FAIL: FuzzParse (0.18s)
--- FAIL: FuzzParse (0.00s)
fuzz_test.go:17: Parse("01") = 1, but "01" is not the plain form of 1
Failing input written to testdata/fuzz/FuzzParse/7f5131ea0ab9779f
FAIL-fuzz=FuzzParse runs the fuzz test of that name. -fuzztime=5s stops it after five seconds. Without it the fuzzer runs until you press Ctrl+C.
The fuzzer found at once what your table missed: Parse("01") is accepted, and so are "+80" and "0080". The fuzzer is random, so the input that it finds and the name of the file can differ from these (for example "00001"). The fault is the same: a text that is not plain digits is accepted. The failing input is saved under testdata, and a plain go test now replays it.
7. Fix the bug and run the fuzzer again
In Parse, add this check between the Atoi check and the range check.
if strconv.Itoa(n) != s {
return 0, fmt.Errorf("parse port %q: not plain digits", s)
}go test ./portspec
go test -fuzz=FuzzParse -fuzztime=5s ./portspecok krlab/safe/portspec 0.005s
fuzz: elapsed: 6s, execs: 2027138 (306973/sec), new interesting: 126 (total: 133)
PASS
ok krlab/safe/portspec 6.215sTwo million inputs found no more failures. Your counts will differ.
8. The finished file
These are the whole files as they stand after the steps above: Parse with the fix of step 7, and the test file with the error-path test of step 3. The lab files of the course hold them.
The finished file: portspec/portspec.go
safe/portspec/portspec.go
package portspec
import (
"errors"
"fmt"
"strconv"
"strings"
)
// ErrRange means a port is outside 1 to 65535.
var ErrRange = errors.New("port out of range")
// Parse converts text such as "443" to a port number.
func Parse(s string) (int, error) {
n, err := strconv.Atoi(s)
if err != nil {
return 0, fmt.Errorf("parse port %q: %w", s, err)
}
if strconv.Itoa(n) != s {
return 0, fmt.Errorf("parse port %q: not plain digits", s)
}
if n < 1 || n > 65535 {
return 0, fmt.Errorf("parse port %q: %w", s, ErrRange)
}
return n, nil
}
// ParseRange converts "80" or "20-25" to the first and the last port.
func ParseRange(s string) (int, int, error) {
first, last, found := strings.Cut(s, "-")
lo, err := Parse(first)
if err != nil {
return 0, 0, err
}
if !found {
return lo, lo, nil
}
hi, err := Parse(last)
if err != nil {
return 0, 0, err
}
if hi < lo {
return 0, 0, fmt.Errorf("parse range %q: end before start", s)
}
return lo, hi, nil
}The finished file: portspec/portspec_test.go
safe/portspec/portspec_test.go
package portspec
import (
"errors"
"testing"
)
func TestParseRange(t *testing.T) {
tests := []struct {
in string
lo, hi int
}{
{"80", 80, 80},
{"20-25", 20, 25},
{"1-65535", 1, 65535},
{"443-443", 443, 443},
}
for _, tc := range tests {
t.Run(tc.in, func(t *testing.T) {
lo, hi, err := ParseRange(tc.in)
if err != nil {
t.Fatalf("ParseRange(%q) error: %v", tc.in, err)
}
if lo != tc.lo || hi != tc.hi {
t.Errorf("ParseRange(%q) = %d, %d; want %d, %d", tc.in, lo, hi, tc.lo, tc.hi)
}
})
}
}
func TestParseRangeErrors(t *testing.T) {
tests := []struct {
in string
wantErr error
}{
{"0", ErrRange},
{"70000", ErrRange},
{"20-70000", ErrRange},
{"25-20", nil},
{"http", nil},
{"", nil},
}
for _, tc := range tests {
t.Run(tc.in, func(t *testing.T) {
_, _, err := ParseRange(tc.in)
if err == nil {
t.Fatalf("ParseRange(%q): want an error, got none", tc.in)
}
if tc.wantErr != nil && !errors.Is(err, tc.wantErr) {
t.Errorf("ParseRange(%q) error = %v; want %v", tc.in, err, tc.wantErr)
}
})
}
}Your turn
Attack the package of your colleague. There are no steps here: use what the worked example showed.
Make the module krlab/mask in ~/krlab/go/mask, and create the package with the commands below. The package is the input of the task, and it has two faults.
mkdir -p ~/krlab/go/mask/cidrmask
cd ~/krlab/go/mask
go mod init krlab/mask
cat > cidrmask/cidrmask.go <<'EOF'
// Package cidrmask reads the prefix length of a network: "24" or "/24".
package cidrmask
import (
"fmt"
"strconv"
"strings"
)
// Parse returns the prefix length. A valid length is 0 to 32.
func Parse(s string) (int, error) {
n, err := strconv.Atoi(strings.TrimPrefix(s, "/"))
if err != nil {
return 0, fmt.Errorf("mask %q: %w", s, err)
}
if n < 1 || n > 32 {
return 0, fmt.Errorf("mask %q: out of range", s)
}
return n, nil
}
EOFThe zip holds this go.mod for it:
go.mod
module krlab/mask
go 1.22The rule: a valid mask is the plain digits of a number from 0 to 32, with an optional / in front. +24 and 024 are not plain.
- Write a table-driven test for the inputs
24,/24,32,33and0. Run it, and find the first fault. - Fix the fault. Write a fuzz test with this rule: when
Parseaccepts a text, the number that it returns, written as plain digits, is the text without its/. Seed it with24and/24, and run it for five seconds. Find the second fault. - Fix it, and run the fuzzer again until it ends with
PASS. - Last, call
Parsefor the eight inputs24,/24,+24,024,32,33,0and an empty text, and count how many it accepts.
Check yourself
Why is a table-driven test better than ten separate test functions?
The check is written once, and a new case is one line. Each case has a name, so a failure points at it. Ten copies of the same code drift apart.
A table test has no case for `"01"`, and `go test -cover` says 100%. Why did the bug stay?
Coverage counts lines that ran, not inputs that were tried. Every line ran, but no case reached the wrong result.
What does the fuzzer do with the failing input, and why does that help?
It saves the input in testdata/fuzz/. Every later go test replays it as a normal test, so the bug cannot return without a failure.
Field notes
- Fuzz the code that reads untrusted input first: parsers, decoders, network replies. A rule such as "never panic" is enough to start. Run long sessions (
-fuzztime=10m) in a scheduled job, not on every commit. - A test that uses a fixed port or a real clock is flaky. Bind to port
0and read the real port from the listener. Lesson 8 does this. - Each dependency is code that you did not write and must trust. The standard library covers HTTP, JSON, flags, TLS, tests and fuzzing, so keep the list short: this course uses none.
go.sumholds a hash for each one, andgo mod verifychecks them. Commitgo.modandgo.sum. - Scan dependencies for known flaws with the Go team's
govulncheck. It needs a network and a separate install, so it is not part of this lesson (not tested here).