Last active
November 18, 2016 22:17
-
-
Save maxdanilov/10943c1a75763c230e52ff73292548a8 to your computer and use it in GitHub Desktop.
[Python] Mocking datetime 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
# Taken from https://solidgeargroup.com/mocking-the-time | |
# (unlike many answers on StackOverflow, this one actually works and is easy to use) | |
import datetime | |
import mock | |
def mock_datetime(target, datetime_module): | |
real_datetime_class = datetime.datetime | |
class DatetimeSubclassMeta(type): | |
@classmethod | |
def __instancecheck__(mcs, obj): | |
return isinstance(obj, real_datetime_class) | |
class BaseMockedDatetime(real_datetime_class): | |
@classmethod | |
def now(cls, tz=None): | |
return target.replace(tzinfo=tz) | |
@classmethod | |
def utcnow(cls): | |
return target | |
@classmethod | |
def today(cls): | |
return target | |
# Python2 & Python3-compatible metaclass | |
mocked_datetime = DatetimeSubclassMeta('datetime', (BaseMockedDatetime,), {}) | |
return mock.patch.object(datetime_module, 'datetime', mocked_datetime) | |
# usage: | |
import mock_datetime from mock_datetime | |
… | |
def test_is_new_years_eve_positive(self): | |
“”” | |
Test that it’s the 25 December | |
“”” | |
target = datetime.datetime(2014, 12, 31) | |
with mock_datetime(target, datetime): | |
is_new_years_eve = date_helpers.is_new_years_eve() | |
self.assertTrue(is_new_years_eve) | |
target = datetime.datetime(2014, 11, 31) | |
with mock_datetime(target, datetime): | |
is_new_years_eve = date_helpers.is_new_years_eve() | |
self.assertFalse(is_new_years_eve) | |
#date_helpers.py | |
#def is_new_years_eve(self): | |
# today = datetime.datetime.today() | |
# return today.month is 12 and today.day is 31 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment