-
Notifications
You must be signed in to change notification settings - Fork 0
/
assert.go
71 lines (59 loc) · 1.66 KB
/
assert.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
package do
import (
"fmt"
"runtime"
)
type AssertHandler interface {
Errorf(format string, args ...any)
}
func Assert[T comparable](handler AssertHandler, l, r T, msgAndArgs ...any) {
if Equal(l, r) {
return
}
_, file, line, ok := runtime.Caller(1)
if ok {
handler.Errorf("[%s:%d] Bad case, %v != %v, %s", file, line, l, r, messageFromMsgAndArgs(msgAndArgs...))
} else {
handler.Errorf("Bad case, %v != %v, %s", l, r, messageFromMsgAndArgs(msgAndArgs...))
}
}
func AssertSlice[T comparable](handler AssertHandler, lslice, rslice []T, msgAndArgs ...any) {
ll, rl := len(lslice), len(rslice)
if ll != rl {
handler.Errorf("Bad case, left length(%d) != right length(%d)", ll, rl)
return
}
for i := 0; i < ll; i++ {
if !Equal(lslice[i], rslice[i]) {
handler.Errorf("Bad case, No.%d: %v != %v, %s", i, lslice[i], rslice[i], messageFromMsgAndArgs(msgAndArgs...))
}
}
}
func AssertSlicePtr[T comparable](handler AssertHandler, lslice, rslice []*T, msgAndArgs ...any) {
ll, rl := len(lslice), len(rslice)
if ll != rl {
handler.Errorf("Bad case, left length(%d) != right length(%d)", ll, rl)
return
}
for i := 0; i < ll; i++ {
if !Equal(*lslice[i], *rslice[i]) {
handler.Errorf("Bad case, No.%d: %v != %v, %s", i, lslice[i], rslice[i], messageFromMsgAndArgs(msgAndArgs...))
}
}
}
func messageFromMsgAndArgs(msgAndArgs ...any) string {
if len(msgAndArgs) == 0 || msgAndArgs == nil {
return ""
}
if len(msgAndArgs) == 1 {
msg := msgAndArgs[0]
if msgAsStr, ok := msg.(string); ok {
return msgAsStr
}
return fmt.Sprintf("%+v", msg)
}
if len(msgAndArgs) > 1 {
return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...)
}
return ""
}