test_struct.py 37 KB

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