METADATA 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. Metadata-Version: 2.1
  2. Name: time-machine
  3. Version: 2.16.0
  4. Summary: Travel through time in your tests.
  5. Author-email: Adam Johnson <me@adamj.eu>
  6. Project-URL: Changelog, https://github.com/adamchainz/time-machine/blob/main/CHANGELOG.rst
  7. Project-URL: Funding, https://adamj.eu/books/
  8. Project-URL: Repository, https://github.com/adamchainz/time-machine
  9. Keywords: date,datetime,mock,test,testing,tests,time,warp
  10. Classifier: Development Status :: 5 - Production/Stable
  11. Classifier: Framework :: Pytest
  12. Classifier: Intended Audience :: Developers
  13. Classifier: License :: OSI Approved :: MIT License
  14. Classifier: Natural Language :: English
  15. Classifier: Operating System :: OS Independent
  16. Classifier: Programming Language :: Python :: 3 :: Only
  17. Classifier: Programming Language :: Python :: 3.9
  18. Classifier: Programming Language :: Python :: 3.10
  19. Classifier: Programming Language :: Python :: 3.11
  20. Classifier: Programming Language :: Python :: 3.12
  21. Classifier: Programming Language :: Python :: 3.13
  22. Classifier: Typing :: Typed
  23. Requires-Python: >=3.9
  24. Description-Content-Type: text/x-rst
  25. License-File: LICENSE
  26. Requires-Dist: python-dateutil
  27. ============
  28. time-machine
  29. ============
  30. .. image:: https://img.shields.io/github/actions/workflow/status/adamchainz/time-machine/main.yml.svg?branch=main&style=for-the-badge
  31. :target: https://github.com/adamchainz/time-machine/actions?workflow=CI
  32. .. image:: https://img.shields.io/badge/Coverage-100%25-success?style=for-the-badge
  33. :target: https://github.com/adamchainz/time-machine/actions?workflow=CI
  34. .. image:: https://img.shields.io/pypi/v/time-machine.svg?style=for-the-badge
  35. :target: https://pypi.org/project/time-machine/
  36. .. image:: https://img.shields.io/badge/code%20style-black-000000.svg?style=for-the-badge
  37. :target: https://github.com/psf/black
  38. .. image:: https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white&style=for-the-badge
  39. :target: https://github.com/pre-commit/pre-commit
  40. :alt: pre-commit
  41. Travel through time in your tests.
  42. A quick example:
  43. .. code-block:: python
  44. import datetime as dt
  45. from zoneinfo import ZoneInfo
  46. import time_machine
  47. hill_valley_tz = ZoneInfo("America/Los_Angeles")
  48. @time_machine.travel(dt.datetime(1985, 10, 26, 1, 24, tzinfo=hill_valley_tz))
  49. def test_delorean():
  50. assert dt.date.today().isoformat() == "1985-10-26"
  51. For a bit of background, see `the introductory blog post <https://adamj.eu/tech/2020/06/03/introducing-time-machine/>`__ and `the benchmark blog post <https://adamj.eu/tech/2021/02/19/freezegun-versus-time-machine/>`__.
  52. ----
  53. **Testing a Django project?**
  54. Check out my book `Speed Up Your Django Tests <https://adamchainz.gumroad.com/l/suydt>`__ which covers loads of ways to write faster, more accurate tests.
  55. I created time-machine whilst writing the book.
  56. ----
  57. Installation
  58. ============
  59. Use **pip**:
  60. .. code-block:: sh
  61. python -m pip install time-machine
  62. Python 3.9 to 3.13 supported.
  63. Only CPython is supported at this time because time-machine directly hooks into the C-level API.
  64. Usage
  65. =====
  66. If you’re coming from freezegun or libfaketime, see also the below section on migrating.
  67. ``travel(destination, *, tick=True)``
  68. -------------------------------------
  69. ``travel()`` is a class that allows time travel, to the datetime specified by ``destination``.
  70. It does so by mocking all functions from Python's standard library that return the current date or datetime.
  71. It can be used independently, as a function decorator, or as a context manager.
  72. ``destination`` specifies the datetime to move to.
  73. It may be:
  74. * A ``datetime.datetime``.
  75. If it is naive, it will be assumed to have the UTC timezone.
  76. If it has ``tzinfo`` set to a |zoneinfo-instance|_, the current timezone will also be mocked.
  77. * A ``datetime.date``.
  78. This will be converted to a UTC datetime with the time 00:00:00.
  79. * A ``datetime.timedelta``.
  80. This will be interpreted relative to the current time.
  81. If already within a ``travel()`` block, the ``shift()`` method is easier to use (documented below).
  82. * A ``float`` or ``int`` specifying a `Unix timestamp <https://en.m.wikipedia.org/wiki/Unix_time>`__
  83. * A string, which will be parsed with `dateutil.parse <https://dateutil.readthedocs.io/en/stable/parser.html>`__ and converted to a timestamp.
  84. If the result is naive, it will be assumed to be local time.
  85. .. |zoneinfo-instance| replace:: ``zoneinfo.ZoneInfo`` instance
  86. .. _zoneinfo-instance: https://docs.python.org/3/library/zoneinfo.html#zoneinfo.ZoneInfo
  87. Additionally, you can provide some more complex types:
  88. * A generator, in which case ``next()`` will be called on it, with the result treated as above.
  89. * A callable, in which case it will be called with no parameters, with the result treated as above.
  90. ``tick`` defines whether time continues to "tick" after travelling, or is frozen.
  91. If ``True``, the default, successive calls to mocked functions return values increasing by the elapsed real time *since the first call.*
  92. So after starting travel to ``0.0`` (the UNIX epoch), the first call to any datetime function will return its representation of ``1970-01-01 00:00:00.000000`` exactly.
  93. The following calls "tick," so if a call was made exactly half a second later, it would return ``1970-01-01 00:00:00.500000``.
  94. Mocked Functions
  95. ^^^^^^^^^^^^^^^^
  96. All datetime functions in the standard library are mocked to move to the destination current datetime:
  97. * ``datetime.datetime.now()``
  98. * ``datetime.datetime.utcnow()``
  99. * ``time.clock_gettime()`` (only for ``CLOCK_REALTIME``)
  100. * ``time.clock_gettime_ns()`` (only for ``CLOCK_REALTIME``)
  101. * ``time.gmtime()``
  102. * ``time.localtime()``
  103. * ``time.monotonic()`` (not a real monotonic clock, returns ``time.time()``)
  104. * ``time.monotonic_ns()`` (not a real monotonic clock, returns ``time.time_ns()``)
  105. * ``time.strftime()``
  106. * ``time.time()``
  107. * ``time.time_ns()``
  108. The mocking is done at the C layer, replacing the function pointers for these built-ins.
  109. Therefore, it automatically affects everywhere those functions have been imported, unlike use of ``unittest.mock.patch()``.
  110. Usage with ``start()`` / ``stop()``
  111. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  112. To use independently, create an instance, use ``start()`` to move to the destination time, and ``stop()`` to move back.
  113. For example:
  114. .. code-block:: python
  115. import datetime as dt
  116. import time_machine
  117. traveller = time_machine.travel(dt.datetime(1985, 10, 26))
  118. traveller.start()
  119. # It's the past!
  120. assert dt.date.today() == dt.date(1985, 10, 26)
  121. traveller.stop()
  122. # We've gone back to the future!
  123. assert dt.date.today() > dt.date(2020, 4, 29)
  124. ``travel()`` instances are nestable, but you'll need to be careful when manually managing to call their ``stop()`` methods in the correct order, even when exceptions occur.
  125. It's recommended to use the decorator or context manager forms instead, to take advantage of Python features to do this.
  126. Function Decorator
  127. ^^^^^^^^^^^^^^^^^^
  128. When used as a function decorator, time is mocked during the wrapped function's duration:
  129. .. code-block:: python
  130. import time
  131. import time_machine
  132. @time_machine.travel("1970-01-01 00:00 +0000")
  133. def test_in_the_deep_past():
  134. assert 0.0 < time.time() < 1.0
  135. You can also decorate asynchronous functions (coroutines):
  136. .. code-block:: python
  137. import time
  138. import time_machine
  139. @time_machine.travel("1970-01-01 00:00 +0000")
  140. async def test_in_the_deep_past():
  141. assert 0.0 < time.time() < 1.0
  142. Beware: time is a *global* state - `see below <#caveats>`__.
  143. Context Manager
  144. ^^^^^^^^^^^^^^^
  145. When used as a context manager, time is mocked during the ``with`` block:
  146. .. code-block:: python
  147. import time
  148. import time_machine
  149. def test_in_the_deep_past():
  150. with time_machine.travel(0.0):
  151. assert 0.0 < time.time() < 1.0
  152. Class Decorator
  153. ^^^^^^^^^^^^^^^
  154. Only ``unittest.TestCase`` subclasses are supported.
  155. When applied as a class decorator to such classes, time is mocked from the start of ``setUpClass()`` to the end of ``tearDownClass()``:
  156. .. code-block:: python
  157. import time
  158. import time_machine
  159. import unittest
  160. @time_machine.travel(0.0)
  161. class DeepPastTests(TestCase):
  162. def test_in_the_deep_past(self):
  163. assert 0.0 < time.time() < 1.0
  164. Note this is different to ``unittest.mock.patch()``\'s behaviour, which is to mock only during the test methods.
  165. For pytest-style test classes, see the pattern `documented below <#pytest-plugin>`__.
  166. Timezone mocking
  167. ^^^^^^^^^^^^^^^^
  168. If the ``destination`` passed to ``time_machine.travel()`` or ``Coordinates.move_to()`` has its ``tzinfo`` set to a |zoneinfo-instance2|_, the current timezone will be mocked.
  169. This will be done by calling |time-tzset|_, so it is only available on Unix.
  170. .. |zoneinfo-instance2| replace:: ``zoneinfo.ZoneInfo`` instance
  171. .. _zoneinfo-instance2: https://docs.python.org/3/library/zoneinfo.html#zoneinfo.ZoneInfo
  172. .. |time-tzset| replace:: ``time.tzset()``
  173. .. _time-tzset: https://docs.python.org/3/library/time.html#time.tzset
  174. ``time.tzset()`` changes the ``time`` module’s `timezone constants <https://docs.python.org/3/library/time.html#timezone-constants>`__ and features that rely on those, such as ``time.localtime()``.
  175. It won’t affect other concepts of “the current timezone”, such as Django’s (which can be changed with its |timezone-override|_).
  176. .. |timezone-override| replace:: ``timezone.override()``
  177. .. _timezone-override: https://docs.djangoproject.com/en/stable/ref/utils/#django.utils.timezone.override
  178. Here’s a worked example changing the current timezone:
  179. .. code-block:: python
  180. import datetime as dt
  181. import time
  182. from zoneinfo import ZoneInfo
  183. import time_machine
  184. hill_valley_tz = ZoneInfo("America/Los_Angeles")
  185. @time_machine.travel(dt.datetime(2015, 10, 21, 16, 29, tzinfo=hill_valley_tz))
  186. def test_hoverboard_era():
  187. assert time.tzname == ("PST", "PDT")
  188. now = dt.datetime.now()
  189. assert (now.hour, now.minute) == (16, 29)
  190. ``Coordinates``
  191. ---------------
  192. The ``start()`` method and entry of the context manager both return a ``Coordinates`` object that corresponds to the given "trip" in time.
  193. This has a couple methods that can be used to travel to other times.
  194. ``move_to(destination, tick=None)``
  195. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  196. ``move_to()`` moves the current time to a new destination.
  197. ``destination`` may be any of the types supported by ``travel``.
  198. ``tick`` may be set to a boolean, to change the ``tick`` flag of ``travel``.
  199. For example:
  200. .. code-block:: python
  201. import datetime as dt
  202. import time
  203. import time_machine
  204. with time_machine.travel(0, tick=False) as traveller:
  205. assert time.time() == 0
  206. traveller.move_to(234)
  207. assert time.time() == 234
  208. ``shift(delta)``
  209. ^^^^^^^^^^^^^^^^
  210. ``shift()`` takes one argument, ``delta``, which moves the current time by the given offset.
  211. ``delta`` may be a ``timedelta`` or a number of seconds, which will be added to destination.
  212. It may be negative, in which case time will move to an earlier point.
  213. For example:
  214. .. code-block:: python
  215. import datetime as dt
  216. import time
  217. import time_machine
  218. with time_machine.travel(0, tick=False) as traveller:
  219. assert time.time() == 0
  220. traveller.shift(dt.timedelta(seconds=100))
  221. assert time.time() == 100
  222. traveller.shift(-dt.timedelta(seconds=10))
  223. assert time.time() == 90
  224. pytest plugin
  225. -------------
  226. time-machine also works as a pytest plugin.
  227. It provides a function-scoped fixture called ``time_machine`` with methods ``move_to()`` and ``shift()``, which have the same signature as their equivalents in ``Coordinates``.
  228. This can be used to mock your test at different points in time and will automatically be un-mock when the test is torn down.
  229. For example:
  230. .. code-block:: python
  231. import datetime as dt
  232. def test_delorean(time_machine):
  233. time_machine.move_to(dt.datetime(1985, 10, 26))
  234. assert dt.date.today().isoformat() == "1985-10-26"
  235. time_machine.move_to(dt.datetime(2015, 10, 21))
  236. assert dt.date.today().isoformat() == "2015-10-21"
  237. time_machine.shift(dt.timedelta(days=1))
  238. assert dt.date.today().isoformat() == "2015-10-22"
  239. If you are using pytest test classes, you can apply the fixture to all test methods in a class by adding an autouse fixture:
  240. .. code-block:: python
  241. import time
  242. import pytest
  243. class TestSomething:
  244. @pytest.fixture(autouse=True)
  245. def set_time(self, time_machine):
  246. time_machine.move_to(1000.0)
  247. def test_one(self):
  248. assert int(time.time()) == 1000.0
  249. def test_two(self, time_machine):
  250. assert int(time.time()) == 1000.0
  251. time_machine.move_to(2000.0)
  252. assert int(time.time()) == 2000.0
  253. ``escape_hatch``
  254. ----------------
  255. The ``escape_hatch`` object provides functions to bypass time-machine.
  256. These allow you to call the real datetime functions, without any mocking.
  257. It also provides a way to check if time-machine is currently time travelling.
  258. These capabilities are useful in rare circumstances.
  259. For example, if you need to authenticate with an external service during time travel, you may need the real value of ``datetime.now()``.
  260. The functions are:
  261. * ``escape_hatch.is_travelling() -> bool`` - returns ``True`` if ``time_machine.travel()`` is active, ``False`` otherwise.
  262. * ``escape_hatch.datetime.datetime.now()`` - wraps the real ``datetime.datetime.now()``.
  263. * ``escape_hatch.datetime.datetime.utcnow()`` - wraps the real ``datetime.datetime.utcnow()``.
  264. * ``escape_hatch.time.clock_gettime()`` - wraps the real ``time.clock_gettime()``.
  265. * ``escape_hatch.time.clock_gettime_ns()`` - wraps the real ``time.clock_gettime_ns()``.
  266. * ``escape_hatch.time.gmtime()`` - wraps the real ``time.gmtime()``.
  267. * ``escape_hatch.time.localtime()`` - wraps the real ``time.localtime()``.
  268. * ``escape_hatch.time.strftime()`` - wraps the real ``time.strftime()``.
  269. * ``escape_hatch.time.time()`` - wraps the real ``time.time()``.
  270. * ``escape_hatch.time.time_ns()`` - wraps the real ``time.time_ns()``.
  271. For example:
  272. .. code-block:: python
  273. import time_machine
  274. with time_machine.travel(...):
  275. if time_machine.escape_hatch.is_travelling():
  276. print("We need to go back to the future!")
  277. real_now = time_machine.escape_hatch.datetime.datetime.now()
  278. external_authenticate(now=real_now)
  279. Caveats
  280. =======
  281. Time is a global state.
  282. Any concurrent threads or asynchronous functions are also be affected.
  283. Some aren't ready for time to move so rapidly or backwards, and may crash or produce unexpected results.
  284. Also beware that other processes are not affected.
  285. For example, if you use SQL datetime functions on a database server, they will return the real time.
  286. Comparison
  287. ==========
  288. There are some prior libraries that try to achieve the same thing.
  289. They have their own strengths and weaknesses.
  290. Here's a quick comparison.
  291. unittest.mock
  292. -------------
  293. The standard library's `unittest.mock <https://docs.python.org/3/library/unittest.mock.html>`__ can be used to target imports of ``datetime`` and ``time`` to change the returned value for current time.
  294. Unfortunately, this is fragile as it only affects the import location the mock targets.
  295. Therefore, if you have several modules in a call tree requesting the date/time, you need several mocks.
  296. This is a general problem with unittest.mock - see `Why Your Mock Doesn't Work <https://nedbatchelder.com//blog/201908/why_your_mock_doesnt_work.html>`__.
  297. It's also impossible to mock certain references, such as function default arguments:
  298. .. code-block:: python
  299. def update_books(_now=time.time): # set as default argument so faster lookup
  300. for book in books:
  301. ...
  302. Although such references are rare, they are occasionally used to optimize highly repeated loops.
  303. freezegun
  304. ---------
  305. Steve Pulec's `freezegun <https://github.com/spulec/freezegun>`__ library is a popular solution.
  306. It provides a clear API which was much of the inspiration for time-machine.
  307. The main drawback is its slow implementation.
  308. It essentially does a find-and-replace mock of all the places that the ``datetime`` and ``time`` modules have been imported.
  309. This gets around the problems with using unittest.mock, but it means the time it takes to do the mocking is proportional to the number of loaded modules.
  310. In large projects, this can take several seconds, an impractical overhead for an individual test.
  311. It's also not a perfect search, since it searches only module-level imports.
  312. Such imports are definitely the most common way projects use date and time functions, but they're not the only way.
  313. freezegun won’t find functions that have been “hidden” inside arbitrary objects, such as class-level attributes.
  314. It also can't affect C extensions that call the standard library functions, including (I believe) Cython-ized Python code.
  315. python-libfaketime
  316. ------------------
  317. Simon Weber's `python-libfaketime <https://github.com/simon-weber/python-libfaketime/>`__ wraps the `libfaketime <https://github.com/wolfcw/libfaketime>`__ library.
  318. libfaketime replaces all the C-level system calls for the current time with its own wrappers.
  319. It's therefore a "perfect" mock for the current process, affecting every single point the current time might be fetched, and performs much faster than freezegun.
  320. Unfortunately python-libfaketime comes with the limitations of ``LD_PRELOAD``.
  321. This is a mechanism to replace system libraries for a program as it loads (`explanation <http://www.goldsborough.me/c/low-level/kernel/2016/08/29/16-48-53-the_-ld_preload-_trick/>`__).
  322. This causes two issues in particular when you use python-libfaketime.
  323. First, ``LD_PRELOAD`` is only available on Unix platforms, which prevents you from using it on Windows.
  324. Second, you have to help manage ``LD_PRELOAD``.
  325. You either use python-libfaketime's ``reexec_if_needed()`` function, which restarts (*re-execs*) your test process while loading, or manually manage the ``LD_PRELOAD`` environment variable.
  326. Neither is ideal.
  327. Re-execing breaks anything that might wrap your test process, such as profilers, debuggers, and IDE test runners.
  328. Manually managing the environment variable is a bit of overhead, and must be done for each environment you run your tests in, including each developer's machine.
  329. time-machine
  330. ------------
  331. time-machine is intended to combine the advantages of freezegun and libfaketime.
  332. It works without ``LD_PRELOAD`` but still mocks the standard library functions everywhere they may be referenced.
  333. Its weak point is that other libraries using date/time system calls won't be mocked.
  334. Thankfully this is rare.
  335. It's also possible such python libraries can be added to the set mocked by time-machine.
  336. One drawback is that it only works with CPython, so can't be used with other Python interpreters like PyPy.
  337. However it may possible to extend it to support other interpreters through different mocking mechanisms.
  338. Migrating from libfaketime or freezegun
  339. =======================================
  340. freezegun has a useful API, and python-libfaketime copies some of it, with a different function name.
  341. time-machine also copies some of freezegun's API, in ``travel()``\'s ``destination``, and ``tick`` arguments, and the ``shift()`` method.
  342. There are a few differences:
  343. * time-machine's ``tick`` argument defaults to ``True``, because code tends to make the (reasonable) assumption that time progresses whilst running, and should normally be tested as such.
  344. Testing with time frozen can make it easy to write complete assertions, but it's quite artificial.
  345. Write assertions against time ranges, rather than against exact values.
  346. * freezegun interprets dates and naive datetimes in the local time zone (including those parsed from strings with ``dateutil``).
  347. This means tests can pass when run in one time zone and fail in another.
  348. time-machine instead interprets dates and naive datetimes in UTC so they are fixed points in time.
  349. Provide time zones where required.
  350. * freezegun's ``tick()`` method has been implemented as ``shift()``, to avoid confusion with the ``tick`` argument.
  351. It also requires an explicit delta rather than defaulting to 1 second.
  352. * freezegun's ``tz_offset`` argument is not supported, since it only partially mocks the current time zone.
  353. Time zones are more complicated than a single offset from UTC, and freezegun only uses the offset in ``time.localtime()``.
  354. Instead, time-machine will mock the current time zone if you give it a ``datetime`` with a ``ZoneInfo`` timezone.
  355. Some features aren't supported like the ``auto_tick_seconds`` argument.
  356. These may be added in a future release.
  357. If you are only fairly simple function calls, you should be able to migrate by replacing calls to ``freezegun.freeze_time()`` and ``libfaketime.fake_time()`` with ``time_machine.travel()``.