(self)
| 936 | self.assertSetEqual(versions, {7}) |
| 937 | |
| 938 | def test_uuid7_monotonicity(self): |
| 939 | equal = self.assertEqual |
| 940 | |
| 941 | us = [self.uuid.uuid7() for _ in range(10_000)] |
| 942 | equal(us, sorted(us)) |
| 943 | |
| 944 | with mock.patch.multiple( |
| 945 | self.uuid, |
| 946 | _last_timestamp_v7=0, |
| 947 | _last_counter_v7=0, |
| 948 | ): |
| 949 | # 1 Jan 2023 12:34:56.123_456_789 |
| 950 | timestamp_ns = 1672533296_123_456_789 # ns precision |
| 951 | timestamp_ms, _ = divmod(timestamp_ns, 1_000_000) |
| 952 | |
| 953 | # counter_{hi,lo} are chosen so that "counter + 1" does not overflow |
| 954 | counter_hi = random.getrandbits(11) |
| 955 | counter_lo = random.getrandbits(29) |
| 956 | counter = (counter_hi << 30) | counter_lo |
| 957 | self.assertLess(counter + 1, 0x3ff_ffff_ffff) |
| 958 | |
| 959 | tail = random.getrandbits(32) |
| 960 | random_bits = counter << 32 | tail |
| 961 | random_data = random_bits.to_bytes(10) |
| 962 | |
| 963 | with ( |
| 964 | mock.patch('time.time_ns', return_value=timestamp_ns), |
| 965 | mock.patch('os.urandom', return_value=random_data) as urand |
| 966 | ): |
| 967 | u1 = self.uuid.uuid7() |
| 968 | urand.assert_called_once_with(10) |
| 969 | equal(self.uuid._last_timestamp_v7, timestamp_ms) |
| 970 | equal(self.uuid._last_counter_v7, counter) |
| 971 | equal(u1.time, timestamp_ms) |
| 972 | equal((u1.int >> 64) & 0xfff, counter_hi) |
| 973 | equal((u1.int >> 32) & 0x3fff_ffff, counter_lo) |
| 974 | equal(u1.int & 0xffff_ffff, tail) |
| 975 | |
| 976 | # 1 Jan 2023 12:34:56.123_457_032 (same millisecond but not same ns) |
| 977 | next_timestamp_ns = 1672533296_123_457_032 |
| 978 | next_timestamp_ms, _ = divmod(timestamp_ns, 1_000_000) |
| 979 | equal(timestamp_ms, next_timestamp_ms) |
| 980 | |
| 981 | next_tail_bytes = os.urandom(4) |
| 982 | next_fail = int.from_bytes(next_tail_bytes) |
| 983 | |
| 984 | with ( |
| 985 | mock.patch('time.time_ns', return_value=next_timestamp_ns), |
| 986 | mock.patch('os.urandom', return_value=next_tail_bytes) as urand |
| 987 | ): |
| 988 | u2 = self.uuid.uuid7() |
| 989 | urand.assert_called_once_with(4) |
| 990 | # same milli-second |
| 991 | equal(self.uuid._last_timestamp_v7, timestamp_ms) |
| 992 | # 42-bit counter advanced by 1 |
| 993 | equal(self.uuid._last_counter_v7, counter + 1) |
| 994 | equal(u2.time, timestamp_ms) |
| 995 | equal((u2.int >> 64) & 0xfff, counter_hi) |
nothing calls this directly
no test coverage detected