blob: c0be3a1f2ddfd43bc15f5ea26808c24a22aae229 [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')
126 f.close()
127 with self.assertRaises(ValueError):
128 f.read(1)
129 with self.assertRaises(ValueError):
130 f.seek(0)
131 with self.assertRaises(ValueError):
132 f.tell()
133 # Open the file for writing, then close it.
134 f = gzip.GzipFile(self.filename, 'w')
135 f.close()
136 with self.assertRaises(ValueError):
137 f.write(b'')
138 with self.assertRaises(ValueError):
139 f.flush()
140
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000141 def test_append(self):
142 self.test_write()
143 # Append to the previous file
Brian Curtin28f96b52010-10-13 02:21:42 +0000144 with gzip.GzipFile(self.filename, 'ab') as f:
145 f.write(data2 * 15)
Andrew M. Kuchling85ab7382000-07-29 20:18:34 +0000146
Brian Curtin28f96b52010-10-13 02:21:42 +0000147 with gzip.GzipFile(self.filename, 'rb') as f:
148 d = f.read()
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000149 self.assertEqual(d, (data1*50) + (data2*15))
Andrew M. Kuchling85ab7382000-07-29 20:18:34 +0000150
Andrew M. Kuchling01cb47b2005-06-09 14:19:32 +0000151 def test_many_append(self):
152 # Bug #1074261 was triggered when reading a file that contained
153 # many, many members. Create such a file and verify that reading it
154 # works.
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200155 with gzip.GzipFile(self.filename, 'wb', 9) as f:
Walter Dörwald5b1284d2007-06-06 16:43:59 +0000156 f.write(b'a')
Brian Curtin28f96b52010-10-13 02:21:42 +0000157 for i in range(0, 200):
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200158 with gzip.GzipFile(self.filename, "ab", 9) as f: # append
Brian Curtin28f96b52010-10-13 02:21:42 +0000159 f.write(b'a')
Andrew M. Kuchling01cb47b2005-06-09 14:19:32 +0000160
161 # Try reading the file
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200162 with gzip.GzipFile(self.filename, "rb") as zgfile:
Brian Curtin28f96b52010-10-13 02:21:42 +0000163 contents = b""
164 while 1:
165 ztxt = zgfile.read(8192)
166 contents += ztxt
167 if not ztxt: break
Ezio Melottib3aedd42010-11-20 19:04:17 +0000168 self.assertEqual(contents, b'a'*201)
Andrew M. Kuchling01cb47b2005-06-09 14:19:32 +0000169
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200170 def test_exclusive_write(self):
171 with gzip.GzipFile(self.filename, 'xb') as f:
172 f.write(data1 * 50)
173 with gzip.GzipFile(self.filename, 'rb') as f:
174 self.assertEqual(f.read(), data1 * 50)
175 with self.assertRaises(FileExistsError):
176 gzip.GzipFile(self.filename, 'xb')
177
Antoine Pitroub1f88352010-01-03 22:37:40 +0000178 def test_buffered_reader(self):
179 # Issue #7471: a GzipFile can be wrapped in a BufferedReader for
180 # performance.
181 self.test_write()
182
Brian Curtin28f96b52010-10-13 02:21:42 +0000183 with gzip.GzipFile(self.filename, 'rb') as f:
184 with io.BufferedReader(f) as r:
185 lines = [line for line in r]
Antoine Pitroub1f88352010-01-03 22:37:40 +0000186
Ezio Melottid8b509b2011-09-28 17:37:55 +0300187 self.assertEqual(lines, 50 * data1.splitlines(keepends=True))
Andrew M. Kuchling01cb47b2005-06-09 14:19:32 +0000188
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000189 def test_readline(self):
190 self.test_write()
191 # Try .readline() with varying line lengths
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000192
Brian Curtin28f96b52010-10-13 02:21:42 +0000193 with gzip.GzipFile(self.filename, 'rb') as f:
194 line_length = 0
195 while 1:
196 L = f.readline(line_length)
197 if not L and line_length != 0: break
198 self.assertTrue(len(L) <= line_length)
199 line_length = (line_length + 1) % 50
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000200
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000201 def test_readlines(self):
202 self.test_write()
203 # Try .readlines()
Andrew M. Kuchling605ebdd1999-03-25 21:50:27 +0000204
Brian Curtin28f96b52010-10-13 02:21:42 +0000205 with gzip.GzipFile(self.filename, 'rb') as f:
206 L = f.readlines()
Skip Montanaro12424bc2002-05-23 01:43:05 +0000207
Brian Curtin28f96b52010-10-13 02:21:42 +0000208 with gzip.GzipFile(self.filename, 'rb') as f:
209 while 1:
210 L = f.readlines(150)
211 if L == []: break
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000212
213 def test_seek_read(self):
214 self.test_write()
215 # Try seek, read test
216
Brian Curtin28f96b52010-10-13 02:21:42 +0000217 with gzip.GzipFile(self.filename) as f:
218 while 1:
219 oldpos = f.tell()
220 line1 = f.readline()
221 if not line1: break
222 newpos = f.tell()
223 f.seek(oldpos) # negative seek
224 if len(line1)>10:
225 amount = 10
226 else:
227 amount = len(line1)
228 line2 = f.read(amount)
229 self.assertEqual(line1[:amount], line2)
230 f.seek(newpos) # positive seek
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000231
Thomas Wouters89f507f2006-12-13 04:49:30 +0000232 def test_seek_whence(self):
233 self.test_write()
234 # Try seek(whence=1), read test
235
Brian Curtin28f96b52010-10-13 02:21:42 +0000236 with gzip.GzipFile(self.filename) as f:
237 f.read(10)
238 f.seek(10, whence=1)
239 y = f.read(10)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000240 self.assertEqual(y, data1[20:30])
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000241
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000242 def test_seek_write(self):
243 # Try seek, write test
Brian Curtin28f96b52010-10-13 02:21:42 +0000244 with gzip.GzipFile(self.filename, 'w') as f:
245 for pos in range(0, 256, 16):
246 f.seek(pos)
247 f.write(b'GZ\n')
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000248
249 def test_mode(self):
250 self.test_write()
Brian Curtin28f96b52010-10-13 02:21:42 +0000251 with gzip.GzipFile(self.filename, 'r') as f:
252 self.assertEqual(f.myfileobj.mode, 'rb')
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200253 support.unlink(self.filename)
254 with gzip.GzipFile(self.filename, 'x') as f:
255 self.assertEqual(f.myfileobj.mode, 'xb')
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000256
Thomas Wouterscf297e42007-02-23 15:07:44 +0000257 def test_1647484(self):
258 for mode in ('wb', 'rb'):
Brian Curtin28f96b52010-10-13 02:21:42 +0000259 with gzip.GzipFile(self.filename, mode) as f:
260 self.assertTrue(hasattr(f, "name"))
261 self.assertEqual(f.name, self.filename)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000262
Georg Brandl9f1c1dc2010-11-20 11:25:01 +0000263 def test_paddedfile_getattr(self):
264 self.test_write()
265 with gzip.GzipFile(self.filename, 'rb') as f:
266 self.assertTrue(hasattr(f.fileobj, "name"))
267 self.assertEqual(f.fileobj.name, self.filename)
268
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000269 def test_mtime(self):
270 mtime = 123456789
Brian Curtin28f96b52010-10-13 02:21:42 +0000271 with gzip.GzipFile(self.filename, 'w', mtime = mtime) as fWrite:
272 fWrite.write(data1)
273 with gzip.GzipFile(self.filename) as fRead:
274 dataRead = fRead.read()
275 self.assertEqual(dataRead, data1)
276 self.assertTrue(hasattr(fRead, 'mtime'))
277 self.assertEqual(fRead.mtime, mtime)
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000278
279 def test_metadata(self):
280 mtime = 123456789
281
Brian Curtin28f96b52010-10-13 02:21:42 +0000282 with gzip.GzipFile(self.filename, 'w', mtime = mtime) as fWrite:
283 fWrite.write(data1)
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000284
Brian Curtin28f96b52010-10-13 02:21:42 +0000285 with open(self.filename, 'rb') as fRead:
286 # see RFC 1952: http://www.faqs.org/rfcs/rfc1952.html
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000287
Brian Curtin28f96b52010-10-13 02:21:42 +0000288 idBytes = fRead.read(2)
289 self.assertEqual(idBytes, b'\x1f\x8b') # gzip ID
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000290
Brian Curtin28f96b52010-10-13 02:21:42 +0000291 cmByte = fRead.read(1)
292 self.assertEqual(cmByte, b'\x08') # deflate
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000293
Brian Curtin28f96b52010-10-13 02:21:42 +0000294 flagsByte = fRead.read(1)
295 self.assertEqual(flagsByte, b'\x08') # only the FNAME flag is set
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000296
Brian Curtin28f96b52010-10-13 02:21:42 +0000297 mtimeBytes = fRead.read(4)
298 self.assertEqual(mtimeBytes, struct.pack('<i', mtime)) # little-endian
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000299
Brian Curtin28f96b52010-10-13 02:21:42 +0000300 xflByte = fRead.read(1)
301 self.assertEqual(xflByte, b'\x02') # maximum compression
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000302
Brian Curtin28f96b52010-10-13 02:21:42 +0000303 osByte = fRead.read(1)
304 self.assertEqual(osByte, b'\xff') # OS "unknown" (OS-independent)
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000305
Brian Curtin28f96b52010-10-13 02:21:42 +0000306 # Since the FNAME flag is set, the zero-terminated filename follows.
307 # RFC 1952 specifies that this is the name of the input file, if any.
308 # However, the gzip module defaults to storing the name of the output
309 # file in this field.
310 expected = self.filename.encode('Latin-1') + b'\x00'
311 nameBytes = fRead.read(len(expected))
312 self.assertEqual(nameBytes, expected)
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000313
Brian Curtin28f96b52010-10-13 02:21:42 +0000314 # Since no other flags were set, the header ends here.
315 # Rather than process the compressed data, let's seek to the trailer.
316 fRead.seek(os.stat(self.filename).st_size - 8)
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000317
Brian Curtin28f96b52010-10-13 02:21:42 +0000318 crc32Bytes = fRead.read(4) # CRC32 of uncompressed data [data1]
319 self.assertEqual(crc32Bytes, b'\xaf\xd7d\x83')
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000320
Brian Curtin28f96b52010-10-13 02:21:42 +0000321 isizeBytes = fRead.read(4)
322 self.assertEqual(isizeBytes, struct.pack('<i', len(data1)))
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000323
Antoine Pitrou308705e2009-01-10 16:22:51 +0000324 def test_with_open(self):
325 # GzipFile supports the context management protocol
326 with gzip.GzipFile(self.filename, "wb") as f:
327 f.write(b"xxx")
328 f = gzip.GzipFile(self.filename, "rb")
329 f.close()
330 try:
331 with f:
332 pass
333 except ValueError:
334 pass
335 else:
336 self.fail("__enter__ on a closed file didn't raise an exception")
337 try:
338 with gzip.GzipFile(self.filename, "wb") as f:
339 1/0
340 except ZeroDivisionError:
341 pass
342 else:
343 self.fail("1/0 didn't raise an exception")
344
Antoine Pitrou8e33fd72010-01-13 14:37:26 +0000345 def test_zero_padded_file(self):
346 with gzip.GzipFile(self.filename, "wb") as f:
347 f.write(data1 * 50)
348
349 # Pad the file with zeroes
350 with open(self.filename, "ab") as f:
351 f.write(b"\x00" * 50)
352
353 with gzip.GzipFile(self.filename, "rb") as f:
354 d = f.read()
355 self.assertEqual(d, data1 * 50, "Incorrect data in file")
356
Antoine Pitrou7b969842010-09-23 16:22:51 +0000357 def test_non_seekable_file(self):
358 uncompressed = data1 * 50
359 buf = UnseekableIO()
360 with gzip.GzipFile(fileobj=buf, mode="wb") as f:
361 f.write(uncompressed)
362 compressed = buf.getvalue()
363 buf = UnseekableIO(compressed)
364 with gzip.GzipFile(fileobj=buf, mode="rb") as f:
365 self.assertEqual(f.read(), uncompressed)
366
Antoine Pitrouc3ed2e72010-09-29 10:49:46 +0000367 def test_peek(self):
368 uncompressed = data1 * 200
369 with gzip.GzipFile(self.filename, "wb") as f:
370 f.write(uncompressed)
371
372 def sizes():
373 while True:
374 for n in range(5, 50, 10):
375 yield n
376
377 with gzip.GzipFile(self.filename, "rb") as f:
378 f.max_read_chunk = 33
379 nread = 0
380 for n in sizes():
381 s = f.peek(n)
382 if s == b'':
383 break
384 self.assertEqual(f.read(len(s)), s)
385 nread += len(s)
386 self.assertEqual(f.read(100), b'')
387 self.assertEqual(nread, len(uncompressed))
388
Antoine Pitrou4ec4b0c2011-04-04 21:00:37 +0200389 def test_textio_readlines(self):
390 # Issue #10791: TextIOWrapper.readlines() fails when wrapping GzipFile.
Ezio Melottid8b509b2011-09-28 17:37:55 +0300391 lines = (data1 * 50).decode("ascii").splitlines(keepends=True)
Antoine Pitrou4ec4b0c2011-04-04 21:00:37 +0200392 self.test_write()
393 with gzip.GzipFile(self.filename, 'r') as f:
394 with io.TextIOWrapper(f, encoding="ascii") as t:
395 self.assertEqual(t.readlines(), lines)
396
Nadeem Vawda892b0b92012-01-18 09:25:58 +0200397 def test_fileobj_from_fdopen(self):
398 # Issue #13781: Opening a GzipFile for writing fails when using a
399 # fileobj created with os.fdopen().
400 fd = os.open(self.filename, os.O_WRONLY | os.O_CREAT)
401 with os.fdopen(fd, "wb") as f:
402 with gzip.GzipFile(fileobj=f, mode="w") as g:
403 pass
404
Nadeem Vawda103e8112012-06-20 01:35:22 +0200405 def test_bytes_filename(self):
406 str_filename = self.filename
407 try:
408 bytes_filename = str_filename.encode("ascii")
409 except UnicodeEncodeError:
410 self.skipTest("Temporary file name needs to be ASCII")
411 with gzip.GzipFile(bytes_filename, "wb") as f:
412 f.write(data1 * 50)
413 with gzip.GzipFile(bytes_filename, "rb") as f:
414 self.assertEqual(f.read(), data1 * 50)
415 # Sanity check that we are actually operating on the right file.
416 with gzip.GzipFile(str_filename, "rb") as f:
417 self.assertEqual(f.read(), data1 * 50)
418
Antoine Pitrou79c5ef12010-08-17 21:10:05 +0000419 # Testing compress/decompress shortcut functions
420
421 def test_compress(self):
422 for data in [data1, data2]:
423 for args in [(), (1,), (6,), (9,)]:
424 datac = gzip.compress(data, *args)
425 self.assertEqual(type(datac), bytes)
426 with gzip.GzipFile(fileobj=io.BytesIO(datac), mode="rb") as f:
427 self.assertEqual(f.read(), data)
428
429 def test_decompress(self):
430 for data in (data1, data2):
431 buf = io.BytesIO()
432 with gzip.GzipFile(fileobj=buf, mode="wb") as f:
433 f.write(data)
434 self.assertEqual(gzip.decompress(buf.getvalue()), data)
435 # Roundtrip with compress
436 datac = gzip.compress(data)
437 self.assertEqual(gzip.decompress(datac), data)
438
Serhiy Storchaka7c3922f2013-01-22 17:01:59 +0200439 def test_read_truncated(self):
440 data = data1*50
441 # Drop the CRC (4 bytes) and file size (4 bytes).
442 truncated = gzip.compress(data)[:-8]
443 with gzip.GzipFile(fileobj=io.BytesIO(truncated)) as f:
444 self.assertRaises(EOFError, f.read)
445 with gzip.GzipFile(fileobj=io.BytesIO(truncated)) as f:
446 self.assertEqual(f.read(len(data)), data)
447 self.assertRaises(EOFError, f.read, 1)
448 # Incomplete 10-byte header.
449 for i in range(2, 10):
450 with gzip.GzipFile(fileobj=io.BytesIO(truncated[:i])) as f:
451 self.assertRaises(EOFError, f.read, 1)
452
Serhiy Storchaka7e69f002013-04-08 22:35:02 +0300453 def test_read_with_extra(self):
454 # Gzip data with an extra field
455 gzdata = (b'\x1f\x8b\x08\x04\xb2\x17cQ\x02\xff'
456 b'\x05\x00Extra'
457 b'\x0bI-.\x01\x002\xd1Mx\x04\x00\x00\x00')
458 with gzip.GzipFile(fileobj=io.BytesIO(gzdata)) as f:
459 self.assertEqual(f.read(), b'Test')
Nadeem Vawda7e126202012-05-06 15:04:01 +0200460
Ned Deily61207392014-03-09 14:44:34 -0700461 def test_prepend_error(self):
462 # See issue #20875
463 with gzip.open(self.filename, "wb") as f:
464 f.write(data1)
465 with gzip.open(self.filename, "rb") as f:
466 f.fileobj.prepend()
467
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200468class TestOpen(BaseTest):
469 def test_binary_modes(self):
Nadeem Vawda7e126202012-05-06 15:04:01 +0200470 uncompressed = data1 * 50
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200471
Nadeem Vawda7e126202012-05-06 15:04:01 +0200472 with gzip.open(self.filename, "wb") as f:
473 f.write(uncompressed)
474 with open(self.filename, "rb") as f:
475 file_data = gzip.decompress(f.read())
476 self.assertEqual(file_data, uncompressed)
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200477
Nadeem Vawda7e126202012-05-06 15:04:01 +0200478 with gzip.open(self.filename, "rb") as f:
479 self.assertEqual(f.read(), uncompressed)
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200480
Nadeem Vawda7e126202012-05-06 15:04:01 +0200481 with gzip.open(self.filename, "ab") as f:
482 f.write(uncompressed)
483 with open(self.filename, "rb") as f:
484 file_data = gzip.decompress(f.read())
485 self.assertEqual(file_data, uncompressed * 2)
486
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200487 with self.assertRaises(FileExistsError):
488 gzip.open(self.filename, "xb")
489 support.unlink(self.filename)
490 with gzip.open(self.filename, "xb") as f:
491 f.write(uncompressed)
492 with open(self.filename, "rb") as f:
493 file_data = gzip.decompress(f.read())
494 self.assertEqual(file_data, uncompressed)
495
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200496 def test_implicit_binary_modes(self):
Nadeem Vawda7e126202012-05-06 15:04:01 +0200497 # Test implicit binary modes (no "b" or "t" in mode string).
498 uncompressed = data1 * 50
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200499
Nadeem Vawda7e126202012-05-06 15:04:01 +0200500 with gzip.open(self.filename, "w") 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)
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200505
Nadeem Vawda7e126202012-05-06 15:04:01 +0200506 with gzip.open(self.filename, "r") as f:
507 self.assertEqual(f.read(), uncompressed)
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200508
Nadeem Vawda7e126202012-05-06 15:04:01 +0200509 with gzip.open(self.filename, "a") 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 * 2)
514
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200515 with self.assertRaises(FileExistsError):
516 gzip.open(self.filename, "x")
517 support.unlink(self.filename)
518 with gzip.open(self.filename, "x") as f:
519 f.write(uncompressed)
520 with open(self.filename, "rb") as f:
521 file_data = gzip.decompress(f.read())
522 self.assertEqual(file_data, uncompressed)
523
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200524 def test_text_modes(self):
Nadeem Vawda11328e42012-05-06 19:24:18 +0200525 uncompressed = data1.decode("ascii") * 50
526 uncompressed_raw = uncompressed.replace("\n", os.linesep)
Nadeem Vawda7e126202012-05-06 15:04:01 +0200527 with gzip.open(self.filename, "wt") as f:
528 f.write(uncompressed)
529 with open(self.filename, "rb") as f:
530 file_data = gzip.decompress(f.read()).decode("ascii")
Nadeem Vawda11328e42012-05-06 19:24:18 +0200531 self.assertEqual(file_data, uncompressed_raw)
Nadeem Vawda7e126202012-05-06 15:04:01 +0200532 with gzip.open(self.filename, "rt") as f:
533 self.assertEqual(f.read(), uncompressed)
534 with gzip.open(self.filename, "at") as f:
535 f.write(uncompressed)
536 with open(self.filename, "rb") as f:
537 file_data = gzip.decompress(f.read()).decode("ascii")
Nadeem Vawda11328e42012-05-06 19:24:18 +0200538 self.assertEqual(file_data, uncompressed_raw * 2)
Nadeem Vawda7e126202012-05-06 15:04:01 +0200539
Nadeem Vawda68721012012-06-04 23:21:38 +0200540 def test_fileobj(self):
541 uncompressed_bytes = data1 * 50
542 uncompressed_str = uncompressed_bytes.decode("ascii")
543 compressed = gzip.compress(uncompressed_bytes)
544 with gzip.open(io.BytesIO(compressed), "r") as f:
545 self.assertEqual(f.read(), uncompressed_bytes)
546 with gzip.open(io.BytesIO(compressed), "rb") as f:
547 self.assertEqual(f.read(), uncompressed_bytes)
548 with gzip.open(io.BytesIO(compressed), "rt") as f:
549 self.assertEqual(f.read(), uncompressed_str)
550
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200551 def test_bad_params(self):
Nadeem Vawda7e126202012-05-06 15:04:01 +0200552 # Test invalid parameter combinations.
Nadeem Vawda68721012012-06-04 23:21:38 +0200553 with self.assertRaises(TypeError):
554 gzip.open(123.456)
Nadeem Vawda7e126202012-05-06 15:04:01 +0200555 with self.assertRaises(ValueError):
556 gzip.open(self.filename, "wbt")
557 with self.assertRaises(ValueError):
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200558 gzip.open(self.filename, "xbt")
559 with self.assertRaises(ValueError):
Nadeem Vawda7e126202012-05-06 15:04:01 +0200560 gzip.open(self.filename, "rb", encoding="utf-8")
561 with self.assertRaises(ValueError):
562 gzip.open(self.filename, "rb", errors="ignore")
563 with self.assertRaises(ValueError):
564 gzip.open(self.filename, "rb", newline="\n")
565
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200566 def test_encoding(self):
Nadeem Vawda7e126202012-05-06 15:04:01 +0200567 # Test non-default encoding.
Nadeem Vawda11328e42012-05-06 19:24:18 +0200568 uncompressed = data1.decode("ascii") * 50
569 uncompressed_raw = uncompressed.replace("\n", os.linesep)
Nadeem Vawda7e126202012-05-06 15:04:01 +0200570 with gzip.open(self.filename, "wt", encoding="utf-16") as f:
571 f.write(uncompressed)
572 with open(self.filename, "rb") as f:
573 file_data = gzip.decompress(f.read()).decode("utf-16")
Nadeem Vawda11328e42012-05-06 19:24:18 +0200574 self.assertEqual(file_data, uncompressed_raw)
Nadeem Vawda7e126202012-05-06 15:04:01 +0200575 with gzip.open(self.filename, "rt", encoding="utf-16") as f:
576 self.assertEqual(f.read(), uncompressed)
577
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200578 def test_encoding_error_handler(self):
Nadeem Vawda7e126202012-05-06 15:04:01 +0200579 # Test with non-default encoding error handler.
580 with gzip.open(self.filename, "wb") as f:
581 f.write(b"foo\xffbar")
582 with gzip.open(self.filename, "rt", encoding="ascii", errors="ignore") \
583 as f:
584 self.assertEqual(f.read(), "foobar")
585
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200586 def test_newline(self):
Nadeem Vawda7e126202012-05-06 15:04:01 +0200587 # Test with explicit newline (universal newline mode disabled).
588 uncompressed = data1.decode("ascii") * 50
Nadeem Vawda9d9dc8e2012-05-06 16:25:35 +0200589 with gzip.open(self.filename, "wt", newline="\n") as f:
Nadeem Vawda7e126202012-05-06 15:04:01 +0200590 f.write(uncompressed)
591 with gzip.open(self.filename, "rt", newline="\r") as f:
592 self.assertEqual(f.readlines(), [uncompressed])
593
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000594def test_main(verbose=None):
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200595 support.run_unittest(TestGzip, TestOpen)
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000596
597if __name__ == "__main__":
598 test_main(verbose=True)