test_zlib.py 24 KB

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