blob: d18a77017fa8081f6c5f99a8ac27b965edc5dd82 [file] [log] [blame]
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001import contextlib
Ezio Melotti74c96ec2009-07-08 22:24:06 +00002import io
3import os
Georg Brandl5ba11de2011-01-01 10:09:32 +00004import sys
Brett Cannonb57a0852013-06-15 17:32:30 -04005import importlib.util
Ezio Melotti35386712009-12-31 13:22:41 +00006import time
Ezio Melotti74c96ec2009-07-08 22:24:06 +00007import struct
8import zipfile
9import unittest
10
Tim Petersa45cacf2004-08-20 03:47:14 +000011
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000012from tempfile import TemporaryFile
Serhiy Storchakafa6bc292013-07-22 21:00:11 +030013from random import randint, random, getrandbits
Tim Petersa19a1682001-03-29 04:36:09 +000014
Victor Stinner57004c62014-09-04 00:49:01 +020015from test.support import (TESTFN, findfile, unlink, rmtree,
Serhiy Storchakac5b75db2013-01-29 20:14:08 +020016 requires_zlib, requires_bz2, requires_lzma,
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +020017 captured_stdout, check_warnings)
Guido van Rossum368f04a2000-04-10 13:23:04 +000018
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000019TESTFN2 = TESTFN + "2"
Martin v. Löwis59e47792009-01-24 14:10:07 +000020TESTFNDIR = TESTFN + "d"
Guido van Rossumb5a755e2007-07-18 18:15:48 +000021FIXEDTEST_SIZE = 1000
Georg Brandl5ba11de2011-01-01 10:09:32 +000022DATAFILES_DIR = 'zipfile_datafiles'
Guido van Rossum368f04a2000-04-10 13:23:04 +000023
Christian Heimes790c8232008-01-07 21:14:23 +000024SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'),
25 ('ziptest2dir/_ziptest2', 'qawsedrftg'),
Gregory P. Smithb47acbf2013-02-01 11:22:43 -080026 ('ziptest2dir/ziptest3dir/_ziptest3', 'azsxdcfvgb'),
Christian Heimes790c8232008-01-07 21:14:23 +000027 ('ziptest2dir/ziptest3dir/ziptest4dir/_ziptest3', '6y7u8i9o0p')]
28
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +020029def getrandbytes(size):
30 return getrandbits(8 * size).to_bytes(size, 'little')
31
Serhiy Storchakafa6bc292013-07-22 21:00:11 +030032def get_files(test):
33 yield TESTFN2
34 with TemporaryFile() as f:
35 yield f
36 test.assertFalse(f.closed)
37 with io.BytesIO() as f:
38 yield f
39 test.assertFalse(f.closed)
Ezio Melotti76430242009-07-11 18:28:48 +000040
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +020041def openU(zipfp, fn):
42 with check_warnings(('', DeprecationWarning)):
43 return zipfp.open(fn, 'rU')
44
Serhiy Storchakafa6bc292013-07-22 21:00:11 +030045class AbstractTestsWithSourceFile:
46 @classmethod
47 def setUpClass(cls):
48 cls.line_gen = [bytes("Zipfile test line %d. random float: %f\n" %
49 (i, random()), "ascii")
50 for i in range(FIXEDTEST_SIZE)]
51 cls.data = b''.join(cls.line_gen)
52
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000053 def setUp(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000054 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +000055 with open(TESTFN, "wb") as fp:
56 fp.write(self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000057
Ezio Melottiafd0d112009-07-15 17:17:17 +000058 def make_test_archive(self, f, compression):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000059 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000060 with zipfile.ZipFile(f, "w", compression) as zipfp:
61 zipfp.write(TESTFN, "another.name")
62 zipfp.write(TESTFN, TESTFN)
63 zipfp.writestr("strfile", self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000064
Ezio Melottiafd0d112009-07-15 17:17:17 +000065 def zip_test(self, f, compression):
66 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +000067
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000068 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000069 with zipfile.ZipFile(f, "r", compression) as zipfp:
70 self.assertEqual(zipfp.read(TESTFN), self.data)
71 self.assertEqual(zipfp.read("another.name"), self.data)
72 self.assertEqual(zipfp.read("strfile"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000073
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000074 # Print the ZIP directory
75 fp = io.StringIO()
76 zipfp.printdir(file=fp)
77 directory = fp.getvalue()
78 lines = directory.splitlines()
Ezio Melotti35386712009-12-31 13:22:41 +000079 self.assertEqual(len(lines), 4) # Number of files + header
Thomas Wouters0e3f5912006-08-11 14:57:12 +000080
Benjamin Peterson577473f2010-01-19 00:09:57 +000081 self.assertIn('File Name', lines[0])
82 self.assertIn('Modified', lines[0])
83 self.assertIn('Size', lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +000084
Ezio Melotti35386712009-12-31 13:22:41 +000085 fn, date, time_, size = lines[1].split()
86 self.assertEqual(fn, 'another.name')
87 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
88 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
89 self.assertEqual(size, str(len(self.data)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000090
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000091 # Check the namelist
92 names = zipfp.namelist()
Ezio Melotti35386712009-12-31 13:22:41 +000093 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +000094 self.assertIn(TESTFN, names)
95 self.assertIn("another.name", names)
96 self.assertIn("strfile", 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]
101 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000102 self.assertIn(TESTFN, names)
103 self.assertIn("another.name", names)
104 self.assertIn("strfile", names)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000105 for i in infos:
Ezio Melotti35386712009-12-31 13:22:41 +0000106 self.assertEqual(i.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000107
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000108 # check getinfo
109 for nm in (TESTFN, "another.name", "strfile"):
110 info = zipfp.getinfo(nm)
Ezio Melotti35386712009-12-31 13:22:41 +0000111 self.assertEqual(info.filename, nm)
112 self.assertEqual(info.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000113
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000114 # Check that testzip doesn't raise an exception
115 zipfp.testzip()
Tim Peters7d3bad62001-04-04 18:56:49 +0000116
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300117 def test_basic(self):
118 for f in get_files(self):
119 self.zip_test(f, self.compression)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000120
Ezio Melottiafd0d112009-07-15 17:17:17 +0000121 def zip_open_test(self, f, compression):
122 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000123
124 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000125 with zipfile.ZipFile(f, "r", compression) as zipfp:
126 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000127 with zipfp.open(TESTFN) as zipopen1:
128 while True:
129 read_data = zipopen1.read(256)
130 if not read_data:
131 break
132 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000133
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000134 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000135 with zipfp.open("another.name") as zipopen2:
136 while True:
137 read_data = zipopen2.read(256)
138 if not read_data:
139 break
140 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000141
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000142 self.assertEqual(b''.join(zipdata1), self.data)
143 self.assertEqual(b''.join(zipdata2), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000144
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300145 def test_open(self):
146 for f in get_files(self):
147 self.zip_open_test(f, self.compression)
Georg Brandlb533e262008-05-25 18:19:30 +0000148
Ezio Melottiafd0d112009-07-15 17:17:17 +0000149 def zip_random_open_test(self, f, compression):
150 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000151
152 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000153 with zipfile.ZipFile(f, "r", compression) as zipfp:
154 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000155 with zipfp.open(TESTFN) as zipopen1:
156 while True:
157 read_data = zipopen1.read(randint(1, 1024))
158 if not read_data:
159 break
160 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000161
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000162 self.assertEqual(b''.join(zipdata1), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000163
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300164 def test_random_open(self):
165 for f in get_files(self):
166 self.zip_random_open_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000167
Serhiy Storchakad2c07a52013-09-27 22:11:57 +0300168 def zip_read1_test(self, f, compression):
169 self.make_test_archive(f, compression)
170
171 # Read the ZIP archive
172 with zipfile.ZipFile(f, "r") as zipfp, \
173 zipfp.open(TESTFN) as zipopen:
174 zipdata = []
175 while True:
176 read_data = zipopen.read1(-1)
177 if not read_data:
178 break
179 zipdata.append(read_data)
180
181 self.assertEqual(b''.join(zipdata), self.data)
182
183 def test_read1(self):
184 for f in get_files(self):
185 self.zip_read1_test(f, self.compression)
186
187 def zip_read1_10_test(self, f, compression):
188 self.make_test_archive(f, compression)
189
190 # Read the ZIP archive
191 with zipfile.ZipFile(f, "r") as zipfp, \
192 zipfp.open(TESTFN) as zipopen:
193 zipdata = []
194 while True:
195 read_data = zipopen.read1(10)
196 self.assertLessEqual(len(read_data), 10)
197 if not read_data:
198 break
199 zipdata.append(read_data)
200
201 self.assertEqual(b''.join(zipdata), self.data)
202
203 def test_read1_10(self):
204 for f in get_files(self):
205 self.zip_read1_10_test(f, self.compression)
206
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000207 def zip_readline_read_test(self, f, compression):
208 self.make_test_archive(f, compression)
209
210 # Read the ZIP archive
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300211 with zipfile.ZipFile(f, "r") as zipfp, \
212 zipfp.open(TESTFN) as zipopen:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000213 data = b''
214 while True:
215 read = zipopen.readline()
216 if not read:
217 break
218 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000219
Brian Curtin8fb9b862010-11-18 02:15:28 +0000220 read = zipopen.read(100)
221 if not read:
222 break
223 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000224
225 self.assertEqual(data, self.data)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300226
227 def test_readline_read(self):
228 # Issue #7610: calls to readline() interleaved with calls to read().
229 for f in get_files(self):
230 self.zip_readline_read_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000231
Ezio Melottiafd0d112009-07-15 17:17:17 +0000232 def zip_readline_test(self, f, compression):
233 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000234
235 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000236 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000237 with zipfp.open(TESTFN) as zipopen:
238 for line in self.line_gen:
239 linedata = zipopen.readline()
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300240 self.assertEqual(linedata, line)
241
242 def test_readline(self):
243 for f in get_files(self):
244 self.zip_readline_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000245
Ezio Melottiafd0d112009-07-15 17:17:17 +0000246 def zip_readlines_test(self, f, compression):
247 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000248
249 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000250 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000251 with zipfp.open(TESTFN) as zipopen:
252 ziplines = zipopen.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000253 for line, zipline in zip(self.line_gen, ziplines):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300254 self.assertEqual(zipline, line)
255
256 def test_readlines(self):
257 for f in get_files(self):
258 self.zip_readlines_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000259
Ezio Melottiafd0d112009-07-15 17:17:17 +0000260 def zip_iterlines_test(self, f, compression):
261 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000262
263 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000264 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000265 with zipfp.open(TESTFN) as zipopen:
266 for line, zipline in zip(self.line_gen, zipopen):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300267 self.assertEqual(zipline, line)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000268
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300269 def test_iterlines(self):
270 for f in get_files(self):
271 self.zip_iterlines_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000272
Ezio Melottiafd0d112009-07-15 17:17:17 +0000273 def test_low_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000274 """Check for cases where compressed data is larger than original."""
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000275 # Create the ZIP archive
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300276 with zipfile.ZipFile(TESTFN2, "w", self.compression) as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000277 zipfp.writestr("strfile", '12')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000278
279 # Get an open object for strfile
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300280 with zipfile.ZipFile(TESTFN2, "r", self.compression) as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000281 with zipfp.open("strfile") as openobj:
282 self.assertEqual(openobj.read(1), b'1')
283 self.assertEqual(openobj.read(1), b'2')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000284
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300285 def test_writestr_compression(self):
286 zipfp = zipfile.ZipFile(TESTFN2, "w")
287 zipfp.writestr("b.txt", "hello world", compress_type=self.compression)
288 info = zipfp.getinfo('b.txt')
289 self.assertEqual(info.compress_type, self.compression)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200290
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300291 def test_read_return_size(self):
292 # Issue #9837: ZipExtFile.read() shouldn't return more bytes
293 # than requested.
294 for test_size in (1, 4095, 4096, 4097, 16384):
295 file_size = test_size + 1
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +0200296 junk = getrandbytes(file_size)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300297 with zipfile.ZipFile(io.BytesIO(), "w", self.compression) as zipf:
298 zipf.writestr('foo', junk)
299 with zipf.open('foo', 'r') as fp:
300 buf = fp.read(test_size)
301 self.assertEqual(len(buf), test_size)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200302
Serhiy Storchaka5ce3f102014-01-09 14:50:20 +0200303 def test_truncated_zipfile(self):
304 fp = io.BytesIO()
305 with zipfile.ZipFile(fp, mode='w') as zipf:
306 zipf.writestr('strfile', self.data, compress_type=self.compression)
307 end_offset = fp.tell()
308 zipfiledata = fp.getvalue()
309
310 fp = io.BytesIO(zipfiledata)
311 with zipfile.ZipFile(fp) as zipf:
312 with zipf.open('strfile') as zipopen:
313 fp.truncate(end_offset - 20)
314 with self.assertRaises(EOFError):
315 zipopen.read()
316
317 fp = io.BytesIO(zipfiledata)
318 with zipfile.ZipFile(fp) as zipf:
319 with zipf.open('strfile') as zipopen:
320 fp.truncate(end_offset - 20)
321 with self.assertRaises(EOFError):
322 while zipopen.read(100):
323 pass
324
325 fp = io.BytesIO(zipfiledata)
326 with zipfile.ZipFile(fp) as zipf:
327 with zipf.open('strfile') as zipopen:
328 fp.truncate(end_offset - 20)
329 with self.assertRaises(EOFError):
330 while zipopen.read1(100):
331 pass
332
Serhiy Storchaka51a43702014-10-29 22:42:06 +0200333 def test_repr(self):
334 fname = 'file.name'
335 for f in get_files(self):
336 with zipfile.ZipFile(f, 'w', self.compression) as zipfp:
337 zipfp.write(TESTFN, fname)
338 r = repr(zipfp)
339 self.assertIn("mode='w'", r)
340
341 with zipfile.ZipFile(f, 'r') as zipfp:
342 r = repr(zipfp)
343 if isinstance(f, str):
344 self.assertIn('filename=%r' % f, r)
345 else:
346 self.assertIn('file=%r' % f, r)
347 self.assertIn("mode='r'", r)
348 r = repr(zipfp.getinfo(fname))
349 self.assertIn('filename=%r' % fname, r)
350 self.assertIn('filemode=', r)
351 self.assertIn('file_size=', r)
352 if self.compression != zipfile.ZIP_STORED:
353 self.assertIn('compress_type=', r)
354 self.assertIn('compress_size=', r)
355 with zipfp.open(fname) as zipopen:
356 r = repr(zipopen)
357 self.assertIn('name=%r' % fname, r)
358 self.assertIn("mode='r'", r)
359 if self.compression != zipfile.ZIP_STORED:
360 self.assertIn('compress_type=', r)
361 self.assertIn('[closed]', repr(zipopen))
362 self.assertIn('[closed]', repr(zipfp))
363
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300364 def tearDown(self):
365 unlink(TESTFN)
366 unlink(TESTFN2)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200367
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200368
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300369class StoredTestsWithSourceFile(AbstractTestsWithSourceFile,
370 unittest.TestCase):
371 compression = zipfile.ZIP_STORED
372 test_low_compression = None
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200373
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300374 def zip_test_writestr_permissions(self, f, compression):
375 # Make sure that writestr creates files with mode 0600,
376 # when it is passed a name rather than a ZipInfo instance.
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200377
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300378 self.make_test_archive(f, compression)
379 with zipfile.ZipFile(f, "r") as zipfp:
380 zinfo = zipfp.getinfo('strfile')
381 self.assertEqual(zinfo.external_attr, 0o600 << 16)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200382
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300383 def test_writestr_permissions(self):
384 for f in get_files(self):
385 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +0200386
Ezio Melottiafd0d112009-07-15 17:17:17 +0000387 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000388 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
389 zipfp.write(TESTFN, "/absolute")
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000390
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000391 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
392 self.assertEqual(zipfp.namelist(), ["absolute"])
Tim Peters32cbc962006-02-20 21:42:18 +0000393
Ezio Melottiafd0d112009-07-15 17:17:17 +0000394 def test_append_to_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000395 """Test appending to an existing zipfile."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000396 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
397 zipfp.write(TESTFN, TESTFN)
398
399 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
400 zipfp.writestr("strfile", self.data)
401 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000402
Ezio Melottiafd0d112009-07-15 17:17:17 +0000403 def test_append_to_non_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000404 """Test appending to an existing file that is not a zipfile."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000405 # NOTE: this test fails if len(d) < 22 because of the first
406 # line "fpin.seek(-22, 2)" in _EndRecData
Ezio Melotti35386712009-12-31 13:22:41 +0000407 data = b'I am not a ZipFile!'*10
408 with open(TESTFN2, 'wb') as f:
409 f.write(data)
410
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000411 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
412 zipfp.write(TESTFN, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000413
Ezio Melotti35386712009-12-31 13:22:41 +0000414 with open(TESTFN2, 'rb') as f:
415 f.seek(len(data))
416 with zipfile.ZipFile(f, "r") as zipfp:
417 self.assertEqual(zipfp.namelist(), [TESTFN])
Serhiy Storchaka8793b212016-10-07 22:20:50 +0300418 self.assertEqual(zipfp.read(TESTFN), self.data)
419 with open(TESTFN2, 'rb') as f:
420 self.assertEqual(f.read(len(data)), data)
421 zipfiledata = f.read()
422 with io.BytesIO(zipfiledata) as bio, zipfile.ZipFile(bio) as zipfp:
423 self.assertEqual(zipfp.namelist(), [TESTFN])
424 self.assertEqual(zipfp.read(TESTFN), self.data)
425
426 def test_read_concatenated_zip_file(self):
427 with io.BytesIO() as bio:
428 with zipfile.ZipFile(bio, 'w', zipfile.ZIP_STORED) as zipfp:
429 zipfp.write(TESTFN, TESTFN)
430 zipfiledata = bio.getvalue()
431 data = b'I am not a ZipFile!'*10
432 with open(TESTFN2, 'wb') as f:
433 f.write(data)
434 f.write(zipfiledata)
435
436 with zipfile.ZipFile(TESTFN2) as zipfp:
437 self.assertEqual(zipfp.namelist(), [TESTFN])
438 self.assertEqual(zipfp.read(TESTFN), self.data)
439
440 def test_append_to_concatenated_zip_file(self):
441 with io.BytesIO() as bio:
442 with zipfile.ZipFile(bio, 'w', zipfile.ZIP_STORED) as zipfp:
443 zipfp.write(TESTFN, TESTFN)
444 zipfiledata = bio.getvalue()
445 data = b'I am not a ZipFile!'*1000000
446 with open(TESTFN2, 'wb') as f:
447 f.write(data)
448 f.write(zipfiledata)
449
450 with zipfile.ZipFile(TESTFN2, 'a') as zipfp:
451 self.assertEqual(zipfp.namelist(), [TESTFN])
452 zipfp.writestr('strfile', self.data)
453
454 with open(TESTFN2, 'rb') as f:
455 self.assertEqual(f.read(len(data)), data)
456 zipfiledata = f.read()
457 with io.BytesIO(zipfiledata) as bio, zipfile.ZipFile(bio) as zipfp:
458 self.assertEqual(zipfp.namelist(), [TESTFN, 'strfile'])
459 self.assertEqual(zipfp.read(TESTFN), self.data)
460 self.assertEqual(zipfp.read('strfile'), self.data)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000461
R David Murray4fbb9db2011-06-09 15:50:51 -0400462 def test_ignores_newline_at_end(self):
463 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
464 zipfp.write(TESTFN, TESTFN)
465 with open(TESTFN2, 'a') as f:
466 f.write("\r\n\00\00\00")
467 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
468 self.assertIsInstance(zipfp, zipfile.ZipFile)
469
470 def test_ignores_stuff_appended_past_comments(self):
471 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
472 zipfp.comment = b"this is a comment"
473 zipfp.write(TESTFN, TESTFN)
474 with open(TESTFN2, 'a') as f:
475 f.write("abcdef\r\n")
476 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
477 self.assertIsInstance(zipfp, zipfile.ZipFile)
478 self.assertEqual(zipfp.comment, b"this is a comment")
479
Ezio Melottiafd0d112009-07-15 17:17:17 +0000480 def test_write_default_name(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000481 """Check that calling ZipFile.write without arcname specified
482 produces the expected result."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000483 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
484 zipfp.write(TESTFN)
Brian Curtin8fb9b862010-11-18 02:15:28 +0000485 with open(TESTFN, "rb") as f:
486 self.assertEqual(zipfp.read(TESTFN), f.read())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000487
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300488 def test_write_to_readonly(self):
489 """Check that trying to call write() on a readonly ZipFile object
490 raises a RuntimeError."""
491 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
492 zipfp.writestr("somefile.txt", "bogus")
493
494 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
495 self.assertRaises(RuntimeError, zipfp.write, TESTFN)
496
497 def test_add_file_before_1980(self):
498 # Set atime and mtime to 1970-01-01
499 os.utime(TESTFN, (0, 0))
500 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
501 self.assertRaises(ValueError, zipfp.write, TESTFN)
502
Serhiy Storchaka5ce3f102014-01-09 14:50:20 +0200503
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300504@requires_zlib
505class DeflateTestsWithSourceFile(AbstractTestsWithSourceFile,
506 unittest.TestCase):
507 compression = zipfile.ZIP_DEFLATED
508
Ezio Melottiafd0d112009-07-15 17:17:17 +0000509 def test_per_file_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000510 """Check that files within a Zip archive can have different
511 compression options."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000512 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
513 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
514 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
515 sinfo = zipfp.getinfo('storeme')
516 dinfo = zipfp.getinfo('deflateme')
517 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
518 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000519
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300520@requires_bz2
521class Bzip2TestsWithSourceFile(AbstractTestsWithSourceFile,
522 unittest.TestCase):
523 compression = zipfile.ZIP_BZIP2
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000524
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300525@requires_lzma
526class LzmaTestsWithSourceFile(AbstractTestsWithSourceFile,
527 unittest.TestCase):
528 compression = zipfile.ZIP_LZMA
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000529
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300530
531class AbstractTestZip64InSmallFiles:
532 # These tests test the ZIP64 functionality without using large files,
533 # see test_zipfile64 for proper tests.
534
535 @classmethod
536 def setUpClass(cls):
537 line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
538 for i in range(0, FIXEDTEST_SIZE))
539 cls.data = b'\n'.join(line_gen)
540
541 def setUp(self):
542 self._limit = zipfile.ZIP64_LIMIT
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300543 self._filecount_limit = zipfile.ZIP_FILECOUNT_LIMIT
544 zipfile.ZIP64_LIMIT = 1000
545 zipfile.ZIP_FILECOUNT_LIMIT = 9
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300546
547 # Make a source file with some lines
548 with open(TESTFN, "wb") as fp:
549 fp.write(self.data)
550
551 def zip_test(self, f, compression):
552 # Create the ZIP archive
553 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
554 zipfp.write(TESTFN, "another.name")
555 zipfp.write(TESTFN, TESTFN)
556 zipfp.writestr("strfile", self.data)
557
558 # Read the ZIP archive
559 with zipfile.ZipFile(f, "r", compression) as zipfp:
560 self.assertEqual(zipfp.read(TESTFN), self.data)
561 self.assertEqual(zipfp.read("another.name"), self.data)
562 self.assertEqual(zipfp.read("strfile"), self.data)
563
564 # Print the ZIP directory
565 fp = io.StringIO()
566 zipfp.printdir(fp)
567
568 directory = fp.getvalue()
569 lines = directory.splitlines()
570 self.assertEqual(len(lines), 4) # Number of files + header
571
572 self.assertIn('File Name', lines[0])
573 self.assertIn('Modified', lines[0])
574 self.assertIn('Size', lines[0])
575
576 fn, date, time_, size = lines[1].split()
577 self.assertEqual(fn, 'another.name')
578 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
579 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
580 self.assertEqual(size, str(len(self.data)))
581
582 # Check the namelist
583 names = zipfp.namelist()
584 self.assertEqual(len(names), 3)
585 self.assertIn(TESTFN, names)
586 self.assertIn("another.name", names)
587 self.assertIn("strfile", names)
588
589 # Check infolist
590 infos = zipfp.infolist()
591 names = [i.filename for i in infos]
592 self.assertEqual(len(names), 3)
593 self.assertIn(TESTFN, names)
594 self.assertIn("another.name", names)
595 self.assertIn("strfile", names)
596 for i in infos:
597 self.assertEqual(i.file_size, len(self.data))
598
599 # check getinfo
600 for nm in (TESTFN, "another.name", "strfile"):
601 info = zipfp.getinfo(nm)
602 self.assertEqual(info.filename, nm)
603 self.assertEqual(info.file_size, len(self.data))
604
605 # Check that testzip doesn't raise an exception
606 zipfp.testzip()
607
608 def test_basic(self):
609 for f in get_files(self):
610 self.zip_test(f, self.compression)
611
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300612 def test_too_many_files(self):
613 # This test checks that more than 64k files can be added to an archive,
614 # and that the resulting archive can be read properly by ZipFile
615 zipf = zipfile.ZipFile(TESTFN, "w", self.compression,
616 allowZip64=True)
617 zipf.debug = 100
618 numfiles = 15
619 for i in range(numfiles):
620 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
621 self.assertEqual(len(zipf.namelist()), numfiles)
622 zipf.close()
623
624 zipf2 = zipfile.ZipFile(TESTFN, "r", self.compression)
625 self.assertEqual(len(zipf2.namelist()), numfiles)
626 for i in range(numfiles):
627 content = zipf2.read("foo%08d" % i).decode('ascii')
628 self.assertEqual(content, "%d" % (i**3 % 57))
629 zipf2.close()
630
631 def test_too_many_files_append(self):
632 zipf = zipfile.ZipFile(TESTFN, "w", self.compression,
633 allowZip64=False)
634 zipf.debug = 100
635 numfiles = 9
636 for i in range(numfiles):
637 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
638 self.assertEqual(len(zipf.namelist()), numfiles)
639 with self.assertRaises(zipfile.LargeZipFile):
640 zipf.writestr("foo%08d" % numfiles, b'')
641 self.assertEqual(len(zipf.namelist()), numfiles)
642 zipf.close()
643
644 zipf = zipfile.ZipFile(TESTFN, "a", self.compression,
645 allowZip64=False)
646 zipf.debug = 100
647 self.assertEqual(len(zipf.namelist()), numfiles)
648 with self.assertRaises(zipfile.LargeZipFile):
649 zipf.writestr("foo%08d" % numfiles, b'')
650 self.assertEqual(len(zipf.namelist()), numfiles)
651 zipf.close()
652
653 zipf = zipfile.ZipFile(TESTFN, "a", self.compression,
654 allowZip64=True)
655 zipf.debug = 100
656 self.assertEqual(len(zipf.namelist()), numfiles)
657 numfiles2 = 15
658 for i in range(numfiles, numfiles2):
659 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
660 self.assertEqual(len(zipf.namelist()), numfiles2)
661 zipf.close()
662
663 zipf2 = zipfile.ZipFile(TESTFN, "r", self.compression)
664 self.assertEqual(len(zipf2.namelist()), numfiles2)
665 for i in range(numfiles2):
666 content = zipf2.read("foo%08d" % i).decode('ascii')
667 self.assertEqual(content, "%d" % (i**3 % 57))
668 zipf2.close()
669
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300670 def tearDown(self):
671 zipfile.ZIP64_LIMIT = self._limit
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300672 zipfile.ZIP_FILECOUNT_LIMIT = self._filecount_limit
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300673 unlink(TESTFN)
674 unlink(TESTFN2)
675
676
677class StoredTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
678 unittest.TestCase):
679 compression = zipfile.ZIP_STORED
680
681 def large_file_exception_test(self, f, compression):
Serhiy Storchaka235c5e02013-11-23 15:55:38 +0200682 with zipfile.ZipFile(f, "w", compression, allowZip64=False) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300683 self.assertRaises(zipfile.LargeZipFile,
684 zipfp.write, TESTFN, "another.name")
685
686 def large_file_exception_test2(self, f, compression):
Serhiy Storchaka235c5e02013-11-23 15:55:38 +0200687 with zipfile.ZipFile(f, "w", compression, allowZip64=False) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300688 self.assertRaises(zipfile.LargeZipFile,
689 zipfp.writestr, "another.name", self.data)
690
691 def test_large_file_exception(self):
692 for f in get_files(self):
693 self.large_file_exception_test(f, zipfile.ZIP_STORED)
694 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
695
696 def test_absolute_arcnames(self):
697 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
698 allowZip64=True) as zipfp:
699 zipfp.write(TESTFN, "/absolute")
700
701 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
702 self.assertEqual(zipfp.namelist(), ["absolute"])
703
704@requires_zlib
705class DeflateTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
706 unittest.TestCase):
707 compression = zipfile.ZIP_DEFLATED
708
709@requires_bz2
710class Bzip2TestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
711 unittest.TestCase):
712 compression = zipfile.ZIP_BZIP2
713
714@requires_lzma
715class LzmaTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
716 unittest.TestCase):
717 compression = zipfile.ZIP_LZMA
718
719
720class PyZipFileTests(unittest.TestCase):
721 def assertCompiledIn(self, name, namelist):
722 if name + 'o' not in namelist:
723 self.assertIn(name + 'c', namelist)
724
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200725 def requiresWriteAccess(self, path):
Berker Peksage1efc072015-02-16 04:36:18 +0200726 # effective_ids unavailable on windows
727 if not os.access(path, os.W_OK,
728 effective_ids=os.access in os.supports_effective_ids):
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200729 self.skipTest('requires write access to the installed location')
Serhiy Storchakad86a6ef2015-09-19 10:55:20 +0300730 filename = os.path.join(path, 'test_zipfile.try')
731 try:
732 fd = os.open(filename, os.O_WRONLY | os.O_CREAT)
733 os.close(fd)
734 except Exception:
735 self.skipTest('requires write access to the installed location')
736 unlink(filename)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200737
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300738 def test_write_pyfile(self):
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200739 self.requiresWriteAccess(os.path.dirname(__file__))
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300740 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
741 fn = __file__
Brett Cannonf299abd2015-04-13 14:21:02 -0400742 if fn.endswith('.pyc'):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300743 path_split = fn.split(os.sep)
744 if os.altsep is not None:
745 path_split.extend(fn.split(os.altsep))
746 if '__pycache__' in path_split:
Serhiy Storchaka9068e4d2013-07-22 21:02:14 +0300747 fn = importlib.util.source_from_cache(fn)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300748 else:
749 fn = fn[:-1]
750
751 zipfp.writepy(fn)
752
753 bn = os.path.basename(fn)
754 self.assertNotIn(bn, zipfp.namelist())
755 self.assertCompiledIn(bn, zipfp.namelist())
756
757 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
758 fn = __file__
Brett Cannonf299abd2015-04-13 14:21:02 -0400759 if fn.endswith('.pyc'):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300760 fn = fn[:-1]
761
762 zipfp.writepy(fn, "testpackage")
763
764 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
765 self.assertNotIn(bn, zipfp.namelist())
766 self.assertCompiledIn(bn, zipfp.namelist())
767
768 def test_write_python_package(self):
769 import email
770 packagedir = os.path.dirname(email.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200771 self.requiresWriteAccess(packagedir)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300772
773 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
774 zipfp.writepy(packagedir)
775
776 # Check for a couple of modules at different levels of the
777 # hierarchy
778 names = zipfp.namelist()
779 self.assertCompiledIn('email/__init__.py', names)
780 self.assertCompiledIn('email/mime/text.py', names)
781
Christian Tismer59202e52013-10-21 03:59:23 +0200782 def test_write_filtered_python_package(self):
783 import test
784 packagedir = os.path.dirname(test.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200785 self.requiresWriteAccess(packagedir)
Christian Tismer59202e52013-10-21 03:59:23 +0200786
787 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
788
Christian Tismer59202e52013-10-21 03:59:23 +0200789 # first make sure that the test folder gives error messages
Georg Brandla6065422013-10-21 08:29:29 +0200790 # (on the badsyntax_... files)
791 with captured_stdout() as reportSIO:
792 zipfp.writepy(packagedir)
Christian Tismer59202e52013-10-21 03:59:23 +0200793 reportStr = reportSIO.getvalue()
794 self.assertTrue('SyntaxError' in reportStr)
795
Christian Tismer410d9312013-10-22 04:09:28 +0200796 # then check that the filter works on the whole package
Georg Brandla6065422013-10-21 08:29:29 +0200797 with captured_stdout() as reportSIO:
798 zipfp.writepy(packagedir, filterfunc=lambda whatever: False)
Christian Tismer59202e52013-10-21 03:59:23 +0200799 reportStr = reportSIO.getvalue()
800 self.assertTrue('SyntaxError' not in reportStr)
801
Christian Tismer410d9312013-10-22 04:09:28 +0200802 # then check that the filter works on individual files
Larry Hastings7e63b362015-05-08 06:54:58 -0700803 def filter(path):
804 return not os.path.basename(path).startswith("bad")
Serhiy Storchakac46d1fa2014-01-20 21:59:33 +0200805 with captured_stdout() as reportSIO, self.assertWarns(UserWarning):
Larry Hastings7e63b362015-05-08 06:54:58 -0700806 zipfp.writepy(packagedir, filterfunc=filter)
Christian Tismer410d9312013-10-22 04:09:28 +0200807 reportStr = reportSIO.getvalue()
808 if reportStr:
809 print(reportStr)
810 self.assertTrue('SyntaxError' not in reportStr)
811
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300812 def test_write_with_optimization(self):
813 import email
814 packagedir = os.path.dirname(email.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200815 self.requiresWriteAccess(packagedir)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300816 optlevel = 1 if __debug__ else 0
Brett Cannonf299abd2015-04-13 14:21:02 -0400817 ext = '.pyc'
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300818
819 with TemporaryFile() as t, \
Christian Tismer59202e52013-10-21 03:59:23 +0200820 zipfile.PyZipFile(t, "w", optimize=optlevel) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300821 zipfp.writepy(packagedir)
822
823 names = zipfp.namelist()
824 self.assertIn('email/__init__' + ext, names)
825 self.assertIn('email/mime/text' + ext, names)
826
827 def test_write_python_directory(self):
828 os.mkdir(TESTFN2)
829 try:
830 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
831 fp.write("print(42)\n")
832
833 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
834 fp.write("print(42 * 42)\n")
835
836 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
837 fp.write("bla bla bla\n")
838
839 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
840 zipfp.writepy(TESTFN2)
841
842 names = zipfp.namelist()
843 self.assertCompiledIn('mod1.py', names)
844 self.assertCompiledIn('mod2.py', names)
845 self.assertNotIn('mod2.txt', names)
846
847 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200848 rmtree(TESTFN2)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300849
Christian Tismer410d9312013-10-22 04:09:28 +0200850 def test_write_python_directory_filtered(self):
851 os.mkdir(TESTFN2)
852 try:
853 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
854 fp.write("print(42)\n")
855
856 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
857 fp.write("print(42 * 42)\n")
858
859 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
860 zipfp.writepy(TESTFN2, filterfunc=lambda fn:
861 not fn.endswith('mod2.py'))
862
863 names = zipfp.namelist()
864 self.assertCompiledIn('mod1.py', names)
865 self.assertNotIn('mod2.py', names)
866
867 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200868 rmtree(TESTFN2)
Christian Tismer410d9312013-10-22 04:09:28 +0200869
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300870 def test_write_non_pyfile(self):
871 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
872 with open(TESTFN, 'w') as f:
873 f.write('most definitely not a python file')
874 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
Victor Stinner88b215e2014-09-04 00:51:09 +0200875 unlink(TESTFN)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300876
877 def test_write_pyfile_bad_syntax(self):
878 os.mkdir(TESTFN2)
879 try:
880 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
881 fp.write("Bad syntax in python file\n")
882
883 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
884 # syntax errors are printed to stdout
885 with captured_stdout() as s:
886 zipfp.writepy(os.path.join(TESTFN2, "mod1.py"))
887
888 self.assertIn("SyntaxError", s.getvalue())
889
890 # as it will not have compiled the python file, it will
Brett Cannonf299abd2015-04-13 14:21:02 -0400891 # include the .py file not .pyc
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300892 names = zipfp.namelist()
893 self.assertIn('mod1.py', names)
894 self.assertNotIn('mod1.pyc', names)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300895
896 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200897 rmtree(TESTFN2)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300898
899
900class ExtractTests(unittest.TestCase):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000901 def test_extract(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000902 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
903 for fpath, fdata in SMALL_TEST_DATA:
904 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000905
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000906 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
907 for fpath, fdata in SMALL_TEST_DATA:
908 writtenfile = zipfp.extract(fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000909
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000910 # make sure it was written to the right place
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800911 correctfile = os.path.join(os.getcwd(), fpath)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000912 correctfile = os.path.normpath(correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000913
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000914 self.assertEqual(writtenfile, correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000915
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000916 # make sure correct data is in correct file
Brian Curtin8fb9b862010-11-18 02:15:28 +0000917 with open(writtenfile, "rb") as f:
918 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000919
Victor Stinner88b215e2014-09-04 00:51:09 +0200920 unlink(writtenfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000921
922 # remove the test file subdirectories
Victor Stinner57004c62014-09-04 00:49:01 +0200923 rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
Christian Heimes790c8232008-01-07 21:14:23 +0000924
Ezio Melottiafd0d112009-07-15 17:17:17 +0000925 def test_extract_all(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000926 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
927 for fpath, fdata in SMALL_TEST_DATA:
928 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000929
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000930 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
931 zipfp.extractall()
932 for fpath, fdata in SMALL_TEST_DATA:
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800933 outfile = os.path.join(os.getcwd(), fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000934
Brian Curtin8fb9b862010-11-18 02:15:28 +0000935 with open(outfile, "rb") as f:
936 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000937
Victor Stinner88b215e2014-09-04 00:51:09 +0200938 unlink(outfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000939
940 # remove the test file subdirectories
Victor Stinner57004c62014-09-04 00:49:01 +0200941 rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
Christian Heimes790c8232008-01-07 21:14:23 +0000942
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800943 def check_file(self, filename, content):
944 self.assertTrue(os.path.isfile(filename))
945 with open(filename, 'rb') as f:
946 self.assertEqual(f.read(), content)
947
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800948 def test_sanitize_windows_name(self):
949 san = zipfile.ZipFile._sanitize_windows_name
950 # Passing pathsep in allows this test to work regardless of platform.
951 self.assertEqual(san(r',,?,C:,foo,bar/z', ','), r'_,C_,foo,bar/z')
952 self.assertEqual(san(r'a\b,c<d>e|f"g?h*i', ','), r'a\b,c_d_e_f_g_h_i')
953 self.assertEqual(san('../../foo../../ba..r', '/'), r'foo/ba..r')
954
955 def test_extract_hackers_arcnames_common_cases(self):
956 common_hacknames = [
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800957 ('../foo/bar', 'foo/bar'),
958 ('foo/../bar', 'foo/bar'),
959 ('foo/../../bar', 'foo/bar'),
960 ('foo/bar/..', 'foo/bar'),
961 ('./../foo/bar', 'foo/bar'),
962 ('/foo/bar', 'foo/bar'),
963 ('/foo/../bar', 'foo/bar'),
964 ('/foo/../../bar', 'foo/bar'),
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800965 ]
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800966 self._test_extract_hackers_arcnames(common_hacknames)
967
968 @unittest.skipIf(os.path.sep != '\\', 'Requires \\ as path separator.')
969 def test_extract_hackers_arcnames_windows_only(self):
970 """Test combination of path fixing and windows name sanitization."""
971 windows_hacknames = [
Christian Tismer59202e52013-10-21 03:59:23 +0200972 (r'..\foo\bar', 'foo/bar'),
973 (r'..\/foo\/bar', 'foo/bar'),
974 (r'foo/\..\/bar', 'foo/bar'),
975 (r'foo\/../\bar', 'foo/bar'),
976 (r'C:foo/bar', 'foo/bar'),
977 (r'C:/foo/bar', 'foo/bar'),
978 (r'C://foo/bar', 'foo/bar'),
979 (r'C:\foo\bar', 'foo/bar'),
980 (r'//conky/mountpoint/foo/bar', 'foo/bar'),
981 (r'\\conky\mountpoint\foo\bar', 'foo/bar'),
982 (r'///conky/mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
983 (r'\\\conky\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
984 (r'//conky//mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
985 (r'\\conky\\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
986 (r'//?/C:/foo/bar', 'foo/bar'),
987 (r'\\?\C:\foo\bar', 'foo/bar'),
988 (r'C:/../C:/foo/bar', 'C_/foo/bar'),
989 (r'a:b\c<d>e|f"g?h*i', 'b/c_d_e_f_g_h_i'),
990 ('../../foo../../ba..r', 'foo/ba..r'),
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800991 ]
992 self._test_extract_hackers_arcnames(windows_hacknames)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800993
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800994 @unittest.skipIf(os.path.sep != '/', r'Requires / as path separator.')
995 def test_extract_hackers_arcnames_posix_only(self):
996 posix_hacknames = [
997 ('//foo/bar', 'foo/bar'),
998 ('../../foo../../ba..r', 'foo../ba..r'),
999 (r'foo/..\bar', r'foo/..\bar'),
1000 ]
1001 self._test_extract_hackers_arcnames(posix_hacknames)
1002
1003 def _test_extract_hackers_arcnames(self, hacknames):
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001004 for arcname, fixedname in hacknames:
1005 content = b'foobar' + arcname.encode()
1006 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipfp:
Serhiy Storchakae5e64442013-02-02 19:50:59 +02001007 zinfo = zipfile.ZipInfo()
1008 # preserve backslashes
1009 zinfo.filename = arcname
1010 zinfo.external_attr = 0o600 << 16
1011 zipfp.writestr(zinfo, content)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001012
Serhiy Storchakae5e64442013-02-02 19:50:59 +02001013 arcname = arcname.replace(os.sep, "/")
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001014 targetpath = os.path.join('target', 'subdir', 'subsub')
1015 correctfile = os.path.join(targetpath, *fixedname.split('/'))
1016
1017 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1018 writtenfile = zipfp.extract(arcname, targetpath)
Serhiy Storchakae5e64442013-02-02 19:50:59 +02001019 self.assertEqual(writtenfile, correctfile,
Gregory P. Smith09aa7522013-02-03 00:36:32 -08001020 msg='extract %r: %r != %r' %
1021 (arcname, writtenfile, correctfile))
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001022 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001023 rmtree('target')
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001024
1025 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1026 zipfp.extractall(targetpath)
1027 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001028 rmtree('target')
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001029
1030 correctfile = os.path.join(os.getcwd(), *fixedname.split('/'))
1031
1032 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1033 writtenfile = zipfp.extract(arcname)
Serhiy Storchakae5e64442013-02-02 19:50:59 +02001034 self.assertEqual(writtenfile, correctfile,
1035 msg="extract %r" % arcname)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001036 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001037 rmtree(fixedname.split('/')[0])
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001038
1039 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
1040 zipfp.extractall()
1041 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001042 rmtree(fixedname.split('/')[0])
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001043
Victor Stinner88b215e2014-09-04 00:51:09 +02001044 unlink(TESTFN2)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001045
Ronald Oussorenee5c8852010-02-07 20:24:02 +00001046
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001047class OtherTests(unittest.TestCase):
1048 def test_open_via_zip_info(self):
1049 # Create the ZIP archive
1050 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
1051 zipfp.writestr("name", "foo")
Serhiy Storchaka9b7a1a12014-01-20 21:57:40 +02001052 with self.assertWarns(UserWarning):
1053 zipfp.writestr("name", "bar")
1054 self.assertEqual(zipfp.namelist(), ["name"] * 2)
Ronald Oussorenee5c8852010-02-07 20:24:02 +00001055
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001056 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1057 infos = zipfp.infolist()
1058 data = b""
1059 for info in infos:
1060 with zipfp.open(info) as zipopen:
1061 data += zipopen.read()
1062 self.assertIn(data, {b"foobar", b"barfoo"})
1063 data = b""
1064 for info in infos:
1065 data += zipfp.read(info)
1066 self.assertIn(data, {b"foobar", b"barfoo"})
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001067
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02001068 def test_universal_deprecation(self):
1069 f = io.BytesIO()
1070 with zipfile.ZipFile(f, "w") as zipfp:
1071 zipfp.writestr('spam.txt', b'ababagalamaga')
1072
1073 with zipfile.ZipFile(f, "r") as zipfp:
1074 for mode in 'U', 'rU':
1075 with self.assertWarns(DeprecationWarning):
1076 zipopen = zipfp.open('spam.txt', mode)
1077 zipopen.close()
1078
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001079 def test_universal_readaheads(self):
1080 f = io.BytesIO()
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001081
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001082 data = b'a\r\n' * 16 * 1024
1083 with zipfile.ZipFile(f, 'w', zipfile.ZIP_STORED) as zipfp:
1084 zipfp.writestr(TESTFN, data)
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +00001085
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001086 data2 = b''
1087 with zipfile.ZipFile(f, 'r') as zipfp, \
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02001088 openU(zipfp, TESTFN) as zipopen:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001089 for line in zipopen:
1090 data2 += line
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +00001091
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001092 self.assertEqual(data, data2.replace(b'\n', b'\r\n'))
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +00001093
Gregory P. Smithb0d9ca922009-07-07 05:06:04 +00001094 def test_writestr_extended_local_header_issue1202(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001095 with zipfile.ZipFile(TESTFN2, 'w') as orig_zip:
1096 for data in 'abcdefghijklmnop':
1097 zinfo = zipfile.ZipInfo(data)
1098 zinfo.flag_bits |= 0x08 # Include an extended local header.
1099 orig_zip.writestr(zinfo, data)
1100
1101 def test_close(self):
1102 """Check that the zipfile is closed after the 'with' block."""
1103 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
1104 for fpath, fdata in SMALL_TEST_DATA:
1105 zipfp.writestr(fpath, fdata)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001106 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
1107 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001108
1109 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001110 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
1111 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001112
1113 def test_close_on_exception(self):
1114 """Check that the zipfile is closed if an exception is raised in the
1115 'with' block."""
1116 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
1117 for fpath, fdata in SMALL_TEST_DATA:
1118 zipfp.writestr(fpath, fdata)
1119
1120 try:
1121 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
Georg Brandl4d540882010-10-28 06:42:33 +00001122 raise zipfile.BadZipFile()
1123 except zipfile.BadZipFile:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001124 self.assertIsNone(zipfp2.fp, 'zipfp is not closed')
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001125
Martin v. Löwisd099b562012-05-01 14:08:22 +02001126 def test_unsupported_version(self):
1127 # File has an extract_version of 120
1128 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 +02001129 b'\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00xPK\x01\x02x\x03x\x00\x00\x00\x00'
1130 b'\x00!p\xa1@\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00'
1131 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00\x00xPK\x05\x06'
1132 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 +03001133
Martin v. Löwisd099b562012-05-01 14:08:22 +02001134 self.assertRaises(NotImplementedError, zipfile.ZipFile,
1135 io.BytesIO(data), 'r')
1136
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001137 @requires_zlib
1138 def test_read_unicode_filenames(self):
1139 # bug #10801
1140 fname = findfile('zip_cp437_header.zip')
1141 with zipfile.ZipFile(fname) as zipfp:
1142 for name in zipfp.namelist():
1143 zipfp.open(name).close()
1144
1145 def test_write_unicode_filenames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001146 with zipfile.ZipFile(TESTFN, "w") as zf:
1147 zf.writestr("foo.txt", "Test for unicode filename")
1148 zf.writestr("\xf6.txt", "Test for unicode filename")
Ezio Melottie9615932010-01-24 19:26:24 +00001149 self.assertIsInstance(zf.infolist()[0].filename, str)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001150
1151 with zipfile.ZipFile(TESTFN, "r") as zf:
1152 self.assertEqual(zf.filelist[0].filename, "foo.txt")
1153 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
Martin v. Löwis8570f6a2008-05-05 17:44:38 +00001154
Serhiy Storchaka764fc9b2015-03-25 10:09:41 +02001155 def test_exclusive_create_zip_file(self):
1156 """Test exclusive creating a new zipfile."""
1157 unlink(TESTFN2)
1158 filename = 'testfile.txt'
1159 content = b'hello, world. this is some content.'
1160 with zipfile.ZipFile(TESTFN2, "x", zipfile.ZIP_STORED) as zipfp:
1161 zipfp.writestr(filename, content)
1162 with self.assertRaises(FileExistsError):
1163 zipfile.ZipFile(TESTFN2, "x", zipfile.ZIP_STORED)
1164 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1165 self.assertEqual(zipfp.namelist(), [filename])
1166 self.assertEqual(zipfp.read(filename), content)
1167
Ezio Melottiafd0d112009-07-15 17:17:17 +00001168 def test_create_non_existent_file_for_append(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001169 if os.path.exists(TESTFN):
1170 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001171
Thomas Wouterscf297e42007-02-23 15:07:44 +00001172 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001173 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +00001174
Thomas Wouterscf297e42007-02-23 15:07:44 +00001175 try:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001176 with zipfile.ZipFile(TESTFN, 'a') as zf:
1177 zf.writestr(filename, content)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001178 except OSError:
Thomas Wouterscf297e42007-02-23 15:07:44 +00001179 self.fail('Could not append data to a non-existent zip file.')
1180
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001181 self.assertTrue(os.path.exists(TESTFN))
Thomas Wouterscf297e42007-02-23 15:07:44 +00001182
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001183 with zipfile.ZipFile(TESTFN, 'r') as zf:
1184 self.assertEqual(zf.read(filename), content)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001185
Ezio Melottiafd0d112009-07-15 17:17:17 +00001186 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001187 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti35386712009-12-31 13:22:41 +00001188 # it opens if there's an error in the file. If it doesn't, the
1189 # traceback holds a reference to the ZipFile object and, indirectly,
1190 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001191 # On Windows, this causes the os.unlink() call to fail because the
1192 # underlying file is still open. This is SF bug #412214.
1193 #
Ezio Melotti35386712009-12-31 13:22:41 +00001194 with open(TESTFN, "w") as fp:
1195 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001196 try:
1197 zf = zipfile.ZipFile(TESTFN)
Georg Brandl4d540882010-10-28 06:42:33 +00001198 except zipfile.BadZipFile:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001199 pass
1200
Ezio Melottiafd0d112009-07-15 17:17:17 +00001201 def test_is_zip_erroneous_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001202 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001203 # - passing a filename
1204 with open(TESTFN, "w") as fp:
1205 fp.write("this is not a legal zip file\n")
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001206 self.assertFalse(zipfile.is_zipfile(TESTFN))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001207 # - passing a file object
1208 with open(TESTFN, "rb") as fp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001209 self.assertFalse(zipfile.is_zipfile(fp))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001210 # - passing a file-like object
1211 fp = io.BytesIO()
1212 fp.write(b"this is not a legal zip file\n")
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001213 self.assertFalse(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001214 fp.seek(0, 0)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001215 self.assertFalse(zipfile.is_zipfile(fp))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001216
Serhiy Storchakad2b15272013-01-31 15:27:07 +02001217 def test_damaged_zipfile(self):
1218 """Check that zipfiles with missing bytes at the end raise BadZipFile."""
1219 # - Create a valid zip file
1220 fp = io.BytesIO()
1221 with zipfile.ZipFile(fp, mode="w") as zipf:
1222 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
1223 zipfiledata = fp.getvalue()
1224
1225 # - Now create copies of it missing the last N bytes and make sure
1226 # a BadZipFile exception is raised when we try to open it
1227 for N in range(len(zipfiledata)):
1228 fp = io.BytesIO(zipfiledata[:N])
1229 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, fp)
1230
Ezio Melottiafd0d112009-07-15 17:17:17 +00001231 def test_is_zip_valid_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001232 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001233 # - passing a filename
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001234 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1235 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
1236
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001237 self.assertTrue(zipfile.is_zipfile(TESTFN))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001238 # - passing a file object
1239 with open(TESTFN, "rb") as fp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001240 self.assertTrue(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001241 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001242 zip_contents = fp.read()
1243 # - passing a file-like object
1244 fp = io.BytesIO()
1245 fp.write(zip_contents)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001246 self.assertTrue(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001247 fp.seek(0, 0)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001248 self.assertTrue(zipfile.is_zipfile(fp))
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001249
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001250 def test_non_existent_file_raises_OSError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001251 # make sure we don't raise an AttributeError when a partially-constructed
1252 # ZipFile instance is finalized; this tests for regression on SF tracker
1253 # bug #403871.
1254
1255 # The bug we're testing for caused an AttributeError to be raised
1256 # when a ZipFile instance was created for a file that did not
1257 # exist; the .fp member was not initialized but was needed by the
1258 # __del__() method. Since the AttributeError is in the __del__(),
1259 # it is ignored, but the user should be sufficiently annoyed by
1260 # the message on the output that regression will be noticed
1261 # quickly.
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001262 self.assertRaises(OSError, zipfile.ZipFile, TESTFN)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001263
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001264 def test_empty_file_raises_BadZipFile(self):
1265 f = open(TESTFN, 'w')
1266 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001267 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001268
Ezio Melotti35386712009-12-31 13:22:41 +00001269 with open(TESTFN, 'w') as fp:
1270 fp.write("short file")
Georg Brandl4d540882010-10-28 06:42:33 +00001271 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001272
Ezio Melottiafd0d112009-07-15 17:17:17 +00001273 def test_closed_zip_raises_RuntimeError(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001274 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001275 data = io.BytesIO()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001276 with zipfile.ZipFile(data, mode="w") as zipf:
1277 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001278
Andrew Svetlov737fb892012-12-18 21:14:22 +02001279 # This is correct; calling .read on a closed ZipFile should raise
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001280 # a RuntimeError, and so should calling .testzip. An earlier
1281 # version of .testzip would swallow this exception (and any other)
1282 # and report that the first file in the archive was corrupt.
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001283 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
1284 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001285 self.assertRaises(RuntimeError, zipf.testzip)
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001286 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Brian Curtin8fb9b862010-11-18 02:15:28 +00001287 with open(TESTFN, 'w') as f:
1288 f.write('zipfile test data')
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001289 self.assertRaises(RuntimeError, zipf.write, TESTFN)
1290
Ezio Melottiafd0d112009-07-15 17:17:17 +00001291 def test_bad_constructor_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001292 """Check that bad modes passed to ZipFile constructor are caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001293 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
1294
Ezio Melottiafd0d112009-07-15 17:17:17 +00001295 def test_bad_open_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001296 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001297 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1298 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1299
1300 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001301 # read the data to make sure the file is there
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001302 zipf.read("foo.txt")
1303 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001304
Ezio Melottiafd0d112009-07-15 17:17:17 +00001305 def test_read0(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001306 """Check that calling read(0) on a ZipExtFile object returns an empty
1307 string and doesn't advance file pointer."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001308 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1309 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1310 # read the data to make sure the file is there
Brian Curtin8fb9b862010-11-18 02:15:28 +00001311 with zipf.open("foo.txt") as f:
1312 for i in range(FIXEDTEST_SIZE):
1313 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001314
Brian Curtin8fb9b862010-11-18 02:15:28 +00001315 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001316
Ezio Melottiafd0d112009-07-15 17:17:17 +00001317 def test_open_non_existent_item(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001318 """Check that attempting to call open() for an item that doesn't
1319 exist in the archive raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001320 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1321 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001322
Ezio Melottiafd0d112009-07-15 17:17:17 +00001323 def test_bad_compression_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001324 """Check that bad compression methods passed to ZipFile.open are
1325 caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001326 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
1327
Martin v. Löwisb3260f02012-05-01 08:38:01 +02001328 def test_unsupported_compression(self):
1329 # data is declared as shrunk, but actually deflated
1330 data = (b'PK\x03\x04.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00'
Christian Tismer59202e52013-10-21 03:59:23 +02001331 b'\x00\x02\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00x\x03\x00PK\x01'
1332 b'\x02.\x03.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00\x00\x02\x00\x00'
1333 b'\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
1334 b'\x80\x01\x00\x00\x00\x00xPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00'
1335 b'/\x00\x00\x00!\x00\x00\x00\x00\x00')
Martin v. Löwisb3260f02012-05-01 08:38:01 +02001336 with zipfile.ZipFile(io.BytesIO(data), 'r') as zipf:
1337 self.assertRaises(NotImplementedError, zipf.open, 'x')
1338
Ezio Melottiafd0d112009-07-15 17:17:17 +00001339 def test_null_byte_in_filename(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001340 """Check that a filename containing a null byte is properly
1341 terminated."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001342 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1343 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
1344 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001345
Ezio Melottiafd0d112009-07-15 17:17:17 +00001346 def test_struct_sizes(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001347 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001348 self.assertEqual(zipfile.sizeEndCentDir, 22)
1349 self.assertEqual(zipfile.sizeCentralDir, 46)
1350 self.assertEqual(zipfile.sizeEndCentDir64, 56)
1351 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
1352
Ezio Melottiafd0d112009-07-15 17:17:17 +00001353 def test_comments(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001354 """Check that comments on the archive are handled properly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001355
1356 # check default comment is empty
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001357 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1358 self.assertEqual(zipf.comment, b'')
1359 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1360
1361 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1362 self.assertEqual(zipfr.comment, b'')
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001363
1364 # check a simple short comment
1365 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001366 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1367 zipf.comment = comment
1368 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1369 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1370 self.assertEqual(zipf.comment, comment)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001371
1372 # check a comment of max length
1373 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
1374 comment2 = comment2.encode("ascii")
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001375 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1376 zipf.comment = comment2
1377 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1378
1379 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1380 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001381
1382 # check a comment that is too long is truncated
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001383 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
Serhiy Storchaka9b7a1a12014-01-20 21:57:40 +02001384 with self.assertWarns(UserWarning):
1385 zipf.comment = comment2 + b'oops'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001386 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1387 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1388 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001389
Antoine Pitrouc3991852012-06-30 17:31:37 +02001390 # check that comments are correctly modified in append mode
1391 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1392 zipf.comment = b"original comment"
1393 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1394 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1395 zipf.comment = b"an updated comment"
1396 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1397 self.assertEqual(zipf.comment, b"an updated comment")
1398
1399 # check that comments are correctly shortened in append mode
1400 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1401 zipf.comment = b"original comment that's longer"
1402 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1403 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1404 zipf.comment = b"shorter comment"
1405 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1406 self.assertEqual(zipf.comment, b"shorter comment")
1407
R David Murrayf50b38a2012-04-12 18:44:58 -04001408 def test_unicode_comment(self):
1409 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1410 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1411 with self.assertRaises(TypeError):
1412 zipf.comment = "this is an error"
1413
1414 def test_change_comment_in_empty_archive(self):
1415 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1416 self.assertFalse(zipf.filelist)
1417 zipf.comment = b"this is a comment"
1418 with zipfile.ZipFile(TESTFN, "r") as zipf:
1419 self.assertEqual(zipf.comment, b"this is a comment")
1420
1421 def test_change_comment_in_nonempty_archive(self):
1422 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1423 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1424 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1425 self.assertTrue(zipf.filelist)
1426 zipf.comment = b"this is a comment"
1427 with zipfile.ZipFile(TESTFN, "r") as zipf:
1428 self.assertEqual(zipf.comment, b"this is a comment")
1429
Georg Brandl268e4d42010-10-14 06:59:45 +00001430 def test_empty_zipfile(self):
1431 # Check that creating a file in 'w' or 'a' mode and closing without
1432 # adding any files to the archives creates a valid empty ZIP file
1433 zipf = zipfile.ZipFile(TESTFN, mode="w")
1434 zipf.close()
1435 try:
1436 zipf = zipfile.ZipFile(TESTFN, mode="r")
1437 except zipfile.BadZipFile:
1438 self.fail("Unable to create empty ZIP file in 'w' mode")
1439
1440 zipf = zipfile.ZipFile(TESTFN, mode="a")
1441 zipf.close()
1442 try:
1443 zipf = zipfile.ZipFile(TESTFN, mode="r")
1444 except:
1445 self.fail("Unable to create empty ZIP file in 'a' mode")
1446
1447 def test_open_empty_file(self):
1448 # Issue 1710703: Check that opening a file with less than 22 bytes
Georg Brandl4d540882010-10-28 06:42:33 +00001449 # raises a BadZipFile exception (rather than the previously unhelpful
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001450 # OSError)
Georg Brandl268e4d42010-10-14 06:59:45 +00001451 f = open(TESTFN, 'w')
1452 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001453 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN, 'r')
Georg Brandl268e4d42010-10-14 06:59:45 +00001454
Senthil Kumaran29fa9d42011-10-20 01:46:00 +08001455 def test_create_zipinfo_before_1980(self):
1456 self.assertRaises(ValueError,
1457 zipfile.ZipInfo, 'seventies', (1979, 1, 1, 0, 0, 0))
1458
Gregory P. Smith0af8a862014-05-29 23:42:14 -07001459 def test_zipfile_with_short_extra_field(self):
1460 """If an extra field in the header is less than 4 bytes, skip it."""
1461 zipdata = (
1462 b'PK\x03\x04\x14\x00\x00\x00\x00\x00\x93\x9b\xad@\x8b\x9e'
1463 b'\xd9\xd3\x01\x00\x00\x00\x01\x00\x00\x00\x03\x00\x03\x00ab'
1464 b'c\x00\x00\x00APK\x01\x02\x14\x03\x14\x00\x00\x00\x00'
1465 b'\x00\x93\x9b\xad@\x8b\x9e\xd9\xd3\x01\x00\x00\x00\x01\x00\x00'
1466 b'\x00\x03\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00'
1467 b'\x00\x00\x00abc\x00\x00PK\x05\x06\x00\x00\x00\x00'
1468 b'\x01\x00\x01\x003\x00\x00\x00%\x00\x00\x00\x00\x00'
1469 )
1470 with zipfile.ZipFile(io.BytesIO(zipdata), 'r') as zipf:
1471 # testzip returns the name of the first corrupt file, or None
1472 self.assertIsNone(zipf.testzip())
1473
Guido van Rossumd8faa362007-04-27 19:54:29 +00001474 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001475 unlink(TESTFN)
1476 unlink(TESTFN2)
1477
Thomas Wouterscf297e42007-02-23 15:07:44 +00001478
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001479class AbstractBadCrcTests:
1480 def test_testzip_with_bad_crc(self):
1481 """Tests that files with bad CRCs return their name from testzip."""
1482 zipdata = self.zip_with_bad_crc
1483
1484 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1485 # testzip returns the name of the first corrupt file, or None
1486 self.assertEqual('afile', zipf.testzip())
1487
1488 def test_read_with_bad_crc(self):
1489 """Tests that files with bad CRCs raise a BadZipFile exception when read."""
1490 zipdata = self.zip_with_bad_crc
1491
1492 # Using ZipFile.read()
1493 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1494 self.assertRaises(zipfile.BadZipFile, zipf.read, 'afile')
1495
1496 # Using ZipExtFile.read()
1497 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1498 with zipf.open('afile', 'r') as corrupt_file:
1499 self.assertRaises(zipfile.BadZipFile, corrupt_file.read)
1500
1501 # Same with small reads (in order to exercise the buffering logic)
1502 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1503 with zipf.open('afile', 'r') as corrupt_file:
1504 corrupt_file.MIN_READ_SIZE = 2
1505 with self.assertRaises(zipfile.BadZipFile):
1506 while corrupt_file.read(2):
1507 pass
1508
1509
1510class StoredBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1511 compression = zipfile.ZIP_STORED
1512 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001513 b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
1514 b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
1515 b'ilehello,AworldP'
1516 b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
1517 b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
1518 b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
1519 b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
1520 b'\0\0/\0\0\0\0\0')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001521
1522@requires_zlib
1523class DeflateBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1524 compression = zipfile.ZIP_DEFLATED
1525 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001526 b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
1527 b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1528 b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
1529 b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
1530 b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
1531 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
1532 b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
1533 b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001534
1535@requires_bz2
1536class Bzip2BadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1537 compression = zipfile.ZIP_BZIP2
1538 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001539 b'PK\x03\x04\x14\x03\x00\x00\x0c\x00nu\x0c=FA'
1540 b'KE8\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1541 b'ileBZh91AY&SY\xd4\xa8\xca'
1542 b'\x7f\x00\x00\x0f\x11\x80@\x00\x06D\x90\x80 \x00 \xa5'
1543 b'P\xd9!\x03\x03\x13\x13\x13\x89\xa9\xa9\xc2u5:\x9f'
1544 b'\x8b\xb9"\x9c(HjTe?\x80PK\x01\x02\x14'
1545 b'\x03\x14\x03\x00\x00\x0c\x00nu\x0c=FAKE8'
1546 b'\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\x00'
1547 b'\x00 \x80\x80\x81\x00\x00\x00\x00afilePK'
1548 b'\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00\x00[\x00'
1549 b'\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001550
1551@requires_lzma
1552class LzmaBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1553 compression = zipfile.ZIP_LZMA
1554 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001555 b'PK\x03\x04\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
1556 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1557 b'ile\t\x04\x05\x00]\x00\x00\x00\x04\x004\x19I'
1558 b'\xee\x8d\xe9\x17\x89:3`\tq!.8\x00PK'
1559 b'\x01\x02\x14\x03\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
1560 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00'
1561 b'\x00\x00\x00\x00 \x80\x80\x81\x00\x00\x00\x00afil'
1562 b'ePK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00'
1563 b'\x00>\x00\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001564
1565
Thomas Wouterscf297e42007-02-23 15:07:44 +00001566class DecryptionTests(unittest.TestCase):
Ezio Melotti35386712009-12-31 13:22:41 +00001567 """Check that ZIP decryption works. Since the library does not
1568 support encryption at the moment, we use a pre-generated encrypted
1569 ZIP file."""
Thomas Wouterscf297e42007-02-23 15:07:44 +00001570
1571 data = (
Christian Tismer59202e52013-10-21 03:59:23 +02001572 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
1573 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
1574 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
1575 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
1576 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
1577 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
1578 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +00001579 data2 = (
Christian Tismer59202e52013-10-21 03:59:23 +02001580 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
1581 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
1582 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
1583 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
1584 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
1585 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
1586 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
1587 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +00001588
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001589 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +00001590 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +00001591
1592 def setUp(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001593 with open(TESTFN, "wb") as fp:
1594 fp.write(self.data)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001595 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti35386712009-12-31 13:22:41 +00001596 with open(TESTFN2, "wb") as fp:
1597 fp.write(self.data2)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001598 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001599
1600 def tearDown(self):
1601 self.zip.close()
1602 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001603 self.zip2.close()
1604 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001605
Ezio Melottiafd0d112009-07-15 17:17:17 +00001606 def test_no_password(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001607 # Reading the encrypted file without password
1608 # must generate a RunTime exception
1609 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001610 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001611
Ezio Melottiafd0d112009-07-15 17:17:17 +00001612 def test_bad_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001613 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001614 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001615 self.zip2.setpassword(b"perl")
1616 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001617
Ezio Melotti975077a2011-05-19 22:03:22 +03001618 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +00001619 def test_good_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001620 self.zip.setpassword(b"python")
Ezio Melotti35386712009-12-31 13:22:41 +00001621 self.assertEqual(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001622 self.zip2.setpassword(b"12345")
Ezio Melotti35386712009-12-31 13:22:41 +00001623 self.assertEqual(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001624
R. David Murray8d855d82010-12-21 21:53:37 +00001625 def test_unicode_password(self):
1626 self.assertRaises(TypeError, self.zip.setpassword, "unicode")
1627 self.assertRaises(TypeError, self.zip.read, "test.txt", "python")
1628 self.assertRaises(TypeError, self.zip.open, "test.txt", pwd="python")
1629 self.assertRaises(TypeError, self.zip.extract, "test.txt", pwd="python")
1630
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001631class AbstractTestsWithRandomBinaryFiles:
1632 @classmethod
1633 def setUpClass(cls):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001634 datacount = randint(16, 64)*1024 + randint(1, 1024)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001635 cls.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
1636 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001637
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001638 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001639 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +00001640 with open(TESTFN, "wb") as fp:
1641 fp.write(self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001642
1643 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001644 unlink(TESTFN)
1645 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001646
Ezio Melottiafd0d112009-07-15 17:17:17 +00001647 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001648 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001649 with zipfile.ZipFile(f, "w", compression) as zipfp:
1650 zipfp.write(TESTFN, "another.name")
1651 zipfp.write(TESTFN, TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001652
Ezio Melottiafd0d112009-07-15 17:17:17 +00001653 def zip_test(self, f, compression):
1654 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001655
1656 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001657 with zipfile.ZipFile(f, "r", compression) as zipfp:
1658 testdata = zipfp.read(TESTFN)
1659 self.assertEqual(len(testdata), len(self.data))
1660 self.assertEqual(testdata, self.data)
1661 self.assertEqual(zipfp.read("another.name"), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001662
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001663 def test_read(self):
1664 for f in get_files(self):
1665 self.zip_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001666
Ezio Melottiafd0d112009-07-15 17:17:17 +00001667 def zip_open_test(self, f, compression):
1668 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001669
1670 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001671 with zipfile.ZipFile(f, "r", compression) as zipfp:
1672 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001673 with zipfp.open(TESTFN) as zipopen1:
1674 while True:
1675 read_data = zipopen1.read(256)
1676 if not read_data:
1677 break
1678 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001679
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001680 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001681 with zipfp.open("another.name") as zipopen2:
1682 while True:
1683 read_data = zipopen2.read(256)
1684 if not read_data:
1685 break
1686 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001687
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001688 testdata1 = b''.join(zipdata1)
1689 self.assertEqual(len(testdata1), len(self.data))
1690 self.assertEqual(testdata1, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001691
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001692 testdata2 = b''.join(zipdata2)
Ezio Melotti35386712009-12-31 13:22:41 +00001693 self.assertEqual(len(testdata2), len(self.data))
1694 self.assertEqual(testdata2, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001695
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001696 def test_open(self):
1697 for f in get_files(self):
1698 self.zip_open_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001699
Ezio Melottiafd0d112009-07-15 17:17:17 +00001700 def zip_random_open_test(self, f, compression):
1701 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001702
1703 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001704 with zipfile.ZipFile(f, "r", compression) as zipfp:
1705 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001706 with zipfp.open(TESTFN) as zipopen1:
1707 while True:
1708 read_data = zipopen1.read(randint(1, 1024))
1709 if not read_data:
1710 break
1711 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001712
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001713 testdata = b''.join(zipdata1)
1714 self.assertEqual(len(testdata), len(self.data))
1715 self.assertEqual(testdata, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001716
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001717 def test_random_open(self):
1718 for f in get_files(self):
1719 self.zip_random_open_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001720
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001721
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001722class StoredTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1723 unittest.TestCase):
1724 compression = zipfile.ZIP_STORED
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001725
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001726@requires_zlib
1727class DeflateTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1728 unittest.TestCase):
1729 compression = zipfile.ZIP_DEFLATED
1730
1731@requires_bz2
1732class Bzip2TestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1733 unittest.TestCase):
1734 compression = zipfile.ZIP_BZIP2
1735
1736@requires_lzma
1737class LzmaTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1738 unittest.TestCase):
1739 compression = zipfile.ZIP_LZMA
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001740
Ezio Melotti76430242009-07-11 18:28:48 +00001741
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001742# Privide the tell() method but not seek()
1743class Tellable:
1744 def __init__(self, fp):
1745 self.fp = fp
1746 self.offset = 0
1747
1748 def write(self, data):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02001749 n = self.fp.write(data)
1750 self.offset += n
1751 return n
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001752
1753 def tell(self):
1754 return self.offset
1755
1756 def flush(self):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02001757 self.fp.flush()
1758
1759class Unseekable:
1760 def __init__(self, fp):
1761 self.fp = fp
1762
1763 def write(self, data):
1764 return self.fp.write(data)
1765
1766 def flush(self):
1767 self.fp.flush()
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001768
1769class UnseekableTests(unittest.TestCase):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02001770 def test_writestr(self):
1771 for wrapper in (lambda f: f), Tellable, Unseekable:
1772 with self.subTest(wrapper=wrapper):
1773 f = io.BytesIO()
1774 f.write(b'abc')
1775 bf = io.BufferedWriter(f)
1776 with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) as zipfp:
1777 zipfp.writestr('ones', b'111')
1778 zipfp.writestr('twos', b'222')
1779 self.assertEqual(f.getvalue()[:5], b'abcPK')
1780 with zipfile.ZipFile(f, mode='r') as zipf:
1781 with zipf.open('ones') as zopen:
1782 self.assertEqual(zopen.read(), b'111')
1783 with zipf.open('twos') as zopen:
1784 self.assertEqual(zopen.read(), b'222')
1785
1786 def test_write(self):
1787 for wrapper in (lambda f: f), Tellable, Unseekable:
1788 with self.subTest(wrapper=wrapper):
1789 f = io.BytesIO()
1790 f.write(b'abc')
1791 bf = io.BufferedWriter(f)
1792 with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) as zipfp:
1793 self.addCleanup(unlink, TESTFN)
1794 with open(TESTFN, 'wb') as f2:
1795 f2.write(b'111')
1796 zipfp.write(TESTFN, 'ones')
1797 with open(TESTFN, 'wb') as f2:
1798 f2.write(b'222')
1799 zipfp.write(TESTFN, 'twos')
1800 self.assertEqual(f.getvalue()[:5], b'abcPK')
1801 with zipfile.ZipFile(f, mode='r') as zipf:
1802 with zipf.open('ones') as zopen:
1803 self.assertEqual(zopen.read(), b'111')
1804 with zipf.open('twos') as zopen:
1805 self.assertEqual(zopen.read(), b'222')
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001806
1807
Ezio Melotti975077a2011-05-19 22:03:22 +03001808@requires_zlib
Guido van Rossumd8faa362007-04-27 19:54:29 +00001809class TestsWithMultipleOpens(unittest.TestCase):
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001810 @classmethod
1811 def setUpClass(cls):
1812 cls.data1 = b'111' + getrandbytes(10000)
1813 cls.data2 = b'222' + getrandbytes(10000)
1814
1815 def make_test_archive(self, f):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001816 # Create the ZIP archive
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001817 with zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as zipfp:
1818 zipfp.writestr('ones', self.data1)
1819 zipfp.writestr('twos', self.data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001820
Ezio Melottiafd0d112009-07-15 17:17:17 +00001821 def test_same_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001822 # Verify that (when the ZipFile is in control of creating file objects)
1823 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001824 for f in get_files(self):
1825 self.make_test_archive(f)
1826 with zipfile.ZipFile(f, mode="r") as zipf:
1827 with zipf.open('ones') as zopen1, zipf.open('ones') as zopen2:
1828 data1 = zopen1.read(500)
1829 data2 = zopen2.read(500)
1830 data1 += zopen1.read()
1831 data2 += zopen2.read()
1832 self.assertEqual(data1, data2)
1833 self.assertEqual(data1, self.data1)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001834
Ezio Melottiafd0d112009-07-15 17:17:17 +00001835 def test_different_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001836 # Verify that (when the ZipFile is in control of creating file objects)
1837 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001838 for f in get_files(self):
1839 self.make_test_archive(f)
1840 with zipfile.ZipFile(f, mode="r") as zipf:
1841 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1842 data1 = zopen1.read(500)
1843 data2 = zopen2.read(500)
1844 data1 += zopen1.read()
1845 data2 += zopen2.read()
1846 self.assertEqual(data1, self.data1)
1847 self.assertEqual(data2, self.data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001848
Ezio Melottiafd0d112009-07-15 17:17:17 +00001849 def test_interleaved(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001850 # Verify that (when the ZipFile is in control of creating file objects)
1851 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001852 for f in get_files(self):
1853 self.make_test_archive(f)
1854 with zipfile.ZipFile(f, mode="r") as zipf:
Serhiy Storchakad76c7c22016-05-13 21:18:58 +03001855 with zipf.open('ones') as zopen1:
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001856 data1 = zopen1.read(500)
Serhiy Storchakad76c7c22016-05-13 21:18:58 +03001857 with zipf.open('twos') as zopen2:
1858 data2 = zopen2.read(500)
1859 data1 += zopen1.read()
1860 data2 += zopen2.read()
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001861 self.assertEqual(data1, self.data1)
1862 self.assertEqual(data2, self.data2)
1863
1864 def test_read_after_close(self):
1865 for f in get_files(self):
1866 self.make_test_archive(f)
1867 with contextlib.ExitStack() as stack:
1868 with zipfile.ZipFile(f, 'r') as zipf:
1869 zopen1 = stack.enter_context(zipf.open('ones'))
1870 zopen2 = stack.enter_context(zipf.open('twos'))
Brian Curtin8fb9b862010-11-18 02:15:28 +00001871 data1 = zopen1.read(500)
1872 data2 = zopen2.read(500)
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001873 data1 += zopen1.read()
1874 data2 += zopen2.read()
1875 self.assertEqual(data1, self.data1)
1876 self.assertEqual(data2, self.data2)
1877
1878 def test_read_after_write(self):
1879 for f in get_files(self):
1880 with zipfile.ZipFile(f, 'w', zipfile.ZIP_DEFLATED) as zipf:
1881 zipf.writestr('ones', self.data1)
1882 zipf.writestr('twos', self.data2)
1883 with zipf.open('ones') as zopen1:
1884 data1 = zopen1.read(500)
1885 self.assertEqual(data1, self.data1[:500])
1886 with zipfile.ZipFile(f, 'r') as zipf:
1887 data1 = zipf.read('ones')
1888 data2 = zipf.read('twos')
1889 self.assertEqual(data1, self.data1)
1890 self.assertEqual(data2, self.data2)
1891
1892 def test_write_after_read(self):
1893 for f in get_files(self):
1894 with zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as zipf:
1895 zipf.writestr('ones', self.data1)
1896 with zipf.open('ones') as zopen1:
1897 zopen1.read(500)
1898 zipf.writestr('twos', self.data2)
1899 with zipfile.ZipFile(f, 'r') as zipf:
1900 data1 = zipf.read('ones')
1901 data2 = zipf.read('twos')
1902 self.assertEqual(data1, self.data1)
1903 self.assertEqual(data2, self.data2)
1904
1905 def test_many_opens(self):
1906 # Verify that read() and open() promptly close the file descriptor,
1907 # and don't rely on the garbage collector to free resources.
1908 self.make_test_archive(TESTFN2)
1909 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
1910 for x in range(100):
1911 zipf.read('ones')
1912 with zipf.open('ones') as zopen1:
1913 pass
1914 with open(os.devnull) as f:
1915 self.assertLess(f.fileno(), 100)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001916
1917 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001918 unlink(TESTFN2)
1919
Guido van Rossumd8faa362007-04-27 19:54:29 +00001920
Martin v. Löwis59e47792009-01-24 14:10:07 +00001921class TestWithDirectory(unittest.TestCase):
1922 def setUp(self):
1923 os.mkdir(TESTFN2)
1924
Ezio Melottiafd0d112009-07-15 17:17:17 +00001925 def test_extract_dir(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001926 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
1927 zipf.extractall(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001928 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1929 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1930 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1931
Ezio Melottiafd0d112009-07-15 17:17:17 +00001932 def test_bug_6050(self):
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001933 # Extraction should succeed if directories already exist
1934 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottiafd0d112009-07-15 17:17:17 +00001935 self.test_extract_dir()
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001936
Serhiy Storchaka46a34922014-09-23 22:40:23 +03001937 def test_write_dir(self):
1938 dirpath = os.path.join(TESTFN2, "x")
1939 os.mkdir(dirpath)
1940 mode = os.stat(dirpath).st_mode & 0xFFFF
1941 with zipfile.ZipFile(TESTFN, "w") as zipf:
1942 zipf.write(dirpath)
1943 zinfo = zipf.filelist[0]
1944 self.assertTrue(zinfo.filename.endswith("/x/"))
1945 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1946 zipf.write(dirpath, "y")
1947 zinfo = zipf.filelist[1]
1948 self.assertTrue(zinfo.filename, "y/")
1949 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1950 with zipfile.ZipFile(TESTFN, "r") as zipf:
1951 zinfo = zipf.filelist[0]
1952 self.assertTrue(zinfo.filename.endswith("/x/"))
1953 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1954 zinfo = zipf.filelist[1]
1955 self.assertTrue(zinfo.filename, "y/")
1956 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1957 target = os.path.join(TESTFN2, "target")
1958 os.mkdir(target)
1959 zipf.extractall(target)
1960 self.assertTrue(os.path.isdir(os.path.join(target, "y")))
1961 self.assertEqual(len(os.listdir(target)), 2)
1962
1963 def test_writestr_dir(self):
Martin v. Löwis59e47792009-01-24 14:10:07 +00001964 os.mkdir(os.path.join(TESTFN2, "x"))
Serhiy Storchaka46a34922014-09-23 22:40:23 +03001965 with zipfile.ZipFile(TESTFN, "w") as zipf:
1966 zipf.writestr("x/", b'')
1967 zinfo = zipf.filelist[0]
1968 self.assertEqual(zinfo.filename, "x/")
1969 self.assertEqual(zinfo.external_attr, (0o40775 << 16) | 0x10)
1970 with zipfile.ZipFile(TESTFN, "r") as zipf:
1971 zinfo = zipf.filelist[0]
1972 self.assertTrue(zinfo.filename.endswith("x/"))
1973 self.assertEqual(zinfo.external_attr, (0o40775 << 16) | 0x10)
1974 target = os.path.join(TESTFN2, "target")
1975 os.mkdir(target)
1976 zipf.extractall(target)
1977 self.assertTrue(os.path.isdir(os.path.join(target, "x")))
1978 self.assertEqual(os.listdir(target), ["x"])
Martin v. Löwis59e47792009-01-24 14:10:07 +00001979
1980 def tearDown(self):
Victor Stinner57004c62014-09-04 00:49:01 +02001981 rmtree(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001982 if os.path.exists(TESTFN):
Ezio Melotti76430242009-07-11 18:28:48 +00001983 unlink(TESTFN)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001984
Guido van Rossumd8faa362007-04-27 19:54:29 +00001985
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001986class AbstractUniversalNewlineTests:
1987 @classmethod
1988 def setUpClass(cls):
1989 cls.line_gen = [bytes("Test of zipfile line %d." % i, "ascii")
1990 for i in range(FIXEDTEST_SIZE)]
1991 cls.seps = (b'\r', b'\r\n', b'\n')
1992 cls.arcdata = {}
1993 for n, s in enumerate(cls.seps):
1994 cls.arcdata[s] = s.join(cls.line_gen) + s
1995
Guido van Rossumd8faa362007-04-27 19:54:29 +00001996 def setUp(self):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001997 self.arcfiles = {}
Guido van Rossumd8faa362007-04-27 19:54:29 +00001998 for n, s in enumerate(self.seps):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001999 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03002000 with open(self.arcfiles[s], "wb") as f:
Guido van Rossumd6ca5462007-05-22 01:29:33 +00002001 f.write(self.arcdata[s])
Guido van Rossumd8faa362007-04-27 19:54:29 +00002002
Ezio Melottiafd0d112009-07-15 17:17:17 +00002003 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00002004 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00002005 with zipfile.ZipFile(f, "w", compression) as zipfp:
2006 for fn in self.arcfiles.values():
2007 zipfp.write(fn, fn)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002008
Ezio Melottiafd0d112009-07-15 17:17:17 +00002009 def read_test(self, f, compression):
2010 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002011
2012 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00002013 with zipfile.ZipFile(f, "r") as zipfp:
2014 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02002015 with openU(zipfp, fn) as fp:
Benjamin Petersond285bdb2010-10-31 17:57:22 +00002016 zipdata = fp.read()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00002017 self.assertEqual(self.arcdata[sep], zipdata)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03002018
2019 def test_read(self):
2020 for f in get_files(self):
2021 self.read_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002022
Antoine Pitroua32f9a22010-01-27 21:18:57 +00002023 def readline_read_test(self, f, compression):
2024 self.make_test_archive(f, compression)
2025
2026 # Read the ZIP archive
Brian Curtin8fb9b862010-11-18 02:15:28 +00002027 with zipfile.ZipFile(f, "r") as zipfp:
2028 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02002029 with openU(zipfp, fn) as zipopen:
Brian Curtin8fb9b862010-11-18 02:15:28 +00002030 data = b''
2031 while True:
2032 read = zipopen.readline()
2033 if not read:
2034 break
2035 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +00002036
Brian Curtin8fb9b862010-11-18 02:15:28 +00002037 read = zipopen.read(5)
2038 if not read:
2039 break
2040 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +00002041
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03002042 self.assertEqual(data, self.arcdata[b'\n'])
Antoine Pitroua32f9a22010-01-27 21:18:57 +00002043
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03002044 def test_readline_read(self):
2045 for f in get_files(self):
2046 self.readline_read_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +00002047
Ezio Melottiafd0d112009-07-15 17:17:17 +00002048 def readline_test(self, f, compression):
2049 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002050
2051 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00002052 with zipfile.ZipFile(f, "r") as zipfp:
2053 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02002054 with openU(zipfp, fn) as zipopen:
Benjamin Petersond285bdb2010-10-31 17:57:22 +00002055 for line in self.line_gen:
2056 linedata = zipopen.readline()
2057 self.assertEqual(linedata, line + b'\n')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03002058
2059 def test_readline(self):
2060 for f in get_files(self):
2061 self.readline_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002062
Ezio Melottiafd0d112009-07-15 17:17:17 +00002063 def readlines_test(self, f, compression):
2064 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002065
2066 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00002067 with zipfile.ZipFile(f, "r") as zipfp:
2068 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02002069 with openU(zipfp, fn) as fp:
Benjamin Petersond285bdb2010-10-31 17:57:22 +00002070 ziplines = fp.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00002071 for line, zipline in zip(self.line_gen, ziplines):
2072 self.assertEqual(zipline, line + b'\n')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03002073
2074 def test_readlines(self):
2075 for f in get_files(self):
2076 self.readlines_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002077
Ezio Melottiafd0d112009-07-15 17:17:17 +00002078 def iterlines_test(self, f, compression):
2079 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002080
2081 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00002082 with zipfile.ZipFile(f, "r") as zipfp:
2083 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02002084 with openU(zipfp, fn) as fp:
Benjamin Petersond285bdb2010-10-31 17:57:22 +00002085 for line, zipline in zip(self.line_gen, fp):
2086 self.assertEqual(zipline, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00002087
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03002088 def test_iterlines(self):
2089 for f in get_files(self):
2090 self.iterlines_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02002091
Guido van Rossumd8faa362007-04-27 19:54:29 +00002092 def tearDown(self):
2093 for sep, fn in self.arcfiles.items():
Victor Stinner88b215e2014-09-04 00:51:09 +02002094 unlink(fn)
Ezio Melotti76430242009-07-11 18:28:48 +00002095 unlink(TESTFN)
2096 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002097
2098
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03002099class StoredUniversalNewlineTests(AbstractUniversalNewlineTests,
2100 unittest.TestCase):
2101 compression = zipfile.ZIP_STORED
2102
2103@requires_zlib
2104class DeflateUniversalNewlineTests(AbstractUniversalNewlineTests,
2105 unittest.TestCase):
2106 compression = zipfile.ZIP_DEFLATED
2107
2108@requires_bz2
2109class Bzip2UniversalNewlineTests(AbstractUniversalNewlineTests,
2110 unittest.TestCase):
2111 compression = zipfile.ZIP_BZIP2
2112
2113@requires_lzma
2114class LzmaUniversalNewlineTests(AbstractUniversalNewlineTests,
2115 unittest.TestCase):
2116 compression = zipfile.ZIP_LZMA
2117
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00002118if __name__ == "__main__":
Brett Cannond5b4e1d2013-06-12 19:57:19 -04002119 unittest.main()