Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@
Changelog
=========

* Add marker support to :doc:`the pytest plugin <pytest_plugin>`.
Decorate tests with ``@pytest.mark.time_machine(<destination>)`` to set time during a test, affecting function-level fixtures as well.

Thanks to Javier Buzzi in `PR #499 <https://github.com/adamchainz/time-machine/pull/499>`__.

* Import date and time functions once in the C extension.

This should improve speed a little bit, and avoid segmentation faults when the functions have been swapped out, such as when freezegun is in effect.
Expand Down
61 changes: 58 additions & 3 deletions docs/pytest_plugin.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,49 @@
pytest plugin
=============

time-machine also works as a pytest plugin.
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``.
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.
time-machine works as a pytest plugin, which pytest will detect automatically.
The plugin supplies both a fixture and a marker to control the time during tests.

``time_machine`` marker
-----------------------

Use the ``time_machine`` `marker <https://docs.pytest.org/en/stable/how-to/mark.html>`__ with a valid destination for :class:`~.travel` to mock the time while a test function runs.
It applies for function-scoped fixtures too, meaning the time will be mocked for any setup or teardown code done in the test function.

For example:

.. code-block:: python

import datetime as dt


@pytest.mark.time_machine(dt.datetime(1985, 10, 26))
def test_delorean_marker():
assert dt.date.today().isoformat() == "1985-10-26"

Or for a class:

.. code-block:: python

import datetime as dt

import pytest


@pytest.mark.time_machine(dt.datetime(1985, 10, 26))
class TestSomething:
def test_one(self):
assert dt.date.today().isoformat() == "1985-10-26"

def test_two(self):
assert dt.date.today().isoformat() == "1985-10-26"

``time_machine`` fixture
------------------------

Use the function-scoped `fixture <https://docs.pytest.org/en/stable/explanation/fixtures.html#about-fixtures>`__ ``time_machine`` to control time in your tests.
It provides an object with two methods, ``move_to()`` and ``shift()``, which work the same as their equivalents in the :class:`time_machine.Coordinates` class.
Until you call ``move_to()``, time is not mocked.

For example:

Expand Down Expand Up @@ -47,3 +87,18 @@ If you are using pytest test classes, you can apply the fixture to all test meth
assert int(time.time()) == 1000.0
time_machine.move_to(2000.0)
assert int(time.time()) == 2000.0

It’s possible to combine the marker and fixture in the same test:

.. code-block:: python

import datetime as dt

import pytest


@pytest.mark.time_machine(dt.datetime(1985, 10, 26))
def test_delorean_marker_and_fixture(time_machine):
assert dt.date.today().isoformat() == "1985-10-26"
time_machine.move_to(dt.datetime(2015, 10, 21))
assert dt.date.today().isoformat() == "2015-10-21"
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ max_supported_python = "3.14"
addopts = """\
--strict-config
--strict-markers
-p pytester
"""
xfail_strict = true

Expand Down
24 changes: 23 additions & 1 deletion src/time_machine/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,22 @@ def time_ns() -> int:

if HAVE_PYTEST: # pragma: no branch

def pytest_collection_modifyitems(items: list[pytest.Item]) -> None:
"""
Add the fixture to any tests with the marker.
"""
for item in items:
if item.get_closest_marker("time_machine"):
item.fixturenames.insert(0, "time_machine") # type: ignore[attr-defined]

def pytest_configure(config: pytest.Config) -> None:
"""
Register the marker.
"""
config.addinivalue_line(
"markers", "time_machine(...): set the time with time-machine"
)

class TimeMachineFixture:
traveller: travel | None
coordinates: Coordinates | None
Expand Down Expand Up @@ -414,8 +430,14 @@ def stop(self) -> None:
self.traveller.stop()

@pytest.fixture(name="time_machine")
def time_machine_fixture() -> TypingGenerator[TimeMachineFixture, None, None]:
def time_machine_fixture(
request: pytest.FixtureRequest,
) -> TypingGenerator[TimeMachineFixture, None, None]:
fixture = TimeMachineFixture()
marker = request.node.get_closest_marker("time_machine")
if marker:
fixture.move_to(*marker.args, **marker.kwargs)

yield fixture
fixture.stop()

Expand Down
73 changes: 73 additions & 0 deletions tests/test_time_machine.py
Original file line number Diff line number Diff line change
Expand Up @@ -948,6 +948,79 @@ def test_fixture_shift_without_move_to(time_machine):
)


def test_marker_function(testdir):
testdir.makepyfile(
"""
import pytest
import time

@pytest.fixture
def current_time():
return time.time()

@pytest.mark.time_machine(0)
def test(current_time):
assert current_time < 10.0
"""
)

result = testdir.runpytest("-v", "-s")
result.assert_outcomes(passed=1)


def test_marker_and_fixture(testdir):
testdir.makepyfile(
"""
import pytest
import time

@pytest.mark.time_machine(0)
def test(time_machine):
assert time.time() < 10.0
time_machine.shift(100)
assert 100.0 <= time.time() < 110.0
time_machine.move_to(0)
assert time.time() < 10.0
"""
)
result = testdir.runpytest("-v", "-s")
result.assert_outcomes(passed=1)


def test_marker_class(testdir):
testdir.makepyfile(
"""
import pytest
import time

@pytest.mark.time_machine(0)
class TestTimeMachine:
def test(self):
assert time.time() < 10.0
"""
)

result = testdir.runpytest("-v", "-s")
result.assert_outcomes(passed=1)


def test_marker_module(testdir):
testdir.makepyfile(
"""
import pytest
import time

pytestmark = pytest.mark.time_machine(0)

def test_module():
assert time.time() < 10.0
"""
)

result = testdir.runpytest("-v", "-s")
result.assert_outcomes(passed=1)


# escape hatch tests


Expand Down