Simulating the passing of time in unittesting Simulating the passing of time in unittesting python python

Simulating the passing of time in unittesting


You can use mock to change the return value of the function you use to get the time (datetime.datetime.now for example).

There are various ways to do so (see the mock documentation), but here is one :

import unittestimport datetimefrom mock import patchclass SomeTestCase(unittest.TestCase):    def setUp(self):        self.time = datetime.datetime(2012, 5, 18)        class fakedatetime(datetime.datetime):            @classmethod            def now(cls):                return self.time        patcher = patch('datetime.datetime', fakedatetime)        self.addCleanup(patcher.stop)        patcher.start()    def test_something(self):        self.assertEqual(datetime.datetime.now(), datetime.datetime(2012, 5, 18))        self.time = datetime.datetime(2012, 5, 20)        self.assertEqual(datetime.datetime.now(), datetime.datetime(2012, 5, 20))

Because we can't replace directly datetime.datetime.now, we create a fake datetime class that does everything the same way, except returning a constant value when now is called.


Without the use of a special mock library, I propose to prepare the code for being in mock-up-mode (probably by a global variable). In mock-up-mode instead of calling the normal time-function (like time.time() or whatever) you could call a mock-up time-function which returns whatever you need in your special case.

I would vote down for changing the system time. That does not seem like a unit test but rather like a functional test as it cannot be done in parallel to anything else on that machine.


You can also take a look at freezegun module. Github - https://github.com/spulec/freezegun

From their docs

from freezegun import freeze_timeimport datetime@freeze_time("2012-01-14")def test():    assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)