Last active
September 4, 2024 07:47
-
-
Save komuw/7accf7628c759f25ed21d18c10e55e79 to your computer and use it in GitHub Desktop.
Golang fuzz testing and also property-based testing.
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" | |
"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 ./... | |
// Use f.Add to provide a seed corpus | |
// f.Add(71,32) // args must match the arguments for the fuzz target. | |
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