blob: 57d851cf9cf156ae4ebeabb54b60c0400087e9f8 [file] [log] [blame]
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +00001"""Test script for the gzip module.
2"""
3
Stéphane Wirtel84eec112018-10-09 23:16:43 +02004import array
5import functools
6import io
Christian Heimes05e8be12008-02-23 18:30:17 +00007import os
Berker Peksag03020cf2016-10-02 13:47:58 +03008import pathlib
Antoine Pitrou42db3ef2009-01-04 21:37:59 +00009import struct
Stéphane Wirtel84eec112018-10-09 23:16:43 +020010import sys
11import unittest
12from subprocess import PIPE, Popen
13from test import support
14from test.support import _4G, bigmemtest
Stéphane Wirtel3e28eed2018-11-03 16:24:23 +010015from test.support.script_helper import assert_python_ok, assert_python_failure
Stéphane Wirtel84eec112018-10-09 23:16:43 +020016
Ezio Melotti78ea2022009-09-12 18:41:20 +000017gzip = support.import_module('gzip')
Andrew M. Kuchling605ebdd1999-03-25 21:50:27 +000018
Walter Dörwald5b1284d2007-06-06 16:43:59 +000019data1 = b""" int length=DEFAULTALLOC, err = Z_OK;
Andrew M. Kuchling605ebdd1999-03-25 21:50:27 +000020 PyObject *RetVal;
21 int flushmode = Z_FINISH;
22 unsigned long start_total_out;
23
24"""
25
Walter Dörwald5b1284d2007-06-06 16:43:59 +000026data2 = b"""/* zlibmodule.c -- gzip-compatible data compression */
Neal Norwitz014f1032004-07-29 03:55:56 +000027/* See http://www.gzip.org/zlib/
Andrew M. Kuchling605ebdd1999-03-25 21:50:27 +000028/* See http://www.winimage.com/zLibDll for Windows */
29"""
30
Andrew M. Kuchling605ebdd1999-03-25 21:50:27 +000031
Stéphane Wirtel84eec112018-10-09 23:16:43 +020032TEMPDIR = os.path.abspath(support.TESTFN) + '-gzdir'
33
34
Antoine Pitrou7b969842010-09-23 16:22:51 +000035class UnseekableIO(io.BytesIO):
36 def seekable(self):
37 return False
38
39 def tell(self):
40 raise io.UnsupportedOperation
41
42 def seek(self, *args):
43 raise io.UnsupportedOperation
44
45
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +020046class BaseTest(unittest.TestCase):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000047 filename = support.TESTFN
Tim Peters5cfb05e2004-07-27 21:02:02 +000048
Georg Brandlb533e262008-05-25 18:19:30 +000049 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000050 support.unlink(self.filename)
Andrew M. Kuchling605ebdd1999-03-25 21:50:27 +000051
Georg Brandlb533e262008-05-25 18:19:30 +000052 def tearDown(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000053 support.unlink(self.filename)
Andrew M. Kuchling605ebdd1999-03-25 21:50:27 +000054
Andrew M. Kuchling85ab7382000-07-29 20:18:34 +000055
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +020056class TestGzip(BaseTest):
Serhiy Storchakabca63b32015-03-23 14:59:48 +020057 def write_and_read_back(self, data, mode='b'):
58 b_data = bytes(data)
59 with gzip.GzipFile(self.filename, 'w'+mode) as f:
60 l = f.write(data)
61 self.assertEqual(l, len(b_data))
62 with gzip.GzipFile(self.filename, 'r'+mode) as f:
63 self.assertEqual(f.read(), b_data)
64
Georg Brandlb533e262008-05-25 18:19:30 +000065 def test_write(self):
Brian Curtin28f96b52010-10-13 02:21:42 +000066 with gzip.GzipFile(self.filename, 'wb') as f:
67 f.write(data1 * 50)
Andrew M. Kuchling85ab7382000-07-29 20:18:34 +000068
Brian Curtin28f96b52010-10-13 02:21:42 +000069 # Try flush and fileno.
70 f.flush()
71 f.fileno()
72 if hasattr(os, 'fsync'):
73 os.fsync(f.fileno())
74 f.close()
Andrew M. Kuchling85ab7382000-07-29 20:18:34 +000075
Georg Brandlb533e262008-05-25 18:19:30 +000076 # Test multiple close() calls.
77 f.close()
78
Berker Peksag03020cf2016-10-02 13:47:58 +030079 def test_write_read_with_pathlike_file(self):
80 filename = pathlib.Path(self.filename)
81 with gzip.GzipFile(filename, 'w') as f:
82 f.write(data1 * 50)
83 self.assertIsInstance(f.name, str)
84 with gzip.GzipFile(filename, 'a') as f:
85 f.write(data1)
86 with gzip.GzipFile(filename) as f:
87 d = f.read()
88 self.assertEqual(d, data1 * 51)
89 self.assertIsInstance(f.name, str)
90
Serhiy Storchakabca63b32015-03-23 14:59:48 +020091 # The following test_write_xy methods test that write accepts
92 # the corresponding bytes-like object type as input
93 # and that the data written equals bytes(xy) in all cases.
94 def test_write_memoryview(self):
95 self.write_and_read_back(memoryview(data1 * 50))
96 m = memoryview(bytes(range(256)))
97 data = m.cast('B', shape=[8,8,4])
98 self.write_and_read_back(data)
99
100 def test_write_bytearray(self):
101 self.write_and_read_back(bytearray(data1 * 50))
102
103 def test_write_array(self):
104 self.write_and_read_back(array.array('I', data1 * 40))
105
106 def test_write_incompatible_type(self):
107 # Test that non-bytes-like types raise TypeError.
108 # Issue #21560: attempts to write incompatible types
109 # should not affect the state of the fileobject
110 with gzip.GzipFile(self.filename, 'wb') as f:
111 with self.assertRaises(TypeError):
112 f.write('')
113 with self.assertRaises(TypeError):
114 f.write([])
115 f.write(data1)
116 with gzip.GzipFile(self.filename, 'rb') as f:
117 self.assertEqual(f.read(), data1)
118
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000119 def test_read(self):
120 self.test_write()
121 # Try reading.
Brian Curtin28f96b52010-10-13 02:21:42 +0000122 with gzip.GzipFile(self.filename, 'r') as f:
123 d = f.read()
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000124 self.assertEqual(d, data1*50)
Andrew M. Kuchling85ab7382000-07-29 20:18:34 +0000125
Antoine Pitrou4ec4b0c2011-04-04 21:00:37 +0200126 def test_read1(self):
127 self.test_write()
128 blocks = []
129 nread = 0
130 with gzip.GzipFile(self.filename, 'r') as f:
131 while True:
132 d = f.read1()
133 if not d:
134 break
135 blocks.append(d)
136 nread += len(d)
137 # Check that position was updated correctly (see issue10791).
138 self.assertEqual(f.tell(), nread)
139 self.assertEqual(b''.join(blocks), data1 * 50)
140
Martin Pantere99e9772015-11-20 08:13:35 +0000141 @bigmemtest(size=_4G, memuse=1)
142 def test_read_large(self, size):
143 # Read chunk size over UINT_MAX should be supported, despite zlib's
144 # limitation per low-level call
145 compressed = gzip.compress(data1, compresslevel=1)
146 f = gzip.GzipFile(fileobj=io.BytesIO(compressed), mode='rb')
147 self.assertEqual(f.read(size), data1)
148
Antoine Pitrou7980eaa2010-10-06 21:21:18 +0000149 def test_io_on_closed_object(self):
150 # Test that I/O operations on closed GzipFile objects raise a
151 # ValueError, just like the corresponding functions on file objects.
152
153 # Write to a file, open it for reading, then close it.
154 self.test_write()
155 f = gzip.GzipFile(self.filename, 'r')
Antoine Pitrou2dbc6e62015-04-11 00:31:01 +0200156 fileobj = f.fileobj
157 self.assertFalse(fileobj.closed)
Antoine Pitrou7980eaa2010-10-06 21:21:18 +0000158 f.close()
Antoine Pitrou2dbc6e62015-04-11 00:31:01 +0200159 self.assertTrue(fileobj.closed)
Antoine Pitrou7980eaa2010-10-06 21:21:18 +0000160 with self.assertRaises(ValueError):
161 f.read(1)
162 with self.assertRaises(ValueError):
163 f.seek(0)
164 with self.assertRaises(ValueError):
165 f.tell()
166 # Open the file for writing, then close it.
167 f = gzip.GzipFile(self.filename, 'w')
Antoine Pitrou2dbc6e62015-04-11 00:31:01 +0200168 fileobj = f.fileobj
169 self.assertFalse(fileobj.closed)
Antoine Pitrou7980eaa2010-10-06 21:21:18 +0000170 f.close()
Antoine Pitrou2dbc6e62015-04-11 00:31:01 +0200171 self.assertTrue(fileobj.closed)
Antoine Pitrou7980eaa2010-10-06 21:21:18 +0000172 with self.assertRaises(ValueError):
173 f.write(b'')
174 with self.assertRaises(ValueError):
175 f.flush()
176
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000177 def test_append(self):
178 self.test_write()
179 # Append to the previous file
Brian Curtin28f96b52010-10-13 02:21:42 +0000180 with gzip.GzipFile(self.filename, 'ab') as f:
181 f.write(data2 * 15)
Andrew M. Kuchling85ab7382000-07-29 20:18:34 +0000182
Brian Curtin28f96b52010-10-13 02:21:42 +0000183 with gzip.GzipFile(self.filename, 'rb') as f:
184 d = f.read()
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000185 self.assertEqual(d, (data1*50) + (data2*15))
Andrew M. Kuchling85ab7382000-07-29 20:18:34 +0000186
Andrew M. Kuchling01cb47b2005-06-09 14:19:32 +0000187 def test_many_append(self):
188 # Bug #1074261 was triggered when reading a file that contained
189 # many, many members. Create such a file and verify that reading it
190 # works.
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200191 with gzip.GzipFile(self.filename, 'wb', 9) as f:
Walter Dörwald5b1284d2007-06-06 16:43:59 +0000192 f.write(b'a')
Brian Curtin28f96b52010-10-13 02:21:42 +0000193 for i in range(0, 200):
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200194 with gzip.GzipFile(self.filename, "ab", 9) as f: # append
Brian Curtin28f96b52010-10-13 02:21:42 +0000195 f.write(b'a')
Andrew M. Kuchling01cb47b2005-06-09 14:19:32 +0000196
197 # Try reading the file
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200198 with gzip.GzipFile(self.filename, "rb") as zgfile:
Brian Curtin28f96b52010-10-13 02:21:42 +0000199 contents = b""
200 while 1:
201 ztxt = zgfile.read(8192)
202 contents += ztxt
203 if not ztxt: break
Ezio Melottib3aedd42010-11-20 19:04:17 +0000204 self.assertEqual(contents, b'a'*201)
Andrew M. Kuchling01cb47b2005-06-09 14:19:32 +0000205
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200206 def test_exclusive_write(self):
207 with gzip.GzipFile(self.filename, 'xb') as f:
208 f.write(data1 * 50)
209 with gzip.GzipFile(self.filename, 'rb') as f:
210 self.assertEqual(f.read(), data1 * 50)
211 with self.assertRaises(FileExistsError):
212 gzip.GzipFile(self.filename, 'xb')
213
Antoine Pitroub1f88352010-01-03 22:37:40 +0000214 def test_buffered_reader(self):
215 # Issue #7471: a GzipFile can be wrapped in a BufferedReader for
216 # performance.
217 self.test_write()
218
Brian Curtin28f96b52010-10-13 02:21:42 +0000219 with gzip.GzipFile(self.filename, 'rb') as f:
220 with io.BufferedReader(f) as r:
221 lines = [line for line in r]
Antoine Pitroub1f88352010-01-03 22:37:40 +0000222
Ezio Melottid8b509b2011-09-28 17:37:55 +0300223 self.assertEqual(lines, 50 * data1.splitlines(keepends=True))
Andrew M. Kuchling01cb47b2005-06-09 14:19:32 +0000224
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000225 def test_readline(self):
226 self.test_write()
227 # Try .readline() with varying line lengths
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000228
Brian Curtin28f96b52010-10-13 02:21:42 +0000229 with gzip.GzipFile(self.filename, 'rb') as f:
230 line_length = 0
231 while 1:
232 L = f.readline(line_length)
233 if not L and line_length != 0: break
234 self.assertTrue(len(L) <= line_length)
235 line_length = (line_length + 1) % 50
Martin v. Löwis8cc965c2001-08-09 07:21:56 +0000236
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000237 def test_readlines(self):
238 self.test_write()
239 # Try .readlines()
Andrew M. Kuchling605ebdd1999-03-25 21:50:27 +0000240
Brian Curtin28f96b52010-10-13 02:21:42 +0000241 with gzip.GzipFile(self.filename, 'rb') as f:
242 L = f.readlines()
Skip Montanaro12424bc2002-05-23 01:43:05 +0000243
Brian Curtin28f96b52010-10-13 02:21:42 +0000244 with gzip.GzipFile(self.filename, 'rb') as f:
245 while 1:
246 L = f.readlines(150)
247 if L == []: break
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000248
249 def test_seek_read(self):
250 self.test_write()
251 # Try seek, read test
252
Brian Curtin28f96b52010-10-13 02:21:42 +0000253 with gzip.GzipFile(self.filename) as f:
254 while 1:
255 oldpos = f.tell()
256 line1 = f.readline()
257 if not line1: break
258 newpos = f.tell()
259 f.seek(oldpos) # negative seek
260 if len(line1)>10:
261 amount = 10
262 else:
263 amount = len(line1)
264 line2 = f.read(amount)
265 self.assertEqual(line1[:amount], line2)
266 f.seek(newpos) # positive seek
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000267
Thomas Wouters89f507f2006-12-13 04:49:30 +0000268 def test_seek_whence(self):
269 self.test_write()
270 # Try seek(whence=1), read test
271
Brian Curtin28f96b52010-10-13 02:21:42 +0000272 with gzip.GzipFile(self.filename) as f:
273 f.read(10)
274 f.seek(10, whence=1)
275 y = f.read(10)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000276 self.assertEqual(y, data1[20:30])
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000277
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000278 def test_seek_write(self):
279 # Try seek, write test
Brian Curtin28f96b52010-10-13 02:21:42 +0000280 with gzip.GzipFile(self.filename, 'w') as f:
281 for pos in range(0, 256, 16):
282 f.seek(pos)
283 f.write(b'GZ\n')
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000284
285 def test_mode(self):
286 self.test_write()
Brian Curtin28f96b52010-10-13 02:21:42 +0000287 with gzip.GzipFile(self.filename, 'r') as f:
288 self.assertEqual(f.myfileobj.mode, 'rb')
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200289 support.unlink(self.filename)
290 with gzip.GzipFile(self.filename, 'x') as f:
291 self.assertEqual(f.myfileobj.mode, 'xb')
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000292
Thomas Wouterscf297e42007-02-23 15:07:44 +0000293 def test_1647484(self):
294 for mode in ('wb', 'rb'):
Brian Curtin28f96b52010-10-13 02:21:42 +0000295 with gzip.GzipFile(self.filename, mode) as f:
296 self.assertTrue(hasattr(f, "name"))
297 self.assertEqual(f.name, self.filename)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000298
Georg Brandl9f1c1dc2010-11-20 11:25:01 +0000299 def test_paddedfile_getattr(self):
300 self.test_write()
301 with gzip.GzipFile(self.filename, 'rb') as f:
302 self.assertTrue(hasattr(f.fileobj, "name"))
303 self.assertEqual(f.fileobj.name, self.filename)
304
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000305 def test_mtime(self):
306 mtime = 123456789
Brian Curtin28f96b52010-10-13 02:21:42 +0000307 with gzip.GzipFile(self.filename, 'w', mtime = mtime) as fWrite:
308 fWrite.write(data1)
309 with gzip.GzipFile(self.filename) as fRead:
Antoine Pitrou2dbc6e62015-04-11 00:31:01 +0200310 self.assertTrue(hasattr(fRead, 'mtime'))
311 self.assertIsNone(fRead.mtime)
Brian Curtin28f96b52010-10-13 02:21:42 +0000312 dataRead = fRead.read()
313 self.assertEqual(dataRead, data1)
Brian Curtin28f96b52010-10-13 02:21:42 +0000314 self.assertEqual(fRead.mtime, mtime)
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000315
316 def test_metadata(self):
317 mtime = 123456789
318
Brian Curtin28f96b52010-10-13 02:21:42 +0000319 with gzip.GzipFile(self.filename, 'w', mtime = mtime) as fWrite:
320 fWrite.write(data1)
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000321
Brian Curtin28f96b52010-10-13 02:21:42 +0000322 with open(self.filename, 'rb') as fRead:
323 # see RFC 1952: http://www.faqs.org/rfcs/rfc1952.html
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000324
Brian Curtin28f96b52010-10-13 02:21:42 +0000325 idBytes = fRead.read(2)
326 self.assertEqual(idBytes, b'\x1f\x8b') # gzip ID
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000327
Brian Curtin28f96b52010-10-13 02:21:42 +0000328 cmByte = fRead.read(1)
329 self.assertEqual(cmByte, b'\x08') # deflate
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000330
Brian Curtin28f96b52010-10-13 02:21:42 +0000331 flagsByte = fRead.read(1)
332 self.assertEqual(flagsByte, b'\x08') # only the FNAME flag is set
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000333
Brian Curtin28f96b52010-10-13 02:21:42 +0000334 mtimeBytes = fRead.read(4)
335 self.assertEqual(mtimeBytes, struct.pack('<i', mtime)) # little-endian
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000336
Brian Curtin28f96b52010-10-13 02:21:42 +0000337 xflByte = fRead.read(1)
338 self.assertEqual(xflByte, b'\x02') # maximum compression
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000339
Brian Curtin28f96b52010-10-13 02:21:42 +0000340 osByte = fRead.read(1)
341 self.assertEqual(osByte, b'\xff') # OS "unknown" (OS-independent)
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000342
Brian Curtin28f96b52010-10-13 02:21:42 +0000343 # Since the FNAME flag is set, the zero-terminated filename follows.
344 # RFC 1952 specifies that this is the name of the input file, if any.
345 # However, the gzip module defaults to storing the name of the output
346 # file in this field.
347 expected = self.filename.encode('Latin-1') + b'\x00'
348 nameBytes = fRead.read(len(expected))
349 self.assertEqual(nameBytes, expected)
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000350
Brian Curtin28f96b52010-10-13 02:21:42 +0000351 # Since no other flags were set, the header ends here.
352 # Rather than process the compressed data, let's seek to the trailer.
353 fRead.seek(os.stat(self.filename).st_size - 8)
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000354
Brian Curtin28f96b52010-10-13 02:21:42 +0000355 crc32Bytes = fRead.read(4) # CRC32 of uncompressed data [data1]
356 self.assertEqual(crc32Bytes, b'\xaf\xd7d\x83')
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000357
Brian Curtin28f96b52010-10-13 02:21:42 +0000358 isizeBytes = fRead.read(4)
359 self.assertEqual(isizeBytes, struct.pack('<i', len(data1)))
Antoine Pitrou42db3ef2009-01-04 21:37:59 +0000360
Antoine Pitrou308705e2009-01-10 16:22:51 +0000361 def test_with_open(self):
362 # GzipFile supports the context management protocol
363 with gzip.GzipFile(self.filename, "wb") as f:
364 f.write(b"xxx")
365 f = gzip.GzipFile(self.filename, "rb")
366 f.close()
367 try:
368 with f:
369 pass
370 except ValueError:
371 pass
372 else:
373 self.fail("__enter__ on a closed file didn't raise an exception")
374 try:
375 with gzip.GzipFile(self.filename, "wb") as f:
376 1/0
377 except ZeroDivisionError:
378 pass
379 else:
380 self.fail("1/0 didn't raise an exception")
381
Antoine Pitrou8e33fd72010-01-13 14:37:26 +0000382 def test_zero_padded_file(self):
383 with gzip.GzipFile(self.filename, "wb") as f:
384 f.write(data1 * 50)
385
386 # Pad the file with zeroes
387 with open(self.filename, "ab") as f:
388 f.write(b"\x00" * 50)
389
390 with gzip.GzipFile(self.filename, "rb") as f:
391 d = f.read()
392 self.assertEqual(d, data1 * 50, "Incorrect data in file")
393
Zackery Spytzcf599f62019-05-13 01:50:52 -0600394 def test_gzip_BadGzipFile_exception(self):
395 self.assertTrue(issubclass(gzip.BadGzipFile, OSError))
396
397 def test_bad_gzip_file(self):
398 with open(self.filename, 'wb') as file:
399 file.write(data1 * 50)
400 with gzip.GzipFile(self.filename, 'r') as file:
401 self.assertRaises(gzip.BadGzipFile, file.readlines)
402
Antoine Pitrou7b969842010-09-23 16:22:51 +0000403 def test_non_seekable_file(self):
404 uncompressed = data1 * 50
405 buf = UnseekableIO()
406 with gzip.GzipFile(fileobj=buf, mode="wb") as f:
407 f.write(uncompressed)
408 compressed = buf.getvalue()
409 buf = UnseekableIO(compressed)
410 with gzip.GzipFile(fileobj=buf, mode="rb") as f:
411 self.assertEqual(f.read(), uncompressed)
412
Antoine Pitrouc3ed2e72010-09-29 10:49:46 +0000413 def test_peek(self):
414 uncompressed = data1 * 200
415 with gzip.GzipFile(self.filename, "wb") as f:
416 f.write(uncompressed)
417
418 def sizes():
419 while True:
420 for n in range(5, 50, 10):
421 yield n
422
423 with gzip.GzipFile(self.filename, "rb") as f:
424 f.max_read_chunk = 33
425 nread = 0
426 for n in sizes():
427 s = f.peek(n)
428 if s == b'':
429 break
430 self.assertEqual(f.read(len(s)), s)
431 nread += len(s)
432 self.assertEqual(f.read(100), b'')
433 self.assertEqual(nread, len(uncompressed))
434
Antoine Pitrou4ec4b0c2011-04-04 21:00:37 +0200435 def test_textio_readlines(self):
436 # Issue #10791: TextIOWrapper.readlines() fails when wrapping GzipFile.
Ezio Melottid8b509b2011-09-28 17:37:55 +0300437 lines = (data1 * 50).decode("ascii").splitlines(keepends=True)
Antoine Pitrou4ec4b0c2011-04-04 21:00:37 +0200438 self.test_write()
439 with gzip.GzipFile(self.filename, 'r') as f:
440 with io.TextIOWrapper(f, encoding="ascii") as t:
441 self.assertEqual(t.readlines(), lines)
442
Nadeem Vawda892b0b92012-01-18 09:25:58 +0200443 def test_fileobj_from_fdopen(self):
444 # Issue #13781: Opening a GzipFile for writing fails when using a
445 # fileobj created with os.fdopen().
446 fd = os.open(self.filename, os.O_WRONLY | os.O_CREAT)
447 with os.fdopen(fd, "wb") as f:
448 with gzip.GzipFile(fileobj=f, mode="w") as g:
449 pass
450
Serhiy Storchakabcbdd2f2017-10-22 13:18:21 +0300451 def test_fileobj_mode(self):
452 gzip.GzipFile(self.filename, "wb").close()
453 with open(self.filename, "r+b") as f:
454 with gzip.GzipFile(fileobj=f, mode='r') as g:
455 self.assertEqual(g.mode, gzip.READ)
456 with gzip.GzipFile(fileobj=f, mode='w') as g:
457 self.assertEqual(g.mode, gzip.WRITE)
458 with gzip.GzipFile(fileobj=f, mode='a') as g:
459 self.assertEqual(g.mode, gzip.WRITE)
460 with gzip.GzipFile(fileobj=f, mode='x') as g:
461 self.assertEqual(g.mode, gzip.WRITE)
462 with self.assertRaises(ValueError):
463 gzip.GzipFile(fileobj=f, mode='z')
464 for mode in "rb", "r+b":
465 with open(self.filename, mode) as f:
466 with gzip.GzipFile(fileobj=f) as g:
467 self.assertEqual(g.mode, gzip.READ)
468 for mode in "wb", "ab", "xb":
469 if "x" in mode:
470 support.unlink(self.filename)
471 with open(self.filename, mode) as f:
Serhiy Storchakaa0652322019-11-16 18:56:57 +0200472 with self.assertWarns(FutureWarning):
473 g = gzip.GzipFile(fileobj=f)
474 with g:
Serhiy Storchakabcbdd2f2017-10-22 13:18:21 +0300475 self.assertEqual(g.mode, gzip.WRITE)
476
Nadeem Vawda103e8112012-06-20 01:35:22 +0200477 def test_bytes_filename(self):
478 str_filename = self.filename
479 try:
480 bytes_filename = str_filename.encode("ascii")
481 except UnicodeEncodeError:
482 self.skipTest("Temporary file name needs to be ASCII")
483 with gzip.GzipFile(bytes_filename, "wb") as f:
484 f.write(data1 * 50)
485 with gzip.GzipFile(bytes_filename, "rb") as f:
486 self.assertEqual(f.read(), data1 * 50)
487 # Sanity check that we are actually operating on the right file.
488 with gzip.GzipFile(str_filename, "rb") as f:
489 self.assertEqual(f.read(), data1 * 50)
490
Antoine Pitrou2dbc6e62015-04-11 00:31:01 +0200491 def test_decompress_limited(self):
492 """Decompressed data buffering should be limited"""
Serhiy Storchaka5f1a5182016-09-11 14:41:02 +0300493 bomb = gzip.compress(b'\0' * int(2e6), compresslevel=9)
Antoine Pitrou2dbc6e62015-04-11 00:31:01 +0200494 self.assertLess(len(bomb), io.DEFAULT_BUFFER_SIZE)
495
496 bomb = io.BytesIO(bomb)
497 decomp = gzip.GzipFile(fileobj=bomb)
Serhiy Storchaka5f1a5182016-09-11 14:41:02 +0300498 self.assertEqual(decomp.read(1), b'\0')
Antoine Pitrou2dbc6e62015-04-11 00:31:01 +0200499 max_decomp = 1 + io.DEFAULT_BUFFER_SIZE
500 self.assertLessEqual(decomp._buffer.raw.tell(), max_decomp,
501 "Excessive amount of data was decompressed")
502
Antoine Pitrou79c5ef12010-08-17 21:10:05 +0000503 # Testing compress/decompress shortcut functions
504
505 def test_compress(self):
506 for data in [data1, data2]:
507 for args in [(), (1,), (6,), (9,)]:
508 datac = gzip.compress(data, *args)
509 self.assertEqual(type(datac), bytes)
510 with gzip.GzipFile(fileobj=io.BytesIO(datac), mode="rb") as f:
511 self.assertEqual(f.read(), data)
512
guoci0e7497c2018-11-07 04:50:23 -0500513 def test_compress_mtime(self):
514 mtime = 123456789
515 for data in [data1, data2]:
516 for args in [(), (1,), (6,), (9,)]:
517 with self.subTest(data=data, args=args):
518 datac = gzip.compress(data, *args, mtime=mtime)
519 self.assertEqual(type(datac), bytes)
520 with gzip.GzipFile(fileobj=io.BytesIO(datac), mode="rb") as f:
521 f.read(1) # to set mtime attribute
522 self.assertEqual(f.mtime, mtime)
523
Antoine Pitrou79c5ef12010-08-17 21:10:05 +0000524 def test_decompress(self):
525 for data in (data1, data2):
526 buf = io.BytesIO()
527 with gzip.GzipFile(fileobj=buf, mode="wb") as f:
528 f.write(data)
529 self.assertEqual(gzip.decompress(buf.getvalue()), data)
530 # Roundtrip with compress
531 datac = gzip.compress(data)
532 self.assertEqual(gzip.decompress(datac), data)
533
Serhiy Storchaka7c3922f2013-01-22 17:01:59 +0200534 def test_read_truncated(self):
535 data = data1*50
536 # Drop the CRC (4 bytes) and file size (4 bytes).
537 truncated = gzip.compress(data)[:-8]
538 with gzip.GzipFile(fileobj=io.BytesIO(truncated)) as f:
539 self.assertRaises(EOFError, f.read)
540 with gzip.GzipFile(fileobj=io.BytesIO(truncated)) as f:
541 self.assertEqual(f.read(len(data)), data)
542 self.assertRaises(EOFError, f.read, 1)
543 # Incomplete 10-byte header.
544 for i in range(2, 10):
545 with gzip.GzipFile(fileobj=io.BytesIO(truncated[:i])) as f:
546 self.assertRaises(EOFError, f.read, 1)
547
Serhiy Storchaka7e69f002013-04-08 22:35:02 +0300548 def test_read_with_extra(self):
549 # Gzip data with an extra field
550 gzdata = (b'\x1f\x8b\x08\x04\xb2\x17cQ\x02\xff'
551 b'\x05\x00Extra'
552 b'\x0bI-.\x01\x002\xd1Mx\x04\x00\x00\x00')
553 with gzip.GzipFile(fileobj=io.BytesIO(gzdata)) as f:
554 self.assertEqual(f.read(), b'Test')
Nadeem Vawda7e126202012-05-06 15:04:01 +0200555
Ned Deily61207392014-03-09 14:44:34 -0700556 def test_prepend_error(self):
557 # See issue #20875
558 with gzip.open(self.filename, "wb") as f:
559 f.write(data1)
560 with gzip.open(self.filename, "rb") as f:
Antoine Pitrou2dbc6e62015-04-11 00:31:01 +0200561 f._buffer.raw._fp.prepend()
Ned Deily61207392014-03-09 14:44:34 -0700562
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200563class TestOpen(BaseTest):
564 def test_binary_modes(self):
Nadeem Vawda7e126202012-05-06 15:04:01 +0200565 uncompressed = data1 * 50
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200566
Nadeem Vawda7e126202012-05-06 15:04:01 +0200567 with gzip.open(self.filename, "wb") as f:
568 f.write(uncompressed)
569 with open(self.filename, "rb") as f:
570 file_data = gzip.decompress(f.read())
571 self.assertEqual(file_data, uncompressed)
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200572
Nadeem Vawda7e126202012-05-06 15:04:01 +0200573 with gzip.open(self.filename, "rb") as f:
574 self.assertEqual(f.read(), uncompressed)
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200575
Nadeem Vawda7e126202012-05-06 15:04:01 +0200576 with gzip.open(self.filename, "ab") as f:
577 f.write(uncompressed)
578 with open(self.filename, "rb") as f:
579 file_data = gzip.decompress(f.read())
580 self.assertEqual(file_data, uncompressed * 2)
581
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200582 with self.assertRaises(FileExistsError):
583 gzip.open(self.filename, "xb")
584 support.unlink(self.filename)
585 with gzip.open(self.filename, "xb") as f:
586 f.write(uncompressed)
587 with open(self.filename, "rb") as f:
588 file_data = gzip.decompress(f.read())
589 self.assertEqual(file_data, uncompressed)
590
Berker Peksag03020cf2016-10-02 13:47:58 +0300591 def test_pathlike_file(self):
592 filename = pathlib.Path(self.filename)
593 with gzip.open(filename, "wb") as f:
594 f.write(data1 * 50)
595 with gzip.open(filename, "ab") as f:
596 f.write(data1)
597 with gzip.open(filename) as f:
598 self.assertEqual(f.read(), data1 * 51)
599
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200600 def test_implicit_binary_modes(self):
Nadeem Vawda7e126202012-05-06 15:04:01 +0200601 # Test implicit binary modes (no "b" or "t" in mode string).
602 uncompressed = data1 * 50
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200603
Nadeem Vawda7e126202012-05-06 15:04:01 +0200604 with gzip.open(self.filename, "w") as f:
605 f.write(uncompressed)
606 with open(self.filename, "rb") as f:
607 file_data = gzip.decompress(f.read())
608 self.assertEqual(file_data, uncompressed)
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200609
Nadeem Vawda7e126202012-05-06 15:04:01 +0200610 with gzip.open(self.filename, "r") as f:
611 self.assertEqual(f.read(), uncompressed)
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200612
Nadeem Vawda7e126202012-05-06 15:04:01 +0200613 with gzip.open(self.filename, "a") as f:
614 f.write(uncompressed)
615 with open(self.filename, "rb") as f:
616 file_data = gzip.decompress(f.read())
617 self.assertEqual(file_data, uncompressed * 2)
618
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200619 with self.assertRaises(FileExistsError):
620 gzip.open(self.filename, "x")
621 support.unlink(self.filename)
622 with gzip.open(self.filename, "x") as f:
623 f.write(uncompressed)
624 with open(self.filename, "rb") as f:
625 file_data = gzip.decompress(f.read())
626 self.assertEqual(file_data, uncompressed)
627
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200628 def test_text_modes(self):
Nadeem Vawda11328e42012-05-06 19:24:18 +0200629 uncompressed = data1.decode("ascii") * 50
630 uncompressed_raw = uncompressed.replace("\n", os.linesep)
Nadeem Vawda7e126202012-05-06 15:04:01 +0200631 with gzip.open(self.filename, "wt") as f:
632 f.write(uncompressed)
633 with open(self.filename, "rb") as f:
634 file_data = gzip.decompress(f.read()).decode("ascii")
Nadeem Vawda11328e42012-05-06 19:24:18 +0200635 self.assertEqual(file_data, uncompressed_raw)
Nadeem Vawda7e126202012-05-06 15:04:01 +0200636 with gzip.open(self.filename, "rt") as f:
637 self.assertEqual(f.read(), uncompressed)
638 with gzip.open(self.filename, "at") as f:
639 f.write(uncompressed)
640 with open(self.filename, "rb") as f:
641 file_data = gzip.decompress(f.read()).decode("ascii")
Nadeem Vawda11328e42012-05-06 19:24:18 +0200642 self.assertEqual(file_data, uncompressed_raw * 2)
Nadeem Vawda7e126202012-05-06 15:04:01 +0200643
Nadeem Vawda68721012012-06-04 23:21:38 +0200644 def test_fileobj(self):
645 uncompressed_bytes = data1 * 50
646 uncompressed_str = uncompressed_bytes.decode("ascii")
647 compressed = gzip.compress(uncompressed_bytes)
648 with gzip.open(io.BytesIO(compressed), "r") as f:
649 self.assertEqual(f.read(), uncompressed_bytes)
650 with gzip.open(io.BytesIO(compressed), "rb") as f:
651 self.assertEqual(f.read(), uncompressed_bytes)
652 with gzip.open(io.BytesIO(compressed), "rt") as f:
653 self.assertEqual(f.read(), uncompressed_str)
654
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200655 def test_bad_params(self):
Nadeem Vawda7e126202012-05-06 15:04:01 +0200656 # Test invalid parameter combinations.
Nadeem Vawda68721012012-06-04 23:21:38 +0200657 with self.assertRaises(TypeError):
658 gzip.open(123.456)
Nadeem Vawda7e126202012-05-06 15:04:01 +0200659 with self.assertRaises(ValueError):
660 gzip.open(self.filename, "wbt")
661 with self.assertRaises(ValueError):
Nadeem Vawdaee1be992013-10-19 00:11:13 +0200662 gzip.open(self.filename, "xbt")
663 with self.assertRaises(ValueError):
Nadeem Vawda7e126202012-05-06 15:04:01 +0200664 gzip.open(self.filename, "rb", encoding="utf-8")
665 with self.assertRaises(ValueError):
666 gzip.open(self.filename, "rb", errors="ignore")
667 with self.assertRaises(ValueError):
668 gzip.open(self.filename, "rb", newline="\n")
669
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200670 def test_encoding(self):
Nadeem Vawda7e126202012-05-06 15:04:01 +0200671 # Test non-default encoding.
Nadeem Vawda11328e42012-05-06 19:24:18 +0200672 uncompressed = data1.decode("ascii") * 50
673 uncompressed_raw = uncompressed.replace("\n", os.linesep)
Nadeem Vawda7e126202012-05-06 15:04:01 +0200674 with gzip.open(self.filename, "wt", encoding="utf-16") as f:
675 f.write(uncompressed)
676 with open(self.filename, "rb") as f:
677 file_data = gzip.decompress(f.read()).decode("utf-16")
Nadeem Vawda11328e42012-05-06 19:24:18 +0200678 self.assertEqual(file_data, uncompressed_raw)
Nadeem Vawda7e126202012-05-06 15:04:01 +0200679 with gzip.open(self.filename, "rt", encoding="utf-16") as f:
680 self.assertEqual(f.read(), uncompressed)
681
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200682 def test_encoding_error_handler(self):
Nadeem Vawda7e126202012-05-06 15:04:01 +0200683 # Test with non-default encoding error handler.
684 with gzip.open(self.filename, "wb") as f:
685 f.write(b"foo\xffbar")
686 with gzip.open(self.filename, "rt", encoding="ascii", errors="ignore") \
687 as f:
688 self.assertEqual(f.read(), "foobar")
689
Nadeem Vawda1b8a14d2012-05-06 15:17:52 +0200690 def test_newline(self):
Nadeem Vawda7e126202012-05-06 15:04:01 +0200691 # Test with explicit newline (universal newline mode disabled).
692 uncompressed = data1.decode("ascii") * 50
Nadeem Vawda9d9dc8e2012-05-06 16:25:35 +0200693 with gzip.open(self.filename, "wt", newline="\n") as f:
Nadeem Vawda7e126202012-05-06 15:04:01 +0200694 f.write(uncompressed)
695 with gzip.open(self.filename, "rt", newline="\r") as f:
696 self.assertEqual(f.readlines(), [uncompressed])
697
Stéphane Wirtel84eec112018-10-09 23:16:43 +0200698
699def create_and_remove_directory(directory):
700 def decorator(function):
701 @functools.wraps(function)
702 def wrapper(*args, **kwargs):
703 os.makedirs(directory)
704 try:
705 return function(*args, **kwargs)
706 finally:
707 support.rmtree(directory)
708 return wrapper
709 return decorator
710
711
712class TestCommandLine(unittest.TestCase):
713 data = b'This is a simple test with gzip'
714
715 def test_decompress_stdin_stdout(self):
716 with io.BytesIO() as bytes_io:
717 with gzip.GzipFile(fileobj=bytes_io, mode='wb') as gzip_file:
718 gzip_file.write(self.data)
719
720 args = sys.executable, '-m', 'gzip', '-d'
721 with Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE) as proc:
722 out, err = proc.communicate(bytes_io.getvalue())
723
724 self.assertEqual(err, b'')
725 self.assertEqual(out, self.data)
726
727 @create_and_remove_directory(TEMPDIR)
728 def test_decompress_infile_outfile(self):
729 gzipname = os.path.join(TEMPDIR, 'testgzip.gz')
730 self.assertFalse(os.path.exists(gzipname))
731
732 with gzip.open(gzipname, mode='wb') as fp:
733 fp.write(self.data)
734 rc, out, err = assert_python_ok('-m', 'gzip', '-d', gzipname)
735
736 with open(os.path.join(TEMPDIR, "testgzip"), "rb") as gunziped:
737 self.assertEqual(gunziped.read(), self.data)
738
739 self.assertTrue(os.path.exists(gzipname))
740 self.assertEqual(rc, 0)
741 self.assertEqual(out, b'')
742 self.assertEqual(err, b'')
743
744 def test_decompress_infile_outfile_error(self):
745 rc, out, err = assert_python_ok('-m', 'gzip', '-d', 'thisisatest.out')
746 self.assertIn(b"filename doesn't end in .gz:", out)
747 self.assertEqual(rc, 0)
748 self.assertEqual(err, b'')
749
750 @create_and_remove_directory(TEMPDIR)
751 def test_compress_stdin_outfile(self):
752 args = sys.executable, '-m', 'gzip'
753 with Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE) as proc:
754 out, err = proc.communicate(self.data)
755
756 self.assertEqual(err, b'')
757 self.assertEqual(out[:2], b"\x1f\x8b")
758
759 @create_and_remove_directory(TEMPDIR)
Gregory P. Smithcd466552019-04-14 10:32:07 -0700760 def test_compress_infile_outfile_default(self):
Stéphane Wirtel84eec112018-10-09 23:16:43 +0200761 local_testgzip = os.path.join(TEMPDIR, 'testgzip')
762 gzipname = local_testgzip + '.gz'
763 self.assertFalse(os.path.exists(gzipname))
764
765 with open(local_testgzip, 'wb') as fp:
766 fp.write(self.data)
767
768 rc, out, err = assert_python_ok('-m', 'gzip', local_testgzip)
769
770 self.assertTrue(os.path.exists(gzipname))
Stéphane Wirtel84eec112018-10-09 23:16:43 +0200771 self.assertEqual(out, b'')
772 self.assertEqual(err, b'')
773
Stéphane Wirtel3e28eed2018-11-03 16:24:23 +0100774 @create_and_remove_directory(TEMPDIR)
775 def test_compress_infile_outfile(self):
776 for compress_level in ('--fast', '--best'):
777 with self.subTest(compress_level=compress_level):
778 local_testgzip = os.path.join(TEMPDIR, 'testgzip')
779 gzipname = local_testgzip + '.gz'
780 self.assertFalse(os.path.exists(gzipname))
781
782 with open(local_testgzip, 'wb') as fp:
783 fp.write(self.data)
784
785 rc, out, err = assert_python_ok('-m', 'gzip', compress_level, local_testgzip)
786
787 self.assertTrue(os.path.exists(gzipname))
788 self.assertEqual(out, b'')
789 self.assertEqual(err, b'')
790 os.remove(gzipname)
791 self.assertFalse(os.path.exists(gzipname))
792
793 def test_compress_fast_best_are_exclusive(self):
794 rc, out, err = assert_python_failure('-m', 'gzip', '--fast', '--best')
795 self.assertIn(b"error: argument --best: not allowed with argument --fast", err)
796 self.assertEqual(out, b'')
797
798 def test_decompress_cannot_have_flags_compression(self):
799 rc, out, err = assert_python_failure('-m', 'gzip', '--fast', '-d')
800 self.assertIn(b'error: argument -d/--decompress: not allowed with argument --fast', err)
801 self.assertEqual(out, b'')
802
Stéphane Wirtel84eec112018-10-09 23:16:43 +0200803
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000804def test_main(verbose=None):
Stéphane Wirtel84eec112018-10-09 23:16:43 +0200805 support.run_unittest(TestGzip, TestOpen, TestCommandLine)
806
Andrew M. Kuchlinga6f68e12005-06-09 14:12:36 +0000807
808if __name__ == "__main__":
809 test_main(verbose=True)