testify icon indicating copy to clipboard operation
testify copied to clipboard

Feature: Fail fast for time comparisons

Open distinctdan opened this issue 3 years ago • 2 comments

I'm running into an issue with time comparisons failing when the tests are run in github actions, due to internal timezone differences in the time structs. I understand why they're failing per this issue: https://github.com/stretchr/testify/issues/666. However, I'd like a way to catch these kind of things locally so that we can prevent coding any time comparisons in the first place.

Would it be possible to globally fail any assertion that tries to compare 2 times directly? Ideally I'm thinking of a global config setting that can be enabled, something like disableTimeCompare, that makes any test fail that directly compares 2 time.Time's.

Example:

type MyStruct struct {
    Now time.Time
}

var a, b MyStruct

// Bad comparison - should fail because of time compare.
assert.Equal(t, a, b)

Alternatively, is there already a way to do this? Thanks!

distinctdan avatar Feb 22 '22 22:02 distinctdan

I'm struggling to come up with a test which is sensitive to the system TimeZone, can you show a minimum reproducible example? In the one you have given time.Time{} == time.Time{} is true in all zones.

A possible workaround might be you can select one of the more obscure time zones in your tests using an init function:

func init() {
    os.Setenv("TZ", "Australia/Broken_Hill")
}

Also, nice issue given the significance of today's date.

brackendawson avatar Feb 23 '22 00:02 brackendawson

So the actual cases for this that I've come across are in integration tests, either when we convert a struct to json and back, or when we read times from the database.

Here's a playground example where I convert a time to json and back. The time shows as having the exact same time, and using the time package's Equal function returns true. However, directly comparing the structs fails: https://go.dev/play/p/rMxB3oq4QBy

Also, that's a creative idea of setting an odd timezone to make any comparisons fail, thanks, I'll have to try that.

distinctdan avatar Feb 23 '22 17:02 distinctdan