Skip to content

Instantly share code, notes, and snippets.

@komuw
Last active January 19, 2024 11:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komuw/7accf7628c759f25ed21d18c10e55e79 to your computer and use it in GitHub Desktop.
Save komuw/7accf7628c759f25ed21d18c10e55e79 to your computer and use it in GitHub Desktop.
Golang fuzz testing and also property-based testing.
package main
import (
"testing"
"pgregory.net/rapid"
)
// Sum adds two numbers.
func Sum(a, b int64) (total int64) {
return a + b
}
func TestSum(t *testing.T) {
// go test -race -count=1 ./...
rapid.Check(t, func(t *rapid.T) {
a := rapid.Int64().Draw(t, "a")
b := rapid.Int64().Draw(t, "b")
tt := Sum(a, b)
if tt < a { // todo: There's bug here since total of negative number and postivive might be less than one of the numbers.
t.Fatalf("got: %d. expected total to be greater than a", tt)
}
})
}
func FuzzSum(f *testing.F) {
// go test -count=1 -fuzz ./...
// f.Add(...) // Use f.Add to provide a seed corpus
f.Fuzz(func(t *testing.T, a, b int64) {
tt := Sum(a, b)
if tt < a { // todo: There's bug here since total of negative number and postivive might be less than one of the numbers.
t.Fatalf("got: %d. expected total to be greater than a", tt)
}
if Sum(a, b) != Sum(b, a) {
t.Fatal("addition should be commutative")
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment