Debian Codegraph @

Lib/test/test_struct.py

raw
1 from collections import abc
2 import array
3 import gc
4 import math
5 import operator
6 import unittest
7 import struct
8 import sys
9 import weakref
10
11 from test import support
12 from test.support import import_helper, suppress_immortalization
13 from test.support.script_helper import assert_python_ok
14
15 ISBIGENDIAN = sys.byteorder == "big"
16
17 integer_codes = 'b', 'B', 'h', 'H', 'i', 'I', 'l', 'L', 'q', 'Q', 'n', 'N'
18 byteorders = '', '@', '=', '<', '>', '!'
19
20 def iter_integer_formats(byteorders=byteorders):
21 for code in integer_codes:
22 for byteorder in byteorders:
23 if (byteorder not in ('', '@') and code in ('n', 'N')):
24 continue
25 yield code, byteorder
26
27 def string_reverse(s):
28 return s[::-1]
29
30 def bigendian_to_native(value):
31 if ISBIGENDIAN:
32 return value
33 else:
34 return string_reverse(value)
35
36 class StructTest(unittest.TestCase):
37 def test_isbigendian(self):
38 self.assertEqual((struct.pack('=i', 1)[0] == 0), ISBIGENDIAN)
39
40 def test_consistence(self):
41 self.assertRaises(struct.error, struct.calcsize, 'Z')
42
43 sz = struct.calcsize('i')
44 self.assertEqual(sz * 3, struct.calcsize('iii'))
45
46 fmt = 'cbxxxxxxhhhhiillffd?'
47 fmt3 = '3c3b18x12h6i6l6f3d3?'
48 sz = struct.calcsize(fmt)
49 sz3 = struct.calcsize(fmt3)
50 self.assertEqual(sz * 3, sz3)
51
52 self.assertRaises(struct.error, struct.pack, 'iii', 3)
53 self.assertRaises(struct.error, struct.pack, 'i', 3, 3, 3)
54 self.assertRaises((TypeError, struct.error), struct.pack, 'i', 'foo')
55 self.assertRaises((TypeError, struct.error), struct.pack, 'P', 'foo')
56 self.assertRaises(struct.error, struct.unpack, 'd', b'flap')
57 s = struct.pack('ii', 1, 2)
58 self.assertRaises(struct.error, struct.unpack, 'iii', s)
59 self.assertRaises(struct.error, struct.unpack, 'i', s)
60
61 def test_transitiveness(self):
62 c = b'a'
63 b = 1
64 h = 255
65 i = 65535
66 l = 65536
67 f = 3.1415
68 d = 3.1415
69 t = True
70
71 for prefix in ('', '@', '<', '>', '=', '!'):
72 for format in ('xcbhilfd?', 'xcBHILfd?'):
73 format = prefix + format
74 s = struct.pack(format, c, b, h, i, l, f, d, t)
75 cp, bp, hp, ip, lp, fp, dp, tp = struct.unpack(format, s)
76 self.assertEqual(cp, c)
77 self.assertEqual(bp, b)
78 self.assertEqual(hp, h)
79 self.assertEqual(ip, i)
80 self.assertEqual(lp, l)
81 self.assertEqual(int(100 * fp), int(100 * f))
82 self.assertEqual(int(100 * dp), int(100 * d))
83 self.assertEqual(tp, t)
84
85 def test_new_features(self):
86 # Test some of the new features in detail
87 # (format, argument, big-endian result, little-endian result, asymmetric)
88 tests = [
89 ('c', b'a', b'a', b'a', 0),
90 ('xc', b'a', b'\0a', b'\0a', 0),
91 ('cx', b'a', b'a\0', b'a\0', 0),
92 ('s', b'a', b'a', b'a', 0),
93 ('0s', b'helloworld', b'', b'', 1),
94 ('1s', b'helloworld', b'h', b'h', 1),
95 ('9s', b'helloworld', b'helloworl', b'helloworl', 1),
96 ('10s', b'helloworld', b'helloworld', b'helloworld', 0),
97 ('11s', b'helloworld', b'helloworld\0', b'helloworld\0', 1),
98 ('20s', b'helloworld', b'helloworld'+10*b'\0', b'helloworld'+10*b'\0', 1),
99 ('0p', b'helloworld', b'', b'', 1),
100 ('1p', b'helloworld', b'\x00', b'\x00', 1),
101 ('2p', b'helloworld', b'\x01h', b'\x01h', 1),
102 ('10p', b'helloworld', b'\x09helloworl', b'\x09helloworl', 1),
103 ('11p', b'helloworld', b'\x0Ahelloworld', b'\x0Ahelloworld', 0),
104 ('12p', b'helloworld', b'\x0Ahelloworld\0', b'\x0Ahelloworld\0', 1),
105 ('20p', b'helloworld', b'\x0Ahelloworld'+9*b'\0', b'\x0Ahelloworld'+9*b'\0', 1),
106 ('b', 7, b'\7', b'\7', 0),
107 ('b', -7, b'\371', b'\371', 0),
108 ('B', 7, b'\7', b'\7', 0),
109 ('B', 249, b'\371', b'\371', 0),
110 ('h', 700, b'\002\274', b'\274\002', 0),
111 ('h', -700, b'\375D', b'D\375', 0),
112 ('H', 700, b'\002\274', b'\274\002', 0),
113 ('H', 0x10000-700, b'\375D', b'D\375', 0),
114 ('i', 70000000, b'\004,\035\200', b'\200\035,\004', 0),
115 ('i', -70000000, b'\373\323\342\200', b'\200\342\323\373', 0),
116 ('I', 70000000, b'\004,\035\200', b'\200\035,\004', 0),
117 ('I', 0x100000000-70000000, b'\373\323\342\200', b'\200\342\323\373', 0),
118 ('l', 70000000, b'\004,\035\200', b'\200\035,\004', 0),
119 ('l', -70000000, b'\373\323\342\200', b'\200\342\323\373', 0),
120 ('L', 70000000, b'\004,\035\200', b'\200\035,\004', 0),
121 ('L', 0x100000000-70000000, b'\373\323\342\200', b'\200\342\323\373', 0),
122 ('f', 2.0, b'@\000\000\000', b'\000\000\000@', 0),
123 ('d', 2.0, b'@\000\000\000\000\000\000\000',
124 b'\000\000\000\000\000\000\000@', 0),
125 ('f', -2.0, b'\300\000\000\000', b'\000\000\000\300', 0),
126 ('d', -2.0, b'\300\000\000\000\000\000\000\000',
127 b'\000\000\000\000\000\000\000\300', 0),
128 ('?', 0, b'\0', b'\0', 0),
129 ('?', 3, b'\1', b'\1', 1),
130 ('?', True, b'\1', b'\1', 0),
131 ('?', [], b'\0', b'\0', 1),
132 ('?', (1,), b'\1', b'\1', 1),
133 ]
134
135 for fmt, arg, big, lil, asy in tests:
136 for (xfmt, exp) in [('>'+fmt, big), ('!'+fmt, big), ('<'+fmt, lil),
137 ('='+fmt, ISBIGENDIAN and big or lil)]:
138 res = struct.pack(xfmt, arg)
139 self.assertEqual(res, exp)
140 self.assertEqual(struct.calcsize(xfmt), len(res))
141 rev = struct.unpack(xfmt, res)[0]
142 if rev != arg:
143 self.assertTrue(asy)
144
145 def test_calcsize(self):
146 expected_size = {
147 'b': 1, 'B': 1,
148 'h': 2, 'H': 2,
149 'i': 4, 'I': 4,
150 'l': 4, 'L': 4,
151 'q': 8, 'Q': 8,
152 }
153
154 # standard integer sizes
155 for code, byteorder in iter_integer_formats(('=', '<', '>', '!')):
156 format = byteorder+code
157 size = struct.calcsize(format)
158 self.assertEqual(size, expected_size[code])
159
160 # native integer sizes
161 native_pairs = 'bB', 'hH', 'iI', 'lL', 'nN', 'qQ'
162 for format_pair in native_pairs:
163 for byteorder in '', '@':
164 signed_size = struct.calcsize(byteorder + format_pair[0])
165 unsigned_size = struct.calcsize(byteorder + format_pair[1])
166 self.assertEqual(signed_size, unsigned_size)
167
168 # bounds for native integer sizes
169 self.assertEqual(struct.calcsize('b'), 1)
170 self.assertLessEqual(2, struct.calcsize('h'))
171 self.assertLessEqual(4, struct.calcsize('l'))
172 self.assertLessEqual(struct.calcsize('h'), struct.calcsize('i'))
173 self.assertLessEqual(struct.calcsize('i'), struct.calcsize('l'))
174 self.assertLessEqual(8, struct.calcsize('q'))
175 self.assertLessEqual(struct.calcsize('l'), struct.calcsize('q'))
176 self.assertGreaterEqual(struct.calcsize('n'), struct.calcsize('i'))
177 self.assertGreaterEqual(struct.calcsize('n'), struct.calcsize('P'))
178
179 def test_integers(self):
180 # Integer tests (bBhHiIlLqQnN).
181 import binascii
182
183 class IntTester(unittest.TestCase):
184 def __init__(self, format):
185 super(IntTester, self).__init__(methodName='test_one')
186 self.format = format
187 self.code = format[-1]
188 self.byteorder = format[:-1]
189 if not self.byteorder in byteorders:
190 raise ValueError("unrecognized packing byteorder: %s" %
191 self.byteorder)
192 self.bytesize = struct.calcsize(format)
193 self.bitsize = self.bytesize * 8
194 if self.code in tuple('bhilqn'):
195 self.signed = True
196 self.min_value = -(2**(self.bitsize-1))
197 self.max_value = 2**(self.bitsize-1) - 1
198 elif self.code in tuple('BHILQN'):
199 self.signed = False
200 self.min_value = 0
201 self.max_value = 2**self.bitsize - 1
202 else:
203 raise ValueError("unrecognized format code: %s" %
204 self.code)
205
206 def test_one(self, x, pack=struct.pack,
207 unpack=struct.unpack,
208 unhexlify=binascii.unhexlify):
209
210 format = self.format
211 if self.min_value <= x <= self.max_value:
212 expected = x
213 if self.signed and x < 0:
214 expected += 1 << self.bitsize
215 self.assertGreaterEqual(expected, 0)
216 expected = '%x' % expected
217 if len(expected) & 1:
218 expected = "0" + expected
219 expected = expected.encode('ascii')
220 expected = unhexlify(expected)
221 expected = (b"\x00" * (self.bytesize - len(expected)) +
222 expected)
223 if (self.byteorder == '<' or
224 self.byteorder in ('', '@', '=') and not ISBIGENDIAN):
225 expected = string_reverse(expected)
226 self.assertEqual(len(expected), self.bytesize)
227
228 # Pack work?
229 got = pack(format, x)
230 self.assertEqual(got, expected)
231
232 # Unpack work?
233 retrieved = unpack(format, got)[0]
234 self.assertEqual(x, retrieved)
235
236 # Adding any byte should cause a "too big" error.
237 self.assertRaises((struct.error, TypeError), unpack, format,
238 b'\x01' + got)
239 else:
240 # x is out of range -- verify pack realizes that.
241 self.assertRaises((OverflowError, ValueError, struct.error),
242 pack, format, x)
243
244 def run(self):
245 from random import randrange
246
247 # Create all interesting powers of 2.
248 values = []
249 for exp in range(self.bitsize + 3):
250 values.append(1 << exp)
251
252 # Add some random values.
253 for i in range(self.bitsize):
254 val = 0
255 for j in range(self.bytesize):
256 val = (val << 8) | randrange(256)
257 values.append(val)
258
259 # Values absorbed from other tests
260 values.extend([300, 700000, sys.maxsize*4])
261
262 # Try all those, and their negations, and +-1 from
263 # them. Note that this tests all power-of-2
264 # boundaries in range, and a few out of range, plus
265 # +-(2**n +- 1).
266 for base in values:
267 for val in -base, base:
268 for incr in -1, 0, 1:
269 x = val + incr
270 self.test_one(x)
271
272 # Some error cases.
273 class NotAnInt:
274 def __int__(self):
275 return 42
276
277 # Objects with an '__index__' method should be allowed
278 # to pack as integers. That is assuming the implemented
279 # '__index__' method returns an 'int'.
280 class Indexable(object):
281 def __init__(self, value):
282 self._value = value
283
284 def __index__(self):
285 return self._value
286
287 # If the '__index__' method raises a type error, then
288 # '__int__' should be used with a deprecation warning.
289 class BadIndex(object):
290 def __index__(self):
291 raise TypeError
292
293 def __int__(self):
294 return 42
295
296 self.assertRaises((TypeError, struct.error),
297 struct.pack, self.format,
298 "a string")
299 self.assertRaises((TypeError, struct.error),
300 struct.pack, self.format,
301 randrange)
302 self.assertRaises((TypeError, struct.error),
303 struct.pack, self.format,
304 3+42j)
305 self.assertRaises((TypeError, struct.error),
306 struct.pack, self.format,
307 NotAnInt())
308 self.assertRaises((TypeError, struct.error),
309 struct.pack, self.format,
310 BadIndex())
311
312 # Check for legitimate values from '__index__'.
313 for obj in (Indexable(0), Indexable(10), Indexable(17),
314 Indexable(42), Indexable(100), Indexable(127)):
315 try:
316 struct.pack(format, obj)
317 except:
318 self.fail("integer code pack failed on object "
319 "with '__index__' method")
320
321 # Check for bogus values from '__index__'.
322 for obj in (Indexable(b'a'), Indexable('b'), Indexable(None),
323 Indexable({'a': 1}), Indexable([1, 2, 3])):
324 self.assertRaises((TypeError, struct.error),
325 struct.pack, self.format,
326 obj)
327
328 for code, byteorder in iter_integer_formats():
329 format = byteorder+code
330 t = IntTester(format)
331 t.run()
332
333 def test_nN_code(self):
334 # n and N don't exist in standard sizes
335 def assertStructError(func, *args, **kwargs):
336 with self.assertRaises(struct.error) as cm:
337 func(*args, **kwargs)
338 self.assertIn("bad char in struct format", str(cm.exception))
339 for code in 'nN':
340 for byteorder in ('=', '<', '>', '!'):
341 format = byteorder+code
342 assertStructError(struct.calcsize, format)
343 assertStructError(struct.pack, format, 0)
344 assertStructError(struct.unpack, format, b"")
345
346 def test_p_code(self):
347 # Test p ("Pascal string") code.
348 for code, input, expected, expectedback in [
349 ('0p', b'abc', b'', b''),
350 ('p', b'abc', b'\x00', b''),
351 ('1p', b'abc', b'\x00', b''),
352 ('2p', b'abc', b'\x01a', b'a'),
353 ('3p', b'abc', b'\x02ab', b'ab'),
354 ('4p', b'abc', b'\x03abc', b'abc'),
355 ('5p', b'abc', b'\x03abc\x00', b'abc'),
356 ('6p', b'abc', b'\x03abc\x00\x00', b'abc'),
357 ('1000p', b'x'*1000, b'\xff' + b'x'*999, b'x'*255)]:
358 got = struct.pack(code, input)
359 self.assertEqual(got, expected)
360 (got,) = struct.unpack(code, got)
361 self.assertEqual(got, expectedback)
362
363 def test_705836(self):
364 # SF bug 705836. "<f" and ">f" had a severe rounding bug, where a carry
365 # from the low-order discarded bits could propagate into the exponent
366 # field, causing the result to be wrong by a factor of 2.
367 for base in range(1, 33):
368 # smaller <- largest representable float less than base.
369 delta = 0.5
370 while base - delta / 2.0 != base:
371 delta /= 2.0
372 smaller = base - delta
373 # Packing this rounds away a solid string of trailing 1 bits.
374 packed = struct.pack("<f", smaller)
375 unpacked = struct.unpack("<f", packed)[0]
376 # This failed at base = 2, 4, and 32, with unpacked = 1, 2, and
377 # 16, respectively.
378 self.assertEqual(base, unpacked)
379 bigpacked = struct.pack(">f", smaller)
380 self.assertEqual(bigpacked, string_reverse(packed))
381 unpacked = struct.unpack(">f", bigpacked)[0]
382 self.assertEqual(base, unpacked)
383
384 # Largest finite IEEE single.
385 big = (1 << 24) - 1
386 big = math.ldexp(big, 127 - 23)
387 packed = struct.pack(">f", big)
388 unpacked = struct.unpack(">f", packed)[0]
389 self.assertEqual(big, unpacked)
390
391 # The same, but tack on a 1 bit so it rounds up to infinity.
392 big = (1 << 25) - 1
393 big = math.ldexp(big, 127 - 24)
394 self.assertRaises(OverflowError, struct.pack, ">f", big)
395
396 def test_1530559(self):
397 for code, byteorder in iter_integer_formats():
398 format = byteorder + code
399 self.assertRaises(struct.error, struct.pack, format, 1.0)
400 self.assertRaises(struct.error, struct.pack, format, 1.5)
401 self.assertRaises(struct.error, struct.pack, 'P', 1.0)
402 self.assertRaises(struct.error, struct.pack, 'P', 1.5)
403
404 def test_unpack_from(self):
405 test_string = b'abcd01234'
406 fmt = '4s'
407 s = struct.Struct(fmt)
408 for cls in (bytes, bytearray):
409 data = cls(test_string)
410 self.assertEqual(s.unpack_from(data), (b'abcd',))
411 self.assertEqual(s.unpack_from(data, 2), (b'cd01',))
412 self.assertEqual(s.unpack_from(data, 4), (b'0123',))
413 for i in range(6):
414 self.assertEqual(s.unpack_from(data, i), (data[i:i+4],))
415 for i in range(6, len(test_string) + 1):
416 self.assertRaises(struct.error, s.unpack_from, data, i)
417 for cls in (bytes, bytearray):
418 data = cls(test_string)
419 self.assertEqual(struct.unpack_from(fmt, data), (b'abcd',))
420 self.assertEqual(struct.unpack_from(fmt, data, 2), (b'cd01',))
421 self.assertEqual(struct.unpack_from(fmt, data, 4), (b'0123',))
422 for i in range(6):
423 self.assertEqual(struct.unpack_from(fmt, data, i), (data[i:i+4],))
424 for i in range(6, len(test_string) + 1):
425 self.assertRaises(struct.error, struct.unpack_from, fmt, data, i)
426
427 # keyword arguments
428 self.assertEqual(s.unpack_from(buffer=test_string, offset=2),
429 (b'cd01',))
430
431 def _test_pack_into(self, pack_into):
432 test_string = b'Reykjavik rocks, eow!'
433 writable_buf = memoryview(array.array('b', b' '*100))
434
435 # Test without offset
436 pack_into(writable_buf, 0, test_string)
437 from_buf = writable_buf.tobytes()[:len(test_string)]
438 self.assertEqual(from_buf, test_string)
439
440 # Test with offset.
441 pack_into(writable_buf, 10, test_string)
442 from_buf = writable_buf.tobytes()[:len(test_string)+10]
443 self.assertEqual(from_buf, test_string[:10] + test_string)
444
445 # Test with negative offset.
446 pack_into(writable_buf, -30, test_string)
447 from_buf = writable_buf.tobytes()[-30:-30+len(test_string)]
448 self.assertEqual(from_buf, test_string)
449
450 # Go beyond boundaries.
451 small_buf = array.array('b', b' '*10)
452 with self.assertRaises((ValueError, struct.error)):
453 pack_into(small_buf, 0, test_string)
454 with self.assertRaises((ValueError, struct.error)):
455 pack_into(writable_buf, 90, test_string)
456 with self.assertRaises((ValueError, struct.error)):
457 pack_into(writable_buf, -10, test_string)
458 with self.assertRaises((ValueError, struct.error)):
459 pack_into(writable_buf, 150, test_string)
460 with self.assertRaises((ValueError, struct.error)):
461 pack_into(writable_buf, -150, test_string)
462
463 # Test invalid buffer.
464 self.assertRaises(TypeError, pack_into, b' '*100, 0, test_string)
465 self.assertRaises(TypeError, pack_into, ' '*100, 0, test_string)
466 self.assertRaises(TypeError, pack_into, [0]*100, 0, test_string)
467 self.assertRaises(TypeError, pack_into, None, 0, test_string)
468 self.assertRaises(TypeError, pack_into, writable_buf[::2], 0, test_string)
469 self.assertRaises(TypeError, pack_into, writable_buf[::-1], 0, test_string)
470
471 # Test bogus offset (issue bpo-3694)
472 with self.assertRaises(TypeError):
473 pack_into(writable_buf, None, test_string)
474 with self.assertRaises(TypeError):
475 pack_into(writable_buf, 0.0, test_string)
476 with self.assertRaises((IndexError, OverflowError)):
477 pack_into(writable_buf, 2**1000, test_string)
478 with self.assertRaises((IndexError, OverflowError)):
479 pack_into(writable_buf, -2**1000, test_string)
480
481 def test_pack_into(self):
482 s = struct.Struct('21s')
483 self._test_pack_into(s.pack_into)
484
485 def test_pack_into_fn(self):
486 pack_into = lambda *args: struct.pack_into('21s', *args)
487 self._test_pack_into(pack_into)
488
489 def test_unpack_with_buffer(self):
490 # SF bug 1563759: struct.unpack doesn't support buffer protocol objects
491 data1 = array.array('B', b'\x12\x34\x56\x78')
492 data2 = memoryview(b'\x12\x34\x56\x78') # XXX b'......XXXX......', 6, 4
493 for data in [data1, data2]:
494 value, = struct.unpack('>I', data)
495 self.assertEqual(value, 0x12345678)
496
497 def test_bool(self):
498 class ExplodingBool(object):
499 def __bool__(self):
500 raise OSError
501 for prefix in tuple("<>!=")+('',):
502 false = (), [], [], '', 0
503 true = [1], 'test', 5, -1, 0xffffffff+1, 0xffffffff/2
504
505 falseFormat = prefix + '?' * len(false)
506 packedFalse = struct.pack(falseFormat, *false)
507 unpackedFalse = struct.unpack(falseFormat, packedFalse)
508
509 trueFormat = prefix + '?' * len(true)
510 packedTrue = struct.pack(trueFormat, *true)
511 unpackedTrue = struct.unpack(trueFormat, packedTrue)
512
513 self.assertEqual(len(true), len(unpackedTrue))
514 self.assertEqual(len(false), len(unpackedFalse))
515
516 for t in unpackedFalse:
517 self.assertFalse(t)
518 for t in unpackedTrue:
519 self.assertTrue(t)
520
521 packed = struct.pack(prefix+'?', 1)
522
523 self.assertEqual(len(packed), struct.calcsize(prefix+'?'))
524
525 if len(packed) != 1:
526 self.assertFalse(prefix, msg='encoded bool is not one byte: %r'
527 %packed)
528
529 try:
530 struct.pack(prefix + '?', ExplodingBool())
531 except OSError:
532 pass
533 else:
534 self.fail("Expected OSError: struct.pack(%r, "
535 "ExplodingBool())" % (prefix + '?'))
536
537 for c in [b'\x01', b'\x7f', b'\xff', b'\x0f', b'\xf0']:
538 self.assertTrue(struct.unpack('>?', c)[0])
539 self.assertTrue(struct.unpack('<?', c)[0])
540 self.assertTrue(struct.unpack('=?', c)[0])
541 self.assertTrue(struct.unpack('@?', c)[0])
542
543 def test_count_overflow(self):
544 hugecount = '{}b'.format(sys.maxsize+1)
545 self.assertRaises(struct.error, struct.calcsize, hugecount)
546
547 hugecount2 = '{}b{}H'.format(sys.maxsize//2, sys.maxsize//2)
548 self.assertRaises(struct.error, struct.calcsize, hugecount2)
549
550 def test_trailing_counter(self):
551 store = array.array('b', b' '*100)
552
553 # format lists containing only count spec should result in an error
554 self.assertRaises(struct.error, struct.pack, '12345')
555 self.assertRaises(struct.error, struct.unpack, '12345', b'')
556 self.assertRaises(struct.error, struct.pack_into, '12345', store, 0)
557 self.assertRaises(struct.error, struct.unpack_from, '12345', store, 0)
558
559 # Format lists with trailing count spec should result in an error
560 self.assertRaises(struct.error, struct.pack, 'c12345', 'x')
561 self.assertRaises(struct.error, struct.unpack, 'c12345', b'x')
562 self.assertRaises(struct.error, struct.pack_into, 'c12345', store, 0,
563 'x')
564 self.assertRaises(struct.error, struct.unpack_from, 'c12345', store,
565 0)
566
567 # Mixed format tests
568 self.assertRaises(struct.error, struct.pack, '14s42', 'spam and eggs')
569 self.assertRaises(struct.error, struct.unpack, '14s42',
570 b'spam and eggs')
571 self.assertRaises(struct.error, struct.pack_into, '14s42', store, 0,
572 'spam and eggs')
573 self.assertRaises(struct.error, struct.unpack_from, '14s42', store, 0)
574
575 def test_Struct_reinitialization(self):
576 # Issue 9422: there was a memory leak when reinitializing a
577 # Struct instance. This test can be used to detect the leak
578 # when running with regrtest -L.
579 s = struct.Struct('i')
580 s.__init__('ii')
581
582 def check_sizeof(self, format_str, number_of_codes):
583 # The size of 'PyStructObject'
584 totalsize = support.calcobjsize('2n3P')
585 # The size taken up by the 'formatcode' dynamic array
586 totalsize += struct.calcsize('P3n0P') * (number_of_codes + 1)
587 support.check_sizeof(self, struct.Struct(format_str), totalsize)
588
589 @support.cpython_only
590 def test__sizeof__(self):
591 for code in integer_codes:
592 self.check_sizeof(code, 1)
593 self.check_sizeof('BHILfdspP', 9)
594 self.check_sizeof('B' * 1234, 1234)
595 self.check_sizeof('fd', 2)
596 self.check_sizeof('xxxxxxxxxxxxxx', 0)
597 self.check_sizeof('100H', 1)
598 self.check_sizeof('187s', 1)
599 self.check_sizeof('20p', 1)
600 self.check_sizeof('0s', 1)
601 self.check_sizeof('0p', 1)
602 self.check_sizeof('0c', 0)
603
604 def test_boundary_error_message(self):
605 regex1 = (
606 r'pack_into requires a buffer of at least 6 '
607 r'bytes for packing 1 bytes at offset 5 '
608 r'\(actual buffer size is 1\)'
609 )
610 with self.assertRaisesRegex(struct.error, regex1):
611 struct.pack_into('b', bytearray(1), 5, 1)
612
613 regex2 = (
614 r'unpack_from requires a buffer of at least 6 '
615 r'bytes for unpacking 1 bytes at offset 5 '
616 r'\(actual buffer size is 1\)'
617 )
618 with self.assertRaisesRegex(struct.error, regex2):
619 struct.unpack_from('b', bytearray(1), 5)
620
621 def test_boundary_error_message_with_negative_offset(self):
622 byte_list = bytearray(10)
623 with self.assertRaisesRegex(
624 struct.error,
625 r'no space to pack 4 bytes at offset -2'):
626 struct.pack_into('<I', byte_list, -2, 123)
627
628 with self.assertRaisesRegex(
629 struct.error,
630 'offset -11 out of range for 10-byte buffer'):
631 struct.pack_into('<B', byte_list, -11, 123)
632
633 with self.assertRaisesRegex(
634 struct.error,
635 r'not enough data to unpack 4 bytes at offset -2'):
636 struct.unpack_from('<I', byte_list, -2)
637
638 with self.assertRaisesRegex(
639 struct.error,
640 "offset -11 out of range for 10-byte buffer"):
641 struct.unpack_from('<B', byte_list, -11)
642
643 def test_boundary_error_message_with_large_offset(self):
644 # Test overflows cause by large offset and value size (issue 30245)
645 regex1 = (
646 r'pack_into requires a buffer of at least ' + str(sys.maxsize + 4) +
647 r' bytes for packing 4 bytes at offset ' + str(sys.maxsize) +
648 r' \(actual buffer size is 10\)'
649 )
650 with self.assertRaisesRegex(struct.error, regex1):
651 struct.pack_into('<I', bytearray(10), sys.maxsize, 1)
652
653 regex2 = (
654 r'unpack_from requires a buffer of at least ' + str(sys.maxsize + 4) +
655 r' bytes for unpacking 4 bytes at offset ' + str(sys.maxsize) +
656 r' \(actual buffer size is 10\)'
657 )
658 with self.assertRaisesRegex(struct.error, regex2):
659 struct.unpack_from('<I', bytearray(10), sys.maxsize)
660
661 def test_issue29802(self):
662 # When the second argument of struct.unpack() was of wrong type
663 # the Struct object was decrefed twice and the reference to
664 # deallocated object was left in a cache.
665 with self.assertRaises(TypeError):
666 struct.unpack('b', 0)
667 # Shouldn't crash.
668 self.assertEqual(struct.unpack('b', b'a'), (b'a'[0],))
669
670 def test_format_attr(self):
671 s = struct.Struct('=i2H')
672 self.assertEqual(s.format, '=i2H')
673
674 # use a bytes string
675 s2 = struct.Struct(s.format.encode())
676 self.assertEqual(s2.format, s.format)
677
678 def test_struct_cleans_up_at_runtime_shutdown(self):
679 code = """if 1:
680 import struct
681
682 class C:
683 def __init__(self):
684 self.pack = struct.pack
685 def __del__(self):
686 self.pack('I', -42)
687
688 struct.x = C()
689 """
690 rc, stdout, stderr = assert_python_ok("-c", code)
691 self.assertEqual(rc, 0)
692 self.assertEqual(stdout.rstrip(), b"")
693 self.assertIn(b"Exception ignored in:", stderr)
694 self.assertIn(b"C.__del__", stderr)
695
696 @suppress_immortalization()
697 def test__struct_reference_cycle_cleaned_up(self):
698 # Regression test for python/cpython#94207.
699
700 # When we create a new struct module, trigger use of its cache,
701 # and then delete it ...
702 _struct_module = import_helper.import_fresh_module("_struct")
703 module_ref = weakref.ref(_struct_module)
704 _struct_module.calcsize("b")
705 del _struct_module
706
707 # Then the module should have been garbage collected.
708 gc.collect()
709 self.assertIsNone(
710 module_ref(), "_struct module was not garbage collected")
711
712 @support.cpython_only
713 def test__struct_types_immutable(self):
714 # See https://github.com/python/cpython/issues/94254
715
716 Struct = struct.Struct
717 unpack_iterator = type(struct.iter_unpack("b", b'x'))
718 for cls in (Struct, unpack_iterator):
719 with self.subTest(cls=cls):
720 with self.assertRaises(TypeError):
721 cls.x = 1
722
723
724 def test_issue35714(self):
725 # Embedded null characters should not be allowed in format strings.
726 for s in '\0', '2\0i', b'\0':
727 with self.assertRaisesRegex(struct.error,
728 'embedded null character'):
729 struct.calcsize(s)
730
731 @support.cpython_only
732 def test_issue98248(self):
733 def test_error_msg(prefix, int_type, is_unsigned):
734 fmt_str = prefix + int_type
735 size = struct.calcsize(fmt_str)
736 if is_unsigned:
737 max_ = 2 ** (size * 8) - 1
738 min_ = 0
739 else:
740 max_ = 2 ** (size * 8 - 1) - 1
741 min_ = -2 ** (size * 8 - 1)
742 error_msg = f"'{int_type}' format requires {min_} <= number <= {max_}"
743 for number in [int(-1e50), min_ - 1, max_ + 1, int(1e50)]:
744 with self.subTest(format_str=fmt_str, number=number):
745 with self.assertRaisesRegex(struct.error, error_msg):
746 struct.pack(fmt_str, number)
747 error_msg = "required argument is not an integer"
748 not_number = ""
749 with self.subTest(format_str=fmt_str, number=not_number):
750 with self.assertRaisesRegex(struct.error, error_msg):
751 struct.pack(fmt_str, not_number)
752
753 for prefix in '@=<>':
754 for int_type in 'BHILQ':
755 test_error_msg(prefix, int_type, True)
756 for int_type in 'bhilq':
757 test_error_msg(prefix, int_type, False)
758
759 int_type = 'N'
760 test_error_msg('@', int_type, True)
761
762 int_type = 'n'
763 test_error_msg('@', int_type, False)
764
765 @support.cpython_only
766 def test_issue98248_error_propagation(self):
767 class Div0:
768 def __index__(self):
769 1 / 0
770
771 def test_error_propagation(fmt_str):
772 with self.subTest(format_str=fmt_str, exception="ZeroDivisionError"):
773 with self.assertRaises(ZeroDivisionError):
774 struct.pack(fmt_str, Div0())
775
776 for prefix in '@=<>':
777 for int_type in 'BHILQbhilq':
778 test_error_propagation(prefix + int_type)
779
780 test_error_propagation('N')
781 test_error_propagation('n')
782
783 def test_struct_subclass_instantiation(self):
784 # Regression test for https://github.com/python/cpython/issues/112358
785 class MyStruct(struct.Struct):
786 def __init__(self):
787 super().__init__('>h')
788
789 my_struct = MyStruct()
790 self.assertEqual(my_struct.pack(12345), b'\x30\x39')
791
792 def test_repr(self):
793 s = struct.Struct('=i2H')
794 self.assertEqual(repr(s), f'Struct({s.format!r})')
795
796 def test_operations_on_half_initialized_Struct(self):
797 S = struct.Struct.__new__(struct.Struct)
798
799 spam = array.array('b', b' ')
800 self.assertRaises(RuntimeError, S.iter_unpack, spam)
801 self.assertRaises(RuntimeError, S.pack, 1)
802 self.assertRaises(RuntimeError, S.pack_into, spam, 1)
803 self.assertRaises(RuntimeError, S.unpack, spam)
804 self.assertRaises(RuntimeError, S.unpack_from, spam)
805 self.assertRaises(RuntimeError, getattr, S, 'format')
806 self.assertEqual(S.size, -1)
807
808
809 class UnpackIteratorTest(unittest.TestCase):
810 """
811 Tests for iterative unpacking (struct.Struct.iter_unpack).
812 """
813
814 def test_construct(self):
815 def _check_iterator(it):
816 self.assertIsInstance(it, abc.Iterator)
817 self.assertIsInstance(it, abc.Iterable)
818 s = struct.Struct('>ibcp')
819 it = s.iter_unpack(b"")
820 _check_iterator(it)
821 it = s.iter_unpack(b"1234567")
822 _check_iterator(it)
823 # Wrong bytes length
824 with self.assertRaises(struct.error):
825 s.iter_unpack(b"123456")
826 with self.assertRaises(struct.error):
827 s.iter_unpack(b"12345678")
828 # Zero-length struct
829 s = struct.Struct('>')
830 with self.assertRaises(struct.error):
831 s.iter_unpack(b"")
832 with self.assertRaises(struct.error):
833 s.iter_unpack(b"12")
834
835 def test_uninstantiable(self):
836 iter_unpack_type = type(struct.Struct(">ibcp").iter_unpack(b""))
837 self.assertRaises(TypeError, iter_unpack_type)
838
839 def test_iterate(self):
840 s = struct.Struct('>IB')
841 b = bytes(range(1, 16))
842 it = s.iter_unpack(b)
843 self.assertEqual(next(it), (0x01020304, 5))
844 self.assertEqual(next(it), (0x06070809, 10))
845 self.assertEqual(next(it), (0x0b0c0d0e, 15))
846 self.assertRaises(StopIteration, next, it)
847 self.assertRaises(StopIteration, next, it)
848
849 def test_arbitrary_buffer(self):
850 s = struct.Struct('>IB')
851 b = bytes(range(1, 11))
852 it = s.iter_unpack(memoryview(b))
853 self.assertEqual(next(it), (0x01020304, 5))
854 self.assertEqual(next(it), (0x06070809, 10))
855 self.assertRaises(StopIteration, next, it)
856 self.assertRaises(StopIteration, next, it)
857
858 def test_length_hint(self):
859 lh = operator.length_hint
860 s = struct.Struct('>IB')
861 b = bytes(range(1, 16))
862 it = s.iter_unpack(b)
863 self.assertEqual(lh(it), 3)
864 next(it)
865 self.assertEqual(lh(it), 2)
866 next(it)
867 self.assertEqual(lh(it), 1)
868 next(it)
869 self.assertEqual(lh(it), 0)
870 self.assertRaises(StopIteration, next, it)
871 self.assertEqual(lh(it), 0)
872
873 def test_module_func(self):
874 # Sanity check for the global struct.iter_unpack()
875 it = struct.iter_unpack('>IB', bytes(range(1, 11)))
876 self.assertEqual(next(it), (0x01020304, 5))
877 self.assertEqual(next(it), (0x06070809, 10))
878 self.assertRaises(StopIteration, next, it)
879 self.assertRaises(StopIteration, next, it)
880
881 def test_half_float(self):
882 # Little-endian examples from:
883 # http://en.wikipedia.org/wiki/Half_precision_floating-point_format
884 format_bits_float__cleanRoundtrip_list = [
885 (b'\x00\x3c', 1.0),
886 (b'\x00\xc0', -2.0),
887 (b'\xff\x7b', 65504.0), # (max half precision)
888 (b'\x00\x04', 2**-14), # ~= 6.10352 * 10**-5 (min pos normal)
889 (b'\x01\x00', 2**-24), # ~= 5.96046 * 10**-8 (min pos subnormal)
890 (b'\x00\x00', 0.0),
891 (b'\x00\x80', -0.0),
892 (b'\x00\x7c', float('+inf')),
893 (b'\x00\xfc', float('-inf')),
894 (b'\x55\x35', 0.333251953125), # ~= 1/3
895 ]
896
897 for le_bits, f in format_bits_float__cleanRoundtrip_list:
898 be_bits = le_bits[::-1]
899 self.assertEqual(f, struct.unpack('<e', le_bits)[0])
900 self.assertEqual(le_bits, struct.pack('<e', f))
901 self.assertEqual(f, struct.unpack('>e', be_bits)[0])
902 self.assertEqual(be_bits, struct.pack('>e', f))
903 if sys.byteorder == 'little':
904 self.assertEqual(f, struct.unpack('e', le_bits)[0])
905 self.assertEqual(le_bits, struct.pack('e', f))
906 else:
907 self.assertEqual(f, struct.unpack('e', be_bits)[0])
908 self.assertEqual(be_bits, struct.pack('e', f))
909
910 # Check for NaN handling:
911 format_bits__nan_list = [
912 ('<e', b'\x01\xfc'),
913 ('<e', b'\x00\xfe'),
914 ('<e', b'\xff\xff'),
915 ('<e', b'\x01\x7c'),
916 ('<e', b'\x00\x7e'),
917 ('<e', b'\xff\x7f'),
918 ]
919
920 for formatcode, bits in format_bits__nan_list:
921 self.assertTrue(math.isnan(struct.unpack('<e', bits)[0]))
922 self.assertTrue(math.isnan(struct.unpack('>e', bits[::-1])[0]))
923
924 # Check that packing produces a bit pattern representing a quiet NaN:
925 # all exponent bits and the msb of the fraction should all be 1.
926 packed = struct.pack('<e', math.nan)
927 self.assertEqual(packed[1] & 0x7e, 0x7e)
928 packed = struct.pack('<e', -math.nan)
929 self.assertEqual(packed[1] & 0x7e, 0x7e)
930
931 # Checks for round-to-even behavior
932 format_bits_float__rounding_list = [
933 ('>e', b'\x00\x01', 2.0**-25 + 2.0**-35), # Rounds to minimum subnormal
934 ('>e', b'\x00\x00', 2.0**-25), # Underflows to zero (nearest even mode)
935 ('>e', b'\x00\x00', 2.0**-26), # Underflows to zero
936 ('>e', b'\x03\xff', 2.0**-14 - 2.0**-24), # Largest subnormal.
937 ('>e', b'\x03\xff', 2.0**-14 - 2.0**-25 - 2.0**-65),
938 ('>e', b'\x04\x00', 2.0**-14 - 2.0**-25),
939 ('>e', b'\x04\x00', 2.0**-14), # Smallest normal.
940 ('>e', b'\x3c\x01', 1.0+2.0**-11 + 2.0**-16), # rounds to 1.0+2**(-10)
941 ('>e', b'\x3c\x00', 1.0+2.0**-11), # rounds to 1.0 (nearest even mode)
942 ('>e', b'\x3c\x00', 1.0+2.0**-12), # rounds to 1.0
943 ('>e', b'\x7b\xff', 65504), # largest normal
944 ('>e', b'\x7b\xff', 65519), # rounds to 65504
945 ('>e', b'\x80\x01', -2.0**-25 - 2.0**-35), # Rounds to minimum subnormal
946 ('>e', b'\x80\x00', -2.0**-25), # Underflows to zero (nearest even mode)
947 ('>e', b'\x80\x00', -2.0**-26), # Underflows to zero
948 ('>e', b'\xbc\x01', -1.0-2.0**-11 - 2.0**-16), # rounds to 1.0+2**(-10)
949 ('>e', b'\xbc\x00', -1.0-2.0**-11), # rounds to 1.0 (nearest even mode)
950 ('>e', b'\xbc\x00', -1.0-2.0**-12), # rounds to 1.0
951 ('>e', b'\xfb\xff', -65519), # rounds to 65504
952 ]
953
954 for formatcode, bits, f in format_bits_float__rounding_list:
955 self.assertEqual(bits, struct.pack(formatcode, f))
956
957 # This overflows, and so raises an error
958 format_bits_float__roundingError_list = [
959 # Values that round to infinity.
960 ('>e', 65520.0),
961 ('>e', 65536.0),
962 ('>e', 1e300),
963 ('>e', -65520.0),
964 ('>e', -65536.0),
965 ('>e', -1e300),
966 ('<e', 65520.0),
967 ('<e', 65536.0),
968 ('<e', 1e300),
969 ('<e', -65520.0),
970 ('<e', -65536.0),
971 ('<e', -1e300),
972 ]
973
974 for formatcode, f in format_bits_float__roundingError_list:
975 self.assertRaises(OverflowError, struct.pack, formatcode, f)
976
977 # Double rounding
978 format_bits_float__doubleRoundingError_list = [
979 ('>e', b'\x67\xff', 0x1ffdffffff * 2**-26), # should be 2047, if double-rounded 64>32>16, becomes 2048
980 ]
981
982 for formatcode, bits, f in format_bits_float__doubleRoundingError_list:
983 self.assertEqual(bits, struct.pack(formatcode, f))
984
985
986 if __name__ == '__main__':
987 unittest.main()