Repaso
EspaƱol
TestingIntermediateTST-08

How do you reliably test code that depends on the current time?

Options

  1. Run the test only at one specific hour of day
  2. Inject a clock, or freeze time with freezegun (Correct option)
  3. Add time.sleep calls inside of the test body
  4. 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.

Key terms

Practice this question in Repaso