Debian Codegraph @

Lib/test/test_gzip.py

raw
1 """Test script for the gzip module.
2 """
3
4 import array
5 import functools
6 import gc
7 import io
8 import os
9 import struct
10 import sys
11 import unittest
12 from subprocess import PIPE, Popen
13 from test.support import catch_unraisable_exception
14 from test.support import import_helper
15 from test.support import os_helper
16 from test.support import _4G, bigmemtest, requires_subprocess
17 from test.support.script_helper import assert_python_ok, assert_python_failure
18
19 gzip = import_helper.import_module('gzip')
20 zlib = import_helper.import_module('zlib')
21
22 data1 = b""" int length=DEFAULTALLOC, err = Z_OK;
23 PyObject *RetVal;
24 int flushmode = Z_FINISH;
25 unsigned long start_total_out;
26
27 """
28
29 data2 = b"""/* zlibmodule.c -- gzip-compatible data compression */
30 /* See http://www.gzip.org/zlib/
31 /* See http://www.winimage.com/zLibDll for Windows */
32 """
33
34
35 TEMPDIR = os.path.abspath(os_helper.TESTFN) + '-gzdir'
36
37
38 class UnseekableIO(io.BytesIO):
39 def seekable(self):
40 return False
41
42 def tell(self):
43 raise io.UnsupportedOperation
44
45 def seek(self, *args):
46 raise io.UnsupportedOperation
47
48
49 class BaseTest(unittest.TestCase):
50 filename = os_helper.TESTFN
51
52 def setUp(self):
53 os_helper.unlink(self.filename)
54
55 def tearDown(self):
56 os_helper.unlink(self.filename)
57
58
59 class TestGzip(BaseTest):
60 def write_and_read_back(self, data, mode='b'):
61 b_data = bytes(data)
62 with gzip.GzipFile(self.filename, 'w'+mode) as f:
63 l = f.write(data)
64 self.assertEqual(l, len(b_data))
65 with gzip.GzipFile(self.filename, 'r'+mode) as f:
66 self.assertEqual(f.read(), b_data)
67
68 def test_write(self):
69 with gzip.GzipFile(self.filename, 'wb') as f:
70 f.write(data1 * 50)
71
72 # Try flush and fileno.
73 f.flush()
74 f.fileno()
75 if hasattr(os, 'fsync'):
76 os.fsync(f.fileno())
77 f.close()
78
79 # Test multiple close() calls.
80 f.close()
81
82 def test_write_read_with_pathlike_file(self):
83 filename = os_helper.FakePath(self.filename)
84 with gzip.GzipFile(filename, 'w') as f:
85 f.write(data1 * 50)
86 self.assertIsInstance(f.name, str)
87 self.assertEqual(f.name, self.filename)
88 with gzip.GzipFile(filename, 'a') as f:
89 f.write(data1)
90 with gzip.GzipFile(filename) as f:
91 d = f.read()
92 self.assertEqual(d, data1 * 51)
93 self.assertIsInstance(f.name, str)
94 self.assertEqual(f.name, self.filename)
95
96 # The following test_write_xy methods test that write accepts
97 # the corresponding bytes-like object type as input
98 # and that the data written equals bytes(xy) in all cases.
99 def test_write_memoryview(self):
100 self.write_and_read_back(memoryview(data1 * 50))
101 m = memoryview(bytes(range(256)))
102 data = m.cast('B', shape=[8,8,4])
103 self.write_and_read_back(data)
104
105 def test_write_bytearray(self):
106 self.write_and_read_back(bytearray(data1 * 50))
107
108 def test_write_array(self):
109 self.write_and_read_back(array.array('I', data1 * 40))
110
111 def test_write_incompatible_type(self):
112 # Test that non-bytes-like types raise TypeError.
113 # Issue #21560: attempts to write incompatible types
114 # should not affect the state of the fileobject
115 with gzip.GzipFile(self.filename, 'wb') as f:
116 with self.assertRaises(TypeError):
117 f.write('')
118 with self.assertRaises(TypeError):
119 f.write([])
120 f.write(data1)
121 with gzip.GzipFile(self.filename, 'rb') as f:
122 self.assertEqual(f.read(), data1)
123
124 def test_read(self):
125 self.test_write()
126 # Try reading.
127 with gzip.GzipFile(self.filename, 'r') as f:
128 d = f.read()
129 self.assertEqual(d, data1*50)
130
131 def test_read1(self):
132 self.test_write()
133 blocks = []
134 nread = 0
135 with gzip.GzipFile(self.filename, 'r') as f:
136 while True:
137 d = f.read1()
138 if not d:
139 break
140 blocks.append(d)
141 nread += len(d)
142 # Check that position was updated correctly (see issue10791).
143 self.assertEqual(f.tell(), nread)
144 self.assertEqual(b''.join(blocks), data1 * 50)
145
146 @bigmemtest(size=_4G, memuse=1)
147 def test_read_large(self, size):
148 # Read chunk size over UINT_MAX should be supported, despite zlib's
149 # limitation per low-level call
150 compressed = gzip.compress(data1, compresslevel=1)
151 f = gzip.GzipFile(fileobj=io.BytesIO(compressed), mode='rb')
152 self.assertEqual(f.read(size), data1)
153
154 def test_io_on_closed_object(self):
155 # Test that I/O operations on closed GzipFile objects raise a
156 # ValueError, just like the corresponding functions on file objects.
157
158 # Write to a file, open it for reading, then close it.
159 self.test_write()
160 f = gzip.GzipFile(self.filename, 'r')
161 fileobj = f.fileobj
162 self.assertFalse(fileobj.closed)
163 f.close()
164 self.assertTrue(fileobj.closed)
165 with self.assertRaises(ValueError):
166 f.read(1)
167 with self.assertRaises(ValueError):
168 f.seek(0)
169 with self.assertRaises(ValueError):
170 f.tell()
171 # Open the file for writing, then close it.
172 f = gzip.GzipFile(self.filename, 'w')
173 fileobj = f.fileobj
174 self.assertFalse(fileobj.closed)
175 f.close()
176 self.assertTrue(fileobj.closed)
177 with self.assertRaises(ValueError):
178 f.write(b'')
179 with self.assertRaises(ValueError):
180 f.flush()
181
182 def test_append(self):
183 self.test_write()
184 # Append to the previous file
185 with gzip.GzipFile(self.filename, 'ab') as f:
186 f.write(data2 * 15)
187
188 with gzip.GzipFile(self.filename, 'rb') as f:
189 d = f.read()
190 self.assertEqual(d, (data1*50) + (data2*15))
191
192 def test_many_append(self):
193 # Bug #1074261 was triggered when reading a file that contained
194 # many, many members. Create such a file and verify that reading it
195 # works.
196 with gzip.GzipFile(self.filename, 'wb', 9) as f:
197 f.write(b'a')
198 for i in range(0, 200):
199 with gzip.GzipFile(self.filename, "ab", 9) as f: # append
200 f.write(b'a')
201
202 # Try reading the file
203 with gzip.GzipFile(self.filename, "rb") as zgfile:
204 contents = b""
205 while 1:
206 ztxt = zgfile.read(8192)
207 contents += ztxt
208 if not ztxt: break
209 self.assertEqual(contents, b'a'*201)
210
211 def test_exclusive_write(self):
212 with gzip.GzipFile(self.filename, 'xb') as f:
213 f.write(data1 * 50)
214 with gzip.GzipFile(self.filename, 'rb') as f:
215 self.assertEqual(f.read(), data1 * 50)
216 with self.assertRaises(FileExistsError):
217 gzip.GzipFile(self.filename, 'xb')
218
219 def test_buffered_reader(self):
220 # Issue #7471: a GzipFile can be wrapped in a BufferedReader for
221 # performance.
222 self.test_write()
223
224 with gzip.GzipFile(self.filename, 'rb') as f:
225 with io.BufferedReader(f) as r:
226 lines = [line for line in r]
227
228 self.assertEqual(lines, 50 * data1.splitlines(keepends=True))
229
230 def test_readline(self):
231 self.test_write()
232 # Try .readline() with varying line lengths
233
234 with gzip.GzipFile(self.filename, 'rb') as f:
235 line_length = 0
236 while 1:
237 L = f.readline(line_length)
238 if not L and line_length != 0: break
239 self.assertTrue(len(L) <= line_length)
240 line_length = (line_length + 1) % 50
241
242 def test_readlines(self):
243 self.test_write()
244 # Try .readlines()
245
246 with gzip.GzipFile(self.filename, 'rb') as f:
247 L = f.readlines()
248
249 with gzip.GzipFile(self.filename, 'rb') as f:
250 while 1:
251 L = f.readlines(150)
252 if L == []: break
253
254 def test_seek_read(self):
255 self.test_write()
256 # Try seek, read test
257
258 with gzip.GzipFile(self.filename) as f:
259 while 1:
260 oldpos = f.tell()
261 line1 = f.readline()
262 if not line1: break
263 newpos = f.tell()
264 f.seek(oldpos) # negative seek
265 if len(line1)>10:
266 amount = 10
267 else:
268 amount = len(line1)
269 line2 = f.read(amount)
270 self.assertEqual(line1[:amount], line2)
271 f.seek(newpos) # positive seek
272
273 def test_seek_whence(self):
274 self.test_write()
275 # Try seek(whence=1), read test
276
277 with gzip.GzipFile(self.filename) as f:
278 f.read(10)
279 f.seek(10, whence=1)
280 y = f.read(10)
281 self.assertEqual(y, data1[20:30])
282
283 def test_seek_write(self):
284 # Try seek, write test
285 with gzip.GzipFile(self.filename, 'w') as f:
286 for pos in range(0, 256, 16):
287 f.seek(pos)
288 f.write(b'GZ\n')
289
290 def test_mode(self):
291 self.test_write()
292 with gzip.GzipFile(self.filename, 'r') as f:
293 self.assertEqual(f.myfileobj.mode, 'rb')
294 os_helper.unlink(self.filename)
295 with gzip.GzipFile(self.filename, 'x') as f:
296 self.assertEqual(f.myfileobj.mode, 'xb')
297
298 def test_1647484(self):
299 for mode in ('wb', 'rb'):
300 with gzip.GzipFile(self.filename, mode) as f:
301 self.assertTrue(hasattr(f, "name"))
302 self.assertEqual(f.name, self.filename)
303
304 def test_paddedfile_getattr(self):
305 self.test_write()
306 with gzip.GzipFile(self.filename, 'rb') as f:
307 self.assertTrue(hasattr(f.fileobj, "name"))
308 self.assertEqual(f.fileobj.name, self.filename)
309
310 def test_mtime(self):
311 mtime = 123456789
312 with gzip.GzipFile(self.filename, 'w', mtime = mtime) as fWrite:
313 fWrite.write(data1)
314 with gzip.GzipFile(self.filename) as fRead:
315 self.assertTrue(hasattr(fRead, 'mtime'))
316 self.assertIsNone(fRead.mtime)
317 dataRead = fRead.read()
318 self.assertEqual(dataRead, data1)
319 self.assertEqual(fRead.mtime, mtime)
320
321 def test_metadata(self):
322 mtime = 123456789
323
324 with gzip.GzipFile(self.filename, 'w', mtime = mtime) as fWrite:
325 fWrite.write(data1)
326
327 with open(self.filename, 'rb') as fRead:
328 # see RFC 1952: http://www.faqs.org/rfcs/rfc1952.html
329
330 idBytes = fRead.read(2)
331 self.assertEqual(idBytes, b'\x1f\x8b') # gzip ID
332
333 cmByte = fRead.read(1)
334 self.assertEqual(cmByte, b'\x08') # deflate
335
336 try:
337 expectedname = self.filename.encode('Latin-1') + b'\x00'
338 expectedflags = b'\x08' # only the FNAME flag is set
339 except UnicodeEncodeError:
340 expectedname = b''
341 expectedflags = b'\x00'
342
343 flagsByte = fRead.read(1)
344 self.assertEqual(flagsByte, expectedflags)
345
346 mtimeBytes = fRead.read(4)
347 self.assertEqual(mtimeBytes, struct.pack('<i', mtime)) # little-endian
348
349 xflByte = fRead.read(1)
350 self.assertEqual(xflByte, b'\x02') # maximum compression
351
352 osByte = fRead.read(1)
353 self.assertEqual(osByte, b'\xff') # OS "unknown" (OS-independent)
354
355 # Since the FNAME flag is set, the zero-terminated filename follows.
356 # RFC 1952 specifies that this is the name of the input file, if any.
357 # However, the gzip module defaults to storing the name of the output
358 # file in this field.
359 nameBytes = fRead.read(len(expectedname))
360 self.assertEqual(nameBytes, expectedname)
361
362 # Since no other flags were set, the header ends here.
363 # Rather than process the compressed data, let's seek to the trailer.
364 fRead.seek(os.stat(self.filename).st_size - 8)
365
366 crc32Bytes = fRead.read(4) # CRC32 of uncompressed data [data1]
367 self.assertEqual(crc32Bytes, b'\xaf\xd7d\x83')
368
369 isizeBytes = fRead.read(4)
370 self.assertEqual(isizeBytes, struct.pack('<i', len(data1)))
371
372 def test_metadata_ascii_name(self):
373 self.filename = os_helper.TESTFN_ASCII
374 self.test_metadata()
375
376 def test_compresslevel_metadata(self):
377 # see RFC 1952: http://www.faqs.org/rfcs/rfc1952.html
378 # specifically, discussion of XFL in section 2.3.1
379 cases = [
380 ('fast', 1, b'\x04'),
381 ('best', 9, b'\x02'),
382 ('tradeoff', 6, b'\x00'),
383 ]
384 xflOffset = 8
385
386 for (name, level, expectedXflByte) in cases:
387 with self.subTest(name):
388 fWrite = gzip.GzipFile(self.filename, 'w', compresslevel=level)
389 with fWrite:
390 fWrite.write(data1)
391 with open(self.filename, 'rb') as fRead:
392 fRead.seek(xflOffset)
393 xflByte = fRead.read(1)
394 self.assertEqual(xflByte, expectedXflByte)
395
396 def test_with_open(self):
397 # GzipFile supports the context management protocol
398 with gzip.GzipFile(self.filename, "wb") as f:
399 f.write(b"xxx")
400 f = gzip.GzipFile(self.filename, "rb")
401 f.close()
402 try:
403 with f:
404 pass
405 except ValueError:
406 pass
407 else:
408 self.fail("__enter__ on a closed file didn't raise an exception")
409 try:
410 with gzip.GzipFile(self.filename, "wb") as f:
411 1/0
412 except ZeroDivisionError:
413 pass
414 else:
415 self.fail("1/0 didn't raise an exception")
416
417 def test_zero_padded_file(self):
418 with gzip.GzipFile(self.filename, "wb") as f:
419 f.write(data1 * 50)
420
421 # Pad the file with zeroes
422 with open(self.filename, "ab") as f:
423 f.write(b"\x00" * 50)
424
425 with gzip.GzipFile(self.filename, "rb") as f:
426 d = f.read()
427 self.assertEqual(d, data1 * 50, "Incorrect data in file")
428
429 def test_gzip_BadGzipFile_exception(self):
430 self.assertTrue(issubclass(gzip.BadGzipFile, OSError))
431
432 def test_bad_gzip_file(self):
433 with open(self.filename, 'wb') as file:
434 file.write(data1 * 50)
435 with gzip.GzipFile(self.filename, 'r') as file:
436 self.assertRaises(gzip.BadGzipFile, file.readlines)
437
438 def test_non_seekable_file(self):
439 uncompressed = data1 * 50
440 buf = UnseekableIO()
441 with gzip.GzipFile(fileobj=buf, mode="wb") as f:
442 f.write(uncompressed)
443 compressed = buf.getvalue()
444 buf = UnseekableIO(compressed)
445 with gzip.GzipFile(fileobj=buf, mode="rb") as f:
446 self.assertEqual(f.read(), uncompressed)
447
448 def test_peek(self):
449 uncompressed = data1 * 200
450 with gzip.GzipFile(self.filename, "wb") as f:
451 f.write(uncompressed)
452
453 def sizes():
454 while True:
455 for n in range(5, 50, 10):
456 yield n
457
458 with gzip.GzipFile(self.filename, "rb") as f:
459 f.max_read_chunk = 33
460 nread = 0
461 for n in sizes():
462 s = f.peek(n)
463 if s == b'':
464 break
465 self.assertEqual(f.read(len(s)), s)
466 nread += len(s)
467 self.assertEqual(f.read(100), b'')
468 self.assertEqual(nread, len(uncompressed))
469
470 def test_textio_readlines(self):
471 # Issue #10791: TextIOWrapper.readlines() fails when wrapping GzipFile.
472 lines = (data1 * 50).decode("ascii").splitlines(keepends=True)
473 self.test_write()
474 with gzip.GzipFile(self.filename, 'r') as f:
475 with io.TextIOWrapper(f, encoding="ascii") as t:
476 self.assertEqual(t.readlines(), lines)
477
478 def test_fileobj_with_name(self):
479 with open(self.filename, "xb") as raw:
480 with gzip.GzipFile(fileobj=raw, mode="x") as f:
481 f.write(b'one')
482 self.assertEqual(f.name, raw.name)
483 self.assertEqual(f.fileno(), raw.fileno())
484 self.assertEqual(f.mode, gzip.WRITE)
485 self.assertIs(f.readable(), False)
486 self.assertIs(f.writable(), True)
487 self.assertIs(f.seekable(), True)
488 self.assertIs(f.closed, False)
489 self.assertIs(f.closed, True)
490 self.assertEqual(f.name, raw.name)
491 self.assertRaises(AttributeError, f.fileno)
492 self.assertEqual(f.mode, gzip.WRITE)
493 self.assertIs(f.readable(), False)
494 self.assertIs(f.writable(), True)
495 self.assertIs(f.seekable(), True)
496
497 with open(self.filename, "wb") as raw:
498 with gzip.GzipFile(fileobj=raw, mode="w") as f:
499 f.write(b'two')
500 self.assertEqual(f.name, raw.name)
501 self.assertEqual(f.fileno(), raw.fileno())
502 self.assertEqual(f.mode, gzip.WRITE)
503 self.assertIs(f.readable(), False)
504 self.assertIs(f.writable(), True)
505 self.assertIs(f.seekable(), True)
506 self.assertIs(f.closed, False)
507 self.assertIs(f.closed, True)
508 self.assertEqual(f.name, raw.name)
509 self.assertRaises(AttributeError, f.fileno)
510 self.assertEqual(f.mode, gzip.WRITE)
511 self.assertIs(f.readable(), False)
512 self.assertIs(f.writable(), True)
513 self.assertIs(f.seekable(), True)
514
515 with open(self.filename, "ab") as raw:
516 with gzip.GzipFile(fileobj=raw, mode="a") as f:
517 f.write(b'three')
518 self.assertEqual(f.name, raw.name)
519 self.assertEqual(f.fileno(), raw.fileno())
520 self.assertEqual(f.mode, gzip.WRITE)
521 self.assertIs(f.readable(), False)
522 self.assertIs(f.writable(), True)
523 self.assertIs(f.seekable(), True)
524 self.assertIs(f.closed, False)
525 self.assertIs(f.closed, True)
526 self.assertEqual(f.name, raw.name)
527 self.assertRaises(AttributeError, f.fileno)
528 self.assertEqual(f.mode, gzip.WRITE)
529 self.assertIs(f.readable(), False)
530 self.assertIs(f.writable(), True)
531 self.assertIs(f.seekable(), True)
532
533 with open(self.filename, "rb") as raw:
534 with gzip.GzipFile(fileobj=raw, mode="r") as f:
535 self.assertEqual(f.read(), b'twothree')
536 self.assertEqual(f.name, raw.name)
537 self.assertEqual(f.fileno(), raw.fileno())
538 self.assertEqual(f.mode, gzip.READ)
539 self.assertIs(f.readable(), True)
540 self.assertIs(f.writable(), False)
541 self.assertIs(f.seekable(), True)
542 self.assertIs(f.closed, False)
543 self.assertIs(f.closed, True)
544 self.assertEqual(f.name, raw.name)
545 self.assertRaises(AttributeError, f.fileno)
546 self.assertEqual(f.mode, gzip.READ)
547 self.assertIs(f.readable(), True)
548 self.assertIs(f.writable(), False)
549 self.assertIs(f.seekable(), True)
550
551 def test_fileobj_from_fdopen(self):
552 # Issue #13781: Opening a GzipFile for writing fails when using a
553 # fileobj created with os.fdopen().
554 fd = os.open(self.filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
555 with os.fdopen(fd, "xb") as raw:
556 with gzip.GzipFile(fileobj=raw, mode="x") as f:
557 f.write(b'one')
558 self.assertEqual(f.name, '')
559 self.assertEqual(f.fileno(), raw.fileno())
560 self.assertIs(f.closed, True)
561 self.assertEqual(f.name, '')
562 self.assertRaises(AttributeError, f.fileno)
563
564 fd = os.open(self.filename, os.O_WRONLY | os.O_CREAT | os.O_TRUNC)
565 with os.fdopen(fd, "wb") as raw:
566 with gzip.GzipFile(fileobj=raw, mode="w") as f:
567 f.write(b'two')
568 self.assertEqual(f.name, '')
569 self.assertEqual(f.fileno(), raw.fileno())
570 self.assertEqual(f.name, '')
571 self.assertRaises(AttributeError, f.fileno)
572
573 fd = os.open(self.filename, os.O_WRONLY | os.O_CREAT | os.O_APPEND)
574 with os.fdopen(fd, "ab") as raw:
575 with gzip.GzipFile(fileobj=raw, mode="a") as f:
576 f.write(b'three')
577 self.assertEqual(f.name, '')
578 self.assertEqual(f.fileno(), raw.fileno())
579 self.assertEqual(f.name, '')
580 self.assertRaises(AttributeError, f.fileno)
581
582 fd = os.open(self.filename, os.O_RDONLY)
583 with os.fdopen(fd, "rb") as raw:
584 with gzip.GzipFile(fileobj=raw, mode="r") as f:
585 self.assertEqual(f.read(), b'twothree')
586 self.assertEqual(f.name, '')
587 self.assertEqual(f.fileno(), raw.fileno())
588 self.assertEqual(f.name, '')
589 self.assertRaises(AttributeError, f.fileno)
590
591 def test_fileobj_mode(self):
592 self.assertEqual(gzip.READ, 'rb')
593 self.assertEqual(gzip.WRITE, 'wb')
594 gzip.GzipFile(self.filename, "wb").close()
595 with open(self.filename, "r+b") as f:
596 with gzip.GzipFile(fileobj=f, mode='r') as g:
597 self.assertEqual(g.mode, gzip.READ)
598 with gzip.GzipFile(fileobj=f, mode='w') as g:
599 self.assertEqual(g.mode, gzip.WRITE)
600 with gzip.GzipFile(fileobj=f, mode='a') as g:
601 self.assertEqual(g.mode, gzip.WRITE)
602 with gzip.GzipFile(fileobj=f, mode='x') as g:
603 self.assertEqual(g.mode, gzip.WRITE)
604 with self.assertRaises(ValueError):
605 gzip.GzipFile(fileobj=f, mode='z')
606 for mode in "rb", "r+b":
607 with open(self.filename, mode) as f:
608 with gzip.GzipFile(fileobj=f) as g:
609 self.assertEqual(g.mode, gzip.READ)
610 for mode in "wb", "ab", "xb":
611 if "x" in mode:
612 os_helper.unlink(self.filename)
613 with open(self.filename, mode) as f:
614 with self.assertWarns(FutureWarning):
615 g = gzip.GzipFile(fileobj=f)
616 with g:
617 self.assertEqual(g.mode, gzip.WRITE)
618
619 def test_bytes_filename(self):
620 str_filename = self.filename
621 bytes_filename = os.fsencode(str_filename)
622 with gzip.GzipFile(bytes_filename, "wb") as f:
623 f.write(data1 * 50)
624 self.assertEqual(f.name, bytes_filename)
625 with gzip.GzipFile(bytes_filename, "rb") as f:
626 self.assertEqual(f.read(), data1 * 50)
627 self.assertEqual(f.name, bytes_filename)
628 # Sanity check that we are actually operating on the right file.
629 with gzip.GzipFile(str_filename, "rb") as f:
630 self.assertEqual(f.read(), data1 * 50)
631 self.assertEqual(f.name, str_filename)
632
633 def test_fileobj_without_name(self):
634 bio = io.BytesIO()
635 with gzip.GzipFile(fileobj=bio, mode='wb') as f:
636 f.write(data1 * 50)
637 self.assertEqual(f.name, '')
638 self.assertRaises(io.UnsupportedOperation, f.fileno)
639 self.assertEqual(f.mode, gzip.WRITE)
640 self.assertIs(f.readable(), False)
641 self.assertIs(f.writable(), True)
642 self.assertIs(f.seekable(), True)
643 self.assertIs(f.closed, False)
644 self.assertIs(f.closed, True)
645 self.assertEqual(f.name, '')
646 self.assertRaises(AttributeError, f.fileno)
647 self.assertEqual(f.mode, gzip.WRITE)
648 self.assertIs(f.readable(), False)
649 self.assertIs(f.writable(), True)
650 self.assertIs(f.seekable(), True)
651
652 bio.seek(0)
653 with gzip.GzipFile(fileobj=bio, mode='rb') as f:
654 self.assertEqual(f.read(), data1 * 50)
655 self.assertEqual(f.name, '')
656 self.assertRaises(io.UnsupportedOperation, f.fileno)
657 self.assertEqual(f.mode, gzip.READ)
658 self.assertIs(f.readable(), True)
659 self.assertIs(f.writable(), False)
660 self.assertIs(f.seekable(), True)
661 self.assertIs(f.closed, False)
662 self.assertIs(f.closed, True)
663 self.assertEqual(f.name, '')
664 self.assertRaises(AttributeError, f.fileno)
665 self.assertEqual(f.mode, gzip.READ)
666 self.assertIs(f.readable(), True)
667 self.assertIs(f.writable(), False)
668 self.assertIs(f.seekable(), True)
669
670 def test_fileobj_and_filename(self):
671 filename2 = self.filename + 'new'
672 with (open(self.filename, 'wb') as fileobj,
673 gzip.GzipFile(fileobj=fileobj, filename=filename2, mode='wb') as f):
674 f.write(data1 * 50)
675 self.assertEqual(f.name, filename2)
676 with (open(self.filename, 'rb') as fileobj,
677 gzip.GzipFile(fileobj=fileobj, filename=filename2, mode='rb') as f):
678 self.assertEqual(f.read(), data1 * 50)
679 self.assertEqual(f.name, filename2)
680 # Sanity check that we are actually operating on the right file.
681 with gzip.GzipFile(self.filename, 'rb') as f:
682 self.assertEqual(f.read(), data1 * 50)
683 self.assertEqual(f.name, self.filename)
684
685 def test_decompress_limited(self):
686 """Decompressed data buffering should be limited"""
687 bomb = gzip.compress(b'\0' * int(2e6), compresslevel=9)
688 self.assertLess(len(bomb), io.DEFAULT_BUFFER_SIZE)
689
690 bomb = io.BytesIO(bomb)
691 decomp = gzip.GzipFile(fileobj=bomb)
692 self.assertEqual(decomp.read(1), b'\0')
693 max_decomp = 1 + io.DEFAULT_BUFFER_SIZE
694 self.assertLessEqual(decomp._buffer.raw.tell(), max_decomp,
695 "Excessive amount of data was decompressed")
696
697 # Testing compress/decompress shortcut functions
698
699 def test_compress(self):
700 for data in [data1, data2]:
701 for args in [(), (1,), (6,), (9,)]:
702 datac = gzip.compress(data, *args)
703 self.assertEqual(type(datac), bytes)
704 with gzip.GzipFile(fileobj=io.BytesIO(datac), mode="rb") as f:
705 self.assertEqual(f.read(), data)
706
707 def test_compress_mtime(self):
708 mtime = 123456789
709 for data in [data1, data2]:
710 for args in [(), (1,), (6,), (9,)]:
711 with self.subTest(data=data, args=args):
712 datac = gzip.compress(data, *args, mtime=mtime)
713 self.assertEqual(type(datac), bytes)
714 with gzip.GzipFile(fileobj=io.BytesIO(datac), mode="rb") as f:
715 f.read(1) # to set mtime attribute
716 self.assertEqual(f.mtime, mtime)
717
718 def test_compress_correct_level(self):
719 for mtime in (0, 42):
720 with self.subTest(mtime=mtime):
721 nocompress = gzip.compress(data1, compresslevel=0, mtime=mtime)
722 yescompress = gzip.compress(data1, compresslevel=1, mtime=mtime)
723 self.assertIn(data1, nocompress)
724 self.assertNotIn(data1, yescompress)
725
726 def test_issue112346(self):
727 # The OS byte should be 255, this should not change between Python versions.
728 for mtime in (0, 42):
729 with self.subTest(mtime=mtime):
730 compress = gzip.compress(data1, compresslevel=1, mtime=mtime)
731 self.assertEqual(
732 struct.unpack("<IxB", compress[4:10]),
733 (mtime, 255),
734 "Gzip header does not properly set either mtime or OS byte."
735 )
736
737 def test_decompress(self):
738 for data in (data1, data2):
739 buf = io.BytesIO()
740 with gzip.GzipFile(fileobj=buf, mode="wb") as f:
741 f.write(data)
742 self.assertEqual(gzip.decompress(buf.getvalue()), data)
743 # Roundtrip with compress
744 datac = gzip.compress(data)
745 self.assertEqual(gzip.decompress(datac), data)
746
747 def test_decompress_truncated_trailer(self):
748 compressed_data = gzip.compress(data1)
749 self.assertRaises(EOFError, gzip.decompress, compressed_data[:-4])
750
751 def test_decompress_missing_trailer(self):
752 compressed_data = gzip.compress(data1)
753 self.assertRaises(EOFError, gzip.decompress, compressed_data[:-8])
754
755 def test_read_truncated(self):
756 data = data1*50
757 # Drop the CRC (4 bytes) and file size (4 bytes).
758 truncated = gzip.compress(data)[:-8]
759 with gzip.GzipFile(fileobj=io.BytesIO(truncated)) as f:
760 self.assertRaises(EOFError, f.read)
761 with gzip.GzipFile(fileobj=io.BytesIO(truncated)) as f:
762 self.assertEqual(f.read(len(data)), data)
763 self.assertRaises(EOFError, f.read, 1)
764 # Incomplete 10-byte header.
765 for i in range(2, 10):
766 with gzip.GzipFile(fileobj=io.BytesIO(truncated[:i])) as f:
767 self.assertRaises(EOFError, f.read, 1)
768
769 def test_read_with_extra(self):
770 # Gzip data with an extra field
771 gzdata = (b'\x1f\x8b\x08\x04\xb2\x17cQ\x02\xff'
772 b'\x05\x00Extra'
773 b'\x0bI-.\x01\x002\xd1Mx\x04\x00\x00\x00')
774 with gzip.GzipFile(fileobj=io.BytesIO(gzdata)) as f:
775 self.assertEqual(f.read(), b'Test')
776
777 def test_prepend_error(self):
778 # See issue #20875
779 with gzip.open(self.filename, "wb") as f:
780 f.write(data1)
781 with gzip.open(self.filename, "rb") as f:
782 f._buffer.raw._fp.prepend()
783
784 def test_issue44439(self):
785 q = array.array('Q', [1, 2, 3, 4, 5])
786 LENGTH = len(q) * q.itemsize
787
788 with gzip.GzipFile(fileobj=io.BytesIO(), mode='w') as f:
789 self.assertEqual(f.write(q), LENGTH)
790 self.assertEqual(f.tell(), LENGTH)
791
792 def test_flush_flushes_compressor(self):
793 # See issue GH-105808.
794 b = io.BytesIO()
795 message = b"important message here."
796 with gzip.GzipFile(fileobj=b, mode='w') as f:
797 f.write(message)
798 f.flush()
799 partial_data = b.getvalue()
800 full_data = b.getvalue()
801 self.assertEqual(gzip.decompress(full_data), message)
802 # The partial data should contain the gzip header and the complete
803 # message, but not the end-of-stream markers (so we can't just
804 # decompress it directly).
805 with self.assertRaises(EOFError):
806 gzip.decompress(partial_data)
807 d = zlib.decompressobj(wbits=-zlib.MAX_WBITS)
808 f = io.BytesIO(partial_data)
809 gzip._read_gzip_header(f)
810 read_message = d.decompress(f.read())
811 self.assertEqual(read_message, message)
812
813 def test_flush_modes(self):
814 # Make sure the argument to flush is properly passed to the
815 # zlib.compressobj; see issue GH-105808.
816 class FakeCompressor:
817 def __init__(self):
818 self.modes = []
819 def compress(self, data):
820 return b''
821 def flush(self, mode=-1):
822 self.modes.append(mode)
823 return b''
824 b = io.BytesIO()
825 fc = FakeCompressor()
826 with gzip.GzipFile(fileobj=b, mode='w') as f:
827 f.compress = fc
828 f.flush()
829 f.flush(50)
830 f.flush(zlib_mode=100)
831 # The implicit close will also flush the compressor.
832 expected_modes = [
833 zlib.Z_SYNC_FLUSH,
834 50,
835 100,
836 -1,
837 ]
838 self.assertEqual(fc.modes, expected_modes)
839
840 def test_write_seek_write(self):
841 # Make sure that offset is up-to-date before seeking
842 # See issue GH-108111
843 b = io.BytesIO()
844 message = b"important message here."
845 with gzip.GzipFile(fileobj=b, mode='w') as f:
846 f.write(message)
847 f.seek(len(message))
848 f.write(message)
849 data = b.getvalue()
850 self.assertEqual(gzip.decompress(data), message * 2)
851
852
853 def test_refloop_unraisable(self):
854 # Ensure a GzipFile referring to a temporary fileobj deletes cleanly.
855 # Previously an unraisable exception would occur on close because the
856 # fileobj would be closed before the GzipFile as the result of a
857 # reference loop. See issue gh-129726
858 with catch_unraisable_exception() as cm:
859 gzip.GzipFile(fileobj=io.BytesIO(), mode="w")
860 gc.collect()
861 self.assertIsNone(cm.unraisable)
862
863
864 class TestOpen(BaseTest):
865 def test_binary_modes(self):
866 uncompressed = data1 * 50
867
868 with gzip.open(self.filename, "wb") as f:
869 f.write(uncompressed)
870 with open(self.filename, "rb") as f:
871 file_data = gzip.decompress(f.read())
872 self.assertEqual(file_data, uncompressed)
873
874 with gzip.open(self.filename, "rb") as f:
875 self.assertEqual(f.read(), uncompressed)
876
877 with gzip.open(self.filename, "ab") as f:
878 f.write(uncompressed)
879 with open(self.filename, "rb") as f:
880 file_data = gzip.decompress(f.read())
881 self.assertEqual(file_data, uncompressed * 2)
882
883 with self.assertRaises(FileExistsError):
884 gzip.open(self.filename, "xb")
885 os_helper.unlink(self.filename)
886 with gzip.open(self.filename, "xb") as f:
887 f.write(uncompressed)
888 with open(self.filename, "rb") as f:
889 file_data = gzip.decompress(f.read())
890 self.assertEqual(file_data, uncompressed)
891
892 def test_pathlike_file(self):
893 filename = os_helper.FakePath(self.filename)
894 with gzip.open(filename, "wb") as f:
895 f.write(data1 * 50)
896 self.assertEqual(f.name, self.filename)
897 with gzip.open(filename, "ab") as f:
898 f.write(data1)
899 self.assertEqual(f.name, self.filename)
900 with gzip.open(filename) as f:
901 self.assertEqual(f.read(), data1 * 51)
902 self.assertEqual(f.name, self.filename)
903
904 def test_implicit_binary_modes(self):
905 # Test implicit binary modes (no "b" or "t" in mode string).
906 uncompressed = data1 * 50
907
908 with gzip.open(self.filename, "w") as f:
909 f.write(uncompressed)
910 with open(self.filename, "rb") as f:
911 file_data = gzip.decompress(f.read())
912 self.assertEqual(file_data, uncompressed)
913
914 with gzip.open(self.filename, "r") as f:
915 self.assertEqual(f.read(), uncompressed)
916
917 with gzip.open(self.filename, "a") as f:
918 f.write(uncompressed)
919 with open(self.filename, "rb") as f:
920 file_data = gzip.decompress(f.read())
921 self.assertEqual(file_data, uncompressed * 2)
922
923 with self.assertRaises(FileExistsError):
924 gzip.open(self.filename, "x")
925 os_helper.unlink(self.filename)
926 with gzip.open(self.filename, "x") as f:
927 f.write(uncompressed)
928 with open(self.filename, "rb") as f:
929 file_data = gzip.decompress(f.read())
930 self.assertEqual(file_data, uncompressed)
931
932 def test_text_modes(self):
933 uncompressed = data1.decode("ascii") * 50
934 uncompressed_raw = uncompressed.replace("\n", os.linesep)
935 with gzip.open(self.filename, "wt", encoding="ascii") as f:
936 f.write(uncompressed)
937 with open(self.filename, "rb") as f:
938 file_data = gzip.decompress(f.read()).decode("ascii")
939 self.assertEqual(file_data, uncompressed_raw)
940 with gzip.open(self.filename, "rt", encoding="ascii") as f:
941 self.assertEqual(f.read(), uncompressed)
942 with gzip.open(self.filename, "at", encoding="ascii") as f:
943 f.write(uncompressed)
944 with open(self.filename, "rb") as f:
945 file_data = gzip.decompress(f.read()).decode("ascii")
946 self.assertEqual(file_data, uncompressed_raw * 2)
947
948 def test_fileobj(self):
949 uncompressed_bytes = data1 * 50
950 uncompressed_str = uncompressed_bytes.decode("ascii")
951 compressed = gzip.compress(uncompressed_bytes)
952 with gzip.open(io.BytesIO(compressed), "r") as f:
953 self.assertEqual(f.read(), uncompressed_bytes)
954 with gzip.open(io.BytesIO(compressed), "rb") as f:
955 self.assertEqual(f.read(), uncompressed_bytes)
956 with gzip.open(io.BytesIO(compressed), "rt", encoding="ascii") as f:
957 self.assertEqual(f.read(), uncompressed_str)
958
959 def test_bad_params(self):
960 # Test invalid parameter combinations.
961 with self.assertRaises(TypeError):
962 gzip.open(123.456)
963 with self.assertRaises(ValueError):
964 gzip.open(self.filename, "wbt")
965 with self.assertRaises(ValueError):
966 gzip.open(self.filename, "xbt")
967 with self.assertRaises(ValueError):
968 gzip.open(self.filename, "rb", encoding="utf-8")
969 with self.assertRaises(ValueError):
970 gzip.open(self.filename, "rb", errors="ignore")
971 with self.assertRaises(ValueError):
972 gzip.open(self.filename, "rb", newline="\n")
973
974 def test_encoding(self):
975 # Test non-default encoding.
976 uncompressed = data1.decode("ascii") * 50
977 uncompressed_raw = uncompressed.replace("\n", os.linesep)
978 with gzip.open(self.filename, "wt", encoding="utf-16") as f:
979 f.write(uncompressed)
980 with open(self.filename, "rb") as f:
981 file_data = gzip.decompress(f.read()).decode("utf-16")
982 self.assertEqual(file_data, uncompressed_raw)
983 with gzip.open(self.filename, "rt", encoding="utf-16") as f:
984 self.assertEqual(f.read(), uncompressed)
985
986 def test_encoding_error_handler(self):
987 # Test with non-default encoding error handler.
988 with gzip.open(self.filename, "wb") as f:
989 f.write(b"foo\xffbar")
990 with gzip.open(self.filename, "rt", encoding="ascii", errors="ignore") \
991 as f:
992 self.assertEqual(f.read(), "foobar")
993
994 def test_newline(self):
995 # Test with explicit newline (universal newline mode disabled).
996 uncompressed = data1.decode("ascii") * 50
997 with gzip.open(self.filename, "wt", encoding="ascii", newline="\n") as f:
998 f.write(uncompressed)
999 with gzip.open(self.filename, "rt", encoding="ascii", newline="\r") as f:
1000 self.assertEqual(f.readlines(), [uncompressed])
1001
1002
1003 def create_and_remove_directory(directory):
1004 def decorator(function):
1005 @functools.wraps(function)
1006 def wrapper(*args, **kwargs):
1007 os.makedirs(directory)
1008 try:
1009 return function(*args, **kwargs)
1010 finally:
1011 os_helper.rmtree(directory)
1012 return wrapper
1013 return decorator
1014
1015
1016 class TestCommandLine(unittest.TestCase):
1017 data = b'This is a simple test with gzip'
1018
1019 @requires_subprocess()
1020 def test_decompress_stdin_stdout(self):
1021 with io.BytesIO() as bytes_io:
1022 with gzip.GzipFile(fileobj=bytes_io, mode='wb') as gzip_file:
1023 gzip_file.write(self.data)
1024
1025 args = sys.executable, '-m', 'gzip', '-d'
1026 with Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE) as proc:
1027 out, err = proc.communicate(bytes_io.getvalue())
1028
1029 self.assertEqual(err, b'')
1030 self.assertEqual(out, self.data)
1031
1032 @create_and_remove_directory(TEMPDIR)
1033 def test_decompress_infile_outfile(self):
1034 gzipname = os.path.join(TEMPDIR, 'testgzip.gz')
1035 self.assertFalse(os.path.exists(gzipname))
1036
1037 with gzip.open(gzipname, mode='wb') as fp:
1038 fp.write(self.data)
1039 rc, out, err = assert_python_ok('-m', 'gzip', '-d', gzipname)
1040
1041 with open(os.path.join(TEMPDIR, "testgzip"), "rb") as gunziped:
1042 self.assertEqual(gunziped.read(), self.data)
1043
1044 self.assertTrue(os.path.exists(gzipname))
1045 self.assertEqual(rc, 0)
1046 self.assertEqual(out, b'')
1047 self.assertEqual(err, b'')
1048
1049 def test_decompress_infile_outfile_error(self):
1050 rc, out, err = assert_python_failure('-m', 'gzip', '-d', 'thisisatest.out')
1051 self.assertEqual(b"filename doesn't end in .gz: 'thisisatest.out'", err.strip())
1052 self.assertEqual(rc, 1)
1053 self.assertEqual(out, b'')
1054
1055 @requires_subprocess()
1056 @create_and_remove_directory(TEMPDIR)
1057 def test_compress_stdin_outfile(self):
1058 args = sys.executable, '-m', 'gzip'
1059 with Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE) as proc:
1060 out, err = proc.communicate(self.data)
1061
1062 self.assertEqual(err, b'')
1063 self.assertEqual(out[:2], b"\x1f\x8b")
1064
1065 @create_and_remove_directory(TEMPDIR)
1066 def test_compress_infile_outfile_default(self):
1067 local_testgzip = os.path.join(TEMPDIR, 'testgzip')
1068 gzipname = local_testgzip + '.gz'
1069 self.assertFalse(os.path.exists(gzipname))
1070
1071 with open(local_testgzip, 'wb') as fp:
1072 fp.write(self.data)
1073
1074 rc, out, err = assert_python_ok('-m', 'gzip', local_testgzip)
1075
1076 self.assertTrue(os.path.exists(gzipname))
1077 self.assertEqual(out, b'')
1078 self.assertEqual(err, b'')
1079
1080 @create_and_remove_directory(TEMPDIR)
1081 def test_compress_infile_outfile(self):
1082 for compress_level in ('--fast', '--best'):
1083 with self.subTest(compress_level=compress_level):
1084 local_testgzip = os.path.join(TEMPDIR, 'testgzip')
1085 gzipname = local_testgzip + '.gz'
1086 self.assertFalse(os.path.exists(gzipname))
1087
1088 with open(local_testgzip, 'wb') as fp:
1089 fp.write(self.data)
1090
1091 rc, out, err = assert_python_ok('-m', 'gzip', compress_level, local_testgzip)
1092
1093 self.assertTrue(os.path.exists(gzipname))
1094 self.assertEqual(out, b'')
1095 self.assertEqual(err, b'')
1096 os.remove(gzipname)
1097 self.assertFalse(os.path.exists(gzipname))
1098
1099 def test_compress_fast_best_are_exclusive(self):
1100 rc, out, err = assert_python_failure('-m', 'gzip', '--fast', '--best')
1101 self.assertIn(b"error: argument --best: not allowed with argument --fast", err)
1102 self.assertEqual(out, b'')
1103
1104 def test_decompress_cannot_have_flags_compression(self):
1105 rc, out, err = assert_python_failure('-m', 'gzip', '--fast', '-d')
1106 self.assertIn(b'error: argument -d/--decompress: not allowed with argument --fast', err)
1107 self.assertEqual(out, b'')
1108
1109
1110 if __name__ == "__main__":
1111 unittest.main()