blob: 5d7b91fcd267504bd3032804b94f156fc31808bb [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 Storchakafa6bc292013-07-22 21:00:11 +030041class AbstractTestsWithSourceFile:
42 @classmethod
43 def setUpClass(cls):
44 cls.line_gen = [bytes("Zipfile test line %d. random float: %f\n" %
45 (i, random()), "ascii")
46 for i in range(FIXEDTEST_SIZE)]
47 cls.data = b''.join(cls.line_gen)
48
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000049 def setUp(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000050 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +000051 with open(TESTFN, "wb") as fp:
52 fp.write(self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000053
Ezio Melottiafd0d112009-07-15 17:17:17 +000054 def make_test_archive(self, f, compression):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000055 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000056 with zipfile.ZipFile(f, "w", compression) as zipfp:
57 zipfp.write(TESTFN, "another.name")
58 zipfp.write(TESTFN, TESTFN)
59 zipfp.writestr("strfile", self.data)
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +030060 with zipfp.open('written-open-w', mode='w') as f:
61 for line in self.line_gen:
62 f.write(line)
Tim Peters7d3bad62001-04-04 18:56:49 +000063
Ezio Melottiafd0d112009-07-15 17:17:17 +000064 def zip_test(self, f, compression):
65 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +000066
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000067 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000068 with zipfile.ZipFile(f, "r", compression) as zipfp:
69 self.assertEqual(zipfp.read(TESTFN), self.data)
70 self.assertEqual(zipfp.read("another.name"), self.data)
71 self.assertEqual(zipfp.read("strfile"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000072
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000073 # Print the ZIP directory
74 fp = io.StringIO()
75 zipfp.printdir(file=fp)
76 directory = fp.getvalue()
77 lines = directory.splitlines()
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +030078 self.assertEqual(len(lines), 5) # Number of files + header
Thomas Wouters0e3f5912006-08-11 14:57:12 +000079
Benjamin Peterson577473f2010-01-19 00:09:57 +000080 self.assertIn('File Name', lines[0])
81 self.assertIn('Modified', lines[0])
82 self.assertIn('Size', lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +000083
Ezio Melotti35386712009-12-31 13:22:41 +000084 fn, date, time_, size = lines[1].split()
85 self.assertEqual(fn, 'another.name')
86 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
87 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
88 self.assertEqual(size, str(len(self.data)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000089
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000090 # Check the namelist
91 names = zipfp.namelist()
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +030092 self.assertEqual(len(names), 4)
Benjamin Peterson577473f2010-01-19 00:09:57 +000093 self.assertIn(TESTFN, names)
94 self.assertIn("another.name", names)
95 self.assertIn("strfile", names)
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +030096 self.assertIn("written-open-w", names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000097
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000098 # Check infolist
99 infos = zipfp.infolist()
Ezio Melotti35386712009-12-31 13:22:41 +0000100 names = [i.filename for i in infos]
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300101 self.assertEqual(len(names), 4)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000102 self.assertIn(TESTFN, names)
103 self.assertIn("another.name", names)
104 self.assertIn("strfile", names)
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300105 self.assertIn("written-open-w", names)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000106 for i in infos:
Ezio Melotti35386712009-12-31 13:22:41 +0000107 self.assertEqual(i.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000108
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000109 # check getinfo
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300110 for nm in (TESTFN, "another.name", "strfile", "written-open-w"):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000111 info = zipfp.getinfo(nm)
Ezio Melotti35386712009-12-31 13:22:41 +0000112 self.assertEqual(info.filename, nm)
113 self.assertEqual(info.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000114
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000115 # Check that testzip doesn't raise an exception
116 zipfp.testzip()
Tim Peters7d3bad62001-04-04 18:56:49 +0000117
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300118 def test_basic(self):
119 for f in get_files(self):
120 self.zip_test(f, self.compression)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000121
Ezio Melottiafd0d112009-07-15 17:17:17 +0000122 def zip_open_test(self, f, compression):
123 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000124
125 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000126 with zipfile.ZipFile(f, "r", compression) as zipfp:
127 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000128 with zipfp.open(TESTFN) as zipopen1:
129 while True:
130 read_data = zipopen1.read(256)
131 if not read_data:
132 break
133 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000134
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000135 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000136 with zipfp.open("another.name") as zipopen2:
137 while True:
138 read_data = zipopen2.read(256)
139 if not read_data:
140 break
141 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000142
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000143 self.assertEqual(b''.join(zipdata1), self.data)
144 self.assertEqual(b''.join(zipdata2), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000145
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300146 def test_open(self):
147 for f in get_files(self):
148 self.zip_open_test(f, self.compression)
Georg Brandlb533e262008-05-25 18:19:30 +0000149
Ezio Melottiafd0d112009-07-15 17:17:17 +0000150 def zip_random_open_test(self, f, compression):
151 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000152
153 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000154 with zipfile.ZipFile(f, "r", compression) as zipfp:
155 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000156 with zipfp.open(TESTFN) as zipopen1:
157 while True:
158 read_data = zipopen1.read(randint(1, 1024))
159 if not read_data:
160 break
161 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000162
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000163 self.assertEqual(b''.join(zipdata1), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000164
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300165 def test_random_open(self):
166 for f in get_files(self):
167 self.zip_random_open_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000168
Serhiy Storchakad2c07a52013-09-27 22:11:57 +0300169 def zip_read1_test(self, f, compression):
170 self.make_test_archive(f, compression)
171
172 # Read the ZIP archive
173 with zipfile.ZipFile(f, "r") as zipfp, \
174 zipfp.open(TESTFN) as zipopen:
175 zipdata = []
176 while True:
177 read_data = zipopen.read1(-1)
178 if not read_data:
179 break
180 zipdata.append(read_data)
181
182 self.assertEqual(b''.join(zipdata), self.data)
183
184 def test_read1(self):
185 for f in get_files(self):
186 self.zip_read1_test(f, self.compression)
187
188 def zip_read1_10_test(self, f, compression):
189 self.make_test_archive(f, compression)
190
191 # Read the ZIP archive
192 with zipfile.ZipFile(f, "r") as zipfp, \
193 zipfp.open(TESTFN) as zipopen:
194 zipdata = []
195 while True:
196 read_data = zipopen.read1(10)
197 self.assertLessEqual(len(read_data), 10)
198 if not read_data:
199 break
200 zipdata.append(read_data)
201
202 self.assertEqual(b''.join(zipdata), self.data)
203
204 def test_read1_10(self):
205 for f in get_files(self):
206 self.zip_read1_10_test(f, self.compression)
207
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000208 def zip_readline_read_test(self, f, compression):
209 self.make_test_archive(f, compression)
210
211 # Read the ZIP archive
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300212 with zipfile.ZipFile(f, "r") as zipfp, \
213 zipfp.open(TESTFN) as zipopen:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000214 data = b''
215 while True:
216 read = zipopen.readline()
217 if not read:
218 break
219 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000220
Brian Curtin8fb9b862010-11-18 02:15:28 +0000221 read = zipopen.read(100)
222 if not read:
223 break
224 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000225
226 self.assertEqual(data, self.data)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300227
228 def test_readline_read(self):
229 # Issue #7610: calls to readline() interleaved with calls to read().
230 for f in get_files(self):
231 self.zip_readline_read_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000232
Ezio Melottiafd0d112009-07-15 17:17:17 +0000233 def zip_readline_test(self, f, compression):
234 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000235
236 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000237 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000238 with zipfp.open(TESTFN) as zipopen:
239 for line in self.line_gen:
240 linedata = zipopen.readline()
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300241 self.assertEqual(linedata, line)
242
243 def test_readline(self):
244 for f in get_files(self):
245 self.zip_readline_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000246
Ezio Melottiafd0d112009-07-15 17:17:17 +0000247 def zip_readlines_test(self, f, compression):
248 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000249
250 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000251 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000252 with zipfp.open(TESTFN) as zipopen:
253 ziplines = zipopen.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000254 for line, zipline in zip(self.line_gen, ziplines):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300255 self.assertEqual(zipline, line)
256
257 def test_readlines(self):
258 for f in get_files(self):
259 self.zip_readlines_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000260
Ezio Melottiafd0d112009-07-15 17:17:17 +0000261 def zip_iterlines_test(self, f, compression):
262 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000263
264 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000265 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000266 with zipfp.open(TESTFN) as zipopen:
267 for line, zipline in zip(self.line_gen, zipopen):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300268 self.assertEqual(zipline, line)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000269
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300270 def test_iterlines(self):
271 for f in get_files(self):
272 self.zip_iterlines_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000273
Ezio Melottiafd0d112009-07-15 17:17:17 +0000274 def test_low_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000275 """Check for cases where compressed data is larger than original."""
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000276 # Create the ZIP archive
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300277 with zipfile.ZipFile(TESTFN2, "w", self.compression) as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000278 zipfp.writestr("strfile", '12')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000279
280 # Get an open object for strfile
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300281 with zipfile.ZipFile(TESTFN2, "r", self.compression) as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000282 with zipfp.open("strfile") as openobj:
283 self.assertEqual(openobj.read(1), b'1')
284 self.assertEqual(openobj.read(1), b'2')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000285
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300286 def test_writestr_compression(self):
287 zipfp = zipfile.ZipFile(TESTFN2, "w")
288 zipfp.writestr("b.txt", "hello world", compress_type=self.compression)
289 info = zipfp.getinfo('b.txt')
290 self.assertEqual(info.compress_type, self.compression)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200291
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300292 def test_read_return_size(self):
293 # Issue #9837: ZipExtFile.read() shouldn't return more bytes
294 # than requested.
295 for test_size in (1, 4095, 4096, 4097, 16384):
296 file_size = test_size + 1
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +0200297 junk = getrandbytes(file_size)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300298 with zipfile.ZipFile(io.BytesIO(), "w", self.compression) as zipf:
299 zipf.writestr('foo', junk)
300 with zipf.open('foo', 'r') as fp:
301 buf = fp.read(test_size)
302 self.assertEqual(len(buf), test_size)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200303
Serhiy Storchaka5ce3f102014-01-09 14:50:20 +0200304 def test_truncated_zipfile(self):
305 fp = io.BytesIO()
306 with zipfile.ZipFile(fp, mode='w') as zipf:
307 zipf.writestr('strfile', self.data, compress_type=self.compression)
308 end_offset = fp.tell()
309 zipfiledata = fp.getvalue()
310
311 fp = io.BytesIO(zipfiledata)
312 with zipfile.ZipFile(fp) as zipf:
313 with zipf.open('strfile') as zipopen:
314 fp.truncate(end_offset - 20)
315 with self.assertRaises(EOFError):
316 zipopen.read()
317
318 fp = io.BytesIO(zipfiledata)
319 with zipfile.ZipFile(fp) as zipf:
320 with zipf.open('strfile') as zipopen:
321 fp.truncate(end_offset - 20)
322 with self.assertRaises(EOFError):
323 while zipopen.read(100):
324 pass
325
326 fp = io.BytesIO(zipfiledata)
327 with zipfile.ZipFile(fp) as zipf:
328 with zipf.open('strfile') as zipopen:
329 fp.truncate(end_offset - 20)
330 with self.assertRaises(EOFError):
331 while zipopen.read1(100):
332 pass
333
Serhiy Storchaka51a43702014-10-29 22:42:06 +0200334 def test_repr(self):
335 fname = 'file.name'
336 for f in get_files(self):
337 with zipfile.ZipFile(f, 'w', self.compression) as zipfp:
338 zipfp.write(TESTFN, fname)
339 r = repr(zipfp)
340 self.assertIn("mode='w'", r)
341
342 with zipfile.ZipFile(f, 'r') as zipfp:
343 r = repr(zipfp)
344 if isinstance(f, str):
345 self.assertIn('filename=%r' % f, r)
346 else:
347 self.assertIn('file=%r' % f, r)
348 self.assertIn("mode='r'", r)
349 r = repr(zipfp.getinfo(fname))
350 self.assertIn('filename=%r' % fname, r)
351 self.assertIn('filemode=', r)
352 self.assertIn('file_size=', r)
353 if self.compression != zipfile.ZIP_STORED:
354 self.assertIn('compress_type=', r)
355 self.assertIn('compress_size=', r)
356 with zipfp.open(fname) as zipopen:
357 r = repr(zipopen)
358 self.assertIn('name=%r' % fname, r)
359 self.assertIn("mode='r'", r)
360 if self.compression != zipfile.ZIP_STORED:
361 self.assertIn('compress_type=', r)
362 self.assertIn('[closed]', repr(zipopen))
363 self.assertIn('[closed]', repr(zipfp))
364
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300365 def tearDown(self):
366 unlink(TESTFN)
367 unlink(TESTFN2)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200368
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200369
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300370class StoredTestsWithSourceFile(AbstractTestsWithSourceFile,
371 unittest.TestCase):
372 compression = zipfile.ZIP_STORED
373 test_low_compression = None
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200374
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300375 def zip_test_writestr_permissions(self, f, compression):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300376 # Make sure that writestr and open(... mode='w') create files with
377 # mode 0600, when they are passed a name rather than a ZipInfo
378 # instance.
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200379
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300380 self.make_test_archive(f, compression)
381 with zipfile.ZipFile(f, "r") as zipfp:
382 zinfo = zipfp.getinfo('strfile')
383 self.assertEqual(zinfo.external_attr, 0o600 << 16)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200384
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300385 zinfo2 = zipfp.getinfo('written-open-w')
386 self.assertEqual(zinfo2.external_attr, 0o600 << 16)
387
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300388 def test_writestr_permissions(self):
389 for f in get_files(self):
390 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +0200391
Ezio Melottiafd0d112009-07-15 17:17:17 +0000392 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000393 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
394 zipfp.write(TESTFN, "/absolute")
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000395
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000396 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
397 self.assertEqual(zipfp.namelist(), ["absolute"])
Tim Peters32cbc962006-02-20 21:42:18 +0000398
Ezio Melottiafd0d112009-07-15 17:17:17 +0000399 def test_append_to_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000400 """Test appending to an existing zipfile."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000401 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
402 zipfp.write(TESTFN, TESTFN)
403
404 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
405 zipfp.writestr("strfile", self.data)
406 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000407
Ezio Melottiafd0d112009-07-15 17:17:17 +0000408 def test_append_to_non_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000409 """Test appending to an existing file that is not a zipfile."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000410 # NOTE: this test fails if len(d) < 22 because of the first
411 # line "fpin.seek(-22, 2)" in _EndRecData
Ezio Melotti35386712009-12-31 13:22:41 +0000412 data = b'I am not a ZipFile!'*10
413 with open(TESTFN2, 'wb') as f:
414 f.write(data)
415
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000416 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
417 zipfp.write(TESTFN, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000418
Ezio Melotti35386712009-12-31 13:22:41 +0000419 with open(TESTFN2, 'rb') as f:
420 f.seek(len(data))
421 with zipfile.ZipFile(f, "r") as zipfp:
422 self.assertEqual(zipfp.namelist(), [TESTFN])
Serhiy Storchaka8793b212016-10-07 22:20:50 +0300423 self.assertEqual(zipfp.read(TESTFN), self.data)
424 with open(TESTFN2, 'rb') as f:
425 self.assertEqual(f.read(len(data)), data)
426 zipfiledata = f.read()
427 with io.BytesIO(zipfiledata) as bio, zipfile.ZipFile(bio) as zipfp:
428 self.assertEqual(zipfp.namelist(), [TESTFN])
429 self.assertEqual(zipfp.read(TESTFN), self.data)
430
431 def test_read_concatenated_zip_file(self):
432 with io.BytesIO() as bio:
433 with zipfile.ZipFile(bio, 'w', zipfile.ZIP_STORED) as zipfp:
434 zipfp.write(TESTFN, TESTFN)
435 zipfiledata = bio.getvalue()
436 data = b'I am not a ZipFile!'*10
437 with open(TESTFN2, 'wb') as f:
438 f.write(data)
439 f.write(zipfiledata)
440
441 with zipfile.ZipFile(TESTFN2) as zipfp:
442 self.assertEqual(zipfp.namelist(), [TESTFN])
443 self.assertEqual(zipfp.read(TESTFN), self.data)
444
445 def test_append_to_concatenated_zip_file(self):
446 with io.BytesIO() as bio:
447 with zipfile.ZipFile(bio, 'w', zipfile.ZIP_STORED) as zipfp:
448 zipfp.write(TESTFN, TESTFN)
449 zipfiledata = bio.getvalue()
450 data = b'I am not a ZipFile!'*1000000
451 with open(TESTFN2, 'wb') as f:
452 f.write(data)
453 f.write(zipfiledata)
454
455 with zipfile.ZipFile(TESTFN2, 'a') as zipfp:
456 self.assertEqual(zipfp.namelist(), [TESTFN])
457 zipfp.writestr('strfile', self.data)
458
459 with open(TESTFN2, 'rb') as f:
460 self.assertEqual(f.read(len(data)), data)
461 zipfiledata = f.read()
462 with io.BytesIO(zipfiledata) as bio, zipfile.ZipFile(bio) as zipfp:
463 self.assertEqual(zipfp.namelist(), [TESTFN, 'strfile'])
464 self.assertEqual(zipfp.read(TESTFN), self.data)
465 self.assertEqual(zipfp.read('strfile'), self.data)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000466
R David Murray4fbb9db2011-06-09 15:50:51 -0400467 def test_ignores_newline_at_end(self):
468 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
469 zipfp.write(TESTFN, TESTFN)
470 with open(TESTFN2, 'a') as f:
471 f.write("\r\n\00\00\00")
472 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
473 self.assertIsInstance(zipfp, zipfile.ZipFile)
474
475 def test_ignores_stuff_appended_past_comments(self):
476 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
477 zipfp.comment = b"this is a comment"
478 zipfp.write(TESTFN, TESTFN)
479 with open(TESTFN2, 'a') as f:
480 f.write("abcdef\r\n")
481 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
482 self.assertIsInstance(zipfp, zipfile.ZipFile)
483 self.assertEqual(zipfp.comment, b"this is a comment")
484
Ezio Melottiafd0d112009-07-15 17:17:17 +0000485 def test_write_default_name(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000486 """Check that calling ZipFile.write without arcname specified
487 produces the expected result."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000488 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
489 zipfp.write(TESTFN)
Brian Curtin8fb9b862010-11-18 02:15:28 +0000490 with open(TESTFN, "rb") as f:
491 self.assertEqual(zipfp.read(TESTFN), f.read())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000492
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300493 def test_write_to_readonly(self):
494 """Check that trying to call write() on a readonly ZipFile object
Serhiy Storchakab0d497c2016-09-10 21:28:07 +0300495 raises a ValueError."""
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300496 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
497 zipfp.writestr("somefile.txt", "bogus")
498
499 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
Serhiy Storchakab0d497c2016-09-10 21:28:07 +0300500 self.assertRaises(ValueError, zipfp.write, TESTFN)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300501
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300502 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
Serhiy Storchakab0d497c2016-09-10 21:28:07 +0300503 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300504 zipfp.open(TESTFN, mode='w')
505
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300506 def test_add_file_before_1980(self):
507 # Set atime and mtime to 1970-01-01
508 os.utime(TESTFN, (0, 0))
509 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
510 self.assertRaises(ValueError, zipfp.write, TESTFN)
511
Serhiy Storchaka5ce3f102014-01-09 14:50:20 +0200512
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300513@requires_zlib
514class DeflateTestsWithSourceFile(AbstractTestsWithSourceFile,
515 unittest.TestCase):
516 compression = zipfile.ZIP_DEFLATED
517
Ezio Melottiafd0d112009-07-15 17:17:17 +0000518 def test_per_file_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000519 """Check that files within a Zip archive can have different
520 compression options."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000521 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
522 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
523 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
524 sinfo = zipfp.getinfo('storeme')
525 dinfo = zipfp.getinfo('deflateme')
526 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
527 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000528
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300529@requires_bz2
530class Bzip2TestsWithSourceFile(AbstractTestsWithSourceFile,
531 unittest.TestCase):
532 compression = zipfile.ZIP_BZIP2
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000533
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300534@requires_lzma
535class LzmaTestsWithSourceFile(AbstractTestsWithSourceFile,
536 unittest.TestCase):
537 compression = zipfile.ZIP_LZMA
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000538
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300539
540class AbstractTestZip64InSmallFiles:
541 # These tests test the ZIP64 functionality without using large files,
542 # see test_zipfile64 for proper tests.
543
544 @classmethod
545 def setUpClass(cls):
546 line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
547 for i in range(0, FIXEDTEST_SIZE))
548 cls.data = b'\n'.join(line_gen)
549
550 def setUp(self):
551 self._limit = zipfile.ZIP64_LIMIT
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300552 self._filecount_limit = zipfile.ZIP_FILECOUNT_LIMIT
553 zipfile.ZIP64_LIMIT = 1000
554 zipfile.ZIP_FILECOUNT_LIMIT = 9
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300555
556 # Make a source file with some lines
557 with open(TESTFN, "wb") as fp:
558 fp.write(self.data)
559
560 def zip_test(self, f, compression):
561 # Create the ZIP archive
562 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
563 zipfp.write(TESTFN, "another.name")
564 zipfp.write(TESTFN, TESTFN)
565 zipfp.writestr("strfile", self.data)
566
567 # Read the ZIP archive
568 with zipfile.ZipFile(f, "r", compression) as zipfp:
569 self.assertEqual(zipfp.read(TESTFN), self.data)
570 self.assertEqual(zipfp.read("another.name"), self.data)
571 self.assertEqual(zipfp.read("strfile"), self.data)
572
573 # Print the ZIP directory
574 fp = io.StringIO()
575 zipfp.printdir(fp)
576
577 directory = fp.getvalue()
578 lines = directory.splitlines()
579 self.assertEqual(len(lines), 4) # Number of files + header
580
581 self.assertIn('File Name', lines[0])
582 self.assertIn('Modified', lines[0])
583 self.assertIn('Size', lines[0])
584
585 fn, date, time_, size = lines[1].split()
586 self.assertEqual(fn, 'another.name')
587 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
588 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
589 self.assertEqual(size, str(len(self.data)))
590
591 # Check the namelist
592 names = zipfp.namelist()
593 self.assertEqual(len(names), 3)
594 self.assertIn(TESTFN, names)
595 self.assertIn("another.name", names)
596 self.assertIn("strfile", names)
597
598 # Check infolist
599 infos = zipfp.infolist()
600 names = [i.filename for i in infos]
601 self.assertEqual(len(names), 3)
602 self.assertIn(TESTFN, names)
603 self.assertIn("another.name", names)
604 self.assertIn("strfile", names)
605 for i in infos:
606 self.assertEqual(i.file_size, len(self.data))
607
608 # check getinfo
609 for nm in (TESTFN, "another.name", "strfile"):
610 info = zipfp.getinfo(nm)
611 self.assertEqual(info.filename, nm)
612 self.assertEqual(info.file_size, len(self.data))
613
614 # Check that testzip doesn't raise an exception
615 zipfp.testzip()
616
617 def test_basic(self):
618 for f in get_files(self):
619 self.zip_test(f, self.compression)
620
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300621 def test_too_many_files(self):
622 # This test checks that more than 64k files can be added to an archive,
623 # and that the resulting archive can be read properly by ZipFile
624 zipf = zipfile.ZipFile(TESTFN, "w", self.compression,
625 allowZip64=True)
626 zipf.debug = 100
627 numfiles = 15
628 for i in range(numfiles):
629 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
630 self.assertEqual(len(zipf.namelist()), numfiles)
631 zipf.close()
632
633 zipf2 = zipfile.ZipFile(TESTFN, "r", self.compression)
634 self.assertEqual(len(zipf2.namelist()), numfiles)
635 for i in range(numfiles):
636 content = zipf2.read("foo%08d" % i).decode('ascii')
637 self.assertEqual(content, "%d" % (i**3 % 57))
638 zipf2.close()
639
640 def test_too_many_files_append(self):
641 zipf = zipfile.ZipFile(TESTFN, "w", self.compression,
642 allowZip64=False)
643 zipf.debug = 100
644 numfiles = 9
645 for i in range(numfiles):
646 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
647 self.assertEqual(len(zipf.namelist()), numfiles)
648 with self.assertRaises(zipfile.LargeZipFile):
649 zipf.writestr("foo%08d" % numfiles, b'')
650 self.assertEqual(len(zipf.namelist()), numfiles)
651 zipf.close()
652
653 zipf = zipfile.ZipFile(TESTFN, "a", self.compression,
654 allowZip64=False)
655 zipf.debug = 100
656 self.assertEqual(len(zipf.namelist()), numfiles)
657 with self.assertRaises(zipfile.LargeZipFile):
658 zipf.writestr("foo%08d" % numfiles, b'')
659 self.assertEqual(len(zipf.namelist()), numfiles)
660 zipf.close()
661
662 zipf = zipfile.ZipFile(TESTFN, "a", self.compression,
663 allowZip64=True)
664 zipf.debug = 100
665 self.assertEqual(len(zipf.namelist()), numfiles)
666 numfiles2 = 15
667 for i in range(numfiles, numfiles2):
668 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
669 self.assertEqual(len(zipf.namelist()), numfiles2)
670 zipf.close()
671
672 zipf2 = zipfile.ZipFile(TESTFN, "r", self.compression)
673 self.assertEqual(len(zipf2.namelist()), numfiles2)
674 for i in range(numfiles2):
675 content = zipf2.read("foo%08d" % i).decode('ascii')
676 self.assertEqual(content, "%d" % (i**3 % 57))
677 zipf2.close()
678
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300679 def tearDown(self):
680 zipfile.ZIP64_LIMIT = self._limit
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300681 zipfile.ZIP_FILECOUNT_LIMIT = self._filecount_limit
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300682 unlink(TESTFN)
683 unlink(TESTFN2)
684
685
686class StoredTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
687 unittest.TestCase):
688 compression = zipfile.ZIP_STORED
689
690 def large_file_exception_test(self, f, compression):
Serhiy Storchaka235c5e02013-11-23 15:55:38 +0200691 with zipfile.ZipFile(f, "w", compression, allowZip64=False) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300692 self.assertRaises(zipfile.LargeZipFile,
693 zipfp.write, TESTFN, "another.name")
694
695 def large_file_exception_test2(self, f, compression):
Serhiy Storchaka235c5e02013-11-23 15:55:38 +0200696 with zipfile.ZipFile(f, "w", compression, allowZip64=False) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300697 self.assertRaises(zipfile.LargeZipFile,
698 zipfp.writestr, "another.name", self.data)
699
700 def test_large_file_exception(self):
701 for f in get_files(self):
702 self.large_file_exception_test(f, zipfile.ZIP_STORED)
703 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
704
705 def test_absolute_arcnames(self):
706 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
707 allowZip64=True) as zipfp:
708 zipfp.write(TESTFN, "/absolute")
709
710 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
711 self.assertEqual(zipfp.namelist(), ["absolute"])
712
713@requires_zlib
714class DeflateTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
715 unittest.TestCase):
716 compression = zipfile.ZIP_DEFLATED
717
718@requires_bz2
719class Bzip2TestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
720 unittest.TestCase):
721 compression = zipfile.ZIP_BZIP2
722
723@requires_lzma
724class LzmaTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
725 unittest.TestCase):
726 compression = zipfile.ZIP_LZMA
727
728
729class PyZipFileTests(unittest.TestCase):
730 def assertCompiledIn(self, name, namelist):
731 if name + 'o' not in namelist:
732 self.assertIn(name + 'c', namelist)
733
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200734 def requiresWriteAccess(self, path):
Berker Peksage1efc072015-02-16 04:36:18 +0200735 # effective_ids unavailable on windows
736 if not os.access(path, os.W_OK,
737 effective_ids=os.access in os.supports_effective_ids):
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200738 self.skipTest('requires write access to the installed location')
Serhiy Storchakad86a6ef2015-09-19 10:55:20 +0300739 filename = os.path.join(path, 'test_zipfile.try')
740 try:
741 fd = os.open(filename, os.O_WRONLY | os.O_CREAT)
742 os.close(fd)
743 except Exception:
744 self.skipTest('requires write access to the installed location')
745 unlink(filename)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200746
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300747 def test_write_pyfile(self):
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200748 self.requiresWriteAccess(os.path.dirname(__file__))
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300749 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
750 fn = __file__
Brett Cannonf299abd2015-04-13 14:21:02 -0400751 if fn.endswith('.pyc'):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300752 path_split = fn.split(os.sep)
753 if os.altsep is not None:
754 path_split.extend(fn.split(os.altsep))
755 if '__pycache__' in path_split:
Serhiy Storchaka9068e4d2013-07-22 21:02:14 +0300756 fn = importlib.util.source_from_cache(fn)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300757 else:
758 fn = fn[:-1]
759
760 zipfp.writepy(fn)
761
762 bn = os.path.basename(fn)
763 self.assertNotIn(bn, zipfp.namelist())
764 self.assertCompiledIn(bn, zipfp.namelist())
765
766 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
767 fn = __file__
Brett Cannonf299abd2015-04-13 14:21:02 -0400768 if fn.endswith('.pyc'):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300769 fn = fn[:-1]
770
771 zipfp.writepy(fn, "testpackage")
772
773 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
774 self.assertNotIn(bn, zipfp.namelist())
775 self.assertCompiledIn(bn, zipfp.namelist())
776
777 def test_write_python_package(self):
778 import email
779 packagedir = os.path.dirname(email.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200780 self.requiresWriteAccess(packagedir)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300781
782 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
783 zipfp.writepy(packagedir)
784
785 # Check for a couple of modules at different levels of the
786 # hierarchy
787 names = zipfp.namelist()
788 self.assertCompiledIn('email/__init__.py', names)
789 self.assertCompiledIn('email/mime/text.py', names)
790
Christian Tismer59202e52013-10-21 03:59:23 +0200791 def test_write_filtered_python_package(self):
792 import test
793 packagedir = os.path.dirname(test.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200794 self.requiresWriteAccess(packagedir)
Christian Tismer59202e52013-10-21 03:59:23 +0200795
796 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
797
Christian Tismer59202e52013-10-21 03:59:23 +0200798 # first make sure that the test folder gives error messages
Georg Brandla6065422013-10-21 08:29:29 +0200799 # (on the badsyntax_... files)
800 with captured_stdout() as reportSIO:
801 zipfp.writepy(packagedir)
Christian Tismer59202e52013-10-21 03:59:23 +0200802 reportStr = reportSIO.getvalue()
803 self.assertTrue('SyntaxError' in reportStr)
804
Christian Tismer410d9312013-10-22 04:09:28 +0200805 # then check that the filter works on the whole package
Georg Brandla6065422013-10-21 08:29:29 +0200806 with captured_stdout() as reportSIO:
807 zipfp.writepy(packagedir, filterfunc=lambda whatever: False)
Christian Tismer59202e52013-10-21 03:59:23 +0200808 reportStr = reportSIO.getvalue()
809 self.assertTrue('SyntaxError' not in reportStr)
810
Christian Tismer410d9312013-10-22 04:09:28 +0200811 # then check that the filter works on individual files
Larry Hastings7e63b362015-05-08 06:54:58 -0700812 def filter(path):
813 return not os.path.basename(path).startswith("bad")
Serhiy Storchakac46d1fa2014-01-20 21:59:33 +0200814 with captured_stdout() as reportSIO, self.assertWarns(UserWarning):
Larry Hastings7e63b362015-05-08 06:54:58 -0700815 zipfp.writepy(packagedir, filterfunc=filter)
Christian Tismer410d9312013-10-22 04:09:28 +0200816 reportStr = reportSIO.getvalue()
817 if reportStr:
818 print(reportStr)
819 self.assertTrue('SyntaxError' not in reportStr)
820
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300821 def test_write_with_optimization(self):
822 import email
823 packagedir = os.path.dirname(email.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200824 self.requiresWriteAccess(packagedir)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300825 optlevel = 1 if __debug__ else 0
Brett Cannonf299abd2015-04-13 14:21:02 -0400826 ext = '.pyc'
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300827
828 with TemporaryFile() as t, \
Christian Tismer59202e52013-10-21 03:59:23 +0200829 zipfile.PyZipFile(t, "w", optimize=optlevel) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300830 zipfp.writepy(packagedir)
831
832 names = zipfp.namelist()
833 self.assertIn('email/__init__' + ext, names)
834 self.assertIn('email/mime/text' + ext, names)
835
836 def test_write_python_directory(self):
837 os.mkdir(TESTFN2)
838 try:
839 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
840 fp.write("print(42)\n")
841
842 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
843 fp.write("print(42 * 42)\n")
844
845 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
846 fp.write("bla bla bla\n")
847
848 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
849 zipfp.writepy(TESTFN2)
850
851 names = zipfp.namelist()
852 self.assertCompiledIn('mod1.py', names)
853 self.assertCompiledIn('mod2.py', names)
854 self.assertNotIn('mod2.txt', names)
855
856 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200857 rmtree(TESTFN2)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300858
Christian Tismer410d9312013-10-22 04:09:28 +0200859 def test_write_python_directory_filtered(self):
860 os.mkdir(TESTFN2)
861 try:
862 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
863 fp.write("print(42)\n")
864
865 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
866 fp.write("print(42 * 42)\n")
867
868 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
869 zipfp.writepy(TESTFN2, filterfunc=lambda fn:
870 not fn.endswith('mod2.py'))
871
872 names = zipfp.namelist()
873 self.assertCompiledIn('mod1.py', names)
874 self.assertNotIn('mod2.py', names)
875
876 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200877 rmtree(TESTFN2)
Christian Tismer410d9312013-10-22 04:09:28 +0200878
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300879 def test_write_non_pyfile(self):
880 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
881 with open(TESTFN, 'w') as f:
882 f.write('most definitely not a python file')
883 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
Victor Stinner88b215e2014-09-04 00:51:09 +0200884 unlink(TESTFN)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300885
886 def test_write_pyfile_bad_syntax(self):
887 os.mkdir(TESTFN2)
888 try:
889 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
890 fp.write("Bad syntax in python file\n")
891
892 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
893 # syntax errors are printed to stdout
894 with captured_stdout() as s:
895 zipfp.writepy(os.path.join(TESTFN2, "mod1.py"))
896
897 self.assertIn("SyntaxError", s.getvalue())
898
899 # as it will not have compiled the python file, it will
Brett Cannonf299abd2015-04-13 14:21:02 -0400900 # include the .py file not .pyc
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300901 names = zipfp.namelist()
902 self.assertIn('mod1.py', names)
903 self.assertNotIn('mod1.pyc', names)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300904
905 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200906 rmtree(TESTFN2)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300907
908
909class ExtractTests(unittest.TestCase):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000910 def test_extract(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000911 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
912 for fpath, fdata in SMALL_TEST_DATA:
913 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000914
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000915 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
916 for fpath, fdata in SMALL_TEST_DATA:
917 writtenfile = zipfp.extract(fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000918
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000919 # make sure it was written to the right place
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800920 correctfile = os.path.join(os.getcwd(), fpath)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000921 correctfile = os.path.normpath(correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000922
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000923 self.assertEqual(writtenfile, correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000924
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000925 # make sure correct data is in correct file
Brian Curtin8fb9b862010-11-18 02:15:28 +0000926 with open(writtenfile, "rb") as f:
927 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000928
Victor Stinner88b215e2014-09-04 00:51:09 +0200929 unlink(writtenfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000930
931 # remove the test file subdirectories
Victor Stinner57004c62014-09-04 00:49:01 +0200932 rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
Christian Heimes790c8232008-01-07 21:14:23 +0000933
Ezio Melottiafd0d112009-07-15 17:17:17 +0000934 def test_extract_all(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000935 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
936 for fpath, fdata in SMALL_TEST_DATA:
937 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000938
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000939 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
940 zipfp.extractall()
941 for fpath, fdata in SMALL_TEST_DATA:
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800942 outfile = os.path.join(os.getcwd(), fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000943
Brian Curtin8fb9b862010-11-18 02:15:28 +0000944 with open(outfile, "rb") as f:
945 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000946
Victor Stinner88b215e2014-09-04 00:51:09 +0200947 unlink(outfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000948
949 # remove the test file subdirectories
Victor Stinner57004c62014-09-04 00:49:01 +0200950 rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
Christian Heimes790c8232008-01-07 21:14:23 +0000951
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800952 def check_file(self, filename, content):
953 self.assertTrue(os.path.isfile(filename))
954 with open(filename, 'rb') as f:
955 self.assertEqual(f.read(), content)
956
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800957 def test_sanitize_windows_name(self):
958 san = zipfile.ZipFile._sanitize_windows_name
959 # Passing pathsep in allows this test to work regardless of platform.
960 self.assertEqual(san(r',,?,C:,foo,bar/z', ','), r'_,C_,foo,bar/z')
961 self.assertEqual(san(r'a\b,c<d>e|f"g?h*i', ','), r'a\b,c_d_e_f_g_h_i')
962 self.assertEqual(san('../../foo../../ba..r', '/'), r'foo/ba..r')
963
964 def test_extract_hackers_arcnames_common_cases(self):
965 common_hacknames = [
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800966 ('../foo/bar', 'foo/bar'),
967 ('foo/../bar', 'foo/bar'),
968 ('foo/../../bar', 'foo/bar'),
969 ('foo/bar/..', 'foo/bar'),
970 ('./../foo/bar', 'foo/bar'),
971 ('/foo/bar', 'foo/bar'),
972 ('/foo/../bar', 'foo/bar'),
973 ('/foo/../../bar', 'foo/bar'),
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800974 ]
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800975 self._test_extract_hackers_arcnames(common_hacknames)
976
977 @unittest.skipIf(os.path.sep != '\\', 'Requires \\ as path separator.')
978 def test_extract_hackers_arcnames_windows_only(self):
979 """Test combination of path fixing and windows name sanitization."""
980 windows_hacknames = [
Christian Tismer59202e52013-10-21 03:59:23 +0200981 (r'..\foo\bar', 'foo/bar'),
982 (r'..\/foo\/bar', 'foo/bar'),
983 (r'foo/\..\/bar', 'foo/bar'),
984 (r'foo\/../\bar', 'foo/bar'),
985 (r'C:foo/bar', 'foo/bar'),
986 (r'C:/foo/bar', 'foo/bar'),
987 (r'C://foo/bar', 'foo/bar'),
988 (r'C:\foo\bar', 'foo/bar'),
989 (r'//conky/mountpoint/foo/bar', 'foo/bar'),
990 (r'\\conky\mountpoint\foo\bar', 'foo/bar'),
991 (r'///conky/mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
992 (r'\\\conky\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
993 (r'//conky//mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
994 (r'\\conky\\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
995 (r'//?/C:/foo/bar', 'foo/bar'),
996 (r'\\?\C:\foo\bar', 'foo/bar'),
997 (r'C:/../C:/foo/bar', 'C_/foo/bar'),
998 (r'a:b\c<d>e|f"g?h*i', 'b/c_d_e_f_g_h_i'),
999 ('../../foo../../ba..r', 'foo/ba..r'),
Gregory P. Smith09aa7522013-02-03 00:36:32 -08001000 ]
1001 self._test_extract_hackers_arcnames(windows_hacknames)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001002
Gregory P. Smith09aa7522013-02-03 00:36:32 -08001003 @unittest.skipIf(os.path.sep != '/', r'Requires / as path separator.')
1004 def test_extract_hackers_arcnames_posix_only(self):
1005 posix_hacknames = [
1006 ('//foo/bar', 'foo/bar'),
1007 ('../../foo../../ba..r', 'foo../ba..r'),
1008 (r'foo/..\bar', r'foo/..\bar'),
1009 ]
1010 self._test_extract_hackers_arcnames(posix_hacknames)
1011
1012 def _test_extract_hackers_arcnames(self, hacknames):
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001013 for arcname, fixedname in hacknames:
1014 content = b'foobar' + arcname.encode()
1015 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipfp:
Serhiy Storchakae5e64442013-02-02 19:50:59 +02001016 zinfo = zipfile.ZipInfo()
1017 # preserve backslashes
1018 zinfo.filename = arcname
1019 zinfo.external_attr = 0o600 << 16
1020 zipfp.writestr(zinfo, content)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001021
Serhiy Storchakae5e64442013-02-02 19:50:59 +02001022 arcname = arcname.replace(os.sep, "/")
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001023 targetpath = os.path.join('target', 'subdir', 'subsub')
1024 correctfile = os.path.join(targetpath, *fixedname.split('/'))
1025
1026 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1027 writtenfile = zipfp.extract(arcname, targetpath)
Serhiy Storchakae5e64442013-02-02 19:50:59 +02001028 self.assertEqual(writtenfile, correctfile,
Gregory P. Smith09aa7522013-02-03 00:36:32 -08001029 msg='extract %r: %r != %r' %
1030 (arcname, writtenfile, correctfile))
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001031 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001032 rmtree('target')
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001033
1034 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1035 zipfp.extractall(targetpath)
1036 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001037 rmtree('target')
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001038
1039 correctfile = os.path.join(os.getcwd(), *fixedname.split('/'))
1040
1041 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1042 writtenfile = zipfp.extract(arcname)
Serhiy Storchakae5e64442013-02-02 19:50:59 +02001043 self.assertEqual(writtenfile, correctfile,
1044 msg="extract %r" % arcname)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001045 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001046 rmtree(fixedname.split('/')[0])
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001047
1048 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1049 zipfp.extractall()
1050 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001051 rmtree(fixedname.split('/')[0])
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001052
Victor Stinner88b215e2014-09-04 00:51:09 +02001053 unlink(TESTFN2)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001054
Ronald Oussorenee5c8852010-02-07 20:24:02 +00001055
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001056class OtherTests(unittest.TestCase):
1057 def test_open_via_zip_info(self):
1058 # Create the ZIP archive
1059 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
1060 zipfp.writestr("name", "foo")
Serhiy Storchaka9b7a1a12014-01-20 21:57:40 +02001061 with self.assertWarns(UserWarning):
1062 zipfp.writestr("name", "bar")
1063 self.assertEqual(zipfp.namelist(), ["name"] * 2)
Ronald Oussorenee5c8852010-02-07 20:24:02 +00001064
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001065 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1066 infos = zipfp.infolist()
1067 data = b""
1068 for info in infos:
1069 with zipfp.open(info) as zipopen:
1070 data += zipopen.read()
1071 self.assertIn(data, {b"foobar", b"barfoo"})
1072 data = b""
1073 for info in infos:
1074 data += zipfp.read(info)
1075 self.assertIn(data, {b"foobar", b"barfoo"})
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001076
Gregory P. Smithb0d9ca922009-07-07 05:06:04 +00001077 def test_writestr_extended_local_header_issue1202(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001078 with zipfile.ZipFile(TESTFN2, 'w') as orig_zip:
1079 for data in 'abcdefghijklmnop':
1080 zinfo = zipfile.ZipInfo(data)
1081 zinfo.flag_bits |= 0x08 # Include an extended local header.
1082 orig_zip.writestr(zinfo, data)
1083
1084 def test_close(self):
1085 """Check that the zipfile is closed after the 'with' block."""
1086 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
1087 for fpath, fdata in SMALL_TEST_DATA:
1088 zipfp.writestr(fpath, fdata)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001089 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
1090 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001091
1092 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001093 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
1094 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001095
1096 def test_close_on_exception(self):
1097 """Check that the zipfile is closed if an exception is raised in the
1098 'with' block."""
1099 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
1100 for fpath, fdata in SMALL_TEST_DATA:
1101 zipfp.writestr(fpath, fdata)
1102
1103 try:
1104 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
Georg Brandl4d540882010-10-28 06:42:33 +00001105 raise zipfile.BadZipFile()
1106 except zipfile.BadZipFile:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001107 self.assertIsNone(zipfp2.fp, 'zipfp is not closed')
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001108
Martin v. Löwisd099b562012-05-01 14:08:22 +02001109 def test_unsupported_version(self):
1110 # File has an extract_version of 120
1111 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 +02001112 b'\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00xPK\x01\x02x\x03x\x00\x00\x00\x00'
1113 b'\x00!p\xa1@\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00'
1114 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00\x00xPK\x05\x06'
1115 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 +03001116
Martin v. Löwisd099b562012-05-01 14:08:22 +02001117 self.assertRaises(NotImplementedError, zipfile.ZipFile,
1118 io.BytesIO(data), 'r')
1119
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001120 @requires_zlib
1121 def test_read_unicode_filenames(self):
1122 # bug #10801
1123 fname = findfile('zip_cp437_header.zip')
1124 with zipfile.ZipFile(fname) as zipfp:
1125 for name in zipfp.namelist():
1126 zipfp.open(name).close()
1127
1128 def test_write_unicode_filenames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001129 with zipfile.ZipFile(TESTFN, "w") as zf:
1130 zf.writestr("foo.txt", "Test for unicode filename")
1131 zf.writestr("\xf6.txt", "Test for unicode filename")
Ezio Melottie9615932010-01-24 19:26:24 +00001132 self.assertIsInstance(zf.infolist()[0].filename, str)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001133
1134 with zipfile.ZipFile(TESTFN, "r") as zf:
1135 self.assertEqual(zf.filelist[0].filename, "foo.txt")
1136 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
Martin v. Löwis8570f6a2008-05-05 17:44:38 +00001137
Serhiy Storchaka764fc9b2015-03-25 10:09:41 +02001138 def test_exclusive_create_zip_file(self):
1139 """Test exclusive creating a new zipfile."""
1140 unlink(TESTFN2)
1141 filename = 'testfile.txt'
1142 content = b'hello, world. this is some content.'
1143 with zipfile.ZipFile(TESTFN2, "x", zipfile.ZIP_STORED) as zipfp:
1144 zipfp.writestr(filename, content)
1145 with self.assertRaises(FileExistsError):
1146 zipfile.ZipFile(TESTFN2, "x", zipfile.ZIP_STORED)
1147 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1148 self.assertEqual(zipfp.namelist(), [filename])
1149 self.assertEqual(zipfp.read(filename), content)
1150
Ezio Melottiafd0d112009-07-15 17:17:17 +00001151 def test_create_non_existent_file_for_append(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001152 if os.path.exists(TESTFN):
1153 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001154
Thomas Wouterscf297e42007-02-23 15:07:44 +00001155 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001156 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +00001157
Thomas Wouterscf297e42007-02-23 15:07:44 +00001158 try:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001159 with zipfile.ZipFile(TESTFN, 'a') as zf:
1160 zf.writestr(filename, content)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001161 except OSError:
Thomas Wouterscf297e42007-02-23 15:07:44 +00001162 self.fail('Could not append data to a non-existent zip file.')
1163
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001164 self.assertTrue(os.path.exists(TESTFN))
Thomas Wouterscf297e42007-02-23 15:07:44 +00001165
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001166 with zipfile.ZipFile(TESTFN, 'r') as zf:
1167 self.assertEqual(zf.read(filename), content)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001168
Ezio Melottiafd0d112009-07-15 17:17:17 +00001169 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001170 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti35386712009-12-31 13:22:41 +00001171 # it opens if there's an error in the file. If it doesn't, the
1172 # traceback holds a reference to the ZipFile object and, indirectly,
1173 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001174 # On Windows, this causes the os.unlink() call to fail because the
1175 # underlying file is still open. This is SF bug #412214.
1176 #
Ezio Melotti35386712009-12-31 13:22:41 +00001177 with open(TESTFN, "w") as fp:
1178 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001179 try:
1180 zf = zipfile.ZipFile(TESTFN)
Georg Brandl4d540882010-10-28 06:42:33 +00001181 except zipfile.BadZipFile:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001182 pass
1183
Ezio Melottiafd0d112009-07-15 17:17:17 +00001184 def test_is_zip_erroneous_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001185 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001186 # - passing a filename
1187 with open(TESTFN, "w") as fp:
1188 fp.write("this is not a legal zip file\n")
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001189 self.assertFalse(zipfile.is_zipfile(TESTFN))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001190 # - passing a file object
1191 with open(TESTFN, "rb") as fp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001192 self.assertFalse(zipfile.is_zipfile(fp))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001193 # - passing a file-like object
1194 fp = io.BytesIO()
1195 fp.write(b"this is not a legal zip file\n")
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001196 self.assertFalse(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001197 fp.seek(0, 0)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001198 self.assertFalse(zipfile.is_zipfile(fp))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001199
Serhiy Storchakad2b15272013-01-31 15:27:07 +02001200 def test_damaged_zipfile(self):
1201 """Check that zipfiles with missing bytes at the end raise BadZipFile."""
1202 # - Create a valid zip file
1203 fp = io.BytesIO()
1204 with zipfile.ZipFile(fp, mode="w") as zipf:
1205 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
1206 zipfiledata = fp.getvalue()
1207
1208 # - Now create copies of it missing the last N bytes and make sure
1209 # a BadZipFile exception is raised when we try to open it
1210 for N in range(len(zipfiledata)):
1211 fp = io.BytesIO(zipfiledata[:N])
1212 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, fp)
1213
Ezio Melottiafd0d112009-07-15 17:17:17 +00001214 def test_is_zip_valid_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001215 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001216 # - passing a filename
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001217 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1218 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
1219
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001220 self.assertTrue(zipfile.is_zipfile(TESTFN))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001221 # - passing a file object
1222 with open(TESTFN, "rb") as fp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001223 self.assertTrue(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001224 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001225 zip_contents = fp.read()
1226 # - passing a file-like object
1227 fp = io.BytesIO()
1228 fp.write(zip_contents)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001229 self.assertTrue(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001230 fp.seek(0, 0)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001231 self.assertTrue(zipfile.is_zipfile(fp))
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001232
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001233 def test_non_existent_file_raises_OSError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001234 # make sure we don't raise an AttributeError when a partially-constructed
1235 # ZipFile instance is finalized; this tests for regression on SF tracker
1236 # bug #403871.
1237
1238 # The bug we're testing for caused an AttributeError to be raised
1239 # when a ZipFile instance was created for a file that did not
1240 # exist; the .fp member was not initialized but was needed by the
1241 # __del__() method. Since the AttributeError is in the __del__(),
1242 # it is ignored, but the user should be sufficiently annoyed by
1243 # the message on the output that regression will be noticed
1244 # quickly.
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001245 self.assertRaises(OSError, zipfile.ZipFile, TESTFN)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001246
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001247 def test_empty_file_raises_BadZipFile(self):
1248 f = open(TESTFN, 'w')
1249 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001250 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001251
Ezio Melotti35386712009-12-31 13:22:41 +00001252 with open(TESTFN, 'w') as fp:
1253 fp.write("short file")
Georg Brandl4d540882010-10-28 06:42:33 +00001254 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001255
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001256 def test_closed_zip_raises_ValueError(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001257 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001258 data = io.BytesIO()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001259 with zipfile.ZipFile(data, mode="w") as zipf:
1260 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001261
Andrew Svetlov737fb892012-12-18 21:14:22 +02001262 # This is correct; calling .read on a closed ZipFile should raise
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001263 # a ValueError, and so should calling .testzip. An earlier
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001264 # version of .testzip would swallow this exception (and any other)
1265 # and report that the first file in the archive was corrupt.
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001266 self.assertRaises(ValueError, zipf.read, "foo.txt")
1267 self.assertRaises(ValueError, zipf.open, "foo.txt")
1268 self.assertRaises(ValueError, zipf.testzip)
1269 self.assertRaises(ValueError, zipf.writestr, "bogus.txt", "bogus")
Brian Curtin8fb9b862010-11-18 02:15:28 +00001270 with open(TESTFN, 'w') as f:
1271 f.write('zipfile test data')
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001272 self.assertRaises(ValueError, zipf.write, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001273
Ezio Melottiafd0d112009-07-15 17:17:17 +00001274 def test_bad_constructor_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001275 """Check that bad modes passed to ZipFile constructor are caught."""
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001276 self.assertRaises(ValueError, zipfile.ZipFile, TESTFN, "q")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001277
Ezio Melottiafd0d112009-07-15 17:17:17 +00001278 def test_bad_open_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001279 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001280 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1281 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1282
1283 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Serhiy Storchakae670be22016-06-11 19:32:44 +03001284 # read the data to make sure the file is there
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001285 zipf.read("foo.txt")
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001286 self.assertRaises(ValueError, zipf.open, "foo.txt", "q")
Serhiy Storchakae670be22016-06-11 19:32:44 +03001287 # universal newlines support is removed
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001288 self.assertRaises(ValueError, zipf.open, "foo.txt", "U")
1289 self.assertRaises(ValueError, zipf.open, "foo.txt", "rU")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001290
Ezio Melottiafd0d112009-07-15 17:17:17 +00001291 def test_read0(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001292 """Check that calling read(0) on a ZipExtFile object returns an empty
1293 string and doesn't advance file pointer."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001294 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1295 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1296 # read the data to make sure the file is there
Brian Curtin8fb9b862010-11-18 02:15:28 +00001297 with zipf.open("foo.txt") as f:
1298 for i in range(FIXEDTEST_SIZE):
1299 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001300
Brian Curtin8fb9b862010-11-18 02:15:28 +00001301 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001302
Ezio Melottiafd0d112009-07-15 17:17:17 +00001303 def test_open_non_existent_item(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001304 """Check that attempting to call open() for an item that doesn't
1305 exist in the archive raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001306 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1307 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001308
Ezio Melottiafd0d112009-07-15 17:17:17 +00001309 def test_bad_compression_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001310 """Check that bad compression methods passed to ZipFile.open are
1311 caught."""
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001312 self.assertRaises(NotImplementedError, zipfile.ZipFile, TESTFN, "w", -1)
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001313
Martin v. Löwisb3260f02012-05-01 08:38:01 +02001314 def test_unsupported_compression(self):
1315 # data is declared as shrunk, but actually deflated
1316 data = (b'PK\x03\x04.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00'
Christian Tismer59202e52013-10-21 03:59:23 +02001317 b'\x00\x02\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00x\x03\x00PK\x01'
1318 b'\x02.\x03.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00\x00\x02\x00\x00'
1319 b'\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
1320 b'\x80\x01\x00\x00\x00\x00xPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00'
1321 b'/\x00\x00\x00!\x00\x00\x00\x00\x00')
Martin v. Löwisb3260f02012-05-01 08:38:01 +02001322 with zipfile.ZipFile(io.BytesIO(data), 'r') as zipf:
1323 self.assertRaises(NotImplementedError, zipf.open, 'x')
1324
Ezio Melottiafd0d112009-07-15 17:17:17 +00001325 def test_null_byte_in_filename(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001326 """Check that a filename containing a null byte is properly
1327 terminated."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001328 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1329 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
1330 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001331
Ezio Melottiafd0d112009-07-15 17:17:17 +00001332 def test_struct_sizes(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001333 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001334 self.assertEqual(zipfile.sizeEndCentDir, 22)
1335 self.assertEqual(zipfile.sizeCentralDir, 46)
1336 self.assertEqual(zipfile.sizeEndCentDir64, 56)
1337 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
1338
Ezio Melottiafd0d112009-07-15 17:17:17 +00001339 def test_comments(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001340 """Check that comments on the archive are handled properly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001341
1342 # check default comment is empty
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001343 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1344 self.assertEqual(zipf.comment, b'')
1345 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1346
1347 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1348 self.assertEqual(zipfr.comment, b'')
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001349
1350 # check a simple short comment
1351 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001352 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1353 zipf.comment = comment
1354 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1355 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1356 self.assertEqual(zipf.comment, comment)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001357
1358 # check a comment of max length
1359 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
1360 comment2 = comment2.encode("ascii")
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001361 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1362 zipf.comment = comment2
1363 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1364
1365 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1366 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001367
1368 # check a comment that is too long is truncated
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001369 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
Serhiy Storchaka9b7a1a12014-01-20 21:57:40 +02001370 with self.assertWarns(UserWarning):
1371 zipf.comment = comment2 + b'oops'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001372 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1373 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1374 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001375
Antoine Pitrouc3991852012-06-30 17:31:37 +02001376 # check that comments are correctly modified in append mode
1377 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1378 zipf.comment = b"original comment"
1379 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1380 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1381 zipf.comment = b"an updated comment"
1382 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1383 self.assertEqual(zipf.comment, b"an updated comment")
1384
1385 # check that comments are correctly shortened in append mode
1386 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1387 zipf.comment = b"original comment that's longer"
1388 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1389 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1390 zipf.comment = b"shorter comment"
1391 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1392 self.assertEqual(zipf.comment, b"shorter comment")
1393
R David Murrayf50b38a2012-04-12 18:44:58 -04001394 def test_unicode_comment(self):
1395 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1396 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1397 with self.assertRaises(TypeError):
1398 zipf.comment = "this is an error"
1399
1400 def test_change_comment_in_empty_archive(self):
1401 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1402 self.assertFalse(zipf.filelist)
1403 zipf.comment = b"this is a comment"
1404 with zipfile.ZipFile(TESTFN, "r") as zipf:
1405 self.assertEqual(zipf.comment, b"this is a comment")
1406
1407 def test_change_comment_in_nonempty_archive(self):
1408 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1409 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1410 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1411 self.assertTrue(zipf.filelist)
1412 zipf.comment = b"this is a comment"
1413 with zipfile.ZipFile(TESTFN, "r") as zipf:
1414 self.assertEqual(zipf.comment, b"this is a comment")
1415
Georg Brandl268e4d42010-10-14 06:59:45 +00001416 def test_empty_zipfile(self):
1417 # Check that creating a file in 'w' or 'a' mode and closing without
1418 # adding any files to the archives creates a valid empty ZIP file
1419 zipf = zipfile.ZipFile(TESTFN, mode="w")
1420 zipf.close()
1421 try:
1422 zipf = zipfile.ZipFile(TESTFN, mode="r")
1423 except zipfile.BadZipFile:
1424 self.fail("Unable to create empty ZIP file in 'w' mode")
1425
1426 zipf = zipfile.ZipFile(TESTFN, mode="a")
1427 zipf.close()
1428 try:
1429 zipf = zipfile.ZipFile(TESTFN, mode="r")
1430 except:
1431 self.fail("Unable to create empty ZIP file in 'a' mode")
1432
1433 def test_open_empty_file(self):
1434 # Issue 1710703: Check that opening a file with less than 22 bytes
Georg Brandl4d540882010-10-28 06:42:33 +00001435 # raises a BadZipFile exception (rather than the previously unhelpful
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001436 # OSError)
Georg Brandl268e4d42010-10-14 06:59:45 +00001437 f = open(TESTFN, 'w')
1438 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001439 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN, 'r')
Georg Brandl268e4d42010-10-14 06:59:45 +00001440
Senthil Kumaran29fa9d42011-10-20 01:46:00 +08001441 def test_create_zipinfo_before_1980(self):
1442 self.assertRaises(ValueError,
1443 zipfile.ZipInfo, 'seventies', (1979, 1, 1, 0, 0, 0))
1444
Gregory P. Smith0af8a862014-05-29 23:42:14 -07001445 def test_zipfile_with_short_extra_field(self):
1446 """If an extra field in the header is less than 4 bytes, skip it."""
1447 zipdata = (
1448 b'PK\x03\x04\x14\x00\x00\x00\x00\x00\x93\x9b\xad@\x8b\x9e'
1449 b'\xd9\xd3\x01\x00\x00\x00\x01\x00\x00\x00\x03\x00\x03\x00ab'
1450 b'c\x00\x00\x00APK\x01\x02\x14\x03\x14\x00\x00\x00\x00'
1451 b'\x00\x93\x9b\xad@\x8b\x9e\xd9\xd3\x01\x00\x00\x00\x01\x00\x00'
1452 b'\x00\x03\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00'
1453 b'\x00\x00\x00abc\x00\x00PK\x05\x06\x00\x00\x00\x00'
1454 b'\x01\x00\x01\x003\x00\x00\x00%\x00\x00\x00\x00\x00'
1455 )
1456 with zipfile.ZipFile(io.BytesIO(zipdata), 'r') as zipf:
1457 # testzip returns the name of the first corrupt file, or None
1458 self.assertIsNone(zipf.testzip())
1459
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001460 def test_open_conflicting_handles(self):
1461 # It's only possible to open one writable file handle at a time
1462 msg1 = b"It's fun to charter an accountant!"
1463 msg2 = b"And sail the wide accountant sea"
1464 msg3 = b"To find, explore the funds offshore"
1465 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipf:
1466 with zipf.open('foo', mode='w') as w2:
1467 w2.write(msg1)
1468 with zipf.open('bar', mode='w') as w1:
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001469 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001470 zipf.open('handle', mode='w')
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001471 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001472 zipf.open('foo', mode='r')
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001473 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001474 zipf.writestr('str', 'abcde')
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001475 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001476 zipf.write(__file__, 'file')
Serhiy Storchakab0d497c2016-09-10 21:28:07 +03001477 with self.assertRaises(ValueError):
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001478 zipf.close()
1479 w1.write(msg2)
1480 with zipf.open('baz', mode='w') as w2:
1481 w2.write(msg3)
1482
1483 with zipfile.ZipFile(TESTFN2, 'r') as zipf:
1484 self.assertEqual(zipf.read('foo'), msg1)
1485 self.assertEqual(zipf.read('bar'), msg2)
1486 self.assertEqual(zipf.read('baz'), msg3)
1487 self.assertEqual(zipf.namelist(), ['foo', 'bar', 'baz'])
1488
Guido van Rossumd8faa362007-04-27 19:54:29 +00001489 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001490 unlink(TESTFN)
1491 unlink(TESTFN2)
1492
Thomas Wouterscf297e42007-02-23 15:07:44 +00001493
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001494class AbstractBadCrcTests:
1495 def test_testzip_with_bad_crc(self):
1496 """Tests that files with bad CRCs return their name from testzip."""
1497 zipdata = self.zip_with_bad_crc
1498
1499 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1500 # testzip returns the name of the first corrupt file, or None
1501 self.assertEqual('afile', zipf.testzip())
1502
1503 def test_read_with_bad_crc(self):
1504 """Tests that files with bad CRCs raise a BadZipFile exception when read."""
1505 zipdata = self.zip_with_bad_crc
1506
1507 # Using ZipFile.read()
1508 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1509 self.assertRaises(zipfile.BadZipFile, zipf.read, 'afile')
1510
1511 # Using ZipExtFile.read()
1512 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1513 with zipf.open('afile', 'r') as corrupt_file:
1514 self.assertRaises(zipfile.BadZipFile, corrupt_file.read)
1515
1516 # Same with small reads (in order to exercise the buffering logic)
1517 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1518 with zipf.open('afile', 'r') as corrupt_file:
1519 corrupt_file.MIN_READ_SIZE = 2
1520 with self.assertRaises(zipfile.BadZipFile):
1521 while corrupt_file.read(2):
1522 pass
1523
1524
1525class StoredBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1526 compression = zipfile.ZIP_STORED
1527 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001528 b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
1529 b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
1530 b'ilehello,AworldP'
1531 b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
1532 b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
1533 b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
1534 b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
1535 b'\0\0/\0\0\0\0\0')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001536
1537@requires_zlib
1538class DeflateBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1539 compression = zipfile.ZIP_DEFLATED
1540 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001541 b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
1542 b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1543 b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
1544 b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
1545 b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
1546 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
1547 b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
1548 b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001549
1550@requires_bz2
1551class Bzip2BadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1552 compression = zipfile.ZIP_BZIP2
1553 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001554 b'PK\x03\x04\x14\x03\x00\x00\x0c\x00nu\x0c=FA'
1555 b'KE8\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1556 b'ileBZh91AY&SY\xd4\xa8\xca'
1557 b'\x7f\x00\x00\x0f\x11\x80@\x00\x06D\x90\x80 \x00 \xa5'
1558 b'P\xd9!\x03\x03\x13\x13\x13\x89\xa9\xa9\xc2u5:\x9f'
1559 b'\x8b\xb9"\x9c(HjTe?\x80PK\x01\x02\x14'
1560 b'\x03\x14\x03\x00\x00\x0c\x00nu\x0c=FAKE8'
1561 b'\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\x00'
1562 b'\x00 \x80\x80\x81\x00\x00\x00\x00afilePK'
1563 b'\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00\x00[\x00'
1564 b'\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001565
1566@requires_lzma
1567class LzmaBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1568 compression = zipfile.ZIP_LZMA
1569 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001570 b'PK\x03\x04\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
1571 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1572 b'ile\t\x04\x05\x00]\x00\x00\x00\x04\x004\x19I'
1573 b'\xee\x8d\xe9\x17\x89:3`\tq!.8\x00PK'
1574 b'\x01\x02\x14\x03\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
1575 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00'
1576 b'\x00\x00\x00\x00 \x80\x80\x81\x00\x00\x00\x00afil'
1577 b'ePK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00'
1578 b'\x00>\x00\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001579
1580
Thomas Wouterscf297e42007-02-23 15:07:44 +00001581class DecryptionTests(unittest.TestCase):
Ezio Melotti35386712009-12-31 13:22:41 +00001582 """Check that ZIP decryption works. Since the library does not
1583 support encryption at the moment, we use a pre-generated encrypted
1584 ZIP file."""
Thomas Wouterscf297e42007-02-23 15:07:44 +00001585
1586 data = (
Christian Tismer59202e52013-10-21 03:59:23 +02001587 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
1588 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
1589 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
1590 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
1591 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
1592 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
1593 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +00001594 data2 = (
Christian Tismer59202e52013-10-21 03:59:23 +02001595 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
1596 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
1597 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
1598 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
1599 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
1600 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
1601 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
1602 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +00001603
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001604 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +00001605 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +00001606
1607 def setUp(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001608 with open(TESTFN, "wb") as fp:
1609 fp.write(self.data)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001610 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti35386712009-12-31 13:22:41 +00001611 with open(TESTFN2, "wb") as fp:
1612 fp.write(self.data2)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001613 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001614
1615 def tearDown(self):
1616 self.zip.close()
1617 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001618 self.zip2.close()
1619 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001620
Ezio Melottiafd0d112009-07-15 17:17:17 +00001621 def test_no_password(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001622 # Reading the encrypted file without password
1623 # must generate a RunTime exception
1624 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001625 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001626
Ezio Melottiafd0d112009-07-15 17:17:17 +00001627 def test_bad_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001628 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001629 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001630 self.zip2.setpassword(b"perl")
1631 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001632
Ezio Melotti975077a2011-05-19 22:03:22 +03001633 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +00001634 def test_good_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001635 self.zip.setpassword(b"python")
Ezio Melotti35386712009-12-31 13:22:41 +00001636 self.assertEqual(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001637 self.zip2.setpassword(b"12345")
Ezio Melotti35386712009-12-31 13:22:41 +00001638 self.assertEqual(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001639
R. David Murray8d855d82010-12-21 21:53:37 +00001640 def test_unicode_password(self):
1641 self.assertRaises(TypeError, self.zip.setpassword, "unicode")
1642 self.assertRaises(TypeError, self.zip.read, "test.txt", "python")
1643 self.assertRaises(TypeError, self.zip.open, "test.txt", pwd="python")
1644 self.assertRaises(TypeError, self.zip.extract, "test.txt", pwd="python")
1645
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001646class AbstractTestsWithRandomBinaryFiles:
1647 @classmethod
1648 def setUpClass(cls):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001649 datacount = randint(16, 64)*1024 + randint(1, 1024)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001650 cls.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
1651 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001652
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001653 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001654 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +00001655 with open(TESTFN, "wb") as fp:
1656 fp.write(self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001657
1658 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001659 unlink(TESTFN)
1660 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001661
Ezio Melottiafd0d112009-07-15 17:17:17 +00001662 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001663 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001664 with zipfile.ZipFile(f, "w", compression) as zipfp:
1665 zipfp.write(TESTFN, "another.name")
1666 zipfp.write(TESTFN, TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001667
Ezio Melottiafd0d112009-07-15 17:17:17 +00001668 def zip_test(self, f, compression):
1669 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001670
1671 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001672 with zipfile.ZipFile(f, "r", compression) as zipfp:
1673 testdata = zipfp.read(TESTFN)
1674 self.assertEqual(len(testdata), len(self.data))
1675 self.assertEqual(testdata, self.data)
1676 self.assertEqual(zipfp.read("another.name"), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001677
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001678 def test_read(self):
1679 for f in get_files(self):
1680 self.zip_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001681
Ezio Melottiafd0d112009-07-15 17:17:17 +00001682 def zip_open_test(self, f, compression):
1683 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001684
1685 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001686 with zipfile.ZipFile(f, "r", compression) as zipfp:
1687 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001688 with zipfp.open(TESTFN) as zipopen1:
1689 while True:
1690 read_data = zipopen1.read(256)
1691 if not read_data:
1692 break
1693 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001694
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001695 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001696 with zipfp.open("another.name") as zipopen2:
1697 while True:
1698 read_data = zipopen2.read(256)
1699 if not read_data:
1700 break
1701 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001702
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001703 testdata1 = b''.join(zipdata1)
1704 self.assertEqual(len(testdata1), len(self.data))
1705 self.assertEqual(testdata1, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001706
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001707 testdata2 = b''.join(zipdata2)
Ezio Melotti35386712009-12-31 13:22:41 +00001708 self.assertEqual(len(testdata2), len(self.data))
1709 self.assertEqual(testdata2, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001710
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001711 def test_open(self):
1712 for f in get_files(self):
1713 self.zip_open_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001714
Ezio Melottiafd0d112009-07-15 17:17:17 +00001715 def zip_random_open_test(self, f, compression):
1716 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001717
1718 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001719 with zipfile.ZipFile(f, "r", compression) as zipfp:
1720 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001721 with zipfp.open(TESTFN) as zipopen1:
1722 while True:
1723 read_data = zipopen1.read(randint(1, 1024))
1724 if not read_data:
1725 break
1726 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001727
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001728 testdata = b''.join(zipdata1)
1729 self.assertEqual(len(testdata), len(self.data))
1730 self.assertEqual(testdata, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001731
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001732 def test_random_open(self):
1733 for f in get_files(self):
1734 self.zip_random_open_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001735
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001736
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001737class StoredTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1738 unittest.TestCase):
1739 compression = zipfile.ZIP_STORED
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001740
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001741@requires_zlib
1742class DeflateTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1743 unittest.TestCase):
1744 compression = zipfile.ZIP_DEFLATED
1745
1746@requires_bz2
1747class Bzip2TestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1748 unittest.TestCase):
1749 compression = zipfile.ZIP_BZIP2
1750
1751@requires_lzma
1752class LzmaTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1753 unittest.TestCase):
1754 compression = zipfile.ZIP_LZMA
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001755
Ezio Melotti76430242009-07-11 18:28:48 +00001756
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001757# Privide the tell() method but not seek()
1758class Tellable:
1759 def __init__(self, fp):
1760 self.fp = fp
1761 self.offset = 0
1762
1763 def write(self, data):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02001764 n = self.fp.write(data)
1765 self.offset += n
1766 return n
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001767
1768 def tell(self):
1769 return self.offset
1770
1771 def flush(self):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02001772 self.fp.flush()
1773
1774class Unseekable:
1775 def __init__(self, fp):
1776 self.fp = fp
1777
1778 def write(self, data):
1779 return self.fp.write(data)
1780
1781 def flush(self):
1782 self.fp.flush()
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001783
1784class UnseekableTests(unittest.TestCase):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02001785 def test_writestr(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 zipfp.writestr('ones', b'111')
1793 zipfp.writestr('twos', b'222')
1794 self.assertEqual(f.getvalue()[:5], b'abcPK')
1795 with zipfile.ZipFile(f, mode='r') as zipf:
1796 with zipf.open('ones') as zopen:
1797 self.assertEqual(zopen.read(), b'111')
1798 with zipf.open('twos') as zopen:
1799 self.assertEqual(zopen.read(), b'222')
1800
1801 def test_write(self):
1802 for wrapper in (lambda f: f), Tellable, Unseekable:
1803 with self.subTest(wrapper=wrapper):
1804 f = io.BytesIO()
1805 f.write(b'abc')
1806 bf = io.BufferedWriter(f)
1807 with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) as zipfp:
1808 self.addCleanup(unlink, TESTFN)
1809 with open(TESTFN, 'wb') as f2:
1810 f2.write(b'111')
1811 zipfp.write(TESTFN, 'ones')
1812 with open(TESTFN, 'wb') as f2:
1813 f2.write(b'222')
1814 zipfp.write(TESTFN, 'twos')
1815 self.assertEqual(f.getvalue()[:5], b'abcPK')
1816 with zipfile.ZipFile(f, mode='r') as zipf:
1817 with zipf.open('ones') as zopen:
1818 self.assertEqual(zopen.read(), b'111')
1819 with zipf.open('twos') as zopen:
1820 self.assertEqual(zopen.read(), b'222')
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001821
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001822 def test_open_write(self):
1823 for wrapper in (lambda f: f), Tellable, Unseekable:
1824 with self.subTest(wrapper=wrapper):
1825 f = io.BytesIO()
1826 f.write(b'abc')
1827 bf = io.BufferedWriter(f)
1828 with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) as zipf:
1829 with zipf.open('ones', 'w') as zopen:
1830 zopen.write(b'111')
1831 with zipf.open('twos', 'w') as zopen:
1832 zopen.write(b'222')
1833 self.assertEqual(f.getvalue()[:5], b'abcPK')
1834 with zipfile.ZipFile(f) as zipf:
1835 self.assertEqual(zipf.read('ones'), b'111')
1836 self.assertEqual(zipf.read('twos'), b'222')
1837
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001838
Ezio Melotti975077a2011-05-19 22:03:22 +03001839@requires_zlib
Guido van Rossumd8faa362007-04-27 19:54:29 +00001840class TestsWithMultipleOpens(unittest.TestCase):
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001841 @classmethod
1842 def setUpClass(cls):
1843 cls.data1 = b'111' + getrandbytes(10000)
1844 cls.data2 = b'222' + getrandbytes(10000)
1845
1846 def make_test_archive(self, f):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001847 # Create the ZIP archive
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001848 with zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as zipfp:
1849 zipfp.writestr('ones', self.data1)
1850 zipfp.writestr('twos', self.data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001851
Ezio Melottiafd0d112009-07-15 17:17:17 +00001852 def test_same_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001853 # Verify that (when the ZipFile is in control of creating file objects)
1854 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001855 for f in get_files(self):
1856 self.make_test_archive(f)
1857 with zipfile.ZipFile(f, mode="r") as zipf:
1858 with zipf.open('ones') as zopen1, zipf.open('ones') as zopen2:
1859 data1 = zopen1.read(500)
1860 data2 = zopen2.read(500)
1861 data1 += zopen1.read()
1862 data2 += zopen2.read()
1863 self.assertEqual(data1, data2)
1864 self.assertEqual(data1, self.data1)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001865
Ezio Melottiafd0d112009-07-15 17:17:17 +00001866 def test_different_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001867 # Verify that (when the ZipFile is in control of creating file objects)
1868 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001869 for f in get_files(self):
1870 self.make_test_archive(f)
1871 with zipfile.ZipFile(f, mode="r") as zipf:
1872 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1873 data1 = zopen1.read(500)
1874 data2 = zopen2.read(500)
1875 data1 += zopen1.read()
1876 data2 += zopen2.read()
1877 self.assertEqual(data1, self.data1)
1878 self.assertEqual(data2, self.data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001879
Ezio Melottiafd0d112009-07-15 17:17:17 +00001880 def test_interleaved(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001881 # Verify that (when the ZipFile is in control of creating file objects)
1882 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001883 for f in get_files(self):
1884 self.make_test_archive(f)
1885 with zipfile.ZipFile(f, mode="r") as zipf:
Serhiy Storchakad76c7c22016-05-13 21:18:58 +03001886 with zipf.open('ones') as zopen1:
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001887 data1 = zopen1.read(500)
Serhiy Storchakad76c7c22016-05-13 21:18:58 +03001888 with zipf.open('twos') as zopen2:
1889 data2 = zopen2.read(500)
1890 data1 += zopen1.read()
1891 data2 += zopen2.read()
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001892 self.assertEqual(data1, self.data1)
1893 self.assertEqual(data2, self.data2)
1894
1895 def test_read_after_close(self):
1896 for f in get_files(self):
1897 self.make_test_archive(f)
1898 with contextlib.ExitStack() as stack:
1899 with zipfile.ZipFile(f, 'r') as zipf:
1900 zopen1 = stack.enter_context(zipf.open('ones'))
1901 zopen2 = stack.enter_context(zipf.open('twos'))
Brian Curtin8fb9b862010-11-18 02:15:28 +00001902 data1 = zopen1.read(500)
1903 data2 = zopen2.read(500)
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001904 data1 += zopen1.read()
1905 data2 += zopen2.read()
1906 self.assertEqual(data1, self.data1)
1907 self.assertEqual(data2, self.data2)
1908
1909 def test_read_after_write(self):
1910 for f in get_files(self):
1911 with zipfile.ZipFile(f, 'w', zipfile.ZIP_DEFLATED) as zipf:
1912 zipf.writestr('ones', self.data1)
1913 zipf.writestr('twos', self.data2)
1914 with zipf.open('ones') as zopen1:
1915 data1 = zopen1.read(500)
1916 self.assertEqual(data1, self.data1[:500])
1917 with zipfile.ZipFile(f, 'r') as zipf:
1918 data1 = zipf.read('ones')
1919 data2 = zipf.read('twos')
1920 self.assertEqual(data1, self.data1)
1921 self.assertEqual(data2, self.data2)
1922
1923 def test_write_after_read(self):
1924 for f in get_files(self):
1925 with zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as zipf:
1926 zipf.writestr('ones', self.data1)
1927 with zipf.open('ones') as zopen1:
1928 zopen1.read(500)
1929 zipf.writestr('twos', self.data2)
1930 with zipfile.ZipFile(f, 'r') as zipf:
1931 data1 = zipf.read('ones')
1932 data2 = zipf.read('twos')
1933 self.assertEqual(data1, self.data1)
1934 self.assertEqual(data2, self.data2)
1935
1936 def test_many_opens(self):
1937 # Verify that read() and open() promptly close the file descriptor,
1938 # and don't rely on the garbage collector to free resources.
1939 self.make_test_archive(TESTFN2)
1940 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
1941 for x in range(100):
1942 zipf.read('ones')
1943 with zipf.open('ones') as zopen1:
1944 pass
1945 with open(os.devnull) as f:
1946 self.assertLess(f.fileno(), 100)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001947
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001948 def test_write_while_reading(self):
1949 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_DEFLATED) as zipf:
1950 zipf.writestr('ones', self.data1)
1951 with zipfile.ZipFile(TESTFN2, 'a', zipfile.ZIP_DEFLATED) as zipf:
1952 with zipf.open('ones', 'r') as r1:
1953 data1 = r1.read(500)
1954 with zipf.open('twos', 'w') as w1:
1955 w1.write(self.data2)
1956 data1 += r1.read()
1957 self.assertEqual(data1, self.data1)
1958 with zipfile.ZipFile(TESTFN2) as zipf:
1959 self.assertEqual(zipf.read('twos'), self.data2)
1960
Guido van Rossumd8faa362007-04-27 19:54:29 +00001961 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001962 unlink(TESTFN2)
1963
Guido van Rossumd8faa362007-04-27 19:54:29 +00001964
Martin v. Löwis59e47792009-01-24 14:10:07 +00001965class TestWithDirectory(unittest.TestCase):
1966 def setUp(self):
1967 os.mkdir(TESTFN2)
1968
Ezio Melottiafd0d112009-07-15 17:17:17 +00001969 def test_extract_dir(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001970 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
1971 zipf.extractall(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001972 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1973 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1974 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1975
Ezio Melottiafd0d112009-07-15 17:17:17 +00001976 def test_bug_6050(self):
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001977 # Extraction should succeed if directories already exist
1978 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottiafd0d112009-07-15 17:17:17 +00001979 self.test_extract_dir()
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001980
Serhiy Storchaka46a34922014-09-23 22:40:23 +03001981 def test_write_dir(self):
1982 dirpath = os.path.join(TESTFN2, "x")
1983 os.mkdir(dirpath)
1984 mode = os.stat(dirpath).st_mode & 0xFFFF
1985 with zipfile.ZipFile(TESTFN, "w") as zipf:
1986 zipf.write(dirpath)
1987 zinfo = zipf.filelist[0]
1988 self.assertTrue(zinfo.filename.endswith("/x/"))
1989 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1990 zipf.write(dirpath, "y")
1991 zinfo = zipf.filelist[1]
1992 self.assertTrue(zinfo.filename, "y/")
1993 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1994 with zipfile.ZipFile(TESTFN, "r") as zipf:
1995 zinfo = zipf.filelist[0]
1996 self.assertTrue(zinfo.filename.endswith("/x/"))
1997 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1998 zinfo = zipf.filelist[1]
1999 self.assertTrue(zinfo.filename, "y/")
2000 self.assertEqual(zinfo.external_attr, (mode << 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, "y")))
2005 self.assertEqual(len(os.listdir(target)), 2)
2006
2007 def test_writestr_dir(self):
Martin v. Löwis59e47792009-01-24 14:10:07 +00002008 os.mkdir(os.path.join(TESTFN2, "x"))
Serhiy Storchaka46a34922014-09-23 22:40:23 +03002009 with zipfile.ZipFile(TESTFN, "w") as zipf:
2010 zipf.writestr("x/", b'')
2011 zinfo = zipf.filelist[0]
2012 self.assertEqual(zinfo.filename, "x/")
2013 self.assertEqual(zinfo.external_attr, (0o40775 << 16) | 0x10)
2014 with zipfile.ZipFile(TESTFN, "r") as zipf:
2015 zinfo = zipf.filelist[0]
2016 self.assertTrue(zinfo.filename.endswith("x/"))
2017 self.assertEqual(zinfo.external_attr, (0o40775 << 16) | 0x10)
2018 target = os.path.join(TESTFN2, "target")
2019 os.mkdir(target)
2020 zipf.extractall(target)
2021 self.assertTrue(os.path.isdir(os.path.join(target, "x")))
2022 self.assertEqual(os.listdir(target), ["x"])
Martin v. Löwis59e47792009-01-24 14:10:07 +00002023
2024 def tearDown(self):
Victor Stinner57004c62014-09-04 00:49:01 +02002025 rmtree(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00002026 if os.path.exists(TESTFN):
Ezio Melotti76430242009-07-11 18:28:48 +00002027 unlink(TESTFN)
Martin v. Löwis59e47792009-01-24 14:10:07 +00002028
Guido van Rossumd8faa362007-04-27 19:54:29 +00002029
Serhiy Storchaka503f9082016-02-08 00:02:25 +02002030class ZipInfoTests(unittest.TestCase):
2031 def test_from_file(self):
2032 zi = zipfile.ZipInfo.from_file(__file__)
2033 self.assertEqual(posixpath.basename(zi.filename), 'test_zipfile.py')
2034 self.assertFalse(zi.is_dir())
2035
2036 def test_from_dir(self):
2037 dirpath = os.path.dirname(os.path.abspath(__file__))
2038 zi = zipfile.ZipInfo.from_file(dirpath, 'stdlib_tests')
2039 self.assertEqual(zi.filename, 'stdlib_tests/')
2040 self.assertTrue(zi.is_dir())
2041 self.assertEqual(zi.compress_type, zipfile.ZIP_STORED)
2042 self.assertEqual(zi.file_size, 0)
2043
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00002044if __name__ == "__main__":
Brett Cannond5b4e1d2013-06-12 19:57:19 -04002045 unittest.main()