Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix time_ns() freeze rounding error #538

Merged
merged 2 commits into from
Apr 23, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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:
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is totally unrelated: this test will crash pytest if the time_ns() function raises an error

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure I understand your comment. On an error, wouldn't the __exit__ code run, and thus NOT cause any other test side effects? I'm failing to see an issue, could you please elaborate?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The issue was present before the change. My comment should have said "did" crash and not "will" crash 😑

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
Loading