Created
July 12, 2023 23:53
-
-
Save hnakamur/6fd8419d8a3c2e0dcf663b67e3954a7a to your computer and use it in GitHub Desktop.
Go generic test must utility
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 testx | |
import "testing" | |
func Must0(t *testing.T) func(error) { | |
return func(err error) { | |
t.Helper() | |
if err != nil { | |
t.Fatal(err) | |
} | |
} | |
} | |
func Must1[T any](t *testing.T) func(T, error) T { | |
return func(ret1 T, err error) T { | |
t.Helper() | |
if err != nil { | |
t.Fatal(err) | |
} | |
return ret1 | |
} | |
} | |
func Must2[T1 any, T2 any](t *testing.T) func(T1, T2, error) (T1, T2) { | |
return func(ret1 T1, ret2 T2, err error) (T1, T2) { | |
t.Helper() | |
if err != nil { | |
t.Fatal(err) | |
} | |
return ret1, ret2 | |
} | |
} |
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 testx | |
import ( | |
"errors" | |
"testing" | |
) | |
func TestMust0(t *testing.T) { | |
f := func(ok bool) error { | |
if ok { | |
return nil | |
} | |
return errors.New("error") | |
} | |
Must0(t)(f(true)) | |
Must0(t)(f(false)) | |
} | |
func TestMust1(t *testing.T) { | |
f := func(ok bool) (int, error) { | |
if ok { | |
return 1, nil | |
} | |
return 0, errors.New("error") | |
} | |
v := Must1[int](t)(f(true)) | |
if got, want := v, 1; got != want { | |
t.Errorf("result mismatch, got=%v, want=%v", got, want) | |
} | |
Must1[int](t)(f(false)) | |
} | |
func TestMust2(t *testing.T) { | |
f := func(ok bool) (int, string, error) { | |
if ok { | |
return 1, "foo", nil | |
} | |
return 0, "", errors.New("error") | |
} | |
v, s := Must2[int, string](t)(f(true)) | |
if got, want := v, 1; got != want { | |
t.Errorf("result1 mismatch, got=%v, want=%v", got, want) | |
} | |
if got, want := s, "foo"; got != want { | |
t.Errorf("result2 mismatch, got=%v, want=%v", got, want) | |
} | |
Must2[int, string](t)(f(false)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Run it on the Go Playground: https://go.dev/play/p/uFEE6pJ7w42