How do you reliably test code that depends on the current time?
Options
- Run the test only at one specific hour of day
- Inject a clock, or freeze time with freezegun (Correct option)
- Add
time.sleepcalls inside of the test body - Skip those tests when they depend on the clock
Answer
Inject a clock (or now function) as a dependency, or freeze time with a library like freezegun / time-machine
Why
Code that calls datetime.now() inside gives different results each time it runs, so tests can't predict it (and may fail at midnight or month-end).
Pass the time source in as a parameter, e.g. is_expired(token, now), so tests give a fixed date. Or freeze time for the test with freezegun.
The same idea applies to random numbers and IDs.
Remember
Time is a dependency: inject or freeze it.