Debian Codegraph @

tests/test/test_zipfile/test_core.py

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