blob: d8408e15cd4dc0bce45345675e3698c74d1930c9 [file] [log] [blame]
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +00001"""Test script for the gzip module.
2"""
3
4import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005from test import support
Christian Heimes05e8be12008-02-23 18:30:17 +00006import os
Antoine Pitroub1f88352010-01-03 22:37:40 +00007import io
Antoine Pitrou42db3ef2009-01-04 21:37:59 +00008import struct
Serhiy Storchakabca63b32015-03-23 14:59:48 +02009import array
Ezio Melotti78ea2022009-09-12 18:41:20 +000010gzip = support.import_module('gzip')
Andrew M. Kuchling605ebdd1999-03-25 21:50:27 +000011
Walter Dörwald5b1284d2007-06-06 16:43:59 +000012data1 = b""" int length=DEFAULTALLOC, err = Z_OK;
Andrew M. Kuchling605ebdd1999-03-25 21:50:27 +000013 PyObject *RetVal;
14 int flushmode = Z_FINISH;
15 unsigned long start_total_out;
16
17"""
18
Walter Dörwald5b1284d2007-06-06 16:43:59 +000019data2 = b"""/* zlibmodule.c -- gzip-compatible data compression */
Neal Norwitz014f1032004-07-29 03:55:56 +000020/* See http://www.gzip.org/zlib/
Andrew M. Kuchling605ebdd1999-03-25 21:50:27 +000021/* See http://www.winimage.com/zLibDll for Windows */
22"""
23
Andrew M. Kuchling605ebdd1999-03-25 21:50:27 +000024
Antoine Pitrou7b969842010-09-23 16:22:51 +000025class UnseekableIO(io.BytesIO):
26 def seekable(self):
27 return False
28
29 def tell(self):
30 raise io.UnsupportedOperation
31
32 def seek(self, *args):
33 raise io.UnsupportedOperation
34
35
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +020036class BaseTest(unittest.TestCase):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000037 filename = support.TESTFN
Tim Peters5cfb05e2004-07-27 21:02:02 +000038
Georg Brandlb533e262008-05-25 18:19:30 +000039 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000040 support.unlink(self.filename)
Andrew M. Kuchling605ebdd1999-03-25 21:50:27 +000041
Georg Brandlb533e262008-05-25 18:19:30 +000042 def tearDown(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000043 support.unlink(self.filename)
Andrew M. Kuchling605ebdd1999-03-25 21:50:27 +000044
Andrew M. Kuchling85ab7382000-07-29 20:18:34 +000045
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +020046class TestGzip(BaseTest):
Serhiy Storchakabca63b32015-03-23 14:59:48 +020047 def write_and_read_back(self, data, mode='b'):
48 b_data = bytes(data)
49 with gzip.GzipFile(self.filename, 'w'+mode) as f:
50 l = f.write(data)
51 self.assertEqual(l, len(b_data))
52 with gzip.GzipFile(self.filename, 'r'+mode) as f:
53 self.assertEqual(f.read(), b_data)
54
Georg Brandlb533e262008-05-25 18:19:30 +000055 def test_write(self):
Brian Curtin28f96b52010-10-13 02:21:42 +000056 with gzip.GzipFile(self.filename, 'wb') as f:
57 f.write(data1 * 50)
Andrew M. Kuchling85ab7382000-07-29 20:18:34 +000058
Brian Curtin28f96b52010-10-13 02:21:42 +000059 # Try flush and fileno.
60 f.flush()
61 f.fileno()
62 if hasattr(os, 'fsync'):
63 os.fsync(f.fileno())
64 f.close()
Andrew M. Kuchling85ab7382000-07-29 20:18:34 +000065
Georg Brandlb533e262008-05-25 18:19:30 +000066 # Test multiple close() calls.
67 f.close()
68
Serhiy Storchakabca63b32015-03-23 14:59:48 +020069 # The following test_write_xy methods test that write accepts
70 # the corresponding bytes-like object type as input
71 # and that the data written equals bytes(xy) in all cases.
72 def test_write_memoryview(self):
73 self.write_and_read_back(memoryview(data1 * 50))
74 m = memoryview(bytes(range(256)))
75 data = m.cast('B', shape=[8,8,4])
76 self.write_and_read_back(data)
77
78 def test_write_bytearray(self):
79 self.write_and_read_back(bytearray(data1 * 50))
80
81 def test_write_array(self):
82 self.write_and_read_back(array.array('I', data1 * 40))
83
84 def test_write_incompatible_type(self):
85 # Test that non-bytes-like types raise TypeError.
86 # Issue #21560: attempts to write incompatible types
87 # should not affect the state of the fileobject
88 with gzip.GzipFile(self.filename, 'wb') as f:
89 with self.assertRaises(TypeError):
90 f.write('')
91 with self.assertRaises(TypeError):
92 f.write([])
93 f.write(data1)
94 with gzip.GzipFile(self.filename, 'rb') as f:
95 self.assertEqual(f.read(), data1)
96
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +000097 def test_read(self):
98 self.test_write()
99 # Try reading.
Brian Curtin28f96b52010-10-13 02:21:42 +0000100 with gzip.GzipFile(self.filename, 'r') as f:
101 d = f.read()
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000102 self.assertEqual(d, data1*50)
Andrew M. Kuchling85ab7382000-07-29 20:18:34 +0000103
Antoine Pitrou4ec4b0c2011-04-04 21:00:37 +0200104 def test_read1(self):
105 self.test_write()
106 blocks = []
107 nread = 0
108 with gzip.GzipFile(self.filename, 'r') as f:
109 while True:
110 d = f.read1()
111 if not d:
112 break
113 blocks.append(d)
114 nread += len(d)
115 # Check that position was updated correctly (see issue10791).
116 self.assertEqual(f.tell(), nread)
117 self.assertEqual(b''.join(blocks), data1 * 50)
118
Antoine Pitrou7980eaa2010-10-06 21:21:18 +0000119 def test_io_on_closed_object(self):
120 # Test that I/O operations on closed GzipFile objects raise a
121 # ValueError, just like the corresponding functions on file objects.
122
123 # Write to a file, open it for reading, then close it.
124 self.test_write()
125 f = gzip.GzipFile(self.filename, 'r')
Antoine Pitrou2dbc6e62015-04-11 00:31:01 +0200126 fileobj = f.fileobj
127 self.assertFalse(fileobj.closed)
Antoine Pitrou7980eaa2010-10-06 21:21:18 +0000128 f.close()
Antoine Pitrou2dbc6e62015-04-11 00:31:01 +0200129 self.assertTrue(fileobj.closed)
Antoine Pitrou7980eaa2010-10-06 21:21:18 +0000130 with self.assertRaises(ValueError):
131 f.read(1)
132 with self.assertRaises(ValueError):
133 f.seek(0)
134 with self.assertRaises(ValueError):
135 f.tell()
136 # Open the file for writing, then close it.
137 f = gzip.GzipFile(self.filename, 'w')
Antoine Pitrou2dbc6e62015-04-11 00:31:01 +0200138 fileobj = f.fileobj
139 self.assertFalse(fileobj.closed)
Antoine Pitrou7980eaa2010-10-06 21:21:18 +0000140 f.close()
Antoine Pitrou2dbc6e62015-04-11 00:31:01 +0200141 self.assertTrue(fileobj.closed)
Antoine Pitrou7980eaa2010-10-06 21:21:18 +0000142 with self.assertRaises(ValueError):
143 f.write(b'')
144 with self.assertRaises(ValueError):
145 f.flush()
146
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000147 def test_append(self):
148 self.test_write()
149 # Append to the previous file
Brian Curtin28f96b52010-10-13 02:21:42 +0000150 with gzip.GzipFile(self.filename, 'ab') as f:
151 f.write(data2 * 15)
Andrew M. Kuchling85ab7382000-07-29 20:18:34 +0000152
Brian Curtin28f96b52010-10-13 02:21:42 +0000153 with gzip.GzipFile(self.filename, 'rb') as f:
154 d = f.read()
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000155 self.assertEqual(d, (data1*50) + (data2*15))
Andrew M. Kuchling85ab7382000-07-29 20:18:34 +0000156
Andrew M. Kuchling01cb47b2005-06-09 14:19:32 +0000157 def test_many_append(self):
158 # Bug #1074261 was triggered when reading a file that contained
159 # many, many members. Create such a file and verify that reading it
160 # works.
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200161 with gzip.GzipFile(self.filename, 'wb', 9) as f:
Walter Dörwald5b1284d2007-06-06 16:43:59 +0000162 f.write(b'a')
Brian Curtin28f96b52010-10-13 02:21:42 +0000163 for i in range(0, 200):
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200164 with gzip.GzipFile(self.filename, "ab", 9) as f: # append
Brian Curtin28f96b52010-10-13 02:21:42 +0000165 f.write(b'a')
Andrew M. Kuchling01cb47b2005-06-09 14:19:32 +0000166
167 # Try reading the file
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200168 with gzip.GzipFile(self.filename, "rb") as zgfile:
Brian Curtin28f96b52010-10-13 02:21:42 +0000169 contents = b""
170 while 1:
171 ztxt = zgfile.read(8192)
172 contents += ztxt
173 if not ztxt: break
Ezio Melottib3aedd42010-11-20 19:04:17 +0000174 self.assertEqual(contents, b'a'*201)
Andrew M. Kuchling01cb47b2005-06-09 14:19:32 +0000175
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200176 def test_exclusive_write(self):
177 with gzip.GzipFile(self.filename, 'xb') as f:
178 f.write(data1 * 50)
179 with gzip.GzipFile(self.filename, 'rb') as f:
180 self.assertEqual(f.read(), data1 * 50)
181 with self.assertRaises(FileExistsError):
182 gzip.GzipFile(self.filename, 'xb')
183
Antoine Pitroub1f88352010-01-03 22:37:40 +0000184 def test_buffered_reader(self):
185 # Issue #7471: a GzipFile can be wrapped in a BufferedReader for
186 # performance.
187 self.test_write()
188
Brian Curtin28f96b52010-10-13 02:21:42 +0000189 with gzip.GzipFile(self.filename, 'rb') as f:
190 with io.BufferedReader(f) as r:
191 lines = [line for line in r]
Antoine Pitroub1f88352010-01-03 22:37:40 +0000192
Ezio Melottid8b509b2011-09-28 17:37:55 +0300193 self.assertEqual(lines, 50 * data1.splitlines(keepends=True))
Andrew M. Kuchling01cb47b2005-06-09 14:19:32 +0000194
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000195 def test_readline(self):
196 self.test_write()
197 # Try .readline() with varying line lengths
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000198
Brian Curtin28f96b52010-10-13 02:21:42 +0000199 with gzip.GzipFile(self.filename, 'rb') as f:
200 line_length = 0
201 while 1:
202 L = f.readline(line_length)
203 if not L and line_length != 0: break
204 self.assertTrue(len(L) <= line_length)
205 line_length = (line_length + 1) % 50
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000206
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000207 def test_readlines(self):
208 self.test_write()
209 # Try .readlines()
Andrew M. Kuchling605ebdd1999-03-25 21:50:27 +0000210
Brian Curtin28f96b52010-10-13 02:21:42 +0000211 with gzip.GzipFile(self.filename, 'rb') as f:
212 L = f.readlines()
Skip Montanaro12424bc2002-05-23 01:43:05 +0000213
Brian Curtin28f96b52010-10-13 02:21:42 +0000214 with gzip.GzipFile(self.filename, 'rb') as f:
215 while 1:
216 L = f.readlines(150)
217 if L == []: break
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000218
219 def test_seek_read(self):
220 self.test_write()
221 # Try seek, read test
222
Brian Curtin28f96b52010-10-13 02:21:42 +0000223 with gzip.GzipFile(self.filename) as f:
224 while 1:
225 oldpos = f.tell()
226 line1 = f.readline()
227 if not line1: break
228 newpos = f.tell()
229 f.seek(oldpos) # negative seek
230 if len(line1)>10:
231 amount = 10
232 else:
233 amount = len(line1)
234 line2 = f.read(amount)
235 self.assertEqual(line1[:amount], line2)
236 f.seek(newpos) # positive seek
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000237
Thomas Wouters89f507f2006-12-13 04:49:30 +0000238 def test_seek_whence(self):
239 self.test_write()
240 # Try seek(whence=1), read test
241
Brian Curtin28f96b52010-10-13 02:21:42 +0000242 with gzip.GzipFile(self.filename) as f:
243 f.read(10)
244 f.seek(10, whence=1)
245 y = f.read(10)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000246 self.assertEqual(y, data1[20:30])
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000247
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000248 def test_seek_write(self):
249 # Try seek, write test
Brian Curtin28f96b52010-10-13 02:21:42 +0000250 with gzip.GzipFile(self.filename, 'w') as f:
251 for pos in range(0, 256, 16):
252 f.seek(pos)
253 f.write(b'GZ\n')
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000254
255 def test_mode(self):
256 self.test_write()
Brian Curtin28f96b52010-10-13 02:21:42 +0000257 with gzip.GzipFile(self.filename, 'r') as f:
258 self.assertEqual(f.myfileobj.mode, 'rb')
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200259 support.unlink(self.filename)
260 with gzip.GzipFile(self.filename, 'x') as f:
261 self.assertEqual(f.myfileobj.mode, 'xb')
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000262
Thomas Wouterscf297e42007-02-23 15:07:44 +0000263 def test_1647484(self):
264 for mode in ('wb', 'rb'):
Brian Curtin28f96b52010-10-13 02:21:42 +0000265 with gzip.GzipFile(self.filename, mode) as f:
266 self.assertTrue(hasattr(f, "name"))
267 self.assertEqual(f.name, self.filename)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000268
Georg Brandl9f1c1dc2010-11-20 11:25:01 +0000269 def test_paddedfile_getattr(self):
270 self.test_write()
271 with gzip.GzipFile(self.filename, 'rb') as f:
272 self.assertTrue(hasattr(f.fileobj, "name"))
273 self.assertEqual(f.fileobj.name, self.filename)
274
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000275 def test_mtime(self):
276 mtime = 123456789
Brian Curtin28f96b52010-10-13 02:21:42 +0000277 with gzip.GzipFile(self.filename, 'w', mtime = mtime) as fWrite:
278 fWrite.write(data1)
279 with gzip.GzipFile(self.filename) as fRead:
Antoine Pitrou2dbc6e62015-04-11 00:31:01 +0200280 self.assertTrue(hasattr(fRead, 'mtime'))
281 self.assertIsNone(fRead.mtime)
Brian Curtin28f96b52010-10-13 02:21:42 +0000282 dataRead = fRead.read()
283 self.assertEqual(dataRead, data1)
Brian Curtin28f96b52010-10-13 02:21:42 +0000284 self.assertEqual(fRead.mtime, mtime)
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000285
286 def test_metadata(self):
287 mtime = 123456789
288
Brian Curtin28f96b52010-10-13 02:21:42 +0000289 with gzip.GzipFile(self.filename, 'w', mtime = mtime) as fWrite:
290 fWrite.write(data1)
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000291
Brian Curtin28f96b52010-10-13 02:21:42 +0000292 with open(self.filename, 'rb') as fRead:
293 # see RFC 1952: http://www.faqs.org/rfcs/rfc1952.html
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000294
Brian Curtin28f96b52010-10-13 02:21:42 +0000295 idBytes = fRead.read(2)
296 self.assertEqual(idBytes, b'\x1f\x8b') # gzip ID
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000297
Brian Curtin28f96b52010-10-13 02:21:42 +0000298 cmByte = fRead.read(1)
299 self.assertEqual(cmByte, b'\x08') # deflate
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000300
Brian Curtin28f96b52010-10-13 02:21:42 +0000301 flagsByte = fRead.read(1)
302 self.assertEqual(flagsByte, b'\x08') # only the FNAME flag is set
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000303
Brian Curtin28f96b52010-10-13 02:21:42 +0000304 mtimeBytes = fRead.read(4)
305 self.assertEqual(mtimeBytes, struct.pack('<i', mtime)) # little-endian
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000306
Brian Curtin28f96b52010-10-13 02:21:42 +0000307 xflByte = fRead.read(1)
308 self.assertEqual(xflByte, b'\x02') # maximum compression
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000309
Brian Curtin28f96b52010-10-13 02:21:42 +0000310 osByte = fRead.read(1)
311 self.assertEqual(osByte, b'\xff') # OS "unknown" (OS-independent)
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000312
Brian Curtin28f96b52010-10-13 02:21:42 +0000313 # Since the FNAME flag is set, the zero-terminated filename follows.
314 # RFC 1952 specifies that this is the name of the input file, if any.
315 # However, the gzip module defaults to storing the name of the output
316 # file in this field.
317 expected = self.filename.encode('Latin-1') + b'\x00'
318 nameBytes = fRead.read(len(expected))
319 self.assertEqual(nameBytes, expected)
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000320
Brian Curtin28f96b52010-10-13 02:21:42 +0000321 # Since no other flags were set, the header ends here.
322 # Rather than process the compressed data, let's seek to the trailer.
323 fRead.seek(os.stat(self.filename).st_size - 8)
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000324
Brian Curtin28f96b52010-10-13 02:21:42 +0000325 crc32Bytes = fRead.read(4) # CRC32 of uncompressed data [data1]
326 self.assertEqual(crc32Bytes, b'\xaf\xd7d\x83')
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000327
Brian Curtin28f96b52010-10-13 02:21:42 +0000328 isizeBytes = fRead.read(4)
329 self.assertEqual(isizeBytes, struct.pack('<i', len(data1)))
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000330
Antoine Pitrou308705e2009-01-10 16:22:51 +0000331 def test_with_open(self):
332 # GzipFile supports the context management protocol
333 with gzip.GzipFile(self.filename, "wb") as f:
334 f.write(b"xxx")
335 f = gzip.GzipFile(self.filename, "rb")
336 f.close()
337 try:
338 with f:
339 pass
340 except ValueError:
341 pass
342 else:
343 self.fail("__enter__ on a closed file didn't raise an exception")
344 try:
345 with gzip.GzipFile(self.filename, "wb") as f:
346 1/0
347 except ZeroDivisionError:
348 pass
349 else:
350 self.fail("1/0 didn't raise an exception")
351
Antoine Pitrou8e33fd72010-01-13 14:37:26 +0000352 def test_zero_padded_file(self):
353 with gzip.GzipFile(self.filename, "wb") as f:
354 f.write(data1 * 50)
355
356 # Pad the file with zeroes
357 with open(self.filename, "ab") as f:
358 f.write(b"\x00" * 50)
359
360 with gzip.GzipFile(self.filename, "rb") as f:
361 d = f.read()
362 self.assertEqual(d, data1 * 50, "Incorrect data in file")
363
Antoine Pitrou7b969842010-09-23 16:22:51 +0000364 def test_non_seekable_file(self):
365 uncompressed = data1 * 50
366 buf = UnseekableIO()
367 with gzip.GzipFile(fileobj=buf, mode="wb") as f:
368 f.write(uncompressed)
369 compressed = buf.getvalue()
370 buf = UnseekableIO(compressed)
371 with gzip.GzipFile(fileobj=buf, mode="rb") as f:
372 self.assertEqual(f.read(), uncompressed)
373
Antoine Pitrouc3ed2e72010-09-29 10:49:46 +0000374 def test_peek(self):
375 uncompressed = data1 * 200
376 with gzip.GzipFile(self.filename, "wb") as f:
377 f.write(uncompressed)
378
379 def sizes():
380 while True:
381 for n in range(5, 50, 10):
382 yield n
383
384 with gzip.GzipFile(self.filename, "rb") as f:
385 f.max_read_chunk = 33
386 nread = 0
387 for n in sizes():
388 s = f.peek(n)
389 if s == b'':
390 break
391 self.assertEqual(f.read(len(s)), s)
392 nread += len(s)
393 self.assertEqual(f.read(100), b'')
394 self.assertEqual(nread, len(uncompressed))
395
Antoine Pitrou4ec4b0c2011-04-04 21:00:37 +0200396 def test_textio_readlines(self):
397 # Issue #10791: TextIOWrapper.readlines() fails when wrapping GzipFile.
Ezio Melottid8b509b2011-09-28 17:37:55 +0300398 lines = (data1 * 50).decode("ascii").splitlines(keepends=True)
Antoine Pitrou4ec4b0c2011-04-04 21:00:37 +0200399 self.test_write()
400 with gzip.GzipFile(self.filename, 'r') as f:
401 with io.TextIOWrapper(f, encoding="ascii") as t:
402 self.assertEqual(t.readlines(), lines)
403
Nadeem Vawda892b0b92012-01-18 09:25:58 +0200404 def test_fileobj_from_fdopen(self):
405 # Issue #13781: Opening a GzipFile for writing fails when using a
406 # fileobj created with os.fdopen().
407 fd = os.open(self.filename, os.O_WRONLY | os.O_CREAT)
408 with os.fdopen(fd, "wb") as f:
409 with gzip.GzipFile(fileobj=f, mode="w") as g:
410 pass
411
Nadeem Vawda103e8112012-06-20 01:35:22 +0200412 def test_bytes_filename(self):
413 str_filename = self.filename
414 try:
415 bytes_filename = str_filename.encode("ascii")
416 except UnicodeEncodeError:
417 self.skipTest("Temporary file name needs to be ASCII")
418 with gzip.GzipFile(bytes_filename, "wb") as f:
419 f.write(data1 * 50)
420 with gzip.GzipFile(bytes_filename, "rb") as f:
421 self.assertEqual(f.read(), data1 * 50)
422 # Sanity check that we are actually operating on the right file.
423 with gzip.GzipFile(str_filename, "rb") as f:
424 self.assertEqual(f.read(), data1 * 50)
425
Antoine Pitrou2dbc6e62015-04-11 00:31:01 +0200426 def test_decompress_limited(self):
427 """Decompressed data buffering should be limited"""
428 bomb = gzip.compress(bytes(int(2e6)), compresslevel=9)
429 self.assertLess(len(bomb), io.DEFAULT_BUFFER_SIZE)
430
431 bomb = io.BytesIO(bomb)
432 decomp = gzip.GzipFile(fileobj=bomb)
433 self.assertEqual(bytes(1), decomp.read(1))
434 max_decomp = 1 + io.DEFAULT_BUFFER_SIZE
435 self.assertLessEqual(decomp._buffer.raw.tell(), max_decomp,
436 "Excessive amount of data was decompressed")
437
Antoine Pitrou79c5ef12010-08-17 21:10:05 +0000438 # Testing compress/decompress shortcut functions
439
440 def test_compress(self):
441 for data in [data1, data2]:
442 for args in [(), (1,), (6,), (9,)]:
443 datac = gzip.compress(data, *args)
444 self.assertEqual(type(datac), bytes)
445 with gzip.GzipFile(fileobj=io.BytesIO(datac), mode="rb") as f:
446 self.assertEqual(f.read(), data)
447
448 def test_decompress(self):
449 for data in (data1, data2):
450 buf = io.BytesIO()
451 with gzip.GzipFile(fileobj=buf, mode="wb") as f:
452 f.write(data)
453 self.assertEqual(gzip.decompress(buf.getvalue()), data)
454 # Roundtrip with compress
455 datac = gzip.compress(data)
456 self.assertEqual(gzip.decompress(datac), data)
457
Serhiy Storchaka7c3922f2013-01-22 17:01:59 +0200458 def test_read_truncated(self):
459 data = data1*50
460 # Drop the CRC (4 bytes) and file size (4 bytes).
461 truncated = gzip.compress(data)[:-8]
462 with gzip.GzipFile(fileobj=io.BytesIO(truncated)) as f:
463 self.assertRaises(EOFError, f.read)
464 with gzip.GzipFile(fileobj=io.BytesIO(truncated)) as f:
465 self.assertEqual(f.read(len(data)), data)
466 self.assertRaises(EOFError, f.read, 1)
467 # Incomplete 10-byte header.
468 for i in range(2, 10):
469 with gzip.GzipFile(fileobj=io.BytesIO(truncated[:i])) as f:
470 self.assertRaises(EOFError, f.read, 1)
471
Serhiy Storchaka7e69f002013-04-08 22:35:02 +0300472 def test_read_with_extra(self):
473 # Gzip data with an extra field
474 gzdata = (b'\x1f\x8b\x08\x04\xb2\x17cQ\x02\xff'
475 b'\x05\x00Extra'
476 b'\x0bI-.\x01\x002\xd1Mx\x04\x00\x00\x00')
477 with gzip.GzipFile(fileobj=io.BytesIO(gzdata)) as f:
478 self.assertEqual(f.read(), b'Test')
Nadeem Vawda7e126202012-05-06 15:04:01 +0200479
Ned Deily61207392014-03-09 14:44:34 -0700480 def test_prepend_error(self):
481 # See issue #20875
482 with gzip.open(self.filename, "wb") as f:
483 f.write(data1)
484 with gzip.open(self.filename, "rb") as f:
Antoine Pitrou2dbc6e62015-04-11 00:31:01 +0200485 f._buffer.raw._fp.prepend()
Ned Deily61207392014-03-09 14:44:34 -0700486
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200487class TestOpen(BaseTest):
488 def test_binary_modes(self):
Nadeem Vawda7e126202012-05-06 15:04:01 +0200489 uncompressed = data1 * 50
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200490
Nadeem Vawda7e126202012-05-06 15:04:01 +0200491 with gzip.open(self.filename, "wb") as f:
492 f.write(uncompressed)
493 with open(self.filename, "rb") as f:
494 file_data = gzip.decompress(f.read())
495 self.assertEqual(file_data, uncompressed)
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200496
Nadeem Vawda7e126202012-05-06 15:04:01 +0200497 with gzip.open(self.filename, "rb") as f:
498 self.assertEqual(f.read(), uncompressed)
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200499
Nadeem Vawda7e126202012-05-06 15:04:01 +0200500 with gzip.open(self.filename, "ab") as f:
501 f.write(uncompressed)
502 with open(self.filename, "rb") as f:
503 file_data = gzip.decompress(f.read())
504 self.assertEqual(file_data, uncompressed * 2)
505
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200506 with self.assertRaises(FileExistsError):
507 gzip.open(self.filename, "xb")
508 support.unlink(self.filename)
509 with gzip.open(self.filename, "xb") as f:
510 f.write(uncompressed)
511 with open(self.filename, "rb") as f:
512 file_data = gzip.decompress(f.read())
513 self.assertEqual(file_data, uncompressed)
514
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200515 def test_implicit_binary_modes(self):
Nadeem Vawda7e126202012-05-06 15:04:01 +0200516 # Test implicit binary modes (no "b" or "t" in mode string).
517 uncompressed = data1 * 50
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200518
Nadeem Vawda7e126202012-05-06 15:04:01 +0200519 with gzip.open(self.filename, "w") as f:
520 f.write(uncompressed)
521 with open(self.filename, "rb") as f:
522 file_data = gzip.decompress(f.read())
523 self.assertEqual(file_data, uncompressed)
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200524
Nadeem Vawda7e126202012-05-06 15:04:01 +0200525 with gzip.open(self.filename, "r") as f:
526 self.assertEqual(f.read(), uncompressed)
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200527
Nadeem Vawda7e126202012-05-06 15:04:01 +0200528 with gzip.open(self.filename, "a") as f:
529 f.write(uncompressed)
530 with open(self.filename, "rb") as f:
531 file_data = gzip.decompress(f.read())
532 self.assertEqual(file_data, uncompressed * 2)
533
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200534 with self.assertRaises(FileExistsError):
535 gzip.open(self.filename, "x")
536 support.unlink(self.filename)
537 with gzip.open(self.filename, "x") as f:
538 f.write(uncompressed)
539 with open(self.filename, "rb") as f:
540 file_data = gzip.decompress(f.read())
541 self.assertEqual(file_data, uncompressed)
542
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200543 def test_text_modes(self):
Nadeem Vawda11328e42012-05-06 19:24:18 +0200544 uncompressed = data1.decode("ascii") * 50
545 uncompressed_raw = uncompressed.replace("\n", os.linesep)
Nadeem Vawda7e126202012-05-06 15:04:01 +0200546 with gzip.open(self.filename, "wt") as f:
547 f.write(uncompressed)
548 with open(self.filename, "rb") as f:
549 file_data = gzip.decompress(f.read()).decode("ascii")
Nadeem Vawda11328e42012-05-06 19:24:18 +0200550 self.assertEqual(file_data, uncompressed_raw)
Nadeem Vawda7e126202012-05-06 15:04:01 +0200551 with gzip.open(self.filename, "rt") as f:
552 self.assertEqual(f.read(), uncompressed)
553 with gzip.open(self.filename, "at") as f:
554 f.write(uncompressed)
555 with open(self.filename, "rb") as f:
556 file_data = gzip.decompress(f.read()).decode("ascii")
Nadeem Vawda11328e42012-05-06 19:24:18 +0200557 self.assertEqual(file_data, uncompressed_raw * 2)
Nadeem Vawda7e126202012-05-06 15:04:01 +0200558
Nadeem Vawda68721012012-06-04 23:21:38 +0200559 def test_fileobj(self):
560 uncompressed_bytes = data1 * 50
561 uncompressed_str = uncompressed_bytes.decode("ascii")
562 compressed = gzip.compress(uncompressed_bytes)
563 with gzip.open(io.BytesIO(compressed), "r") as f:
564 self.assertEqual(f.read(), uncompressed_bytes)
565 with gzip.open(io.BytesIO(compressed), "rb") as f:
566 self.assertEqual(f.read(), uncompressed_bytes)
567 with gzip.open(io.BytesIO(compressed), "rt") as f:
568 self.assertEqual(f.read(), uncompressed_str)
569
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200570 def test_bad_params(self):
Nadeem Vawda7e126202012-05-06 15:04:01 +0200571 # Test invalid parameter combinations.
Nadeem Vawda68721012012-06-04 23:21:38 +0200572 with self.assertRaises(TypeError):
573 gzip.open(123.456)
Nadeem Vawda7e126202012-05-06 15:04:01 +0200574 with self.assertRaises(ValueError):
575 gzip.open(self.filename, "wbt")
576 with self.assertRaises(ValueError):
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200577 gzip.open(self.filename, "xbt")
578 with self.assertRaises(ValueError):
Nadeem Vawda7e126202012-05-06 15:04:01 +0200579 gzip.open(self.filename, "rb", encoding="utf-8")
580 with self.assertRaises(ValueError):
581 gzip.open(self.filename, "rb", errors="ignore")
582 with self.assertRaises(ValueError):
583 gzip.open(self.filename, "rb", newline="\n")
584
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200585 def test_encoding(self):
Nadeem Vawda7e126202012-05-06 15:04:01 +0200586 # Test non-default encoding.
Nadeem Vawda11328e42012-05-06 19:24:18 +0200587 uncompressed = data1.decode("ascii") * 50
588 uncompressed_raw = uncompressed.replace("\n", os.linesep)
Nadeem Vawda7e126202012-05-06 15:04:01 +0200589 with gzip.open(self.filename, "wt", encoding="utf-16") as f:
590 f.write(uncompressed)
591 with open(self.filename, "rb") as f:
592 file_data = gzip.decompress(f.read()).decode("utf-16")
Nadeem Vawda11328e42012-05-06 19:24:18 +0200593 self.assertEqual(file_data, uncompressed_raw)
Nadeem Vawda7e126202012-05-06 15:04:01 +0200594 with gzip.open(self.filename, "rt", encoding="utf-16") as f:
595 self.assertEqual(f.read(), uncompressed)
596
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200597 def test_encoding_error_handler(self):
Nadeem Vawda7e126202012-05-06 15:04:01 +0200598 # Test with non-default encoding error handler.
599 with gzip.open(self.filename, "wb") as f:
600 f.write(b"foo\xffbar")
601 with gzip.open(self.filename, "rt", encoding="ascii", errors="ignore") \
602 as f:
603 self.assertEqual(f.read(), "foobar")
604
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200605 def test_newline(self):
Nadeem Vawda7e126202012-05-06 15:04:01 +0200606 # Test with explicit newline (universal newline mode disabled).
607 uncompressed = data1.decode("ascii") * 50
Nadeem Vawda9d9dc8e2012-05-06 16:25:35 +0200608 with gzip.open(self.filename, "wt", newline="\n") as f:
Nadeem Vawda7e126202012-05-06 15:04:01 +0200609 f.write(uncompressed)
610 with gzip.open(self.filename, "rt", newline="\r") as f:
611 self.assertEqual(f.readlines(), [uncompressed])
612
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000613def test_main(verbose=None):
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200614 support.run_unittest(TestGzip, TestOpen)
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000615
616if __name__ == "__main__":
617 test_main(verbose=True)