===== Usage ===== .. currentmodule:: time_machine This document covers time-machine’s API. .. warning:: Time is a global state. When mocking it, all concurrent threads or asynchronous functions are also affected. Some aren't ready for time to move so rapidly or backwards, and may crash or produce unexpected results. Also beware that other processes are not affected. For example, if you call datetime functions on a database server, they will return the real time. Main API ======== .. autoclass:: travel :param destination: :param tick: :return: ``travel`` instance ``travel()`` is a class that allows time travel, to the datetime specified by ``destination``. It does so by mocking all functions from Python's standard library that return the current date or datetime. It can be used independently, as a function decorator, or as a context manager (synchronous or asynchronous). ``destination`` specifies the datetime to move to. It may be: * A |datetime.datetime|__. If it is naive, it will have a timezone added per the current :attr:`naive_mode` value (which defaults to ``MIXED``, which treats naive datetimes as UTC). If it has ``tzinfo`` set to a |zoneinfo-instance|__ or |datetime.UTC|__, the current timezone will also be mocked. .. |datetime.datetime| replace:: ``datetime.datetime`` __ https://docs.python.org/3/library/datetime.html#datetime.datetime .. |zoneinfo-instance| replace:: ``zoneinfo.ZoneInfo`` instance __ https://docs.python.org/3/library/zoneinfo.html#zoneinfo.ZoneInfo .. |datetime.UTC| replace:: ``datetime.UTC`` (``datetime.timezone.utc``) __ https://docs.python.org/3/library/datetime.html#datetime.UTC * A |datetime.date|__. This will be converted to a datetime with the time 00:00:00, and the timezone set per the current :attr:`naive_mode` value (defaults to MIXED, which treats dates as UTC). .. |datetime.date| replace:: ``datetime.date`` __ https://docs.python.org/3/library/datetime.html#datetime.date * A |datetime.timedelta|__. This will be interpreted relative to the current time. If already within a ``travel()`` block, the :meth:`Traveller.shift` method is easier to use. .. |datetime.timedelta| replace:: ``datetime.timedelta`` __ https://docs.python.org/3/library/datetime.html#datetime.timedelta * A ``float`` or ``int`` specifying a `Unix timestamp `__. * A ``str``. This will be parsed with |datetime.fromisoformat()|__ first, which supports ISO 8601 formats like ``YYYY-MM-DD`` and ``YYYY-MM-DDTHH:MM:SS``. If that parsing fails and `dateutil `__ is installed, the value will be parsed with |dateutil.parse()|__, which supports a wider variety of formats, although beware that some are ambiguous. In either case, if the result is naive, it will be assumed to be in local time. .. |datetime.fromisoformat()| replace:: ``datetime.fromisoformat()`` __ https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat .. |dateutil.parse()| replace:: ``dateutil.parse()`` __ https://dateutil.readthedocs.io/en/stable/parser.html Additionally, you can provide some more complex types: * A generator, in which case ``next()`` will be called on it, with the result treated as above. * A callable, in which case it will be called with no parameters, with the result treated as above. ``tick`` defines whether time continues to "tick" after travelling, or is frozen. If ``True``, the default, successive calls to mocked functions return values increasing by the elapsed real time *since the first call.* 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. 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``. Mocked functions ^^^^^^^^^^^^^^^^ All datetime functions in the standard library are mocked to move to the destination current datetime: * ``datetime.datetime.now()`` * ``datetime.datetime.utcnow()`` * ``time.clock_gettime()`` (only for ``CLOCK_REALTIME``) * ``time.clock_gettime_ns()`` (only for ``CLOCK_REALTIME``) * ``time.gmtime()`` * ``time.localtime()`` * ``time.strftime()`` * ``time.time()`` * ``time.time_ns()`` The mocking is done at the C layer, replacing the function pointers for these built-ins. Therefore, it automatically affects everywhere those functions have been imported, unlike use of ``unittest.mock.patch()``. Usage with ``start()`` / ``stop()`` ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To use ``travel()`` independently, use its ``start()`` method to move to the destination time, and ``stop()`` to move back. .. automethod:: start .. automethod:: stop For example: .. code-block:: python import datetime as dt import time_machine traveller = time_machine.travel(dt.datetime(1985, 10, 26)) traveller.start() # It's the past! assert dt.date.today() == dt.date(1985, 10, 26) traveller.stop() # We've gone back to the future! assert dt.date.today() > dt.date(2020, 4, 29) ``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. It's recommended to use the decorator or context manager forms instead, to take advantage of Python features to do this. Function decorator ^^^^^^^^^^^^^^^^^^ When used as a function decorator, time is mocked during the wrapped function's duration: .. code-block:: python import time import time_machine @time_machine.travel("1970-01-01 00:00 +0000") def test_in_the_deep_past(): assert 0.0 < time.time() < 1.0 You can also decorate asynchronous functions (coroutines): .. code-block:: python import time import time_machine @time_machine.travel("1970-01-01 00:00 +0000") async def test_in_the_deep_past(): assert 0.0 < time.time() < 1.0 .. _travel-context-manager: Context manager ^^^^^^^^^^^^^^^ When used as a context manager, time is mocked during the ``with`` block. This works both synchronously: .. code-block:: python import time import time_machine def test_in_the_deep_past(): with time_machine.travel(0.0): assert 0.0 < time.time() < 1.0 …and asynchronously: .. code-block:: python import time import time_machine async def test_in_the_deep_past(): async with time_machine.travel(0.0): assert 0.0 < time.time() < 1.0 Class decorator ^^^^^^^^^^^^^^^ Only ``unittest.TestCase`` subclasses are supported. When applied as a class decorator to such classes, time is mocked from the start of ``setUpClass()`` to the end of ``tearDownClass()``: .. code-block:: python import time import time_machine import unittest @time_machine.travel(0.0) class DeepPastTests(TestCase): def test_in_the_deep_past(self): assert 0.0 < time.time() < 1.0 Note this is different to ``unittest.mock.patch()``\'s behaviour, which is to mock only during the test methods. For pytest-style test classes, see the autouse fixture pattern :doc:`in the pytest plugin documentation `. Timezone mocking ^^^^^^^^^^^^^^^^ If the ``destination`` passed to ``time_machine.travel()`` or ``Traveller.move_to()`` has its ``tzinfo`` set to a |zoneinfo-instance2|_, the current timezone will be mocked. This will be done by calling |time-tzset|_, so it is only available on Unix. .. |zoneinfo-instance2| replace:: ``zoneinfo.ZoneInfo`` instance .. _zoneinfo-instance2: https://docs.python.org/3/library/zoneinfo.html#zoneinfo.ZoneInfo .. |time-tzset| replace:: ``time.tzset()`` .. _time-tzset: https://docs.python.org/3/library/time.html#time.tzset ``time.tzset()`` changes the ``time`` module’s `timezone constants `__ and features that rely on those, such as ``time.localtime()``. It won’t affect other concepts of “the current timezone”, such as Django’s (which can be changed with its |timezone-override|_). .. |timezone-override| replace:: ``timezone.override()`` .. _timezone-override: https://docs.djangoproject.com/en/stable/ref/utils/#django.utils.timezone.override Here’s a worked example changing the current timezone: .. code-block:: python import datetime as dt import time from zoneinfo import ZoneInfo import time_machine hill_valley_tz = ZoneInfo("America/Los_Angeles") @time_machine.travel(dt.datetime(2015, 10, 21, 16, 29, tzinfo=hill_valley_tz)) def test_hoverboard_era(): assert time.tzname == ("PST", "PDT") now = dt.datetime.now() assert (now.hour, now.minute) == (16, 29) .. autoclass:: Traveller The ``start()`` method and entry of the context manager both return a ``Traveller`` object that corresponds to the given "trip" in time. This has a couple methods that can be used to travel to other times. .. automethod:: move_to ``move_to()`` moves the current time to a new destination. ``destination`` may be any of the types supported by ``travel``. ``tick`` may be set to a boolean, to change the ``tick`` flag of ``travel``. For example: .. code-block:: python import datetime as dt import time import time_machine with time_machine.travel(0, tick=False) as traveller: assert time.time() == 0 traveller.move_to(234) assert time.time() == 234 .. automethod:: shift ``shift()`` takes one argument, ``delta``, which moves the current time by the given offset. ``delta`` may be a ``timedelta`` or a number of seconds, which will be added to destination. It may be negative, in which case time will move to an earlier point. For example: .. code-block:: python import datetime as dt import time import time_machine with time_machine.travel(0, tick=False) as traveller: assert time.time() == 0 traveller.shift(dt.timedelta(seconds=100)) assert time.time() == 100 traveller.shift(-dt.timedelta(seconds=10)) assert time.time() == 90 .. attribute:: naive_mode The ``naive_mode`` attribute controls how naive datetimes are interpreted. It takes a value from the ``NaiveMode`` enum: .. class:: NaiveMode .. attribute:: MIXED Naive ``datetime`` objects and ``date`` objects are interpreted as UTC. Naive datetime strings are interpreted as local time. This mode is the default for backward compatibility with existing behaviour. .. attribute:: UTC Naive datetimes are interpreted as UTC, regardless of input type. This mode provides consistency across all input types, but is inconsistent with Python's default behaviour for naive datetimes. .. attribute:: LOCAL All naive datetimes are interpreted as local time. This mode represents Python’s default behaviour for naive datetimes, as well as how freezegun interprets them. It’s especially useful when migrating tests from freezegun to time-machine. .. attribute:: ERROR Using a naive datetime raises a ``RuntimeError``. This includes ``dt.date`` objects, as they do not have timezone information. This mode prevents your test suite from changing meaning depending on the timezone of the machine it is run on. Use it for maximum reproducibility. To use a different mode, set the ``time_machine.naive_mode`` attribute to your chosen value, like: .. code-block:: python import time_machine time_machine.naive_mode = time_machine.NaiveMode.LOCAL This is probably best done at the start of your test suite, such as within module-level code in a |pytest conftest.py file|__. .. |pytest conftest.py file| replace:: pytest ``conftest.py`` file __ https://docs.pytest.org/en/stable/reference/fixtures.html#conftest-py-sharing-fixtures-across-multiple-files To temporarily set a different mode, use |mock.patch.object()|__: .. |mock.patch.object()| replace:: ``unittest.mock.patch.object()`` __ https://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch.object .. code-block:: python from unittest import mock import time_machine with mock.patch.object(time_machine, "naive_mode", time_machine.NaiveMode.ERROR): # Code within this block will use the ERROR mode with time_machine.travel(...): ... Escape hatch API ================ .. autodata:: escape_hatch The ``escape_hatch`` object provides functions to bypass time-machine, calling the real datetime functions, without any mocking. It also provides a way to check if time-machine is currently time travelling. These capabilities are useful in rare circumstances. For example, if you need to authenticate with an external service during time travel, you may need the real value of ``datetime.now()``. When not time-travelling, these functions (except ``is_travelling()``) raise ``ValueError`` to avoid accidental use. The functions are: * ``escape_hatch.is_travelling() -> bool`` Returns ``True`` if ``time_machine.travel()`` is active, ``False`` otherwise. * ``escape_hatch.datetime.datetime.now()`` Wraps the real ``datetime.datetime.now()``. * ``escape_hatch.datetime.datetime.utcnow()`` Wraps the real ``datetime.datetime.utcnow()``. * ``escape_hatch.time.clock_gettime()`` Wraps the real ``time.clock_gettime()``. * ``escape_hatch.time.clock_gettime_ns()`` Wraps the real ``time.clock_gettime_ns()``. * ``escape_hatch.time.gmtime()`` Wraps the real ``time.gmtime()``. * ``escape_hatch.time.localtime()`` Wraps the real ``time.localtime()``. * ``escape_hatch.time.strftime()`` Wraps the real ``time.strftime()``. * ``escape_hatch.time.time()`` Wraps the real ``time.time()``. * ``escape_hatch.time.time_ns()`` Wraps the real ``time.time_ns()``. For example: .. code-block:: python import time_machine with time_machine.travel(...): if time_machine.escape_hatch.is_travelling(): print("We need to go back to the future!") real_now = time_machine.escape_hatch.datetime.datetime.now() external_authenticate(now=real_now)