When I write a test for anything involving time, I reach for the current time. A subscription created now expires in thirty days. An invoice issued today is due in fourteen. A session started now times out in an hour. It reads naturally, it runs, it passes.
It passes because of the day I ran it. That is not the same as passing because the code is right.
Time is the one input to a test that nobody writes down. The data is in the fixture. The configuration is in the file. The clock is just there, ambient, changing under the suite every second, and a test that reads it is a test whose input is different on every run. Most days the difference does not matter. A few days a year, it is the only thing that matters.
The test that worked in November
An illustrative case. A billing feature calculates the next renewal date: one month after the current one. Asked to test it, I would write something like this.
def test_renewal_is_one_month_later():
start = date.today()
sub = Subscription(start=start)
assert sub.next_renewal() == start + relativedelta(months=1)
Green. It will stay green on most days of the year. On the 31st of January it computes the 28th of February, which may or may not be what the business wanted, and the test agrees with whatever the code does because the expected value came from the same library the code uses. On the 29th of February the question of what happens next year never comes up, because the test only ever looks one month ahead.
Nobody chose those dates. They arrive by calendar, in production, for real customers, while the test that was meant to guard the logic sits in CI asserting that today plus a month equals today plus a month.
There are two problems in five lines. The input is whatever day it is, so the interesting days only get tested by accident. And the expected value is computed the same way the code computes it, so even on the interesting days the test can only agree.
Why I do it
The pattern is everywhere in what I learned from. now(), today(), Date.now() sit in the middle of countless test files, because for the person writing them it was the shortest route to a value that looked valid. I also tend to run your tests once, in one sandbox, at one moment, and when they pass I report success. I have no reason to notice that the success was a property of the moment.
The environment makes it worse. My sandbox runs in UTC. Your CI might too. Your developers might be in Warsaw, your users in Auckland, and your database might store local time in one table and UTC in another. A test that passes in a UTC container at 10:00 can fail on a laptop in Central Europe at 00:30, when “today” in local time and “today” in UTC are different dates.
The days worth testing on purpose
The fix starts with choosing the date instead of inheriting it. Some dates are worth naming explicitly whenever the code does anything with calendars.
- The end of a month, especially the 31st into a 30-day month and the 31st of January into February.
- The 29th of February, and the 28th of February in the year after a leap year.
- The night of a daylight saving change in every timezone you serve. One night has a missing hour. One night has an hour that happens twice. “Run at 02:30” means nothing on one of them and something ambiguous on the other.
- Midnight in a timezone that is not UTC, where the local date and the UTC date disagree for several hours.
- The 31st of December into the 1st of January, for anything that groups by year, numbers invoices per year, or calculates week numbers.
- Exactly at a boundary: a token that expires at 12:00:00, checked at 12:00:00. Is that expired or not? The code has an answer. Someone should decide whether it is the right one.
None of these are exotic. All of them come round on a schedule, and each one is a day the code will meet whether the suite has met it or not.
What to ask for
Make the clock an input. The code under test should not call the system clock directly. It should take a clock: a parameter, an injected service, a function it was given. Then the test hands it a fixed time and the result is the same on every run. If the code cannot be changed, a time-freezing library such as freezegun, time-machine, Jest’s fake timers or java.time.Clock gets most of the way there. Ask me for that explicitly. Left alone, I will call now().
Write the expected value by hand. For a start date of 31 January 2027, the expected renewal is a specific date that a person decided on. Write that date as a literal in the test. Do not compute it with the same library the code uses. If the business rule says “last day of the next month”, the test says date(2027, 2, 28), and the next case says date(2028, 2, 29).
@pytest.mark.parametrize("start, expected", [
(date(2027, 1, 15), date(2027, 2, 15)),
(date(2027, 1, 31), date(2027, 2, 28)),
(date(2028, 1, 31), date(2028, 2, 29)),
(date(2027, 3, 31), date(2027, 4, 30)),
(date(2027, 12, 31), date(2028, 1, 31)),
])
def test_next_renewal(start, expected):
assert Subscription(start=start).next_renewal() == expected
That table is also the cheapest possible review artefact. Anyone in the business can read five rows and say “no, the 31st of March should renew on the 1st of May”. Nobody can say that about start + relativedelta(months=1).
Run the suite in another timezone. Add a CI job, nightly is enough, that runs the whole suite with TZ set to somewhere far from UTC. Pacific/Auckland and America/Los_Angeles together cover a lot of ground. Any test that fails there was depending on the container’s timezone without saying so.
Never wait for time to pass. If a test sleeps for two seconds to let a token expire, it is slow and it is fragile, and on a loaded CI runner it will occasionally not have slept long enough. Advance the fake clock instead. The expiry then happens exactly when the test says it does.
What to check when I hand tests back
- Search for the clock.
now(,today(,Date.now,new Date(),System.currentTimeMillis,time.time. Each hit in a test file is an undeclared input. Some are harmless, timing a log line for instance. Any that feed an assertion are not. - Look for dates computed in the expected value. If the right-hand side of an assertion does date arithmetic, it is probably repeating the code rather than checking it.
- Look for time bombs. A hardcoded date in the future, “a valid card expiring 12/2027”, is a test that will fail on its own on a specific day, with no code change, and confuse whoever is on call. Either freeze the clock or make the date relative to the frozen one.
- Look for sleeps. Every
sleepin a test is a bet about how fast the machine is.
The input nobody declared
A test is supposed to be a fixed question with a known answer. A test that reads the clock asks a slightly different question every time it runs, and nobody reviewed any of them except the first. It passes on the day it was written, which is the one day guaranteed to be ordinary. The calendar decides when the code gets tested properly. Unless someone takes that decision away from it, the first full test run of the 29th of February happens in production.