Debian Codegraph @

Lib/test/test_zipfile/test_core.py

raw
1 import _pyio
2 import array
3 import contextlib
4 import importlib.util
5 import io
6 import itertools
7 import os
8 import posixpath
9 import struct
10 import subprocess
11 import sys
12 import time
13 import unittest
14 import unittest.mock as mock
15 import zipfile
16
17
18 from tempfile import TemporaryFile
19 from random import randint, random, randbytes
20
21 from test import archiver_tests
22 from test.support import script_helper
23 from test.support import (
24 findfile, requires_zlib, requires_bz2, requires_lzma,
25 captured_stdout, captured_stderr, requires_subprocess
26 )
27 from test.support.os_helper import (
28 TESTFN, unlink, rmtree, temp_dir, temp_cwd, fd_count, FakePath
29 )
30
31
32 TESTFN2 = TESTFN + "2"
33 TESTFNDIR = TESTFN + "d"
34 FIXEDTEST_SIZE = 1000
35 DATAFILES_DIR = 'zipfile_datafiles'
36
37 SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'),
38 ('ziptest2dir/_ziptest2', 'qawsedrftg'),
39 ('ziptest2dir/ziptest3dir/_ziptest3', 'azsxdcfvgb'),
40 ('ziptest2dir/ziptest3dir/ziptest4dir/_ziptest3', '6y7u8i9o0p')]
41
42 def get_files(test):
43 yield TESTFN2
44 with TemporaryFile() as f:
45 yield f
46 test.assertFalse(f.closed)
47 with io.BytesIO() as f:
48 yield f
49 test.assertFalse(f.closed)
50
51 class AbstractTestsWithSourceFile:
52 @classmethod
53 def setUpClass(cls):
54 cls.line_gen = [bytes("Zipfile test line %d. random float: %f\n" %
55 (i, random()), "ascii")
56 for i in range(FIXEDTEST_SIZE)]
57 cls.data = b''.join(cls.line_gen)
58
59 def setUp(self):
60 # Make a source file with some lines
61 with open(TESTFN, "wb") as fp:
62 fp.write(self.data)
63
64 def make_test_archive(self, f, compression, compresslevel=None):
65 kwargs = {'compression': compression, 'compresslevel': compresslevel}
66 # Create the ZIP archive
67 with zipfile.ZipFile(f, "w", **kwargs) as zipfp:
68 zipfp.write(TESTFN, "another.name")
69 zipfp.write(TESTFN, TESTFN)
70 zipfp.writestr("strfile", self.data)
71 with zipfp.open('written-open-w', mode='w') as f:
72 for line in self.line_gen:
73 f.write(line)
74
75 def zip_test(self, f, compression, compresslevel=None):
76 self.make_test_archive(f, compression, compresslevel)
77
78 # Read the ZIP archive
79 with zipfile.ZipFile(f, "r", compression) as zipfp:
80 self.assertEqual(zipfp.read(TESTFN), self.data)
81 self.assertEqual(zipfp.read("another.name"), self.data)
82 self.assertEqual(zipfp.read("strfile"), self.data)
83
84 # Print the ZIP directory
85 fp = io.StringIO()
86 zipfp.printdir(file=fp)
87 directory = fp.getvalue()
88 lines = directory.splitlines()
89 self.assertEqual(len(lines), 5) # Number of files + header
90
91 self.assertIn('File Name', lines[0])
92 self.assertIn('Modified', lines[0])
93 self.assertIn('Size', lines[0])
94
95 fn, date, time_, size = lines[1].split()
96 self.assertEqual(fn, 'another.name')
97 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
98 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
99 self.assertEqual(size, str(len(self.data)))
100
101 # Check the namelist
102 names = zipfp.namelist()
103 self.assertEqual(len(names), 4)
104 self.assertIn(TESTFN, names)
105 self.assertIn("another.name", names)
106 self.assertIn("strfile", names)
107 self.assertIn("written-open-w", names)
108
109 # Check infolist
110 infos = zipfp.infolist()
111 names = [i.filename for i in infos]
112 self.assertEqual(len(names), 4)
113 self.assertIn(TESTFN, names)
114 self.assertIn("another.name", names)
115 self.assertIn("strfile", names)
116 self.assertIn("written-open-w", names)
117 for i in infos:
118 self.assertEqual(i.file_size, len(self.data))
119
120 # check getinfo
121 for nm in (TESTFN, "another.name", "strfile", "written-open-w"):
122 info = zipfp.getinfo(nm)
123 self.assertEqual(info.filename, nm)
124 self.assertEqual(info.file_size, len(self.data))
125
126 # Check that testzip thinks the archive is ok
127 # (it returns None if all contents could be read properly)
128 self.assertIsNone(zipfp.testzip())
129
130 def test_basic(self):
131 for f in get_files(self):
132 self.zip_test(f, self.compression)
133
134 def zip_open_test(self, f, compression):
135 self.make_test_archive(f, compression)
136
137 # Read the ZIP archive
138 with zipfile.ZipFile(f, "r", compression) as zipfp:
139 zipdata1 = []
140 with zipfp.open(TESTFN) as zipopen1:
141 while True:
142 read_data = zipopen1.read(256)
143 if not read_data:
144 break
145 zipdata1.append(read_data)
146
147 zipdata2 = []
148 with zipfp.open("another.name") as zipopen2:
149 while True:
150 read_data = zipopen2.read(256)
151 if not read_data:
152 break
153 zipdata2.append(read_data)
154
155 self.assertEqual(b''.join(zipdata1), self.data)
156 self.assertEqual(b''.join(zipdata2), self.data)
157
158 def test_open(self):
159 for f in get_files(self):
160 self.zip_open_test(f, self.compression)
161
162 def test_open_with_pathlike(self):
163 path = FakePath(TESTFN2)
164 self.zip_open_test(path, self.compression)
165 with zipfile.ZipFile(path, "r", self.compression) as zipfp:
166 self.assertIsInstance(zipfp.filename, str)
167
168 def zip_random_open_test(self, f, compression):
169 self.make_test_archive(f, compression)
170
171 # Read the ZIP archive
172 with zipfile.ZipFile(f, "r", compression) as zipfp:
173 zipdata1 = []
174 with zipfp.open(TESTFN) as zipopen1:
175 while True:
176 read_data = zipopen1.read(randint(1, 1024))
177 if not read_data:
178 break
179 zipdata1.append(read_data)
180
181 self.assertEqual(b''.join(zipdata1), self.data)
182
183 def test_random_open(self):
184 for f in get_files(self):
185 self.zip_random_open_test(f, self.compression)
186
187 def zip_read1_test(self, f, compression):
188 self.make_test_archive(f, compression)
189
190 # Read the ZIP archive
191 with zipfile.ZipFile(f, "r") as zipfp, \
192 zipfp.open(TESTFN) as zipopen:
193 zipdata = []
194 while True:
195 read_data = zipopen.read1(-1)
196 if not read_data:
197 break
198 zipdata.append(read_data)
199
200 self.assertEqual(b''.join(zipdata), self.data)
201
202 def test_read1(self):
203 for f in get_files(self):
204 self.zip_read1_test(f, self.compression)
205
206 def zip_read1_10_test(self, f, compression):
207 self.make_test_archive(f, compression)
208
209 # Read the ZIP archive
210 with zipfile.ZipFile(f, "r") as zipfp, \
211 zipfp.open(TESTFN) as zipopen:
212 zipdata = []
213 while True:
214 read_data = zipopen.read1(10)
215 self.assertLessEqual(len(read_data), 10)
216 if not read_data:
217 break
218 zipdata.append(read_data)
219
220 self.assertEqual(b''.join(zipdata), self.data)
221
222 def test_read1_10(self):
223 for f in get_files(self):
224 self.zip_read1_10_test(f, self.compression)
225
226 def zip_readline_read_test(self, f, compression):
227 self.make_test_archive(f, compression)
228
229 # Read the ZIP archive
230 with zipfile.ZipFile(f, "r") as zipfp, \
231 zipfp.open(TESTFN) as zipopen:
232 data = b''
233 while True:
234 read = zipopen.readline()
235 if not read:
236 break
237 data += read
238
239 read = zipopen.read(100)
240 if not read:
241 break
242 data += read
243
244 self.assertEqual(data, self.data)
245
246 def test_readline_read(self):
247 # Issue #7610: calls to readline() interleaved with calls to read().
248 for f in get_files(self):
249 self.zip_readline_read_test(f, self.compression)
250
251 def zip_readline_test(self, f, compression):
252 self.make_test_archive(f, compression)
253
254 # Read the ZIP archive
255 with zipfile.ZipFile(f, "r") as zipfp:
256 with zipfp.open(TESTFN) as zipopen:
257 for line in self.line_gen:
258 linedata = zipopen.readline()
259 self.assertEqual(linedata, line)
260
261 def test_readline(self):
262 for f in get_files(self):
263 self.zip_readline_test(f, self.compression)
264
265 def zip_readlines_test(self, f, compression):
266 self.make_test_archive(f, compression)
267
268 # Read the ZIP archive
269 with zipfile.ZipFile(f, "r") as zipfp:
270 with zipfp.open(TESTFN) as zipopen:
271 ziplines = zipopen.readlines()
272 for line, zipline in zip(self.line_gen, ziplines):
273 self.assertEqual(zipline, line)
274
275 def test_readlines(self):
276 for f in get_files(self):
277 self.zip_readlines_test(f, self.compression)
278
279 def zip_iterlines_test(self, f, compression):
280 self.make_test_archive(f, compression)
281
282 # Read the ZIP archive
283 with zipfile.ZipFile(f, "r") as zipfp:
284 with zipfp.open(TESTFN) as zipopen:
285 for line, zipline in zip(self.line_gen, zipopen):
286 self.assertEqual(zipline, line)
287
288 def test_iterlines(self):
289 for f in get_files(self):
290 self.zip_iterlines_test(f, self.compression)
291
292 def test_low_compression(self):
293 """Check for cases where compressed data is larger than original."""
294 # Create the ZIP archive
295 with zipfile.ZipFile(TESTFN2, "w", self.compression) as zipfp:
296 zipfp.writestr("strfile", '12')
297
298 # Get an open object for strfile
299 with zipfile.ZipFile(TESTFN2, "r", self.compression) as zipfp:
300 with zipfp.open("strfile") as openobj:
301 self.assertEqual(openobj.read(1), b'1')
302 self.assertEqual(openobj.read(1), b'2')
303
304 def test_writestr_compression(self):
305 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
306 zipfp.writestr("b.txt", "hello world", compress_type=self.compression)
307 info = zipfp.getinfo('b.txt')
308 self.assertEqual(info.compress_type, self.compression)
309
310 def test_writestr_compresslevel(self):
311 with zipfile.ZipFile(TESTFN2, "w", compresslevel=1) as zipfp:
312 zipfp.writestr("a.txt", "hello world", compress_type=self.compression)
313 zipfp.writestr("b.txt", "hello world", compress_type=self.compression,
314 compresslevel=2)
315
316 # Compression level follows the constructor.
317 a_info = zipfp.getinfo('a.txt')
318 self.assertEqual(a_info.compress_type, self.compression)
319 self.assertEqual(a_info.compress_level, 1)
320
321 # Compression level is overridden.
322 b_info = zipfp.getinfo('b.txt')
323 self.assertEqual(b_info.compress_type, self.compression)
324 self.assertEqual(b_info._compresslevel, 2)
325
326 def test_read_return_size(self):
327 # Issue #9837: ZipExtFile.read() shouldn't return more bytes
328 # than requested.
329 for test_size in (1, 4095, 4096, 4097, 16384):
330 file_size = test_size + 1
331 junk = randbytes(file_size)
332 with zipfile.ZipFile(io.BytesIO(), "w", self.compression) as zipf:
333 zipf.writestr('foo', junk)
334 with zipf.open('foo', 'r') as fp:
335 buf = fp.read(test_size)
336 self.assertEqual(len(buf), test_size)
337
338 def test_truncated_zipfile(self):
339 fp = io.BytesIO()
340 with zipfile.ZipFile(fp, mode='w') as zipf:
341 zipf.writestr('strfile', self.data, compress_type=self.compression)
342 end_offset = fp.tell()
343 zipfiledata = fp.getvalue()
344
345 fp = io.BytesIO(zipfiledata)
346 with zipfile.ZipFile(fp) as zipf:
347 with zipf.open('strfile') as zipopen:
348 fp.truncate(end_offset - 20)
349 with self.assertRaises(EOFError):
350 zipopen.read()
351
352 fp = io.BytesIO(zipfiledata)
353 with zipfile.ZipFile(fp) as zipf:
354 with zipf.open('strfile') as zipopen:
355 fp.truncate(end_offset - 20)
356 with self.assertRaises(EOFError):
357 while zipopen.read(100):
358 pass
359
360 fp = io.BytesIO(zipfiledata)
361 with zipfile.ZipFile(fp) as zipf:
362 with zipf.open('strfile') as zipopen:
363 fp.truncate(end_offset - 20)
364 with self.assertRaises(EOFError):
365 while zipopen.read1(100):
366 pass
367
368 def test_repr(self):
369 fname = 'file.name'
370 for f in get_files(self):
371 with zipfile.ZipFile(f, 'w', self.compression) as zipfp:
372 zipfp.write(TESTFN, fname)
373 r = repr(zipfp)
374 self.assertIn("mode='w'", r)
375
376 with zipfile.ZipFile(f, 'r') as zipfp:
377 r = repr(zipfp)
378 if isinstance(f, str):
379 self.assertIn('filename=%r' % f, r)
380 else:
381 self.assertIn('file=%r' % f, r)
382 self.assertIn("mode='r'", r)
383 r = repr(zipfp.getinfo(fname))
384 self.assertIn('filename=%r' % fname, r)
385 self.assertIn('filemode=', r)
386 self.assertIn('file_size=', r)
387 if self.compression != zipfile.ZIP_STORED:
388 self.assertIn('compress_type=', r)
389 self.assertIn('compress_size=', r)
390 with zipfp.open(fname) as zipopen:
391 r = repr(zipopen)
392 self.assertIn('name=%r' % fname, r)
393 if self.compression != zipfile.ZIP_STORED:
394 self.assertIn('compress_type=', r)
395 self.assertIn('[closed]', repr(zipopen))
396 self.assertIn('[closed]', repr(zipfp))
397
398 def test_compresslevel_basic(self):
399 for f in get_files(self):
400 self.zip_test(f, self.compression, compresslevel=9)
401
402 def test_per_file_compresslevel(self):
403 """Check that files within a Zip archive can have different
404 compression levels."""
405 with zipfile.ZipFile(TESTFN2, "w", compresslevel=1) as zipfp:
406 zipfp.write(TESTFN, 'compress_1')
407 zipfp.write(TESTFN, 'compress_9', compresslevel=9)
408 one_info = zipfp.getinfo('compress_1')
409 nine_info = zipfp.getinfo('compress_9')
410 self.assertEqual(one_info._compresslevel, 1)
411 self.assertEqual(nine_info.compress_level, 9)
412
413 def test_writing_errors(self):
414 class BrokenFile(io.BytesIO):
415 def write(self, data):
416 nonlocal count
417 if count is not None:
418 if count == stop:
419 raise OSError
420 count += 1
421 super().write(data)
422
423 stop = 0
424 while True:
425 testfile = BrokenFile()
426 count = None
427 with zipfile.ZipFile(testfile, 'w', self.compression) as zipfp:
428 with zipfp.open('file1', 'w') as f:
429 f.write(b'data1')
430 count = 0
431 try:
432 with zipfp.open('file2', 'w') as f:
433 f.write(b'data2')
434 except OSError:
435 stop += 1
436 else:
437 break
438 finally:
439 count = None
440 with zipfile.ZipFile(io.BytesIO(testfile.getvalue())) as zipfp:
441 self.assertEqual(zipfp.namelist(), ['file1'])
442 self.assertEqual(zipfp.read('file1'), b'data1')
443
444 with zipfile.ZipFile(io.BytesIO(testfile.getvalue())) as zipfp:
445 self.assertEqual(zipfp.namelist(), ['file1', 'file2'])
446 self.assertEqual(zipfp.read('file1'), b'data1')
447 self.assertEqual(zipfp.read('file2'), b'data2')
448
449 def test_zipextfile_attrs(self):
450 fname = "somefile.txt"
451 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
452 zipfp.writestr(fname, "bogus")
453
454 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
455 with zipfp.open(fname) as fid:
456 self.assertEqual(fid.name, fname)
457 self.assertRaises(io.UnsupportedOperation, fid.fileno)
458 self.assertEqual(fid.mode, 'rb')
459 self.assertIs(fid.readable(), True)
460 self.assertIs(fid.writable(), False)
461 self.assertIs(fid.seekable(), True)
462 self.assertIs(fid.closed, False)
463 self.assertIs(fid.closed, True)
464 self.assertEqual(fid.name, fname)
465 self.assertEqual(fid.mode, 'rb')
466 self.assertRaises(io.UnsupportedOperation, fid.fileno)
467 self.assertRaises(ValueError, fid.readable)
468 self.assertIs(fid.writable(), False)
469 self.assertRaises(ValueError, fid.seekable)
470
471 def tearDown(self):
472 unlink(TESTFN)
473 unlink(TESTFN2)
474
475
476 class StoredTestsWithSourceFile(AbstractTestsWithSourceFile,
477 unittest.TestCase):
478 compression = zipfile.ZIP_STORED
479 test_low_compression = None
480
481 def zip_test_writestr_permissions(self, f, compression):
482 # Make sure that writestr and open(... mode='w') create files with
483 # mode 0600, when they are passed a name rather than a ZipInfo
484 # instance.
485
486 self.make_test_archive(f, compression)
487 with zipfile.ZipFile(f, "r") as zipfp:
488 zinfo = zipfp.getinfo('strfile')
489 self.assertEqual(zinfo.external_attr, 0o600 << 16)
490
491 zinfo2 = zipfp.getinfo('written-open-w')
492 self.assertEqual(zinfo2.external_attr, 0o600 << 16)
493
494 def test_writestr_permissions(self):
495 for f in get_files(self):
496 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
497
498 def test_absolute_arcnames(self):
499 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
500 zipfp.write(TESTFN, "/absolute")
501
502 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
503 self.assertEqual(zipfp.namelist(), ["absolute"])
504
505 def test_append_to_zip_file(self):
506 """Test appending to an existing zipfile."""
507 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
508 zipfp.write(TESTFN, TESTFN)
509
510 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
511 zipfp.writestr("strfile", self.data)
512 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
513
514 def test_append_to_non_zip_file(self):
515 """Test appending to an existing file that is not a zipfile."""
516 # NOTE: this test fails if len(d) < 22 because of the first
517 # line "fpin.seek(-22, 2)" in _EndRecData
518 data = b'I am not a ZipFile!'*10
519 with open(TESTFN2, 'wb') as f:
520 f.write(data)
521
522 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
523 zipfp.write(TESTFN, TESTFN)
524
525 with open(TESTFN2, 'rb') as f:
526 f.seek(len(data))
527 with zipfile.ZipFile(f, "r") as zipfp:
528 self.assertEqual(zipfp.namelist(), [TESTFN])
529 self.assertEqual(zipfp.read(TESTFN), self.data)
530 with open(TESTFN2, 'rb') as f:
531 self.assertEqual(f.read(len(data)), data)
532 zipfiledata = f.read()
533 with io.BytesIO(zipfiledata) as bio, zipfile.ZipFile(bio) as zipfp:
534 self.assertEqual(zipfp.namelist(), [TESTFN])
535 self.assertEqual(zipfp.read(TESTFN), self.data)
536
537 def test_read_concatenated_zip_file(self):
538 with io.BytesIO() as bio:
539 with zipfile.ZipFile(bio, 'w', zipfile.ZIP_STORED) as zipfp:
540 zipfp.write(TESTFN, TESTFN)
541 zipfiledata = bio.getvalue()
542 data = b'I am not a ZipFile!'*10
543 with open(TESTFN2, 'wb') as f:
544 f.write(data)
545 f.write(zipfiledata)
546
547 with zipfile.ZipFile(TESTFN2) as zipfp:
548 self.assertEqual(zipfp.namelist(), [TESTFN])
549 self.assertEqual(zipfp.read(TESTFN), self.data)
550
551 def test_append_to_concatenated_zip_file(self):
552 with io.BytesIO() as bio:
553 with zipfile.ZipFile(bio, 'w', zipfile.ZIP_STORED) as zipfp:
554 zipfp.write(TESTFN, TESTFN)
555 zipfiledata = bio.getvalue()
556 data = b'I am not a ZipFile!'*1000000
557 with open(TESTFN2, 'wb') as f:
558 f.write(data)
559 f.write(zipfiledata)
560
561 with zipfile.ZipFile(TESTFN2, 'a') as zipfp:
562 self.assertEqual(zipfp.namelist(), [TESTFN])
563 zipfp.writestr('strfile', self.data)
564
565 with open(TESTFN2, 'rb') as f:
566 self.assertEqual(f.read(len(data)), data)
567 zipfiledata = f.read()
568 with io.BytesIO(zipfiledata) as bio, zipfile.ZipFile(bio) as zipfp:
569 self.assertEqual(zipfp.namelist(), [TESTFN, 'strfile'])
570 self.assertEqual(zipfp.read(TESTFN), self.data)
571 self.assertEqual(zipfp.read('strfile'), self.data)
572
573 def test_ignores_newline_at_end(self):
574 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
575 zipfp.write(TESTFN, TESTFN)
576 with open(TESTFN2, 'a', encoding='utf-8') as f:
577 f.write("\r\n\00\00\00")
578 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
579 self.assertIsInstance(zipfp, zipfile.ZipFile)
580
581 def test_ignores_stuff_appended_past_comments(self):
582 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
583 zipfp.comment = b"this is a comment"
584 zipfp.write(TESTFN, TESTFN)
585 with open(TESTFN2, 'a', encoding='utf-8') as f:
586 f.write("abcdef\r\n")
587 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
588 self.assertIsInstance(zipfp, zipfile.ZipFile)
589 self.assertEqual(zipfp.comment, b"this is a comment")
590
591 def test_write_default_name(self):
592 """Check that calling ZipFile.write without arcname specified
593 produces the expected result."""
594 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
595 zipfp.write(TESTFN)
596 with open(TESTFN, "rb") as f:
597 self.assertEqual(zipfp.read(TESTFN), f.read())
598
599 def test_io_on_closed_zipextfile(self):
600 fname = "somefile.txt"
601 with zipfile.ZipFile(TESTFN2, mode="w", compression=self.compression) as zipfp:
602 zipfp.writestr(fname, "bogus")
603
604 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
605 with zipfp.open(fname) as fid:
606 fid.close()
607 self.assertIs(fid.closed, True)
608 self.assertRaises(ValueError, fid.read)
609 self.assertRaises(ValueError, fid.seek, 0)
610 self.assertRaises(ValueError, fid.tell)
611
612 def test_write_to_readonly(self):
613 """Check that trying to call write() on a readonly ZipFile object
614 raises a ValueError."""
615 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
616 zipfp.writestr("somefile.txt", "bogus")
617
618 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
619 self.assertRaises(ValueError, zipfp.write, TESTFN)
620
621 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
622 with self.assertRaises(ValueError):
623 zipfp.open(TESTFN, mode='w')
624
625 def test_add_file_before_1980(self):
626 # Set atime and mtime to 1970-01-01
627 os.utime(TESTFN, (0, 0))
628 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
629 self.assertRaises(ValueError, zipfp.write, TESTFN)
630
631 with zipfile.ZipFile(TESTFN2, "w", strict_timestamps=False) as zipfp:
632 zipfp.write(TESTFN)
633 zinfo = zipfp.getinfo(TESTFN)
634 self.assertEqual(zinfo.date_time, (1980, 1, 1, 0, 0, 0))
635
636 def test_add_file_after_2107(self):
637 # Set atime and mtime to 2108-12-30
638 ts = 4386268800
639 try:
640 time.localtime(ts)
641 except OverflowError:
642 self.skipTest(f'time.localtime({ts}) raises OverflowError')
643 try:
644 os.utime(TESTFN, (ts, ts))
645 except OverflowError:
646 self.skipTest('Host fs cannot set timestamp to required value.')
647
648 mtime_ns = os.stat(TESTFN).st_mtime_ns
649 if mtime_ns != (4386268800 * 10**9):
650 # XFS filesystem is limited to 32-bit timestamp, but the syscall
651 # didn't fail. Moreover, there is a VFS bug which returns
652 # a cached timestamp which is different than the value on disk.
653 #
654 # Test st_mtime_ns rather than st_mtime to avoid rounding issues.
655 #
656 # https://bugzilla.redhat.com/show_bug.cgi?id=1795576
657 # https://bugs.python.org/issue39460#msg360952
658 self.skipTest(f"Linux VFS/XFS kernel bug detected: {mtime_ns=}")
659
660 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
661 self.assertRaises(struct.error, zipfp.write, TESTFN)
662
663 with zipfile.ZipFile(TESTFN2, "w", strict_timestamps=False) as zipfp:
664 zipfp.write(TESTFN)
665 zinfo = zipfp.getinfo(TESTFN)
666 self.assertEqual(zinfo.date_time, (2107, 12, 31, 23, 59, 59))
667
668
669 @requires_zlib()
670 class DeflateTestsWithSourceFile(AbstractTestsWithSourceFile,
671 unittest.TestCase):
672 compression = zipfile.ZIP_DEFLATED
673
674 def test_per_file_compression(self):
675 """Check that files within a Zip archive can have different
676 compression options."""
677 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
678 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
679 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
680 sinfo = zipfp.getinfo('storeme')
681 dinfo = zipfp.getinfo('deflateme')
682 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
683 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
684
685 @requires_bz2()
686 class Bzip2TestsWithSourceFile(AbstractTestsWithSourceFile,
687 unittest.TestCase):
688 compression = zipfile.ZIP_BZIP2
689
690 @requires_lzma()
691 class LzmaTestsWithSourceFile(AbstractTestsWithSourceFile,
692 unittest.TestCase):
693 compression = zipfile.ZIP_LZMA
694
695
696 class AbstractTestZip64InSmallFiles:
697 # These tests test the ZIP64 functionality without using large files,
698 # see test_zipfile64 for proper tests.
699
700 @classmethod
701 def setUpClass(cls):
702 line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
703 for i in range(0, FIXEDTEST_SIZE))
704 cls.data = b'\n'.join(line_gen)
705
706 def setUp(self):
707 self._limit = zipfile.ZIP64_LIMIT
708 self._filecount_limit = zipfile.ZIP_FILECOUNT_LIMIT
709 zipfile.ZIP64_LIMIT = 1000
710 zipfile.ZIP_FILECOUNT_LIMIT = 9
711
712 # Make a source file with some lines
713 with open(TESTFN, "wb") as fp:
714 fp.write(self.data)
715
716 def zip_test(self, f, compression):
717 # Create the ZIP archive
718 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
719 zipfp.write(TESTFN, "another.name")
720 zipfp.write(TESTFN, TESTFN)
721 zipfp.writestr("strfile", self.data)
722
723 # Read the ZIP archive
724 with zipfile.ZipFile(f, "r", compression) as zipfp:
725 self.assertEqual(zipfp.read(TESTFN), self.data)
726 self.assertEqual(zipfp.read("another.name"), self.data)
727 self.assertEqual(zipfp.read("strfile"), self.data)
728
729 # Print the ZIP directory
730 fp = io.StringIO()
731 zipfp.printdir(fp)
732
733 directory = fp.getvalue()
734 lines = directory.splitlines()
735 self.assertEqual(len(lines), 4) # Number of files + header
736
737 self.assertIn('File Name', lines[0])
738 self.assertIn('Modified', lines[0])
739 self.assertIn('Size', lines[0])
740
741 fn, date, time_, size = lines[1].split()
742 self.assertEqual(fn, 'another.name')
743 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
744 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
745 self.assertEqual(size, str(len(self.data)))
746
747 # Check the namelist
748 names = zipfp.namelist()
749 self.assertEqual(len(names), 3)
750 self.assertIn(TESTFN, names)
751 self.assertIn("another.name", names)
752 self.assertIn("strfile", names)
753
754 # Check infolist
755 infos = zipfp.infolist()
756 names = [i.filename for i in infos]
757 self.assertEqual(len(names), 3)
758 self.assertIn(TESTFN, names)
759 self.assertIn("another.name", names)
760 self.assertIn("strfile", names)
761 for i in infos:
762 self.assertEqual(i.file_size, len(self.data))
763
764 # check getinfo
765 for nm in (TESTFN, "another.name", "strfile"):
766 info = zipfp.getinfo(nm)
767 self.assertEqual(info.filename, nm)
768 self.assertEqual(info.file_size, len(self.data))
769
770 # Check that testzip thinks the archive is valid
771 self.assertIsNone(zipfp.testzip())
772
773 def test_basic(self):
774 for f in get_files(self):
775 self.zip_test(f, self.compression)
776
777 def test_too_many_files(self):
778 # This test checks that more than 64k files can be added to an archive,
779 # and that the resulting archive can be read properly by ZipFile
780 zipf = zipfile.ZipFile(TESTFN, "w", self.compression,
781 allowZip64=True)
782 zipf.debug = 100
783 numfiles = 15
784 for i in range(numfiles):
785 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
786 self.assertEqual(len(zipf.namelist()), numfiles)
787 zipf.close()
788
789 zipf2 = zipfile.ZipFile(TESTFN, "r", self.compression)
790 self.assertEqual(len(zipf2.namelist()), numfiles)
791 for i in range(numfiles):
792 content = zipf2.read("foo%08d" % i).decode('ascii')
793 self.assertEqual(content, "%d" % (i**3 % 57))
794 zipf2.close()
795
796 def test_too_many_files_append(self):
797 zipf = zipfile.ZipFile(TESTFN, "w", self.compression,
798 allowZip64=False)
799 zipf.debug = 100
800 numfiles = 9
801 for i in range(numfiles):
802 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
803 self.assertEqual(len(zipf.namelist()), numfiles)
804 with self.assertRaises(zipfile.LargeZipFile):
805 zipf.writestr("foo%08d" % numfiles, b'')
806 self.assertEqual(len(zipf.namelist()), numfiles)
807 zipf.close()
808
809 zipf = zipfile.ZipFile(TESTFN, "a", self.compression,
810 allowZip64=False)
811 zipf.debug = 100
812 self.assertEqual(len(zipf.namelist()), numfiles)
813 with self.assertRaises(zipfile.LargeZipFile):
814 zipf.writestr("foo%08d" % numfiles, b'')
815 self.assertEqual(len(zipf.namelist()), numfiles)
816 zipf.close()
817
818 zipf = zipfile.ZipFile(TESTFN, "a", self.compression,
819 allowZip64=True)
820 zipf.debug = 100
821 self.assertEqual(len(zipf.namelist()), numfiles)
822 numfiles2 = 15
823 for i in range(numfiles, numfiles2):
824 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
825 self.assertEqual(len(zipf.namelist()), numfiles2)
826 zipf.close()
827
828 zipf2 = zipfile.ZipFile(TESTFN, "r", self.compression)
829 self.assertEqual(len(zipf2.namelist()), numfiles2)
830 for i in range(numfiles2):
831 content = zipf2.read("foo%08d" % i).decode('ascii')
832 self.assertEqual(content, "%d" % (i**3 % 57))
833 zipf2.close()
834
835 def tearDown(self):
836 zipfile.ZIP64_LIMIT = self._limit
837 zipfile.ZIP_FILECOUNT_LIMIT = self._filecount_limit
838 unlink(TESTFN)
839 unlink(TESTFN2)
840
841
842 class StoredTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
843 unittest.TestCase):
844 compression = zipfile.ZIP_STORED
845
846 def large_file_exception_test(self, f, compression):
847 with zipfile.ZipFile(f, "w", compression, allowZip64=False) as zipfp:
848 self.assertRaises(zipfile.LargeZipFile,
849 zipfp.write, TESTFN, "another.name")
850
851 def large_file_exception_test2(self, f, compression):
852 with zipfile.ZipFile(f, "w", compression, allowZip64=False) as zipfp:
853 self.assertRaises(zipfile.LargeZipFile,
854 zipfp.writestr, "another.name", self.data)
855
856 def test_large_file_exception(self):
857 for f in get_files(self):
858 self.large_file_exception_test(f, zipfile.ZIP_STORED)
859 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
860
861 def test_absolute_arcnames(self):
862 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
863 allowZip64=True) as zipfp:
864 zipfp.write(TESTFN, "/absolute")
865
866 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
867 self.assertEqual(zipfp.namelist(), ["absolute"])
868
869 def test_append(self):
870 # Test that appending to the Zip64 archive doesn't change
871 # extra fields of existing entries.
872 with zipfile.ZipFile(TESTFN2, "w", allowZip64=True) as zipfp:
873 zipfp.writestr("strfile", self.data)
874 with zipfile.ZipFile(TESTFN2, "r", allowZip64=True) as zipfp:
875 zinfo = zipfp.getinfo("strfile")
876 extra = zinfo.extra
877 with zipfile.ZipFile(TESTFN2, "a", allowZip64=True) as zipfp:
878 zipfp.writestr("strfile2", self.data)
879 with zipfile.ZipFile(TESTFN2, "r", allowZip64=True) as zipfp:
880 zinfo = zipfp.getinfo("strfile")
881 self.assertEqual(zinfo.extra, extra)
882
883 def make_zip64_file(
884 self, file_size_64_set=False, file_size_extra=False,
885 compress_size_64_set=False, compress_size_extra=False,
886 header_offset_64_set=False, header_offset_extra=False,
887 extensible_data=b'',
888 end_of_central_dir_size=None, offset_to_end_of_central_dir=None,
889 ):
890 """Generate bytes sequence for a zip with (incomplete) zip64 data.
891
892 The actual values (not the zip 64 0xffffffff values) stored in the file
893 are:
894 file_size: 8
895 compress_size: 8
896 header_offset: 0
897 """
898 actual_size = 8
899 actual_header_offset = 0
900 local_zip64_fields = []
901 central_zip64_fields = []
902
903 file_size = actual_size
904 if file_size_64_set:
905 file_size = 0xffffffff
906 if file_size_extra:
907 local_zip64_fields.append(actual_size)
908 central_zip64_fields.append(actual_size)
909 file_size = struct.pack("<L", file_size)
910
911 compress_size = actual_size
912 if compress_size_64_set:
913 compress_size = 0xffffffff
914 if compress_size_extra:
915 local_zip64_fields.append(actual_size)
916 central_zip64_fields.append(actual_size)
917 compress_size = struct.pack("<L", compress_size)
918
919 header_offset = actual_header_offset
920 if header_offset_64_set:
921 header_offset = 0xffffffff
922 if header_offset_extra:
923 central_zip64_fields.append(actual_header_offset)
924 header_offset = struct.pack("<L", header_offset)
925
926 local_extra = struct.pack(
927 '<HH' + 'Q'*len(local_zip64_fields),
928 0x0001,
929 8*len(local_zip64_fields),
930 *local_zip64_fields
931 )
932
933 central_extra = struct.pack(
934 '<HH' + 'Q'*len(central_zip64_fields),
935 0x0001,
936 8*len(central_zip64_fields),
937 *central_zip64_fields
938 )
939
940 central_dir_size = struct.pack('<Q', 58 + 8 * len(central_zip64_fields))
941 offset_to_central_dir = struct.pack('<Q', 50 + 8 * len(local_zip64_fields))
942 if end_of_central_dir_size is None:
943 end_of_central_dir_size = 44 + len(extensible_data)
944 if offset_to_end_of_central_dir is None:
945 offset_to_end_of_central_dir = (108
946 + 8 * len(local_zip64_fields)
947 + 8 * len(central_zip64_fields))
948
949 local_extra_length = struct.pack("<H", 4 + 8 * len(local_zip64_fields))
950 central_extra_length = struct.pack("<H", 4 + 8 * len(central_zip64_fields))
951
952 filename = b"test.txt"
953 content = b"test1234"
954 filename_length = struct.pack("<H", len(filename))
955 zip64_contents = (
956 # Local file header
957 b"PK\x03\x04\x14\x00\x00\x00\x00\x00\x00\x00!\x00\x9e%\xf5\xaf"
958 + compress_size
959 + file_size
960 + filename_length
961 + local_extra_length
962 + filename
963 + local_extra
964 + content
965 # Central directory:
966 + b"PK\x01\x02-\x03-\x00\x00\x00\x00\x00\x00\x00!\x00\x9e%\xf5\xaf"
967 + compress_size
968 + file_size
969 + filename_length
970 + central_extra_length
971 + b"\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01"
972 + header_offset
973 + filename
974 + central_extra
975 # Zip64 end of central directory
976 + b"PK\x06\x06"
977 + struct.pack('<Q', end_of_central_dir_size)
978 + b"-\x00-\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00"
979 + b"\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00"
980 + central_dir_size
981 + offset_to_central_dir
982 + extensible_data
983 # Zip64 end of central directory locator
984 + b"PK\x06\x07\x00\x00\x00\x00"
985 + struct.pack('<Q', offset_to_end_of_central_dir)
986 + b"\x01\x00\x00\x00"
987 # end of central directory
988 + b"PK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00:\x00\x00\x002\x00"
989 + b"\x00\x00\x00\x00"
990 )
991 return zip64_contents
992
993 def test_bad_zip64_extra(self):
994 """Missing zip64 extra records raises an exception.
995
996 There are 4 fields that the zip64 format handles (the disk number is
997 not used in this module and so is ignored here). According to the zip
998 spec:
999 The order of the fields in the zip64 extended
1000 information record is fixed, but the fields MUST
1001 only appear if the corresponding Local or Central
1002 directory record field is set to 0xFFFF or 0xFFFFFFFF.
1003
1004 If the zip64 extra content doesn't contain enough entries for the
1005 number of fields marked with 0xFFFF or 0xFFFFFFFF, we raise an error.
1006 This test mismatches the length of the zip64 extra field and the number
1007 of fields set to indicate the presence of zip64 data.
1008 """
1009 # zip64 file size present, no fields in extra, expecting one, equals
1010 # missing file size.
1011 missing_file_size_extra = self.make_zip64_file(
1012 file_size_64_set=True,
1013 )
1014 with self.assertRaises(zipfile.BadZipFile) as e:
1015 zipfile.ZipFile(io.BytesIO(missing_file_size_extra))
1016 self.assertIn('file size', str(e.exception).lower())
1017 self.assertTrue(zipfile.is_zipfile(io.BytesIO(missing_file_size_extra)))
1018
1019 # zip64 file size present, zip64 compress size present, one field in
1020 # extra, expecting two, equals missing compress size.
1021 missing_compress_size_extra = self.make_zip64_file(
1022 file_size_64_set=True,
1023 file_size_extra=True,
1024 compress_size_64_set=True,
1025 )
1026 with self.assertRaises(zipfile.BadZipFile) as e:
1027 zipfile.ZipFile(io.BytesIO(missing_compress_size_extra))
1028 self.assertIn('compress size', str(e.exception).lower())
1029 self.assertTrue(zipfile.is_zipfile(io.BytesIO(missing_compress_size_extra)))
1030
1031 # zip64 compress size present, no fields in extra, expecting one,
1032 # equals missing compress size.
1033 missing_compress_size_extra = self.make_zip64_file(
1034 compress_size_64_set=True,
1035 )
1036 with self.assertRaises(zipfile.BadZipFile) as e:
1037 zipfile.ZipFile(io.BytesIO(missing_compress_size_extra))
1038 self.assertIn('compress size', str(e.exception).lower())
1039 self.assertTrue(zipfile.is_zipfile(io.BytesIO(missing_compress_size_extra)))
1040
1041 # zip64 file size present, zip64 compress size present, zip64 header
1042 # offset present, two fields in extra, expecting three, equals missing
1043 # header offset
1044 missing_header_offset_extra = self.make_zip64_file(
1045 file_size_64_set=True,
1046 file_size_extra=True,
1047 compress_size_64_set=True,
1048 compress_size_extra=True,
1049 header_offset_64_set=True,
1050 )
1051 with self.assertRaises(zipfile.BadZipFile) as e:
1052 zipfile.ZipFile(io.BytesIO(missing_header_offset_extra))
1053 self.assertIn('header offset', str(e.exception).lower())
1054 self.assertTrue(zipfile.is_zipfile(io.BytesIO(missing_header_offset_extra)))
1055
1056 # zip64 compress size present, zip64 header offset present, one field
1057 # in extra, expecting two, equals missing header offset
1058 missing_header_offset_extra = self.make_zip64_file(
1059 file_size_64_set=False,
1060 compress_size_64_set=True,
1061 compress_size_extra=True,
1062 header_offset_64_set=True,
1063 )
1064 with self.assertRaises(zipfile.BadZipFile) as e:
1065 zipfile.ZipFile(io.BytesIO(missing_header_offset_extra))
1066 self.assertIn('header offset', str(e.exception).lower())
1067 self.assertTrue(zipfile.is_zipfile(io.BytesIO(missing_header_offset_extra)))
1068
1069 # zip64 file size present, zip64 header offset present, one field in
1070 # extra, expecting two, equals missing header offset
1071 missing_header_offset_extra = self.make_zip64_file(
1072 file_size_64_set=True,
1073 file_size_extra=True,
1074 compress_size_64_set=False,
1075 header_offset_64_set=True,
1076 )
1077 with self.assertRaises(zipfile.BadZipFile) as e:
1078 zipfile.ZipFile(io.BytesIO(missing_header_offset_extra))
1079 self.assertIn('header offset', str(e.exception).lower())
1080 self.assertTrue(zipfile.is_zipfile(io.BytesIO(missing_header_offset_extra)))
1081
1082 # zip64 header offset present, no fields in extra, expecting one,
1083 # equals missing header offset
1084 missing_header_offset_extra = self.make_zip64_file(
1085 file_size_64_set=False,
1086 compress_size_64_set=False,
1087 header_offset_64_set=True,
1088 )
1089 with self.assertRaises(zipfile.BadZipFile) as e:
1090 zipfile.ZipFile(io.BytesIO(missing_header_offset_extra))
1091 self.assertIn('header offset', str(e.exception).lower())
1092 self.assertTrue(zipfile.is_zipfile(io.BytesIO(missing_header_offset_extra)))
1093
1094 def test_bad_zip64_end_of_central_dir(self):
1095 zipdata = self.make_zip64_file(end_of_central_dir_size=0)
1096 with self.assertRaisesRegex(zipfile.BadZipFile, 'Corrupt.*record'):
1097 zipfile.ZipFile(io.BytesIO(zipdata))
1098 self.assertFalse(zipfile.is_zipfile(io.BytesIO(zipdata)))
1099
1100 zipdata = self.make_zip64_file(end_of_central_dir_size=100)
1101 with self.assertRaisesRegex(zipfile.BadZipFile, 'Corrupt.*record'):
1102 zipfile.ZipFile(io.BytesIO(zipdata))
1103 self.assertFalse(zipfile.is_zipfile(io.BytesIO(zipdata)))
1104
1105 zipdata = self.make_zip64_file(offset_to_end_of_central_dir=0)
1106 with self.assertRaisesRegex(zipfile.BadZipFile, 'Corrupt.*record'):
1107 zipfile.ZipFile(io.BytesIO(zipdata))
1108 self.assertFalse(zipfile.is_zipfile(io.BytesIO(zipdata)))
1109
1110 zipdata = self.make_zip64_file(offset_to_end_of_central_dir=1000)
1111 with self.assertRaisesRegex(zipfile.BadZipFile, 'Corrupt.*locator'):
1112 zipfile.ZipFile(io.BytesIO(zipdata))
1113 self.assertFalse(zipfile.is_zipfile(io.BytesIO(zipdata)))
1114
1115 def test_zip64_end_of_central_dir_record_not_found(self):
1116 zipdata = self.make_zip64_file()
1117 zipdata = zipdata.replace(b"PK\x06\x06", b'\x00'*4)
1118 with self.assertRaisesRegex(zipfile.BadZipFile, 'record not found'):
1119 zipfile.ZipFile(io.BytesIO(zipdata))
1120 self.assertFalse(zipfile.is_zipfile(io.BytesIO(zipdata)))
1121
1122 zipdata = self.make_zip64_file(
1123 extensible_data=b'\xca\xfe\x04\x00\x00\x00data')
1124 zipdata = zipdata.replace(b"PK\x06\x06", b'\x00'*4)
1125 with self.assertRaisesRegex(zipfile.BadZipFile, 'record not found'):
1126 zipfile.ZipFile(io.BytesIO(zipdata))
1127 self.assertFalse(zipfile.is_zipfile(io.BytesIO(zipdata)))
1128
1129 def test_zip64_extensible_data(self):
1130 # These values are what is set in the make_zip64_file method.
1131 expected_file_size = 8
1132 expected_compress_size = 8
1133 expected_header_offset = 0
1134 expected_content = b"test1234"
1135
1136 zipdata = self.make_zip64_file(
1137 extensible_data=b'\xca\xfe\x04\x00\x00\x00data')
1138 with zipfile.ZipFile(io.BytesIO(zipdata)) as zf:
1139 zinfo = zf.infolist()[0]
1140 self.assertEqual(zinfo.file_size, expected_file_size)
1141 self.assertEqual(zinfo.compress_size, expected_compress_size)
1142 self.assertEqual(zinfo.header_offset, expected_header_offset)
1143 self.assertEqual(zf.read(zinfo), expected_content)
1144 self.assertTrue(zipfile.is_zipfile(io.BytesIO(zipdata)))
1145
1146 with self.assertRaisesRegex(zipfile.BadZipFile, 'record not found'):
1147 zipfile.ZipFile(io.BytesIO(b'prepended' + zipdata))
1148 self.assertFalse(zipfile.is_zipfile(io.BytesIO(b'prepended' + zipdata)))
1149
1150 def test_generated_valid_zip64_extra(self):
1151 # These values are what is set in the make_zip64_file method.
1152 expected_file_size = 8
1153 expected_compress_size = 8
1154 expected_header_offset = 0
1155 expected_content = b"test1234"
1156
1157 # Loop through the various valid combinations of zip64 masks
1158 # present and extra fields present.
1159 params = (
1160 {"file_size_64_set": True, "file_size_extra": True},
1161 {"compress_size_64_set": True, "compress_size_extra": True},
1162 {"header_offset_64_set": True, "header_offset_extra": True},
1163 )
1164
1165 for r in range(1, len(params) + 1):
1166 for combo in itertools.combinations(params, r):
1167 kwargs = {}
1168 for c in combo:
1169 kwargs.update(c)
1170 with zipfile.ZipFile(io.BytesIO(self.make_zip64_file(**kwargs))) as zf:
1171 zinfo = zf.infolist()[0]
1172 self.assertEqual(zinfo.file_size, expected_file_size)
1173 self.assertEqual(zinfo.compress_size, expected_compress_size)
1174 self.assertEqual(zinfo.header_offset, expected_header_offset)
1175 self.assertEqual(zf.read(zinfo), expected_content)
1176
1177 def test_force_zip64(self):
1178 """Test that forcing zip64 extensions correctly notes this in the zip file"""
1179
1180 # GH-103861 describes an issue where forcing a small file to use zip64
1181 # extensions would add a zip64 extra record, but not change the data
1182 # sizes to 0xFFFFFFFF to indicate to the extractor that the zip64
1183 # record should be read. Additionally, it would not set the required
1184 # version to indicate that zip64 extensions are required to extract it.
1185 # This test replicates the situation and reads the raw data to specifically ensure:
1186 # - The required extract version is always >= ZIP64_VERSION
1187 # - The compressed and uncompressed size in the file headers are both
1188 # 0xFFFFFFFF (ie. point to zip64 record)
1189 # - The zip64 record is provided and has the correct sizes in it
1190 # Other aspects of the zip are checked as well, but verifying the above is the main goal.
1191 # Because this is hard to verify by parsing the data as a zip, the raw
1192 # bytes are checked to ensure that they line up with the zip spec.
1193 # The spec for this can be found at: https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT
1194 # The relevant sections for this test are:
1195 # - 4.3.7 for local file header
1196 # - 4.5.3 for zip64 extra field
1197
1198 data = io.BytesIO()
1199 with zipfile.ZipFile(data, mode="w", allowZip64=True) as zf:
1200 with zf.open("text.txt", mode="w", force_zip64=True) as zi:
1201 zi.write(b"_")
1202
1203 zipdata = data.getvalue()
1204
1205 # pull out and check zip information
1206 (
1207 header, vers, os, flags, comp, csize, usize, fn_len,
1208 ex_total_len, filename, ex_id, ex_len, ex_usize, ex_csize, cd_sig
1209 ) = struct.unpack("<4sBBHH8xIIHH8shhQQx4s", zipdata[:63])
1210
1211 self.assertEqual(header, b"PK\x03\x04") # local file header
1212 self.assertGreaterEqual(vers, zipfile.ZIP64_VERSION) # requires zip64 to extract
1213 self.assertEqual(os, 0) # compatible with MS-DOS
1214 self.assertEqual(flags, 0) # no flags
1215 self.assertEqual(comp, 0) # compression method = stored
1216 self.assertEqual(csize, 0xFFFFFFFF) # sizes are in zip64 extra
1217 self.assertEqual(usize, 0xFFFFFFFF)
1218 self.assertEqual(fn_len, 8) # filename len
1219 self.assertEqual(ex_total_len, 20) # size of extra records
1220 self.assertEqual(ex_id, 1) # Zip64 extra record
1221 self.assertEqual(ex_len, 16) # 16 bytes of data
1222 self.assertEqual(ex_usize, 1) # uncompressed size
1223 self.assertEqual(ex_csize, 1) # compressed size
1224 self.assertEqual(cd_sig, b"PK\x01\x02") # ensure the central directory header is next
1225
1226 z = zipfile.ZipFile(io.BytesIO(zipdata))
1227 zinfos = z.infolist()
1228 self.assertEqual(len(zinfos), 1)
1229 self.assertGreaterEqual(zinfos[0].extract_version, zipfile.ZIP64_VERSION) # requires zip64 to extract
1230
1231 def test_unseekable_zip_unknown_filesize(self):
1232 """Test that creating a zip with/without seeking will raise a RuntimeError if zip64 was required but not used"""
1233
1234 def make_zip(fp):
1235 with zipfile.ZipFile(fp, mode="w", allowZip64=True) as zf:
1236 with zf.open("text.txt", mode="w", force_zip64=False) as zi:
1237 zi.write(b"_" * (zipfile.ZIP64_LIMIT + 1))
1238
1239 self.assertRaises(RuntimeError, make_zip, io.BytesIO())
1240 self.assertRaises(RuntimeError, make_zip, Unseekable(io.BytesIO()))
1241
1242 def test_zip64_required_not_allowed_fail(self):
1243 """Test that trying to add a large file to a zip that doesn't allow zip64 extensions fails on add"""
1244 def make_zip(fp):
1245 with zipfile.ZipFile(fp, mode="w", allowZip64=False) as zf:
1246 # pretend zipfile.ZipInfo.from_file was used to get the name and filesize
1247 info = zipfile.ZipInfo("text.txt")
1248 info.file_size = zipfile.ZIP64_LIMIT + 1
1249 zf.open(info, mode="w")
1250
1251 self.assertRaises(zipfile.LargeZipFile, make_zip, io.BytesIO())
1252 self.assertRaises(zipfile.LargeZipFile, make_zip, Unseekable(io.BytesIO()))
1253
1254 def test_unseekable_zip_known_filesize(self):
1255 """Test that creating a zip without seeking will use zip64 extensions if the file size is provided up-front"""
1256
1257 # This test ensures that the zip will use a zip64 data descriptor (same
1258 # as a regular data descriptor except the sizes are 8 bytes instead of
1259 # 4) record to communicate the size of a file if the zip is being
1260 # written to an unseekable stream.
1261 # Because this sort of thing is hard to verify by parsing the data back
1262 # in as a zip, this test looks at the raw bytes created to ensure that
1263 # the correct data has been generated.
1264 # The spec for this can be found at: https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT
1265 # The relevant sections for this test are:
1266 # - 4.3.7 for local file header
1267 # - 4.3.9 for the data descriptor
1268 # - 4.5.3 for zip64 extra field
1269
1270 file_size = zipfile.ZIP64_LIMIT + 1
1271
1272 def make_zip(fp):
1273 with zipfile.ZipFile(fp, mode="w", allowZip64=True) as zf:
1274 # pretend zipfile.ZipInfo.from_file was used to get the name and filesize
1275 info = zipfile.ZipInfo("text.txt")
1276 info.file_size = file_size
1277 with zf.open(info, mode="w", force_zip64=False) as zi:
1278 zi.write(b"_" * file_size)
1279 return fp
1280
1281 # check seekable file information
1282 seekable_data = make_zip(io.BytesIO()).getvalue()
1283 (
1284 header, vers, os, flags, comp, csize, usize, fn_len,
1285 ex_total_len, filename, ex_id, ex_len, ex_usize, ex_csize,
1286 cd_sig
1287 ) = struct.unpack("<4sBBHH8xIIHH8shhQQ{}x4s".format(file_size), seekable_data[:62 + file_size])
1288
1289 self.assertEqual(header, b"PK\x03\x04") # local file header
1290 self.assertGreaterEqual(vers, zipfile.ZIP64_VERSION) # requires zip64 to extract
1291 self.assertEqual(os, 0) # compatible with MS-DOS
1292 self.assertEqual(flags, 0) # no flags set
1293 self.assertEqual(comp, 0) # compression method = stored
1294 self.assertEqual(csize, 0xFFFFFFFF) # sizes are in zip64 extra
1295 self.assertEqual(usize, 0xFFFFFFFF)
1296 self.assertEqual(fn_len, 8) # filename len
1297 self.assertEqual(ex_total_len, 20) # size of extra records
1298 self.assertEqual(ex_id, 1) # Zip64 extra record
1299 self.assertEqual(ex_len, 16) # 16 bytes of data
1300 self.assertEqual(ex_usize, file_size) # uncompressed size
1301 self.assertEqual(ex_csize, file_size) # compressed size
1302 self.assertEqual(cd_sig, b"PK\x01\x02") # ensure the central directory header is next
1303
1304 # check unseekable file information
1305 unseekable_data = make_zip(Unseekable(io.BytesIO())).fp.getvalue()
1306 (
1307 header, vers, os, flags, comp, csize, usize, fn_len,
1308 ex_total_len, filename, ex_id, ex_len, ex_usize, ex_csize,
1309 dd_header, dd_usize, dd_csize, cd_sig
1310 ) = struct.unpack("<4sBBHH8xIIHH8shhQQ{}x4s4xQQ4s".format(file_size), unseekable_data[:86 + file_size])
1311
1312 self.assertEqual(header, b"PK\x03\x04") # local file header
1313 self.assertGreaterEqual(vers, zipfile.ZIP64_VERSION) # requires zip64 to extract
1314 self.assertEqual(os, 0) # compatible with MS-DOS
1315 self.assertEqual("{:b}".format(flags), "1000") # streaming flag set
1316 self.assertEqual(comp, 0) # compression method = stored
1317 self.assertEqual(csize, 0xFFFFFFFF) # sizes are in zip64 extra
1318 self.assertEqual(usize, 0xFFFFFFFF)
1319 self.assertEqual(fn_len, 8) # filename len
1320 self.assertEqual(ex_total_len, 20) # size of extra records
1321 self.assertEqual(ex_id, 1) # Zip64 extra record
1322 self.assertEqual(ex_len, 16) # 16 bytes of data
1323 self.assertEqual(ex_usize, 0) # uncompressed size - 0 to defer to data descriptor
1324 self.assertEqual(ex_csize, 0) # compressed size - 0 to defer to data descriptor
1325 self.assertEqual(dd_header, b"PK\07\x08") # data descriptor
1326 self.assertEqual(dd_usize, file_size) # file size (8 bytes because zip64)
1327 self.assertEqual(dd_csize, file_size) # compressed size (8 bytes because zip64)
1328 self.assertEqual(cd_sig, b"PK\x01\x02") # ensure the central directory header is next
1329
1330
1331 @requires_zlib()
1332 class DeflateTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
1333 unittest.TestCase):
1334 compression = zipfile.ZIP_DEFLATED
1335
1336 @requires_bz2()
1337 class Bzip2TestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
1338 unittest.TestCase):
1339 compression = zipfile.ZIP_BZIP2
1340
1341 @requires_lzma()
1342 class LzmaTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
1343 unittest.TestCase):
1344 compression = zipfile.ZIP_LZMA
1345
1346
1347 class AbstractWriterTests:
1348
1349 def tearDown(self):
1350 unlink(TESTFN2)
1351
1352 def test_close_after_close(self):
1353 data = b'content'
1354 with zipfile.ZipFile(TESTFN2, "w", self.compression) as zipf:
1355 w = zipf.open('test', 'w')
1356 w.write(data)
1357 w.close()
1358 self.assertTrue(w.closed)
1359 w.close()
1360 self.assertTrue(w.closed)
1361 self.assertEqual(zipf.read('test'), data)
1362
1363 def test_write_after_close(self):
1364 data = b'content'
1365 with zipfile.ZipFile(TESTFN2, "w", self.compression) as zipf:
1366 w = zipf.open('test', 'w')
1367 w.write(data)
1368 w.close()
1369 self.assertTrue(w.closed)
1370 self.assertRaises(ValueError, w.write, b'')
1371 self.assertEqual(zipf.read('test'), data)
1372
1373 def test_issue44439(self):
1374 q = array.array('Q', [1, 2, 3, 4, 5])
1375 LENGTH = len(q) * q.itemsize
1376 with zipfile.ZipFile(io.BytesIO(), 'w', self.compression) as zip:
1377 with zip.open('data', 'w') as data:
1378 self.assertEqual(data.write(q), LENGTH)
1379 self.assertEqual(zip.getinfo('data').file_size, LENGTH)
1380
1381 def test_zipwritefile_attrs(self):
1382 fname = "somefile.txt"
1383 with zipfile.ZipFile(TESTFN2, mode="w", compression=self.compression) as zipfp:
1384 with zipfp.open(fname, 'w') as fid:
1385 self.assertEqual(fid.name, fname)
1386 self.assertRaises(io.UnsupportedOperation, fid.fileno)
1387 self.assertEqual(fid.mode, 'wb')
1388 self.assertIs(fid.readable(), False)
1389 self.assertIs(fid.writable(), True)
1390 self.assertIs(fid.seekable(), False)
1391 self.assertIs(fid.closed, False)
1392 self.assertIs(fid.closed, True)
1393 self.assertEqual(fid.name, fname)
1394 self.assertEqual(fid.mode, 'wb')
1395 self.assertRaises(io.UnsupportedOperation, fid.fileno)
1396 self.assertIs(fid.readable(), False)
1397 self.assertIs(fid.writable(), True)
1398 self.assertIs(fid.seekable(), False)
1399
1400 class StoredWriterTests(AbstractWriterTests, unittest.TestCase):
1401 compression = zipfile.ZIP_STORED
1402
1403 @requires_zlib()
1404 class DeflateWriterTests(AbstractWriterTests, unittest.TestCase):
1405 compression = zipfile.ZIP_DEFLATED
1406
1407 @requires_bz2()
1408 class Bzip2WriterTests(AbstractWriterTests, unittest.TestCase):
1409 compression = zipfile.ZIP_BZIP2
1410
1411 @requires_lzma()
1412 class LzmaWriterTests(AbstractWriterTests, unittest.TestCase):
1413 compression = zipfile.ZIP_LZMA
1414
1415
1416 class PyZipFileTests(unittest.TestCase):
1417 def assertCompiledIn(self, name, namelist):
1418 if name + 'o' not in namelist:
1419 self.assertIn(name + 'c', namelist)
1420
1421 def requiresWriteAccess(self, path):
1422 # effective_ids unavailable on windows
1423 if not os.access(path, os.W_OK,
1424 effective_ids=os.access in os.supports_effective_ids):
1425 self.skipTest('requires write access to the installed location')
1426 filename = os.path.join(path, 'test_zipfile.try')
1427 try:
1428 fd = os.open(filename, os.O_WRONLY | os.O_CREAT)
1429 os.close(fd)
1430 except Exception:
1431 self.skipTest('requires write access to the installed location')
1432 unlink(filename)
1433
1434 def test_write_pyfile(self):
1435 self.requiresWriteAccess(os.path.dirname(__file__))
1436 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
1437 fn = __file__
1438 if fn.endswith('.pyc'):
1439 path_split = fn.split(os.sep)
1440 if os.altsep is not None:
1441 path_split.extend(fn.split(os.altsep))
1442 if '__pycache__' in path_split:
1443 fn = importlib.util.source_from_cache(fn)
1444 else:
1445 fn = fn[:-1]
1446
1447 zipfp.writepy(fn)
1448
1449 bn = os.path.basename(fn)
1450 self.assertNotIn(bn, zipfp.namelist())
1451 self.assertCompiledIn(bn, zipfp.namelist())
1452
1453 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
1454 fn = __file__
1455 if fn.endswith('.pyc'):
1456 fn = fn[:-1]
1457
1458 zipfp.writepy(fn, "testpackage")
1459
1460 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
1461 self.assertNotIn(bn, zipfp.namelist())
1462 self.assertCompiledIn(bn, zipfp.namelist())
1463
1464 def test_write_python_package(self):
1465 import email
1466 packagedir = os.path.dirname(email.__file__)
1467 self.requiresWriteAccess(packagedir)
1468
1469 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
1470 zipfp.writepy(packagedir)
1471
1472 # Check for a couple of modules at different levels of the
1473 # hierarchy
1474 names = zipfp.namelist()
1475 self.assertCompiledIn('email/__init__.py', names)
1476 self.assertCompiledIn('email/mime/text.py', names)
1477
1478 def test_write_filtered_python_package(self):
1479 import test
1480 packagedir = os.path.dirname(test.__file__)
1481 self.requiresWriteAccess(packagedir)
1482
1483 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
1484
1485 # first make sure that the test folder gives error messages
1486 # (on the badsyntax_... files)
1487 with captured_stdout() as reportSIO:
1488 zipfp.writepy(packagedir)
1489 reportStr = reportSIO.getvalue()
1490 self.assertTrue('SyntaxError' in reportStr)
1491
1492 # then check that the filter works on the whole package
1493 with captured_stdout() as reportSIO:
1494 zipfp.writepy(packagedir, filterfunc=lambda whatever: False)
1495 reportStr = reportSIO.getvalue()
1496 self.assertTrue('SyntaxError' not in reportStr)
1497
1498 # then check that the filter works on individual files
1499 def filter(path):
1500 return not os.path.basename(path).startswith("bad")
1501 with captured_stdout() as reportSIO, self.assertWarns(UserWarning):
1502 zipfp.writepy(packagedir, filterfunc=filter)
1503 reportStr = reportSIO.getvalue()
1504 if reportStr:
1505 print(reportStr)
1506 self.assertTrue('SyntaxError' not in reportStr)
1507
1508 def test_write_with_optimization(self):
1509 import email
1510 packagedir = os.path.dirname(email.__file__)
1511 self.requiresWriteAccess(packagedir)
1512 optlevel = 1 if __debug__ else 0
1513 ext = '.pyc'
1514
1515 with TemporaryFile() as t, \
1516 zipfile.PyZipFile(t, "w", optimize=optlevel) as zipfp:
1517 zipfp.writepy(packagedir)
1518
1519 names = zipfp.namelist()
1520 self.assertIn('email/__init__' + ext, names)
1521 self.assertIn('email/mime/text' + ext, names)
1522
1523 def test_write_python_directory(self):
1524 os.mkdir(TESTFN2)
1525 try:
1526 with open(os.path.join(TESTFN2, "mod1.py"), "w", encoding='utf-8') as fp:
1527 fp.write("print(42)\n")
1528
1529 with open(os.path.join(TESTFN2, "mod2.py"), "w", encoding='utf-8') as fp:
1530 fp.write("print(42 * 42)\n")
1531
1532 with open(os.path.join(TESTFN2, "mod2.txt"), "w", encoding='utf-8') as fp:
1533 fp.write("bla bla bla\n")
1534
1535 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
1536 zipfp.writepy(TESTFN2)
1537
1538 names = zipfp.namelist()
1539 self.assertCompiledIn('mod1.py', names)
1540 self.assertCompiledIn('mod2.py', names)
1541 self.assertNotIn('mod2.txt', names)
1542
1543 finally:
1544 rmtree(TESTFN2)
1545
1546 def test_write_python_directory_filtered(self):
1547 os.mkdir(TESTFN2)
1548 try:
1549 with open(os.path.join(TESTFN2, "mod1.py"), "w", encoding='utf-8') as fp:
1550 fp.write("print(42)\n")
1551
1552 with open(os.path.join(TESTFN2, "mod2.py"), "w", encoding='utf-8') as fp:
1553 fp.write("print(42 * 42)\n")
1554
1555 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
1556 zipfp.writepy(TESTFN2, filterfunc=lambda fn:
1557 not fn.endswith('mod2.py'))
1558
1559 names = zipfp.namelist()
1560 self.assertCompiledIn('mod1.py', names)
1561 self.assertNotIn('mod2.py', names)
1562
1563 finally:
1564 rmtree(TESTFN2)
1565
1566 def test_write_non_pyfile(self):
1567 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
1568 with open(TESTFN, 'w', encoding='utf-8') as f:
1569 f.write('most definitely not a python file')
1570 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
1571 unlink(TESTFN)
1572
1573 def test_write_pyfile_bad_syntax(self):
1574 os.mkdir(TESTFN2)
1575 try:
1576 with open(os.path.join(TESTFN2, "mod1.py"), "w", encoding='utf-8') as fp:
1577 fp.write("Bad syntax in python file\n")
1578
1579 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
1580 # syntax errors are printed to stdout
1581 with captured_stdout() as s:
1582 zipfp.writepy(os.path.join(TESTFN2, "mod1.py"))
1583
1584 self.assertIn("SyntaxError", s.getvalue())
1585
1586 # as it will not have compiled the python file, it will
1587 # include the .py file not .pyc
1588 names = zipfp.namelist()
1589 self.assertIn('mod1.py', names)
1590 self.assertNotIn('mod1.pyc', names)
1591
1592 finally:
1593 rmtree(TESTFN2)
1594
1595 def test_write_pathlike(self):
1596 os.mkdir(TESTFN2)
1597 try:
1598 with open(os.path.join(TESTFN2, "mod1.py"), "w", encoding='utf-8') as fp:
1599 fp.write("print(42)\n")
1600
1601 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
1602 zipfp.writepy(FakePath(os.path.join(TESTFN2, "mod1.py")))
1603 names = zipfp.namelist()
1604 self.assertCompiledIn('mod1.py', names)
1605 finally:
1606 rmtree(TESTFN2)
1607
1608
1609 class ExtractTests(unittest.TestCase):
1610
1611 def make_test_file(self):
1612 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
1613 for fpath, fdata in SMALL_TEST_DATA:
1614 zipfp.writestr(fpath, fdata)
1615
1616 def test_extract(self):
1617 with temp_cwd():
1618 self.make_test_file()
1619 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1620 for fpath, fdata in SMALL_TEST_DATA:
1621 writtenfile = zipfp.extract(fpath)
1622
1623 # make sure it was written to the right place
1624 correctfile = os.path.join(os.getcwd(), fpath)
1625 correctfile = os.path.normpath(correctfile)
1626
1627 self.assertEqual(writtenfile, correctfile)
1628
1629 # make sure correct data is in correct file
1630 with open(writtenfile, "rb") as f:
1631 self.assertEqual(fdata.encode(), f.read())
1632
1633 unlink(writtenfile)
1634
1635 def _test_extract_with_target(self, target):
1636 self.make_test_file()
1637 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1638 for fpath, fdata in SMALL_TEST_DATA:
1639 writtenfile = zipfp.extract(fpath, target)
1640
1641 # make sure it was written to the right place
1642 correctfile = os.path.join(target, fpath)
1643 correctfile = os.path.normpath(correctfile)
1644 self.assertTrue(os.path.samefile(writtenfile, correctfile), (writtenfile, target))
1645
1646 # make sure correct data is in correct file
1647 with open(writtenfile, "rb") as f:
1648 self.assertEqual(fdata.encode(), f.read())
1649
1650 unlink(writtenfile)
1651
1652 unlink(TESTFN2)
1653
1654 def test_extract_with_target(self):
1655 with temp_dir() as extdir:
1656 self._test_extract_with_target(extdir)
1657
1658 def test_extract_with_target_pathlike(self):
1659 with temp_dir() as extdir:
1660 self._test_extract_with_target(FakePath(extdir))
1661
1662 def test_extract_all(self):
1663 with temp_cwd():
1664 self.make_test_file()
1665 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1666 zipfp.extractall()
1667 for fpath, fdata in SMALL_TEST_DATA:
1668 outfile = os.path.join(os.getcwd(), fpath)
1669
1670 with open(outfile, "rb") as f:
1671 self.assertEqual(fdata.encode(), f.read())
1672
1673 unlink(outfile)
1674
1675 def _test_extract_all_with_target(self, target):
1676 self.make_test_file()
1677 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1678 zipfp.extractall(target)
1679 for fpath, fdata in SMALL_TEST_DATA:
1680 outfile = os.path.join(target, fpath)
1681
1682 with open(outfile, "rb") as f:
1683 self.assertEqual(fdata.encode(), f.read())
1684
1685 unlink(outfile)
1686
1687 unlink(TESTFN2)
1688
1689 def test_extract_all_with_target(self):
1690 with temp_dir() as extdir:
1691 self._test_extract_all_with_target(extdir)
1692
1693 def test_extract_all_with_target_pathlike(self):
1694 with temp_dir() as extdir:
1695 self._test_extract_all_with_target(FakePath(extdir))
1696
1697 def check_file(self, filename, content):
1698 self.assertTrue(os.path.isfile(filename))
1699 with open(filename, 'rb') as f:
1700 self.assertEqual(f.read(), content)
1701
1702 def test_sanitize_windows_name(self):
1703 san = zipfile.ZipFile._sanitize_windows_name
1704 # Passing pathsep in allows this test to work regardless of platform.
1705 self.assertEqual(san(r',,?,C:,foo,bar/z', ','), r'_,C_,foo,bar/z')
1706 self.assertEqual(san(r'a\b,c<d>e|f"g?h*i', ','), r'a\b,c_d_e_f_g_h_i')
1707 self.assertEqual(san('../../foo../../ba..r', '/'), r'foo/ba..r')
1708 self.assertEqual(san(' / /foo / /ba r', '/'), r'foo/ba r')
1709 self.assertEqual(san(' . /. /foo ./ . /. ./ba .r', '/'), r'foo/ba .r')
1710
1711 def test_extract_hackers_arcnames_common_cases(self):
1712 common_hacknames = [
1713 ('../foo/bar', 'foo/bar'),
1714 ('foo/../bar', 'foo/bar'),
1715 ('foo/../../bar', 'foo/bar'),
1716 ('foo/bar/..', 'foo/bar'),
1717 ('./../foo/bar', 'foo/bar'),
1718 ('/foo/bar', 'foo/bar'),
1719 ('/foo/../bar', 'foo/bar'),
1720 ('/foo/../../bar', 'foo/bar'),
1721 ]
1722 self._test_extract_hackers_arcnames(common_hacknames)
1723
1724 @unittest.skipIf(os.path.sep != '\\', 'Requires \\ as path separator.')
1725 def test_extract_hackers_arcnames_windows_only(self):
1726 """Test combination of path fixing and windows name sanitization."""
1727 windows_hacknames = [
1728 (r'..\foo\bar', 'foo/bar'),
1729 (r'..\/foo\/bar', 'foo/bar'),
1730 (r'foo/\..\/bar', 'foo/bar'),
1731 (r'foo\/../\bar', 'foo/bar'),
1732 (r'C:foo/bar', 'foo/bar'),
1733 (r'C:/foo/bar', 'foo/bar'),
1734 (r'C://foo/bar', 'foo/bar'),
1735 (r'C:\foo\bar', 'foo/bar'),
1736 (r'//conky/mountpoint/foo/bar', 'foo/bar'),
1737 (r'\\conky\mountpoint\foo\bar', 'foo/bar'),
1738 (r'///conky/mountpoint/foo/bar', 'mountpoint/foo/bar'),
1739 (r'\\\conky\mountpoint\foo\bar', 'mountpoint/foo/bar'),
1740 (r'//conky//mountpoint/foo/bar', 'mountpoint/foo/bar'),
1741 (r'\\conky\\mountpoint\foo\bar', 'mountpoint/foo/bar'),
1742 (r'//?/C:/foo/bar', 'foo/bar'),
1743 (r'\\?\C:\foo\bar', 'foo/bar'),
1744 (r'C:/../C:/foo/bar', 'C_/foo/bar'),
1745 (r'a:b\c<d>e|f"g?h*i', 'b/c_d_e_f_g_h_i'),
1746 ('../../foo../../ba..r', 'foo/ba..r'),
1747 ]
1748 self._test_extract_hackers_arcnames(windows_hacknames)
1749
1750 @unittest.skipIf(os.path.sep != '/', r'Requires / as path separator.')
1751 def test_extract_hackers_arcnames_posix_only(self):
1752 posix_hacknames = [
1753 ('//foo/bar', 'foo/bar'),
1754 ('../../foo../../ba..r', 'foo../ba..r'),
1755 (r'foo/..\bar', r'foo/..\bar'),
1756 ]
1757 self._test_extract_hackers_arcnames(posix_hacknames)
1758
1759 def _test_extract_hackers_arcnames(self, hacknames):
1760 for arcname, fixedname in hacknames:
1761 content = b'foobar' + arcname.encode()
1762 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipfp:
1763 zinfo = zipfile.ZipInfo()
1764 # preserve backslashes
1765 zinfo.filename = arcname
1766 zinfo.external_attr = 0o600 << 16
1767 zipfp.writestr(zinfo, content)
1768
1769 arcname = arcname.replace(os.sep, "/")
1770 targetpath = os.path.join('target', 'subdir', 'subsub')
1771 correctfile = os.path.join(targetpath, *fixedname.split('/'))
1772
1773 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1774 writtenfile = zipfp.extract(arcname, targetpath)
1775 self.assertEqual(writtenfile, correctfile,
1776 msg='extract %r: %r != %r' %
1777 (arcname, writtenfile, correctfile))
1778 self.check_file(correctfile, content)
1779 rmtree('target')
1780
1781 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1782 zipfp.extractall(targetpath)
1783 self.check_file(correctfile, content)
1784 rmtree('target')
1785
1786 correctfile = os.path.join(os.getcwd(), *fixedname.split('/'))
1787
1788 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1789 writtenfile = zipfp.extract(arcname)
1790 self.assertEqual(writtenfile, correctfile,
1791 msg="extract %r" % arcname)
1792 self.check_file(correctfile, content)
1793 rmtree(fixedname.split('/')[0])
1794
1795 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1796 zipfp.extractall()
1797 self.check_file(correctfile, content)
1798 rmtree(fixedname.split('/')[0])
1799
1800 unlink(TESTFN2)
1801
1802
1803 class OverwriteTests(archiver_tests.OverwriteTests, unittest.TestCase):
1804 testdir = TESTFN
1805
1806 @classmethod
1807 def setUpClass(cls):
1808 p = cls.ar_with_file = TESTFN + '-with-file.zip'
1809 cls.addClassCleanup(unlink, p)
1810 with zipfile.ZipFile(p, 'w') as zipfp:
1811 zipfp.writestr('test', b'newcontent')
1812
1813 p = cls.ar_with_dir = TESTFN + '-with-dir.zip'
1814 cls.addClassCleanup(unlink, p)
1815 with zipfile.ZipFile(p, 'w') as zipfp:
1816 zipfp.mkdir('test')
1817
1818 p = cls.ar_with_implicit_dir = TESTFN + '-with-implicit-dir.zip'
1819 cls.addClassCleanup(unlink, p)
1820 with zipfile.ZipFile(p, 'w') as zipfp:
1821 zipfp.writestr('test/file', b'newcontent')
1822
1823 def open(self, path):
1824 return zipfile.ZipFile(path, 'r')
1825
1826 def extractall(self, ar):
1827 ar.extractall(self.testdir)
1828
1829
1830 class OtherTests(unittest.TestCase):
1831 def test_open_via_zip_info(self):
1832 # Create the ZIP archive
1833 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
1834 zipfp.writestr("name", "foo")
1835 with self.assertWarns(UserWarning):
1836 zipfp.writestr("name", "bar")
1837 self.assertEqual(zipfp.namelist(), ["name"] * 2)
1838
1839 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1840 infos = zipfp.infolist()
1841 data = b""
1842 for info in infos:
1843 with zipfp.open(info) as zipopen:
1844 data += zipopen.read()
1845 self.assertIn(data, {b"foobar", b"barfoo"})
1846 data = b""
1847 for info in infos:
1848 data += zipfp.read(info)
1849 self.assertIn(data, {b"foobar", b"barfoo"})
1850
1851 def test_writestr_extended_local_header_issue1202(self):
1852 with zipfile.ZipFile(TESTFN2, 'w') as orig_zip:
1853 for data in 'abcdefghijklmnop':
1854 zinfo = zipfile.ZipInfo(data)
1855 zinfo.flag_bits |= zipfile._MASK_USE_DATA_DESCRIPTOR # Include an extended local header.
1856 orig_zip.writestr(zinfo, data)
1857
1858 def test_close(self):
1859 """Check that the zipfile is closed after the 'with' block."""
1860 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
1861 for fpath, fdata in SMALL_TEST_DATA:
1862 zipfp.writestr(fpath, fdata)
1863 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
1864 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
1865
1866 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1867 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
1868 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
1869
1870 def test_close_on_exception(self):
1871 """Check that the zipfile is closed if an exception is raised in the
1872 'with' block."""
1873 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
1874 for fpath, fdata in SMALL_TEST_DATA:
1875 zipfp.writestr(fpath, fdata)
1876
1877 try:
1878 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
1879 raise zipfile.BadZipFile()
1880 except zipfile.BadZipFile:
1881 self.assertIsNone(zipfp2.fp, 'zipfp is not closed')
1882
1883 def test_unsupported_version(self):
1884 # File has an extract_version of 120
1885 data = (b'PK\x03\x04x\x00\x00\x00\x00\x00!p\xa1@\x00\x00\x00\x00\x00\x00'
1886 b'\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00xPK\x01\x02x\x03x\x00\x00\x00\x00'
1887 b'\x00!p\xa1@\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00'
1888 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00\x00xPK\x05\x06'
1889 b'\x00\x00\x00\x00\x01\x00\x01\x00/\x00\x00\x00\x1f\x00\x00\x00\x00\x00')
1890
1891 self.assertRaises(NotImplementedError, zipfile.ZipFile,
1892 io.BytesIO(data), 'r')
1893
1894 @requires_zlib()
1895 def test_read_unicode_filenames(self):
1896 # bug #10801
1897 fname = findfile('zip_cp437_header.zip', subdir='archivetestdata')
1898 with zipfile.ZipFile(fname) as zipfp:
1899 for name in zipfp.namelist():
1900 zipfp.open(name).close()
1901
1902 def test_write_unicode_filenames(self):
1903 with zipfile.ZipFile(TESTFN, "w") as zf:
1904 zf.writestr("foo.txt", "Test for unicode filename")
1905 zf.writestr("\xf6.txt", "Test for unicode filename")
1906 self.assertIsInstance(zf.infolist()[0].filename, str)
1907
1908 with zipfile.ZipFile(TESTFN, "r") as zf:
1909 self.assertEqual(zf.filelist[0].filename, "foo.txt")
1910 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
1911
1912 def create_zipfile_with_extra_data(self, filename, extra_data_name):
1913 with zipfile.ZipFile(TESTFN, mode='w') as zf:
1914 filename_encoded = filename.encode("utf-8")
1915 # create a ZipInfo object with Unicode path extra field
1916 zip_info = zipfile.ZipInfo(filename)
1917
1918 tag_for_unicode_path = b'\x75\x70'
1919 version_of_unicode_path = b'\x01'
1920
1921 import zlib
1922 filename_crc = struct.pack('<L', zlib.crc32(filename_encoded))
1923
1924 extra_data = version_of_unicode_path + filename_crc + extra_data_name
1925 tsize = len(extra_data).to_bytes(2, 'little')
1926
1927 zip_info.extra = tag_for_unicode_path + tsize + extra_data
1928
1929 # add the file to the ZIP archive
1930 zf.writestr(zip_info, b'Hello World!')
1931
1932 @requires_zlib()
1933 def test_read_zipfile_containing_unicode_path_extra_field(self):
1934 self.create_zipfile_with_extra_data("이름.txt", "이름.txt".encode("utf-8"))
1935 with zipfile.ZipFile(TESTFN, "r") as zf:
1936 self.assertEqual(zf.filelist[0].filename, "이름.txt")
1937
1938 @requires_zlib()
1939 def test_read_zipfile_warning(self):
1940 self.create_zipfile_with_extra_data("이름.txt", b"")
1941 with self.assertWarns(UserWarning):
1942 zipfile.ZipFile(TESTFN, "r").close()
1943
1944 @requires_zlib()
1945 def test_read_zipfile_error(self):
1946 self.create_zipfile_with_extra_data("이름.txt", b"\xff")
1947 with self.assertRaises(zipfile.BadZipfile):
1948 zipfile.ZipFile(TESTFN, "r").close()
1949
1950 def test_read_after_write_unicode_filenames(self):
1951 with zipfile.ZipFile(TESTFN2, 'w') as zipfp:
1952 zipfp.writestr('приклад', b'sample')
1953 self.assertEqual(zipfp.read('приклад'), b'sample')
1954
1955 def test_exclusive_create_zip_file(self):
1956 """Test exclusive creating a new zipfile."""
1957 unlink(TESTFN2)
1958 filename = 'testfile.txt'
1959 content = b'hello, world. this is some content.'
1960 with zipfile.ZipFile(TESTFN2, "x", zipfile.ZIP_STORED) as zipfp:
1961 zipfp.writestr(filename, content)
1962 with self.assertRaises(FileExistsError):
1963 zipfile.ZipFile(TESTFN2, "x", zipfile.ZIP_STORED)
1964 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1965 self.assertEqual(zipfp.namelist(), [filename])
1966 self.assertEqual(zipfp.read(filename), content)
1967
1968 def test_create_non_existent_file_for_append(self):
1969 if os.path.exists(TESTFN):
1970 os.unlink(TESTFN)
1971
1972 filename = 'testfile.txt'
1973 content = b'hello, world. this is some content.'
1974
1975 try:
1976 with zipfile.ZipFile(TESTFN, 'a') as zf:
1977 zf.writestr(filename, content)
1978 except OSError:
1979 self.fail('Could not append data to a non-existent zip file.')
1980
1981 self.assertTrue(os.path.exists(TESTFN))
1982
1983 with zipfile.ZipFile(TESTFN, 'r') as zf:
1984 self.assertEqual(zf.read(filename), content)
1985
1986 def test_close_erroneous_file(self):
1987 # This test checks that the ZipFile constructor closes the file object
1988 # it opens if there's an error in the file. If it doesn't, the
1989 # traceback holds a reference to the ZipFile object and, indirectly,
1990 # the file object.
1991 # On Windows, this causes the os.unlink() call to fail because the
1992 # underlying file is still open. This is SF bug #412214.
1993 #
1994 with open(TESTFN, "w", encoding="utf-8") as fp:
1995 fp.write("this is not a legal zip file\n")
1996 try:
1997 zf = zipfile.ZipFile(TESTFN)
1998 except zipfile.BadZipFile:
1999 pass
2000
2001 def test_is_zip_erroneous_file(self):
2002 """Check that is_zipfile() correctly identifies non-zip files."""
2003 # - passing a filename
2004 with open(TESTFN, "w", encoding='utf-8') as fp:
2005 fp.write("this is not a legal zip file\n")
2006 self.assertFalse(zipfile.is_zipfile(TESTFN))
2007 # - passing a path-like object
2008 self.assertFalse(zipfile.is_zipfile(FakePath(TESTFN)))
2009 # - passing a file object
2010 with open(TESTFN, "rb") as fp:
2011 self.assertFalse(zipfile.is_zipfile(fp))
2012 # - passing a file-like object
2013 fp = io.BytesIO()
2014 fp.write(b"this is not a legal zip file\n")
2015 self.assertFalse(zipfile.is_zipfile(fp))
2016 fp.seek(0, 0)
2017 self.assertFalse(zipfile.is_zipfile(fp))
2018
2019 def test_damaged_zipfile(self):
2020 """Check that zipfiles with missing bytes at the end raise BadZipFile."""
2021 # - Create a valid zip file
2022 fp = io.BytesIO()
2023 with zipfile.ZipFile(fp, mode="w") as zipf:
2024 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
2025 zipfiledata = fp.getvalue()
2026
2027 # - Now create copies of it missing the last N bytes and make sure
2028 # a BadZipFile exception is raised when we try to open it
2029 for N in range(len(zipfiledata)):
2030 fp = io.BytesIO(zipfiledata[:N])
2031 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, fp)
2032
2033 def test_is_zip_valid_file(self):
2034 """Check that is_zipfile() correctly identifies zip files."""
2035 # - passing a filename
2036 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
2037 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
2038
2039 self.assertTrue(zipfile.is_zipfile(TESTFN))
2040 # - passing a file object
2041 with open(TESTFN, "rb") as fp:
2042 self.assertTrue(zipfile.is_zipfile(fp))
2043 fp.seek(0, 0)
2044 zip_contents = fp.read()
2045 # - passing a file-like object
2046 fp = io.BytesIO()
2047 fp.write(zip_contents)
2048 self.assertTrue(zipfile.is_zipfile(fp))
2049 fp.seek(0, 0)
2050 self.assertTrue(zipfile.is_zipfile(fp))
2051
2052 def test_non_existent_file_raises_OSError(self):
2053 # make sure we don't raise an AttributeError when a partially-constructed
2054 # ZipFile instance is finalized; this tests for regression on SF tracker
2055 # bug #403871.
2056
2057 # The bug we're testing for caused an AttributeError to be raised
2058 # when a ZipFile instance was created for a file that did not
2059 # exist; the .fp member was not initialized but was needed by the
2060 # __del__() method. Since the AttributeError is in the __del__(),
2061 # it is ignored, but the user should be sufficiently annoyed by
2062 # the message on the output that regression will be noticed
2063 # quickly.
2064 self.assertRaises(OSError, zipfile.ZipFile, TESTFN)
2065
2066 def test_empty_file_raises_BadZipFile(self):
2067 f = open(TESTFN, 'w', encoding='utf-8')
2068 f.close()
2069 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
2070
2071 with open(TESTFN, 'w', encoding='utf-8') as fp:
2072 fp.write("short file")
2073 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
2074
2075 def test_negative_central_directory_offset_raises_BadZipFile(self):
2076 # Zip file containing an empty EOCD record
2077 buffer = bytearray(b'PK\x05\x06' + b'\0'*18)
2078
2079 # Set the size of the central directory bytes to become 1,
2080 # causing the central directory offset to become negative
2081 for dirsize in 1, 2**32-1:
2082 buffer[12:16] = struct.pack('<L', dirsize)
2083 f = io.BytesIO(buffer)
2084 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, f)
2085
2086 def test_closed_zip_raises_ValueError(self):
2087 """Verify that testzip() doesn't swallow inappropriate exceptions."""
2088 data = io.BytesIO()
2089 with zipfile.ZipFile(data, mode="w") as zipf:
2090 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
2091
2092 # This is correct; calling .read on a closed ZipFile should raise
2093 # a ValueError, and so should calling .testzip. An earlier
2094 # version of .testzip would swallow this exception (and any other)
2095 # and report that the first file in the archive was corrupt.
2096 self.assertRaises(ValueError, zipf.read, "foo.txt")
2097 self.assertRaises(ValueError, zipf.open, "foo.txt")
2098 self.assertRaises(ValueError, zipf.testzip)
2099 self.assertRaises(ValueError, zipf.writestr, "bogus.txt", "bogus")
2100 with open(TESTFN, 'w', encoding='utf-8') as f:
2101 f.write('zipfile test data')
2102 self.assertRaises(ValueError, zipf.write, TESTFN)
2103
2104 def test_bad_constructor_mode(self):
2105 """Check that bad modes passed to ZipFile constructor are caught."""
2106 self.assertRaises(ValueError, zipfile.ZipFile, TESTFN, "q")
2107
2108 def test_bad_open_mode(self):
2109 """Check that bad modes passed to ZipFile.open are caught."""
2110 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
2111 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
2112
2113 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
2114 # read the data to make sure the file is there
2115 zipf.read("foo.txt")
2116 self.assertRaises(ValueError, zipf.open, "foo.txt", "q")
2117 # universal newlines support is removed
2118 self.assertRaises(ValueError, zipf.open, "foo.txt", "U")
2119 self.assertRaises(ValueError, zipf.open, "foo.txt", "rU")
2120
2121 def test_read0(self):
2122 """Check that calling read(0) on a ZipExtFile object returns an empty
2123 string and doesn't advance file pointer."""
2124 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
2125 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
2126 # read the data to make sure the file is there
2127 with zipf.open("foo.txt") as f:
2128 for i in range(FIXEDTEST_SIZE):
2129 self.assertEqual(f.read(0), b'')
2130
2131 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
2132
2133 def test_open_non_existent_item(self):
2134 """Check that attempting to call open() for an item that doesn't
2135 exist in the archive raises a RuntimeError."""
2136 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
2137 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
2138
2139 def test_bad_compression_mode(self):
2140 """Check that bad compression methods passed to ZipFile.open are
2141 caught."""
2142 self.assertRaises(NotImplementedError, zipfile.ZipFile, TESTFN, "w", -1)
2143
2144 def test_unsupported_compression(self):
2145 # data is declared as shrunk, but actually deflated
2146 data = (b'PK\x03\x04.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00'
2147 b'\x00\x02\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00x\x03\x00PK\x01'
2148 b'\x02.\x03.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00\x00\x02\x00\x00'
2149 b'\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
2150 b'\x80\x01\x00\x00\x00\x00xPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00'
2151 b'/\x00\x00\x00!\x00\x00\x00\x00\x00')
2152 with zipfile.ZipFile(io.BytesIO(data), 'r') as zipf:
2153 self.assertRaises(NotImplementedError, zipf.open, 'x')
2154
2155 def test_null_byte_in_filename(self):
2156 """Check that a filename containing a null byte is properly
2157 terminated."""
2158 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
2159 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
2160 self.assertEqual(zipf.namelist(), ['foo.txt'])
2161
2162 def test_struct_sizes(self):
2163 """Check that ZIP internal structure sizes are calculated correctly."""
2164 self.assertEqual(zipfile.sizeEndCentDir, 22)
2165 self.assertEqual(zipfile.sizeCentralDir, 46)
2166 self.assertEqual(zipfile.sizeEndCentDir64, 56)
2167 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
2168
2169 def test_comments(self):
2170 """Check that comments on the archive are handled properly."""
2171
2172 # check default comment is empty
2173 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
2174 self.assertEqual(zipf.comment, b'')
2175 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
2176
2177 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
2178 self.assertEqual(zipfr.comment, b'')
2179
2180 # check a simple short comment
2181 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
2182 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
2183 zipf.comment = comment
2184 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
2185 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
2186 self.assertEqual(zipf.comment, comment)
2187
2188 # check a comment of max length
2189 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
2190 comment2 = comment2.encode("ascii")
2191 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
2192 zipf.comment = comment2
2193 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
2194
2195 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
2196 self.assertEqual(zipfr.comment, comment2)
2197
2198 # check a comment that is too long is truncated
2199 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
2200 with self.assertWarns(UserWarning):
2201 zipf.comment = comment2 + b'oops'
2202 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
2203 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
2204 self.assertEqual(zipfr.comment, comment2)
2205
2206 # check that comments are correctly modified in append mode
2207 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
2208 zipf.comment = b"original comment"
2209 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
2210 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
2211 zipf.comment = b"an updated comment"
2212 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
2213 self.assertEqual(zipf.comment, b"an updated comment")
2214
2215 # check that comments are correctly shortened in append mode
2216 # and the file is indeed truncated
2217 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
2218 zipf.comment = b"original comment that's longer"
2219 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
2220 original_zip_size = os.path.getsize(TESTFN)
2221 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
2222 zipf.comment = b"shorter comment"
2223 self.assertTrue(original_zip_size > os.path.getsize(TESTFN))
2224 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
2225 self.assertEqual(zipf.comment, b"shorter comment")
2226
2227 def test_unicode_comment(self):
2228 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
2229 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
2230 with self.assertRaises(TypeError):
2231 zipf.comment = "this is an error"
2232
2233 def test_change_comment_in_empty_archive(self):
2234 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
2235 self.assertFalse(zipf.filelist)
2236 zipf.comment = b"this is a comment"
2237 with zipfile.ZipFile(TESTFN, "r") as zipf:
2238 self.assertEqual(zipf.comment, b"this is a comment")
2239
2240 def test_change_comment_in_nonempty_archive(self):
2241 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
2242 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
2243 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
2244 self.assertTrue(zipf.filelist)
2245 zipf.comment = b"this is a comment"
2246 with zipfile.ZipFile(TESTFN, "r") as zipf:
2247 self.assertEqual(zipf.comment, b"this is a comment")
2248
2249 def test_empty_zipfile(self):
2250 # Check that creating a file in 'w' or 'a' mode and closing without
2251 # adding any files to the archives creates a valid empty ZIP file
2252 zipf = zipfile.ZipFile(TESTFN, mode="w")
2253 zipf.close()
2254 try:
2255 zipf = zipfile.ZipFile(TESTFN, mode="r")
2256 except zipfile.BadZipFile:
2257 self.fail("Unable to create empty ZIP file in 'w' mode")
2258 zipf.close()
2259
2260 zipf = zipfile.ZipFile(TESTFN, mode="a")
2261 zipf.close()
2262 try:
2263 zipf = zipfile.ZipFile(TESTFN, mode="r")
2264 except:
2265 self.fail("Unable to create empty ZIP file in 'a' mode")
2266 zipf.close()
2267
2268 def test_open_empty_file(self):
2269 # Issue 1710703: Check that opening a file with less than 22 bytes
2270 # raises a BadZipFile exception (rather than the previously unhelpful
2271 # OSError)
2272 f = open(TESTFN, 'w', encoding='utf-8')
2273 f.close()
2274 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN, 'r')
2275
2276 def test_create_zipinfo_before_1980(self):
2277 self.assertRaises(ValueError,
2278 zipfile.ZipInfo, 'seventies', (1979, 1, 1, 0, 0, 0))
2279
2280 def test_create_empty_zipinfo_repr(self):
2281 """Before bpo-26185, repr() on empty ZipInfo object was failing."""
2282 zi = zipfile.ZipInfo(filename="empty")
2283 self.assertEqual(repr(zi), "<ZipInfo filename='empty' file_size=0>")
2284
2285 def test_create_empty_zipinfo_default_attributes(self):
2286 """Ensure all required attributes are set."""
2287 zi = zipfile.ZipInfo()
2288 self.assertEqual(zi.orig_filename, "NoName")
2289 self.assertEqual(zi.filename, "NoName")
2290 self.assertEqual(zi.date_time, (1980, 1, 1, 0, 0, 0))
2291 self.assertEqual(zi.compress_type, zipfile.ZIP_STORED)
2292 self.assertEqual(zi.comment, b"")
2293 self.assertEqual(zi.extra, b"")
2294 self.assertIn(zi.create_system, (0, 3))
2295 self.assertEqual(zi.create_version, zipfile.DEFAULT_VERSION)
2296 self.assertEqual(zi.extract_version, zipfile.DEFAULT_VERSION)
2297 self.assertEqual(zi.reserved, 0)
2298 self.assertEqual(zi.flag_bits, 0)
2299 self.assertEqual(zi.volume, 0)
2300 self.assertEqual(zi.internal_attr, 0)
2301 self.assertEqual(zi.external_attr, 0)
2302
2303 # Before bpo-26185, both were missing
2304 self.assertEqual(zi.file_size, 0)
2305 self.assertEqual(zi.compress_size, 0)
2306
2307 def test_zipfile_with_short_extra_field(self):
2308 """If an extra field in the header is less than 4 bytes, skip it."""
2309 zipdata = (
2310 b'PK\x03\x04\x14\x00\x00\x00\x00\x00\x93\x9b\xad@\x8b\x9e'
2311 b'\xd9\xd3\x01\x00\x00\x00\x01\x00\x00\x00\x03\x00\x03\x00ab'
2312 b'c\x00\x00\x00APK\x01\x02\x14\x03\x14\x00\x00\x00\x00'
2313 b'\x00\x93\x9b\xad@\x8b\x9e\xd9\xd3\x01\x00\x00\x00\x01\x00\x00'
2314 b'\x00\x03\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00'
2315 b'\x00\x00\x00abc\x00\x00PK\x05\x06\x00\x00\x00\x00'
2316 b'\x01\x00\x01\x003\x00\x00\x00%\x00\x00\x00\x00\x00'
2317 )
2318 with zipfile.ZipFile(io.BytesIO(zipdata), 'r') as zipf:
2319 # testzip returns the name of the first corrupt file, or None
2320 self.assertIsNone(zipf.testzip())
2321
2322 def test_open_conflicting_handles(self):
2323 # It's only possible to open one writable file handle at a time
2324 msg1 = b"It's fun to charter an accountant!"
2325 msg2 = b"And sail the wide accountant sea"
2326 msg3 = b"To find, explore the funds offshore"
2327 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipf:
2328 with zipf.open('foo', mode='w') as w2:
2329 w2.write(msg1)
2330 with zipf.open('bar', mode='w') as w1:
2331 with self.assertRaises(ValueError):
2332 zipf.open('handle', mode='w')
2333 with self.assertRaises(ValueError):
2334 zipf.open('foo', mode='r')
2335 with self.assertRaises(ValueError):
2336 zipf.writestr('str', 'abcde')
2337 with self.assertRaises(ValueError):
2338 zipf.write(__file__, 'file')
2339 with self.assertRaises(ValueError):
2340 zipf.close()
2341 w1.write(msg2)
2342 with zipf.open('baz', mode='w') as w2:
2343 w2.write(msg3)
2344
2345 with zipfile.ZipFile(TESTFN2, 'r') as zipf:
2346 self.assertEqual(zipf.read('foo'), msg1)
2347 self.assertEqual(zipf.read('bar'), msg2)
2348 self.assertEqual(zipf.read('baz'), msg3)
2349 self.assertEqual(zipf.namelist(), ['foo', 'bar', 'baz'])
2350
2351 def test_seek_tell(self):
2352 # Test seek functionality
2353 txt = b"Where's Bruce?"
2354 bloc = txt.find(b"Bruce")
2355 # Check seek on a file
2356 with zipfile.ZipFile(TESTFN, "w") as zipf:
2357 zipf.writestr("foo.txt", txt)
2358 with zipfile.ZipFile(TESTFN, "r") as zipf:
2359 with zipf.open("foo.txt", "r") as fp:
2360 fp.seek(bloc, os.SEEK_SET)
2361 self.assertEqual(fp.tell(), bloc)
2362 fp.seek(-bloc, os.SEEK_CUR)
2363 self.assertEqual(fp.tell(), 0)
2364 fp.seek(bloc, os.SEEK_CUR)
2365 self.assertEqual(fp.tell(), bloc)
2366 self.assertEqual(fp.read(5), txt[bloc:bloc+5])
2367 self.assertEqual(fp.tell(), bloc + 5)
2368 fp.seek(0, os.SEEK_END)
2369 self.assertEqual(fp.tell(), len(txt))
2370 fp.seek(0, os.SEEK_SET)
2371 self.assertEqual(fp.tell(), 0)
2372 # Check seek on memory file
2373 data = io.BytesIO()
2374 with zipfile.ZipFile(data, mode="w") as zipf:
2375 zipf.writestr("foo.txt", txt)
2376 with zipfile.ZipFile(data, mode="r") as zipf:
2377 with zipf.open("foo.txt", "r") as fp:
2378 fp.seek(bloc, os.SEEK_SET)
2379 self.assertEqual(fp.tell(), bloc)
2380 fp.seek(-bloc, os.SEEK_CUR)
2381 self.assertEqual(fp.tell(), 0)
2382 fp.seek(bloc, os.SEEK_CUR)
2383 self.assertEqual(fp.tell(), bloc)
2384 self.assertEqual(fp.read(5), txt[bloc:bloc+5])
2385 self.assertEqual(fp.tell(), bloc + 5)
2386 fp.seek(0, os.SEEK_END)
2387 self.assertEqual(fp.tell(), len(txt))
2388 fp.seek(0, os.SEEK_SET)
2389 self.assertEqual(fp.tell(), 0)
2390
2391 def test_read_after_seek(self):
2392 # Issue 102956: Make sure seek(x, os.SEEK_CUR) doesn't break read()
2393 txt = b"Charge men!"
2394 bloc = txt.find(b"men")
2395 with zipfile.ZipFile(TESTFN, "w") as zipf:
2396 zipf.writestr("foo.txt", txt)
2397 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
2398 with zipf.open("foo.txt", "r") as fp:
2399 fp.seek(bloc, os.SEEK_CUR)
2400 self.assertEqual(fp.read(-1), b'men!')
2401 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
2402 with zipf.open("foo.txt", "r") as fp:
2403 fp.read(6)
2404 fp.seek(1, os.SEEK_CUR)
2405 self.assertEqual(fp.read(-1), b'men!')
2406
2407 def test_uncompressed_interleaved_seek_read(self):
2408 # gh-127847: Make sure the position in the archive is correct
2409 # in the special case of seeking in a ZIP_STORED entry.
2410 with zipfile.ZipFile(TESTFN, "w") as zipf:
2411 zipf.writestr("a.txt", "123")
2412 zipf.writestr("b.txt", "456")
2413 with zipfile.ZipFile(TESTFN, "r") as zipf:
2414 with zipf.open("a.txt", "r") as a, zipf.open("b.txt", "r") as b:
2415 self.assertEqual(a.read(1), b"1")
2416 self.assertEqual(b.seek(1), 1)
2417 self.assertEqual(b.read(1), b"5")
2418
2419 @requires_bz2()
2420 def test_decompress_without_3rd_party_library(self):
2421 data = b'PK\x05\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
2422 zip_file = io.BytesIO(data)
2423 with zipfile.ZipFile(zip_file, 'w', compression=zipfile.ZIP_BZIP2) as zf:
2424 zf.writestr('a.txt', b'a')
2425 with mock.patch('zipfile.bz2', None):
2426 with zipfile.ZipFile(zip_file) as zf:
2427 self.assertRaises(RuntimeError, zf.extract, 'a.txt')
2428
2429 @requires_zlib()
2430 def test_full_overlap_different_names(self):
2431 # The ZIP file contains two central directory entries with
2432 # different names which refer to the same local header.
2433 # The name of the local header matches the name of the first
2434 # central directory entry.
2435 data = (
2436 b'PK\x03\x04\x14\x00\x00\x00\x08\x00\xa0lH\x05\xe2\x1e'
2437 b'8\xbb\x10\x00\x00\x00\t\x04\x00\x00\x01\x00\x00\x00b\xed'
2438 b'\xc0\x81\x08\x00\x00\x00\xc00\xd6\xfbK\\d\x0b`P'
2439 b'K\x01\x02\x14\x00\x14\x00\x00\x00\x08\x00\xa0lH\x05\xe2'
2440 b'\x1e8\xbb\x10\x00\x00\x00\t\x04\x00\x00\x01\x00\x00\x00\x00'
2441 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00aPK'
2442 b'\x01\x02\x14\x00\x14\x00\x00\x00\x08\x00\xa0lH\x05\xe2\x1e'
2443 b'8\xbb\x10\x00\x00\x00\t\x04\x00\x00\x01\x00\x00\x00\x00\x00'
2444 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00bPK\x05'
2445 b'\x06\x00\x00\x00\x00\x02\x00\x02\x00^\x00\x00\x00/\x00\x00'
2446 b'\x00\x00\x00'
2447 )
2448 with zipfile.ZipFile(io.BytesIO(data), 'r') as zipf:
2449 self.assertEqual(zipf.namelist(), ['a', 'b'])
2450 zi = zipf.getinfo('a')
2451 self.assertEqual(zi.header_offset, 0)
2452 self.assertEqual(zi.compress_size, 16)
2453 self.assertEqual(zi.file_size, 1033)
2454 zi = zipf.getinfo('b')
2455 self.assertEqual(zi.header_offset, 0)
2456 self.assertEqual(zi.compress_size, 16)
2457 self.assertEqual(zi.file_size, 1033)
2458 self.assertEqual(len(zipf.read('b')), 1033)
2459 with self.assertRaisesRegex(zipfile.BadZipFile, 'File name.*differ'):
2460 zipf.read('a')
2461
2462 @requires_zlib()
2463 def test_full_overlap_different_names2(self):
2464 # The ZIP file contains two central directory entries with
2465 # different names which refer to the same local header.
2466 # The name of the local header matches the name of the second
2467 # central directory entry.
2468 data = (
2469 b'PK\x03\x04\x14\x00\x00\x00\x08\x00\xa0lH\x05\xe2\x1e'
2470 b'8\xbb\x10\x00\x00\x00\t\x04\x00\x00\x01\x00\x00\x00a\xed'
2471 b'\xc0\x81\x08\x00\x00\x00\xc00\xd6\xfbK\\d\x0b`P'
2472 b'K\x01\x02\x14\x00\x14\x00\x00\x00\x08\x00\xa0lH\x05\xe2'
2473 b'\x1e8\xbb\x10\x00\x00\x00\t\x04\x00\x00\x01\x00\x00\x00\x00'
2474 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00aPK'
2475 b'\x01\x02\x14\x00\x14\x00\x00\x00\x08\x00\xa0lH\x05\xe2\x1e'
2476 b'8\xbb\x10\x00\x00\x00\t\x04\x00\x00\x01\x00\x00\x00\x00\x00'
2477 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00bPK\x05'
2478 b'\x06\x00\x00\x00\x00\x02\x00\x02\x00^\x00\x00\x00/\x00\x00'
2479 b'\x00\x00\x00'
2480 )
2481 with zipfile.ZipFile(io.BytesIO(data), 'r') as zipf:
2482 self.assertEqual(zipf.namelist(), ['a', 'b'])
2483 zi = zipf.getinfo('a')
2484 self.assertEqual(zi.header_offset, 0)
2485 self.assertEqual(zi.compress_size, 16)
2486 self.assertEqual(zi.file_size, 1033)
2487 zi = zipf.getinfo('b')
2488 self.assertEqual(zi.header_offset, 0)
2489 self.assertEqual(zi.compress_size, 16)
2490 self.assertEqual(zi.file_size, 1033)
2491 with self.assertRaisesRegex(zipfile.BadZipFile, 'File name.*differ'):
2492 zipf.read('b')
2493 with self.assertWarnsRegex(UserWarning, 'Overlapped entries') as cm:
2494 self.assertEqual(len(zipf.read('a')), 1033)
2495 self.assertEqual(cm.filename, __file__)
2496
2497 @requires_zlib()
2498 def test_full_overlap_same_name(self):
2499 # The ZIP file contains two central directory entries with
2500 # the same name which refer to the same local header.
2501 data = (
2502 b'PK\x03\x04\x14\x00\x00\x00\x08\x00\xa0lH\x05\xe2\x1e'
2503 b'8\xbb\x10\x00\x00\x00\t\x04\x00\x00\x01\x00\x00\x00a\xed'
2504 b'\xc0\x81\x08\x00\x00\x00\xc00\xd6\xfbK\\d\x0b`P'
2505 b'K\x01\x02\x14\x00\x14\x00\x00\x00\x08\x00\xa0lH\x05\xe2'
2506 b'\x1e8\xbb\x10\x00\x00\x00\t\x04\x00\x00\x01\x00\x00\x00\x00'
2507 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00aPK'
2508 b'\x01\x02\x14\x00\x14\x00\x00\x00\x08\x00\xa0lH\x05\xe2\x1e'
2509 b'8\xbb\x10\x00\x00\x00\t\x04\x00\x00\x01\x00\x00\x00\x00\x00'
2510 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00aPK\x05'
2511 b'\x06\x00\x00\x00\x00\x02\x00\x02\x00^\x00\x00\x00/\x00\x00'
2512 b'\x00\x00\x00'
2513 )
2514 with zipfile.ZipFile(io.BytesIO(data), 'r') as zipf:
2515 self.assertEqual(zipf.namelist(), ['a', 'a'])
2516 self.assertEqual(len(zipf.infolist()), 2)
2517 zi = zipf.getinfo('a')
2518 self.assertEqual(zi.header_offset, 0)
2519 self.assertEqual(zi.compress_size, 16)
2520 self.assertEqual(zi.file_size, 1033)
2521 self.assertEqual(len(zipf.read('a')), 1033)
2522 self.assertEqual(len(zipf.read(zi)), 1033)
2523 self.assertEqual(len(zipf.read(zipf.infolist()[1])), 1033)
2524 with self.assertWarnsRegex(UserWarning, 'Overlapped entries') as cm:
2525 self.assertEqual(len(zipf.read(zipf.infolist()[0])), 1033)
2526 self.assertEqual(cm.filename, __file__)
2527 with self.assertWarnsRegex(UserWarning, 'Overlapped entries') as cm:
2528 zipf.open(zipf.infolist()[0]).close()
2529 self.assertEqual(cm.filename, __file__)
2530
2531 @requires_zlib()
2532 def test_quoted_overlap(self):
2533 # The ZIP file contains two files. The second local header
2534 # is contained in the range of the first file.
2535 data = (
2536 b'PK\x03\x04\x14\x00\x00\x00\x08\x00\xa0lH\x05Y\xfc'
2537 b'8\x044\x00\x00\x00(\x04\x00\x00\x01\x00\x00\x00a\x00'
2538 b'\x1f\x00\xe0\xffPK\x03\x04\x14\x00\x00\x00\x08\x00\xa0l'
2539 b'H\x05\xe2\x1e8\xbb\x10\x00\x00\x00\t\x04\x00\x00\x01\x00'
2540 b'\x00\x00b\xed\xc0\x81\x08\x00\x00\x00\xc00\xd6\xfbK\\'
2541 b'd\x0b`PK\x01\x02\x14\x00\x14\x00\x00\x00\x08\x00\xa0'
2542 b'lH\x05Y\xfc8\x044\x00\x00\x00(\x04\x00\x00\x01'
2543 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
2544 b'\x00aPK\x01\x02\x14\x00\x14\x00\x00\x00\x08\x00\xa0l'
2545 b'H\x05\xe2\x1e8\xbb\x10\x00\x00\x00\t\x04\x00\x00\x01\x00'
2546 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00$\x00\x00\x00'
2547 b'bPK\x05\x06\x00\x00\x00\x00\x02\x00\x02\x00^\x00\x00'
2548 b'\x00S\x00\x00\x00\x00\x00'
2549 )
2550 with zipfile.ZipFile(io.BytesIO(data), 'r') as zipf:
2551 self.assertEqual(zipf.namelist(), ['a', 'b'])
2552 zi = zipf.getinfo('a')
2553 self.assertEqual(zi.header_offset, 0)
2554 self.assertEqual(zi.compress_size, 52)
2555 self.assertEqual(zi.file_size, 1064)
2556 zi = zipf.getinfo('b')
2557 self.assertEqual(zi.header_offset, 36)
2558 self.assertEqual(zi.compress_size, 16)
2559 self.assertEqual(zi.file_size, 1033)
2560 with self.assertRaisesRegex(zipfile.BadZipFile, 'Overlapped entries'):
2561 zipf.read('a')
2562 self.assertEqual(len(zipf.read('b')), 1033)
2563
2564 @requires_zlib()
2565 def test_overlap_with_central_dir(self):
2566 # The local header offset is equal to the central directory offset.
2567 data = (
2568 b'PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00G_|Z'
2569 b'\xe2\x1e8\xbb\x0b\x00\x00\x00\t\x04\x00\x00\x01\x00\x00\x00'
2570 b'\x00\x00\x00\x00\x00\x00\x00\x00\xb4\x81\x00\x00\x00\x00aP'
2571 b'K\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00/\x00\x00\x00\x00'
2572 b'\x00\x00\x00\x00\x00'
2573 )
2574 with zipfile.ZipFile(io.BytesIO(data), 'r') as zipf:
2575 self.assertEqual(zipf.namelist(), ['a'])
2576 self.assertEqual(len(zipf.infolist()), 1)
2577 zi = zipf.getinfo('a')
2578 self.assertEqual(zi.header_offset, 0)
2579 self.assertEqual(zi.compress_size, 11)
2580 self.assertEqual(zi.file_size, 1033)
2581 # Found central directory signature PK\x01\x02 instead of
2582 # local header signature PK\x03\x04.
2583 with self.assertRaisesRegex(zipfile.BadZipFile, 'Bad magic number'):
2584 zipf.read('a')
2585
2586 @requires_zlib()
2587 def test_overlap_with_archive_comment(self):
2588 # The local header is written after the central directory,
2589 # in the archive comment.
2590 data = (
2591 b'PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00G_|Z'
2592 b'\xe2\x1e8\xbb\x0b\x00\x00\x00\t\x04\x00\x00\x01\x00\x00\x00'
2593 b'\x00\x00\x00\x00\x00\x00\x00\x00\xb4\x81E\x00\x00\x00aP'
2594 b'K\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00/\x00\x00\x00\x00'
2595 b'\x00\x00\x00*\x00'
2596 b'PK\x03\x04\x14\x00\x00\x00\x08\x00G_|Z\xe2\x1e'
2597 b'8\xbb\x0b\x00\x00\x00\t\x04\x00\x00\x01\x00\x00\x00aK'
2598 b'L\x1c\x05\xa3`\x14\x8cx\x00\x00'
2599 )
2600 with zipfile.ZipFile(io.BytesIO(data), 'r') as zipf:
2601 self.assertEqual(zipf.namelist(), ['a'])
2602 self.assertEqual(len(zipf.infolist()), 1)
2603 zi = zipf.getinfo('a')
2604 self.assertEqual(zi.header_offset, 69)
2605 self.assertEqual(zi.compress_size, 11)
2606 self.assertEqual(zi.file_size, 1033)
2607 with self.assertRaisesRegex(zipfile.BadZipFile, 'Overlapped entries'):
2608 zipf.read('a')
2609
2610 def tearDown(self):
2611 unlink(TESTFN)
2612 unlink(TESTFN2)
2613
2614
2615 class AbstractBadCrcTests:
2616 def test_testzip_with_bad_crc(self):
2617 """Tests that files with bad CRCs return their name from testzip."""
2618 zipdata = self.zip_with_bad_crc
2619
2620 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
2621 # testzip returns the name of the first corrupt file, or None
2622 self.assertEqual('afile', zipf.testzip())
2623
2624 def test_read_with_bad_crc(self):
2625 """Tests that files with bad CRCs raise a BadZipFile exception when read."""
2626 zipdata = self.zip_with_bad_crc
2627
2628 # Using ZipFile.read()
2629 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
2630 self.assertRaises(zipfile.BadZipFile, zipf.read, 'afile')
2631
2632 # Using ZipExtFile.read()
2633 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
2634 with zipf.open('afile', 'r') as corrupt_file:
2635 self.assertRaises(zipfile.BadZipFile, corrupt_file.read)
2636
2637 # Same with small reads (in order to exercise the buffering logic)
2638 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
2639 with zipf.open('afile', 'r') as corrupt_file:
2640 corrupt_file.MIN_READ_SIZE = 2
2641 with self.assertRaises(zipfile.BadZipFile):
2642 while corrupt_file.read(2):
2643 pass
2644
2645
2646 class StoredBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
2647 compression = zipfile.ZIP_STORED
2648 zip_with_bad_crc = (
2649 b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
2650 b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
2651 b'ilehello,AworldP'
2652 b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
2653 b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
2654 b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
2655 b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
2656 b'\0\0/\0\0\0\0\0')
2657
2658 @requires_zlib()
2659 class DeflateBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
2660 compression = zipfile.ZIP_DEFLATED
2661 zip_with_bad_crc = (
2662 b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
2663 b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
2664 b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
2665 b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
2666 b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
2667 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
2668 b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
2669 b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00')
2670
2671 @requires_bz2()
2672 class Bzip2BadCrcTests(AbstractBadCrcTests, unittest.TestCase):
2673 compression = zipfile.ZIP_BZIP2
2674 zip_with_bad_crc = (
2675 b'PK\x03\x04\x14\x03\x00\x00\x0c\x00nu\x0c=FA'
2676 b'KE8\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
2677 b'ileBZh91AY&SY\xd4\xa8\xca'
2678 b'\x7f\x00\x00\x0f\x11\x80@\x00\x06D\x90\x80 \x00 \xa5'
2679 b'P\xd9!\x03\x03\x13\x13\x13\x89\xa9\xa9\xc2u5:\x9f'
2680 b'\x8b\xb9"\x9c(HjTe?\x80PK\x01\x02\x14'
2681 b'\x03\x14\x03\x00\x00\x0c\x00nu\x0c=FAKE8'
2682 b'\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\x00'
2683 b'\x00 \x80\x80\x81\x00\x00\x00\x00afilePK'
2684 b'\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00\x00[\x00'
2685 b'\x00\x00\x00\x00')
2686
2687 @requires_lzma()
2688 class LzmaBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
2689 compression = zipfile.ZIP_LZMA
2690 zip_with_bad_crc = (
2691 b'PK\x03\x04\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
2692 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
2693 b'ile\t\x04\x05\x00]\x00\x00\x00\x04\x004\x19I'
2694 b'\xee\x8d\xe9\x17\x89:3`\tq!.8\x00PK'
2695 b'\x01\x02\x14\x03\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
2696 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00'
2697 b'\x00\x00\x00\x00 \x80\x80\x81\x00\x00\x00\x00afil'
2698 b'ePK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00'
2699 b'\x00>\x00\x00\x00\x00\x00')
2700
2701
2702 class DecryptionTests(unittest.TestCase):
2703 """Check that ZIP decryption works. Since the library does not
2704 support encryption at the moment, we use a pre-generated encrypted
2705 ZIP file."""
2706
2707 data = (
2708 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
2709 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
2710 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
2711 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
2712 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
2713 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
2714 b'\x00\x00L\x00\x00\x00\x00\x00' )
2715 data2 = (
2716 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
2717 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
2718 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
2719 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
2720 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
2721 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
2722 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
2723 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
2724
2725 plain = b'zipfile.py encryption test'
2726 plain2 = b'\x00'*512
2727
2728 def setUp(self):
2729 with open(TESTFN, "wb") as fp:
2730 fp.write(self.data)
2731 self.zip = zipfile.ZipFile(TESTFN, "r")
2732 with open(TESTFN2, "wb") as fp:
2733 fp.write(self.data2)
2734 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
2735
2736 def tearDown(self):
2737 self.zip.close()
2738 os.unlink(TESTFN)
2739 self.zip2.close()
2740 os.unlink(TESTFN2)
2741
2742 def test_no_password(self):
2743 # Reading the encrypted file without password
2744 # must generate a RunTime exception
2745 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
2746 self.assertRaises(RuntimeError, self.zip2.read, "zero")
2747
2748 def test_bad_password(self):
2749 self.zip.setpassword(b"perl")
2750 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
2751 self.zip2.setpassword(b"perl")
2752 self.assertRaises(RuntimeError, self.zip2.read, "zero")
2753
2754 @requires_zlib()
2755 def test_good_password(self):
2756 self.zip.setpassword(b"python")
2757 self.assertEqual(self.zip.read("test.txt"), self.plain)
2758 self.zip2.setpassword(b"12345")
2759 self.assertEqual(self.zip2.read("zero"), self.plain2)
2760
2761 def test_unicode_password(self):
2762 expected_msg = "pwd: expected bytes, got str"
2763
2764 with self.assertRaisesRegex(TypeError, expected_msg):
2765 self.zip.setpassword("unicode")
2766
2767 with self.assertRaisesRegex(TypeError, expected_msg):
2768 self.zip.read("test.txt", "python")
2769
2770 with self.assertRaisesRegex(TypeError, expected_msg):
2771 self.zip.open("test.txt", pwd="python")
2772
2773 with self.assertRaisesRegex(TypeError, expected_msg):
2774 self.zip.extract("test.txt", pwd="python")
2775
2776 with self.assertRaisesRegex(TypeError, expected_msg):
2777 self.zip.pwd = "python"
2778 self.zip.open("test.txt")
2779
2780 def test_seek_tell(self):
2781 self.zip.setpassword(b"python")
2782 txt = self.plain
2783 test_word = b'encryption'
2784 bloc = txt.find(test_word)
2785 bloc_len = len(test_word)
2786 with self.zip.open("test.txt", "r") as fp:
2787 fp.seek(bloc, os.SEEK_SET)
2788 self.assertEqual(fp.tell(), bloc)
2789 fp.seek(-bloc, os.SEEK_CUR)
2790 self.assertEqual(fp.tell(), 0)
2791 fp.seek(bloc, os.SEEK_CUR)
2792 self.assertEqual(fp.tell(), bloc)
2793 self.assertEqual(fp.read(bloc_len), txt[bloc:bloc+bloc_len])
2794
2795 # Make sure that the second read after seeking back beyond
2796 # _readbuffer returns the same content (ie. rewind to the start of
2797 # the file to read forward to the required position).
2798 old_read_size = fp.MIN_READ_SIZE
2799 fp.MIN_READ_SIZE = 1
2800 fp._readbuffer = b''
2801 fp._offset = 0
2802 fp.seek(0, os.SEEK_SET)
2803 self.assertEqual(fp.tell(), 0)
2804 fp.seek(bloc, os.SEEK_CUR)
2805 self.assertEqual(fp.read(bloc_len), txt[bloc:bloc+bloc_len])
2806 fp.MIN_READ_SIZE = old_read_size
2807
2808 fp.seek(0, os.SEEK_END)
2809 self.assertEqual(fp.tell(), len(txt))
2810 fp.seek(0, os.SEEK_SET)
2811 self.assertEqual(fp.tell(), 0)
2812
2813 # Read the file completely to definitely call any eof integrity
2814 # checks (crc) and make sure they still pass.
2815 fp.read()
2816
2817
2818 class AbstractTestsWithRandomBinaryFiles:
2819 @classmethod
2820 def setUpClass(cls):
2821 datacount = randint(16, 64)*1024 + randint(1, 1024)
2822 cls.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
2823 for i in range(datacount))
2824
2825 def setUp(self):
2826 # Make a source file with some lines
2827 with open(TESTFN, "wb") as fp:
2828 fp.write(self.data)
2829
2830 def tearDown(self):
2831 unlink(TESTFN)
2832 unlink(TESTFN2)
2833
2834 def make_test_archive(self, f, compression):
2835 # Create the ZIP archive
2836 with zipfile.ZipFile(f, "w", compression) as zipfp:
2837 zipfp.write(TESTFN, "another.name")
2838 zipfp.write(TESTFN, TESTFN)
2839
2840 def zip_test(self, f, compression):
2841 self.make_test_archive(f, compression)
2842
2843 # Read the ZIP archive
2844 with zipfile.ZipFile(f, "r", compression) as zipfp:
2845 testdata = zipfp.read(TESTFN)
2846 self.assertEqual(len(testdata), len(self.data))
2847 self.assertEqual(testdata, self.data)
2848 self.assertEqual(zipfp.read("another.name"), self.data)
2849
2850 def test_read(self):
2851 for f in get_files(self):
2852 self.zip_test(f, self.compression)
2853
2854 def zip_open_test(self, f, compression):
2855 self.make_test_archive(f, compression)
2856
2857 # Read the ZIP archive
2858 with zipfile.ZipFile(f, "r", compression) as zipfp:
2859 zipdata1 = []
2860 with zipfp.open(TESTFN) as zipopen1:
2861 while True:
2862 read_data = zipopen1.read(256)
2863 if not read_data:
2864 break
2865 zipdata1.append(read_data)
2866
2867 zipdata2 = []
2868 with zipfp.open("another.name") as zipopen2:
2869 while True:
2870 read_data = zipopen2.read(256)
2871 if not read_data:
2872 break
2873 zipdata2.append(read_data)
2874
2875 testdata1 = b''.join(zipdata1)
2876 self.assertEqual(len(testdata1), len(self.data))
2877 self.assertEqual(testdata1, self.data)
2878
2879 testdata2 = b''.join(zipdata2)
2880 self.assertEqual(len(testdata2), len(self.data))
2881 self.assertEqual(testdata2, self.data)
2882
2883 def test_open(self):
2884 for f in get_files(self):
2885 self.zip_open_test(f, self.compression)
2886
2887 def zip_random_open_test(self, f, compression):
2888 self.make_test_archive(f, compression)
2889
2890 # Read the ZIP archive
2891 with zipfile.ZipFile(f, "r", compression) as zipfp:
2892 zipdata1 = []
2893 with zipfp.open(TESTFN) as zipopen1:
2894 while True:
2895 read_data = zipopen1.read(randint(1, 1024))
2896 if not read_data:
2897 break
2898 zipdata1.append(read_data)
2899
2900 testdata = b''.join(zipdata1)
2901 self.assertEqual(len(testdata), len(self.data))
2902 self.assertEqual(testdata, self.data)
2903
2904 def test_random_open(self):
2905 for f in get_files(self):
2906 self.zip_random_open_test(f, self.compression)
2907
2908
2909 class StoredTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
2910 unittest.TestCase):
2911 compression = zipfile.ZIP_STORED
2912
2913 @requires_zlib()
2914 class DeflateTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
2915 unittest.TestCase):
2916 compression = zipfile.ZIP_DEFLATED
2917
2918 @requires_bz2()
2919 class Bzip2TestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
2920 unittest.TestCase):
2921 compression = zipfile.ZIP_BZIP2
2922
2923 @requires_lzma()
2924 class LzmaTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
2925 unittest.TestCase):
2926 compression = zipfile.ZIP_LZMA
2927
2928
2929 # Provide the tell() method but not seek()
2930 class Tellable:
2931 def __init__(self, fp):
2932 self.fp = fp
2933 self.offset = 0
2934
2935 def write(self, data):
2936 n = self.fp.write(data)
2937 self.offset += n
2938 return n
2939
2940 def tell(self):
2941 return self.offset
2942
2943 def flush(self):
2944 self.fp.flush()
2945
2946 class Unseekable:
2947 def __init__(self, fp):
2948 self.fp = fp
2949
2950 def write(self, data):
2951 return self.fp.write(data)
2952
2953 def flush(self):
2954 self.fp.flush()
2955
2956 class UnseekableTests(unittest.TestCase):
2957 def test_writestr(self):
2958 for wrapper in (lambda f: f), Tellable, Unseekable:
2959 with self.subTest(wrapper=wrapper):
2960 f = io.BytesIO()
2961 f.write(b'abc')
2962 bf = io.BufferedWriter(f)
2963 with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) as zipfp:
2964 zipfp.writestr('ones', b'111')
2965 zipfp.writestr('twos', b'222')
2966 self.assertEqual(f.getvalue()[:5], b'abcPK')
2967 with zipfile.ZipFile(f, mode='r') as zipf:
2968 with zipf.open('ones') as zopen:
2969 self.assertEqual(zopen.read(), b'111')
2970 with zipf.open('twos') as zopen:
2971 self.assertEqual(zopen.read(), b'222')
2972
2973 def test_write(self):
2974 for wrapper in (lambda f: f), Tellable, Unseekable:
2975 with self.subTest(wrapper=wrapper):
2976 f = io.BytesIO()
2977 f.write(b'abc')
2978 bf = io.BufferedWriter(f)
2979 with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) as zipfp:
2980 self.addCleanup(unlink, TESTFN)
2981 with open(TESTFN, 'wb') as f2:
2982 f2.write(b'111')
2983 zipfp.write(TESTFN, 'ones')
2984 with open(TESTFN, 'wb') as f2:
2985 f2.write(b'222')
2986 zipfp.write(TESTFN, 'twos')
2987 self.assertEqual(f.getvalue()[:5], b'abcPK')
2988 with zipfile.ZipFile(f, mode='r') as zipf:
2989 with zipf.open('ones') as zopen:
2990 self.assertEqual(zopen.read(), b'111')
2991 with zipf.open('twos') as zopen:
2992 self.assertEqual(zopen.read(), b'222')
2993
2994 def test_open_write(self):
2995 for wrapper in (lambda f: f), Tellable, Unseekable:
2996 with self.subTest(wrapper=wrapper):
2997 f = io.BytesIO()
2998 f.write(b'abc')
2999 bf = io.BufferedWriter(f)
3000 with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) as zipf:
3001 with zipf.open('ones', 'w') as zopen:
3002 zopen.write(b'111')
3003 with zipf.open('twos', 'w') as zopen:
3004 zopen.write(b'222')
3005 self.assertEqual(f.getvalue()[:5], b'abcPK')
3006 with zipfile.ZipFile(f) as zipf:
3007 self.assertEqual(zipf.read('ones'), b'111')
3008 self.assertEqual(zipf.read('twos'), b'222')
3009
3010
3011 @requires_zlib()
3012 class TestsWithMultipleOpens(unittest.TestCase):
3013 @classmethod
3014 def setUpClass(cls):
3015 cls.data1 = b'111' + randbytes(10000)
3016 cls.data2 = b'222' + randbytes(10000)
3017
3018 def make_test_archive(self, f):
3019 # Create the ZIP archive
3020 with zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as zipfp:
3021 zipfp.writestr('ones', self.data1)
3022 zipfp.writestr('twos', self.data2)
3023
3024 def test_same_file(self):
3025 # Verify that (when the ZipFile is in control of creating file objects)
3026 # multiple open() calls can be made without interfering with each other.
3027 for f in get_files(self):
3028 self.make_test_archive(f)
3029 with zipfile.ZipFile(f, mode="r") as zipf:
3030 with zipf.open('ones') as zopen1, zipf.open('ones') as zopen2:
3031 data1 = zopen1.read(500)
3032 data2 = zopen2.read(500)
3033 data1 += zopen1.read()
3034 data2 += zopen2.read()
3035 self.assertEqual(data1, data2)
3036 self.assertEqual(data1, self.data1)
3037
3038 def test_different_file(self):
3039 # Verify that (when the ZipFile is in control of creating file objects)
3040 # multiple open() calls can be made without interfering with each other.
3041 for f in get_files(self):
3042 self.make_test_archive(f)
3043 with zipfile.ZipFile(f, mode="r") as zipf:
3044 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
3045 data1 = zopen1.read(500)
3046 data2 = zopen2.read(500)
3047 data1 += zopen1.read()
3048 data2 += zopen2.read()
3049 self.assertEqual(data1, self.data1)
3050 self.assertEqual(data2, self.data2)
3051
3052 def test_interleaved(self):
3053 # Verify that (when the ZipFile is in control of creating file objects)
3054 # multiple open() calls can be made without interfering with each other.
3055 for f in get_files(self):
3056 self.make_test_archive(f)
3057 with zipfile.ZipFile(f, mode="r") as zipf:
3058 with zipf.open('ones') as zopen1:
3059 data1 = zopen1.read(500)
3060 with zipf.open('twos') as zopen2:
3061 data2 = zopen2.read(500)
3062 data1 += zopen1.read()
3063 data2 += zopen2.read()
3064 self.assertEqual(data1, self.data1)
3065 self.assertEqual(data2, self.data2)
3066
3067 def test_read_after_close(self):
3068 for f in get_files(self):
3069 self.make_test_archive(f)
3070 with contextlib.ExitStack() as stack:
3071 with zipfile.ZipFile(f, 'r') as zipf:
3072 zopen1 = stack.enter_context(zipf.open('ones'))
3073 zopen2 = stack.enter_context(zipf.open('twos'))
3074 data1 = zopen1.read(500)
3075 data2 = zopen2.read(500)
3076 data1 += zopen1.read()
3077 data2 += zopen2.read()
3078 self.assertEqual(data1, self.data1)
3079 self.assertEqual(data2, self.data2)
3080
3081 def test_read_after_write(self):
3082 for f in get_files(self):
3083 with zipfile.ZipFile(f, 'w', zipfile.ZIP_DEFLATED) as zipf:
3084 zipf.writestr('ones', self.data1)
3085 zipf.writestr('twos', self.data2)
3086 with zipf.open('ones') as zopen1:
3087 data1 = zopen1.read(500)
3088 self.assertEqual(data1, self.data1[:500])
3089 with zipfile.ZipFile(f, 'r') as zipf:
3090 data1 = zipf.read('ones')
3091 data2 = zipf.read('twos')
3092 self.assertEqual(data1, self.data1)
3093 self.assertEqual(data2, self.data2)
3094
3095 def test_write_after_read(self):
3096 for f in get_files(self):
3097 with zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as zipf:
3098 zipf.writestr('ones', self.data1)
3099 with zipf.open('ones') as zopen1:
3100 zopen1.read(500)
3101 zipf.writestr('twos', self.data2)
3102 with zipfile.ZipFile(f, 'r') as zipf:
3103 data1 = zipf.read('ones')
3104 data2 = zipf.read('twos')
3105 self.assertEqual(data1, self.data1)
3106 self.assertEqual(data2, self.data2)
3107
3108 def test_many_opens(self):
3109 # Verify that read() and open() promptly close the file descriptor,
3110 # and don't rely on the garbage collector to free resources.
3111 startcount = fd_count()
3112 self.make_test_archive(TESTFN2)
3113 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
3114 for x in range(100):
3115 zipf.read('ones')
3116 with zipf.open('ones') as zopen1:
3117 pass
3118 self.assertEqual(startcount, fd_count())
3119
3120 def test_write_while_reading(self):
3121 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_DEFLATED) as zipf:
3122 zipf.writestr('ones', self.data1)
3123 with zipfile.ZipFile(TESTFN2, 'a', zipfile.ZIP_DEFLATED) as zipf:
3124 with zipf.open('ones', 'r') as r1:
3125 data1 = r1.read(500)
3126 with zipf.open('twos', 'w') as w1:
3127 w1.write(self.data2)
3128 data1 += r1.read()
3129 self.assertEqual(data1, self.data1)
3130 with zipfile.ZipFile(TESTFN2) as zipf:
3131 self.assertEqual(zipf.read('twos'), self.data2)
3132
3133 def tearDown(self):
3134 unlink(TESTFN2)
3135
3136
3137 class TestWithDirectory(unittest.TestCase):
3138 def setUp(self):
3139 os.mkdir(TESTFN2)
3140
3141 def test_extract_dir(self):
3142 with zipfile.ZipFile(findfile("zipdir.zip", subdir="archivetestdata")) as zipf:
3143 zipf.extractall(TESTFN2)
3144 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
3145 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
3146 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
3147
3148 def test_bug_6050(self):
3149 # Extraction should succeed if directories already exist
3150 os.mkdir(os.path.join(TESTFN2, "a"))
3151 self.test_extract_dir()
3152
3153 def test_extract_dir_backslash(self):
3154 zfname = findfile("zipdir_backslash.zip", subdir="archivetestdata")
3155 with zipfile.ZipFile(zfname) as zipf:
3156 zipf.extractall(TESTFN2)
3157 if os.name == 'nt':
3158 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
3159 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
3160 self.assertTrue(os.path.isfile(os.path.join(TESTFN2, "a", "b", "c")))
3161 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "d")))
3162 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "d", "e")))
3163 else:
3164 self.assertTrue(os.path.isfile(os.path.join(TESTFN2, "a\\b\\c")))
3165 self.assertTrue(os.path.isfile(os.path.join(TESTFN2, "d\\e\\")))
3166 self.assertFalse(os.path.exists(os.path.join(TESTFN2, "a")))
3167 self.assertFalse(os.path.exists(os.path.join(TESTFN2, "d")))
3168
3169 def test_write_dir(self):
3170 dirpath = os.path.join(TESTFN2, "x")
3171 os.mkdir(dirpath)
3172 mode = os.stat(dirpath).st_mode & 0xFFFF
3173 with zipfile.ZipFile(TESTFN, "w") as zipf:
3174 zipf.write(dirpath)
3175 zinfo = zipf.filelist[0]
3176 self.assertTrue(zinfo.filename.endswith("/x/"))
3177 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
3178 zipf.write(dirpath, "y")
3179 zinfo = zipf.filelist[1]
3180 self.assertTrue(zinfo.filename, "y/")
3181 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
3182 with zipfile.ZipFile(TESTFN, "r") as zipf:
3183 zinfo = zipf.filelist[0]
3184 self.assertTrue(zinfo.filename.endswith("/x/"))
3185 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
3186 zinfo = zipf.filelist[1]
3187 self.assertTrue(zinfo.filename, "y/")
3188 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
3189 target = os.path.join(TESTFN2, "target")
3190 os.mkdir(target)
3191 zipf.extractall(target)
3192 self.assertTrue(os.path.isdir(os.path.join(target, "y")))
3193 self.assertEqual(len(os.listdir(target)), 2)
3194
3195 def test_writestr_dir(self):
3196 os.mkdir(os.path.join(TESTFN2, "x"))
3197 with zipfile.ZipFile(TESTFN, "w") as zipf:
3198 zipf.writestr("x/", b'')
3199 zinfo = zipf.filelist[0]
3200 self.assertEqual(zinfo.filename, "x/")
3201 self.assertEqual(zinfo.external_attr, (0o40775 << 16) | 0x10)
3202 with zipfile.ZipFile(TESTFN, "r") as zipf:
3203 zinfo = zipf.filelist[0]
3204 self.assertTrue(zinfo.filename.endswith("x/"))
3205 self.assertEqual(zinfo.external_attr, (0o40775 << 16) | 0x10)
3206 target = os.path.join(TESTFN2, "target")
3207 os.mkdir(target)
3208 zipf.extractall(target)
3209 self.assertTrue(os.path.isdir(os.path.join(target, "x")))
3210 self.assertEqual(os.listdir(target), ["x"])
3211
3212 def test_mkdir(self):
3213 with zipfile.ZipFile(TESTFN, "w") as zf:
3214 zf.mkdir("directory")
3215 zinfo = zf.filelist[0]
3216 self.assertEqual(zinfo.filename, "directory/")
3217 self.assertEqual(zinfo.external_attr, (0o40777 << 16) | 0x10)
3218
3219 zf.mkdir("directory2/")
3220 zinfo = zf.filelist[1]
3221 self.assertEqual(zinfo.filename, "directory2/")
3222 self.assertEqual(zinfo.external_attr, (0o40777 << 16) | 0x10)
3223
3224 zf.mkdir("directory3", mode=0o777)
3225 zinfo = zf.filelist[2]
3226 self.assertEqual(zinfo.filename, "directory3/")
3227 self.assertEqual(zinfo.external_attr, (0o40777 << 16) | 0x10)
3228
3229 old_zinfo = zipfile.ZipInfo("directory4/")
3230 old_zinfo.external_attr = (0o40777 << 16) | 0x10
3231 old_zinfo.CRC = 0
3232 old_zinfo.file_size = 0
3233 old_zinfo.compress_size = 0
3234 zf.mkdir(old_zinfo)
3235 new_zinfo = zf.filelist[3]
3236 self.assertEqual(old_zinfo.filename, "directory4/")
3237 self.assertEqual(old_zinfo.external_attr, new_zinfo.external_attr)
3238
3239 target = os.path.join(TESTFN2, "target")
3240 os.mkdir(target)
3241 zf.extractall(target)
3242 self.assertEqual(set(os.listdir(target)), {"directory", "directory2", "directory3", "directory4"})
3243
3244 def test_create_directory_with_write(self):
3245 with zipfile.ZipFile(TESTFN, "w") as zf:
3246 zf.writestr(zipfile.ZipInfo('directory/'), '')
3247
3248 zinfo = zf.filelist[0]
3249 self.assertEqual(zinfo.filename, "directory/")
3250
3251 directory = os.path.join(TESTFN2, "directory2")
3252 os.mkdir(directory)
3253 mode = os.stat(directory).st_mode & 0xFFFF
3254 zf.write(directory, arcname="directory2/")
3255 zinfo = zf.filelist[1]
3256 self.assertEqual(zinfo.filename, "directory2/")
3257 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
3258
3259 target = os.path.join(TESTFN2, "target")
3260 os.mkdir(target)
3261 zf.extractall(target)
3262
3263 self.assertEqual(set(os.listdir(target)), {"directory", "directory2"})
3264
3265 def test_root_folder_in_zipfile(self):
3266 """
3267 gh-112795: Some tools or self constructed codes will add '/' folder to
3268 the zip file, this is a strange behavior, but we should support it.
3269 """
3270 in_memory_file = io.BytesIO()
3271 zf = zipfile.ZipFile(in_memory_file, "w")
3272 zf.mkdir('/')
3273 zf.writestr('./a.txt', 'aaa')
3274 zf.extractall(TESTFN2)
3275
3276 def tearDown(self):
3277 rmtree(TESTFN2)
3278 if os.path.exists(TESTFN):
3279 unlink(TESTFN)
3280
3281
3282 class ZipInfoTests(unittest.TestCase):
3283 def test_from_file(self):
3284 zi = zipfile.ZipInfo.from_file(__file__)
3285 self.assertEqual(posixpath.basename(zi.filename), 'test_core.py')
3286 self.assertFalse(zi.is_dir())
3287 self.assertEqual(zi.file_size, os.path.getsize(__file__))
3288
3289 def test_from_file_pathlike(self):
3290 zi = zipfile.ZipInfo.from_file(FakePath(__file__))
3291 self.assertEqual(posixpath.basename(zi.filename), 'test_core.py')
3292 self.assertFalse(zi.is_dir())
3293 self.assertEqual(zi.file_size, os.path.getsize(__file__))
3294
3295 def test_from_file_bytes(self):
3296 zi = zipfile.ZipInfo.from_file(os.fsencode(__file__), 'test')
3297 self.assertEqual(posixpath.basename(zi.filename), 'test')
3298 self.assertFalse(zi.is_dir())
3299 self.assertEqual(zi.file_size, os.path.getsize(__file__))
3300
3301 def test_from_file_fileno(self):
3302 with open(__file__, 'rb') as f:
3303 zi = zipfile.ZipInfo.from_file(f.fileno(), 'test')
3304 self.assertEqual(posixpath.basename(zi.filename), 'test')
3305 self.assertFalse(zi.is_dir())
3306 self.assertEqual(zi.file_size, os.path.getsize(__file__))
3307
3308 def test_from_dir(self):
3309 dirpath = os.path.dirname(os.path.abspath(__file__))
3310 zi = zipfile.ZipInfo.from_file(dirpath, 'stdlib_tests')
3311 self.assertEqual(zi.filename, 'stdlib_tests/')
3312 self.assertTrue(zi.is_dir())
3313 self.assertEqual(zi.compress_type, zipfile.ZIP_STORED)
3314 self.assertEqual(zi.file_size, 0)
3315
3316 def test_compresslevel_property(self):
3317 zinfo = zipfile.ZipInfo("xxx")
3318 self.assertFalse(zinfo._compresslevel)
3319 self.assertFalse(zinfo.compress_level)
3320 zinfo._compresslevel = 99 # test the legacy @property.setter
3321 self.assertEqual(zinfo.compress_level, 99)
3322 self.assertEqual(zinfo._compresslevel, 99)
3323 zinfo.compress_level = 8
3324 self.assertEqual(zinfo.compress_level, 8)
3325 self.assertEqual(zinfo._compresslevel, 8)
3326
3327
3328 class CommandLineTest(unittest.TestCase):
3329
3330 def zipfilecmd(self, *args, **kwargs):
3331 rc, out, err = script_helper.assert_python_ok('-m', 'zipfile', *args,
3332 **kwargs)
3333 return out.replace(os.linesep.encode(), b'\n')
3334
3335 def zipfilecmd_failure(self, *args):
3336 return script_helper.assert_python_failure('-m', 'zipfile', *args)
3337
3338 def test_bad_use(self):
3339 rc, out, err = self.zipfilecmd_failure()
3340 self.assertEqual(out, b'')
3341 self.assertIn(b'usage', err.lower())
3342 self.assertIn(b'error', err.lower())
3343 self.assertIn(b'required', err.lower())
3344 rc, out, err = self.zipfilecmd_failure('-l', '')
3345 self.assertEqual(out, b'')
3346 self.assertNotEqual(err.strip(), b'')
3347
3348 def test_test_command(self):
3349 zip_name = findfile('zipdir.zip', subdir='archivetestdata')
3350 for opt in '-t', '--test':
3351 out = self.zipfilecmd(opt, zip_name)
3352 self.assertEqual(out.rstrip(), b'Done testing')
3353 zip_name = findfile('testtar.tar')
3354 rc, out, err = self.zipfilecmd_failure('-t', zip_name)
3355 self.assertEqual(out, b'')
3356
3357 def test_list_command(self):
3358 zip_name = findfile('zipdir.zip', subdir='archivetestdata')
3359 t = io.StringIO()
3360 with zipfile.ZipFile(zip_name, 'r') as tf:
3361 tf.printdir(t)
3362 expected = t.getvalue().encode('ascii', 'backslashreplace')
3363 for opt in '-l', '--list':
3364 out = self.zipfilecmd(opt, zip_name,
3365 PYTHONIOENCODING='ascii:backslashreplace')
3366 self.assertEqual(out, expected)
3367
3368 @requires_zlib()
3369 def test_create_command(self):
3370 self.addCleanup(unlink, TESTFN)
3371 with open(TESTFN, 'w', encoding='utf-8') as f:
3372 f.write('test 1')
3373 os.mkdir(TESTFNDIR)
3374 self.addCleanup(rmtree, TESTFNDIR)
3375 with open(os.path.join(TESTFNDIR, 'file.txt'), 'w', encoding='utf-8') as f:
3376 f.write('test 2')
3377 files = [TESTFN, TESTFNDIR]
3378 namelist = [TESTFN, TESTFNDIR + '/', TESTFNDIR + '/file.txt']
3379 for opt in '-c', '--create':
3380 try:
3381 out = self.zipfilecmd(opt, TESTFN2, *files)
3382 self.assertEqual(out, b'')
3383 with zipfile.ZipFile(TESTFN2) as zf:
3384 self.assertEqual(zf.namelist(), namelist)
3385 self.assertEqual(zf.read(namelist[0]), b'test 1')
3386 self.assertEqual(zf.read(namelist[2]), b'test 2')
3387 finally:
3388 unlink(TESTFN2)
3389
3390 def test_extract_command(self):
3391 zip_name = findfile('zipdir.zip', subdir='archivetestdata')
3392 for opt in '-e', '--extract':
3393 with temp_dir() as extdir:
3394 out = self.zipfilecmd(opt, zip_name, extdir)
3395 self.assertEqual(out, b'')
3396 with zipfile.ZipFile(zip_name) as zf:
3397 for zi in zf.infolist():
3398 path = os.path.join(extdir,
3399 zi.filename.replace('/', os.sep))
3400 if zi.is_dir():
3401 self.assertTrue(os.path.isdir(path))
3402 else:
3403 self.assertTrue(os.path.isfile(path))
3404 with open(path, 'rb') as f:
3405 self.assertEqual(f.read(), zf.read(zi))
3406
3407
3408 class TestExecutablePrependedZip(unittest.TestCase):
3409 """Test our ability to open zip files with an executable prepended."""
3410
3411 def setUp(self):
3412 self.exe_zip = findfile('exe_with_zip', subdir='archivetestdata')
3413 self.exe_zip64 = findfile('exe_with_z64', subdir='archivetestdata')
3414
3415 def _test_zip_works(self, name):
3416 # bpo28494 sanity check: ensure is_zipfile works on these.
3417 self.assertTrue(zipfile.is_zipfile(name),
3418 f'is_zipfile failed on {name}')
3419 # Ensure we can operate on these via ZipFile.
3420 with zipfile.ZipFile(name) as zipfp:
3421 for n in zipfp.namelist():
3422 data = zipfp.read(n)
3423 self.assertIn(b'FAVORITE_NUMBER', data)
3424
3425 def test_read_zip_with_exe_prepended(self):
3426 self._test_zip_works(self.exe_zip)
3427
3428 def test_read_zip64_with_exe_prepended(self):
3429 self._test_zip_works(self.exe_zip64)
3430
3431 @unittest.skipUnless(sys.executable, 'sys.executable required.')
3432 @unittest.skipUnless(os.access('/bin/bash', os.X_OK),
3433 'Test relies on #!/bin/bash working.')
3434 @requires_subprocess()
3435 def test_execute_zip2(self):
3436 output = subprocess.check_output([self.exe_zip, sys.executable])
3437 self.assertIn(b'number in executable: 5', output)
3438
3439 @unittest.skipUnless(sys.executable, 'sys.executable required.')
3440 @unittest.skipUnless(os.access('/bin/bash', os.X_OK),
3441 'Test relies on #!/bin/bash working.')
3442 @requires_subprocess()
3443 def test_execute_zip64(self):
3444 output = subprocess.check_output([self.exe_zip64, sys.executable])
3445 self.assertIn(b'number in executable: 5', output)
3446
3447
3448 class EncodedMetadataTests(unittest.TestCase):
3449 file_names = ['\u4e00', '\u4e8c', '\u4e09'] # Han 'one', 'two', 'three'
3450 file_content = [
3451 "This is pure ASCII.\n".encode('ascii'),
3452 # This is modern Japanese. (UTF-8)
3453 "\u3053\u308c\u306f\u73fe\u4ee3\u7684\u65e5\u672c\u8a9e\u3067\u3059\u3002\n".encode('utf-8'),
3454 # This is obsolete Japanese. (Shift JIS)
3455 "\u3053\u308c\u306f\u53e4\u3044\u65e5\u672c\u8a9e\u3067\u3059\u3002\n".encode('shift_jis'),
3456 ]
3457
3458 def setUp(self):
3459 self.addCleanup(unlink, TESTFN)
3460 # Create .zip of 3 members with Han names encoded in Shift JIS.
3461 # Each name is 1 Han character encoding to 2 bytes in Shift JIS.
3462 # The ASCII names are arbitrary as long as they are length 2 and
3463 # not otherwise contained in the zip file.
3464 # Data elements are encoded bytes (ascii, utf-8, shift_jis).
3465 placeholders = ["n1", "n2"] + self.file_names[2:]
3466 with zipfile.ZipFile(TESTFN, mode="w") as tf:
3467 for temp, content in zip(placeholders, self.file_content):
3468 tf.writestr(temp, content, zipfile.ZIP_STORED)
3469 # Hack in the Shift JIS names with flag bit 11 (UTF-8) unset.
3470 with open(TESTFN, "rb") as tf:
3471 data = tf.read()
3472 for name, temp in zip(self.file_names, placeholders[:2]):
3473 data = data.replace(temp.encode('ascii'),
3474 name.encode('shift_jis'))
3475 with open(TESTFN, "wb") as tf:
3476 tf.write(data)
3477
3478 def _test_read(self, zipfp, expected_names, expected_content):
3479 # Check the namelist
3480 names = zipfp.namelist()
3481 self.assertEqual(sorted(names), sorted(expected_names))
3482
3483 # Check infolist
3484 infos = zipfp.infolist()
3485 names = [zi.filename for zi in infos]
3486 self.assertEqual(sorted(names), sorted(expected_names))
3487
3488 # check getinfo
3489 for name, content in zip(expected_names, expected_content):
3490 info = zipfp.getinfo(name)
3491 self.assertEqual(info.filename, name)
3492 self.assertEqual(info.file_size, len(content))
3493 self.assertEqual(zipfp.read(name), content)
3494
3495 def test_read_with_metadata_encoding(self):
3496 # Read the ZIP archive with correct metadata_encoding
3497 with zipfile.ZipFile(TESTFN, "r", metadata_encoding='shift_jis') as zipfp:
3498 self._test_read(zipfp, self.file_names, self.file_content)
3499
3500 def test_read_without_metadata_encoding(self):
3501 # Read the ZIP archive without metadata_encoding
3502 expected_names = [name.encode('shift_jis').decode('cp437')
3503 for name in self.file_names[:2]] + self.file_names[2:]
3504 with zipfile.ZipFile(TESTFN, "r") as zipfp:
3505 self._test_read(zipfp, expected_names, self.file_content)
3506
3507 def test_read_with_incorrect_metadata_encoding(self):
3508 # Read the ZIP archive with incorrect metadata_encoding
3509 expected_names = [name.encode('shift_jis').decode('koi8-u')
3510 for name in self.file_names[:2]] + self.file_names[2:]
3511 with zipfile.ZipFile(TESTFN, "r", metadata_encoding='koi8-u') as zipfp:
3512 self._test_read(zipfp, expected_names, self.file_content)
3513
3514 def test_read_with_unsuitable_metadata_encoding(self):
3515 # Read the ZIP archive with metadata_encoding unsuitable for
3516 # decoding metadata
3517 with self.assertRaises(UnicodeDecodeError):
3518 zipfile.ZipFile(TESTFN, "r", metadata_encoding='ascii')
3519 with self.assertRaises(UnicodeDecodeError):
3520 zipfile.ZipFile(TESTFN, "r", metadata_encoding='utf-8')
3521
3522 def test_read_after_append(self):
3523 newname = '\u56db' # Han 'four'
3524 expected_names = [name.encode('shift_jis').decode('cp437')
3525 for name in self.file_names[:2]] + self.file_names[2:]
3526 expected_names.append(newname)
3527 expected_content = (*self.file_content, b"newcontent")
3528
3529 with zipfile.ZipFile(TESTFN, "a") as zipfp:
3530 zipfp.writestr(newname, "newcontent")
3531 self.assertEqual(sorted(zipfp.namelist()), sorted(expected_names))
3532
3533 with zipfile.ZipFile(TESTFN, "r") as zipfp:
3534 self._test_read(zipfp, expected_names, expected_content)
3535
3536 with zipfile.ZipFile(TESTFN, "r", metadata_encoding='shift_jis') as zipfp:
3537 self.assertEqual(sorted(zipfp.namelist()), sorted(expected_names))
3538 for i, (name, content) in enumerate(zip(expected_names, expected_content)):
3539 info = zipfp.getinfo(name)
3540 self.assertEqual(info.filename, name)
3541 self.assertEqual(info.file_size, len(content))
3542 if i < 2:
3543 with self.assertRaises(zipfile.BadZipFile):
3544 zipfp.read(name)
3545 else:
3546 self.assertEqual(zipfp.read(name), content)
3547
3548 def test_write_with_metadata_encoding(self):
3549 ZF = zipfile.ZipFile
3550 for mode in ("w", "x", "a"):
3551 with self.assertRaisesRegex(ValueError,
3552 "^metadata_encoding is only"):
3553 ZF("nonesuch.zip", mode, metadata_encoding="shift_jis")
3554
3555 def test_cli_with_metadata_encoding(self):
3556 errmsg = "Non-conforming encodings not supported with -c."
3557 args = ["--metadata-encoding=shift_jis", "-c", "nonesuch", "nonesuch"]
3558 with captured_stdout() as stdout:
3559 with captured_stderr() as stderr:
3560 self.assertRaises(SystemExit, zipfile.main, args)
3561 self.assertEqual(stdout.getvalue(), "")
3562 self.assertIn(errmsg, stderr.getvalue())
3563
3564 with captured_stdout() as stdout:
3565 zipfile.main(["--metadata-encoding=shift_jis", "-t", TESTFN])
3566 listing = stdout.getvalue()
3567
3568 with captured_stdout() as stdout:
3569 zipfile.main(["--metadata-encoding=shift_jis", "-l", TESTFN])
3570 listing = stdout.getvalue()
3571 for name in self.file_names:
3572 self.assertIn(name, listing)
3573
3574 def test_cli_with_metadata_encoding_extract(self):
3575 os.mkdir(TESTFN2)
3576 self.addCleanup(rmtree, TESTFN2)
3577 # Depending on locale, extracted file names can be not encodable
3578 # with the filesystem encoding.
3579 for fn in self.file_names:
3580 try:
3581 os.stat(os.path.join(TESTFN2, fn))
3582 except OSError:
3583 pass
3584 except UnicodeEncodeError:
3585 self.skipTest(f'cannot encode file name {fn!a}')
3586
3587 zipfile.main(["--metadata-encoding=shift_jis", "-e", TESTFN, TESTFN2])
3588 listing = os.listdir(TESTFN2)
3589 for name in self.file_names:
3590 self.assertIn(name, listing)
3591
3592
3593 class StripExtraTests(unittest.TestCase):
3594 # Note: all of the "z" characters are technically invalid, but up
3595 # to 3 bytes at the end of the extra will be passed through as they
3596 # are too short to encode a valid extra.
3597
3598 ZIP64_EXTRA = 1
3599
3600 def test_no_data(self):
3601 s = struct.Struct("<HH")
3602 a = s.pack(self.ZIP64_EXTRA, 0)
3603 b = s.pack(2, 0)
3604 c = s.pack(3, 0)
3605
3606 self.assertEqual(b'', zipfile._Extra.strip(a, (self.ZIP64_EXTRA,)))
3607 self.assertEqual(b, zipfile._Extra.strip(b, (self.ZIP64_EXTRA,)))
3608 self.assertEqual(
3609 b+b"z", zipfile._Extra.strip(b+b"z", (self.ZIP64_EXTRA,)))
3610
3611 self.assertEqual(b+c, zipfile._Extra.strip(a+b+c, (self.ZIP64_EXTRA,)))
3612 self.assertEqual(b+c, zipfile._Extra.strip(b+a+c, (self.ZIP64_EXTRA,)))
3613 self.assertEqual(b+c, zipfile._Extra.strip(b+c+a, (self.ZIP64_EXTRA,)))
3614
3615 def test_with_data(self):
3616 s = struct.Struct("<HH")
3617 a = s.pack(self.ZIP64_EXTRA, 1) + b"a"
3618 b = s.pack(2, 2) + b"bb"
3619 c = s.pack(3, 3) + b"ccc"
3620
3621 self.assertEqual(b"", zipfile._Extra.strip(a, (self.ZIP64_EXTRA,)))
3622 self.assertEqual(b, zipfile._Extra.strip(b, (self.ZIP64_EXTRA,)))
3623 self.assertEqual(
3624 b+b"z", zipfile._Extra.strip(b+b"z", (self.ZIP64_EXTRA,)))
3625
3626 self.assertEqual(b+c, zipfile._Extra.strip(a+b+c, (self.ZIP64_EXTRA,)))
3627 self.assertEqual(b+c, zipfile._Extra.strip(b+a+c, (self.ZIP64_EXTRA,)))
3628 self.assertEqual(b+c, zipfile._Extra.strip(b+c+a, (self.ZIP64_EXTRA,)))
3629
3630 def test_multiples(self):
3631 s = struct.Struct("<HH")
3632 a = s.pack(self.ZIP64_EXTRA, 1) + b"a"
3633 b = s.pack(2, 2) + b"bb"
3634
3635 self.assertEqual(b"", zipfile._Extra.strip(a+a, (self.ZIP64_EXTRA,)))
3636 self.assertEqual(b"", zipfile._Extra.strip(a+a+a, (self.ZIP64_EXTRA,)))
3637 self.assertEqual(
3638 b"z", zipfile._Extra.strip(a+a+b"z", (self.ZIP64_EXTRA,)))
3639 self.assertEqual(
3640 b+b"z", zipfile._Extra.strip(a+a+b+b"z", (self.ZIP64_EXTRA,)))
3641
3642 self.assertEqual(b, zipfile._Extra.strip(a+a+b, (self.ZIP64_EXTRA,)))
3643 self.assertEqual(b, zipfile._Extra.strip(a+b+a, (self.ZIP64_EXTRA,)))
3644 self.assertEqual(b, zipfile._Extra.strip(b+a+a, (self.ZIP64_EXTRA,)))
3645
3646 def test_too_short(self):
3647 self.assertEqual(b"", zipfile._Extra.strip(b"", (self.ZIP64_EXTRA,)))
3648 self.assertEqual(b"z", zipfile._Extra.strip(b"z", (self.ZIP64_EXTRA,)))
3649 self.assertEqual(
3650 b"zz", zipfile._Extra.strip(b"zz", (self.ZIP64_EXTRA,)))
3651 self.assertEqual(
3652 b"zzz", zipfile._Extra.strip(b"zzz", (self.ZIP64_EXTRA,)))
3653
3654
3655 class StatIO(_pyio.BytesIO):
3656 """Buffer which remembers the number of bytes that were read."""
3657
3658 def __init__(self):
3659 super().__init__()
3660 self.bytes_read = 0
3661
3662 def read(self, size=-1):
3663 bs = super().read(size)
3664 self.bytes_read += len(bs)
3665 return bs
3666
3667
3668 class StoredZipExtFileRandomReadTest(unittest.TestCase):
3669 """Tests whether an uncompressed, unencrypted zip entry can be randomly
3670 seek and read without reading redundant bytes."""
3671 def test_stored_seek_and_read(self):
3672
3673 sio = StatIO()
3674 # 20000 bytes
3675 txt = b'0123456789' * 2000
3676
3677 # The seek length must be greater than ZipExtFile.MIN_READ_SIZE
3678 # as `ZipExtFile._read2()` reads in blocks of this size and we
3679 # need to seek out of the buffered data
3680 read_buffer_size = zipfile.ZipExtFile.MIN_READ_SIZE
3681 self.assertGreaterEqual(10002, read_buffer_size) # for forward seek test
3682 self.assertGreaterEqual(5003, read_buffer_size) # for backward seek test
3683 # The read length must be less than MIN_READ_SIZE, since we assume that
3684 # only 1 block is read in the test.
3685 read_length = 100
3686 self.assertGreaterEqual(read_buffer_size, read_length) # for read() calls
3687
3688 with zipfile.ZipFile(sio, "w", compression=zipfile.ZIP_STORED) as zipf:
3689 zipf.writestr("foo.txt", txt)
3690
3691 # check random seek and read on a file
3692 with zipfile.ZipFile(sio, "r") as zipf:
3693 with zipf.open("foo.txt", "r") as fp:
3694 # Test this optimized read hasn't rewound and read from the
3695 # start of the file (as in the case of the unoptimized path)
3696
3697 # forward seek
3698 old_count = sio.bytes_read
3699 forward_seek_len = 10002
3700 current_pos = 0
3701 fp.seek(forward_seek_len, os.SEEK_CUR)
3702 current_pos += forward_seek_len
3703 self.assertEqual(fp.tell(), current_pos)
3704 self.assertEqual(fp._left, fp._compress_left)
3705 arr = fp.read(read_length)
3706 current_pos += read_length
3707 self.assertEqual(fp.tell(), current_pos)
3708 self.assertEqual(arr, txt[current_pos - read_length:current_pos])
3709 self.assertEqual(fp._left, fp._compress_left)
3710 read_count = sio.bytes_read - old_count
3711 self.assertLessEqual(read_count, read_buffer_size)
3712
3713 # backward seek
3714 old_count = sio.bytes_read
3715 backward_seek_len = 5003
3716 fp.seek(-backward_seek_len, os.SEEK_CUR)
3717 current_pos -= backward_seek_len
3718 self.assertEqual(fp.tell(), current_pos)
3719 self.assertEqual(fp._left, fp._compress_left)
3720 arr = fp.read(read_length)
3721 current_pos += read_length
3722 self.assertEqual(fp.tell(), current_pos)
3723 self.assertEqual(arr, txt[current_pos - read_length:current_pos])
3724 self.assertEqual(fp._left, fp._compress_left)
3725 read_count = sio.bytes_read - old_count
3726 self.assertLessEqual(read_count, read_buffer_size)
3727
3728 # eof flags test
3729 fp.seek(0, os.SEEK_END)
3730 fp.seek(12345, os.SEEK_SET)
3731 current_pos = 12345
3732 arr = fp.read(read_length)
3733 current_pos += read_length
3734 self.assertEqual(arr, txt[current_pos - read_length:current_pos])
3735
3736
3737 if __name__ == "__main__":
3738 unittest.main()