Last active
November 11, 2021 14:08
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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