Skip to content

Instantly share code, notes, and snippets.

@glenfant
Last active November 11, 2021 14:08
Show Gist options
  • Save glenfant/7322247 to your computer and use it in GitHub Desktop.
Save glenfant/7322247 to your computer and use it in GitHub Desktop.
A simple context manager that enabes to change time.time() to whatever you need (future or past) in your unit tests.
import contextlib
import time
@contextlib.contextmanager
def mock_time(timestamp):
"""A simple context manager for mocking time.time() useful for traveling
immediately in the future or in the past in unit tests.
>>> t0 = time.time()
>>> with mock_time(t0 + 5.0):
>>> t1 = time.time()
>>> t1 - t0
5.0
"""
def my_time():
return timestamp
sv_time = time.time
time.time = my_time
try:
yield timestamp
finally:
time.time = sv_time
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment