Created
February 2, 2018 23:20
-
-
Save ksindi/c1fcd591fe06a9b60e895d46e8fd85a5 to your computer and use it in GitHub Desktop.
Mock datetime.datetime.now
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
import datetime | |
def mock_now(now): | |
from datetime import datetime | |
class FakeDateType(type): | |
def __instancecheck__(self, instance): | |
return isinstance(instance, datetime) | |
class FakeDate(datetime, metaclass=FakeDateType): | |
def __new__(cls, *args, **kwargs): | |
return datetime.__new__(datetime, *args, **kwargs) | |
@staticmethod | |
def now(timezone=None): | |
return now | |
return mock.patch('datetime.datetime', FakeDate) | |
with mock_now(datetime.datetime(2013, 11, 22, 8, 0, 0)): | |
assert datetime.datetime.now().strftime('%Y-%m-%d') == '2013-11-22' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment