From 408aaf62b3d2f64e781ce4bb9608c3ca513aa8b7 Mon Sep 17 00:00:00 2001 From: Morten Brekkevold Date: Tue, 27 Feb 2024 15:06:03 +0100 Subject: [PATCH 1/2] Don't test epoch values against naive datetimes When running the test suite on a machine set to the UTC timezone, `test_find_timestamp` would fail, because the datetime object used to seed the value is timezone-naive. The test would work fine in UTC+1 timezones, but not in other timezones. --- tests/unittests/general/prefix_ip_collector_test.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/unittests/general/prefix_ip_collector_test.py b/tests/unittests/general/prefix_ip_collector_test.py index f90b84dbf4..a6655113b0 100644 --- a/tests/unittests/general/prefix_ip_collector_test.py +++ b/tests/unittests/general/prefix_ip_collector_test.py @@ -3,7 +3,7 @@ """Tests for prefix_ip_collector""" import unittest -from datetime import datetime +from datetime import datetime, timezone from nav.activeipcollector.manager import find_range, get_timestamp @@ -14,5 +14,5 @@ def test_find_range(self): self.assertEqual(find_range('2001:700:0:251e::/64'), 0) def test_find_timestamp(self): - ts = datetime(2012, 10, 4, 14, 30) - self.assertEqual(get_timestamp(ts), 1349353800) + ts = datetime(2012, 10, 4, 14, 30, tzinfo=timezone.utc) + self.assertEqual(get_timestamp(ts), 1349361000) From 8ff73b0aa2e58898ed17901ab4be03346ab884af Mon Sep 17 00:00:00 2001 From: Morten Brekkevold Date: Tue, 27 Feb 2024 15:11:41 +0100 Subject: [PATCH 2/2] Refactor `get_timestamp()` No need to get convoluted about how a unix timestamp is derived from a datetime object - it's right there in its methods. Also adds type annotations to make it easer to reason about what the arguments and results are. --- python/nav/activeipcollector/manager.py | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/python/nav/activeipcollector/manager.py b/python/nav/activeipcollector/manager.py index ae52ccd392..99ba4c0edc 100644 --- a/python/nav/activeipcollector/manager.py +++ b/python/nav/activeipcollector/manager.py @@ -16,9 +16,11 @@ # License along with NAV. If not, see . # """Manage collection and storing of active ip-addresses statistics""" - +import datetime import logging import time +from typing import Optional + from IPy import IP import nav.activeipcollector.collector as collector @@ -82,11 +84,7 @@ def find_range(prefix): return 0 -def get_timestamp(timestamp=None): +def get_timestamp(timestamp: Optional[datetime.datetime] = None) -> int: """Find timestamp closest to 30 minutes intervals""" - def get_epoch(): - """Find epoch from a datetime object""" - return int(time.mktime(timestamp.timetuple())) - - return get_epoch() if timestamp else int(time.time()) + return timestamp.timestamp() if timestamp else int(time.time())