blob: 3bc867ea51c946be7ed975676e7515a05a8228e7 [file] [log] [blame]
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001import contextlib
Ezio Melotti74c96ec2009-07-08 22:24:06 +00002import io
3import os
Brett Cannonb57a0852013-06-15 17:32:30 -04004import importlib.util
Serhiy Storchaka8606e952017-03-08 14:37:51 +02005import pathlib
Serhiy Storchaka503f9082016-02-08 00:02:25 +02006import posixpath
Ezio Melotti35386712009-12-31 13:22:41 +00007import time
Ezio Melotti74c96ec2009-07-08 22:24:06 +00008import struct
9import zipfile
10import unittest
11
Tim Petersa45cacf2004-08-20 03:47:14 +000012
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000013from tempfile import TemporaryFile
Serhiy Storchakafa6bc292013-07-22 21:00:11 +030014from random import randint, random, getrandbits
Tim Petersa19a1682001-03-29 04:36:09 +000015
Serhiy Storchaka61c4c442016-10-23 13:07:59 +030016from test.support import script_helper
Serhiy Storchaka8606e952017-03-08 14:37:51 +020017from test.support import (TESTFN, findfile, unlink, rmtree, temp_dir, temp_cwd,
Serhiy Storchakac5b75db2013-01-29 20:14:08 +020018 requires_zlib, requires_bz2, requires_lzma,
Victor Stinnerd6debb22017-03-27 16:05:26 +020019 captured_stdout)
Guido van Rossum368f04a2000-04-10 13:23:04 +000020
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000021TESTFN2 = TESTFN + "2"
Martin v. Löwis59e47792009-01-24 14:10:07 +000022TESTFNDIR = TESTFN + "d"
Guido van Rossumb5a755e2007-07-18 18:15:48 +000023FIXEDTEST_SIZE = 1000
Georg Brandl5ba11de2011-01-01 10:09:32 +000024DATAFILES_DIR = 'zipfile_datafiles'
Guido van Rossum368f04a2000-04-10 13:23:04 +000025
Christian Heimes790c8232008-01-07 21:14:23 +000026SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'),
27 ('ziptest2dir/_ziptest2', 'qawsedrftg'),
Gregory P. Smithb47acbf2013-02-01 11:22:43 -080028 ('ziptest2dir/ziptest3dir/_ziptest3', 'azsxdcfvgb'),
Christian Heimes790c8232008-01-07 21:14:23 +000029 ('ziptest2dir/ziptest3dir/ziptest4dir/_ziptest3', '6y7u8i9o0p')]
30
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +020031def getrandbytes(size):
32 return getrandbits(8 * size).to_bytes(size, 'little')
33
Serhiy Storchakafa6bc292013-07-22 21:00:11 +030034def get_files(test):
35 yield TESTFN2
36 with TemporaryFile() as f:
37 yield f
38 test.assertFalse(f.closed)
39 with io.BytesIO() as f:
40 yield f
41 test.assertFalse(f.closed)
Ezio Melotti76430242009-07-11 18:28:48 +000042
Serhiy Storchakafa6bc292013-07-22 21:00:11 +030043class AbstractTestsWithSourceFile:
44 @classmethod
45 def setUpClass(cls):
46 cls.line_gen = [bytes("Zipfile test line %d. random float: %f\n" %
47 (i, random()), "ascii")
48 for i in range(FIXEDTEST_SIZE)]
49 cls.data = b''.join(cls.line_gen)
50
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000051 def setUp(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000052 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +000053 with open(TESTFN, "wb") as fp:
54 fp.write(self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000055
Ezio Melottiafd0d112009-07-15 17:17:17 +000056 def make_test_archive(self, f, compression):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000057 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000058 with zipfile.ZipFile(f, "w", compression) as zipfp:
59 zipfp.write(TESTFN, "another.name")
60 zipfp.write(TESTFN, TESTFN)
61 zipfp.writestr("strfile", self.data)
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +030062 with zipfp.open('written-open-w', mode='w') as f:
63 for line in self.line_gen:
64 f.write(line)
Tim Peters7d3bad62001-04-04 18:56:49 +000065
Ezio Melottiafd0d112009-07-15 17:17:17 +000066 def zip_test(self, f, compression):
67 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +000068
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000069 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000070 with zipfile.ZipFile(f, "r", compression) as zipfp:
71 self.assertEqual(zipfp.read(TESTFN), self.data)
72 self.assertEqual(zipfp.read("another.name"), self.data)
73 self.assertEqual(zipfp.read("strfile"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000074
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000075 # Print the ZIP directory
76 fp = io.StringIO()
77 zipfp.printdir(file=fp)
78 directory = fp.getvalue()
79 lines = directory.splitlines()
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +030080 self.assertEqual(len(lines), 5) # Number of files + header
Thomas Wouters0e3f5912006-08-11 14:57:12 +000081
Benjamin Peterson577473f2010-01-19 00:09:57 +000082 self.assertIn('File Name', lines[0])
83 self.assertIn('Modified', lines[0])
84 self.assertIn('Size', lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +000085
Ezio Melotti35386712009-12-31 13:22:41 +000086 fn, date, time_, size = lines[1].split()
87 self.assertEqual(fn, 'another.name')
88 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
89 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
90 self.assertEqual(size, str(len(self.data)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000091
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000092 # Check the namelist
93 names = zipfp.namelist()
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +030094 self.assertEqual(len(names), 4)
Benjamin Peterson577473f2010-01-19 00:09:57 +000095 self.assertIn(TESTFN, names)
96 self.assertIn("another.name", names)
97 self.assertIn("strfile", names)
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +030098 self.assertIn("written-open-w", names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000099
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000100 # Check infolist
101 infos = zipfp.infolist()
Ezio Melotti35386712009-12-31 13:22:41 +0000102 names = [i.filename for i in infos]
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300103 self.assertEqual(len(names), 4)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000104 self.assertIn(TESTFN, names)
105 self.assertIn("another.name", names)
106 self.assertIn("strfile", names)
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300107 self.assertIn("written-open-w", names)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000108 for i in infos:
Ezio Melotti35386712009-12-31 13:22:41 +0000109 self.assertEqual(i.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000110
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000111 # check getinfo
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300112 for nm in (TESTFN, "another.name", "strfile", "written-open-w"):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000113 info = zipfp.getinfo(nm)
Ezio Melotti35386712009-12-31 13:22:41 +0000114 self.assertEqual(info.filename, nm)
115 self.assertEqual(info.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000116
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000117 # Check that testzip doesn't raise an exception
118 zipfp.testzip()
Tim Peters7d3bad62001-04-04 18:56:49 +0000119
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300120 def test_basic(self):
121 for f in get_files(self):
122 self.zip_test(f, self.compression)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000123
Ezio Melottiafd0d112009-07-15 17:17:17 +0000124 def zip_open_test(self, f, compression):
125 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000126
127 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000128 with zipfile.ZipFile(f, "r", compression) as zipfp:
129 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000130 with zipfp.open(TESTFN) as zipopen1:
131 while True:
132 read_data = zipopen1.read(256)
133 if not read_data:
134 break
135 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000136
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000137 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000138 with zipfp.open("another.name") as zipopen2:
139 while True:
140 read_data = zipopen2.read(256)
141 if not read_data:
142 break
143 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000144
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000145 self.assertEqual(b''.join(zipdata1), self.data)
146 self.assertEqual(b''.join(zipdata2), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000147
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300148 def test_open(self):
149 for f in get_files(self):
150 self.zip_open_test(f, self.compression)
Georg Brandlb533e262008-05-25 18:19:30 +0000151
Serhiy Storchaka8606e952017-03-08 14:37:51 +0200152 def test_open_with_pathlike(self):
153 path = pathlib.Path(TESTFN2)
154 self.zip_open_test(path, self.compression)
155 with zipfile.ZipFile(path, "r", self.compression) as zipfp:
156 self.assertIsInstance(zipfp.filename, str)
157
Ezio Melottiafd0d112009-07-15 17:17:17 +0000158 def zip_random_open_test(self, f, compression):
159 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000160
161 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000162 with zipfile.ZipFile(f, "r", compression) as zipfp:
163 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000164 with zipfp.open(TESTFN) as zipopen1:
165 while True:
166 read_data = zipopen1.read(randint(1, 1024))
167 if not read_data:
168 break
169 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000170
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000171 self.assertEqual(b''.join(zipdata1), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000172
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300173 def test_random_open(self):
174 for f in get_files(self):
175 self.zip_random_open_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000176
Serhiy Storchakad2c07a52013-09-27 22:11:57 +0300177 def zip_read1_test(self, f, compression):
178 self.make_test_archive(f, compression)
179
180 # Read the ZIP archive
181 with zipfile.ZipFile(f, "r") as zipfp, \
182 zipfp.open(TESTFN) as zipopen:
183 zipdata = []
184 while True:
185 read_data = zipopen.read1(-1)
186 if not read_data:
187 break
188 zipdata.append(read_data)
189
190 self.assertEqual(b''.join(zipdata), self.data)
191
192 def test_read1(self):
193 for f in get_files(self):
194 self.zip_read1_test(f, self.compression)
195
196 def zip_read1_10_test(self, f, compression):
197 self.make_test_archive(f, compression)
198
199 # Read the ZIP archive
200 with zipfile.ZipFile(f, "r") as zipfp, \
201 zipfp.open(TESTFN) as zipopen:
202 zipdata = []
203 while True:
204 read_data = zipopen.read1(10)
205 self.assertLessEqual(len(read_data), 10)
206 if not read_data:
207 break
208 zipdata.append(read_data)
209
210 self.assertEqual(b''.join(zipdata), self.data)
211
212 def test_read1_10(self):
213 for f in get_files(self):
214 self.zip_read1_10_test(f, self.compression)
215
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000216 def zip_readline_read_test(self, f, compression):
217 self.make_test_archive(f, compression)
218
219 # Read the ZIP archive
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300220 with zipfile.ZipFile(f, "r") as zipfp, \
221 zipfp.open(TESTFN) as zipopen:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000222 data = b''
223 while True:
224 read = zipopen.readline()
225 if not read:
226 break
227 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000228
Brian Curtin8fb9b862010-11-18 02:15:28 +0000229 read = zipopen.read(100)
230 if not read:
231 break
232 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000233
234 self.assertEqual(data, self.data)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300235
236 def test_readline_read(self):
237 # Issue #7610: calls to readline() interleaved with calls to read().
238 for f in get_files(self):
239 self.zip_readline_read_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000240
Ezio Melottiafd0d112009-07-15 17:17:17 +0000241 def zip_readline_test(self, f, compression):
242 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000243
244 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000245 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000246 with zipfp.open(TESTFN) as zipopen:
247 for line in self.line_gen:
248 linedata = zipopen.readline()
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300249 self.assertEqual(linedata, line)
250
251 def test_readline(self):
252 for f in get_files(self):
253 self.zip_readline_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000254
Ezio Melottiafd0d112009-07-15 17:17:17 +0000255 def zip_readlines_test(self, f, compression):
256 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000257
258 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000259 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000260 with zipfp.open(TESTFN) as zipopen:
261 ziplines = zipopen.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000262 for line, zipline in zip(self.line_gen, ziplines):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300263 self.assertEqual(zipline, line)
264
265 def test_readlines(self):
266 for f in get_files(self):
267 self.zip_readlines_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000268
Ezio Melottiafd0d112009-07-15 17:17:17 +0000269 def zip_iterlines_test(self, f, compression):
270 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000271
272 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000273 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000274 with zipfp.open(TESTFN) as zipopen:
275 for line, zipline in zip(self.line_gen, zipopen):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300276 self.assertEqual(zipline, line)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000277
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300278 def test_iterlines(self):
279 for f in get_files(self):
280 self.zip_iterlines_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000281
Ezio Melottiafd0d112009-07-15 17:17:17 +0000282 def test_low_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000283 """Check for cases where compressed data is larger than original."""
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000284 # Create the ZIP archive
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300285 with zipfile.ZipFile(TESTFN2, "w", self.compression) as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000286 zipfp.writestr("strfile", '12')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000287
288 # Get an open object for strfile
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300289 with zipfile.ZipFile(TESTFN2, "r", self.compression) as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000290 with zipfp.open("strfile") as openobj:
291 self.assertEqual(openobj.read(1), b'1')
292 self.assertEqual(openobj.read(1), b'2')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000293
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300294 def test_writestr_compression(self):
295 zipfp = zipfile.ZipFile(TESTFN2, "w")
296 zipfp.writestr("b.txt", "hello world", compress_type=self.compression)
297 info = zipfp.getinfo('b.txt')
298 self.assertEqual(info.compress_type, self.compression)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200299
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300300 def test_read_return_size(self):
301 # Issue #9837: ZipExtFile.read() shouldn't return more bytes
302 # than requested.
303 for test_size in (1, 4095, 4096, 4097, 16384):
304 file_size = test_size + 1
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +0200305 junk = getrandbytes(file_size)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300306 with zipfile.ZipFile(io.BytesIO(), "w", self.compression) as zipf:
307 zipf.writestr('foo', junk)
308 with zipf.open('foo', 'r') as fp:
309 buf = fp.read(test_size)
310 self.assertEqual(len(buf), test_size)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200311
Serhiy Storchaka5ce3f102014-01-09 14:50:20 +0200312 def test_truncated_zipfile(self):
313 fp = io.BytesIO()
314 with zipfile.ZipFile(fp, mode='w') as zipf:
315 zipf.writestr('strfile', self.data, compress_type=self.compression)
316 end_offset = fp.tell()
317 zipfiledata = fp.getvalue()
318
319 fp = io.BytesIO(zipfiledata)
320 with zipfile.ZipFile(fp) as zipf:
321 with zipf.open('strfile') as zipopen:
322 fp.truncate(end_offset - 20)
323 with self.assertRaises(EOFError):
324 zipopen.read()
325
326 fp = io.BytesIO(zipfiledata)
327 with zipfile.ZipFile(fp) as zipf:
328 with zipf.open('strfile') as zipopen:
329 fp.truncate(end_offset - 20)
330 with self.assertRaises(EOFError):
331 while zipopen.read(100):
332 pass
333
334 fp = io.BytesIO(zipfiledata)
335 with zipfile.ZipFile(fp) as zipf:
336 with zipf.open('strfile') as zipopen:
337 fp.truncate(end_offset - 20)
338 with self.assertRaises(EOFError):
339 while zipopen.read1(100):
340 pass
341
Serhiy Storchaka51a43702014-10-29 22:42:06 +0200342 def test_repr(self):
343 fname = 'file.name'
344 for f in get_files(self):
345 with zipfile.ZipFile(f, 'w', self.compression) as zipfp:
346 zipfp.write(TESTFN, fname)
347 r = repr(zipfp)
348 self.assertIn("mode='w'", r)
349
350 with zipfile.ZipFile(f, 'r') as zipfp:
351 r = repr(zipfp)
352 if isinstance(f, str):
353 self.assertIn('filename=%r' % f, r)
354 else:
355 self.assertIn('file=%r' % f, r)
356 self.assertIn("mode='r'", r)
357 r = repr(zipfp.getinfo(fname))
358 self.assertIn('filename=%r' % fname, r)
359 self.assertIn('filemode=', r)
360 self.assertIn('file_size=', r)
361 if self.compression != zipfile.ZIP_STORED:
362 self.assertIn('compress_type=', r)
363 self.assertIn('compress_size=', r)
364 with zipfp.open(fname) as zipopen:
365 r = repr(zipopen)
366 self.assertIn('name=%r' % fname, r)
367 self.assertIn("mode='r'", r)
368 if self.compression != zipfile.ZIP_STORED:
369 self.assertIn('compress_type=', r)
370 self.assertIn('[closed]', repr(zipopen))
371 self.assertIn('[closed]', repr(zipfp))
372
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300373 def tearDown(self):
374 unlink(TESTFN)
375 unlink(TESTFN2)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200376
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200377
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300378class StoredTestsWithSourceFile(AbstractTestsWithSourceFile,
379 unittest.TestCase):
380 compression = zipfile.ZIP_STORED
381 test_low_compression = None
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200382
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300383 def zip_test_writestr_permissions(self, f, compression):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300384 # Make sure that writestr and open(... mode='w') create files with
385 # mode 0600, when they are passed a name rather than a ZipInfo
386 # instance.
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200387
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300388 self.make_test_archive(f, compression)
389 with zipfile.ZipFile(f, "r") as zipfp:
390 zinfo = zipfp.getinfo('strfile')
391 self.assertEqual(zinfo.external_attr, 0o600 << 16)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200392
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300393 zinfo2 = zipfp.getinfo('written-open-w')
394 self.assertEqual(zinfo2.external_attr, 0o600 << 16)
395
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300396 def test_writestr_permissions(self):
397 for f in get_files(self):
398 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +0200399
Ezio Melottiafd0d112009-07-15 17:17:17 +0000400 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000401 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
402 zipfp.write(TESTFN, "/absolute")
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000403
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000404 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
405 self.assertEqual(zipfp.namelist(), ["absolute"])
Tim Peters32cbc962006-02-20 21:42:18 +0000406
Ezio Melottiafd0d112009-07-15 17:17:17 +0000407 def test_append_to_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000408 """Test appending to an existing zipfile."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000409 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
410 zipfp.write(TESTFN, TESTFN)
411
412 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
413 zipfp.writestr("strfile", self.data)
414 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000415
Ezio Melottiafd0d112009-07-15 17:17:17 +0000416 def test_append_to_non_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000417 """Test appending to an existing file that is not a zipfile."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000418 # NOTE: this test fails if len(d) < 22 because of the first
419 # line "fpin.seek(-22, 2)" in _EndRecData
Ezio Melotti35386712009-12-31 13:22:41 +0000420 data = b'I am not a ZipFile!'*10
421 with open(TESTFN2, 'wb') as f:
422 f.write(data)
423
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000424 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
425 zipfp.write(TESTFN, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000426
Ezio Melotti35386712009-12-31 13:22:41 +0000427 with open(TESTFN2, 'rb') as f:
428 f.seek(len(data))
429 with zipfile.ZipFile(f, "r") as zipfp:
430 self.assertEqual(zipfp.namelist(), [TESTFN])
Serhiy Storchaka8793b212016-10-07 22:20:50 +0300431 self.assertEqual(zipfp.read(TESTFN), self.data)
432 with open(TESTFN2, 'rb') as f:
433 self.assertEqual(f.read(len(data)), data)
434 zipfiledata = f.read()
435 with io.BytesIO(zipfiledata) as bio, zipfile.ZipFile(bio) as zipfp:
436 self.assertEqual(zipfp.namelist(), [TESTFN])
437 self.assertEqual(zipfp.read(TESTFN), self.data)
438
439 def test_read_concatenated_zip_file(self):
440 with io.BytesIO() as bio:
441 with zipfile.ZipFile(bio, 'w', zipfile.ZIP_STORED) as zipfp:
442 zipfp.write(TESTFN, TESTFN)
443 zipfiledata = bio.getvalue()
444 data = b'I am not a ZipFile!'*10
445 with open(TESTFN2, 'wb') as f:
446 f.write(data)
447 f.write(zipfiledata)
448
449 with zipfile.ZipFile(TESTFN2) as zipfp:
450 self.assertEqual(zipfp.namelist(), [TESTFN])
451 self.assertEqual(zipfp.read(TESTFN), self.data)
452
453 def test_append_to_concatenated_zip_file(self):
454 with io.BytesIO() as bio:
455 with zipfile.ZipFile(bio, 'w', zipfile.ZIP_STORED) as zipfp:
456 zipfp.write(TESTFN, TESTFN)
457 zipfiledata = bio.getvalue()
458 data = b'I am not a ZipFile!'*1000000
459 with open(TESTFN2, 'wb') as f:
460 f.write(data)
461 f.write(zipfiledata)
462
463 with zipfile.ZipFile(TESTFN2, 'a') as zipfp:
464 self.assertEqual(zipfp.namelist(), [TESTFN])
465 zipfp.writestr('strfile', self.data)
466
467 with open(TESTFN2, 'rb') as f:
468 self.assertEqual(f.read(len(data)), data)
469 zipfiledata = f.read()
470 with io.BytesIO(zipfiledata) as bio, zipfile.ZipFile(bio) as zipfp:
471 self.assertEqual(zipfp.namelist(), [TESTFN, 'strfile'])
472 self.assertEqual(zipfp.read(TESTFN), self.data)
473 self.assertEqual(zipfp.read('strfile'), self.data)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000474
R David Murray4fbb9db2011-06-09 15:50:51 -0400475 def test_ignores_newline_at_end(self):
476 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
477 zipfp.write(TESTFN, TESTFN)
478 with open(TESTFN2, 'a') as f:
479 f.write("\r\n\00\00\00")
480 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
481 self.assertIsInstance(zipfp, zipfile.ZipFile)
482
483 def test_ignores_stuff_appended_past_comments(self):
484 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
485 zipfp.comment = b"this is a comment"
486 zipfp.write(TESTFN, TESTFN)
487 with open(TESTFN2, 'a') as f:
488 f.write("abcdef\r\n")
489 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
490 self.assertIsInstance(zipfp, zipfile.ZipFile)
491 self.assertEqual(zipfp.comment, b"this is a comment")
492
Ezio Melottiafd0d112009-07-15 17:17:17 +0000493 def test_write_default_name(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000494 """Check that calling ZipFile.write without arcname specified
495 produces the expected result."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000496 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
497 zipfp.write(TESTFN)
Brian Curtin8fb9b862010-11-18 02:15:28 +0000498 with open(TESTFN, "rb") as f:
499 self.assertEqual(zipfp.read(TESTFN), f.read())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000500
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300501 def test_write_to_readonly(self):
502 """Check that trying to call write() on a readonly ZipFile object
Serhiy Storchakab0d497c2016-09-10 21:28:07 +0300503 raises a ValueError."""
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300504 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
505 zipfp.writestr("somefile.txt", "bogus")
506
507 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
Serhiy Storchakab0d497c2016-09-10 21:28:07 +0300508 self.assertRaises(ValueError, zipfp.write, TESTFN)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300509
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300510 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
Serhiy Storchakab0d497c2016-09-10 21:28:07 +0300511 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300512 zipfp.open(TESTFN, mode='w')
513
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300514 def test_add_file_before_1980(self):
515 # Set atime and mtime to 1970-01-01
516 os.utime(TESTFN, (0, 0))
517 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
518 self.assertRaises(ValueError, zipfp.write, TESTFN)
519
Serhiy Storchaka5ce3f102014-01-09 14:50:20 +0200520
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300521@requires_zlib
522class DeflateTestsWithSourceFile(AbstractTestsWithSourceFile,
523 unittest.TestCase):
524 compression = zipfile.ZIP_DEFLATED
525
Ezio Melottiafd0d112009-07-15 17:17:17 +0000526 def test_per_file_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000527 """Check that files within a Zip archive can have different
528 compression options."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000529 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
530 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
531 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
532 sinfo = zipfp.getinfo('storeme')
533 dinfo = zipfp.getinfo('deflateme')
534 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
535 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000536
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300537@requires_bz2
538class Bzip2TestsWithSourceFile(AbstractTestsWithSourceFile,
539 unittest.TestCase):
540 compression = zipfile.ZIP_BZIP2
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000541
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300542@requires_lzma
543class LzmaTestsWithSourceFile(AbstractTestsWithSourceFile,
544 unittest.TestCase):
545 compression = zipfile.ZIP_LZMA
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000546
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300547
548class AbstractTestZip64InSmallFiles:
549 # These tests test the ZIP64 functionality without using large files,
550 # see test_zipfile64 for proper tests.
551
552 @classmethod
553 def setUpClass(cls):
554 line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
555 for i in range(0, FIXEDTEST_SIZE))
556 cls.data = b'\n'.join(line_gen)
557
558 def setUp(self):
559 self._limit = zipfile.ZIP64_LIMIT
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300560 self._filecount_limit = zipfile.ZIP_FILECOUNT_LIMIT
561 zipfile.ZIP64_LIMIT = 1000
562 zipfile.ZIP_FILECOUNT_LIMIT = 9
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300563
564 # Make a source file with some lines
565 with open(TESTFN, "wb") as fp:
566 fp.write(self.data)
567
568 def zip_test(self, f, compression):
569 # Create the ZIP archive
570 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
571 zipfp.write(TESTFN, "another.name")
572 zipfp.write(TESTFN, TESTFN)
573 zipfp.writestr("strfile", self.data)
574
575 # Read the ZIP archive
576 with zipfile.ZipFile(f, "r", compression) as zipfp:
577 self.assertEqual(zipfp.read(TESTFN), self.data)
578 self.assertEqual(zipfp.read("another.name"), self.data)
579 self.assertEqual(zipfp.read("strfile"), self.data)
580
581 # Print the ZIP directory
582 fp = io.StringIO()
583 zipfp.printdir(fp)
584
585 directory = fp.getvalue()
586 lines = directory.splitlines()
587 self.assertEqual(len(lines), 4) # Number of files + header
588
589 self.assertIn('File Name', lines[0])
590 self.assertIn('Modified', lines[0])
591 self.assertIn('Size', lines[0])
592
593 fn, date, time_, size = lines[1].split()
594 self.assertEqual(fn, 'another.name')
595 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
596 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
597 self.assertEqual(size, str(len(self.data)))
598
599 # Check the namelist
600 names = zipfp.namelist()
601 self.assertEqual(len(names), 3)
602 self.assertIn(TESTFN, names)
603 self.assertIn("another.name", names)
604 self.assertIn("strfile", names)
605
606 # Check infolist
607 infos = zipfp.infolist()
608 names = [i.filename for i in infos]
609 self.assertEqual(len(names), 3)
610 self.assertIn(TESTFN, names)
611 self.assertIn("another.name", names)
612 self.assertIn("strfile", names)
613 for i in infos:
614 self.assertEqual(i.file_size, len(self.data))
615
616 # check getinfo
617 for nm in (TESTFN, "another.name", "strfile"):
618 info = zipfp.getinfo(nm)
619 self.assertEqual(info.filename, nm)
620 self.assertEqual(info.file_size, len(self.data))
621
622 # Check that testzip doesn't raise an exception
623 zipfp.testzip()
624
625 def test_basic(self):
626 for f in get_files(self):
627 self.zip_test(f, self.compression)
628
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300629 def test_too_many_files(self):
630 # This test checks that more than 64k files can be added to an archive,
631 # and that the resulting archive can be read properly by ZipFile
632 zipf = zipfile.ZipFile(TESTFN, "w", self.compression,
633 allowZip64=True)
634 zipf.debug = 100
635 numfiles = 15
636 for i in range(numfiles):
637 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
638 self.assertEqual(len(zipf.namelist()), numfiles)
639 zipf.close()
640
641 zipf2 = zipfile.ZipFile(TESTFN, "r", self.compression)
642 self.assertEqual(len(zipf2.namelist()), numfiles)
643 for i in range(numfiles):
644 content = zipf2.read("foo%08d" % i).decode('ascii')
645 self.assertEqual(content, "%d" % (i**3 % 57))
646 zipf2.close()
647
648 def test_too_many_files_append(self):
649 zipf = zipfile.ZipFile(TESTFN, "w", self.compression,
650 allowZip64=False)
651 zipf.debug = 100
652 numfiles = 9
653 for i in range(numfiles):
654 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
655 self.assertEqual(len(zipf.namelist()), numfiles)
656 with self.assertRaises(zipfile.LargeZipFile):
657 zipf.writestr("foo%08d" % numfiles, b'')
658 self.assertEqual(len(zipf.namelist()), numfiles)
659 zipf.close()
660
661 zipf = zipfile.ZipFile(TESTFN, "a", self.compression,
662 allowZip64=False)
663 zipf.debug = 100
664 self.assertEqual(len(zipf.namelist()), numfiles)
665 with self.assertRaises(zipfile.LargeZipFile):
666 zipf.writestr("foo%08d" % numfiles, b'')
667 self.assertEqual(len(zipf.namelist()), numfiles)
668 zipf.close()
669
670 zipf = zipfile.ZipFile(TESTFN, "a", self.compression,
671 allowZip64=True)
672 zipf.debug = 100
673 self.assertEqual(len(zipf.namelist()), numfiles)
674 numfiles2 = 15
675 for i in range(numfiles, numfiles2):
676 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
677 self.assertEqual(len(zipf.namelist()), numfiles2)
678 zipf.close()
679
680 zipf2 = zipfile.ZipFile(TESTFN, "r", self.compression)
681 self.assertEqual(len(zipf2.namelist()), numfiles2)
682 for i in range(numfiles2):
683 content = zipf2.read("foo%08d" % i).decode('ascii')
684 self.assertEqual(content, "%d" % (i**3 % 57))
685 zipf2.close()
686
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300687 def tearDown(self):
688 zipfile.ZIP64_LIMIT = self._limit
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300689 zipfile.ZIP_FILECOUNT_LIMIT = self._filecount_limit
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300690 unlink(TESTFN)
691 unlink(TESTFN2)
692
693
694class StoredTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
695 unittest.TestCase):
696 compression = zipfile.ZIP_STORED
697
698 def large_file_exception_test(self, f, compression):
Serhiy Storchaka235c5e02013-11-23 15:55:38 +0200699 with zipfile.ZipFile(f, "w", compression, allowZip64=False) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300700 self.assertRaises(zipfile.LargeZipFile,
701 zipfp.write, TESTFN, "another.name")
702
703 def large_file_exception_test2(self, f, compression):
Serhiy Storchaka235c5e02013-11-23 15:55:38 +0200704 with zipfile.ZipFile(f, "w", compression, allowZip64=False) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300705 self.assertRaises(zipfile.LargeZipFile,
706 zipfp.writestr, "another.name", self.data)
707
708 def test_large_file_exception(self):
709 for f in get_files(self):
710 self.large_file_exception_test(f, zipfile.ZIP_STORED)
711 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
712
713 def test_absolute_arcnames(self):
714 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
715 allowZip64=True) as zipfp:
716 zipfp.write(TESTFN, "/absolute")
717
718 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
719 self.assertEqual(zipfp.namelist(), ["absolute"])
720
721@requires_zlib
722class DeflateTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
723 unittest.TestCase):
724 compression = zipfile.ZIP_DEFLATED
725
726@requires_bz2
727class Bzip2TestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
728 unittest.TestCase):
729 compression = zipfile.ZIP_BZIP2
730
731@requires_lzma
732class LzmaTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
733 unittest.TestCase):
734 compression = zipfile.ZIP_LZMA
735
736
Serhiy Storchaka4c0d9ea2017-04-12 16:03:23 +0300737class AbstractWriterTests:
738
739 def tearDown(self):
740 unlink(TESTFN2)
741
742 def test_close_after_close(self):
743 data = b'content'
744 with zipfile.ZipFile(TESTFN2, "w", self.compression) as zipf:
745 w = zipf.open('test', 'w')
746 w.write(data)
747 w.close()
748 self.assertTrue(w.closed)
749 w.close()
750 self.assertTrue(w.closed)
751 self.assertEqual(zipf.read('test'), data)
752
753 def test_write_after_close(self):
754 data = b'content'
755 with zipfile.ZipFile(TESTFN2, "w", self.compression) as zipf:
756 w = zipf.open('test', 'w')
757 w.write(data)
758 w.close()
759 self.assertTrue(w.closed)
760 self.assertRaises(ValueError, w.write, b'')
761 self.assertEqual(zipf.read('test'), data)
762
763class StoredWriterTests(AbstractWriterTests, unittest.TestCase):
764 compression = zipfile.ZIP_STORED
765
766@requires_zlib
767class DeflateWriterTests(AbstractWriterTests, unittest.TestCase):
768 compression = zipfile.ZIP_DEFLATED
769
770@requires_bz2
771class Bzip2WriterTests(AbstractWriterTests, unittest.TestCase):
772 compression = zipfile.ZIP_BZIP2
773
774@requires_lzma
775class LzmaWriterTests(AbstractWriterTests, unittest.TestCase):
776 compression = zipfile.ZIP_LZMA
777
778
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300779class PyZipFileTests(unittest.TestCase):
780 def assertCompiledIn(self, name, namelist):
781 if name + 'o' not in namelist:
782 self.assertIn(name + 'c', namelist)
783
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200784 def requiresWriteAccess(self, path):
Berker Peksage1efc072015-02-16 04:36:18 +0200785 # effective_ids unavailable on windows
786 if not os.access(path, os.W_OK,
787 effective_ids=os.access in os.supports_effective_ids):
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200788 self.skipTest('requires write access to the installed location')
Serhiy Storchakad86a6ef2015-09-19 10:55:20 +0300789 filename = os.path.join(path, 'test_zipfile.try')
790 try:
791 fd = os.open(filename, os.O_WRONLY | os.O_CREAT)
792 os.close(fd)
793 except Exception:
794 self.skipTest('requires write access to the installed location')
795 unlink(filename)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200796
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300797 def test_write_pyfile(self):
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200798 self.requiresWriteAccess(os.path.dirname(__file__))
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300799 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
800 fn = __file__
Brett Cannonf299abd2015-04-13 14:21:02 -0400801 if fn.endswith('.pyc'):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300802 path_split = fn.split(os.sep)
803 if os.altsep is not None:
804 path_split.extend(fn.split(os.altsep))
805 if '__pycache__' in path_split:
Serhiy Storchaka9068e4d2013-07-22 21:02:14 +0300806 fn = importlib.util.source_from_cache(fn)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300807 else:
808 fn = fn[:-1]
809
810 zipfp.writepy(fn)
811
812 bn = os.path.basename(fn)
813 self.assertNotIn(bn, zipfp.namelist())
814 self.assertCompiledIn(bn, zipfp.namelist())
815
816 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
817 fn = __file__
Brett Cannonf299abd2015-04-13 14:21:02 -0400818 if fn.endswith('.pyc'):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300819 fn = fn[:-1]
820
821 zipfp.writepy(fn, "testpackage")
822
823 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
824 self.assertNotIn(bn, zipfp.namelist())
825 self.assertCompiledIn(bn, zipfp.namelist())
826
827 def test_write_python_package(self):
828 import email
829 packagedir = os.path.dirname(email.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200830 self.requiresWriteAccess(packagedir)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300831
832 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
833 zipfp.writepy(packagedir)
834
835 # Check for a couple of modules at different levels of the
836 # hierarchy
837 names = zipfp.namelist()
838 self.assertCompiledIn('email/__init__.py', names)
839 self.assertCompiledIn('email/mime/text.py', names)
840
Christian Tismer59202e52013-10-21 03:59:23 +0200841 def test_write_filtered_python_package(self):
842 import test
843 packagedir = os.path.dirname(test.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200844 self.requiresWriteAccess(packagedir)
Christian Tismer59202e52013-10-21 03:59:23 +0200845
846 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
847
Christian Tismer59202e52013-10-21 03:59:23 +0200848 # first make sure that the test folder gives error messages
Georg Brandla6065422013-10-21 08:29:29 +0200849 # (on the badsyntax_... files)
850 with captured_stdout() as reportSIO:
851 zipfp.writepy(packagedir)
Christian Tismer59202e52013-10-21 03:59:23 +0200852 reportStr = reportSIO.getvalue()
853 self.assertTrue('SyntaxError' in reportStr)
854
Christian Tismer410d9312013-10-22 04:09:28 +0200855 # then check that the filter works on the whole package
Georg Brandla6065422013-10-21 08:29:29 +0200856 with captured_stdout() as reportSIO:
857 zipfp.writepy(packagedir, filterfunc=lambda whatever: False)
Christian Tismer59202e52013-10-21 03:59:23 +0200858 reportStr = reportSIO.getvalue()
859 self.assertTrue('SyntaxError' not in reportStr)
860
Christian Tismer410d9312013-10-22 04:09:28 +0200861 # then check that the filter works on individual files
Larry Hastings7e63b362015-05-08 06:54:58 -0700862 def filter(path):
863 return not os.path.basename(path).startswith("bad")
Serhiy Storchakac46d1fa2014-01-20 21:59:33 +0200864 with captured_stdout() as reportSIO, self.assertWarns(UserWarning):
Larry Hastings7e63b362015-05-08 06:54:58 -0700865 zipfp.writepy(packagedir, filterfunc=filter)
Christian Tismer410d9312013-10-22 04:09:28 +0200866 reportStr = reportSIO.getvalue()
867 if reportStr:
868 print(reportStr)
869 self.assertTrue('SyntaxError' not in reportStr)
870
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300871 def test_write_with_optimization(self):
872 import email
873 packagedir = os.path.dirname(email.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200874 self.requiresWriteAccess(packagedir)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300875 optlevel = 1 if __debug__ else 0
Brett Cannonf299abd2015-04-13 14:21:02 -0400876 ext = '.pyc'
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300877
878 with TemporaryFile() as t, \
Christian Tismer59202e52013-10-21 03:59:23 +0200879 zipfile.PyZipFile(t, "w", optimize=optlevel) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300880 zipfp.writepy(packagedir)
881
882 names = zipfp.namelist()
883 self.assertIn('email/__init__' + ext, names)
884 self.assertIn('email/mime/text' + ext, names)
885
886 def test_write_python_directory(self):
887 os.mkdir(TESTFN2)
888 try:
889 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
890 fp.write("print(42)\n")
891
892 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
893 fp.write("print(42 * 42)\n")
894
895 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
896 fp.write("bla bla bla\n")
897
898 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
899 zipfp.writepy(TESTFN2)
900
901 names = zipfp.namelist()
902 self.assertCompiledIn('mod1.py', names)
903 self.assertCompiledIn('mod2.py', names)
904 self.assertNotIn('mod2.txt', names)
905
906 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200907 rmtree(TESTFN2)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300908
Christian Tismer410d9312013-10-22 04:09:28 +0200909 def test_write_python_directory_filtered(self):
910 os.mkdir(TESTFN2)
911 try:
912 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
913 fp.write("print(42)\n")
914
915 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
916 fp.write("print(42 * 42)\n")
917
918 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
919 zipfp.writepy(TESTFN2, filterfunc=lambda fn:
920 not fn.endswith('mod2.py'))
921
922 names = zipfp.namelist()
923 self.assertCompiledIn('mod1.py', names)
924 self.assertNotIn('mod2.py', names)
925
926 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200927 rmtree(TESTFN2)
Christian Tismer410d9312013-10-22 04:09:28 +0200928
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300929 def test_write_non_pyfile(self):
930 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
931 with open(TESTFN, 'w') as f:
932 f.write('most definitely not a python file')
933 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
Victor Stinner88b215e2014-09-04 00:51:09 +0200934 unlink(TESTFN)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300935
936 def test_write_pyfile_bad_syntax(self):
937 os.mkdir(TESTFN2)
938 try:
939 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
940 fp.write("Bad syntax in python file\n")
941
942 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
943 # syntax errors are printed to stdout
944 with captured_stdout() as s:
945 zipfp.writepy(os.path.join(TESTFN2, "mod1.py"))
946
947 self.assertIn("SyntaxError", s.getvalue())
948
949 # as it will not have compiled the python file, it will
Brett Cannonf299abd2015-04-13 14:21:02 -0400950 # include the .py file not .pyc
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300951 names = zipfp.namelist()
952 self.assertIn('mod1.py', names)
953 self.assertNotIn('mod1.pyc', names)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300954
955 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200956 rmtree(TESTFN2)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300957
Serhiy Storchaka8606e952017-03-08 14:37:51 +0200958 def test_write_pathlike(self):
959 os.mkdir(TESTFN2)
960 try:
961 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
962 fp.write("print(42)\n")
963
964 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
965 zipfp.writepy(pathlib.Path(TESTFN2) / "mod1.py")
966 names = zipfp.namelist()
967 self.assertCompiledIn('mod1.py', names)
968 finally:
969 rmtree(TESTFN2)
970
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300971
972class ExtractTests(unittest.TestCase):
Serhiy Storchaka8606e952017-03-08 14:37:51 +0200973
974 def make_test_file(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000975 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
976 for fpath, fdata in SMALL_TEST_DATA:
977 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000978
Serhiy Storchaka8606e952017-03-08 14:37:51 +0200979 def test_extract(self):
980 with temp_cwd():
981 self.make_test_file()
982 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
983 for fpath, fdata in SMALL_TEST_DATA:
984 writtenfile = zipfp.extract(fpath)
985
986 # make sure it was written to the right place
987 correctfile = os.path.join(os.getcwd(), fpath)
988 correctfile = os.path.normpath(correctfile)
989
990 self.assertEqual(writtenfile, correctfile)
991
992 # make sure correct data is in correct file
993 with open(writtenfile, "rb") as f:
994 self.assertEqual(fdata.encode(), f.read())
995
996 unlink(writtenfile)
997
998 def _test_extract_with_target(self, target):
999 self.make_test_file()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001000 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1001 for fpath, fdata in SMALL_TEST_DATA:
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001002 writtenfile = zipfp.extract(fpath, target)
Christian Heimes790c8232008-01-07 21:14:23 +00001003
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001004 # make sure it was written to the right place
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001005 correctfile = os.path.join(target, fpath)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001006 correctfile = os.path.normpath(correctfile)
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001007 self.assertTrue(os.path.samefile(writtenfile, correctfile), (writtenfile, target))
Christian Heimes790c8232008-01-07 21:14:23 +00001008
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001009 # make sure correct data is in correct file
Brian Curtin8fb9b862010-11-18 02:15:28 +00001010 with open(writtenfile, "rb") as f:
1011 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +00001012
Victor Stinner88b215e2014-09-04 00:51:09 +02001013 unlink(writtenfile)
Christian Heimes790c8232008-01-07 21:14:23 +00001014
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001015 unlink(TESTFN2)
1016
1017 def test_extract_with_target(self):
1018 with temp_dir() as extdir:
1019 self._test_extract_with_target(extdir)
1020
1021 def test_extract_with_target_pathlike(self):
1022 with temp_dir() as extdir:
1023 self._test_extract_with_target(pathlib.Path(extdir))
Christian Heimes790c8232008-01-07 21:14:23 +00001024
Ezio Melottiafd0d112009-07-15 17:17:17 +00001025 def test_extract_all(self):
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001026 with temp_cwd():
1027 self.make_test_file()
1028 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1029 zipfp.extractall()
1030 for fpath, fdata in SMALL_TEST_DATA:
1031 outfile = os.path.join(os.getcwd(), fpath)
Christian Heimes790c8232008-01-07 21:14:23 +00001032
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001033 with open(outfile, "rb") as f:
1034 self.assertEqual(fdata.encode(), f.read())
1035
1036 unlink(outfile)
1037
1038 def _test_extract_all_with_target(self, target):
1039 self.make_test_file()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001040 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001041 zipfp.extractall(target)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001042 for fpath, fdata in SMALL_TEST_DATA:
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001043 outfile = os.path.join(target, fpath)
Christian Heimes790c8232008-01-07 21:14:23 +00001044
Brian Curtin8fb9b862010-11-18 02:15:28 +00001045 with open(outfile, "rb") as f:
1046 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +00001047
Victor Stinner88b215e2014-09-04 00:51:09 +02001048 unlink(outfile)
Christian Heimes790c8232008-01-07 21:14:23 +00001049
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001050 unlink(TESTFN2)
1051
1052 def test_extract_all_with_target(self):
1053 with temp_dir() as extdir:
1054 self._test_extract_all_with_target(extdir)
1055
1056 def test_extract_all_with_target_pathlike(self):
1057 with temp_dir() as extdir:
1058 self._test_extract_all_with_target(pathlib.Path(extdir))
Christian Heimes790c8232008-01-07 21:14:23 +00001059
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001060 def check_file(self, filename, content):
1061 self.assertTrue(os.path.isfile(filename))
1062 with open(filename, 'rb') as f:
1063 self.assertEqual(f.read(), content)
1064
Gregory P. Smith09aa7522013-02-03 00:36:32 -08001065 def test_sanitize_windows_name(self):
1066 san = zipfile.ZipFile._sanitize_windows_name
1067 # Passing pathsep in allows this test to work regardless of platform.
1068 self.assertEqual(san(r',,?,C:,foo,bar/z', ','), r'_,C_,foo,bar/z')
1069 self.assertEqual(san(r'a\b,c<d>e|f"g?h*i', ','), r'a\b,c_d_e_f_g_h_i')
1070 self.assertEqual(san('../../foo../../ba..r', '/'), r'foo/ba..r')
1071
1072 def test_extract_hackers_arcnames_common_cases(self):
1073 common_hacknames = [
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001074 ('../foo/bar', 'foo/bar'),
1075 ('foo/../bar', 'foo/bar'),
1076 ('foo/../../bar', 'foo/bar'),
1077 ('foo/bar/..', 'foo/bar'),
1078 ('./../foo/bar', 'foo/bar'),
1079 ('/foo/bar', 'foo/bar'),
1080 ('/foo/../bar', 'foo/bar'),
1081 ('/foo/../../bar', 'foo/bar'),
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001082 ]
Gregory P. Smith09aa7522013-02-03 00:36:32 -08001083 self._test_extract_hackers_arcnames(common_hacknames)
1084
1085 @unittest.skipIf(os.path.sep != '\\', 'Requires \\ as path separator.')
1086 def test_extract_hackers_arcnames_windows_only(self):
1087 """Test combination of path fixing and windows name sanitization."""
1088 windows_hacknames = [
Christian Tismer59202e52013-10-21 03:59:23 +02001089 (r'..\foo\bar', 'foo/bar'),
1090 (r'..\/foo\/bar', 'foo/bar'),
1091 (r'foo/\..\/bar', 'foo/bar'),
1092 (r'foo\/../\bar', 'foo/bar'),
1093 (r'C:foo/bar', 'foo/bar'),
1094 (r'C:/foo/bar', 'foo/bar'),
1095 (r'C://foo/bar', 'foo/bar'),
1096 (r'C:\foo\bar', 'foo/bar'),
1097 (r'//conky/mountpoint/foo/bar', 'foo/bar'),
1098 (r'\\conky\mountpoint\foo\bar', 'foo/bar'),
1099 (r'///conky/mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
1100 (r'\\\conky\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
1101 (r'//conky//mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
1102 (r'\\conky\\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
1103 (r'//?/C:/foo/bar', 'foo/bar'),
1104 (r'\\?\C:\foo\bar', 'foo/bar'),
1105 (r'C:/../C:/foo/bar', 'C_/foo/bar'),
1106 (r'a:b\c<d>e|f"g?h*i', 'b/c_d_e_f_g_h_i'),
1107 ('../../foo../../ba..r', 'foo/ba..r'),
Gregory P. Smith09aa7522013-02-03 00:36:32 -08001108 ]
1109 self._test_extract_hackers_arcnames(windows_hacknames)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001110
Gregory P. Smith09aa7522013-02-03 00:36:32 -08001111 @unittest.skipIf(os.path.sep != '/', r'Requires / as path separator.')
1112 def test_extract_hackers_arcnames_posix_only(self):
1113 posix_hacknames = [
1114 ('//foo/bar', 'foo/bar'),
1115 ('../../foo../../ba..r', 'foo../ba..r'),
1116 (r'foo/..\bar', r'foo/..\bar'),
1117 ]
1118 self._test_extract_hackers_arcnames(posix_hacknames)
1119
1120 def _test_extract_hackers_arcnames(self, hacknames):
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001121 for arcname, fixedname in hacknames:
1122 content = b'foobar' + arcname.encode()
1123 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipfp:
Serhiy Storchakae5e64442013-02-02 19:50:59 +02001124 zinfo = zipfile.ZipInfo()
1125 # preserve backslashes
1126 zinfo.filename = arcname
1127 zinfo.external_attr = 0o600 << 16
1128 zipfp.writestr(zinfo, content)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001129
Serhiy Storchakae5e64442013-02-02 19:50:59 +02001130 arcname = arcname.replace(os.sep, "/")
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001131 targetpath = os.path.join('target', 'subdir', 'subsub')
1132 correctfile = os.path.join(targetpath, *fixedname.split('/'))
1133
1134 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1135 writtenfile = zipfp.extract(arcname, targetpath)
Serhiy Storchakae5e64442013-02-02 19:50:59 +02001136 self.assertEqual(writtenfile, correctfile,
Gregory P. Smith09aa7522013-02-03 00:36:32 -08001137 msg='extract %r: %r != %r' %
1138 (arcname, writtenfile, correctfile))
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001139 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001140 rmtree('target')
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001141
1142 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1143 zipfp.extractall(targetpath)
1144 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001145 rmtree('target')
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001146
1147 correctfile = os.path.join(os.getcwd(), *fixedname.split('/'))
1148
1149 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1150 writtenfile = zipfp.extract(arcname)
Serhiy Storchakae5e64442013-02-02 19:50:59 +02001151 self.assertEqual(writtenfile, correctfile,
1152 msg="extract %r" % arcname)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001153 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001154 rmtree(fixedname.split('/')[0])
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001155
1156 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1157 zipfp.extractall()
1158 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001159 rmtree(fixedname.split('/')[0])
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001160
Victor Stinner88b215e2014-09-04 00:51:09 +02001161 unlink(TESTFN2)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001162
Ronald Oussorenee5c8852010-02-07 20:24:02 +00001163
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001164class OtherTests(unittest.TestCase):
1165 def test_open_via_zip_info(self):
1166 # Create the ZIP archive
1167 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
1168 zipfp.writestr("name", "foo")
Serhiy Storchaka9b7a1a12014-01-20 21:57:40 +02001169 with self.assertWarns(UserWarning):
1170 zipfp.writestr("name", "bar")
1171 self.assertEqual(zipfp.namelist(), ["name"] * 2)
Ronald Oussorenee5c8852010-02-07 20:24:02 +00001172
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001173 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1174 infos = zipfp.infolist()
1175 data = b""
1176 for info in infos:
1177 with zipfp.open(info) as zipopen:
1178 data += zipopen.read()
1179 self.assertIn(data, {b"foobar", b"barfoo"})
1180 data = b""
1181 for info in infos:
1182 data += zipfp.read(info)
1183 self.assertIn(data, {b"foobar", b"barfoo"})
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001184
Gregory P. Smithb0d9ca92009-07-07 05:06:04 +00001185 def test_writestr_extended_local_header_issue1202(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001186 with zipfile.ZipFile(TESTFN2, 'w') as orig_zip:
1187 for data in 'abcdefghijklmnop':
1188 zinfo = zipfile.ZipInfo(data)
1189 zinfo.flag_bits |= 0x08 # Include an extended local header.
1190 orig_zip.writestr(zinfo, data)
1191
1192 def test_close(self):
1193 """Check that the zipfile is closed after the 'with' block."""
1194 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
1195 for fpath, fdata in SMALL_TEST_DATA:
1196 zipfp.writestr(fpath, fdata)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001197 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
1198 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001199
1200 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001201 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
1202 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001203
1204 def test_close_on_exception(self):
1205 """Check that the zipfile is closed if an exception is raised in the
1206 'with' block."""
1207 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
1208 for fpath, fdata in SMALL_TEST_DATA:
1209 zipfp.writestr(fpath, fdata)
1210
1211 try:
1212 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
Georg Brandl4d540882010-10-28 06:42:33 +00001213 raise zipfile.BadZipFile()
1214 except zipfile.BadZipFile:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001215 self.assertIsNone(zipfp2.fp, 'zipfp is not closed')
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001216
Martin v. Löwisd099b562012-05-01 14:08:22 +02001217 def test_unsupported_version(self):
1218 # File has an extract_version of 120
1219 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 +02001220 b'\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00xPK\x01\x02x\x03x\x00\x00\x00\x00'
1221 b'\x00!p\xa1@\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00'
1222 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00\x00xPK\x05\x06'
1223 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 +03001224
Martin v. Löwisd099b562012-05-01 14:08:22 +02001225 self.assertRaises(NotImplementedError, zipfile.ZipFile,
1226 io.BytesIO(data), 'r')
1227
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001228 @requires_zlib
1229 def test_read_unicode_filenames(self):
1230 # bug #10801
1231 fname = findfile('zip_cp437_header.zip')
1232 with zipfile.ZipFile(fname) as zipfp:
1233 for name in zipfp.namelist():
1234 zipfp.open(name).close()
1235
1236 def test_write_unicode_filenames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001237 with zipfile.ZipFile(TESTFN, "w") as zf:
1238 zf.writestr("foo.txt", "Test for unicode filename")
1239 zf.writestr("\xf6.txt", "Test for unicode filename")
Ezio Melottie9615932010-01-24 19:26:24 +00001240 self.assertIsInstance(zf.infolist()[0].filename, str)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001241
1242 with zipfile.ZipFile(TESTFN, "r") as zf:
1243 self.assertEqual(zf.filelist[0].filename, "foo.txt")
1244 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
Martin v. Löwis8570f6a2008-05-05 17:44:38 +00001245
Serhiy Storchaka764fc9b2015-03-25 10:09:41 +02001246 def test_exclusive_create_zip_file(self):
1247 """Test exclusive creating a new zipfile."""
1248 unlink(TESTFN2)
1249 filename = 'testfile.txt'
1250 content = b'hello, world. this is some content.'
1251 with zipfile.ZipFile(TESTFN2, "x", zipfile.ZIP_STORED) as zipfp:
1252 zipfp.writestr(filename, content)
1253 with self.assertRaises(FileExistsError):
1254 zipfile.ZipFile(TESTFN2, "x", zipfile.ZIP_STORED)
1255 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1256 self.assertEqual(zipfp.namelist(), [filename])
1257 self.assertEqual(zipfp.read(filename), content)
1258
Ezio Melottiafd0d112009-07-15 17:17:17 +00001259 def test_create_non_existent_file_for_append(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001260 if os.path.exists(TESTFN):
1261 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001262
Thomas Wouterscf297e42007-02-23 15:07:44 +00001263 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001264 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +00001265
Thomas Wouterscf297e42007-02-23 15:07:44 +00001266 try:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001267 with zipfile.ZipFile(TESTFN, 'a') as zf:
1268 zf.writestr(filename, content)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001269 except OSError:
Thomas Wouterscf297e42007-02-23 15:07:44 +00001270 self.fail('Could not append data to a non-existent zip file.')
1271
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001272 self.assertTrue(os.path.exists(TESTFN))
Thomas Wouterscf297e42007-02-23 15:07:44 +00001273
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001274 with zipfile.ZipFile(TESTFN, 'r') as zf:
1275 self.assertEqual(zf.read(filename), content)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001276
Ezio Melottiafd0d112009-07-15 17:17:17 +00001277 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001278 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti35386712009-12-31 13:22:41 +00001279 # it opens if there's an error in the file. If it doesn't, the
1280 # traceback holds a reference to the ZipFile object and, indirectly,
1281 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001282 # On Windows, this causes the os.unlink() call to fail because the
1283 # underlying file is still open. This is SF bug #412214.
1284 #
Ezio Melotti35386712009-12-31 13:22:41 +00001285 with open(TESTFN, "w") as fp:
1286 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001287 try:
1288 zf = zipfile.ZipFile(TESTFN)
Georg Brandl4d540882010-10-28 06:42:33 +00001289 except zipfile.BadZipFile:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001290 pass
1291
Ezio Melottiafd0d112009-07-15 17:17:17 +00001292 def test_is_zip_erroneous_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001293 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001294 # - passing a filename
1295 with open(TESTFN, "w") as fp:
1296 fp.write("this is not a legal zip file\n")
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001297 self.assertFalse(zipfile.is_zipfile(TESTFN))
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001298 # - passing a path-like object
1299 self.assertFalse(zipfile.is_zipfile(pathlib.Path(TESTFN)))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001300 # - passing a file object
1301 with open(TESTFN, "rb") as fp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001302 self.assertFalse(zipfile.is_zipfile(fp))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001303 # - passing a file-like object
1304 fp = io.BytesIO()
1305 fp.write(b"this is not a legal zip file\n")
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001306 self.assertFalse(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001307 fp.seek(0, 0)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001308 self.assertFalse(zipfile.is_zipfile(fp))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001309
Serhiy Storchakad2b15272013-01-31 15:27:07 +02001310 def test_damaged_zipfile(self):
1311 """Check that zipfiles with missing bytes at the end raise BadZipFile."""
1312 # - Create a valid zip file
1313 fp = io.BytesIO()
1314 with zipfile.ZipFile(fp, mode="w") as zipf:
1315 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
1316 zipfiledata = fp.getvalue()
1317
1318 # - Now create copies of it missing the last N bytes and make sure
1319 # a BadZipFile exception is raised when we try to open it
1320 for N in range(len(zipfiledata)):
1321 fp = io.BytesIO(zipfiledata[:N])
1322 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, fp)
1323
Ezio Melottiafd0d112009-07-15 17:17:17 +00001324 def test_is_zip_valid_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001325 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001326 # - passing a filename
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001327 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1328 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
1329
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001330 self.assertTrue(zipfile.is_zipfile(TESTFN))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001331 # - passing a file object
1332 with open(TESTFN, "rb") as fp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001333 self.assertTrue(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001334 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001335 zip_contents = fp.read()
1336 # - passing a file-like object
1337 fp = io.BytesIO()
1338 fp.write(zip_contents)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001339 self.assertTrue(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001340 fp.seek(0, 0)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001341 self.assertTrue(zipfile.is_zipfile(fp))
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001342
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001343 def test_non_existent_file_raises_OSError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001344 # make sure we don't raise an AttributeError when a partially-constructed
1345 # ZipFile instance is finalized; this tests for regression on SF tracker
1346 # bug #403871.
1347
1348 # The bug we're testing for caused an AttributeError to be raised
1349 # when a ZipFile instance was created for a file that did not
1350 # exist; the .fp member was not initialized but was needed by the
1351 # __del__() method. Since the AttributeError is in the __del__(),
1352 # it is ignored, but the user should be sufficiently annoyed by
1353 # the message on the output that regression will be noticed
1354 # quickly.
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001355 self.assertRaises(OSError, zipfile.ZipFile, TESTFN)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001356
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001357 def test_empty_file_raises_BadZipFile(self):
1358 f = open(TESTFN, 'w')
1359 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001360 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001361
Ezio Melotti35386712009-12-31 13:22:41 +00001362 with open(TESTFN, 'w') as fp:
1363 fp.write("short file")
Georg Brandl4d540882010-10-28 06:42:33 +00001364 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001365
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001366 def test_closed_zip_raises_ValueError(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001367 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001368 data = io.BytesIO()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001369 with zipfile.ZipFile(data, mode="w") as zipf:
1370 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001371
Andrew Svetlov737fb892012-12-18 21:14:22 +02001372 # This is correct; calling .read on a closed ZipFile should raise
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001373 # a ValueError, and so should calling .testzip. An earlier
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001374 # version of .testzip would swallow this exception (and any other)
1375 # and report that the first file in the archive was corrupt.
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001376 self.assertRaises(ValueError, zipf.read, "foo.txt")
1377 self.assertRaises(ValueError, zipf.open, "foo.txt")
1378 self.assertRaises(ValueError, zipf.testzip)
1379 self.assertRaises(ValueError, zipf.writestr, "bogus.txt", "bogus")
Brian Curtin8fb9b862010-11-18 02:15:28 +00001380 with open(TESTFN, 'w') as f:
1381 f.write('zipfile test data')
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001382 self.assertRaises(ValueError, zipf.write, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001383
Ezio Melottiafd0d112009-07-15 17:17:17 +00001384 def test_bad_constructor_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001385 """Check that bad modes passed to ZipFile constructor are caught."""
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001386 self.assertRaises(ValueError, zipfile.ZipFile, TESTFN, "q")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001387
Ezio Melottiafd0d112009-07-15 17:17:17 +00001388 def test_bad_open_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001389 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001390 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1391 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1392
1393 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Serhiy Storchakae670be22016-06-11 19:32:44 +03001394 # read the data to make sure the file is there
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001395 zipf.read("foo.txt")
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001396 self.assertRaises(ValueError, zipf.open, "foo.txt", "q")
Serhiy Storchakae670be22016-06-11 19:32:44 +03001397 # universal newlines support is removed
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001398 self.assertRaises(ValueError, zipf.open, "foo.txt", "U")
1399 self.assertRaises(ValueError, zipf.open, "foo.txt", "rU")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001400
Ezio Melottiafd0d112009-07-15 17:17:17 +00001401 def test_read0(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001402 """Check that calling read(0) on a ZipExtFile object returns an empty
1403 string and doesn't advance file pointer."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001404 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1405 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1406 # read the data to make sure the file is there
Brian Curtin8fb9b862010-11-18 02:15:28 +00001407 with zipf.open("foo.txt") as f:
1408 for i in range(FIXEDTEST_SIZE):
1409 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001410
Brian Curtin8fb9b862010-11-18 02:15:28 +00001411 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001412
Ezio Melottiafd0d112009-07-15 17:17:17 +00001413 def test_open_non_existent_item(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001414 """Check that attempting to call open() for an item that doesn't
1415 exist in the archive raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001416 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1417 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001418
Ezio Melottiafd0d112009-07-15 17:17:17 +00001419 def test_bad_compression_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001420 """Check that bad compression methods passed to ZipFile.open are
1421 caught."""
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001422 self.assertRaises(NotImplementedError, zipfile.ZipFile, TESTFN, "w", -1)
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001423
Martin v. Löwisb3260f02012-05-01 08:38:01 +02001424 def test_unsupported_compression(self):
1425 # data is declared as shrunk, but actually deflated
1426 data = (b'PK\x03\x04.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00'
Christian Tismer59202e52013-10-21 03:59:23 +02001427 b'\x00\x02\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00x\x03\x00PK\x01'
1428 b'\x02.\x03.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00\x00\x02\x00\x00'
1429 b'\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
1430 b'\x80\x01\x00\x00\x00\x00xPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00'
1431 b'/\x00\x00\x00!\x00\x00\x00\x00\x00')
Martin v. Löwisb3260f02012-05-01 08:38:01 +02001432 with zipfile.ZipFile(io.BytesIO(data), 'r') as zipf:
1433 self.assertRaises(NotImplementedError, zipf.open, 'x')
1434
Ezio Melottiafd0d112009-07-15 17:17:17 +00001435 def test_null_byte_in_filename(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001436 """Check that a filename containing a null byte is properly
1437 terminated."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001438 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1439 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
1440 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001441
Ezio Melottiafd0d112009-07-15 17:17:17 +00001442 def test_struct_sizes(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001443 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001444 self.assertEqual(zipfile.sizeEndCentDir, 22)
1445 self.assertEqual(zipfile.sizeCentralDir, 46)
1446 self.assertEqual(zipfile.sizeEndCentDir64, 56)
1447 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
1448
Ezio Melottiafd0d112009-07-15 17:17:17 +00001449 def test_comments(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001450 """Check that comments on the archive are handled properly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001451
1452 # check default comment is empty
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001453 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1454 self.assertEqual(zipf.comment, b'')
1455 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1456
1457 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1458 self.assertEqual(zipfr.comment, b'')
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001459
1460 # check a simple short comment
1461 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001462 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1463 zipf.comment = comment
1464 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1465 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1466 self.assertEqual(zipf.comment, comment)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001467
1468 # check a comment of max length
1469 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
1470 comment2 = comment2.encode("ascii")
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001471 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1472 zipf.comment = comment2
1473 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1474
1475 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1476 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001477
1478 # check a comment that is too long is truncated
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001479 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
Serhiy Storchaka9b7a1a12014-01-20 21:57:40 +02001480 with self.assertWarns(UserWarning):
1481 zipf.comment = comment2 + b'oops'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001482 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1483 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1484 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001485
Antoine Pitrouc3991852012-06-30 17:31:37 +02001486 # check that comments are correctly modified in append mode
1487 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1488 zipf.comment = b"original comment"
1489 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1490 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1491 zipf.comment = b"an updated comment"
1492 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1493 self.assertEqual(zipf.comment, b"an updated comment")
1494
1495 # check that comments are correctly shortened in append mode
1496 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1497 zipf.comment = b"original comment that's longer"
1498 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1499 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1500 zipf.comment = b"shorter comment"
1501 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1502 self.assertEqual(zipf.comment, b"shorter comment")
1503
R David Murrayf50b38a2012-04-12 18:44:58 -04001504 def test_unicode_comment(self):
1505 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1506 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1507 with self.assertRaises(TypeError):
1508 zipf.comment = "this is an error"
1509
1510 def test_change_comment_in_empty_archive(self):
1511 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1512 self.assertFalse(zipf.filelist)
1513 zipf.comment = b"this is a comment"
1514 with zipfile.ZipFile(TESTFN, "r") as zipf:
1515 self.assertEqual(zipf.comment, b"this is a comment")
1516
1517 def test_change_comment_in_nonempty_archive(self):
1518 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1519 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1520 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1521 self.assertTrue(zipf.filelist)
1522 zipf.comment = b"this is a comment"
1523 with zipfile.ZipFile(TESTFN, "r") as zipf:
1524 self.assertEqual(zipf.comment, b"this is a comment")
1525
Georg Brandl268e4d42010-10-14 06:59:45 +00001526 def test_empty_zipfile(self):
1527 # Check that creating a file in 'w' or 'a' mode and closing without
1528 # adding any files to the archives creates a valid empty ZIP file
1529 zipf = zipfile.ZipFile(TESTFN, mode="w")
1530 zipf.close()
1531 try:
1532 zipf = zipfile.ZipFile(TESTFN, mode="r")
1533 except zipfile.BadZipFile:
1534 self.fail("Unable to create empty ZIP file in 'w' mode")
1535
1536 zipf = zipfile.ZipFile(TESTFN, mode="a")
1537 zipf.close()
1538 try:
1539 zipf = zipfile.ZipFile(TESTFN, mode="r")
1540 except:
1541 self.fail("Unable to create empty ZIP file in 'a' mode")
1542
1543 def test_open_empty_file(self):
1544 # Issue 1710703: Check that opening a file with less than 22 bytes
Georg Brandl4d540882010-10-28 06:42:33 +00001545 # raises a BadZipFile exception (rather than the previously unhelpful
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001546 # OSError)
Georg Brandl268e4d42010-10-14 06:59:45 +00001547 f = open(TESTFN, 'w')
1548 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001549 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN, 'r')
Georg Brandl268e4d42010-10-14 06:59:45 +00001550
Senthil Kumaran29fa9d42011-10-20 01:46:00 +08001551 def test_create_zipinfo_before_1980(self):
1552 self.assertRaises(ValueError,
1553 zipfile.ZipInfo, 'seventies', (1979, 1, 1, 0, 0, 0))
1554
Gregory P. Smith0af8a862014-05-29 23:42:14 -07001555 def test_zipfile_with_short_extra_field(self):
1556 """If an extra field in the header is less than 4 bytes, skip it."""
1557 zipdata = (
1558 b'PK\x03\x04\x14\x00\x00\x00\x00\x00\x93\x9b\xad@\x8b\x9e'
1559 b'\xd9\xd3\x01\x00\x00\x00\x01\x00\x00\x00\x03\x00\x03\x00ab'
1560 b'c\x00\x00\x00APK\x01\x02\x14\x03\x14\x00\x00\x00\x00'
1561 b'\x00\x93\x9b\xad@\x8b\x9e\xd9\xd3\x01\x00\x00\x00\x01\x00\x00'
1562 b'\x00\x03\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00'
1563 b'\x00\x00\x00abc\x00\x00PK\x05\x06\x00\x00\x00\x00'
1564 b'\x01\x00\x01\x003\x00\x00\x00%\x00\x00\x00\x00\x00'
1565 )
1566 with zipfile.ZipFile(io.BytesIO(zipdata), 'r') as zipf:
1567 # testzip returns the name of the first corrupt file, or None
1568 self.assertIsNone(zipf.testzip())
1569
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001570 def test_open_conflicting_handles(self):
1571 # It's only possible to open one writable file handle at a time
1572 msg1 = b"It's fun to charter an accountant!"
1573 msg2 = b"And sail the wide accountant sea"
1574 msg3 = b"To find, explore the funds offshore"
1575 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipf:
1576 with zipf.open('foo', mode='w') as w2:
1577 w2.write(msg1)
1578 with zipf.open('bar', mode='w') as w1:
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001579 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001580 zipf.open('handle', mode='w')
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001581 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001582 zipf.open('foo', mode='r')
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001583 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001584 zipf.writestr('str', 'abcde')
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001585 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001586 zipf.write(__file__, 'file')
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001587 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001588 zipf.close()
1589 w1.write(msg2)
1590 with zipf.open('baz', mode='w') as w2:
1591 w2.write(msg3)
1592
1593 with zipfile.ZipFile(TESTFN2, 'r') as zipf:
1594 self.assertEqual(zipf.read('foo'), msg1)
1595 self.assertEqual(zipf.read('bar'), msg2)
1596 self.assertEqual(zipf.read('baz'), msg3)
1597 self.assertEqual(zipf.namelist(), ['foo', 'bar', 'baz'])
1598
Guido van Rossumd8faa362007-04-27 19:54:29 +00001599 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001600 unlink(TESTFN)
1601 unlink(TESTFN2)
1602
Thomas Wouterscf297e42007-02-23 15:07:44 +00001603
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001604class AbstractBadCrcTests:
1605 def test_testzip_with_bad_crc(self):
1606 """Tests that files with bad CRCs return their name from testzip."""
1607 zipdata = self.zip_with_bad_crc
1608
1609 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1610 # testzip returns the name of the first corrupt file, or None
1611 self.assertEqual('afile', zipf.testzip())
1612
1613 def test_read_with_bad_crc(self):
1614 """Tests that files with bad CRCs raise a BadZipFile exception when read."""
1615 zipdata = self.zip_with_bad_crc
1616
1617 # Using ZipFile.read()
1618 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1619 self.assertRaises(zipfile.BadZipFile, zipf.read, 'afile')
1620
1621 # Using ZipExtFile.read()
1622 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1623 with zipf.open('afile', 'r') as corrupt_file:
1624 self.assertRaises(zipfile.BadZipFile, corrupt_file.read)
1625
1626 # Same with small reads (in order to exercise the buffering logic)
1627 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1628 with zipf.open('afile', 'r') as corrupt_file:
1629 corrupt_file.MIN_READ_SIZE = 2
1630 with self.assertRaises(zipfile.BadZipFile):
1631 while corrupt_file.read(2):
1632 pass
1633
1634
1635class StoredBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1636 compression = zipfile.ZIP_STORED
1637 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001638 b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
1639 b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
1640 b'ilehello,AworldP'
1641 b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
1642 b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
1643 b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
1644 b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
1645 b'\0\0/\0\0\0\0\0')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001646
1647@requires_zlib
1648class DeflateBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1649 compression = zipfile.ZIP_DEFLATED
1650 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001651 b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
1652 b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1653 b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
1654 b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
1655 b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
1656 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
1657 b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
1658 b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001659
1660@requires_bz2
1661class Bzip2BadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1662 compression = zipfile.ZIP_BZIP2
1663 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001664 b'PK\x03\x04\x14\x03\x00\x00\x0c\x00nu\x0c=FA'
1665 b'KE8\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1666 b'ileBZh91AY&SY\xd4\xa8\xca'
1667 b'\x7f\x00\x00\x0f\x11\x80@\x00\x06D\x90\x80 \x00 \xa5'
1668 b'P\xd9!\x03\x03\x13\x13\x13\x89\xa9\xa9\xc2u5:\x9f'
1669 b'\x8b\xb9"\x9c(HjTe?\x80PK\x01\x02\x14'
1670 b'\x03\x14\x03\x00\x00\x0c\x00nu\x0c=FAKE8'
1671 b'\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\x00'
1672 b'\x00 \x80\x80\x81\x00\x00\x00\x00afilePK'
1673 b'\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00\x00[\x00'
1674 b'\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001675
1676@requires_lzma
1677class LzmaBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1678 compression = zipfile.ZIP_LZMA
1679 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001680 b'PK\x03\x04\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
1681 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1682 b'ile\t\x04\x05\x00]\x00\x00\x00\x04\x004\x19I'
1683 b'\xee\x8d\xe9\x17\x89:3`\tq!.8\x00PK'
1684 b'\x01\x02\x14\x03\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
1685 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00'
1686 b'\x00\x00\x00\x00 \x80\x80\x81\x00\x00\x00\x00afil'
1687 b'ePK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00'
1688 b'\x00>\x00\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001689
1690
Thomas Wouterscf297e42007-02-23 15:07:44 +00001691class DecryptionTests(unittest.TestCase):
Ezio Melotti35386712009-12-31 13:22:41 +00001692 """Check that ZIP decryption works. Since the library does not
1693 support encryption at the moment, we use a pre-generated encrypted
1694 ZIP file."""
Thomas Wouterscf297e42007-02-23 15:07:44 +00001695
1696 data = (
Christian Tismer59202e52013-10-21 03:59:23 +02001697 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
1698 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
1699 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
1700 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
1701 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
1702 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
1703 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +00001704 data2 = (
Christian Tismer59202e52013-10-21 03:59:23 +02001705 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
1706 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
1707 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
1708 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
1709 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
1710 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
1711 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
1712 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +00001713
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001714 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +00001715 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +00001716
1717 def setUp(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001718 with open(TESTFN, "wb") as fp:
1719 fp.write(self.data)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001720 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti35386712009-12-31 13:22:41 +00001721 with open(TESTFN2, "wb") as fp:
1722 fp.write(self.data2)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001723 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001724
1725 def tearDown(self):
1726 self.zip.close()
1727 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001728 self.zip2.close()
1729 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001730
Ezio Melottiafd0d112009-07-15 17:17:17 +00001731 def test_no_password(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001732 # Reading the encrypted file without password
1733 # must generate a RunTime exception
1734 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001735 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001736
Ezio Melottiafd0d112009-07-15 17:17:17 +00001737 def test_bad_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001738 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001739 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001740 self.zip2.setpassword(b"perl")
1741 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001742
Ezio Melotti975077a2011-05-19 22:03:22 +03001743 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +00001744 def test_good_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001745 self.zip.setpassword(b"python")
Ezio Melotti35386712009-12-31 13:22:41 +00001746 self.assertEqual(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001747 self.zip2.setpassword(b"12345")
Ezio Melotti35386712009-12-31 13:22:41 +00001748 self.assertEqual(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001749
R. David Murray8d855d82010-12-21 21:53:37 +00001750 def test_unicode_password(self):
1751 self.assertRaises(TypeError, self.zip.setpassword, "unicode")
1752 self.assertRaises(TypeError, self.zip.read, "test.txt", "python")
1753 self.assertRaises(TypeError, self.zip.open, "test.txt", pwd="python")
1754 self.assertRaises(TypeError, self.zip.extract, "test.txt", pwd="python")
1755
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001756class AbstractTestsWithRandomBinaryFiles:
1757 @classmethod
1758 def setUpClass(cls):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001759 datacount = randint(16, 64)*1024 + randint(1, 1024)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001760 cls.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
1761 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001762
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001763 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001764 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +00001765 with open(TESTFN, "wb") as fp:
1766 fp.write(self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001767
1768 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001769 unlink(TESTFN)
1770 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001771
Ezio Melottiafd0d112009-07-15 17:17:17 +00001772 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001773 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001774 with zipfile.ZipFile(f, "w", compression) as zipfp:
1775 zipfp.write(TESTFN, "another.name")
1776 zipfp.write(TESTFN, TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001777
Ezio Melottiafd0d112009-07-15 17:17:17 +00001778 def zip_test(self, f, compression):
1779 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001780
1781 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001782 with zipfile.ZipFile(f, "r", compression) as zipfp:
1783 testdata = zipfp.read(TESTFN)
1784 self.assertEqual(len(testdata), len(self.data))
1785 self.assertEqual(testdata, self.data)
1786 self.assertEqual(zipfp.read("another.name"), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001787
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001788 def test_read(self):
1789 for f in get_files(self):
1790 self.zip_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001791
Ezio Melottiafd0d112009-07-15 17:17:17 +00001792 def zip_open_test(self, f, compression):
1793 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001794
1795 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001796 with zipfile.ZipFile(f, "r", compression) as zipfp:
1797 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001798 with zipfp.open(TESTFN) as zipopen1:
1799 while True:
1800 read_data = zipopen1.read(256)
1801 if not read_data:
1802 break
1803 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001804
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001805 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001806 with zipfp.open("another.name") as zipopen2:
1807 while True:
1808 read_data = zipopen2.read(256)
1809 if not read_data:
1810 break
1811 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001812
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001813 testdata1 = b''.join(zipdata1)
1814 self.assertEqual(len(testdata1), len(self.data))
1815 self.assertEqual(testdata1, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001816
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001817 testdata2 = b''.join(zipdata2)
Ezio Melotti35386712009-12-31 13:22:41 +00001818 self.assertEqual(len(testdata2), len(self.data))
1819 self.assertEqual(testdata2, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001820
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001821 def test_open(self):
1822 for f in get_files(self):
1823 self.zip_open_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001824
Ezio Melottiafd0d112009-07-15 17:17:17 +00001825 def zip_random_open_test(self, f, compression):
1826 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001827
1828 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001829 with zipfile.ZipFile(f, "r", compression) as zipfp:
1830 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001831 with zipfp.open(TESTFN) as zipopen1:
1832 while True:
1833 read_data = zipopen1.read(randint(1, 1024))
1834 if not read_data:
1835 break
1836 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001837
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001838 testdata = b''.join(zipdata1)
1839 self.assertEqual(len(testdata), len(self.data))
1840 self.assertEqual(testdata, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001841
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001842 def test_random_open(self):
1843 for f in get_files(self):
1844 self.zip_random_open_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001845
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001846
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001847class StoredTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1848 unittest.TestCase):
1849 compression = zipfile.ZIP_STORED
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001850
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001851@requires_zlib
1852class DeflateTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1853 unittest.TestCase):
1854 compression = zipfile.ZIP_DEFLATED
1855
1856@requires_bz2
1857class Bzip2TestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1858 unittest.TestCase):
1859 compression = zipfile.ZIP_BZIP2
1860
1861@requires_lzma
1862class LzmaTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1863 unittest.TestCase):
1864 compression = zipfile.ZIP_LZMA
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001865
Ezio Melotti76430242009-07-11 18:28:48 +00001866
luzpaza5293b42017-11-05 07:37:50 -06001867# Provide the tell() method but not seek()
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001868class Tellable:
1869 def __init__(self, fp):
1870 self.fp = fp
1871 self.offset = 0
1872
1873 def write(self, data):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02001874 n = self.fp.write(data)
1875 self.offset += n
1876 return n
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001877
1878 def tell(self):
1879 return self.offset
1880
1881 def flush(self):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02001882 self.fp.flush()
1883
1884class Unseekable:
1885 def __init__(self, fp):
1886 self.fp = fp
1887
1888 def write(self, data):
1889 return self.fp.write(data)
1890
1891 def flush(self):
1892 self.fp.flush()
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001893
1894class UnseekableTests(unittest.TestCase):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02001895 def test_writestr(self):
1896 for wrapper in (lambda f: f), Tellable, Unseekable:
1897 with self.subTest(wrapper=wrapper):
1898 f = io.BytesIO()
1899 f.write(b'abc')
1900 bf = io.BufferedWriter(f)
1901 with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) as zipfp:
1902 zipfp.writestr('ones', b'111')
1903 zipfp.writestr('twos', b'222')
1904 self.assertEqual(f.getvalue()[:5], b'abcPK')
1905 with zipfile.ZipFile(f, mode='r') as zipf:
1906 with zipf.open('ones') as zopen:
1907 self.assertEqual(zopen.read(), b'111')
1908 with zipf.open('twos') as zopen:
1909 self.assertEqual(zopen.read(), b'222')
1910
1911 def test_write(self):
1912 for wrapper in (lambda f: f), Tellable, Unseekable:
1913 with self.subTest(wrapper=wrapper):
1914 f = io.BytesIO()
1915 f.write(b'abc')
1916 bf = io.BufferedWriter(f)
1917 with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) as zipfp:
1918 self.addCleanup(unlink, TESTFN)
1919 with open(TESTFN, 'wb') as f2:
1920 f2.write(b'111')
1921 zipfp.write(TESTFN, 'ones')
1922 with open(TESTFN, 'wb') as f2:
1923 f2.write(b'222')
1924 zipfp.write(TESTFN, 'twos')
1925 self.assertEqual(f.getvalue()[:5], b'abcPK')
1926 with zipfile.ZipFile(f, mode='r') as zipf:
1927 with zipf.open('ones') as zopen:
1928 self.assertEqual(zopen.read(), b'111')
1929 with zipf.open('twos') as zopen:
1930 self.assertEqual(zopen.read(), b'222')
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001931
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001932 def test_open_write(self):
1933 for wrapper in (lambda f: f), Tellable, Unseekable:
1934 with self.subTest(wrapper=wrapper):
1935 f = io.BytesIO()
1936 f.write(b'abc')
1937 bf = io.BufferedWriter(f)
1938 with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) as zipf:
1939 with zipf.open('ones', 'w') as zopen:
1940 zopen.write(b'111')
1941 with zipf.open('twos', 'w') as zopen:
1942 zopen.write(b'222')
1943 self.assertEqual(f.getvalue()[:5], b'abcPK')
1944 with zipfile.ZipFile(f) as zipf:
1945 self.assertEqual(zipf.read('ones'), b'111')
1946 self.assertEqual(zipf.read('twos'), b'222')
1947
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001948
Ezio Melotti975077a2011-05-19 22:03:22 +03001949@requires_zlib
Guido van Rossumd8faa362007-04-27 19:54:29 +00001950class TestsWithMultipleOpens(unittest.TestCase):
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001951 @classmethod
1952 def setUpClass(cls):
1953 cls.data1 = b'111' + getrandbytes(10000)
1954 cls.data2 = b'222' + getrandbytes(10000)
1955
1956 def make_test_archive(self, f):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001957 # Create the ZIP archive
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001958 with zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as zipfp:
1959 zipfp.writestr('ones', self.data1)
1960 zipfp.writestr('twos', self.data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001961
Ezio Melottiafd0d112009-07-15 17:17:17 +00001962 def test_same_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001963 # Verify that (when the ZipFile is in control of creating file objects)
1964 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001965 for f in get_files(self):
1966 self.make_test_archive(f)
1967 with zipfile.ZipFile(f, mode="r") as zipf:
1968 with zipf.open('ones') as zopen1, zipf.open('ones') as zopen2:
1969 data1 = zopen1.read(500)
1970 data2 = zopen2.read(500)
1971 data1 += zopen1.read()
1972 data2 += zopen2.read()
1973 self.assertEqual(data1, data2)
1974 self.assertEqual(data1, self.data1)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001975
Ezio Melottiafd0d112009-07-15 17:17:17 +00001976 def test_different_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001977 # Verify that (when the ZipFile is in control of creating file objects)
1978 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001979 for f in get_files(self):
1980 self.make_test_archive(f)
1981 with zipfile.ZipFile(f, mode="r") as zipf:
1982 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1983 data1 = zopen1.read(500)
1984 data2 = zopen2.read(500)
1985 data1 += zopen1.read()
1986 data2 += zopen2.read()
1987 self.assertEqual(data1, self.data1)
1988 self.assertEqual(data2, self.data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001989
Ezio Melottiafd0d112009-07-15 17:17:17 +00001990 def test_interleaved(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001991 # Verify that (when the ZipFile is in control of creating file objects)
1992 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001993 for f in get_files(self):
1994 self.make_test_archive(f)
1995 with zipfile.ZipFile(f, mode="r") as zipf:
Serhiy Storchakad76c7c22016-05-13 21:18:58 +03001996 with zipf.open('ones') as zopen1:
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001997 data1 = zopen1.read(500)
Serhiy Storchakad76c7c22016-05-13 21:18:58 +03001998 with zipf.open('twos') as zopen2:
1999 data2 = zopen2.read(500)
2000 data1 += zopen1.read()
2001 data2 += zopen2.read()
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02002002 self.assertEqual(data1, self.data1)
2003 self.assertEqual(data2, self.data2)
2004
2005 def test_read_after_close(self):
2006 for f in get_files(self):
2007 self.make_test_archive(f)
2008 with contextlib.ExitStack() as stack:
2009 with zipfile.ZipFile(f, 'r') as zipf:
2010 zopen1 = stack.enter_context(zipf.open('ones'))
2011 zopen2 = stack.enter_context(zipf.open('twos'))
Brian Curtin8fb9b862010-11-18 02:15:28 +00002012 data1 = zopen1.read(500)
2013 data2 = zopen2.read(500)
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02002014 data1 += zopen1.read()
2015 data2 += zopen2.read()
2016 self.assertEqual(data1, self.data1)
2017 self.assertEqual(data2, self.data2)
2018
2019 def test_read_after_write(self):
2020 for f in get_files(self):
2021 with zipfile.ZipFile(f, 'w', zipfile.ZIP_DEFLATED) as zipf:
2022 zipf.writestr('ones', self.data1)
2023 zipf.writestr('twos', self.data2)
2024 with zipf.open('ones') as zopen1:
2025 data1 = zopen1.read(500)
2026 self.assertEqual(data1, self.data1[:500])
2027 with zipfile.ZipFile(f, 'r') as zipf:
2028 data1 = zipf.read('ones')
2029 data2 = zipf.read('twos')
2030 self.assertEqual(data1, self.data1)
2031 self.assertEqual(data2, self.data2)
2032
2033 def test_write_after_read(self):
2034 for f in get_files(self):
2035 with zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as zipf:
2036 zipf.writestr('ones', self.data1)
2037 with zipf.open('ones') as zopen1:
2038 zopen1.read(500)
2039 zipf.writestr('twos', self.data2)
2040 with zipfile.ZipFile(f, 'r') as zipf:
2041 data1 = zipf.read('ones')
2042 data2 = zipf.read('twos')
2043 self.assertEqual(data1, self.data1)
2044 self.assertEqual(data2, self.data2)
2045
2046 def test_many_opens(self):
2047 # Verify that read() and open() promptly close the file descriptor,
2048 # and don't rely on the garbage collector to free resources.
2049 self.make_test_archive(TESTFN2)
2050 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
2051 for x in range(100):
2052 zipf.read('ones')
2053 with zipf.open('ones') as zopen1:
2054 pass
2055 with open(os.devnull) as f:
2056 self.assertLess(f.fileno(), 100)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002057
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03002058 def test_write_while_reading(self):
2059 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_DEFLATED) as zipf:
2060 zipf.writestr('ones', self.data1)
2061 with zipfile.ZipFile(TESTFN2, 'a', zipfile.ZIP_DEFLATED) as zipf:
2062 with zipf.open('ones', 'r') as r1:
2063 data1 = r1.read(500)
2064 with zipf.open('twos', 'w') as w1:
2065 w1.write(self.data2)
2066 data1 += r1.read()
2067 self.assertEqual(data1, self.data1)
2068 with zipfile.ZipFile(TESTFN2) as zipf:
2069 self.assertEqual(zipf.read('twos'), self.data2)
2070
Guido van Rossumd8faa362007-04-27 19:54:29 +00002071 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00002072 unlink(TESTFN2)
2073
Guido van Rossumd8faa362007-04-27 19:54:29 +00002074
Martin v. Löwis59e47792009-01-24 14:10:07 +00002075class TestWithDirectory(unittest.TestCase):
2076 def setUp(self):
2077 os.mkdir(TESTFN2)
2078
Ezio Melottiafd0d112009-07-15 17:17:17 +00002079 def test_extract_dir(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00002080 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
2081 zipf.extractall(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00002082 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
2083 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
2084 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
2085
Ezio Melottiafd0d112009-07-15 17:17:17 +00002086 def test_bug_6050(self):
Martin v. Löwis70ccd162009-05-24 19:47:22 +00002087 # Extraction should succeed if directories already exist
2088 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottiafd0d112009-07-15 17:17:17 +00002089 self.test_extract_dir()
Martin v. Löwis70ccd162009-05-24 19:47:22 +00002090
Serhiy Storchaka46a34922014-09-23 22:40:23 +03002091 def test_write_dir(self):
2092 dirpath = os.path.join(TESTFN2, "x")
2093 os.mkdir(dirpath)
2094 mode = os.stat(dirpath).st_mode & 0xFFFF
2095 with zipfile.ZipFile(TESTFN, "w") as zipf:
2096 zipf.write(dirpath)
2097 zinfo = zipf.filelist[0]
2098 self.assertTrue(zinfo.filename.endswith("/x/"))
2099 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
2100 zipf.write(dirpath, "y")
2101 zinfo = zipf.filelist[1]
2102 self.assertTrue(zinfo.filename, "y/")
2103 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
2104 with zipfile.ZipFile(TESTFN, "r") as zipf:
2105 zinfo = zipf.filelist[0]
2106 self.assertTrue(zinfo.filename.endswith("/x/"))
2107 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
2108 zinfo = zipf.filelist[1]
2109 self.assertTrue(zinfo.filename, "y/")
2110 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
2111 target = os.path.join(TESTFN2, "target")
2112 os.mkdir(target)
2113 zipf.extractall(target)
2114 self.assertTrue(os.path.isdir(os.path.join(target, "y")))
2115 self.assertEqual(len(os.listdir(target)), 2)
2116
2117 def test_writestr_dir(self):
Martin v. Löwis59e47792009-01-24 14:10:07 +00002118 os.mkdir(os.path.join(TESTFN2, "x"))
Serhiy Storchaka46a34922014-09-23 22:40:23 +03002119 with zipfile.ZipFile(TESTFN, "w") as zipf:
2120 zipf.writestr("x/", b'')
2121 zinfo = zipf.filelist[0]
2122 self.assertEqual(zinfo.filename, "x/")
2123 self.assertEqual(zinfo.external_attr, (0o40775 << 16) | 0x10)
2124 with zipfile.ZipFile(TESTFN, "r") as zipf:
2125 zinfo = zipf.filelist[0]
2126 self.assertTrue(zinfo.filename.endswith("x/"))
2127 self.assertEqual(zinfo.external_attr, (0o40775 << 16) | 0x10)
2128 target = os.path.join(TESTFN2, "target")
2129 os.mkdir(target)
2130 zipf.extractall(target)
2131 self.assertTrue(os.path.isdir(os.path.join(target, "x")))
2132 self.assertEqual(os.listdir(target), ["x"])
Martin v. Löwis59e47792009-01-24 14:10:07 +00002133
2134 def tearDown(self):
Victor Stinner57004c62014-09-04 00:49:01 +02002135 rmtree(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00002136 if os.path.exists(TESTFN):
Ezio Melotti76430242009-07-11 18:28:48 +00002137 unlink(TESTFN)
Martin v. Löwis59e47792009-01-24 14:10:07 +00002138
Guido van Rossumd8faa362007-04-27 19:54:29 +00002139
Serhiy Storchaka503f9082016-02-08 00:02:25 +02002140class ZipInfoTests(unittest.TestCase):
2141 def test_from_file(self):
2142 zi = zipfile.ZipInfo.from_file(__file__)
2143 self.assertEqual(posixpath.basename(zi.filename), 'test_zipfile.py')
2144 self.assertFalse(zi.is_dir())
Serhiy Storchaka8606e952017-03-08 14:37:51 +02002145 self.assertEqual(zi.file_size, os.path.getsize(__file__))
2146
2147 def test_from_file_pathlike(self):
2148 zi = zipfile.ZipInfo.from_file(pathlib.Path(__file__))
2149 self.assertEqual(posixpath.basename(zi.filename), 'test_zipfile.py')
2150 self.assertFalse(zi.is_dir())
2151 self.assertEqual(zi.file_size, os.path.getsize(__file__))
2152
2153 def test_from_file_bytes(self):
2154 zi = zipfile.ZipInfo.from_file(os.fsencode(__file__), 'test')
2155 self.assertEqual(posixpath.basename(zi.filename), 'test')
2156 self.assertFalse(zi.is_dir())
2157 self.assertEqual(zi.file_size, os.path.getsize(__file__))
2158
2159 def test_from_file_fileno(self):
2160 with open(__file__, 'rb') as f:
2161 zi = zipfile.ZipInfo.from_file(f.fileno(), 'test')
2162 self.assertEqual(posixpath.basename(zi.filename), 'test')
2163 self.assertFalse(zi.is_dir())
2164 self.assertEqual(zi.file_size, os.path.getsize(__file__))
Serhiy Storchaka503f9082016-02-08 00:02:25 +02002165
2166 def test_from_dir(self):
2167 dirpath = os.path.dirname(os.path.abspath(__file__))
2168 zi = zipfile.ZipInfo.from_file(dirpath, 'stdlib_tests')
2169 self.assertEqual(zi.filename, 'stdlib_tests/')
2170 self.assertTrue(zi.is_dir())
2171 self.assertEqual(zi.compress_type, zipfile.ZIP_STORED)
2172 self.assertEqual(zi.file_size, 0)
2173
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002174
2175class CommandLineTest(unittest.TestCase):
2176
2177 def zipfilecmd(self, *args, **kwargs):
2178 rc, out, err = script_helper.assert_python_ok('-m', 'zipfile', *args,
2179 **kwargs)
2180 return out.replace(os.linesep.encode(), b'\n')
2181
2182 def zipfilecmd_failure(self, *args):
2183 return script_helper.assert_python_failure('-m', 'zipfile', *args)
2184
Serhiy Storchaka150cd192017-04-07 18:56:12 +03002185 def test_bad_use(self):
2186 rc, out, err = self.zipfilecmd_failure()
2187 self.assertEqual(out, b'')
2188 self.assertIn(b'usage', err.lower())
2189 self.assertIn(b'error', err.lower())
2190 self.assertIn(b'required', err.lower())
2191 rc, out, err = self.zipfilecmd_failure('-l', '')
2192 self.assertEqual(out, b'')
2193 self.assertNotEqual(err.strip(), b'')
2194
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002195 def test_test_command(self):
2196 zip_name = findfile('zipdir.zip')
Serhiy Storchaka8c933102016-10-23 13:32:12 +03002197 for opt in '-t', '--test':
2198 out = self.zipfilecmd(opt, zip_name)
2199 self.assertEqual(out.rstrip(), b'Done testing')
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002200 zip_name = findfile('testtar.tar')
2201 rc, out, err = self.zipfilecmd_failure('-t', zip_name)
2202 self.assertEqual(out, b'')
2203
2204 def test_list_command(self):
2205 zip_name = findfile('zipdir.zip')
2206 t = io.StringIO()
2207 with zipfile.ZipFile(zip_name, 'r') as tf:
2208 tf.printdir(t)
2209 expected = t.getvalue().encode('ascii', 'backslashreplace')
Serhiy Storchaka8c933102016-10-23 13:32:12 +03002210 for opt in '-l', '--list':
2211 out = self.zipfilecmd(opt, zip_name,
2212 PYTHONIOENCODING='ascii:backslashreplace')
2213 self.assertEqual(out, expected)
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002214
Serhiy Storchakab4293ef2016-10-23 22:32:30 +03002215 @requires_zlib
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002216 def test_create_command(self):
2217 self.addCleanup(unlink, TESTFN)
2218 with open(TESTFN, 'w') as f:
2219 f.write('test 1')
2220 os.mkdir(TESTFNDIR)
2221 self.addCleanup(rmtree, TESTFNDIR)
2222 with open(os.path.join(TESTFNDIR, 'file.txt'), 'w') as f:
2223 f.write('test 2')
2224 files = [TESTFN, TESTFNDIR]
2225 namelist = [TESTFN, TESTFNDIR + '/', TESTFNDIR + '/file.txt']
Serhiy Storchaka8c933102016-10-23 13:32:12 +03002226 for opt in '-c', '--create':
2227 try:
2228 out = self.zipfilecmd(opt, TESTFN2, *files)
2229 self.assertEqual(out, b'')
2230 with zipfile.ZipFile(TESTFN2) as zf:
2231 self.assertEqual(zf.namelist(), namelist)
2232 self.assertEqual(zf.read(namelist[0]), b'test 1')
2233 self.assertEqual(zf.read(namelist[2]), b'test 2')
2234 finally:
2235 unlink(TESTFN2)
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002236
2237 def test_extract_command(self):
2238 zip_name = findfile('zipdir.zip')
Serhiy Storchaka8c933102016-10-23 13:32:12 +03002239 for opt in '-e', '--extract':
2240 with temp_dir() as extdir:
2241 out = self.zipfilecmd(opt, zip_name, extdir)
2242 self.assertEqual(out, b'')
2243 with zipfile.ZipFile(zip_name) as zf:
2244 for zi in zf.infolist():
2245 path = os.path.join(extdir,
2246 zi.filename.replace('/', os.sep))
2247 if zi.is_dir():
2248 self.assertTrue(os.path.isdir(path))
2249 else:
2250 self.assertTrue(os.path.isfile(path))
2251 with open(path, 'rb') as f:
2252 self.assertEqual(f.read(), zf.read(zi))
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002253
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00002254if __name__ == "__main__":
Brett Cannond5b4e1d2013-06-12 19:57:19 -04002255 unittest.main()