Debian Codegraph @

Lib/test/test_uuid.py

raw
1 import builtins
2 import contextlib
3 import copy
4 import enum
5 import io
6 import os
7 import pickle
8 import random
9 import sys
10 import unittest
11 import weakref
12 from itertools import product
13 from unittest import mock
14
15 from test import support
16 from test.support import import_helper
17 from test.support.script_helper import assert_python_ok
18
19 py_uuid = import_helper.import_fresh_module('uuid', blocked=['_uuid'])
20 c_uuid = import_helper.import_fresh_module('uuid', fresh=['_uuid'])
21
22 def importable(name):
23 try:
24 __import__(name)
25 return True
26 except ModuleNotFoundError:
27 return False
28
29
30 def mock_get_command_stdout(data):
31 def get_command_stdout(command, args):
32 return io.BytesIO(data.encode())
33 return get_command_stdout
34
35
36 class BaseTestUUID:
37 uuid = None
38
39 def test_nil_uuid(self):
40 nil_uuid = self.uuid.NIL
41
42 s = '00000000-0000-0000-0000-000000000000'
43 i = 0
44 self.assertEqual(nil_uuid, self.uuid.UUID(s))
45 self.assertEqual(nil_uuid, self.uuid.UUID(int=i))
46 self.assertEqual(nil_uuid.int, i)
47 self.assertEqual(str(nil_uuid), s)
48 # The Nil UUID falls within the range of the Apollo NCS variant as per
49 # RFC 9562.
50 # See https://www.rfc-editor.org/rfc/rfc9562.html#section-5.9-4
51 self.assertEqual(nil_uuid.variant, self.uuid.RESERVED_NCS)
52 # A version field of all zeros is "Unused" in RFC 9562, but the version
53 # field also only applies to the 10xx variant, i.e. the variant
54 # specified in RFC 9562. As such, because the Nil UUID falls under a
55 # different variant, its version is considered undefined.
56 # See https://www.rfc-editor.org/rfc/rfc9562.html#table2
57 self.assertIsNone(nil_uuid.version)
58
59 def test_max_uuid(self):
60 max_uuid = self.uuid.MAX
61
62 s = 'ffffffff-ffff-ffff-ffff-ffffffffffff'
63 i = (1 << 128) - 1
64 self.assertEqual(max_uuid, self.uuid.UUID(s))
65 self.assertEqual(max_uuid, self.uuid.UUID(int=i))
66 self.assertEqual(max_uuid.int, i)
67 self.assertEqual(str(max_uuid), s)
68 # The Max UUID falls within the range of the "yet-to-be defined" future
69 # UUID variant as per RFC 9562.
70 # See https://www.rfc-editor.org/rfc/rfc9562.html#section-5.10-4
71 self.assertEqual(max_uuid.variant, self.uuid.RESERVED_FUTURE)
72 # A version field of all ones is "Reserved for future definition" in
73 # RFC 9562, but the version field also only applies to the 10xx
74 # variant, i.e. the variant specified in RFC 9562. As such, because the
75 # Max UUID falls under a different variant, its version is considered
76 # undefined.
77 # See https://www.rfc-editor.org/rfc/rfc9562.html#table2
78 self.assertIsNone(max_uuid.version)
79
80 def test_safe_uuid_enum(self):
81 class CheckedSafeUUID(enum.Enum):
82 safe = 0
83 unsafe = -1
84 unknown = None
85 enum._test_simple_enum(CheckedSafeUUID, py_uuid.SafeUUID)
86
87 def test_UUID(self):
88 equal = self.assertEqual
89 ascending = []
90 for (string, curly, hex, bytes, bytes_le, fields, integer, urn,
91 time, clock_seq, variant, version) in [
92 ('00000000-0000-0000-0000-000000000000',
93 '{00000000-0000-0000-0000-000000000000}',
94 '00000000000000000000000000000000',
95 b'\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0',
96 b'\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0',
97 (0, 0, 0, 0, 0, 0),
98 0,
99 'urn:uuid:00000000-0000-0000-0000-000000000000',
100 0, 0, self.uuid.RESERVED_NCS, None),
101 ('00010203-0405-0607-0809-0a0b0c0d0e0f',
102 '{00010203-0405-0607-0809-0a0b0c0d0e0f}',
103 '000102030405060708090a0b0c0d0e0f',
104 b'\0\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\x0d\x0e\x0f',
105 b'\x03\x02\x01\0\x05\x04\x07\x06\x08\t\n\x0b\x0c\x0d\x0e\x0f',
106 (0x00010203, 0x0405, 0x0607, 8, 9, 0x0a0b0c0d0e0f),
107 0x000102030405060708090a0b0c0d0e0f,
108 'urn:uuid:00010203-0405-0607-0809-0a0b0c0d0e0f',
109 0x607040500010203, 0x809, self.uuid.RESERVED_NCS, None),
110 ('02d9e6d5-9467-382e-8f9b-9300a64ac3cd',
111 '{02d9e6d5-9467-382e-8f9b-9300a64ac3cd}',
112 '02d9e6d59467382e8f9b9300a64ac3cd',
113 b'\x02\xd9\xe6\xd5\x94\x67\x38\x2e\x8f\x9b\x93\x00\xa6\x4a\xc3\xcd',
114 b'\xd5\xe6\xd9\x02\x67\x94\x2e\x38\x8f\x9b\x93\x00\xa6\x4a\xc3\xcd',
115 (0x02d9e6d5, 0x9467, 0x382e, 0x8f, 0x9b, 0x9300a64ac3cd),
116 0x02d9e6d59467382e8f9b9300a64ac3cd,
117 'urn:uuid:02d9e6d5-9467-382e-8f9b-9300a64ac3cd',
118 0x82e946702d9e6d5, 0xf9b, self.uuid.RFC_4122, 3),
119 ('12345678-1234-5678-1234-567812345678',
120 '{12345678-1234-5678-1234-567812345678}',
121 '12345678123456781234567812345678',
122 b'\x12\x34\x56\x78'*4,
123 b'\x78\x56\x34\x12\x34\x12\x78\x56\x12\x34\x56\x78\x12\x34\x56\x78',
124 (0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678),
125 0x12345678123456781234567812345678,
126 'urn:uuid:12345678-1234-5678-1234-567812345678',
127 0x678123412345678, 0x1234, self.uuid.RESERVED_NCS, None),
128 ('6ba7b810-9dad-11d1-80b4-00c04fd430c8',
129 '{6ba7b810-9dad-11d1-80b4-00c04fd430c8}',
130 '6ba7b8109dad11d180b400c04fd430c8',
131 b'\x6b\xa7\xb8\x10\x9d\xad\x11\xd1\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
132 b'\x10\xb8\xa7\x6b\xad\x9d\xd1\x11\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
133 (0x6ba7b810, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8),
134 0x6ba7b8109dad11d180b400c04fd430c8,
135 'urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8',
136 0x1d19dad6ba7b810, 0xb4, self.uuid.RFC_4122, 1),
137 ('6ba7b811-9dad-11d1-80b4-00c04fd430c8',
138 '{6ba7b811-9dad-11d1-80b4-00c04fd430c8}',
139 '6ba7b8119dad11d180b400c04fd430c8',
140 b'\x6b\xa7\xb8\x11\x9d\xad\x11\xd1\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
141 b'\x11\xb8\xa7\x6b\xad\x9d\xd1\x11\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
142 (0x6ba7b811, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8),
143 0x6ba7b8119dad11d180b400c04fd430c8,
144 'urn:uuid:6ba7b811-9dad-11d1-80b4-00c04fd430c8',
145 0x1d19dad6ba7b811, 0xb4, self.uuid.RFC_4122, 1),
146 ('6ba7b812-9dad-11d1-80b4-00c04fd430c8',
147 '{6ba7b812-9dad-11d1-80b4-00c04fd430c8}',
148 '6ba7b8129dad11d180b400c04fd430c8',
149 b'\x6b\xa7\xb8\x12\x9d\xad\x11\xd1\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
150 b'\x12\xb8\xa7\x6b\xad\x9d\xd1\x11\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
151 (0x6ba7b812, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8),
152 0x6ba7b8129dad11d180b400c04fd430c8,
153 'urn:uuid:6ba7b812-9dad-11d1-80b4-00c04fd430c8',
154 0x1d19dad6ba7b812, 0xb4, self.uuid.RFC_4122, 1),
155 ('6ba7b814-9dad-11d1-80b4-00c04fd430c8',
156 '{6ba7b814-9dad-11d1-80b4-00c04fd430c8}',
157 '6ba7b8149dad11d180b400c04fd430c8',
158 b'\x6b\xa7\xb8\x14\x9d\xad\x11\xd1\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
159 b'\x14\xb8\xa7\x6b\xad\x9d\xd1\x11\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
160 (0x6ba7b814, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8),
161 0x6ba7b8149dad11d180b400c04fd430c8,
162 'urn:uuid:6ba7b814-9dad-11d1-80b4-00c04fd430c8',
163 0x1d19dad6ba7b814, 0xb4, self.uuid.RFC_4122, 1),
164 ('7d444840-9dc0-11d1-b245-5ffdce74fad2',
165 '{7d444840-9dc0-11d1-b245-5ffdce74fad2}',
166 '7d4448409dc011d1b2455ffdce74fad2',
167 b'\x7d\x44\x48\x40\x9d\xc0\x11\xd1\xb2\x45\x5f\xfd\xce\x74\xfa\xd2',
168 b'\x40\x48\x44\x7d\xc0\x9d\xd1\x11\xb2\x45\x5f\xfd\xce\x74\xfa\xd2',
169 (0x7d444840, 0x9dc0, 0x11d1, 0xb2, 0x45, 0x5ffdce74fad2),
170 0x7d4448409dc011d1b2455ffdce74fad2,
171 'urn:uuid:7d444840-9dc0-11d1-b245-5ffdce74fad2',
172 0x1d19dc07d444840, 0x3245, self.uuid.RFC_4122, 1),
173 ('e902893a-9d22-3c7e-a7b8-d6e313b71d9f',
174 '{e902893a-9d22-3c7e-a7b8-d6e313b71d9f}',
175 'e902893a9d223c7ea7b8d6e313b71d9f',
176 b'\xe9\x02\x89\x3a\x9d\x22\x3c\x7e\xa7\xb8\xd6\xe3\x13\xb7\x1d\x9f',
177 b'\x3a\x89\x02\xe9\x22\x9d\x7e\x3c\xa7\xb8\xd6\xe3\x13\xb7\x1d\x9f',
178 (0xe902893a, 0x9d22, 0x3c7e, 0xa7, 0xb8, 0xd6e313b71d9f),
179 0xe902893a9d223c7ea7b8d6e313b71d9f,
180 'urn:uuid:e902893a-9d22-3c7e-a7b8-d6e313b71d9f',
181 0xc7e9d22e902893a, 0x27b8, self.uuid.RFC_4122, 3),
182 ('eb424026-6f54-4ef8-a4d0-bb658a1fc6cf',
183 '{eb424026-6f54-4ef8-a4d0-bb658a1fc6cf}',
184 'eb4240266f544ef8a4d0bb658a1fc6cf',
185 b'\xeb\x42\x40\x26\x6f\x54\x4e\xf8\xa4\xd0\xbb\x65\x8a\x1f\xc6\xcf',
186 b'\x26\x40\x42\xeb\x54\x6f\xf8\x4e\xa4\xd0\xbb\x65\x8a\x1f\xc6\xcf',
187 (0xeb424026, 0x6f54, 0x4ef8, 0xa4, 0xd0, 0xbb658a1fc6cf),
188 0xeb4240266f544ef8a4d0bb658a1fc6cf,
189 'urn:uuid:eb424026-6f54-4ef8-a4d0-bb658a1fc6cf',
190 0xef86f54eb424026, 0x24d0, self.uuid.RFC_4122, 4),
191 ('f81d4fae-7dec-11d0-a765-00a0c91e6bf6',
192 '{f81d4fae-7dec-11d0-a765-00a0c91e6bf6}',
193 'f81d4fae7dec11d0a76500a0c91e6bf6',
194 b'\xf8\x1d\x4f\xae\x7d\xec\x11\xd0\xa7\x65\x00\xa0\xc9\x1e\x6b\xf6',
195 b'\xae\x4f\x1d\xf8\xec\x7d\xd0\x11\xa7\x65\x00\xa0\xc9\x1e\x6b\xf6',
196 (0xf81d4fae, 0x7dec, 0x11d0, 0xa7, 0x65, 0x00a0c91e6bf6),
197 0xf81d4fae7dec11d0a76500a0c91e6bf6,
198 'urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6',
199 0x1d07decf81d4fae, 0x2765, self.uuid.RFC_4122, 1),
200 ('fffefdfc-fffe-fffe-fffe-fffefdfcfbfa',
201 '{fffefdfc-fffe-fffe-fffe-fffefdfcfbfa}',
202 'fffefdfcfffefffefffefffefdfcfbfa',
203 b'\xff\xfe\xfd\xfc\xff\xfe\xff\xfe\xff\xfe\xff\xfe\xfd\xfc\xfb\xfa',
204 b'\xfc\xfd\xfe\xff\xfe\xff\xfe\xff\xff\xfe\xff\xfe\xfd\xfc\xfb\xfa',
205 (0xfffefdfc, 0xfffe, 0xfffe, 0xff, 0xfe, 0xfffefdfcfbfa),
206 0xfffefdfcfffefffefffefffefdfcfbfa,
207 'urn:uuid:fffefdfc-fffe-fffe-fffe-fffefdfcfbfa',
208 0xffefffefffefdfc, 0x3ffe, self.uuid.RESERVED_FUTURE, None),
209 ('ffffffff-ffff-ffff-ffff-ffffffffffff',
210 '{ffffffff-ffff-ffff-ffff-ffffffffffff}',
211 'ffffffffffffffffffffffffffffffff',
212 b'\xff'*16,
213 b'\xff'*16,
214 (0xffffffff, 0xffff, 0xffff, 0xff, 0xff, 0xffffffffffff),
215 0xffffffffffffffffffffffffffffffff,
216 'urn:uuid:ffffffff-ffff-ffff-ffff-ffffffffffff',
217 0xfffffffffffffff, 0x3fff, self.uuid.RESERVED_FUTURE, None),
218 ]:
219 equivalents = []
220 # Construct each UUID in several different ways.
221 for u in [self.uuid.UUID(string), self.uuid.UUID(curly), self.uuid.UUID(hex),
222 self.uuid.UUID(bytes=bytes), self.uuid.UUID(bytes_le=bytes_le),
223 self.uuid.UUID(fields=fields), self.uuid.UUID(int=integer),
224 self.uuid.UUID(urn)]:
225 # Test all conversions and properties of the UUID object.
226 equal(str(u), string)
227 equal(int(u), integer)
228 equal(u.bytes, bytes)
229 equal(u.bytes_le, bytes_le)
230 equal(u.fields, fields)
231 equal(u.time_low, fields[0])
232 equal(u.time_mid, fields[1])
233 equal(u.time_hi_version, fields[2])
234 equal(u.clock_seq_hi_variant, fields[3])
235 equal(u.clock_seq_low, fields[4])
236 equal(u.node, fields[5])
237 equal(u.hex, hex)
238 equal(u.int, integer)
239 equal(u.urn, urn)
240 equal(u.time, time)
241 equal(u.clock_seq, clock_seq)
242 equal(u.variant, variant)
243 equal(u.version, version)
244 equivalents.append(u)
245
246 # Different construction methods should give the same UUID.
247 for u in equivalents:
248 for v in equivalents:
249 equal(u, v)
250
251 # Bug 7380: "bytes" and "bytes_le" should give the same type.
252 equal(type(u.bytes), builtins.bytes)
253 equal(type(u.bytes_le), builtins.bytes)
254
255 ascending.append(u)
256
257 # Test comparison of UUIDs.
258 for i in range(len(ascending)):
259 for j in range(len(ascending)):
260 equal(i < j, ascending[i] < ascending[j])
261 equal(i <= j, ascending[i] <= ascending[j])
262 equal(i == j, ascending[i] == ascending[j])
263 equal(i > j, ascending[i] > ascending[j])
264 equal(i >= j, ascending[i] >= ascending[j])
265 equal(i != j, ascending[i] != ascending[j])
266
267 # Test sorting of UUIDs (above list is in ascending order).
268 resorted = ascending[:]
269 resorted.reverse()
270 resorted.sort()
271 equal(ascending, resorted)
272
273 def test_exceptions(self):
274 badvalue = lambda f: self.assertRaises(ValueError, f)
275 badtype = lambda f: self.assertRaises(TypeError, f)
276
277 # Badly formed hex strings.
278 badvalue(lambda: self.uuid.UUID(''))
279 badvalue(lambda: self.uuid.UUID('abc'))
280 badvalue(lambda: self.uuid.UUID('1234567812345678123456781234567'))
281 badvalue(lambda: self.uuid.UUID('123456781234567812345678123456789'))
282 badvalue(lambda: self.uuid.UUID('123456781234567812345678z2345678'))
283
284 # Badly formed bytes.
285 badvalue(lambda: self.uuid.UUID(bytes='abc'))
286 badvalue(lambda: self.uuid.UUID(bytes='\0'*15))
287 badvalue(lambda: self.uuid.UUID(bytes='\0'*17))
288
289 # Badly formed bytes_le.
290 badvalue(lambda: self.uuid.UUID(bytes_le='abc'))
291 badvalue(lambda: self.uuid.UUID(bytes_le='\0'*15))
292 badvalue(lambda: self.uuid.UUID(bytes_le='\0'*17))
293
294 # Badly formed fields.
295 badvalue(lambda: self.uuid.UUID(fields=(1,)))
296 badvalue(lambda: self.uuid.UUID(fields=(1, 2, 3, 4, 5)))
297 badvalue(lambda: self.uuid.UUID(fields=(1, 2, 3, 4, 5, 6, 7)))
298
299 # Field values out of range.
300 badvalue(lambda: self.uuid.UUID(fields=(-1, 0, 0, 0, 0, 0)))
301 badvalue(lambda: self.uuid.UUID(fields=(0x100000000, 0, 0, 0, 0, 0)))
302 badvalue(lambda: self.uuid.UUID(fields=(0, -1, 0, 0, 0, 0)))
303 badvalue(lambda: self.uuid.UUID(fields=(0, 0x10000, 0, 0, 0, 0)))
304 badvalue(lambda: self.uuid.UUID(fields=(0, 0, -1, 0, 0, 0)))
305 badvalue(lambda: self.uuid.UUID(fields=(0, 0, 0x10000, 0, 0, 0)))
306 badvalue(lambda: self.uuid.UUID(fields=(0, 0, 0, -1, 0, 0)))
307 badvalue(lambda: self.uuid.UUID(fields=(0, 0, 0, 0x100, 0, 0)))
308 badvalue(lambda: self.uuid.UUID(fields=(0, 0, 0, 0, -1, 0)))
309 badvalue(lambda: self.uuid.UUID(fields=(0, 0, 0, 0, 0x100, 0)))
310 badvalue(lambda: self.uuid.UUID(fields=(0, 0, 0, 0, 0, -1)))
311 badvalue(lambda: self.uuid.UUID(fields=(0, 0, 0, 0, 0, 0x1000000000000)))
312
313 # Version number out of range.
314 badvalue(lambda: self.uuid.UUID('00'*16, version=0))
315 badvalue(lambda: self.uuid.UUID('00'*16, version=42))
316
317 # Integer value out of range.
318 badvalue(lambda: self.uuid.UUID(int=-1))
319 badvalue(lambda: self.uuid.UUID(int=1<<128))
320
321 # Must supply exactly one of hex, bytes, fields, int.
322 h, b, f, i = '00'*16, b'\0'*16, (0, 0, 0, 0, 0, 0), 0
323 self.uuid.UUID(h)
324 self.uuid.UUID(hex=h)
325 self.uuid.UUID(bytes=b)
326 self.uuid.UUID(bytes_le=b)
327 self.uuid.UUID(fields=f)
328 self.uuid.UUID(int=i)
329
330 # Wrong number of arguments (positional).
331 badtype(lambda: self.uuid.UUID())
332 badtype(lambda: self.uuid.UUID(h, b))
333 badtype(lambda: self.uuid.UUID(h, b, b))
334 badtype(lambda: self.uuid.UUID(h, b, b, f))
335 badtype(lambda: self.uuid.UUID(h, b, b, f, i))
336
337 # Duplicate arguments.
338 for hh in [[], [('hex', h)]]:
339 for bb in [[], [('bytes', b)]]:
340 for bble in [[], [('bytes_le', b)]]:
341 for ii in [[], [('int', i)]]:
342 for ff in [[], [('fields', f)]]:
343 args = dict(hh + bb + bble + ii + ff)
344 if len(args) != 0:
345 badtype(lambda: self.uuid.UUID(h, **args))
346 if len(args) != 1:
347 badtype(lambda: self.uuid.UUID(**args))
348
349 # Immutability.
350 u = self.uuid.UUID(h)
351 badtype(lambda: setattr(u, 'hex', h))
352 badtype(lambda: setattr(u, 'bytes', b))
353 badtype(lambda: setattr(u, 'bytes_le', b))
354 badtype(lambda: setattr(u, 'fields', f))
355 badtype(lambda: setattr(u, 'int', i))
356 badtype(lambda: setattr(u, 'time_low', 0))
357 badtype(lambda: setattr(u, 'time_mid', 0))
358 badtype(lambda: setattr(u, 'time_hi_version', 0))
359 badtype(lambda: setattr(u, 'time_hi_version', 0))
360 badtype(lambda: setattr(u, 'clock_seq_hi_variant', 0))
361 badtype(lambda: setattr(u, 'clock_seq_low', 0))
362 badtype(lambda: setattr(u, 'node', 0))
363
364 # Comparison with a non-UUID object
365 badtype(lambda: u < object())
366 badtype(lambda: u > object())
367
368 def test_getnode(self):
369 node1 = self.uuid.getnode()
370 self.assertTrue(0 < node1 < (1 << 48), '%012x' % node1)
371
372 # Test it again to ensure consistency.
373 node2 = self.uuid.getnode()
374 self.assertEqual(node1, node2, '%012x != %012x' % (node1, node2))
375
376 def test_pickle_roundtrip(self):
377 def check(actual, expected):
378 self.assertEqual(actual, expected)
379 self.assertEqual(actual.is_safe, expected.is_safe)
380
381 with support.swap_item(sys.modules, 'uuid', self.uuid):
382 for is_safe in self.uuid.SafeUUID:
383 u = self.uuid.UUID('d82579ce6642a0de7ddf490a7aec7aa5',
384 is_safe=is_safe)
385 check(copy.copy(u), u)
386 check(copy.deepcopy(u), u)
387 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
388 with self.subTest(protocol=proto):
389 check(pickle.loads(pickle.dumps(u, proto)), u)
390
391 def test_unpickle_previous_python_versions(self):
392 def check(actual, expected):
393 self.assertEqual(actual, expected)
394 self.assertEqual(actual.is_safe, expected.is_safe)
395
396 pickled_uuids = [
397 # Python 2.7, protocol 0
398 b'ccopy_reg\n_reconstructor\n(cuuid\nUUID\nc__builtin__\nobject\nN'
399 b'tR(dS\'int\'\nL287307832597519156748809049798316161701L\nsb.',
400 # Python 2.7, protocol 1
401 b'ccopy_reg\n_reconstructor\n(cuuid\nUUID\nc__builtin__\nobject\nN'
402 b'tR}U\x03intL287307832597519156748809049798316161701L\nsb.',
403 # Python 2.7, protocol 2
404 b'\x80\x02cuuid\nUUID\n)\x81}U\x03int\x8a\x11\xa5z\xecz\nI\xdf}'
405 b'\xde\xa0Bf\xcey%\xd8\x00sb.',
406 # Python 3.6, protocol 0
407 b'ccopy_reg\n_reconstructor\n(cuuid\nUUID\nc__builtin__\nobject\nN'
408 b'tR(dVint\nL287307832597519156748809049798316161701L\nsb.',
409 # Python 3.6, protocol 1
410 b'ccopy_reg\n_reconstructor\n(cuuid\nUUID\nc__builtin__\nobject\nN'
411 b'tR}X\x03\x00\x00\x00intL287307832597519156748809049798316161701L'
412 b'\nsb.',
413 # Python 3.6, protocol 2
414 b'\x80\x02cuuid\nUUID\n)\x81}X\x03\x00\x00\x00int\x8a\x11\xa5z\xec'
415 b'z\nI\xdf}\xde\xa0Bf\xcey%\xd8\x00sb.',
416 # Python 3.6, protocol 3
417 b'\x80\x03cuuid\nUUID\n)\x81}X\x03\x00\x00\x00int\x8a\x11\xa5z\xec'
418 b'z\nI\xdf}\xde\xa0Bf\xcey%\xd8\x00sb.',
419 # Python 3.6, protocol 4
420 b'\x80\x04\x95+\x00\x00\x00\x00\x00\x00\x00\x8c\x04uuid\x8c\x04UUI'
421 b'D\x93)\x81}\x8c\x03int\x8a\x11\xa5z\xecz\nI\xdf}\xde\xa0Bf\xcey%'
422 b'\xd8\x00sb.',
423 # Python 3.7, protocol 0
424 b'ccopy_reg\n_reconstructor\n(cuuid\nUUID\nc__builtin__\nobject\nN'
425 b'tR(dVint\nL287307832597519156748809049798316161701L\nsVis_safe\n'
426 b'cuuid\nSafeUUID\n(NtRsb.',
427 # Python 3.7, protocol 1
428 b'ccopy_reg\n_reconstructor\n(cuuid\nUUID\nc__builtin__\nobject\nN'
429 b'tR}(X\x03\x00\x00\x00intL287307832597519156748809049798316161701'
430 b'L\nX\x07\x00\x00\x00is_safecuuid\nSafeUUID\n(NtRub.',
431 # Python 3.7, protocol 2
432 b'\x80\x02cuuid\nUUID\n)\x81}(X\x03\x00\x00\x00int\x8a\x11\xa5z'
433 b'\xecz\nI\xdf}\xde\xa0Bf\xcey%\xd8\x00X\x07\x00\x00\x00is_safecuu'
434 b'id\nSafeUUID\nN\x85Rub.',
435 # Python 3.7, protocol 3
436 b'\x80\x03cuuid\nUUID\n)\x81}(X\x03\x00\x00\x00int\x8a\x11\xa5z'
437 b'\xecz\nI\xdf}\xde\xa0Bf\xcey%\xd8\x00X\x07\x00\x00\x00is_safecuu'
438 b'id\nSafeUUID\nN\x85Rub.',
439 # Python 3.7, protocol 4
440 b'\x80\x04\x95F\x00\x00\x00\x00\x00\x00\x00\x8c\x04uuid\x94\x8c'
441 b'\x04UUID\x93)\x81}(\x8c\x03int\x8a\x11\xa5z\xecz\nI\xdf}\xde\xa0'
442 b'Bf\xcey%\xd8\x00\x8c\x07is_safeh\x00\x8c\x08SafeUUID\x93N\x85Rub'
443 b'.',
444 ]
445 pickled_uuids_safe = [
446 # Python 3.7, protocol 0
447 b'ccopy_reg\n_reconstructor\n(cuuid\nUUID\nc__builtin__\nobject\nN'
448 b'tR(dVint\nL287307832597519156748809049798316161701L\nsVis_safe\n'
449 b'cuuid\nSafeUUID\n(I0\ntRsb.',
450 # Python 3.7, protocol 1
451 b'ccopy_reg\n_reconstructor\n(cuuid\nUUID\nc__builtin__\nobject\nN'
452 b'tR}(X\x03\x00\x00\x00intL287307832597519156748809049798316161701'
453 b'L\nX\x07\x00\x00\x00is_safecuuid\nSafeUUID\n(K\x00tRub.',
454 # Python 3.7, protocol 2
455 b'\x80\x02cuuid\nUUID\n)\x81}(X\x03\x00\x00\x00int\x8a\x11\xa5z'
456 b'\xecz\nI\xdf}\xde\xa0Bf\xcey%\xd8\x00X\x07\x00\x00\x00is_safecuu'
457 b'id\nSafeUUID\nK\x00\x85Rub.',
458 # Python 3.7, protocol 3
459 b'\x80\x03cuuid\nUUID\n)\x81}(X\x03\x00\x00\x00int\x8a\x11\xa5z'
460 b'\xecz\nI\xdf}\xde\xa0Bf\xcey%\xd8\x00X\x07\x00\x00\x00is_safecuu'
461 b'id\nSafeUUID\nK\x00\x85Rub.',
462 # Python 3.7, protocol 4
463 b'\x80\x04\x95G\x00\x00\x00\x00\x00\x00\x00\x8c\x04uuid\x94\x8c'
464 b'\x04UUID\x93)\x81}(\x8c\x03int\x8a\x11\xa5z\xecz\nI\xdf}\xde\xa0'
465 b'Bf\xcey%\xd8\x00\x8c\x07is_safeh\x00\x8c\x08SafeUUID\x93K\x00'
466 b'\x85Rub.',
467 ]
468 pickled_uuids_unsafe = [
469 # Python 3.7, protocol 0
470 b'ccopy_reg\n_reconstructor\n(cuuid\nUUID\nc__builtin__\nobject\nN'
471 b'tR(dVint\nL287307832597519156748809049798316161701L\nsVis_safe\n'
472 b'cuuid\nSafeUUID\n(I-1\ntRsb.',
473 # Python 3.7, protocol 1
474 b'ccopy_reg\n_reconstructor\n(cuuid\nUUID\nc__builtin__\nobject\nN'
475 b'tR}(X\x03\x00\x00\x00intL287307832597519156748809049798316161701'
476 b'L\nX\x07\x00\x00\x00is_safecuuid\nSafeUUID\n(J\xff\xff\xff\xfftR'
477 b'ub.',
478 # Python 3.7, protocol 2
479 b'\x80\x02cuuid\nUUID\n)\x81}(X\x03\x00\x00\x00int\x8a\x11\xa5z'
480 b'\xecz\nI\xdf}\xde\xa0Bf\xcey%\xd8\x00X\x07\x00\x00\x00is_safecuu'
481 b'id\nSafeUUID\nJ\xff\xff\xff\xff\x85Rub.',
482 # Python 3.7, protocol 3
483 b'\x80\x03cuuid\nUUID\n)\x81}(X\x03\x00\x00\x00int\x8a\x11\xa5z'
484 b'\xecz\nI\xdf}\xde\xa0Bf\xcey%\xd8\x00X\x07\x00\x00\x00is_safecuu'
485 b'id\nSafeUUID\nJ\xff\xff\xff\xff\x85Rub.',
486 # Python 3.7, protocol 4
487 b'\x80\x04\x95J\x00\x00\x00\x00\x00\x00\x00\x8c\x04uuid\x94\x8c'
488 b'\x04UUID\x93)\x81}(\x8c\x03int\x8a\x11\xa5z\xecz\nI\xdf}\xde\xa0'
489 b'Bf\xcey%\xd8\x00\x8c\x07is_safeh\x00\x8c\x08SafeUUID\x93J\xff'
490 b'\xff\xff\xff\x85Rub.',
491 ]
492
493 u = self.uuid.UUID('d82579ce6642a0de7ddf490a7aec7aa5')
494 u_safe = self.uuid.UUID('d82579ce6642a0de7ddf490a7aec7aa5',
495 is_safe=self.uuid.SafeUUID.safe)
496 u_unsafe = self.uuid.UUID('d82579ce6642a0de7ddf490a7aec7aa5',
497 is_safe=self.uuid.SafeUUID.unsafe)
498
499 with support.swap_item(sys.modules, 'uuid', self.uuid):
500 for pickled in pickled_uuids:
501 # is_safe was added in 3.7. When unpickling values from older
502 # versions, is_safe will be missing, so it should be set to
503 # SafeUUID.unknown.
504 check(pickle.loads(pickled), u)
505 for pickled in pickled_uuids_safe:
506 check(pickle.loads(pickled), u_safe)
507 for pickled in pickled_uuids_unsafe:
508 check(pickle.loads(pickled), u_unsafe)
509
510 # bpo-32502: UUID1 requires a 48-bit identifier, but hardware identifiers
511 # need not necessarily be 48 bits (e.g., EUI-64).
512 def test_uuid1_eui64(self):
513 # Confirm that uuid.getnode ignores hardware addresses larger than 48
514 # bits. Mock out each platform's *_getnode helper functions to return
515 # something just larger than 48 bits to test. This will cause
516 # uuid.getnode to fall back on uuid._random_getnode, which will
517 # generate a valid value.
518 too_large_getter = lambda: 1 << 48
519 with mock.patch.multiple(
520 self.uuid,
521 _node=None, # Ignore any cached node value.
522 _GETTERS=[too_large_getter],
523 ):
524 node = self.uuid.getnode()
525 self.assertTrue(0 < node < (1 << 48), '%012x' % node)
526
527 # Confirm that uuid1 can use the generated node, i.e., the that
528 # uuid.getnode fell back on uuid._random_getnode() rather than using
529 # the value from too_large_getter above.
530 try:
531 self.uuid.uuid1(node=node)
532 except ValueError:
533 self.fail('uuid1 was given an invalid node ID')
534
535 def test_uuid1(self):
536 equal = self.assertEqual
537
538 # Make sure uuid1() generates UUIDs that are actually version 1.
539 for u in [self.uuid.uuid1() for i in range(10)]:
540 equal(u.variant, self.uuid.RFC_4122)
541 equal(u.version, 1)
542 self.assertIn(u.is_safe, {self.uuid.SafeUUID.safe,
543 self.uuid.SafeUUID.unsafe,
544 self.uuid.SafeUUID.unknown})
545
546 # Make sure the generated UUIDs are actually unique.
547 uuids = {}
548 for u in [self.uuid.uuid1() for i in range(1000)]:
549 uuids[u] = 1
550 equal(len(uuids.keys()), 1000)
551
552 # Make sure the supplied node ID appears in the UUID.
553 u = self.uuid.uuid1(0)
554 equal(u.node, 0)
555 u = self.uuid.uuid1(0x123456789abc)
556 equal(u.node, 0x123456789abc)
557 u = self.uuid.uuid1(0xffffffffffff)
558 equal(u.node, 0xffffffffffff)
559
560 # Make sure the supplied clock sequence appears in the UUID.
561 u = self.uuid.uuid1(0x123456789abc, 0)
562 equal(u.node, 0x123456789abc)
563 equal(((u.clock_seq_hi_variant & 0x3f) << 8) | u.clock_seq_low, 0)
564 u = self.uuid.uuid1(0x123456789abc, 0x1234)
565 equal(u.node, 0x123456789abc)
566 equal(((u.clock_seq_hi_variant & 0x3f) << 8) |
567 u.clock_seq_low, 0x1234)
568 u = self.uuid.uuid1(0x123456789abc, 0x3fff)
569 equal(u.node, 0x123456789abc)
570 equal(((u.clock_seq_hi_variant & 0x3f) << 8) |
571 u.clock_seq_low, 0x3fff)
572
573 # bpo-29925: On Mac OS X Tiger, self.uuid.uuid1().is_safe returns
574 # self.uuid.SafeUUID.unknown
575 @support.requires_mac_ver(10, 5)
576 @unittest.skipUnless(os.name == 'posix', 'POSIX-only test')
577 def test_uuid1_safe(self):
578 try:
579 import _uuid
580 except ImportError:
581 has_uuid_generate_time_safe = False
582 else:
583 has_uuid_generate_time_safe = _uuid.has_uuid_generate_time_safe
584
585 if not has_uuid_generate_time_safe or not self.uuid._generate_time_safe:
586 self.skipTest('requires uuid_generate_time_safe(3)')
587
588 u = self.uuid.uuid1()
589 # uuid_generate_time_safe() may return 0 or -1 but what it returns is
590 # dependent on the underlying platform support. At least it cannot be
591 # unknown (unless I suppose the platform is buggy).
592 self.assertNotEqual(u.is_safe, self.uuid.SafeUUID.unknown)
593
594 @contextlib.contextmanager
595 def mock_generate_time_safe(self, safe_value):
596 """
597 Mock uuid._generate_time_safe() to return a given *safe_value*.
598 """
599 if os.name != 'posix':
600 self.skipTest('POSIX-only test')
601 f = self.uuid._generate_time_safe
602 if f is None:
603 self.skipTest('need uuid._generate_time_safe')
604 with mock.patch.object(self.uuid, '_generate_time_safe',
605 lambda: (f()[0], safe_value)):
606 yield
607
608 @unittest.skipUnless(os.name == 'posix', 'POSIX-only test')
609 def test_uuid1_unknown(self):
610 # Even if the platform has uuid_generate_time_safe(), let's mock it to
611 # be uuid_generate_time() and ensure the safety is unknown.
612 with self.mock_generate_time_safe(None):
613 u = self.uuid.uuid1()
614 self.assertEqual(u.is_safe, self.uuid.SafeUUID.unknown)
615
616 @unittest.skipUnless(os.name == 'posix', 'POSIX-only test')
617 def test_uuid1_is_safe(self):
618 with self.mock_generate_time_safe(0):
619 u = self.uuid.uuid1()
620 self.assertEqual(u.is_safe, self.uuid.SafeUUID.safe)
621
622 @unittest.skipUnless(os.name == 'posix', 'POSIX-only test')
623 def test_uuid1_is_unsafe(self):
624 with self.mock_generate_time_safe(-1):
625 u = self.uuid.uuid1()
626 self.assertEqual(u.is_safe, self.uuid.SafeUUID.unsafe)
627
628 @unittest.skipUnless(os.name == 'posix', 'POSIX-only test')
629 def test_uuid1_bogus_return_value(self):
630 with self.mock_generate_time_safe(3):
631 u = self.uuid.uuid1()
632 self.assertEqual(u.is_safe, self.uuid.SafeUUID.unknown)
633
634 def test_uuid1_time(self):
635 with mock.patch.object(self.uuid, '_generate_time_safe', None), \
636 mock.patch.object(self.uuid, '_last_timestamp', None), \
637 mock.patch.object(self.uuid, 'getnode', return_value=93328246233727), \
638 mock.patch('time.time_ns', return_value=1545052026752910643), \
639 mock.patch('random.getrandbits', return_value=5317): # guaranteed to be random
640 u = self.uuid.uuid1()
641 self.assertEqual(u, self.uuid.UUID('a7a55b92-01fc-11e9-94c5-54e1acf6da7f'))
642
643 with mock.patch.object(self.uuid, '_generate_time_safe', None), \
644 mock.patch.object(self.uuid, '_last_timestamp', None), \
645 mock.patch('time.time_ns', return_value=1545052026752910643):
646 u = self.uuid.uuid1(node=93328246233727, clock_seq=5317)
647 self.assertEqual(u, self.uuid.UUID('a7a55b92-01fc-11e9-94c5-54e1acf6da7f'))
648
649 def test_uuid3(self):
650 equal = self.assertEqual
651
652 # Test some known version-3 UUIDs with name passed as a byte object
653 for u, v in [(self.uuid.uuid3(self.uuid.NAMESPACE_DNS, b'python.org'),
654 '6fa459ea-ee8a-3ca4-894e-db77e160355e'),
655 (self.uuid.uuid3(self.uuid.NAMESPACE_URL, b'http://python.org/'),
656 '9fe8e8c4-aaa8-32a9-a55c-4535a88b748d'),
657 (self.uuid.uuid3(self.uuid.NAMESPACE_OID, b'1.3.6.1'),
658 'dd1a1cef-13d5-368a-ad82-eca71acd4cd1'),
659 (self.uuid.uuid3(self.uuid.NAMESPACE_X500, b'c=ca'),
660 '658d3002-db6b-3040-a1d1-8ddd7d189a4d'),
661 ]:
662 equal(u.variant, self.uuid.RFC_4122)
663 equal(u.version, 3)
664 equal(u, self.uuid.UUID(v))
665 equal(str(u), v)
666
667 # Test some known version-3 UUIDs with name passed as a string
668 for u, v in [(self.uuid.uuid3(self.uuid.NAMESPACE_DNS, 'python.org'),
669 '6fa459ea-ee8a-3ca4-894e-db77e160355e'),
670 (self.uuid.uuid3(self.uuid.NAMESPACE_URL, 'http://python.org/'),
671 '9fe8e8c4-aaa8-32a9-a55c-4535a88b748d'),
672 (self.uuid.uuid3(self.uuid.NAMESPACE_OID, '1.3.6.1'),
673 'dd1a1cef-13d5-368a-ad82-eca71acd4cd1'),
674 (self.uuid.uuid3(self.uuid.NAMESPACE_X500, 'c=ca'),
675 '658d3002-db6b-3040-a1d1-8ddd7d189a4d'),
676 ]:
677 equal(u.variant, self.uuid.RFC_4122)
678 equal(u.version, 3)
679 equal(u, self.uuid.UUID(v))
680 equal(str(u), v)
681
682 def test_uuid4(self):
683 equal = self.assertEqual
684
685 # Make sure uuid4() generates UUIDs that are actually version 4.
686 for u in [self.uuid.uuid4() for i in range(10)]:
687 equal(u.variant, self.uuid.RFC_4122)
688 equal(u.version, 4)
689
690 # Make sure the generated UUIDs are actually unique.
691 uuids = {}
692 for u in [self.uuid.uuid4() for i in range(1000)]:
693 uuids[u] = 1
694 equal(len(uuids.keys()), 1000)
695
696 def test_uuid5(self):
697 equal = self.assertEqual
698
699 # Test some known version-5 UUIDs with names given as byte objects
700 for u, v in [(self.uuid.uuid5(self.uuid.NAMESPACE_DNS, b'python.org'),
701 '886313e1-3b8a-5372-9b90-0c9aee199e5d'),
702 (self.uuid.uuid5(self.uuid.NAMESPACE_URL, b'http://python.org/'),
703 '4c565f0d-3f5a-5890-b41b-20cf47701c5e'),
704 (self.uuid.uuid5(self.uuid.NAMESPACE_OID, b'1.3.6.1'),
705 '1447fa61-5277-5fef-a9b3-fbc6e44f4af3'),
706 (self.uuid.uuid5(self.uuid.NAMESPACE_X500, b'c=ca'),
707 'cc957dd1-a972-5349-98cd-874190002798'),
708 ]:
709 equal(u.variant, self.uuid.RFC_4122)
710 equal(u.version, 5)
711 equal(u, self.uuid.UUID(v))
712 equal(str(u), v)
713
714 # Test some known version-5 UUIDs with names given as strings
715 for u, v in [(self.uuid.uuid5(self.uuid.NAMESPACE_DNS, 'python.org'),
716 '886313e1-3b8a-5372-9b90-0c9aee199e5d'),
717 (self.uuid.uuid5(self.uuid.NAMESPACE_URL, 'http://python.org/'),
718 '4c565f0d-3f5a-5890-b41b-20cf47701c5e'),
719 (self.uuid.uuid5(self.uuid.NAMESPACE_OID, '1.3.6.1'),
720 '1447fa61-5277-5fef-a9b3-fbc6e44f4af3'),
721 (self.uuid.uuid5(self.uuid.NAMESPACE_X500, 'c=ca'),
722 'cc957dd1-a972-5349-98cd-874190002798'),
723 ]:
724 equal(u.variant, self.uuid.RFC_4122)
725 equal(u.version, 5)
726 equal(u, self.uuid.UUID(v))
727 equal(str(u), v)
728
729 def test_uuid6(self):
730 equal = self.assertEqual
731 u = self.uuid.uuid6()
732 equal(u.variant, self.uuid.RFC_4122)
733 equal(u.version, 6)
734
735 fake_nanoseconds = 0x1571_20a1_de1a_c533
736 fake_node_value = 0x54e1_acf6_da7f
737 fake_clock_seq = 0x14c5
738 with (
739 mock.patch.object(self.uuid, '_last_timestamp_v6', None),
740 mock.patch.object(self.uuid, 'getnode', return_value=fake_node_value),
741 mock.patch('time.time_ns', return_value=fake_nanoseconds),
742 mock.patch('random.getrandbits', return_value=fake_clock_seq)
743 ):
744 u = self.uuid.uuid6()
745 equal(u.variant, self.uuid.RFC_4122)
746 equal(u.version, 6)
747
748 # 32 (top) | 16 (mid) | 12 (low) == 60 (timestamp)
749 equal(u.time, 0x1e901fca_7a55_b92)
750 equal(u.fields[0], 0x1e901fca) # 32 top bits of time
751 equal(u.fields[1], 0x7a55) # 16 mid bits of time
752 # 4 bits of version + 12 low bits of time
753 equal((u.fields[2] >> 12) & 0xf, 6)
754 equal((u.fields[2] & 0xfff), 0xb92)
755 # 2 bits of variant + 6 high bits of clock_seq
756 equal((u.fields[3] >> 6) & 0xf, 2)
757 equal(u.fields[3] & 0x3f, fake_clock_seq >> 8)
758 # 8 low bits of clock_seq
759 equal(u.fields[4], fake_clock_seq & 0xff)
760 equal(u.fields[5], fake_node_value)
761
762 def test_uuid6_uniqueness(self):
763 # Test that UUIDv6-generated values are unique.
764
765 # Unlike UUIDv8, only 62 bits can be randomized for UUIDv6.
766 # In practice, however, it remains unlikely to generate two
767 # identical UUIDs for the same 60-bit timestamp if neither
768 # the node ID nor the clock sequence is specified.
769 uuids = {self.uuid.uuid6() for _ in range(1000)}
770 self.assertEqual(len(uuids), 1000)
771 versions = {u.version for u in uuids}
772 self.assertSetEqual(versions, {6})
773
774 timestamp = 0x1ec9414c_232a_b00
775 fake_nanoseconds = (timestamp - 0x1b21dd21_3814_000) * 100
776
777 with mock.patch('time.time_ns', return_value=fake_nanoseconds):
778 def gen():
779 with mock.patch.object(self.uuid, '_last_timestamp_v6', None):
780 return self.uuid.uuid6(node=0, clock_seq=None)
781
782 # By the birthday paradox, sampling N = 1024 UUIDs with identical
783 # node IDs and timestamps results in duplicates with probability
784 # close to 1 (not having a duplicate happens with probability of
785 # order 1E-15) since only the 14-bit clock sequence is randomized.
786 N = 1024
787 uuids = {gen() for _ in range(N)}
788 self.assertSetEqual({u.node for u in uuids}, {0})
789 self.assertSetEqual({u.time for u in uuids}, {timestamp})
790 self.assertLess(len(uuids), N, 'collision property does not hold')
791
792 def test_uuid6_node(self):
793 # Make sure the given node ID appears in the UUID.
794 #
795 # Note: when no node ID is specified, the same logic as for UUIDv1
796 # is applied to UUIDv6. In particular, there is no need to test that
797 # getnode() correctly returns positive integers of exactly 48 bits
798 # since this is done in test_uuid1_eui64().
799 self.assertLessEqual(self.uuid.uuid6().node.bit_length(), 48)
800
801 self.assertEqual(self.uuid.uuid6(0).node, 0)
802
803 # tests with explicit values
804 max_node = 0xffff_ffff_ffff
805 self.assertEqual(self.uuid.uuid6(max_node).node, max_node)
806 big_node = 0xE_1234_5678_ABCD # 52-bit node
807 res_node = 0x0_1234_5678_ABCD # truncated to 48 bits
808 self.assertEqual(self.uuid.uuid6(big_node).node, res_node)
809
810 # randomized tests
811 for _ in range(10):
812 # node with > 48 bits is truncated
813 for b in [24, 48, 72]:
814 node = (1 << (b - 1)) | random.getrandbits(b)
815 with self.subTest(node=node, bitlen=b):
816 self.assertEqual(node.bit_length(), b)
817 u = self.uuid.uuid6(node=node)
818 self.assertEqual(u.node, node & 0xffff_ffff_ffff)
819
820 def test_uuid6_clock_seq(self):
821 # Make sure the supplied clock sequence appears in the UUID.
822 #
823 # For UUIDv6, clock sequence bits are stored from bit 48 to bit 62,
824 # with the convention that the least significant bit is bit 0 and
825 # the most significant bit is bit 127.
826 get_clock_seq = lambda u: (u.int >> 48) & 0x3fff
827
828 u = self.uuid.uuid6()
829 self.assertLessEqual(get_clock_seq(u).bit_length(), 14)
830
831 # tests with explicit values
832 big_clock_seq = 0xffff # 16-bit clock sequence
833 res_clock_seq = 0x3fff # truncated to 14 bits
834 u = self.uuid.uuid6(clock_seq=big_clock_seq)
835 self.assertEqual(get_clock_seq(u), res_clock_seq)
836
837 # some randomized tests
838 for _ in range(10):
839 # clock_seq with > 14 bits is truncated
840 for b in [7, 14, 28]:
841 node = random.getrandbits(48)
842 clock_seq = (1 << (b - 1)) | random.getrandbits(b)
843 with self.subTest(node=node, clock_seq=clock_seq, bitlen=b):
844 self.assertEqual(clock_seq.bit_length(), b)
845 u = self.uuid.uuid6(node=node, clock_seq=clock_seq)
846 self.assertEqual(get_clock_seq(u), clock_seq & 0x3fff)
847
848 def test_uuid6_test_vectors(self):
849 equal = self.assertEqual
850 # https://www.rfc-editor.org/rfc/rfc9562#name-test-vectors
851 # (separators are put at the 12th and 28th bits)
852 timestamp = 0x1ec9414c_232a_b00
853 fake_nanoseconds = (timestamp - 0x1b21dd21_3814_000) * 100
854 # https://www.rfc-editor.org/rfc/rfc9562#name-example-of-a-uuidv6-value
855 node = 0x9f6bdeced846
856 clock_seq = (3 << 12) | 0x3c8
857
858 with (
859 mock.patch.object(self.uuid, '_last_timestamp_v6', None),
860 mock.patch('time.time_ns', return_value=fake_nanoseconds)
861 ):
862 u = self.uuid.uuid6(node=node, clock_seq=clock_seq)
863 equal(str(u).upper(), '1EC9414C-232A-6B00-B3C8-9F6BDECED846')
864 # 32 16 4 12 2 14 48
865 # time_hi | time_mid | ver | time_lo | var | clock_seq | node
866 equal(u.time, timestamp)
867 equal(u.int & 0xffff_ffff_ffff, node)
868 equal((u.int >> 48) & 0x3fff, clock_seq)
869 equal((u.int >> 62) & 0x3, 0b10)
870 equal((u.int >> 64) & 0xfff, 0xb00)
871 equal((u.int >> 76) & 0xf, 0x6)
872 equal((u.int >> 80) & 0xffff, 0x232a)
873 equal((u.int >> 96) & 0xffff_ffff, 0x1ec9_414c)
874
875 def test_uuid7(self):
876 equal = self.assertEqual
877 u = self.uuid.uuid7()
878 equal(u.variant, self.uuid.RFC_4122)
879 equal(u.version, 7)
880
881 # 1 Jan 2023 12:34:56.123_456_789
882 timestamp_ns = 1672533296_123_456_789 # ns precision
883 timestamp_ms, _ = divmod(timestamp_ns, 1_000_000)
884
885 for _ in range(100):
886 counter_hi = random.getrandbits(11)
887 counter_lo = random.getrandbits(30)
888 counter = (counter_hi << 30) | counter_lo
889
890 tail = random.getrandbits(32)
891 # effective number of bits is 32 + 30 + 11 = 73
892 random_bits = counter << 32 | tail
893
894 # set all remaining MSB of fake random bits to 1 to ensure that
895 # the implementation correctly removes them
896 random_bits = (((1 << 7) - 1) << 73) | random_bits
897 random_data = random_bits.to_bytes(10)
898
899 with (
900 mock.patch.multiple(
901 self.uuid,
902 _last_timestamp_v7=None,
903 _last_counter_v7=0,
904 ),
905 mock.patch('time.time_ns', return_value=timestamp_ns),
906 mock.patch('os.urandom', return_value=random_data) as urand
907 ):
908 u = self.uuid.uuid7()
909 urand.assert_called_once_with(10)
910 equal(u.variant, self.uuid.RFC_4122)
911 equal(u.version, 7)
912
913 equal(self.uuid._last_timestamp_v7, timestamp_ms)
914 equal(self.uuid._last_counter_v7, counter)
915
916 unix_ts_ms = timestamp_ms & 0xffff_ffff_ffff
917 equal(u.time, unix_ts_ms)
918 equal((u.int >> 80) & 0xffff_ffff_ffff, unix_ts_ms)
919
920 equal((u.int >> 75) & 1, 0) # check that the MSB is 0
921 equal((u.int >> 64) & 0xfff, counter_hi)
922 equal((u.int >> 32) & 0x3fff_ffff, counter_lo)
923 equal(u.int & 0xffff_ffff, tail)
924
925 def test_uuid7_uniqueness(self):
926 # Test that UUIDv7-generated values are unique.
927 #
928 # While UUIDv8 has an entropy of 122 bits, those 122 bits may not
929 # necessarily be sampled from a PRNG. On the other hand, UUIDv7
930 # uses os.urandom() as a PRNG which features better randomness.
931 N = 1000
932 uuids = {self.uuid.uuid7() for _ in range(N)}
933 self.assertEqual(len(uuids), N)
934
935 versions = {u.version for u in uuids}
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)
996 equal((u2.int >> 32) & 0x3fff_ffff, counter_lo + 1)
997 equal(u2.int & 0xffff_ffff, next_fail)
998
999 self.assertLess(u1, u2)
1000
1001 def test_uuid7_timestamp_backwards(self):
1002 equal = self.assertEqual
1003 # 1 Jan 2023 12:34:56.123_456_789
1004 timestamp_ns = 1672533296_123_456_789 # ns precision
1005 timestamp_ms, _ = divmod(timestamp_ns, 1_000_000)
1006 fake_last_timestamp_v7 = timestamp_ms + 1
1007
1008 # counter_{hi,lo} are chosen so that "counter + 1" does not overflow
1009 counter_hi = random.getrandbits(11)
1010 counter_lo = random.getrandbits(29)
1011 counter = (counter_hi << 30) | counter_lo
1012 self.assertLess(counter + 1, 0x3ff_ffff_ffff)
1013
1014 tail_bytes = os.urandom(4)
1015 tail = int.from_bytes(tail_bytes)
1016
1017 with (
1018 mock.patch.multiple(
1019 self.uuid,
1020 _last_timestamp_v7=fake_last_timestamp_v7,
1021 _last_counter_v7=counter,
1022 ),
1023 mock.patch('time.time_ns', return_value=timestamp_ns),
1024 mock.patch('os.urandom', return_value=tail_bytes) as urand
1025 ):
1026 u = self.uuid.uuid7()
1027 urand.assert_called_once_with(4)
1028 equal(u.variant, self.uuid.RFC_4122)
1029 equal(u.version, 7)
1030 equal(self.uuid._last_timestamp_v7, fake_last_timestamp_v7 + 1)
1031 unix_ts_ms = (fake_last_timestamp_v7 + 1) & 0xffff_ffff_ffff
1032 equal(u.time, unix_ts_ms)
1033 equal((u.int >> 80) & 0xffff_ffff_ffff, unix_ts_ms)
1034 # 42-bit counter advanced by 1
1035 equal(self.uuid._last_counter_v7, counter + 1)
1036 equal((u.int >> 64) & 0xfff, counter_hi)
1037 # 42-bit counter advanced by 1 (counter_hi is untouched)
1038 equal((u.int >> 32) & 0x3fff_ffff, counter_lo + 1)
1039 equal(u.int & 0xffff_ffff, tail)
1040
1041 def test_uuid7_overflow_counter(self):
1042 equal = self.assertEqual
1043 # 1 Jan 2023 12:34:56.123_456_789
1044 timestamp_ns = 1672533296_123_456_789 # ns precision
1045 timestamp_ms, _ = divmod(timestamp_ns, 1_000_000)
1046
1047 new_counter_hi = random.getrandbits(11)
1048 new_counter_lo = random.getrandbits(30)
1049 new_counter = (new_counter_hi << 30) | new_counter_lo
1050
1051 tail = random.getrandbits(32)
1052 random_bits = (new_counter << 32) | tail
1053 random_data = random_bits.to_bytes(10)
1054
1055 with (
1056 mock.patch.multiple(
1057 self.uuid,
1058 _last_timestamp_v7=timestamp_ms,
1059 # same timestamp, but force an overflow on the counter
1060 _last_counter_v7=0x3ff_ffff_ffff,
1061 ),
1062 mock.patch('time.time_ns', return_value=timestamp_ns),
1063 mock.patch('os.urandom', return_value=random_data) as urand
1064 ):
1065 u = self.uuid.uuid7()
1066 urand.assert_called_with(10)
1067 equal(u.variant, self.uuid.RFC_4122)
1068 equal(u.version, 7)
1069 # timestamp advanced due to overflow
1070 equal(self.uuid._last_timestamp_v7, timestamp_ms + 1)
1071 unix_ts_ms = (timestamp_ms + 1) & 0xffff_ffff_ffff
1072 equal(u.time, unix_ts_ms)
1073 equal((u.int >> 80) & 0xffff_ffff_ffff, unix_ts_ms)
1074 # counter overflowed, so we picked a new one
1075 equal(self.uuid._last_counter_v7, new_counter)
1076 equal((u.int >> 64) & 0xfff, new_counter_hi)
1077 equal((u.int >> 32) & 0x3fff_ffff, new_counter_lo)
1078 equal(u.int & 0xffff_ffff, tail)
1079
1080 def test_uuid8(self):
1081 equal = self.assertEqual
1082 u = self.uuid.uuid8()
1083
1084 equal(u.variant, self.uuid.RFC_4122)
1085 equal(u.version, 8)
1086
1087 for (_, hi, mid, lo) in product(
1088 range(10), # repeat 10 times
1089 [None, 0, random.getrandbits(48)],
1090 [None, 0, random.getrandbits(12)],
1091 [None, 0, random.getrandbits(62)],
1092 ):
1093 u = self.uuid.uuid8(hi, mid, lo)
1094 equal(u.variant, self.uuid.RFC_4122)
1095 equal(u.version, 8)
1096 if hi is not None:
1097 equal((u.int >> 80) & 0xffffffffffff, hi)
1098 if mid is not None:
1099 equal((u.int >> 64) & 0xfff, mid)
1100 if lo is not None:
1101 equal(u.int & 0x3fffffffffffffff, lo)
1102
1103 def test_uuid8_uniqueness(self):
1104 # Test that UUIDv8-generated values are unique (up to a negligible
1105 # probability of failure). There are 122 bits of entropy and assuming
1106 # that the underlying mt-19937-based random generator is sufficiently
1107 # good, it is unlikely to have a collision of two UUIDs.
1108 N = 1000
1109 uuids = {self.uuid.uuid8() for _ in range(N)}
1110 self.assertEqual(len(uuids), N)
1111
1112 versions = {u.version for u in uuids}
1113 self.assertSetEqual(versions, {8})
1114
1115 @support.requires_fork()
1116 def testIssue8621(self):
1117 # On at least some versions of OSX self.uuid.uuid4 generates
1118 # the same sequence of UUIDs in the parent and any
1119 # children started using fork.
1120 fds = os.pipe()
1121 pid = os.fork()
1122 if pid == 0:
1123 os.close(fds[0])
1124 value = self.uuid.uuid4()
1125 os.write(fds[1], value.hex.encode('latin-1'))
1126 os._exit(0)
1127
1128 else:
1129 os.close(fds[1])
1130 self.addCleanup(os.close, fds[0])
1131 parent_value = self.uuid.uuid4().hex
1132 support.wait_process(pid, exitcode=0)
1133 child_value = os.read(fds[0], 100).decode('latin-1')
1134
1135 self.assertNotEqual(parent_value, child_value)
1136
1137 def test_uuid_weakref(self):
1138 # bpo-35701: check that weak referencing to a UUID object can be created
1139 strong = self.uuid.uuid4()
1140 weak = weakref.ref(strong)
1141 self.assertIs(strong, weak())
1142
1143
1144 class CommandLineTestCases:
1145 uuid = None # to be defined in subclasses
1146
1147 def do_test_standalone_uuid(self, version):
1148 stdout = io.StringIO()
1149 with contextlib.redirect_stdout(stdout):
1150 self.uuid.main()
1151 output = stdout.getvalue().strip()
1152 u = self.uuid.UUID(output)
1153 self.assertEqual(output, str(u))
1154 self.assertEqual(u.version, version)
1155
1156 @mock.patch.object(sys, "argv", ["", "-u", "uuid1"])
1157 def test_cli_uuid1(self):
1158 self.do_test_standalone_uuid(1)
1159
1160 @mock.patch.object(sys, "argv", ["", "-u", "uuid3", "-n", "@dns"])
1161 @mock.patch('sys.stderr', new_callable=io.StringIO)
1162 def test_cli_namespace_required_for_uuid3(self, mock_err):
1163 with self.assertRaises(SystemExit) as cm:
1164 self.uuid.main()
1165
1166 # Check that exception code is the same as argparse.ArgumentParser.error
1167 self.assertEqual(cm.exception.code, 2)
1168 self.assertIn("error: Incorrect number of arguments", mock_err.getvalue())
1169
1170 @mock.patch.object(sys, "argv", ["", "-u", "uuid3", "-N", "python.org"])
1171 @mock.patch('sys.stderr', new_callable=io.StringIO)
1172 def test_cli_name_required_for_uuid3(self, mock_err):
1173 with self.assertRaises(SystemExit) as cm:
1174 self.uuid.main()
1175 # Check that exception code is the same as argparse.ArgumentParser.error
1176 self.assertEqual(cm.exception.code, 2)
1177 self.assertIn("error: Incorrect number of arguments", mock_err.getvalue())
1178
1179 @mock.patch.object(sys, "argv",
1180 ["", "-u", "uuid3", "-n", "@dns", "-N", "python.org"])
1181 def test_cli_uuid3_outputted_with_valid_namespace_and_name(self):
1182 stdout = io.StringIO()
1183 with contextlib.redirect_stdout(stdout):
1184 self.uuid.main()
1185
1186 output = stdout.getvalue().strip()
1187 uuid_output = self.uuid.UUID(output)
1188
1189 # Output should be in the form of uuid3
1190 self.assertEqual(output, str(uuid_output))
1191 self.assertEqual(uuid_output.version, 3)
1192
1193 @mock.patch.object(sys, "argv",
1194 ["", "-u", "uuid3", "-n",
1195 "0d6a16cc-34a7-47d8-b660-214d0ae184d2",
1196 "-N", "some.user"])
1197 def test_cli_uuid3_outputted_with_custom_namespace_and_name(self):
1198 stdout = io.StringIO()
1199 with contextlib.redirect_stdout(stdout):
1200 self.uuid.main()
1201
1202 output = stdout.getvalue().strip()
1203 uuid_output = self.uuid.UUID(output)
1204
1205 # Output should be in the form of uuid3
1206 self.assertEqual(output, str(uuid_output))
1207 self.assertEqual(uuid_output.version, 3)
1208
1209 @mock.patch.object(sys, "argv",
1210 ["", "-u", "uuid3", "-n", "any UUID", "-N", "python.org"])
1211 @mock.patch('sys.stderr', new_callable=io.StringIO)
1212 def test_cli_uuid3_with_invalid_namespace(self, mock_err):
1213 with self.assertRaises(SystemExit) as cm:
1214 self.uuid.main()
1215 # Check that exception code is the same as argparse.ArgumentParser.error
1216 self.assertEqual(cm.exception.code, 2)
1217 self.assertIn("error: badly formed hexadecimal UUID string",
1218 mock_err.getvalue())
1219
1220 @mock.patch.object(sys, "argv", [""])
1221 def test_cli_uuid4_outputted_with_no_args(self):
1222 stdout = io.StringIO()
1223 with contextlib.redirect_stdout(stdout):
1224 self.uuid.main()
1225
1226 output = stdout.getvalue().strip()
1227 uuid_output = self.uuid.UUID(output)
1228
1229 # Output uuid should be in the format of uuid4
1230 self.assertEqual(output, str(uuid_output))
1231 self.assertEqual(uuid_output.version, 4)
1232
1233 @mock.patch.object(sys, "argv", ["", "-C", "3"])
1234 def test_cli_uuid4_outputted_with_count(self):
1235 stdout = io.StringIO()
1236 with contextlib.redirect_stdout(stdout):
1237 self.uuid.main()
1238
1239 output = stdout.getvalue().strip().splitlines()
1240
1241 # Check that 3 UUIDs in the format of uuid4 have been generated
1242 self.assertEqual(len(output), 3)
1243 for o in output:
1244 uuid_output = self.uuid.UUID(o)
1245 self.assertEqual(uuid_output.version, 4)
1246
1247 @mock.patch.object(sys, "argv",
1248 ["", "-u", "uuid5", "-n", "@dns", "-N", "python.org"])
1249 def test_cli_uuid5_outputted_with_valid_namespace_and_name(self):
1250 stdout = io.StringIO()
1251 with contextlib.redirect_stdout(stdout):
1252 self.uuid.main()
1253
1254 output = stdout.getvalue().strip()
1255 uuid_output = self.uuid.UUID(output)
1256
1257 # Output should be in the form of uuid5
1258 self.assertEqual(output, str(uuid_output))
1259 self.assertEqual(uuid_output.version, 5)
1260
1261 @mock.patch.object(sys, "argv",
1262 ["", "-u", "uuid5", "-n",
1263 "0d6a16cc-34a7-47d8-b660-214d0ae184d2",
1264 "-N", "some.user"])
1265 def test_cli_uuid5_ouputted_with_custom_namespace_and_name(self):
1266 stdout = io.StringIO()
1267 with contextlib.redirect_stdout(stdout):
1268 self.uuid.main()
1269
1270 output = stdout.getvalue().strip()
1271 uuid_output = self.uuid.UUID(output)
1272
1273 # Output should be in the form of uuid5
1274 self.assertEqual(output, str(uuid_output))
1275 self.assertEqual(uuid_output.version, 5)
1276
1277 @mock.patch.object(sys, "argv",
1278 ["", "-u", "uuid5", "-n", "any UUID", "-N", "python.org"])
1279 @mock.patch('sys.stderr', new_callable=io.StringIO)
1280 def test_cli_uuid5_with_invalid_namespace(self, mock_err):
1281 with self.assertRaises(SystemExit) as cm:
1282 self.uuid.main()
1283 # Check that exception code is the same as argparse.ArgumentParser.error
1284 self.assertEqual(cm.exception.code, 2)
1285 self.assertIn("error: badly formed hexadecimal UUID string",
1286 mock_err.getvalue())
1287
1288 @mock.patch.object(sys, "argv", ["", "-u", "uuid6"])
1289 def test_cli_uuid6(self):
1290 self.do_test_standalone_uuid(6)
1291
1292 @mock.patch.object(sys, "argv", ["", "-u", "uuid7"])
1293 def test_cli_uuid7(self):
1294 self.do_test_standalone_uuid(7)
1295
1296 @mock.patch.object(sys, "argv", ["", "-u", "uuid8"])
1297 def test_cli_uuid8(self):
1298 self.do_test_standalone_uuid(8)
1299
1300
1301 class TestUUIDWithoutExtModule(CommandLineTestCases, BaseTestUUID, unittest.TestCase):
1302 uuid = py_uuid
1303
1304
1305 @unittest.skipUnless(c_uuid, 'requires the C _uuid module')
1306 class TestUUIDWithExtModule(CommandLineTestCases, BaseTestUUID, unittest.TestCase):
1307 uuid = c_uuid
1308
1309 def check_has_stable_libuuid_extractable_node(self):
1310 if not self.uuid._has_stable_extractable_node:
1311 self.skipTest("libuuid cannot deduce MAC address")
1312
1313 @unittest.skipUnless(os.name == 'posix', 'POSIX only')
1314 def test_unix_getnode_from_libuuid(self):
1315 self.check_has_stable_libuuid_extractable_node()
1316 script = 'import uuid; print(uuid._unix_getnode())'
1317 _, n_a, _ = assert_python_ok('-c', script)
1318 _, n_b, _ = assert_python_ok('-c', script)
1319 n_a, n_b = n_a.decode().strip(), n_b.decode().strip()
1320 self.assertTrue(n_a.isdigit())
1321 self.assertTrue(n_b.isdigit())
1322 self.assertEqual(n_a, n_b)
1323
1324 @unittest.skipUnless(os.name == 'nt', 'Windows only')
1325 def test_windows_getnode_from_libuuid(self):
1326 self.check_has_stable_libuuid_extractable_node()
1327 script = 'import uuid; print(uuid._windll_getnode())'
1328 _, n_a, _ = assert_python_ok('-c', script)
1329 _, n_b, _ = assert_python_ok('-c', script)
1330 n_a, n_b = n_a.decode().strip(), n_b.decode().strip()
1331 self.assertTrue(n_a.isdigit())
1332 self.assertTrue(n_b.isdigit())
1333 self.assertEqual(n_a, n_b)
1334
1335
1336 class BaseTestInternals:
1337 _uuid = py_uuid
1338
1339 def check_parse_mac(self, aix):
1340 if not aix:
1341 patch = mock.patch.multiple(self.uuid,
1342 _MAC_DELIM=b':',
1343 _MAC_OMITS_LEADING_ZEROES=False)
1344 else:
1345 patch = mock.patch.multiple(self.uuid,
1346 _MAC_DELIM=b'.',
1347 _MAC_OMITS_LEADING_ZEROES=True)
1348
1349 with patch:
1350 # Valid MAC addresses
1351 if not aix:
1352 tests = (
1353 (b'52:54:00:9d:0e:67', 0x5254009d0e67),
1354 (b'12:34:56:78:90:ab', 0x1234567890ab),
1355 )
1356 else:
1357 # AIX format
1358 tests = (
1359 (b'fe.ad.c.1.23.4', 0xfead0c012304),
1360 )
1361 for mac, expected in tests:
1362 self.assertEqual(self.uuid._parse_mac(mac), expected)
1363
1364 # Invalid MAC addresses
1365 for mac in (
1366 b'',
1367 # IPv6 addresses with same length than valid MAC address
1368 # (17 characters)
1369 b'fe80::5054:ff:fe9',
1370 b'123:2:3:4:5:6:7:8',
1371 # empty 5rd field
1372 b'52:54:00:9d::67',
1373 # only 5 fields instead of 6
1374 b'52:54:00:9d:0e'
1375 # invalid character 'x'
1376 b'52:54:00:9d:0e:6x'
1377 # dash separator
1378 b'52-54-00-9d-0e-67',
1379 ):
1380 if aix:
1381 mac = mac.replace(b':', b'.')
1382 with self.subTest(mac=mac):
1383 self.assertIsNone(self.uuid._parse_mac(mac))
1384
1385 def test_parse_mac(self):
1386 self.check_parse_mac(False)
1387
1388 def test_parse_mac_aix(self):
1389 self.check_parse_mac(True)
1390
1391 def test_find_under_heading(self):
1392 data = '''\
1393 Name Mtu Network Address Ipkts Ierrs Opkts Oerrs Coll
1394 en0 1500 link#2 fe.ad.c.1.23.4 1714807956 0 711348489 0 0
1395 01:00:5e:00:00:01
1396 en0 1500 192.168.129 x071 1714807956 0 711348489 0 0
1397 224.0.0.1
1398 en0 1500 192.168.90 x071 1714807956 0 711348489 0 0
1399 224.0.0.1
1400 '''
1401
1402 # The above data is from AIX - with '.' as _MAC_DELIM and strings
1403 # shorter than 17 bytes (no leading 0). (_MAC_OMITS_LEADING_ZEROES=True)
1404 with mock.patch.multiple(self.uuid,
1405 _MAC_DELIM=b'.',
1406 _MAC_OMITS_LEADING_ZEROES=True,
1407 _get_command_stdout=mock_get_command_stdout(data)):
1408 mac = self.uuid._find_mac_under_heading(
1409 command='netstat',
1410 args='-ian',
1411 heading=b'Address',
1412 )
1413
1414 self.assertEqual(mac, 0xfead0c012304)
1415
1416 def test_find_under_heading_ipv6(self):
1417 # bpo-39991: IPv6 address "fe80::5054:ff:fe9" looks like a MAC address
1418 # (same string length) but must be skipped
1419 data = '''\
1420 Name Mtu Network Address Ipkts Ierrs Idrop Opkts Oerrs Coll
1421 vtnet 1500 <Link#1> 52:54:00:9d:0e:67 10017 0 0 8174 0 0
1422 vtnet - fe80::%vtnet0 fe80::5054:ff:fe9 0 - - 4 - -
1423 vtnet - 192.168.122.0 192.168.122.45 8844 - - 8171 - -
1424 lo0 16384 <Link#2> lo0 260148 0 0 260148 0 0
1425 lo0 - ::1/128 ::1 193 - - 193 - -
1426 ff01::1%lo0
1427 ff02::2:2eb7:74fa
1428 ff02::2:ff2e:b774
1429 ff02::1%lo0
1430 ff02::1:ff00:1%lo
1431 lo0 - fe80::%lo0/64 fe80::1%lo0 0 - - 0 - -
1432 ff01::1%lo0
1433 ff02::2:2eb7:74fa
1434 ff02::2:ff2e:b774
1435 ff02::1%lo0
1436 ff02::1:ff00:1%lo
1437 lo0 - 127.0.0.0/8 127.0.0.1 259955 - - 259955 - -
1438 224.0.0.1
1439 '''
1440
1441 with mock.patch.multiple(self.uuid,
1442 _MAC_DELIM=b':',
1443 _MAC_OMITS_LEADING_ZEROES=False,
1444 _get_command_stdout=mock_get_command_stdout(data)):
1445 mac = self.uuid._find_mac_under_heading(
1446 command='netstat',
1447 args='-ian',
1448 heading=b'Address',
1449 )
1450
1451 self.assertEqual(mac, 0x5254009d0e67)
1452
1453 def test_find_mac_near_keyword(self):
1454 # key and value are on the same line
1455 data = '''
1456 fake Link encap:UNSPEC hwaddr 00-00
1457 cscotun0 Link encap:UNSPEC HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
1458 eth0 Link encap:Ethernet HWaddr 12:34:56:78:90:ab
1459 '''
1460
1461 # The above data will only be parsed properly on non-AIX unixes.
1462 with mock.patch.multiple(self.uuid,
1463 _MAC_DELIM=b':',
1464 _MAC_OMITS_LEADING_ZEROES=False,
1465 _get_command_stdout=mock_get_command_stdout(data)):
1466 mac = self.uuid._find_mac_near_keyword(
1467 command='ifconfig',
1468 args='',
1469 keywords=[b'hwaddr'],
1470 get_word_index=lambda x: x + 1,
1471 )
1472
1473 self.assertEqual(mac, 0x1234567890ab)
1474
1475 def check_node(self, node, requires=None):
1476 if requires and node is None:
1477 self.skipTest('requires ' + requires)
1478 hex = '%012x' % node
1479 if support.verbose >= 2:
1480 print(hex, end=' ')
1481 self.assertTrue(0 < node < (1 << 48),
1482 "%s is not an RFC 4122 node ID" % hex)
1483
1484 @unittest.skipUnless(_uuid._ifconfig_getnode in _uuid._GETTERS,
1485 "ifconfig is not used for introspection on this platform")
1486 def test_ifconfig_getnode(self):
1487 node = self.uuid._ifconfig_getnode()
1488 self.check_node(node, 'ifconfig')
1489
1490 @unittest.skipUnless(_uuid._ip_getnode in _uuid._GETTERS,
1491 "ip is not used for introspection on this platform")
1492 def test_ip_getnode(self):
1493 node = self.uuid._ip_getnode()
1494 self.check_node(node, 'ip')
1495
1496 @unittest.skipUnless(_uuid._arp_getnode in _uuid._GETTERS,
1497 "arp is not used for introspection on this platform")
1498 def test_arp_getnode(self):
1499 node = self.uuid._arp_getnode()
1500 self.check_node(node, 'arp')
1501
1502 @unittest.skipUnless(_uuid._lanscan_getnode in _uuid._GETTERS,
1503 "lanscan is not used for introspection on this platform")
1504 def test_lanscan_getnode(self):
1505 node = self.uuid._lanscan_getnode()
1506 self.check_node(node, 'lanscan')
1507
1508 @unittest.skipUnless(_uuid._netstat_getnode in _uuid._GETTERS,
1509 "netstat is not used for introspection on this platform")
1510 def test_netstat_getnode(self):
1511 node = self.uuid._netstat_getnode()
1512 self.check_node(node, 'netstat')
1513
1514 def test_random_getnode(self):
1515 node = self.uuid._random_getnode()
1516 # The multicast bit, i.e. the least significant bit of first octet,
1517 # must be set for randomly generated MAC addresses. See RFC 4122,
1518 # $4.1.6.
1519 self.assertTrue(node & (1 << 40), '%012x' % node)
1520 self.check_node(node)
1521
1522 node2 = self.uuid._random_getnode()
1523 self.assertNotEqual(node2, node, '%012x' % node)
1524
1525 class TestInternalsWithoutExtModule(BaseTestInternals, unittest.TestCase):
1526 uuid = py_uuid
1527
1528 @unittest.skipUnless(c_uuid, 'requires the C _uuid module')
1529 class TestInternalsWithExtModule(BaseTestInternals, unittest.TestCase):
1530 uuid = c_uuid
1531
1532 @unittest.skipUnless(os.name == 'posix', 'requires Posix')
1533 def test_unix_getnode(self):
1534 if not importable('_uuid') and not importable('ctypes'):
1535 self.skipTest("neither _uuid extension nor ctypes available")
1536 try: # Issues 1481, 3581: _uuid_generate_time() might be None.
1537 node = self.uuid._unix_getnode()
1538 except TypeError:
1539 self.skipTest('requires uuid_generate_time')
1540 self.check_node(node, 'unix')
1541
1542 @unittest.skipUnless(os.name == 'nt', 'requires Windows')
1543 def test_windll_getnode(self):
1544 node = self.uuid._windll_getnode()
1545 self.check_node(node)
1546
1547
1548 if __name__ == '__main__':
1549 unittest.main()