Debian Codegraph @

tests/test/test_zipfile/test_core.py

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