From 6ad237dd6479934c617728fea17bc156a33934b5 Mon Sep 17 00:00:00 2001 From: Jeff Nettleton Date: Thu, 20 Oct 2022 14:23:51 -0700 Subject: [PATCH] Correct ticking behavior with `time.time_ns()` Previously, when `freeze_time(..., tick=True)` was used in conjunction with functions that called out to `time.time_ns()`, identical values were being returned. This was caused by the existing version of `fake_time_ns` rounding off the last nine digits of the returned integer value -- ensuring that each tick would be erased. This commit only casts to `int` _after_ the value has been shifted by `1e9`, rather than before _and_ after. --- freezegun/api.py | 2 +- tests/test_ticking.py | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/freezegun/api.py b/freezegun/api.py index bcc83a6e..01ab29ac 100644 --- a/freezegun/api.py +++ b/freezegun/api.py @@ -180,7 +180,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_ticking.py b/tests/test_ticking.py index e29ce070..0fea463b 100644 --- a/tests/test_ticking.py +++ b/tests/test_ticking.py @@ -63,6 +63,15 @@ def test_ticking_time(): assert time.time() > 1326585599.0 +@utils.cpython_only +def test_ticking_time_ns(): + with freeze_time("Jan 14th, 2012, 23:59:59", tick=True): + first_value = time.time_ns() + second_value = time.time_ns() + + assert first_value != second_value + + @utils.cpython_only_mark @pytest.mark.parametrize("func_name", ("monotonic", "monotonic_ns", "perf_counter", "perf_counter_ns"),