/Lib/test/test_zlib.py

http://unladen-swallow.googlecode.com/ · Python · 480 lines · 360 code · 70 blank · 50 comment · 36 complexity · c485555df45e3a4dabed09bbad279301 MD5 · raw file

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