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!

3 comments:

  1. Waooow!!! Magnificent blogs, this is what I wanted to search. Thanks buddy
    Social Media Marketing

    ReplyDelete
  2. Structured Data has been one of the key themes at two SEO conferences that I’ve attended in the past 12 months,
    xenforo

    ReplyDelete
  3. I truly appreciate your working guys, thumbs up!!
    Men Sex Toys

    ReplyDelete