PageRenderTime 50ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/modified-2.7/test/test_struct.py

https://bitbucket.org/dac_io/pypy
Python | 552 lines | 546 code | 4 blank | 2 comment | 3 complexity | c1e042b54236bfa5ae9f08172f52a56f MD5 | raw file
  1. import os
  2. import array
  3. import unittest
  4. import struct
  5. import inspect
  6. from test.test_support import run_unittest, check_warnings, check_py3k_warnings
  7. import sys
  8. ISBIGENDIAN = sys.byteorder == "big"
  9. IS32BIT = sys.maxsize == 0x7fffffff
  10. integer_codes = 'b', 'B', 'h', 'H', 'i', 'I', 'l', 'L', 'q', 'Q'
  11. testmod_filename = os.path.splitext(__file__)[0] + '.py'
  12. # Native 'q' packing isn't available on systems that don't have the C
  13. # long long type.
  14. try:
  15. struct.pack('q', 5)
  16. except struct.error:
  17. HAVE_LONG_LONG = False
  18. else:
  19. HAVE_LONG_LONG = True
  20. def string_reverse(s):
  21. return "".join(reversed(s))
  22. def bigendian_to_native(value):
  23. if ISBIGENDIAN:
  24. return value
  25. else:
  26. return string_reverse(value)
  27. class StructTest(unittest.TestCase):
  28. def check_float_coerce(self, format, number):
  29. # SF bug 1530559. struct.pack raises TypeError where it used
  30. # to convert.
  31. with check_warnings((".*integer argument expected, got float",
  32. DeprecationWarning)) as w:
  33. got = struct.pack(format, number)
  34. lineno = inspect.currentframe().f_lineno - 1
  35. self.assertEqual(w.filename, testmod_filename)
  36. self.assertEqual(w.lineno, lineno)
  37. self.assertEqual(len(w.warnings), 1)
  38. expected = struct.pack(format, int(number))
  39. self.assertEqual(got, expected)
  40. def test_isbigendian(self):
  41. self.assertEqual((struct.pack('=i', 1)[0] == chr(0)), ISBIGENDIAN)
  42. def test_consistence(self):
  43. self.assertRaises(struct.error, struct.calcsize, 'Z')
  44. sz = struct.calcsize('i')
  45. self.assertEqual(sz * 3, struct.calcsize('iii'))
  46. fmt = 'cbxxxxxxhhhhiillffd?'
  47. fmt3 = '3c3b18x12h6i6l6f3d3?'
  48. sz = struct.calcsize(fmt)
  49. sz3 = struct.calcsize(fmt3)
  50. self.assertEqual(sz * 3, sz3)
  51. self.assertRaises(struct.error, struct.pack, 'iii', 3)
  52. self.assertRaises(struct.error, struct.pack, 'i', 3, 3, 3)
  53. self.assertRaises((TypeError, struct.error), struct.pack, 'i', 'foo')
  54. self.assertRaises((TypeError, struct.error), struct.pack, 'P', 'foo')
  55. self.assertRaises(struct.error, struct.unpack, 'd', 'flap')
  56. s = struct.pack('ii', 1, 2)
  57. self.assertRaises(struct.error, struct.unpack, 'iii', s)
  58. self.assertRaises(struct.error, struct.unpack, 'i', s)
  59. def test_transitiveness(self):
  60. c = 'a'
  61. b = 1
  62. h = 255
  63. i = 65535
  64. l = 65536
  65. f = 3.1415
  66. d = 3.1415
  67. t = True
  68. for prefix in ('', '@', '<', '>', '=', '!'):
  69. for format in ('xcbhilfd?', 'xcBHILfd?'):
  70. format = prefix + format
  71. s = struct.pack(format, c, b, h, i, l, f, d, t)
  72. cp, bp, hp, ip, lp, fp, dp, tp = struct.unpack(format, s)
  73. self.assertEqual(cp, c)
  74. self.assertEqual(bp, b)
  75. self.assertEqual(hp, h)
  76. self.assertEqual(ip, i)
  77. self.assertEqual(lp, l)
  78. self.assertEqual(int(100 * fp), int(100 * f))
  79. self.assertEqual(int(100 * dp), int(100 * d))
  80. self.assertEqual(tp, t)
  81. def test_new_features(self):
  82. # Test some of the new features in detail
  83. # (format, argument, big-endian result, little-endian result, asymmetric)
  84. tests = [
  85. ('c', 'a', 'a', 'a', 0),
  86. ('xc', 'a', '\0a', '\0a', 0),
  87. ('cx', 'a', 'a\0', 'a\0', 0),
  88. ('s', 'a', 'a', 'a', 0),
  89. ('0s', 'helloworld', '', '', 1),
  90. ('1s', 'helloworld', 'h', 'h', 1),
  91. ('9s', 'helloworld', 'helloworl', 'helloworl', 1),
  92. ('10s', 'helloworld', 'helloworld', 'helloworld', 0),
  93. ('11s', 'helloworld', 'helloworld\0', 'helloworld\0', 1),
  94. ('20s', 'helloworld', 'helloworld'+10*'\0', 'helloworld'+10*'\0', 1),
  95. ('b', 7, '\7', '\7', 0),
  96. ('b', -7, '\371', '\371', 0),
  97. ('B', 7, '\7', '\7', 0),
  98. ('B', 249, '\371', '\371', 0),
  99. ('h', 700, '\002\274', '\274\002', 0),
  100. ('h', -700, '\375D', 'D\375', 0),
  101. ('H', 700, '\002\274', '\274\002', 0),
  102. ('H', 0x10000-700, '\375D', 'D\375', 0),
  103. ('i', 70000000, '\004,\035\200', '\200\035,\004', 0),
  104. ('i', -70000000, '\373\323\342\200', '\200\342\323\373', 0),
  105. ('I', 70000000L, '\004,\035\200', '\200\035,\004', 0),
  106. ('I', 0x100000000L-70000000, '\373\323\342\200', '\200\342\323\373', 0),
  107. ('l', 70000000, '\004,\035\200', '\200\035,\004', 0),
  108. ('l', -70000000, '\373\323\342\200', '\200\342\323\373', 0),
  109. ('L', 70000000L, '\004,\035\200', '\200\035,\004', 0),
  110. ('L', 0x100000000L-70000000, '\373\323\342\200', '\200\342\323\373', 0),
  111. ('f', 2.0, '@\000\000\000', '\000\000\000@', 0),
  112. ('d', 2.0, '@\000\000\000\000\000\000\000',
  113. '\000\000\000\000\000\000\000@', 0),
  114. ('f', -2.0, '\300\000\000\000', '\000\000\000\300', 0),
  115. ('d', -2.0, '\300\000\000\000\000\000\000\000',
  116. '\000\000\000\000\000\000\000\300', 0),
  117. ('?', 0, '\0', '\0', 0),
  118. ('?', 3, '\1', '\1', 1),
  119. ('?', True, '\1', '\1', 0),
  120. ('?', [], '\0', '\0', 1),
  121. ('?', (1,), '\1', '\1', 1),
  122. ]
  123. for fmt, arg, big, lil, asy in tests:
  124. for (xfmt, exp) in [('>'+fmt, big), ('!'+fmt, big), ('<'+fmt, lil),
  125. ('='+fmt, ISBIGENDIAN and big or lil)]:
  126. res = struct.pack(xfmt, arg)
  127. self.assertEqual(res, exp)
  128. self.assertEqual(struct.calcsize(xfmt), len(res))
  129. rev = struct.unpack(xfmt, res)[0]
  130. if rev != arg:
  131. self.assertTrue(asy)
  132. def test_calcsize(self):
  133. expected_size = {
  134. 'b': 1, 'B': 1,
  135. 'h': 2, 'H': 2,
  136. 'i': 4, 'I': 4,
  137. 'l': 4, 'L': 4,
  138. 'q': 8, 'Q': 8,
  139. }
  140. # standard integer sizes
  141. for code in integer_codes:
  142. for byteorder in ('=', '<', '>', '!'):
  143. format = byteorder+code
  144. size = struct.calcsize(format)
  145. self.assertEqual(size, expected_size[code])
  146. # native integer sizes, except 'q' and 'Q'
  147. for format_pair in ('bB', 'hH', 'iI', 'lL'):
  148. for byteorder in ['', '@']:
  149. signed_size = struct.calcsize(byteorder + format_pair[0])
  150. unsigned_size = struct.calcsize(byteorder + format_pair[1])
  151. self.assertEqual(signed_size, unsigned_size)
  152. # bounds for native integer sizes
  153. self.assertEqual(struct.calcsize('b'), 1)
  154. self.assertLessEqual(2, struct.calcsize('h'))
  155. self.assertLessEqual(4, struct.calcsize('l'))
  156. self.assertLessEqual(struct.calcsize('h'), struct.calcsize('i'))
  157. self.assertLessEqual(struct.calcsize('i'), struct.calcsize('l'))
  158. # tests for native 'q' and 'Q' when applicable
  159. if HAVE_LONG_LONG:
  160. self.assertEqual(struct.calcsize('q'), struct.calcsize('Q'))
  161. self.assertLessEqual(8, struct.calcsize('q'))
  162. self.assertLessEqual(struct.calcsize('l'), struct.calcsize('q'))
  163. def test_integers(self):
  164. # Integer tests (bBhHiIlLqQ).
  165. import binascii
  166. class IntTester(unittest.TestCase):
  167. def __init__(self, format):
  168. super(IntTester, self).__init__(methodName='test_one')
  169. self.format = format
  170. self.code = format[-1]
  171. self.direction = format[:-1]
  172. if not self.direction in ('', '@', '=', '<', '>', '!'):
  173. raise ValueError("unrecognized packing direction: %s" %
  174. self.direction)
  175. self.bytesize = struct.calcsize(format)
  176. self.bitsize = self.bytesize * 8
  177. if self.code in tuple('bhilq'):
  178. self.signed = True
  179. self.min_value = -(2L**(self.bitsize-1))
  180. self.max_value = 2L**(self.bitsize-1) - 1
  181. elif self.code in tuple('BHILQ'):
  182. self.signed = False
  183. self.min_value = 0
  184. self.max_value = 2L**self.bitsize - 1
  185. else:
  186. raise ValueError("unrecognized format code: %s" %
  187. self.code)
  188. def test_one(self, x, pack=struct.pack,
  189. unpack=struct.unpack,
  190. unhexlify=binascii.unhexlify):
  191. format = self.format
  192. if self.min_value <= x <= self.max_value:
  193. expected = long(x)
  194. if self.signed and x < 0:
  195. expected += 1L << self.bitsize
  196. self.assertGreaterEqual(expected, 0)
  197. expected = '%x' % expected
  198. if len(expected) & 1:
  199. expected = "0" + expected
  200. expected = unhexlify(expected)
  201. expected = ("\x00" * (self.bytesize - len(expected)) +
  202. expected)
  203. if (self.direction == '<' or
  204. self.direction in ('', '@', '=') and not ISBIGENDIAN):
  205. expected = string_reverse(expected)
  206. self.assertEqual(len(expected), self.bytesize)
  207. # Pack work?
  208. got = pack(format, x)
  209. self.assertEqual(got, expected)
  210. # Unpack work?
  211. retrieved = unpack(format, got)[0]
  212. self.assertEqual(x, retrieved)
  213. # Adding any byte should cause a "too big" error.
  214. self.assertRaises((struct.error, TypeError), unpack, format,
  215. '\x01' + got)
  216. else:
  217. # x is out of range -- verify pack realizes that.
  218. self.assertRaises((OverflowError, ValueError, struct.error),
  219. pack, format, x)
  220. def run(self):
  221. from random import randrange
  222. # Create all interesting powers of 2.
  223. values = []
  224. for exp in range(self.bitsize + 3):
  225. values.append(1L << exp)
  226. # Add some random values.
  227. for i in range(self.bitsize):
  228. val = 0L
  229. for j in range(self.bytesize):
  230. val = (val << 8) | randrange(256)
  231. values.append(val)
  232. # Values absorbed from other tests
  233. values.extend([300, 700000, sys.maxint*4])
  234. # Try all those, and their negations, and +-1 from
  235. # them. Note that this tests all power-of-2
  236. # boundaries in range, and a few out of range, plus
  237. # +-(2**n +- 1).
  238. for base in values:
  239. for val in -base, base:
  240. for incr in -1, 0, 1:
  241. x = val + incr
  242. self.test_one(int(x))
  243. self.test_one(long(x))
  244. # Some error cases.
  245. class NotAnIntNS(object):
  246. def __int__(self):
  247. return 42
  248. def __long__(self):
  249. return 1729L
  250. class NotAnIntOS:
  251. def __int__(self):
  252. return 85
  253. def __long__(self):
  254. return -163L
  255. # Objects with an '__index__' method should be allowed
  256. # to pack as integers. That is assuming the implemented
  257. # '__index__' method returns and 'int' or 'long'.
  258. class Indexable(object):
  259. def __init__(self, value):
  260. self._value = value
  261. def __index__(self):
  262. return self._value
  263. # If the '__index__' method raises a type error, then
  264. # '__int__' should be used with a deprecation warning.
  265. class BadIndex(object):
  266. def __index__(self):
  267. raise TypeError
  268. def __int__(self):
  269. return 42
  270. self.assertRaises((TypeError, struct.error),
  271. struct.pack, self.format,
  272. "a string")
  273. self.assertRaises((TypeError, struct.error),
  274. struct.pack, self.format,
  275. randrange)
  276. with check_warnings(("integer argument expected, "
  277. "got non-integer", DeprecationWarning)):
  278. with self.assertRaises((TypeError, struct.error)):
  279. struct.pack(self.format, 3+42j)
  280. # an attempt to convert a non-integer (with an
  281. # implicit conversion via __int__) should succeed,
  282. # with a DeprecationWarning
  283. for nonint in NotAnIntNS(), NotAnIntOS(), BadIndex():
  284. with check_warnings((".*integer argument expected, got non"
  285. "-integer", DeprecationWarning)) as w:
  286. got = struct.pack(self.format, nonint)
  287. lineno = inspect.currentframe().f_lineno - 1
  288. self.assertEqual(w.filename, testmod_filename)
  289. self.assertEqual(w.lineno, lineno)
  290. self.assertEqual(len(w.warnings), 1)
  291. expected = struct.pack(self.format, int(nonint))
  292. self.assertEqual(got, expected)
  293. # Check for legitimate values from '__index__'.
  294. for obj in (Indexable(0), Indexable(10), Indexable(17),
  295. Indexable(42), Indexable(100), Indexable(127)):
  296. try:
  297. struct.pack(format, obj)
  298. except:
  299. self.fail("integer code pack failed on object "
  300. "with '__index__' method")
  301. # Check for bogus values from '__index__'.
  302. for obj in (Indexable('a'), Indexable(u'b'), Indexable(None),
  303. Indexable({'a': 1}), Indexable([1, 2, 3])):
  304. self.assertRaises((TypeError, struct.error),
  305. struct.pack, self.format,
  306. obj)
  307. byteorders = '', '@', '=', '<', '>', '!'
  308. for code in integer_codes:
  309. for byteorder in byteorders:
  310. if (byteorder in ('', '@') and code in ('q', 'Q') and
  311. not HAVE_LONG_LONG):
  312. continue
  313. format = byteorder+code
  314. t = IntTester(format)
  315. t.run()
  316. def test_p_code(self):
  317. # Test p ("Pascal string") code.
  318. for code, input, expected, expectedback in [
  319. ('p','abc', '\x00', ''),
  320. ('1p', 'abc', '\x00', ''),
  321. ('2p', 'abc', '\x01a', 'a'),
  322. ('3p', 'abc', '\x02ab', 'ab'),
  323. ('4p', 'abc', '\x03abc', 'abc'),
  324. ('5p', 'abc', '\x03abc\x00', 'abc'),
  325. ('6p', 'abc', '\x03abc\x00\x00', 'abc'),
  326. ('1000p', 'x'*1000, '\xff' + 'x'*999, 'x'*255)]:
  327. got = struct.pack(code, input)
  328. self.assertEqual(got, expected)
  329. (got,) = struct.unpack(code, got)
  330. self.assertEqual(got, expectedback)
  331. def test_705836(self):
  332. # SF bug 705836. "<f" and ">f" had a severe rounding bug, where a carry
  333. # from the low-order discarded bits could propagate into the exponent
  334. # field, causing the result to be wrong by a factor of 2.
  335. import math
  336. for base in range(1, 33):
  337. # smaller <- largest representable float less than base.
  338. delta = 0.5
  339. while base - delta / 2.0 != base:
  340. delta /= 2.0
  341. smaller = base - delta
  342. # Packing this rounds away a solid string of trailing 1 bits.
  343. packed = struct.pack("<f", smaller)
  344. unpacked = struct.unpack("<f", packed)[0]
  345. # This failed at base = 2, 4, and 32, with unpacked = 1, 2, and
  346. # 16, respectively.
  347. self.assertEqual(base, unpacked)
  348. bigpacked = struct.pack(">f", smaller)
  349. self.assertEqual(bigpacked, string_reverse(packed))
  350. unpacked = struct.unpack(">f", bigpacked)[0]
  351. self.assertEqual(base, unpacked)
  352. # Largest finite IEEE single.
  353. big = (1 << 24) - 1
  354. big = math.ldexp(big, 127 - 23)
  355. packed = struct.pack(">f", big)
  356. unpacked = struct.unpack(">f", packed)[0]
  357. self.assertEqual(big, unpacked)
  358. # The same, but tack on a 1 bit so it rounds up to infinity.
  359. big = (1 << 25) - 1
  360. big = math.ldexp(big, 127 - 24)
  361. self.assertRaises(OverflowError, struct.pack, ">f", big)
  362. def test_1530559(self):
  363. # SF bug 1530559. struct.pack raises TypeError where it used to convert.
  364. for endian in ('', '>', '<'):
  365. for fmt in integer_codes:
  366. self.check_float_coerce(endian + fmt, 1.0)
  367. self.check_float_coerce(endian + fmt, 1.5)
  368. def test_unpack_from(self, cls=str):
  369. data = cls('abcd01234')
  370. fmt = '4s'
  371. s = struct.Struct(fmt)
  372. self.assertEqual(s.unpack_from(data), ('abcd',))
  373. self.assertEqual(struct.unpack_from(fmt, data), ('abcd',))
  374. for i in xrange(6):
  375. self.assertEqual(s.unpack_from(data, i), (data[i:i+4],))
  376. self.assertEqual(struct.unpack_from(fmt, data, i), (data[i:i+4],))
  377. for i in xrange(6, len(data) + 1):
  378. self.assertRaises(struct.error, s.unpack_from, data, i)
  379. self.assertRaises(struct.error, struct.unpack_from, fmt, data, i)
  380. def test_pack_into(self):
  381. test_string = 'Reykjavik rocks, eow!'
  382. writable_buf = array.array('c', ' '*100)
  383. fmt = '21s'
  384. s = struct.Struct(fmt)
  385. # Test without offset
  386. s.pack_into(writable_buf, 0, test_string)
  387. from_buf = writable_buf.tostring()[:len(test_string)]
  388. self.assertEqual(from_buf, test_string)
  389. # Test with offset.
  390. s.pack_into(writable_buf, 10, test_string)
  391. from_buf = writable_buf.tostring()[:len(test_string)+10]
  392. self.assertEqual(from_buf, test_string[:10] + test_string)
  393. # Go beyond boundaries.
  394. small_buf = array.array('c', ' '*10)
  395. self.assertRaises((ValueError, struct.error), s.pack_into, small_buf, 0,
  396. test_string)
  397. self.assertRaises((ValueError, struct.error), s.pack_into, small_buf, 2,
  398. test_string)
  399. # Test bogus offset (issue 3694)
  400. sb = small_buf
  401. self.assertRaises((TypeError, struct.error), struct.pack_into, b'', sb,
  402. None)
  403. def test_pack_into_fn(self):
  404. test_string = 'Reykjavik rocks, eow!'
  405. writable_buf = array.array('c', ' '*100)
  406. fmt = '21s'
  407. pack_into = lambda *args: struct.pack_into(fmt, *args)
  408. # Test without offset.
  409. pack_into(writable_buf, 0, test_string)
  410. from_buf = writable_buf.tostring()[:len(test_string)]
  411. self.assertEqual(from_buf, test_string)
  412. # Test with offset.
  413. pack_into(writable_buf, 10, test_string)
  414. from_buf = writable_buf.tostring()[:len(test_string)+10]
  415. self.assertEqual(from_buf, test_string[:10] + test_string)
  416. # Go beyond boundaries.
  417. small_buf = array.array('c', ' '*10)
  418. self.assertRaises((ValueError, struct.error), pack_into, small_buf, 0,
  419. test_string)
  420. self.assertRaises((ValueError, struct.error), pack_into, small_buf, 2,
  421. test_string)
  422. def test_unpack_with_buffer(self):
  423. with check_py3k_warnings(("buffer.. not supported in 3.x",
  424. DeprecationWarning)):
  425. # SF bug 1563759: struct.unpack doesn't support buffer protocol objects
  426. data1 = array.array('B', '\x12\x34\x56\x78')
  427. data2 = buffer('......\x12\x34\x56\x78......', 6, 4)
  428. for data in [data1, data2]:
  429. value, = struct.unpack('>I', data)
  430. self.assertEqual(value, 0x12345678)
  431. self.test_unpack_from(cls=buffer)
  432. def test_bool(self):
  433. class ExplodingBool(object):
  434. def __nonzero__(self):
  435. raise IOError
  436. for prefix in tuple("<>!=")+('',):
  437. false = (), [], [], '', 0
  438. true = [1], 'test', 5, -1, 0xffffffffL+1, 0xffffffff//2
  439. falseFormat = prefix + '?' * len(false)
  440. packedFalse = struct.pack(falseFormat, *false)
  441. unpackedFalse = struct.unpack(falseFormat, packedFalse)
  442. trueFormat = prefix + '?' * len(true)
  443. packedTrue = struct.pack(trueFormat, *true)
  444. unpackedTrue = struct.unpack(trueFormat, packedTrue)
  445. self.assertEqual(len(true), len(unpackedTrue))
  446. self.assertEqual(len(false), len(unpackedFalse))
  447. for t in unpackedFalse:
  448. self.assertFalse(t)
  449. for t in unpackedTrue:
  450. self.assertTrue(t)
  451. packed = struct.pack(prefix+'?', 1)
  452. self.assertEqual(len(packed), struct.calcsize(prefix+'?'))
  453. if len(packed) != 1:
  454. self.assertFalse(prefix, msg='encoded bool is not one byte: %r'
  455. %packed)
  456. self.assertRaises(IOError, struct.pack, prefix + '?',
  457. ExplodingBool())
  458. for c in [b'\x01', b'\x7f', b'\xff', b'\x0f', b'\xf0']:
  459. self.assertTrue(struct.unpack('>?', c)[0])
  460. @unittest.skipUnless(IS32BIT, "Specific to 32bit machines")
  461. def test_crasher(self):
  462. self.assertRaises((MemoryError, struct.error), struct.pack,
  463. "357913941c", "a")
  464. def test_count_overflow(self):
  465. hugecount = '{}b'.format(sys.maxsize+1)
  466. self.assertRaises(struct.error, struct.calcsize, hugecount)
  467. hugecount2 = '{}b{}H'.format(sys.maxsize//2, sys.maxsize//2)
  468. self.assertRaises(struct.error, struct.calcsize, hugecount2)
  469. def test_main():
  470. run_unittest(StructTest)
  471. if __name__ == '__main__':
  472. test_main()