test_zlib.py revision c72737e7b6ec3beeecafbef75fbc31e22e0d710b
1import zlib
2from test_support import TestFailed
3import sys
4import imp
5
6try:
7    t = imp.find_module('test_zlib')
8    file = t[0]
9except ImportError:
10    file = open(__file__)
11buf = file.read() * 8
12file.close()
13
14# test the checksums (hex so the test doesn't break on 64-bit machines)
15print hex(zlib.crc32('penguin')), hex(zlib.crc32('penguin', 1))
16print hex(zlib.adler32('penguin')), hex(zlib.adler32('penguin', 1))
17
18# make sure we generate some expected errors
19try:
20    zlib.compress('ERROR', zlib.MAX_WBITS + 1)
21except zlib.error, msg:
22    print "expecting", msg
23try:
24    zlib.compressobj(1, 8, 0)
25except ValueError, msg:
26    print "expecting", msg
27try:
28    zlib.decompressobj(0)
29except ValueError, msg:
30    print "expecting", msg
31
32x = zlib.compress(buf)
33y = zlib.decompress(x)
34if buf != y:
35    print "normal compression/decompression failed"
36else:
37    print "normal compression/decompression succeeded"
38
39buf = buf * 16
40
41co = zlib.compressobj(8, 8, -15)
42x1 = co.compress(buf)
43x2 = co.flush()
44try:
45    co.flush()
46    print "Oops - second flush worked when it should not have!"
47except zlib.error:
48    pass
49
50x = x1 + x2
51
52dc = zlib.decompressobj(-15)
53y1 = dc.decompress(x)
54y2 = dc.flush()
55y = y1 + y2
56if buf != y:
57    print "compress/decompression obj failed"
58else:
59    print "compress/decompression obj succeeded"
60
61co = zlib.compressobj(2, 8, -12, 9, 1)
62bufs = []
63for i in range(0, len(buf), 256):
64    bufs.append(co.compress(buf[i:i+256]))
65bufs.append(co.flush())
66combuf = ''.join(bufs)
67
68decomp1 = zlib.decompress(combuf, -12, -5)
69if decomp1 != buf:
70    print "decompress with init options failed"
71else:
72    print "decompress with init options succeeded"
73
74deco = zlib.decompressobj(-12)
75bufs = []
76for i in range(0, len(combuf), 128):
77    bufs.append(deco.decompress(combuf[i:i+128]))
78bufs.append(deco.flush())
79decomp2 = ''.join(bufs)
80if decomp2 != buf:
81    print "decompressobj with init options failed"
82else:
83    print "decompressobj with init options succeeded"
84
85print "should be '':", `deco.unconsumed_tail`
86
87# Check a decompression object with max_length specified
88deco = zlib.decompressobj(-12)
89cb = combuf
90bufs = []
91while cb:
92    max_length = 1 + len(cb)/10
93    chunk = deco.decompress(cb, max_length)
94    if len(chunk) > max_length:
95        print 'chunk too big (%d>%d)' % (len(chunk),max_length)
96    bufs.append(chunk)
97    cb = deco.unconsumed_tail
98bufs.append(deco.flush())
99decomp2 = ''.join(buf)
100if decomp2 != buf:
101    print "max_length decompressobj failed"
102else:
103    print "max_length decompressobj succeeded"
104
105# Misc tests of max_length
106deco = zlib.decompressobj(-12)
107try:
108    deco.decompress("", -1)
109except ValueError:
110    pass
111else:
112    print "failed to raise value error on bad max_length"
113print "unconsumed_tail should be '':", `deco.unconsumed_tail`
114
115# Test flush() with the various options, using all the different levels
116# in order to provide more variations.
117sync_opt = ['Z_NO_FLUSH', 'Z_SYNC_FLUSH', 'Z_FULL_FLUSH']
118sync_opt = [getattr(zlib, opt) for opt in sync_opt if hasattr(zlib, opt)]
119
120for sync in sync_opt:
121    for level in range(10):
122        obj = zlib.compressobj( level )
123        d = obj.compress( buf[:3000] )
124        d = d + obj.flush( sync )
125        d = d + obj.compress( buf[3000:] )
126        d = d + obj.flush()
127        if zlib.decompress(d) != buf:
128            print "Decompress failed: flush mode=%i, level=%i" % (sync,level)
129        del obj
130
131# Test for the odd flushing bugs noted in 2.0, and hopefully fixed in 2.1
132
133import random
134random.seed(1)
135
136print 'Testing on 17K of random data'
137
138if hasattr(zlib, 'Z_SYNC_FLUSH'):
139
140    # Create compressor and decompressor objects
141    c=zlib.compressobj(9)
142    d=zlib.decompressobj()
143
144    # Try 17K of data
145    # generate random data stream
146    a=""
147    for i in range(17*1024):
148        a=a+chr(random.randint(0,255))
149
150    # compress, sync-flush, and decompress
151    t = d.decompress( c.compress(a)+c.flush(zlib.Z_SYNC_FLUSH) )
152
153    # if decompressed data is different from the input data, choke.
154    if len(t) != len(a):
155        print len(a),len(t),len(d.unused_data)
156        raise TestFailed, "output of 17K doesn't match"
157
158def ignore():
159    """An empty function with a big string.
160
161    Make the compression algorithm work a little harder.
162    """
163
164    """
165LAERTES
166
167       O, fear me not.
168       I stay too long: but here my father comes.
169
170       Enter POLONIUS
171
172       A double blessing is a double grace,
173       Occasion smiles upon a second leave.
174
175LORD POLONIUS
176
177       Yet here, Laertes! aboard, aboard, for shame!
178       The wind sits in the shoulder of your sail,
179       And you are stay'd for. There; my blessing with thee!
180       And these few precepts in thy memory
181       See thou character. Give thy thoughts no tongue,
182       Nor any unproportioned thought his act.
183       Be thou familiar, but by no means vulgar.
184       Those friends thou hast, and their adoption tried,
185       Grapple them to thy soul with hoops of steel;
186       But do not dull thy palm with entertainment
187       Of each new-hatch'd, unfledged comrade. Beware
188       Of entrance to a quarrel, but being in,
189       Bear't that the opposed may beware of thee.
190       Give every man thy ear, but few thy voice;
191       Take each man's censure, but reserve thy judgment.
192       Costly thy habit as thy purse can buy,
193       But not express'd in fancy; rich, not gaudy;
194       For the apparel oft proclaims the man,
195       And they in France of the best rank and station
196       Are of a most select and generous chief in that.
197       Neither a borrower nor a lender be;
198       For loan oft loses both itself and friend,
199       And borrowing dulls the edge of husbandry.
200       This above all: to thine ownself be true,
201       And it must follow, as the night the day,
202       Thou canst not then be false to any man.
203       Farewell: my blessing season this in thee!
204
205LAERTES
206
207       Most humbly do I take my leave, my lord.
208
209LORD POLONIUS
210
211       The time invites you; go; your servants tend.
212
213LAERTES
214
215       Farewell, Ophelia; and remember well
216       What I have said to you.
217
218OPHELIA
219
220       'Tis in my memory lock'd,
221       And you yourself shall keep the key of it.
222
223LAERTES
224
225       Farewell.
226"""
227