Skip to content

Instantly share code, notes, and snippets.

@hnakamur
Created July 12, 2023 23:53
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 hnakamur/6fd8419d8a3c2e0dcf663b67e3954a7a to your computer and use it in GitHub Desktop.
Save hnakamur/6fd8419d8a3c2e0dcf663b67e3954a7a to your computer and use it in GitHub Desktop.
Go generic test must utility
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
}
}
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))
}
@hnakamur
Copy link
Author

hnakamur commented Jul 12, 2023

$ go test -v
=== RUN   TestMust0
    must_test.go:17: error
--- FAIL: TestMust0 (0.00s)
=== RUN   TestMust1
    must_test.go:32: error
--- FAIL: TestMust1 (0.00s)
=== RUN   TestMust2
    must_test.go:50: error
--- FAIL: TestMust2 (0.00s)
FAIL
exit status 1

Run it on the Go Playground: https://go.dev/play/p/uFEE6pJ7w42

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment