blob: ef3c3d8d676c0b3a3c5a64fb23d414e485c78bfa [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])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000423
R David Murray4fbb9db2011-06-09 15:50:51 -0400424 def test_ignores_newline_at_end(self):
425 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
426 zipfp.write(TESTFN, TESTFN)
427 with open(TESTFN2, 'a') as f:
428 f.write("\r\n\00\00\00")
429 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
430 self.assertIsInstance(zipfp, zipfile.ZipFile)
431
432 def test_ignores_stuff_appended_past_comments(self):
433 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
434 zipfp.comment = b"this is a comment"
435 zipfp.write(TESTFN, TESTFN)
436 with open(TESTFN2, 'a') as f:
437 f.write("abcdef\r\n")
438 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
439 self.assertIsInstance(zipfp, zipfile.ZipFile)
440 self.assertEqual(zipfp.comment, b"this is a comment")
441
Ezio Melottiafd0d112009-07-15 17:17:17 +0000442 def test_write_default_name(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000443 """Check that calling ZipFile.write without arcname specified
444 produces the expected result."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000445 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
446 zipfp.write(TESTFN)
Brian Curtin8fb9b862010-11-18 02:15:28 +0000447 with open(TESTFN, "rb") as f:
448 self.assertEqual(zipfp.read(TESTFN), f.read())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000449
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300450 def test_write_to_readonly(self):
451 """Check that trying to call write() on a readonly ZipFile object
452 raises a RuntimeError."""
453 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
454 zipfp.writestr("somefile.txt", "bogus")
455
456 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
457 self.assertRaises(RuntimeError, zipfp.write, TESTFN)
458
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +0300459 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
460 with self.assertRaises(RuntimeError):
461 zipfp.open(TESTFN, mode='w')
462
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300463 def test_add_file_before_1980(self):
464 # Set atime and mtime to 1970-01-01
465 os.utime(TESTFN, (0, 0))
466 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
467 self.assertRaises(ValueError, zipfp.write, TESTFN)
468
Serhiy Storchaka5ce3f102014-01-09 14:50:20 +0200469
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300470@requires_zlib
471class DeflateTestsWithSourceFile(AbstractTestsWithSourceFile,
472 unittest.TestCase):
473 compression = zipfile.ZIP_DEFLATED
474
Ezio Melottiafd0d112009-07-15 17:17:17 +0000475 def test_per_file_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000476 """Check that files within a Zip archive can have different
477 compression options."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000478 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
479 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
480 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
481 sinfo = zipfp.getinfo('storeme')
482 dinfo = zipfp.getinfo('deflateme')
483 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
484 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000485
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300486@requires_bz2
487class Bzip2TestsWithSourceFile(AbstractTestsWithSourceFile,
488 unittest.TestCase):
489 compression = zipfile.ZIP_BZIP2
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000490
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300491@requires_lzma
492class LzmaTestsWithSourceFile(AbstractTestsWithSourceFile,
493 unittest.TestCase):
494 compression = zipfile.ZIP_LZMA
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000495
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300496
497class AbstractTestZip64InSmallFiles:
498 # These tests test the ZIP64 functionality without using large files,
499 # see test_zipfile64 for proper tests.
500
501 @classmethod
502 def setUpClass(cls):
503 line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
504 for i in range(0, FIXEDTEST_SIZE))
505 cls.data = b'\n'.join(line_gen)
506
507 def setUp(self):
508 self._limit = zipfile.ZIP64_LIMIT
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300509 self._filecount_limit = zipfile.ZIP_FILECOUNT_LIMIT
510 zipfile.ZIP64_LIMIT = 1000
511 zipfile.ZIP_FILECOUNT_LIMIT = 9
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300512
513 # Make a source file with some lines
514 with open(TESTFN, "wb") as fp:
515 fp.write(self.data)
516
517 def zip_test(self, f, compression):
518 # Create the ZIP archive
519 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
520 zipfp.write(TESTFN, "another.name")
521 zipfp.write(TESTFN, TESTFN)
522 zipfp.writestr("strfile", self.data)
523
524 # Read the ZIP archive
525 with zipfile.ZipFile(f, "r", compression) as zipfp:
526 self.assertEqual(zipfp.read(TESTFN), self.data)
527 self.assertEqual(zipfp.read("another.name"), self.data)
528 self.assertEqual(zipfp.read("strfile"), self.data)
529
530 # Print the ZIP directory
531 fp = io.StringIO()
532 zipfp.printdir(fp)
533
534 directory = fp.getvalue()
535 lines = directory.splitlines()
536 self.assertEqual(len(lines), 4) # Number of files + header
537
538 self.assertIn('File Name', lines[0])
539 self.assertIn('Modified', lines[0])
540 self.assertIn('Size', lines[0])
541
542 fn, date, time_, size = lines[1].split()
543 self.assertEqual(fn, 'another.name')
544 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
545 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
546 self.assertEqual(size, str(len(self.data)))
547
548 # Check the namelist
549 names = zipfp.namelist()
550 self.assertEqual(len(names), 3)
551 self.assertIn(TESTFN, names)
552 self.assertIn("another.name", names)
553 self.assertIn("strfile", names)
554
555 # Check infolist
556 infos = zipfp.infolist()
557 names = [i.filename for i in infos]
558 self.assertEqual(len(names), 3)
559 self.assertIn(TESTFN, names)
560 self.assertIn("another.name", names)
561 self.assertIn("strfile", names)
562 for i in infos:
563 self.assertEqual(i.file_size, len(self.data))
564
565 # check getinfo
566 for nm in (TESTFN, "another.name", "strfile"):
567 info = zipfp.getinfo(nm)
568 self.assertEqual(info.filename, nm)
569 self.assertEqual(info.file_size, len(self.data))
570
571 # Check that testzip doesn't raise an exception
572 zipfp.testzip()
573
574 def test_basic(self):
575 for f in get_files(self):
576 self.zip_test(f, self.compression)
577
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300578 def test_too_many_files(self):
579 # This test checks that more than 64k files can be added to an archive,
580 # and that the resulting archive can be read properly by ZipFile
581 zipf = zipfile.ZipFile(TESTFN, "w", self.compression,
582 allowZip64=True)
583 zipf.debug = 100
584 numfiles = 15
585 for i in range(numfiles):
586 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
587 self.assertEqual(len(zipf.namelist()), numfiles)
588 zipf.close()
589
590 zipf2 = zipfile.ZipFile(TESTFN, "r", self.compression)
591 self.assertEqual(len(zipf2.namelist()), numfiles)
592 for i in range(numfiles):
593 content = zipf2.read("foo%08d" % i).decode('ascii')
594 self.assertEqual(content, "%d" % (i**3 % 57))
595 zipf2.close()
596
597 def test_too_many_files_append(self):
598 zipf = zipfile.ZipFile(TESTFN, "w", self.compression,
599 allowZip64=False)
600 zipf.debug = 100
601 numfiles = 9
602 for i in range(numfiles):
603 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
604 self.assertEqual(len(zipf.namelist()), numfiles)
605 with self.assertRaises(zipfile.LargeZipFile):
606 zipf.writestr("foo%08d" % numfiles, b'')
607 self.assertEqual(len(zipf.namelist()), numfiles)
608 zipf.close()
609
610 zipf = zipfile.ZipFile(TESTFN, "a", self.compression,
611 allowZip64=False)
612 zipf.debug = 100
613 self.assertEqual(len(zipf.namelist()), numfiles)
614 with self.assertRaises(zipfile.LargeZipFile):
615 zipf.writestr("foo%08d" % numfiles, b'')
616 self.assertEqual(len(zipf.namelist()), numfiles)
617 zipf.close()
618
619 zipf = zipfile.ZipFile(TESTFN, "a", self.compression,
620 allowZip64=True)
621 zipf.debug = 100
622 self.assertEqual(len(zipf.namelist()), numfiles)
623 numfiles2 = 15
624 for i in range(numfiles, numfiles2):
625 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
626 self.assertEqual(len(zipf.namelist()), numfiles2)
627 zipf.close()
628
629 zipf2 = zipfile.ZipFile(TESTFN, "r", self.compression)
630 self.assertEqual(len(zipf2.namelist()), numfiles2)
631 for i in range(numfiles2):
632 content = zipf2.read("foo%08d" % i).decode('ascii')
633 self.assertEqual(content, "%d" % (i**3 % 57))
634 zipf2.close()
635
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300636 def tearDown(self):
637 zipfile.ZIP64_LIMIT = self._limit
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300638 zipfile.ZIP_FILECOUNT_LIMIT = self._filecount_limit
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300639 unlink(TESTFN)
640 unlink(TESTFN2)
641
642
643class StoredTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
644 unittest.TestCase):
645 compression = zipfile.ZIP_STORED
646
647 def large_file_exception_test(self, f, compression):
Serhiy Storchaka235c5e02013-11-23 15:55:38 +0200648 with zipfile.ZipFile(f, "w", compression, allowZip64=False) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300649 self.assertRaises(zipfile.LargeZipFile,
650 zipfp.write, TESTFN, "another.name")
651
652 def large_file_exception_test2(self, f, compression):
Serhiy Storchaka235c5e02013-11-23 15:55:38 +0200653 with zipfile.ZipFile(f, "w", compression, allowZip64=False) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300654 self.assertRaises(zipfile.LargeZipFile,
655 zipfp.writestr, "another.name", self.data)
656
657 def test_large_file_exception(self):
658 for f in get_files(self):
659 self.large_file_exception_test(f, zipfile.ZIP_STORED)
660 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
661
662 def test_absolute_arcnames(self):
663 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
664 allowZip64=True) as zipfp:
665 zipfp.write(TESTFN, "/absolute")
666
667 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
668 self.assertEqual(zipfp.namelist(), ["absolute"])
669
670@requires_zlib
671class DeflateTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
672 unittest.TestCase):
673 compression = zipfile.ZIP_DEFLATED
674
675@requires_bz2
676class Bzip2TestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
677 unittest.TestCase):
678 compression = zipfile.ZIP_BZIP2
679
680@requires_lzma
681class LzmaTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
682 unittest.TestCase):
683 compression = zipfile.ZIP_LZMA
684
685
686class PyZipFileTests(unittest.TestCase):
687 def assertCompiledIn(self, name, namelist):
688 if name + 'o' not in namelist:
689 self.assertIn(name + 'c', namelist)
690
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200691 def requiresWriteAccess(self, path):
Berker Peksage1efc072015-02-16 04:36:18 +0200692 # effective_ids unavailable on windows
693 if not os.access(path, os.W_OK,
694 effective_ids=os.access in os.supports_effective_ids):
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200695 self.skipTest('requires write access to the installed location')
Serhiy Storchakad86a6ef2015-09-19 10:55:20 +0300696 filename = os.path.join(path, 'test_zipfile.try')
697 try:
698 fd = os.open(filename, os.O_WRONLY | os.O_CREAT)
699 os.close(fd)
700 except Exception:
701 self.skipTest('requires write access to the installed location')
702 unlink(filename)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200703
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300704 def test_write_pyfile(self):
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200705 self.requiresWriteAccess(os.path.dirname(__file__))
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300706 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
707 fn = __file__
Brett Cannonf299abd2015-04-13 14:21:02 -0400708 if fn.endswith('.pyc'):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300709 path_split = fn.split(os.sep)
710 if os.altsep is not None:
711 path_split.extend(fn.split(os.altsep))
712 if '__pycache__' in path_split:
Serhiy Storchaka9068e4d2013-07-22 21:02:14 +0300713 fn = importlib.util.source_from_cache(fn)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300714 else:
715 fn = fn[:-1]
716
717 zipfp.writepy(fn)
718
719 bn = os.path.basename(fn)
720 self.assertNotIn(bn, zipfp.namelist())
721 self.assertCompiledIn(bn, zipfp.namelist())
722
723 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
724 fn = __file__
Brett Cannonf299abd2015-04-13 14:21:02 -0400725 if fn.endswith('.pyc'):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300726 fn = fn[:-1]
727
728 zipfp.writepy(fn, "testpackage")
729
730 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
731 self.assertNotIn(bn, zipfp.namelist())
732 self.assertCompiledIn(bn, zipfp.namelist())
733
734 def test_write_python_package(self):
735 import email
736 packagedir = os.path.dirname(email.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200737 self.requiresWriteAccess(packagedir)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300738
739 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
740 zipfp.writepy(packagedir)
741
742 # Check for a couple of modules at different levels of the
743 # hierarchy
744 names = zipfp.namelist()
745 self.assertCompiledIn('email/__init__.py', names)
746 self.assertCompiledIn('email/mime/text.py', names)
747
Christian Tismer59202e52013-10-21 03:59:23 +0200748 def test_write_filtered_python_package(self):
749 import test
750 packagedir = os.path.dirname(test.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200751 self.requiresWriteAccess(packagedir)
Christian Tismer59202e52013-10-21 03:59:23 +0200752
753 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
754
Christian Tismer59202e52013-10-21 03:59:23 +0200755 # first make sure that the test folder gives error messages
Georg Brandla6065422013-10-21 08:29:29 +0200756 # (on the badsyntax_... files)
757 with captured_stdout() as reportSIO:
758 zipfp.writepy(packagedir)
Christian Tismer59202e52013-10-21 03:59:23 +0200759 reportStr = reportSIO.getvalue()
760 self.assertTrue('SyntaxError' in reportStr)
761
Christian Tismer410d9312013-10-22 04:09:28 +0200762 # then check that the filter works on the whole package
Georg Brandla6065422013-10-21 08:29:29 +0200763 with captured_stdout() as reportSIO:
764 zipfp.writepy(packagedir, filterfunc=lambda whatever: False)
Christian Tismer59202e52013-10-21 03:59:23 +0200765 reportStr = reportSIO.getvalue()
766 self.assertTrue('SyntaxError' not in reportStr)
767
Christian Tismer410d9312013-10-22 04:09:28 +0200768 # then check that the filter works on individual files
Larry Hastings7e63b362015-05-08 06:54:58 -0700769 def filter(path):
770 return not os.path.basename(path).startswith("bad")
Serhiy Storchakac46d1fa2014-01-20 21:59:33 +0200771 with captured_stdout() as reportSIO, self.assertWarns(UserWarning):
Larry Hastings7e63b362015-05-08 06:54:58 -0700772 zipfp.writepy(packagedir, filterfunc=filter)
Christian Tismer410d9312013-10-22 04:09:28 +0200773 reportStr = reportSIO.getvalue()
774 if reportStr:
775 print(reportStr)
776 self.assertTrue('SyntaxError' not in reportStr)
777
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300778 def test_write_with_optimization(self):
779 import email
780 packagedir = os.path.dirname(email.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200781 self.requiresWriteAccess(packagedir)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300782 optlevel = 1 if __debug__ else 0
Brett Cannonf299abd2015-04-13 14:21:02 -0400783 ext = '.pyc'
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300784
785 with TemporaryFile() as t, \
Christian Tismer59202e52013-10-21 03:59:23 +0200786 zipfile.PyZipFile(t, "w", optimize=optlevel) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300787 zipfp.writepy(packagedir)
788
789 names = zipfp.namelist()
790 self.assertIn('email/__init__' + ext, names)
791 self.assertIn('email/mime/text' + ext, names)
792
793 def test_write_python_directory(self):
794 os.mkdir(TESTFN2)
795 try:
796 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
797 fp.write("print(42)\n")
798
799 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
800 fp.write("print(42 * 42)\n")
801
802 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
803 fp.write("bla bla bla\n")
804
805 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
806 zipfp.writepy(TESTFN2)
807
808 names = zipfp.namelist()
809 self.assertCompiledIn('mod1.py', names)
810 self.assertCompiledIn('mod2.py', names)
811 self.assertNotIn('mod2.txt', names)
812
813 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200814 rmtree(TESTFN2)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300815
Christian Tismer410d9312013-10-22 04:09:28 +0200816 def test_write_python_directory_filtered(self):
817 os.mkdir(TESTFN2)
818 try:
819 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
820 fp.write("print(42)\n")
821
822 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
823 fp.write("print(42 * 42)\n")
824
825 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
826 zipfp.writepy(TESTFN2, filterfunc=lambda fn:
827 not fn.endswith('mod2.py'))
828
829 names = zipfp.namelist()
830 self.assertCompiledIn('mod1.py', names)
831 self.assertNotIn('mod2.py', names)
832
833 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200834 rmtree(TESTFN2)
Christian Tismer410d9312013-10-22 04:09:28 +0200835
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300836 def test_write_non_pyfile(self):
837 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
838 with open(TESTFN, 'w') as f:
839 f.write('most definitely not a python file')
840 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
Victor Stinner88b215e2014-09-04 00:51:09 +0200841 unlink(TESTFN)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300842
843 def test_write_pyfile_bad_syntax(self):
844 os.mkdir(TESTFN2)
845 try:
846 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
847 fp.write("Bad syntax in python file\n")
848
849 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
850 # syntax errors are printed to stdout
851 with captured_stdout() as s:
852 zipfp.writepy(os.path.join(TESTFN2, "mod1.py"))
853
854 self.assertIn("SyntaxError", s.getvalue())
855
856 # as it will not have compiled the python file, it will
Brett Cannonf299abd2015-04-13 14:21:02 -0400857 # include the .py file not .pyc
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300858 names = zipfp.namelist()
859 self.assertIn('mod1.py', names)
860 self.assertNotIn('mod1.pyc', names)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300861
862 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200863 rmtree(TESTFN2)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300864
865
866class ExtractTests(unittest.TestCase):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000867 def test_extract(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000868 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
869 for fpath, fdata in SMALL_TEST_DATA:
870 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000871
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000872 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
873 for fpath, fdata in SMALL_TEST_DATA:
874 writtenfile = zipfp.extract(fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000875
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000876 # make sure it was written to the right place
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800877 correctfile = os.path.join(os.getcwd(), fpath)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000878 correctfile = os.path.normpath(correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000879
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000880 self.assertEqual(writtenfile, correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000881
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000882 # make sure correct data is in correct file
Brian Curtin8fb9b862010-11-18 02:15:28 +0000883 with open(writtenfile, "rb") as f:
884 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000885
Victor Stinner88b215e2014-09-04 00:51:09 +0200886 unlink(writtenfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000887
888 # remove the test file subdirectories
Victor Stinner57004c62014-09-04 00:49:01 +0200889 rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
Christian Heimes790c8232008-01-07 21:14:23 +0000890
Ezio Melottiafd0d112009-07-15 17:17:17 +0000891 def test_extract_all(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000892 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
893 for fpath, fdata in SMALL_TEST_DATA:
894 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000895
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000896 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
897 zipfp.extractall()
898 for fpath, fdata in SMALL_TEST_DATA:
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800899 outfile = os.path.join(os.getcwd(), fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000900
Brian Curtin8fb9b862010-11-18 02:15:28 +0000901 with open(outfile, "rb") as f:
902 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000903
Victor Stinner88b215e2014-09-04 00:51:09 +0200904 unlink(outfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000905
906 # remove the test file subdirectories
Victor Stinner57004c62014-09-04 00:49:01 +0200907 rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
Christian Heimes790c8232008-01-07 21:14:23 +0000908
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800909 def check_file(self, filename, content):
910 self.assertTrue(os.path.isfile(filename))
911 with open(filename, 'rb') as f:
912 self.assertEqual(f.read(), content)
913
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800914 def test_sanitize_windows_name(self):
915 san = zipfile.ZipFile._sanitize_windows_name
916 # Passing pathsep in allows this test to work regardless of platform.
917 self.assertEqual(san(r',,?,C:,foo,bar/z', ','), r'_,C_,foo,bar/z')
918 self.assertEqual(san(r'a\b,c<d>e|f"g?h*i', ','), r'a\b,c_d_e_f_g_h_i')
919 self.assertEqual(san('../../foo../../ba..r', '/'), r'foo/ba..r')
920
921 def test_extract_hackers_arcnames_common_cases(self):
922 common_hacknames = [
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800923 ('../foo/bar', 'foo/bar'),
924 ('foo/../bar', 'foo/bar'),
925 ('foo/../../bar', 'foo/bar'),
926 ('foo/bar/..', 'foo/bar'),
927 ('./../foo/bar', 'foo/bar'),
928 ('/foo/bar', 'foo/bar'),
929 ('/foo/../bar', 'foo/bar'),
930 ('/foo/../../bar', 'foo/bar'),
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800931 ]
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800932 self._test_extract_hackers_arcnames(common_hacknames)
933
934 @unittest.skipIf(os.path.sep != '\\', 'Requires \\ as path separator.')
935 def test_extract_hackers_arcnames_windows_only(self):
936 """Test combination of path fixing and windows name sanitization."""
937 windows_hacknames = [
Christian Tismer59202e52013-10-21 03:59:23 +0200938 (r'..\foo\bar', 'foo/bar'),
939 (r'..\/foo\/bar', 'foo/bar'),
940 (r'foo/\..\/bar', 'foo/bar'),
941 (r'foo\/../\bar', 'foo/bar'),
942 (r'C:foo/bar', 'foo/bar'),
943 (r'C:/foo/bar', 'foo/bar'),
944 (r'C://foo/bar', 'foo/bar'),
945 (r'C:\foo\bar', 'foo/bar'),
946 (r'//conky/mountpoint/foo/bar', 'foo/bar'),
947 (r'\\conky\mountpoint\foo\bar', 'foo/bar'),
948 (r'///conky/mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
949 (r'\\\conky\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
950 (r'//conky//mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
951 (r'\\conky\\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
952 (r'//?/C:/foo/bar', 'foo/bar'),
953 (r'\\?\C:\foo\bar', 'foo/bar'),
954 (r'C:/../C:/foo/bar', 'C_/foo/bar'),
955 (r'a:b\c<d>e|f"g?h*i', 'b/c_d_e_f_g_h_i'),
956 ('../../foo../../ba..r', 'foo/ba..r'),
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800957 ]
958 self._test_extract_hackers_arcnames(windows_hacknames)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800959
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800960 @unittest.skipIf(os.path.sep != '/', r'Requires / as path separator.')
961 def test_extract_hackers_arcnames_posix_only(self):
962 posix_hacknames = [
963 ('//foo/bar', 'foo/bar'),
964 ('../../foo../../ba..r', 'foo../ba..r'),
965 (r'foo/..\bar', r'foo/..\bar'),
966 ]
967 self._test_extract_hackers_arcnames(posix_hacknames)
968
969 def _test_extract_hackers_arcnames(self, hacknames):
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800970 for arcname, fixedname in hacknames:
971 content = b'foobar' + arcname.encode()
972 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipfp:
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200973 zinfo = zipfile.ZipInfo()
974 # preserve backslashes
975 zinfo.filename = arcname
976 zinfo.external_attr = 0o600 << 16
977 zipfp.writestr(zinfo, content)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800978
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200979 arcname = arcname.replace(os.sep, "/")
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800980 targetpath = os.path.join('target', 'subdir', 'subsub')
981 correctfile = os.path.join(targetpath, *fixedname.split('/'))
982
983 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
984 writtenfile = zipfp.extract(arcname, targetpath)
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200985 self.assertEqual(writtenfile, correctfile,
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800986 msg='extract %r: %r != %r' %
987 (arcname, writtenfile, correctfile))
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800988 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +0200989 rmtree('target')
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800990
991 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
992 zipfp.extractall(targetpath)
993 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +0200994 rmtree('target')
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800995
996 correctfile = os.path.join(os.getcwd(), *fixedname.split('/'))
997
998 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
999 writtenfile = zipfp.extract(arcname)
Serhiy Storchakae5e64442013-02-02 19:50:59 +02001000 self.assertEqual(writtenfile, correctfile,
1001 msg="extract %r" % arcname)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001002 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001003 rmtree(fixedname.split('/')[0])
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001004
1005 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1006 zipfp.extractall()
1007 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001008 rmtree(fixedname.split('/')[0])
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001009
Victor Stinner88b215e2014-09-04 00:51:09 +02001010 unlink(TESTFN2)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001011
Ronald Oussorenee5c8852010-02-07 20:24:02 +00001012
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001013class OtherTests(unittest.TestCase):
1014 def test_open_via_zip_info(self):
1015 # Create the ZIP archive
1016 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
1017 zipfp.writestr("name", "foo")
Serhiy Storchaka9b7a1a12014-01-20 21:57:40 +02001018 with self.assertWarns(UserWarning):
1019 zipfp.writestr("name", "bar")
1020 self.assertEqual(zipfp.namelist(), ["name"] * 2)
Ronald Oussorenee5c8852010-02-07 20:24:02 +00001021
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001022 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1023 infos = zipfp.infolist()
1024 data = b""
1025 for info in infos:
1026 with zipfp.open(info) as zipopen:
1027 data += zipopen.read()
1028 self.assertIn(data, {b"foobar", b"barfoo"})
1029 data = b""
1030 for info in infos:
1031 data += zipfp.read(info)
1032 self.assertIn(data, {b"foobar", b"barfoo"})
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001033
Gregory P. Smithb0d9ca922009-07-07 05:06:04 +00001034 def test_writestr_extended_local_header_issue1202(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001035 with zipfile.ZipFile(TESTFN2, 'w') as orig_zip:
1036 for data in 'abcdefghijklmnop':
1037 zinfo = zipfile.ZipInfo(data)
1038 zinfo.flag_bits |= 0x08 # Include an extended local header.
1039 orig_zip.writestr(zinfo, data)
1040
1041 def test_close(self):
1042 """Check that the zipfile is closed after the 'with' block."""
1043 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
1044 for fpath, fdata in SMALL_TEST_DATA:
1045 zipfp.writestr(fpath, fdata)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001046 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
1047 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001048
1049 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001050 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
1051 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001052
1053 def test_close_on_exception(self):
1054 """Check that the zipfile is closed if an exception is raised in the
1055 'with' block."""
1056 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
1057 for fpath, fdata in SMALL_TEST_DATA:
1058 zipfp.writestr(fpath, fdata)
1059
1060 try:
1061 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
Georg Brandl4d540882010-10-28 06:42:33 +00001062 raise zipfile.BadZipFile()
1063 except zipfile.BadZipFile:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001064 self.assertIsNone(zipfp2.fp, 'zipfp is not closed')
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001065
Martin v. Löwisd099b562012-05-01 14:08:22 +02001066 def test_unsupported_version(self):
1067 # File has an extract_version of 120
1068 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 +02001069 b'\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00xPK\x01\x02x\x03x\x00\x00\x00\x00'
1070 b'\x00!p\xa1@\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00'
1071 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00\x00xPK\x05\x06'
1072 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 +03001073
Martin v. Löwisd099b562012-05-01 14:08:22 +02001074 self.assertRaises(NotImplementedError, zipfile.ZipFile,
1075 io.BytesIO(data), 'r')
1076
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001077 @requires_zlib
1078 def test_read_unicode_filenames(self):
1079 # bug #10801
1080 fname = findfile('zip_cp437_header.zip')
1081 with zipfile.ZipFile(fname) as zipfp:
1082 for name in zipfp.namelist():
1083 zipfp.open(name).close()
1084
1085 def test_write_unicode_filenames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001086 with zipfile.ZipFile(TESTFN, "w") as zf:
1087 zf.writestr("foo.txt", "Test for unicode filename")
1088 zf.writestr("\xf6.txt", "Test for unicode filename")
Ezio Melottie9615932010-01-24 19:26:24 +00001089 self.assertIsInstance(zf.infolist()[0].filename, str)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001090
1091 with zipfile.ZipFile(TESTFN, "r") as zf:
1092 self.assertEqual(zf.filelist[0].filename, "foo.txt")
1093 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
Martin v. Löwis8570f6a2008-05-05 17:44:38 +00001094
Serhiy Storchaka764fc9b2015-03-25 10:09:41 +02001095 def test_exclusive_create_zip_file(self):
1096 """Test exclusive creating a new zipfile."""
1097 unlink(TESTFN2)
1098 filename = 'testfile.txt'
1099 content = b'hello, world. this is some content.'
1100 with zipfile.ZipFile(TESTFN2, "x", zipfile.ZIP_STORED) as zipfp:
1101 zipfp.writestr(filename, content)
1102 with self.assertRaises(FileExistsError):
1103 zipfile.ZipFile(TESTFN2, "x", zipfile.ZIP_STORED)
1104 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1105 self.assertEqual(zipfp.namelist(), [filename])
1106 self.assertEqual(zipfp.read(filename), content)
1107
Ezio Melottiafd0d112009-07-15 17:17:17 +00001108 def test_create_non_existent_file_for_append(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001109 if os.path.exists(TESTFN):
1110 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001111
Thomas Wouterscf297e42007-02-23 15:07:44 +00001112 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001113 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +00001114
Thomas Wouterscf297e42007-02-23 15:07:44 +00001115 try:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001116 with zipfile.ZipFile(TESTFN, 'a') as zf:
1117 zf.writestr(filename, content)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001118 except OSError:
Thomas Wouterscf297e42007-02-23 15:07:44 +00001119 self.fail('Could not append data to a non-existent zip file.')
1120
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001121 self.assertTrue(os.path.exists(TESTFN))
Thomas Wouterscf297e42007-02-23 15:07:44 +00001122
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001123 with zipfile.ZipFile(TESTFN, 'r') as zf:
1124 self.assertEqual(zf.read(filename), content)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001125
Ezio Melottiafd0d112009-07-15 17:17:17 +00001126 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001127 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti35386712009-12-31 13:22:41 +00001128 # it opens if there's an error in the file. If it doesn't, the
1129 # traceback holds a reference to the ZipFile object and, indirectly,
1130 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001131 # On Windows, this causes the os.unlink() call to fail because the
1132 # underlying file is still open. This is SF bug #412214.
1133 #
Ezio Melotti35386712009-12-31 13:22:41 +00001134 with open(TESTFN, "w") as fp:
1135 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001136 try:
1137 zf = zipfile.ZipFile(TESTFN)
Georg Brandl4d540882010-10-28 06:42:33 +00001138 except zipfile.BadZipFile:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001139 pass
1140
Ezio Melottiafd0d112009-07-15 17:17:17 +00001141 def test_is_zip_erroneous_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001142 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001143 # - passing a filename
1144 with open(TESTFN, "w") as fp:
1145 fp.write("this is not a legal zip file\n")
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001146 self.assertFalse(zipfile.is_zipfile(TESTFN))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001147 # - passing a file object
1148 with open(TESTFN, "rb") as fp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001149 self.assertFalse(zipfile.is_zipfile(fp))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001150 # - passing a file-like object
1151 fp = io.BytesIO()
1152 fp.write(b"this is not a legal zip file\n")
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001153 self.assertFalse(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001154 fp.seek(0, 0)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001155 self.assertFalse(zipfile.is_zipfile(fp))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001156
Serhiy Storchakad2b15272013-01-31 15:27:07 +02001157 def test_damaged_zipfile(self):
1158 """Check that zipfiles with missing bytes at the end raise BadZipFile."""
1159 # - Create a valid zip file
1160 fp = io.BytesIO()
1161 with zipfile.ZipFile(fp, mode="w") as zipf:
1162 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
1163 zipfiledata = fp.getvalue()
1164
1165 # - Now create copies of it missing the last N bytes and make sure
1166 # a BadZipFile exception is raised when we try to open it
1167 for N in range(len(zipfiledata)):
1168 fp = io.BytesIO(zipfiledata[:N])
1169 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, fp)
1170
Ezio Melottiafd0d112009-07-15 17:17:17 +00001171 def test_is_zip_valid_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001172 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001173 # - passing a filename
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001174 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1175 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
1176
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001177 self.assertTrue(zipfile.is_zipfile(TESTFN))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001178 # - passing a file object
1179 with open(TESTFN, "rb") as fp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001180 self.assertTrue(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001181 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001182 zip_contents = fp.read()
1183 # - passing a file-like object
1184 fp = io.BytesIO()
1185 fp.write(zip_contents)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001186 self.assertTrue(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001187 fp.seek(0, 0)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001188 self.assertTrue(zipfile.is_zipfile(fp))
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001189
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001190 def test_non_existent_file_raises_OSError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001191 # make sure we don't raise an AttributeError when a partially-constructed
1192 # ZipFile instance is finalized; this tests for regression on SF tracker
1193 # bug #403871.
1194
1195 # The bug we're testing for caused an AttributeError to be raised
1196 # when a ZipFile instance was created for a file that did not
1197 # exist; the .fp member was not initialized but was needed by the
1198 # __del__() method. Since the AttributeError is in the __del__(),
1199 # it is ignored, but the user should be sufficiently annoyed by
1200 # the message on the output that regression will be noticed
1201 # quickly.
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001202 self.assertRaises(OSError, zipfile.ZipFile, TESTFN)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001203
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001204 def test_empty_file_raises_BadZipFile(self):
1205 f = open(TESTFN, 'w')
1206 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001207 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001208
Ezio Melotti35386712009-12-31 13:22:41 +00001209 with open(TESTFN, 'w') as fp:
1210 fp.write("short file")
Georg Brandl4d540882010-10-28 06:42:33 +00001211 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001212
Ezio Melottiafd0d112009-07-15 17:17:17 +00001213 def test_closed_zip_raises_RuntimeError(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001214 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001215 data = io.BytesIO()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001216 with zipfile.ZipFile(data, mode="w") as zipf:
1217 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001218
Andrew Svetlov737fb892012-12-18 21:14:22 +02001219 # This is correct; calling .read on a closed ZipFile should raise
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001220 # a RuntimeError, and so should calling .testzip. An earlier
1221 # version of .testzip would swallow this exception (and any other)
1222 # and report that the first file in the archive was corrupt.
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001223 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
1224 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001225 self.assertRaises(RuntimeError, zipf.testzip)
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001226 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Brian Curtin8fb9b862010-11-18 02:15:28 +00001227 with open(TESTFN, 'w') as f:
1228 f.write('zipfile test data')
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001229 self.assertRaises(RuntimeError, zipf.write, TESTFN)
1230
Ezio Melottiafd0d112009-07-15 17:17:17 +00001231 def test_bad_constructor_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001232 """Check that bad modes passed to ZipFile constructor are caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001233 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
1234
Ezio Melottiafd0d112009-07-15 17:17:17 +00001235 def test_bad_open_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001236 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001237 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1238 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1239
1240 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Serhiy Storchakae670be22016-06-11 19:32:44 +03001241 # read the data to make sure the file is there
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001242 zipf.read("foo.txt")
1243 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
Serhiy Storchakae670be22016-06-11 19:32:44 +03001244 # universal newlines support is removed
1245 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "U")
1246 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "rU")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001247
Ezio Melottiafd0d112009-07-15 17:17:17 +00001248 def test_read0(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001249 """Check that calling read(0) on a ZipExtFile object returns an empty
1250 string and doesn't advance file pointer."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001251 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1252 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1253 # read the data to make sure the file is there
Brian Curtin8fb9b862010-11-18 02:15:28 +00001254 with zipf.open("foo.txt") as f:
1255 for i in range(FIXEDTEST_SIZE):
1256 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001257
Brian Curtin8fb9b862010-11-18 02:15:28 +00001258 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001259
Ezio Melottiafd0d112009-07-15 17:17:17 +00001260 def test_open_non_existent_item(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001261 """Check that attempting to call open() for an item that doesn't
1262 exist in the archive raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001263 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1264 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001265
Ezio Melottiafd0d112009-07-15 17:17:17 +00001266 def test_bad_compression_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001267 """Check that bad compression methods passed to ZipFile.open are
1268 caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001269 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
1270
Martin v. Löwisb3260f02012-05-01 08:38:01 +02001271 def test_unsupported_compression(self):
1272 # data is declared as shrunk, but actually deflated
1273 data = (b'PK\x03\x04.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00'
Christian Tismer59202e52013-10-21 03:59:23 +02001274 b'\x00\x02\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00x\x03\x00PK\x01'
1275 b'\x02.\x03.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00\x00\x02\x00\x00'
1276 b'\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
1277 b'\x80\x01\x00\x00\x00\x00xPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00'
1278 b'/\x00\x00\x00!\x00\x00\x00\x00\x00')
Martin v. Löwisb3260f02012-05-01 08:38:01 +02001279 with zipfile.ZipFile(io.BytesIO(data), 'r') as zipf:
1280 self.assertRaises(NotImplementedError, zipf.open, 'x')
1281
Ezio Melottiafd0d112009-07-15 17:17:17 +00001282 def test_null_byte_in_filename(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001283 """Check that a filename containing a null byte is properly
1284 terminated."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001285 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1286 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
1287 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001288
Ezio Melottiafd0d112009-07-15 17:17:17 +00001289 def test_struct_sizes(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001290 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001291 self.assertEqual(zipfile.sizeEndCentDir, 22)
1292 self.assertEqual(zipfile.sizeCentralDir, 46)
1293 self.assertEqual(zipfile.sizeEndCentDir64, 56)
1294 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
1295
Ezio Melottiafd0d112009-07-15 17:17:17 +00001296 def test_comments(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001297 """Check that comments on the archive are handled properly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001298
1299 # check default comment is empty
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001300 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1301 self.assertEqual(zipf.comment, b'')
1302 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1303
1304 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1305 self.assertEqual(zipfr.comment, b'')
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001306
1307 # check a simple short comment
1308 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001309 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1310 zipf.comment = comment
1311 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1312 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1313 self.assertEqual(zipf.comment, comment)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001314
1315 # check a comment of max length
1316 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
1317 comment2 = comment2.encode("ascii")
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001318 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1319 zipf.comment = comment2
1320 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1321
1322 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1323 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001324
1325 # check a comment that is too long is truncated
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001326 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
Serhiy Storchaka9b7a1a12014-01-20 21:57:40 +02001327 with self.assertWarns(UserWarning):
1328 zipf.comment = comment2 + b'oops'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001329 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1330 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1331 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001332
Antoine Pitrouc3991852012-06-30 17:31:37 +02001333 # check that comments are correctly modified in append mode
1334 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1335 zipf.comment = b"original comment"
1336 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1337 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1338 zipf.comment = b"an updated comment"
1339 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1340 self.assertEqual(zipf.comment, b"an updated comment")
1341
1342 # check that comments are correctly shortened in append mode
1343 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1344 zipf.comment = b"original comment that's longer"
1345 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1346 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1347 zipf.comment = b"shorter comment"
1348 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1349 self.assertEqual(zipf.comment, b"shorter comment")
1350
R David Murrayf50b38a2012-04-12 18:44:58 -04001351 def test_unicode_comment(self):
1352 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1353 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1354 with self.assertRaises(TypeError):
1355 zipf.comment = "this is an error"
1356
1357 def test_change_comment_in_empty_archive(self):
1358 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1359 self.assertFalse(zipf.filelist)
1360 zipf.comment = b"this is a comment"
1361 with zipfile.ZipFile(TESTFN, "r") as zipf:
1362 self.assertEqual(zipf.comment, b"this is a comment")
1363
1364 def test_change_comment_in_nonempty_archive(self):
1365 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1366 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1367 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1368 self.assertTrue(zipf.filelist)
1369 zipf.comment = b"this is a comment"
1370 with zipfile.ZipFile(TESTFN, "r") as zipf:
1371 self.assertEqual(zipf.comment, b"this is a comment")
1372
Georg Brandl268e4d42010-10-14 06:59:45 +00001373 def test_empty_zipfile(self):
1374 # Check that creating a file in 'w' or 'a' mode and closing without
1375 # adding any files to the archives creates a valid empty ZIP file
1376 zipf = zipfile.ZipFile(TESTFN, mode="w")
1377 zipf.close()
1378 try:
1379 zipf = zipfile.ZipFile(TESTFN, mode="r")
1380 except zipfile.BadZipFile:
1381 self.fail("Unable to create empty ZIP file in 'w' mode")
1382
1383 zipf = zipfile.ZipFile(TESTFN, mode="a")
1384 zipf.close()
1385 try:
1386 zipf = zipfile.ZipFile(TESTFN, mode="r")
1387 except:
1388 self.fail("Unable to create empty ZIP file in 'a' mode")
1389
1390 def test_open_empty_file(self):
1391 # Issue 1710703: Check that opening a file with less than 22 bytes
Georg Brandl4d540882010-10-28 06:42:33 +00001392 # raises a BadZipFile exception (rather than the previously unhelpful
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001393 # OSError)
Georg Brandl268e4d42010-10-14 06:59:45 +00001394 f = open(TESTFN, 'w')
1395 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001396 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN, 'r')
Georg Brandl268e4d42010-10-14 06:59:45 +00001397
Senthil Kumaran29fa9d42011-10-20 01:46:00 +08001398 def test_create_zipinfo_before_1980(self):
1399 self.assertRaises(ValueError,
1400 zipfile.ZipInfo, 'seventies', (1979, 1, 1, 0, 0, 0))
1401
Gregory P. Smith0af8a862014-05-29 23:42:14 -07001402 def test_zipfile_with_short_extra_field(self):
1403 """If an extra field in the header is less than 4 bytes, skip it."""
1404 zipdata = (
1405 b'PK\x03\x04\x14\x00\x00\x00\x00\x00\x93\x9b\xad@\x8b\x9e'
1406 b'\xd9\xd3\x01\x00\x00\x00\x01\x00\x00\x00\x03\x00\x03\x00ab'
1407 b'c\x00\x00\x00APK\x01\x02\x14\x03\x14\x00\x00\x00\x00'
1408 b'\x00\x93\x9b\xad@\x8b\x9e\xd9\xd3\x01\x00\x00\x00\x01\x00\x00'
1409 b'\x00\x03\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00'
1410 b'\x00\x00\x00abc\x00\x00PK\x05\x06\x00\x00\x00\x00'
1411 b'\x01\x00\x01\x003\x00\x00\x00%\x00\x00\x00\x00\x00'
1412 )
1413 with zipfile.ZipFile(io.BytesIO(zipdata), 'r') as zipf:
1414 # testzip returns the name of the first corrupt file, or None
1415 self.assertIsNone(zipf.testzip())
1416
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001417 def test_open_conflicting_handles(self):
1418 # It's only possible to open one writable file handle at a time
1419 msg1 = b"It's fun to charter an accountant!"
1420 msg2 = b"And sail the wide accountant sea"
1421 msg3 = b"To find, explore the funds offshore"
1422 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipf:
1423 with zipf.open('foo', mode='w') as w2:
1424 w2.write(msg1)
1425 with zipf.open('bar', mode='w') as w1:
1426 with self.assertRaises(RuntimeError):
1427 zipf.open('handle', mode='w')
1428 with self.assertRaises(RuntimeError):
1429 zipf.open('foo', mode='r')
1430 with self.assertRaises(RuntimeError):
1431 zipf.writestr('str', 'abcde')
1432 with self.assertRaises(RuntimeError):
1433 zipf.write(__file__, 'file')
1434 with self.assertRaises(RuntimeError):
1435 zipf.close()
1436 w1.write(msg2)
1437 with zipf.open('baz', mode='w') as w2:
1438 w2.write(msg3)
1439
1440 with zipfile.ZipFile(TESTFN2, 'r') as zipf:
1441 self.assertEqual(zipf.read('foo'), msg1)
1442 self.assertEqual(zipf.read('bar'), msg2)
1443 self.assertEqual(zipf.read('baz'), msg3)
1444 self.assertEqual(zipf.namelist(), ['foo', 'bar', 'baz'])
1445
Guido van Rossumd8faa362007-04-27 19:54:29 +00001446 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001447 unlink(TESTFN)
1448 unlink(TESTFN2)
1449
Thomas Wouterscf297e42007-02-23 15:07:44 +00001450
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001451class AbstractBadCrcTests:
1452 def test_testzip_with_bad_crc(self):
1453 """Tests that files with bad CRCs return their name from testzip."""
1454 zipdata = self.zip_with_bad_crc
1455
1456 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1457 # testzip returns the name of the first corrupt file, or None
1458 self.assertEqual('afile', zipf.testzip())
1459
1460 def test_read_with_bad_crc(self):
1461 """Tests that files with bad CRCs raise a BadZipFile exception when read."""
1462 zipdata = self.zip_with_bad_crc
1463
1464 # Using ZipFile.read()
1465 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1466 self.assertRaises(zipfile.BadZipFile, zipf.read, 'afile')
1467
1468 # Using ZipExtFile.read()
1469 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1470 with zipf.open('afile', 'r') as corrupt_file:
1471 self.assertRaises(zipfile.BadZipFile, corrupt_file.read)
1472
1473 # Same with small reads (in order to exercise the buffering logic)
1474 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1475 with zipf.open('afile', 'r') as corrupt_file:
1476 corrupt_file.MIN_READ_SIZE = 2
1477 with self.assertRaises(zipfile.BadZipFile):
1478 while corrupt_file.read(2):
1479 pass
1480
1481
1482class StoredBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1483 compression = zipfile.ZIP_STORED
1484 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001485 b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
1486 b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
1487 b'ilehello,AworldP'
1488 b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
1489 b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
1490 b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
1491 b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
1492 b'\0\0/\0\0\0\0\0')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001493
1494@requires_zlib
1495class DeflateBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1496 compression = zipfile.ZIP_DEFLATED
1497 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001498 b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
1499 b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1500 b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
1501 b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
1502 b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
1503 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
1504 b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
1505 b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001506
1507@requires_bz2
1508class Bzip2BadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1509 compression = zipfile.ZIP_BZIP2
1510 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001511 b'PK\x03\x04\x14\x03\x00\x00\x0c\x00nu\x0c=FA'
1512 b'KE8\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1513 b'ileBZh91AY&SY\xd4\xa8\xca'
1514 b'\x7f\x00\x00\x0f\x11\x80@\x00\x06D\x90\x80 \x00 \xa5'
1515 b'P\xd9!\x03\x03\x13\x13\x13\x89\xa9\xa9\xc2u5:\x9f'
1516 b'\x8b\xb9"\x9c(HjTe?\x80PK\x01\x02\x14'
1517 b'\x03\x14\x03\x00\x00\x0c\x00nu\x0c=FAKE8'
1518 b'\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\x00'
1519 b'\x00 \x80\x80\x81\x00\x00\x00\x00afilePK'
1520 b'\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00\x00[\x00'
1521 b'\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001522
1523@requires_lzma
1524class LzmaBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1525 compression = zipfile.ZIP_LZMA
1526 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001527 b'PK\x03\x04\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
1528 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1529 b'ile\t\x04\x05\x00]\x00\x00\x00\x04\x004\x19I'
1530 b'\xee\x8d\xe9\x17\x89:3`\tq!.8\x00PK'
1531 b'\x01\x02\x14\x03\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
1532 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00'
1533 b'\x00\x00\x00\x00 \x80\x80\x81\x00\x00\x00\x00afil'
1534 b'ePK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00'
1535 b'\x00>\x00\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001536
1537
Thomas Wouterscf297e42007-02-23 15:07:44 +00001538class DecryptionTests(unittest.TestCase):
Ezio Melotti35386712009-12-31 13:22:41 +00001539 """Check that ZIP decryption works. Since the library does not
1540 support encryption at the moment, we use a pre-generated encrypted
1541 ZIP file."""
Thomas Wouterscf297e42007-02-23 15:07:44 +00001542
1543 data = (
Christian Tismer59202e52013-10-21 03:59:23 +02001544 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
1545 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
1546 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
1547 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
1548 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
1549 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
1550 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +00001551 data2 = (
Christian Tismer59202e52013-10-21 03:59:23 +02001552 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
1553 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
1554 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
1555 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
1556 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
1557 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
1558 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
1559 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +00001560
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001561 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +00001562 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +00001563
1564 def setUp(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001565 with open(TESTFN, "wb") as fp:
1566 fp.write(self.data)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001567 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti35386712009-12-31 13:22:41 +00001568 with open(TESTFN2, "wb") as fp:
1569 fp.write(self.data2)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001570 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001571
1572 def tearDown(self):
1573 self.zip.close()
1574 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001575 self.zip2.close()
1576 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001577
Ezio Melottiafd0d112009-07-15 17:17:17 +00001578 def test_no_password(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001579 # Reading the encrypted file without password
1580 # must generate a RunTime exception
1581 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001582 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001583
Ezio Melottiafd0d112009-07-15 17:17:17 +00001584 def test_bad_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001585 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001586 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001587 self.zip2.setpassword(b"perl")
1588 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001589
Ezio Melotti975077a2011-05-19 22:03:22 +03001590 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +00001591 def test_good_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001592 self.zip.setpassword(b"python")
Ezio Melotti35386712009-12-31 13:22:41 +00001593 self.assertEqual(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001594 self.zip2.setpassword(b"12345")
Ezio Melotti35386712009-12-31 13:22:41 +00001595 self.assertEqual(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001596
R. David Murray8d855d82010-12-21 21:53:37 +00001597 def test_unicode_password(self):
1598 self.assertRaises(TypeError, self.zip.setpassword, "unicode")
1599 self.assertRaises(TypeError, self.zip.read, "test.txt", "python")
1600 self.assertRaises(TypeError, self.zip.open, "test.txt", pwd="python")
1601 self.assertRaises(TypeError, self.zip.extract, "test.txt", pwd="python")
1602
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001603class AbstractTestsWithRandomBinaryFiles:
1604 @classmethod
1605 def setUpClass(cls):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001606 datacount = randint(16, 64)*1024 + randint(1, 1024)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001607 cls.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
1608 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001609
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001610 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001611 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +00001612 with open(TESTFN, "wb") as fp:
1613 fp.write(self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001614
1615 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001616 unlink(TESTFN)
1617 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001618
Ezio Melottiafd0d112009-07-15 17:17:17 +00001619 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001620 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001621 with zipfile.ZipFile(f, "w", compression) as zipfp:
1622 zipfp.write(TESTFN, "another.name")
1623 zipfp.write(TESTFN, TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001624
Ezio Melottiafd0d112009-07-15 17:17:17 +00001625 def zip_test(self, f, compression):
1626 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001627
1628 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001629 with zipfile.ZipFile(f, "r", compression) as zipfp:
1630 testdata = zipfp.read(TESTFN)
1631 self.assertEqual(len(testdata), len(self.data))
1632 self.assertEqual(testdata, self.data)
1633 self.assertEqual(zipfp.read("another.name"), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001634
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001635 def test_read(self):
1636 for f in get_files(self):
1637 self.zip_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001638
Ezio Melottiafd0d112009-07-15 17:17:17 +00001639 def zip_open_test(self, f, compression):
1640 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001641
1642 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001643 with zipfile.ZipFile(f, "r", compression) as zipfp:
1644 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001645 with zipfp.open(TESTFN) as zipopen1:
1646 while True:
1647 read_data = zipopen1.read(256)
1648 if not read_data:
1649 break
1650 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001651
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001652 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001653 with zipfp.open("another.name") as zipopen2:
1654 while True:
1655 read_data = zipopen2.read(256)
1656 if not read_data:
1657 break
1658 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001659
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001660 testdata1 = b''.join(zipdata1)
1661 self.assertEqual(len(testdata1), len(self.data))
1662 self.assertEqual(testdata1, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001663
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001664 testdata2 = b''.join(zipdata2)
Ezio Melotti35386712009-12-31 13:22:41 +00001665 self.assertEqual(len(testdata2), len(self.data))
1666 self.assertEqual(testdata2, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001667
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001668 def test_open(self):
1669 for f in get_files(self):
1670 self.zip_open_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001671
Ezio Melottiafd0d112009-07-15 17:17:17 +00001672 def zip_random_open_test(self, f, compression):
1673 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001674
1675 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001676 with zipfile.ZipFile(f, "r", compression) as zipfp:
1677 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001678 with zipfp.open(TESTFN) as zipopen1:
1679 while True:
1680 read_data = zipopen1.read(randint(1, 1024))
1681 if not read_data:
1682 break
1683 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001684
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001685 testdata = b''.join(zipdata1)
1686 self.assertEqual(len(testdata), len(self.data))
1687 self.assertEqual(testdata, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001688
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001689 def test_random_open(self):
1690 for f in get_files(self):
1691 self.zip_random_open_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001692
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001693
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001694class StoredTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1695 unittest.TestCase):
1696 compression = zipfile.ZIP_STORED
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001697
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001698@requires_zlib
1699class DeflateTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1700 unittest.TestCase):
1701 compression = zipfile.ZIP_DEFLATED
1702
1703@requires_bz2
1704class Bzip2TestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1705 unittest.TestCase):
1706 compression = zipfile.ZIP_BZIP2
1707
1708@requires_lzma
1709class LzmaTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1710 unittest.TestCase):
1711 compression = zipfile.ZIP_LZMA
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001712
Ezio Melotti76430242009-07-11 18:28:48 +00001713
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001714# Privide the tell() method but not seek()
1715class Tellable:
1716 def __init__(self, fp):
1717 self.fp = fp
1718 self.offset = 0
1719
1720 def write(self, data):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02001721 n = self.fp.write(data)
1722 self.offset += n
1723 return n
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001724
1725 def tell(self):
1726 return self.offset
1727
1728 def flush(self):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02001729 self.fp.flush()
1730
1731class Unseekable:
1732 def __init__(self, fp):
1733 self.fp = fp
1734
1735 def write(self, data):
1736 return self.fp.write(data)
1737
1738 def flush(self):
1739 self.fp.flush()
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001740
1741class UnseekableTests(unittest.TestCase):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02001742 def test_writestr(self):
1743 for wrapper in (lambda f: f), Tellable, Unseekable:
1744 with self.subTest(wrapper=wrapper):
1745 f = io.BytesIO()
1746 f.write(b'abc')
1747 bf = io.BufferedWriter(f)
1748 with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) as zipfp:
1749 zipfp.writestr('ones', b'111')
1750 zipfp.writestr('twos', b'222')
1751 self.assertEqual(f.getvalue()[:5], b'abcPK')
1752 with zipfile.ZipFile(f, mode='r') as zipf:
1753 with zipf.open('ones') as zopen:
1754 self.assertEqual(zopen.read(), b'111')
1755 with zipf.open('twos') as zopen:
1756 self.assertEqual(zopen.read(), b'222')
1757
1758 def test_write(self):
1759 for wrapper in (lambda f: f), Tellable, Unseekable:
1760 with self.subTest(wrapper=wrapper):
1761 f = io.BytesIO()
1762 f.write(b'abc')
1763 bf = io.BufferedWriter(f)
1764 with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) as zipfp:
1765 self.addCleanup(unlink, TESTFN)
1766 with open(TESTFN, 'wb') as f2:
1767 f2.write(b'111')
1768 zipfp.write(TESTFN, 'ones')
1769 with open(TESTFN, 'wb') as f2:
1770 f2.write(b'222')
1771 zipfp.write(TESTFN, 'twos')
1772 self.assertEqual(f.getvalue()[:5], b'abcPK')
1773 with zipfile.ZipFile(f, mode='r') as zipf:
1774 with zipf.open('ones') as zopen:
1775 self.assertEqual(zopen.read(), b'111')
1776 with zipf.open('twos') as zopen:
1777 self.assertEqual(zopen.read(), b'222')
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001778
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001779 def test_open_write(self):
1780 for wrapper in (lambda f: f), Tellable, Unseekable:
1781 with self.subTest(wrapper=wrapper):
1782 f = io.BytesIO()
1783 f.write(b'abc')
1784 bf = io.BufferedWriter(f)
1785 with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) as zipf:
1786 with zipf.open('ones', 'w') as zopen:
1787 zopen.write(b'111')
1788 with zipf.open('twos', 'w') as zopen:
1789 zopen.write(b'222')
1790 self.assertEqual(f.getvalue()[:5], b'abcPK')
1791 with zipfile.ZipFile(f) as zipf:
1792 self.assertEqual(zipf.read('ones'), b'111')
1793 self.assertEqual(zipf.read('twos'), b'222')
1794
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001795
Ezio Melotti975077a2011-05-19 22:03:22 +03001796@requires_zlib
Guido van Rossumd8faa362007-04-27 19:54:29 +00001797class TestsWithMultipleOpens(unittest.TestCase):
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001798 @classmethod
1799 def setUpClass(cls):
1800 cls.data1 = b'111' + getrandbytes(10000)
1801 cls.data2 = b'222' + getrandbytes(10000)
1802
1803 def make_test_archive(self, f):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001804 # Create the ZIP archive
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001805 with zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as zipfp:
1806 zipfp.writestr('ones', self.data1)
1807 zipfp.writestr('twos', self.data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001808
Ezio Melottiafd0d112009-07-15 17:17:17 +00001809 def test_same_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001810 # Verify that (when the ZipFile is in control of creating file objects)
1811 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001812 for f in get_files(self):
1813 self.make_test_archive(f)
1814 with zipfile.ZipFile(f, mode="r") as zipf:
1815 with zipf.open('ones') as zopen1, zipf.open('ones') as zopen2:
1816 data1 = zopen1.read(500)
1817 data2 = zopen2.read(500)
1818 data1 += zopen1.read()
1819 data2 += zopen2.read()
1820 self.assertEqual(data1, data2)
1821 self.assertEqual(data1, self.data1)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001822
Ezio Melottiafd0d112009-07-15 17:17:17 +00001823 def test_different_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001824 # Verify that (when the ZipFile is in control of creating file objects)
1825 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001826 for f in get_files(self):
1827 self.make_test_archive(f)
1828 with zipfile.ZipFile(f, mode="r") as zipf:
1829 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1830 data1 = zopen1.read(500)
1831 data2 = zopen2.read(500)
1832 data1 += zopen1.read()
1833 data2 += zopen2.read()
1834 self.assertEqual(data1, self.data1)
1835 self.assertEqual(data2, self.data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001836
Ezio Melottiafd0d112009-07-15 17:17:17 +00001837 def test_interleaved(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001838 # Verify that (when the ZipFile is in control of creating file objects)
1839 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001840 for f in get_files(self):
1841 self.make_test_archive(f)
1842 with zipfile.ZipFile(f, mode="r") as zipf:
Serhiy Storchakad76c7c22016-05-13 21:18:58 +03001843 with zipf.open('ones') as zopen1:
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001844 data1 = zopen1.read(500)
Serhiy Storchakad76c7c22016-05-13 21:18:58 +03001845 with zipf.open('twos') as zopen2:
1846 data2 = zopen2.read(500)
1847 data1 += zopen1.read()
1848 data2 += zopen2.read()
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001849 self.assertEqual(data1, self.data1)
1850 self.assertEqual(data2, self.data2)
1851
1852 def test_read_after_close(self):
1853 for f in get_files(self):
1854 self.make_test_archive(f)
1855 with contextlib.ExitStack() as stack:
1856 with zipfile.ZipFile(f, 'r') as zipf:
1857 zopen1 = stack.enter_context(zipf.open('ones'))
1858 zopen2 = stack.enter_context(zipf.open('twos'))
Brian Curtin8fb9b862010-11-18 02:15:28 +00001859 data1 = zopen1.read(500)
1860 data2 = zopen2.read(500)
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001861 data1 += zopen1.read()
1862 data2 += zopen2.read()
1863 self.assertEqual(data1, self.data1)
1864 self.assertEqual(data2, self.data2)
1865
1866 def test_read_after_write(self):
1867 for f in get_files(self):
1868 with zipfile.ZipFile(f, 'w', zipfile.ZIP_DEFLATED) as zipf:
1869 zipf.writestr('ones', self.data1)
1870 zipf.writestr('twos', self.data2)
1871 with zipf.open('ones') as zopen1:
1872 data1 = zopen1.read(500)
1873 self.assertEqual(data1, self.data1[:500])
1874 with zipfile.ZipFile(f, 'r') as zipf:
1875 data1 = zipf.read('ones')
1876 data2 = zipf.read('twos')
1877 self.assertEqual(data1, self.data1)
1878 self.assertEqual(data2, self.data2)
1879
1880 def test_write_after_read(self):
1881 for f in get_files(self):
1882 with zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as zipf:
1883 zipf.writestr('ones', self.data1)
1884 with zipf.open('ones') as zopen1:
1885 zopen1.read(500)
1886 zipf.writestr('twos', self.data2)
1887 with zipfile.ZipFile(f, 'r') as zipf:
1888 data1 = zipf.read('ones')
1889 data2 = zipf.read('twos')
1890 self.assertEqual(data1, self.data1)
1891 self.assertEqual(data2, self.data2)
1892
1893 def test_many_opens(self):
1894 # Verify that read() and open() promptly close the file descriptor,
1895 # and don't rely on the garbage collector to free resources.
1896 self.make_test_archive(TESTFN2)
1897 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
1898 for x in range(100):
1899 zipf.read('ones')
1900 with zipf.open('ones') as zopen1:
1901 pass
1902 with open(os.devnull) as f:
1903 self.assertLess(f.fileno(), 100)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001904
Serhiy Storchaka18ee29d2016-05-13 13:52:49 +03001905 def test_write_while_reading(self):
1906 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_DEFLATED) as zipf:
1907 zipf.writestr('ones', self.data1)
1908 with zipfile.ZipFile(TESTFN2, 'a', zipfile.ZIP_DEFLATED) as zipf:
1909 with zipf.open('ones', 'r') as r1:
1910 data1 = r1.read(500)
1911 with zipf.open('twos', 'w') as w1:
1912 w1.write(self.data2)
1913 data1 += r1.read()
1914 self.assertEqual(data1, self.data1)
1915 with zipfile.ZipFile(TESTFN2) as zipf:
1916 self.assertEqual(zipf.read('twos'), self.data2)
1917
Guido van Rossumd8faa362007-04-27 19:54:29 +00001918 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001919 unlink(TESTFN2)
1920
Guido van Rossumd8faa362007-04-27 19:54:29 +00001921
Martin v. Löwis59e47792009-01-24 14:10:07 +00001922class TestWithDirectory(unittest.TestCase):
1923 def setUp(self):
1924 os.mkdir(TESTFN2)
1925
Ezio Melottiafd0d112009-07-15 17:17:17 +00001926 def test_extract_dir(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001927 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
1928 zipf.extractall(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001929 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1930 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1931 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1932
Ezio Melottiafd0d112009-07-15 17:17:17 +00001933 def test_bug_6050(self):
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001934 # Extraction should succeed if directories already exist
1935 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottiafd0d112009-07-15 17:17:17 +00001936 self.test_extract_dir()
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001937
Serhiy Storchaka46a34922014-09-23 22:40:23 +03001938 def test_write_dir(self):
1939 dirpath = os.path.join(TESTFN2, "x")
1940 os.mkdir(dirpath)
1941 mode = os.stat(dirpath).st_mode & 0xFFFF
1942 with zipfile.ZipFile(TESTFN, "w") as zipf:
1943 zipf.write(dirpath)
1944 zinfo = zipf.filelist[0]
1945 self.assertTrue(zinfo.filename.endswith("/x/"))
1946 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1947 zipf.write(dirpath, "y")
1948 zinfo = zipf.filelist[1]
1949 self.assertTrue(zinfo.filename, "y/")
1950 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1951 with zipfile.ZipFile(TESTFN, "r") as zipf:
1952 zinfo = zipf.filelist[0]
1953 self.assertTrue(zinfo.filename.endswith("/x/"))
1954 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1955 zinfo = zipf.filelist[1]
1956 self.assertTrue(zinfo.filename, "y/")
1957 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1958 target = os.path.join(TESTFN2, "target")
1959 os.mkdir(target)
1960 zipf.extractall(target)
1961 self.assertTrue(os.path.isdir(os.path.join(target, "y")))
1962 self.assertEqual(len(os.listdir(target)), 2)
1963
1964 def test_writestr_dir(self):
Martin v. Löwis59e47792009-01-24 14:10:07 +00001965 os.mkdir(os.path.join(TESTFN2, "x"))
Serhiy Storchaka46a34922014-09-23 22:40:23 +03001966 with zipfile.ZipFile(TESTFN, "w") as zipf:
1967 zipf.writestr("x/", b'')
1968 zinfo = zipf.filelist[0]
1969 self.assertEqual(zinfo.filename, "x/")
1970 self.assertEqual(zinfo.external_attr, (0o40775 << 16) | 0x10)
1971 with zipfile.ZipFile(TESTFN, "r") as zipf:
1972 zinfo = zipf.filelist[0]
1973 self.assertTrue(zinfo.filename.endswith("x/"))
1974 self.assertEqual(zinfo.external_attr, (0o40775 << 16) | 0x10)
1975 target = os.path.join(TESTFN2, "target")
1976 os.mkdir(target)
1977 zipf.extractall(target)
1978 self.assertTrue(os.path.isdir(os.path.join(target, "x")))
1979 self.assertEqual(os.listdir(target), ["x"])
Martin v. Löwis59e47792009-01-24 14:10:07 +00001980
1981 def tearDown(self):
Victor Stinner57004c62014-09-04 00:49:01 +02001982 rmtree(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001983 if os.path.exists(TESTFN):
Ezio Melotti76430242009-07-11 18:28:48 +00001984 unlink(TESTFN)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001985
Guido van Rossumd8faa362007-04-27 19:54:29 +00001986
Serhiy Storchaka503f9082016-02-08 00:02:25 +02001987class ZipInfoTests(unittest.TestCase):
1988 def test_from_file(self):
1989 zi = zipfile.ZipInfo.from_file(__file__)
1990 self.assertEqual(posixpath.basename(zi.filename), 'test_zipfile.py')
1991 self.assertFalse(zi.is_dir())
1992
1993 def test_from_dir(self):
1994 dirpath = os.path.dirname(os.path.abspath(__file__))
1995 zi = zipfile.ZipInfo.from_file(dirpath, 'stdlib_tests')
1996 self.assertEqual(zi.filename, 'stdlib_tests/')
1997 self.assertTrue(zi.is_dir())
1998 self.assertEqual(zi.compress_type, zipfile.ZIP_STORED)
1999 self.assertEqual(zi.file_size, 0)
2000
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00002001if __name__ == "__main__":
Brett Cannond5b4e1d2013-06-12 19:57:19 -04002002 unittest.main()