Use freeze_time as a decorator
masterThe freeze_time decorator can be used to freeze time for various scopes:
- Pytest style functions: Decorate the test function directly.
- unittest.TestCase classes: Decorate the entire class to freeze time for every test, including setup and teardown.
- Other classes: Decorate a class to freeze time around each callable (behavior may vary).
- Methods: Decorate specific methods. You can pass the frozen time object into the method using
as_kwarg.
Note: freeze_time mocks datetime.datetime.now(), datetime.datetime.utcnow(), datetime.date.today(), time.time(), time.localtime(), time.gmtime(), and time.strftime(). It also freezes time.monotonic() and time.perf_counter(), though only their relative changes are guaranteed.
from freezegun import freeze_time
import datetime
import unittest
# Pytest style
@freeze_time("2012-01-14")
def test():
assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)
# unittest TestCase
@freeze_time("1955-11-12")
class MyTests(unittest.TestCase):
def test_the_class(self):
assert datetime.datetime.now() == datetime.datetime(1955, 11, 12)
# Method decorator with kwarg injection
class TestUnitTestMethodDecorator(unittest.TestCase):
@freeze_time('2013-04-09', as_kwarg='frozen_time')
def test_method_decorator_works_on_unittest(self, frozen_time):
self.assertEqual(datetime.date(2013, 4, 9), datetime.date.today())
self.assertEqual(datetime.date(2013, 4, 9), frozen_time.time_to_freeze.date())