Mock Datetime Object
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 datetime | |
import mock | |
real_datetime_class = datetime.datetime | |
def mock_datetime_now(target): | |
""" | |
A mock patch context, we override the datetime.datetime with a custom value. | |
""" | |
class DatetimeSubclassMeta(type): | |
"""Custom __instancecheck__ instance()""" | |
@classmethod | |
def __instancecheck__(mcs, obj): | |
return isinstance(obj, real_datetime_class) | |
class BaseMockedDatetime(real_datetime_class): | |
@classmethod | |
def today(cls): | |
return target | |
MockedDatetime = DatetimeSubclassMeta("datetime", (BaseMockedDatetime,), {}) | |
return mock.patch.object(datetime, "datetime", MockedDatetime) | |
# Example | |
today = datetime.datetime.today(2010, 1, 1) | |
with mock_datetime_now(today): | |
print datetime.datetime.today() # It prints 2010-1-1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment