README.rst 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. FreezeGun: Let your Python tests travel through time
  2. ====================================================
  3. .. image:: https://img.shields.io/pypi/v/freezegun.svg
  4. :target: https://pypi.python.org/pypi/freezegun/
  5. .. image:: https://github.com/spulec/freezegun/workflows/CI/badge.svg
  6. :target: https://github.com/spulec/freezegun/actions
  7. .. image:: https://coveralls.io/repos/spulec/freezegun/badge.svg?branch=master
  8. :target: https://coveralls.io/r/spulec/freezegun
  9. FreezeGun is a library that allows your Python tests to travel through time by mocking the datetime module.
  10. Usage
  11. -----
  12. Once the decorator or context manager have been invoked, all calls to datetime.datetime.now(), datetime.datetime.utcnow(), datetime.date.today(), time.time(), time.localtime(), time.gmtime(), and time.strftime() will return the time that has been frozen. time.monotonic() and time.perf_counter() will also be frozen, but as usual it makes no guarantees about their absolute value, only their changes over time.
  13. Decorator
  14. ~~~~~~~~~
  15. .. code-block:: python
  16. from freezegun import freeze_time
  17. import datetime
  18. import unittest
  19. # Freeze time for a pytest style test:
  20. @freeze_time("2012-01-14")
  21. def test():
  22. assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)
  23. # Or a unittest TestCase - freezes for every test, and set up and tear down code
  24. @freeze_time("1955-11-12")
  25. class MyTests(unittest.TestCase):
  26. def test_the_class(self):
  27. assert datetime.datetime.now() == datetime.datetime(1955, 11, 12)
  28. # Or any other class - freezes around each callable (may not work in every case)
  29. @freeze_time("2012-01-14")
  30. class Tester(object):
  31. def test_the_class(self):
  32. assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)
  33. # Or method decorator, might also pass frozen time object as kwarg
  34. class TestUnitTestMethodDecorator(unittest.TestCase):
  35. @freeze_time('2013-04-09')
  36. def test_method_decorator_works_on_unittest(self):
  37. self.assertEqual(datetime.date(2013, 4, 9), datetime.date.today())
  38. @freeze_time('2013-04-09', as_kwarg='frozen_time')
  39. def test_method_decorator_works_on_unittest(self, frozen_time):
  40. self.assertEqual(datetime.date(2013, 4, 9), datetime.date.today())
  41. self.assertEqual(datetime.date(2013, 4, 9), frozen_time.time_to_freeze.today())
  42. @freeze_time('2013-04-09', as_kwarg='hello')
  43. def test_method_decorator_works_on_unittest(self, **kwargs):
  44. self.assertEqual(datetime.date(2013, 4, 9), datetime.date.today())
  45. self.assertEqual(datetime.date(2013, 4, 9), kwargs.get('hello').time_to_freeze.today())
  46. Context manager
  47. ~~~~~~~~~~~~~~~
  48. .. code-block:: python
  49. from freezegun import freeze_time
  50. def test():
  51. assert datetime.datetime.now() != datetime.datetime(2012, 1, 14)
  52. with freeze_time("2012-01-14"):
  53. assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)
  54. assert datetime.datetime.now() != datetime.datetime(2012, 1, 14)
  55. Raw use
  56. ~~~~~~~
  57. .. code-block:: python
  58. from freezegun import freeze_time
  59. freezer = freeze_time("2012-01-14 12:00:01")
  60. freezer.start()
  61. assert datetime.datetime.now() == datetime.datetime(2012, 1, 14, 12, 0, 1)
  62. freezer.stop()
  63. Timezones
  64. ~~~~~~~~~
  65. .. code-block:: python
  66. from freezegun import freeze_time
  67. @freeze_time("2012-01-14 03:21:34", tz_offset=-4)
  68. def test():
  69. assert datetime.datetime.utcnow() == datetime.datetime(2012, 1, 14, 3, 21, 34)
  70. assert datetime.datetime.now() == datetime.datetime(2012, 1, 13, 23, 21, 34)
  71. # datetime.date.today() uses local time
  72. assert datetime.date.today() == datetime.date(2012, 1, 13)
  73. @freeze_time("2012-01-14 03:21:34", tz_offset=-datetime.timedelta(hours=3, minutes=30))
  74. def test_timedelta_offset():
  75. assert datetime.datetime.now() == datetime.datetime(2012, 1, 13, 23, 51, 34)
  76. Nice inputs
  77. ~~~~~~~~~~~
  78. FreezeGun uses dateutil behind the scenes so you can have nice-looking datetimes.
  79. .. code-block:: python
  80. @freeze_time("Jan 14th, 2012")
  81. def test_nice_datetime():
  82. assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)
  83. Function and generator objects
  84. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  85. FreezeGun is able to handle function and generator objects.
  86. .. code-block:: python
  87. def test_lambda():
  88. with freeze_time(lambda: datetime.datetime(2012, 1, 14)):
  89. assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)
  90. def test_generator():
  91. datetimes = (datetime.datetime(year, 1, 1) for year in range(2010, 2012))
  92. with freeze_time(datetimes):
  93. assert datetime.datetime.now() == datetime.datetime(2010, 1, 1)
  94. with freeze_time(datetimes):
  95. assert datetime.datetime.now() == datetime.datetime(2011, 1, 1)
  96. # The next call to freeze_time(datetimes) would raise a StopIteration exception.
  97. ``tick`` argument
  98. ~~~~~~~~~~~~~~~~~
  99. FreezeGun has an additional ``tick`` argument which will restart time at the given
  100. value, but then time will keep ticking. This is an alternative to the default
  101. parameters which will keep time stopped.
  102. .. code-block:: python
  103. @freeze_time("Jan 14th, 2020", tick=True)
  104. def test_nice_datetime():
  105. assert datetime.datetime.now() > datetime.datetime(2020, 1, 14)
  106. ``auto_tick_seconds`` argument
  107. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  108. FreezeGun has an additional ``auto_tick_seconds`` argument which will autoincrement the
  109. value every time by the given amount from the start value. This is an alternative to the default
  110. parameters which will keep time stopped. Note that given ``auto_tick_seconds`` the ``tick`` parameter will be ignored.
  111. .. code-block:: python
  112. @freeze_time("Jan 14th, 2020", auto_tick_seconds=15)
  113. def test_nice_datetime():
  114. first_time = datetime.datetime.now()
  115. auto_incremented_time = datetime.datetime.now()
  116. assert first_time + datetime.timedelta(seconds=15) == auto_incremented_time
  117. Manual ticks
  118. ~~~~~~~~~~~~
  119. FreezeGun allows for the time to be manually forwarded as well.
  120. .. code-block:: python
  121. def test_manual_tick():
  122. initial_datetime = datetime.datetime(year=1, month=7, day=12,
  123. hour=15, minute=6, second=3)
  124. with freeze_time(initial_datetime) as frozen_datetime:
  125. assert frozen_datetime() == initial_datetime
  126. frozen_datetime.tick()
  127. initial_datetime += datetime.timedelta(seconds=1)
  128. assert frozen_datetime() == initial_datetime
  129. frozen_datetime.tick(delta=datetime.timedelta(seconds=10))
  130. initial_datetime += datetime.timedelta(seconds=10)
  131. assert frozen_datetime() == initial_datetime
  132. .. code-block:: python
  133. def test_monotonic_manual_tick():
  134. initial_datetime = datetime.datetime(year=1, month=7, day=12,
  135. hour=15, minute=6, second=3)
  136. with freeze_time(initial_datetime) as frozen_datetime:
  137. monotonic_t0 = time.monotonic()
  138. frozen_datetime.tick(1.0)
  139. monotonic_t1 = time.monotonic()
  140. assert monotonic_t1 == monotonic_t0 + 1.0
  141. Moving time to specify datetime
  142. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  143. FreezeGun allows moving time to specific dates.
  144. .. code-block:: python
  145. def test_move_to():
  146. initial_datetime = datetime.datetime(year=1, month=7, day=12,
  147. hour=15, minute=6, second=3)
  148. other_datetime = datetime.datetime(year=2, month=8, day=13,
  149. hour=14, minute=5, second=0)
  150. with freeze_time(initial_datetime) as frozen_datetime:
  151. assert frozen_datetime() == initial_datetime
  152. frozen_datetime.move_to(other_datetime)
  153. assert frozen_datetime() == other_datetime
  154. frozen_datetime.move_to(initial_datetime)
  155. assert frozen_datetime() == initial_datetime
  156. @freeze_time("2012-01-14", as_arg=True)
  157. def test(frozen_time):
  158. assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)
  159. frozen_time.move_to("2014-02-12")
  160. assert datetime.datetime.now() == datetime.datetime(2014, 2, 12)
  161. Parameter for ``move_to`` can be any valid ``freeze_time`` date (string, date, datetime).
  162. Default arguments
  163. ~~~~~~~~~~~~~~~~~
  164. Note that FreezeGun will not modify default arguments. The following code will
  165. print the current date. See `here <http://docs.python-guide.org/en/latest/writing/gotchas/#mutable-default-arguments>`_ for why.
  166. .. code-block:: python
  167. from freezegun import freeze_time
  168. import datetime as dt
  169. def test(default=dt.date.today()):
  170. print(default)
  171. with freeze_time('2000-1-1'):
  172. test()
  173. Installation
  174. ------------
  175. To install FreezeGun, simply:
  176. .. code-block:: bash
  177. $ pip install freezegun
  178. On Debian systems:
  179. .. code-block:: bash
  180. $ sudo apt-get install python-freezegun
  181. Ignore packages
  182. ---------------
  183. Sometimes it's desired to ignore FreezeGun behaviour for particular packages (i.e. libraries).
  184. It's possible to ignore them for a single invocation:
  185. .. code-block:: python
  186. from freezegun import freeze_time
  187. with freeze_time('2020-10-06', ignore=['threading']):
  188. # ...
  189. By default FreezeGun ignores following packages:
  190. .. code-block:: python
  191. [
  192. 'nose.plugins',
  193. 'six.moves',
  194. 'django.utils.six.moves',
  195. 'google.gax',
  196. 'threading',
  197. 'Queue',
  198. 'selenium',
  199. '_pytest.terminal.',
  200. '_pytest.runner.',
  201. 'gi',
  202. ]
  203. It's possible to set your own default ignore list:
  204. .. code-block:: python
  205. import freezegun
  206. freezegun.configure(default_ignore_list=['threading', 'tensorflow'])
  207. Please note this will override default ignore list. If you want to extend existing defaults
  208. please use:
  209. .. code-block:: python
  210. import freezegun
  211. freezegun.configure(extend_ignore_list=['tensorflow'])