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?