]>
git.proxmox.com Git - mirror_edk2.git/blob - AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_zlib.py
2 from test
.test_support
import TESTFN
, run_unittest
, import_module
, unlink
, requires
5 from test
.test_support
import precisionbigmemtest
, _1G
, _4G
13 zlib
= import_module('zlib')
16 class ChecksumTestCase(unittest
.TestCase
):
18 def test_crc32start(self
):
19 self
.assertEqual(zlib
.crc32(""), zlib
.crc32("", 0))
20 self
.assertTrue(zlib
.crc32("abc", 0xffffffff))
22 def test_crc32empty(self
):
23 self
.assertEqual(zlib
.crc32("", 0), 0)
24 self
.assertEqual(zlib
.crc32("", 1), 1)
25 self
.assertEqual(zlib
.crc32("", 432), 432)
27 def test_adler32start(self
):
28 self
.assertEqual(zlib
.adler32(""), zlib
.adler32("", 1))
29 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)
36 def assertEqual32(self
, seen
, expected
):
37 # 32-bit values masked -- checksums on 32- vs 64- bit machines
38 # This is important if bit 31 (0x08000000L) is set.
39 self
.assertEqual(seen
& 0x0FFFFFFFFL
, expected
& 0x0FFFFFFFFL
)
41 def test_penguins(self
):
42 self
.assertEqual32(zlib
.crc32("penguin", 0), 0x0e5c1a120L
)
43 self
.assertEqual32(zlib
.crc32("penguin", 1), 0x43b6aa94)
44 self
.assertEqual32(zlib
.adler32("penguin", 0), 0x0bcf02f6)
45 self
.assertEqual32(zlib
.adler32("penguin", 1), 0x0bd602f7)
47 self
.assertEqual(zlib
.crc32("penguin"), zlib
.crc32("penguin", 0))
48 self
.assertEqual(zlib
.adler32("penguin"),zlib
.adler32("penguin",1))
50 def test_abcdefghijklmnop(self
):
51 """test issue1202 compliance: signed crc32, adler32 in 2.x"""
52 foo
= 'abcdefghijklmnop'
53 # explicitly test signed behavior
54 self
.assertEqual(zlib
.crc32(foo
), -1808088941)
55 self
.assertEqual(zlib
.crc32('spam'), 1138425661)
56 self
.assertEqual(zlib
.adler32(foo
+foo
), -721416943)
57 self
.assertEqual(zlib
.adler32('spam'), 72286642)
59 def test_same_as_binascii_crc32(self
):
60 foo
= 'abcdefghijklmnop'
61 self
.assertEqual(binascii
.crc32(foo
), zlib
.crc32(foo
))
62 self
.assertEqual(binascii
.crc32('spam'), zlib
.crc32('spam'))
64 def test_negative_crc_iv_input(self
):
65 # The range of valid input values for the crc state should be
66 # -2**31 through 2**32-1 to allow inputs artifically constrained
67 # to a signed 32-bit integer.
68 self
.assertEqual(zlib
.crc32('ham', -1), zlib
.crc32('ham', 0xffffffffL
))
69 self
.assertEqual(zlib
.crc32('spam', -3141593),
70 zlib
.crc32('spam', 0xffd01027L
))
71 self
.assertEqual(zlib
.crc32('spam', -(2**31)),
72 zlib
.crc32('spam', (2**31)))
75 class ExceptionTestCase(unittest
.TestCase
):
76 # make sure we generate some expected errors
77 def test_badlevel(self
):
78 # specifying compression level out of range causes an error
79 # (but -1 is Z_DEFAULT_COMPRESSION and apparently the zlib
81 self
.assertRaises(zlib
.error
, zlib
.compress
, 'ERROR', 10)
83 def test_badcompressobj(self
):
84 # verify failure on building compress object with bad params
85 self
.assertRaises(ValueError, zlib
.compressobj
, 1, zlib
.DEFLATED
, 0)
86 # specifying total bits too large causes an error
87 self
.assertRaises(ValueError,
88 zlib
.compressobj
, 1, zlib
.DEFLATED
, zlib
.MAX_WBITS
+ 1)
90 def test_baddecompressobj(self
):
91 # verify failure on building decompress object with bad params
92 self
.assertRaises(ValueError, zlib
.decompressobj
, -1)
94 def test_decompressobj_badflush(self
):
95 # verify failure on calling decompressobj.flush with bad params
96 self
.assertRaises(ValueError, zlib
.decompressobj().flush
, 0)
97 self
.assertRaises(ValueError, zlib
.decompressobj().flush
, -1)
100 class BaseCompressTestCase(object):
101 def check_big_compress_buffer(self
, size
, compress_func
):
103 fmt
= "%%0%dx" % (2 * _1M
)
104 # Generate 10MB worth of random, and expand it by repeating it.
105 # The assumption is that zlib's memory is not big enough to exploit
106 # such spread out redundancy.
107 data
= ''.join([binascii
.a2b_hex(fmt
% random
.getrandbits(8 * _1M
))
109 data
= data
* (size
// len(data
) + 1)
116 def check_big_decompress_buffer(self
, size
, decompress_func
):
119 compressed
= zlib
.compress(data
, 1)
123 data
= decompress_func(compressed
)
126 self
.assertEqual(len(data
), size
)
127 self
.assertEqual(len(data
.strip('x')), 0)
132 class CompressTestCase(BaseCompressTestCase
, unittest
.TestCase
):
133 # Test compression in one go (whole message compression)
134 def test_speech(self
):
135 x
= zlib
.compress(HAMLET_SCENE
)
136 self
.assertEqual(zlib
.decompress(x
), HAMLET_SCENE
)
138 def test_speech128(self
):
140 data
= HAMLET_SCENE
* 128
141 x
= zlib
.compress(data
)
142 self
.assertEqual(zlib
.decompress(x
), data
)
144 def test_incomplete_stream(self
):
145 # An useful error message is given
146 x
= zlib
.compress(HAMLET_SCENE
)
147 self
.assertRaisesRegexp(zlib
.error
,
148 "Error -5 while decompressing data: incomplete or truncated stream",
149 zlib
.decompress
, x
[:-1])
151 # Memory use of the following functions takes into account overallocation
153 @precisionbigmemtest(size
=_1G
+ 1024 * 1024, memuse
=3)
154 def test_big_compress_buffer(self
, size
):
155 compress
= lambda s
: zlib
.compress(s
, 1)
156 self
.check_big_compress_buffer(size
, compress
)
158 @precisionbigmemtest(size
=_1G
+ 1024 * 1024, memuse
=2)
159 def test_big_decompress_buffer(self
, size
):
160 self
.check_big_decompress_buffer(size
, zlib
.decompress
)
163 class CompressObjectTestCase(BaseCompressTestCase
, unittest
.TestCase
):
164 # Test compression object
166 # straightforward compress/decompress objects
167 data
= HAMLET_SCENE
* 128
168 co
= zlib
.compressobj()
169 x1
= co
.compress(data
)
171 self
.assertRaises(zlib
.error
, co
.flush
) # second flush should not work
172 dco
= zlib
.decompressobj()
173 y1
= dco
.decompress(x1
+ x2
)
175 self
.assertEqual(data
, y1
+ y2
)
177 def test_compressoptions(self
):
178 # specify lots of options to compressobj()
180 method
= zlib
.DEFLATED
183 strategy
= zlib
.Z_FILTERED
184 co
= zlib
.compressobj(level
, method
, wbits
, memlevel
, strategy
)
185 x1
= co
.compress(HAMLET_SCENE
)
187 dco
= zlib
.decompressobj(wbits
)
188 y1
= dco
.decompress(x1
+ x2
)
190 self
.assertEqual(HAMLET_SCENE
, y1
+ y2
)
192 def test_compressincremental(self
):
193 # compress object in steps, decompress object as one-shot
194 data
= HAMLET_SCENE
* 128
195 co
= zlib
.compressobj()
197 for i
in range(0, len(data
), 256):
198 bufs
.append(co
.compress(data
[i
:i
+256]))
199 bufs
.append(co
.flush())
200 combuf
= ''.join(bufs
)
202 dco
= zlib
.decompressobj()
203 y1
= dco
.decompress(''.join(bufs
))
205 self
.assertEqual(data
, y1
+ y2
)
207 def test_decompinc(self
, flush
=False, source
=None, cx
=256, dcx
=64):
208 # compress object in steps, decompress object in steps
209 source
= source
or HAMLET_SCENE
211 co
= zlib
.compressobj()
213 for i
in range(0, len(data
), cx
):
214 bufs
.append(co
.compress(data
[i
:i
+cx
]))
215 bufs
.append(co
.flush())
216 combuf
= ''.join(bufs
)
218 self
.assertEqual(data
, zlib
.decompress(combuf
))
220 dco
= zlib
.decompressobj()
222 for i
in range(0, len(combuf
), dcx
):
223 bufs
.append(dco
.decompress(combuf
[i
:i
+dcx
]))
224 self
.assertEqual('', dco
.unconsumed_tail
, ########
225 "(A) uct should be '': not %d long" %
226 len(dco
.unconsumed_tail
))
228 bufs
.append(dco
.flush())
231 chunk
= dco
.decompress('')
236 self
.assertEqual('', dco
.unconsumed_tail
, ########
237 "(B) uct should be '': not %d long" %
238 len(dco
.unconsumed_tail
))
239 self
.assertEqual(data
, ''.join(bufs
))
240 # Failure means: "decompressobj with init options failed"
242 def test_decompincflush(self
):
243 self
.test_decompinc(flush
=True)
245 def test_decompimax(self
, source
=None, cx
=256, dcx
=64):
246 # compress in steps, decompress in length-restricted steps
247 source
= source
or HAMLET_SCENE
248 # Check a decompression object with max_length specified
250 co
= zlib
.compressobj()
252 for i
in range(0, len(data
), cx
):
253 bufs
.append(co
.compress(data
[i
:i
+cx
]))
254 bufs
.append(co
.flush())
255 combuf
= ''.join(bufs
)
256 self
.assertEqual(data
, zlib
.decompress(combuf
),
257 'compressed data failure')
259 dco
= zlib
.decompressobj()
263 #max_length = 1 + len(cb)//10
264 chunk
= dco
.decompress(cb
, dcx
)
265 self
.assertFalse(len(chunk
) > dcx
,
266 'chunk too big (%d>%d)' % (len(chunk
), dcx
))
268 cb
= dco
.unconsumed_tail
269 bufs
.append(dco
.flush())
270 self
.assertEqual(data
, ''.join(bufs
), 'Wrong data retrieved')
272 def test_decompressmaxlen(self
, flush
=False):
273 # Check a decompression object with max_length specified
274 data
= HAMLET_SCENE
* 128
275 co
= zlib
.compressobj()
277 for i
in range(0, len(data
), 256):
278 bufs
.append(co
.compress(data
[i
:i
+256]))
279 bufs
.append(co
.flush())
280 combuf
= ''.join(bufs
)
281 self
.assertEqual(data
, zlib
.decompress(combuf
),
282 'compressed data failure')
284 dco
= zlib
.decompressobj()
288 max_length
= 1 + len(cb
)//10
289 chunk
= dco
.decompress(cb
, max_length
)
290 self
.assertFalse(len(chunk
) > max_length
,
291 'chunk too big (%d>%d)' % (len(chunk
),max_length
))
293 cb
= dco
.unconsumed_tail
295 bufs
.append(dco
.flush())
298 chunk
= dco
.decompress('', max_length
)
299 self
.assertFalse(len(chunk
) > max_length
,
300 'chunk too big (%d>%d)' % (len(chunk
),max_length
))
302 self
.assertEqual(data
, ''.join(bufs
), 'Wrong data retrieved')
304 def test_decompressmaxlenflush(self
):
305 self
.test_decompressmaxlen(flush
=True)
307 def test_maxlenmisc(self
):
308 # Misc tests of max_length
309 dco
= zlib
.decompressobj()
310 self
.assertRaises(ValueError, dco
.decompress
, "", -1)
311 self
.assertEqual('', dco
.unconsumed_tail
)
313 def test_clear_unconsumed_tail(self
):
314 # Issue #12050: calling decompress() without providing max_length
315 # should clear the unconsumed_tail attribute.
316 cdata
= "x\x9cKLJ\x06\x00\x02M\x01" # "abc"
317 dco
= zlib
.decompressobj()
318 ddata
= dco
.decompress(cdata
, 1)
319 ddata
+= dco
.decompress(dco
.unconsumed_tail
)
320 self
.assertEqual(dco
.unconsumed_tail
, "")
322 def test_flushes(self
):
323 # Test flush() with the various options, using all the
324 # different levels in order to provide more variations.
325 sync_opt
= ['Z_NO_FLUSH', 'Z_SYNC_FLUSH', 'Z_FULL_FLUSH']
326 sync_opt
= [getattr(zlib
, opt
) for opt
in sync_opt
327 if hasattr(zlib
, opt
)]
328 data
= HAMLET_SCENE
* 8
330 for sync
in sync_opt
:
331 for level
in range(10):
332 obj
= zlib
.compressobj( level
)
333 a
= obj
.compress( data
[:3000] )
334 b
= obj
.flush( sync
)
335 c
= obj
.compress( data
[3000:] )
337 self
.assertEqual(zlib
.decompress(''.join([a
,b
,c
,d
])),
338 data
, ("Decompress failed: flush "
339 "mode=%i, level=%i") % (sync
, level
))
342 def test_odd_flush(self
):
343 # Test for odd flushing bugs noted in 2.0, and hopefully fixed in 2.1
346 if hasattr(zlib
, 'Z_SYNC_FLUSH'):
347 # Testing on 17K of "random" data
349 # Create compressor and decompressor objects
350 co
= zlib
.compressobj(zlib
.Z_BEST_COMPRESSION
)
351 dco
= zlib
.decompressobj()
354 # generate random data stream
356 # In 2.3 and later, WichmannHill is the RNG of the bug report
357 gen
= random
.WichmannHill()
358 except AttributeError:
360 # 2.2 called it Random
361 gen
= random
.Random()
362 except AttributeError:
363 # others might simply have a single RNG
366 data
= genblock(1, 17 * 1024, generator
=gen
)
368 # compress, sync-flush, and decompress
369 first
= co
.compress(data
)
370 second
= co
.flush(zlib
.Z_SYNC_FLUSH
)
371 expanded
= dco
.decompress(first
+ second
)
373 # if decompressed data is different from the input data, choke.
374 self
.assertEqual(expanded
, data
, "17K random source doesn't match")
376 def test_empty_flush(self
):
377 # Test that calling .flush() on unused objects works.
378 # (Bug #1083110 -- calling .flush() on decompress objects
379 # caused a core dump.)
381 co
= zlib
.compressobj(zlib
.Z_BEST_COMPRESSION
)
382 self
.assertTrue(co
.flush()) # Returns a zlib header
383 dco
= zlib
.decompressobj()
384 self
.assertEqual(dco
.flush(), "") # Returns nothing
386 def test_decompress_incomplete_stream(self
):
387 # This is 'foo', deflated
388 x
= 'x\x9cK\xcb\xcf\x07\x00\x02\x82\x01E'
390 self
.assertEqual(zlib
.decompress(x
), 'foo')
391 self
.assertRaises(zlib
.error
, zlib
.decompress
, x
[:-5])
392 # Omitting the stream end works with decompressor objects
394 dco
= zlib
.decompressobj()
395 y
= dco
.decompress(x
[:-5])
397 self
.assertEqual(y
, 'foo')
399 if hasattr(zlib
.compressobj(), "copy"):
400 def test_compresscopy(self
):
401 # Test copying a compression object
403 data1
= HAMLET_SCENE
.swapcase()
404 c0
= zlib
.compressobj(zlib
.Z_BEST_COMPRESSION
)
406 bufs0
.append(c0
.compress(data0
))
411 bufs0
.append(c0
.compress(data0
))
412 bufs0
.append(c0
.flush())
415 bufs1
.append(c1
.compress(data1
))
416 bufs1
.append(c1
.flush())
419 self
.assertEqual(zlib
.decompress(s0
),data0
+data0
)
420 self
.assertEqual(zlib
.decompress(s1
),data0
+data1
)
422 def test_badcompresscopy(self
):
423 # Test copying a compression object in an inconsistent state
424 c
= zlib
.compressobj()
425 c
.compress(HAMLET_SCENE
)
427 self
.assertRaises(ValueError, c
.copy
)
429 if hasattr(zlib
.decompressobj(), "copy"):
430 def test_decompresscopy(self
):
431 # Test copying a decompression object
433 comp
= zlib
.compress(data
)
435 d0
= zlib
.decompressobj()
437 bufs0
.append(d0
.decompress(comp
[:32]))
442 bufs0
.append(d0
.decompress(comp
[32:]))
445 bufs1
.append(d1
.decompress(comp
[32:]))
448 self
.assertEqual(s0
,s1
)
449 self
.assertEqual(s0
,data
)
451 def test_baddecompresscopy(self
):
452 # Test copying a compression object in an inconsistent state
453 data
= zlib
.compress(HAMLET_SCENE
)
454 d
= zlib
.decompressobj()
457 self
.assertRaises(ValueError, d
.copy
)
459 # Memory use of the following functions takes into account overallocation
461 @precisionbigmemtest(size
=_1G
+ 1024 * 1024, memuse
=3)
462 def test_big_compress_buffer(self
, size
):
463 c
= zlib
.compressobj(1)
464 compress
= lambda s
: c
.compress(s
) + c
.flush()
465 self
.check_big_compress_buffer(size
, compress
)
467 @precisionbigmemtest(size
=_1G
+ 1024 * 1024, memuse
=2)
468 def test_big_decompress_buffer(self
, size
):
469 d
= zlib
.decompressobj()
470 decompress
= lambda s
: d
.decompress(s
) + d
.flush()
471 self
.check_big_decompress_buffer(size
, decompress
)
474 def genblock(seed
, length
, step
=1024, generator
=random
):
475 """length-byte stream of random data from a seed (in step-byte blocks)."""
478 randint
= generator
.randint
479 if length
< step
or step
< 2:
482 for i
in range(0, length
, step
):
483 blocks
.append(''.join([chr(randint(0,255))
484 for x
in range(step
)]))
485 return ''.join(blocks
)[:length
]
489 def choose_lines(source
, number
, seed
=None, generator
=random
):
490 """Return a list of number lines randomly chosen from the source"""
493 sources
= source
.split('\n')
494 return [generator
.choice(sources
) for n
in range(number
)]
502 I stay too long: but here my father comes.
506 A double blessing is a double grace,
507 Occasion smiles upon a second leave.
511 Yet here, Laertes! aboard, aboard, for shame!
512 The wind sits in the shoulder of your sail,
513 And you are stay'd for. There; my blessing with thee!
514 And these few precepts in thy memory
515 See thou character. Give thy thoughts no tongue,
516 Nor any unproportioned thought his act.
517 Be thou familiar, but by no means vulgar.
518 Those friends thou hast, and their adoption tried,
519 Grapple them to thy soul with hoops of steel;
520 But do not dull thy palm with entertainment
521 Of each new-hatch'd, unfledged comrade. Beware
522 Of entrance to a quarrel, but being in,
523 Bear't that the opposed may beware of thee.
524 Give every man thy ear, but few thy voice;
525 Take each man's censure, but reserve thy judgment.
526 Costly thy habit as thy purse can buy,
527 But not express'd in fancy; rich, not gaudy;
528 For the apparel oft proclaims the man,
529 And they in France of the best rank and station
530 Are of a most select and generous chief in that.
531 Neither a borrower nor a lender be;
532 For loan oft loses both itself and friend,
533 And borrowing dulls the edge of husbandry.
534 This above all: to thine ownself be true,
535 And it must follow, as the night the day,
536 Thou canst not then be false to any man.
537 Farewell: my blessing season this in thee!
541 Most humbly do I take my leave, my lord.
545 The time invites you; go; your servants tend.
549 Farewell, Ophelia; and remember well
550 What I have said to you.
554 'Tis in my memory lock'd,
555 And you yourself shall keep the key of it.
568 CompressObjectTestCase
571 if __name__
== "__main__":