Debian Codegraph @

Lib/test/test_zipfile/test_core.py

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