blob: 1b802b88d3cf475f08247c0bdc3b30f961c0dbb1 [file] [log] [blame]
Guido van Rossum7d9ea502003-02-03 20:45:52 +00001import unittest
2from test import test_support
Jeremy Hylton6eb4b6a1997-08-15 15:59:43 +00003import zlib
Gregory P. Smithc856fa82008-03-18 22:27:41 +00004import binascii
Andrew M. Kuchling9a0f98e2001-02-21 02:17:01 +00005import random
Antoine Pitrouc7035cd2010-05-07 16:59:00 +00006from test.test_support import precisionbigmemtest, _1G
Andrew M. Kuchling9a0f98e2001-02-21 02:17:01 +00007
Andrew M. Kuchling9a0f98e2001-02-21 02:17:01 +00008
Guido van Rossum7d9ea502003-02-03 20:45:52 +00009class ChecksumTestCase(unittest.TestCase):
10 # checksum test cases
11 def test_crc32start(self):
12 self.assertEqual(zlib.crc32(""), zlib.crc32("", 0))
Andrew M. Kuchlingbb7e8002005-11-22 15:32:28 +000013 self.assert_(zlib.crc32("abc", 0xffffffff))
Andrew M. Kuchlingfcfc8d52001-08-10 15:50:11 +000014
Guido van Rossum7d9ea502003-02-03 20:45:52 +000015 def test_crc32empty(self):
16 self.assertEqual(zlib.crc32("", 0), 0)
17 self.assertEqual(zlib.crc32("", 1), 1)
18 self.assertEqual(zlib.crc32("", 432), 432)
Andrew M. Kuchling9a0f98e2001-02-21 02:17:01 +000019
Guido van Rossum7d9ea502003-02-03 20:45:52 +000020 def test_adler32start(self):
21 self.assertEqual(zlib.adler32(""), zlib.adler32("", 1))
Andrew M. Kuchlingbb7e8002005-11-22 15:32:28 +000022 self.assert_(zlib.adler32("abc", 0xffffffff))
Jeremy Hylton6eb4b6a1997-08-15 15:59:43 +000023
Guido van Rossum7d9ea502003-02-03 20:45:52 +000024 def test_adler32empty(self):
25 self.assertEqual(zlib.adler32("", 0), 0)
26 self.assertEqual(zlib.adler32("", 1), 1)
27 self.assertEqual(zlib.adler32("", 432), 432)
Jeremy Hylton6eb4b6a1997-08-15 15:59:43 +000028
Guido van Rossum7d9ea502003-02-03 20:45:52 +000029 def assertEqual32(self, seen, expected):
30 # 32-bit values masked -- checksums on 32- vs 64- bit machines
31 # This is important if bit 31 (0x08000000L) is set.
32 self.assertEqual(seen & 0x0FFFFFFFFL, expected & 0x0FFFFFFFFL)
33
34 def test_penguins(self):
35 self.assertEqual32(zlib.crc32("penguin", 0), 0x0e5c1a120L)
36 self.assertEqual32(zlib.crc32("penguin", 1), 0x43b6aa94)
37 self.assertEqual32(zlib.adler32("penguin", 0), 0x0bcf02f6)
38 self.assertEqual32(zlib.adler32("penguin", 1), 0x0bd602f7)
39
40 self.assertEqual(zlib.crc32("penguin"), zlib.crc32("penguin", 0))
41 self.assertEqual(zlib.adler32("penguin"),zlib.adler32("penguin",1))
42
Gregory P. Smithf48f9d32008-03-17 18:48:05 +000043 def test_abcdefghijklmnop(self):
44 """test issue1202 compliance: signed crc32, adler32 in 2.x"""
45 foo = 'abcdefghijklmnop'
46 # explicitly test signed behavior
47 self.assertEqual(zlib.crc32(foo), -1808088941)
48 self.assertEqual(zlib.crc32('spam'), 1138425661)
49 self.assertEqual(zlib.adler32(foo+foo), -721416943)
50 self.assertEqual(zlib.adler32('spam'), 72286642)
51
Gregory P. Smithc856fa82008-03-18 22:27:41 +000052 def test_same_as_binascii_crc32(self):
53 foo = 'abcdefghijklmnop'
54 self.assertEqual(binascii.crc32(foo), zlib.crc32(foo))
55 self.assertEqual(binascii.crc32('spam'), zlib.crc32('spam'))
56
Gregory P. Smith88440962008-03-25 06:12:45 +000057 def test_negative_crc_iv_input(self):
58 # The range of valid input values for the crc state should be
59 # -2**31 through 2**32-1 to allow inputs artifically constrained
60 # to a signed 32-bit integer.
61 self.assertEqual(zlib.crc32('ham', -1), zlib.crc32('ham', 0xffffffffL))
62 self.assertEqual(zlib.crc32('spam', -3141593),
63 zlib.crc32('spam', 0xffd01027L))
64 self.assertEqual(zlib.crc32('spam', -(2**31)),
65 zlib.crc32('spam', (2**31)))
Guido van Rossum7d9ea502003-02-03 20:45:52 +000066
67
68class ExceptionTestCase(unittest.TestCase):
69 # make sure we generate some expected errors
Armin Rigoec560192007-10-15 07:48:35 +000070 def test_badlevel(self):
71 # specifying compression level out of range causes an error
72 # (but -1 is Z_DEFAULT_COMPRESSION and apparently the zlib
73 # accepts 0 too)
74 self.assertRaises(zlib.error, zlib.compress, 'ERROR', 10)
Guido van Rossum7d9ea502003-02-03 20:45:52 +000075
76 def test_badcompressobj(self):
77 # verify failure on building compress object with bad params
Neil Schemenauer94afd3e2004-06-05 19:02:52 +000078 self.assertRaises(ValueError, zlib.compressobj, 1, zlib.DEFLATED, 0)
Armin Rigoec560192007-10-15 07:48:35 +000079 # specifying total bits too large causes an error
80 self.assertRaises(ValueError,
81 zlib.compressobj, 1, zlib.DEFLATED, zlib.MAX_WBITS + 1)
Guido van Rossum7d9ea502003-02-03 20:45:52 +000082
83 def test_baddecompressobj(self):
84 # verify failure on building decompress object with bad params
Antoine Pitrou644c9dd2010-04-06 17:24:02 +000085 self.assertRaises(ValueError, zlib.decompressobj, -1)
Guido van Rossum7d9ea502003-02-03 20:45:52 +000086
Gregory P. Smith79e42a02008-04-09 00:25:17 +000087 def test_decompressobj_badflush(self):
88 # verify failure on calling decompressobj.flush with bad params
89 self.assertRaises(ValueError, zlib.decompressobj().flush, 0)
90 self.assertRaises(ValueError, zlib.decompressobj().flush, -1)
91
Guido van Rossum7d9ea502003-02-03 20:45:52 +000092
Antoine Pitrouc7035cd2010-05-07 16:59:00 +000093class BaseCompressTestCase(object):
94 def check_big_compress_buffer(self, size, compress_func):
95 _1M = 1024 * 1024
96 fmt = "%%0%dx" % (2 * _1M)
97 # Generate 10MB worth of random, and expand it by repeating it.
98 # The assumption is that zlib's memory is not big enough to exploit
99 # such spread out redundancy.
100 data = ''.join([binascii.a2b_hex(fmt % random.getrandbits(8 * _1M))
101 for i in range(10)])
102 data = data * (size // len(data) + 1)
103 try:
104 compress_func(data)
105 finally:
106 # Release memory
107 data = None
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000108
Antoine Pitrouc7035cd2010-05-07 16:59:00 +0000109 def check_big_decompress_buffer(self, size, decompress_func):
110 data = 'x' * size
111 try:
112 compressed = zlib.compress(data, 1)
113 finally:
114 # Release memory
115 data = None
116 data = decompress_func(compressed)
117 # Sanity check
118 try:
119 self.assertEqual(len(data), size)
120 self.assertEqual(len(data.strip('x')), 0)
121 finally:
122 data = None
123
124
125class CompressTestCase(BaseCompressTestCase, unittest.TestCase):
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000126 # Test compression in one go (whole message compression)
127 def test_speech(self):
Neil Schemenauer6412b122004-06-05 19:34:28 +0000128 x = zlib.compress(HAMLET_SCENE)
129 self.assertEqual(zlib.decompress(x), HAMLET_SCENE)
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000130
131 def test_speech128(self):
Neil Schemenauer6412b122004-06-05 19:34:28 +0000132 # compress more data
133 data = HAMLET_SCENE * 128
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000134 x = zlib.compress(data)
135 self.assertEqual(zlib.decompress(x), data)
136
Antoine Pitrouca561f52010-05-11 23:45:55 +0000137 def test_incomplete_stream(self):
138 # An useful error message is given
139 x = zlib.compress(HAMLET_SCENE)
140 try:
141 zlib.decompress(x[:-1])
142 except zlib.error as e:
143 self.assertTrue(
144 "Error -5 while decompressing data: incomplete or truncated stream"
145 in str(e), str(e))
146 else:
147 self.fail("zlib.error not raised")
148
Antoine Pitrouc7035cd2010-05-07 16:59:00 +0000149 # Memory use of the following functions takes into account overallocation
150
151 @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=3)
152 def test_big_compress_buffer(self, size):
153 compress = lambda s: zlib.compress(s, 1)
154 self.check_big_compress_buffer(size, compress)
155
156 @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=2)
157 def test_big_decompress_buffer(self, size):
158 self.check_big_decompress_buffer(size, zlib.decompress)
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000159
160
Antoine Pitrouc7035cd2010-05-07 16:59:00 +0000161class CompressObjectTestCase(BaseCompressTestCase, unittest.TestCase):
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000162 # Test compression object
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000163 def test_pair(self):
Neil Schemenauer6412b122004-06-05 19:34:28 +0000164 # straightforward compress/decompress objects
165 data = HAMLET_SCENE * 128
166 co = zlib.compressobj()
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000167 x1 = co.compress(data)
168 x2 = co.flush()
169 self.assertRaises(zlib.error, co.flush) # second flush should not work
Neil Schemenauer94afd3e2004-06-05 19:02:52 +0000170 dco = zlib.decompressobj()
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000171 y1 = dco.decompress(x1 + x2)
172 y2 = dco.flush()
173 self.assertEqual(data, y1 + y2)
174
Neil Schemenauer94afd3e2004-06-05 19:02:52 +0000175 def test_compressoptions(self):
176 # specify lots of options to compressobj()
177 level = 2
178 method = zlib.DEFLATED
179 wbits = -12
180 memlevel = 9
181 strategy = zlib.Z_FILTERED
182 co = zlib.compressobj(level, method, wbits, memlevel, strategy)
Neil Schemenauer6412b122004-06-05 19:34:28 +0000183 x1 = co.compress(HAMLET_SCENE)
Neil Schemenauer94afd3e2004-06-05 19:02:52 +0000184 x2 = co.flush()
185 dco = zlib.decompressobj(wbits)
186 y1 = dco.decompress(x1 + x2)
187 y2 = dco.flush()
Neil Schemenauer6412b122004-06-05 19:34:28 +0000188 self.assertEqual(HAMLET_SCENE, y1 + y2)
Neil Schemenauer94afd3e2004-06-05 19:02:52 +0000189
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000190 def test_compressincremental(self):
191 # compress object in steps, decompress object as one-shot
Neil Schemenauer6412b122004-06-05 19:34:28 +0000192 data = HAMLET_SCENE * 128
Neil Schemenauer94afd3e2004-06-05 19:02:52 +0000193 co = zlib.compressobj()
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000194 bufs = []
195 for i in range(0, len(data), 256):
196 bufs.append(co.compress(data[i:i+256]))
197 bufs.append(co.flush())
198 combuf = ''.join(bufs)
199
Neil Schemenauer94afd3e2004-06-05 19:02:52 +0000200 dco = zlib.decompressobj()
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000201 y1 = dco.decompress(''.join(bufs))
202 y2 = dco.flush()
203 self.assertEqual(data, y1 + y2)
204
Neil Schemenauer6412b122004-06-05 19:34:28 +0000205 def test_decompinc(self, flush=False, source=None, cx=256, dcx=64):
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000206 # compress object in steps, decompress object in steps
Neil Schemenauer6412b122004-06-05 19:34:28 +0000207 source = source or HAMLET_SCENE
208 data = source * 128
Neil Schemenauer94afd3e2004-06-05 19:02:52 +0000209 co = zlib.compressobj()
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000210 bufs = []
Neil Schemenauer6412b122004-06-05 19:34:28 +0000211 for i in range(0, len(data), cx):
212 bufs.append(co.compress(data[i:i+cx]))
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000213 bufs.append(co.flush())
214 combuf = ''.join(bufs)
215
Neil Schemenauer94afd3e2004-06-05 19:02:52 +0000216 self.assertEqual(data, zlib.decompress(combuf))
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000217
Neil Schemenauer94afd3e2004-06-05 19:02:52 +0000218 dco = zlib.decompressobj()
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000219 bufs = []
Neil Schemenauer6412b122004-06-05 19:34:28 +0000220 for i in range(0, len(combuf), dcx):
221 bufs.append(dco.decompress(combuf[i:i+dcx]))
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000222 self.assertEqual('', dco.unconsumed_tail, ########
223 "(A) uct should be '': not %d long" %
Neil Schemenauer6412b122004-06-05 19:34:28 +0000224 len(dco.unconsumed_tail))
225 if flush:
226 bufs.append(dco.flush())
227 else:
228 while True:
229 chunk = dco.decompress('')
230 if chunk:
231 bufs.append(chunk)
232 else:
233 break
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000234 self.assertEqual('', dco.unconsumed_tail, ########
Neil Schemenauer6412b122004-06-05 19:34:28 +0000235 "(B) uct should be '': not %d long" %
236 len(dco.unconsumed_tail))
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000237 self.assertEqual(data, ''.join(bufs))
238 # Failure means: "decompressobj with init options failed"
239
Neil Schemenauer6412b122004-06-05 19:34:28 +0000240 def test_decompincflush(self):
241 self.test_decompinc(flush=True)
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000242
Neil Schemenauer6412b122004-06-05 19:34:28 +0000243 def test_decompimax(self, source=None, cx=256, dcx=64):
244 # compress in steps, decompress in length-restricted steps
245 source = source or HAMLET_SCENE
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000246 # Check a decompression object with max_length specified
Neil Schemenauer6412b122004-06-05 19:34:28 +0000247 data = source * 128
248 co = zlib.compressobj()
249 bufs = []
250 for i in range(0, len(data), cx):
251 bufs.append(co.compress(data[i:i+cx]))
252 bufs.append(co.flush())
253 combuf = ''.join(bufs)
254 self.assertEqual(data, zlib.decompress(combuf),
255 'compressed data failure')
256
257 dco = zlib.decompressobj()
258 bufs = []
259 cb = combuf
260 while cb:
261 #max_length = 1 + len(cb)//10
262 chunk = dco.decompress(cb, dcx)
263 self.failIf(len(chunk) > dcx,
264 'chunk too big (%d>%d)' % (len(chunk), dcx))
265 bufs.append(chunk)
266 cb = dco.unconsumed_tail
267 bufs.append(dco.flush())
268 self.assertEqual(data, ''.join(bufs), 'Wrong data retrieved')
269
270 def test_decompressmaxlen(self, flush=False):
271 # Check a decompression object with max_length specified
272 data = HAMLET_SCENE * 128
Neil Schemenauer94afd3e2004-06-05 19:02:52 +0000273 co = zlib.compressobj()
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000274 bufs = []
275 for i in range(0, len(data), 256):
276 bufs.append(co.compress(data[i:i+256]))
277 bufs.append(co.flush())
278 combuf = ''.join(bufs)
Neil Schemenauer94afd3e2004-06-05 19:02:52 +0000279 self.assertEqual(data, zlib.decompress(combuf),
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000280 'compressed data failure')
281
Neil Schemenauer94afd3e2004-06-05 19:02:52 +0000282 dco = zlib.decompressobj()
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000283 bufs = []
284 cb = combuf
285 while cb:
Guido van Rossumf3594102003-02-27 18:39:18 +0000286 max_length = 1 + len(cb)//10
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000287 chunk = dco.decompress(cb, max_length)
288 self.failIf(len(chunk) > max_length,
289 'chunk too big (%d>%d)' % (len(chunk),max_length))
290 bufs.append(chunk)
291 cb = dco.unconsumed_tail
Neil Schemenauer6412b122004-06-05 19:34:28 +0000292 if flush:
293 bufs.append(dco.flush())
294 else:
295 while chunk:
296 chunk = dco.decompress('', max_length)
297 self.failIf(len(chunk) > max_length,
298 'chunk too big (%d>%d)' % (len(chunk),max_length))
299 bufs.append(chunk)
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000300 self.assertEqual(data, ''.join(bufs), 'Wrong data retrieved')
301
Neil Schemenauer6412b122004-06-05 19:34:28 +0000302 def test_decompressmaxlenflush(self):
303 self.test_decompressmaxlen(flush=True)
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000304
305 def test_maxlenmisc(self):
306 # Misc tests of max_length
Neil Schemenauer94afd3e2004-06-05 19:02:52 +0000307 dco = zlib.decompressobj()
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000308 self.assertRaises(ValueError, dco.decompress, "", -1)
309 self.assertEqual('', dco.unconsumed_tail)
310
311 def test_flushes(self):
312 # Test flush() with the various options, using all the
313 # different levels in order to provide more variations.
314 sync_opt = ['Z_NO_FLUSH', 'Z_SYNC_FLUSH', 'Z_FULL_FLUSH']
315 sync_opt = [getattr(zlib, opt) for opt in sync_opt
316 if hasattr(zlib, opt)]
Neil Schemenauer6412b122004-06-05 19:34:28 +0000317 data = HAMLET_SCENE * 8
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000318
319 for sync in sync_opt:
320 for level in range(10):
321 obj = zlib.compressobj( level )
322 a = obj.compress( data[:3000] )
323 b = obj.flush( sync )
324 c = obj.compress( data[3000:] )
325 d = obj.flush()
326 self.assertEqual(zlib.decompress(''.join([a,b,c,d])),
327 data, ("Decompress failed: flush "
328 "mode=%i, level=%i") % (sync, level))
329 del obj
330
331 def test_odd_flush(self):
332 # Test for odd flushing bugs noted in 2.0, and hopefully fixed in 2.1
333 import random
334
335 if hasattr(zlib, 'Z_SYNC_FLUSH'):
336 # Testing on 17K of "random" data
337
338 # Create compressor and decompressor objects
Neil Schemenauer6412b122004-06-05 19:34:28 +0000339 co = zlib.compressobj(zlib.Z_BEST_COMPRESSION)
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000340 dco = zlib.decompressobj()
341
342 # Try 17K of data
343 # generate random data stream
344 try:
345 # In 2.3 and later, WichmannHill is the RNG of the bug report
346 gen = random.WichmannHill()
347 except AttributeError:
348 try:
349 # 2.2 called it Random
350 gen = random.Random()
351 except AttributeError:
352 # others might simply have a single RNG
353 gen = random
354 gen.seed(1)
355 data = genblock(1, 17 * 1024, generator=gen)
356
357 # compress, sync-flush, and decompress
358 first = co.compress(data)
359 second = co.flush(zlib.Z_SYNC_FLUSH)
360 expanded = dco.decompress(first + second)
361
362 # if decompressed data is different from the input data, choke.
363 self.assertEqual(expanded, data, "17K random source doesn't match")
364
Andrew M. Kuchling3b585b32004-12-28 20:10:48 +0000365 def test_empty_flush(self):
366 # Test that calling .flush() on unused objects works.
367 # (Bug #1083110 -- calling .flush() on decompress objects
368 # caused a core dump.)
369
370 co = zlib.compressobj(zlib.Z_BEST_COMPRESSION)
371 self.failUnless(co.flush()) # Returns a zlib header
372 dco = zlib.decompressobj()
373 self.assertEqual(dco.flush(), "") # Returns nothing
Tim Peters5a9fb3c2005-01-07 16:01:32 +0000374
Antoine Pitrou33c58132010-05-11 23:33:53 +0000375 def test_decompress_incomplete_stream(self):
376 # This is 'foo', deflated
377 x = 'x\x9cK\xcb\xcf\x07\x00\x02\x82\x01E'
378 # For the record
379 self.assertEqual(zlib.decompress(x), 'foo')
380 self.assertRaises(zlib.error, zlib.decompress, x[:-5])
381 # Omitting the stream end works with decompressor objects
382 # (see issue #8672).
383 dco = zlib.decompressobj()
384 y = dco.decompress(x[:-5])
385 y += dco.flush()
386 self.assertEqual(y, 'foo')
387
Neal Norwitz6e73aaa2006-06-12 03:33:09 +0000388 if hasattr(zlib.compressobj(), "copy"):
389 def test_compresscopy(self):
390 # Test copying a compression object
391 data0 = HAMLET_SCENE
392 data1 = HAMLET_SCENE.swapcase()
393 c0 = zlib.compressobj(zlib.Z_BEST_COMPRESSION)
394 bufs0 = []
395 bufs0.append(c0.compress(data0))
Georg Brandl8d3342b2006-05-16 07:38:27 +0000396
Neal Norwitz6e73aaa2006-06-12 03:33:09 +0000397 c1 = c0.copy()
398 bufs1 = bufs0[:]
Georg Brandl8d3342b2006-05-16 07:38:27 +0000399
Neal Norwitz6e73aaa2006-06-12 03:33:09 +0000400 bufs0.append(c0.compress(data0))
401 bufs0.append(c0.flush())
402 s0 = ''.join(bufs0)
Georg Brandl8d3342b2006-05-16 07:38:27 +0000403
Neal Norwitz6e73aaa2006-06-12 03:33:09 +0000404 bufs1.append(c1.compress(data1))
405 bufs1.append(c1.flush())
406 s1 = ''.join(bufs1)
Georg Brandl8d3342b2006-05-16 07:38:27 +0000407
Neal Norwitz6e73aaa2006-06-12 03:33:09 +0000408 self.assertEqual(zlib.decompress(s0),data0+data0)
409 self.assertEqual(zlib.decompress(s1),data0+data1)
Georg Brandl8d3342b2006-05-16 07:38:27 +0000410
Neal Norwitz6e73aaa2006-06-12 03:33:09 +0000411 def test_badcompresscopy(self):
412 # Test copying a compression object in an inconsistent state
413 c = zlib.compressobj()
414 c.compress(HAMLET_SCENE)
415 c.flush()
416 self.assertRaises(ValueError, c.copy)
Georg Brandl8d3342b2006-05-16 07:38:27 +0000417
Neal Norwitz6e73aaa2006-06-12 03:33:09 +0000418 if hasattr(zlib.decompressobj(), "copy"):
419 def test_decompresscopy(self):
420 # Test copying a decompression object
421 data = HAMLET_SCENE
422 comp = zlib.compress(data)
Georg Brandl8d3342b2006-05-16 07:38:27 +0000423
Neal Norwitz6e73aaa2006-06-12 03:33:09 +0000424 d0 = zlib.decompressobj()
425 bufs0 = []
426 bufs0.append(d0.decompress(comp[:32]))
Georg Brandl8d3342b2006-05-16 07:38:27 +0000427
Neal Norwitz6e73aaa2006-06-12 03:33:09 +0000428 d1 = d0.copy()
429 bufs1 = bufs0[:]
Georg Brandl8d3342b2006-05-16 07:38:27 +0000430
Neal Norwitz6e73aaa2006-06-12 03:33:09 +0000431 bufs0.append(d0.decompress(comp[32:]))
432 s0 = ''.join(bufs0)
Georg Brandl8d3342b2006-05-16 07:38:27 +0000433
Neal Norwitz6e73aaa2006-06-12 03:33:09 +0000434 bufs1.append(d1.decompress(comp[32:]))
435 s1 = ''.join(bufs1)
Georg Brandl8d3342b2006-05-16 07:38:27 +0000436
Neal Norwitz6e73aaa2006-06-12 03:33:09 +0000437 self.assertEqual(s0,s1)
438 self.assertEqual(s0,data)
Georg Brandl8d3342b2006-05-16 07:38:27 +0000439
Neal Norwitz6e73aaa2006-06-12 03:33:09 +0000440 def test_baddecompresscopy(self):
441 # Test copying a compression object in an inconsistent state
442 data = zlib.compress(HAMLET_SCENE)
443 d = zlib.decompressobj()
444 d.decompress(data)
445 d.flush()
446 self.assertRaises(ValueError, d.copy)
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000447
Antoine Pitrouc7035cd2010-05-07 16:59:00 +0000448 # Memory use of the following functions takes into account overallocation
449
450 @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=3)
451 def test_big_compress_buffer(self, size):
452 c = zlib.compressobj(1)
453 compress = lambda s: c.compress(s) + c.flush()
454 self.check_big_compress_buffer(size, compress)
455
456 @precisionbigmemtest(size=_1G + 1024 * 1024, memuse=2)
457 def test_big_decompress_buffer(self, size):
458 d = zlib.decompressobj()
459 decompress = lambda s: d.decompress(s) + d.flush()
460 self.check_big_decompress_buffer(size, decompress)
461
462
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000463def genblock(seed, length, step=1024, generator=random):
464 """length-byte stream of random data from a seed (in step-byte blocks)."""
465 if seed is not None:
466 generator.seed(seed)
467 randint = generator.randint
468 if length < step or step < 2:
469 step = length
470 blocks = []
471 for i in range(0, length, step):
472 blocks.append(''.join([chr(randint(0,255))
473 for x in range(step)]))
474 return ''.join(blocks)[:length]
475
476
477
478def choose_lines(source, number, seed=None, generator=random):
479 """Return a list of number lines randomly chosen from the source"""
480 if seed is not None:
481 generator.seed(seed)
482 sources = source.split('\n')
483 return [generator.choice(sources) for n in range(number)]
484
485
486
Neil Schemenauer6412b122004-06-05 19:34:28 +0000487HAMLET_SCENE = """
Fred Drake004d5e62000-10-23 17:22:08 +0000488LAERTES
Jeremy Hylton6eb4b6a1997-08-15 15:59:43 +0000489
490 O, fear me not.
491 I stay too long: but here my father comes.
492
493 Enter POLONIUS
494
495 A double blessing is a double grace,
496 Occasion smiles upon a second leave.
497
Fred Drake004d5e62000-10-23 17:22:08 +0000498LORD POLONIUS
Jeremy Hylton6eb4b6a1997-08-15 15:59:43 +0000499
500 Yet here, Laertes! aboard, aboard, for shame!
501 The wind sits in the shoulder of your sail,
502 And you are stay'd for. There; my blessing with thee!
503 And these few precepts in thy memory
504 See thou character. Give thy thoughts no tongue,
505 Nor any unproportioned thought his act.
506 Be thou familiar, but by no means vulgar.
507 Those friends thou hast, and their adoption tried,
508 Grapple them to thy soul with hoops of steel;
509 But do not dull thy palm with entertainment
510 Of each new-hatch'd, unfledged comrade. Beware
511 Of entrance to a quarrel, but being in,
512 Bear't that the opposed may beware of thee.
513 Give every man thy ear, but few thy voice;
514 Take each man's censure, but reserve thy judgment.
515 Costly thy habit as thy purse can buy,
516 But not express'd in fancy; rich, not gaudy;
517 For the apparel oft proclaims the man,
518 And they in France of the best rank and station
519 Are of a most select and generous chief in that.
520 Neither a borrower nor a lender be;
521 For loan oft loses both itself and friend,
522 And borrowing dulls the edge of husbandry.
523 This above all: to thine ownself be true,
524 And it must follow, as the night the day,
525 Thou canst not then be false to any man.
526 Farewell: my blessing season this in thee!
527
Fred Drake004d5e62000-10-23 17:22:08 +0000528LAERTES
Jeremy Hylton6eb4b6a1997-08-15 15:59:43 +0000529
530 Most humbly do I take my leave, my lord.
531
Fred Drake004d5e62000-10-23 17:22:08 +0000532LORD POLONIUS
Jeremy Hylton6eb4b6a1997-08-15 15:59:43 +0000533
534 The time invites you; go; your servants tend.
535
Fred Drake004d5e62000-10-23 17:22:08 +0000536LAERTES
Jeremy Hylton6eb4b6a1997-08-15 15:59:43 +0000537
538 Farewell, Ophelia; and remember well
539 What I have said to you.
540
Fred Drake004d5e62000-10-23 17:22:08 +0000541OPHELIA
Jeremy Hylton6eb4b6a1997-08-15 15:59:43 +0000542
543 'Tis in my memory lock'd,
544 And you yourself shall keep the key of it.
545
Fred Drake004d5e62000-10-23 17:22:08 +0000546LAERTES
Jeremy Hylton6eb4b6a1997-08-15 15:59:43 +0000547
548 Farewell.
549"""
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000550
551
552def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +0000553 test_support.run_unittest(
554 ChecksumTestCase,
555 ExceptionTestCase,
556 CompressTestCase,
557 CompressObjectTestCase
558 )
Guido van Rossum7d9ea502003-02-03 20:45:52 +0000559
560if __name__ == "__main__":
561 test_main()