Skip to content

Instantly share code, notes, and snippets.

@0xbepresent
Created January 10, 2015 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0xbepresent/ba6e307cf709f153c6ba to your computer and use it in GitHub Desktop.
Save 0xbepresent/ba6e307cf709f153c6ba to your computer and use it in GitHub Desktop.
Mock Datetime Object
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