Fuzzing in Go
A fuzz target gets random input until it finds one that breaks the property.
func Reverse(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
func FuzzReverse(f *testing.F) {
f.Add("typestar")
f.Add("")
f.Fuzz(func(t *testing.T, input string) {
once := Reverse(input)
twice := Reverse(once)
if twice != input {
t.Errorf("round trip: %q -> %q -> %q", input, once, twice)
}
if utf8.ValidString(input) && !utf8.ValidString(once) {
t.Errorf("reverse broke utf8 for %q", input)
}
})
}
How it works
f.Addseeds the corpus with known-interesting values.f.Fuzzreceives generated arguments of the seeded types.- Assert a property, not a specific output.
Keywords and builtins used here
forfunciflenreturnrunestring
The run, in numbers
- Lines
- 23
- Characters to type
- 509
- Tokens
- 168
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 92 seconds.
Step 2 of 3 in Measuring & generating, step 9 of 13 in Testing.