Skip to content

Commit

Permalink
Fix time_ns() freeze rounding error
Browse files Browse the repository at this point in the history
The previous behavior of time_ns() mock did round the value of the
frozen date to the seconds, excluding the microseconds if specified

This is mostly problematic when freeze_time() is used with the uuid1()
method: multiple "frozen" dates within the same second would all
generate the same uuid
  • Loading branch information
romuald committed Mar 20, 2024
1 parent c65f4db commit 9591645
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 @@ -183,7 +183,7 @@ def fake_time():
def fake_time_ns():
if _should_use_real_time():
return real_time_ns()
return int(int(fake_time()) * 1e9)
return int(fake_time() * 1e9)


def fake_localtime(t=None):
Expand Down
19 changes: 15 additions & 4 deletions tests/test_datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -759,14 +759,25 @@ def test_time_ns():
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():
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):
"""
Compare the result of datetime.datetime.now() and time.time() in a non-UTC timezone. These
Expand Down

0 comments on commit 9591645

Please sign in to comment.