-
Notifications
You must be signed in to change notification settings - Fork 0
/
deep_equal.go
63 lines (57 loc) · 1.58 KB
/
deep_equal.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
package assert
import (
"fmt"
"testing"
"github.com/pierrre/compare"
)
// DeepEqualer is a function that checks if two values are deep equal.
//
// It can be customized to provide a better comparison.
//
// By default it uses [compare.DefaultComparator].
var DeepEqualer = NewDeepEqualerWithComparator(compare.DefaultComparator)
// NewDeepEqualerWithComparator creates a new [DeepEqualer] with a custom [compare.Comparator].
func NewDeepEqualerWithComparator(cr *compare.Comparator) func(v1, v2 any) (string, bool) {
return func(v1, v2 any) (string, bool) {
res := cr.Compare(v1, v2)
if len(res) == 0 {
return "", true
}
diff := fmt.Sprintf("%+v", res)
return diff, false
}
}
// DeepEqual asserts that v1 and v2 are deep equal according to [DeepEqualer].
//
//nolint:thelper // It's called below.
func DeepEqual[T any](tb testing.TB, v1, v2 T, opts ...Option) bool {
diff, equal := DeepEqualer(v1, v2)
ok := equal
if !ok {
tb.Helper()
Fail(
tb,
fmt.Sprintf("deep_equal[%s]", typeName[T]()),
fmt.Sprintf("not equal:\ndiff = %s\nv1 = %s\nv2 = %s", diff, ValueStringer(v1), ValueStringer(v2)),
opts...,
)
}
return ok
}
// NotDeepEqual asserts that v1 and v2 are not deep equal according to [DeepEqualer].
//
//nolint:thelper // It's called below.
func NotDeepEqual[T any](tb testing.TB, v1, v2 T, opts ...Option) bool {
_, equal := DeepEqualer(v1, v2)
ok := !equal
if !ok {
tb.Helper()
Fail(
tb,
fmt.Sprintf("not_deep_equal[%s]", typeName[T]()),
fmt.Sprintf("equal:\nv1 = %s\nv2 = %s", ValueStringer(v1), ValueStringer(v2)),
opts...,
)
}
return ok
}