PageRenderTime 53ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/dac_io/pypy
Python | 566 lines | 561 code | 4 blank | 1 comment | 4 complexity | 8f06d1bf5fd596fc17e62156666664d6 MD5 | raw file
  1. import unittest
  2. from test.test_support import TESTFN, run_unittest, import_module, unlink, requires
  3. import binascii
  4. import os
  5. import random
  6. from test.test_support import precisionbigmemtest, _1G, _4G
  7. import sys
  8. try:
  9. import mmap
  10. except ImportError:
  11. mmap = None
  12. zlib = import_module('zlib')
  13. class ChecksumTestCase(unittest.TestCase):
  14. # checksum test cases
  15. def test_crc32start(self):
  16. self.assertEqual(zlib.crc32(""), zlib.crc32("", 0))
  17. self.assertTrue(zlib.crc32("abc", 0xffffffff))
  18. def test_crc32empty(self):
  19. self.assertEqual(zlib.crc32("", 0), 0)
  20. self.assertEqual(zlib.crc32("", 1), 1)
  21. self.assertEqual(zlib.crc32("", 432), 432)
  22. def test_adler32start(self):
  23. self.assertEqual(zlib.adler32(""), zlib.adler32("", 1))
  24. self.assertTrue(zlib.adler32("abc", 0xffffffff))
  25. def test_adler32empty(self):
  26. self.assertEqual(zlib.adler32("", 0), 0)
  27. self.assertEqual(zlib.adler32("", 1), 1)
  28. self.assertEqual(zlib.adler32("", 432), 432)
  29. def assertEqual32(self, seen, expected):
  30. # 32-bit values masked -- checksums on 32- vs 64- bit machines
  31. # This is important if bit 31 (0x08000000L) is set.
  32. self.assertEqual(seen & 0x0FFFFFFFFL, expected & 0x0FFFFFFFFL)
  33. def test_penguins(self):
  34. self.assertEqual32(zlib.crc32("penguin", 0), 0x0e5c1a120L)
  35. self.assertEqual32(zlib.crc32("penguin", 1), 0x43b6aa94)
  36. self.assertEqual32(zlib.adler32("penguin", 0), 0x0bcf02f6)
  37. self.assertEqual32(zlib.adler32("penguin", 1), 0x0bd602f7)
  38. self.assertEqual(zlib.crc32("penguin"), zlib.crc32("penguin", 0))
  39. self.assertEqual(zlib.adler32("penguin"),zlib.adler32("penguin",1))
  40. def test_abcdefghijklmnop(self):
  41. """test issue1202 compliance: signed crc32, adler32 in 2.x"""
  42. foo = 'abcdefghijklmnop'
  43. # explicitly test signed behavior
  44. self.assertEqual(zlib.crc32(foo), -1808088941)
  45. self.assertEqual(zlib.crc32('spam'), 1138425661)
  46. self.assertEqual(zlib.adler32(foo+foo), -721416943)
  47. self.assertEqual(zlib.adler32('spam'), 72286642)
  48. def test_same_as_binascii_crc32(self):
  49. foo = 'abcdefghijklmnop'
  50. self.assertEqual(binascii.crc32(foo), zlib.crc32(foo))
  51. self.assertEqual(binascii.crc32('spam'), zlib.crc32('spam'))
  52. def test_negative_crc_iv_input(self):
  53. # The range of valid input values for the crc state should be
  54. # -2**31 through 2**32-1 to allow inputs artifically constrained
  55. # to a signed 32-bit integer.
  56. self.assertEqual(zlib.crc32('ham', -1), zlib.crc32('ham', 0xffffffffL))
  57. self.assertEqual(zlib.crc32('spam', -3141593),
  58. zlib.crc32('spam', 0xffd01027L))
  59. self.assertEqual(zlib.crc32('spam', -(2**31)),
  60. zlib.crc32('spam', (2**31)))
  61. class ExceptionTestCase(unittest.TestCase):
  62. # make sure we generate some expected errors
  63. def test_badlevel(self):
  64. # specifying compression level out of range causes an error
  65. # (but -1 is Z_DEFAULT_COMPRESSION and apparently the zlib
  66. # accepts 0 too)
  67. self.assertRaises(zlib.error, zlib.compress, 'ERROR', 10)
  68. def test_badcompressobj(self):
  69. # verify failure on building compress object with bad params
  70. self.assertRaises(ValueError, zlib.compressobj, 1, zlib.DEFLATED, 0)
  71. # specifying total bits too large causes an error
  72. self.assertRaises(ValueError,
  73. zlib.compressobj, 1, zlib.DEFLATED, zlib.MAX_WBITS + 1)
  74. def test_baddecompressobj(self):
  75. # verify failure on building decompress object with bad params
  76. self.assertRaises(ValueError, zlib.decompressobj, -1)
  77. def test_decompressobj_badflush(self):
  78. # verify failure on calling decompressobj.flush with bad params
  79. self.assertRaises(ValueError, zlib.decompressobj().flush, 0)
  80. self.assertRaises(ValueError, zlib.decompressobj().flush, -1)
  81. class BaseCompressTestCase(object):
  82. def check_big_compress_buffer(self, size, compress_func):
  83. data = os.urandom(size)
  84. try:
  85. compress_func(data)
  86. finally:
  87. # Release memory
  88. data = None
  89. def check_big_decompress_buffer(self, size, decompress_func):
  90. data = 'x' * size
  91. try:
  92. compressed = zlib.compress(data, 1)
  93. finally:
  94. # Release memory
  95. data = None
  96. data = decompress_func(compressed)
  97. # Sanity check
  98. try:
  99. self.assertEqual(len(data), size)
  100. self.assertEqual(len(data.strip('x')), 0)
  101. finally:
  102. data = None
  103. class CompressTestCase(BaseCompressTestCase, unittest.TestCase):
  104. # Test compression in one go (whole message compression)
  105. def test_speech(self):
  106. x = zlib.compress(HAMLET_SCENE)
  107. self.assertEqual(zlib.decompress(x), HAMLET_SCENE)
  108. def test_speech128(self):
  109. # compress more data
  110. data = HAMLET_SCENE * 128
  111. x = zlib.compress(data)
  112. self.assertEqual(zlib.decompress(x), data)
  113. def test_incomplete_stream(self):
  114. # An useful error message is given
  115. x = zlib.compress(HAMLET_SCENE)
  116. self.assertRaisesRegexp(zlib.error,
  117. "Error -5 while decompressing data: incomplete or truncated stream",
  118. zlib.decompress, x[:-1])
  119. # Memory use of the following functions takes into account overallocation
  120. @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=3)
  121. def test_big_compress_buffer(self, size):
  122. compress = lambda s: zlib.compress(s, 1)
  123. self.check_big_compress_buffer(size, compress)
  124. @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=2)
  125. def test_big_decompress_buffer(self, size):
  126. self.check_big_decompress_buffer(size, zlib.decompress)
  127. class CompressObjectTestCase(BaseCompressTestCase, unittest.TestCase):
  128. # Test compression object
  129. def test_pair(self):
  130. # straightforward compress/decompress objects
  131. data = HAMLET_SCENE * 128
  132. co = zlib.compressobj()
  133. x1 = co.compress(data)
  134. x2 = co.flush()
  135. self.assertRaises(zlib.error, co.flush) # second flush should not work
  136. dco = zlib.decompressobj()
  137. y1 = dco.decompress(x1 + x2)
  138. y2 = dco.flush()
  139. self.assertEqual(data, y1 + y2)
  140. def test_compressoptions(self):
  141. # specify lots of options to compressobj()
  142. level = 2
  143. method = zlib.DEFLATED
  144. wbits = -12
  145. memlevel = 9
  146. strategy = zlib.Z_FILTERED
  147. co = zlib.compressobj(level, method, wbits, memlevel, strategy)
  148. x1 = co.compress(HAMLET_SCENE)
  149. x2 = co.flush()
  150. dco = zlib.decompressobj(wbits)
  151. y1 = dco.decompress(x1 + x2)
  152. y2 = dco.flush()
  153. self.assertEqual(HAMLET_SCENE, y1 + y2)
  154. def test_compressincremental(self):
  155. # compress object in steps, decompress object as one-shot
  156. data = HAMLET_SCENE * 128
  157. co = zlib.compressobj()
  158. bufs = []
  159. for i in range(0, len(data), 256):
  160. bufs.append(co.compress(data[i:i+256]))
  161. bufs.append(co.flush())
  162. combuf = ''.join(bufs)
  163. dco = zlib.decompressobj()
  164. y1 = dco.decompress(''.join(bufs))
  165. y2 = dco.flush()
  166. self.assertEqual(data, y1 + y2)
  167. def test_decompinc(self, flush=False, source=None, cx=256, dcx=64):
  168. # compress object in steps, decompress object in steps
  169. source = source or HAMLET_SCENE
  170. data = source * 128
  171. co = zlib.compressobj()
  172. bufs = []
  173. for i in range(0, len(data), cx):
  174. bufs.append(co.compress(data[i:i+cx]))
  175. bufs.append(co.flush())
  176. combuf = ''.join(bufs)
  177. self.assertEqual(data, zlib.decompress(combuf))
  178. dco = zlib.decompressobj()
  179. bufs = []
  180. for i in range(0, len(combuf), dcx):
  181. bufs.append(dco.decompress(combuf[i:i+dcx]))
  182. self.assertEqual('', dco.unconsumed_tail, ########
  183. "(A) uct should be '': not %d long" %
  184. len(dco.unconsumed_tail))
  185. if flush:
  186. bufs.append(dco.flush())
  187. else:
  188. while True:
  189. chunk = dco.decompress('')
  190. if chunk:
  191. bufs.append(chunk)
  192. else:
  193. break
  194. self.assertEqual('', dco.unconsumed_tail, ########
  195. "(B) uct should be '': not %d long" %
  196. len(dco.unconsumed_tail))
  197. self.assertEqual(data, ''.join(bufs))
  198. # Failure means: "decompressobj with init options failed"
  199. def test_decompincflush(self):
  200. self.test_decompinc(flush=True)
  201. def test_decompimax(self, source=None, cx=256, dcx=64):
  202. # compress in steps, decompress in length-restricted steps
  203. source = source or HAMLET_SCENE
  204. # Check a decompression object with max_length specified
  205. data = source * 128
  206. co = zlib.compressobj()
  207. bufs = []
  208. for i in range(0, len(data), cx):
  209. bufs.append(co.compress(data[i:i+cx]))
  210. bufs.append(co.flush())
  211. combuf = ''.join(bufs)
  212. self.assertEqual(data, zlib.decompress(combuf),
  213. 'compressed data failure')
  214. dco = zlib.decompressobj()
  215. bufs = []
  216. cb = combuf
  217. while cb:
  218. #max_length = 1 + len(cb)//10
  219. chunk = dco.decompress(cb, dcx)
  220. self.assertFalse(len(chunk) > dcx,
  221. 'chunk too big (%d>%d)' % (len(chunk), dcx))
  222. bufs.append(chunk)
  223. cb = dco.unconsumed_tail
  224. bufs.append(dco.flush())
  225. self.assertEqual(data, ''.join(bufs), 'Wrong data retrieved')
  226. def test_decompressmaxlen(self, flush=False):
  227. # Check a decompression object with max_length specified
  228. data = HAMLET_SCENE * 128
  229. co = zlib.compressobj()
  230. bufs = []
  231. for i in range(0, len(data), 256):
  232. bufs.append(co.compress(data[i:i+256]))
  233. bufs.append(co.flush())
  234. combuf = ''.join(bufs)
  235. self.assertEqual(data, zlib.decompress(combuf),
  236. 'compressed data failure')
  237. dco = zlib.decompressobj()
  238. bufs = []
  239. cb = combuf
  240. while cb:
  241. max_length = 1 + len(cb)//10
  242. chunk = dco.decompress(cb, max_length)
  243. self.assertFalse(len(chunk) > max_length,
  244. 'chunk too big (%d>%d)' % (len(chunk),max_length))
  245. bufs.append(chunk)
  246. cb = dco.unconsumed_tail
  247. if flush:
  248. bufs.append(dco.flush())
  249. else:
  250. while chunk:
  251. chunk = dco.decompress('', max_length)
  252. self.assertFalse(len(chunk) > max_length,
  253. 'chunk too big (%d>%d)' % (len(chunk),max_length))
  254. bufs.append(chunk)
  255. self.assertEqual(data, ''.join(bufs), 'Wrong data retrieved')
  256. def test_decompressmaxlenflush(self):
  257. self.test_decompressmaxlen(flush=True)
  258. def test_maxlenmisc(self):
  259. # Misc tests of max_length
  260. dco = zlib.decompressobj()
  261. self.assertRaises(ValueError, dco.decompress, "", -1)
  262. self.assertEqual('', dco.unconsumed_tail)
  263. def test_clear_unconsumed_tail(self):
  264. # Issue #12050: calling decompress() without providing max_length
  265. # should clear the unconsumed_tail attribute.
  266. cdata = "x\x9cKLJ\x06\x00\x02M\x01" # "abc"
  267. dco = zlib.decompressobj()
  268. ddata = dco.decompress(cdata, 1)
  269. ddata += dco.decompress(dco.unconsumed_tail)
  270. self.assertEqual(dco.unconsumed_tail, "")
  271. def test_flushes(self):
  272. # Test flush() with the various options, using all the
  273. # different levels in order to provide more variations.
  274. sync_opt = ['Z_NO_FLUSH', 'Z_SYNC_FLUSH', 'Z_FULL_FLUSH']
  275. sync_opt = [getattr(zlib, opt) for opt in sync_opt
  276. if hasattr(zlib, opt)]
  277. data = HAMLET_SCENE * 8
  278. for sync in sync_opt:
  279. for level in range(10):
  280. obj = zlib.compressobj( level )
  281. a = obj.compress( data[:3000] )
  282. b = obj.flush( sync )
  283. c = obj.compress( data[3000:] )
  284. d = obj.flush()
  285. self.assertEqual(zlib.decompress(''.join([a,b,c,d])),
  286. data, ("Decompress failed: flush "
  287. "mode=%i, level=%i") % (sync, level))
  288. del obj
  289. def test_odd_flush(self):
  290. # Test for odd flushing bugs noted in 2.0, and hopefully fixed in 2.1
  291. import random
  292. if hasattr(zlib, 'Z_SYNC_FLUSH'):
  293. # Testing on 17K of "random" data
  294. # Create compressor and decompressor objects
  295. co = zlib.compressobj(zlib.Z_BEST_COMPRESSION)
  296. dco = zlib.decompressobj()
  297. # Try 17K of data
  298. # generate random data stream
  299. try:
  300. # In 2.3 and later, WichmannHill is the RNG of the bug report
  301. gen = random.WichmannHill()
  302. except AttributeError:
  303. try:
  304. # 2.2 called it Random
  305. gen = random.Random()
  306. except AttributeError:
  307. # others might simply have a single RNG
  308. gen = random
  309. gen.seed(1)
  310. data = genblock(1, 17 * 1024, generator=gen)
  311. # compress, sync-flush, and decompress
  312. first = co.compress(data)
  313. second = co.flush(zlib.Z_SYNC_FLUSH)
  314. expanded = dco.decompress(first + second)
  315. # if decompressed data is different from the input data, choke.
  316. self.assertEqual(expanded, data, "17K random source doesn't match")
  317. def test_empty_flush(self):
  318. # Test that calling .flush() on unused objects works.
  319. # (Bug #1083110 -- calling .flush() on decompress objects
  320. # caused a core dump.)
  321. co = zlib.compressobj(zlib.Z_BEST_COMPRESSION)
  322. self.assertTrue(co.flush()) # Returns a zlib header
  323. dco = zlib.decompressobj()
  324. self.assertEqual(dco.flush(), "") # Returns nothing
  325. def test_decompress_incomplete_stream(self):
  326. # This is 'foo', deflated
  327. x = 'x\x9cK\xcb\xcf\x07\x00\x02\x82\x01E'
  328. # For the record
  329. self.assertEqual(zlib.decompress(x), 'foo')
  330. self.assertRaises(zlib.error, zlib.decompress, x[:-5])
  331. # Omitting the stream end works with decompressor objects
  332. # (see issue #8672).
  333. dco = zlib.decompressobj()
  334. y = dco.decompress(x[:-5])
  335. y += dco.flush()
  336. self.assertEqual(y, 'foo')
  337. if hasattr(zlib.compressobj(), "copy"):
  338. def test_compresscopy(self):
  339. # Test copying a compression object
  340. data0 = HAMLET_SCENE
  341. data1 = HAMLET_SCENE.swapcase()
  342. c0 = zlib.compressobj(zlib.Z_BEST_COMPRESSION)
  343. bufs0 = []
  344. bufs0.append(c0.compress(data0))
  345. c1 = c0.copy()
  346. bufs1 = bufs0[:]
  347. bufs0.append(c0.compress(data0))
  348. bufs0.append(c0.flush())
  349. s0 = ''.join(bufs0)
  350. bufs1.append(c1.compress(data1))
  351. bufs1.append(c1.flush())
  352. s1 = ''.join(bufs1)
  353. self.assertEqual(zlib.decompress(s0),data0+data0)
  354. self.assertEqual(zlib.decompress(s1),data0+data1)
  355. def test_badcompresscopy(self):
  356. # Test copying a compression object in an inconsistent state
  357. c = zlib.compressobj()
  358. c.compress(HAMLET_SCENE)
  359. c.flush()
  360. self.assertRaises(ValueError, c.copy)
  361. if hasattr(zlib.decompressobj(), "copy"):
  362. def test_decompresscopy(self):
  363. # Test copying a decompression object
  364. data = HAMLET_SCENE
  365. comp = zlib.compress(data)
  366. d0 = zlib.decompressobj()
  367. bufs0 = []
  368. bufs0.append(d0.decompress(comp[:32]))
  369. d1 = d0.copy()
  370. bufs1 = bufs0[:]
  371. bufs0.append(d0.decompress(comp[32:]))
  372. s0 = ''.join(bufs0)
  373. bufs1.append(d1.decompress(comp[32:]))
  374. s1 = ''.join(bufs1)
  375. self.assertEqual(s0,s1)
  376. self.assertEqual(s0,data)
  377. def test_baddecompresscopy(self):
  378. # Test copying a compression object in an inconsistent state
  379. data = zlib.compress(HAMLET_SCENE)
  380. d = zlib.decompressobj()
  381. d.decompress(data)
  382. d.flush()
  383. self.assertRaises(ValueError, d.copy)
  384. # Memory use of the following functions takes into account overallocation
  385. @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=3)
  386. def test_big_compress_buffer(self, size):
  387. c = zlib.compressobj(1)
  388. compress = lambda s: c.compress(s) + c.flush()
  389. self.check_big_compress_buffer(size, compress)
  390. @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=2)
  391. def test_big_decompress_buffer(self, size):
  392. d = zlib.decompressobj()
  393. decompress = lambda s: d.decompress(s) + d.flush()
  394. self.check_big_decompress_buffer(size, decompress)
  395. def genblock(seed, length, step=1024, generator=random):
  396. """length-byte stream of random data from a seed (in step-byte blocks)."""
  397. if seed is not None:
  398. generator.seed(seed)
  399. randint = generator.randint
  400. if length < step or step < 2:
  401. step = length
  402. blocks = []
  403. for i in range(0, length, step):
  404. blocks.append(''.join([chr(randint(0,255))
  405. for x in range(step)]))
  406. return ''.join(blocks)[:length]
  407. def choose_lines(source, number, seed=None, generator=random):
  408. """Return a list of number lines randomly chosen from the source"""
  409. if seed is not None:
  410. generator.seed(seed)
  411. sources = source.split('\n')
  412. return [generator.choice(sources) for n in range(number)]
  413. HAMLET_SCENE = """
  414. LAERTES
  415. O, fear me not.
  416. I stay too long: but here my father comes.
  417. Enter POLONIUS
  418. A double blessing is a double grace,
  419. Occasion smiles upon a second leave.
  420. LORD POLONIUS
  421. Yet here, Laertes! aboard, aboard, for shame!
  422. The wind sits in the shoulder of your sail,
  423. And you are stay'd for. There; my blessing with thee!
  424. And these few precepts in thy memory
  425. See thou character. Give thy thoughts no tongue,
  426. Nor any unproportioned thought his act.
  427. Be thou familiar, but by no means vulgar.
  428. Those friends thou hast, and their adoption tried,
  429. Grapple them to thy soul with hoops of steel;
  430. But do not dull thy palm with entertainment
  431. Of each new-hatch'd, unfledged comrade. Beware
  432. Of entrance to a quarrel, but being in,
  433. Bear't that the opposed may beware of thee.
  434. Give every man thy ear, but few thy voice;
  435. Take each man's censure, but reserve thy judgment.
  436. Costly thy habit as thy purse can buy,
  437. But not express'd in fancy; rich, not gaudy;
  438. For the apparel oft proclaims the man,
  439. And they in France of the best rank and station
  440. Are of a most select and generous chief in that.
  441. Neither a borrower nor a lender be;
  442. For loan oft loses both itself and friend,
  443. And borrowing dulls the edge of husbandry.
  444. This above all: to thine ownself be true,
  445. And it must follow, as the night the day,
  446. Thou canst not then be false to any man.
  447. Farewell: my blessing season this in thee!
  448. LAERTES
  449. Most humbly do I take my leave, my lord.
  450. LORD POLONIUS
  451. The time invites you; go; your servants tend.
  452. LAERTES
  453. Farewell, Ophelia; and remember well
  454. What I have said to you.
  455. OPHELIA
  456. 'Tis in my memory lock'd,
  457. And you yourself shall keep the key of it.
  458. LAERTES
  459. Farewell.
  460. """
  461. def test_main():
  462. run_unittest(
  463. ChecksumTestCase,
  464. ExceptionTestCase,
  465. CompressTestCase,
  466. CompressObjectTestCase
  467. )
  468. if __name__ == "__main__":
  469. test_main()