-
Notifications
You must be signed in to change notification settings - Fork 39
/
equal.go
105 lines (81 loc) · 1.93 KB
/
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package minimock
import (
"context"
"reflect"
"unsafe"
"github.com/davecgh/go-spew/spew"
"github.com/pmezard/go-difflib/difflib"
)
var dumpConf = spew.ConfigState{
Indent: " ",
DisablePointerAddresses: true,
SortKeys: true,
}
type anyContext struct {
context.Context
}
var AnyContext = anyContext{}
// Equal returns true if a equals b
func Equal(a, b interface{}) bool {
if a == nil && b == nil {
return a == b
}
if reflect.TypeOf(a).Kind() == reflect.Struct {
ap := copyValue(a)
bp := copyValue(b)
// for every field in a
for i := 0; i < reflect.TypeOf(a).NumField(); i++ {
aFieldValue := unexported(ap.Field(i))
bFieldValue := unexported(bp.Field(i))
if checkAnyContext(aFieldValue, bFieldValue) {
continue
}
if !reflect.DeepEqual(aFieldValue, bFieldValue) {
return false
}
}
return true
}
return reflect.DeepEqual(a, b)
}
// Diff returns unified diff of the textual representations of e and a
func Diff(e, a interface{}) string {
if e == nil || a == nil {
return ""
}
t := reflect.TypeOf(e)
k := t.Kind()
if reflect.TypeOf(a) != t {
return ""
}
initialKind := k
if k == reflect.Ptr {
t = t.Elem()
k = t.Kind()
}
if k != reflect.Array && k != reflect.Map && k != reflect.Slice && k != reflect.Struct {
return ""
}
if initialKind == reflect.Struct {
a = setAnyContext(e, a)
}
es := dumpConf.Sdump(e)
as := dumpConf.Sdump(a)
diff, err := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
A: difflib.SplitLines(es),
B: difflib.SplitLines(as),
Context: 1,
FromFile: "Expected params",
ToFile: "Actual params",
})
if err != nil {
panic(err)
}
return "\n\nDiff:\n" + diff
}
func unexported(field reflect.Value) interface{} {
return unexportedVal(field).Interface()
}
func unexportedVal(field reflect.Value) reflect.Value {
return reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())).Elem()
}