diff --git a/HISTORY.rst b/HISTORY.rst index b25395e..056678b 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -3,6 +3,7 @@ History ======= * Build Windows ARM64 wheels. +* Add ``shift()`` method to the pytest ``time_machine`` fixture. 2.8.2 (2022-09-29) ------------------ diff --git a/README.rst b/README.rst index ff85c37..0a86e83 100644 --- a/README.rst +++ b/README.rst @@ -295,7 +295,7 @@ pytest plugin ------------- time-machine also works as a pytest plugin. -It provides a function-scoped fixture called ``time_machine`` that has one method, ``move_to()``, which has the same signature as ``Coordinates.move_to()``. +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. For example: diff --git a/src/time_machine/__init__.py b/src/time_machine/__init__.py index 3bf180c..5128437 100644 --- a/src/time_machine/__init__.py +++ b/src/time_machine/__init__.py @@ -441,6 +441,14 @@ def move_to( assert self.coordinates is not None self.coordinates.move_to(destination, tick=tick) + def shift(self, delta: dt.timedelta | int | float) -> None: + if self.traveller is None: + raise RuntimeError( + "Initialize with `move_to()` first before using `shift()`" + ) + assert self.coordinates is not None + self.coordinates.shift(delta=delta) + def stop(self) -> None: if self.traveller is not None: self.traveller.stop() diff --git a/tests/test_time_machine.py b/tests/test_time_machine.py index 1b71115..b5feb0d 100644 --- a/tests/test_time_machine.py +++ b/tests/test_time_machine.py @@ -701,7 +701,7 @@ def test_fixture_used_tick_true(time_machine): assert original < time.time() < EPOCH + 10.0 -def test_fixture_used_twice(time_machine): +def test_fixture_move_to_twice(time_machine): time_machine.move_to(EPOCH) assert time.time() == EPOCH @@ -709,6 +709,13 @@ def test_fixture_used_twice(time_machine): assert time.time() == EPOCH_PLUS_ONE_YEAR +def test_fixture_move_to_and_shift(time_machine): + time_machine.move_to(EPOCH, tick=False) + assert time.time() == EPOCH + time_machine.shift(100) + assert time.time() == EPOCH + 100 + + # escape hatch tests