Fuzzing
A fuzz test is func FuzzXxx(f *testing.F) that registers seed inputs and a f.Fuzz callback. The toolchain mutates the seeds and looks for panics, failures, and go test crashes.
Detailed Explanation
You write f.Add("8080") then f.Fuzz(func(t *testing.T, in string) { ... }). go test -fuzz=FuzzParse mutates in and runs the callback. If parse panics or t.Fatal fires, the failing input is written under testdata/fuzz/ so the next go test (without -fuzz) replays it.
Supported argument types. The fuzz engine knows primitives, []byte, string, and some integer sizes. A struct of those can be several parameters. You cannot fuzz an arbitrary struct graph without encoding it into bytes yourself.
The callback must be deterministic and fast. Do not dial the network. Do not skip based on time. Reject useless inputs with t.Skip sparingly; better to cover them. Compare two implementations (parse vs parseRef) and t.Fatal on disagreement — that is how you find parser bugs.
Corpus. Seeds in f.Add and files in testdata/fuzz/FuzzXxx are the corpus. Commit interesting failures. Do not commit a gigabyte of random noise.
What it costs. Fuzzing is a long-running search. CI usually runs go test without -fuzz so the saved crashers still replay, and a nightly job runs -fuzz for a few minutes. -fuzztime=30s bounds a local run.
Code Examples
package parse
import "testing"
func FuzzParsePort(f *testing.F) {
f.Add("8080")
f.Add("0")
f.Fuzz(func(t *testing.T, in string) {
_, _ = parsePort(in) // must not panic
})
}
func parsePort(s string) (int, error) {
if s == "" {
return 0, errBad
}
return 8080, nil
}
var errBad = errString("bad")
type errString string
func (e errString) Error() string { return string(e) }go test -fuzz=FuzzParsePort -fuzztime=10sCommon Gotchas
Fuzzing a function that talks to the network will hammer that network
keep fuzz targets pure.
A failing input file is a regression test
keep it.
`f.Fuzz` callback cannot use `t.Parallel`
`f.Fuzz` callback cannot use `t.Parallel`