Skip to content

Commit

Permalink
Add shift() method to pytest time_machine fixture (#247)
Browse files Browse the repository at this point in the history
  • Loading branch information
soxofaan committed Dec 16, 2022
1 parent 01f0ee2 commit 1426fc7
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 2 deletions.
1 change: 1 addition & 0 deletions HISTORY.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ History
=======

* Build Windows ARM64 wheels.
* Add ``shift()`` method to the pytest ``time_machine`` fixture.

2.8.2 (2022-09-29)
------------------
Expand Down
2 changes: 1 addition & 1 deletion README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
8 changes: 8 additions & 0 deletions src/time_machine/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
14 changes: 13 additions & 1 deletion tests/test_time_machine.py
Original file line number Diff line number Diff line change
Expand Up @@ -701,14 +701,26 @@ 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

time_machine.move_to(EPOCH_PLUS_ONE_YEAR)
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


def test_fixture_shift_without_move_to(time_machine):
with pytest.raises(RuntimeError):
time_machine.shift(100)


# escape hatch tests


Expand Down

0 comments on commit 1426fc7

Please sign in to comment.