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.

GoSecurity Boundaries

Code

gosnippet
33 lines
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

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.