testify
testify copied to clipboard
Feature: Fail fast for time comparisons
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!
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.
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.