-
Notifications
You must be signed in to change notification settings - Fork 0
/
assert.go
48 lines (38 loc) · 1.06 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
package do
import "fmt"
type AssertHandler interface {
Errorf(format string, args ...any)
}
func Assert[T comparable](handler AssertHandler, l, r T, msgAndArgs ...any) {
if Equal(l, r) {
return
}
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)
}
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 ""
}