Here's a resource manager class that will do that for you. Since you might want to put it in a separate file from your test classes, it uses inspect to look up the calling module, so that it can pass the correctly qualified target module name to mock.patch.
import datetime
import inspect
# import mock according to your python version
class mock_datetime(object):
def __init__(self, target, new_utcnow):
self.new_utcnow = new_utcnow
self.target = target
def __enter__(self):
calling_module = inspect.getmodule(inspect.stack()[1][0])
target_from_here = calling_module.__name__ + '.' + self.target
self.patcher = mock.patch(target_from_here)
mock_dt = self.patcher.start()
mock_dt.datetime.utcnow.return_value = self.new_utcnow.replace(tzinfo=None)
mock_dt.datetime.side_effect = lambda *args, **kw: datetime.datetime(*args, **kw)
return mock_dt
def __exit__(self, *args, **kwargs):
self.patcher.stop()
You can then invoke it with
with mock_datetime('mymodule.datetime', datetime.datetime(2016, 3, 23)):
assert mymodule.datetime.datetime.utcnow() == datetime.datetime(2016, 3, 23)