Skip to content

Instantly share code, notes, and snippets.

@glenfant
Last active November 11, 2021 14:08
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 glenfant/7336285 to your computer and use it in GitHub Desktop.
Save glenfant/7336285 to your computer and use it in GitHub Desktop.
A context manager that enables go quickly in the future or in the past with datetime.datetime.now(). This may be useful in lots of unit tests.
# -*- coding: utf-8 -*-
"""Mock datetime.datetime.now()"""
import contextlib
import datetime
@contextlib.contextmanager
def mock_datetime_now(*args, **kwargs):
"""Context manager for mocking out datetime.datetime.now() in unit tests.
:param args: provide arguments as expected by :class:`datetime.datetime`
http://docs.python.org/2.7/library/datetime.html#datetime.datetime
Example::
>>> with mock_datetime_now(2011, 2, 3, 10, 11):
... now = datetime.datetime.now()
>>> now == datetime.datetime(2011, 2, 3, 10, 11)
True
"""
class MockDateTime(datetime.datetime):
@classmethod
def now(cls):
return cls(*args, **kwargs)
real_datetime = datetime.datetime
datetime.datetime = MockDateTime
try:
yield datetime.datetime
finally:
datetime.datetime = real_datetime
if __name__ == '__main__':
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment