Skip to content

Commit 685e562

Browse files
committed
settable time precision for small differences
1 parent 9e863ff commit 685e562

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

deep.go

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,17 @@ import (
99
"log"
1010
"reflect"
1111
"strings"
12+
"time"
1213
)
1314

1415
var (
1516
// FloatPrecision is the number of decimal places to round float values
1617
// to when comparing.
1718
FloatPrecision = 10
1819

20+
// TimePrecision is a precision used for time.Time.Truncate(), if it is non-zero.
21+
TimePrecision time.Duration
22+
1923
// MaxDiff specifies the maximum number of differences to return.
2024
MaxDiff = 10
2125

@@ -79,7 +83,11 @@ type cmp struct {
7983
flag map[byte]bool
8084
}
8185

82-
var errorType = reflect.TypeOf((*error)(nil)).Elem()
86+
var (
87+
errorType = reflect.TypeOf((*error)(nil)).Elem()
88+
timeType = reflect.TypeOf(time.Time{})
89+
durationType = reflect.TypeOf(time.Nanosecond)
90+
)
8391

8492
// Equal compares variables a and b, recursing into their structure up to
8593
// MaxDepth levels deep (if greater than zero), and returns a list of differences,
@@ -221,6 +229,21 @@ func (c *cmp) equals(a, b reflect.Value, level int) {
221229
Iterate through the fields (FirstName, LastName), recurse into their values.
222230
*/
223231

232+
if TimePrecision > 0 {
233+
switch aType {
234+
case timeType, durationType:
235+
aFunc := a.MethodByName("Truncate")
236+
bFunc := a.MethodByName("Truncate")
237+
238+
if aFunc.CanInterface() && bFunc.CanInterface() {
239+
precision := reflect.ValueOf(TimePrecision)
240+
241+
a = aFunc.Call([]reflect.Value{precision})[0]
242+
b = bFunc.Call([]reflect.Value{precision})[0]
243+
}
244+
}
245+
}
246+
224247
// Types with an Equal() method, like time.Time, only if struct field
225248
// is exported (CanInterface)
226249
if eqFunc := a.MethodByName("Equal"); eqFunc.IsValid() && eqFunc.CanInterface() {

0 commit comments

Comments
 (0)