test_zlib.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  1. import unittest
  2. from test import support
  3. from test.support import import_helper
  4. import binascii
  5. import copy
  6. import os
  7. import pickle
  8. import random
  9. import sys
  10. from test.support import bigmemtest, _1G, _4G
  11. zlib = import_helper.import_module('zlib')
  12. requires_Compress_copy = unittest.skipUnless(
  13. hasattr(zlib.compressobj(), "copy"),
  14. 'requires Compress.copy()')
  15. requires_Decompress_copy = unittest.skipUnless(
  16. hasattr(zlib.decompressobj(), "copy"),
  17. 'requires Decompress.copy()')
  18. # bpo-46623: On s390x, when a hardware accelerator is used, using different
  19. # ways to compress data with zlib can produce different compressed data.
  20. # Simplified test_pair() code:
  21. #
  22. # def func1(data):
  23. # return zlib.compress(data)
  24. #
  25. # def func2(data)
  26. # co = zlib.compressobj()
  27. # x1 = co.compress(data)
  28. # x2 = co.flush()
  29. # return x1 + x2
  30. #
  31. # On s390x if zlib uses a hardware accelerator, func1() creates a single
  32. # "final" compressed block whereas func2() produces 3 compressed blocks (the
  33. # last one is a final block). On other platforms with no accelerator, func1()
  34. # and func2() produce the same compressed data made of a single (final)
  35. # compressed block.
  36. #
  37. # Only the compressed data is different, the decompression returns the original
  38. # data:
  39. #
  40. # zlib.decompress(func1(data)) == zlib.decompress(func2(data)) == data
  41. #
  42. # Make the assumption that s390x always has an accelerator to simplify the skip
  43. # condition. Windows doesn't have os.uname() but it doesn't support s390x.
  44. skip_on_s390x = unittest.skipIf(hasattr(os, 'uname') and os.uname().machine == 's390x',
  45. 'skipped on s390x')
  46. class VersionTestCase(unittest.TestCase):
  47. def test_library_version(self):
  48. # Test that the major version of the actual library in use matches the
  49. # major version that we were compiled against. We can't guarantee that
  50. # the minor versions will match (even on the machine on which the module
  51. # was compiled), and the API is stable between minor versions, so
  52. # testing only the major versions avoids spurious failures.
  53. self.assertEqual(zlib.ZLIB_RUNTIME_VERSION[0], zlib.ZLIB_VERSION[0])
  54. class ChecksumTestCase(unittest.TestCase):
  55. # checksum test cases
  56. def test_crc32start(self):
  57. self.assertEqual(zlib.crc32(b""), zlib.crc32(b"", 0))
  58. self.assertTrue(zlib.crc32(b"abc", 0xffffffff))
  59. def test_crc32empty(self):
  60. self.assertEqual(zlib.crc32(b"", 0), 0)
  61. self.assertEqual(zlib.crc32(b"", 1), 1)
  62. self.assertEqual(zlib.crc32(b"", 432), 432)
  63. def test_adler32start(self):
  64. self.assertEqual(zlib.adler32(b""), zlib.adler32(b"", 1))
  65. self.assertTrue(zlib.adler32(b"abc", 0xffffffff))
  66. def test_adler32empty(self):
  67. self.assertEqual(zlib.adler32(b"", 0), 0)
  68. self.assertEqual(zlib.adler32(b"", 1), 1)
  69. self.assertEqual(zlib.adler32(b"", 432), 432)
  70. def test_penguins(self):
  71. self.assertEqual(zlib.crc32(b"penguin", 0), 0x0e5c1a120)
  72. self.assertEqual(zlib.crc32(b"penguin", 1), 0x43b6aa94)
  73. self.assertEqual(zlib.adler32(b"penguin", 0), 0x0bcf02f6)
  74. self.assertEqual(zlib.adler32(b"penguin", 1), 0x0bd602f7)
  75. self.assertEqual(zlib.crc32(b"penguin"), zlib.crc32(b"penguin", 0))
  76. self.assertEqual(zlib.adler32(b"penguin"),zlib.adler32(b"penguin",1))
  77. def test_crc32_adler32_unsigned(self):
  78. foo = b'abcdefghijklmnop'
  79. # explicitly test signed behavior
  80. self.assertEqual(zlib.crc32(foo), 2486878355)
  81. self.assertEqual(zlib.crc32(b'spam'), 1138425661)
  82. self.assertEqual(zlib.adler32(foo+foo), 3573550353)
  83. self.assertEqual(zlib.adler32(b'spam'), 72286642)
  84. def test_same_as_binascii_crc32(self):
  85. foo = b'abcdefghijklmnop'
  86. crc = 2486878355
  87. self.assertEqual(binascii.crc32(foo), crc)
  88. self.assertEqual(zlib.crc32(foo), crc)
  89. self.assertEqual(binascii.crc32(b'spam'), zlib.crc32(b'spam'))
  90. # Issue #10276 - check that inputs >=4 GiB are handled correctly.
  91. class ChecksumBigBufferTestCase(unittest.TestCase):
  92. @bigmemtest(size=_4G + 4, memuse=1, dry_run=False)
  93. def test_big_buffer(self, size):
  94. data = b"nyan" * (_1G + 1)
  95. self.assertEqual(zlib.crc32(data), 1044521549)
  96. self.assertEqual(zlib.adler32(data), 2256789997)
  97. class ExceptionTestCase(unittest.TestCase):
  98. # make sure we generate some expected errors
  99. def test_badlevel(self):
  100. # specifying compression level out of range causes an error
  101. # (but -1 is Z_DEFAULT_COMPRESSION and apparently the zlib
  102. # accepts 0 too)
  103. self.assertRaises(zlib.error, zlib.compress, b'ERROR', 10)
  104. def test_badargs(self):
  105. self.assertRaises(TypeError, zlib.adler32)
  106. self.assertRaises(TypeError, zlib.crc32)
  107. self.assertRaises(TypeError, zlib.compress)
  108. self.assertRaises(TypeError, zlib.decompress)
  109. for arg in (42, None, '', 'abc', (), []):
  110. self.assertRaises(TypeError, zlib.adler32, arg)
  111. self.assertRaises(TypeError, zlib.crc32, arg)
  112. self.assertRaises(TypeError, zlib.compress, arg)
  113. self.assertRaises(TypeError, zlib.decompress, arg)
  114. def test_badcompressobj(self):
  115. # verify failure on building compress object with bad params
  116. self.assertRaises(ValueError, zlib.compressobj, 1, zlib.DEFLATED, 0)
  117. # specifying total bits too large causes an error
  118. self.assertRaises(ValueError,
  119. zlib.compressobj, 1, zlib.DEFLATED, zlib.MAX_WBITS + 1)
  120. def test_baddecompressobj(self):
  121. # verify failure on building decompress object with bad params
  122. self.assertRaises(ValueError, zlib.decompressobj, -1)
  123. def test_decompressobj_badflush(self):
  124. # verify failure on calling decompressobj.flush with bad params
  125. self.assertRaises(ValueError, zlib.decompressobj().flush, 0)
  126. self.assertRaises(ValueError, zlib.decompressobj().flush, -1)
  127. @support.cpython_only
  128. def test_overflow(self):
  129. with self.assertRaisesRegex(OverflowError, 'int too large'):
  130. zlib.decompress(b'', 15, sys.maxsize + 1)
  131. with self.assertRaisesRegex(OverflowError, 'int too large'):
  132. zlib.decompressobj().decompress(b'', sys.maxsize + 1)
  133. with self.assertRaisesRegex(OverflowError, 'int too large'):
  134. zlib.decompressobj().flush(sys.maxsize + 1)
  135. @support.cpython_only
  136. def test_disallow_instantiation(self):
  137. # Ensure that the type disallows instantiation (bpo-43916)
  138. support.check_disallow_instantiation(self, type(zlib.compressobj()))
  139. support.check_disallow_instantiation(self, type(zlib.decompressobj()))
  140. class BaseCompressTestCase(object):
  141. def check_big_compress_buffer(self, size, compress_func):
  142. _1M = 1024 * 1024
  143. # Generate 10 MiB worth of random, and expand it by repeating it.
  144. # The assumption is that zlib's memory is not big enough to exploit
  145. # such spread out redundancy.
  146. data = random.randbytes(_1M * 10)
  147. data = data * (size // len(data) + 1)
  148. try:
  149. compress_func(data)
  150. finally:
  151. # Release memory
  152. data = None
  153. def check_big_decompress_buffer(self, size, decompress_func):
  154. data = b'x' * size
  155. try:
  156. compressed = zlib.compress(data, 1)
  157. finally:
  158. # Release memory
  159. data = None
  160. data = decompress_func(compressed)
  161. # Sanity check
  162. try:
  163. self.assertEqual(len(data), size)
  164. self.assertEqual(len(data.strip(b'x')), 0)
  165. finally:
  166. data = None
  167. class CompressTestCase(BaseCompressTestCase, unittest.TestCase):
  168. # Test compression in one go (whole message compression)
  169. def test_speech(self):
  170. x = zlib.compress(HAMLET_SCENE)
  171. self.assertEqual(zlib.decompress(x), HAMLET_SCENE)
  172. def test_keywords(self):
  173. x = zlib.compress(HAMLET_SCENE, level=3)
  174. self.assertEqual(zlib.decompress(x), HAMLET_SCENE)
  175. with self.assertRaises(TypeError):
  176. zlib.compress(data=HAMLET_SCENE, level=3)
  177. self.assertEqual(zlib.decompress(x,
  178. wbits=zlib.MAX_WBITS,
  179. bufsize=zlib.DEF_BUF_SIZE),
  180. HAMLET_SCENE)
  181. @skip_on_s390x
  182. def test_speech128(self):
  183. # compress more data
  184. data = HAMLET_SCENE * 128
  185. x = zlib.compress(data)
  186. self.assertEqual(zlib.compress(bytearray(data)), x)
  187. for ob in x, bytearray(x):
  188. self.assertEqual(zlib.decompress(ob), data)
  189. def test_incomplete_stream(self):
  190. # A useful error message is given
  191. x = zlib.compress(HAMLET_SCENE)
  192. self.assertRaisesRegex(zlib.error,
  193. "Error -5 while decompressing data: incomplete or truncated stream",
  194. zlib.decompress, x[:-1])
  195. # Memory use of the following functions takes into account overallocation
  196. @bigmemtest(size=_1G + 1024 * 1024, memuse=3)
  197. def test_big_compress_buffer(self, size):
  198. compress = lambda s: zlib.compress(s, 1)
  199. self.check_big_compress_buffer(size, compress)
  200. @bigmemtest(size=_1G + 1024 * 1024, memuse=2)
  201. def test_big_decompress_buffer(self, size):
  202. self.check_big_decompress_buffer(size, zlib.decompress)
  203. @bigmemtest(size=_4G, memuse=1)
  204. def test_large_bufsize(self, size):
  205. # Test decompress(bufsize) parameter greater than the internal limit
  206. data = HAMLET_SCENE * 10
  207. compressed = zlib.compress(data, 1)
  208. self.assertEqual(zlib.decompress(compressed, 15, size), data)
  209. def test_custom_bufsize(self):
  210. data = HAMLET_SCENE * 10
  211. compressed = zlib.compress(data, 1)
  212. self.assertEqual(zlib.decompress(compressed, 15, CustomInt()), data)
  213. @unittest.skipUnless(sys.maxsize > 2**32, 'requires 64bit platform')
  214. @bigmemtest(size=_4G + 100, memuse=4)
  215. def test_64bit_compress(self, size):
  216. data = b'x' * size
  217. try:
  218. comp = zlib.compress(data, 0)
  219. self.assertEqual(zlib.decompress(comp), data)
  220. finally:
  221. comp = data = None
  222. class CompressObjectTestCase(BaseCompressTestCase, unittest.TestCase):
  223. # Test compression object
  224. @skip_on_s390x
  225. def test_pair(self):
  226. # straightforward compress/decompress objects
  227. datasrc = HAMLET_SCENE * 128
  228. datazip = zlib.compress(datasrc)
  229. # should compress both bytes and bytearray data
  230. for data in (datasrc, bytearray(datasrc)):
  231. co = zlib.compressobj()
  232. x1 = co.compress(data)
  233. x2 = co.flush()
  234. self.assertRaises(zlib.error, co.flush) # second flush should not work
  235. self.assertEqual(x1 + x2, datazip)
  236. for v1, v2 in ((x1, x2), (bytearray(x1), bytearray(x2))):
  237. dco = zlib.decompressobj()
  238. y1 = dco.decompress(v1 + v2)
  239. y2 = dco.flush()
  240. self.assertEqual(data, y1 + y2)
  241. self.assertIsInstance(dco.unconsumed_tail, bytes)
  242. self.assertIsInstance(dco.unused_data, bytes)
  243. def test_keywords(self):
  244. level = 2
  245. method = zlib.DEFLATED
  246. wbits = -12
  247. memLevel = 9
  248. strategy = zlib.Z_FILTERED
  249. co = zlib.compressobj(level=level,
  250. method=method,
  251. wbits=wbits,
  252. memLevel=memLevel,
  253. strategy=strategy,
  254. zdict=b"")
  255. do = zlib.decompressobj(wbits=wbits, zdict=b"")
  256. with self.assertRaises(TypeError):
  257. co.compress(data=HAMLET_SCENE)
  258. with self.assertRaises(TypeError):
  259. do.decompress(data=zlib.compress(HAMLET_SCENE))
  260. x = co.compress(HAMLET_SCENE) + co.flush()
  261. y = do.decompress(x, max_length=len(HAMLET_SCENE)) + do.flush()
  262. self.assertEqual(HAMLET_SCENE, y)
  263. def test_compressoptions(self):
  264. # specify lots of options to compressobj()
  265. level = 2
  266. method = zlib.DEFLATED
  267. wbits = -12
  268. memLevel = 9
  269. strategy = zlib.Z_FILTERED
  270. co = zlib.compressobj(level, method, wbits, memLevel, strategy)
  271. x1 = co.compress(HAMLET_SCENE)
  272. x2 = co.flush()
  273. dco = zlib.decompressobj(wbits)
  274. y1 = dco.decompress(x1 + x2)
  275. y2 = dco.flush()
  276. self.assertEqual(HAMLET_SCENE, y1 + y2)
  277. def test_compressincremental(self):
  278. # compress object in steps, decompress object as one-shot
  279. data = HAMLET_SCENE * 128
  280. co = zlib.compressobj()
  281. bufs = []
  282. for i in range(0, len(data), 256):
  283. bufs.append(co.compress(data[i:i+256]))
  284. bufs.append(co.flush())
  285. combuf = b''.join(bufs)
  286. dco = zlib.decompressobj()
  287. y1 = dco.decompress(b''.join(bufs))
  288. y2 = dco.flush()
  289. self.assertEqual(data, y1 + y2)
  290. def test_decompinc(self, flush=False, source=None, cx=256, dcx=64):
  291. # compress object in steps, decompress object in steps
  292. source = source or HAMLET_SCENE
  293. data = source * 128
  294. co = zlib.compressobj()
  295. bufs = []
  296. for i in range(0, len(data), cx):
  297. bufs.append(co.compress(data[i:i+cx]))
  298. bufs.append(co.flush())
  299. combuf = b''.join(bufs)
  300. decombuf = zlib.decompress(combuf)
  301. # Test type of return value
  302. self.assertIsInstance(decombuf, bytes)
  303. self.assertEqual(data, decombuf)
  304. dco = zlib.decompressobj()
  305. bufs = []
  306. for i in range(0, len(combuf), dcx):
  307. bufs.append(dco.decompress(combuf[i:i+dcx]))
  308. self.assertEqual(b'', dco.unconsumed_tail, ########
  309. "(A) uct should be b'': not %d long" %
  310. len(dco.unconsumed_tail))
  311. self.assertEqual(b'', dco.unused_data)
  312. if flush:
  313. bufs.append(dco.flush())
  314. else:
  315. while True:
  316. chunk = dco.decompress(b'')
  317. if chunk:
  318. bufs.append(chunk)
  319. else:
  320. break
  321. self.assertEqual(b'', dco.unconsumed_tail, ########
  322. "(B) uct should be b'': not %d long" %
  323. len(dco.unconsumed_tail))
  324. self.assertEqual(b'', dco.unused_data)
  325. self.assertEqual(data, b''.join(bufs))
  326. # Failure means: "decompressobj with init options failed"
  327. def test_decompincflush(self):
  328. self.test_decompinc(flush=True)
  329. def test_decompimax(self, source=None, cx=256, dcx=64):
  330. # compress in steps, decompress in length-restricted steps
  331. source = source or HAMLET_SCENE
  332. # Check a decompression object with max_length specified
  333. data = source * 128
  334. co = zlib.compressobj()
  335. bufs = []
  336. for i in range(0, len(data), cx):
  337. bufs.append(co.compress(data[i:i+cx]))
  338. bufs.append(co.flush())
  339. combuf = b''.join(bufs)
  340. self.assertEqual(data, zlib.decompress(combuf),
  341. 'compressed data failure')
  342. dco = zlib.decompressobj()
  343. bufs = []
  344. cb = combuf
  345. while cb:
  346. #max_length = 1 + len(cb)//10
  347. chunk = dco.decompress(cb, dcx)
  348. self.assertFalse(len(chunk) > dcx,
  349. 'chunk too big (%d>%d)' % (len(chunk), dcx))
  350. bufs.append(chunk)
  351. cb = dco.unconsumed_tail
  352. bufs.append(dco.flush())
  353. self.assertEqual(data, b''.join(bufs), 'Wrong data retrieved')
  354. def test_decompressmaxlen(self, flush=False):
  355. # Check a decompression object with max_length specified
  356. data = HAMLET_SCENE * 128
  357. co = zlib.compressobj()
  358. bufs = []
  359. for i in range(0, len(data), 256):
  360. bufs.append(co.compress(data[i:i+256]))
  361. bufs.append(co.flush())
  362. combuf = b''.join(bufs)
  363. self.assertEqual(data, zlib.decompress(combuf),
  364. 'compressed data failure')
  365. dco = zlib.decompressobj()
  366. bufs = []
  367. cb = combuf
  368. while cb:
  369. max_length = 1 + len(cb)//10
  370. chunk = dco.decompress(cb, max_length)
  371. self.assertFalse(len(chunk) > max_length,
  372. 'chunk too big (%d>%d)' % (len(chunk),max_length))
  373. bufs.append(chunk)
  374. cb = dco.unconsumed_tail
  375. if flush:
  376. bufs.append(dco.flush())
  377. else:
  378. while chunk:
  379. chunk = dco.decompress(b'', max_length)
  380. self.assertFalse(len(chunk) > max_length,
  381. 'chunk too big (%d>%d)' % (len(chunk),max_length))
  382. bufs.append(chunk)
  383. self.assertEqual(data, b''.join(bufs), 'Wrong data retrieved')
  384. def test_decompressmaxlenflush(self):
  385. self.test_decompressmaxlen(flush=True)
  386. def test_maxlenmisc(self):
  387. # Misc tests of max_length
  388. dco = zlib.decompressobj()
  389. self.assertRaises(ValueError, dco.decompress, b"", -1)
  390. self.assertEqual(b'', dco.unconsumed_tail)
  391. def test_maxlen_large(self):
  392. # Sizes up to sys.maxsize should be accepted, although zlib is
  393. # internally limited to expressing sizes with unsigned int
  394. data = HAMLET_SCENE * 10
  395. self.assertGreater(len(data), zlib.DEF_BUF_SIZE)
  396. compressed = zlib.compress(data, 1)
  397. dco = zlib.decompressobj()
  398. self.assertEqual(dco.decompress(compressed, sys.maxsize), data)
  399. def test_maxlen_custom(self):
  400. data = HAMLET_SCENE * 10
  401. compressed = zlib.compress(data, 1)
  402. dco = zlib.decompressobj()
  403. self.assertEqual(dco.decompress(compressed, CustomInt()), data[:100])
  404. def test_clear_unconsumed_tail(self):
  405. # Issue #12050: calling decompress() without providing max_length
  406. # should clear the unconsumed_tail attribute.
  407. cdata = b"x\x9cKLJ\x06\x00\x02M\x01" # "abc"
  408. dco = zlib.decompressobj()
  409. ddata = dco.decompress(cdata, 1)
  410. ddata += dco.decompress(dco.unconsumed_tail)
  411. self.assertEqual(dco.unconsumed_tail, b"")
  412. def test_flushes(self):
  413. # Test flush() with the various options, using all the
  414. # different levels in order to provide more variations.
  415. sync_opt = ['Z_NO_FLUSH', 'Z_SYNC_FLUSH', 'Z_FULL_FLUSH',
  416. 'Z_PARTIAL_FLUSH']
  417. ver = tuple(int(v) for v in zlib.ZLIB_RUNTIME_VERSION.split('.'))
  418. # Z_BLOCK has a known failure prior to 1.2.5.3
  419. if ver >= (1, 2, 5, 3):
  420. sync_opt.append('Z_BLOCK')
  421. sync_opt = [getattr(zlib, opt) for opt in sync_opt
  422. if hasattr(zlib, opt)]
  423. data = HAMLET_SCENE * 8
  424. for sync in sync_opt:
  425. for level in range(10):
  426. try:
  427. obj = zlib.compressobj( level )
  428. a = obj.compress( data[:3000] )
  429. b = obj.flush( sync )
  430. c = obj.compress( data[3000:] )
  431. d = obj.flush()
  432. except:
  433. print("Error for flush mode={}, level={}"
  434. .format(sync, level))
  435. raise
  436. self.assertEqual(zlib.decompress(b''.join([a,b,c,d])),
  437. data, ("Decompress failed: flush "
  438. "mode=%i, level=%i") % (sync, level))
  439. del obj
  440. @unittest.skipUnless(hasattr(zlib, 'Z_SYNC_FLUSH'),
  441. 'requires zlib.Z_SYNC_FLUSH')
  442. def test_odd_flush(self):
  443. # Test for odd flushing bugs noted in 2.0, and hopefully fixed in 2.1
  444. import random
  445. # Testing on 17K of "random" data
  446. # Create compressor and decompressor objects
  447. co = zlib.compressobj(zlib.Z_BEST_COMPRESSION)
  448. dco = zlib.decompressobj()
  449. # Try 17K of data
  450. # generate random data stream
  451. try:
  452. # In 2.3 and later, WichmannHill is the RNG of the bug report
  453. gen = random.WichmannHill()
  454. except AttributeError:
  455. try:
  456. # 2.2 called it Random
  457. gen = random.Random()
  458. except AttributeError:
  459. # others might simply have a single RNG
  460. gen = random
  461. gen.seed(1)
  462. data = gen.randbytes(17 * 1024)
  463. # compress, sync-flush, and decompress
  464. first = co.compress(data)
  465. second = co.flush(zlib.Z_SYNC_FLUSH)
  466. expanded = dco.decompress(first + second)
  467. # if decompressed data is different from the input data, choke.
  468. self.assertEqual(expanded, data, "17K random source doesn't match")
  469. def test_empty_flush(self):
  470. # Test that calling .flush() on unused objects works.
  471. # (Bug #1083110 -- calling .flush() on decompress objects
  472. # caused a core dump.)
  473. co = zlib.compressobj(zlib.Z_BEST_COMPRESSION)
  474. self.assertTrue(co.flush()) # Returns a zlib header
  475. dco = zlib.decompressobj()
  476. self.assertEqual(dco.flush(), b"") # Returns nothing
  477. def test_dictionary(self):
  478. h = HAMLET_SCENE
  479. # Build a simulated dictionary out of the words in HAMLET.
  480. words = h.split()
  481. random.shuffle(words)
  482. zdict = b''.join(words)
  483. # Use it to compress HAMLET.
  484. co = zlib.compressobj(zdict=zdict)
  485. cd = co.compress(h) + co.flush()
  486. # Verify that it will decompress with the dictionary.
  487. dco = zlib.decompressobj(zdict=zdict)
  488. self.assertEqual(dco.decompress(cd) + dco.flush(), h)
  489. # Verify that it fails when not given the dictionary.
  490. dco = zlib.decompressobj()
  491. self.assertRaises(zlib.error, dco.decompress, cd)
  492. def test_dictionary_streaming(self):
  493. # This simulates the reuse of a compressor object for compressing
  494. # several separate data streams.
  495. co = zlib.compressobj(zdict=HAMLET_SCENE)
  496. do = zlib.decompressobj(zdict=HAMLET_SCENE)
  497. piece = HAMLET_SCENE[1000:1500]
  498. d0 = co.compress(piece) + co.flush(zlib.Z_SYNC_FLUSH)
  499. d1 = co.compress(piece[100:]) + co.flush(zlib.Z_SYNC_FLUSH)
  500. d2 = co.compress(piece[:-100]) + co.flush(zlib.Z_SYNC_FLUSH)
  501. self.assertEqual(do.decompress(d0), piece)
  502. self.assertEqual(do.decompress(d1), piece[100:])
  503. self.assertEqual(do.decompress(d2), piece[:-100])
  504. def test_decompress_incomplete_stream(self):
  505. # This is 'foo', deflated
  506. x = b'x\x9cK\xcb\xcf\x07\x00\x02\x82\x01E'
  507. # For the record
  508. self.assertEqual(zlib.decompress(x), b'foo')
  509. self.assertRaises(zlib.error, zlib.decompress, x[:-5])
  510. # Omitting the stream end works with decompressor objects
  511. # (see issue #8672).
  512. dco = zlib.decompressobj()
  513. y = dco.decompress(x[:-5])
  514. y += dco.flush()
  515. self.assertEqual(y, b'foo')
  516. def test_decompress_eof(self):
  517. x = b'x\x9cK\xcb\xcf\x07\x00\x02\x82\x01E' # 'foo'
  518. dco = zlib.decompressobj()
  519. self.assertFalse(dco.eof)
  520. dco.decompress(x[:-5])
  521. self.assertFalse(dco.eof)
  522. dco.decompress(x[-5:])
  523. self.assertTrue(dco.eof)
  524. dco.flush()
  525. self.assertTrue(dco.eof)
  526. def test_decompress_eof_incomplete_stream(self):
  527. x = b'x\x9cK\xcb\xcf\x07\x00\x02\x82\x01E' # 'foo'
  528. dco = zlib.decompressobj()
  529. self.assertFalse(dco.eof)
  530. dco.decompress(x[:-5])
  531. self.assertFalse(dco.eof)
  532. dco.flush()
  533. self.assertFalse(dco.eof)
  534. def test_decompress_unused_data(self):
  535. # Repeated calls to decompress() after EOF should accumulate data in
  536. # dco.unused_data, instead of just storing the arg to the last call.
  537. source = b'abcdefghijklmnopqrstuvwxyz'
  538. remainder = b'0123456789'
  539. y = zlib.compress(source)
  540. x = y + remainder
  541. for maxlen in 0, 1000:
  542. for step in 1, 2, len(y), len(x):
  543. dco = zlib.decompressobj()
  544. data = b''
  545. for i in range(0, len(x), step):
  546. if i < len(y):
  547. self.assertEqual(dco.unused_data, b'')
  548. if maxlen == 0:
  549. data += dco.decompress(x[i : i + step])
  550. self.assertEqual(dco.unconsumed_tail, b'')
  551. else:
  552. data += dco.decompress(
  553. dco.unconsumed_tail + x[i : i + step], maxlen)
  554. data += dco.flush()
  555. self.assertTrue(dco.eof)
  556. self.assertEqual(data, source)
  557. self.assertEqual(dco.unconsumed_tail, b'')
  558. self.assertEqual(dco.unused_data, remainder)
  559. # issue27164
  560. def test_decompress_raw_with_dictionary(self):
  561. zdict = b'abcdefghijklmnopqrstuvwxyz'
  562. co = zlib.compressobj(wbits=-zlib.MAX_WBITS, zdict=zdict)
  563. comp = co.compress(zdict) + co.flush()
  564. dco = zlib.decompressobj(wbits=-zlib.MAX_WBITS, zdict=zdict)
  565. uncomp = dco.decompress(comp) + dco.flush()
  566. self.assertEqual(zdict, uncomp)
  567. def test_flush_with_freed_input(self):
  568. # Issue #16411: decompressor accesses input to last decompress() call
  569. # in flush(), even if this object has been freed in the meanwhile.
  570. input1 = b'abcdefghijklmnopqrstuvwxyz'
  571. input2 = b'QWERTYUIOPASDFGHJKLZXCVBNM'
  572. data = zlib.compress(input1)
  573. dco = zlib.decompressobj()
  574. dco.decompress(data, 1)
  575. del data
  576. data = zlib.compress(input2)
  577. self.assertEqual(dco.flush(), input1[1:])
  578. @bigmemtest(size=_4G, memuse=1)
  579. def test_flush_large_length(self, size):
  580. # Test flush(length) parameter greater than internal limit UINT_MAX
  581. input = HAMLET_SCENE * 10
  582. data = zlib.compress(input, 1)
  583. dco = zlib.decompressobj()
  584. dco.decompress(data, 1)
  585. self.assertEqual(dco.flush(size), input[1:])
  586. def test_flush_custom_length(self):
  587. input = HAMLET_SCENE * 10
  588. data = zlib.compress(input, 1)
  589. dco = zlib.decompressobj()
  590. dco.decompress(data, 1)
  591. self.assertEqual(dco.flush(CustomInt()), input[1:])
  592. @requires_Compress_copy
  593. def test_compresscopy(self):
  594. # Test copying a compression object
  595. data0 = HAMLET_SCENE
  596. data1 = bytes(str(HAMLET_SCENE, "ascii").swapcase(), "ascii")
  597. for func in lambda c: c.copy(), copy.copy, copy.deepcopy:
  598. c0 = zlib.compressobj(zlib.Z_BEST_COMPRESSION)
  599. bufs0 = []
  600. bufs0.append(c0.compress(data0))
  601. c1 = func(c0)
  602. bufs1 = bufs0[:]
  603. bufs0.append(c0.compress(data0))
  604. bufs0.append(c0.flush())
  605. s0 = b''.join(bufs0)
  606. bufs1.append(c1.compress(data1))
  607. bufs1.append(c1.flush())
  608. s1 = b''.join(bufs1)
  609. self.assertEqual(zlib.decompress(s0),data0+data0)
  610. self.assertEqual(zlib.decompress(s1),data0+data1)
  611. @requires_Compress_copy
  612. def test_badcompresscopy(self):
  613. # Test copying a compression object in an inconsistent state
  614. c = zlib.compressobj()
  615. c.compress(HAMLET_SCENE)
  616. c.flush()
  617. self.assertRaises(ValueError, c.copy)
  618. self.assertRaises(ValueError, copy.copy, c)
  619. self.assertRaises(ValueError, copy.deepcopy, c)
  620. @requires_Decompress_copy
  621. def test_decompresscopy(self):
  622. # Test copying a decompression object
  623. data = HAMLET_SCENE
  624. comp = zlib.compress(data)
  625. # Test type of return value
  626. self.assertIsInstance(comp, bytes)
  627. for func in lambda c: c.copy(), copy.copy, copy.deepcopy:
  628. d0 = zlib.decompressobj()
  629. bufs0 = []
  630. bufs0.append(d0.decompress(comp[:32]))
  631. d1 = func(d0)
  632. bufs1 = bufs0[:]
  633. bufs0.append(d0.decompress(comp[32:]))
  634. s0 = b''.join(bufs0)
  635. bufs1.append(d1.decompress(comp[32:]))
  636. s1 = b''.join(bufs1)
  637. self.assertEqual(s0,s1)
  638. self.assertEqual(s0,data)
  639. @requires_Decompress_copy
  640. def test_baddecompresscopy(self):
  641. # Test copying a compression object in an inconsistent state
  642. data = zlib.compress(HAMLET_SCENE)
  643. d = zlib.decompressobj()
  644. d.decompress(data)
  645. d.flush()
  646. self.assertRaises(ValueError, d.copy)
  647. self.assertRaises(ValueError, copy.copy, d)
  648. self.assertRaises(ValueError, copy.deepcopy, d)
  649. def test_compresspickle(self):
  650. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  651. with self.assertRaises((TypeError, pickle.PicklingError)):
  652. pickle.dumps(zlib.compressobj(zlib.Z_BEST_COMPRESSION), proto)
  653. def test_decompresspickle(self):
  654. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  655. with self.assertRaises((TypeError, pickle.PicklingError)):
  656. pickle.dumps(zlib.decompressobj(), proto)
  657. # Memory use of the following functions takes into account overallocation
  658. @bigmemtest(size=_1G + 1024 * 1024, memuse=3)
  659. def test_big_compress_buffer(self, size):
  660. c = zlib.compressobj(1)
  661. compress = lambda s: c.compress(s) + c.flush()
  662. self.check_big_compress_buffer(size, compress)
  663. @bigmemtest(size=_1G + 1024 * 1024, memuse=2)
  664. def test_big_decompress_buffer(self, size):
  665. d = zlib.decompressobj()
  666. decompress = lambda s: d.decompress(s) + d.flush()
  667. self.check_big_decompress_buffer(size, decompress)
  668. @unittest.skipUnless(sys.maxsize > 2**32, 'requires 64bit platform')
  669. @bigmemtest(size=_4G + 100, memuse=4)
  670. def test_64bit_compress(self, size):
  671. data = b'x' * size
  672. co = zlib.compressobj(0)
  673. do = zlib.decompressobj()
  674. try:
  675. comp = co.compress(data) + co.flush()
  676. uncomp = do.decompress(comp) + do.flush()
  677. self.assertEqual(uncomp, data)
  678. finally:
  679. comp = uncomp = data = None
  680. @unittest.skipUnless(sys.maxsize > 2**32, 'requires 64bit platform')
  681. @bigmemtest(size=_4G + 100, memuse=3)
  682. def test_large_unused_data(self, size):
  683. data = b'abcdefghijklmnop'
  684. unused = b'x' * size
  685. comp = zlib.compress(data) + unused
  686. do = zlib.decompressobj()
  687. try:
  688. uncomp = do.decompress(comp) + do.flush()
  689. self.assertEqual(unused, do.unused_data)
  690. self.assertEqual(uncomp, data)
  691. finally:
  692. unused = comp = do = None
  693. @unittest.skipUnless(sys.maxsize > 2**32, 'requires 64bit platform')
  694. @bigmemtest(size=_4G + 100, memuse=5)
  695. def test_large_unconsumed_tail(self, size):
  696. data = b'x' * size
  697. do = zlib.decompressobj()
  698. try:
  699. comp = zlib.compress(data, 0)
  700. uncomp = do.decompress(comp, 1) + do.flush()
  701. self.assertEqual(uncomp, data)
  702. self.assertEqual(do.unconsumed_tail, b'')
  703. finally:
  704. comp = uncomp = data = None
  705. def test_wbits(self):
  706. # wbits=0 only supported since zlib v1.2.3.5
  707. # Register "1.2.3" as "1.2.3.0"
  708. # or "1.2.0-linux","1.2.0.f","1.2.0.f-linux"
  709. v = zlib.ZLIB_RUNTIME_VERSION.split('-', 1)[0].split('.')
  710. if len(v) < 4:
  711. v.append('0')
  712. elif not v[-1].isnumeric():
  713. v[-1] = '0'
  714. v = tuple(map(int, v))
  715. supports_wbits_0 = v >= (1, 2, 3, 5)
  716. co = zlib.compressobj(level=1, wbits=15)
  717. zlib15 = co.compress(HAMLET_SCENE) + co.flush()
  718. self.assertEqual(zlib.decompress(zlib15, 15), HAMLET_SCENE)
  719. if supports_wbits_0:
  720. self.assertEqual(zlib.decompress(zlib15, 0), HAMLET_SCENE)
  721. self.assertEqual(zlib.decompress(zlib15, 32 + 15), HAMLET_SCENE)
  722. with self.assertRaisesRegex(zlib.error, 'invalid window size'):
  723. zlib.decompress(zlib15, 14)
  724. dco = zlib.decompressobj(wbits=32 + 15)
  725. self.assertEqual(dco.decompress(zlib15), HAMLET_SCENE)
  726. dco = zlib.decompressobj(wbits=14)
  727. with self.assertRaisesRegex(zlib.error, 'invalid window size'):
  728. dco.decompress(zlib15)
  729. co = zlib.compressobj(level=1, wbits=9)
  730. zlib9 = co.compress(HAMLET_SCENE) + co.flush()
  731. self.assertEqual(zlib.decompress(zlib9, 9), HAMLET_SCENE)
  732. self.assertEqual(zlib.decompress(zlib9, 15), HAMLET_SCENE)
  733. if supports_wbits_0:
  734. self.assertEqual(zlib.decompress(zlib9, 0), HAMLET_SCENE)
  735. self.assertEqual(zlib.decompress(zlib9, 32 + 9), HAMLET_SCENE)
  736. dco = zlib.decompressobj(wbits=32 + 9)
  737. self.assertEqual(dco.decompress(zlib9), HAMLET_SCENE)
  738. co = zlib.compressobj(level=1, wbits=-15)
  739. deflate15 = co.compress(HAMLET_SCENE) + co.flush()
  740. self.assertEqual(zlib.decompress(deflate15, -15), HAMLET_SCENE)
  741. dco = zlib.decompressobj(wbits=-15)
  742. self.assertEqual(dco.decompress(deflate15), HAMLET_SCENE)
  743. co = zlib.compressobj(level=1, wbits=-9)
  744. deflate9 = co.compress(HAMLET_SCENE) + co.flush()
  745. self.assertEqual(zlib.decompress(deflate9, -9), HAMLET_SCENE)
  746. self.assertEqual(zlib.decompress(deflate9, -15), HAMLET_SCENE)
  747. dco = zlib.decompressobj(wbits=-9)
  748. self.assertEqual(dco.decompress(deflate9), HAMLET_SCENE)
  749. co = zlib.compressobj(level=1, wbits=16 + 15)
  750. gzip = co.compress(HAMLET_SCENE) + co.flush()
  751. self.assertEqual(zlib.decompress(gzip, 16 + 15), HAMLET_SCENE)
  752. self.assertEqual(zlib.decompress(gzip, 32 + 15), HAMLET_SCENE)
  753. dco = zlib.decompressobj(32 + 15)
  754. self.assertEqual(dco.decompress(gzip), HAMLET_SCENE)
  755. for wbits in (-15, 15, 31):
  756. with self.subTest(wbits=wbits):
  757. expected = HAMLET_SCENE
  758. actual = zlib.decompress(
  759. zlib.compress(HAMLET_SCENE, wbits=wbits), wbits=wbits
  760. )
  761. self.assertEqual(expected, actual)
  762. def choose_lines(source, number, seed=None, generator=random):
  763. """Return a list of number lines randomly chosen from the source"""
  764. if seed is not None:
  765. generator.seed(seed)
  766. sources = source.split('\n')
  767. return [generator.choice(sources) for n in range(number)]
  768. HAMLET_SCENE = b"""
  769. LAERTES
  770. O, fear me not.
  771. I stay too long: but here my father comes.
  772. Enter POLONIUS
  773. A double blessing is a double grace,
  774. Occasion smiles upon a second leave.
  775. LORD POLONIUS
  776. Yet here, Laertes! aboard, aboard, for shame!
  777. The wind sits in the shoulder of your sail,
  778. And you are stay'd for. There; my blessing with thee!
  779. And these few precepts in thy memory
  780. See thou character. Give thy thoughts no tongue,
  781. Nor any unproportioned thought his act.
  782. Be thou familiar, but by no means vulgar.
  783. Those friends thou hast, and their adoption tried,
  784. Grapple them to thy soul with hoops of steel;
  785. But do not dull thy palm with entertainment
  786. Of each new-hatch'd, unfledged comrade. Beware
  787. Of entrance to a quarrel, but being in,
  788. Bear't that the opposed may beware of thee.
  789. Give every man thy ear, but few thy voice;
  790. Take each man's censure, but reserve thy judgment.
  791. Costly thy habit as thy purse can buy,
  792. But not express'd in fancy; rich, not gaudy;
  793. For the apparel oft proclaims the man,
  794. And they in France of the best rank and station
  795. Are of a most select and generous chief in that.
  796. Neither a borrower nor a lender be;
  797. For loan oft loses both itself and friend,
  798. And borrowing dulls the edge of husbandry.
  799. This above all: to thine ownself be true,
  800. And it must follow, as the night the day,
  801. Thou canst not then be false to any man.
  802. Farewell: my blessing season this in thee!
  803. LAERTES
  804. Most humbly do I take my leave, my lord.
  805. LORD POLONIUS
  806. The time invites you; go; your servants tend.
  807. LAERTES
  808. Farewell, Ophelia; and remember well
  809. What I have said to you.
  810. OPHELIA
  811. 'Tis in my memory lock'd,
  812. And you yourself shall keep the key of it.
  813. LAERTES
  814. Farewell.
  815. """
  816. class CustomInt:
  817. def __index__(self):
  818. return 100
  819. if __name__ == "__main__":
  820. unittest.main()