Created
July 29, 2011 05:02
-
-
Save jimmydo/1113164 to your computer and use it in GitHub Desktop.
Python context manager for mocking out datetime.now() in unit tests.
This file contains 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 datetime | |
@contextlib.contextmanager | |
def mock_now(dt_value): | |
"""Context manager for mocking out datetime.now() in unit tests. | |
Example: | |
with mock_now(datetime.datetime(2011, 2, 3, 10, 11)): | |
assert datetime.datetime.now() == datetime.datetime(2011, 2, 3, 10, 11) | |
""" | |
class MockDateTime(datetime.datetime): | |
@classmethod | |
def now(cls): | |
# Create a copy of dt_value. | |
return datetime.datetime( | |
dt_value.year, dt_value.month, dt_value.day, | |
dt_value.hour, dt_value.minute, dt_value.second, dt_value.microsecond, | |
dt_value.tzinfo | |
) | |
real_datetime = datetime.datetime | |
datetime.datetime = MockDateTime | |
try: | |
yield datetime.datetime | |
finally: | |
datetime.datetime = real_datetime |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment