Fuzz Tests With Seed Corpus
Turn fixed edge cases into a fuzz target with seed inputs, letting the engine mutate strings and search for round-trip violations.
Code
package fuzz
import (
"testing"
"unicode/utf8"
)
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)
}
// go test -fuzz=FuzzReverse
func FuzzReverse(f *testing.F) {
// Fuzz tests replay this seed corpus before mutating inputs
f.Add("hello")
f.Add("héllo")
f.Add("")
f.Fuzz(func(t *testing.T, input string) {
once := reverse(input)
twice := reverse(once)
if twice != input {
t.Fatalf("double reverse changed %q into %q", input, twice)
}
if !utf8.ValidString(once) {
t.Fatalf("reversed value is not valid UTF-8: %q", once)
}
})
}How it works
Everything that acts runs through the functions reverse and FuzzReverse — everything else is wiring.
Iteration happens inside for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 — everything outside it runs once.
Putting it to use
What the code exposes: func FuzzReverse(f *testing.F)
Callers only need FuzzReverse — everything else stays internal.
The core lines, annotated
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)
}
Interactive Tools for This Topic
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.
FAQ
- Does the runtime need any help from npm, pip, cargo, or the like?
- No — the package manager has nothing to do here; nothing is declared. Every import resolves inside the standard library — `testing`, `unicode/utf8`. The file defines `reverse`, `FuzzReverse` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.