Skip to content

Commit

Permalink
Add support for dt.timedelta to travel class
Browse files Browse the repository at this point in the history
  • Loading branch information
AgDude committed Nov 3, 2022
1 parent 522b647 commit 011a8f3
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/time_machine/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@
int,
float,
dt.datetime,
dt.timedelta,
dt.date,
str,
]
Expand Down Expand Up @@ -117,6 +118,12 @@ def extract_timestamp_tzname(
if dest.tzinfo is None:
dest = dest.replace(tzinfo=dt.timezone.utc)
timestamp = dest.timestamp()
elif isinstance(dest, dt.timedelta):
if escape_hatch.is_travelling():
raise TypeError(
"Timedelta destination is not supported when already time travelling."
)
timestamp = time() + dest.total_seconds()
elif isinstance(dest, dt.date):
timestamp = dt.datetime.combine(
dest, dt.time(0, 0), tzinfo=dt.timezone.utc
Expand Down
22 changes: 22 additions & 0 deletions tests/test_time_machine.py
Original file line number Diff line number Diff line change
Expand Up @@ -445,6 +445,28 @@ def test_destination_generator():
assert time.time() == EPOCH + 13.0


def test_destination_delta():
now = time.time()
with time_machine.travel(dt.timedelta(seconds=3600)):
assert now + 3600 < time.time() < now + 3601


def test_destination_negative_delta():
now = time.time()
with time_machine.travel(dt.timedelta(seconds=-3600)):
assert now - 3600 < time.time() < now - 3599


@time_machine.travel(0)
def test_destination_delta_raises():
with pytest.raises(TypeError) as excinfo:
time_machine.travel(dt.timedelta(seconds=3600))

assert excinfo.value.args == (
"Timedelta destination is not supported when already time travelling.",
)


def test_traveller_object():
traveller = time_machine.travel(EPOCH + 10.0)
assert time.time() >= LIBRARY_EPOCH
Expand Down

0 comments on commit 011a8f3

Please sign in to comment.