Last active
November 11, 2021 14:08
-
-
Save glenfant/7336285 to your computer and use it in GitHub Desktop.
A context manager that enables go quickly in the future or in the past with datetime.datetime.now(). This may be useful in lots of 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
# -*- coding: utf-8 -*- | |
"""Mock datetime.datetime.now()""" | |
import contextlib | |
import datetime | |
@contextlib.contextmanager | |
def mock_datetime_now(*args, **kwargs): | |
"""Context manager for mocking out datetime.datetime.now() in unit tests. | |
:param args: provide arguments as expected by :class:`datetime.datetime` | |
http://docs.python.org/2.7/library/datetime.html#datetime.datetime | |
Example:: | |
>>> with mock_datetime_now(2011, 2, 3, 10, 11): | |
... now = datetime.datetime.now() | |
>>> now == datetime.datetime(2011, 2, 3, 10, 11) | |
True | |
""" | |
class MockDateTime(datetime.datetime): | |
@classmethod | |
def now(cls): | |
return cls(*args, **kwargs) | |
real_datetime = datetime.datetime | |
datetime.datetime = MockDateTime | |
try: | |
yield datetime.datetime | |
finally: | |
datetime.datetime = real_datetime | |
if __name__ == '__main__': | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment