Mocking datetime in Python
It might be that pythonistas really don’t like monkey patching, but as I couldn’t find a quick answer on how to mock time in Python I thought I write down here how I did it.
It’s no big deal really, just replace datetime in the module tested
with a local implementation. In my case I wanted to to mock
datetime.utcnow and to match the call I created a class with
utcnow as a static method.
class TimeStandsStill: # define the methods you want mocked # Here we have @staticmethod def utcnow(): return datetime(2015, 8, 1) def test_setup_result_without_error(): my_module.datetime = TimeStandsStill assert_equals('2015-08-01T00:00:00', my_module.some_method())
Really, not a big deal.