Debian Codegraph @

lib-python/3/test/test_gzip.py

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