Timezone testing locally

Fixing timezone related tests

Have you ever had failing tests when testing locally but not in your CI/CD platform? There’s an easy fix to get around this in any programming language.

There have been instances where I’ve had to make adjustments in my code so that I could get tests to pass locally. Some developers might accidentally write unit tests without knowing that those unit tests will fail on another machine in a different timezone. Code that will fail on a different machine can look like this.

1// this code asserts that the timestamp is equal to the value below
2// assume the one who wrote this has their machine set to UTC
3got := time.Unix(1729825337, 0).Format(time.RFC3339)
4assert.Equal(t, "2024-10-25T03:02:17Z", got)

If you run the above 2 lines on a machine not in the utc timezone you’ll get an error. This is because time.Unix will use the local timezone of the machine.

Output on my machine

 1➜  days git:(master) go test
 2--- FAIL: TestTimeAssertion (0.00s)
 3    time_test.go:24:
 4        Error Trace:    time_test.go:24
 5        Error:          Not equal:
 6                        expected: "2024-10-25T03:02:17Z"
 7                        actual  : "2024-10-24T22:02:17-05:00"
 8
 9                        Diff:
10                        --- Expected
11                        +++ Actual
12                        @@ -1 +1 @@
13                        -2024-10-25T03:02:17Z
14                        +2024-10-24T22:02:17-05:00
15        Test:           TestTimeAssertion
16FAIL
17exit status 1
18FAIL    github.com/whatsadebugger/golangplaybook/days   0.115s

There is a short and sweet solution. You could match your timezone to match what’s written in the test. This helps you avoid rewriting many lines of code where the timezone is using local time. This approach is sometimes seen as a hack rather than a fix by some.

1TZ="UTC" go test
2PASS
3ok      github.com/whatsadebugger/golangplaybook/days   0.112s

When writing code it helps to validate that it can work on any machine to reduce friction. This helps developers/consumers of the application tremendously. In my career I’ve seen many instances where it’s difficult to run go test without setting up dependencies.

Setting the timezone explicitly here creates a specific expectation that’s reproducible across machines.

1got := time.Unix(1729825337, 0).UTC().Format(time.RFC3339)
2assert.Equal(t, "2024-10-25T03:02:17Z", got)

Thank you for reading.

← Back to Posts

#Programming   #Time-Zones   #Golang   #Testing