Debian Codegraph @

lib-python/3/test/test_zlib.py

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