-
Notifications
You must be signed in to change notification settings - Fork 1
/
diffmatcher.go
42 lines (36 loc) · 1.05 KB
/
diffmatcher.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
package cmpmock
import (
"fmt"
"time"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"go.uber.org/mock/gomock"
)
// DiffEq is a simple custom matcher. it is be able to modify behavior with `github.com/google/go-cmp/cmp/cmpopts`.
// If `DiffEq` is set no `opts`, default behavior ignores a time differences of less than a second.
func DiffEq(v interface{}, opts ...cmp.Option) gomock.Matcher {
var lopts cmp.Options
if len(opts) == 0 {
lopts = append(lopts, cmpopts.EquateApproxTime(1*time.Second))
} else {
lopts = append(lopts, opts...)
}
return &diffMatcher{want: v, opts: lopts}
}
type diffMatcher struct {
want interface{}
diff string
opts cmp.Options
}
// Matches implements golang/mock/gomock#Matcher interface.
func (d *diffMatcher) Matches(x interface{}) bool {
d.diff = cmp.Diff(x, d.want, d.opts...)
return len(d.diff) == 0
}
// String implements golang/mock/gomock#Matcher interface.
func (d *diffMatcher) String() string {
if d.diff == "" {
return ""
}
return fmt.Sprintf("diff(-got +want) is %s", d.diff)
}