blob: b48366a53263524e8e07d7bc961b7fa85364c38c [file] [log] [blame]
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001import contextlib
Ezio Melotti74c96ec2009-07-08 22:24:06 +00002import io
3import os
Brett Cannonb57a0852013-06-15 17:32:30 -04004import importlib.util
Serhiy Storchaka8606e952017-03-08 14:37:51 +02005import pathlib
Serhiy Storchaka503f9082016-02-08 00:02:25 +02006import posixpath
Ezio Melotti35386712009-12-31 13:22:41 +00007import time
Ezio Melotti74c96ec2009-07-08 22:24:06 +00008import struct
9import zipfile
10import unittest
11
Tim Petersa45cacf2004-08-20 03:47:14 +000012
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000013from tempfile import TemporaryFile
Serhiy Storchakafa6bc292013-07-22 21:00:11 +030014from random import randint, random, getrandbits
Tim Petersa19a1682001-03-29 04:36:09 +000015
Serhiy Storchaka61c4c442016-10-23 13:07:59 +030016from test.support import script_helper
Serhiy Storchaka8606e952017-03-08 14:37:51 +020017from test.support import (TESTFN, findfile, unlink, rmtree, temp_dir, temp_cwd,
Serhiy Storchakac5b75db2013-01-29 20:14:08 +020018 requires_zlib, requires_bz2, requires_lzma,
Victor Stinnerd6debb22017-03-27 16:05:26 +020019 captured_stdout)
Guido van Rossum368f04a2000-04-10 13:23:04 +000020
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000021TESTFN2 = TESTFN + "2"
Martin v. Löwis59e47792009-01-24 14:10:07 +000022TESTFNDIR = TESTFN + "d"
Guido van Rossumb5a755e2007-07-18 18:15:48 +000023FIXEDTEST_SIZE = 1000
Georg Brandl5ba11de2011-01-01 10:09:32 +000024DATAFILES_DIR = 'zipfile_datafiles'
Guido van Rossum368f04a2000-04-10 13:23:04 +000025
Christian Heimes790c8232008-01-07 21:14:23 +000026SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'),
27 ('ziptest2dir/_ziptest2', 'qawsedrftg'),
Gregory P. Smithb47acbf2013-02-01 11:22:43 -080028 ('ziptest2dir/ziptest3dir/_ziptest3', 'azsxdcfvgb'),
Christian Heimes790c8232008-01-07 21:14:23 +000029 ('ziptest2dir/ziptest3dir/ziptest4dir/_ziptest3', '6y7u8i9o0p')]
30
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +020031def getrandbytes(size):
32 return getrandbits(8 * size).to_bytes(size, 'little')
33
Serhiy Storchakafa6bc292013-07-22 21:00:11 +030034def get_files(test):
35 yield TESTFN2
36 with TemporaryFile() as f:
37 yield f
38 test.assertFalse(f.closed)
39 with io.BytesIO() as f:
40 yield f
41 test.assertFalse(f.closed)
Ezio Melotti76430242009-07-11 18:28:48 +000042
Serhiy Storchakafa6bc292013-07-22 21:00:11 +030043class AbstractTestsWithSourceFile:
44 @classmethod
45 def setUpClass(cls):
46 cls.line_gen = [bytes("Zipfile test line %d. random float: %f\n" %
47 (i, random()), "ascii")
48 for i in range(FIXEDTEST_SIZE)]
49 cls.data = b''.join(cls.line_gen)
50
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000051 def setUp(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000052 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +000053 with open(TESTFN, "wb") as fp:
54 fp.write(self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000055
Bo Baylesce237c72018-01-29 23:54:07 -060056 def make_test_archive(self, f, compression, compresslevel=None):
57 kwargs = {'compression': compression, 'compresslevel': compresslevel}
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000058 # Create the ZIP archive
Bo Baylesce237c72018-01-29 23:54:07 -060059 with zipfile.ZipFile(f, "w", **kwargs) as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000060 zipfp.write(TESTFN, "another.name")
61 zipfp.write(TESTFN, TESTFN)
62 zipfp.writestr("strfile", self.data)
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +030063 with zipfp.open('written-open-w', mode='w') as f:
64 for line in self.line_gen:
65 f.write(line)
Tim Peters7d3bad62001-04-04 18:56:49 +000066
Bo Baylesce237c72018-01-29 23:54:07 -060067 def zip_test(self, f, compression, compresslevel=None):
68 self.make_test_archive(f, compression, compresslevel)
Guido van Rossumd8faa362007-04-27 19:54:29 +000069
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000070 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000071 with zipfile.ZipFile(f, "r", compression) as zipfp:
72 self.assertEqual(zipfp.read(TESTFN), self.data)
73 self.assertEqual(zipfp.read("another.name"), self.data)
74 self.assertEqual(zipfp.read("strfile"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000075
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000076 # Print the ZIP directory
77 fp = io.StringIO()
78 zipfp.printdir(file=fp)
79 directory = fp.getvalue()
80 lines = directory.splitlines()
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +030081 self.assertEqual(len(lines), 5) # Number of files + header
Thomas Wouters0e3f5912006-08-11 14:57:12 +000082
Benjamin Peterson577473f2010-01-19 00:09:57 +000083 self.assertIn('File Name', lines[0])
84 self.assertIn('Modified', lines[0])
85 self.assertIn('Size', lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +000086
Ezio Melotti35386712009-12-31 13:22:41 +000087 fn, date, time_, size = lines[1].split()
88 self.assertEqual(fn, 'another.name')
89 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
90 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
91 self.assertEqual(size, str(len(self.data)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000092
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000093 # Check the namelist
94 names = zipfp.namelist()
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +030095 self.assertEqual(len(names), 4)
Benjamin Peterson577473f2010-01-19 00:09:57 +000096 self.assertIn(TESTFN, names)
97 self.assertIn("another.name", names)
98 self.assertIn("strfile", names)
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +030099 self.assertIn("written-open-w", names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000100
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000101 # Check infolist
102 infos = zipfp.infolist()
Ezio Melotti35386712009-12-31 13:22:41 +0000103 names = [i.filename for i in infos]
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300104 self.assertEqual(len(names), 4)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000105 self.assertIn(TESTFN, names)
106 self.assertIn("another.name", names)
107 self.assertIn("strfile", names)
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300108 self.assertIn("written-open-w", names)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000109 for i in infos:
Ezio Melotti35386712009-12-31 13:22:41 +0000110 self.assertEqual(i.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000111
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000112 # check getinfo
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300113 for nm in (TESTFN, "another.name", "strfile", "written-open-w"):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000114 info = zipfp.getinfo(nm)
Ezio Melotti35386712009-12-31 13:22:41 +0000115 self.assertEqual(info.filename, nm)
116 self.assertEqual(info.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000117
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000118 # Check that testzip doesn't raise an exception
119 zipfp.testzip()
Tim Peters7d3bad62001-04-04 18:56:49 +0000120
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300121 def test_basic(self):
122 for f in get_files(self):
123 self.zip_test(f, self.compression)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000124
Ezio Melottiafd0d112009-07-15 17:17:17 +0000125 def zip_open_test(self, f, compression):
126 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000127
128 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000129 with zipfile.ZipFile(f, "r", compression) as zipfp:
130 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000131 with zipfp.open(TESTFN) as zipopen1:
132 while True:
133 read_data = zipopen1.read(256)
134 if not read_data:
135 break
136 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000137
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000138 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000139 with zipfp.open("another.name") as zipopen2:
140 while True:
141 read_data = zipopen2.read(256)
142 if not read_data:
143 break
144 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000145
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000146 self.assertEqual(b''.join(zipdata1), self.data)
147 self.assertEqual(b''.join(zipdata2), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000148
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300149 def test_open(self):
150 for f in get_files(self):
151 self.zip_open_test(f, self.compression)
Georg Brandlb533e262008-05-25 18:19:30 +0000152
Serhiy Storchaka8606e952017-03-08 14:37:51 +0200153 def test_open_with_pathlike(self):
154 path = pathlib.Path(TESTFN2)
155 self.zip_open_test(path, self.compression)
156 with zipfile.ZipFile(path, "r", self.compression) as zipfp:
157 self.assertIsInstance(zipfp.filename, str)
158
Ezio Melottiafd0d112009-07-15 17:17:17 +0000159 def zip_random_open_test(self, f, compression):
160 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000161
162 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000163 with zipfile.ZipFile(f, "r", compression) as zipfp:
164 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000165 with zipfp.open(TESTFN) as zipopen1:
166 while True:
167 read_data = zipopen1.read(randint(1, 1024))
168 if not read_data:
169 break
170 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000171
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000172 self.assertEqual(b''.join(zipdata1), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000173
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300174 def test_random_open(self):
175 for f in get_files(self):
176 self.zip_random_open_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000177
Serhiy Storchakad2c07a52013-09-27 22:11:57 +0300178 def zip_read1_test(self, f, compression):
179 self.make_test_archive(f, compression)
180
181 # Read the ZIP archive
182 with zipfile.ZipFile(f, "r") as zipfp, \
183 zipfp.open(TESTFN) as zipopen:
184 zipdata = []
185 while True:
186 read_data = zipopen.read1(-1)
187 if not read_data:
188 break
189 zipdata.append(read_data)
190
191 self.assertEqual(b''.join(zipdata), self.data)
192
193 def test_read1(self):
194 for f in get_files(self):
195 self.zip_read1_test(f, self.compression)
196
197 def zip_read1_10_test(self, f, compression):
198 self.make_test_archive(f, compression)
199
200 # Read the ZIP archive
201 with zipfile.ZipFile(f, "r") as zipfp, \
202 zipfp.open(TESTFN) as zipopen:
203 zipdata = []
204 while True:
205 read_data = zipopen.read1(10)
206 self.assertLessEqual(len(read_data), 10)
207 if not read_data:
208 break
209 zipdata.append(read_data)
210
211 self.assertEqual(b''.join(zipdata), self.data)
212
213 def test_read1_10(self):
214 for f in get_files(self):
215 self.zip_read1_10_test(f, self.compression)
216
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000217 def zip_readline_read_test(self, f, compression):
218 self.make_test_archive(f, compression)
219
220 # Read the ZIP archive
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300221 with zipfile.ZipFile(f, "r") as zipfp, \
222 zipfp.open(TESTFN) as zipopen:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000223 data = b''
224 while True:
225 read = zipopen.readline()
226 if not read:
227 break
228 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000229
Brian Curtin8fb9b862010-11-18 02:15:28 +0000230 read = zipopen.read(100)
231 if not read:
232 break
233 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000234
235 self.assertEqual(data, self.data)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300236
237 def test_readline_read(self):
238 # Issue #7610: calls to readline() interleaved with calls to read().
239 for f in get_files(self):
240 self.zip_readline_read_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000241
Ezio Melottiafd0d112009-07-15 17:17:17 +0000242 def zip_readline_test(self, f, compression):
243 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000244
245 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000246 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000247 with zipfp.open(TESTFN) as zipopen:
248 for line in self.line_gen:
249 linedata = zipopen.readline()
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300250 self.assertEqual(linedata, line)
251
252 def test_readline(self):
253 for f in get_files(self):
254 self.zip_readline_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000255
Ezio Melottiafd0d112009-07-15 17:17:17 +0000256 def zip_readlines_test(self, f, compression):
257 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000258
259 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000260 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000261 with zipfp.open(TESTFN) as zipopen:
262 ziplines = zipopen.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000263 for line, zipline in zip(self.line_gen, ziplines):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300264 self.assertEqual(zipline, line)
265
266 def test_readlines(self):
267 for f in get_files(self):
268 self.zip_readlines_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000269
Ezio Melottiafd0d112009-07-15 17:17:17 +0000270 def zip_iterlines_test(self, f, compression):
271 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000272
273 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000274 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000275 with zipfp.open(TESTFN) as zipopen:
276 for line, zipline in zip(self.line_gen, zipopen):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300277 self.assertEqual(zipline, line)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000278
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300279 def test_iterlines(self):
280 for f in get_files(self):
281 self.zip_iterlines_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000282
Ezio Melottiafd0d112009-07-15 17:17:17 +0000283 def test_low_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000284 """Check for cases where compressed data is larger than original."""
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000285 # Create the ZIP archive
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300286 with zipfile.ZipFile(TESTFN2, "w", self.compression) as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000287 zipfp.writestr("strfile", '12')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000288
289 # Get an open object for strfile
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300290 with zipfile.ZipFile(TESTFN2, "r", self.compression) as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000291 with zipfp.open("strfile") as openobj:
292 self.assertEqual(openobj.read(1), b'1')
293 self.assertEqual(openobj.read(1), b'2')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000294
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300295 def test_writestr_compression(self):
296 zipfp = zipfile.ZipFile(TESTFN2, "w")
297 zipfp.writestr("b.txt", "hello world", compress_type=self.compression)
298 info = zipfp.getinfo('b.txt')
299 self.assertEqual(info.compress_type, self.compression)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200300
Bo Baylesce237c72018-01-29 23:54:07 -0600301 def test_writestr_compresslevel(self):
302 zipfp = zipfile.ZipFile(TESTFN2, "w", compresslevel=1)
303 zipfp.writestr("a.txt", "hello world", compress_type=self.compression)
304 zipfp.writestr("b.txt", "hello world", compress_type=self.compression,
305 compresslevel=2)
306
307 # Compression level follows the constructor.
308 a_info = zipfp.getinfo('a.txt')
309 self.assertEqual(a_info.compress_type, self.compression)
310 self.assertEqual(a_info._compresslevel, 1)
311
312 # Compression level is overridden.
313 b_info = zipfp.getinfo('b.txt')
314 self.assertEqual(b_info.compress_type, self.compression)
315 self.assertEqual(b_info._compresslevel, 2)
316
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300317 def test_read_return_size(self):
318 # Issue #9837: ZipExtFile.read() shouldn't return more bytes
319 # than requested.
320 for test_size in (1, 4095, 4096, 4097, 16384):
321 file_size = test_size + 1
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +0200322 junk = getrandbytes(file_size)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300323 with zipfile.ZipFile(io.BytesIO(), "w", self.compression) as zipf:
324 zipf.writestr('foo', junk)
325 with zipf.open('foo', 'r') as fp:
326 buf = fp.read(test_size)
327 self.assertEqual(len(buf), test_size)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200328
Serhiy Storchaka5ce3f102014-01-09 14:50:20 +0200329 def test_truncated_zipfile(self):
330 fp = io.BytesIO()
331 with zipfile.ZipFile(fp, mode='w') as zipf:
332 zipf.writestr('strfile', self.data, compress_type=self.compression)
333 end_offset = fp.tell()
334 zipfiledata = fp.getvalue()
335
336 fp = io.BytesIO(zipfiledata)
337 with zipfile.ZipFile(fp) as zipf:
338 with zipf.open('strfile') as zipopen:
339 fp.truncate(end_offset - 20)
340 with self.assertRaises(EOFError):
341 zipopen.read()
342
343 fp = io.BytesIO(zipfiledata)
344 with zipfile.ZipFile(fp) as zipf:
345 with zipf.open('strfile') as zipopen:
346 fp.truncate(end_offset - 20)
347 with self.assertRaises(EOFError):
348 while zipopen.read(100):
349 pass
350
351 fp = io.BytesIO(zipfiledata)
352 with zipfile.ZipFile(fp) as zipf:
353 with zipf.open('strfile') as zipopen:
354 fp.truncate(end_offset - 20)
355 with self.assertRaises(EOFError):
356 while zipopen.read1(100):
357 pass
358
Serhiy Storchaka51a43702014-10-29 22:42:06 +0200359 def test_repr(self):
360 fname = 'file.name'
361 for f in get_files(self):
362 with zipfile.ZipFile(f, 'w', self.compression) as zipfp:
363 zipfp.write(TESTFN, fname)
364 r = repr(zipfp)
365 self.assertIn("mode='w'", r)
366
367 with zipfile.ZipFile(f, 'r') as zipfp:
368 r = repr(zipfp)
369 if isinstance(f, str):
370 self.assertIn('filename=%r' % f, r)
371 else:
372 self.assertIn('file=%r' % f, r)
373 self.assertIn("mode='r'", r)
374 r = repr(zipfp.getinfo(fname))
375 self.assertIn('filename=%r' % fname, r)
376 self.assertIn('filemode=', r)
377 self.assertIn('file_size=', r)
378 if self.compression != zipfile.ZIP_STORED:
379 self.assertIn('compress_type=', r)
380 self.assertIn('compress_size=', r)
381 with zipfp.open(fname) as zipopen:
382 r = repr(zipopen)
383 self.assertIn('name=%r' % fname, r)
384 self.assertIn("mode='r'", r)
385 if self.compression != zipfile.ZIP_STORED:
386 self.assertIn('compress_type=', r)
387 self.assertIn('[closed]', repr(zipopen))
388 self.assertIn('[closed]', repr(zipfp))
389
Bo Baylesce237c72018-01-29 23:54:07 -0600390 def test_compresslevel_basic(self):
391 for f in get_files(self):
392 self.zip_test(f, self.compression, compresslevel=9)
393
394 def test_per_file_compresslevel(self):
395 """Check that files within a Zip archive can have different
396 compression levels."""
397 with zipfile.ZipFile(TESTFN2, "w", compresslevel=1) as zipfp:
398 zipfp.write(TESTFN, 'compress_1')
399 zipfp.write(TESTFN, 'compress_9', compresslevel=9)
400 one_info = zipfp.getinfo('compress_1')
401 nine_info = zipfp.getinfo('compress_9')
402 self.assertEqual(one_info._compresslevel, 1)
403 self.assertEqual(nine_info._compresslevel, 9)
404
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300405 def tearDown(self):
406 unlink(TESTFN)
407 unlink(TESTFN2)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200408
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200409
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300410class StoredTestsWithSourceFile(AbstractTestsWithSourceFile,
411 unittest.TestCase):
412 compression = zipfile.ZIP_STORED
413 test_low_compression = None
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200414
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300415 def zip_test_writestr_permissions(self, f, compression):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300416 # Make sure that writestr and open(... mode='w') create files with
417 # mode 0600, when they are passed a name rather than a ZipInfo
418 # instance.
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200419
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300420 self.make_test_archive(f, compression)
421 with zipfile.ZipFile(f, "r") as zipfp:
422 zinfo = zipfp.getinfo('strfile')
423 self.assertEqual(zinfo.external_attr, 0o600 << 16)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200424
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300425 zinfo2 = zipfp.getinfo('written-open-w')
426 self.assertEqual(zinfo2.external_attr, 0o600 << 16)
427
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300428 def test_writestr_permissions(self):
429 for f in get_files(self):
430 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +0200431
Ezio Melottiafd0d112009-07-15 17:17:17 +0000432 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000433 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
434 zipfp.write(TESTFN, "/absolute")
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000435
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000436 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
437 self.assertEqual(zipfp.namelist(), ["absolute"])
Tim Peters32cbc962006-02-20 21:42:18 +0000438
Ezio Melottiafd0d112009-07-15 17:17:17 +0000439 def test_append_to_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000440 """Test appending to an existing zipfile."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000441 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
442 zipfp.write(TESTFN, TESTFN)
443
444 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
445 zipfp.writestr("strfile", self.data)
446 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000447
Ezio Melottiafd0d112009-07-15 17:17:17 +0000448 def test_append_to_non_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000449 """Test appending to an existing file that is not a zipfile."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000450 # NOTE: this test fails if len(d) < 22 because of the first
451 # line "fpin.seek(-22, 2)" in _EndRecData
Ezio Melotti35386712009-12-31 13:22:41 +0000452 data = b'I am not a ZipFile!'*10
453 with open(TESTFN2, 'wb') as f:
454 f.write(data)
455
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000456 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
457 zipfp.write(TESTFN, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000458
Ezio Melotti35386712009-12-31 13:22:41 +0000459 with open(TESTFN2, 'rb') as f:
460 f.seek(len(data))
461 with zipfile.ZipFile(f, "r") as zipfp:
462 self.assertEqual(zipfp.namelist(), [TESTFN])
Serhiy Storchaka8793b212016-10-07 22:20:50 +0300463 self.assertEqual(zipfp.read(TESTFN), self.data)
464 with open(TESTFN2, 'rb') as f:
465 self.assertEqual(f.read(len(data)), data)
466 zipfiledata = f.read()
467 with io.BytesIO(zipfiledata) as bio, zipfile.ZipFile(bio) as zipfp:
468 self.assertEqual(zipfp.namelist(), [TESTFN])
469 self.assertEqual(zipfp.read(TESTFN), self.data)
470
471 def test_read_concatenated_zip_file(self):
472 with io.BytesIO() as bio:
473 with zipfile.ZipFile(bio, 'w', zipfile.ZIP_STORED) as zipfp:
474 zipfp.write(TESTFN, TESTFN)
475 zipfiledata = bio.getvalue()
476 data = b'I am not a ZipFile!'*10
477 with open(TESTFN2, 'wb') as f:
478 f.write(data)
479 f.write(zipfiledata)
480
481 with zipfile.ZipFile(TESTFN2) as zipfp:
482 self.assertEqual(zipfp.namelist(), [TESTFN])
483 self.assertEqual(zipfp.read(TESTFN), self.data)
484
485 def test_append_to_concatenated_zip_file(self):
486 with io.BytesIO() as bio:
487 with zipfile.ZipFile(bio, 'w', zipfile.ZIP_STORED) as zipfp:
488 zipfp.write(TESTFN, TESTFN)
489 zipfiledata = bio.getvalue()
490 data = b'I am not a ZipFile!'*1000000
491 with open(TESTFN2, 'wb') as f:
492 f.write(data)
493 f.write(zipfiledata)
494
495 with zipfile.ZipFile(TESTFN2, 'a') as zipfp:
496 self.assertEqual(zipfp.namelist(), [TESTFN])
497 zipfp.writestr('strfile', self.data)
498
499 with open(TESTFN2, 'rb') as f:
500 self.assertEqual(f.read(len(data)), data)
501 zipfiledata = f.read()
502 with io.BytesIO(zipfiledata) as bio, zipfile.ZipFile(bio) as zipfp:
503 self.assertEqual(zipfp.namelist(), [TESTFN, 'strfile'])
504 self.assertEqual(zipfp.read(TESTFN), self.data)
505 self.assertEqual(zipfp.read('strfile'), self.data)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000506
R David Murray4fbb9db2011-06-09 15:50:51 -0400507 def test_ignores_newline_at_end(self):
508 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
509 zipfp.write(TESTFN, TESTFN)
510 with open(TESTFN2, 'a') as f:
511 f.write("\r\n\00\00\00")
512 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
513 self.assertIsInstance(zipfp, zipfile.ZipFile)
514
515 def test_ignores_stuff_appended_past_comments(self):
516 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
517 zipfp.comment = b"this is a comment"
518 zipfp.write(TESTFN, TESTFN)
519 with open(TESTFN2, 'a') as f:
520 f.write("abcdef\r\n")
521 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
522 self.assertIsInstance(zipfp, zipfile.ZipFile)
523 self.assertEqual(zipfp.comment, b"this is a comment")
524
Ezio Melottiafd0d112009-07-15 17:17:17 +0000525 def test_write_default_name(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000526 """Check that calling ZipFile.write without arcname specified
527 produces the expected result."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000528 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
529 zipfp.write(TESTFN)
Brian Curtin8fb9b862010-11-18 02:15:28 +0000530 with open(TESTFN, "rb") as f:
531 self.assertEqual(zipfp.read(TESTFN), f.read())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000532
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300533 def test_write_to_readonly(self):
534 """Check that trying to call write() on a readonly ZipFile object
Serhiy Storchakab0d497c2016-09-10 21:28:07 +0300535 raises a ValueError."""
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300536 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
537 zipfp.writestr("somefile.txt", "bogus")
538
539 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
Serhiy Storchakab0d497c2016-09-10 21:28:07 +0300540 self.assertRaises(ValueError, zipfp.write, TESTFN)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300541
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300542 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
Serhiy Storchakab0d497c2016-09-10 21:28:07 +0300543 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300544 zipfp.open(TESTFN, mode='w')
545
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300546 def test_add_file_before_1980(self):
547 # Set atime and mtime to 1970-01-01
548 os.utime(TESTFN, (0, 0))
549 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
550 self.assertRaises(ValueError, zipfp.write, TESTFN)
551
Serhiy Storchaka5ce3f102014-01-09 14:50:20 +0200552
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300553@requires_zlib
554class DeflateTestsWithSourceFile(AbstractTestsWithSourceFile,
555 unittest.TestCase):
556 compression = zipfile.ZIP_DEFLATED
557
Ezio Melottiafd0d112009-07-15 17:17:17 +0000558 def test_per_file_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000559 """Check that files within a Zip archive can have different
560 compression options."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000561 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
562 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
563 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
564 sinfo = zipfp.getinfo('storeme')
565 dinfo = zipfp.getinfo('deflateme')
566 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
567 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000568
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300569@requires_bz2
570class Bzip2TestsWithSourceFile(AbstractTestsWithSourceFile,
571 unittest.TestCase):
572 compression = zipfile.ZIP_BZIP2
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000573
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300574@requires_lzma
575class LzmaTestsWithSourceFile(AbstractTestsWithSourceFile,
576 unittest.TestCase):
577 compression = zipfile.ZIP_LZMA
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000578
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300579
580class AbstractTestZip64InSmallFiles:
581 # These tests test the ZIP64 functionality without using large files,
582 # see test_zipfile64 for proper tests.
583
584 @classmethod
585 def setUpClass(cls):
586 line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
587 for i in range(0, FIXEDTEST_SIZE))
588 cls.data = b'\n'.join(line_gen)
589
590 def setUp(self):
591 self._limit = zipfile.ZIP64_LIMIT
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300592 self._filecount_limit = zipfile.ZIP_FILECOUNT_LIMIT
593 zipfile.ZIP64_LIMIT = 1000
594 zipfile.ZIP_FILECOUNT_LIMIT = 9
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300595
596 # Make a source file with some lines
597 with open(TESTFN, "wb") as fp:
598 fp.write(self.data)
599
600 def zip_test(self, f, compression):
601 # Create the ZIP archive
602 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
603 zipfp.write(TESTFN, "another.name")
604 zipfp.write(TESTFN, TESTFN)
605 zipfp.writestr("strfile", self.data)
606
607 # Read the ZIP archive
608 with zipfile.ZipFile(f, "r", compression) as zipfp:
609 self.assertEqual(zipfp.read(TESTFN), self.data)
610 self.assertEqual(zipfp.read("another.name"), self.data)
611 self.assertEqual(zipfp.read("strfile"), self.data)
612
613 # Print the ZIP directory
614 fp = io.StringIO()
615 zipfp.printdir(fp)
616
617 directory = fp.getvalue()
618 lines = directory.splitlines()
619 self.assertEqual(len(lines), 4) # Number of files + header
620
621 self.assertIn('File Name', lines[0])
622 self.assertIn('Modified', lines[0])
623 self.assertIn('Size', lines[0])
624
625 fn, date, time_, size = lines[1].split()
626 self.assertEqual(fn, 'another.name')
627 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
628 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
629 self.assertEqual(size, str(len(self.data)))
630
631 # Check the namelist
632 names = zipfp.namelist()
633 self.assertEqual(len(names), 3)
634 self.assertIn(TESTFN, names)
635 self.assertIn("another.name", names)
636 self.assertIn("strfile", names)
637
638 # Check infolist
639 infos = zipfp.infolist()
640 names = [i.filename for i in infos]
641 self.assertEqual(len(names), 3)
642 self.assertIn(TESTFN, names)
643 self.assertIn("another.name", names)
644 self.assertIn("strfile", names)
645 for i in infos:
646 self.assertEqual(i.file_size, len(self.data))
647
648 # check getinfo
649 for nm in (TESTFN, "another.name", "strfile"):
650 info = zipfp.getinfo(nm)
651 self.assertEqual(info.filename, nm)
652 self.assertEqual(info.file_size, len(self.data))
653
654 # Check that testzip doesn't raise an exception
655 zipfp.testzip()
656
657 def test_basic(self):
658 for f in get_files(self):
659 self.zip_test(f, self.compression)
660
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300661 def test_too_many_files(self):
662 # This test checks that more than 64k files can be added to an archive,
663 # and that the resulting archive can be read properly by ZipFile
664 zipf = zipfile.ZipFile(TESTFN, "w", self.compression,
665 allowZip64=True)
666 zipf.debug = 100
667 numfiles = 15
668 for i in range(numfiles):
669 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
670 self.assertEqual(len(zipf.namelist()), numfiles)
671 zipf.close()
672
673 zipf2 = zipfile.ZipFile(TESTFN, "r", self.compression)
674 self.assertEqual(len(zipf2.namelist()), numfiles)
675 for i in range(numfiles):
676 content = zipf2.read("foo%08d" % i).decode('ascii')
677 self.assertEqual(content, "%d" % (i**3 % 57))
678 zipf2.close()
679
680 def test_too_many_files_append(self):
681 zipf = zipfile.ZipFile(TESTFN, "w", self.compression,
682 allowZip64=False)
683 zipf.debug = 100
684 numfiles = 9
685 for i in range(numfiles):
686 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
687 self.assertEqual(len(zipf.namelist()), numfiles)
688 with self.assertRaises(zipfile.LargeZipFile):
689 zipf.writestr("foo%08d" % numfiles, b'')
690 self.assertEqual(len(zipf.namelist()), numfiles)
691 zipf.close()
692
693 zipf = zipfile.ZipFile(TESTFN, "a", self.compression,
694 allowZip64=False)
695 zipf.debug = 100
696 self.assertEqual(len(zipf.namelist()), numfiles)
697 with self.assertRaises(zipfile.LargeZipFile):
698 zipf.writestr("foo%08d" % numfiles, b'')
699 self.assertEqual(len(zipf.namelist()), numfiles)
700 zipf.close()
701
702 zipf = zipfile.ZipFile(TESTFN, "a", self.compression,
703 allowZip64=True)
704 zipf.debug = 100
705 self.assertEqual(len(zipf.namelist()), numfiles)
706 numfiles2 = 15
707 for i in range(numfiles, numfiles2):
708 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
709 self.assertEqual(len(zipf.namelist()), numfiles2)
710 zipf.close()
711
712 zipf2 = zipfile.ZipFile(TESTFN, "r", self.compression)
713 self.assertEqual(len(zipf2.namelist()), numfiles2)
714 for i in range(numfiles2):
715 content = zipf2.read("foo%08d" % i).decode('ascii')
716 self.assertEqual(content, "%d" % (i**3 % 57))
717 zipf2.close()
718
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300719 def tearDown(self):
720 zipfile.ZIP64_LIMIT = self._limit
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300721 zipfile.ZIP_FILECOUNT_LIMIT = self._filecount_limit
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300722 unlink(TESTFN)
723 unlink(TESTFN2)
724
725
726class StoredTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
727 unittest.TestCase):
728 compression = zipfile.ZIP_STORED
729
730 def large_file_exception_test(self, f, compression):
Serhiy Storchaka235c5e02013-11-23 15:55:38 +0200731 with zipfile.ZipFile(f, "w", compression, allowZip64=False) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300732 self.assertRaises(zipfile.LargeZipFile,
733 zipfp.write, TESTFN, "another.name")
734
735 def large_file_exception_test2(self, f, compression):
Serhiy Storchaka235c5e02013-11-23 15:55:38 +0200736 with zipfile.ZipFile(f, "w", compression, allowZip64=False) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300737 self.assertRaises(zipfile.LargeZipFile,
738 zipfp.writestr, "another.name", self.data)
739
740 def test_large_file_exception(self):
741 for f in get_files(self):
742 self.large_file_exception_test(f, zipfile.ZIP_STORED)
743 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
744
745 def test_absolute_arcnames(self):
746 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
747 allowZip64=True) as zipfp:
748 zipfp.write(TESTFN, "/absolute")
749
750 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
751 self.assertEqual(zipfp.namelist(), ["absolute"])
752
Miss Islington (bot)efdf3162018-09-17 06:08:45 -0700753 def test_append(self):
754 # Test that appending to the Zip64 archive doesn't change
755 # extra fields of existing entries.
756 with zipfile.ZipFile(TESTFN2, "w", allowZip64=True) as zipfp:
757 zipfp.writestr("strfile", self.data)
758 with zipfile.ZipFile(TESTFN2, "r", allowZip64=True) as zipfp:
759 zinfo = zipfp.getinfo("strfile")
760 extra = zinfo.extra
761 with zipfile.ZipFile(TESTFN2, "a", allowZip64=True) as zipfp:
762 zipfp.writestr("strfile2", self.data)
763 with zipfile.ZipFile(TESTFN2, "r", allowZip64=True) as zipfp:
764 zinfo = zipfp.getinfo("strfile")
765 self.assertEqual(zinfo.extra, extra)
766
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300767@requires_zlib
768class DeflateTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
769 unittest.TestCase):
770 compression = zipfile.ZIP_DEFLATED
771
772@requires_bz2
773class Bzip2TestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
774 unittest.TestCase):
775 compression = zipfile.ZIP_BZIP2
776
777@requires_lzma
778class LzmaTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
779 unittest.TestCase):
780 compression = zipfile.ZIP_LZMA
781
782
Serhiy Storchaka4c0d9ea2017-04-12 16:03:23 +0300783class AbstractWriterTests:
784
785 def tearDown(self):
786 unlink(TESTFN2)
787
788 def test_close_after_close(self):
789 data = b'content'
790 with zipfile.ZipFile(TESTFN2, "w", self.compression) as zipf:
791 w = zipf.open('test', 'w')
792 w.write(data)
793 w.close()
794 self.assertTrue(w.closed)
795 w.close()
796 self.assertTrue(w.closed)
797 self.assertEqual(zipf.read('test'), data)
798
799 def test_write_after_close(self):
800 data = b'content'
801 with zipfile.ZipFile(TESTFN2, "w", self.compression) as zipf:
802 w = zipf.open('test', 'w')
803 w.write(data)
804 w.close()
805 self.assertTrue(w.closed)
806 self.assertRaises(ValueError, w.write, b'')
807 self.assertEqual(zipf.read('test'), data)
808
809class StoredWriterTests(AbstractWriterTests, unittest.TestCase):
810 compression = zipfile.ZIP_STORED
811
812@requires_zlib
813class DeflateWriterTests(AbstractWriterTests, unittest.TestCase):
814 compression = zipfile.ZIP_DEFLATED
815
816@requires_bz2
817class Bzip2WriterTests(AbstractWriterTests, unittest.TestCase):
818 compression = zipfile.ZIP_BZIP2
819
820@requires_lzma
821class LzmaWriterTests(AbstractWriterTests, unittest.TestCase):
822 compression = zipfile.ZIP_LZMA
823
824
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300825class PyZipFileTests(unittest.TestCase):
826 def assertCompiledIn(self, name, namelist):
827 if name + 'o' not in namelist:
828 self.assertIn(name + 'c', namelist)
829
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200830 def requiresWriteAccess(self, path):
Berker Peksage1efc072015-02-16 04:36:18 +0200831 # effective_ids unavailable on windows
832 if not os.access(path, os.W_OK,
833 effective_ids=os.access in os.supports_effective_ids):
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200834 self.skipTest('requires write access to the installed location')
Serhiy Storchakad86a6ef2015-09-19 10:55:20 +0300835 filename = os.path.join(path, 'test_zipfile.try')
836 try:
837 fd = os.open(filename, os.O_WRONLY | os.O_CREAT)
838 os.close(fd)
839 except Exception:
840 self.skipTest('requires write access to the installed location')
841 unlink(filename)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200842
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300843 def test_write_pyfile(self):
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200844 self.requiresWriteAccess(os.path.dirname(__file__))
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300845 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
846 fn = __file__
Brett Cannonf299abd2015-04-13 14:21:02 -0400847 if fn.endswith('.pyc'):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300848 path_split = fn.split(os.sep)
849 if os.altsep is not None:
850 path_split.extend(fn.split(os.altsep))
851 if '__pycache__' in path_split:
Serhiy Storchaka9068e4d2013-07-22 21:02:14 +0300852 fn = importlib.util.source_from_cache(fn)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300853 else:
854 fn = fn[:-1]
855
856 zipfp.writepy(fn)
857
858 bn = os.path.basename(fn)
859 self.assertNotIn(bn, zipfp.namelist())
860 self.assertCompiledIn(bn, zipfp.namelist())
861
862 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
863 fn = __file__
Brett Cannonf299abd2015-04-13 14:21:02 -0400864 if fn.endswith('.pyc'):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300865 fn = fn[:-1]
866
867 zipfp.writepy(fn, "testpackage")
868
869 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
870 self.assertNotIn(bn, zipfp.namelist())
871 self.assertCompiledIn(bn, zipfp.namelist())
872
873 def test_write_python_package(self):
874 import email
875 packagedir = os.path.dirname(email.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200876 self.requiresWriteAccess(packagedir)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300877
878 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
879 zipfp.writepy(packagedir)
880
881 # Check for a couple of modules at different levels of the
882 # hierarchy
883 names = zipfp.namelist()
884 self.assertCompiledIn('email/__init__.py', names)
885 self.assertCompiledIn('email/mime/text.py', names)
886
Christian Tismer59202e52013-10-21 03:59:23 +0200887 def test_write_filtered_python_package(self):
888 import test
889 packagedir = os.path.dirname(test.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200890 self.requiresWriteAccess(packagedir)
Christian Tismer59202e52013-10-21 03:59:23 +0200891
892 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
893
Christian Tismer59202e52013-10-21 03:59:23 +0200894 # first make sure that the test folder gives error messages
Georg Brandla6065422013-10-21 08:29:29 +0200895 # (on the badsyntax_... files)
896 with captured_stdout() as reportSIO:
897 zipfp.writepy(packagedir)
Christian Tismer59202e52013-10-21 03:59:23 +0200898 reportStr = reportSIO.getvalue()
899 self.assertTrue('SyntaxError' in reportStr)
900
Christian Tismer410d9312013-10-22 04:09:28 +0200901 # then check that the filter works on the whole package
Georg Brandla6065422013-10-21 08:29:29 +0200902 with captured_stdout() as reportSIO:
903 zipfp.writepy(packagedir, filterfunc=lambda whatever: False)
Christian Tismer59202e52013-10-21 03:59:23 +0200904 reportStr = reportSIO.getvalue()
905 self.assertTrue('SyntaxError' not in reportStr)
906
Christian Tismer410d9312013-10-22 04:09:28 +0200907 # then check that the filter works on individual files
Larry Hastings7e63b362015-05-08 06:54:58 -0700908 def filter(path):
909 return not os.path.basename(path).startswith("bad")
Serhiy Storchakac46d1fa2014-01-20 21:59:33 +0200910 with captured_stdout() as reportSIO, self.assertWarns(UserWarning):
Larry Hastings7e63b362015-05-08 06:54:58 -0700911 zipfp.writepy(packagedir, filterfunc=filter)
Christian Tismer410d9312013-10-22 04:09:28 +0200912 reportStr = reportSIO.getvalue()
913 if reportStr:
914 print(reportStr)
915 self.assertTrue('SyntaxError' not in reportStr)
916
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300917 def test_write_with_optimization(self):
918 import email
919 packagedir = os.path.dirname(email.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200920 self.requiresWriteAccess(packagedir)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300921 optlevel = 1 if __debug__ else 0
Brett Cannonf299abd2015-04-13 14:21:02 -0400922 ext = '.pyc'
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300923
924 with TemporaryFile() as t, \
Christian Tismer59202e52013-10-21 03:59:23 +0200925 zipfile.PyZipFile(t, "w", optimize=optlevel) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300926 zipfp.writepy(packagedir)
927
928 names = zipfp.namelist()
929 self.assertIn('email/__init__' + ext, names)
930 self.assertIn('email/mime/text' + ext, names)
931
932 def test_write_python_directory(self):
933 os.mkdir(TESTFN2)
934 try:
935 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
936 fp.write("print(42)\n")
937
938 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
939 fp.write("print(42 * 42)\n")
940
941 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
942 fp.write("bla bla bla\n")
943
944 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
945 zipfp.writepy(TESTFN2)
946
947 names = zipfp.namelist()
948 self.assertCompiledIn('mod1.py', names)
949 self.assertCompiledIn('mod2.py', names)
950 self.assertNotIn('mod2.txt', names)
951
952 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200953 rmtree(TESTFN2)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300954
Christian Tismer410d9312013-10-22 04:09:28 +0200955 def test_write_python_directory_filtered(self):
956 os.mkdir(TESTFN2)
957 try:
958 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
959 fp.write("print(42)\n")
960
961 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
962 fp.write("print(42 * 42)\n")
963
964 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
965 zipfp.writepy(TESTFN2, filterfunc=lambda fn:
966 not fn.endswith('mod2.py'))
967
968 names = zipfp.namelist()
969 self.assertCompiledIn('mod1.py', names)
970 self.assertNotIn('mod2.py', names)
971
972 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200973 rmtree(TESTFN2)
Christian Tismer410d9312013-10-22 04:09:28 +0200974
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300975 def test_write_non_pyfile(self):
976 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
977 with open(TESTFN, 'w') as f:
978 f.write('most definitely not a python file')
979 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
Victor Stinner88b215e2014-09-04 00:51:09 +0200980 unlink(TESTFN)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300981
982 def test_write_pyfile_bad_syntax(self):
983 os.mkdir(TESTFN2)
984 try:
985 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
986 fp.write("Bad syntax in python file\n")
987
988 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
989 # syntax errors are printed to stdout
990 with captured_stdout() as s:
991 zipfp.writepy(os.path.join(TESTFN2, "mod1.py"))
992
993 self.assertIn("SyntaxError", s.getvalue())
994
995 # as it will not have compiled the python file, it will
Brett Cannonf299abd2015-04-13 14:21:02 -0400996 # include the .py file not .pyc
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300997 names = zipfp.namelist()
998 self.assertIn('mod1.py', names)
999 self.assertNotIn('mod1.pyc', names)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001000
1001 finally:
Victor Stinner57004c62014-09-04 00:49:01 +02001002 rmtree(TESTFN2)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001003
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001004 def test_write_pathlike(self):
1005 os.mkdir(TESTFN2)
1006 try:
1007 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
1008 fp.write("print(42)\n")
1009
1010 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
1011 zipfp.writepy(pathlib.Path(TESTFN2) / "mod1.py")
1012 names = zipfp.namelist()
1013 self.assertCompiledIn('mod1.py', names)
1014 finally:
1015 rmtree(TESTFN2)
1016
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001017
1018class ExtractTests(unittest.TestCase):
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001019
1020 def make_test_file(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001021 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
1022 for fpath, fdata in SMALL_TEST_DATA:
1023 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +00001024
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001025 def test_extract(self):
1026 with temp_cwd():
1027 self.make_test_file()
1028 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1029 for fpath, fdata in SMALL_TEST_DATA:
1030 writtenfile = zipfp.extract(fpath)
1031
1032 # make sure it was written to the right place
1033 correctfile = os.path.join(os.getcwd(), fpath)
1034 correctfile = os.path.normpath(correctfile)
1035
1036 self.assertEqual(writtenfile, correctfile)
1037
1038 # make sure correct data is in correct file
1039 with open(writtenfile, "rb") as f:
1040 self.assertEqual(fdata.encode(), f.read())
1041
1042 unlink(writtenfile)
1043
1044 def _test_extract_with_target(self, target):
1045 self.make_test_file()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001046 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1047 for fpath, fdata in SMALL_TEST_DATA:
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001048 writtenfile = zipfp.extract(fpath, target)
Christian Heimes790c8232008-01-07 21:14:23 +00001049
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001050 # make sure it was written to the right place
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001051 correctfile = os.path.join(target, fpath)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001052 correctfile = os.path.normpath(correctfile)
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001053 self.assertTrue(os.path.samefile(writtenfile, correctfile), (writtenfile, target))
Christian Heimes790c8232008-01-07 21:14:23 +00001054
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001055 # make sure correct data is in correct file
Brian Curtin8fb9b862010-11-18 02:15:28 +00001056 with open(writtenfile, "rb") as f:
1057 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +00001058
Victor Stinner88b215e2014-09-04 00:51:09 +02001059 unlink(writtenfile)
Christian Heimes790c8232008-01-07 21:14:23 +00001060
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001061 unlink(TESTFN2)
1062
1063 def test_extract_with_target(self):
1064 with temp_dir() as extdir:
1065 self._test_extract_with_target(extdir)
1066
1067 def test_extract_with_target_pathlike(self):
1068 with temp_dir() as extdir:
1069 self._test_extract_with_target(pathlib.Path(extdir))
Christian Heimes790c8232008-01-07 21:14:23 +00001070
Ezio Melottiafd0d112009-07-15 17:17:17 +00001071 def test_extract_all(self):
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001072 with temp_cwd():
1073 self.make_test_file()
1074 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1075 zipfp.extractall()
1076 for fpath, fdata in SMALL_TEST_DATA:
1077 outfile = os.path.join(os.getcwd(), fpath)
Christian Heimes790c8232008-01-07 21:14:23 +00001078
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001079 with open(outfile, "rb") as f:
1080 self.assertEqual(fdata.encode(), f.read())
1081
1082 unlink(outfile)
1083
1084 def _test_extract_all_with_target(self, target):
1085 self.make_test_file()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001086 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001087 zipfp.extractall(target)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001088 for fpath, fdata in SMALL_TEST_DATA:
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001089 outfile = os.path.join(target, fpath)
Christian Heimes790c8232008-01-07 21:14:23 +00001090
Brian Curtin8fb9b862010-11-18 02:15:28 +00001091 with open(outfile, "rb") as f:
1092 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +00001093
Victor Stinner88b215e2014-09-04 00:51:09 +02001094 unlink(outfile)
Christian Heimes790c8232008-01-07 21:14:23 +00001095
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001096 unlink(TESTFN2)
1097
1098 def test_extract_all_with_target(self):
1099 with temp_dir() as extdir:
1100 self._test_extract_all_with_target(extdir)
1101
1102 def test_extract_all_with_target_pathlike(self):
1103 with temp_dir() as extdir:
1104 self._test_extract_all_with_target(pathlib.Path(extdir))
Christian Heimes790c8232008-01-07 21:14:23 +00001105
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001106 def check_file(self, filename, content):
1107 self.assertTrue(os.path.isfile(filename))
1108 with open(filename, 'rb') as f:
1109 self.assertEqual(f.read(), content)
1110
Gregory P. Smith09aa7522013-02-03 00:36:32 -08001111 def test_sanitize_windows_name(self):
1112 san = zipfile.ZipFile._sanitize_windows_name
1113 # Passing pathsep in allows this test to work regardless of platform.
1114 self.assertEqual(san(r',,?,C:,foo,bar/z', ','), r'_,C_,foo,bar/z')
1115 self.assertEqual(san(r'a\b,c<d>e|f"g?h*i', ','), r'a\b,c_d_e_f_g_h_i')
1116 self.assertEqual(san('../../foo../../ba..r', '/'), r'foo/ba..r')
1117
1118 def test_extract_hackers_arcnames_common_cases(self):
1119 common_hacknames = [
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001120 ('../foo/bar', 'foo/bar'),
1121 ('foo/../bar', 'foo/bar'),
1122 ('foo/../../bar', 'foo/bar'),
1123 ('foo/bar/..', 'foo/bar'),
1124 ('./../foo/bar', 'foo/bar'),
1125 ('/foo/bar', 'foo/bar'),
1126 ('/foo/../bar', 'foo/bar'),
1127 ('/foo/../../bar', 'foo/bar'),
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001128 ]
Gregory P. Smith09aa7522013-02-03 00:36:32 -08001129 self._test_extract_hackers_arcnames(common_hacknames)
1130
1131 @unittest.skipIf(os.path.sep != '\\', 'Requires \\ as path separator.')
1132 def test_extract_hackers_arcnames_windows_only(self):
1133 """Test combination of path fixing and windows name sanitization."""
1134 windows_hacknames = [
Christian Tismer59202e52013-10-21 03:59:23 +02001135 (r'..\foo\bar', 'foo/bar'),
1136 (r'..\/foo\/bar', 'foo/bar'),
1137 (r'foo/\..\/bar', 'foo/bar'),
1138 (r'foo\/../\bar', 'foo/bar'),
1139 (r'C:foo/bar', 'foo/bar'),
1140 (r'C:/foo/bar', 'foo/bar'),
1141 (r'C://foo/bar', 'foo/bar'),
1142 (r'C:\foo\bar', 'foo/bar'),
1143 (r'//conky/mountpoint/foo/bar', 'foo/bar'),
1144 (r'\\conky\mountpoint\foo\bar', 'foo/bar'),
1145 (r'///conky/mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
1146 (r'\\\conky\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
1147 (r'//conky//mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
1148 (r'\\conky\\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
1149 (r'//?/C:/foo/bar', 'foo/bar'),
1150 (r'\\?\C:\foo\bar', 'foo/bar'),
1151 (r'C:/../C:/foo/bar', 'C_/foo/bar'),
1152 (r'a:b\c<d>e|f"g?h*i', 'b/c_d_e_f_g_h_i'),
1153 ('../../foo../../ba..r', 'foo/ba..r'),
Gregory P. Smith09aa7522013-02-03 00:36:32 -08001154 ]
1155 self._test_extract_hackers_arcnames(windows_hacknames)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001156
Gregory P. Smith09aa7522013-02-03 00:36:32 -08001157 @unittest.skipIf(os.path.sep != '/', r'Requires / as path separator.')
1158 def test_extract_hackers_arcnames_posix_only(self):
1159 posix_hacknames = [
1160 ('//foo/bar', 'foo/bar'),
1161 ('../../foo../../ba..r', 'foo../ba..r'),
1162 (r'foo/..\bar', r'foo/..\bar'),
1163 ]
1164 self._test_extract_hackers_arcnames(posix_hacknames)
1165
1166 def _test_extract_hackers_arcnames(self, hacknames):
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001167 for arcname, fixedname in hacknames:
1168 content = b'foobar' + arcname.encode()
1169 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipfp:
Serhiy Storchakae5e64442013-02-02 19:50:59 +02001170 zinfo = zipfile.ZipInfo()
1171 # preserve backslashes
1172 zinfo.filename = arcname
1173 zinfo.external_attr = 0o600 << 16
1174 zipfp.writestr(zinfo, content)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001175
Serhiy Storchakae5e64442013-02-02 19:50:59 +02001176 arcname = arcname.replace(os.sep, "/")
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001177 targetpath = os.path.join('target', 'subdir', 'subsub')
1178 correctfile = os.path.join(targetpath, *fixedname.split('/'))
1179
1180 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1181 writtenfile = zipfp.extract(arcname, targetpath)
Serhiy Storchakae5e64442013-02-02 19:50:59 +02001182 self.assertEqual(writtenfile, correctfile,
Gregory P. Smith09aa7522013-02-03 00:36:32 -08001183 msg='extract %r: %r != %r' %
1184 (arcname, writtenfile, correctfile))
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001185 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001186 rmtree('target')
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001187
1188 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1189 zipfp.extractall(targetpath)
1190 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001191 rmtree('target')
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001192
1193 correctfile = os.path.join(os.getcwd(), *fixedname.split('/'))
1194
1195 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1196 writtenfile = zipfp.extract(arcname)
Serhiy Storchakae5e64442013-02-02 19:50:59 +02001197 self.assertEqual(writtenfile, correctfile,
1198 msg="extract %r" % arcname)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001199 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001200 rmtree(fixedname.split('/')[0])
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001201
1202 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1203 zipfp.extractall()
1204 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001205 rmtree(fixedname.split('/')[0])
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001206
Victor Stinner88b215e2014-09-04 00:51:09 +02001207 unlink(TESTFN2)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001208
Ronald Oussorenee5c8852010-02-07 20:24:02 +00001209
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001210class OtherTests(unittest.TestCase):
1211 def test_open_via_zip_info(self):
1212 # Create the ZIP archive
1213 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
1214 zipfp.writestr("name", "foo")
Serhiy Storchaka9b7a1a12014-01-20 21:57:40 +02001215 with self.assertWarns(UserWarning):
1216 zipfp.writestr("name", "bar")
1217 self.assertEqual(zipfp.namelist(), ["name"] * 2)
Ronald Oussorenee5c8852010-02-07 20:24:02 +00001218
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001219 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1220 infos = zipfp.infolist()
1221 data = b""
1222 for info in infos:
1223 with zipfp.open(info) as zipopen:
1224 data += zipopen.read()
1225 self.assertIn(data, {b"foobar", b"barfoo"})
1226 data = b""
1227 for info in infos:
1228 data += zipfp.read(info)
1229 self.assertIn(data, {b"foobar", b"barfoo"})
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001230
Gregory P. Smithb0d9ca922009-07-07 05:06:04 +00001231 def test_writestr_extended_local_header_issue1202(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001232 with zipfile.ZipFile(TESTFN2, 'w') as orig_zip:
1233 for data in 'abcdefghijklmnop':
1234 zinfo = zipfile.ZipInfo(data)
1235 zinfo.flag_bits |= 0x08 # Include an extended local header.
1236 orig_zip.writestr(zinfo, data)
1237
1238 def test_close(self):
1239 """Check that the zipfile is closed after the 'with' block."""
1240 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
1241 for fpath, fdata in SMALL_TEST_DATA:
1242 zipfp.writestr(fpath, fdata)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001243 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
1244 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001245
1246 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001247 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
1248 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001249
1250 def test_close_on_exception(self):
1251 """Check that the zipfile is closed if an exception is raised in the
1252 'with' block."""
1253 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
1254 for fpath, fdata in SMALL_TEST_DATA:
1255 zipfp.writestr(fpath, fdata)
1256
1257 try:
1258 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
Georg Brandl4d540882010-10-28 06:42:33 +00001259 raise zipfile.BadZipFile()
1260 except zipfile.BadZipFile:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001261 self.assertIsNone(zipfp2.fp, 'zipfp is not closed')
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001262
Martin v. Löwisd099b562012-05-01 14:08:22 +02001263 def test_unsupported_version(self):
1264 # File has an extract_version of 120
1265 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 +02001266 b'\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00xPK\x01\x02x\x03x\x00\x00\x00\x00'
1267 b'\x00!p\xa1@\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00'
1268 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00\x00xPK\x05\x06'
1269 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 +03001270
Martin v. Löwisd099b562012-05-01 14:08:22 +02001271 self.assertRaises(NotImplementedError, zipfile.ZipFile,
1272 io.BytesIO(data), 'r')
1273
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001274 @requires_zlib
1275 def test_read_unicode_filenames(self):
1276 # bug #10801
1277 fname = findfile('zip_cp437_header.zip')
1278 with zipfile.ZipFile(fname) as zipfp:
1279 for name in zipfp.namelist():
1280 zipfp.open(name).close()
1281
1282 def test_write_unicode_filenames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001283 with zipfile.ZipFile(TESTFN, "w") as zf:
1284 zf.writestr("foo.txt", "Test for unicode filename")
1285 zf.writestr("\xf6.txt", "Test for unicode filename")
Ezio Melottie9615932010-01-24 19:26:24 +00001286 self.assertIsInstance(zf.infolist()[0].filename, str)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001287
1288 with zipfile.ZipFile(TESTFN, "r") as zf:
1289 self.assertEqual(zf.filelist[0].filename, "foo.txt")
1290 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
Martin v. Löwis8570f6a2008-05-05 17:44:38 +00001291
Serhiy Storchaka764fc9b2015-03-25 10:09:41 +02001292 def test_exclusive_create_zip_file(self):
1293 """Test exclusive creating a new zipfile."""
1294 unlink(TESTFN2)
1295 filename = 'testfile.txt'
1296 content = b'hello, world. this is some content.'
1297 with zipfile.ZipFile(TESTFN2, "x", zipfile.ZIP_STORED) as zipfp:
1298 zipfp.writestr(filename, content)
1299 with self.assertRaises(FileExistsError):
1300 zipfile.ZipFile(TESTFN2, "x", zipfile.ZIP_STORED)
1301 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1302 self.assertEqual(zipfp.namelist(), [filename])
1303 self.assertEqual(zipfp.read(filename), content)
1304
Ezio Melottiafd0d112009-07-15 17:17:17 +00001305 def test_create_non_existent_file_for_append(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001306 if os.path.exists(TESTFN):
1307 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001308
Thomas Wouterscf297e42007-02-23 15:07:44 +00001309 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001310 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +00001311
Thomas Wouterscf297e42007-02-23 15:07:44 +00001312 try:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001313 with zipfile.ZipFile(TESTFN, 'a') as zf:
1314 zf.writestr(filename, content)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001315 except OSError:
Thomas Wouterscf297e42007-02-23 15:07:44 +00001316 self.fail('Could not append data to a non-existent zip file.')
1317
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001318 self.assertTrue(os.path.exists(TESTFN))
Thomas Wouterscf297e42007-02-23 15:07:44 +00001319
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001320 with zipfile.ZipFile(TESTFN, 'r') as zf:
1321 self.assertEqual(zf.read(filename), content)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001322
Ezio Melottiafd0d112009-07-15 17:17:17 +00001323 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001324 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti35386712009-12-31 13:22:41 +00001325 # it opens if there's an error in the file. If it doesn't, the
1326 # traceback holds a reference to the ZipFile object and, indirectly,
1327 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001328 # On Windows, this causes the os.unlink() call to fail because the
1329 # underlying file is still open. This is SF bug #412214.
1330 #
Ezio Melotti35386712009-12-31 13:22:41 +00001331 with open(TESTFN, "w") as fp:
1332 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001333 try:
1334 zf = zipfile.ZipFile(TESTFN)
Georg Brandl4d540882010-10-28 06:42:33 +00001335 except zipfile.BadZipFile:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001336 pass
1337
Ezio Melottiafd0d112009-07-15 17:17:17 +00001338 def test_is_zip_erroneous_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001339 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001340 # - passing a filename
1341 with open(TESTFN, "w") as fp:
1342 fp.write("this is not a legal zip file\n")
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001343 self.assertFalse(zipfile.is_zipfile(TESTFN))
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001344 # - passing a path-like object
1345 self.assertFalse(zipfile.is_zipfile(pathlib.Path(TESTFN)))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001346 # - passing a file object
1347 with open(TESTFN, "rb") as fp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001348 self.assertFalse(zipfile.is_zipfile(fp))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001349 # - passing a file-like object
1350 fp = io.BytesIO()
1351 fp.write(b"this is not a legal zip file\n")
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001352 self.assertFalse(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001353 fp.seek(0, 0)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001354 self.assertFalse(zipfile.is_zipfile(fp))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001355
Serhiy Storchakad2b15272013-01-31 15:27:07 +02001356 def test_damaged_zipfile(self):
1357 """Check that zipfiles with missing bytes at the end raise BadZipFile."""
1358 # - Create a valid zip file
1359 fp = io.BytesIO()
1360 with zipfile.ZipFile(fp, mode="w") as zipf:
1361 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
1362 zipfiledata = fp.getvalue()
1363
1364 # - Now create copies of it missing the last N bytes and make sure
1365 # a BadZipFile exception is raised when we try to open it
1366 for N in range(len(zipfiledata)):
1367 fp = io.BytesIO(zipfiledata[:N])
1368 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, fp)
1369
Ezio Melottiafd0d112009-07-15 17:17:17 +00001370 def test_is_zip_valid_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001371 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001372 # - passing a filename
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001373 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1374 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
1375
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001376 self.assertTrue(zipfile.is_zipfile(TESTFN))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001377 # - passing a file object
1378 with open(TESTFN, "rb") as fp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001379 self.assertTrue(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001380 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001381 zip_contents = fp.read()
1382 # - passing a file-like object
1383 fp = io.BytesIO()
1384 fp.write(zip_contents)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001385 self.assertTrue(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001386 fp.seek(0, 0)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001387 self.assertTrue(zipfile.is_zipfile(fp))
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001388
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001389 def test_non_existent_file_raises_OSError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001390 # make sure we don't raise an AttributeError when a partially-constructed
1391 # ZipFile instance is finalized; this tests for regression on SF tracker
1392 # bug #403871.
1393
1394 # The bug we're testing for caused an AttributeError to be raised
1395 # when a ZipFile instance was created for a file that did not
1396 # exist; the .fp member was not initialized but was needed by the
1397 # __del__() method. Since the AttributeError is in the __del__(),
1398 # it is ignored, but the user should be sufficiently annoyed by
1399 # the message on the output that regression will be noticed
1400 # quickly.
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001401 self.assertRaises(OSError, zipfile.ZipFile, TESTFN)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001402
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001403 def test_empty_file_raises_BadZipFile(self):
1404 f = open(TESTFN, 'w')
1405 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001406 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001407
Ezio Melotti35386712009-12-31 13:22:41 +00001408 with open(TESTFN, 'w') as fp:
1409 fp.write("short file")
Georg Brandl4d540882010-10-28 06:42:33 +00001410 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001411
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001412 def test_closed_zip_raises_ValueError(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001413 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001414 data = io.BytesIO()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001415 with zipfile.ZipFile(data, mode="w") as zipf:
1416 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001417
Andrew Svetlov737fb892012-12-18 21:14:22 +02001418 # This is correct; calling .read on a closed ZipFile should raise
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001419 # a ValueError, and so should calling .testzip. An earlier
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001420 # version of .testzip would swallow this exception (and any other)
1421 # and report that the first file in the archive was corrupt.
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001422 self.assertRaises(ValueError, zipf.read, "foo.txt")
1423 self.assertRaises(ValueError, zipf.open, "foo.txt")
1424 self.assertRaises(ValueError, zipf.testzip)
1425 self.assertRaises(ValueError, zipf.writestr, "bogus.txt", "bogus")
Brian Curtin8fb9b862010-11-18 02:15:28 +00001426 with open(TESTFN, 'w') as f:
1427 f.write('zipfile test data')
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001428 self.assertRaises(ValueError, zipf.write, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001429
Ezio Melottiafd0d112009-07-15 17:17:17 +00001430 def test_bad_constructor_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001431 """Check that bad modes passed to ZipFile constructor are caught."""
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001432 self.assertRaises(ValueError, zipfile.ZipFile, TESTFN, "q")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001433
Ezio Melottiafd0d112009-07-15 17:17:17 +00001434 def test_bad_open_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001435 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001436 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1437 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1438
1439 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Serhiy Storchakae670be22016-06-11 19:32:44 +03001440 # read the data to make sure the file is there
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001441 zipf.read("foo.txt")
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001442 self.assertRaises(ValueError, zipf.open, "foo.txt", "q")
Serhiy Storchakae670be22016-06-11 19:32:44 +03001443 # universal newlines support is removed
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001444 self.assertRaises(ValueError, zipf.open, "foo.txt", "U")
1445 self.assertRaises(ValueError, zipf.open, "foo.txt", "rU")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001446
Ezio Melottiafd0d112009-07-15 17:17:17 +00001447 def test_read0(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001448 """Check that calling read(0) on a ZipExtFile object returns an empty
1449 string and doesn't advance file pointer."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001450 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1451 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1452 # read the data to make sure the file is there
Brian Curtin8fb9b862010-11-18 02:15:28 +00001453 with zipf.open("foo.txt") as f:
1454 for i in range(FIXEDTEST_SIZE):
1455 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001456
Brian Curtin8fb9b862010-11-18 02:15:28 +00001457 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001458
Ezio Melottiafd0d112009-07-15 17:17:17 +00001459 def test_open_non_existent_item(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001460 """Check that attempting to call open() for an item that doesn't
1461 exist in the archive raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001462 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1463 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001464
Ezio Melottiafd0d112009-07-15 17:17:17 +00001465 def test_bad_compression_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001466 """Check that bad compression methods passed to ZipFile.open are
1467 caught."""
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001468 self.assertRaises(NotImplementedError, zipfile.ZipFile, TESTFN, "w", -1)
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001469
Martin v. Löwisb3260f02012-05-01 08:38:01 +02001470 def test_unsupported_compression(self):
1471 # data is declared as shrunk, but actually deflated
1472 data = (b'PK\x03\x04.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00'
Christian Tismer59202e52013-10-21 03:59:23 +02001473 b'\x00\x02\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00x\x03\x00PK\x01'
1474 b'\x02.\x03.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00\x00\x02\x00\x00'
1475 b'\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
1476 b'\x80\x01\x00\x00\x00\x00xPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00'
1477 b'/\x00\x00\x00!\x00\x00\x00\x00\x00')
Martin v. Löwisb3260f02012-05-01 08:38:01 +02001478 with zipfile.ZipFile(io.BytesIO(data), 'r') as zipf:
1479 self.assertRaises(NotImplementedError, zipf.open, 'x')
1480
Ezio Melottiafd0d112009-07-15 17:17:17 +00001481 def test_null_byte_in_filename(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001482 """Check that a filename containing a null byte is properly
1483 terminated."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001484 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1485 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
1486 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001487
Ezio Melottiafd0d112009-07-15 17:17:17 +00001488 def test_struct_sizes(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001489 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001490 self.assertEqual(zipfile.sizeEndCentDir, 22)
1491 self.assertEqual(zipfile.sizeCentralDir, 46)
1492 self.assertEqual(zipfile.sizeEndCentDir64, 56)
1493 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
1494
Ezio Melottiafd0d112009-07-15 17:17:17 +00001495 def test_comments(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001496 """Check that comments on the archive are handled properly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001497
1498 # check default comment is empty
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001499 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1500 self.assertEqual(zipf.comment, b'')
1501 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1502
1503 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1504 self.assertEqual(zipfr.comment, b'')
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001505
1506 # check a simple short comment
1507 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001508 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1509 zipf.comment = comment
1510 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1511 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1512 self.assertEqual(zipf.comment, comment)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001513
1514 # check a comment of max length
1515 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
1516 comment2 = comment2.encode("ascii")
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001517 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1518 zipf.comment = comment2
1519 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1520
1521 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1522 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001523
1524 # check a comment that is too long is truncated
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001525 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
Serhiy Storchaka9b7a1a12014-01-20 21:57:40 +02001526 with self.assertWarns(UserWarning):
1527 zipf.comment = comment2 + b'oops'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001528 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1529 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1530 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001531
Antoine Pitrouc3991852012-06-30 17:31:37 +02001532 # check that comments are correctly modified in append mode
1533 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1534 zipf.comment = b"original comment"
1535 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1536 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1537 zipf.comment = b"an updated comment"
1538 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1539 self.assertEqual(zipf.comment, b"an updated comment")
1540
1541 # check that comments are correctly shortened in append mode
1542 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1543 zipf.comment = b"original comment that's longer"
1544 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1545 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1546 zipf.comment = b"shorter comment"
1547 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1548 self.assertEqual(zipf.comment, b"shorter comment")
1549
R David Murrayf50b38a2012-04-12 18:44:58 -04001550 def test_unicode_comment(self):
1551 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1552 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1553 with self.assertRaises(TypeError):
1554 zipf.comment = "this is an error"
1555
1556 def test_change_comment_in_empty_archive(self):
1557 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1558 self.assertFalse(zipf.filelist)
1559 zipf.comment = b"this is a comment"
1560 with zipfile.ZipFile(TESTFN, "r") as zipf:
1561 self.assertEqual(zipf.comment, b"this is a comment")
1562
1563 def test_change_comment_in_nonempty_archive(self):
1564 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1565 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1566 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1567 self.assertTrue(zipf.filelist)
1568 zipf.comment = b"this is a comment"
1569 with zipfile.ZipFile(TESTFN, "r") as zipf:
1570 self.assertEqual(zipf.comment, b"this is a comment")
1571
Georg Brandl268e4d42010-10-14 06:59:45 +00001572 def test_empty_zipfile(self):
1573 # Check that creating a file in 'w' or 'a' mode and closing without
1574 # adding any files to the archives creates a valid empty ZIP file
1575 zipf = zipfile.ZipFile(TESTFN, mode="w")
1576 zipf.close()
1577 try:
1578 zipf = zipfile.ZipFile(TESTFN, mode="r")
1579 except zipfile.BadZipFile:
1580 self.fail("Unable to create empty ZIP file in 'w' mode")
1581
1582 zipf = zipfile.ZipFile(TESTFN, mode="a")
1583 zipf.close()
1584 try:
1585 zipf = zipfile.ZipFile(TESTFN, mode="r")
1586 except:
1587 self.fail("Unable to create empty ZIP file in 'a' mode")
1588
1589 def test_open_empty_file(self):
1590 # Issue 1710703: Check that opening a file with less than 22 bytes
Georg Brandl4d540882010-10-28 06:42:33 +00001591 # raises a BadZipFile exception (rather than the previously unhelpful
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001592 # OSError)
Georg Brandl268e4d42010-10-14 06:59:45 +00001593 f = open(TESTFN, 'w')
1594 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001595 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN, 'r')
Georg Brandl268e4d42010-10-14 06:59:45 +00001596
Senthil Kumaran29fa9d42011-10-20 01:46:00 +08001597 def test_create_zipinfo_before_1980(self):
1598 self.assertRaises(ValueError,
1599 zipfile.ZipInfo, 'seventies', (1979, 1, 1, 0, 0, 0))
1600
Gregory P. Smith0af8a862014-05-29 23:42:14 -07001601 def test_zipfile_with_short_extra_field(self):
1602 """If an extra field in the header is less than 4 bytes, skip it."""
1603 zipdata = (
1604 b'PK\x03\x04\x14\x00\x00\x00\x00\x00\x93\x9b\xad@\x8b\x9e'
1605 b'\xd9\xd3\x01\x00\x00\x00\x01\x00\x00\x00\x03\x00\x03\x00ab'
1606 b'c\x00\x00\x00APK\x01\x02\x14\x03\x14\x00\x00\x00\x00'
1607 b'\x00\x93\x9b\xad@\x8b\x9e\xd9\xd3\x01\x00\x00\x00\x01\x00\x00'
1608 b'\x00\x03\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00'
1609 b'\x00\x00\x00abc\x00\x00PK\x05\x06\x00\x00\x00\x00'
1610 b'\x01\x00\x01\x003\x00\x00\x00%\x00\x00\x00\x00\x00'
1611 )
1612 with zipfile.ZipFile(io.BytesIO(zipdata), 'r') as zipf:
1613 # testzip returns the name of the first corrupt file, or None
1614 self.assertIsNone(zipf.testzip())
1615
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001616 def test_open_conflicting_handles(self):
1617 # It's only possible to open one writable file handle at a time
1618 msg1 = b"It's fun to charter an accountant!"
1619 msg2 = b"And sail the wide accountant sea"
1620 msg3 = b"To find, explore the funds offshore"
1621 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipf:
1622 with zipf.open('foo', mode='w') as w2:
1623 w2.write(msg1)
1624 with zipf.open('bar', mode='w') as w1:
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001625 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001626 zipf.open('handle', mode='w')
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001627 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001628 zipf.open('foo', mode='r')
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001629 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001630 zipf.writestr('str', 'abcde')
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001631 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001632 zipf.write(__file__, 'file')
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001633 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001634 zipf.close()
1635 w1.write(msg2)
1636 with zipf.open('baz', mode='w') as w2:
1637 w2.write(msg3)
1638
1639 with zipfile.ZipFile(TESTFN2, 'r') as zipf:
1640 self.assertEqual(zipf.read('foo'), msg1)
1641 self.assertEqual(zipf.read('bar'), msg2)
1642 self.assertEqual(zipf.read('baz'), msg3)
1643 self.assertEqual(zipf.namelist(), ['foo', 'bar', 'baz'])
1644
John Jolly066df4f2018-01-30 01:51:35 -07001645 def test_seek_tell(self):
1646 # Test seek functionality
1647 txt = b"Where's Bruce?"
1648 bloc = txt.find(b"Bruce")
1649 # Check seek on a file
1650 with zipfile.ZipFile(TESTFN, "w") as zipf:
1651 zipf.writestr("foo.txt", txt)
1652 with zipfile.ZipFile(TESTFN, "r") as zipf:
1653 with zipf.open("foo.txt", "r") as fp:
1654 fp.seek(bloc, os.SEEK_SET)
1655 self.assertEqual(fp.tell(), bloc)
1656 fp.seek(-bloc, os.SEEK_CUR)
1657 self.assertEqual(fp.tell(), 0)
1658 fp.seek(bloc, os.SEEK_CUR)
1659 self.assertEqual(fp.tell(), bloc)
1660 self.assertEqual(fp.read(5), txt[bloc:bloc+5])
1661 fp.seek(0, os.SEEK_END)
1662 self.assertEqual(fp.tell(), len(txt))
Miss Islington (bot)ad4f64d2018-07-29 12:57:21 -07001663 fp.seek(0, os.SEEK_SET)
1664 self.assertEqual(fp.tell(), 0)
John Jolly066df4f2018-01-30 01:51:35 -07001665 # Check seek on memory file
1666 data = io.BytesIO()
1667 with zipfile.ZipFile(data, mode="w") as zipf:
1668 zipf.writestr("foo.txt", txt)
1669 with zipfile.ZipFile(data, mode="r") as zipf:
1670 with zipf.open("foo.txt", "r") as fp:
1671 fp.seek(bloc, os.SEEK_SET)
1672 self.assertEqual(fp.tell(), bloc)
1673 fp.seek(-bloc, os.SEEK_CUR)
1674 self.assertEqual(fp.tell(), 0)
1675 fp.seek(bloc, os.SEEK_CUR)
1676 self.assertEqual(fp.tell(), bloc)
1677 self.assertEqual(fp.read(5), txt[bloc:bloc+5])
1678 fp.seek(0, os.SEEK_END)
1679 self.assertEqual(fp.tell(), len(txt))
Miss Islington (bot)ad4f64d2018-07-29 12:57:21 -07001680 fp.seek(0, os.SEEK_SET)
1681 self.assertEqual(fp.tell(), 0)
John Jolly066df4f2018-01-30 01:51:35 -07001682
Guido van Rossumd8faa362007-04-27 19:54:29 +00001683 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001684 unlink(TESTFN)
1685 unlink(TESTFN2)
1686
Thomas Wouterscf297e42007-02-23 15:07:44 +00001687
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001688class AbstractBadCrcTests:
1689 def test_testzip_with_bad_crc(self):
1690 """Tests that files with bad CRCs return their name from testzip."""
1691 zipdata = self.zip_with_bad_crc
1692
1693 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1694 # testzip returns the name of the first corrupt file, or None
1695 self.assertEqual('afile', zipf.testzip())
1696
1697 def test_read_with_bad_crc(self):
1698 """Tests that files with bad CRCs raise a BadZipFile exception when read."""
1699 zipdata = self.zip_with_bad_crc
1700
1701 # Using ZipFile.read()
1702 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1703 self.assertRaises(zipfile.BadZipFile, zipf.read, 'afile')
1704
1705 # Using ZipExtFile.read()
1706 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1707 with zipf.open('afile', 'r') as corrupt_file:
1708 self.assertRaises(zipfile.BadZipFile, corrupt_file.read)
1709
1710 # Same with small reads (in order to exercise the buffering logic)
1711 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1712 with zipf.open('afile', 'r') as corrupt_file:
1713 corrupt_file.MIN_READ_SIZE = 2
1714 with self.assertRaises(zipfile.BadZipFile):
1715 while corrupt_file.read(2):
1716 pass
1717
1718
1719class StoredBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1720 compression = zipfile.ZIP_STORED
1721 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001722 b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
1723 b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
1724 b'ilehello,AworldP'
1725 b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
1726 b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
1727 b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
1728 b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
1729 b'\0\0/\0\0\0\0\0')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001730
1731@requires_zlib
1732class DeflateBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1733 compression = zipfile.ZIP_DEFLATED
1734 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001735 b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
1736 b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1737 b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
1738 b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
1739 b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
1740 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
1741 b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
1742 b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001743
1744@requires_bz2
1745class Bzip2BadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1746 compression = zipfile.ZIP_BZIP2
1747 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001748 b'PK\x03\x04\x14\x03\x00\x00\x0c\x00nu\x0c=FA'
1749 b'KE8\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1750 b'ileBZh91AY&SY\xd4\xa8\xca'
1751 b'\x7f\x00\x00\x0f\x11\x80@\x00\x06D\x90\x80 \x00 \xa5'
1752 b'P\xd9!\x03\x03\x13\x13\x13\x89\xa9\xa9\xc2u5:\x9f'
1753 b'\x8b\xb9"\x9c(HjTe?\x80PK\x01\x02\x14'
1754 b'\x03\x14\x03\x00\x00\x0c\x00nu\x0c=FAKE8'
1755 b'\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\x00'
1756 b'\x00 \x80\x80\x81\x00\x00\x00\x00afilePK'
1757 b'\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00\x00[\x00'
1758 b'\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001759
1760@requires_lzma
1761class LzmaBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1762 compression = zipfile.ZIP_LZMA
1763 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001764 b'PK\x03\x04\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
1765 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1766 b'ile\t\x04\x05\x00]\x00\x00\x00\x04\x004\x19I'
1767 b'\xee\x8d\xe9\x17\x89:3`\tq!.8\x00PK'
1768 b'\x01\x02\x14\x03\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
1769 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00'
1770 b'\x00\x00\x00\x00 \x80\x80\x81\x00\x00\x00\x00afil'
1771 b'ePK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00'
1772 b'\x00>\x00\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001773
1774
Thomas Wouterscf297e42007-02-23 15:07:44 +00001775class DecryptionTests(unittest.TestCase):
Ezio Melotti35386712009-12-31 13:22:41 +00001776 """Check that ZIP decryption works. Since the library does not
1777 support encryption at the moment, we use a pre-generated encrypted
1778 ZIP file."""
Thomas Wouterscf297e42007-02-23 15:07:44 +00001779
1780 data = (
Christian Tismer59202e52013-10-21 03:59:23 +02001781 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
1782 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
1783 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
1784 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
1785 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
1786 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
1787 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +00001788 data2 = (
Christian Tismer59202e52013-10-21 03:59:23 +02001789 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
1790 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
1791 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
1792 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
1793 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
1794 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
1795 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
1796 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +00001797
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001798 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +00001799 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +00001800
1801 def setUp(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001802 with open(TESTFN, "wb") as fp:
1803 fp.write(self.data)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001804 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti35386712009-12-31 13:22:41 +00001805 with open(TESTFN2, "wb") as fp:
1806 fp.write(self.data2)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001807 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001808
1809 def tearDown(self):
1810 self.zip.close()
1811 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001812 self.zip2.close()
1813 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001814
Ezio Melottiafd0d112009-07-15 17:17:17 +00001815 def test_no_password(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001816 # Reading the encrypted file without password
1817 # must generate a RunTime exception
1818 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001819 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001820
Ezio Melottiafd0d112009-07-15 17:17:17 +00001821 def test_bad_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001822 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001823 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001824 self.zip2.setpassword(b"perl")
1825 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001826
Ezio Melotti975077a2011-05-19 22:03:22 +03001827 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +00001828 def test_good_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001829 self.zip.setpassword(b"python")
Ezio Melotti35386712009-12-31 13:22:41 +00001830 self.assertEqual(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001831 self.zip2.setpassword(b"12345")
Ezio Melotti35386712009-12-31 13:22:41 +00001832 self.assertEqual(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001833
R. David Murray8d855d82010-12-21 21:53:37 +00001834 def test_unicode_password(self):
1835 self.assertRaises(TypeError, self.zip.setpassword, "unicode")
1836 self.assertRaises(TypeError, self.zip.read, "test.txt", "python")
1837 self.assertRaises(TypeError, self.zip.open, "test.txt", pwd="python")
1838 self.assertRaises(TypeError, self.zip.extract, "test.txt", pwd="python")
1839
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001840class AbstractTestsWithRandomBinaryFiles:
1841 @classmethod
1842 def setUpClass(cls):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001843 datacount = randint(16, 64)*1024 + randint(1, 1024)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001844 cls.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
1845 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001846
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001847 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001848 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +00001849 with open(TESTFN, "wb") as fp:
1850 fp.write(self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001851
1852 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001853 unlink(TESTFN)
1854 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001855
Ezio Melottiafd0d112009-07-15 17:17:17 +00001856 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001857 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001858 with zipfile.ZipFile(f, "w", compression) as zipfp:
1859 zipfp.write(TESTFN, "another.name")
1860 zipfp.write(TESTFN, TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001861
Ezio Melottiafd0d112009-07-15 17:17:17 +00001862 def zip_test(self, f, compression):
1863 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001864
1865 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001866 with zipfile.ZipFile(f, "r", compression) as zipfp:
1867 testdata = zipfp.read(TESTFN)
1868 self.assertEqual(len(testdata), len(self.data))
1869 self.assertEqual(testdata, self.data)
1870 self.assertEqual(zipfp.read("another.name"), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001871
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001872 def test_read(self):
1873 for f in get_files(self):
1874 self.zip_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001875
Ezio Melottiafd0d112009-07-15 17:17:17 +00001876 def zip_open_test(self, f, compression):
1877 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001878
1879 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001880 with zipfile.ZipFile(f, "r", compression) as zipfp:
1881 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001882 with zipfp.open(TESTFN) as zipopen1:
1883 while True:
1884 read_data = zipopen1.read(256)
1885 if not read_data:
1886 break
1887 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001888
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001889 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001890 with zipfp.open("another.name") as zipopen2:
1891 while True:
1892 read_data = zipopen2.read(256)
1893 if not read_data:
1894 break
1895 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001896
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001897 testdata1 = b''.join(zipdata1)
1898 self.assertEqual(len(testdata1), len(self.data))
1899 self.assertEqual(testdata1, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001900
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001901 testdata2 = b''.join(zipdata2)
Ezio Melotti35386712009-12-31 13:22:41 +00001902 self.assertEqual(len(testdata2), len(self.data))
1903 self.assertEqual(testdata2, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001904
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001905 def test_open(self):
1906 for f in get_files(self):
1907 self.zip_open_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001908
Ezio Melottiafd0d112009-07-15 17:17:17 +00001909 def zip_random_open_test(self, f, compression):
1910 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001911
1912 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001913 with zipfile.ZipFile(f, "r", compression) as zipfp:
1914 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001915 with zipfp.open(TESTFN) as zipopen1:
1916 while True:
1917 read_data = zipopen1.read(randint(1, 1024))
1918 if not read_data:
1919 break
1920 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001921
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001922 testdata = b''.join(zipdata1)
1923 self.assertEqual(len(testdata), len(self.data))
1924 self.assertEqual(testdata, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001925
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001926 def test_random_open(self):
1927 for f in get_files(self):
1928 self.zip_random_open_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001929
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001930
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001931class StoredTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1932 unittest.TestCase):
1933 compression = zipfile.ZIP_STORED
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001934
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001935@requires_zlib
1936class DeflateTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1937 unittest.TestCase):
1938 compression = zipfile.ZIP_DEFLATED
1939
1940@requires_bz2
1941class Bzip2TestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1942 unittest.TestCase):
1943 compression = zipfile.ZIP_BZIP2
1944
1945@requires_lzma
1946class LzmaTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1947 unittest.TestCase):
1948 compression = zipfile.ZIP_LZMA
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001949
Ezio Melotti76430242009-07-11 18:28:48 +00001950
luzpaza5293b42017-11-05 07:37:50 -06001951# Provide the tell() method but not seek()
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001952class Tellable:
1953 def __init__(self, fp):
1954 self.fp = fp
1955 self.offset = 0
1956
1957 def write(self, data):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02001958 n = self.fp.write(data)
1959 self.offset += n
1960 return n
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001961
1962 def tell(self):
1963 return self.offset
1964
1965 def flush(self):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02001966 self.fp.flush()
1967
1968class Unseekable:
1969 def __init__(self, fp):
1970 self.fp = fp
1971
1972 def write(self, data):
1973 return self.fp.write(data)
1974
1975 def flush(self):
1976 self.fp.flush()
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001977
1978class UnseekableTests(unittest.TestCase):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02001979 def test_writestr(self):
1980 for wrapper in (lambda f: f), Tellable, Unseekable:
1981 with self.subTest(wrapper=wrapper):
1982 f = io.BytesIO()
1983 f.write(b'abc')
1984 bf = io.BufferedWriter(f)
1985 with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) as zipfp:
1986 zipfp.writestr('ones', b'111')
1987 zipfp.writestr('twos', b'222')
1988 self.assertEqual(f.getvalue()[:5], b'abcPK')
1989 with zipfile.ZipFile(f, mode='r') as zipf:
1990 with zipf.open('ones') as zopen:
1991 self.assertEqual(zopen.read(), b'111')
1992 with zipf.open('twos') as zopen:
1993 self.assertEqual(zopen.read(), b'222')
1994
1995 def test_write(self):
1996 for wrapper in (lambda f: f), Tellable, Unseekable:
1997 with self.subTest(wrapper=wrapper):
1998 f = io.BytesIO()
1999 f.write(b'abc')
2000 bf = io.BufferedWriter(f)
2001 with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) as zipfp:
2002 self.addCleanup(unlink, TESTFN)
2003 with open(TESTFN, 'wb') as f2:
2004 f2.write(b'111')
2005 zipfp.write(TESTFN, 'ones')
2006 with open(TESTFN, 'wb') as f2:
2007 f2.write(b'222')
2008 zipfp.write(TESTFN, 'twos')
2009 self.assertEqual(f.getvalue()[:5], b'abcPK')
2010 with zipfile.ZipFile(f, mode='r') as zipf:
2011 with zipf.open('ones') as zopen:
2012 self.assertEqual(zopen.read(), b'111')
2013 with zipf.open('twos') as zopen:
2014 self.assertEqual(zopen.read(), b'222')
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02002015
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03002016 def test_open_write(self):
2017 for wrapper in (lambda f: f), Tellable, Unseekable:
2018 with self.subTest(wrapper=wrapper):
2019 f = io.BytesIO()
2020 f.write(b'abc')
2021 bf = io.BufferedWriter(f)
2022 with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) as zipf:
2023 with zipf.open('ones', 'w') as zopen:
2024 zopen.write(b'111')
2025 with zipf.open('twos', 'w') as zopen:
2026 zopen.write(b'222')
2027 self.assertEqual(f.getvalue()[:5], b'abcPK')
2028 with zipfile.ZipFile(f) as zipf:
2029 self.assertEqual(zipf.read('ones'), b'111')
2030 self.assertEqual(zipf.read('twos'), b'222')
2031
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02002032
Ezio Melotti975077a2011-05-19 22:03:22 +03002033@requires_zlib
Guido van Rossumd8faa362007-04-27 19:54:29 +00002034class TestsWithMultipleOpens(unittest.TestCase):
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02002035 @classmethod
2036 def setUpClass(cls):
2037 cls.data1 = b'111' + getrandbytes(10000)
2038 cls.data2 = b'222' + getrandbytes(10000)
2039
2040 def make_test_archive(self, f):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002041 # Create the ZIP archive
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02002042 with zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as zipfp:
2043 zipfp.writestr('ones', self.data1)
2044 zipfp.writestr('twos', self.data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002045
Ezio Melottiafd0d112009-07-15 17:17:17 +00002046 def test_same_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002047 # Verify that (when the ZipFile is in control of creating file objects)
2048 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02002049 for f in get_files(self):
2050 self.make_test_archive(f)
2051 with zipfile.ZipFile(f, mode="r") as zipf:
2052 with zipf.open('ones') as zopen1, zipf.open('ones') as zopen2:
2053 data1 = zopen1.read(500)
2054 data2 = zopen2.read(500)
2055 data1 += zopen1.read()
2056 data2 += zopen2.read()
2057 self.assertEqual(data1, data2)
2058 self.assertEqual(data1, self.data1)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002059
Ezio Melottiafd0d112009-07-15 17:17:17 +00002060 def test_different_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002061 # Verify that (when the ZipFile is in control of creating file objects)
2062 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02002063 for f in get_files(self):
2064 self.make_test_archive(f)
2065 with zipfile.ZipFile(f, mode="r") as zipf:
2066 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
2067 data1 = zopen1.read(500)
2068 data2 = zopen2.read(500)
2069 data1 += zopen1.read()
2070 data2 += zopen2.read()
2071 self.assertEqual(data1, self.data1)
2072 self.assertEqual(data2, self.data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002073
Ezio Melottiafd0d112009-07-15 17:17:17 +00002074 def test_interleaved(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002075 # Verify that (when the ZipFile is in control of creating file objects)
2076 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02002077 for f in get_files(self):
2078 self.make_test_archive(f)
2079 with zipfile.ZipFile(f, mode="r") as zipf:
Serhiy Storchakad76c7c22016-05-13 21:18:58 +03002080 with zipf.open('ones') as zopen1:
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02002081 data1 = zopen1.read(500)
Serhiy Storchakad76c7c22016-05-13 21:18:58 +03002082 with zipf.open('twos') as zopen2:
2083 data2 = zopen2.read(500)
2084 data1 += zopen1.read()
2085 data2 += zopen2.read()
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02002086 self.assertEqual(data1, self.data1)
2087 self.assertEqual(data2, self.data2)
2088
2089 def test_read_after_close(self):
2090 for f in get_files(self):
2091 self.make_test_archive(f)
2092 with contextlib.ExitStack() as stack:
2093 with zipfile.ZipFile(f, 'r') as zipf:
2094 zopen1 = stack.enter_context(zipf.open('ones'))
2095 zopen2 = stack.enter_context(zipf.open('twos'))
Brian Curtin8fb9b862010-11-18 02:15:28 +00002096 data1 = zopen1.read(500)
2097 data2 = zopen2.read(500)
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02002098 data1 += zopen1.read()
2099 data2 += zopen2.read()
2100 self.assertEqual(data1, self.data1)
2101 self.assertEqual(data2, self.data2)
2102
2103 def test_read_after_write(self):
2104 for f in get_files(self):
2105 with zipfile.ZipFile(f, 'w', zipfile.ZIP_DEFLATED) as zipf:
2106 zipf.writestr('ones', self.data1)
2107 zipf.writestr('twos', self.data2)
2108 with zipf.open('ones') as zopen1:
2109 data1 = zopen1.read(500)
2110 self.assertEqual(data1, self.data1[:500])
2111 with zipfile.ZipFile(f, 'r') as zipf:
2112 data1 = zipf.read('ones')
2113 data2 = zipf.read('twos')
2114 self.assertEqual(data1, self.data1)
2115 self.assertEqual(data2, self.data2)
2116
2117 def test_write_after_read(self):
2118 for f in get_files(self):
2119 with zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as zipf:
2120 zipf.writestr('ones', self.data1)
2121 with zipf.open('ones') as zopen1:
2122 zopen1.read(500)
2123 zipf.writestr('twos', self.data2)
2124 with zipfile.ZipFile(f, 'r') as zipf:
2125 data1 = zipf.read('ones')
2126 data2 = zipf.read('twos')
2127 self.assertEqual(data1, self.data1)
2128 self.assertEqual(data2, self.data2)
2129
2130 def test_many_opens(self):
2131 # Verify that read() and open() promptly close the file descriptor,
2132 # and don't rely on the garbage collector to free resources.
2133 self.make_test_archive(TESTFN2)
2134 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
2135 for x in range(100):
2136 zipf.read('ones')
2137 with zipf.open('ones') as zopen1:
2138 pass
2139 with open(os.devnull) as f:
2140 self.assertLess(f.fileno(), 100)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002141
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03002142 def test_write_while_reading(self):
2143 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_DEFLATED) as zipf:
2144 zipf.writestr('ones', self.data1)
2145 with zipfile.ZipFile(TESTFN2, 'a', zipfile.ZIP_DEFLATED) as zipf:
2146 with zipf.open('ones', 'r') as r1:
2147 data1 = r1.read(500)
2148 with zipf.open('twos', 'w') as w1:
2149 w1.write(self.data2)
2150 data1 += r1.read()
2151 self.assertEqual(data1, self.data1)
2152 with zipfile.ZipFile(TESTFN2) as zipf:
2153 self.assertEqual(zipf.read('twos'), self.data2)
2154
Guido van Rossumd8faa362007-04-27 19:54:29 +00002155 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00002156 unlink(TESTFN2)
2157
Guido van Rossumd8faa362007-04-27 19:54:29 +00002158
Martin v. Löwis59e47792009-01-24 14:10:07 +00002159class TestWithDirectory(unittest.TestCase):
2160 def setUp(self):
2161 os.mkdir(TESTFN2)
2162
Ezio Melottiafd0d112009-07-15 17:17:17 +00002163 def test_extract_dir(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00002164 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
2165 zipf.extractall(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00002166 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
2167 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
2168 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
2169
Ezio Melottiafd0d112009-07-15 17:17:17 +00002170 def test_bug_6050(self):
Martin v. Löwis70ccd162009-05-24 19:47:22 +00002171 # Extraction should succeed if directories already exist
2172 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottiafd0d112009-07-15 17:17:17 +00002173 self.test_extract_dir()
Martin v. Löwis70ccd162009-05-24 19:47:22 +00002174
Serhiy Storchaka46a34922014-09-23 22:40:23 +03002175 def test_write_dir(self):
2176 dirpath = os.path.join(TESTFN2, "x")
2177 os.mkdir(dirpath)
2178 mode = os.stat(dirpath).st_mode & 0xFFFF
2179 with zipfile.ZipFile(TESTFN, "w") as zipf:
2180 zipf.write(dirpath)
2181 zinfo = zipf.filelist[0]
2182 self.assertTrue(zinfo.filename.endswith("/x/"))
2183 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
2184 zipf.write(dirpath, "y")
2185 zinfo = zipf.filelist[1]
2186 self.assertTrue(zinfo.filename, "y/")
2187 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
2188 with zipfile.ZipFile(TESTFN, "r") as zipf:
2189 zinfo = zipf.filelist[0]
2190 self.assertTrue(zinfo.filename.endswith("/x/"))
2191 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
2192 zinfo = zipf.filelist[1]
2193 self.assertTrue(zinfo.filename, "y/")
2194 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
2195 target = os.path.join(TESTFN2, "target")
2196 os.mkdir(target)
2197 zipf.extractall(target)
2198 self.assertTrue(os.path.isdir(os.path.join(target, "y")))
2199 self.assertEqual(len(os.listdir(target)), 2)
2200
2201 def test_writestr_dir(self):
Martin v. Löwis59e47792009-01-24 14:10:07 +00002202 os.mkdir(os.path.join(TESTFN2, "x"))
Serhiy Storchaka46a34922014-09-23 22:40:23 +03002203 with zipfile.ZipFile(TESTFN, "w") as zipf:
2204 zipf.writestr("x/", b'')
2205 zinfo = zipf.filelist[0]
2206 self.assertEqual(zinfo.filename, "x/")
2207 self.assertEqual(zinfo.external_attr, (0o40775 << 16) | 0x10)
2208 with zipfile.ZipFile(TESTFN, "r") as zipf:
2209 zinfo = zipf.filelist[0]
2210 self.assertTrue(zinfo.filename.endswith("x/"))
2211 self.assertEqual(zinfo.external_attr, (0o40775 << 16) | 0x10)
2212 target = os.path.join(TESTFN2, "target")
2213 os.mkdir(target)
2214 zipf.extractall(target)
2215 self.assertTrue(os.path.isdir(os.path.join(target, "x")))
2216 self.assertEqual(os.listdir(target), ["x"])
Martin v. Löwis59e47792009-01-24 14:10:07 +00002217
2218 def tearDown(self):
Victor Stinner57004c62014-09-04 00:49:01 +02002219 rmtree(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00002220 if os.path.exists(TESTFN):
Ezio Melotti76430242009-07-11 18:28:48 +00002221 unlink(TESTFN)
Martin v. Löwis59e47792009-01-24 14:10:07 +00002222
Guido van Rossumd8faa362007-04-27 19:54:29 +00002223
Serhiy Storchaka503f9082016-02-08 00:02:25 +02002224class ZipInfoTests(unittest.TestCase):
2225 def test_from_file(self):
2226 zi = zipfile.ZipInfo.from_file(__file__)
2227 self.assertEqual(posixpath.basename(zi.filename), 'test_zipfile.py')
2228 self.assertFalse(zi.is_dir())
Serhiy Storchaka8606e952017-03-08 14:37:51 +02002229 self.assertEqual(zi.file_size, os.path.getsize(__file__))
2230
2231 def test_from_file_pathlike(self):
2232 zi = zipfile.ZipInfo.from_file(pathlib.Path(__file__))
2233 self.assertEqual(posixpath.basename(zi.filename), 'test_zipfile.py')
2234 self.assertFalse(zi.is_dir())
2235 self.assertEqual(zi.file_size, os.path.getsize(__file__))
2236
2237 def test_from_file_bytes(self):
2238 zi = zipfile.ZipInfo.from_file(os.fsencode(__file__), 'test')
2239 self.assertEqual(posixpath.basename(zi.filename), 'test')
2240 self.assertFalse(zi.is_dir())
2241 self.assertEqual(zi.file_size, os.path.getsize(__file__))
2242
2243 def test_from_file_fileno(self):
2244 with open(__file__, 'rb') as f:
2245 zi = zipfile.ZipInfo.from_file(f.fileno(), 'test')
2246 self.assertEqual(posixpath.basename(zi.filename), 'test')
2247 self.assertFalse(zi.is_dir())
2248 self.assertEqual(zi.file_size, os.path.getsize(__file__))
Serhiy Storchaka503f9082016-02-08 00:02:25 +02002249
2250 def test_from_dir(self):
2251 dirpath = os.path.dirname(os.path.abspath(__file__))
2252 zi = zipfile.ZipInfo.from_file(dirpath, 'stdlib_tests')
2253 self.assertEqual(zi.filename, 'stdlib_tests/')
2254 self.assertTrue(zi.is_dir())
2255 self.assertEqual(zi.compress_type, zipfile.ZIP_STORED)
2256 self.assertEqual(zi.file_size, 0)
2257
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002258
2259class CommandLineTest(unittest.TestCase):
2260
2261 def zipfilecmd(self, *args, **kwargs):
2262 rc, out, err = script_helper.assert_python_ok('-m', 'zipfile', *args,
2263 **kwargs)
2264 return out.replace(os.linesep.encode(), b'\n')
2265
2266 def zipfilecmd_failure(self, *args):
2267 return script_helper.assert_python_failure('-m', 'zipfile', *args)
2268
Serhiy Storchaka150cd192017-04-07 18:56:12 +03002269 def test_bad_use(self):
2270 rc, out, err = self.zipfilecmd_failure()
2271 self.assertEqual(out, b'')
2272 self.assertIn(b'usage', err.lower())
2273 self.assertIn(b'error', err.lower())
2274 self.assertIn(b'required', err.lower())
2275 rc, out, err = self.zipfilecmd_failure('-l', '')
2276 self.assertEqual(out, b'')
2277 self.assertNotEqual(err.strip(), b'')
2278
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002279 def test_test_command(self):
2280 zip_name = findfile('zipdir.zip')
Serhiy Storchaka8c933102016-10-23 13:32:12 +03002281 for opt in '-t', '--test':
2282 out = self.zipfilecmd(opt, zip_name)
2283 self.assertEqual(out.rstrip(), b'Done testing')
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002284 zip_name = findfile('testtar.tar')
2285 rc, out, err = self.zipfilecmd_failure('-t', zip_name)
2286 self.assertEqual(out, b'')
2287
2288 def test_list_command(self):
2289 zip_name = findfile('zipdir.zip')
2290 t = io.StringIO()
2291 with zipfile.ZipFile(zip_name, 'r') as tf:
2292 tf.printdir(t)
2293 expected = t.getvalue().encode('ascii', 'backslashreplace')
Serhiy Storchaka8c933102016-10-23 13:32:12 +03002294 for opt in '-l', '--list':
2295 out = self.zipfilecmd(opt, zip_name,
2296 PYTHONIOENCODING='ascii:backslashreplace')
2297 self.assertEqual(out, expected)
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002298
Serhiy Storchakab4293ef2016-10-23 22:32:30 +03002299 @requires_zlib
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002300 def test_create_command(self):
2301 self.addCleanup(unlink, TESTFN)
2302 with open(TESTFN, 'w') as f:
2303 f.write('test 1')
2304 os.mkdir(TESTFNDIR)
2305 self.addCleanup(rmtree, TESTFNDIR)
2306 with open(os.path.join(TESTFNDIR, 'file.txt'), 'w') as f:
2307 f.write('test 2')
2308 files = [TESTFN, TESTFNDIR]
2309 namelist = [TESTFN, TESTFNDIR + '/', TESTFNDIR + '/file.txt']
Serhiy Storchaka8c933102016-10-23 13:32:12 +03002310 for opt in '-c', '--create':
2311 try:
2312 out = self.zipfilecmd(opt, TESTFN2, *files)
2313 self.assertEqual(out, b'')
2314 with zipfile.ZipFile(TESTFN2) as zf:
2315 self.assertEqual(zf.namelist(), namelist)
2316 self.assertEqual(zf.read(namelist[0]), b'test 1')
2317 self.assertEqual(zf.read(namelist[2]), b'test 2')
2318 finally:
2319 unlink(TESTFN2)
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002320
2321 def test_extract_command(self):
2322 zip_name = findfile('zipdir.zip')
Serhiy Storchaka8c933102016-10-23 13:32:12 +03002323 for opt in '-e', '--extract':
2324 with temp_dir() as extdir:
2325 out = self.zipfilecmd(opt, zip_name, extdir)
2326 self.assertEqual(out, b'')
2327 with zipfile.ZipFile(zip_name) as zf:
2328 for zi in zf.infolist():
2329 path = os.path.join(extdir,
2330 zi.filename.replace('/', os.sep))
2331 if zi.is_dir():
2332 self.assertTrue(os.path.isdir(path))
2333 else:
2334 self.assertTrue(os.path.isfile(path))
2335 with open(path, 'rb') as f:
2336 self.assertEqual(f.read(), zf.read(zi))
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002337
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00002338if __name__ == "__main__":
Brett Cannond5b4e1d2013-06-12 19:57:19 -04002339 unittest.main()