From 294fc77b51418d73840b528a8d9e75cb8d6bf2fe Mon Sep 17 00:00:00 2001 From: "Bernhard M. Wiedemann" Date: Mon, 29 Aug 2022 21:18:19 +0200 Subject: [PATCH] Fix a year 2038 issue the utcnow assumtion in the test failed for dates after 2038-01-19 because the date wraps back to 1902 This bug was found while working on reproducible builds for openSUSE. --- bson/objectid.py | 4 ++-- bson/tests/test_objectid.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/bson/objectid.py b/bson/objectid.py index 35061b1..60edfcc 100644 --- a/bson/objectid.py +++ b/bson/objectid.py @@ -158,7 +158,7 @@ def from_datetime(cls, generation_time): generation_time = generation_time - generation_time.utcoffset() timestamp = calendar.timegm(generation_time.timetuple()) oid = struct.pack( - ">i", int(timestamp)) + b"\x00\x00\x00\x00\x00\x00\x00\x00" + ">L", int(timestamp) & 0xFFFFFFFF) + b"\x00\x00\x00\x00\x00\x00\x00\x00" return cls(oid) @classmethod @@ -184,7 +184,7 @@ def __generate(self): """ # 4 bytes current time - oid = struct.pack(">i", int(time.time())) + oid = struct.pack(">L", int(time.time()) & 0xFFFFFFFF) # 3 bytes machine oid += ObjectId._machine_bytes diff --git a/bson/tests/test_objectid.py b/bson/tests/test_objectid.py index 52eb62b..06aadfb 100644 --- a/bson/tests/test_objectid.py +++ b/bson/tests/test_objectid.py @@ -522,7 +522,7 @@ def test_from_datetime(self): if 'PyPy 1.8.0' in sys.version: # See https://bugs.pypy.org/issue1092 raise SkipTest("datetime.timedelta is broken in pypy 1.8.0") - d = datetime.datetime.utcnow() + d = datetime.datetime.utcfromtimestamp(2000000000) d = d - datetime.timedelta(microseconds=d.microsecond) oid = ObjectId.from_datetime(d) self.assertEqual(d, oid.generation_time.replace(tzinfo=None))