Debian Codegraph @

lib-python/3/test/test_zipfile.py

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