From 9591645e0fd49b54bab688ac7eeeec14b87a9226 Mon Sep 17 00:00:00 2001 From: Romuald Brunet Date: Wed, 20 Mar 2024 18:35:38 +0100 Subject: [PATCH] Fix time_ns() freeze rounding error 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 --- freezegun/api.py | 2 +- tests/test_datetimes.py | 19 +++++++++++++++---- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/freezegun/api.py b/freezegun/api.py index 43b117eb..10a1fbe8 100644 --- a/freezegun/api.py +++ b/freezegun/api.py @@ -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): diff --git a/tests/test_datetimes.py b/tests/test_datetimes.py index 0632f9ff..d22c593e 100644 --- a/tests/test_datetimes.py +++ b/tests/test_datetimes.py @@ -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