Skip to content

Commit

Permalink
Merge pull request #538 from romuald/fix-time-ns-mock
Browse files Browse the repository at this point in the history
Fix time_ns() freeze rounding error
  • Loading branch information
bblommers authored Apr 23, 2024
2 parents 5b6c4a2 + 6f14dc3 commit 45d9293
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
2 changes: 1 addition & 1 deletion freezegun/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ def fake_time() -> float:
def fake_time_ns() -> int:
if _should_use_real_time():
return real_time_ns()
return int(int(fake_time()) * 1e9)
return int(fake_time() * 1e9)


def fake_localtime(t: Optional[float]=None) -> time.struct_time:
Expand Down
19 changes: 15 additions & 4 deletions tests/test_datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -749,14 +749,25 @@ def test_time_ns() -> None:
utc_time = local_time - datetime.timedelta(seconds=time.timezone)
expected_timestamp = time.mktime(utc_time.timetuple())

freezer.start()
assert time.time() == expected_timestamp
assert time.time_ns() == expected_timestamp * 1e9
freezer.stop()
with freezer:
assert time.time() == expected_timestamp
assert time.time_ns() == expected_timestamp * 1e9

assert time.time() != expected_timestamp
assert time.time_ns() != expected_timestamp * 1e9


@pytest.mark.skipif(not HAS_TIME_NS,
reason="time.time_ns is present only on 3.7 and above")
def test_time_ns_with_microseconds() -> None:
freezer = freeze_time("2024-03-20 18:21:10.12345")

with freezer:
assert time.time_ns() == 1710958870123450112

assert time.time_ns() != 1710958870123450112


def test_compare_datetime_and_time_with_timezone(monkeypatch: pytest.MonkeyPatch) -> None:
"""
Compare the result of datetime.datetime.now() and time.time() in a non-UTC timezone. These
Expand Down

0 comments on commit 45d9293

Please sign in to comment.