Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use (time.Time).Equal for time objects #1011

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions assert/assertions.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,12 @@ func ObjectsAreEqual(expected, actual interface{}) bool {
return expected == actual
}

if e, ok := objectToTime(expected); ok {
if a, ok := objectToTime(actual); ok {
return e.Equal(a)
}
}

exp, ok := expected.([]byte)
if !ok {
return reflect.DeepEqual(expected, actual)
Expand All @@ -75,6 +81,20 @@ func ObjectsAreEqual(expected, actual interface{}) bool {
return bytes.Equal(exp, act)
}

func objectToTime(o interface{}) (time.Time, bool) {
s, ok := o.(time.Time)
if ok {
return s, ok
}

p, ok := o.(*time.Time)
if ok {
return *p, true
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

p could be a nil pointer, please check that p != nil before dereferencing it.

}

return time.Time{}, false
}

// ObjectsAreEqualValues gets whether two objects are equal, or if their
// values are equal.
func ObjectsAreEqualValues(expected, actual interface{}) bool {
Expand Down
19 changes: 19 additions & 0 deletions assert/assertions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1975,6 +1975,25 @@ Diff:
Equal(t, expected, actual)
}

func TestTimeEqualUsesBuiltinFunction(t *testing.T) {
t0, err := time.ParseInLocation("2006-01-02T15:04:05", "2020-03-01T12:23:14", &time.Location{})
NoError(t, err)

t1 := time.Date(2020, 3, 1, 12, 23, 14, 0, time.UTC)

sinkT := sinkT{}
testifyAssertion := Equal(sinkT, t0, t1)
builtinAssertion := t0.Equal(t1)

Equal(t, builtinAssertion, testifyAssertion)
}

// sinkT is a helper TestingT to discard generated errors
// Is intended to be used when assertion message is not relevant, but result it is
type sinkT struct{}

func (s sinkT) Errorf(string, ...interface{}) {}

func TestTimeEqualityErrorFormatting(t *testing.T) {
mockT := new(mockTestingT)

Expand Down