Created
March 29, 2022 00:03
-
-
Save wtask/3156c55a6bfa1233ffc23f6994a37803 to your computer and use it in GitHub Desktop.
Table driven tests for generics
This file contains hidden or 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 number | |
import "golang.org/x/exp/constraints" | |
func Min[T constraints.Ordered](x, y T) T { | |
if x <= y { | |
return x | |
} | |
return y | |
} | |
func Max[t constraints.Ordered](x, y t) t { | |
if y == Min(x, y) { | |
return x | |
} | |
return y | |
} |
This file contains hidden or 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 number_test | |
import ( | |
"testing" | |
"generics/internal/number" | |
"golang.org/x/exp/constraints" | |
) | |
type casesMinMax[T constraints.Ordered] []*struct { | |
x, y, exp T | |
} | |
func testMin[T constraints.Ordered](cases casesMinMax[T]) func(*testing.T) { | |
return func(t *testing.T) { | |
t.Helper() | |
if len(cases) == 0 { | |
t.Fatal("no cases") | |
} | |
for _, c := range cases { | |
if act := number.Min(c.x, c.y); act != c.exp { | |
t.Fatalf("number.Min(%v, %v) != %v: %v", c.x, c.y, c.exp, act) | |
} | |
} | |
} | |
} | |
func testMax[T constraints.Ordered](cases casesMinMax[T]) func(*testing.T) { | |
return func(t *testing.T) { | |
t.Helper() | |
if len(cases) == 0 { | |
t.Fatal("no cases") | |
} | |
for _, c := range cases { | |
if act := number.Max(c.x, c.y); act != c.exp { | |
t.Fatalf("number.Max(%v, %v) != %v: %v", c.x, c.y, c.exp, act) | |
} | |
} | |
} | |
} | |
func TestMin(t *testing.T) { | |
t.Parallel() | |
t.Run("Integer", testMin(casesMinMax[int]{ | |
{0, -1, -1}, | |
{-1, 0, -1}, | |
{0, 0, 0}, | |
{0, 1, 0}, | |
{1, 0, 0}, | |
})) | |
t.Run("Float", testMin(casesMinMax[float32]{ | |
{0, -0.5, -0.5}, | |
{-0.5, 0, -0.5}, | |
{0, 0, 0}, | |
{0, 0.5, 0}, | |
{0.5, 0, 0}, | |
})) | |
t.Run("String", testMin(casesMinMax[string]{ | |
{"", "", ""}, | |
{"aa", "bb", "aa"}, | |
{"bb", "aa", "aa"}, | |
})) | |
} | |
func TestMax(t *testing.T) { | |
t.Parallel() | |
t.Run("Integer", testMax(casesMinMax[int]{ | |
{0, -1, 0}, | |
{-1, 0, 0}, | |
{0, 0, 0}, | |
{0, 1, 1}, | |
{1, 0, 1}, | |
})) | |
t.Run("Float", testMax(casesMinMax[float32]{ | |
{0, -0.5, 0}, | |
{-0.5, 0, 0}, | |
{0, 0, 0}, | |
{0, 0.5, 0.5}, | |
{0.5, 0, 0.5}, | |
})) | |
t.Run("String", testMax(casesMinMax[string]{ | |
{"", "", ""}, | |
{"aa", "bb", "bb"}, | |
{"bb", "aa", "bb"}, | |
})) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment