blob: b33995566cfa38273b9d9fc7a245e827bebcf0f7 [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 Storchaka503f9082016-02-08 00:02:25 +02005import posixpath
Ezio Melotti35386712009-12-31 13:22:41 +00006import time
Ezio Melotti74c96ec2009-07-08 22:24:06 +00007import struct
8import zipfile
9import unittest
10
Tim Petersa45cacf2004-08-20 03:47:14 +000011
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000012from tempfile import TemporaryFile
Serhiy Storchakafa6bc292013-07-22 21:00:11 +030013from random import randint, random, getrandbits
Tim Petersa19a1682001-03-29 04:36:09 +000014
Victor Stinner57004c62014-09-04 00:49:01 +020015from test.support import (TESTFN, findfile, unlink, rmtree,
Serhiy Storchakac5b75db2013-01-29 20:14:08 +020016 requires_zlib, requires_bz2, requires_lzma,
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +020017 captured_stdout, check_warnings)
Guido van Rossum368f04a2000-04-10 13:23:04 +000018
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000019TESTFN2 = TESTFN + "2"
Martin v. Löwis59e47792009-01-24 14:10:07 +000020TESTFNDIR = TESTFN + "d"
Guido van Rossumb5a755e2007-07-18 18:15:48 +000021FIXEDTEST_SIZE = 1000
Georg Brandl5ba11de2011-01-01 10:09:32 +000022DATAFILES_DIR = 'zipfile_datafiles'
Guido van Rossum368f04a2000-04-10 13:23:04 +000023
Christian Heimes790c8232008-01-07 21:14:23 +000024SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'),
25 ('ziptest2dir/_ziptest2', 'qawsedrftg'),
Gregory P. Smithb47acbf2013-02-01 11:22:43 -080026 ('ziptest2dir/ziptest3dir/_ziptest3', 'azsxdcfvgb'),
Christian Heimes790c8232008-01-07 21:14:23 +000027 ('ziptest2dir/ziptest3dir/ziptest4dir/_ziptest3', '6y7u8i9o0p')]
28
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +020029def getrandbytes(size):
30 return getrandbits(8 * size).to_bytes(size, 'little')
31
Serhiy Storchakafa6bc292013-07-22 21:00:11 +030032def get_files(test):
33 yield TESTFN2
34 with TemporaryFile() as f:
35 yield f
36 test.assertFalse(f.closed)
37 with io.BytesIO() as f:
38 yield f
39 test.assertFalse(f.closed)
Ezio Melotti76430242009-07-11 18:28:48 +000040
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +020041def openU(zipfp, fn):
42 with check_warnings(('', DeprecationWarning)):
43 return zipfp.open(fn, 'rU')
44
Serhiy Storchakafa6bc292013-07-22 21:00:11 +030045class AbstractTestsWithSourceFile:
46 @classmethod
47 def setUpClass(cls):
48 cls.line_gen = [bytes("Zipfile test line %d. random float: %f\n" %
49 (i, random()), "ascii")
50 for i in range(FIXEDTEST_SIZE)]
51 cls.data = b''.join(cls.line_gen)
52
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000053 def setUp(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000054 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +000055 with open(TESTFN, "wb") as fp:
56 fp.write(self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000057
Ezio Melottiafd0d112009-07-15 17:17:17 +000058 def make_test_archive(self, f, compression):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000059 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000060 with zipfile.ZipFile(f, "w", compression) as zipfp:
61 zipfp.write(TESTFN, "another.name")
62 zipfp.write(TESTFN, TESTFN)
63 zipfp.writestr("strfile", self.data)
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +030064 with zipfp.open('written-open-w', mode='w') as f:
65 for line in self.line_gen:
66 f.write(line)
Tim Peters7d3bad62001-04-04 18:56:49 +000067
Ezio Melottiafd0d112009-07-15 17:17:17 +000068 def zip_test(self, f, compression):
69 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +000070
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000071 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000072 with zipfile.ZipFile(f, "r", compression) as zipfp:
73 self.assertEqual(zipfp.read(TESTFN), self.data)
74 self.assertEqual(zipfp.read("another.name"), self.data)
75 self.assertEqual(zipfp.read("strfile"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000076
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000077 # Print the ZIP directory
78 fp = io.StringIO()
79 zipfp.printdir(file=fp)
80 directory = fp.getvalue()
81 lines = directory.splitlines()
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +030082 self.assertEqual(len(lines), 5) # Number of files + header
Thomas Wouters0e3f5912006-08-11 14:57:12 +000083
Benjamin Peterson577473f2010-01-19 00:09:57 +000084 self.assertIn('File Name', lines[0])
85 self.assertIn('Modified', lines[0])
86 self.assertIn('Size', lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +000087
Ezio Melotti35386712009-12-31 13:22:41 +000088 fn, date, time_, size = lines[1].split()
89 self.assertEqual(fn, 'another.name')
90 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
91 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
92 self.assertEqual(size, str(len(self.data)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000093
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000094 # Check the namelist
95 names = zipfp.namelist()
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +030096 self.assertEqual(len(names), 4)
Benjamin Peterson577473f2010-01-19 00:09:57 +000097 self.assertIn(TESTFN, names)
98 self.assertIn("another.name", names)
99 self.assertIn("strfile", names)
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300100 self.assertIn("written-open-w", names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000101
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000102 # Check infolist
103 infos = zipfp.infolist()
Ezio Melotti35386712009-12-31 13:22:41 +0000104 names = [i.filename for i in infos]
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300105 self.assertEqual(len(names), 4)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000106 self.assertIn(TESTFN, names)
107 self.assertIn("another.name", names)
108 self.assertIn("strfile", names)
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300109 self.assertIn("written-open-w", names)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000110 for i in infos:
Ezio Melotti35386712009-12-31 13:22:41 +0000111 self.assertEqual(i.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000112
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000113 # check getinfo
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300114 for nm in (TESTFN, "another.name", "strfile", "written-open-w"):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000115 info = zipfp.getinfo(nm)
Ezio Melotti35386712009-12-31 13:22:41 +0000116 self.assertEqual(info.filename, nm)
117 self.assertEqual(info.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000118
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000119 # Check that testzip doesn't raise an exception
120 zipfp.testzip()
Tim Peters7d3bad62001-04-04 18:56:49 +0000121
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300122 def test_basic(self):
123 for f in get_files(self):
124 self.zip_test(f, self.compression)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000125
Ezio Melottiafd0d112009-07-15 17:17:17 +0000126 def zip_open_test(self, f, compression):
127 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000128
129 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000130 with zipfile.ZipFile(f, "r", compression) as zipfp:
131 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000132 with zipfp.open(TESTFN) as zipopen1:
133 while True:
134 read_data = zipopen1.read(256)
135 if not read_data:
136 break
137 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000138
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000139 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000140 with zipfp.open("another.name") as zipopen2:
141 while True:
142 read_data = zipopen2.read(256)
143 if not read_data:
144 break
145 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000146
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000147 self.assertEqual(b''.join(zipdata1), self.data)
148 self.assertEqual(b''.join(zipdata2), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000149
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300150 def test_open(self):
151 for f in get_files(self):
152 self.zip_open_test(f, self.compression)
Georg Brandlb533e262008-05-25 18:19:30 +0000153
Ezio Melottiafd0d112009-07-15 17:17:17 +0000154 def zip_random_open_test(self, f, compression):
155 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000156
157 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000158 with zipfile.ZipFile(f, "r", compression) as zipfp:
159 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000160 with zipfp.open(TESTFN) as zipopen1:
161 while True:
162 read_data = zipopen1.read(randint(1, 1024))
163 if not read_data:
164 break
165 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000166
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000167 self.assertEqual(b''.join(zipdata1), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000168
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300169 def test_random_open(self):
170 for f in get_files(self):
171 self.zip_random_open_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000172
Serhiy Storchakad2c07a52013-09-27 22:11:57 +0300173 def zip_read1_test(self, f, compression):
174 self.make_test_archive(f, compression)
175
176 # Read the ZIP archive
177 with zipfile.ZipFile(f, "r") as zipfp, \
178 zipfp.open(TESTFN) as zipopen:
179 zipdata = []
180 while True:
181 read_data = zipopen.read1(-1)
182 if not read_data:
183 break
184 zipdata.append(read_data)
185
186 self.assertEqual(b''.join(zipdata), self.data)
187
188 def test_read1(self):
189 for f in get_files(self):
190 self.zip_read1_test(f, self.compression)
191
192 def zip_read1_10_test(self, f, compression):
193 self.make_test_archive(f, compression)
194
195 # Read the ZIP archive
196 with zipfile.ZipFile(f, "r") as zipfp, \
197 zipfp.open(TESTFN) as zipopen:
198 zipdata = []
199 while True:
200 read_data = zipopen.read1(10)
201 self.assertLessEqual(len(read_data), 10)
202 if not read_data:
203 break
204 zipdata.append(read_data)
205
206 self.assertEqual(b''.join(zipdata), self.data)
207
208 def test_read1_10(self):
209 for f in get_files(self):
210 self.zip_read1_10_test(f, self.compression)
211
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000212 def zip_readline_read_test(self, f, compression):
213 self.make_test_archive(f, compression)
214
215 # Read the ZIP archive
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300216 with zipfile.ZipFile(f, "r") as zipfp, \
217 zipfp.open(TESTFN) as zipopen:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000218 data = b''
219 while True:
220 read = zipopen.readline()
221 if not read:
222 break
223 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000224
Brian Curtin8fb9b862010-11-18 02:15:28 +0000225 read = zipopen.read(100)
226 if not read:
227 break
228 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000229
230 self.assertEqual(data, self.data)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300231
232 def test_readline_read(self):
233 # Issue #7610: calls to readline() interleaved with calls to read().
234 for f in get_files(self):
235 self.zip_readline_read_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000236
Ezio Melottiafd0d112009-07-15 17:17:17 +0000237 def zip_readline_test(self, f, compression):
238 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000239
240 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000241 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000242 with zipfp.open(TESTFN) as zipopen:
243 for line in self.line_gen:
244 linedata = zipopen.readline()
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300245 self.assertEqual(linedata, line)
246
247 def test_readline(self):
248 for f in get_files(self):
249 self.zip_readline_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000250
Ezio Melottiafd0d112009-07-15 17:17:17 +0000251 def zip_readlines_test(self, f, compression):
252 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000253
254 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000255 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000256 with zipfp.open(TESTFN) as zipopen:
257 ziplines = zipopen.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000258 for line, zipline in zip(self.line_gen, ziplines):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300259 self.assertEqual(zipline, line)
260
261 def test_readlines(self):
262 for f in get_files(self):
263 self.zip_readlines_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000264
Ezio Melottiafd0d112009-07-15 17:17:17 +0000265 def zip_iterlines_test(self, f, compression):
266 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000267
268 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000269 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000270 with zipfp.open(TESTFN) as zipopen:
271 for line, zipline in zip(self.line_gen, zipopen):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300272 self.assertEqual(zipline, line)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000273
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300274 def test_iterlines(self):
275 for f in get_files(self):
276 self.zip_iterlines_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000277
Ezio Melottiafd0d112009-07-15 17:17:17 +0000278 def test_low_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000279 """Check for cases where compressed data is larger than original."""
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000280 # Create the ZIP archive
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300281 with zipfile.ZipFile(TESTFN2, "w", self.compression) as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000282 zipfp.writestr("strfile", '12')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000283
284 # Get an open object for strfile
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300285 with zipfile.ZipFile(TESTFN2, "r", self.compression) as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000286 with zipfp.open("strfile") as openobj:
287 self.assertEqual(openobj.read(1), b'1')
288 self.assertEqual(openobj.read(1), b'2')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000289
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300290 def test_writestr_compression(self):
291 zipfp = zipfile.ZipFile(TESTFN2, "w")
292 zipfp.writestr("b.txt", "hello world", compress_type=self.compression)
293 info = zipfp.getinfo('b.txt')
294 self.assertEqual(info.compress_type, self.compression)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200295
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300296 def test_read_return_size(self):
297 # Issue #9837: ZipExtFile.read() shouldn't return more bytes
298 # than requested.
299 for test_size in (1, 4095, 4096, 4097, 16384):
300 file_size = test_size + 1
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +0200301 junk = getrandbytes(file_size)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300302 with zipfile.ZipFile(io.BytesIO(), "w", self.compression) as zipf:
303 zipf.writestr('foo', junk)
304 with zipf.open('foo', 'r') as fp:
305 buf = fp.read(test_size)
306 self.assertEqual(len(buf), test_size)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200307
Serhiy Storchaka5ce3f102014-01-09 14:50:20 +0200308 def test_truncated_zipfile(self):
309 fp = io.BytesIO()
310 with zipfile.ZipFile(fp, mode='w') as zipf:
311 zipf.writestr('strfile', self.data, compress_type=self.compression)
312 end_offset = fp.tell()
313 zipfiledata = fp.getvalue()
314
315 fp = io.BytesIO(zipfiledata)
316 with zipfile.ZipFile(fp) as zipf:
317 with zipf.open('strfile') as zipopen:
318 fp.truncate(end_offset - 20)
319 with self.assertRaises(EOFError):
320 zipopen.read()
321
322 fp = io.BytesIO(zipfiledata)
323 with zipfile.ZipFile(fp) as zipf:
324 with zipf.open('strfile') as zipopen:
325 fp.truncate(end_offset - 20)
326 with self.assertRaises(EOFError):
327 while zipopen.read(100):
328 pass
329
330 fp = io.BytesIO(zipfiledata)
331 with zipfile.ZipFile(fp) as zipf:
332 with zipf.open('strfile') as zipopen:
333 fp.truncate(end_offset - 20)
334 with self.assertRaises(EOFError):
335 while zipopen.read1(100):
336 pass
337
Serhiy Storchaka51a43702014-10-29 22:42:06 +0200338 def test_repr(self):
339 fname = 'file.name'
340 for f in get_files(self):
341 with zipfile.ZipFile(f, 'w', self.compression) as zipfp:
342 zipfp.write(TESTFN, fname)
343 r = repr(zipfp)
344 self.assertIn("mode='w'", r)
345
346 with zipfile.ZipFile(f, 'r') as zipfp:
347 r = repr(zipfp)
348 if isinstance(f, str):
349 self.assertIn('filename=%r' % f, r)
350 else:
351 self.assertIn('file=%r' % f, r)
352 self.assertIn("mode='r'", r)
353 r = repr(zipfp.getinfo(fname))
354 self.assertIn('filename=%r' % fname, r)
355 self.assertIn('filemode=', r)
356 self.assertIn('file_size=', r)
357 if self.compression != zipfile.ZIP_STORED:
358 self.assertIn('compress_type=', r)
359 self.assertIn('compress_size=', r)
360 with zipfp.open(fname) as zipopen:
361 r = repr(zipopen)
362 self.assertIn('name=%r' % fname, r)
363 self.assertIn("mode='r'", r)
364 if self.compression != zipfile.ZIP_STORED:
365 self.assertIn('compress_type=', r)
366 self.assertIn('[closed]', repr(zipopen))
367 self.assertIn('[closed]', repr(zipfp))
368
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300369 def tearDown(self):
370 unlink(TESTFN)
371 unlink(TESTFN2)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200372
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200373
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300374class StoredTestsWithSourceFile(AbstractTestsWithSourceFile,
375 unittest.TestCase):
376 compression = zipfile.ZIP_STORED
377 test_low_compression = None
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200378
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300379 def zip_test_writestr_permissions(self, f, compression):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300380 # Make sure that writestr and open(... mode='w') create files with
381 # mode 0600, when they are passed a name rather than a ZipInfo
382 # instance.
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200383
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300384 self.make_test_archive(f, compression)
385 with zipfile.ZipFile(f, "r") as zipfp:
386 zinfo = zipfp.getinfo('strfile')
387 self.assertEqual(zinfo.external_attr, 0o600 << 16)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200388
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300389 zinfo2 = zipfp.getinfo('written-open-w')
390 self.assertEqual(zinfo2.external_attr, 0o600 << 16)
391
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300392 def test_writestr_permissions(self):
393 for f in get_files(self):
394 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +0200395
Ezio Melottiafd0d112009-07-15 17:17:17 +0000396 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000397 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
398 zipfp.write(TESTFN, "/absolute")
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000399
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000400 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
401 self.assertEqual(zipfp.namelist(), ["absolute"])
Tim Peters32cbc962006-02-20 21:42:18 +0000402
Ezio Melottiafd0d112009-07-15 17:17:17 +0000403 def test_append_to_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000404 """Test appending to an existing zipfile."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000405 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
406 zipfp.write(TESTFN, TESTFN)
407
408 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
409 zipfp.writestr("strfile", self.data)
410 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000411
Ezio Melottiafd0d112009-07-15 17:17:17 +0000412 def test_append_to_non_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000413 """Test appending to an existing file that is not a zipfile."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000414 # NOTE: this test fails if len(d) < 22 because of the first
415 # line "fpin.seek(-22, 2)" in _EndRecData
Ezio Melotti35386712009-12-31 13:22:41 +0000416 data = b'I am not a ZipFile!'*10
417 with open(TESTFN2, 'wb') as f:
418 f.write(data)
419
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000420 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
421 zipfp.write(TESTFN, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000422
Ezio Melotti35386712009-12-31 13:22:41 +0000423 with open(TESTFN2, 'rb') as f:
424 f.seek(len(data))
425 with zipfile.ZipFile(f, "r") as zipfp:
426 self.assertEqual(zipfp.namelist(), [TESTFN])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000427
R David Murray4fbb9db2011-06-09 15:50:51 -0400428 def test_ignores_newline_at_end(self):
429 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
430 zipfp.write(TESTFN, TESTFN)
431 with open(TESTFN2, 'a') as f:
432 f.write("\r\n\00\00\00")
433 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
434 self.assertIsInstance(zipfp, zipfile.ZipFile)
435
436 def test_ignores_stuff_appended_past_comments(self):
437 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
438 zipfp.comment = b"this is a comment"
439 zipfp.write(TESTFN, TESTFN)
440 with open(TESTFN2, 'a') as f:
441 f.write("abcdef\r\n")
442 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
443 self.assertIsInstance(zipfp, zipfile.ZipFile)
444 self.assertEqual(zipfp.comment, b"this is a comment")
445
Ezio Melottiafd0d112009-07-15 17:17:17 +0000446 def test_write_default_name(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000447 """Check that calling ZipFile.write without arcname specified
448 produces the expected result."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000449 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
450 zipfp.write(TESTFN)
Brian Curtin8fb9b862010-11-18 02:15:28 +0000451 with open(TESTFN, "rb") as f:
452 self.assertEqual(zipfp.read(TESTFN), f.read())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000453
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300454 def test_write_to_readonly(self):
455 """Check that trying to call write() on a readonly ZipFile object
456 raises a RuntimeError."""
457 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
458 zipfp.writestr("somefile.txt", "bogus")
459
460 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
461 self.assertRaises(RuntimeError, zipfp.write, TESTFN)
462
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300463 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
464 with self.assertRaises(RuntimeError):
465 zipfp.open(TESTFN, mode='w')
466
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300467 def test_add_file_before_1980(self):
468 # Set atime and mtime to 1970-01-01
469 os.utime(TESTFN, (0, 0))
470 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
471 self.assertRaises(ValueError, zipfp.write, TESTFN)
472
Serhiy Storchaka5ce3f102014-01-09 14:50:20 +0200473
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300474@requires_zlib
475class DeflateTestsWithSourceFile(AbstractTestsWithSourceFile,
476 unittest.TestCase):
477 compression = zipfile.ZIP_DEFLATED
478
Ezio Melottiafd0d112009-07-15 17:17:17 +0000479 def test_per_file_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000480 """Check that files within a Zip archive can have different
481 compression options."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000482 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
483 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
484 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
485 sinfo = zipfp.getinfo('storeme')
486 dinfo = zipfp.getinfo('deflateme')
487 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
488 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000489
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300490@requires_bz2
491class Bzip2TestsWithSourceFile(AbstractTestsWithSourceFile,
492 unittest.TestCase):
493 compression = zipfile.ZIP_BZIP2
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000494
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300495@requires_lzma
496class LzmaTestsWithSourceFile(AbstractTestsWithSourceFile,
497 unittest.TestCase):
498 compression = zipfile.ZIP_LZMA
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000499
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300500
501class AbstractTestZip64InSmallFiles:
502 # These tests test the ZIP64 functionality without using large files,
503 # see test_zipfile64 for proper tests.
504
505 @classmethod
506 def setUpClass(cls):
507 line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
508 for i in range(0, FIXEDTEST_SIZE))
509 cls.data = b'\n'.join(line_gen)
510
511 def setUp(self):
512 self._limit = zipfile.ZIP64_LIMIT
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300513 self._filecount_limit = zipfile.ZIP_FILECOUNT_LIMIT
514 zipfile.ZIP64_LIMIT = 1000
515 zipfile.ZIP_FILECOUNT_LIMIT = 9
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300516
517 # Make a source file with some lines
518 with open(TESTFN, "wb") as fp:
519 fp.write(self.data)
520
521 def zip_test(self, f, compression):
522 # Create the ZIP archive
523 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
524 zipfp.write(TESTFN, "another.name")
525 zipfp.write(TESTFN, TESTFN)
526 zipfp.writestr("strfile", self.data)
527
528 # Read the ZIP archive
529 with zipfile.ZipFile(f, "r", compression) as zipfp:
530 self.assertEqual(zipfp.read(TESTFN), self.data)
531 self.assertEqual(zipfp.read("another.name"), self.data)
532 self.assertEqual(zipfp.read("strfile"), self.data)
533
534 # Print the ZIP directory
535 fp = io.StringIO()
536 zipfp.printdir(fp)
537
538 directory = fp.getvalue()
539 lines = directory.splitlines()
540 self.assertEqual(len(lines), 4) # Number of files + header
541
542 self.assertIn('File Name', lines[0])
543 self.assertIn('Modified', lines[0])
544 self.assertIn('Size', lines[0])
545
546 fn, date, time_, size = lines[1].split()
547 self.assertEqual(fn, 'another.name')
548 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
549 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
550 self.assertEqual(size, str(len(self.data)))
551
552 # Check the namelist
553 names = zipfp.namelist()
554 self.assertEqual(len(names), 3)
555 self.assertIn(TESTFN, names)
556 self.assertIn("another.name", names)
557 self.assertIn("strfile", names)
558
559 # Check infolist
560 infos = zipfp.infolist()
561 names = [i.filename for i in infos]
562 self.assertEqual(len(names), 3)
563 self.assertIn(TESTFN, names)
564 self.assertIn("another.name", names)
565 self.assertIn("strfile", names)
566 for i in infos:
567 self.assertEqual(i.file_size, len(self.data))
568
569 # check getinfo
570 for nm in (TESTFN, "another.name", "strfile"):
571 info = zipfp.getinfo(nm)
572 self.assertEqual(info.filename, nm)
573 self.assertEqual(info.file_size, len(self.data))
574
575 # Check that testzip doesn't raise an exception
576 zipfp.testzip()
577
578 def test_basic(self):
579 for f in get_files(self):
580 self.zip_test(f, self.compression)
581
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300582 def test_too_many_files(self):
583 # This test checks that more than 64k files can be added to an archive,
584 # and that the resulting archive can be read properly by ZipFile
585 zipf = zipfile.ZipFile(TESTFN, "w", self.compression,
586 allowZip64=True)
587 zipf.debug = 100
588 numfiles = 15
589 for i in range(numfiles):
590 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
591 self.assertEqual(len(zipf.namelist()), numfiles)
592 zipf.close()
593
594 zipf2 = zipfile.ZipFile(TESTFN, "r", self.compression)
595 self.assertEqual(len(zipf2.namelist()), numfiles)
596 for i in range(numfiles):
597 content = zipf2.read("foo%08d" % i).decode('ascii')
598 self.assertEqual(content, "%d" % (i**3 % 57))
599 zipf2.close()
600
601 def test_too_many_files_append(self):
602 zipf = zipfile.ZipFile(TESTFN, "w", self.compression,
603 allowZip64=False)
604 zipf.debug = 100
605 numfiles = 9
606 for i in range(numfiles):
607 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
608 self.assertEqual(len(zipf.namelist()), numfiles)
609 with self.assertRaises(zipfile.LargeZipFile):
610 zipf.writestr("foo%08d" % numfiles, b'')
611 self.assertEqual(len(zipf.namelist()), numfiles)
612 zipf.close()
613
614 zipf = zipfile.ZipFile(TESTFN, "a", self.compression,
615 allowZip64=False)
616 zipf.debug = 100
617 self.assertEqual(len(zipf.namelist()), numfiles)
618 with self.assertRaises(zipfile.LargeZipFile):
619 zipf.writestr("foo%08d" % numfiles, b'')
620 self.assertEqual(len(zipf.namelist()), numfiles)
621 zipf.close()
622
623 zipf = zipfile.ZipFile(TESTFN, "a", self.compression,
624 allowZip64=True)
625 zipf.debug = 100
626 self.assertEqual(len(zipf.namelist()), numfiles)
627 numfiles2 = 15
628 for i in range(numfiles, numfiles2):
629 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
630 self.assertEqual(len(zipf.namelist()), numfiles2)
631 zipf.close()
632
633 zipf2 = zipfile.ZipFile(TESTFN, "r", self.compression)
634 self.assertEqual(len(zipf2.namelist()), numfiles2)
635 for i in range(numfiles2):
636 content = zipf2.read("foo%08d" % i).decode('ascii')
637 self.assertEqual(content, "%d" % (i**3 % 57))
638 zipf2.close()
639
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300640 def tearDown(self):
641 zipfile.ZIP64_LIMIT = self._limit
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300642 zipfile.ZIP_FILECOUNT_LIMIT = self._filecount_limit
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300643 unlink(TESTFN)
644 unlink(TESTFN2)
645
646
647class StoredTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
648 unittest.TestCase):
649 compression = zipfile.ZIP_STORED
650
651 def large_file_exception_test(self, f, compression):
Serhiy Storchaka235c5e02013-11-23 15:55:38 +0200652 with zipfile.ZipFile(f, "w", compression, allowZip64=False) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300653 self.assertRaises(zipfile.LargeZipFile,
654 zipfp.write, TESTFN, "another.name")
655
656 def large_file_exception_test2(self, f, compression):
Serhiy Storchaka235c5e02013-11-23 15:55:38 +0200657 with zipfile.ZipFile(f, "w", compression, allowZip64=False) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300658 self.assertRaises(zipfile.LargeZipFile,
659 zipfp.writestr, "another.name", self.data)
660
661 def test_large_file_exception(self):
662 for f in get_files(self):
663 self.large_file_exception_test(f, zipfile.ZIP_STORED)
664 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
665
666 def test_absolute_arcnames(self):
667 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
668 allowZip64=True) as zipfp:
669 zipfp.write(TESTFN, "/absolute")
670
671 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
672 self.assertEqual(zipfp.namelist(), ["absolute"])
673
674@requires_zlib
675class DeflateTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
676 unittest.TestCase):
677 compression = zipfile.ZIP_DEFLATED
678
679@requires_bz2
680class Bzip2TestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
681 unittest.TestCase):
682 compression = zipfile.ZIP_BZIP2
683
684@requires_lzma
685class LzmaTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
686 unittest.TestCase):
687 compression = zipfile.ZIP_LZMA
688
689
690class PyZipFileTests(unittest.TestCase):
691 def assertCompiledIn(self, name, namelist):
692 if name + 'o' not in namelist:
693 self.assertIn(name + 'c', namelist)
694
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200695 def requiresWriteAccess(self, path):
Berker Peksage1efc072015-02-16 04:36:18 +0200696 # effective_ids unavailable on windows
697 if not os.access(path, os.W_OK,
698 effective_ids=os.access in os.supports_effective_ids):
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200699 self.skipTest('requires write access to the installed location')
Serhiy Storchakad86a6ef2015-09-19 10:55:20 +0300700 filename = os.path.join(path, 'test_zipfile.try')
701 try:
702 fd = os.open(filename, os.O_WRONLY | os.O_CREAT)
703 os.close(fd)
704 except Exception:
705 self.skipTest('requires write access to the installed location')
706 unlink(filename)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200707
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300708 def test_write_pyfile(self):
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200709 self.requiresWriteAccess(os.path.dirname(__file__))
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300710 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
711 fn = __file__
Brett Cannonf299abd2015-04-13 14:21:02 -0400712 if fn.endswith('.pyc'):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300713 path_split = fn.split(os.sep)
714 if os.altsep is not None:
715 path_split.extend(fn.split(os.altsep))
716 if '__pycache__' in path_split:
Serhiy Storchaka9068e4d2013-07-22 21:02:14 +0300717 fn = importlib.util.source_from_cache(fn)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300718 else:
719 fn = fn[:-1]
720
721 zipfp.writepy(fn)
722
723 bn = os.path.basename(fn)
724 self.assertNotIn(bn, zipfp.namelist())
725 self.assertCompiledIn(bn, zipfp.namelist())
726
727 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
728 fn = __file__
Brett Cannonf299abd2015-04-13 14:21:02 -0400729 if fn.endswith('.pyc'):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300730 fn = fn[:-1]
731
732 zipfp.writepy(fn, "testpackage")
733
734 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
735 self.assertNotIn(bn, zipfp.namelist())
736 self.assertCompiledIn(bn, zipfp.namelist())
737
738 def test_write_python_package(self):
739 import email
740 packagedir = os.path.dirname(email.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200741 self.requiresWriteAccess(packagedir)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300742
743 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
744 zipfp.writepy(packagedir)
745
746 # Check for a couple of modules at different levels of the
747 # hierarchy
748 names = zipfp.namelist()
749 self.assertCompiledIn('email/__init__.py', names)
750 self.assertCompiledIn('email/mime/text.py', names)
751
Christian Tismer59202e52013-10-21 03:59:23 +0200752 def test_write_filtered_python_package(self):
753 import test
754 packagedir = os.path.dirname(test.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200755 self.requiresWriteAccess(packagedir)
Christian Tismer59202e52013-10-21 03:59:23 +0200756
757 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
758
Christian Tismer59202e52013-10-21 03:59:23 +0200759 # first make sure that the test folder gives error messages
Georg Brandla6065422013-10-21 08:29:29 +0200760 # (on the badsyntax_... files)
761 with captured_stdout() as reportSIO:
762 zipfp.writepy(packagedir)
Christian Tismer59202e52013-10-21 03:59:23 +0200763 reportStr = reportSIO.getvalue()
764 self.assertTrue('SyntaxError' in reportStr)
765
Christian Tismer410d9312013-10-22 04:09:28 +0200766 # then check that the filter works on the whole package
Georg Brandla6065422013-10-21 08:29:29 +0200767 with captured_stdout() as reportSIO:
768 zipfp.writepy(packagedir, filterfunc=lambda whatever: False)
Christian Tismer59202e52013-10-21 03:59:23 +0200769 reportStr = reportSIO.getvalue()
770 self.assertTrue('SyntaxError' not in reportStr)
771
Christian Tismer410d9312013-10-22 04:09:28 +0200772 # then check that the filter works on individual files
Larry Hastings7e63b362015-05-08 06:54:58 -0700773 def filter(path):
774 return not os.path.basename(path).startswith("bad")
Serhiy Storchakac46d1fa2014-01-20 21:59:33 +0200775 with captured_stdout() as reportSIO, self.assertWarns(UserWarning):
Larry Hastings7e63b362015-05-08 06:54:58 -0700776 zipfp.writepy(packagedir, filterfunc=filter)
Christian Tismer410d9312013-10-22 04:09:28 +0200777 reportStr = reportSIO.getvalue()
778 if reportStr:
779 print(reportStr)
780 self.assertTrue('SyntaxError' not in reportStr)
781
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300782 def test_write_with_optimization(self):
783 import email
784 packagedir = os.path.dirname(email.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200785 self.requiresWriteAccess(packagedir)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300786 optlevel = 1 if __debug__ else 0
Brett Cannonf299abd2015-04-13 14:21:02 -0400787 ext = '.pyc'
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300788
789 with TemporaryFile() as t, \
Christian Tismer59202e52013-10-21 03:59:23 +0200790 zipfile.PyZipFile(t, "w", optimize=optlevel) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300791 zipfp.writepy(packagedir)
792
793 names = zipfp.namelist()
794 self.assertIn('email/__init__' + ext, names)
795 self.assertIn('email/mime/text' + ext, names)
796
797 def test_write_python_directory(self):
798 os.mkdir(TESTFN2)
799 try:
800 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
801 fp.write("print(42)\n")
802
803 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
804 fp.write("print(42 * 42)\n")
805
806 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
807 fp.write("bla bla bla\n")
808
809 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
810 zipfp.writepy(TESTFN2)
811
812 names = zipfp.namelist()
813 self.assertCompiledIn('mod1.py', names)
814 self.assertCompiledIn('mod2.py', names)
815 self.assertNotIn('mod2.txt', names)
816
817 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200818 rmtree(TESTFN2)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300819
Christian Tismer410d9312013-10-22 04:09:28 +0200820 def test_write_python_directory_filtered(self):
821 os.mkdir(TESTFN2)
822 try:
823 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
824 fp.write("print(42)\n")
825
826 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
827 fp.write("print(42 * 42)\n")
828
829 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
830 zipfp.writepy(TESTFN2, filterfunc=lambda fn:
831 not fn.endswith('mod2.py'))
832
833 names = zipfp.namelist()
834 self.assertCompiledIn('mod1.py', names)
835 self.assertNotIn('mod2.py', names)
836
837 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200838 rmtree(TESTFN2)
Christian Tismer410d9312013-10-22 04:09:28 +0200839
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300840 def test_write_non_pyfile(self):
841 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
842 with open(TESTFN, 'w') as f:
843 f.write('most definitely not a python file')
844 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
Victor Stinner88b215e2014-09-04 00:51:09 +0200845 unlink(TESTFN)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300846
847 def test_write_pyfile_bad_syntax(self):
848 os.mkdir(TESTFN2)
849 try:
850 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
851 fp.write("Bad syntax in python file\n")
852
853 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
854 # syntax errors are printed to stdout
855 with captured_stdout() as s:
856 zipfp.writepy(os.path.join(TESTFN2, "mod1.py"))
857
858 self.assertIn("SyntaxError", s.getvalue())
859
860 # as it will not have compiled the python file, it will
Brett Cannonf299abd2015-04-13 14:21:02 -0400861 # include the .py file not .pyc
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300862 names = zipfp.namelist()
863 self.assertIn('mod1.py', names)
864 self.assertNotIn('mod1.pyc', names)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300865
866 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200867 rmtree(TESTFN2)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300868
869
870class ExtractTests(unittest.TestCase):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000871 def test_extract(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000872 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
873 for fpath, fdata in SMALL_TEST_DATA:
874 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000875
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000876 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
877 for fpath, fdata in SMALL_TEST_DATA:
878 writtenfile = zipfp.extract(fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000879
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000880 # make sure it was written to the right place
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800881 correctfile = os.path.join(os.getcwd(), fpath)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000882 correctfile = os.path.normpath(correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000883
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000884 self.assertEqual(writtenfile, correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000885
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000886 # make sure correct data is in correct file
Brian Curtin8fb9b862010-11-18 02:15:28 +0000887 with open(writtenfile, "rb") as f:
888 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000889
Victor Stinner88b215e2014-09-04 00:51:09 +0200890 unlink(writtenfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000891
892 # remove the test file subdirectories
Victor Stinner57004c62014-09-04 00:49:01 +0200893 rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
Christian Heimes790c8232008-01-07 21:14:23 +0000894
Ezio Melottiafd0d112009-07-15 17:17:17 +0000895 def test_extract_all(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000896 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
897 for fpath, fdata in SMALL_TEST_DATA:
898 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000899
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000900 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
901 zipfp.extractall()
902 for fpath, fdata in SMALL_TEST_DATA:
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800903 outfile = os.path.join(os.getcwd(), fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000904
Brian Curtin8fb9b862010-11-18 02:15:28 +0000905 with open(outfile, "rb") as f:
906 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000907
Victor Stinner88b215e2014-09-04 00:51:09 +0200908 unlink(outfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000909
910 # remove the test file subdirectories
Victor Stinner57004c62014-09-04 00:49:01 +0200911 rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
Christian Heimes790c8232008-01-07 21:14:23 +0000912
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800913 def check_file(self, filename, content):
914 self.assertTrue(os.path.isfile(filename))
915 with open(filename, 'rb') as f:
916 self.assertEqual(f.read(), content)
917
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800918 def test_sanitize_windows_name(self):
919 san = zipfile.ZipFile._sanitize_windows_name
920 # Passing pathsep in allows this test to work regardless of platform.
921 self.assertEqual(san(r',,?,C:,foo,bar/z', ','), r'_,C_,foo,bar/z')
922 self.assertEqual(san(r'a\b,c<d>e|f"g?h*i', ','), r'a\b,c_d_e_f_g_h_i')
923 self.assertEqual(san('../../foo../../ba..r', '/'), r'foo/ba..r')
924
925 def test_extract_hackers_arcnames_common_cases(self):
926 common_hacknames = [
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800927 ('../foo/bar', 'foo/bar'),
928 ('foo/../bar', 'foo/bar'),
929 ('foo/../../bar', 'foo/bar'),
930 ('foo/bar/..', 'foo/bar'),
931 ('./../foo/bar', 'foo/bar'),
932 ('/foo/bar', 'foo/bar'),
933 ('/foo/../bar', 'foo/bar'),
934 ('/foo/../../bar', 'foo/bar'),
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800935 ]
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800936 self._test_extract_hackers_arcnames(common_hacknames)
937
938 @unittest.skipIf(os.path.sep != '\\', 'Requires \\ as path separator.')
939 def test_extract_hackers_arcnames_windows_only(self):
940 """Test combination of path fixing and windows name sanitization."""
941 windows_hacknames = [
Christian Tismer59202e52013-10-21 03:59:23 +0200942 (r'..\foo\bar', 'foo/bar'),
943 (r'..\/foo\/bar', 'foo/bar'),
944 (r'foo/\..\/bar', 'foo/bar'),
945 (r'foo\/../\bar', 'foo/bar'),
946 (r'C:foo/bar', 'foo/bar'),
947 (r'C:/foo/bar', 'foo/bar'),
948 (r'C://foo/bar', 'foo/bar'),
949 (r'C:\foo\bar', 'foo/bar'),
950 (r'//conky/mountpoint/foo/bar', 'foo/bar'),
951 (r'\\conky\mountpoint\foo\bar', 'foo/bar'),
952 (r'///conky/mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
953 (r'\\\conky\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
954 (r'//conky//mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
955 (r'\\conky\\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
956 (r'//?/C:/foo/bar', 'foo/bar'),
957 (r'\\?\C:\foo\bar', 'foo/bar'),
958 (r'C:/../C:/foo/bar', 'C_/foo/bar'),
959 (r'a:b\c<d>e|f"g?h*i', 'b/c_d_e_f_g_h_i'),
960 ('../../foo../../ba..r', 'foo/ba..r'),
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800961 ]
962 self._test_extract_hackers_arcnames(windows_hacknames)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800963
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800964 @unittest.skipIf(os.path.sep != '/', r'Requires / as path separator.')
965 def test_extract_hackers_arcnames_posix_only(self):
966 posix_hacknames = [
967 ('//foo/bar', 'foo/bar'),
968 ('../../foo../../ba..r', 'foo../ba..r'),
969 (r'foo/..\bar', r'foo/..\bar'),
970 ]
971 self._test_extract_hackers_arcnames(posix_hacknames)
972
973 def _test_extract_hackers_arcnames(self, hacknames):
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800974 for arcname, fixedname in hacknames:
975 content = b'foobar' + arcname.encode()
976 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipfp:
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200977 zinfo = zipfile.ZipInfo()
978 # preserve backslashes
979 zinfo.filename = arcname
980 zinfo.external_attr = 0o600 << 16
981 zipfp.writestr(zinfo, content)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800982
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200983 arcname = arcname.replace(os.sep, "/")
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800984 targetpath = os.path.join('target', 'subdir', 'subsub')
985 correctfile = os.path.join(targetpath, *fixedname.split('/'))
986
987 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
988 writtenfile = zipfp.extract(arcname, targetpath)
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200989 self.assertEqual(writtenfile, correctfile,
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800990 msg='extract %r: %r != %r' %
991 (arcname, writtenfile, correctfile))
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800992 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +0200993 rmtree('target')
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800994
995 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
996 zipfp.extractall(targetpath)
997 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +0200998 rmtree('target')
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800999
1000 correctfile = os.path.join(os.getcwd(), *fixedname.split('/'))
1001
1002 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1003 writtenfile = zipfp.extract(arcname)
Serhiy Storchakae5e64442013-02-02 19:50:59 +02001004 self.assertEqual(writtenfile, correctfile,
1005 msg="extract %r" % arcname)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001006 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001007 rmtree(fixedname.split('/')[0])
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001008
1009 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1010 zipfp.extractall()
1011 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001012 rmtree(fixedname.split('/')[0])
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001013
Victor Stinner88b215e2014-09-04 00:51:09 +02001014 unlink(TESTFN2)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001015
Ronald Oussorenee5c8852010-02-07 20:24:02 +00001016
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001017class OtherTests(unittest.TestCase):
1018 def test_open_via_zip_info(self):
1019 # Create the ZIP archive
1020 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
1021 zipfp.writestr("name", "foo")
Serhiy Storchaka9b7a1a12014-01-20 21:57:40 +02001022 with self.assertWarns(UserWarning):
1023 zipfp.writestr("name", "bar")
1024 self.assertEqual(zipfp.namelist(), ["name"] * 2)
Ronald Oussorenee5c8852010-02-07 20:24:02 +00001025
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001026 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1027 infos = zipfp.infolist()
1028 data = b""
1029 for info in infos:
1030 with zipfp.open(info) as zipopen:
1031 data += zipopen.read()
1032 self.assertIn(data, {b"foobar", b"barfoo"})
1033 data = b""
1034 for info in infos:
1035 data += zipfp.read(info)
1036 self.assertIn(data, {b"foobar", b"barfoo"})
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001037
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02001038 def test_universal_deprecation(self):
1039 f = io.BytesIO()
1040 with zipfile.ZipFile(f, "w") as zipfp:
1041 zipfp.writestr('spam.txt', b'ababagalamaga')
1042
1043 with zipfile.ZipFile(f, "r") as zipfp:
1044 for mode in 'U', 'rU':
1045 with self.assertWarns(DeprecationWarning):
1046 zipopen = zipfp.open('spam.txt', mode)
1047 zipopen.close()
1048
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001049 def test_universal_readaheads(self):
1050 f = io.BytesIO()
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001051
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001052 data = b'a\r\n' * 16 * 1024
1053 with zipfile.ZipFile(f, 'w', zipfile.ZIP_STORED) as zipfp:
1054 zipfp.writestr(TESTFN, data)
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +00001055
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001056 data2 = b''
1057 with zipfile.ZipFile(f, 'r') as zipfp, \
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02001058 openU(zipfp, TESTFN) as zipopen:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001059 for line in zipopen:
1060 data2 += line
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +00001061
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001062 self.assertEqual(data, data2.replace(b'\n', b'\r\n'))
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +00001063
Gregory P. Smithb0d9ca92009-07-07 05:06:04 +00001064 def test_writestr_extended_local_header_issue1202(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001065 with zipfile.ZipFile(TESTFN2, 'w') as orig_zip:
1066 for data in 'abcdefghijklmnop':
1067 zinfo = zipfile.ZipInfo(data)
1068 zinfo.flag_bits |= 0x08 # Include an extended local header.
1069 orig_zip.writestr(zinfo, data)
1070
1071 def test_close(self):
1072 """Check that the zipfile is closed after the 'with' block."""
1073 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
1074 for fpath, fdata in SMALL_TEST_DATA:
1075 zipfp.writestr(fpath, fdata)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001076 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
1077 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001078
1079 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001080 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
1081 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001082
1083 def test_close_on_exception(self):
1084 """Check that the zipfile is closed if an exception is raised in the
1085 'with' block."""
1086 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
1087 for fpath, fdata in SMALL_TEST_DATA:
1088 zipfp.writestr(fpath, fdata)
1089
1090 try:
1091 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
Georg Brandl4d540882010-10-28 06:42:33 +00001092 raise zipfile.BadZipFile()
1093 except zipfile.BadZipFile:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001094 self.assertIsNone(zipfp2.fp, 'zipfp is not closed')
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001095
Martin v. Löwisd099b562012-05-01 14:08:22 +02001096 def test_unsupported_version(self):
1097 # File has an extract_version of 120
1098 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 +02001099 b'\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00xPK\x01\x02x\x03x\x00\x00\x00\x00'
1100 b'\x00!p\xa1@\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00'
1101 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00\x00xPK\x05\x06'
1102 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 +03001103
Martin v. Löwisd099b562012-05-01 14:08:22 +02001104 self.assertRaises(NotImplementedError, zipfile.ZipFile,
1105 io.BytesIO(data), 'r')
1106
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001107 @requires_zlib
1108 def test_read_unicode_filenames(self):
1109 # bug #10801
1110 fname = findfile('zip_cp437_header.zip')
1111 with zipfile.ZipFile(fname) as zipfp:
1112 for name in zipfp.namelist():
1113 zipfp.open(name).close()
1114
1115 def test_write_unicode_filenames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001116 with zipfile.ZipFile(TESTFN, "w") as zf:
1117 zf.writestr("foo.txt", "Test for unicode filename")
1118 zf.writestr("\xf6.txt", "Test for unicode filename")
Ezio Melottie9615932010-01-24 19:26:24 +00001119 self.assertIsInstance(zf.infolist()[0].filename, str)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001120
1121 with zipfile.ZipFile(TESTFN, "r") as zf:
1122 self.assertEqual(zf.filelist[0].filename, "foo.txt")
1123 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
Martin v. Löwis8570f6a2008-05-05 17:44:38 +00001124
Serhiy Storchaka764fc9b2015-03-25 10:09:41 +02001125 def test_exclusive_create_zip_file(self):
1126 """Test exclusive creating a new zipfile."""
1127 unlink(TESTFN2)
1128 filename = 'testfile.txt'
1129 content = b'hello, world. this is some content.'
1130 with zipfile.ZipFile(TESTFN2, "x", zipfile.ZIP_STORED) as zipfp:
1131 zipfp.writestr(filename, content)
1132 with self.assertRaises(FileExistsError):
1133 zipfile.ZipFile(TESTFN2, "x", zipfile.ZIP_STORED)
1134 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1135 self.assertEqual(zipfp.namelist(), [filename])
1136 self.assertEqual(zipfp.read(filename), content)
1137
Ezio Melottiafd0d112009-07-15 17:17:17 +00001138 def test_create_non_existent_file_for_append(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001139 if os.path.exists(TESTFN):
1140 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001141
Thomas Wouterscf297e42007-02-23 15:07:44 +00001142 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001143 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +00001144
Thomas Wouterscf297e42007-02-23 15:07:44 +00001145 try:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001146 with zipfile.ZipFile(TESTFN, 'a') as zf:
1147 zf.writestr(filename, content)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001148 except OSError:
Thomas Wouterscf297e42007-02-23 15:07:44 +00001149 self.fail('Could not append data to a non-existent zip file.')
1150
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001151 self.assertTrue(os.path.exists(TESTFN))
Thomas Wouterscf297e42007-02-23 15:07:44 +00001152
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001153 with zipfile.ZipFile(TESTFN, 'r') as zf:
1154 self.assertEqual(zf.read(filename), content)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001155
Ezio Melottiafd0d112009-07-15 17:17:17 +00001156 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001157 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti35386712009-12-31 13:22:41 +00001158 # it opens if there's an error in the file. If it doesn't, the
1159 # traceback holds a reference to the ZipFile object and, indirectly,
1160 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001161 # On Windows, this causes the os.unlink() call to fail because the
1162 # underlying file is still open. This is SF bug #412214.
1163 #
Ezio Melotti35386712009-12-31 13:22:41 +00001164 with open(TESTFN, "w") as fp:
1165 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001166 try:
1167 zf = zipfile.ZipFile(TESTFN)
Georg Brandl4d540882010-10-28 06:42:33 +00001168 except zipfile.BadZipFile:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001169 pass
1170
Ezio Melottiafd0d112009-07-15 17:17:17 +00001171 def test_is_zip_erroneous_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001172 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001173 # - passing a filename
1174 with open(TESTFN, "w") as fp:
1175 fp.write("this is not a legal zip file\n")
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001176 self.assertFalse(zipfile.is_zipfile(TESTFN))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001177 # - passing a file object
1178 with open(TESTFN, "rb") as fp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001179 self.assertFalse(zipfile.is_zipfile(fp))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001180 # - passing a file-like object
1181 fp = io.BytesIO()
1182 fp.write(b"this is not a legal zip file\n")
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001183 self.assertFalse(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001184 fp.seek(0, 0)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001185 self.assertFalse(zipfile.is_zipfile(fp))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001186
Serhiy Storchakad2b15272013-01-31 15:27:07 +02001187 def test_damaged_zipfile(self):
1188 """Check that zipfiles with missing bytes at the end raise BadZipFile."""
1189 # - Create a valid zip file
1190 fp = io.BytesIO()
1191 with zipfile.ZipFile(fp, mode="w") as zipf:
1192 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
1193 zipfiledata = fp.getvalue()
1194
1195 # - Now create copies of it missing the last N bytes and make sure
1196 # a BadZipFile exception is raised when we try to open it
1197 for N in range(len(zipfiledata)):
1198 fp = io.BytesIO(zipfiledata[:N])
1199 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, fp)
1200
Ezio Melottiafd0d112009-07-15 17:17:17 +00001201 def test_is_zip_valid_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001202 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001203 # - passing a filename
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001204 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1205 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
1206
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001207 self.assertTrue(zipfile.is_zipfile(TESTFN))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001208 # - passing a file object
1209 with open(TESTFN, "rb") as fp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001210 self.assertTrue(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001211 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001212 zip_contents = fp.read()
1213 # - passing a file-like object
1214 fp = io.BytesIO()
1215 fp.write(zip_contents)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001216 self.assertTrue(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001217 fp.seek(0, 0)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001218 self.assertTrue(zipfile.is_zipfile(fp))
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001219
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001220 def test_non_existent_file_raises_OSError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001221 # make sure we don't raise an AttributeError when a partially-constructed
1222 # ZipFile instance is finalized; this tests for regression on SF tracker
1223 # bug #403871.
1224
1225 # The bug we're testing for caused an AttributeError to be raised
1226 # when a ZipFile instance was created for a file that did not
1227 # exist; the .fp member was not initialized but was needed by the
1228 # __del__() method. Since the AttributeError is in the __del__(),
1229 # it is ignored, but the user should be sufficiently annoyed by
1230 # the message on the output that regression will be noticed
1231 # quickly.
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001232 self.assertRaises(OSError, zipfile.ZipFile, TESTFN)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001233
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001234 def test_empty_file_raises_BadZipFile(self):
1235 f = open(TESTFN, 'w')
1236 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001237 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001238
Ezio Melotti35386712009-12-31 13:22:41 +00001239 with open(TESTFN, 'w') as fp:
1240 fp.write("short file")
Georg Brandl4d540882010-10-28 06:42:33 +00001241 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001242
Ezio Melottiafd0d112009-07-15 17:17:17 +00001243 def test_closed_zip_raises_RuntimeError(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001244 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001245 data = io.BytesIO()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001246 with zipfile.ZipFile(data, mode="w") as zipf:
1247 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001248
Andrew Svetlov737fb892012-12-18 21:14:22 +02001249 # This is correct; calling .read on a closed ZipFile should raise
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001250 # a RuntimeError, and so should calling .testzip. An earlier
1251 # version of .testzip would swallow this exception (and any other)
1252 # and report that the first file in the archive was corrupt.
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001253 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
1254 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001255 self.assertRaises(RuntimeError, zipf.testzip)
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001256 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Brian Curtin8fb9b862010-11-18 02:15:28 +00001257 with open(TESTFN, 'w') as f:
1258 f.write('zipfile test data')
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001259 self.assertRaises(RuntimeError, zipf.write, TESTFN)
1260
Ezio Melottiafd0d112009-07-15 17:17:17 +00001261 def test_bad_constructor_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001262 """Check that bad modes passed to ZipFile constructor are caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001263 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
1264
Ezio Melottiafd0d112009-07-15 17:17:17 +00001265 def test_bad_open_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001266 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001267 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1268 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1269
1270 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001271 # read the data to make sure the file is there
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001272 zipf.read("foo.txt")
1273 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001274
Ezio Melottiafd0d112009-07-15 17:17:17 +00001275 def test_read0(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001276 """Check that calling read(0) on a ZipExtFile object returns an empty
1277 string and doesn't advance file pointer."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001278 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1279 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1280 # read the data to make sure the file is there
Brian Curtin8fb9b862010-11-18 02:15:28 +00001281 with zipf.open("foo.txt") as f:
1282 for i in range(FIXEDTEST_SIZE):
1283 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001284
Brian Curtin8fb9b862010-11-18 02:15:28 +00001285 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001286
Ezio Melottiafd0d112009-07-15 17:17:17 +00001287 def test_open_non_existent_item(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001288 """Check that attempting to call open() for an item that doesn't
1289 exist in the archive raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001290 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1291 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001292
Ezio Melottiafd0d112009-07-15 17:17:17 +00001293 def test_bad_compression_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001294 """Check that bad compression methods passed to ZipFile.open are
1295 caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001296 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
1297
Martin v. Löwisb3260f02012-05-01 08:38:01 +02001298 def test_unsupported_compression(self):
1299 # data is declared as shrunk, but actually deflated
1300 data = (b'PK\x03\x04.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00'
Christian Tismer59202e52013-10-21 03:59:23 +02001301 b'\x00\x02\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00x\x03\x00PK\x01'
1302 b'\x02.\x03.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00\x00\x02\x00\x00'
1303 b'\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
1304 b'\x80\x01\x00\x00\x00\x00xPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00'
1305 b'/\x00\x00\x00!\x00\x00\x00\x00\x00')
Martin v. Löwisb3260f02012-05-01 08:38:01 +02001306 with zipfile.ZipFile(io.BytesIO(data), 'r') as zipf:
1307 self.assertRaises(NotImplementedError, zipf.open, 'x')
1308
Ezio Melottiafd0d112009-07-15 17:17:17 +00001309 def test_null_byte_in_filename(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001310 """Check that a filename containing a null byte is properly
1311 terminated."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001312 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1313 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
1314 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001315
Ezio Melottiafd0d112009-07-15 17:17:17 +00001316 def test_struct_sizes(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001317 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001318 self.assertEqual(zipfile.sizeEndCentDir, 22)
1319 self.assertEqual(zipfile.sizeCentralDir, 46)
1320 self.assertEqual(zipfile.sizeEndCentDir64, 56)
1321 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
1322
Ezio Melottiafd0d112009-07-15 17:17:17 +00001323 def test_comments(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001324 """Check that comments on the archive are handled properly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001325
1326 # check default comment is empty
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001327 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1328 self.assertEqual(zipf.comment, b'')
1329 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1330
1331 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1332 self.assertEqual(zipfr.comment, b'')
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001333
1334 # check a simple short comment
1335 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001336 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1337 zipf.comment = comment
1338 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1339 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1340 self.assertEqual(zipf.comment, comment)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001341
1342 # check a comment of max length
1343 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
1344 comment2 = comment2.encode("ascii")
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001345 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1346 zipf.comment = comment2
1347 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1348
1349 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1350 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001351
1352 # check a comment that is too long is truncated
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001353 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
Serhiy Storchaka9b7a1a12014-01-20 21:57:40 +02001354 with self.assertWarns(UserWarning):
1355 zipf.comment = comment2 + b'oops'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001356 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1357 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1358 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001359
Antoine Pitrouc3991852012-06-30 17:31:37 +02001360 # check that comments are correctly modified in append mode
1361 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1362 zipf.comment = b"original comment"
1363 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1364 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1365 zipf.comment = b"an updated comment"
1366 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1367 self.assertEqual(zipf.comment, b"an updated comment")
1368
1369 # check that comments are correctly shortened in append mode
1370 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1371 zipf.comment = b"original comment that's longer"
1372 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1373 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1374 zipf.comment = b"shorter comment"
1375 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1376 self.assertEqual(zipf.comment, b"shorter comment")
1377
R David Murrayf50b38a2012-04-12 18:44:58 -04001378 def test_unicode_comment(self):
1379 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1380 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1381 with self.assertRaises(TypeError):
1382 zipf.comment = "this is an error"
1383
1384 def test_change_comment_in_empty_archive(self):
1385 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1386 self.assertFalse(zipf.filelist)
1387 zipf.comment = b"this is a comment"
1388 with zipfile.ZipFile(TESTFN, "r") as zipf:
1389 self.assertEqual(zipf.comment, b"this is a comment")
1390
1391 def test_change_comment_in_nonempty_archive(self):
1392 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1393 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1394 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1395 self.assertTrue(zipf.filelist)
1396 zipf.comment = b"this is a comment"
1397 with zipfile.ZipFile(TESTFN, "r") as zipf:
1398 self.assertEqual(zipf.comment, b"this is a comment")
1399
Georg Brandl268e4d42010-10-14 06:59:45 +00001400 def test_empty_zipfile(self):
1401 # Check that creating a file in 'w' or 'a' mode and closing without
1402 # adding any files to the archives creates a valid empty ZIP file
1403 zipf = zipfile.ZipFile(TESTFN, mode="w")
1404 zipf.close()
1405 try:
1406 zipf = zipfile.ZipFile(TESTFN, mode="r")
1407 except zipfile.BadZipFile:
1408 self.fail("Unable to create empty ZIP file in 'w' mode")
1409
1410 zipf = zipfile.ZipFile(TESTFN, mode="a")
1411 zipf.close()
1412 try:
1413 zipf = zipfile.ZipFile(TESTFN, mode="r")
1414 except:
1415 self.fail("Unable to create empty ZIP file in 'a' mode")
1416
1417 def test_open_empty_file(self):
1418 # Issue 1710703: Check that opening a file with less than 22 bytes
Georg Brandl4d540882010-10-28 06:42:33 +00001419 # raises a BadZipFile exception (rather than the previously unhelpful
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001420 # OSError)
Georg Brandl268e4d42010-10-14 06:59:45 +00001421 f = open(TESTFN, 'w')
1422 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001423 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN, 'r')
Georg Brandl268e4d42010-10-14 06:59:45 +00001424
Senthil Kumaran29fa9d42011-10-20 01:46:00 +08001425 def test_create_zipinfo_before_1980(self):
1426 self.assertRaises(ValueError,
1427 zipfile.ZipInfo, 'seventies', (1979, 1, 1, 0, 0, 0))
1428
Gregory P. Smith0af8a862014-05-29 23:42:14 -07001429 def test_zipfile_with_short_extra_field(self):
1430 """If an extra field in the header is less than 4 bytes, skip it."""
1431 zipdata = (
1432 b'PK\x03\x04\x14\x00\x00\x00\x00\x00\x93\x9b\xad@\x8b\x9e'
1433 b'\xd9\xd3\x01\x00\x00\x00\x01\x00\x00\x00\x03\x00\x03\x00ab'
1434 b'c\x00\x00\x00APK\x01\x02\x14\x03\x14\x00\x00\x00\x00'
1435 b'\x00\x93\x9b\xad@\x8b\x9e\xd9\xd3\x01\x00\x00\x00\x01\x00\x00'
1436 b'\x00\x03\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00'
1437 b'\x00\x00\x00abc\x00\x00PK\x05\x06\x00\x00\x00\x00'
1438 b'\x01\x00\x01\x003\x00\x00\x00%\x00\x00\x00\x00\x00'
1439 )
1440 with zipfile.ZipFile(io.BytesIO(zipdata), 'r') as zipf:
1441 # testzip returns the name of the first corrupt file, or None
1442 self.assertIsNone(zipf.testzip())
1443
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001444 def test_open_conflicting_handles(self):
1445 # It's only possible to open one writable file handle at a time
1446 msg1 = b"It's fun to charter an accountant!"
1447 msg2 = b"And sail the wide accountant sea"
1448 msg3 = b"To find, explore the funds offshore"
1449 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipf:
1450 with zipf.open('foo', mode='w') as w2:
1451 w2.write(msg1)
1452 with zipf.open('bar', mode='w') as w1:
1453 with self.assertRaises(RuntimeError):
1454 zipf.open('handle', mode='w')
1455 with self.assertRaises(RuntimeError):
1456 zipf.open('foo', mode='r')
1457 with self.assertRaises(RuntimeError):
1458 zipf.writestr('str', 'abcde')
1459 with self.assertRaises(RuntimeError):
1460 zipf.write(__file__, 'file')
1461 with self.assertRaises(RuntimeError):
1462 zipf.close()
1463 w1.write(msg2)
1464 with zipf.open('baz', mode='w') as w2:
1465 w2.write(msg3)
1466
1467 with zipfile.ZipFile(TESTFN2, 'r') as zipf:
1468 self.assertEqual(zipf.read('foo'), msg1)
1469 self.assertEqual(zipf.read('bar'), msg2)
1470 self.assertEqual(zipf.read('baz'), msg3)
1471 self.assertEqual(zipf.namelist(), ['foo', 'bar', 'baz'])
1472
Guido van Rossumd8faa362007-04-27 19:54:29 +00001473 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001474 unlink(TESTFN)
1475 unlink(TESTFN2)
1476
Thomas Wouterscf297e42007-02-23 15:07:44 +00001477
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001478class AbstractBadCrcTests:
1479 def test_testzip_with_bad_crc(self):
1480 """Tests that files with bad CRCs return their name from testzip."""
1481 zipdata = self.zip_with_bad_crc
1482
1483 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1484 # testzip returns the name of the first corrupt file, or None
1485 self.assertEqual('afile', zipf.testzip())
1486
1487 def test_read_with_bad_crc(self):
1488 """Tests that files with bad CRCs raise a BadZipFile exception when read."""
1489 zipdata = self.zip_with_bad_crc
1490
1491 # Using ZipFile.read()
1492 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1493 self.assertRaises(zipfile.BadZipFile, zipf.read, 'afile')
1494
1495 # Using ZipExtFile.read()
1496 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1497 with zipf.open('afile', 'r') as corrupt_file:
1498 self.assertRaises(zipfile.BadZipFile, corrupt_file.read)
1499
1500 # Same with small reads (in order to exercise the buffering logic)
1501 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1502 with zipf.open('afile', 'r') as corrupt_file:
1503 corrupt_file.MIN_READ_SIZE = 2
1504 with self.assertRaises(zipfile.BadZipFile):
1505 while corrupt_file.read(2):
1506 pass
1507
1508
1509class StoredBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1510 compression = zipfile.ZIP_STORED
1511 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001512 b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
1513 b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
1514 b'ilehello,AworldP'
1515 b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
1516 b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
1517 b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
1518 b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
1519 b'\0\0/\0\0\0\0\0')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001520
1521@requires_zlib
1522class DeflateBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1523 compression = zipfile.ZIP_DEFLATED
1524 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001525 b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
1526 b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1527 b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
1528 b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
1529 b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
1530 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
1531 b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
1532 b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001533
1534@requires_bz2
1535class Bzip2BadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1536 compression = zipfile.ZIP_BZIP2
1537 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001538 b'PK\x03\x04\x14\x03\x00\x00\x0c\x00nu\x0c=FA'
1539 b'KE8\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1540 b'ileBZh91AY&SY\xd4\xa8\xca'
1541 b'\x7f\x00\x00\x0f\x11\x80@\x00\x06D\x90\x80 \x00 \xa5'
1542 b'P\xd9!\x03\x03\x13\x13\x13\x89\xa9\xa9\xc2u5:\x9f'
1543 b'\x8b\xb9"\x9c(HjTe?\x80PK\x01\x02\x14'
1544 b'\x03\x14\x03\x00\x00\x0c\x00nu\x0c=FAKE8'
1545 b'\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\x00'
1546 b'\x00 \x80\x80\x81\x00\x00\x00\x00afilePK'
1547 b'\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00\x00[\x00'
1548 b'\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001549
1550@requires_lzma
1551class LzmaBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1552 compression = zipfile.ZIP_LZMA
1553 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001554 b'PK\x03\x04\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
1555 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1556 b'ile\t\x04\x05\x00]\x00\x00\x00\x04\x004\x19I'
1557 b'\xee\x8d\xe9\x17\x89:3`\tq!.8\x00PK'
1558 b'\x01\x02\x14\x03\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
1559 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00'
1560 b'\x00\x00\x00\x00 \x80\x80\x81\x00\x00\x00\x00afil'
1561 b'ePK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00'
1562 b'\x00>\x00\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001563
1564
Thomas Wouterscf297e42007-02-23 15:07:44 +00001565class DecryptionTests(unittest.TestCase):
Ezio Melotti35386712009-12-31 13:22:41 +00001566 """Check that ZIP decryption works. Since the library does not
1567 support encryption at the moment, we use a pre-generated encrypted
1568 ZIP file."""
Thomas Wouterscf297e42007-02-23 15:07:44 +00001569
1570 data = (
Christian Tismer59202e52013-10-21 03:59:23 +02001571 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
1572 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
1573 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
1574 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
1575 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
1576 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
1577 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +00001578 data2 = (
Christian Tismer59202e52013-10-21 03:59:23 +02001579 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
1580 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
1581 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
1582 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
1583 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
1584 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
1585 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
1586 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +00001587
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001588 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +00001589 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +00001590
1591 def setUp(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001592 with open(TESTFN, "wb") as fp:
1593 fp.write(self.data)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001594 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti35386712009-12-31 13:22:41 +00001595 with open(TESTFN2, "wb") as fp:
1596 fp.write(self.data2)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001597 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001598
1599 def tearDown(self):
1600 self.zip.close()
1601 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001602 self.zip2.close()
1603 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001604
Ezio Melottiafd0d112009-07-15 17:17:17 +00001605 def test_no_password(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001606 # Reading the encrypted file without password
1607 # must generate a RunTime exception
1608 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001609 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001610
Ezio Melottiafd0d112009-07-15 17:17:17 +00001611 def test_bad_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001612 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001613 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001614 self.zip2.setpassword(b"perl")
1615 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001616
Ezio Melotti975077a2011-05-19 22:03:22 +03001617 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +00001618 def test_good_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001619 self.zip.setpassword(b"python")
Ezio Melotti35386712009-12-31 13:22:41 +00001620 self.assertEqual(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001621 self.zip2.setpassword(b"12345")
Ezio Melotti35386712009-12-31 13:22:41 +00001622 self.assertEqual(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001623
R. David Murray8d855d82010-12-21 21:53:37 +00001624 def test_unicode_password(self):
1625 self.assertRaises(TypeError, self.zip.setpassword, "unicode")
1626 self.assertRaises(TypeError, self.zip.read, "test.txt", "python")
1627 self.assertRaises(TypeError, self.zip.open, "test.txt", pwd="python")
1628 self.assertRaises(TypeError, self.zip.extract, "test.txt", pwd="python")
1629
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001630class AbstractTestsWithRandomBinaryFiles:
1631 @classmethod
1632 def setUpClass(cls):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001633 datacount = randint(16, 64)*1024 + randint(1, 1024)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001634 cls.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
1635 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001636
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001637 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001638 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +00001639 with open(TESTFN, "wb") as fp:
1640 fp.write(self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001641
1642 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001643 unlink(TESTFN)
1644 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001645
Ezio Melottiafd0d112009-07-15 17:17:17 +00001646 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001647 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001648 with zipfile.ZipFile(f, "w", compression) as zipfp:
1649 zipfp.write(TESTFN, "another.name")
1650 zipfp.write(TESTFN, TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001651
Ezio Melottiafd0d112009-07-15 17:17:17 +00001652 def zip_test(self, f, compression):
1653 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001654
1655 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001656 with zipfile.ZipFile(f, "r", compression) as zipfp:
1657 testdata = zipfp.read(TESTFN)
1658 self.assertEqual(len(testdata), len(self.data))
1659 self.assertEqual(testdata, self.data)
1660 self.assertEqual(zipfp.read("another.name"), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001661
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001662 def test_read(self):
1663 for f in get_files(self):
1664 self.zip_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001665
Ezio Melottiafd0d112009-07-15 17:17:17 +00001666 def zip_open_test(self, f, compression):
1667 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001668
1669 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001670 with zipfile.ZipFile(f, "r", compression) as zipfp:
1671 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001672 with zipfp.open(TESTFN) as zipopen1:
1673 while True:
1674 read_data = zipopen1.read(256)
1675 if not read_data:
1676 break
1677 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001678
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001679 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001680 with zipfp.open("another.name") as zipopen2:
1681 while True:
1682 read_data = zipopen2.read(256)
1683 if not read_data:
1684 break
1685 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001686
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001687 testdata1 = b''.join(zipdata1)
1688 self.assertEqual(len(testdata1), len(self.data))
1689 self.assertEqual(testdata1, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001690
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001691 testdata2 = b''.join(zipdata2)
Ezio Melotti35386712009-12-31 13:22:41 +00001692 self.assertEqual(len(testdata2), len(self.data))
1693 self.assertEqual(testdata2, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001694
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001695 def test_open(self):
1696 for f in get_files(self):
1697 self.zip_open_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001698
Ezio Melottiafd0d112009-07-15 17:17:17 +00001699 def zip_random_open_test(self, f, compression):
1700 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001701
1702 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001703 with zipfile.ZipFile(f, "r", compression) as zipfp:
1704 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001705 with zipfp.open(TESTFN) as zipopen1:
1706 while True:
1707 read_data = zipopen1.read(randint(1, 1024))
1708 if not read_data:
1709 break
1710 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001711
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001712 testdata = b''.join(zipdata1)
1713 self.assertEqual(len(testdata), len(self.data))
1714 self.assertEqual(testdata, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001715
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001716 def test_random_open(self):
1717 for f in get_files(self):
1718 self.zip_random_open_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001719
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001720
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001721class StoredTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1722 unittest.TestCase):
1723 compression = zipfile.ZIP_STORED
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001724
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001725@requires_zlib
1726class DeflateTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1727 unittest.TestCase):
1728 compression = zipfile.ZIP_DEFLATED
1729
1730@requires_bz2
1731class Bzip2TestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1732 unittest.TestCase):
1733 compression = zipfile.ZIP_BZIP2
1734
1735@requires_lzma
1736class LzmaTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1737 unittest.TestCase):
1738 compression = zipfile.ZIP_LZMA
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001739
Ezio Melotti76430242009-07-11 18:28:48 +00001740
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001741# Privide the tell() method but not seek()
1742class Tellable:
1743 def __init__(self, fp):
1744 self.fp = fp
1745 self.offset = 0
1746
1747 def write(self, data):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02001748 n = self.fp.write(data)
1749 self.offset += n
1750 return n
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001751
1752 def tell(self):
1753 return self.offset
1754
1755 def flush(self):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02001756 self.fp.flush()
1757
1758class Unseekable:
1759 def __init__(self, fp):
1760 self.fp = fp
1761
1762 def write(self, data):
1763 return self.fp.write(data)
1764
1765 def flush(self):
1766 self.fp.flush()
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001767
1768class UnseekableTests(unittest.TestCase):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02001769 def test_writestr(self):
1770 for wrapper in (lambda f: f), Tellable, Unseekable:
1771 with self.subTest(wrapper=wrapper):
1772 f = io.BytesIO()
1773 f.write(b'abc')
1774 bf = io.BufferedWriter(f)
1775 with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) as zipfp:
1776 zipfp.writestr('ones', b'111')
1777 zipfp.writestr('twos', b'222')
1778 self.assertEqual(f.getvalue()[:5], b'abcPK')
1779 with zipfile.ZipFile(f, mode='r') as zipf:
1780 with zipf.open('ones') as zopen:
1781 self.assertEqual(zopen.read(), b'111')
1782 with zipf.open('twos') as zopen:
1783 self.assertEqual(zopen.read(), b'222')
1784
1785 def test_write(self):
1786 for wrapper in (lambda f: f), Tellable, Unseekable:
1787 with self.subTest(wrapper=wrapper):
1788 f = io.BytesIO()
1789 f.write(b'abc')
1790 bf = io.BufferedWriter(f)
1791 with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) as zipfp:
1792 self.addCleanup(unlink, TESTFN)
1793 with open(TESTFN, 'wb') as f2:
1794 f2.write(b'111')
1795 zipfp.write(TESTFN, 'ones')
1796 with open(TESTFN, 'wb') as f2:
1797 f2.write(b'222')
1798 zipfp.write(TESTFN, 'twos')
1799 self.assertEqual(f.getvalue()[:5], b'abcPK')
1800 with zipfile.ZipFile(f, mode='r') as zipf:
1801 with zipf.open('ones') as zopen:
1802 self.assertEqual(zopen.read(), b'111')
1803 with zipf.open('twos') as zopen:
1804 self.assertEqual(zopen.read(), b'222')
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001805
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001806 def test_open_write(self):
1807 for wrapper in (lambda f: f), Tellable, Unseekable:
1808 with self.subTest(wrapper=wrapper):
1809 f = io.BytesIO()
1810 f.write(b'abc')
1811 bf = io.BufferedWriter(f)
1812 with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) as zipf:
1813 with zipf.open('ones', 'w') as zopen:
1814 zopen.write(b'111')
1815 with zipf.open('twos', 'w') as zopen:
1816 zopen.write(b'222')
1817 self.assertEqual(f.getvalue()[:5], b'abcPK')
1818 with zipfile.ZipFile(f) as zipf:
1819 self.assertEqual(zipf.read('ones'), b'111')
1820 self.assertEqual(zipf.read('twos'), b'222')
1821
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001822
Ezio Melotti975077a2011-05-19 22:03:22 +03001823@requires_zlib
Guido van Rossumd8faa362007-04-27 19:54:29 +00001824class TestsWithMultipleOpens(unittest.TestCase):
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001825 @classmethod
1826 def setUpClass(cls):
1827 cls.data1 = b'111' + getrandbytes(10000)
1828 cls.data2 = b'222' + getrandbytes(10000)
1829
1830 def make_test_archive(self, f):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001831 # Create the ZIP archive
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001832 with zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as zipfp:
1833 zipfp.writestr('ones', self.data1)
1834 zipfp.writestr('twos', self.data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001835
Ezio Melottiafd0d112009-07-15 17:17:17 +00001836 def test_same_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001837 # Verify that (when the ZipFile is in control of creating file objects)
1838 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001839 for f in get_files(self):
1840 self.make_test_archive(f)
1841 with zipfile.ZipFile(f, mode="r") as zipf:
1842 with zipf.open('ones') as zopen1, zipf.open('ones') as zopen2:
1843 data1 = zopen1.read(500)
1844 data2 = zopen2.read(500)
1845 data1 += zopen1.read()
1846 data2 += zopen2.read()
1847 self.assertEqual(data1, data2)
1848 self.assertEqual(data1, self.data1)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001849
Ezio Melottiafd0d112009-07-15 17:17:17 +00001850 def test_different_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001851 # Verify that (when the ZipFile is in control of creating file objects)
1852 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001853 for f in get_files(self):
1854 self.make_test_archive(f)
1855 with zipfile.ZipFile(f, mode="r") as zipf:
1856 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1857 data1 = zopen1.read(500)
1858 data2 = zopen2.read(500)
1859 data1 += zopen1.read()
1860 data2 += zopen2.read()
1861 self.assertEqual(data1, self.data1)
1862 self.assertEqual(data2, self.data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001863
Ezio Melottiafd0d112009-07-15 17:17:17 +00001864 def test_interleaved(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001865 # Verify that (when the ZipFile is in control of creating file objects)
1866 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001867 for f in get_files(self):
1868 self.make_test_archive(f)
1869 with zipfile.ZipFile(f, mode="r") as zipf:
1870 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1871 data1 = zopen1.read(500)
1872 data2 = zopen2.read(500)
1873 data1 += zopen1.read()
1874 data2 += zopen2.read()
1875 self.assertEqual(data1, self.data1)
1876 self.assertEqual(data2, self.data2)
1877
1878 def test_read_after_close(self):
1879 for f in get_files(self):
1880 self.make_test_archive(f)
1881 with contextlib.ExitStack() as stack:
1882 with zipfile.ZipFile(f, 'r') as zipf:
1883 zopen1 = stack.enter_context(zipf.open('ones'))
1884 zopen2 = stack.enter_context(zipf.open('twos'))
Brian Curtin8fb9b862010-11-18 02:15:28 +00001885 data1 = zopen1.read(500)
1886 data2 = zopen2.read(500)
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001887 data1 += zopen1.read()
1888 data2 += zopen2.read()
1889 self.assertEqual(data1, self.data1)
1890 self.assertEqual(data2, self.data2)
1891
1892 def test_read_after_write(self):
1893 for f in get_files(self):
1894 with zipfile.ZipFile(f, 'w', zipfile.ZIP_DEFLATED) as zipf:
1895 zipf.writestr('ones', self.data1)
1896 zipf.writestr('twos', self.data2)
1897 with zipf.open('ones') as zopen1:
1898 data1 = zopen1.read(500)
1899 self.assertEqual(data1, self.data1[:500])
1900 with zipfile.ZipFile(f, 'r') as zipf:
1901 data1 = zipf.read('ones')
1902 data2 = zipf.read('twos')
1903 self.assertEqual(data1, self.data1)
1904 self.assertEqual(data2, self.data2)
1905
1906 def test_write_after_read(self):
1907 for f in get_files(self):
1908 with zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as zipf:
1909 zipf.writestr('ones', self.data1)
1910 with zipf.open('ones') as zopen1:
1911 zopen1.read(500)
1912 zipf.writestr('twos', self.data2)
1913 with zipfile.ZipFile(f, 'r') as zipf:
1914 data1 = zipf.read('ones')
1915 data2 = zipf.read('twos')
1916 self.assertEqual(data1, self.data1)
1917 self.assertEqual(data2, self.data2)
1918
1919 def test_many_opens(self):
1920 # Verify that read() and open() promptly close the file descriptor,
1921 # and don't rely on the garbage collector to free resources.
1922 self.make_test_archive(TESTFN2)
1923 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
1924 for x in range(100):
1925 zipf.read('ones')
1926 with zipf.open('ones') as zopen1:
1927 pass
1928 with open(os.devnull) as f:
1929 self.assertLess(f.fileno(), 100)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001930
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001931 def test_write_while_reading(self):
1932 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_DEFLATED) as zipf:
1933 zipf.writestr('ones', self.data1)
1934 with zipfile.ZipFile(TESTFN2, 'a', zipfile.ZIP_DEFLATED) as zipf:
1935 with zipf.open('ones', 'r') as r1:
1936 data1 = r1.read(500)
1937 with zipf.open('twos', 'w') as w1:
1938 w1.write(self.data2)
1939 data1 += r1.read()
1940 self.assertEqual(data1, self.data1)
1941 with zipfile.ZipFile(TESTFN2) as zipf:
1942 self.assertEqual(zipf.read('twos'), self.data2)
1943
Guido van Rossumd8faa362007-04-27 19:54:29 +00001944 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001945 unlink(TESTFN2)
1946
Guido van Rossumd8faa362007-04-27 19:54:29 +00001947
Martin v. Löwis59e47792009-01-24 14:10:07 +00001948class TestWithDirectory(unittest.TestCase):
1949 def setUp(self):
1950 os.mkdir(TESTFN2)
1951
Ezio Melottiafd0d112009-07-15 17:17:17 +00001952 def test_extract_dir(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001953 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
1954 zipf.extractall(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001955 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1956 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1957 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1958
Ezio Melottiafd0d112009-07-15 17:17:17 +00001959 def test_bug_6050(self):
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001960 # Extraction should succeed if directories already exist
1961 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottiafd0d112009-07-15 17:17:17 +00001962 self.test_extract_dir()
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001963
Serhiy Storchaka46a34922014-09-23 22:40:23 +03001964 def test_write_dir(self):
1965 dirpath = os.path.join(TESTFN2, "x")
1966 os.mkdir(dirpath)
1967 mode = os.stat(dirpath).st_mode & 0xFFFF
1968 with zipfile.ZipFile(TESTFN, "w") as zipf:
1969 zipf.write(dirpath)
1970 zinfo = zipf.filelist[0]
1971 self.assertTrue(zinfo.filename.endswith("/x/"))
1972 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1973 zipf.write(dirpath, "y")
1974 zinfo = zipf.filelist[1]
1975 self.assertTrue(zinfo.filename, "y/")
1976 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1977 with zipfile.ZipFile(TESTFN, "r") as zipf:
1978 zinfo = zipf.filelist[0]
1979 self.assertTrue(zinfo.filename.endswith("/x/"))
1980 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1981 zinfo = zipf.filelist[1]
1982 self.assertTrue(zinfo.filename, "y/")
1983 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1984 target = os.path.join(TESTFN2, "target")
1985 os.mkdir(target)
1986 zipf.extractall(target)
1987 self.assertTrue(os.path.isdir(os.path.join(target, "y")))
1988 self.assertEqual(len(os.listdir(target)), 2)
1989
1990 def test_writestr_dir(self):
Martin v. Löwis59e47792009-01-24 14:10:07 +00001991 os.mkdir(os.path.join(TESTFN2, "x"))
Serhiy Storchaka46a34922014-09-23 22:40:23 +03001992 with zipfile.ZipFile(TESTFN, "w") as zipf:
1993 zipf.writestr("x/", b'')
1994 zinfo = zipf.filelist[0]
1995 self.assertEqual(zinfo.filename, "x/")
1996 self.assertEqual(zinfo.external_attr, (0o40775 << 16) | 0x10)
1997 with zipfile.ZipFile(TESTFN, "r") as zipf:
1998 zinfo = zipf.filelist[0]
1999 self.assertTrue(zinfo.filename.endswith("x/"))
2000 self.assertEqual(zinfo.external_attr, (0o40775 << 16) | 0x10)
2001 target = os.path.join(TESTFN2, "target")
2002 os.mkdir(target)
2003 zipf.extractall(target)
2004 self.assertTrue(os.path.isdir(os.path.join(target, "x")))
2005 self.assertEqual(os.listdir(target), ["x"])
Martin v. Löwis59e47792009-01-24 14:10:07 +00002006
2007 def tearDown(self):
Victor Stinner57004c62014-09-04 00:49:01 +02002008 rmtree(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00002009 if os.path.exists(TESTFN):
Ezio Melotti76430242009-07-11 18:28:48 +00002010 unlink(TESTFN)
Martin v. Löwis59e47792009-01-24 14:10:07 +00002011
Guido van Rossumd8faa362007-04-27 19:54:29 +00002012
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03002013class AbstractUniversalNewlineTests:
2014 @classmethod
2015 def setUpClass(cls):
2016 cls.line_gen = [bytes("Test of zipfile line %d." % i, "ascii")
2017 for i in range(FIXEDTEST_SIZE)]
2018 cls.seps = (b'\r', b'\r\n', b'\n')
2019 cls.arcdata = {}
2020 for n, s in enumerate(cls.seps):
2021 cls.arcdata[s] = s.join(cls.line_gen) + s
2022
Guido van Rossumd8faa362007-04-27 19:54:29 +00002023 def setUp(self):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03002024 self.arcfiles = {}
Guido van Rossumd8faa362007-04-27 19:54:29 +00002025 for n, s in enumerate(self.seps):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002026 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03002027 with open(self.arcfiles[s], "wb") as f:
Guido van Rossumd6ca5462007-05-22 01:29:33 +00002028 f.write(self.arcdata[s])
Guido van Rossumd8faa362007-04-27 19:54:29 +00002029
Ezio Melottiafd0d112009-07-15 17:17:17 +00002030 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002031 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00002032 with zipfile.ZipFile(f, "w", compression) as zipfp:
2033 for fn in self.arcfiles.values():
2034 zipfp.write(fn, fn)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002035
Ezio Melottiafd0d112009-07-15 17:17:17 +00002036 def read_test(self, f, compression):
2037 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002038
2039 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00002040 with zipfile.ZipFile(f, "r") as zipfp:
2041 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02002042 with openU(zipfp, fn) as fp:
Benjamin Petersond285bdb2010-10-31 17:57:22 +00002043 zipdata = fp.read()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00002044 self.assertEqual(self.arcdata[sep], zipdata)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03002045
2046 def test_read(self):
2047 for f in get_files(self):
2048 self.read_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002049
Antoine Pitroua32f9a22010-01-27 21:18:57 +00002050 def readline_read_test(self, f, compression):
2051 self.make_test_archive(f, compression)
2052
2053 # Read the ZIP archive
Brian Curtin8fb9b862010-11-18 02:15:28 +00002054 with zipfile.ZipFile(f, "r") as zipfp:
2055 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02002056 with openU(zipfp, fn) as zipopen:
Brian Curtin8fb9b862010-11-18 02:15:28 +00002057 data = b''
2058 while True:
2059 read = zipopen.readline()
2060 if not read:
2061 break
2062 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +00002063
Brian Curtin8fb9b862010-11-18 02:15:28 +00002064 read = zipopen.read(5)
2065 if not read:
2066 break
2067 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +00002068
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03002069 self.assertEqual(data, self.arcdata[b'\n'])
Antoine Pitroua32f9a22010-01-27 21:18:57 +00002070
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03002071 def test_readline_read(self):
2072 for f in get_files(self):
2073 self.readline_read_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +00002074
Ezio Melottiafd0d112009-07-15 17:17:17 +00002075 def readline_test(self, f, compression):
2076 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002077
2078 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00002079 with zipfile.ZipFile(f, "r") as zipfp:
2080 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02002081 with openU(zipfp, fn) as zipopen:
Benjamin Petersond285bdb2010-10-31 17:57:22 +00002082 for line in self.line_gen:
2083 linedata = zipopen.readline()
2084 self.assertEqual(linedata, line + b'\n')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03002085
2086 def test_readline(self):
2087 for f in get_files(self):
2088 self.readline_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002089
Ezio Melottiafd0d112009-07-15 17:17:17 +00002090 def readlines_test(self, f, compression):
2091 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002092
2093 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00002094 with zipfile.ZipFile(f, "r") as zipfp:
2095 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02002096 with openU(zipfp, fn) as fp:
Benjamin Petersond285bdb2010-10-31 17:57:22 +00002097 ziplines = fp.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00002098 for line, zipline in zip(self.line_gen, ziplines):
2099 self.assertEqual(zipline, line + b'\n')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03002100
2101 def test_readlines(self):
2102 for f in get_files(self):
2103 self.readlines_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002104
Ezio Melottiafd0d112009-07-15 17:17:17 +00002105 def iterlines_test(self, f, compression):
2106 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002107
2108 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00002109 with zipfile.ZipFile(f, "r") as zipfp:
2110 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02002111 with openU(zipfp, fn) as fp:
Benjamin Petersond285bdb2010-10-31 17:57:22 +00002112 for line, zipline in zip(self.line_gen, fp):
2113 self.assertEqual(zipline, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00002114
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03002115 def test_iterlines(self):
2116 for f in get_files(self):
2117 self.iterlines_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02002118
Guido van Rossumd8faa362007-04-27 19:54:29 +00002119 def tearDown(self):
2120 for sep, fn in self.arcfiles.items():
Victor Stinner88b215e2014-09-04 00:51:09 +02002121 unlink(fn)
Ezio Melotti76430242009-07-11 18:28:48 +00002122 unlink(TESTFN)
2123 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002124
2125
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03002126class StoredUniversalNewlineTests(AbstractUniversalNewlineTests,
2127 unittest.TestCase):
2128 compression = zipfile.ZIP_STORED
2129
2130@requires_zlib
2131class DeflateUniversalNewlineTests(AbstractUniversalNewlineTests,
2132 unittest.TestCase):
2133 compression = zipfile.ZIP_DEFLATED
2134
2135@requires_bz2
2136class Bzip2UniversalNewlineTests(AbstractUniversalNewlineTests,
2137 unittest.TestCase):
2138 compression = zipfile.ZIP_BZIP2
2139
2140@requires_lzma
2141class LzmaUniversalNewlineTests(AbstractUniversalNewlineTests,
2142 unittest.TestCase):
2143 compression = zipfile.ZIP_LZMA
2144
Serhiy Storchaka503f9082016-02-08 00:02:25 +02002145class ZipInfoTests(unittest.TestCase):
2146 def test_from_file(self):
2147 zi = zipfile.ZipInfo.from_file(__file__)
2148 self.assertEqual(posixpath.basename(zi.filename), 'test_zipfile.py')
2149 self.assertFalse(zi.is_dir())
2150
2151 def test_from_dir(self):
2152 dirpath = os.path.dirname(os.path.abspath(__file__))
2153 zi = zipfile.ZipInfo.from_file(dirpath, 'stdlib_tests')
2154 self.assertEqual(zi.filename, 'stdlib_tests/')
2155 self.assertTrue(zi.is_dir())
2156 self.assertEqual(zi.compress_type, zipfile.ZIP_STORED)
2157 self.assertEqual(zi.file_size, 0)
2158
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00002159if __name__ == "__main__":
Brett Cannond5b4e1d2013-06-12 19:57:19 -04002160 unittest.main()