Skip to content

Commit 8344e64

Browse files
committed
fix random bytes generation
1 parent 943d13e commit 8344e64

File tree

2 files changed

+19
-18
lines changed

2 files changed

+19
-18
lines changed

Lib/test/test_uuid.py

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -721,22 +721,23 @@ def test_uuid7(self):
721721
fake_nanoseconds = 1545052026752910643
722722
# some fake 74 = 12 + 62 random bits speared over 76 bits
723723
# are generated by generating a random 76-bit number, and
724-
# split into chunks of 62 (hi) and 12 (lo) bits. It is a
725-
rand_a = random.getrandbits(12)
726-
rand_b = random.getrandbits(62)
727-
fake_bytes = (rand_b << 12) | rand_a
728-
fake_bytes = fake_bytes.to_bytes(19, byteorder='big')
729-
730-
with mock.patch.object(self.uuid, '_last_timestamp_v7', None), \
731-
mock.patch('time.time_ns', return_value=fake_nanoseconds), \
732-
mock.patch('os.urandom', return_value=fake_bytes):
733-
u = self.uuid.uuid7()
734-
equal(u.variant, self.uuid.RFC_4122)
735-
equal(u.version, 7)
736-
fake_milliseconds = (fake_nanoseconds // 1_000_000) & 0xffffffffffff
737-
equal((u.int >> 80) & 0xffffffffffff, fake_milliseconds)
738-
equal((u.int >> 64) & 0x0fff, rand_a)
739-
equal(u.int & 0x3fffffffffffffff, rand_b)
724+
# split into chunks of 62 (hi) and 12 (lo) bits.
725+
for _ in range(100):
726+
rand_a = random.getrandbits(12)
727+
rand_b = random.getrandbits(62)
728+
fake_bytes = (rand_b << 12) | rand_a
729+
fake_bytes = fake_bytes.to_bytes(10, byteorder='big')
730+
731+
with mock.patch.object(self.uuid, '_last_timestamp_v7', None), \
732+
mock.patch('time.time_ns', return_value=fake_nanoseconds), \
733+
mock.patch('os.urandom', return_value=fake_bytes):
734+
u = self.uuid.uuid7()
735+
equal(u.variant, self.uuid.RFC_4122)
736+
equal(u.version, 7)
737+
fake_milliseconds = (fake_nanoseconds // 1_000_000) & 0xffffffffffff
738+
equal((u.int >> 80) & 0xffffffffffff, fake_milliseconds)
739+
equal((u.int >> 64) & 0x0fff, rand_a)
740+
equal(u.int & 0x3fffffffffffffff, rand_b)
740741

741742
def test_uuid8(self):
742743
equal = self.assertEqual

Lib/uuid.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -782,9 +782,9 @@ def uuid7():
782782
# Ideally, we would have 'rand_a' = first 12 bits of 'rand'
783783
# and 'rand_b' = lowest 62 bits, but it is easier to test
784784
# when we pick 'rand_a' from the lowest bits of 'rand' and
785-
# 'rand_b' from the next 62 bits, ignoring the first bits
785+
# 'rand_b' from the next 62 bits, ignoring the 6 first bits
786786
# of 'rand'.
787-
rand = int.from_bytes(os.urandom(19)) # 76 random bits (ignore 2 first)
787+
rand = int.from_bytes(os.urandom(10)) # 80 random bits (ignore 6 first)
788788
int_uuid_7 |= (rand & 0x0fff) << 64 # rand_a
789789
int_uuid_7 |= (rand >> 12) & 0x3fffffffffffffff # rand_b
790790
return UUID(int=int_uuid_7, version=7)

0 commit comments

Comments
 (0)