How do you test code that depends on the current time?
AdvancedConceptTesting, services & metrics
Answer
Do not call datetime.now() deep inside logic. Either inject now as a parameter (simplest, clearest), or freeze time in tests with freezegun or time-machine:
import time_machine
@time_machine.travel("2026-11-09 00:00:00+00:00")
def test_expiry():
assert is_expired({"StartTime": datetime(2026, 7, 1, tzinfo=UTC)}, days=90)
Time-based retention rules (snapshot cleanup, certificate expiry, key rotation) are exactly where an off-by-one deletes something it should not.
More on Testing, services & metrics
Why should automation scripts have tests at all?BeginnerHow does pytest discover and run tests?BeginnerWhy does pytest use plain `assert` instead of `assertEqual`?BeginnerWhat are pytest fixtures, and what scopes exist?IntermediateWhat built-in fixtures do you use most?IntermediateHow does `@pytest.mark.parametrize` work?Beginner