blob: 76e2f647c607bfab7ab0ffa45b08af5f37f3713d [file] [log] [blame]
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001import contextlib
Jason R. Coombsb2758ff2019-05-08 09:45:06 -04002import importlib.util
Ezio Melotti74c96ec2009-07-08 22:24:06 +00003import io
4import os
Serhiy Storchaka8606e952017-03-08 14:37:51 +02005import pathlib
Serhiy Storchaka503f9082016-02-08 00:02:25 +02006import posixpath
Ezio Melotti74c96ec2009-07-08 22:24:06 +00007import struct
Miss Islington (bot)74b02912019-09-10 15:57:54 -07008import subprocess
9import sys
Jason R. Coombsb2758ff2019-05-08 09:45:06 -040010import time
Ezio Melotti74c96ec2009-07-08 22:24:06 +000011import unittest
Miss Islington (bot)717cc612019-09-12 07:33:53 -070012import unittest.mock as mock
Jason R. Coombsb2758ff2019-05-08 09:45:06 -040013import zipfile
Ezio Melotti74c96ec2009-07-08 22:24:06 +000014
Tim Petersa45cacf2004-08-20 03:47:14 +000015
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000016from tempfile import TemporaryFile
Serhiy Storchakafa6bc292013-07-22 21:00:11 +030017from random import randint, random, getrandbits
Tim Petersa19a1682001-03-29 04:36:09 +000018
Serhiy Storchaka61c4c442016-10-23 13:07:59 +030019from test.support import script_helper
Serhiy Storchaka8606e952017-03-08 14:37:51 +020020from test.support import (TESTFN, findfile, unlink, rmtree, temp_dir, temp_cwd,
Serhiy Storchakac5b75db2013-01-29 20:14:08 +020021 requires_zlib, requires_bz2, requires_lzma,
Victor Stinnerd6debb22017-03-27 16:05:26 +020022 captured_stdout)
Guido van Rossum368f04a2000-04-10 13:23:04 +000023
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000024TESTFN2 = TESTFN + "2"
Martin v. Löwis59e47792009-01-24 14:10:07 +000025TESTFNDIR = TESTFN + "d"
Guido van Rossumb5a755e2007-07-18 18:15:48 +000026FIXEDTEST_SIZE = 1000
Georg Brandl5ba11de2011-01-01 10:09:32 +000027DATAFILES_DIR = 'zipfile_datafiles'
Guido van Rossum368f04a2000-04-10 13:23:04 +000028
Christian Heimes790c8232008-01-07 21:14:23 +000029SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'),
30 ('ziptest2dir/_ziptest2', 'qawsedrftg'),
Gregory P. Smithb47acbf2013-02-01 11:22:43 -080031 ('ziptest2dir/ziptest3dir/_ziptest3', 'azsxdcfvgb'),
Christian Heimes790c8232008-01-07 21:14:23 +000032 ('ziptest2dir/ziptest3dir/ziptest4dir/_ziptest3', '6y7u8i9o0p')]
33
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +020034def getrandbytes(size):
35 return getrandbits(8 * size).to_bytes(size, 'little')
36
Serhiy Storchakafa6bc292013-07-22 21:00:11 +030037def get_files(test):
38 yield TESTFN2
39 with TemporaryFile() as f:
40 yield f
41 test.assertFalse(f.closed)
42 with io.BytesIO() as f:
43 yield f
44 test.assertFalse(f.closed)
Ezio Melotti76430242009-07-11 18:28:48 +000045
Serhiy Storchakafa6bc292013-07-22 21:00:11 +030046class AbstractTestsWithSourceFile:
47 @classmethod
48 def setUpClass(cls):
49 cls.line_gen = [bytes("Zipfile test line %d. random float: %f\n" %
50 (i, random()), "ascii")
51 for i in range(FIXEDTEST_SIZE)]
52 cls.data = b''.join(cls.line_gen)
53
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000054 def setUp(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000055 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +000056 with open(TESTFN, "wb") as fp:
57 fp.write(self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000058
Bo Baylesce237c72018-01-29 23:54:07 -060059 def make_test_archive(self, f, compression, compresslevel=None):
60 kwargs = {'compression': compression, 'compresslevel': compresslevel}
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000061 # Create the ZIP archive
Bo Baylesce237c72018-01-29 23:54:07 -060062 with zipfile.ZipFile(f, "w", **kwargs) as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000063 zipfp.write(TESTFN, "another.name")
64 zipfp.write(TESTFN, TESTFN)
65 zipfp.writestr("strfile", self.data)
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +030066 with zipfp.open('written-open-w', mode='w') as f:
67 for line in self.line_gen:
68 f.write(line)
Tim Peters7d3bad62001-04-04 18:56:49 +000069
Bo Baylesce237c72018-01-29 23:54:07 -060070 def zip_test(self, f, compression, compresslevel=None):
71 self.make_test_archive(f, compression, compresslevel)
Guido van Rossumd8faa362007-04-27 19:54:29 +000072
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000073 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000074 with zipfile.ZipFile(f, "r", compression) as zipfp:
75 self.assertEqual(zipfp.read(TESTFN), self.data)
76 self.assertEqual(zipfp.read("another.name"), self.data)
77 self.assertEqual(zipfp.read("strfile"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000078
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000079 # Print the ZIP directory
80 fp = io.StringIO()
81 zipfp.printdir(file=fp)
82 directory = fp.getvalue()
83 lines = directory.splitlines()
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +030084 self.assertEqual(len(lines), 5) # Number of files + header
Thomas Wouters0e3f5912006-08-11 14:57:12 +000085
Benjamin Peterson577473f2010-01-19 00:09:57 +000086 self.assertIn('File Name', lines[0])
87 self.assertIn('Modified', lines[0])
88 self.assertIn('Size', lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +000089
Ezio Melotti35386712009-12-31 13:22:41 +000090 fn, date, time_, size = lines[1].split()
91 self.assertEqual(fn, 'another.name')
92 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
93 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
94 self.assertEqual(size, str(len(self.data)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000095
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000096 # Check the namelist
97 names = zipfp.namelist()
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +030098 self.assertEqual(len(names), 4)
Benjamin Peterson577473f2010-01-19 00:09:57 +000099 self.assertIn(TESTFN, names)
100 self.assertIn("another.name", names)
101 self.assertIn("strfile", names)
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300102 self.assertIn("written-open-w", names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000103
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000104 # Check infolist
105 infos = zipfp.infolist()
Ezio Melotti35386712009-12-31 13:22:41 +0000106 names = [i.filename for i in infos]
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300107 self.assertEqual(len(names), 4)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000108 self.assertIn(TESTFN, names)
109 self.assertIn("another.name", names)
110 self.assertIn("strfile", names)
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300111 self.assertIn("written-open-w", names)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000112 for i in infos:
Ezio Melotti35386712009-12-31 13:22:41 +0000113 self.assertEqual(i.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000114
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000115 # check getinfo
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300116 for nm in (TESTFN, "another.name", "strfile", "written-open-w"):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000117 info = zipfp.getinfo(nm)
Ezio Melotti35386712009-12-31 13:22:41 +0000118 self.assertEqual(info.filename, nm)
119 self.assertEqual(info.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000120
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000121 # Check that testzip doesn't raise an exception
122 zipfp.testzip()
Tim Peters7d3bad62001-04-04 18:56:49 +0000123
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300124 def test_basic(self):
125 for f in get_files(self):
126 self.zip_test(f, self.compression)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000127
Ezio Melottiafd0d112009-07-15 17:17:17 +0000128 def zip_open_test(self, f, compression):
129 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000130
131 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000132 with zipfile.ZipFile(f, "r", compression) as zipfp:
133 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000134 with zipfp.open(TESTFN) as zipopen1:
135 while True:
136 read_data = zipopen1.read(256)
137 if not read_data:
138 break
139 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000140
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000141 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000142 with zipfp.open("another.name") as zipopen2:
143 while True:
144 read_data = zipopen2.read(256)
145 if not read_data:
146 break
147 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000148
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000149 self.assertEqual(b''.join(zipdata1), self.data)
150 self.assertEqual(b''.join(zipdata2), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000151
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300152 def test_open(self):
153 for f in get_files(self):
154 self.zip_open_test(f, self.compression)
Georg Brandlb533e262008-05-25 18:19:30 +0000155
Serhiy Storchaka8606e952017-03-08 14:37:51 +0200156 def test_open_with_pathlike(self):
157 path = pathlib.Path(TESTFN2)
158 self.zip_open_test(path, self.compression)
159 with zipfile.ZipFile(path, "r", self.compression) as zipfp:
160 self.assertIsInstance(zipfp.filename, str)
161
Ezio Melottiafd0d112009-07-15 17:17:17 +0000162 def zip_random_open_test(self, f, compression):
163 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000164
165 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000166 with zipfile.ZipFile(f, "r", compression) as zipfp:
167 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000168 with zipfp.open(TESTFN) as zipopen1:
169 while True:
170 read_data = zipopen1.read(randint(1, 1024))
171 if not read_data:
172 break
173 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000174
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000175 self.assertEqual(b''.join(zipdata1), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000176
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300177 def test_random_open(self):
178 for f in get_files(self):
179 self.zip_random_open_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000180
Serhiy Storchakad2c07a52013-09-27 22:11:57 +0300181 def zip_read1_test(self, f, compression):
182 self.make_test_archive(f, compression)
183
184 # Read the ZIP archive
185 with zipfile.ZipFile(f, "r") as zipfp, \
186 zipfp.open(TESTFN) as zipopen:
187 zipdata = []
188 while True:
189 read_data = zipopen.read1(-1)
190 if not read_data:
191 break
192 zipdata.append(read_data)
193
194 self.assertEqual(b''.join(zipdata), self.data)
195
196 def test_read1(self):
197 for f in get_files(self):
198 self.zip_read1_test(f, self.compression)
199
200 def zip_read1_10_test(self, f, compression):
201 self.make_test_archive(f, compression)
202
203 # Read the ZIP archive
204 with zipfile.ZipFile(f, "r") as zipfp, \
205 zipfp.open(TESTFN) as zipopen:
206 zipdata = []
207 while True:
208 read_data = zipopen.read1(10)
209 self.assertLessEqual(len(read_data), 10)
210 if not read_data:
211 break
212 zipdata.append(read_data)
213
214 self.assertEqual(b''.join(zipdata), self.data)
215
216 def test_read1_10(self):
217 for f in get_files(self):
218 self.zip_read1_10_test(f, self.compression)
219
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000220 def zip_readline_read_test(self, f, compression):
221 self.make_test_archive(f, compression)
222
223 # Read the ZIP archive
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300224 with zipfile.ZipFile(f, "r") as zipfp, \
225 zipfp.open(TESTFN) as zipopen:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000226 data = b''
227 while True:
228 read = zipopen.readline()
229 if not read:
230 break
231 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000232
Brian Curtin8fb9b862010-11-18 02:15:28 +0000233 read = zipopen.read(100)
234 if not read:
235 break
236 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000237
238 self.assertEqual(data, self.data)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300239
240 def test_readline_read(self):
241 # Issue #7610: calls to readline() interleaved with calls to read().
242 for f in get_files(self):
243 self.zip_readline_read_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000244
Ezio Melottiafd0d112009-07-15 17:17:17 +0000245 def zip_readline_test(self, f, compression):
246 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000247
248 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000249 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000250 with zipfp.open(TESTFN) as zipopen:
251 for line in self.line_gen:
252 linedata = zipopen.readline()
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300253 self.assertEqual(linedata, line)
254
255 def test_readline(self):
256 for f in get_files(self):
257 self.zip_readline_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000258
Ezio Melottiafd0d112009-07-15 17:17:17 +0000259 def zip_readlines_test(self, f, compression):
260 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000261
262 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000263 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000264 with zipfp.open(TESTFN) as zipopen:
265 ziplines = zipopen.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000266 for line, zipline in zip(self.line_gen, ziplines):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300267 self.assertEqual(zipline, line)
268
269 def test_readlines(self):
270 for f in get_files(self):
271 self.zip_readlines_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000272
Ezio Melottiafd0d112009-07-15 17:17:17 +0000273 def zip_iterlines_test(self, f, compression):
274 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000275
276 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000277 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000278 with zipfp.open(TESTFN) as zipopen:
279 for line, zipline in zip(self.line_gen, zipopen):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300280 self.assertEqual(zipline, line)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000281
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300282 def test_iterlines(self):
283 for f in get_files(self):
284 self.zip_iterlines_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000285
Ezio Melottiafd0d112009-07-15 17:17:17 +0000286 def test_low_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000287 """Check for cases where compressed data is larger than original."""
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000288 # Create the ZIP archive
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300289 with zipfile.ZipFile(TESTFN2, "w", self.compression) as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000290 zipfp.writestr("strfile", '12')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000291
292 # Get an open object for strfile
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300293 with zipfile.ZipFile(TESTFN2, "r", self.compression) as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000294 with zipfp.open("strfile") as openobj:
295 self.assertEqual(openobj.read(1), b'1')
296 self.assertEqual(openobj.read(1), b'2')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000297
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300298 def test_writestr_compression(self):
299 zipfp = zipfile.ZipFile(TESTFN2, "w")
300 zipfp.writestr("b.txt", "hello world", compress_type=self.compression)
301 info = zipfp.getinfo('b.txt')
302 self.assertEqual(info.compress_type, self.compression)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200303
Bo Baylesce237c72018-01-29 23:54:07 -0600304 def test_writestr_compresslevel(self):
305 zipfp = zipfile.ZipFile(TESTFN2, "w", compresslevel=1)
306 zipfp.writestr("a.txt", "hello world", compress_type=self.compression)
307 zipfp.writestr("b.txt", "hello world", compress_type=self.compression,
308 compresslevel=2)
309
310 # Compression level follows the constructor.
311 a_info = zipfp.getinfo('a.txt')
312 self.assertEqual(a_info.compress_type, self.compression)
313 self.assertEqual(a_info._compresslevel, 1)
314
315 # Compression level is overridden.
316 b_info = zipfp.getinfo('b.txt')
317 self.assertEqual(b_info.compress_type, self.compression)
318 self.assertEqual(b_info._compresslevel, 2)
319
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300320 def test_read_return_size(self):
321 # Issue #9837: ZipExtFile.read() shouldn't return more bytes
322 # than requested.
323 for test_size in (1, 4095, 4096, 4097, 16384):
324 file_size = test_size + 1
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +0200325 junk = getrandbytes(file_size)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300326 with zipfile.ZipFile(io.BytesIO(), "w", self.compression) as zipf:
327 zipf.writestr('foo', junk)
328 with zipf.open('foo', 'r') as fp:
329 buf = fp.read(test_size)
330 self.assertEqual(len(buf), test_size)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200331
Serhiy Storchaka5ce3f102014-01-09 14:50:20 +0200332 def test_truncated_zipfile(self):
333 fp = io.BytesIO()
334 with zipfile.ZipFile(fp, mode='w') as zipf:
335 zipf.writestr('strfile', self.data, compress_type=self.compression)
336 end_offset = fp.tell()
337 zipfiledata = fp.getvalue()
338
339 fp = io.BytesIO(zipfiledata)
340 with zipfile.ZipFile(fp) as zipf:
341 with zipf.open('strfile') as zipopen:
342 fp.truncate(end_offset - 20)
343 with self.assertRaises(EOFError):
344 zipopen.read()
345
346 fp = io.BytesIO(zipfiledata)
347 with zipfile.ZipFile(fp) as zipf:
348 with zipf.open('strfile') as zipopen:
349 fp.truncate(end_offset - 20)
350 with self.assertRaises(EOFError):
351 while zipopen.read(100):
352 pass
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.read1(100):
360 pass
361
Serhiy Storchaka51a43702014-10-29 22:42:06 +0200362 def test_repr(self):
363 fname = 'file.name'
364 for f in get_files(self):
365 with zipfile.ZipFile(f, 'w', self.compression) as zipfp:
366 zipfp.write(TESTFN, fname)
367 r = repr(zipfp)
368 self.assertIn("mode='w'", r)
369
370 with zipfile.ZipFile(f, 'r') as zipfp:
371 r = repr(zipfp)
372 if isinstance(f, str):
373 self.assertIn('filename=%r' % f, r)
374 else:
375 self.assertIn('file=%r' % f, r)
376 self.assertIn("mode='r'", r)
377 r = repr(zipfp.getinfo(fname))
378 self.assertIn('filename=%r' % fname, r)
379 self.assertIn('filemode=', r)
380 self.assertIn('file_size=', r)
381 if self.compression != zipfile.ZIP_STORED:
382 self.assertIn('compress_type=', r)
383 self.assertIn('compress_size=', r)
384 with zipfp.open(fname) as zipopen:
385 r = repr(zipopen)
386 self.assertIn('name=%r' % fname, r)
387 self.assertIn("mode='r'", r)
388 if self.compression != zipfile.ZIP_STORED:
389 self.assertIn('compress_type=', r)
390 self.assertIn('[closed]', repr(zipopen))
391 self.assertIn('[closed]', repr(zipfp))
392
Bo Baylesce237c72018-01-29 23:54:07 -0600393 def test_compresslevel_basic(self):
394 for f in get_files(self):
395 self.zip_test(f, self.compression, compresslevel=9)
396
397 def test_per_file_compresslevel(self):
398 """Check that files within a Zip archive can have different
399 compression levels."""
400 with zipfile.ZipFile(TESTFN2, "w", compresslevel=1) as zipfp:
401 zipfp.write(TESTFN, 'compress_1')
402 zipfp.write(TESTFN, 'compress_9', compresslevel=9)
403 one_info = zipfp.getinfo('compress_1')
404 nine_info = zipfp.getinfo('compress_9')
405 self.assertEqual(one_info._compresslevel, 1)
406 self.assertEqual(nine_info._compresslevel, 9)
407
Serhiy Storchaka2524fde2019-03-30 08:25:19 +0200408 def test_writing_errors(self):
409 class BrokenFile(io.BytesIO):
410 def write(self, data):
411 nonlocal count
412 if count is not None:
413 if count == stop:
414 raise OSError
415 count += 1
416 super().write(data)
417
418 stop = 0
419 while True:
420 testfile = BrokenFile()
421 count = None
422 with zipfile.ZipFile(testfile, 'w', self.compression) as zipfp:
423 with zipfp.open('file1', 'w') as f:
424 f.write(b'data1')
425 count = 0
426 try:
427 with zipfp.open('file2', 'w') as f:
428 f.write(b'data2')
429 except OSError:
430 stop += 1
431 else:
432 break
433 finally:
434 count = None
435 with zipfile.ZipFile(io.BytesIO(testfile.getvalue())) as zipfp:
436 self.assertEqual(zipfp.namelist(), ['file1'])
437 self.assertEqual(zipfp.read('file1'), b'data1')
438
439 with zipfile.ZipFile(io.BytesIO(testfile.getvalue())) as zipfp:
440 self.assertEqual(zipfp.namelist(), ['file1', 'file2'])
441 self.assertEqual(zipfp.read('file1'), b'data1')
442 self.assertEqual(zipfp.read('file2'), b'data2')
443
444
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300445 def tearDown(self):
446 unlink(TESTFN)
447 unlink(TESTFN2)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200448
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200449
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300450class StoredTestsWithSourceFile(AbstractTestsWithSourceFile,
451 unittest.TestCase):
452 compression = zipfile.ZIP_STORED
453 test_low_compression = None
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200454
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300455 def zip_test_writestr_permissions(self, f, compression):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300456 # Make sure that writestr and open(... mode='w') create files with
457 # mode 0600, when they are passed a name rather than a ZipInfo
458 # instance.
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200459
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300460 self.make_test_archive(f, compression)
461 with zipfile.ZipFile(f, "r") as zipfp:
462 zinfo = zipfp.getinfo('strfile')
463 self.assertEqual(zinfo.external_attr, 0o600 << 16)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200464
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300465 zinfo2 = zipfp.getinfo('written-open-w')
466 self.assertEqual(zinfo2.external_attr, 0o600 << 16)
467
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300468 def test_writestr_permissions(self):
469 for f in get_files(self):
470 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +0200471
Ezio Melottiafd0d112009-07-15 17:17:17 +0000472 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000473 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
474 zipfp.write(TESTFN, "/absolute")
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000475
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000476 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
477 self.assertEqual(zipfp.namelist(), ["absolute"])
Tim Peters32cbc962006-02-20 21:42:18 +0000478
Ezio Melottiafd0d112009-07-15 17:17:17 +0000479 def test_append_to_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000480 """Test appending to an existing zipfile."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000481 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
482 zipfp.write(TESTFN, TESTFN)
483
484 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
485 zipfp.writestr("strfile", self.data)
486 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000487
Ezio Melottiafd0d112009-07-15 17:17:17 +0000488 def test_append_to_non_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000489 """Test appending to an existing file that is not a zipfile."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000490 # NOTE: this test fails if len(d) < 22 because of the first
491 # line "fpin.seek(-22, 2)" in _EndRecData
Ezio Melotti35386712009-12-31 13:22:41 +0000492 data = b'I am not a ZipFile!'*10
493 with open(TESTFN2, 'wb') as f:
494 f.write(data)
495
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000496 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
497 zipfp.write(TESTFN, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000498
Ezio Melotti35386712009-12-31 13:22:41 +0000499 with open(TESTFN2, 'rb') as f:
500 f.seek(len(data))
501 with zipfile.ZipFile(f, "r") as zipfp:
502 self.assertEqual(zipfp.namelist(), [TESTFN])
Serhiy Storchaka8793b212016-10-07 22:20:50 +0300503 self.assertEqual(zipfp.read(TESTFN), self.data)
504 with open(TESTFN2, 'rb') as f:
505 self.assertEqual(f.read(len(data)), data)
506 zipfiledata = f.read()
507 with io.BytesIO(zipfiledata) as bio, zipfile.ZipFile(bio) as zipfp:
508 self.assertEqual(zipfp.namelist(), [TESTFN])
509 self.assertEqual(zipfp.read(TESTFN), self.data)
510
511 def test_read_concatenated_zip_file(self):
512 with io.BytesIO() as bio:
513 with zipfile.ZipFile(bio, 'w', zipfile.ZIP_STORED) as zipfp:
514 zipfp.write(TESTFN, TESTFN)
515 zipfiledata = bio.getvalue()
516 data = b'I am not a ZipFile!'*10
517 with open(TESTFN2, 'wb') as f:
518 f.write(data)
519 f.write(zipfiledata)
520
521 with zipfile.ZipFile(TESTFN2) as zipfp:
522 self.assertEqual(zipfp.namelist(), [TESTFN])
523 self.assertEqual(zipfp.read(TESTFN), self.data)
524
525 def test_append_to_concatenated_zip_file(self):
526 with io.BytesIO() as bio:
527 with zipfile.ZipFile(bio, 'w', zipfile.ZIP_STORED) as zipfp:
528 zipfp.write(TESTFN, TESTFN)
529 zipfiledata = bio.getvalue()
530 data = b'I am not a ZipFile!'*1000000
531 with open(TESTFN2, 'wb') as f:
532 f.write(data)
533 f.write(zipfiledata)
534
535 with zipfile.ZipFile(TESTFN2, 'a') as zipfp:
536 self.assertEqual(zipfp.namelist(), [TESTFN])
537 zipfp.writestr('strfile', self.data)
538
539 with open(TESTFN2, 'rb') as f:
540 self.assertEqual(f.read(len(data)), data)
541 zipfiledata = f.read()
542 with io.BytesIO(zipfiledata) as bio, zipfile.ZipFile(bio) as zipfp:
543 self.assertEqual(zipfp.namelist(), [TESTFN, 'strfile'])
544 self.assertEqual(zipfp.read(TESTFN), self.data)
545 self.assertEqual(zipfp.read('strfile'), self.data)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000546
R David Murray4fbb9db2011-06-09 15:50:51 -0400547 def test_ignores_newline_at_end(self):
548 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
549 zipfp.write(TESTFN, TESTFN)
550 with open(TESTFN2, 'a') as f:
551 f.write("\r\n\00\00\00")
552 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
553 self.assertIsInstance(zipfp, zipfile.ZipFile)
554
555 def test_ignores_stuff_appended_past_comments(self):
556 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
557 zipfp.comment = b"this is a comment"
558 zipfp.write(TESTFN, TESTFN)
559 with open(TESTFN2, 'a') as f:
560 f.write("abcdef\r\n")
561 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
562 self.assertIsInstance(zipfp, zipfile.ZipFile)
563 self.assertEqual(zipfp.comment, b"this is a comment")
564
Ezio Melottiafd0d112009-07-15 17:17:17 +0000565 def test_write_default_name(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000566 """Check that calling ZipFile.write without arcname specified
567 produces the expected result."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000568 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
569 zipfp.write(TESTFN)
Brian Curtin8fb9b862010-11-18 02:15:28 +0000570 with open(TESTFN, "rb") as f:
571 self.assertEqual(zipfp.read(TESTFN), f.read())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000572
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300573 def test_write_to_readonly(self):
574 """Check that trying to call write() on a readonly ZipFile object
Serhiy Storchakab0d497c2016-09-10 21:28:07 +0300575 raises a ValueError."""
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300576 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
577 zipfp.writestr("somefile.txt", "bogus")
578
579 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
Serhiy Storchakab0d497c2016-09-10 21:28:07 +0300580 self.assertRaises(ValueError, zipfp.write, TESTFN)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300581
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300582 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
Serhiy Storchakab0d497c2016-09-10 21:28:07 +0300583 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300584 zipfp.open(TESTFN, mode='w')
585
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300586 def test_add_file_before_1980(self):
587 # Set atime and mtime to 1970-01-01
588 os.utime(TESTFN, (0, 0))
589 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
590 self.assertRaises(ValueError, zipfp.write, TESTFN)
591
Marcel Plch77b112c2018-08-31 16:43:31 +0200592 with zipfile.ZipFile(TESTFN2, "w", strict_timestamps=False) as zipfp:
593 zipfp.write(TESTFN)
Marcel Plcha2fe1e52018-08-02 15:04:52 +0200594 zinfo = zipfp.getinfo(TESTFN)
595 self.assertEqual(zinfo.date_time, (1980, 1, 1, 0, 0, 0))
596
597 def test_add_file_after_2107(self):
598 # Set atime and mtime to 2108-12-30
Marcel Plch7b41dba2018-08-03 17:59:19 +0200599 try:
600 os.utime(TESTFN, (4386268800, 4386268800))
601 except OverflowError:
602 self.skipTest('Host fs cannot set timestamp to required value.')
603
Marcel Plcha2fe1e52018-08-02 15:04:52 +0200604 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
605 self.assertRaises(struct.error, zipfp.write, TESTFN)
606
Marcel Plch77b112c2018-08-31 16:43:31 +0200607 with zipfile.ZipFile(TESTFN2, "w", strict_timestamps=False) as zipfp:
608 zipfp.write(TESTFN)
Marcel Plcha2fe1e52018-08-02 15:04:52 +0200609 zinfo = zipfp.getinfo(TESTFN)
610 self.assertEqual(zinfo.date_time, (2107, 12, 31, 23, 59, 59))
611
Serhiy Storchaka5ce3f102014-01-09 14:50:20 +0200612
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300613@requires_zlib
614class DeflateTestsWithSourceFile(AbstractTestsWithSourceFile,
615 unittest.TestCase):
616 compression = zipfile.ZIP_DEFLATED
617
Ezio Melottiafd0d112009-07-15 17:17:17 +0000618 def test_per_file_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000619 """Check that files within a Zip archive can have different
620 compression options."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000621 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
622 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
623 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
624 sinfo = zipfp.getinfo('storeme')
625 dinfo = zipfp.getinfo('deflateme')
626 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
627 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000628
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300629@requires_bz2
630class Bzip2TestsWithSourceFile(AbstractTestsWithSourceFile,
631 unittest.TestCase):
632 compression = zipfile.ZIP_BZIP2
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000633
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300634@requires_lzma
635class LzmaTestsWithSourceFile(AbstractTestsWithSourceFile,
636 unittest.TestCase):
637 compression = zipfile.ZIP_LZMA
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000638
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300639
640class AbstractTestZip64InSmallFiles:
641 # These tests test the ZIP64 functionality without using large files,
642 # see test_zipfile64 for proper tests.
643
644 @classmethod
645 def setUpClass(cls):
646 line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
647 for i in range(0, FIXEDTEST_SIZE))
648 cls.data = b'\n'.join(line_gen)
649
650 def setUp(self):
651 self._limit = zipfile.ZIP64_LIMIT
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300652 self._filecount_limit = zipfile.ZIP_FILECOUNT_LIMIT
653 zipfile.ZIP64_LIMIT = 1000
654 zipfile.ZIP_FILECOUNT_LIMIT = 9
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300655
656 # Make a source file with some lines
657 with open(TESTFN, "wb") as fp:
658 fp.write(self.data)
659
660 def zip_test(self, f, compression):
661 # Create the ZIP archive
662 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
663 zipfp.write(TESTFN, "another.name")
664 zipfp.write(TESTFN, TESTFN)
665 zipfp.writestr("strfile", self.data)
666
667 # Read the ZIP archive
668 with zipfile.ZipFile(f, "r", compression) as zipfp:
669 self.assertEqual(zipfp.read(TESTFN), self.data)
670 self.assertEqual(zipfp.read("another.name"), self.data)
671 self.assertEqual(zipfp.read("strfile"), self.data)
672
673 # Print the ZIP directory
674 fp = io.StringIO()
675 zipfp.printdir(fp)
676
677 directory = fp.getvalue()
678 lines = directory.splitlines()
679 self.assertEqual(len(lines), 4) # Number of files + header
680
681 self.assertIn('File Name', lines[0])
682 self.assertIn('Modified', lines[0])
683 self.assertIn('Size', lines[0])
684
685 fn, date, time_, size = lines[1].split()
686 self.assertEqual(fn, 'another.name')
687 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
688 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
689 self.assertEqual(size, str(len(self.data)))
690
691 # Check the namelist
692 names = zipfp.namelist()
693 self.assertEqual(len(names), 3)
694 self.assertIn(TESTFN, names)
695 self.assertIn("another.name", names)
696 self.assertIn("strfile", names)
697
698 # Check infolist
699 infos = zipfp.infolist()
700 names = [i.filename for i in infos]
701 self.assertEqual(len(names), 3)
702 self.assertIn(TESTFN, names)
703 self.assertIn("another.name", names)
704 self.assertIn("strfile", names)
705 for i in infos:
706 self.assertEqual(i.file_size, len(self.data))
707
708 # check getinfo
709 for nm in (TESTFN, "another.name", "strfile"):
710 info = zipfp.getinfo(nm)
711 self.assertEqual(info.filename, nm)
712 self.assertEqual(info.file_size, len(self.data))
713
714 # Check that testzip doesn't raise an exception
715 zipfp.testzip()
716
717 def test_basic(self):
718 for f in get_files(self):
719 self.zip_test(f, self.compression)
720
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300721 def test_too_many_files(self):
722 # This test checks that more than 64k files can be added to an archive,
723 # and that the resulting archive can be read properly by ZipFile
724 zipf = zipfile.ZipFile(TESTFN, "w", self.compression,
725 allowZip64=True)
726 zipf.debug = 100
727 numfiles = 15
728 for i in range(numfiles):
729 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
730 self.assertEqual(len(zipf.namelist()), numfiles)
731 zipf.close()
732
733 zipf2 = zipfile.ZipFile(TESTFN, "r", self.compression)
734 self.assertEqual(len(zipf2.namelist()), numfiles)
735 for i in range(numfiles):
736 content = zipf2.read("foo%08d" % i).decode('ascii')
737 self.assertEqual(content, "%d" % (i**3 % 57))
738 zipf2.close()
739
740 def test_too_many_files_append(self):
741 zipf = zipfile.ZipFile(TESTFN, "w", self.compression,
742 allowZip64=False)
743 zipf.debug = 100
744 numfiles = 9
745 for i in range(numfiles):
746 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
747 self.assertEqual(len(zipf.namelist()), numfiles)
748 with self.assertRaises(zipfile.LargeZipFile):
749 zipf.writestr("foo%08d" % numfiles, b'')
750 self.assertEqual(len(zipf.namelist()), numfiles)
751 zipf.close()
752
753 zipf = zipfile.ZipFile(TESTFN, "a", self.compression,
754 allowZip64=False)
755 zipf.debug = 100
756 self.assertEqual(len(zipf.namelist()), numfiles)
757 with self.assertRaises(zipfile.LargeZipFile):
758 zipf.writestr("foo%08d" % numfiles, b'')
759 self.assertEqual(len(zipf.namelist()), numfiles)
760 zipf.close()
761
762 zipf = zipfile.ZipFile(TESTFN, "a", self.compression,
763 allowZip64=True)
764 zipf.debug = 100
765 self.assertEqual(len(zipf.namelist()), numfiles)
766 numfiles2 = 15
767 for i in range(numfiles, numfiles2):
768 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
769 self.assertEqual(len(zipf.namelist()), numfiles2)
770 zipf.close()
771
772 zipf2 = zipfile.ZipFile(TESTFN, "r", self.compression)
773 self.assertEqual(len(zipf2.namelist()), numfiles2)
774 for i in range(numfiles2):
775 content = zipf2.read("foo%08d" % i).decode('ascii')
776 self.assertEqual(content, "%d" % (i**3 % 57))
777 zipf2.close()
778
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300779 def tearDown(self):
780 zipfile.ZIP64_LIMIT = self._limit
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300781 zipfile.ZIP_FILECOUNT_LIMIT = self._filecount_limit
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300782 unlink(TESTFN)
783 unlink(TESTFN2)
784
785
786class StoredTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
787 unittest.TestCase):
788 compression = zipfile.ZIP_STORED
789
790 def large_file_exception_test(self, f, compression):
Serhiy Storchaka235c5e02013-11-23 15:55:38 +0200791 with zipfile.ZipFile(f, "w", compression, allowZip64=False) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300792 self.assertRaises(zipfile.LargeZipFile,
793 zipfp.write, TESTFN, "another.name")
794
795 def large_file_exception_test2(self, f, compression):
Serhiy Storchaka235c5e02013-11-23 15:55:38 +0200796 with zipfile.ZipFile(f, "w", compression, allowZip64=False) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300797 self.assertRaises(zipfile.LargeZipFile,
798 zipfp.writestr, "another.name", self.data)
799
800 def test_large_file_exception(self):
801 for f in get_files(self):
802 self.large_file_exception_test(f, zipfile.ZIP_STORED)
803 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
804
805 def test_absolute_arcnames(self):
806 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
807 allowZip64=True) as zipfp:
808 zipfp.write(TESTFN, "/absolute")
809
810 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
811 self.assertEqual(zipfp.namelist(), ["absolute"])
812
Serhiy Storchaka9bdb7be2018-09-17 15:36:40 +0300813 def test_append(self):
814 # Test that appending to the Zip64 archive doesn't change
815 # extra fields of existing entries.
816 with zipfile.ZipFile(TESTFN2, "w", allowZip64=True) as zipfp:
817 zipfp.writestr("strfile", self.data)
818 with zipfile.ZipFile(TESTFN2, "r", allowZip64=True) as zipfp:
819 zinfo = zipfp.getinfo("strfile")
820 extra = zinfo.extra
821 with zipfile.ZipFile(TESTFN2, "a", allowZip64=True) as zipfp:
822 zipfp.writestr("strfile2", self.data)
823 with zipfile.ZipFile(TESTFN2, "r", allowZip64=True) as zipfp:
824 zinfo = zipfp.getinfo("strfile")
825 self.assertEqual(zinfo.extra, extra)
826
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300827@requires_zlib
828class DeflateTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
829 unittest.TestCase):
830 compression = zipfile.ZIP_DEFLATED
831
832@requires_bz2
833class Bzip2TestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
834 unittest.TestCase):
835 compression = zipfile.ZIP_BZIP2
836
837@requires_lzma
838class LzmaTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
839 unittest.TestCase):
840 compression = zipfile.ZIP_LZMA
841
842
Serhiy Storchaka4c0d9ea2017-04-12 16:03:23 +0300843class AbstractWriterTests:
844
845 def tearDown(self):
846 unlink(TESTFN2)
847
848 def test_close_after_close(self):
849 data = b'content'
850 with zipfile.ZipFile(TESTFN2, "w", self.compression) as zipf:
851 w = zipf.open('test', 'w')
852 w.write(data)
853 w.close()
854 self.assertTrue(w.closed)
855 w.close()
856 self.assertTrue(w.closed)
857 self.assertEqual(zipf.read('test'), data)
858
859 def test_write_after_close(self):
860 data = b'content'
861 with zipfile.ZipFile(TESTFN2, "w", self.compression) as zipf:
862 w = zipf.open('test', 'w')
863 w.write(data)
864 w.close()
865 self.assertTrue(w.closed)
866 self.assertRaises(ValueError, w.write, b'')
867 self.assertEqual(zipf.read('test'), data)
868
869class StoredWriterTests(AbstractWriterTests, unittest.TestCase):
870 compression = zipfile.ZIP_STORED
871
872@requires_zlib
873class DeflateWriterTests(AbstractWriterTests, unittest.TestCase):
874 compression = zipfile.ZIP_DEFLATED
875
876@requires_bz2
877class Bzip2WriterTests(AbstractWriterTests, unittest.TestCase):
878 compression = zipfile.ZIP_BZIP2
879
880@requires_lzma
881class LzmaWriterTests(AbstractWriterTests, unittest.TestCase):
882 compression = zipfile.ZIP_LZMA
883
884
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300885class PyZipFileTests(unittest.TestCase):
886 def assertCompiledIn(self, name, namelist):
887 if name + 'o' not in namelist:
888 self.assertIn(name + 'c', namelist)
889
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200890 def requiresWriteAccess(self, path):
Berker Peksage1efc072015-02-16 04:36:18 +0200891 # effective_ids unavailable on windows
892 if not os.access(path, os.W_OK,
893 effective_ids=os.access in os.supports_effective_ids):
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200894 self.skipTest('requires write access to the installed location')
Serhiy Storchakad86a6ef2015-09-19 10:55:20 +0300895 filename = os.path.join(path, 'test_zipfile.try')
896 try:
897 fd = os.open(filename, os.O_WRONLY | os.O_CREAT)
898 os.close(fd)
899 except Exception:
900 self.skipTest('requires write access to the installed location')
901 unlink(filename)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200902
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300903 def test_write_pyfile(self):
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200904 self.requiresWriteAccess(os.path.dirname(__file__))
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300905 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
906 fn = __file__
Brett Cannonf299abd2015-04-13 14:21:02 -0400907 if fn.endswith('.pyc'):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300908 path_split = fn.split(os.sep)
909 if os.altsep is not None:
910 path_split.extend(fn.split(os.altsep))
911 if '__pycache__' in path_split:
Serhiy Storchaka9068e4d2013-07-22 21:02:14 +0300912 fn = importlib.util.source_from_cache(fn)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300913 else:
914 fn = fn[:-1]
915
916 zipfp.writepy(fn)
917
918 bn = os.path.basename(fn)
919 self.assertNotIn(bn, zipfp.namelist())
920 self.assertCompiledIn(bn, zipfp.namelist())
921
922 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
923 fn = __file__
Brett Cannonf299abd2015-04-13 14:21:02 -0400924 if fn.endswith('.pyc'):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300925 fn = fn[:-1]
926
927 zipfp.writepy(fn, "testpackage")
928
929 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
930 self.assertNotIn(bn, zipfp.namelist())
931 self.assertCompiledIn(bn, zipfp.namelist())
932
933 def test_write_python_package(self):
934 import email
935 packagedir = os.path.dirname(email.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200936 self.requiresWriteAccess(packagedir)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300937
938 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
939 zipfp.writepy(packagedir)
940
941 # Check for a couple of modules at different levels of the
942 # hierarchy
943 names = zipfp.namelist()
944 self.assertCompiledIn('email/__init__.py', names)
945 self.assertCompiledIn('email/mime/text.py', names)
946
Christian Tismer59202e52013-10-21 03:59:23 +0200947 def test_write_filtered_python_package(self):
948 import test
949 packagedir = os.path.dirname(test.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200950 self.requiresWriteAccess(packagedir)
Christian Tismer59202e52013-10-21 03:59:23 +0200951
952 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
953
Christian Tismer59202e52013-10-21 03:59:23 +0200954 # first make sure that the test folder gives error messages
Georg Brandla6065422013-10-21 08:29:29 +0200955 # (on the badsyntax_... files)
956 with captured_stdout() as reportSIO:
957 zipfp.writepy(packagedir)
Christian Tismer59202e52013-10-21 03:59:23 +0200958 reportStr = reportSIO.getvalue()
959 self.assertTrue('SyntaxError' in reportStr)
960
Christian Tismer410d9312013-10-22 04:09:28 +0200961 # then check that the filter works on the whole package
Georg Brandla6065422013-10-21 08:29:29 +0200962 with captured_stdout() as reportSIO:
963 zipfp.writepy(packagedir, filterfunc=lambda whatever: False)
Christian Tismer59202e52013-10-21 03:59:23 +0200964 reportStr = reportSIO.getvalue()
965 self.assertTrue('SyntaxError' not in reportStr)
966
Christian Tismer410d9312013-10-22 04:09:28 +0200967 # then check that the filter works on individual files
Larry Hastings7e63b362015-05-08 06:54:58 -0700968 def filter(path):
969 return not os.path.basename(path).startswith("bad")
Serhiy Storchakac46d1fa2014-01-20 21:59:33 +0200970 with captured_stdout() as reportSIO, self.assertWarns(UserWarning):
Larry Hastings7e63b362015-05-08 06:54:58 -0700971 zipfp.writepy(packagedir, filterfunc=filter)
Christian Tismer410d9312013-10-22 04:09:28 +0200972 reportStr = reportSIO.getvalue()
973 if reportStr:
974 print(reportStr)
975 self.assertTrue('SyntaxError' not in reportStr)
976
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300977 def test_write_with_optimization(self):
978 import email
979 packagedir = os.path.dirname(email.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200980 self.requiresWriteAccess(packagedir)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300981 optlevel = 1 if __debug__ else 0
Brett Cannonf299abd2015-04-13 14:21:02 -0400982 ext = '.pyc'
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300983
984 with TemporaryFile() as t, \
Christian Tismer59202e52013-10-21 03:59:23 +0200985 zipfile.PyZipFile(t, "w", optimize=optlevel) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300986 zipfp.writepy(packagedir)
987
988 names = zipfp.namelist()
989 self.assertIn('email/__init__' + ext, names)
990 self.assertIn('email/mime/text' + ext, names)
991
992 def test_write_python_directory(self):
993 os.mkdir(TESTFN2)
994 try:
995 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
996 fp.write("print(42)\n")
997
998 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
999 fp.write("print(42 * 42)\n")
1000
1001 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
1002 fp.write("bla bla bla\n")
1003
1004 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
1005 zipfp.writepy(TESTFN2)
1006
1007 names = zipfp.namelist()
1008 self.assertCompiledIn('mod1.py', names)
1009 self.assertCompiledIn('mod2.py', names)
1010 self.assertNotIn('mod2.txt', names)
1011
1012 finally:
Victor Stinner57004c62014-09-04 00:49:01 +02001013 rmtree(TESTFN2)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001014
Christian Tismer410d9312013-10-22 04:09:28 +02001015 def test_write_python_directory_filtered(self):
1016 os.mkdir(TESTFN2)
1017 try:
1018 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
1019 fp.write("print(42)\n")
1020
1021 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
1022 fp.write("print(42 * 42)\n")
1023
1024 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
1025 zipfp.writepy(TESTFN2, filterfunc=lambda fn:
1026 not fn.endswith('mod2.py'))
1027
1028 names = zipfp.namelist()
1029 self.assertCompiledIn('mod1.py', names)
1030 self.assertNotIn('mod2.py', names)
1031
1032 finally:
Victor Stinner57004c62014-09-04 00:49:01 +02001033 rmtree(TESTFN2)
Christian Tismer410d9312013-10-22 04:09:28 +02001034
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001035 def test_write_non_pyfile(self):
1036 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
1037 with open(TESTFN, 'w') as f:
1038 f.write('most definitely not a python file')
1039 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
Victor Stinner88b215e2014-09-04 00:51:09 +02001040 unlink(TESTFN)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001041
1042 def test_write_pyfile_bad_syntax(self):
1043 os.mkdir(TESTFN2)
1044 try:
1045 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
1046 fp.write("Bad syntax in python file\n")
1047
1048 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
1049 # syntax errors are printed to stdout
1050 with captured_stdout() as s:
1051 zipfp.writepy(os.path.join(TESTFN2, "mod1.py"))
1052
1053 self.assertIn("SyntaxError", s.getvalue())
1054
1055 # as it will not have compiled the python file, it will
Brett Cannonf299abd2015-04-13 14:21:02 -04001056 # include the .py file not .pyc
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001057 names = zipfp.namelist()
1058 self.assertIn('mod1.py', names)
1059 self.assertNotIn('mod1.pyc', names)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001060
1061 finally:
Victor Stinner57004c62014-09-04 00:49:01 +02001062 rmtree(TESTFN2)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001063
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001064 def test_write_pathlike(self):
1065 os.mkdir(TESTFN2)
1066 try:
1067 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
1068 fp.write("print(42)\n")
1069
1070 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
1071 zipfp.writepy(pathlib.Path(TESTFN2) / "mod1.py")
1072 names = zipfp.namelist()
1073 self.assertCompiledIn('mod1.py', names)
1074 finally:
1075 rmtree(TESTFN2)
1076
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001077
1078class ExtractTests(unittest.TestCase):
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001079
1080 def make_test_file(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001081 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
1082 for fpath, fdata in SMALL_TEST_DATA:
1083 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +00001084
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001085 def test_extract(self):
1086 with temp_cwd():
1087 self.make_test_file()
1088 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1089 for fpath, fdata in SMALL_TEST_DATA:
1090 writtenfile = zipfp.extract(fpath)
1091
1092 # make sure it was written to the right place
1093 correctfile = os.path.join(os.getcwd(), fpath)
1094 correctfile = os.path.normpath(correctfile)
1095
1096 self.assertEqual(writtenfile, correctfile)
1097
1098 # make sure correct data is in correct file
1099 with open(writtenfile, "rb") as f:
1100 self.assertEqual(fdata.encode(), f.read())
1101
1102 unlink(writtenfile)
1103
1104 def _test_extract_with_target(self, target):
1105 self.make_test_file()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001106 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1107 for fpath, fdata in SMALL_TEST_DATA:
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001108 writtenfile = zipfp.extract(fpath, target)
Christian Heimes790c8232008-01-07 21:14:23 +00001109
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001110 # make sure it was written to the right place
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001111 correctfile = os.path.join(target, fpath)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001112 correctfile = os.path.normpath(correctfile)
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001113 self.assertTrue(os.path.samefile(writtenfile, correctfile), (writtenfile, target))
Christian Heimes790c8232008-01-07 21:14:23 +00001114
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001115 # make sure correct data is in correct file
Brian Curtin8fb9b862010-11-18 02:15:28 +00001116 with open(writtenfile, "rb") as f:
1117 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +00001118
Victor Stinner88b215e2014-09-04 00:51:09 +02001119 unlink(writtenfile)
Christian Heimes790c8232008-01-07 21:14:23 +00001120
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001121 unlink(TESTFN2)
1122
1123 def test_extract_with_target(self):
1124 with temp_dir() as extdir:
1125 self._test_extract_with_target(extdir)
1126
1127 def test_extract_with_target_pathlike(self):
1128 with temp_dir() as extdir:
1129 self._test_extract_with_target(pathlib.Path(extdir))
Christian Heimes790c8232008-01-07 21:14:23 +00001130
Ezio Melottiafd0d112009-07-15 17:17:17 +00001131 def test_extract_all(self):
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001132 with temp_cwd():
1133 self.make_test_file()
1134 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1135 zipfp.extractall()
1136 for fpath, fdata in SMALL_TEST_DATA:
1137 outfile = os.path.join(os.getcwd(), fpath)
Christian Heimes790c8232008-01-07 21:14:23 +00001138
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001139 with open(outfile, "rb") as f:
1140 self.assertEqual(fdata.encode(), f.read())
1141
1142 unlink(outfile)
1143
1144 def _test_extract_all_with_target(self, target):
1145 self.make_test_file()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001146 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001147 zipfp.extractall(target)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001148 for fpath, fdata in SMALL_TEST_DATA:
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001149 outfile = os.path.join(target, fpath)
Christian Heimes790c8232008-01-07 21:14:23 +00001150
Brian Curtin8fb9b862010-11-18 02:15:28 +00001151 with open(outfile, "rb") as f:
1152 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +00001153
Victor Stinner88b215e2014-09-04 00:51:09 +02001154 unlink(outfile)
Christian Heimes790c8232008-01-07 21:14:23 +00001155
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001156 unlink(TESTFN2)
1157
1158 def test_extract_all_with_target(self):
1159 with temp_dir() as extdir:
1160 self._test_extract_all_with_target(extdir)
1161
1162 def test_extract_all_with_target_pathlike(self):
1163 with temp_dir() as extdir:
1164 self._test_extract_all_with_target(pathlib.Path(extdir))
Christian Heimes790c8232008-01-07 21:14:23 +00001165
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001166 def check_file(self, filename, content):
1167 self.assertTrue(os.path.isfile(filename))
1168 with open(filename, 'rb') as f:
1169 self.assertEqual(f.read(), content)
1170
Gregory P. Smith09aa7522013-02-03 00:36:32 -08001171 def test_sanitize_windows_name(self):
1172 san = zipfile.ZipFile._sanitize_windows_name
1173 # Passing pathsep in allows this test to work regardless of platform.
1174 self.assertEqual(san(r',,?,C:,foo,bar/z', ','), r'_,C_,foo,bar/z')
1175 self.assertEqual(san(r'a\b,c<d>e|f"g?h*i', ','), r'a\b,c_d_e_f_g_h_i')
1176 self.assertEqual(san('../../foo../../ba..r', '/'), r'foo/ba..r')
1177
1178 def test_extract_hackers_arcnames_common_cases(self):
1179 common_hacknames = [
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001180 ('../foo/bar', 'foo/bar'),
1181 ('foo/../bar', 'foo/bar'),
1182 ('foo/../../bar', 'foo/bar'),
1183 ('foo/bar/..', 'foo/bar'),
1184 ('./../foo/bar', 'foo/bar'),
1185 ('/foo/bar', 'foo/bar'),
1186 ('/foo/../bar', 'foo/bar'),
1187 ('/foo/../../bar', 'foo/bar'),
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001188 ]
Gregory P. Smith09aa7522013-02-03 00:36:32 -08001189 self._test_extract_hackers_arcnames(common_hacknames)
1190
1191 @unittest.skipIf(os.path.sep != '\\', 'Requires \\ as path separator.')
1192 def test_extract_hackers_arcnames_windows_only(self):
1193 """Test combination of path fixing and windows name sanitization."""
1194 windows_hacknames = [
Christian Tismer59202e52013-10-21 03:59:23 +02001195 (r'..\foo\bar', 'foo/bar'),
1196 (r'..\/foo\/bar', 'foo/bar'),
1197 (r'foo/\..\/bar', 'foo/bar'),
1198 (r'foo\/../\bar', 'foo/bar'),
1199 (r'C:foo/bar', 'foo/bar'),
1200 (r'C:/foo/bar', 'foo/bar'),
1201 (r'C://foo/bar', 'foo/bar'),
1202 (r'C:\foo\bar', 'foo/bar'),
1203 (r'//conky/mountpoint/foo/bar', 'foo/bar'),
1204 (r'\\conky\mountpoint\foo\bar', 'foo/bar'),
1205 (r'///conky/mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
1206 (r'\\\conky\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
1207 (r'//conky//mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
1208 (r'\\conky\\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
1209 (r'//?/C:/foo/bar', 'foo/bar'),
1210 (r'\\?\C:\foo\bar', 'foo/bar'),
1211 (r'C:/../C:/foo/bar', 'C_/foo/bar'),
1212 (r'a:b\c<d>e|f"g?h*i', 'b/c_d_e_f_g_h_i'),
1213 ('../../foo../../ba..r', 'foo/ba..r'),
Gregory P. Smith09aa7522013-02-03 00:36:32 -08001214 ]
1215 self._test_extract_hackers_arcnames(windows_hacknames)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001216
Gregory P. Smith09aa7522013-02-03 00:36:32 -08001217 @unittest.skipIf(os.path.sep != '/', r'Requires / as path separator.')
1218 def test_extract_hackers_arcnames_posix_only(self):
1219 posix_hacknames = [
1220 ('//foo/bar', 'foo/bar'),
1221 ('../../foo../../ba..r', 'foo../ba..r'),
1222 (r'foo/..\bar', r'foo/..\bar'),
1223 ]
1224 self._test_extract_hackers_arcnames(posix_hacknames)
1225
1226 def _test_extract_hackers_arcnames(self, hacknames):
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001227 for arcname, fixedname in hacknames:
1228 content = b'foobar' + arcname.encode()
1229 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipfp:
Serhiy Storchakae5e64442013-02-02 19:50:59 +02001230 zinfo = zipfile.ZipInfo()
1231 # preserve backslashes
1232 zinfo.filename = arcname
1233 zinfo.external_attr = 0o600 << 16
1234 zipfp.writestr(zinfo, content)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001235
Serhiy Storchakae5e64442013-02-02 19:50:59 +02001236 arcname = arcname.replace(os.sep, "/")
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001237 targetpath = os.path.join('target', 'subdir', 'subsub')
1238 correctfile = os.path.join(targetpath, *fixedname.split('/'))
1239
1240 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1241 writtenfile = zipfp.extract(arcname, targetpath)
Serhiy Storchakae5e64442013-02-02 19:50:59 +02001242 self.assertEqual(writtenfile, correctfile,
Gregory P. Smith09aa7522013-02-03 00:36:32 -08001243 msg='extract %r: %r != %r' %
1244 (arcname, writtenfile, correctfile))
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001245 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001246 rmtree('target')
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001247
1248 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1249 zipfp.extractall(targetpath)
1250 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001251 rmtree('target')
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001252
1253 correctfile = os.path.join(os.getcwd(), *fixedname.split('/'))
1254
1255 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1256 writtenfile = zipfp.extract(arcname)
Serhiy Storchakae5e64442013-02-02 19:50:59 +02001257 self.assertEqual(writtenfile, correctfile,
1258 msg="extract %r" % arcname)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001259 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001260 rmtree(fixedname.split('/')[0])
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001261
1262 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1263 zipfp.extractall()
1264 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001265 rmtree(fixedname.split('/')[0])
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001266
Victor Stinner88b215e2014-09-04 00:51:09 +02001267 unlink(TESTFN2)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001268
Ronald Oussorenee5c8852010-02-07 20:24:02 +00001269
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001270class OtherTests(unittest.TestCase):
1271 def test_open_via_zip_info(self):
1272 # Create the ZIP archive
1273 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
1274 zipfp.writestr("name", "foo")
Serhiy Storchaka9b7a1a12014-01-20 21:57:40 +02001275 with self.assertWarns(UserWarning):
1276 zipfp.writestr("name", "bar")
1277 self.assertEqual(zipfp.namelist(), ["name"] * 2)
Ronald Oussorenee5c8852010-02-07 20:24:02 +00001278
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001279 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1280 infos = zipfp.infolist()
1281 data = b""
1282 for info in infos:
1283 with zipfp.open(info) as zipopen:
1284 data += zipopen.read()
1285 self.assertIn(data, {b"foobar", b"barfoo"})
1286 data = b""
1287 for info in infos:
1288 data += zipfp.read(info)
1289 self.assertIn(data, {b"foobar", b"barfoo"})
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001290
Gregory P. Smithb0d9ca92009-07-07 05:06:04 +00001291 def test_writestr_extended_local_header_issue1202(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001292 with zipfile.ZipFile(TESTFN2, 'w') as orig_zip:
1293 for data in 'abcdefghijklmnop':
1294 zinfo = zipfile.ZipInfo(data)
1295 zinfo.flag_bits |= 0x08 # Include an extended local header.
1296 orig_zip.writestr(zinfo, data)
1297
1298 def test_close(self):
1299 """Check that the zipfile is closed after the 'with' block."""
1300 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
1301 for fpath, fdata in SMALL_TEST_DATA:
1302 zipfp.writestr(fpath, fdata)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001303 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
1304 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001305
1306 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001307 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
1308 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001309
1310 def test_close_on_exception(self):
1311 """Check that the zipfile is closed if an exception is raised in the
1312 'with' block."""
1313 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
1314 for fpath, fdata in SMALL_TEST_DATA:
1315 zipfp.writestr(fpath, fdata)
1316
1317 try:
1318 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
Georg Brandl4d540882010-10-28 06:42:33 +00001319 raise zipfile.BadZipFile()
1320 except zipfile.BadZipFile:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001321 self.assertIsNone(zipfp2.fp, 'zipfp is not closed')
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001322
Martin v. Löwisd099b562012-05-01 14:08:22 +02001323 def test_unsupported_version(self):
1324 # File has an extract_version of 120
1325 data = (b'PK\x03\x04x\x00\x00\x00\x00\x00!p\xa1@\x00\x00\x00\x00\x00\x00'
Christian Tismer59202e52013-10-21 03:59:23 +02001326 b'\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00xPK\x01\x02x\x03x\x00\x00\x00\x00'
1327 b'\x00!p\xa1@\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00'
1328 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00\x00xPK\x05\x06'
1329 b'\x00\x00\x00\x00\x01\x00\x01\x00/\x00\x00\x00\x1f\x00\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001330
Martin v. Löwisd099b562012-05-01 14:08:22 +02001331 self.assertRaises(NotImplementedError, zipfile.ZipFile,
1332 io.BytesIO(data), 'r')
1333
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001334 @requires_zlib
1335 def test_read_unicode_filenames(self):
1336 # bug #10801
1337 fname = findfile('zip_cp437_header.zip')
1338 with zipfile.ZipFile(fname) as zipfp:
1339 for name in zipfp.namelist():
1340 zipfp.open(name).close()
1341
1342 def test_write_unicode_filenames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001343 with zipfile.ZipFile(TESTFN, "w") as zf:
1344 zf.writestr("foo.txt", "Test for unicode filename")
1345 zf.writestr("\xf6.txt", "Test for unicode filename")
Ezio Melottie9615932010-01-24 19:26:24 +00001346 self.assertIsInstance(zf.infolist()[0].filename, str)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001347
1348 with zipfile.ZipFile(TESTFN, "r") as zf:
1349 self.assertEqual(zf.filelist[0].filename, "foo.txt")
1350 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
Martin v. Löwis8570f6a2008-05-05 17:44:38 +00001351
Serhiy Storchaka764fc9b2015-03-25 10:09:41 +02001352 def test_exclusive_create_zip_file(self):
1353 """Test exclusive creating a new zipfile."""
1354 unlink(TESTFN2)
1355 filename = 'testfile.txt'
1356 content = b'hello, world. this is some content.'
1357 with zipfile.ZipFile(TESTFN2, "x", zipfile.ZIP_STORED) as zipfp:
1358 zipfp.writestr(filename, content)
1359 with self.assertRaises(FileExistsError):
1360 zipfile.ZipFile(TESTFN2, "x", zipfile.ZIP_STORED)
1361 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1362 self.assertEqual(zipfp.namelist(), [filename])
1363 self.assertEqual(zipfp.read(filename), content)
1364
Ezio Melottiafd0d112009-07-15 17:17:17 +00001365 def test_create_non_existent_file_for_append(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001366 if os.path.exists(TESTFN):
1367 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001368
Thomas Wouterscf297e42007-02-23 15:07:44 +00001369 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001370 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +00001371
Thomas Wouterscf297e42007-02-23 15:07:44 +00001372 try:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001373 with zipfile.ZipFile(TESTFN, 'a') as zf:
1374 zf.writestr(filename, content)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001375 except OSError:
Thomas Wouterscf297e42007-02-23 15:07:44 +00001376 self.fail('Could not append data to a non-existent zip file.')
1377
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001378 self.assertTrue(os.path.exists(TESTFN))
Thomas Wouterscf297e42007-02-23 15:07:44 +00001379
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001380 with zipfile.ZipFile(TESTFN, 'r') as zf:
1381 self.assertEqual(zf.read(filename), content)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001382
Ezio Melottiafd0d112009-07-15 17:17:17 +00001383 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001384 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti35386712009-12-31 13:22:41 +00001385 # it opens if there's an error in the file. If it doesn't, the
1386 # traceback holds a reference to the ZipFile object and, indirectly,
1387 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001388 # On Windows, this causes the os.unlink() call to fail because the
1389 # underlying file is still open. This is SF bug #412214.
1390 #
Ezio Melotti35386712009-12-31 13:22:41 +00001391 with open(TESTFN, "w") as fp:
1392 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001393 try:
1394 zf = zipfile.ZipFile(TESTFN)
Georg Brandl4d540882010-10-28 06:42:33 +00001395 except zipfile.BadZipFile:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001396 pass
1397
Ezio Melottiafd0d112009-07-15 17:17:17 +00001398 def test_is_zip_erroneous_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001399 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001400 # - passing a filename
1401 with open(TESTFN, "w") as fp:
1402 fp.write("this is not a legal zip file\n")
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001403 self.assertFalse(zipfile.is_zipfile(TESTFN))
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001404 # - passing a path-like object
1405 self.assertFalse(zipfile.is_zipfile(pathlib.Path(TESTFN)))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001406 # - passing a file object
1407 with open(TESTFN, "rb") as fp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001408 self.assertFalse(zipfile.is_zipfile(fp))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001409 # - passing a file-like object
1410 fp = io.BytesIO()
1411 fp.write(b"this is not a legal zip file\n")
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001412 self.assertFalse(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001413 fp.seek(0, 0)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001414 self.assertFalse(zipfile.is_zipfile(fp))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001415
Serhiy Storchakad2b15272013-01-31 15:27:07 +02001416 def test_damaged_zipfile(self):
1417 """Check that zipfiles with missing bytes at the end raise BadZipFile."""
1418 # - Create a valid zip file
1419 fp = io.BytesIO()
1420 with zipfile.ZipFile(fp, mode="w") as zipf:
1421 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
1422 zipfiledata = fp.getvalue()
1423
1424 # - Now create copies of it missing the last N bytes and make sure
1425 # a BadZipFile exception is raised when we try to open it
1426 for N in range(len(zipfiledata)):
1427 fp = io.BytesIO(zipfiledata[:N])
1428 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, fp)
1429
Ezio Melottiafd0d112009-07-15 17:17:17 +00001430 def test_is_zip_valid_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001431 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001432 # - passing a filename
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001433 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1434 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
1435
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001436 self.assertTrue(zipfile.is_zipfile(TESTFN))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001437 # - passing a file object
1438 with open(TESTFN, "rb") as fp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001439 self.assertTrue(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001440 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001441 zip_contents = fp.read()
1442 # - passing a file-like object
1443 fp = io.BytesIO()
1444 fp.write(zip_contents)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001445 self.assertTrue(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001446 fp.seek(0, 0)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001447 self.assertTrue(zipfile.is_zipfile(fp))
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001448
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001449 def test_non_existent_file_raises_OSError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001450 # make sure we don't raise an AttributeError when a partially-constructed
1451 # ZipFile instance is finalized; this tests for regression on SF tracker
1452 # bug #403871.
1453
1454 # The bug we're testing for caused an AttributeError to be raised
1455 # when a ZipFile instance was created for a file that did not
1456 # exist; the .fp member was not initialized but was needed by the
1457 # __del__() method. Since the AttributeError is in the __del__(),
1458 # it is ignored, but the user should be sufficiently annoyed by
1459 # the message on the output that regression will be noticed
1460 # quickly.
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001461 self.assertRaises(OSError, zipfile.ZipFile, TESTFN)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001462
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001463 def test_empty_file_raises_BadZipFile(self):
1464 f = open(TESTFN, 'w')
1465 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001466 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001467
Ezio Melotti35386712009-12-31 13:22:41 +00001468 with open(TESTFN, 'w') as fp:
1469 fp.write("short file")
Georg Brandl4d540882010-10-28 06:42:33 +00001470 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001471
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001472 def test_closed_zip_raises_ValueError(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001473 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001474 data = io.BytesIO()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001475 with zipfile.ZipFile(data, mode="w") as zipf:
1476 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001477
Andrew Svetlov737fb892012-12-18 21:14:22 +02001478 # This is correct; calling .read on a closed ZipFile should raise
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001479 # a ValueError, and so should calling .testzip. An earlier
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001480 # version of .testzip would swallow this exception (and any other)
1481 # and report that the first file in the archive was corrupt.
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001482 self.assertRaises(ValueError, zipf.read, "foo.txt")
1483 self.assertRaises(ValueError, zipf.open, "foo.txt")
1484 self.assertRaises(ValueError, zipf.testzip)
1485 self.assertRaises(ValueError, zipf.writestr, "bogus.txt", "bogus")
Brian Curtin8fb9b862010-11-18 02:15:28 +00001486 with open(TESTFN, 'w') as f:
1487 f.write('zipfile test data')
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001488 self.assertRaises(ValueError, zipf.write, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001489
Ezio Melottiafd0d112009-07-15 17:17:17 +00001490 def test_bad_constructor_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001491 """Check that bad modes passed to ZipFile constructor are caught."""
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001492 self.assertRaises(ValueError, zipfile.ZipFile, TESTFN, "q")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001493
Ezio Melottiafd0d112009-07-15 17:17:17 +00001494 def test_bad_open_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001495 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001496 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1497 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1498
1499 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Serhiy Storchakae670be22016-06-11 19:32:44 +03001500 # read the data to make sure the file is there
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001501 zipf.read("foo.txt")
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001502 self.assertRaises(ValueError, zipf.open, "foo.txt", "q")
Serhiy Storchakae670be22016-06-11 19:32:44 +03001503 # universal newlines support is removed
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001504 self.assertRaises(ValueError, zipf.open, "foo.txt", "U")
1505 self.assertRaises(ValueError, zipf.open, "foo.txt", "rU")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001506
Ezio Melottiafd0d112009-07-15 17:17:17 +00001507 def test_read0(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001508 """Check that calling read(0) on a ZipExtFile object returns an empty
1509 string and doesn't advance file pointer."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001510 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1511 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1512 # read the data to make sure the file is there
Brian Curtin8fb9b862010-11-18 02:15:28 +00001513 with zipf.open("foo.txt") as f:
1514 for i in range(FIXEDTEST_SIZE):
1515 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001516
Brian Curtin8fb9b862010-11-18 02:15:28 +00001517 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001518
Ezio Melottiafd0d112009-07-15 17:17:17 +00001519 def test_open_non_existent_item(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001520 """Check that attempting to call open() for an item that doesn't
1521 exist in the archive raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001522 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1523 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001524
Ezio Melottiafd0d112009-07-15 17:17:17 +00001525 def test_bad_compression_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001526 """Check that bad compression methods passed to ZipFile.open are
1527 caught."""
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001528 self.assertRaises(NotImplementedError, zipfile.ZipFile, TESTFN, "w", -1)
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001529
Martin v. Löwisb3260f02012-05-01 08:38:01 +02001530 def test_unsupported_compression(self):
1531 # data is declared as shrunk, but actually deflated
1532 data = (b'PK\x03\x04.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00'
Christian Tismer59202e52013-10-21 03:59:23 +02001533 b'\x00\x02\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00x\x03\x00PK\x01'
1534 b'\x02.\x03.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00\x00\x02\x00\x00'
1535 b'\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
1536 b'\x80\x01\x00\x00\x00\x00xPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00'
1537 b'/\x00\x00\x00!\x00\x00\x00\x00\x00')
Martin v. Löwisb3260f02012-05-01 08:38:01 +02001538 with zipfile.ZipFile(io.BytesIO(data), 'r') as zipf:
1539 self.assertRaises(NotImplementedError, zipf.open, 'x')
1540
Ezio Melottiafd0d112009-07-15 17:17:17 +00001541 def test_null_byte_in_filename(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001542 """Check that a filename containing a null byte is properly
1543 terminated."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001544 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1545 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
1546 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001547
Ezio Melottiafd0d112009-07-15 17:17:17 +00001548 def test_struct_sizes(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001549 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001550 self.assertEqual(zipfile.sizeEndCentDir, 22)
1551 self.assertEqual(zipfile.sizeCentralDir, 46)
1552 self.assertEqual(zipfile.sizeEndCentDir64, 56)
1553 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
1554
Ezio Melottiafd0d112009-07-15 17:17:17 +00001555 def test_comments(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001556 """Check that comments on the archive are handled properly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001557
1558 # check default comment is empty
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001559 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1560 self.assertEqual(zipf.comment, b'')
1561 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1562
1563 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1564 self.assertEqual(zipfr.comment, b'')
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001565
1566 # check a simple short comment
1567 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001568 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1569 zipf.comment = comment
1570 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1571 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1572 self.assertEqual(zipf.comment, comment)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001573
1574 # check a comment of max length
1575 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
1576 comment2 = comment2.encode("ascii")
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001577 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1578 zipf.comment = comment2
1579 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1580
1581 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1582 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001583
1584 # check a comment that is too long is truncated
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001585 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
Serhiy Storchaka9b7a1a12014-01-20 21:57:40 +02001586 with self.assertWarns(UserWarning):
1587 zipf.comment = comment2 + b'oops'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001588 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1589 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1590 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001591
Antoine Pitrouc3991852012-06-30 17:31:37 +02001592 # check that comments are correctly modified in append mode
1593 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1594 zipf.comment = b"original comment"
1595 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1596 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1597 zipf.comment = b"an updated comment"
1598 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1599 self.assertEqual(zipf.comment, b"an updated comment")
1600
1601 # check that comments are correctly shortened in append mode
1602 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1603 zipf.comment = b"original comment that's longer"
1604 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1605 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1606 zipf.comment = b"shorter comment"
1607 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1608 self.assertEqual(zipf.comment, b"shorter comment")
1609
R David Murrayf50b38a2012-04-12 18:44:58 -04001610 def test_unicode_comment(self):
1611 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1612 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1613 with self.assertRaises(TypeError):
1614 zipf.comment = "this is an error"
1615
1616 def test_change_comment_in_empty_archive(self):
1617 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1618 self.assertFalse(zipf.filelist)
1619 zipf.comment = b"this is a comment"
1620 with zipfile.ZipFile(TESTFN, "r") as zipf:
1621 self.assertEqual(zipf.comment, b"this is a comment")
1622
1623 def test_change_comment_in_nonempty_archive(self):
1624 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1625 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1626 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1627 self.assertTrue(zipf.filelist)
1628 zipf.comment = b"this is a comment"
1629 with zipfile.ZipFile(TESTFN, "r") as zipf:
1630 self.assertEqual(zipf.comment, b"this is a comment")
1631
Georg Brandl268e4d42010-10-14 06:59:45 +00001632 def test_empty_zipfile(self):
1633 # Check that creating a file in 'w' or 'a' mode and closing without
1634 # adding any files to the archives creates a valid empty ZIP file
1635 zipf = zipfile.ZipFile(TESTFN, mode="w")
1636 zipf.close()
1637 try:
1638 zipf = zipfile.ZipFile(TESTFN, mode="r")
1639 except zipfile.BadZipFile:
1640 self.fail("Unable to create empty ZIP file in 'w' mode")
1641
1642 zipf = zipfile.ZipFile(TESTFN, mode="a")
1643 zipf.close()
1644 try:
1645 zipf = zipfile.ZipFile(TESTFN, mode="r")
1646 except:
1647 self.fail("Unable to create empty ZIP file in 'a' mode")
1648
1649 def test_open_empty_file(self):
1650 # Issue 1710703: Check that opening a file with less than 22 bytes
Georg Brandl4d540882010-10-28 06:42:33 +00001651 # raises a BadZipFile exception (rather than the previously unhelpful
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001652 # OSError)
Georg Brandl268e4d42010-10-14 06:59:45 +00001653 f = open(TESTFN, 'w')
1654 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001655 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN, 'r')
Georg Brandl268e4d42010-10-14 06:59:45 +00001656
Senthil Kumaran29fa9d42011-10-20 01:46:00 +08001657 def test_create_zipinfo_before_1980(self):
1658 self.assertRaises(ValueError,
1659 zipfile.ZipInfo, 'seventies', (1979, 1, 1, 0, 0, 0))
1660
Gregory P. Smith0af8a862014-05-29 23:42:14 -07001661 def test_zipfile_with_short_extra_field(self):
1662 """If an extra field in the header is less than 4 bytes, skip it."""
1663 zipdata = (
1664 b'PK\x03\x04\x14\x00\x00\x00\x00\x00\x93\x9b\xad@\x8b\x9e'
1665 b'\xd9\xd3\x01\x00\x00\x00\x01\x00\x00\x00\x03\x00\x03\x00ab'
1666 b'c\x00\x00\x00APK\x01\x02\x14\x03\x14\x00\x00\x00\x00'
1667 b'\x00\x93\x9b\xad@\x8b\x9e\xd9\xd3\x01\x00\x00\x00\x01\x00\x00'
1668 b'\x00\x03\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00'
1669 b'\x00\x00\x00abc\x00\x00PK\x05\x06\x00\x00\x00\x00'
1670 b'\x01\x00\x01\x003\x00\x00\x00%\x00\x00\x00\x00\x00'
1671 )
1672 with zipfile.ZipFile(io.BytesIO(zipdata), 'r') as zipf:
1673 # testzip returns the name of the first corrupt file, or None
1674 self.assertIsNone(zipf.testzip())
1675
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001676 def test_open_conflicting_handles(self):
1677 # It's only possible to open one writable file handle at a time
1678 msg1 = b"It's fun to charter an accountant!"
1679 msg2 = b"And sail the wide accountant sea"
1680 msg3 = b"To find, explore the funds offshore"
1681 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipf:
1682 with zipf.open('foo', mode='w') as w2:
1683 w2.write(msg1)
1684 with zipf.open('bar', mode='w') as w1:
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001685 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001686 zipf.open('handle', mode='w')
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001687 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001688 zipf.open('foo', mode='r')
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001689 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001690 zipf.writestr('str', 'abcde')
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001691 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001692 zipf.write(__file__, 'file')
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001693 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001694 zipf.close()
1695 w1.write(msg2)
1696 with zipf.open('baz', mode='w') as w2:
1697 w2.write(msg3)
1698
1699 with zipfile.ZipFile(TESTFN2, 'r') as zipf:
1700 self.assertEqual(zipf.read('foo'), msg1)
1701 self.assertEqual(zipf.read('bar'), msg2)
1702 self.assertEqual(zipf.read('baz'), msg3)
1703 self.assertEqual(zipf.namelist(), ['foo', 'bar', 'baz'])
1704
John Jolly066df4f2018-01-30 01:51:35 -07001705 def test_seek_tell(self):
1706 # Test seek functionality
1707 txt = b"Where's Bruce?"
1708 bloc = txt.find(b"Bruce")
1709 # Check seek on a file
1710 with zipfile.ZipFile(TESTFN, "w") as zipf:
1711 zipf.writestr("foo.txt", txt)
1712 with zipfile.ZipFile(TESTFN, "r") as zipf:
1713 with zipf.open("foo.txt", "r") as fp:
1714 fp.seek(bloc, os.SEEK_SET)
1715 self.assertEqual(fp.tell(), bloc)
1716 fp.seek(-bloc, os.SEEK_CUR)
1717 self.assertEqual(fp.tell(), 0)
1718 fp.seek(bloc, os.SEEK_CUR)
1719 self.assertEqual(fp.tell(), bloc)
1720 self.assertEqual(fp.read(5), txt[bloc:bloc+5])
1721 fp.seek(0, os.SEEK_END)
1722 self.assertEqual(fp.tell(), len(txt))
Mickaël Schoentgen3f8c6912018-07-29 20:26:52 +02001723 fp.seek(0, os.SEEK_SET)
1724 self.assertEqual(fp.tell(), 0)
John Jolly066df4f2018-01-30 01:51:35 -07001725 # Check seek on memory file
1726 data = io.BytesIO()
1727 with zipfile.ZipFile(data, mode="w") as zipf:
1728 zipf.writestr("foo.txt", txt)
1729 with zipfile.ZipFile(data, mode="r") as zipf:
1730 with zipf.open("foo.txt", "r") as fp:
1731 fp.seek(bloc, os.SEEK_SET)
1732 self.assertEqual(fp.tell(), bloc)
1733 fp.seek(-bloc, os.SEEK_CUR)
1734 self.assertEqual(fp.tell(), 0)
1735 fp.seek(bloc, os.SEEK_CUR)
1736 self.assertEqual(fp.tell(), bloc)
1737 self.assertEqual(fp.read(5), txt[bloc:bloc+5])
1738 fp.seek(0, os.SEEK_END)
1739 self.assertEqual(fp.tell(), len(txt))
Mickaël Schoentgen3f8c6912018-07-29 20:26:52 +02001740 fp.seek(0, os.SEEK_SET)
1741 self.assertEqual(fp.tell(), 0)
John Jolly066df4f2018-01-30 01:51:35 -07001742
Miss Islington (bot)717cc612019-09-12 07:33:53 -07001743 @requires_bz2
1744 def test_decompress_without_3rd_party_library(self):
1745 data = b'PK\x05\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
1746 zip_file = io.BytesIO(data)
1747 with zipfile.ZipFile(zip_file, 'w', compression=zipfile.ZIP_BZIP2) as zf:
1748 zf.writestr('a.txt', b'a')
1749 with mock.patch('zipfile.bz2', None):
1750 with zipfile.ZipFile(zip_file) as zf:
1751 self.assertRaises(RuntimeError, zf.extract, 'a.txt')
1752
Guido van Rossumd8faa362007-04-27 19:54:29 +00001753 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001754 unlink(TESTFN)
1755 unlink(TESTFN2)
1756
Thomas Wouterscf297e42007-02-23 15:07:44 +00001757
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001758class AbstractBadCrcTests:
1759 def test_testzip_with_bad_crc(self):
1760 """Tests that files with bad CRCs return their name from testzip."""
1761 zipdata = self.zip_with_bad_crc
1762
1763 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1764 # testzip returns the name of the first corrupt file, or None
1765 self.assertEqual('afile', zipf.testzip())
1766
1767 def test_read_with_bad_crc(self):
1768 """Tests that files with bad CRCs raise a BadZipFile exception when read."""
1769 zipdata = self.zip_with_bad_crc
1770
1771 # Using ZipFile.read()
1772 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1773 self.assertRaises(zipfile.BadZipFile, zipf.read, 'afile')
1774
1775 # Using ZipExtFile.read()
1776 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1777 with zipf.open('afile', 'r') as corrupt_file:
1778 self.assertRaises(zipfile.BadZipFile, corrupt_file.read)
1779
1780 # Same with small reads (in order to exercise the buffering logic)
1781 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1782 with zipf.open('afile', 'r') as corrupt_file:
1783 corrupt_file.MIN_READ_SIZE = 2
1784 with self.assertRaises(zipfile.BadZipFile):
1785 while corrupt_file.read(2):
1786 pass
1787
1788
1789class StoredBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1790 compression = zipfile.ZIP_STORED
1791 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001792 b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
1793 b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
1794 b'ilehello,AworldP'
1795 b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
1796 b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
1797 b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
1798 b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
1799 b'\0\0/\0\0\0\0\0')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001800
1801@requires_zlib
1802class DeflateBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1803 compression = zipfile.ZIP_DEFLATED
1804 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001805 b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
1806 b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1807 b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
1808 b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
1809 b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
1810 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
1811 b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
1812 b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001813
1814@requires_bz2
1815class Bzip2BadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1816 compression = zipfile.ZIP_BZIP2
1817 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001818 b'PK\x03\x04\x14\x03\x00\x00\x0c\x00nu\x0c=FA'
1819 b'KE8\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1820 b'ileBZh91AY&SY\xd4\xa8\xca'
1821 b'\x7f\x00\x00\x0f\x11\x80@\x00\x06D\x90\x80 \x00 \xa5'
1822 b'P\xd9!\x03\x03\x13\x13\x13\x89\xa9\xa9\xc2u5:\x9f'
1823 b'\x8b\xb9"\x9c(HjTe?\x80PK\x01\x02\x14'
1824 b'\x03\x14\x03\x00\x00\x0c\x00nu\x0c=FAKE8'
1825 b'\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\x00'
1826 b'\x00 \x80\x80\x81\x00\x00\x00\x00afilePK'
1827 b'\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00\x00[\x00'
1828 b'\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001829
1830@requires_lzma
1831class LzmaBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1832 compression = zipfile.ZIP_LZMA
1833 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001834 b'PK\x03\x04\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
1835 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1836 b'ile\t\x04\x05\x00]\x00\x00\x00\x04\x004\x19I'
1837 b'\xee\x8d\xe9\x17\x89:3`\tq!.8\x00PK'
1838 b'\x01\x02\x14\x03\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
1839 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00'
1840 b'\x00\x00\x00\x00 \x80\x80\x81\x00\x00\x00\x00afil'
1841 b'ePK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00'
1842 b'\x00>\x00\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001843
1844
Thomas Wouterscf297e42007-02-23 15:07:44 +00001845class DecryptionTests(unittest.TestCase):
Ezio Melotti35386712009-12-31 13:22:41 +00001846 """Check that ZIP decryption works. Since the library does not
1847 support encryption at the moment, we use a pre-generated encrypted
1848 ZIP file."""
Thomas Wouterscf297e42007-02-23 15:07:44 +00001849
1850 data = (
Christian Tismer59202e52013-10-21 03:59:23 +02001851 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
1852 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
1853 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
1854 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
1855 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
1856 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
1857 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +00001858 data2 = (
Christian Tismer59202e52013-10-21 03:59:23 +02001859 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
1860 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
1861 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
1862 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
1863 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
1864 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
1865 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
1866 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +00001867
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001868 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +00001869 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +00001870
1871 def setUp(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001872 with open(TESTFN, "wb") as fp:
1873 fp.write(self.data)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001874 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti35386712009-12-31 13:22:41 +00001875 with open(TESTFN2, "wb") as fp:
1876 fp.write(self.data2)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001877 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001878
1879 def tearDown(self):
1880 self.zip.close()
1881 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001882 self.zip2.close()
1883 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001884
Ezio Melottiafd0d112009-07-15 17:17:17 +00001885 def test_no_password(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001886 # Reading the encrypted file without password
1887 # must generate a RunTime exception
1888 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001889 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001890
Ezio Melottiafd0d112009-07-15 17:17:17 +00001891 def test_bad_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001892 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001893 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001894 self.zip2.setpassword(b"perl")
1895 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001896
Ezio Melotti975077a2011-05-19 22:03:22 +03001897 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +00001898 def test_good_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001899 self.zip.setpassword(b"python")
Ezio Melotti35386712009-12-31 13:22:41 +00001900 self.assertEqual(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001901 self.zip2.setpassword(b"12345")
Ezio Melotti35386712009-12-31 13:22:41 +00001902 self.assertEqual(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001903
R. David Murray8d855d82010-12-21 21:53:37 +00001904 def test_unicode_password(self):
1905 self.assertRaises(TypeError, self.zip.setpassword, "unicode")
1906 self.assertRaises(TypeError, self.zip.read, "test.txt", "python")
1907 self.assertRaises(TypeError, self.zip.open, "test.txt", pwd="python")
1908 self.assertRaises(TypeError, self.zip.extract, "test.txt", pwd="python")
1909
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001910class AbstractTestsWithRandomBinaryFiles:
1911 @classmethod
1912 def setUpClass(cls):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001913 datacount = randint(16, 64)*1024 + randint(1, 1024)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001914 cls.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
1915 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001916
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001917 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001918 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +00001919 with open(TESTFN, "wb") as fp:
1920 fp.write(self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001921
1922 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001923 unlink(TESTFN)
1924 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001925
Ezio Melottiafd0d112009-07-15 17:17:17 +00001926 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001927 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001928 with zipfile.ZipFile(f, "w", compression) as zipfp:
1929 zipfp.write(TESTFN, "another.name")
1930 zipfp.write(TESTFN, TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001931
Ezio Melottiafd0d112009-07-15 17:17:17 +00001932 def zip_test(self, f, compression):
1933 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001934
1935 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001936 with zipfile.ZipFile(f, "r", compression) as zipfp:
1937 testdata = zipfp.read(TESTFN)
1938 self.assertEqual(len(testdata), len(self.data))
1939 self.assertEqual(testdata, self.data)
1940 self.assertEqual(zipfp.read("another.name"), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001941
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001942 def test_read(self):
1943 for f in get_files(self):
1944 self.zip_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001945
Ezio Melottiafd0d112009-07-15 17:17:17 +00001946 def zip_open_test(self, f, compression):
1947 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001948
1949 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001950 with zipfile.ZipFile(f, "r", compression) as zipfp:
1951 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001952 with zipfp.open(TESTFN) as zipopen1:
1953 while True:
1954 read_data = zipopen1.read(256)
1955 if not read_data:
1956 break
1957 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001958
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001959 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001960 with zipfp.open("another.name") as zipopen2:
1961 while True:
1962 read_data = zipopen2.read(256)
1963 if not read_data:
1964 break
1965 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001966
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001967 testdata1 = b''.join(zipdata1)
1968 self.assertEqual(len(testdata1), len(self.data))
1969 self.assertEqual(testdata1, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001970
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001971 testdata2 = b''.join(zipdata2)
Ezio Melotti35386712009-12-31 13:22:41 +00001972 self.assertEqual(len(testdata2), len(self.data))
1973 self.assertEqual(testdata2, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001974
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001975 def test_open(self):
1976 for f in get_files(self):
1977 self.zip_open_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001978
Ezio Melottiafd0d112009-07-15 17:17:17 +00001979 def zip_random_open_test(self, f, compression):
1980 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001981
1982 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001983 with zipfile.ZipFile(f, "r", compression) as zipfp:
1984 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001985 with zipfp.open(TESTFN) as zipopen1:
1986 while True:
1987 read_data = zipopen1.read(randint(1, 1024))
1988 if not read_data:
1989 break
1990 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001991
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001992 testdata = b''.join(zipdata1)
1993 self.assertEqual(len(testdata), len(self.data))
1994 self.assertEqual(testdata, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001995
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001996 def test_random_open(self):
1997 for f in get_files(self):
1998 self.zip_random_open_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001999
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00002000
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03002001class StoredTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
2002 unittest.TestCase):
2003 compression = zipfile.ZIP_STORED
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02002004
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03002005@requires_zlib
2006class DeflateTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
2007 unittest.TestCase):
2008 compression = zipfile.ZIP_DEFLATED
2009
2010@requires_bz2
2011class Bzip2TestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
2012 unittest.TestCase):
2013 compression = zipfile.ZIP_BZIP2
2014
2015@requires_lzma
2016class LzmaTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
2017 unittest.TestCase):
2018 compression = zipfile.ZIP_LZMA
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02002019
Ezio Melotti76430242009-07-11 18:28:48 +00002020
luzpaza5293b42017-11-05 07:37:50 -06002021# Provide the tell() method but not seek()
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02002022class Tellable:
2023 def __init__(self, fp):
2024 self.fp = fp
2025 self.offset = 0
2026
2027 def write(self, data):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02002028 n = self.fp.write(data)
2029 self.offset += n
2030 return n
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02002031
2032 def tell(self):
2033 return self.offset
2034
2035 def flush(self):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02002036 self.fp.flush()
2037
2038class Unseekable:
2039 def __init__(self, fp):
2040 self.fp = fp
2041
2042 def write(self, data):
2043 return self.fp.write(data)
2044
2045 def flush(self):
2046 self.fp.flush()
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02002047
2048class UnseekableTests(unittest.TestCase):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02002049 def test_writestr(self):
2050 for wrapper in (lambda f: f), Tellable, Unseekable:
2051 with self.subTest(wrapper=wrapper):
2052 f = io.BytesIO()
2053 f.write(b'abc')
2054 bf = io.BufferedWriter(f)
2055 with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) as zipfp:
2056 zipfp.writestr('ones', b'111')
2057 zipfp.writestr('twos', b'222')
2058 self.assertEqual(f.getvalue()[:5], b'abcPK')
2059 with zipfile.ZipFile(f, mode='r') as zipf:
2060 with zipf.open('ones') as zopen:
2061 self.assertEqual(zopen.read(), b'111')
2062 with zipf.open('twos') as zopen:
2063 self.assertEqual(zopen.read(), b'222')
2064
2065 def test_write(self):
2066 for wrapper in (lambda f: f), Tellable, Unseekable:
2067 with self.subTest(wrapper=wrapper):
2068 f = io.BytesIO()
2069 f.write(b'abc')
2070 bf = io.BufferedWriter(f)
2071 with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) as zipfp:
2072 self.addCleanup(unlink, TESTFN)
2073 with open(TESTFN, 'wb') as f2:
2074 f2.write(b'111')
2075 zipfp.write(TESTFN, 'ones')
2076 with open(TESTFN, 'wb') as f2:
2077 f2.write(b'222')
2078 zipfp.write(TESTFN, 'twos')
2079 self.assertEqual(f.getvalue()[:5], b'abcPK')
2080 with zipfile.ZipFile(f, mode='r') as zipf:
2081 with zipf.open('ones') as zopen:
2082 self.assertEqual(zopen.read(), b'111')
2083 with zipf.open('twos') as zopen:
2084 self.assertEqual(zopen.read(), b'222')
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02002085
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03002086 def test_open_write(self):
2087 for wrapper in (lambda f: f), Tellable, Unseekable:
2088 with self.subTest(wrapper=wrapper):
2089 f = io.BytesIO()
2090 f.write(b'abc')
2091 bf = io.BufferedWriter(f)
2092 with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) as zipf:
2093 with zipf.open('ones', 'w') as zopen:
2094 zopen.write(b'111')
2095 with zipf.open('twos', 'w') as zopen:
2096 zopen.write(b'222')
2097 self.assertEqual(f.getvalue()[:5], b'abcPK')
2098 with zipfile.ZipFile(f) as zipf:
2099 self.assertEqual(zipf.read('ones'), b'111')
2100 self.assertEqual(zipf.read('twos'), b'222')
2101
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02002102
Ezio Melotti975077a2011-05-19 22:03:22 +03002103@requires_zlib
Guido van Rossumd8faa362007-04-27 19:54:29 +00002104class TestsWithMultipleOpens(unittest.TestCase):
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02002105 @classmethod
2106 def setUpClass(cls):
2107 cls.data1 = b'111' + getrandbytes(10000)
2108 cls.data2 = b'222' + getrandbytes(10000)
2109
2110 def make_test_archive(self, f):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002111 # Create the ZIP archive
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02002112 with zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as zipfp:
2113 zipfp.writestr('ones', self.data1)
2114 zipfp.writestr('twos', self.data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002115
Ezio Melottiafd0d112009-07-15 17:17:17 +00002116 def test_same_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002117 # Verify that (when the ZipFile is in control of creating file objects)
2118 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02002119 for f in get_files(self):
2120 self.make_test_archive(f)
2121 with zipfile.ZipFile(f, mode="r") as zipf:
2122 with zipf.open('ones') as zopen1, zipf.open('ones') as zopen2:
2123 data1 = zopen1.read(500)
2124 data2 = zopen2.read(500)
2125 data1 += zopen1.read()
2126 data2 += zopen2.read()
2127 self.assertEqual(data1, data2)
2128 self.assertEqual(data1, self.data1)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002129
Ezio Melottiafd0d112009-07-15 17:17:17 +00002130 def test_different_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002131 # Verify that (when the ZipFile is in control of creating file objects)
2132 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02002133 for f in get_files(self):
2134 self.make_test_archive(f)
2135 with zipfile.ZipFile(f, mode="r") as zipf:
2136 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
2137 data1 = zopen1.read(500)
2138 data2 = zopen2.read(500)
2139 data1 += zopen1.read()
2140 data2 += zopen2.read()
2141 self.assertEqual(data1, self.data1)
2142 self.assertEqual(data2, self.data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002143
Ezio Melottiafd0d112009-07-15 17:17:17 +00002144 def test_interleaved(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002145 # Verify that (when the ZipFile is in control of creating file objects)
2146 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02002147 for f in get_files(self):
2148 self.make_test_archive(f)
2149 with zipfile.ZipFile(f, mode="r") as zipf:
Serhiy Storchakad76c7c22016-05-13 21:18:58 +03002150 with zipf.open('ones') as zopen1:
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02002151 data1 = zopen1.read(500)
Serhiy Storchakad76c7c22016-05-13 21:18:58 +03002152 with zipf.open('twos') as zopen2:
2153 data2 = zopen2.read(500)
2154 data1 += zopen1.read()
2155 data2 += zopen2.read()
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02002156 self.assertEqual(data1, self.data1)
2157 self.assertEqual(data2, self.data2)
2158
2159 def test_read_after_close(self):
2160 for f in get_files(self):
2161 self.make_test_archive(f)
2162 with contextlib.ExitStack() as stack:
2163 with zipfile.ZipFile(f, 'r') as zipf:
2164 zopen1 = stack.enter_context(zipf.open('ones'))
2165 zopen2 = stack.enter_context(zipf.open('twos'))
Brian Curtin8fb9b862010-11-18 02:15:28 +00002166 data1 = zopen1.read(500)
2167 data2 = zopen2.read(500)
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02002168 data1 += zopen1.read()
2169 data2 += zopen2.read()
2170 self.assertEqual(data1, self.data1)
2171 self.assertEqual(data2, self.data2)
2172
2173 def test_read_after_write(self):
2174 for f in get_files(self):
2175 with zipfile.ZipFile(f, 'w', zipfile.ZIP_DEFLATED) as zipf:
2176 zipf.writestr('ones', self.data1)
2177 zipf.writestr('twos', self.data2)
2178 with zipf.open('ones') as zopen1:
2179 data1 = zopen1.read(500)
2180 self.assertEqual(data1, self.data1[:500])
2181 with zipfile.ZipFile(f, 'r') as zipf:
2182 data1 = zipf.read('ones')
2183 data2 = zipf.read('twos')
2184 self.assertEqual(data1, self.data1)
2185 self.assertEqual(data2, self.data2)
2186
2187 def test_write_after_read(self):
2188 for f in get_files(self):
2189 with zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as zipf:
2190 zipf.writestr('ones', self.data1)
2191 with zipf.open('ones') as zopen1:
2192 zopen1.read(500)
2193 zipf.writestr('twos', self.data2)
2194 with zipfile.ZipFile(f, 'r') as zipf:
2195 data1 = zipf.read('ones')
2196 data2 = zipf.read('twos')
2197 self.assertEqual(data1, self.data1)
2198 self.assertEqual(data2, self.data2)
2199
2200 def test_many_opens(self):
2201 # Verify that read() and open() promptly close the file descriptor,
2202 # and don't rely on the garbage collector to free resources.
2203 self.make_test_archive(TESTFN2)
2204 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
2205 for x in range(100):
2206 zipf.read('ones')
2207 with zipf.open('ones') as zopen1:
2208 pass
2209 with open(os.devnull) as f:
2210 self.assertLess(f.fileno(), 100)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002211
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03002212 def test_write_while_reading(self):
2213 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_DEFLATED) as zipf:
2214 zipf.writestr('ones', self.data1)
2215 with zipfile.ZipFile(TESTFN2, 'a', zipfile.ZIP_DEFLATED) as zipf:
2216 with zipf.open('ones', 'r') as r1:
2217 data1 = r1.read(500)
2218 with zipf.open('twos', 'w') as w1:
2219 w1.write(self.data2)
2220 data1 += r1.read()
2221 self.assertEqual(data1, self.data1)
2222 with zipfile.ZipFile(TESTFN2) as zipf:
2223 self.assertEqual(zipf.read('twos'), self.data2)
2224
Guido van Rossumd8faa362007-04-27 19:54:29 +00002225 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00002226 unlink(TESTFN2)
2227
Guido van Rossumd8faa362007-04-27 19:54:29 +00002228
Martin v. Löwis59e47792009-01-24 14:10:07 +00002229class TestWithDirectory(unittest.TestCase):
2230 def setUp(self):
2231 os.mkdir(TESTFN2)
2232
Ezio Melottiafd0d112009-07-15 17:17:17 +00002233 def test_extract_dir(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00002234 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
2235 zipf.extractall(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00002236 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
2237 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
2238 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
2239
Ezio Melottiafd0d112009-07-15 17:17:17 +00002240 def test_bug_6050(self):
Martin v. Löwis70ccd162009-05-24 19:47:22 +00002241 # Extraction should succeed if directories already exist
2242 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottiafd0d112009-07-15 17:17:17 +00002243 self.test_extract_dir()
Martin v. Löwis70ccd162009-05-24 19:47:22 +00002244
Serhiy Storchaka46a34922014-09-23 22:40:23 +03002245 def test_write_dir(self):
2246 dirpath = os.path.join(TESTFN2, "x")
2247 os.mkdir(dirpath)
2248 mode = os.stat(dirpath).st_mode & 0xFFFF
2249 with zipfile.ZipFile(TESTFN, "w") as zipf:
2250 zipf.write(dirpath)
2251 zinfo = zipf.filelist[0]
2252 self.assertTrue(zinfo.filename.endswith("/x/"))
2253 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
2254 zipf.write(dirpath, "y")
2255 zinfo = zipf.filelist[1]
2256 self.assertTrue(zinfo.filename, "y/")
2257 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
2258 with zipfile.ZipFile(TESTFN, "r") as zipf:
2259 zinfo = zipf.filelist[0]
2260 self.assertTrue(zinfo.filename.endswith("/x/"))
2261 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
2262 zinfo = zipf.filelist[1]
2263 self.assertTrue(zinfo.filename, "y/")
2264 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
2265 target = os.path.join(TESTFN2, "target")
2266 os.mkdir(target)
2267 zipf.extractall(target)
2268 self.assertTrue(os.path.isdir(os.path.join(target, "y")))
2269 self.assertEqual(len(os.listdir(target)), 2)
2270
2271 def test_writestr_dir(self):
Martin v. Löwis59e47792009-01-24 14:10:07 +00002272 os.mkdir(os.path.join(TESTFN2, "x"))
Serhiy Storchaka46a34922014-09-23 22:40:23 +03002273 with zipfile.ZipFile(TESTFN, "w") as zipf:
2274 zipf.writestr("x/", b'')
2275 zinfo = zipf.filelist[0]
2276 self.assertEqual(zinfo.filename, "x/")
2277 self.assertEqual(zinfo.external_attr, (0o40775 << 16) | 0x10)
2278 with zipfile.ZipFile(TESTFN, "r") as zipf:
2279 zinfo = zipf.filelist[0]
2280 self.assertTrue(zinfo.filename.endswith("x/"))
2281 self.assertEqual(zinfo.external_attr, (0o40775 << 16) | 0x10)
2282 target = os.path.join(TESTFN2, "target")
2283 os.mkdir(target)
2284 zipf.extractall(target)
2285 self.assertTrue(os.path.isdir(os.path.join(target, "x")))
2286 self.assertEqual(os.listdir(target), ["x"])
Martin v. Löwis59e47792009-01-24 14:10:07 +00002287
2288 def tearDown(self):
Victor Stinner57004c62014-09-04 00:49:01 +02002289 rmtree(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00002290 if os.path.exists(TESTFN):
Ezio Melotti76430242009-07-11 18:28:48 +00002291 unlink(TESTFN)
Martin v. Löwis59e47792009-01-24 14:10:07 +00002292
Guido van Rossumd8faa362007-04-27 19:54:29 +00002293
Serhiy Storchaka503f9082016-02-08 00:02:25 +02002294class ZipInfoTests(unittest.TestCase):
2295 def test_from_file(self):
2296 zi = zipfile.ZipInfo.from_file(__file__)
2297 self.assertEqual(posixpath.basename(zi.filename), 'test_zipfile.py')
2298 self.assertFalse(zi.is_dir())
Serhiy Storchaka8606e952017-03-08 14:37:51 +02002299 self.assertEqual(zi.file_size, os.path.getsize(__file__))
2300
2301 def test_from_file_pathlike(self):
2302 zi = zipfile.ZipInfo.from_file(pathlib.Path(__file__))
2303 self.assertEqual(posixpath.basename(zi.filename), 'test_zipfile.py')
2304 self.assertFalse(zi.is_dir())
2305 self.assertEqual(zi.file_size, os.path.getsize(__file__))
2306
2307 def test_from_file_bytes(self):
2308 zi = zipfile.ZipInfo.from_file(os.fsencode(__file__), 'test')
2309 self.assertEqual(posixpath.basename(zi.filename), 'test')
2310 self.assertFalse(zi.is_dir())
2311 self.assertEqual(zi.file_size, os.path.getsize(__file__))
2312
2313 def test_from_file_fileno(self):
2314 with open(__file__, 'rb') as f:
2315 zi = zipfile.ZipInfo.from_file(f.fileno(), 'test')
2316 self.assertEqual(posixpath.basename(zi.filename), 'test')
2317 self.assertFalse(zi.is_dir())
2318 self.assertEqual(zi.file_size, os.path.getsize(__file__))
Serhiy Storchaka503f9082016-02-08 00:02:25 +02002319
2320 def test_from_dir(self):
2321 dirpath = os.path.dirname(os.path.abspath(__file__))
2322 zi = zipfile.ZipInfo.from_file(dirpath, 'stdlib_tests')
2323 self.assertEqual(zi.filename, 'stdlib_tests/')
2324 self.assertTrue(zi.is_dir())
2325 self.assertEqual(zi.compress_type, zipfile.ZIP_STORED)
2326 self.assertEqual(zi.file_size, 0)
2327
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002328
2329class CommandLineTest(unittest.TestCase):
2330
2331 def zipfilecmd(self, *args, **kwargs):
2332 rc, out, err = script_helper.assert_python_ok('-m', 'zipfile', *args,
2333 **kwargs)
2334 return out.replace(os.linesep.encode(), b'\n')
2335
2336 def zipfilecmd_failure(self, *args):
2337 return script_helper.assert_python_failure('-m', 'zipfile', *args)
2338
Serhiy Storchaka150cd192017-04-07 18:56:12 +03002339 def test_bad_use(self):
2340 rc, out, err = self.zipfilecmd_failure()
2341 self.assertEqual(out, b'')
2342 self.assertIn(b'usage', err.lower())
2343 self.assertIn(b'error', err.lower())
2344 self.assertIn(b'required', err.lower())
2345 rc, out, err = self.zipfilecmd_failure('-l', '')
2346 self.assertEqual(out, b'')
2347 self.assertNotEqual(err.strip(), b'')
2348
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002349 def test_test_command(self):
2350 zip_name = findfile('zipdir.zip')
Serhiy Storchaka8c933102016-10-23 13:32:12 +03002351 for opt in '-t', '--test':
2352 out = self.zipfilecmd(opt, zip_name)
2353 self.assertEqual(out.rstrip(), b'Done testing')
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002354 zip_name = findfile('testtar.tar')
2355 rc, out, err = self.zipfilecmd_failure('-t', zip_name)
2356 self.assertEqual(out, b'')
2357
2358 def test_list_command(self):
2359 zip_name = findfile('zipdir.zip')
2360 t = io.StringIO()
2361 with zipfile.ZipFile(zip_name, 'r') as tf:
2362 tf.printdir(t)
2363 expected = t.getvalue().encode('ascii', 'backslashreplace')
Serhiy Storchaka8c933102016-10-23 13:32:12 +03002364 for opt in '-l', '--list':
2365 out = self.zipfilecmd(opt, zip_name,
2366 PYTHONIOENCODING='ascii:backslashreplace')
2367 self.assertEqual(out, expected)
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002368
Serhiy Storchakab4293ef2016-10-23 22:32:30 +03002369 @requires_zlib
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002370 def test_create_command(self):
2371 self.addCleanup(unlink, TESTFN)
2372 with open(TESTFN, 'w') as f:
2373 f.write('test 1')
2374 os.mkdir(TESTFNDIR)
2375 self.addCleanup(rmtree, TESTFNDIR)
2376 with open(os.path.join(TESTFNDIR, 'file.txt'), 'w') as f:
2377 f.write('test 2')
2378 files = [TESTFN, TESTFNDIR]
2379 namelist = [TESTFN, TESTFNDIR + '/', TESTFNDIR + '/file.txt']
Serhiy Storchaka8c933102016-10-23 13:32:12 +03002380 for opt in '-c', '--create':
2381 try:
2382 out = self.zipfilecmd(opt, TESTFN2, *files)
2383 self.assertEqual(out, b'')
2384 with zipfile.ZipFile(TESTFN2) as zf:
2385 self.assertEqual(zf.namelist(), namelist)
2386 self.assertEqual(zf.read(namelist[0]), b'test 1')
2387 self.assertEqual(zf.read(namelist[2]), b'test 2')
2388 finally:
2389 unlink(TESTFN2)
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002390
2391 def test_extract_command(self):
2392 zip_name = findfile('zipdir.zip')
Serhiy Storchaka8c933102016-10-23 13:32:12 +03002393 for opt in '-e', '--extract':
2394 with temp_dir() as extdir:
2395 out = self.zipfilecmd(opt, zip_name, extdir)
2396 self.assertEqual(out, b'')
2397 with zipfile.ZipFile(zip_name) as zf:
2398 for zi in zf.infolist():
2399 path = os.path.join(extdir,
2400 zi.filename.replace('/', os.sep))
2401 if zi.is_dir():
2402 self.assertTrue(os.path.isdir(path))
2403 else:
2404 self.assertTrue(os.path.isfile(path))
2405 with open(path, 'rb') as f:
2406 self.assertEqual(f.read(), zf.read(zi))
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002407
Jason R. Coombsb2758ff2019-05-08 09:45:06 -04002408
2409# Poor man's technique to consume a (smallish) iterable.
2410consume = tuple
2411
2412
Miss Islington (bot)c410f382019-08-24 09:03:52 -07002413def add_dirs(zf):
Jason R. Coombsb2758ff2019-05-08 09:45:06 -04002414 """
Miss Islington (bot)c410f382019-08-24 09:03:52 -07002415 Given a writable zip file zf, inject directory entries for
Jason R. Coombsb2758ff2019-05-08 09:45:06 -04002416 any directories implied by the presence of children.
2417 """
Miss Islington (bot)c410f382019-08-24 09:03:52 -07002418 for name in zipfile.Path._implied_dirs(zf.namelist()):
2419 zf.writestr(name, b"")
2420 return zf
Jason R. Coombsb2758ff2019-05-08 09:45:06 -04002421
2422
Miss Islington (bot)c410f382019-08-24 09:03:52 -07002423def build_alpharep_fixture():
Jason R. Coombsb2758ff2019-05-08 09:45:06 -04002424 """
2425 Create a zip file with this structure:
2426
2427 .
2428 ├── a.txt
Miss Islington (bot)c410f382019-08-24 09:03:52 -07002429 ├── b
2430 │ ├── c.txt
2431 │ ├── d
2432 │ │ └── e.txt
2433 │ └── f.txt
2434 └── g
2435 └── h
2436 └── i.txt
2437
2438 This fixture has the following key characteristics:
2439
2440 - a file at the root (a)
2441 - a file two levels deep (b/d/e)
2442 - multiple files in a directory (b/c, b/f)
2443 - a directory containing only a directory (g/h)
2444
2445 "alpha" because it uses alphabet
2446 "rep" because it's a representative example
Jason R. Coombsb2758ff2019-05-08 09:45:06 -04002447 """
2448 data = io.BytesIO()
2449 zf = zipfile.ZipFile(data, "w")
2450 zf.writestr("a.txt", b"content of a")
2451 zf.writestr("b/c.txt", b"content of c")
2452 zf.writestr("b/d/e.txt", b"content of e")
Miss Islington (bot)c410f382019-08-24 09:03:52 -07002453 zf.writestr("b/f.txt", b"content of f")
2454 zf.writestr("g/h/i.txt", b"content of i")
2455 zf.filename = "alpharep.zip"
Jason R. Coombsb2758ff2019-05-08 09:45:06 -04002456 return zf
2457
2458
Miss Islington (bot)74b02912019-09-10 15:57:54 -07002459class TestExecutablePrependedZip(unittest.TestCase):
2460 """Test our ability to open zip files with an executable prepended."""
2461
2462 def setUp(self):
2463 self.exe_zip = findfile('exe_with_zip', subdir='ziptestdata')
2464 self.exe_zip64 = findfile('exe_with_z64', subdir='ziptestdata')
2465
2466 def _test_zip_works(self, name):
2467 # bpo-28494 sanity check: ensure is_zipfile works on these.
2468 self.assertTrue(zipfile.is_zipfile(name),
2469 f'is_zipfile failed on {name}')
2470 # Ensure we can operate on these via ZipFile.
2471 with zipfile.ZipFile(name) as zipfp:
2472 for n in zipfp.namelist():
2473 data = zipfp.read(n)
2474 self.assertIn(b'FAVORITE_NUMBER', data)
2475
2476 def test_read_zip_with_exe_prepended(self):
2477 self._test_zip_works(self.exe_zip)
2478
2479 def test_read_zip64_with_exe_prepended(self):
2480 self._test_zip_works(self.exe_zip64)
2481
2482 @unittest.skipUnless(sys.executable, 'sys.executable required.')
2483 @unittest.skipUnless(os.access('/bin/bash', os.X_OK),
2484 'Test relies on #!/bin/bash working.')
2485 def test_execute_zip2(self):
2486 output = subprocess.check_output([self.exe_zip, sys.executable])
2487 self.assertIn(b'number in executable: 5', output)
2488
2489 @unittest.skipUnless(sys.executable, 'sys.executable required.')
2490 @unittest.skipUnless(os.access('/bin/bash', os.X_OK),
2491 'Test relies on #!/bin/bash working.')
2492 def test_execute_zip64(self):
2493 output = subprocess.check_output([self.exe_zip64, sys.executable])
2494 self.assertIn(b'number in executable: 5', output)
2495
2496
Jason R. Coombsb2758ff2019-05-08 09:45:06 -04002497class TestPath(unittest.TestCase):
2498 def setUp(self):
2499 self.fixtures = contextlib.ExitStack()
2500 self.addCleanup(self.fixtures.close)
2501
Miss Islington (bot)c410f382019-08-24 09:03:52 -07002502 def zipfile_alpharep(self):
Jason R. Coombsb2758ff2019-05-08 09:45:06 -04002503 with self.subTest():
Miss Islington (bot)c410f382019-08-24 09:03:52 -07002504 yield build_alpharep_fixture()
Jason R. Coombsb2758ff2019-05-08 09:45:06 -04002505 with self.subTest():
Miss Islington (bot)c410f382019-08-24 09:03:52 -07002506 yield add_dirs(build_alpharep_fixture())
Jason R. Coombsb2758ff2019-05-08 09:45:06 -04002507
2508 def zipfile_ondisk(self):
2509 tmpdir = pathlib.Path(self.fixtures.enter_context(temp_dir()))
Miss Islington (bot)c410f382019-08-24 09:03:52 -07002510 for alpharep in self.zipfile_alpharep():
2511 buffer = alpharep.fp
2512 alpharep.close()
2513 path = tmpdir / alpharep.filename
Jason R. Coombsb2758ff2019-05-08 09:45:06 -04002514 with path.open("wb") as strm:
2515 strm.write(buffer.getvalue())
2516 yield path
2517
Miss Islington (bot)c410f382019-08-24 09:03:52 -07002518 def test_iterdir_and_types(self):
2519 for alpharep in self.zipfile_alpharep():
2520 root = zipfile.Path(alpharep)
Jason R. Coombsb2758ff2019-05-08 09:45:06 -04002521 assert root.is_dir()
Miss Islington (bot)c410f382019-08-24 09:03:52 -07002522 a, b, g = root.iterdir()
Jason R. Coombsb2758ff2019-05-08 09:45:06 -04002523 assert a.is_file()
2524 assert b.is_dir()
Miss Islington (bot)c410f382019-08-24 09:03:52 -07002525 assert g.is_dir()
2526 c, f, d = b.iterdir()
2527 assert c.is_file() and f.is_file()
Jason R. Coombsb2758ff2019-05-08 09:45:06 -04002528 e, = d.iterdir()
2529 assert e.is_file()
Miss Islington (bot)c410f382019-08-24 09:03:52 -07002530 h, = g.iterdir()
2531 i, = h.iterdir()
2532 assert i.is_file()
Jason R. Coombsb2758ff2019-05-08 09:45:06 -04002533
2534 def test_open(self):
Miss Islington (bot)c410f382019-08-24 09:03:52 -07002535 for alpharep in self.zipfile_alpharep():
2536 root = zipfile.Path(alpharep)
2537 a, b, g = root.iterdir()
Jason R. Coombsb2758ff2019-05-08 09:45:06 -04002538 with a.open() as strm:
2539 data = strm.read()
2540 assert data == b"content of a"
2541
2542 def test_read(self):
Miss Islington (bot)c410f382019-08-24 09:03:52 -07002543 for alpharep in self.zipfile_alpharep():
2544 root = zipfile.Path(alpharep)
2545 a, b, g = root.iterdir()
Jason R. Coombsb2758ff2019-05-08 09:45:06 -04002546 assert a.read_text() == "content of a"
2547 assert a.read_bytes() == b"content of a"
2548
Jason R. Coombs33e067d2019-05-09 11:34:36 -04002549 def test_joinpath(self):
Miss Islington (bot)c410f382019-08-24 09:03:52 -07002550 for alpharep in self.zipfile_alpharep():
2551 root = zipfile.Path(alpharep)
Jason R. Coombs33e067d2019-05-09 11:34:36 -04002552 a = root.joinpath("a")
2553 assert a.is_file()
2554 e = root.joinpath("b").joinpath("d").joinpath("e.txt")
2555 assert e.read_text() == "content of e"
2556
Jason R. Coombsb2758ff2019-05-08 09:45:06 -04002557 def test_traverse_truediv(self):
Miss Islington (bot)c410f382019-08-24 09:03:52 -07002558 for alpharep in self.zipfile_alpharep():
2559 root = zipfile.Path(alpharep)
Jason R. Coombsb2758ff2019-05-08 09:45:06 -04002560 a = root / "a"
2561 assert a.is_file()
2562 e = root / "b" / "d" / "e.txt"
2563 assert e.read_text() == "content of e"
2564
2565 def test_pathlike_construction(self):
2566 """
2567 zipfile.Path should be constructable from a path-like object
2568 """
2569 for zipfile_ondisk in self.zipfile_ondisk():
2570 pathlike = pathlib.Path(str(zipfile_ondisk))
2571 zipfile.Path(pathlike)
2572
2573 def test_traverse_pathlike(self):
Miss Islington (bot)c410f382019-08-24 09:03:52 -07002574 for alpharep in self.zipfile_alpharep():
2575 root = zipfile.Path(alpharep)
Jason R. Coombsb2758ff2019-05-08 09:45:06 -04002576 root / pathlib.Path("a")
2577
Jason R. Coombs33e067d2019-05-09 11:34:36 -04002578 def test_parent(self):
Miss Islington (bot)c410f382019-08-24 09:03:52 -07002579 for alpharep in self.zipfile_alpharep():
2580 root = zipfile.Path(alpharep)
Jason R. Coombs33e067d2019-05-09 11:34:36 -04002581 assert (root / 'a').parent.at == ''
2582 assert (root / 'a' / 'b').parent.at == 'a/'
2583
Miss Islington (bot)66905d12019-07-07 15:05:53 -07002584 def test_dir_parent(self):
Miss Islington (bot)c410f382019-08-24 09:03:52 -07002585 for alpharep in self.zipfile_alpharep():
2586 root = zipfile.Path(alpharep)
Miss Islington (bot)66905d12019-07-07 15:05:53 -07002587 assert (root / 'b').parent.at == ''
2588 assert (root / 'b/').parent.at == ''
2589
2590 def test_missing_dir_parent(self):
Miss Islington (bot)c410f382019-08-24 09:03:52 -07002591 for alpharep in self.zipfile_alpharep():
2592 root = zipfile.Path(alpharep)
Miss Islington (bot)66905d12019-07-07 15:05:53 -07002593 assert (root / 'missing dir/').parent.at == ''
2594
Miss Islington (bot)c410f382019-08-24 09:03:52 -07002595
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00002596if __name__ == "__main__":
Brett Cannond5b4e1d2013-06-12 19:57:19 -04002597 unittest.main()