-
Notifications
You must be signed in to change notification settings - Fork 0
/
ftests.go
72 lines (63 loc) · 1.63 KB
/
ftests.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package main
// https://tales.mbivert.com/on-a-function-based-test-framework/
import (
"testing"
"reflect"
"strings"
"runtime"
"fmt"
"encoding/json" // pretty-printing
)
type test struct {
name string
fun any
args []any
expected []any
}
func getFn(f any) string {
xs := strings.Split((runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()), ".")
return xs[len(xs)-1]
}
func doTest(t *testing.T, f any, args []any, expected []any) {
// any -> []reflect.Value
var vargs []reflect.Value
for _, v := range args {
vargs = append(vargs, reflect.ValueOf(v))
}
got := reflect.ValueOf(f).Call(vargs)
// []reflect.Value -> []any
var igot []any
for _, v := range got {
igot = append(igot, v.Interface())
}
if !reflect.DeepEqual(igot, expected) {
sgot, err := json.MarshalIndent(igot, "", "\t")
if err != nil {
sgot = []byte(fmt.Sprintf("%+v (%s)", igot, err))
}
sexp, err := json.MarshalIndent(expected, "", "\t")
if err != nil {
sexp = []byte(fmt.Sprintf("%+v (%s)", expected, err))
}
// >= 4 and we get nothing; 3 is asm, 2 is testing, 1 is doTests()
// not sure we can do better
/*
_, fn, l, ok := runtime.Caller(3)
if !ok {
fn = "???"
l = 0
}
fmt.Printf("%s:%d got: '%s', expected: '%s'", fn, l, igot, expected)
*/
// meh, error are printed as {} with JSON.
fmt.Printf("got: '%s', expected: '%s'", igot, expected)
t.Fatalf("got: '%s', expected: '%s'", sgot, sexp)
}
}
func doTests(t *testing.T, tests []test) {
for _, test := range tests {
t.Run(fmt.Sprintf("%s()/%s", getFn(test.fun), test.name), func(t *testing.T) {
doTest(t, test.fun, test.args, test.expected)
})
}
}