Created
November 9, 2022 12:31
-
-
Save asspirin12/5bc5397db47b43b1ea7ec45c99f762ec to your computer and use it in GitHub Desktop.
Code example for fuzz testing in GoLand
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
func Reverse(s string) string { | |
b := []byte(s) | |
for i, j := 0, len(b)-1; i < len(b)/2; i, j = i+1, j-1 { | |
b[i], b[j] = b[j], b[i] | |
} | |
return string(b) | |
} | |
func main() { | |
input := "The quick brown fox jumped over the lazy dog" | |
rev := Reverse(input) | |
doubleRev := Reverse(rev) | |
fmt.Printf("original: %q\n", input) | |
fmt.Printf("reversed: %q\n", rev) | |
fmt.Printf("reversed again: %q\n", doubleRev) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"testing" | |
"unicode/utf8" | |
) | |
func FuzzReverse(f *testing.F) { | |
testcases := []string{"Hello, world", " ", "!12345"} | |
for _, tc := range testcases { | |
f.Add(tc) | |
} | |
f.Fuzz(func(t *testing.T, orig string) { | |
rev := Reverse(orig) | |
doubleRev := Reverse(rev) | |
if orig != doubleRev { | |
t.Errorf("Before: %q, after: %q", orig, doubleRev) | |
} | |
if utf8.ValidString(orig) && !utf8.ValidString(rev) { | |
t.Errorf("Reverse produced invalid UTF-8 string %q", rev) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment