How to Write Fuzz Tests in Go (Go 1.18+)

Write a Fuzz function with *testing.F, add seed inputs, and run with go test -fuzz to automatically find bugs with random data.

Write a fuzz test function named Fuzz<Name> that accepts a *testing.F argument, add seed inputs with f.Add, and define the fuzzing logic inside f.Fuzz.

func FuzzReader(f *testing.F) {
	// Add a valid seed input
	f.Add([]byte("valid input data"))

	f.Fuzz(func(t *testing.T, data []byte) {
		// Your code under test
		// Example: r := NewReader(bytes.NewReader(data))
		// If parsing fails, return early to skip this iteration
		if err := r.Read(); err != nil {
			return
		}
		// Add assertions or checks here
	})
}

Run the test with go test -fuzz=FuzzReader ./....