Skip to content

Commit 62a68b7

Browse files
authored
bpo-31784: Use time.time_ns() in uuid.uuid1() (GH-11189)
uuid.uuid1() now calls time.time_ns() rather than int(time.time() * 1e9). Replace also int(nanoseconds/100) with nanoseconds // 100. Add an unit test.
1 parent 1dd0359 commit 62a68b7

3 files changed

Lines changed: 22 additions & 2 deletions

File tree

Lib/test/test_uuid.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import shutil
1010
import subprocess
1111
import sys
12+
from unittest import mock
1213

1314
py_uuid = support.import_fresh_module('uuid', blocked=['_uuid'])
1415
c_uuid = support.import_fresh_module('uuid', fresh=['_uuid'])
@@ -567,6 +568,23 @@ def test_uuid1_bogus_return_value(self):
567568
u = self.uuid.uuid1()
568569
self.assertEqual(u.is_safe, self.uuid.SafeUUID.unknown)
569570

571+
def test_uuid1_time(self):
572+
with mock.patch.object(self.uuid, '_has_uuid_generate_time_safe', False), \
573+
mock.patch.object(self.uuid, '_generate_time_safe', None), \
574+
mock.patch.object(self.uuid, '_last_timestamp', None), \
575+
mock.patch.object(self.uuid, 'getnode', return_value=93328246233727), \
576+
mock.patch('time.time_ns', return_value=1545052026752910643), \
577+
mock.patch('random.getrandbits', return_value=5317): # guaranteed to be random
578+
u = self.uuid.uuid1()
579+
self.assertEqual(u, self.uuid.UUID('a7a55b92-01fc-11e9-94c5-54e1acf6da7f'))
580+
581+
with mock.patch.object(self.uuid, '_has_uuid_generate_time_safe', False), \
582+
mock.patch.object(self.uuid, '_generate_time_safe', None), \
583+
mock.patch.object(self.uuid, '_last_timestamp', None), \
584+
mock.patch('time.time_ns', return_value=1545052026752910643):
585+
u = self.uuid.uuid1(node=93328246233727, clock_seq=5317)
586+
self.assertEqual(u, self.uuid.UUID('a7a55b92-01fc-11e9-94c5-54e1acf6da7f'))
587+
570588
def test_uuid3(self):
571589
equal = self.assertEqual
572590

Lib/uuid.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -728,10 +728,10 @@ def uuid1(node=None, clock_seq=None):
728728

729729
global _last_timestamp
730730
import time
731-
nanoseconds = int(time.time() * 1e9)
731+
nanoseconds = time.time_ns()
732732
# 0x01b21dd213814000 is the number of 100-ns intervals between the
733733
# UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00.
734-
timestamp = int(nanoseconds/100) + 0x01b21dd213814000
734+
timestamp = nanoseconds // 100 + 0x01b21dd213814000
735735
if _last_timestamp is not None and timestamp <= _last_timestamp:
736736
timestamp = _last_timestamp + 1
737737
_last_timestamp = timestamp
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
:func:`uuid.uuid1` now calls :func:`time.time_ns` rather than
2+
``int(time.time() * 1e9)``.

0 commit comments

Comments
 (0)