Freezegun, time travel for Python tests
Yesterday I discovered freezegun, a Python library to run test cases at defined moments in time. It feels just like the equivalent of Ruby’s timecop gem, and it saves me a lot of headaches trying to mock the datetime module.
What I was trying to test is a method named delete_expired_promises, which removes reservations for items after the expiration time has run out. The code, using freezegun came to be this simple:
with freeze_time(‘2013-10-30 10:00:00’): self.store.save(‘1111’, ‘2222’, reservation_id=‘1’) self.store.save(‘3333’, ‘4444’, reservation_id=‘2’)
with freeze_time(‘2013-10-30 11:00:00’): self.store.save(‘1111’, ‘2222’, reservation_id=‘3’)
with freeze_time(‘2013-10-30 12:30:00’): self.store.delete_expired_promises()
self.assertIsNone(self.collection.find\_one({'reservation\_id': '1'}) )
self.assertIsNone(self.collection.find\_one({'reservation\_id': '2'}) )
self.assertIsNotNone(self.collection.find\_one({'reservation\_id': '3'}) )
As you can see, I “freeze” the time at different intervals, create reservations, then run the delete_expired_promises method, and check if they have been removed correctly. It could not be more straighforward!