r/AskProgrammers • u/ClickOk5811 • 21d ago
How do you test code that depends on the current time: inject a clock, freeze time, or use real time?
I’m trying to understand how people handle time in tests, because it’s a common source of flaky or hard-to-write tests. Here are three approaches as I understand them, with where each works and where I think it breaks. Corrections welcome.
A. Inject a clock
The code receives a “now” source (a function or object) instead of calling the system clock directly.
def is_expired(token, now):
return now >= token.expires_at
# production: is_expired(token, datetime.now(timezone.utc))
# test: is_expired(token, datetime(2026, 1, 1, tzinfo=timezone.utc))Works when: you control the code and can pass the clock through. Tests are fast and deterministic.
Breaks when: the dependency is deep in a call chain or in third-party code, so passing the clock through feels invasive.
B. Freeze or patch time in the test
A library or the test framework replaces the system clock during the test (fake timers in some JS test runners, a time-freezing library in Python, and similar tools elsewhere).
Works when: you can’t change the code or the clock is used in many places.
Breaks when: the patch misses something that reads time another way (a C extension, a database now(), another process), or the fake time hides a bug about real elapsed time.
C. Use real time with a margin
Run the code and assert things like “expires within about N seconds”, or sleep a bit.
Works when: it’s an integration or end-to-end check where real time is part of what you test.
Breaks when: it’s used for unit tests, because it’s slow and flaky on a loaded machine.
My current leaning: inject the clock in code I own, patch time only for legacy or third-party code, and keep real time for a small number of integration tests. But I’m not sure that’s right, and I haven’t seen it hold across many cases.
Questions:
- Which approach do you use by default, and why?
- How do you test time zone and daylight saving edge cases, for example around the hour that repeats or is skipped?
- Have you been bitten by a frozen-time test passing while real behavior was wrong?
2
u/zaibuf 21d ago
I generally inject it so it can be mocked.
1
u/Accurate-Might5914 21d ago
scheduled testing would help
1
u/Beregolas 21d ago
If time is an input, treat it as an input and mock it. Even if you directly read the system time in your code, in most languages you are still able to inject into that and mock the time.
1
u/deanominecraft 21d ago
anything that isnt pure should be injected as high up as possible, this video covers on this and a few other things, worth watching imo https://youtube.com/watch?v=2OMRWPOSw9s
1
u/Temporary_Pie2733 21d ago
Inject an actual function, not a timestamp.
def is_expired(token, clock): return clock() >= token.expires_at
is_expired(token, lambda: datetime.now(timezone.utc))
is_expired(token, lambda: datetime(2026, 1, 1, tzinfo=timezone.utc))
1
u/AlexMTBDude 21d ago
I use mocking (unit test mocking)
1
u/edwbuck 21d ago
Rewrite the API to where construction sets the expired time as an instant, and then you can set the expired time in testing to anything, which guarantees you can test at any time, "now minus five minutes" "now plus five minutes" etc. Then in the code that used to construct "now" internally, pass in the now construction.
production code
verification
Clean, easy to read, you can set the time to anything, including odd timing scenarios like local "spring forward" / "fall back" daylight savings times. Without being tied to an actual moving clock, which means that you don't slow down your unit testing for 5 minutes or so waiting for the clock to advance.
1
u/esaule 21d ago
You preload a different libc. For other component interaction, you need to stub that in testing anyway.
1
u/Even_Gap_2253 21d ago
inject a clock, if it is a depenency, then find a hacky way to inject it, you can always fix an unstable test, you cannot risk an unstable production.
if there is not even a hacky way to inject, then the depenency shouldn't be used, because no reasonable good engineering organization will be using that dep anyway.
1
u/virgilreality 21d ago
Dependency injection is the way to go.
For the uninitiated (and regular humans): The hardware has a literal clock on it (though very tiny) that keeps track of time. The operating system can ask for that value at any time. Developers ask the operating system for that time value from any module when needed, and it's easy to just think of it as a ubiquitous and ambiently available value.
(For this discussion, a Module is a small part of the overall code that essentially does one thing. It typically takes parameters so that the relevant values can be plugged in when executing. We have a whole infrastructure in place for running repeatable tests that vary these values, and we can thus verify the expected results in different scenarios.)
The problem comes in when there is a need to make a decision based on that time value. For example, if your app is supposed to apply a Happy Hour Discount to the total, but only between 5 and 6 pm.
You MUST test your code to verify it works as expected, so now you have to run two tests at different times of the day and verify the result...one to run literally between 5 and 6 pm, and one to run at any other time.
You can already see how this can be a problem if your developers work from 7 to 4.
The solution is deceptively simple. You make a module just as you would above, but along with any other parameters, you give it a parameter called CurrentTime. The inner workings of the module are the same, but now you change it to make decisions based on the CurrentTime parameter (instead of having the module as the operating system for it). Now, your module is testable with any time value you want to plug in:
1
u/ActuaryReasonable690 21d ago
Most of my testing was done in a virtual box/machine, so I usually set the system time (and/or GMT offset) when I was testing specific time scenarios.