blob: ac8f64ce22f6bfb77f18dcce281f8ca7e1a12bf7 [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
Miss Islington (bot)4724ba92019-03-30 06:52:16 -0700405 def test_writing_errors(self):
406 class BrokenFile(io.BytesIO):
407 def write(self, data):
408 nonlocal count
409 if count is not None:
410 if count == stop:
411 raise OSError
412 count += 1
413 super().write(data)
414
415 stop = 0
416 while True:
417 testfile = BrokenFile()
418 count = None
419 with zipfile.ZipFile(testfile, 'w', self.compression) as zipfp:
420 with zipfp.open('file1', 'w') as f:
421 f.write(b'data1')
422 count = 0
423 try:
424 with zipfp.open('file2', 'w') as f:
425 f.write(b'data2')
426 except OSError:
427 stop += 1
428 else:
429 break
430 finally:
431 count = None
432 with zipfile.ZipFile(io.BytesIO(testfile.getvalue())) as zipfp:
433 self.assertEqual(zipfp.namelist(), ['file1'])
434 self.assertEqual(zipfp.read('file1'), b'data1')
435
436 with zipfile.ZipFile(io.BytesIO(testfile.getvalue())) as zipfp:
437 self.assertEqual(zipfp.namelist(), ['file1', 'file2'])
438 self.assertEqual(zipfp.read('file1'), b'data1')
439 self.assertEqual(zipfp.read('file2'), b'data2')
440
441
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300442 def tearDown(self):
443 unlink(TESTFN)
444 unlink(TESTFN2)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200445
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200446
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300447class StoredTestsWithSourceFile(AbstractTestsWithSourceFile,
448 unittest.TestCase):
449 compression = zipfile.ZIP_STORED
450 test_low_compression = None
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200451
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300452 def zip_test_writestr_permissions(self, f, compression):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300453 # Make sure that writestr and open(... mode='w') create files with
454 # mode 0600, when they are passed a name rather than a ZipInfo
455 # instance.
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200456
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300457 self.make_test_archive(f, compression)
458 with zipfile.ZipFile(f, "r") as zipfp:
459 zinfo = zipfp.getinfo('strfile')
460 self.assertEqual(zinfo.external_attr, 0o600 << 16)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200461
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300462 zinfo2 = zipfp.getinfo('written-open-w')
463 self.assertEqual(zinfo2.external_attr, 0o600 << 16)
464
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300465 def test_writestr_permissions(self):
466 for f in get_files(self):
467 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +0200468
Ezio Melottiafd0d112009-07-15 17:17:17 +0000469 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000470 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
471 zipfp.write(TESTFN, "/absolute")
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000472
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000473 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
474 self.assertEqual(zipfp.namelist(), ["absolute"])
Tim Peters32cbc962006-02-20 21:42:18 +0000475
Ezio Melottiafd0d112009-07-15 17:17:17 +0000476 def test_append_to_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000477 """Test appending to an existing zipfile."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000478 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
479 zipfp.write(TESTFN, TESTFN)
480
481 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
482 zipfp.writestr("strfile", self.data)
483 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000484
Ezio Melottiafd0d112009-07-15 17:17:17 +0000485 def test_append_to_non_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000486 """Test appending to an existing file that is not a zipfile."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000487 # NOTE: this test fails if len(d) < 22 because of the first
488 # line "fpin.seek(-22, 2)" in _EndRecData
Ezio Melotti35386712009-12-31 13:22:41 +0000489 data = b'I am not a ZipFile!'*10
490 with open(TESTFN2, 'wb') as f:
491 f.write(data)
492
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000493 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
494 zipfp.write(TESTFN, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000495
Ezio Melotti35386712009-12-31 13:22:41 +0000496 with open(TESTFN2, 'rb') as f:
497 f.seek(len(data))
498 with zipfile.ZipFile(f, "r") as zipfp:
499 self.assertEqual(zipfp.namelist(), [TESTFN])
Serhiy Storchaka8793b212016-10-07 22:20:50 +0300500 self.assertEqual(zipfp.read(TESTFN), self.data)
501 with open(TESTFN2, 'rb') as f:
502 self.assertEqual(f.read(len(data)), data)
503 zipfiledata = f.read()
504 with io.BytesIO(zipfiledata) as bio, zipfile.ZipFile(bio) as zipfp:
505 self.assertEqual(zipfp.namelist(), [TESTFN])
506 self.assertEqual(zipfp.read(TESTFN), self.data)
507
508 def test_read_concatenated_zip_file(self):
509 with io.BytesIO() as bio:
510 with zipfile.ZipFile(bio, 'w', zipfile.ZIP_STORED) as zipfp:
511 zipfp.write(TESTFN, TESTFN)
512 zipfiledata = bio.getvalue()
513 data = b'I am not a ZipFile!'*10
514 with open(TESTFN2, 'wb') as f:
515 f.write(data)
516 f.write(zipfiledata)
517
518 with zipfile.ZipFile(TESTFN2) as zipfp:
519 self.assertEqual(zipfp.namelist(), [TESTFN])
520 self.assertEqual(zipfp.read(TESTFN), self.data)
521
522 def test_append_to_concatenated_zip_file(self):
523 with io.BytesIO() as bio:
524 with zipfile.ZipFile(bio, 'w', zipfile.ZIP_STORED) as zipfp:
525 zipfp.write(TESTFN, TESTFN)
526 zipfiledata = bio.getvalue()
527 data = b'I am not a ZipFile!'*1000000
528 with open(TESTFN2, 'wb') as f:
529 f.write(data)
530 f.write(zipfiledata)
531
532 with zipfile.ZipFile(TESTFN2, 'a') as zipfp:
533 self.assertEqual(zipfp.namelist(), [TESTFN])
534 zipfp.writestr('strfile', self.data)
535
536 with open(TESTFN2, 'rb') as f:
537 self.assertEqual(f.read(len(data)), data)
538 zipfiledata = f.read()
539 with io.BytesIO(zipfiledata) as bio, zipfile.ZipFile(bio) as zipfp:
540 self.assertEqual(zipfp.namelist(), [TESTFN, 'strfile'])
541 self.assertEqual(zipfp.read(TESTFN), self.data)
542 self.assertEqual(zipfp.read('strfile'), self.data)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000543
R David Murray4fbb9db2011-06-09 15:50:51 -0400544 def test_ignores_newline_at_end(self):
545 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
546 zipfp.write(TESTFN, TESTFN)
547 with open(TESTFN2, 'a') as f:
548 f.write("\r\n\00\00\00")
549 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
550 self.assertIsInstance(zipfp, zipfile.ZipFile)
551
552 def test_ignores_stuff_appended_past_comments(self):
553 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
554 zipfp.comment = b"this is a comment"
555 zipfp.write(TESTFN, TESTFN)
556 with open(TESTFN2, 'a') as f:
557 f.write("abcdef\r\n")
558 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
559 self.assertIsInstance(zipfp, zipfile.ZipFile)
560 self.assertEqual(zipfp.comment, b"this is a comment")
561
Ezio Melottiafd0d112009-07-15 17:17:17 +0000562 def test_write_default_name(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000563 """Check that calling ZipFile.write without arcname specified
564 produces the expected result."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000565 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
566 zipfp.write(TESTFN)
Brian Curtin8fb9b862010-11-18 02:15:28 +0000567 with open(TESTFN, "rb") as f:
568 self.assertEqual(zipfp.read(TESTFN), f.read())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000569
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300570 def test_write_to_readonly(self):
571 """Check that trying to call write() on a readonly ZipFile object
Serhiy Storchakab0d497c2016-09-10 21:28:07 +0300572 raises a ValueError."""
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300573 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
574 zipfp.writestr("somefile.txt", "bogus")
575
576 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
Serhiy Storchakab0d497c2016-09-10 21:28:07 +0300577 self.assertRaises(ValueError, zipfp.write, TESTFN)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300578
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300579 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
Serhiy Storchakab0d497c2016-09-10 21:28:07 +0300580 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300581 zipfp.open(TESTFN, mode='w')
582
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300583 def test_add_file_before_1980(self):
584 # Set atime and mtime to 1970-01-01
585 os.utime(TESTFN, (0, 0))
586 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
587 self.assertRaises(ValueError, zipfp.write, TESTFN)
588
Serhiy Storchaka5ce3f102014-01-09 14:50:20 +0200589
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300590@requires_zlib
591class DeflateTestsWithSourceFile(AbstractTestsWithSourceFile,
592 unittest.TestCase):
593 compression = zipfile.ZIP_DEFLATED
594
Ezio Melottiafd0d112009-07-15 17:17:17 +0000595 def test_per_file_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000596 """Check that files within a Zip archive can have different
597 compression options."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000598 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
599 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
600 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
601 sinfo = zipfp.getinfo('storeme')
602 dinfo = zipfp.getinfo('deflateme')
603 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
604 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000605
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300606@requires_bz2
607class Bzip2TestsWithSourceFile(AbstractTestsWithSourceFile,
608 unittest.TestCase):
609 compression = zipfile.ZIP_BZIP2
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000610
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300611@requires_lzma
612class LzmaTestsWithSourceFile(AbstractTestsWithSourceFile,
613 unittest.TestCase):
614 compression = zipfile.ZIP_LZMA
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000615
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300616
617class AbstractTestZip64InSmallFiles:
618 # These tests test the ZIP64 functionality without using large files,
619 # see test_zipfile64 for proper tests.
620
621 @classmethod
622 def setUpClass(cls):
623 line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
624 for i in range(0, FIXEDTEST_SIZE))
625 cls.data = b'\n'.join(line_gen)
626
627 def setUp(self):
628 self._limit = zipfile.ZIP64_LIMIT
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300629 self._filecount_limit = zipfile.ZIP_FILECOUNT_LIMIT
630 zipfile.ZIP64_LIMIT = 1000
631 zipfile.ZIP_FILECOUNT_LIMIT = 9
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300632
633 # Make a source file with some lines
634 with open(TESTFN, "wb") as fp:
635 fp.write(self.data)
636
637 def zip_test(self, f, compression):
638 # Create the ZIP archive
639 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
640 zipfp.write(TESTFN, "another.name")
641 zipfp.write(TESTFN, TESTFN)
642 zipfp.writestr("strfile", self.data)
643
644 # Read the ZIP archive
645 with zipfile.ZipFile(f, "r", compression) as zipfp:
646 self.assertEqual(zipfp.read(TESTFN), self.data)
647 self.assertEqual(zipfp.read("another.name"), self.data)
648 self.assertEqual(zipfp.read("strfile"), self.data)
649
650 # Print the ZIP directory
651 fp = io.StringIO()
652 zipfp.printdir(fp)
653
654 directory = fp.getvalue()
655 lines = directory.splitlines()
656 self.assertEqual(len(lines), 4) # Number of files + header
657
658 self.assertIn('File Name', lines[0])
659 self.assertIn('Modified', lines[0])
660 self.assertIn('Size', lines[0])
661
662 fn, date, time_, size = lines[1].split()
663 self.assertEqual(fn, 'another.name')
664 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
665 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
666 self.assertEqual(size, str(len(self.data)))
667
668 # Check the namelist
669 names = zipfp.namelist()
670 self.assertEqual(len(names), 3)
671 self.assertIn(TESTFN, names)
672 self.assertIn("another.name", names)
673 self.assertIn("strfile", names)
674
675 # Check infolist
676 infos = zipfp.infolist()
677 names = [i.filename for i in infos]
678 self.assertEqual(len(names), 3)
679 self.assertIn(TESTFN, names)
680 self.assertIn("another.name", names)
681 self.assertIn("strfile", names)
682 for i in infos:
683 self.assertEqual(i.file_size, len(self.data))
684
685 # check getinfo
686 for nm in (TESTFN, "another.name", "strfile"):
687 info = zipfp.getinfo(nm)
688 self.assertEqual(info.filename, nm)
689 self.assertEqual(info.file_size, len(self.data))
690
691 # Check that testzip doesn't raise an exception
692 zipfp.testzip()
693
694 def test_basic(self):
695 for f in get_files(self):
696 self.zip_test(f, self.compression)
697
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300698 def test_too_many_files(self):
699 # This test checks that more than 64k files can be added to an archive,
700 # and that the resulting archive can be read properly by ZipFile
701 zipf = zipfile.ZipFile(TESTFN, "w", self.compression,
702 allowZip64=True)
703 zipf.debug = 100
704 numfiles = 15
705 for i in range(numfiles):
706 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
707 self.assertEqual(len(zipf.namelist()), numfiles)
708 zipf.close()
709
710 zipf2 = zipfile.ZipFile(TESTFN, "r", self.compression)
711 self.assertEqual(len(zipf2.namelist()), numfiles)
712 for i in range(numfiles):
713 content = zipf2.read("foo%08d" % i).decode('ascii')
714 self.assertEqual(content, "%d" % (i**3 % 57))
715 zipf2.close()
716
717 def test_too_many_files_append(self):
718 zipf = zipfile.ZipFile(TESTFN, "w", self.compression,
719 allowZip64=False)
720 zipf.debug = 100
721 numfiles = 9
722 for i in range(numfiles):
723 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
724 self.assertEqual(len(zipf.namelist()), numfiles)
725 with self.assertRaises(zipfile.LargeZipFile):
726 zipf.writestr("foo%08d" % numfiles, b'')
727 self.assertEqual(len(zipf.namelist()), numfiles)
728 zipf.close()
729
730 zipf = zipfile.ZipFile(TESTFN, "a", self.compression,
731 allowZip64=False)
732 zipf.debug = 100
733 self.assertEqual(len(zipf.namelist()), numfiles)
734 with self.assertRaises(zipfile.LargeZipFile):
735 zipf.writestr("foo%08d" % numfiles, b'')
736 self.assertEqual(len(zipf.namelist()), numfiles)
737 zipf.close()
738
739 zipf = zipfile.ZipFile(TESTFN, "a", self.compression,
740 allowZip64=True)
741 zipf.debug = 100
742 self.assertEqual(len(zipf.namelist()), numfiles)
743 numfiles2 = 15
744 for i in range(numfiles, numfiles2):
745 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
746 self.assertEqual(len(zipf.namelist()), numfiles2)
747 zipf.close()
748
749 zipf2 = zipfile.ZipFile(TESTFN, "r", self.compression)
750 self.assertEqual(len(zipf2.namelist()), numfiles2)
751 for i in range(numfiles2):
752 content = zipf2.read("foo%08d" % i).decode('ascii')
753 self.assertEqual(content, "%d" % (i**3 % 57))
754 zipf2.close()
755
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300756 def tearDown(self):
757 zipfile.ZIP64_LIMIT = self._limit
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300758 zipfile.ZIP_FILECOUNT_LIMIT = self._filecount_limit
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300759 unlink(TESTFN)
760 unlink(TESTFN2)
761
762
763class StoredTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
764 unittest.TestCase):
765 compression = zipfile.ZIP_STORED
766
767 def large_file_exception_test(self, f, compression):
Serhiy Storchaka235c5e02013-11-23 15:55:38 +0200768 with zipfile.ZipFile(f, "w", compression, allowZip64=False) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300769 self.assertRaises(zipfile.LargeZipFile,
770 zipfp.write, TESTFN, "another.name")
771
772 def large_file_exception_test2(self, f, compression):
Serhiy Storchaka235c5e02013-11-23 15:55:38 +0200773 with zipfile.ZipFile(f, "w", compression, allowZip64=False) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300774 self.assertRaises(zipfile.LargeZipFile,
775 zipfp.writestr, "another.name", self.data)
776
777 def test_large_file_exception(self):
778 for f in get_files(self):
779 self.large_file_exception_test(f, zipfile.ZIP_STORED)
780 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
781
782 def test_absolute_arcnames(self):
783 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
784 allowZip64=True) as zipfp:
785 zipfp.write(TESTFN, "/absolute")
786
787 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
788 self.assertEqual(zipfp.namelist(), ["absolute"])
789
Miss Islington (bot)efdf3162018-09-17 06:08:45 -0700790 def test_append(self):
791 # Test that appending to the Zip64 archive doesn't change
792 # extra fields of existing entries.
793 with zipfile.ZipFile(TESTFN2, "w", allowZip64=True) as zipfp:
794 zipfp.writestr("strfile", self.data)
795 with zipfile.ZipFile(TESTFN2, "r", allowZip64=True) as zipfp:
796 zinfo = zipfp.getinfo("strfile")
797 extra = zinfo.extra
798 with zipfile.ZipFile(TESTFN2, "a", allowZip64=True) as zipfp:
799 zipfp.writestr("strfile2", self.data)
800 with zipfile.ZipFile(TESTFN2, "r", allowZip64=True) as zipfp:
801 zinfo = zipfp.getinfo("strfile")
802 self.assertEqual(zinfo.extra, extra)
803
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300804@requires_zlib
805class DeflateTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
806 unittest.TestCase):
807 compression = zipfile.ZIP_DEFLATED
808
809@requires_bz2
810class Bzip2TestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
811 unittest.TestCase):
812 compression = zipfile.ZIP_BZIP2
813
814@requires_lzma
815class LzmaTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
816 unittest.TestCase):
817 compression = zipfile.ZIP_LZMA
818
819
Serhiy Storchaka4c0d9ea2017-04-12 16:03:23 +0300820class AbstractWriterTests:
821
822 def tearDown(self):
823 unlink(TESTFN2)
824
825 def test_close_after_close(self):
826 data = b'content'
827 with zipfile.ZipFile(TESTFN2, "w", self.compression) as zipf:
828 w = zipf.open('test', 'w')
829 w.write(data)
830 w.close()
831 self.assertTrue(w.closed)
832 w.close()
833 self.assertTrue(w.closed)
834 self.assertEqual(zipf.read('test'), data)
835
836 def test_write_after_close(self):
837 data = b'content'
838 with zipfile.ZipFile(TESTFN2, "w", self.compression) as zipf:
839 w = zipf.open('test', 'w')
840 w.write(data)
841 w.close()
842 self.assertTrue(w.closed)
843 self.assertRaises(ValueError, w.write, b'')
844 self.assertEqual(zipf.read('test'), data)
845
846class StoredWriterTests(AbstractWriterTests, unittest.TestCase):
847 compression = zipfile.ZIP_STORED
848
849@requires_zlib
850class DeflateWriterTests(AbstractWriterTests, unittest.TestCase):
851 compression = zipfile.ZIP_DEFLATED
852
853@requires_bz2
854class Bzip2WriterTests(AbstractWriterTests, unittest.TestCase):
855 compression = zipfile.ZIP_BZIP2
856
857@requires_lzma
858class LzmaWriterTests(AbstractWriterTests, unittest.TestCase):
859 compression = zipfile.ZIP_LZMA
860
861
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300862class PyZipFileTests(unittest.TestCase):
863 def assertCompiledIn(self, name, namelist):
864 if name + 'o' not in namelist:
865 self.assertIn(name + 'c', namelist)
866
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200867 def requiresWriteAccess(self, path):
Berker Peksage1efc072015-02-16 04:36:18 +0200868 # effective_ids unavailable on windows
869 if not os.access(path, os.W_OK,
870 effective_ids=os.access in os.supports_effective_ids):
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200871 self.skipTest('requires write access to the installed location')
Serhiy Storchakad86a6ef2015-09-19 10:55:20 +0300872 filename = os.path.join(path, 'test_zipfile.try')
873 try:
874 fd = os.open(filename, os.O_WRONLY | os.O_CREAT)
875 os.close(fd)
876 except Exception:
877 self.skipTest('requires write access to the installed location')
878 unlink(filename)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200879
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300880 def test_write_pyfile(self):
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200881 self.requiresWriteAccess(os.path.dirname(__file__))
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300882 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
883 fn = __file__
Brett Cannonf299abd2015-04-13 14:21:02 -0400884 if fn.endswith('.pyc'):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300885 path_split = fn.split(os.sep)
886 if os.altsep is not None:
887 path_split.extend(fn.split(os.altsep))
888 if '__pycache__' in path_split:
Serhiy Storchaka9068e4d2013-07-22 21:02:14 +0300889 fn = importlib.util.source_from_cache(fn)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300890 else:
891 fn = fn[:-1]
892
893 zipfp.writepy(fn)
894
895 bn = os.path.basename(fn)
896 self.assertNotIn(bn, zipfp.namelist())
897 self.assertCompiledIn(bn, zipfp.namelist())
898
899 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
900 fn = __file__
Brett Cannonf299abd2015-04-13 14:21:02 -0400901 if fn.endswith('.pyc'):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300902 fn = fn[:-1]
903
904 zipfp.writepy(fn, "testpackage")
905
906 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
907 self.assertNotIn(bn, zipfp.namelist())
908 self.assertCompiledIn(bn, zipfp.namelist())
909
910 def test_write_python_package(self):
911 import email
912 packagedir = os.path.dirname(email.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200913 self.requiresWriteAccess(packagedir)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300914
915 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
916 zipfp.writepy(packagedir)
917
918 # Check for a couple of modules at different levels of the
919 # hierarchy
920 names = zipfp.namelist()
921 self.assertCompiledIn('email/__init__.py', names)
922 self.assertCompiledIn('email/mime/text.py', names)
923
Christian Tismer59202e52013-10-21 03:59:23 +0200924 def test_write_filtered_python_package(self):
925 import test
926 packagedir = os.path.dirname(test.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200927 self.requiresWriteAccess(packagedir)
Christian Tismer59202e52013-10-21 03:59:23 +0200928
929 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
930
Christian Tismer59202e52013-10-21 03:59:23 +0200931 # first make sure that the test folder gives error messages
Georg Brandla6065422013-10-21 08:29:29 +0200932 # (on the badsyntax_... files)
933 with captured_stdout() as reportSIO:
934 zipfp.writepy(packagedir)
Christian Tismer59202e52013-10-21 03:59:23 +0200935 reportStr = reportSIO.getvalue()
936 self.assertTrue('SyntaxError' in reportStr)
937
Christian Tismer410d9312013-10-22 04:09:28 +0200938 # then check that the filter works on the whole package
Georg Brandla6065422013-10-21 08:29:29 +0200939 with captured_stdout() as reportSIO:
940 zipfp.writepy(packagedir, filterfunc=lambda whatever: False)
Christian Tismer59202e52013-10-21 03:59:23 +0200941 reportStr = reportSIO.getvalue()
942 self.assertTrue('SyntaxError' not in reportStr)
943
Christian Tismer410d9312013-10-22 04:09:28 +0200944 # then check that the filter works on individual files
Larry Hastings7e63b362015-05-08 06:54:58 -0700945 def filter(path):
946 return not os.path.basename(path).startswith("bad")
Serhiy Storchakac46d1fa2014-01-20 21:59:33 +0200947 with captured_stdout() as reportSIO, self.assertWarns(UserWarning):
Larry Hastings7e63b362015-05-08 06:54:58 -0700948 zipfp.writepy(packagedir, filterfunc=filter)
Christian Tismer410d9312013-10-22 04:09:28 +0200949 reportStr = reportSIO.getvalue()
950 if reportStr:
951 print(reportStr)
952 self.assertTrue('SyntaxError' not in reportStr)
953
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300954 def test_write_with_optimization(self):
955 import email
956 packagedir = os.path.dirname(email.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200957 self.requiresWriteAccess(packagedir)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300958 optlevel = 1 if __debug__ else 0
Brett Cannonf299abd2015-04-13 14:21:02 -0400959 ext = '.pyc'
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300960
961 with TemporaryFile() as t, \
Christian Tismer59202e52013-10-21 03:59:23 +0200962 zipfile.PyZipFile(t, "w", optimize=optlevel) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300963 zipfp.writepy(packagedir)
964
965 names = zipfp.namelist()
966 self.assertIn('email/__init__' + ext, names)
967 self.assertIn('email/mime/text' + ext, names)
968
969 def test_write_python_directory(self):
970 os.mkdir(TESTFN2)
971 try:
972 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
973 fp.write("print(42)\n")
974
975 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
976 fp.write("print(42 * 42)\n")
977
978 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
979 fp.write("bla bla bla\n")
980
981 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
982 zipfp.writepy(TESTFN2)
983
984 names = zipfp.namelist()
985 self.assertCompiledIn('mod1.py', names)
986 self.assertCompiledIn('mod2.py', names)
987 self.assertNotIn('mod2.txt', names)
988
989 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200990 rmtree(TESTFN2)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300991
Christian Tismer410d9312013-10-22 04:09:28 +0200992 def test_write_python_directory_filtered(self):
993 os.mkdir(TESTFN2)
994 try:
995 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
996 fp.write("print(42)\n")
997
998 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
999 fp.write("print(42 * 42)\n")
1000
1001 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
1002 zipfp.writepy(TESTFN2, filterfunc=lambda fn:
1003 not fn.endswith('mod2.py'))
1004
1005 names = zipfp.namelist()
1006 self.assertCompiledIn('mod1.py', names)
1007 self.assertNotIn('mod2.py', names)
1008
1009 finally:
Victor Stinner57004c62014-09-04 00:49:01 +02001010 rmtree(TESTFN2)
Christian Tismer410d9312013-10-22 04:09:28 +02001011
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001012 def test_write_non_pyfile(self):
1013 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
1014 with open(TESTFN, 'w') as f:
1015 f.write('most definitely not a python file')
1016 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
Victor Stinner88b215e2014-09-04 00:51:09 +02001017 unlink(TESTFN)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001018
1019 def test_write_pyfile_bad_syntax(self):
1020 os.mkdir(TESTFN2)
1021 try:
1022 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
1023 fp.write("Bad syntax in python file\n")
1024
1025 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
1026 # syntax errors are printed to stdout
1027 with captured_stdout() as s:
1028 zipfp.writepy(os.path.join(TESTFN2, "mod1.py"))
1029
1030 self.assertIn("SyntaxError", s.getvalue())
1031
1032 # as it will not have compiled the python file, it will
Brett Cannonf299abd2015-04-13 14:21:02 -04001033 # include the .py file not .pyc
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001034 names = zipfp.namelist()
1035 self.assertIn('mod1.py', names)
1036 self.assertNotIn('mod1.pyc', names)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001037
1038 finally:
Victor Stinner57004c62014-09-04 00:49:01 +02001039 rmtree(TESTFN2)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001040
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001041 def test_write_pathlike(self):
1042 os.mkdir(TESTFN2)
1043 try:
1044 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
1045 fp.write("print(42)\n")
1046
1047 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
1048 zipfp.writepy(pathlib.Path(TESTFN2) / "mod1.py")
1049 names = zipfp.namelist()
1050 self.assertCompiledIn('mod1.py', names)
1051 finally:
1052 rmtree(TESTFN2)
1053
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001054
1055class ExtractTests(unittest.TestCase):
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001056
1057 def make_test_file(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001058 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
1059 for fpath, fdata in SMALL_TEST_DATA:
1060 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +00001061
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001062 def test_extract(self):
1063 with temp_cwd():
1064 self.make_test_file()
1065 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1066 for fpath, fdata in SMALL_TEST_DATA:
1067 writtenfile = zipfp.extract(fpath)
1068
1069 # make sure it was written to the right place
1070 correctfile = os.path.join(os.getcwd(), fpath)
1071 correctfile = os.path.normpath(correctfile)
1072
1073 self.assertEqual(writtenfile, correctfile)
1074
1075 # make sure correct data is in correct file
1076 with open(writtenfile, "rb") as f:
1077 self.assertEqual(fdata.encode(), f.read())
1078
1079 unlink(writtenfile)
1080
1081 def _test_extract_with_target(self, target):
1082 self.make_test_file()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001083 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1084 for fpath, fdata in SMALL_TEST_DATA:
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001085 writtenfile = zipfp.extract(fpath, target)
Christian Heimes790c8232008-01-07 21:14:23 +00001086
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001087 # make sure it was written to the right place
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001088 correctfile = os.path.join(target, fpath)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001089 correctfile = os.path.normpath(correctfile)
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001090 self.assertTrue(os.path.samefile(writtenfile, correctfile), (writtenfile, target))
Christian Heimes790c8232008-01-07 21:14:23 +00001091
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001092 # make sure correct data is in correct file
Brian Curtin8fb9b862010-11-18 02:15:28 +00001093 with open(writtenfile, "rb") as f:
1094 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +00001095
Victor Stinner88b215e2014-09-04 00:51:09 +02001096 unlink(writtenfile)
Christian Heimes790c8232008-01-07 21:14:23 +00001097
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001098 unlink(TESTFN2)
1099
1100 def test_extract_with_target(self):
1101 with temp_dir() as extdir:
1102 self._test_extract_with_target(extdir)
1103
1104 def test_extract_with_target_pathlike(self):
1105 with temp_dir() as extdir:
1106 self._test_extract_with_target(pathlib.Path(extdir))
Christian Heimes790c8232008-01-07 21:14:23 +00001107
Ezio Melottiafd0d112009-07-15 17:17:17 +00001108 def test_extract_all(self):
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001109 with temp_cwd():
1110 self.make_test_file()
1111 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1112 zipfp.extractall()
1113 for fpath, fdata in SMALL_TEST_DATA:
1114 outfile = os.path.join(os.getcwd(), fpath)
Christian Heimes790c8232008-01-07 21:14:23 +00001115
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001116 with open(outfile, "rb") as f:
1117 self.assertEqual(fdata.encode(), f.read())
1118
1119 unlink(outfile)
1120
1121 def _test_extract_all_with_target(self, target):
1122 self.make_test_file()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001123 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001124 zipfp.extractall(target)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001125 for fpath, fdata in SMALL_TEST_DATA:
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001126 outfile = os.path.join(target, fpath)
Christian Heimes790c8232008-01-07 21:14:23 +00001127
Brian Curtin8fb9b862010-11-18 02:15:28 +00001128 with open(outfile, "rb") as f:
1129 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +00001130
Victor Stinner88b215e2014-09-04 00:51:09 +02001131 unlink(outfile)
Christian Heimes790c8232008-01-07 21:14:23 +00001132
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001133 unlink(TESTFN2)
1134
1135 def test_extract_all_with_target(self):
1136 with temp_dir() as extdir:
1137 self._test_extract_all_with_target(extdir)
1138
1139 def test_extract_all_with_target_pathlike(self):
1140 with temp_dir() as extdir:
1141 self._test_extract_all_with_target(pathlib.Path(extdir))
Christian Heimes790c8232008-01-07 21:14:23 +00001142
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001143 def check_file(self, filename, content):
1144 self.assertTrue(os.path.isfile(filename))
1145 with open(filename, 'rb') as f:
1146 self.assertEqual(f.read(), content)
1147
Gregory P. Smith09aa7522013-02-03 00:36:32 -08001148 def test_sanitize_windows_name(self):
1149 san = zipfile.ZipFile._sanitize_windows_name
1150 # Passing pathsep in allows this test to work regardless of platform.
1151 self.assertEqual(san(r',,?,C:,foo,bar/z', ','), r'_,C_,foo,bar/z')
1152 self.assertEqual(san(r'a\b,c<d>e|f"g?h*i', ','), r'a\b,c_d_e_f_g_h_i')
1153 self.assertEqual(san('../../foo../../ba..r', '/'), r'foo/ba..r')
1154
1155 def test_extract_hackers_arcnames_common_cases(self):
1156 common_hacknames = [
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001157 ('../foo/bar', 'foo/bar'),
1158 ('foo/../bar', 'foo/bar'),
1159 ('foo/../../bar', 'foo/bar'),
1160 ('foo/bar/..', 'foo/bar'),
1161 ('./../foo/bar', 'foo/bar'),
1162 ('/foo/bar', 'foo/bar'),
1163 ('/foo/../bar', 'foo/bar'),
1164 ('/foo/../../bar', 'foo/bar'),
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001165 ]
Gregory P. Smith09aa7522013-02-03 00:36:32 -08001166 self._test_extract_hackers_arcnames(common_hacknames)
1167
1168 @unittest.skipIf(os.path.sep != '\\', 'Requires \\ as path separator.')
1169 def test_extract_hackers_arcnames_windows_only(self):
1170 """Test combination of path fixing and windows name sanitization."""
1171 windows_hacknames = [
Christian Tismer59202e52013-10-21 03:59:23 +02001172 (r'..\foo\bar', 'foo/bar'),
1173 (r'..\/foo\/bar', 'foo/bar'),
1174 (r'foo/\..\/bar', 'foo/bar'),
1175 (r'foo\/../\bar', 'foo/bar'),
1176 (r'C:foo/bar', 'foo/bar'),
1177 (r'C:/foo/bar', 'foo/bar'),
1178 (r'C://foo/bar', 'foo/bar'),
1179 (r'C:\foo\bar', 'foo/bar'),
1180 (r'//conky/mountpoint/foo/bar', 'foo/bar'),
1181 (r'\\conky\mountpoint\foo\bar', 'foo/bar'),
1182 (r'///conky/mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
1183 (r'\\\conky\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
1184 (r'//conky//mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
1185 (r'\\conky\\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
1186 (r'//?/C:/foo/bar', 'foo/bar'),
1187 (r'\\?\C:\foo\bar', 'foo/bar'),
1188 (r'C:/../C:/foo/bar', 'C_/foo/bar'),
1189 (r'a:b\c<d>e|f"g?h*i', 'b/c_d_e_f_g_h_i'),
1190 ('../../foo../../ba..r', 'foo/ba..r'),
Gregory P. Smith09aa7522013-02-03 00:36:32 -08001191 ]
1192 self._test_extract_hackers_arcnames(windows_hacknames)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001193
Gregory P. Smith09aa7522013-02-03 00:36:32 -08001194 @unittest.skipIf(os.path.sep != '/', r'Requires / as path separator.')
1195 def test_extract_hackers_arcnames_posix_only(self):
1196 posix_hacknames = [
1197 ('//foo/bar', 'foo/bar'),
1198 ('../../foo../../ba..r', 'foo../ba..r'),
1199 (r'foo/..\bar', r'foo/..\bar'),
1200 ]
1201 self._test_extract_hackers_arcnames(posix_hacknames)
1202
1203 def _test_extract_hackers_arcnames(self, hacknames):
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001204 for arcname, fixedname in hacknames:
1205 content = b'foobar' + arcname.encode()
1206 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipfp:
Serhiy Storchakae5e64442013-02-02 19:50:59 +02001207 zinfo = zipfile.ZipInfo()
1208 # preserve backslashes
1209 zinfo.filename = arcname
1210 zinfo.external_attr = 0o600 << 16
1211 zipfp.writestr(zinfo, content)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001212
Serhiy Storchakae5e64442013-02-02 19:50:59 +02001213 arcname = arcname.replace(os.sep, "/")
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001214 targetpath = os.path.join('target', 'subdir', 'subsub')
1215 correctfile = os.path.join(targetpath, *fixedname.split('/'))
1216
1217 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1218 writtenfile = zipfp.extract(arcname, targetpath)
Serhiy Storchakae5e64442013-02-02 19:50:59 +02001219 self.assertEqual(writtenfile, correctfile,
Gregory P. Smith09aa7522013-02-03 00:36:32 -08001220 msg='extract %r: %r != %r' %
1221 (arcname, writtenfile, correctfile))
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001222 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001223 rmtree('target')
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001224
1225 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1226 zipfp.extractall(targetpath)
1227 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001228 rmtree('target')
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001229
1230 correctfile = os.path.join(os.getcwd(), *fixedname.split('/'))
1231
1232 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1233 writtenfile = zipfp.extract(arcname)
Serhiy Storchakae5e64442013-02-02 19:50:59 +02001234 self.assertEqual(writtenfile, correctfile,
1235 msg="extract %r" % arcname)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001236 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001237 rmtree(fixedname.split('/')[0])
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001238
1239 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1240 zipfp.extractall()
1241 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001242 rmtree(fixedname.split('/')[0])
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001243
Victor Stinner88b215e2014-09-04 00:51:09 +02001244 unlink(TESTFN2)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001245
Ronald Oussorenee5c8852010-02-07 20:24:02 +00001246
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001247class OtherTests(unittest.TestCase):
1248 def test_open_via_zip_info(self):
1249 # Create the ZIP archive
1250 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
1251 zipfp.writestr("name", "foo")
Serhiy Storchaka9b7a1a12014-01-20 21:57:40 +02001252 with self.assertWarns(UserWarning):
1253 zipfp.writestr("name", "bar")
1254 self.assertEqual(zipfp.namelist(), ["name"] * 2)
Ronald Oussorenee5c8852010-02-07 20:24:02 +00001255
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001256 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1257 infos = zipfp.infolist()
1258 data = b""
1259 for info in infos:
1260 with zipfp.open(info) as zipopen:
1261 data += zipopen.read()
1262 self.assertIn(data, {b"foobar", b"barfoo"})
1263 data = b""
1264 for info in infos:
1265 data += zipfp.read(info)
1266 self.assertIn(data, {b"foobar", b"barfoo"})
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001267
Gregory P. Smithb0d9ca922009-07-07 05:06:04 +00001268 def test_writestr_extended_local_header_issue1202(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001269 with zipfile.ZipFile(TESTFN2, 'w') as orig_zip:
1270 for data in 'abcdefghijklmnop':
1271 zinfo = zipfile.ZipInfo(data)
1272 zinfo.flag_bits |= 0x08 # Include an extended local header.
1273 orig_zip.writestr(zinfo, data)
1274
1275 def test_close(self):
1276 """Check that the zipfile is closed after the 'with' block."""
1277 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
1278 for fpath, fdata in SMALL_TEST_DATA:
1279 zipfp.writestr(fpath, fdata)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001280 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
1281 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001282
1283 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001284 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
1285 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001286
1287 def test_close_on_exception(self):
1288 """Check that the zipfile is closed if an exception is raised in the
1289 'with' block."""
1290 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
1291 for fpath, fdata in SMALL_TEST_DATA:
1292 zipfp.writestr(fpath, fdata)
1293
1294 try:
1295 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
Georg Brandl4d540882010-10-28 06:42:33 +00001296 raise zipfile.BadZipFile()
1297 except zipfile.BadZipFile:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001298 self.assertIsNone(zipfp2.fp, 'zipfp is not closed')
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001299
Martin v. Löwisd099b562012-05-01 14:08:22 +02001300 def test_unsupported_version(self):
1301 # File has an extract_version of 120
1302 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 +02001303 b'\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00xPK\x01\x02x\x03x\x00\x00\x00\x00'
1304 b'\x00!p\xa1@\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00'
1305 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00\x00xPK\x05\x06'
1306 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 +03001307
Martin v. Löwisd099b562012-05-01 14:08:22 +02001308 self.assertRaises(NotImplementedError, zipfile.ZipFile,
1309 io.BytesIO(data), 'r')
1310
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001311 @requires_zlib
1312 def test_read_unicode_filenames(self):
1313 # bug #10801
1314 fname = findfile('zip_cp437_header.zip')
1315 with zipfile.ZipFile(fname) as zipfp:
1316 for name in zipfp.namelist():
1317 zipfp.open(name).close()
1318
1319 def test_write_unicode_filenames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001320 with zipfile.ZipFile(TESTFN, "w") as zf:
1321 zf.writestr("foo.txt", "Test for unicode filename")
1322 zf.writestr("\xf6.txt", "Test for unicode filename")
Ezio Melottie9615932010-01-24 19:26:24 +00001323 self.assertIsInstance(zf.infolist()[0].filename, str)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001324
1325 with zipfile.ZipFile(TESTFN, "r") as zf:
1326 self.assertEqual(zf.filelist[0].filename, "foo.txt")
1327 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
Martin v. Löwis8570f6a2008-05-05 17:44:38 +00001328
Serhiy Storchaka764fc9b2015-03-25 10:09:41 +02001329 def test_exclusive_create_zip_file(self):
1330 """Test exclusive creating a new zipfile."""
1331 unlink(TESTFN2)
1332 filename = 'testfile.txt'
1333 content = b'hello, world. this is some content.'
1334 with zipfile.ZipFile(TESTFN2, "x", zipfile.ZIP_STORED) as zipfp:
1335 zipfp.writestr(filename, content)
1336 with self.assertRaises(FileExistsError):
1337 zipfile.ZipFile(TESTFN2, "x", zipfile.ZIP_STORED)
1338 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1339 self.assertEqual(zipfp.namelist(), [filename])
1340 self.assertEqual(zipfp.read(filename), content)
1341
Ezio Melottiafd0d112009-07-15 17:17:17 +00001342 def test_create_non_existent_file_for_append(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001343 if os.path.exists(TESTFN):
1344 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001345
Thomas Wouterscf297e42007-02-23 15:07:44 +00001346 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001347 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +00001348
Thomas Wouterscf297e42007-02-23 15:07:44 +00001349 try:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001350 with zipfile.ZipFile(TESTFN, 'a') as zf:
1351 zf.writestr(filename, content)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001352 except OSError:
Thomas Wouterscf297e42007-02-23 15:07:44 +00001353 self.fail('Could not append data to a non-existent zip file.')
1354
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001355 self.assertTrue(os.path.exists(TESTFN))
Thomas Wouterscf297e42007-02-23 15:07:44 +00001356
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001357 with zipfile.ZipFile(TESTFN, 'r') as zf:
1358 self.assertEqual(zf.read(filename), content)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001359
Ezio Melottiafd0d112009-07-15 17:17:17 +00001360 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001361 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti35386712009-12-31 13:22:41 +00001362 # it opens if there's an error in the file. If it doesn't, the
1363 # traceback holds a reference to the ZipFile object and, indirectly,
1364 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001365 # On Windows, this causes the os.unlink() call to fail because the
1366 # underlying file is still open. This is SF bug #412214.
1367 #
Ezio Melotti35386712009-12-31 13:22:41 +00001368 with open(TESTFN, "w") as fp:
1369 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001370 try:
1371 zf = zipfile.ZipFile(TESTFN)
Georg Brandl4d540882010-10-28 06:42:33 +00001372 except zipfile.BadZipFile:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001373 pass
1374
Ezio Melottiafd0d112009-07-15 17:17:17 +00001375 def test_is_zip_erroneous_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001376 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001377 # - passing a filename
1378 with open(TESTFN, "w") as fp:
1379 fp.write("this is not a legal zip file\n")
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001380 self.assertFalse(zipfile.is_zipfile(TESTFN))
Serhiy Storchaka8606e952017-03-08 14:37:51 +02001381 # - passing a path-like object
1382 self.assertFalse(zipfile.is_zipfile(pathlib.Path(TESTFN)))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001383 # - passing a file object
1384 with open(TESTFN, "rb") as fp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001385 self.assertFalse(zipfile.is_zipfile(fp))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001386 # - passing a file-like object
1387 fp = io.BytesIO()
1388 fp.write(b"this is not a legal zip file\n")
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001389 self.assertFalse(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001390 fp.seek(0, 0)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001391 self.assertFalse(zipfile.is_zipfile(fp))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001392
Serhiy Storchakad2b15272013-01-31 15:27:07 +02001393 def test_damaged_zipfile(self):
1394 """Check that zipfiles with missing bytes at the end raise BadZipFile."""
1395 # - Create a valid zip file
1396 fp = io.BytesIO()
1397 with zipfile.ZipFile(fp, mode="w") as zipf:
1398 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
1399 zipfiledata = fp.getvalue()
1400
1401 # - Now create copies of it missing the last N bytes and make sure
1402 # a BadZipFile exception is raised when we try to open it
1403 for N in range(len(zipfiledata)):
1404 fp = io.BytesIO(zipfiledata[:N])
1405 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, fp)
1406
Ezio Melottiafd0d112009-07-15 17:17:17 +00001407 def test_is_zip_valid_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001408 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001409 # - passing a filename
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001410 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1411 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
1412
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001413 self.assertTrue(zipfile.is_zipfile(TESTFN))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001414 # - passing a file object
1415 with open(TESTFN, "rb") as fp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001416 self.assertTrue(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001417 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001418 zip_contents = fp.read()
1419 # - passing a file-like object
1420 fp = io.BytesIO()
1421 fp.write(zip_contents)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001422 self.assertTrue(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001423 fp.seek(0, 0)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001424 self.assertTrue(zipfile.is_zipfile(fp))
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001425
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001426 def test_non_existent_file_raises_OSError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001427 # make sure we don't raise an AttributeError when a partially-constructed
1428 # ZipFile instance is finalized; this tests for regression on SF tracker
1429 # bug #403871.
1430
1431 # The bug we're testing for caused an AttributeError to be raised
1432 # when a ZipFile instance was created for a file that did not
1433 # exist; the .fp member was not initialized but was needed by the
1434 # __del__() method. Since the AttributeError is in the __del__(),
1435 # it is ignored, but the user should be sufficiently annoyed by
1436 # the message on the output that regression will be noticed
1437 # quickly.
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001438 self.assertRaises(OSError, zipfile.ZipFile, TESTFN)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001439
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001440 def test_empty_file_raises_BadZipFile(self):
1441 f = open(TESTFN, 'w')
1442 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001443 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001444
Ezio Melotti35386712009-12-31 13:22:41 +00001445 with open(TESTFN, 'w') as fp:
1446 fp.write("short file")
Georg Brandl4d540882010-10-28 06:42:33 +00001447 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001448
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001449 def test_closed_zip_raises_ValueError(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001450 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001451 data = io.BytesIO()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001452 with zipfile.ZipFile(data, mode="w") as zipf:
1453 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001454
Andrew Svetlov737fb892012-12-18 21:14:22 +02001455 # This is correct; calling .read on a closed ZipFile should raise
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001456 # a ValueError, and so should calling .testzip. An earlier
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001457 # version of .testzip would swallow this exception (and any other)
1458 # and report that the first file in the archive was corrupt.
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001459 self.assertRaises(ValueError, zipf.read, "foo.txt")
1460 self.assertRaises(ValueError, zipf.open, "foo.txt")
1461 self.assertRaises(ValueError, zipf.testzip)
1462 self.assertRaises(ValueError, zipf.writestr, "bogus.txt", "bogus")
Brian Curtin8fb9b862010-11-18 02:15:28 +00001463 with open(TESTFN, 'w') as f:
1464 f.write('zipfile test data')
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001465 self.assertRaises(ValueError, zipf.write, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001466
Ezio Melottiafd0d112009-07-15 17:17:17 +00001467 def test_bad_constructor_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001468 """Check that bad modes passed to ZipFile constructor are caught."""
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001469 self.assertRaises(ValueError, zipfile.ZipFile, TESTFN, "q")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001470
Ezio Melottiafd0d112009-07-15 17:17:17 +00001471 def test_bad_open_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001472 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001473 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1474 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1475
1476 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Serhiy Storchakae670be22016-06-11 19:32:44 +03001477 # read the data to make sure the file is there
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001478 zipf.read("foo.txt")
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001479 self.assertRaises(ValueError, zipf.open, "foo.txt", "q")
Serhiy Storchakae670be22016-06-11 19:32:44 +03001480 # universal newlines support is removed
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001481 self.assertRaises(ValueError, zipf.open, "foo.txt", "U")
1482 self.assertRaises(ValueError, zipf.open, "foo.txt", "rU")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001483
Ezio Melottiafd0d112009-07-15 17:17:17 +00001484 def test_read0(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001485 """Check that calling read(0) on a ZipExtFile object returns an empty
1486 string and doesn't advance file pointer."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001487 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1488 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1489 # read the data to make sure the file is there
Brian Curtin8fb9b862010-11-18 02:15:28 +00001490 with zipf.open("foo.txt") as f:
1491 for i in range(FIXEDTEST_SIZE):
1492 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001493
Brian Curtin8fb9b862010-11-18 02:15:28 +00001494 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001495
Ezio Melottiafd0d112009-07-15 17:17:17 +00001496 def test_open_non_existent_item(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001497 """Check that attempting to call open() for an item that doesn't
1498 exist in the archive raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001499 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1500 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001501
Ezio Melottiafd0d112009-07-15 17:17:17 +00001502 def test_bad_compression_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001503 """Check that bad compression methods passed to ZipFile.open are
1504 caught."""
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001505 self.assertRaises(NotImplementedError, zipfile.ZipFile, TESTFN, "w", -1)
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001506
Martin v. Löwisb3260f02012-05-01 08:38:01 +02001507 def test_unsupported_compression(self):
1508 # data is declared as shrunk, but actually deflated
1509 data = (b'PK\x03\x04.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00'
Christian Tismer59202e52013-10-21 03:59:23 +02001510 b'\x00\x02\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00x\x03\x00PK\x01'
1511 b'\x02.\x03.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00\x00\x02\x00\x00'
1512 b'\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
1513 b'\x80\x01\x00\x00\x00\x00xPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00'
1514 b'/\x00\x00\x00!\x00\x00\x00\x00\x00')
Martin v. Löwisb3260f02012-05-01 08:38:01 +02001515 with zipfile.ZipFile(io.BytesIO(data), 'r') as zipf:
1516 self.assertRaises(NotImplementedError, zipf.open, 'x')
1517
Ezio Melottiafd0d112009-07-15 17:17:17 +00001518 def test_null_byte_in_filename(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001519 """Check that a filename containing a null byte is properly
1520 terminated."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001521 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1522 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
1523 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001524
Ezio Melottiafd0d112009-07-15 17:17:17 +00001525 def test_struct_sizes(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001526 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001527 self.assertEqual(zipfile.sizeEndCentDir, 22)
1528 self.assertEqual(zipfile.sizeCentralDir, 46)
1529 self.assertEqual(zipfile.sizeEndCentDir64, 56)
1530 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
1531
Ezio Melottiafd0d112009-07-15 17:17:17 +00001532 def test_comments(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001533 """Check that comments on the archive are handled properly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001534
1535 # check default comment is empty
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001536 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1537 self.assertEqual(zipf.comment, b'')
1538 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1539
1540 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1541 self.assertEqual(zipfr.comment, b'')
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001542
1543 # check a simple short comment
1544 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001545 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1546 zipf.comment = comment
1547 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1548 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1549 self.assertEqual(zipf.comment, comment)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001550
1551 # check a comment of max length
1552 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
1553 comment2 = comment2.encode("ascii")
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001554 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1555 zipf.comment = comment2
1556 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1557
1558 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1559 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001560
1561 # check a comment that is too long is truncated
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001562 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
Serhiy Storchaka9b7a1a12014-01-20 21:57:40 +02001563 with self.assertWarns(UserWarning):
1564 zipf.comment = comment2 + b'oops'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001565 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1566 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1567 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001568
Antoine Pitrouc3991852012-06-30 17:31:37 +02001569 # check that comments are correctly modified in append mode
1570 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1571 zipf.comment = b"original comment"
1572 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1573 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1574 zipf.comment = b"an updated comment"
1575 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1576 self.assertEqual(zipf.comment, b"an updated comment")
1577
1578 # check that comments are correctly shortened in append mode
1579 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1580 zipf.comment = b"original comment that's longer"
1581 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1582 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1583 zipf.comment = b"shorter comment"
1584 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1585 self.assertEqual(zipf.comment, b"shorter comment")
1586
R David Murrayf50b38a2012-04-12 18:44:58 -04001587 def test_unicode_comment(self):
1588 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1589 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1590 with self.assertRaises(TypeError):
1591 zipf.comment = "this is an error"
1592
1593 def test_change_comment_in_empty_archive(self):
1594 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1595 self.assertFalse(zipf.filelist)
1596 zipf.comment = b"this is a comment"
1597 with zipfile.ZipFile(TESTFN, "r") as zipf:
1598 self.assertEqual(zipf.comment, b"this is a comment")
1599
1600 def test_change_comment_in_nonempty_archive(self):
1601 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1602 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1603 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1604 self.assertTrue(zipf.filelist)
1605 zipf.comment = b"this is a comment"
1606 with zipfile.ZipFile(TESTFN, "r") as zipf:
1607 self.assertEqual(zipf.comment, b"this is a comment")
1608
Georg Brandl268e4d42010-10-14 06:59:45 +00001609 def test_empty_zipfile(self):
1610 # Check that creating a file in 'w' or 'a' mode and closing without
1611 # adding any files to the archives creates a valid empty ZIP file
1612 zipf = zipfile.ZipFile(TESTFN, mode="w")
1613 zipf.close()
1614 try:
1615 zipf = zipfile.ZipFile(TESTFN, mode="r")
1616 except zipfile.BadZipFile:
1617 self.fail("Unable to create empty ZIP file in 'w' mode")
1618
1619 zipf = zipfile.ZipFile(TESTFN, mode="a")
1620 zipf.close()
1621 try:
1622 zipf = zipfile.ZipFile(TESTFN, mode="r")
1623 except:
1624 self.fail("Unable to create empty ZIP file in 'a' mode")
1625
1626 def test_open_empty_file(self):
1627 # Issue 1710703: Check that opening a file with less than 22 bytes
Georg Brandl4d540882010-10-28 06:42:33 +00001628 # raises a BadZipFile exception (rather than the previously unhelpful
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001629 # OSError)
Georg Brandl268e4d42010-10-14 06:59:45 +00001630 f = open(TESTFN, 'w')
1631 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001632 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN, 'r')
Georg Brandl268e4d42010-10-14 06:59:45 +00001633
Senthil Kumaran29fa9d42011-10-20 01:46:00 +08001634 def test_create_zipinfo_before_1980(self):
1635 self.assertRaises(ValueError,
1636 zipfile.ZipInfo, 'seventies', (1979, 1, 1, 0, 0, 0))
1637
Gregory P. Smith0af8a862014-05-29 23:42:14 -07001638 def test_zipfile_with_short_extra_field(self):
1639 """If an extra field in the header is less than 4 bytes, skip it."""
1640 zipdata = (
1641 b'PK\x03\x04\x14\x00\x00\x00\x00\x00\x93\x9b\xad@\x8b\x9e'
1642 b'\xd9\xd3\x01\x00\x00\x00\x01\x00\x00\x00\x03\x00\x03\x00ab'
1643 b'c\x00\x00\x00APK\x01\x02\x14\x03\x14\x00\x00\x00\x00'
1644 b'\x00\x93\x9b\xad@\x8b\x9e\xd9\xd3\x01\x00\x00\x00\x01\x00\x00'
1645 b'\x00\x03\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00'
1646 b'\x00\x00\x00abc\x00\x00PK\x05\x06\x00\x00\x00\x00'
1647 b'\x01\x00\x01\x003\x00\x00\x00%\x00\x00\x00\x00\x00'
1648 )
1649 with zipfile.ZipFile(io.BytesIO(zipdata), 'r') as zipf:
1650 # testzip returns the name of the first corrupt file, or None
1651 self.assertIsNone(zipf.testzip())
1652
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001653 def test_open_conflicting_handles(self):
1654 # It's only possible to open one writable file handle at a time
1655 msg1 = b"It's fun to charter an accountant!"
1656 msg2 = b"And sail the wide accountant sea"
1657 msg3 = b"To find, explore the funds offshore"
1658 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipf:
1659 with zipf.open('foo', mode='w') as w2:
1660 w2.write(msg1)
1661 with zipf.open('bar', mode='w') as w1:
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001662 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001663 zipf.open('handle', mode='w')
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001664 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001665 zipf.open('foo', mode='r')
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001666 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001667 zipf.writestr('str', 'abcde')
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001668 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001669 zipf.write(__file__, 'file')
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001670 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001671 zipf.close()
1672 w1.write(msg2)
1673 with zipf.open('baz', mode='w') as w2:
1674 w2.write(msg3)
1675
1676 with zipfile.ZipFile(TESTFN2, 'r') as zipf:
1677 self.assertEqual(zipf.read('foo'), msg1)
1678 self.assertEqual(zipf.read('bar'), msg2)
1679 self.assertEqual(zipf.read('baz'), msg3)
1680 self.assertEqual(zipf.namelist(), ['foo', 'bar', 'baz'])
1681
John Jolly066df4f2018-01-30 01:51:35 -07001682 def test_seek_tell(self):
1683 # Test seek functionality
1684 txt = b"Where's Bruce?"
1685 bloc = txt.find(b"Bruce")
1686 # Check seek on a file
1687 with zipfile.ZipFile(TESTFN, "w") as zipf:
1688 zipf.writestr("foo.txt", txt)
1689 with zipfile.ZipFile(TESTFN, "r") as zipf:
1690 with zipf.open("foo.txt", "r") as fp:
1691 fp.seek(bloc, os.SEEK_SET)
1692 self.assertEqual(fp.tell(), bloc)
1693 fp.seek(-bloc, os.SEEK_CUR)
1694 self.assertEqual(fp.tell(), 0)
1695 fp.seek(bloc, os.SEEK_CUR)
1696 self.assertEqual(fp.tell(), bloc)
1697 self.assertEqual(fp.read(5), txt[bloc:bloc+5])
1698 fp.seek(0, os.SEEK_END)
1699 self.assertEqual(fp.tell(), len(txt))
Miss Islington (bot)ad4f64d2018-07-29 12:57:21 -07001700 fp.seek(0, os.SEEK_SET)
1701 self.assertEqual(fp.tell(), 0)
John Jolly066df4f2018-01-30 01:51:35 -07001702 # Check seek on memory file
1703 data = io.BytesIO()
1704 with zipfile.ZipFile(data, mode="w") as zipf:
1705 zipf.writestr("foo.txt", txt)
1706 with zipfile.ZipFile(data, mode="r") as zipf:
1707 with zipf.open("foo.txt", "r") as fp:
1708 fp.seek(bloc, os.SEEK_SET)
1709 self.assertEqual(fp.tell(), bloc)
1710 fp.seek(-bloc, os.SEEK_CUR)
1711 self.assertEqual(fp.tell(), 0)
1712 fp.seek(bloc, os.SEEK_CUR)
1713 self.assertEqual(fp.tell(), bloc)
1714 self.assertEqual(fp.read(5), txt[bloc:bloc+5])
1715 fp.seek(0, os.SEEK_END)
1716 self.assertEqual(fp.tell(), len(txt))
Miss Islington (bot)ad4f64d2018-07-29 12:57:21 -07001717 fp.seek(0, os.SEEK_SET)
1718 self.assertEqual(fp.tell(), 0)
John Jolly066df4f2018-01-30 01:51:35 -07001719
Guido van Rossumd8faa362007-04-27 19:54:29 +00001720 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001721 unlink(TESTFN)
1722 unlink(TESTFN2)
1723
Thomas Wouterscf297e42007-02-23 15:07:44 +00001724
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001725class AbstractBadCrcTests:
1726 def test_testzip_with_bad_crc(self):
1727 """Tests that files with bad CRCs return their name from testzip."""
1728 zipdata = self.zip_with_bad_crc
1729
1730 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1731 # testzip returns the name of the first corrupt file, or None
1732 self.assertEqual('afile', zipf.testzip())
1733
1734 def test_read_with_bad_crc(self):
1735 """Tests that files with bad CRCs raise a BadZipFile exception when read."""
1736 zipdata = self.zip_with_bad_crc
1737
1738 # Using ZipFile.read()
1739 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1740 self.assertRaises(zipfile.BadZipFile, zipf.read, 'afile')
1741
1742 # Using ZipExtFile.read()
1743 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1744 with zipf.open('afile', 'r') as corrupt_file:
1745 self.assertRaises(zipfile.BadZipFile, corrupt_file.read)
1746
1747 # Same with small reads (in order to exercise the buffering logic)
1748 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1749 with zipf.open('afile', 'r') as corrupt_file:
1750 corrupt_file.MIN_READ_SIZE = 2
1751 with self.assertRaises(zipfile.BadZipFile):
1752 while corrupt_file.read(2):
1753 pass
1754
1755
1756class StoredBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1757 compression = zipfile.ZIP_STORED
1758 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001759 b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
1760 b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
1761 b'ilehello,AworldP'
1762 b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
1763 b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
1764 b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
1765 b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
1766 b'\0\0/\0\0\0\0\0')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001767
1768@requires_zlib
1769class DeflateBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1770 compression = zipfile.ZIP_DEFLATED
1771 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001772 b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
1773 b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1774 b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
1775 b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
1776 b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
1777 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
1778 b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
1779 b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001780
1781@requires_bz2
1782class Bzip2BadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1783 compression = zipfile.ZIP_BZIP2
1784 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001785 b'PK\x03\x04\x14\x03\x00\x00\x0c\x00nu\x0c=FA'
1786 b'KE8\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1787 b'ileBZh91AY&SY\xd4\xa8\xca'
1788 b'\x7f\x00\x00\x0f\x11\x80@\x00\x06D\x90\x80 \x00 \xa5'
1789 b'P\xd9!\x03\x03\x13\x13\x13\x89\xa9\xa9\xc2u5:\x9f'
1790 b'\x8b\xb9"\x9c(HjTe?\x80PK\x01\x02\x14'
1791 b'\x03\x14\x03\x00\x00\x0c\x00nu\x0c=FAKE8'
1792 b'\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\x00'
1793 b'\x00 \x80\x80\x81\x00\x00\x00\x00afilePK'
1794 b'\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00\x00[\x00'
1795 b'\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001796
1797@requires_lzma
1798class LzmaBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1799 compression = zipfile.ZIP_LZMA
1800 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001801 b'PK\x03\x04\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
1802 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1803 b'ile\t\x04\x05\x00]\x00\x00\x00\x04\x004\x19I'
1804 b'\xee\x8d\xe9\x17\x89:3`\tq!.8\x00PK'
1805 b'\x01\x02\x14\x03\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
1806 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00'
1807 b'\x00\x00\x00\x00 \x80\x80\x81\x00\x00\x00\x00afil'
1808 b'ePK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00'
1809 b'\x00>\x00\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001810
1811
Thomas Wouterscf297e42007-02-23 15:07:44 +00001812class DecryptionTests(unittest.TestCase):
Ezio Melotti35386712009-12-31 13:22:41 +00001813 """Check that ZIP decryption works. Since the library does not
1814 support encryption at the moment, we use a pre-generated encrypted
1815 ZIP file."""
Thomas Wouterscf297e42007-02-23 15:07:44 +00001816
1817 data = (
Christian Tismer59202e52013-10-21 03:59:23 +02001818 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
1819 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
1820 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
1821 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
1822 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
1823 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
1824 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +00001825 data2 = (
Christian Tismer59202e52013-10-21 03:59:23 +02001826 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
1827 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
1828 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
1829 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
1830 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
1831 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
1832 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
1833 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +00001834
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001835 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +00001836 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +00001837
1838 def setUp(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001839 with open(TESTFN, "wb") as fp:
1840 fp.write(self.data)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001841 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti35386712009-12-31 13:22:41 +00001842 with open(TESTFN2, "wb") as fp:
1843 fp.write(self.data2)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001844 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001845
1846 def tearDown(self):
1847 self.zip.close()
1848 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001849 self.zip2.close()
1850 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001851
Ezio Melottiafd0d112009-07-15 17:17:17 +00001852 def test_no_password(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001853 # Reading the encrypted file without password
1854 # must generate a RunTime exception
1855 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001856 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001857
Ezio Melottiafd0d112009-07-15 17:17:17 +00001858 def test_bad_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001859 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001860 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001861 self.zip2.setpassword(b"perl")
1862 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001863
Ezio Melotti975077a2011-05-19 22:03:22 +03001864 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +00001865 def test_good_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001866 self.zip.setpassword(b"python")
Ezio Melotti35386712009-12-31 13:22:41 +00001867 self.assertEqual(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001868 self.zip2.setpassword(b"12345")
Ezio Melotti35386712009-12-31 13:22:41 +00001869 self.assertEqual(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001870
R. David Murray8d855d82010-12-21 21:53:37 +00001871 def test_unicode_password(self):
1872 self.assertRaises(TypeError, self.zip.setpassword, "unicode")
1873 self.assertRaises(TypeError, self.zip.read, "test.txt", "python")
1874 self.assertRaises(TypeError, self.zip.open, "test.txt", pwd="python")
1875 self.assertRaises(TypeError, self.zip.extract, "test.txt", pwd="python")
1876
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001877class AbstractTestsWithRandomBinaryFiles:
1878 @classmethod
1879 def setUpClass(cls):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001880 datacount = randint(16, 64)*1024 + randint(1, 1024)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001881 cls.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
1882 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001883
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001884 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001885 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +00001886 with open(TESTFN, "wb") as fp:
1887 fp.write(self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001888
1889 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001890 unlink(TESTFN)
1891 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001892
Ezio Melottiafd0d112009-07-15 17:17:17 +00001893 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001894 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001895 with zipfile.ZipFile(f, "w", compression) as zipfp:
1896 zipfp.write(TESTFN, "another.name")
1897 zipfp.write(TESTFN, TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001898
Ezio Melottiafd0d112009-07-15 17:17:17 +00001899 def zip_test(self, f, compression):
1900 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001901
1902 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001903 with zipfile.ZipFile(f, "r", compression) as zipfp:
1904 testdata = zipfp.read(TESTFN)
1905 self.assertEqual(len(testdata), len(self.data))
1906 self.assertEqual(testdata, self.data)
1907 self.assertEqual(zipfp.read("another.name"), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001908
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001909 def test_read(self):
1910 for f in get_files(self):
1911 self.zip_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001912
Ezio Melottiafd0d112009-07-15 17:17:17 +00001913 def zip_open_test(self, f, compression):
1914 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001915
1916 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001917 with zipfile.ZipFile(f, "r", compression) as zipfp:
1918 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001919 with zipfp.open(TESTFN) as zipopen1:
1920 while True:
1921 read_data = zipopen1.read(256)
1922 if not read_data:
1923 break
1924 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001925
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001926 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001927 with zipfp.open("another.name") as zipopen2:
1928 while True:
1929 read_data = zipopen2.read(256)
1930 if not read_data:
1931 break
1932 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001933
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001934 testdata1 = b''.join(zipdata1)
1935 self.assertEqual(len(testdata1), len(self.data))
1936 self.assertEqual(testdata1, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001937
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001938 testdata2 = b''.join(zipdata2)
Ezio Melotti35386712009-12-31 13:22:41 +00001939 self.assertEqual(len(testdata2), len(self.data))
1940 self.assertEqual(testdata2, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001941
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001942 def test_open(self):
1943 for f in get_files(self):
1944 self.zip_open_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001945
Ezio Melottiafd0d112009-07-15 17:17:17 +00001946 def zip_random_open_test(self, f, compression):
1947 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001948
1949 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001950 with zipfile.ZipFile(f, "r", compression) as zipfp:
1951 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001952 with zipfp.open(TESTFN) as zipopen1:
1953 while True:
1954 read_data = zipopen1.read(randint(1, 1024))
1955 if not read_data:
1956 break
1957 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001958
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001959 testdata = b''.join(zipdata1)
1960 self.assertEqual(len(testdata), len(self.data))
1961 self.assertEqual(testdata, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001962
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001963 def test_random_open(self):
1964 for f in get_files(self):
1965 self.zip_random_open_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001966
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001967
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001968class StoredTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1969 unittest.TestCase):
1970 compression = zipfile.ZIP_STORED
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001971
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001972@requires_zlib
1973class DeflateTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1974 unittest.TestCase):
1975 compression = zipfile.ZIP_DEFLATED
1976
1977@requires_bz2
1978class Bzip2TestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1979 unittest.TestCase):
1980 compression = zipfile.ZIP_BZIP2
1981
1982@requires_lzma
1983class LzmaTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1984 unittest.TestCase):
1985 compression = zipfile.ZIP_LZMA
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001986
Ezio Melotti76430242009-07-11 18:28:48 +00001987
luzpaza5293b42017-11-05 07:37:50 -06001988# Provide the tell() method but not seek()
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001989class Tellable:
1990 def __init__(self, fp):
1991 self.fp = fp
1992 self.offset = 0
1993
1994 def write(self, data):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02001995 n = self.fp.write(data)
1996 self.offset += n
1997 return n
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001998
1999 def tell(self):
2000 return self.offset
2001
2002 def flush(self):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02002003 self.fp.flush()
2004
2005class Unseekable:
2006 def __init__(self, fp):
2007 self.fp = fp
2008
2009 def write(self, data):
2010 return self.fp.write(data)
2011
2012 def flush(self):
2013 self.fp.flush()
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02002014
2015class UnseekableTests(unittest.TestCase):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02002016 def test_writestr(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 zipfp:
2023 zipfp.writestr('ones', b'111')
2024 zipfp.writestr('twos', b'222')
2025 self.assertEqual(f.getvalue()[:5], b'abcPK')
2026 with zipfile.ZipFile(f, mode='r') as zipf:
2027 with zipf.open('ones') as zopen:
2028 self.assertEqual(zopen.read(), b'111')
2029 with zipf.open('twos') as zopen:
2030 self.assertEqual(zopen.read(), b'222')
2031
2032 def test_write(self):
2033 for wrapper in (lambda f: f), Tellable, Unseekable:
2034 with self.subTest(wrapper=wrapper):
2035 f = io.BytesIO()
2036 f.write(b'abc')
2037 bf = io.BufferedWriter(f)
2038 with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) as zipfp:
2039 self.addCleanup(unlink, TESTFN)
2040 with open(TESTFN, 'wb') as f2:
2041 f2.write(b'111')
2042 zipfp.write(TESTFN, 'ones')
2043 with open(TESTFN, 'wb') as f2:
2044 f2.write(b'222')
2045 zipfp.write(TESTFN, 'twos')
2046 self.assertEqual(f.getvalue()[:5], b'abcPK')
2047 with zipfile.ZipFile(f, mode='r') as zipf:
2048 with zipf.open('ones') as zopen:
2049 self.assertEqual(zopen.read(), b'111')
2050 with zipf.open('twos') as zopen:
2051 self.assertEqual(zopen.read(), b'222')
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02002052
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03002053 def test_open_write(self):
2054 for wrapper in (lambda f: f), Tellable, Unseekable:
2055 with self.subTest(wrapper=wrapper):
2056 f = io.BytesIO()
2057 f.write(b'abc')
2058 bf = io.BufferedWriter(f)
2059 with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) as zipf:
2060 with zipf.open('ones', 'w') as zopen:
2061 zopen.write(b'111')
2062 with zipf.open('twos', 'w') as zopen:
2063 zopen.write(b'222')
2064 self.assertEqual(f.getvalue()[:5], b'abcPK')
2065 with zipfile.ZipFile(f) as zipf:
2066 self.assertEqual(zipf.read('ones'), b'111')
2067 self.assertEqual(zipf.read('twos'), b'222')
2068
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02002069
Ezio Melotti975077a2011-05-19 22:03:22 +03002070@requires_zlib
Guido van Rossumd8faa362007-04-27 19:54:29 +00002071class TestsWithMultipleOpens(unittest.TestCase):
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02002072 @classmethod
2073 def setUpClass(cls):
2074 cls.data1 = b'111' + getrandbytes(10000)
2075 cls.data2 = b'222' + getrandbytes(10000)
2076
2077 def make_test_archive(self, f):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002078 # Create the ZIP archive
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02002079 with zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as zipfp:
2080 zipfp.writestr('ones', self.data1)
2081 zipfp.writestr('twos', self.data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002082
Ezio Melottiafd0d112009-07-15 17:17:17 +00002083 def test_same_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002084 # Verify that (when the ZipFile is in control of creating file objects)
2085 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02002086 for f in get_files(self):
2087 self.make_test_archive(f)
2088 with zipfile.ZipFile(f, mode="r") as zipf:
2089 with zipf.open('ones') as zopen1, zipf.open('ones') as zopen2:
2090 data1 = zopen1.read(500)
2091 data2 = zopen2.read(500)
2092 data1 += zopen1.read()
2093 data2 += zopen2.read()
2094 self.assertEqual(data1, data2)
2095 self.assertEqual(data1, self.data1)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002096
Ezio Melottiafd0d112009-07-15 17:17:17 +00002097 def test_different_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002098 # Verify that (when the ZipFile is in control of creating file objects)
2099 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02002100 for f in get_files(self):
2101 self.make_test_archive(f)
2102 with zipfile.ZipFile(f, mode="r") as zipf:
2103 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
2104 data1 = zopen1.read(500)
2105 data2 = zopen2.read(500)
2106 data1 += zopen1.read()
2107 data2 += zopen2.read()
2108 self.assertEqual(data1, self.data1)
2109 self.assertEqual(data2, self.data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002110
Ezio Melottiafd0d112009-07-15 17:17:17 +00002111 def test_interleaved(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002112 # Verify that (when the ZipFile is in control of creating file objects)
2113 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02002114 for f in get_files(self):
2115 self.make_test_archive(f)
2116 with zipfile.ZipFile(f, mode="r") as zipf:
Serhiy Storchakad76c7c22016-05-13 21:18:58 +03002117 with zipf.open('ones') as zopen1:
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02002118 data1 = zopen1.read(500)
Serhiy Storchakad76c7c22016-05-13 21:18:58 +03002119 with zipf.open('twos') as zopen2:
2120 data2 = zopen2.read(500)
2121 data1 += zopen1.read()
2122 data2 += zopen2.read()
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02002123 self.assertEqual(data1, self.data1)
2124 self.assertEqual(data2, self.data2)
2125
2126 def test_read_after_close(self):
2127 for f in get_files(self):
2128 self.make_test_archive(f)
2129 with contextlib.ExitStack() as stack:
2130 with zipfile.ZipFile(f, 'r') as zipf:
2131 zopen1 = stack.enter_context(zipf.open('ones'))
2132 zopen2 = stack.enter_context(zipf.open('twos'))
Brian Curtin8fb9b862010-11-18 02:15:28 +00002133 data1 = zopen1.read(500)
2134 data2 = zopen2.read(500)
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02002135 data1 += zopen1.read()
2136 data2 += zopen2.read()
2137 self.assertEqual(data1, self.data1)
2138 self.assertEqual(data2, self.data2)
2139
2140 def test_read_after_write(self):
2141 for f in get_files(self):
2142 with zipfile.ZipFile(f, 'w', zipfile.ZIP_DEFLATED) as zipf:
2143 zipf.writestr('ones', self.data1)
2144 zipf.writestr('twos', self.data2)
2145 with zipf.open('ones') as zopen1:
2146 data1 = zopen1.read(500)
2147 self.assertEqual(data1, self.data1[:500])
2148 with zipfile.ZipFile(f, 'r') as zipf:
2149 data1 = zipf.read('ones')
2150 data2 = zipf.read('twos')
2151 self.assertEqual(data1, self.data1)
2152 self.assertEqual(data2, self.data2)
2153
2154 def test_write_after_read(self):
2155 for f in get_files(self):
2156 with zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as zipf:
2157 zipf.writestr('ones', self.data1)
2158 with zipf.open('ones') as zopen1:
2159 zopen1.read(500)
2160 zipf.writestr('twos', self.data2)
2161 with zipfile.ZipFile(f, 'r') as zipf:
2162 data1 = zipf.read('ones')
2163 data2 = zipf.read('twos')
2164 self.assertEqual(data1, self.data1)
2165 self.assertEqual(data2, self.data2)
2166
2167 def test_many_opens(self):
2168 # Verify that read() and open() promptly close the file descriptor,
2169 # and don't rely on the garbage collector to free resources.
2170 self.make_test_archive(TESTFN2)
2171 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
2172 for x in range(100):
2173 zipf.read('ones')
2174 with zipf.open('ones') as zopen1:
2175 pass
2176 with open(os.devnull) as f:
2177 self.assertLess(f.fileno(), 100)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002178
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03002179 def test_write_while_reading(self):
2180 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_DEFLATED) as zipf:
2181 zipf.writestr('ones', self.data1)
2182 with zipfile.ZipFile(TESTFN2, 'a', zipfile.ZIP_DEFLATED) as zipf:
2183 with zipf.open('ones', 'r') as r1:
2184 data1 = r1.read(500)
2185 with zipf.open('twos', 'w') as w1:
2186 w1.write(self.data2)
2187 data1 += r1.read()
2188 self.assertEqual(data1, self.data1)
2189 with zipfile.ZipFile(TESTFN2) as zipf:
2190 self.assertEqual(zipf.read('twos'), self.data2)
2191
Guido van Rossumd8faa362007-04-27 19:54:29 +00002192 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00002193 unlink(TESTFN2)
2194
Guido van Rossumd8faa362007-04-27 19:54:29 +00002195
Martin v. Löwis59e47792009-01-24 14:10:07 +00002196class TestWithDirectory(unittest.TestCase):
2197 def setUp(self):
2198 os.mkdir(TESTFN2)
2199
Ezio Melottiafd0d112009-07-15 17:17:17 +00002200 def test_extract_dir(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00002201 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
2202 zipf.extractall(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00002203 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
2204 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
2205 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
2206
Ezio Melottiafd0d112009-07-15 17:17:17 +00002207 def test_bug_6050(self):
Martin v. Löwis70ccd162009-05-24 19:47:22 +00002208 # Extraction should succeed if directories already exist
2209 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottiafd0d112009-07-15 17:17:17 +00002210 self.test_extract_dir()
Martin v. Löwis70ccd162009-05-24 19:47:22 +00002211
Serhiy Storchaka46a34922014-09-23 22:40:23 +03002212 def test_write_dir(self):
2213 dirpath = os.path.join(TESTFN2, "x")
2214 os.mkdir(dirpath)
2215 mode = os.stat(dirpath).st_mode & 0xFFFF
2216 with zipfile.ZipFile(TESTFN, "w") as zipf:
2217 zipf.write(dirpath)
2218 zinfo = zipf.filelist[0]
2219 self.assertTrue(zinfo.filename.endswith("/x/"))
2220 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
2221 zipf.write(dirpath, "y")
2222 zinfo = zipf.filelist[1]
2223 self.assertTrue(zinfo.filename, "y/")
2224 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
2225 with zipfile.ZipFile(TESTFN, "r") as zipf:
2226 zinfo = zipf.filelist[0]
2227 self.assertTrue(zinfo.filename.endswith("/x/"))
2228 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
2229 zinfo = zipf.filelist[1]
2230 self.assertTrue(zinfo.filename, "y/")
2231 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
2232 target = os.path.join(TESTFN2, "target")
2233 os.mkdir(target)
2234 zipf.extractall(target)
2235 self.assertTrue(os.path.isdir(os.path.join(target, "y")))
2236 self.assertEqual(len(os.listdir(target)), 2)
2237
2238 def test_writestr_dir(self):
Martin v. Löwis59e47792009-01-24 14:10:07 +00002239 os.mkdir(os.path.join(TESTFN2, "x"))
Serhiy Storchaka46a34922014-09-23 22:40:23 +03002240 with zipfile.ZipFile(TESTFN, "w") as zipf:
2241 zipf.writestr("x/", b'')
2242 zinfo = zipf.filelist[0]
2243 self.assertEqual(zinfo.filename, "x/")
2244 self.assertEqual(zinfo.external_attr, (0o40775 << 16) | 0x10)
2245 with zipfile.ZipFile(TESTFN, "r") as zipf:
2246 zinfo = zipf.filelist[0]
2247 self.assertTrue(zinfo.filename.endswith("x/"))
2248 self.assertEqual(zinfo.external_attr, (0o40775 << 16) | 0x10)
2249 target = os.path.join(TESTFN2, "target")
2250 os.mkdir(target)
2251 zipf.extractall(target)
2252 self.assertTrue(os.path.isdir(os.path.join(target, "x")))
2253 self.assertEqual(os.listdir(target), ["x"])
Martin v. Löwis59e47792009-01-24 14:10:07 +00002254
2255 def tearDown(self):
Victor Stinner57004c62014-09-04 00:49:01 +02002256 rmtree(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00002257 if os.path.exists(TESTFN):
Ezio Melotti76430242009-07-11 18:28:48 +00002258 unlink(TESTFN)
Martin v. Löwis59e47792009-01-24 14:10:07 +00002259
Guido van Rossumd8faa362007-04-27 19:54:29 +00002260
Serhiy Storchaka503f9082016-02-08 00:02:25 +02002261class ZipInfoTests(unittest.TestCase):
2262 def test_from_file(self):
2263 zi = zipfile.ZipInfo.from_file(__file__)
2264 self.assertEqual(posixpath.basename(zi.filename), 'test_zipfile.py')
2265 self.assertFalse(zi.is_dir())
Serhiy Storchaka8606e952017-03-08 14:37:51 +02002266 self.assertEqual(zi.file_size, os.path.getsize(__file__))
2267
2268 def test_from_file_pathlike(self):
2269 zi = zipfile.ZipInfo.from_file(pathlib.Path(__file__))
2270 self.assertEqual(posixpath.basename(zi.filename), 'test_zipfile.py')
2271 self.assertFalse(zi.is_dir())
2272 self.assertEqual(zi.file_size, os.path.getsize(__file__))
2273
2274 def test_from_file_bytes(self):
2275 zi = zipfile.ZipInfo.from_file(os.fsencode(__file__), 'test')
2276 self.assertEqual(posixpath.basename(zi.filename), 'test')
2277 self.assertFalse(zi.is_dir())
2278 self.assertEqual(zi.file_size, os.path.getsize(__file__))
2279
2280 def test_from_file_fileno(self):
2281 with open(__file__, 'rb') as f:
2282 zi = zipfile.ZipInfo.from_file(f.fileno(), 'test')
2283 self.assertEqual(posixpath.basename(zi.filename), 'test')
2284 self.assertFalse(zi.is_dir())
2285 self.assertEqual(zi.file_size, os.path.getsize(__file__))
Serhiy Storchaka503f9082016-02-08 00:02:25 +02002286
2287 def test_from_dir(self):
2288 dirpath = os.path.dirname(os.path.abspath(__file__))
2289 zi = zipfile.ZipInfo.from_file(dirpath, 'stdlib_tests')
2290 self.assertEqual(zi.filename, 'stdlib_tests/')
2291 self.assertTrue(zi.is_dir())
2292 self.assertEqual(zi.compress_type, zipfile.ZIP_STORED)
2293 self.assertEqual(zi.file_size, 0)
2294
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002295
2296class CommandLineTest(unittest.TestCase):
2297
2298 def zipfilecmd(self, *args, **kwargs):
2299 rc, out, err = script_helper.assert_python_ok('-m', 'zipfile', *args,
2300 **kwargs)
2301 return out.replace(os.linesep.encode(), b'\n')
2302
2303 def zipfilecmd_failure(self, *args):
2304 return script_helper.assert_python_failure('-m', 'zipfile', *args)
2305
Serhiy Storchaka150cd192017-04-07 18:56:12 +03002306 def test_bad_use(self):
2307 rc, out, err = self.zipfilecmd_failure()
2308 self.assertEqual(out, b'')
2309 self.assertIn(b'usage', err.lower())
2310 self.assertIn(b'error', err.lower())
2311 self.assertIn(b'required', err.lower())
2312 rc, out, err = self.zipfilecmd_failure('-l', '')
2313 self.assertEqual(out, b'')
2314 self.assertNotEqual(err.strip(), b'')
2315
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002316 def test_test_command(self):
2317 zip_name = findfile('zipdir.zip')
Serhiy Storchaka8c933102016-10-23 13:32:12 +03002318 for opt in '-t', '--test':
2319 out = self.zipfilecmd(opt, zip_name)
2320 self.assertEqual(out.rstrip(), b'Done testing')
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002321 zip_name = findfile('testtar.tar')
2322 rc, out, err = self.zipfilecmd_failure('-t', zip_name)
2323 self.assertEqual(out, b'')
2324
2325 def test_list_command(self):
2326 zip_name = findfile('zipdir.zip')
2327 t = io.StringIO()
2328 with zipfile.ZipFile(zip_name, 'r') as tf:
2329 tf.printdir(t)
2330 expected = t.getvalue().encode('ascii', 'backslashreplace')
Serhiy Storchaka8c933102016-10-23 13:32:12 +03002331 for opt in '-l', '--list':
2332 out = self.zipfilecmd(opt, zip_name,
2333 PYTHONIOENCODING='ascii:backslashreplace')
2334 self.assertEqual(out, expected)
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002335
Serhiy Storchakab4293ef2016-10-23 22:32:30 +03002336 @requires_zlib
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002337 def test_create_command(self):
2338 self.addCleanup(unlink, TESTFN)
2339 with open(TESTFN, 'w') as f:
2340 f.write('test 1')
2341 os.mkdir(TESTFNDIR)
2342 self.addCleanup(rmtree, TESTFNDIR)
2343 with open(os.path.join(TESTFNDIR, 'file.txt'), 'w') as f:
2344 f.write('test 2')
2345 files = [TESTFN, TESTFNDIR]
2346 namelist = [TESTFN, TESTFNDIR + '/', TESTFNDIR + '/file.txt']
Serhiy Storchaka8c933102016-10-23 13:32:12 +03002347 for opt in '-c', '--create':
2348 try:
2349 out = self.zipfilecmd(opt, TESTFN2, *files)
2350 self.assertEqual(out, b'')
2351 with zipfile.ZipFile(TESTFN2) as zf:
2352 self.assertEqual(zf.namelist(), namelist)
2353 self.assertEqual(zf.read(namelist[0]), b'test 1')
2354 self.assertEqual(zf.read(namelist[2]), b'test 2')
2355 finally:
2356 unlink(TESTFN2)
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002357
2358 def test_extract_command(self):
2359 zip_name = findfile('zipdir.zip')
Serhiy Storchaka8c933102016-10-23 13:32:12 +03002360 for opt in '-e', '--extract':
2361 with temp_dir() as extdir:
2362 out = self.zipfilecmd(opt, zip_name, extdir)
2363 self.assertEqual(out, b'')
2364 with zipfile.ZipFile(zip_name) as zf:
2365 for zi in zf.infolist():
2366 path = os.path.join(extdir,
2367 zi.filename.replace('/', os.sep))
2368 if zi.is_dir():
2369 self.assertTrue(os.path.isdir(path))
2370 else:
2371 self.assertTrue(os.path.isfile(path))
2372 with open(path, 'rb') as f:
2373 self.assertEqual(f.read(), zf.read(zi))
Serhiy Storchaka61c4c442016-10-23 13:07:59 +03002374
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00002375if __name__ == "__main__":
Brett Cannond5b4e1d2013-06-12 19:57:19 -04002376 unittest.main()