blob: f3d993608f62e28768f3eae312df0de60ca1d8cb [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,
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +020019 captured_stdout, check_warnings)
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
737class PyZipFileTests(unittest.TestCase):
738 def assertCompiledIn(self, name, namelist):
739 if name + 'o' not in namelist:
740 self.assertIn(name + 'c', namelist)
741
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200742 def requiresWriteAccess(self, path):
Berker Peksage1efc072015-02-16 04:36:18 +0200743 # effective_ids unavailable on windows
744 if not os.access(path, os.W_OK,
745 effective_ids=os.access in os.supports_effective_ids):
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200746 self.skipTest('requires write access to the installed location')
Serhiy Storchakad86a6ef2015-09-19 10:55:20 +0300747 filename = os.path.join(path, 'test_zipfile.try')
748 try:
749 fd = os.open(filename, os.O_WRONLY | os.O_CREAT)
750 os.close(fd)
751 except Exception:
752 self.skipTest('requires write access to the installed location')
753 unlink(filename)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200754
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300755 def test_write_pyfile(self):
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200756 self.requiresWriteAccess(os.path.dirname(__file__))
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300757 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
758 fn = __file__
Brett Cannonf299abd2015-04-13 14:21:02 -0400759 if fn.endswith('.pyc'):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300760 path_split = fn.split(os.sep)
761 if os.altsep is not None:
762 path_split.extend(fn.split(os.altsep))
763 if '__pycache__' in path_split:
Serhiy Storchaka9068e4d2013-07-22 21:02:14 +0300764 fn = importlib.util.source_from_cache(fn)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300765 else:
766 fn = fn[:-1]
767
768 zipfp.writepy(fn)
769
770 bn = os.path.basename(fn)
771 self.assertNotIn(bn, zipfp.namelist())
772 self.assertCompiledIn(bn, zipfp.namelist())
773
774 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
775 fn = __file__
Brett Cannonf299abd2015-04-13 14:21:02 -0400776 if fn.endswith('.pyc'):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300777 fn = fn[:-1]
778
779 zipfp.writepy(fn, "testpackage")
780
781 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
782 self.assertNotIn(bn, zipfp.namelist())
783 self.assertCompiledIn(bn, zipfp.namelist())
784
785 def test_write_python_package(self):
786 import email
787 packagedir = os.path.dirname(email.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200788 self.requiresWriteAccess(packagedir)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300789
790 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
791 zipfp.writepy(packagedir)
792
793 # Check for a couple of modules at different levels of the
794 # hierarchy
795 names = zipfp.namelist()
796 self.assertCompiledIn('email/__init__.py', names)
797 self.assertCompiledIn('email/mime/text.py', names)
798
Christian Tismer59202e52013-10-21 03:59:23 +0200799 def test_write_filtered_python_package(self):
800 import test
801 packagedir = os.path.dirname(test.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200802 self.requiresWriteAccess(packagedir)
Christian Tismer59202e52013-10-21 03:59:23 +0200803
804 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
805
Christian Tismer59202e52013-10-21 03:59:23 +0200806 # first make sure that the test folder gives error messages
Georg Brandla6065422013-10-21 08:29:29 +0200807 # (on the badsyntax_... files)
808 with captured_stdout() as reportSIO:
809 zipfp.writepy(packagedir)
Christian Tismer59202e52013-10-21 03:59:23 +0200810 reportStr = reportSIO.getvalue()
811 self.assertTrue('SyntaxError' in reportStr)
812
Christian Tismer410d9312013-10-22 04:09:28 +0200813 # then check that the filter works on the whole package
Georg Brandla6065422013-10-21 08:29:29 +0200814 with captured_stdout() as reportSIO:
815 zipfp.writepy(packagedir, filterfunc=lambda whatever: False)
Christian Tismer59202e52013-10-21 03:59:23 +0200816 reportStr = reportSIO.getvalue()
817 self.assertTrue('SyntaxError' not in reportStr)
818
Christian Tismer410d9312013-10-22 04:09:28 +0200819 # then check that the filter works on individual files
Larry Hastings7e63b362015-05-08 06:54:58 -0700820 def filter(path):
821 return not os.path.basename(path).startswith("bad")
Serhiy Storchakac46d1fa2014-01-20 21:59:33 +0200822 with captured_stdout() as reportSIO, self.assertWarns(UserWarning):
Larry Hastings7e63b362015-05-08 06:54:58 -0700823 zipfp.writepy(packagedir, filterfunc=filter)
Christian Tismer410d9312013-10-22 04:09:28 +0200824 reportStr = reportSIO.getvalue()
825 if reportStr:
826 print(reportStr)
827 self.assertTrue('SyntaxError' not in reportStr)
828
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300829 def test_write_with_optimization(self):
830 import email
831 packagedir = os.path.dirname(email.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200832 self.requiresWriteAccess(packagedir)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300833 optlevel = 1 if __debug__ else 0
Brett Cannonf299abd2015-04-13 14:21:02 -0400834 ext = '.pyc'
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300835
836 with TemporaryFile() as t, \
Christian Tismer59202e52013-10-21 03:59:23 +0200837 zipfile.PyZipFile(t, "w", optimize=optlevel) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300838 zipfp.writepy(packagedir)
839
840 names = zipfp.namelist()
841 self.assertIn('email/__init__' + ext, names)
842 self.assertIn('email/mime/text' + ext, names)
843
844 def test_write_python_directory(self):
845 os.mkdir(TESTFN2)
846 try:
847 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
848 fp.write("print(42)\n")
849
850 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
851 fp.write("print(42 * 42)\n")
852
853 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
854 fp.write("bla bla bla\n")
855
856 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
857 zipfp.writepy(TESTFN2)
858
859 names = zipfp.namelist()
860 self.assertCompiledIn('mod1.py', names)
861 self.assertCompiledIn('mod2.py', names)
862 self.assertNotIn('mod2.txt', names)
863
864 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200865 rmtree(TESTFN2)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300866
Christian Tismer410d9312013-10-22 04:09:28 +0200867 def test_write_python_directory_filtered(self):
868 os.mkdir(TESTFN2)
869 try:
870 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
871 fp.write("print(42)\n")
872
873 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
874 fp.write("print(42 * 42)\n")
875
876 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
877 zipfp.writepy(TESTFN2, filterfunc=lambda fn:
878 not fn.endswith('mod2.py'))
879
880 names = zipfp.namelist()
881 self.assertCompiledIn('mod1.py', names)
882 self.assertNotIn('mod2.py', names)
883
884 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200885 rmtree(TESTFN2)
Christian Tismer410d9312013-10-22 04:09:28 +0200886
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300887 def test_write_non_pyfile(self):
888 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
889 with open(TESTFN, 'w') as f:
890 f.write('most definitely not a python file')
891 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
Victor Stinner88b215e2014-09-04 00:51:09 +0200892 unlink(TESTFN)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300893
894 def test_write_pyfile_bad_syntax(self):
895 os.mkdir(TESTFN2)
896 try:
897 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
898 fp.write("Bad syntax in python file\n")
899
900 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
901 # syntax errors are printed to stdout
902 with captured_stdout() as s:
903 zipfp.writepy(os.path.join(TESTFN2, "mod1.py"))
904
905 self.assertIn("SyntaxError", s.getvalue())
906
907 # as it will not have compiled the python file, it will
Brett Cannonf299abd2015-04-13 14:21:02 -0400908 # include the .py file not .pyc
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300909 names = zipfp.namelist()
910 self.assertIn('mod1.py', names)
911 self.assertNotIn('mod1.pyc', names)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300912
913 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200914 rmtree(TESTFN2)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300915
Serhiy Storchaka8606e952017-03-08 14:37:51 +0200916 def test_write_pathlike(self):
917 os.mkdir(TESTFN2)
918 try:
919 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
920 fp.write("print(42)\n")
921
922 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
923 zipfp.writepy(pathlib.Path(TESTFN2) / "mod1.py")
924 names = zipfp.namelist()
925 self.assertCompiledIn('mod1.py', names)
926 finally:
927 rmtree(TESTFN2)
928
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300929
930class ExtractTests(unittest.TestCase):
Serhiy Storchaka8606e952017-03-08 14:37:51 +0200931
932 def make_test_file(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000933 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
934 for fpath, fdata in SMALL_TEST_DATA:
935 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000936
Serhiy Storchaka8606e952017-03-08 14:37:51 +0200937 def test_extract(self):
938 with temp_cwd():
939 self.make_test_file()
940 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
941 for fpath, fdata in SMALL_TEST_DATA:
942 writtenfile = zipfp.extract(fpath)
943
944 # make sure it was written to the right place
945 correctfile = os.path.join(os.getcwd(), fpath)
946 correctfile = os.path.normpath(correctfile)
947
948 self.assertEqual(writtenfile, correctfile)
949
950 # make sure correct data is in correct file
951 with open(writtenfile, "rb") as f:
952 self.assertEqual(fdata.encode(), f.read())
953
954 unlink(writtenfile)
955
956 def _test_extract_with_target(self, target):
957 self.make_test_file()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000958 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
959 for fpath, fdata in SMALL_TEST_DATA:
Serhiy Storchaka8606e952017-03-08 14:37:51 +0200960 writtenfile = zipfp.extract(fpath, target)
Christian Heimes790c8232008-01-07 21:14:23 +0000961
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000962 # make sure it was written to the right place
Serhiy Storchaka8606e952017-03-08 14:37:51 +0200963 correctfile = os.path.join(target, fpath)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000964 correctfile = os.path.normpath(correctfile)
Serhiy Storchaka8606e952017-03-08 14:37:51 +0200965 self.assertTrue(os.path.samefile(writtenfile, correctfile), (writtenfile, target))
Christian Heimes790c8232008-01-07 21:14:23 +0000966
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000967 # make sure correct data is in correct file
Brian Curtin8fb9b862010-11-18 02:15:28 +0000968 with open(writtenfile, "rb") as f:
969 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000970
Victor Stinner88b215e2014-09-04 00:51:09 +0200971 unlink(writtenfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000972
Serhiy Storchaka8606e952017-03-08 14:37:51 +0200973 unlink(TESTFN2)
974
975 def test_extract_with_target(self):
976 with temp_dir() as extdir:
977 self._test_extract_with_target(extdir)
978
979 def test_extract_with_target_pathlike(self):
980 with temp_dir() as extdir:
981 self._test_extract_with_target(pathlib.Path(extdir))
Christian Heimes790c8232008-01-07 21:14:23 +0000982
Ezio Melottiafd0d112009-07-15 17:17:17 +0000983 def test_extract_all(self):
Serhiy Storchaka8606e952017-03-08 14:37:51 +0200984 with temp_cwd():
985 self.make_test_file()
986 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
987 zipfp.extractall()
988 for fpath, fdata in SMALL_TEST_DATA:
989 outfile = os.path.join(os.getcwd(), fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000990
Serhiy Storchaka8606e952017-03-08 14:37:51 +0200991 with open(outfile, "rb") as f:
992 self.assertEqual(fdata.encode(), f.read())
993
994 unlink(outfile)
995
996 def _test_extract_all_with_target(self, target):
997 self.make_test_file()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000998 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
Serhiy Storchaka8606e952017-03-08 14:37:51 +0200999 zipfp.extractall(target)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001000 for fpath, fdata in SMALL_TEST_DATA:
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001001 outfile = os.path.join(target, fpath)
Christian Heimes790c8232008-01-07 21:14:23 +00001002
Brian Curtin8fb9b862010-11-18 02:15:28 +00001003 with open(outfile, "rb") as f:
1004 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +00001005
Victor Stinner88b215e2014-09-04 00:51:09 +02001006 unlink(outfile)
Christian Heimes790c8232008-01-07 21:14:23 +00001007
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001008 unlink(TESTFN2)
1009
1010 def test_extract_all_with_target(self):
1011 with temp_dir() as extdir:
1012 self._test_extract_all_with_target(extdir)
1013
1014 def test_extract_all_with_target_pathlike(self):
1015 with temp_dir() as extdir:
1016 self._test_extract_all_with_target(pathlib.Path(extdir))
Christian Heimes790c8232008-01-07 21:14:23 +00001017
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001018 def check_file(self, filename, content):
1019 self.assertTrue(os.path.isfile(filename))
1020 with open(filename, 'rb') as f:
1021 self.assertEqual(f.read(), content)
1022
Gregory P. Smith09aa7522013-02-03 00:36:32 -08001023 def test_sanitize_windows_name(self):
1024 san = zipfile.ZipFile._sanitize_windows_name
1025 # Passing pathsep in allows this test to work regardless of platform.
1026 self.assertEqual(san(r',,?,C:,foo,bar/z', ','), r'_,C_,foo,bar/z')
1027 self.assertEqual(san(r'a\b,c<d>e|f"g?h*i', ','), r'a\b,c_d_e_f_g_h_i')
1028 self.assertEqual(san('../../foo../../ba..r', '/'), r'foo/ba..r')
1029
1030 def test_extract_hackers_arcnames_common_cases(self):
1031 common_hacknames = [
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001032 ('../foo/bar', 'foo/bar'),
1033 ('foo/../bar', 'foo/bar'),
1034 ('foo/../../bar', 'foo/bar'),
1035 ('foo/bar/..', 'foo/bar'),
1036 ('./../foo/bar', 'foo/bar'),
1037 ('/foo/bar', 'foo/bar'),
1038 ('/foo/../bar', 'foo/bar'),
1039 ('/foo/../../bar', 'foo/bar'),
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001040 ]
Gregory P. Smith09aa7522013-02-03 00:36:32 -08001041 self._test_extract_hackers_arcnames(common_hacknames)
1042
1043 @unittest.skipIf(os.path.sep != '\\', 'Requires \\ as path separator.')
1044 def test_extract_hackers_arcnames_windows_only(self):
1045 """Test combination of path fixing and windows name sanitization."""
1046 windows_hacknames = [
Christian Tismer59202e52013-10-21 03:59:23 +02001047 (r'..\foo\bar', 'foo/bar'),
1048 (r'..\/foo\/bar', 'foo/bar'),
1049 (r'foo/\..\/bar', 'foo/bar'),
1050 (r'foo\/../\bar', 'foo/bar'),
1051 (r'C:foo/bar', 'foo/bar'),
1052 (r'C:/foo/bar', 'foo/bar'),
1053 (r'C://foo/bar', 'foo/bar'),
1054 (r'C:\foo\bar', 'foo/bar'),
1055 (r'//conky/mountpoint/foo/bar', 'foo/bar'),
1056 (r'\\conky\mountpoint\foo\bar', 'foo/bar'),
1057 (r'///conky/mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
1058 (r'\\\conky\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
1059 (r'//conky//mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
1060 (r'\\conky\\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
1061 (r'//?/C:/foo/bar', 'foo/bar'),
1062 (r'\\?\C:\foo\bar', 'foo/bar'),
1063 (r'C:/../C:/foo/bar', 'C_/foo/bar'),
1064 (r'a:b\c<d>e|f"g?h*i', 'b/c_d_e_f_g_h_i'),
1065 ('../../foo../../ba..r', 'foo/ba..r'),
Gregory P. Smith09aa7522013-02-03 00:36:32 -08001066 ]
1067 self._test_extract_hackers_arcnames(windows_hacknames)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001068
Gregory P. Smith09aa7522013-02-03 00:36:32 -08001069 @unittest.skipIf(os.path.sep != '/', r'Requires / as path separator.')
1070 def test_extract_hackers_arcnames_posix_only(self):
1071 posix_hacknames = [
1072 ('//foo/bar', 'foo/bar'),
1073 ('../../foo../../ba..r', 'foo../ba..r'),
1074 (r'foo/..\bar', r'foo/..\bar'),
1075 ]
1076 self._test_extract_hackers_arcnames(posix_hacknames)
1077
1078 def _test_extract_hackers_arcnames(self, hacknames):
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001079 for arcname, fixedname in hacknames:
1080 content = b'foobar' + arcname.encode()
1081 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipfp:
Serhiy Storchakae5e64442013-02-02 19:50:59 +02001082 zinfo = zipfile.ZipInfo()
1083 # preserve backslashes
1084 zinfo.filename = arcname
1085 zinfo.external_attr = 0o600 << 16
1086 zipfp.writestr(zinfo, content)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001087
Serhiy Storchakae5e64442013-02-02 19:50:59 +02001088 arcname = arcname.replace(os.sep, "/")
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001089 targetpath = os.path.join('target', 'subdir', 'subsub')
1090 correctfile = os.path.join(targetpath, *fixedname.split('/'))
1091
1092 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1093 writtenfile = zipfp.extract(arcname, targetpath)
Serhiy Storchakae5e64442013-02-02 19:50:59 +02001094 self.assertEqual(writtenfile, correctfile,
Gregory P. Smith09aa7522013-02-03 00:36:32 -08001095 msg='extract %r: %r != %r' %
1096 (arcname, writtenfile, correctfile))
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001097 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001098 rmtree('target')
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001099
1100 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1101 zipfp.extractall(targetpath)
1102 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001103 rmtree('target')
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001104
1105 correctfile = os.path.join(os.getcwd(), *fixedname.split('/'))
1106
1107 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1108 writtenfile = zipfp.extract(arcname)
Serhiy Storchakae5e64442013-02-02 19:50:59 +02001109 self.assertEqual(writtenfile, correctfile,
1110 msg="extract %r" % arcname)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001111 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001112 rmtree(fixedname.split('/')[0])
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001113
1114 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1115 zipfp.extractall()
1116 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001117 rmtree(fixedname.split('/')[0])
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001118
Victor Stinner88b215e2014-09-04 00:51:09 +02001119 unlink(TESTFN2)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001120
Ronald Oussorenee5c8852010-02-07 20:24:02 +00001121
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001122class OtherTests(unittest.TestCase):
1123 def test_open_via_zip_info(self):
1124 # Create the ZIP archive
1125 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
1126 zipfp.writestr("name", "foo")
Serhiy Storchaka9b7a1a12014-01-20 21:57:40 +02001127 with self.assertWarns(UserWarning):
1128 zipfp.writestr("name", "bar")
1129 self.assertEqual(zipfp.namelist(), ["name"] * 2)
Ronald Oussorenee5c8852010-02-07 20:24:02 +00001130
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001131 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1132 infos = zipfp.infolist()
1133 data = b""
1134 for info in infos:
1135 with zipfp.open(info) as zipopen:
1136 data += zipopen.read()
1137 self.assertIn(data, {b"foobar", b"barfoo"})
1138 data = b""
1139 for info in infos:
1140 data += zipfp.read(info)
1141 self.assertIn(data, {b"foobar", b"barfoo"})
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001142
Gregory P. Smithb0d9ca92009-07-07 05:06:04 +00001143 def test_writestr_extended_local_header_issue1202(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001144 with zipfile.ZipFile(TESTFN2, 'w') as orig_zip:
1145 for data in 'abcdefghijklmnop':
1146 zinfo = zipfile.ZipInfo(data)
1147 zinfo.flag_bits |= 0x08 # Include an extended local header.
1148 orig_zip.writestr(zinfo, data)
1149
1150 def test_close(self):
1151 """Check that the zipfile is closed after the 'with' block."""
1152 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
1153 for fpath, fdata in SMALL_TEST_DATA:
1154 zipfp.writestr(fpath, fdata)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001155 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
1156 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001157
1158 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001159 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
1160 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001161
1162 def test_close_on_exception(self):
1163 """Check that the zipfile is closed if an exception is raised in the
1164 'with' block."""
1165 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
1166 for fpath, fdata in SMALL_TEST_DATA:
1167 zipfp.writestr(fpath, fdata)
1168
1169 try:
1170 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
Georg Brandl4d540882010-10-28 06:42:33 +00001171 raise zipfile.BadZipFile()
1172 except zipfile.BadZipFile:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001173 self.assertIsNone(zipfp2.fp, 'zipfp is not closed')
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001174
Martin v. Löwisd099b562012-05-01 14:08:22 +02001175 def test_unsupported_version(self):
1176 # File has an extract_version of 120
1177 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 +02001178 b'\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00xPK\x01\x02x\x03x\x00\x00\x00\x00'
1179 b'\x00!p\xa1@\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00'
1180 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00\x00xPK\x05\x06'
1181 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 +03001182
Martin v. Löwisd099b562012-05-01 14:08:22 +02001183 self.assertRaises(NotImplementedError, zipfile.ZipFile,
1184 io.BytesIO(data), 'r')
1185
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001186 @requires_zlib
1187 def test_read_unicode_filenames(self):
1188 # bug #10801
1189 fname = findfile('zip_cp437_header.zip')
1190 with zipfile.ZipFile(fname) as zipfp:
1191 for name in zipfp.namelist():
1192 zipfp.open(name).close()
1193
1194 def test_write_unicode_filenames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001195 with zipfile.ZipFile(TESTFN, "w") as zf:
1196 zf.writestr("foo.txt", "Test for unicode filename")
1197 zf.writestr("\xf6.txt", "Test for unicode filename")
Ezio Melottie9615932010-01-24 19:26:24 +00001198 self.assertIsInstance(zf.infolist()[0].filename, str)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001199
1200 with zipfile.ZipFile(TESTFN, "r") as zf:
1201 self.assertEqual(zf.filelist[0].filename, "foo.txt")
1202 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
Martin v. Löwis8570f6a2008-05-05 17:44:38 +00001203
Serhiy Storchaka764fc9b2015-03-25 10:09:41 +02001204 def test_exclusive_create_zip_file(self):
1205 """Test exclusive creating a new zipfile."""
1206 unlink(TESTFN2)
1207 filename = 'testfile.txt'
1208 content = b'hello, world. this is some content.'
1209 with zipfile.ZipFile(TESTFN2, "x", zipfile.ZIP_STORED) as zipfp:
1210 zipfp.writestr(filename, content)
1211 with self.assertRaises(FileExistsError):
1212 zipfile.ZipFile(TESTFN2, "x", zipfile.ZIP_STORED)
1213 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1214 self.assertEqual(zipfp.namelist(), [filename])
1215 self.assertEqual(zipfp.read(filename), content)
1216
Ezio Melottiafd0d112009-07-15 17:17:17 +00001217 def test_create_non_existent_file_for_append(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001218 if os.path.exists(TESTFN):
1219 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001220
Thomas Wouterscf297e42007-02-23 15:07:44 +00001221 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001222 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +00001223
Thomas Wouterscf297e42007-02-23 15:07:44 +00001224 try:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001225 with zipfile.ZipFile(TESTFN, 'a') as zf:
1226 zf.writestr(filename, content)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001227 except OSError:
Thomas Wouterscf297e42007-02-23 15:07:44 +00001228 self.fail('Could not append data to a non-existent zip file.')
1229
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001230 self.assertTrue(os.path.exists(TESTFN))
Thomas Wouterscf297e42007-02-23 15:07:44 +00001231
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001232 with zipfile.ZipFile(TESTFN, 'r') as zf:
1233 self.assertEqual(zf.read(filename), content)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001234
Ezio Melottiafd0d112009-07-15 17:17:17 +00001235 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001236 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti35386712009-12-31 13:22:41 +00001237 # it opens if there's an error in the file. If it doesn't, the
1238 # traceback holds a reference to the ZipFile object and, indirectly,
1239 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001240 # On Windows, this causes the os.unlink() call to fail because the
1241 # underlying file is still open. This is SF bug #412214.
1242 #
Ezio Melotti35386712009-12-31 13:22:41 +00001243 with open(TESTFN, "w") as fp:
1244 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001245 try:
1246 zf = zipfile.ZipFile(TESTFN)
Georg Brandl4d540882010-10-28 06:42:33 +00001247 except zipfile.BadZipFile:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001248 pass
1249
Ezio Melottiafd0d112009-07-15 17:17:17 +00001250 def test_is_zip_erroneous_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001251 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001252 # - passing a filename
1253 with open(TESTFN, "w") as fp:
1254 fp.write("this is not a legal zip file\n")
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001255 self.assertFalse(zipfile.is_zipfile(TESTFN))
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001256 # - passing a path-like object
1257 self.assertFalse(zipfile.is_zipfile(pathlib.Path(TESTFN)))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001258 # - passing a file object
1259 with open(TESTFN, "rb") as fp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001260 self.assertFalse(zipfile.is_zipfile(fp))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001261 # - passing a file-like object
1262 fp = io.BytesIO()
1263 fp.write(b"this is not a legal zip file\n")
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001264 self.assertFalse(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001265 fp.seek(0, 0)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001266 self.assertFalse(zipfile.is_zipfile(fp))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001267
Serhiy Storchakad2b15272013-01-31 15:27:07 +02001268 def test_damaged_zipfile(self):
1269 """Check that zipfiles with missing bytes at the end raise BadZipFile."""
1270 # - Create a valid zip file
1271 fp = io.BytesIO()
1272 with zipfile.ZipFile(fp, mode="w") as zipf:
1273 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
1274 zipfiledata = fp.getvalue()
1275
1276 # - Now create copies of it missing the last N bytes and make sure
1277 # a BadZipFile exception is raised when we try to open it
1278 for N in range(len(zipfiledata)):
1279 fp = io.BytesIO(zipfiledata[:N])
1280 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, fp)
1281
Ezio Melottiafd0d112009-07-15 17:17:17 +00001282 def test_is_zip_valid_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001283 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001284 # - passing a filename
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001285 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1286 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
1287
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001288 self.assertTrue(zipfile.is_zipfile(TESTFN))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001289 # - passing a file object
1290 with open(TESTFN, "rb") as fp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001291 self.assertTrue(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001292 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001293 zip_contents = fp.read()
1294 # - passing a file-like object
1295 fp = io.BytesIO()
1296 fp.write(zip_contents)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001297 self.assertTrue(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001298 fp.seek(0, 0)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001299 self.assertTrue(zipfile.is_zipfile(fp))
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001300
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001301 def test_non_existent_file_raises_OSError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001302 # make sure we don't raise an AttributeError when a partially-constructed
1303 # ZipFile instance is finalized; this tests for regression on SF tracker
1304 # bug #403871.
1305
1306 # The bug we're testing for caused an AttributeError to be raised
1307 # when a ZipFile instance was created for a file that did not
1308 # exist; the .fp member was not initialized but was needed by the
1309 # __del__() method. Since the AttributeError is in the __del__(),
1310 # it is ignored, but the user should be sufficiently annoyed by
1311 # the message on the output that regression will be noticed
1312 # quickly.
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001313 self.assertRaises(OSError, zipfile.ZipFile, TESTFN)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001314
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001315 def test_empty_file_raises_BadZipFile(self):
1316 f = open(TESTFN, 'w')
1317 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001318 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001319
Ezio Melotti35386712009-12-31 13:22:41 +00001320 with open(TESTFN, 'w') as fp:
1321 fp.write("short file")
Georg Brandl4d540882010-10-28 06:42:33 +00001322 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001323
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001324 def test_closed_zip_raises_ValueError(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001325 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001326 data = io.BytesIO()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001327 with zipfile.ZipFile(data, mode="w") as zipf:
1328 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001329
Andrew Svetlov737fb892012-12-18 21:14:22 +02001330 # This is correct; calling .read on a closed ZipFile should raise
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001331 # a ValueError, and so should calling .testzip. An earlier
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001332 # version of .testzip would swallow this exception (and any other)
1333 # and report that the first file in the archive was corrupt.
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001334 self.assertRaises(ValueError, zipf.read, "foo.txt")
1335 self.assertRaises(ValueError, zipf.open, "foo.txt")
1336 self.assertRaises(ValueError, zipf.testzip)
1337 self.assertRaises(ValueError, zipf.writestr, "bogus.txt", "bogus")
Brian Curtin8fb9b862010-11-18 02:15:28 +00001338 with open(TESTFN, 'w') as f:
1339 f.write('zipfile test data')
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001340 self.assertRaises(ValueError, zipf.write, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001341
Ezio Melottiafd0d112009-07-15 17:17:17 +00001342 def test_bad_constructor_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001343 """Check that bad modes passed to ZipFile constructor are caught."""
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001344 self.assertRaises(ValueError, zipfile.ZipFile, TESTFN, "q")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001345
Ezio Melottiafd0d112009-07-15 17:17:17 +00001346 def test_bad_open_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001347 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001348 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1349 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1350
1351 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Serhiy Storchakae670be22016-06-11 19:32:44 +03001352 # read the data to make sure the file is there
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001353 zipf.read("foo.txt")
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001354 self.assertRaises(ValueError, zipf.open, "foo.txt", "q")
Serhiy Storchakae670be22016-06-11 19:32:44 +03001355 # universal newlines support is removed
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001356 self.assertRaises(ValueError, zipf.open, "foo.txt", "U")
1357 self.assertRaises(ValueError, zipf.open, "foo.txt", "rU")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001358
Ezio Melottiafd0d112009-07-15 17:17:17 +00001359 def test_read0(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001360 """Check that calling read(0) on a ZipExtFile object returns an empty
1361 string and doesn't advance file pointer."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001362 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1363 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1364 # read the data to make sure the file is there
Brian Curtin8fb9b862010-11-18 02:15:28 +00001365 with zipf.open("foo.txt") as f:
1366 for i in range(FIXEDTEST_SIZE):
1367 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001368
Brian Curtin8fb9b862010-11-18 02:15:28 +00001369 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001370
Ezio Melottiafd0d112009-07-15 17:17:17 +00001371 def test_open_non_existent_item(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001372 """Check that attempting to call open() for an item that doesn't
1373 exist in the archive raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001374 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1375 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001376
Ezio Melottiafd0d112009-07-15 17:17:17 +00001377 def test_bad_compression_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001378 """Check that bad compression methods passed to ZipFile.open are
1379 caught."""
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001380 self.assertRaises(NotImplementedError, zipfile.ZipFile, TESTFN, "w", -1)
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001381
Martin v. Löwisb3260f02012-05-01 08:38:01 +02001382 def test_unsupported_compression(self):
1383 # data is declared as shrunk, but actually deflated
1384 data = (b'PK\x03\x04.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00'
Christian Tismer59202e52013-10-21 03:59:23 +02001385 b'\x00\x02\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00x\x03\x00PK\x01'
1386 b'\x02.\x03.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00\x00\x02\x00\x00'
1387 b'\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
1388 b'\x80\x01\x00\x00\x00\x00xPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00'
1389 b'/\x00\x00\x00!\x00\x00\x00\x00\x00')
Martin v. Löwisb3260f02012-05-01 08:38:01 +02001390 with zipfile.ZipFile(io.BytesIO(data), 'r') as zipf:
1391 self.assertRaises(NotImplementedError, zipf.open, 'x')
1392
Ezio Melottiafd0d112009-07-15 17:17:17 +00001393 def test_null_byte_in_filename(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001394 """Check that a filename containing a null byte is properly
1395 terminated."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001396 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1397 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
1398 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001399
Ezio Melottiafd0d112009-07-15 17:17:17 +00001400 def test_struct_sizes(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001401 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001402 self.assertEqual(zipfile.sizeEndCentDir, 22)
1403 self.assertEqual(zipfile.sizeCentralDir, 46)
1404 self.assertEqual(zipfile.sizeEndCentDir64, 56)
1405 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
1406
Ezio Melottiafd0d112009-07-15 17:17:17 +00001407 def test_comments(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001408 """Check that comments on the archive are handled properly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001409
1410 # check default comment is empty
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001411 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1412 self.assertEqual(zipf.comment, b'')
1413 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1414
1415 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1416 self.assertEqual(zipfr.comment, b'')
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001417
1418 # check a simple short comment
1419 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001420 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1421 zipf.comment = comment
1422 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1423 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1424 self.assertEqual(zipf.comment, comment)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001425
1426 # check a comment of max length
1427 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
1428 comment2 = comment2.encode("ascii")
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001429 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1430 zipf.comment = comment2
1431 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1432
1433 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1434 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001435
1436 # check a comment that is too long is truncated
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001437 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
Serhiy Storchaka9b7a1a12014-01-20 21:57:40 +02001438 with self.assertWarns(UserWarning):
1439 zipf.comment = comment2 + b'oops'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001440 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1441 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1442 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001443
Antoine Pitrouc3991852012-06-30 17:31:37 +02001444 # check that comments are correctly modified in append mode
1445 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1446 zipf.comment = b"original comment"
1447 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1448 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1449 zipf.comment = b"an updated comment"
1450 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1451 self.assertEqual(zipf.comment, b"an updated comment")
1452
1453 # check that comments are correctly shortened in append mode
1454 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1455 zipf.comment = b"original comment that's longer"
1456 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1457 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1458 zipf.comment = b"shorter comment"
1459 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1460 self.assertEqual(zipf.comment, b"shorter comment")
1461
R David Murrayf50b38a2012-04-12 18:44:58 -04001462 def test_unicode_comment(self):
1463 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1464 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1465 with self.assertRaises(TypeError):
1466 zipf.comment = "this is an error"
1467
1468 def test_change_comment_in_empty_archive(self):
1469 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1470 self.assertFalse(zipf.filelist)
1471 zipf.comment = b"this is a comment"
1472 with zipfile.ZipFile(TESTFN, "r") as zipf:
1473 self.assertEqual(zipf.comment, b"this is a comment")
1474
1475 def test_change_comment_in_nonempty_archive(self):
1476 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1477 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1478 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1479 self.assertTrue(zipf.filelist)
1480 zipf.comment = b"this is a comment"
1481 with zipfile.ZipFile(TESTFN, "r") as zipf:
1482 self.assertEqual(zipf.comment, b"this is a comment")
1483
Georg Brandl268e4d42010-10-14 06:59:45 +00001484 def test_empty_zipfile(self):
1485 # Check that creating a file in 'w' or 'a' mode and closing without
1486 # adding any files to the archives creates a valid empty ZIP file
1487 zipf = zipfile.ZipFile(TESTFN, mode="w")
1488 zipf.close()
1489 try:
1490 zipf = zipfile.ZipFile(TESTFN, mode="r")
1491 except zipfile.BadZipFile:
1492 self.fail("Unable to create empty ZIP file in 'w' mode")
1493
1494 zipf = zipfile.ZipFile(TESTFN, mode="a")
1495 zipf.close()
1496 try:
1497 zipf = zipfile.ZipFile(TESTFN, mode="r")
1498 except:
1499 self.fail("Unable to create empty ZIP file in 'a' mode")
1500
1501 def test_open_empty_file(self):
1502 # Issue 1710703: Check that opening a file with less than 22 bytes
Georg Brandl4d540882010-10-28 06:42:33 +00001503 # raises a BadZipFile exception (rather than the previously unhelpful
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001504 # OSError)
Georg Brandl268e4d42010-10-14 06:59:45 +00001505 f = open(TESTFN, 'w')
1506 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001507 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN, 'r')
Georg Brandl268e4d42010-10-14 06:59:45 +00001508
Senthil Kumaran29fa9d42011-10-20 01:46:00 +08001509 def test_create_zipinfo_before_1980(self):
1510 self.assertRaises(ValueError,
1511 zipfile.ZipInfo, 'seventies', (1979, 1, 1, 0, 0, 0))
1512
Gregory P. Smith0af8a862014-05-29 23:42:14 -07001513 def test_zipfile_with_short_extra_field(self):
1514 """If an extra field in the header is less than 4 bytes, skip it."""
1515 zipdata = (
1516 b'PK\x03\x04\x14\x00\x00\x00\x00\x00\x93\x9b\xad@\x8b\x9e'
1517 b'\xd9\xd3\x01\x00\x00\x00\x01\x00\x00\x00\x03\x00\x03\x00ab'
1518 b'c\x00\x00\x00APK\x01\x02\x14\x03\x14\x00\x00\x00\x00'
1519 b'\x00\x93\x9b\xad@\x8b\x9e\xd9\xd3\x01\x00\x00\x00\x01\x00\x00'
1520 b'\x00\x03\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00'
1521 b'\x00\x00\x00abc\x00\x00PK\x05\x06\x00\x00\x00\x00'
1522 b'\x01\x00\x01\x003\x00\x00\x00%\x00\x00\x00\x00\x00'
1523 )
1524 with zipfile.ZipFile(io.BytesIO(zipdata), 'r') as zipf:
1525 # testzip returns the name of the first corrupt file, or None
1526 self.assertIsNone(zipf.testzip())
1527
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001528 def test_open_conflicting_handles(self):
1529 # It's only possible to open one writable file handle at a time
1530 msg1 = b"It's fun to charter an accountant!"
1531 msg2 = b"And sail the wide accountant sea"
1532 msg3 = b"To find, explore the funds offshore"
1533 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipf:
1534 with zipf.open('foo', mode='w') as w2:
1535 w2.write(msg1)
1536 with zipf.open('bar', mode='w') as w1:
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001537 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001538 zipf.open('handle', mode='w')
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001539 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001540 zipf.open('foo', mode='r')
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001541 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001542 zipf.writestr('str', 'abcde')
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001543 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001544 zipf.write(__file__, 'file')
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001545 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001546 zipf.close()
1547 w1.write(msg2)
1548 with zipf.open('baz', mode='w') as w2:
1549 w2.write(msg3)
1550
1551 with zipfile.ZipFile(TESTFN2, 'r') as zipf:
1552 self.assertEqual(zipf.read('foo'), msg1)
1553 self.assertEqual(zipf.read('bar'), msg2)
1554 self.assertEqual(zipf.read('baz'), msg3)
1555 self.assertEqual(zipf.namelist(), ['foo', 'bar', 'baz'])
1556
Guido van Rossumd8faa362007-04-27 19:54:29 +00001557 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001558 unlink(TESTFN)
1559 unlink(TESTFN2)
1560
Thomas Wouterscf297e42007-02-23 15:07:44 +00001561
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001562class AbstractBadCrcTests:
1563 def test_testzip_with_bad_crc(self):
1564 """Tests that files with bad CRCs return their name from testzip."""
1565 zipdata = self.zip_with_bad_crc
1566
1567 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1568 # testzip returns the name of the first corrupt file, or None
1569 self.assertEqual('afile', zipf.testzip())
1570
1571 def test_read_with_bad_crc(self):
1572 """Tests that files with bad CRCs raise a BadZipFile exception when read."""
1573 zipdata = self.zip_with_bad_crc
1574
1575 # Using ZipFile.read()
1576 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1577 self.assertRaises(zipfile.BadZipFile, zipf.read, 'afile')
1578
1579 # Using ZipExtFile.read()
1580 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1581 with zipf.open('afile', 'r') as corrupt_file:
1582 self.assertRaises(zipfile.BadZipFile, corrupt_file.read)
1583
1584 # Same with small reads (in order to exercise the buffering logic)
1585 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1586 with zipf.open('afile', 'r') as corrupt_file:
1587 corrupt_file.MIN_READ_SIZE = 2
1588 with self.assertRaises(zipfile.BadZipFile):
1589 while corrupt_file.read(2):
1590 pass
1591
1592
1593class StoredBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1594 compression = zipfile.ZIP_STORED
1595 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001596 b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
1597 b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
1598 b'ilehello,AworldP'
1599 b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
1600 b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
1601 b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
1602 b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
1603 b'\0\0/\0\0\0\0\0')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001604
1605@requires_zlib
1606class DeflateBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1607 compression = zipfile.ZIP_DEFLATED
1608 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001609 b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
1610 b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1611 b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
1612 b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
1613 b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
1614 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
1615 b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
1616 b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001617
1618@requires_bz2
1619class Bzip2BadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1620 compression = zipfile.ZIP_BZIP2
1621 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001622 b'PK\x03\x04\x14\x03\x00\x00\x0c\x00nu\x0c=FA'
1623 b'KE8\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1624 b'ileBZh91AY&SY\xd4\xa8\xca'
1625 b'\x7f\x00\x00\x0f\x11\x80@\x00\x06D\x90\x80 \x00 \xa5'
1626 b'P\xd9!\x03\x03\x13\x13\x13\x89\xa9\xa9\xc2u5:\x9f'
1627 b'\x8b\xb9"\x9c(HjTe?\x80PK\x01\x02\x14'
1628 b'\x03\x14\x03\x00\x00\x0c\x00nu\x0c=FAKE8'
1629 b'\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\x00'
1630 b'\x00 \x80\x80\x81\x00\x00\x00\x00afilePK'
1631 b'\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00\x00[\x00'
1632 b'\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001633
1634@requires_lzma
1635class LzmaBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1636 compression = zipfile.ZIP_LZMA
1637 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001638 b'PK\x03\x04\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
1639 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1640 b'ile\t\x04\x05\x00]\x00\x00\x00\x04\x004\x19I'
1641 b'\xee\x8d\xe9\x17\x89:3`\tq!.8\x00PK'
1642 b'\x01\x02\x14\x03\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
1643 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00'
1644 b'\x00\x00\x00\x00 \x80\x80\x81\x00\x00\x00\x00afil'
1645 b'ePK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00'
1646 b'\x00>\x00\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001647
1648
Thomas Wouterscf297e42007-02-23 15:07:44 +00001649class DecryptionTests(unittest.TestCase):
Ezio Melotti35386712009-12-31 13:22:41 +00001650 """Check that ZIP decryption works. Since the library does not
1651 support encryption at the moment, we use a pre-generated encrypted
1652 ZIP file."""
Thomas Wouterscf297e42007-02-23 15:07:44 +00001653
1654 data = (
Christian Tismer59202e52013-10-21 03:59:23 +02001655 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
1656 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
1657 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
1658 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
1659 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
1660 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
1661 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +00001662 data2 = (
Christian Tismer59202e52013-10-21 03:59:23 +02001663 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
1664 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
1665 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
1666 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
1667 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
1668 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
1669 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
1670 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +00001671
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001672 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +00001673 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +00001674
1675 def setUp(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001676 with open(TESTFN, "wb") as fp:
1677 fp.write(self.data)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001678 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti35386712009-12-31 13:22:41 +00001679 with open(TESTFN2, "wb") as fp:
1680 fp.write(self.data2)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001681 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001682
1683 def tearDown(self):
1684 self.zip.close()
1685 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001686 self.zip2.close()
1687 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001688
Ezio Melottiafd0d112009-07-15 17:17:17 +00001689 def test_no_password(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001690 # Reading the encrypted file without password
1691 # must generate a RunTime exception
1692 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001693 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001694
Ezio Melottiafd0d112009-07-15 17:17:17 +00001695 def test_bad_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001696 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001697 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001698 self.zip2.setpassword(b"perl")
1699 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001700
Ezio Melotti975077a2011-05-19 22:03:22 +03001701 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +00001702 def test_good_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001703 self.zip.setpassword(b"python")
Ezio Melotti35386712009-12-31 13:22:41 +00001704 self.assertEqual(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001705 self.zip2.setpassword(b"12345")
Ezio Melotti35386712009-12-31 13:22:41 +00001706 self.assertEqual(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001707
R. David Murray8d855d82010-12-21 21:53:37 +00001708 def test_unicode_password(self):
1709 self.assertRaises(TypeError, self.zip.setpassword, "unicode")
1710 self.assertRaises(TypeError, self.zip.read, "test.txt", "python")
1711 self.assertRaises(TypeError, self.zip.open, "test.txt", pwd="python")
1712 self.assertRaises(TypeError, self.zip.extract, "test.txt", pwd="python")
1713
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001714class AbstractTestsWithRandomBinaryFiles:
1715 @classmethod
1716 def setUpClass(cls):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001717 datacount = randint(16, 64)*1024 + randint(1, 1024)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001718 cls.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
1719 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001720
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001721 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001722 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +00001723 with open(TESTFN, "wb") as fp:
1724 fp.write(self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001725
1726 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001727 unlink(TESTFN)
1728 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001729
Ezio Melottiafd0d112009-07-15 17:17:17 +00001730 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001731 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001732 with zipfile.ZipFile(f, "w", compression) as zipfp:
1733 zipfp.write(TESTFN, "another.name")
1734 zipfp.write(TESTFN, TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001735
Ezio Melottiafd0d112009-07-15 17:17:17 +00001736 def zip_test(self, f, compression):
1737 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001738
1739 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001740 with zipfile.ZipFile(f, "r", compression) as zipfp:
1741 testdata = zipfp.read(TESTFN)
1742 self.assertEqual(len(testdata), len(self.data))
1743 self.assertEqual(testdata, self.data)
1744 self.assertEqual(zipfp.read("another.name"), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001745
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001746 def test_read(self):
1747 for f in get_files(self):
1748 self.zip_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001749
Ezio Melottiafd0d112009-07-15 17:17:17 +00001750 def zip_open_test(self, f, compression):
1751 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001752
1753 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001754 with zipfile.ZipFile(f, "r", compression) as zipfp:
1755 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001756 with zipfp.open(TESTFN) as zipopen1:
1757 while True:
1758 read_data = zipopen1.read(256)
1759 if not read_data:
1760 break
1761 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001762
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001763 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001764 with zipfp.open("another.name") as zipopen2:
1765 while True:
1766 read_data = zipopen2.read(256)
1767 if not read_data:
1768 break
1769 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001770
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001771 testdata1 = b''.join(zipdata1)
1772 self.assertEqual(len(testdata1), len(self.data))
1773 self.assertEqual(testdata1, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001774
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001775 testdata2 = b''.join(zipdata2)
Ezio Melotti35386712009-12-31 13:22:41 +00001776 self.assertEqual(len(testdata2), len(self.data))
1777 self.assertEqual(testdata2, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001778
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001779 def test_open(self):
1780 for f in get_files(self):
1781 self.zip_open_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001782
Ezio Melottiafd0d112009-07-15 17:17:17 +00001783 def zip_random_open_test(self, f, compression):
1784 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001785
1786 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001787 with zipfile.ZipFile(f, "r", compression) as zipfp:
1788 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001789 with zipfp.open(TESTFN) as zipopen1:
1790 while True:
1791 read_data = zipopen1.read(randint(1, 1024))
1792 if not read_data:
1793 break
1794 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001795
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001796 testdata = b''.join(zipdata1)
1797 self.assertEqual(len(testdata), len(self.data))
1798 self.assertEqual(testdata, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001799
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001800 def test_random_open(self):
1801 for f in get_files(self):
1802 self.zip_random_open_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001803
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001804
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001805class StoredTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1806 unittest.TestCase):
1807 compression = zipfile.ZIP_STORED
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001808
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001809@requires_zlib
1810class DeflateTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1811 unittest.TestCase):
1812 compression = zipfile.ZIP_DEFLATED
1813
1814@requires_bz2
1815class Bzip2TestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1816 unittest.TestCase):
1817 compression = zipfile.ZIP_BZIP2
1818
1819@requires_lzma
1820class LzmaTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1821 unittest.TestCase):
1822 compression = zipfile.ZIP_LZMA
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001823
Ezio Melotti76430242009-07-11 18:28:48 +00001824
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001825# Privide the tell() method but not seek()
1826class Tellable:
1827 def __init__(self, fp):
1828 self.fp = fp
1829 self.offset = 0
1830
1831 def write(self, data):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02001832 n = self.fp.write(data)
1833 self.offset += n
1834 return n
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001835
1836 def tell(self):
1837 return self.offset
1838
1839 def flush(self):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02001840 self.fp.flush()
1841
1842class Unseekable:
1843 def __init__(self, fp):
1844 self.fp = fp
1845
1846 def write(self, data):
1847 return self.fp.write(data)
1848
1849 def flush(self):
1850 self.fp.flush()
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001851
1852class UnseekableTests(unittest.TestCase):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02001853 def test_writestr(self):
1854 for wrapper in (lambda f: f), Tellable, Unseekable:
1855 with self.subTest(wrapper=wrapper):
1856 f = io.BytesIO()
1857 f.write(b'abc')
1858 bf = io.BufferedWriter(f)
1859 with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) as zipfp:
1860 zipfp.writestr('ones', b'111')
1861 zipfp.writestr('twos', b'222')
1862 self.assertEqual(f.getvalue()[:5], b'abcPK')
1863 with zipfile.ZipFile(f, mode='r') as zipf:
1864 with zipf.open('ones') as zopen:
1865 self.assertEqual(zopen.read(), b'111')
1866 with zipf.open('twos') as zopen:
1867 self.assertEqual(zopen.read(), b'222')
1868
1869 def test_write(self):
1870 for wrapper in (lambda f: f), Tellable, Unseekable:
1871 with self.subTest(wrapper=wrapper):
1872 f = io.BytesIO()
1873 f.write(b'abc')
1874 bf = io.BufferedWriter(f)
1875 with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) as zipfp:
1876 self.addCleanup(unlink, TESTFN)
1877 with open(TESTFN, 'wb') as f2:
1878 f2.write(b'111')
1879 zipfp.write(TESTFN, 'ones')
1880 with open(TESTFN, 'wb') as f2:
1881 f2.write(b'222')
1882 zipfp.write(TESTFN, 'twos')
1883 self.assertEqual(f.getvalue()[:5], b'abcPK')
1884 with zipfile.ZipFile(f, mode='r') as zipf:
1885 with zipf.open('ones') as zopen:
1886 self.assertEqual(zopen.read(), b'111')
1887 with zipf.open('twos') as zopen:
1888 self.assertEqual(zopen.read(), b'222')
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001889
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001890 def test_open_write(self):
1891 for wrapper in (lambda f: f), Tellable, Unseekable:
1892 with self.subTest(wrapper=wrapper):
1893 f = io.BytesIO()
1894 f.write(b'abc')
1895 bf = io.BufferedWriter(f)
1896 with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) as zipf:
1897 with zipf.open('ones', 'w') as zopen:
1898 zopen.write(b'111')
1899 with zipf.open('twos', 'w') as zopen:
1900 zopen.write(b'222')
1901 self.assertEqual(f.getvalue()[:5], b'abcPK')
1902 with zipfile.ZipFile(f) as zipf:
1903 self.assertEqual(zipf.read('ones'), b'111')
1904 self.assertEqual(zipf.read('twos'), b'222')
1905
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001906
Ezio Melotti975077a2011-05-19 22:03:22 +03001907@requires_zlib
Guido van Rossumd8faa362007-04-27 19:54:29 +00001908class TestsWithMultipleOpens(unittest.TestCase):
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001909 @classmethod
1910 def setUpClass(cls):
1911 cls.data1 = b'111' + getrandbytes(10000)
1912 cls.data2 = b'222' + getrandbytes(10000)
1913
1914 def make_test_archive(self, f):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001915 # Create the ZIP archive
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001916 with zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as zipfp:
1917 zipfp.writestr('ones', self.data1)
1918 zipfp.writestr('twos', self.data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001919
Ezio Melottiafd0d112009-07-15 17:17:17 +00001920 def test_same_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001921 # Verify that (when the ZipFile is in control of creating file objects)
1922 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001923 for f in get_files(self):
1924 self.make_test_archive(f)
1925 with zipfile.ZipFile(f, mode="r") as zipf:
1926 with zipf.open('ones') as zopen1, zipf.open('ones') as zopen2:
1927 data1 = zopen1.read(500)
1928 data2 = zopen2.read(500)
1929 data1 += zopen1.read()
1930 data2 += zopen2.read()
1931 self.assertEqual(data1, data2)
1932 self.assertEqual(data1, self.data1)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001933
Ezio Melottiafd0d112009-07-15 17:17:17 +00001934 def test_different_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001935 # Verify that (when the ZipFile is in control of creating file objects)
1936 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001937 for f in get_files(self):
1938 self.make_test_archive(f)
1939 with zipfile.ZipFile(f, mode="r") as zipf:
1940 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1941 data1 = zopen1.read(500)
1942 data2 = zopen2.read(500)
1943 data1 += zopen1.read()
1944 data2 += zopen2.read()
1945 self.assertEqual(data1, self.data1)
1946 self.assertEqual(data2, self.data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001947
Ezio Melottiafd0d112009-07-15 17:17:17 +00001948 def test_interleaved(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001949 # Verify that (when the ZipFile is in control of creating file objects)
1950 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001951 for f in get_files(self):
1952 self.make_test_archive(f)
1953 with zipfile.ZipFile(f, mode="r") as zipf:
Serhiy Storchakad76c7c22016-05-13 21:18:58 +03001954 with zipf.open('ones') as zopen1:
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001955 data1 = zopen1.read(500)
Serhiy Storchakad76c7c22016-05-13 21:18:58 +03001956 with zipf.open('twos') as zopen2:
1957 data2 = zopen2.read(500)
1958 data1 += zopen1.read()
1959 data2 += zopen2.read()
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001960 self.assertEqual(data1, self.data1)
1961 self.assertEqual(data2, self.data2)
1962
1963 def test_read_after_close(self):
1964 for f in get_files(self):
1965 self.make_test_archive(f)
1966 with contextlib.ExitStack() as stack:
1967 with zipfile.ZipFile(f, 'r') as zipf:
1968 zopen1 = stack.enter_context(zipf.open('ones'))
1969 zopen2 = stack.enter_context(zipf.open('twos'))
Brian Curtin8fb9b862010-11-18 02:15:28 +00001970 data1 = zopen1.read(500)
1971 data2 = zopen2.read(500)
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001972 data1 += zopen1.read()
1973 data2 += zopen2.read()
1974 self.assertEqual(data1, self.data1)
1975 self.assertEqual(data2, self.data2)
1976
1977 def test_read_after_write(self):
1978 for f in get_files(self):
1979 with zipfile.ZipFile(f, 'w', zipfile.ZIP_DEFLATED) as zipf:
1980 zipf.writestr('ones', self.data1)
1981 zipf.writestr('twos', self.data2)
1982 with zipf.open('ones') as zopen1:
1983 data1 = zopen1.read(500)
1984 self.assertEqual(data1, self.data1[:500])
1985 with zipfile.ZipFile(f, 'r') as zipf:
1986 data1 = zipf.read('ones')
1987 data2 = zipf.read('twos')
1988 self.assertEqual(data1, self.data1)
1989 self.assertEqual(data2, self.data2)
1990
1991 def test_write_after_read(self):
1992 for f in get_files(self):
1993 with zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as zipf:
1994 zipf.writestr('ones', self.data1)
1995 with zipf.open('ones') as zopen1:
1996 zopen1.read(500)
1997 zipf.writestr('twos', self.data2)
1998 with zipfile.ZipFile(f, 'r') as zipf:
1999 data1 = zipf.read('ones')
2000 data2 = zipf.read('twos')
2001 self.assertEqual(data1, self.data1)
2002 self.assertEqual(data2, self.data2)
2003
2004 def test_many_opens(self):
2005 # Verify that read() and open() promptly close the file descriptor,
2006 # and don't rely on the garbage collector to free resources.
2007 self.make_test_archive(TESTFN2)
2008 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
2009 for x in range(100):
2010 zipf.read('ones')
2011 with zipf.open('ones') as zopen1:
2012 pass
2013 with open(os.devnull) as f:
2014 self.assertLess(f.fileno(), 100)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002015
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03002016 def test_write_while_reading(self):
2017 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_DEFLATED) as zipf:
2018 zipf.writestr('ones', self.data1)
2019 with zipfile.ZipFile(TESTFN2, 'a', zipfile.ZIP_DEFLATED) as zipf:
2020 with zipf.open('ones', 'r') as r1:
2021 data1 = r1.read(500)
2022 with zipf.open('twos', 'w') as w1:
2023 w1.write(self.data2)
2024 data1 += r1.read()
2025 self.assertEqual(data1, self.data1)
2026 with zipfile.ZipFile(TESTFN2) as zipf:
2027 self.assertEqual(zipf.read('twos'), self.data2)
2028
Guido van Rossumd8faa362007-04-27 19:54:29 +00002029 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00002030 unlink(TESTFN2)
2031
Guido van Rossumd8faa362007-04-27 19:54:29 +00002032
Martin v. Löwis59e47792009-01-24 14:10:07 +00002033class TestWithDirectory(unittest.TestCase):
2034 def setUp(self):
2035 os.mkdir(TESTFN2)
2036
Ezio Melottiafd0d112009-07-15 17:17:17 +00002037 def test_extract_dir(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00002038 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
2039 zipf.extractall(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00002040 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
2041 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
2042 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
2043
Ezio Melottiafd0d112009-07-15 17:17:17 +00002044 def test_bug_6050(self):
Martin v. Löwis70ccd162009-05-24 19:47:22 +00002045 # Extraction should succeed if directories already exist
2046 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottiafd0d112009-07-15 17:17:17 +00002047 self.test_extract_dir()
Martin v. Löwis70ccd162009-05-24 19:47:22 +00002048
Serhiy Storchaka46a34922014-09-23 22:40:23 +03002049 def test_write_dir(self):
2050 dirpath = os.path.join(TESTFN2, "x")
2051 os.mkdir(dirpath)
2052 mode = os.stat(dirpath).st_mode & 0xFFFF
2053 with zipfile.ZipFile(TESTFN, "w") as zipf:
2054 zipf.write(dirpath)
2055 zinfo = zipf.filelist[0]
2056 self.assertTrue(zinfo.filename.endswith("/x/"))
2057 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
2058 zipf.write(dirpath, "y")
2059 zinfo = zipf.filelist[1]
2060 self.assertTrue(zinfo.filename, "y/")
2061 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
2062 with zipfile.ZipFile(TESTFN, "r") as zipf:
2063 zinfo = zipf.filelist[0]
2064 self.assertTrue(zinfo.filename.endswith("/x/"))
2065 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
2066 zinfo = zipf.filelist[1]
2067 self.assertTrue(zinfo.filename, "y/")
2068 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
2069 target = os.path.join(TESTFN2, "target")
2070 os.mkdir(target)
2071 zipf.extractall(target)
2072 self.assertTrue(os.path.isdir(os.path.join(target, "y")))
2073 self.assertEqual(len(os.listdir(target)), 2)
2074
2075 def test_writestr_dir(self):
Martin v. Löwis59e47792009-01-24 14:10:07 +00002076 os.mkdir(os.path.join(TESTFN2, "x"))
Serhiy Storchaka46a34922014-09-23 22:40:23 +03002077 with zipfile.ZipFile(TESTFN, "w") as zipf:
2078 zipf.writestr("x/", b'')
2079 zinfo = zipf.filelist[0]
2080 self.assertEqual(zinfo.filename, "x/")
2081 self.assertEqual(zinfo.external_attr, (0o40775 << 16) | 0x10)
2082 with zipfile.ZipFile(TESTFN, "r") as zipf:
2083 zinfo = zipf.filelist[0]
2084 self.assertTrue(zinfo.filename.endswith("x/"))
2085 self.assertEqual(zinfo.external_attr, (0o40775 << 16) | 0x10)
2086 target = os.path.join(TESTFN2, "target")
2087 os.mkdir(target)
2088 zipf.extractall(target)
2089 self.assertTrue(os.path.isdir(os.path.join(target, "x")))
2090 self.assertEqual(os.listdir(target), ["x"])
Martin v. Löwis59e47792009-01-24 14:10:07 +00002091
2092 def tearDown(self):
Victor Stinner57004c62014-09-04 00:49:01 +02002093 rmtree(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00002094 if os.path.exists(TESTFN):
Ezio Melotti76430242009-07-11 18:28:48 +00002095 unlink(TESTFN)
Martin v. Löwis59e47792009-01-24 14:10:07 +00002096
Guido van Rossumd8faa362007-04-27 19:54:29 +00002097
Serhiy Storchaka503f9082016-02-08 00:02:25 +02002098class ZipInfoTests(unittest.TestCase):
2099 def test_from_file(self):
2100 zi = zipfile.ZipInfo.from_file(__file__)
2101 self.assertEqual(posixpath.basename(zi.filename), 'test_zipfile.py')
2102 self.assertFalse(zi.is_dir())
Serhiy Storchaka8606e952017-03-08 14:37:51 +02002103 self.assertEqual(zi.file_size, os.path.getsize(__file__))
2104
2105 def test_from_file_pathlike(self):
2106 zi = zipfile.ZipInfo.from_file(pathlib.Path(__file__))
2107 self.assertEqual(posixpath.basename(zi.filename), 'test_zipfile.py')
2108 self.assertFalse(zi.is_dir())
2109 self.assertEqual(zi.file_size, os.path.getsize(__file__))
2110
2111 def test_from_file_bytes(self):
2112 zi = zipfile.ZipInfo.from_file(os.fsencode(__file__), 'test')
2113 self.assertEqual(posixpath.basename(zi.filename), 'test')
2114 self.assertFalse(zi.is_dir())
2115 self.assertEqual(zi.file_size, os.path.getsize(__file__))
2116
2117 def test_from_file_fileno(self):
2118 with open(__file__, 'rb') as f:
2119 zi = zipfile.ZipInfo.from_file(f.fileno(), 'test')
2120 self.assertEqual(posixpath.basename(zi.filename), 'test')
2121 self.assertFalse(zi.is_dir())
2122 self.assertEqual(zi.file_size, os.path.getsize(__file__))
Serhiy Storchaka503f9082016-02-08 00:02:25 +02002123
2124 def test_from_dir(self):
2125 dirpath = os.path.dirname(os.path.abspath(__file__))
2126 zi = zipfile.ZipInfo.from_file(dirpath, 'stdlib_tests')
2127 self.assertEqual(zi.filename, 'stdlib_tests/')
2128 self.assertTrue(zi.is_dir())
2129 self.assertEqual(zi.compress_type, zipfile.ZIP_STORED)
2130 self.assertEqual(zi.file_size, 0)
2131
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002132
2133class CommandLineTest(unittest.TestCase):
2134
2135 def zipfilecmd(self, *args, **kwargs):
2136 rc, out, err = script_helper.assert_python_ok('-m', 'zipfile', *args,
2137 **kwargs)
2138 return out.replace(os.linesep.encode(), b'\n')
2139
2140 def zipfilecmd_failure(self, *args):
2141 return script_helper.assert_python_failure('-m', 'zipfile', *args)
2142
2143 def test_test_command(self):
2144 zip_name = findfile('zipdir.zip')
Serhiy Storchaka8c933102016-10-23 13:32:12 +03002145 for opt in '-t', '--test':
2146 out = self.zipfilecmd(opt, zip_name)
2147 self.assertEqual(out.rstrip(), b'Done testing')
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002148 zip_name = findfile('testtar.tar')
2149 rc, out, err = self.zipfilecmd_failure('-t', zip_name)
2150 self.assertEqual(out, b'')
2151
2152 def test_list_command(self):
2153 zip_name = findfile('zipdir.zip')
2154 t = io.StringIO()
2155 with zipfile.ZipFile(zip_name, 'r') as tf:
2156 tf.printdir(t)
2157 expected = t.getvalue().encode('ascii', 'backslashreplace')
Serhiy Storchaka8c933102016-10-23 13:32:12 +03002158 for opt in '-l', '--list':
2159 out = self.zipfilecmd(opt, zip_name,
2160 PYTHONIOENCODING='ascii:backslashreplace')
2161 self.assertEqual(out, expected)
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002162
Serhiy Storchakab4293ef2016-10-23 22:32:30 +03002163 @requires_zlib
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002164 def test_create_command(self):
2165 self.addCleanup(unlink, TESTFN)
2166 with open(TESTFN, 'w') as f:
2167 f.write('test 1')
2168 os.mkdir(TESTFNDIR)
2169 self.addCleanup(rmtree, TESTFNDIR)
2170 with open(os.path.join(TESTFNDIR, 'file.txt'), 'w') as f:
2171 f.write('test 2')
2172 files = [TESTFN, TESTFNDIR]
2173 namelist = [TESTFN, TESTFNDIR + '/', TESTFNDIR + '/file.txt']
Serhiy Storchaka8c933102016-10-23 13:32:12 +03002174 for opt in '-c', '--create':
2175 try:
2176 out = self.zipfilecmd(opt, TESTFN2, *files)
2177 self.assertEqual(out, b'')
2178 with zipfile.ZipFile(TESTFN2) as zf:
2179 self.assertEqual(zf.namelist(), namelist)
2180 self.assertEqual(zf.read(namelist[0]), b'test 1')
2181 self.assertEqual(zf.read(namelist[2]), b'test 2')
2182 finally:
2183 unlink(TESTFN2)
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002184
2185 def test_extract_command(self):
2186 zip_name = findfile('zipdir.zip')
Serhiy Storchaka8c933102016-10-23 13:32:12 +03002187 for opt in '-e', '--extract':
2188 with temp_dir() as extdir:
2189 out = self.zipfilecmd(opt, zip_name, extdir)
2190 self.assertEqual(out, b'')
2191 with zipfile.ZipFile(zip_name) as zf:
2192 for zi in zf.infolist():
2193 path = os.path.join(extdir,
2194 zi.filename.replace('/', os.sep))
2195 if zi.is_dir():
2196 self.assertTrue(os.path.isdir(path))
2197 else:
2198 self.assertTrue(os.path.isfile(path))
2199 with open(path, 'rb') as f:
2200 self.assertEqual(f.read(), zf.read(zi))
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002201
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00002202if __name__ == "__main__":
Brett Cannond5b4e1d2013-06-12 19:57:19 -04002203 unittest.main()