blob: aa8c463dab7adb18197339180b434a15b4ce59a6 [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])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000418
R David Murray4fbb9db2011-06-09 15:50:51 -0400419 def test_ignores_newline_at_end(self):
420 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
421 zipfp.write(TESTFN, TESTFN)
422 with open(TESTFN2, 'a') as f:
423 f.write("\r\n\00\00\00")
424 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
425 self.assertIsInstance(zipfp, zipfile.ZipFile)
426
427 def test_ignores_stuff_appended_past_comments(self):
428 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
429 zipfp.comment = b"this is a comment"
430 zipfp.write(TESTFN, TESTFN)
431 with open(TESTFN2, 'a') as f:
432 f.write("abcdef\r\n")
433 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
434 self.assertIsInstance(zipfp, zipfile.ZipFile)
435 self.assertEqual(zipfp.comment, b"this is a comment")
436
Ezio Melottiafd0d112009-07-15 17:17:17 +0000437 def test_write_default_name(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000438 """Check that calling ZipFile.write without arcname specified
439 produces the expected result."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000440 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
441 zipfp.write(TESTFN)
Brian Curtin8fb9b862010-11-18 02:15:28 +0000442 with open(TESTFN, "rb") as f:
443 self.assertEqual(zipfp.read(TESTFN), f.read())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000444
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300445 def test_write_to_readonly(self):
446 """Check that trying to call write() on a readonly ZipFile object
447 raises a RuntimeError."""
448 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
449 zipfp.writestr("somefile.txt", "bogus")
450
451 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
452 self.assertRaises(RuntimeError, zipfp.write, TESTFN)
453
454 def test_add_file_before_1980(self):
455 # Set atime and mtime to 1970-01-01
456 os.utime(TESTFN, (0, 0))
457 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
458 self.assertRaises(ValueError, zipfp.write, TESTFN)
459
Serhiy Storchaka5ce3f102014-01-09 14:50:20 +0200460
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300461@requires_zlib
462class DeflateTestsWithSourceFile(AbstractTestsWithSourceFile,
463 unittest.TestCase):
464 compression = zipfile.ZIP_DEFLATED
465
Ezio Melottiafd0d112009-07-15 17:17:17 +0000466 def test_per_file_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000467 """Check that files within a Zip archive can have different
468 compression options."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000469 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
470 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
471 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
472 sinfo = zipfp.getinfo('storeme')
473 dinfo = zipfp.getinfo('deflateme')
474 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
475 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000476
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300477@requires_bz2
478class Bzip2TestsWithSourceFile(AbstractTestsWithSourceFile,
479 unittest.TestCase):
480 compression = zipfile.ZIP_BZIP2
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000481
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300482@requires_lzma
483class LzmaTestsWithSourceFile(AbstractTestsWithSourceFile,
484 unittest.TestCase):
485 compression = zipfile.ZIP_LZMA
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000486
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300487
488class AbstractTestZip64InSmallFiles:
489 # These tests test the ZIP64 functionality without using large files,
490 # see test_zipfile64 for proper tests.
491
492 @classmethod
493 def setUpClass(cls):
494 line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
495 for i in range(0, FIXEDTEST_SIZE))
496 cls.data = b'\n'.join(line_gen)
497
498 def setUp(self):
499 self._limit = zipfile.ZIP64_LIMIT
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300500 self._filecount_limit = zipfile.ZIP_FILECOUNT_LIMIT
501 zipfile.ZIP64_LIMIT = 1000
502 zipfile.ZIP_FILECOUNT_LIMIT = 9
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300503
504 # Make a source file with some lines
505 with open(TESTFN, "wb") as fp:
506 fp.write(self.data)
507
508 def zip_test(self, f, compression):
509 # Create the ZIP archive
510 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
511 zipfp.write(TESTFN, "another.name")
512 zipfp.write(TESTFN, TESTFN)
513 zipfp.writestr("strfile", self.data)
514
515 # Read the ZIP archive
516 with zipfile.ZipFile(f, "r", compression) as zipfp:
517 self.assertEqual(zipfp.read(TESTFN), self.data)
518 self.assertEqual(zipfp.read("another.name"), self.data)
519 self.assertEqual(zipfp.read("strfile"), self.data)
520
521 # Print the ZIP directory
522 fp = io.StringIO()
523 zipfp.printdir(fp)
524
525 directory = fp.getvalue()
526 lines = directory.splitlines()
527 self.assertEqual(len(lines), 4) # Number of files + header
528
529 self.assertIn('File Name', lines[0])
530 self.assertIn('Modified', lines[0])
531 self.assertIn('Size', lines[0])
532
533 fn, date, time_, size = lines[1].split()
534 self.assertEqual(fn, 'another.name')
535 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
536 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
537 self.assertEqual(size, str(len(self.data)))
538
539 # Check the namelist
540 names = zipfp.namelist()
541 self.assertEqual(len(names), 3)
542 self.assertIn(TESTFN, names)
543 self.assertIn("another.name", names)
544 self.assertIn("strfile", names)
545
546 # Check infolist
547 infos = zipfp.infolist()
548 names = [i.filename for i in infos]
549 self.assertEqual(len(names), 3)
550 self.assertIn(TESTFN, names)
551 self.assertIn("another.name", names)
552 self.assertIn("strfile", names)
553 for i in infos:
554 self.assertEqual(i.file_size, len(self.data))
555
556 # check getinfo
557 for nm in (TESTFN, "another.name", "strfile"):
558 info = zipfp.getinfo(nm)
559 self.assertEqual(info.filename, nm)
560 self.assertEqual(info.file_size, len(self.data))
561
562 # Check that testzip doesn't raise an exception
563 zipfp.testzip()
564
565 def test_basic(self):
566 for f in get_files(self):
567 self.zip_test(f, self.compression)
568
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300569 def test_too_many_files(self):
570 # This test checks that more than 64k files can be added to an archive,
571 # and that the resulting archive can be read properly by ZipFile
572 zipf = zipfile.ZipFile(TESTFN, "w", self.compression,
573 allowZip64=True)
574 zipf.debug = 100
575 numfiles = 15
576 for i in range(numfiles):
577 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
578 self.assertEqual(len(zipf.namelist()), numfiles)
579 zipf.close()
580
581 zipf2 = zipfile.ZipFile(TESTFN, "r", self.compression)
582 self.assertEqual(len(zipf2.namelist()), numfiles)
583 for i in range(numfiles):
584 content = zipf2.read("foo%08d" % i).decode('ascii')
585 self.assertEqual(content, "%d" % (i**3 % 57))
586 zipf2.close()
587
588 def test_too_many_files_append(self):
589 zipf = zipfile.ZipFile(TESTFN, "w", self.compression,
590 allowZip64=False)
591 zipf.debug = 100
592 numfiles = 9
593 for i in range(numfiles):
594 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
595 self.assertEqual(len(zipf.namelist()), numfiles)
596 with self.assertRaises(zipfile.LargeZipFile):
597 zipf.writestr("foo%08d" % numfiles, b'')
598 self.assertEqual(len(zipf.namelist()), numfiles)
599 zipf.close()
600
601 zipf = zipfile.ZipFile(TESTFN, "a", self.compression,
602 allowZip64=False)
603 zipf.debug = 100
604 self.assertEqual(len(zipf.namelist()), numfiles)
605 with self.assertRaises(zipfile.LargeZipFile):
606 zipf.writestr("foo%08d" % numfiles, b'')
607 self.assertEqual(len(zipf.namelist()), numfiles)
608 zipf.close()
609
610 zipf = zipfile.ZipFile(TESTFN, "a", self.compression,
611 allowZip64=True)
612 zipf.debug = 100
613 self.assertEqual(len(zipf.namelist()), numfiles)
614 numfiles2 = 15
615 for i in range(numfiles, numfiles2):
616 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
617 self.assertEqual(len(zipf.namelist()), numfiles2)
618 zipf.close()
619
620 zipf2 = zipfile.ZipFile(TESTFN, "r", self.compression)
621 self.assertEqual(len(zipf2.namelist()), numfiles2)
622 for i in range(numfiles2):
623 content = zipf2.read("foo%08d" % i).decode('ascii')
624 self.assertEqual(content, "%d" % (i**3 % 57))
625 zipf2.close()
626
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300627 def tearDown(self):
628 zipfile.ZIP64_LIMIT = self._limit
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300629 zipfile.ZIP_FILECOUNT_LIMIT = self._filecount_limit
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300630 unlink(TESTFN)
631 unlink(TESTFN2)
632
633
634class StoredTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
635 unittest.TestCase):
636 compression = zipfile.ZIP_STORED
637
638 def large_file_exception_test(self, f, compression):
Serhiy Storchaka235c5e02013-11-23 15:55:38 +0200639 with zipfile.ZipFile(f, "w", compression, allowZip64=False) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300640 self.assertRaises(zipfile.LargeZipFile,
641 zipfp.write, TESTFN, "another.name")
642
643 def large_file_exception_test2(self, f, compression):
Serhiy Storchaka235c5e02013-11-23 15:55:38 +0200644 with zipfile.ZipFile(f, "w", compression, allowZip64=False) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300645 self.assertRaises(zipfile.LargeZipFile,
646 zipfp.writestr, "another.name", self.data)
647
648 def test_large_file_exception(self):
649 for f in get_files(self):
650 self.large_file_exception_test(f, zipfile.ZIP_STORED)
651 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
652
653 def test_absolute_arcnames(self):
654 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
655 allowZip64=True) as zipfp:
656 zipfp.write(TESTFN, "/absolute")
657
658 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
659 self.assertEqual(zipfp.namelist(), ["absolute"])
660
661@requires_zlib
662class DeflateTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
663 unittest.TestCase):
664 compression = zipfile.ZIP_DEFLATED
665
666@requires_bz2
667class Bzip2TestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
668 unittest.TestCase):
669 compression = zipfile.ZIP_BZIP2
670
671@requires_lzma
672class LzmaTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
673 unittest.TestCase):
674 compression = zipfile.ZIP_LZMA
675
676
677class PyZipFileTests(unittest.TestCase):
678 def assertCompiledIn(self, name, namelist):
679 if name + 'o' not in namelist:
680 self.assertIn(name + 'c', namelist)
681
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200682 def requiresWriteAccess(self, path):
Berker Peksage1efc072015-02-16 04:36:18 +0200683 # effective_ids unavailable on windows
684 if not os.access(path, os.W_OK,
685 effective_ids=os.access in os.supports_effective_ids):
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200686 self.skipTest('requires write access to the installed location')
687
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300688 def test_write_pyfile(self):
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200689 self.requiresWriteAccess(os.path.dirname(__file__))
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300690 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
691 fn = __file__
Brett Cannonf299abd2015-04-13 14:21:02 -0400692 if fn.endswith('.pyc'):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300693 path_split = fn.split(os.sep)
694 if os.altsep is not None:
695 path_split.extend(fn.split(os.altsep))
696 if '__pycache__' in path_split:
Serhiy Storchaka9068e4d2013-07-22 21:02:14 +0300697 fn = importlib.util.source_from_cache(fn)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300698 else:
699 fn = fn[:-1]
700
701 zipfp.writepy(fn)
702
703 bn = os.path.basename(fn)
704 self.assertNotIn(bn, zipfp.namelist())
705 self.assertCompiledIn(bn, zipfp.namelist())
706
707 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
708 fn = __file__
Brett Cannonf299abd2015-04-13 14:21:02 -0400709 if fn.endswith('.pyc'):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300710 fn = fn[:-1]
711
712 zipfp.writepy(fn, "testpackage")
713
714 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
715 self.assertNotIn(bn, zipfp.namelist())
716 self.assertCompiledIn(bn, zipfp.namelist())
717
718 def test_write_python_package(self):
719 import email
720 packagedir = os.path.dirname(email.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200721 self.requiresWriteAccess(packagedir)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300722
723 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
724 zipfp.writepy(packagedir)
725
726 # Check for a couple of modules at different levels of the
727 # hierarchy
728 names = zipfp.namelist()
729 self.assertCompiledIn('email/__init__.py', names)
730 self.assertCompiledIn('email/mime/text.py', names)
731
Christian Tismer59202e52013-10-21 03:59:23 +0200732 def test_write_filtered_python_package(self):
733 import test
734 packagedir = os.path.dirname(test.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200735 self.requiresWriteAccess(packagedir)
Christian Tismer59202e52013-10-21 03:59:23 +0200736
737 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
738
Christian Tismer59202e52013-10-21 03:59:23 +0200739 # first make sure that the test folder gives error messages
Georg Brandla6065422013-10-21 08:29:29 +0200740 # (on the badsyntax_... files)
741 with captured_stdout() as reportSIO:
742 zipfp.writepy(packagedir)
Christian Tismer59202e52013-10-21 03:59:23 +0200743 reportStr = reportSIO.getvalue()
744 self.assertTrue('SyntaxError' in reportStr)
745
Christian Tismer410d9312013-10-22 04:09:28 +0200746 # then check that the filter works on the whole package
Georg Brandla6065422013-10-21 08:29:29 +0200747 with captured_stdout() as reportSIO:
748 zipfp.writepy(packagedir, filterfunc=lambda whatever: False)
Christian Tismer59202e52013-10-21 03:59:23 +0200749 reportStr = reportSIO.getvalue()
750 self.assertTrue('SyntaxError' not in reportStr)
751
Christian Tismer410d9312013-10-22 04:09:28 +0200752 # then check that the filter works on individual files
Serhiy Storchakac46d1fa2014-01-20 21:59:33 +0200753 with captured_stdout() as reportSIO, self.assertWarns(UserWarning):
Christian Tismer410d9312013-10-22 04:09:28 +0200754 zipfp.writepy(packagedir, filterfunc=lambda fn:
755 'bad' not in fn)
756 reportStr = reportSIO.getvalue()
757 if reportStr:
758 print(reportStr)
759 self.assertTrue('SyntaxError' not in reportStr)
760
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300761 def test_write_with_optimization(self):
762 import email
763 packagedir = os.path.dirname(email.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200764 self.requiresWriteAccess(packagedir)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300765 optlevel = 1 if __debug__ else 0
Brett Cannonf299abd2015-04-13 14:21:02 -0400766 ext = '.pyc'
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300767
768 with TemporaryFile() as t, \
Christian Tismer59202e52013-10-21 03:59:23 +0200769 zipfile.PyZipFile(t, "w", optimize=optlevel) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300770 zipfp.writepy(packagedir)
771
772 names = zipfp.namelist()
773 self.assertIn('email/__init__' + ext, names)
774 self.assertIn('email/mime/text' + ext, names)
775
776 def test_write_python_directory(self):
777 os.mkdir(TESTFN2)
778 try:
779 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
780 fp.write("print(42)\n")
781
782 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
783 fp.write("print(42 * 42)\n")
784
785 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
786 fp.write("bla bla bla\n")
787
788 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
789 zipfp.writepy(TESTFN2)
790
791 names = zipfp.namelist()
792 self.assertCompiledIn('mod1.py', names)
793 self.assertCompiledIn('mod2.py', names)
794 self.assertNotIn('mod2.txt', names)
795
796 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200797 rmtree(TESTFN2)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300798
Christian Tismer410d9312013-10-22 04:09:28 +0200799 def test_write_python_directory_filtered(self):
800 os.mkdir(TESTFN2)
801 try:
802 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
803 fp.write("print(42)\n")
804
805 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
806 fp.write("print(42 * 42)\n")
807
808 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
809 zipfp.writepy(TESTFN2, filterfunc=lambda fn:
810 not fn.endswith('mod2.py'))
811
812 names = zipfp.namelist()
813 self.assertCompiledIn('mod1.py', names)
814 self.assertNotIn('mod2.py', names)
815
816 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200817 rmtree(TESTFN2)
Christian Tismer410d9312013-10-22 04:09:28 +0200818
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300819 def test_write_non_pyfile(self):
820 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
821 with open(TESTFN, 'w') as f:
822 f.write('most definitely not a python file')
823 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
Victor Stinner88b215e2014-09-04 00:51:09 +0200824 unlink(TESTFN)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300825
826 def test_write_pyfile_bad_syntax(self):
827 os.mkdir(TESTFN2)
828 try:
829 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
830 fp.write("Bad syntax in python file\n")
831
832 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
833 # syntax errors are printed to stdout
834 with captured_stdout() as s:
835 zipfp.writepy(os.path.join(TESTFN2, "mod1.py"))
836
837 self.assertIn("SyntaxError", s.getvalue())
838
839 # as it will not have compiled the python file, it will
Brett Cannonf299abd2015-04-13 14:21:02 -0400840 # include the .py file not .pyc
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300841 names = zipfp.namelist()
842 self.assertIn('mod1.py', names)
843 self.assertNotIn('mod1.pyc', names)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300844
845 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200846 rmtree(TESTFN2)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300847
848
849class ExtractTests(unittest.TestCase):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000850 def test_extract(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000851 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
852 for fpath, fdata in SMALL_TEST_DATA:
853 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000854
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000855 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
856 for fpath, fdata in SMALL_TEST_DATA:
857 writtenfile = zipfp.extract(fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000858
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000859 # make sure it was written to the right place
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800860 correctfile = os.path.join(os.getcwd(), fpath)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000861 correctfile = os.path.normpath(correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000862
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000863 self.assertEqual(writtenfile, correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000864
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000865 # make sure correct data is in correct file
Brian Curtin8fb9b862010-11-18 02:15:28 +0000866 with open(writtenfile, "rb") as f:
867 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000868
Victor Stinner88b215e2014-09-04 00:51:09 +0200869 unlink(writtenfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000870
871 # remove the test file subdirectories
Victor Stinner57004c62014-09-04 00:49:01 +0200872 rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
Christian Heimes790c8232008-01-07 21:14:23 +0000873
Ezio Melottiafd0d112009-07-15 17:17:17 +0000874 def test_extract_all(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000875 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
876 for fpath, fdata in SMALL_TEST_DATA:
877 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000878
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000879 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
880 zipfp.extractall()
881 for fpath, fdata in SMALL_TEST_DATA:
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800882 outfile = os.path.join(os.getcwd(), fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000883
Brian Curtin8fb9b862010-11-18 02:15:28 +0000884 with open(outfile, "rb") as f:
885 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000886
Victor Stinner88b215e2014-09-04 00:51:09 +0200887 unlink(outfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000888
889 # remove the test file subdirectories
Victor Stinner57004c62014-09-04 00:49:01 +0200890 rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
Christian Heimes790c8232008-01-07 21:14:23 +0000891
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800892 def check_file(self, filename, content):
893 self.assertTrue(os.path.isfile(filename))
894 with open(filename, 'rb') as f:
895 self.assertEqual(f.read(), content)
896
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800897 def test_sanitize_windows_name(self):
898 san = zipfile.ZipFile._sanitize_windows_name
899 # Passing pathsep in allows this test to work regardless of platform.
900 self.assertEqual(san(r',,?,C:,foo,bar/z', ','), r'_,C_,foo,bar/z')
901 self.assertEqual(san(r'a\b,c<d>e|f"g?h*i', ','), r'a\b,c_d_e_f_g_h_i')
902 self.assertEqual(san('../../foo../../ba..r', '/'), r'foo/ba..r')
903
904 def test_extract_hackers_arcnames_common_cases(self):
905 common_hacknames = [
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800906 ('../foo/bar', 'foo/bar'),
907 ('foo/../bar', 'foo/bar'),
908 ('foo/../../bar', 'foo/bar'),
909 ('foo/bar/..', 'foo/bar'),
910 ('./../foo/bar', 'foo/bar'),
911 ('/foo/bar', 'foo/bar'),
912 ('/foo/../bar', 'foo/bar'),
913 ('/foo/../../bar', 'foo/bar'),
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800914 ]
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800915 self._test_extract_hackers_arcnames(common_hacknames)
916
917 @unittest.skipIf(os.path.sep != '\\', 'Requires \\ as path separator.')
918 def test_extract_hackers_arcnames_windows_only(self):
919 """Test combination of path fixing and windows name sanitization."""
920 windows_hacknames = [
Christian Tismer59202e52013-10-21 03:59:23 +0200921 (r'..\foo\bar', 'foo/bar'),
922 (r'..\/foo\/bar', 'foo/bar'),
923 (r'foo/\..\/bar', 'foo/bar'),
924 (r'foo\/../\bar', 'foo/bar'),
925 (r'C:foo/bar', 'foo/bar'),
926 (r'C:/foo/bar', 'foo/bar'),
927 (r'C://foo/bar', 'foo/bar'),
928 (r'C:\foo\bar', 'foo/bar'),
929 (r'//conky/mountpoint/foo/bar', 'foo/bar'),
930 (r'\\conky\mountpoint\foo\bar', 'foo/bar'),
931 (r'///conky/mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
932 (r'\\\conky\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
933 (r'//conky//mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
934 (r'\\conky\\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
935 (r'//?/C:/foo/bar', 'foo/bar'),
936 (r'\\?\C:\foo\bar', 'foo/bar'),
937 (r'C:/../C:/foo/bar', 'C_/foo/bar'),
938 (r'a:b\c<d>e|f"g?h*i', 'b/c_d_e_f_g_h_i'),
939 ('../../foo../../ba..r', 'foo/ba..r'),
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800940 ]
941 self._test_extract_hackers_arcnames(windows_hacknames)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800942
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800943 @unittest.skipIf(os.path.sep != '/', r'Requires / as path separator.')
944 def test_extract_hackers_arcnames_posix_only(self):
945 posix_hacknames = [
946 ('//foo/bar', 'foo/bar'),
947 ('../../foo../../ba..r', 'foo../ba..r'),
948 (r'foo/..\bar', r'foo/..\bar'),
949 ]
950 self._test_extract_hackers_arcnames(posix_hacknames)
951
952 def _test_extract_hackers_arcnames(self, hacknames):
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800953 for arcname, fixedname in hacknames:
954 content = b'foobar' + arcname.encode()
955 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipfp:
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200956 zinfo = zipfile.ZipInfo()
957 # preserve backslashes
958 zinfo.filename = arcname
959 zinfo.external_attr = 0o600 << 16
960 zipfp.writestr(zinfo, content)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800961
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200962 arcname = arcname.replace(os.sep, "/")
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800963 targetpath = os.path.join('target', 'subdir', 'subsub')
964 correctfile = os.path.join(targetpath, *fixedname.split('/'))
965
966 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
967 writtenfile = zipfp.extract(arcname, targetpath)
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200968 self.assertEqual(writtenfile, correctfile,
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800969 msg='extract %r: %r != %r' %
970 (arcname, writtenfile, correctfile))
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800971 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +0200972 rmtree('target')
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800973
974 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
975 zipfp.extractall(targetpath)
976 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +0200977 rmtree('target')
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800978
979 correctfile = os.path.join(os.getcwd(), *fixedname.split('/'))
980
981 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
982 writtenfile = zipfp.extract(arcname)
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200983 self.assertEqual(writtenfile, correctfile,
984 msg="extract %r" % arcname)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800985 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +0200986 rmtree(fixedname.split('/')[0])
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800987
988 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
989 zipfp.extractall()
990 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +0200991 rmtree(fixedname.split('/')[0])
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800992
Victor Stinner88b215e2014-09-04 00:51:09 +0200993 unlink(TESTFN2)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800994
Ronald Oussorenee5c8852010-02-07 20:24:02 +0000995
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300996class OtherTests(unittest.TestCase):
997 def test_open_via_zip_info(self):
998 # Create the ZIP archive
999 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
1000 zipfp.writestr("name", "foo")
Serhiy Storchaka9b7a1a12014-01-20 21:57:40 +02001001 with self.assertWarns(UserWarning):
1002 zipfp.writestr("name", "bar")
1003 self.assertEqual(zipfp.namelist(), ["name"] * 2)
Ronald Oussorenee5c8852010-02-07 20:24:02 +00001004
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001005 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1006 infos = zipfp.infolist()
1007 data = b""
1008 for info in infos:
1009 with zipfp.open(info) as zipopen:
1010 data += zipopen.read()
1011 self.assertIn(data, {b"foobar", b"barfoo"})
1012 data = b""
1013 for info in infos:
1014 data += zipfp.read(info)
1015 self.assertIn(data, {b"foobar", b"barfoo"})
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001016
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02001017 def test_universal_deprecation(self):
1018 f = io.BytesIO()
1019 with zipfile.ZipFile(f, "w") as zipfp:
1020 zipfp.writestr('spam.txt', b'ababagalamaga')
1021
1022 with zipfile.ZipFile(f, "r") as zipfp:
1023 for mode in 'U', 'rU':
1024 with self.assertWarns(DeprecationWarning):
1025 zipopen = zipfp.open('spam.txt', mode)
1026 zipopen.close()
1027
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001028 def test_universal_readaheads(self):
1029 f = io.BytesIO()
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001030
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001031 data = b'a\r\n' * 16 * 1024
1032 with zipfile.ZipFile(f, 'w', zipfile.ZIP_STORED) as zipfp:
1033 zipfp.writestr(TESTFN, data)
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +00001034
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001035 data2 = b''
1036 with zipfile.ZipFile(f, 'r') as zipfp, \
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02001037 openU(zipfp, TESTFN) as zipopen:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001038 for line in zipopen:
1039 data2 += line
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +00001040
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001041 self.assertEqual(data, data2.replace(b'\n', b'\r\n'))
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +00001042
Gregory P. Smithb0d9ca92009-07-07 05:06:04 +00001043 def test_writestr_extended_local_header_issue1202(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001044 with zipfile.ZipFile(TESTFN2, 'w') as orig_zip:
1045 for data in 'abcdefghijklmnop':
1046 zinfo = zipfile.ZipInfo(data)
1047 zinfo.flag_bits |= 0x08 # Include an extended local header.
1048 orig_zip.writestr(zinfo, data)
1049
1050 def test_close(self):
1051 """Check that the zipfile is closed after the 'with' block."""
1052 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
1053 for fpath, fdata in SMALL_TEST_DATA:
1054 zipfp.writestr(fpath, fdata)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001055 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
1056 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001057
1058 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001059 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
1060 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001061
1062 def test_close_on_exception(self):
1063 """Check that the zipfile is closed if an exception is raised in the
1064 'with' block."""
1065 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
1066 for fpath, fdata in SMALL_TEST_DATA:
1067 zipfp.writestr(fpath, fdata)
1068
1069 try:
1070 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
Georg Brandl4d540882010-10-28 06:42:33 +00001071 raise zipfile.BadZipFile()
1072 except zipfile.BadZipFile:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001073 self.assertIsNone(zipfp2.fp, 'zipfp is not closed')
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001074
Martin v. Löwisd099b562012-05-01 14:08:22 +02001075 def test_unsupported_version(self):
1076 # File has an extract_version of 120
1077 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 +02001078 b'\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00xPK\x01\x02x\x03x\x00\x00\x00\x00'
1079 b'\x00!p\xa1@\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00'
1080 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00\x00xPK\x05\x06'
1081 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 +03001082
Martin v. Löwisd099b562012-05-01 14:08:22 +02001083 self.assertRaises(NotImplementedError, zipfile.ZipFile,
1084 io.BytesIO(data), 'r')
1085
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001086 @requires_zlib
1087 def test_read_unicode_filenames(self):
1088 # bug #10801
1089 fname = findfile('zip_cp437_header.zip')
1090 with zipfile.ZipFile(fname) as zipfp:
1091 for name in zipfp.namelist():
1092 zipfp.open(name).close()
1093
1094 def test_write_unicode_filenames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001095 with zipfile.ZipFile(TESTFN, "w") as zf:
1096 zf.writestr("foo.txt", "Test for unicode filename")
1097 zf.writestr("\xf6.txt", "Test for unicode filename")
Ezio Melottie9615932010-01-24 19:26:24 +00001098 self.assertIsInstance(zf.infolist()[0].filename, str)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001099
1100 with zipfile.ZipFile(TESTFN, "r") as zf:
1101 self.assertEqual(zf.filelist[0].filename, "foo.txt")
1102 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
Martin v. Löwis8570f6a2008-05-05 17:44:38 +00001103
Serhiy Storchaka764fc9b2015-03-25 10:09:41 +02001104 def test_exclusive_create_zip_file(self):
1105 """Test exclusive creating a new zipfile."""
1106 unlink(TESTFN2)
1107 filename = 'testfile.txt'
1108 content = b'hello, world. this is some content.'
1109 with zipfile.ZipFile(TESTFN2, "x", zipfile.ZIP_STORED) as zipfp:
1110 zipfp.writestr(filename, content)
1111 with self.assertRaises(FileExistsError):
1112 zipfile.ZipFile(TESTFN2, "x", zipfile.ZIP_STORED)
1113 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1114 self.assertEqual(zipfp.namelist(), [filename])
1115 self.assertEqual(zipfp.read(filename), content)
1116
Ezio Melottiafd0d112009-07-15 17:17:17 +00001117 def test_create_non_existent_file_for_append(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001118 if os.path.exists(TESTFN):
1119 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001120
Thomas Wouterscf297e42007-02-23 15:07:44 +00001121 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001122 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +00001123
Thomas Wouterscf297e42007-02-23 15:07:44 +00001124 try:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001125 with zipfile.ZipFile(TESTFN, 'a') as zf:
1126 zf.writestr(filename, content)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001127 except OSError:
Thomas Wouterscf297e42007-02-23 15:07:44 +00001128 self.fail('Could not append data to a non-existent zip file.')
1129
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001130 self.assertTrue(os.path.exists(TESTFN))
Thomas Wouterscf297e42007-02-23 15:07:44 +00001131
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001132 with zipfile.ZipFile(TESTFN, 'r') as zf:
1133 self.assertEqual(zf.read(filename), content)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001134
Ezio Melottiafd0d112009-07-15 17:17:17 +00001135 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001136 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti35386712009-12-31 13:22:41 +00001137 # it opens if there's an error in the file. If it doesn't, the
1138 # traceback holds a reference to the ZipFile object and, indirectly,
1139 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001140 # On Windows, this causes the os.unlink() call to fail because the
1141 # underlying file is still open. This is SF bug #412214.
1142 #
Ezio Melotti35386712009-12-31 13:22:41 +00001143 with open(TESTFN, "w") as fp:
1144 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001145 try:
1146 zf = zipfile.ZipFile(TESTFN)
Georg Brandl4d540882010-10-28 06:42:33 +00001147 except zipfile.BadZipFile:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001148 pass
1149
Ezio Melottiafd0d112009-07-15 17:17:17 +00001150 def test_is_zip_erroneous_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001151 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001152 # - passing a filename
1153 with open(TESTFN, "w") as fp:
1154 fp.write("this is not a legal zip file\n")
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001155 self.assertFalse(zipfile.is_zipfile(TESTFN))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001156 # - passing a file object
1157 with open(TESTFN, "rb") as fp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001158 self.assertFalse(zipfile.is_zipfile(fp))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001159 # - passing a file-like object
1160 fp = io.BytesIO()
1161 fp.write(b"this is not a legal zip file\n")
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001162 self.assertFalse(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001163 fp.seek(0, 0)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001164 self.assertFalse(zipfile.is_zipfile(fp))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001165
Serhiy Storchakad2b15272013-01-31 15:27:07 +02001166 def test_damaged_zipfile(self):
1167 """Check that zipfiles with missing bytes at the end raise BadZipFile."""
1168 # - Create a valid zip file
1169 fp = io.BytesIO()
1170 with zipfile.ZipFile(fp, mode="w") as zipf:
1171 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
1172 zipfiledata = fp.getvalue()
1173
1174 # - Now create copies of it missing the last N bytes and make sure
1175 # a BadZipFile exception is raised when we try to open it
1176 for N in range(len(zipfiledata)):
1177 fp = io.BytesIO(zipfiledata[:N])
1178 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, fp)
1179
Ezio Melottiafd0d112009-07-15 17:17:17 +00001180 def test_is_zip_valid_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001181 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001182 # - passing a filename
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001183 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1184 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
1185
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001186 self.assertTrue(zipfile.is_zipfile(TESTFN))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001187 # - passing a file object
1188 with open(TESTFN, "rb") as fp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001189 self.assertTrue(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001190 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001191 zip_contents = fp.read()
1192 # - passing a file-like object
1193 fp = io.BytesIO()
1194 fp.write(zip_contents)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001195 self.assertTrue(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001196 fp.seek(0, 0)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001197 self.assertTrue(zipfile.is_zipfile(fp))
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001198
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001199 def test_non_existent_file_raises_OSError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001200 # make sure we don't raise an AttributeError when a partially-constructed
1201 # ZipFile instance is finalized; this tests for regression on SF tracker
1202 # bug #403871.
1203
1204 # The bug we're testing for caused an AttributeError to be raised
1205 # when a ZipFile instance was created for a file that did not
1206 # exist; the .fp member was not initialized but was needed by the
1207 # __del__() method. Since the AttributeError is in the __del__(),
1208 # it is ignored, but the user should be sufficiently annoyed by
1209 # the message on the output that regression will be noticed
1210 # quickly.
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001211 self.assertRaises(OSError, zipfile.ZipFile, TESTFN)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001212
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001213 def test_empty_file_raises_BadZipFile(self):
1214 f = open(TESTFN, 'w')
1215 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001216 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001217
Ezio Melotti35386712009-12-31 13:22:41 +00001218 with open(TESTFN, 'w') as fp:
1219 fp.write("short file")
Georg Brandl4d540882010-10-28 06:42:33 +00001220 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001221
Ezio Melottiafd0d112009-07-15 17:17:17 +00001222 def test_closed_zip_raises_RuntimeError(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001223 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001224 data = io.BytesIO()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001225 with zipfile.ZipFile(data, mode="w") as zipf:
1226 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001227
Andrew Svetlov737fb892012-12-18 21:14:22 +02001228 # This is correct; calling .read on a closed ZipFile should raise
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001229 # a RuntimeError, and so should calling .testzip. An earlier
1230 # version of .testzip would swallow this exception (and any other)
1231 # and report that the first file in the archive was corrupt.
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001232 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
1233 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001234 self.assertRaises(RuntimeError, zipf.testzip)
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001235 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Brian Curtin8fb9b862010-11-18 02:15:28 +00001236 with open(TESTFN, 'w') as f:
1237 f.write('zipfile test data')
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001238 self.assertRaises(RuntimeError, zipf.write, TESTFN)
1239
Ezio Melottiafd0d112009-07-15 17:17:17 +00001240 def test_bad_constructor_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001241 """Check that bad modes passed to ZipFile constructor are caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001242 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
1243
Ezio Melottiafd0d112009-07-15 17:17:17 +00001244 def test_bad_open_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001245 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001246 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1247 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1248
1249 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001250 # read the data to make sure the file is there
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001251 zipf.read("foo.txt")
1252 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001253
Ezio Melottiafd0d112009-07-15 17:17:17 +00001254 def test_read0(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001255 """Check that calling read(0) on a ZipExtFile object returns an empty
1256 string and doesn't advance file pointer."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001257 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1258 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1259 # read the data to make sure the file is there
Brian Curtin8fb9b862010-11-18 02:15:28 +00001260 with zipf.open("foo.txt") as f:
1261 for i in range(FIXEDTEST_SIZE):
1262 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001263
Brian Curtin8fb9b862010-11-18 02:15:28 +00001264 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001265
Ezio Melottiafd0d112009-07-15 17:17:17 +00001266 def test_open_non_existent_item(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001267 """Check that attempting to call open() for an item that doesn't
1268 exist in the archive raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001269 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1270 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001271
Ezio Melottiafd0d112009-07-15 17:17:17 +00001272 def test_bad_compression_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001273 """Check that bad compression methods passed to ZipFile.open are
1274 caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001275 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
1276
Martin v. Löwisb3260f02012-05-01 08:38:01 +02001277 def test_unsupported_compression(self):
1278 # data is declared as shrunk, but actually deflated
1279 data = (b'PK\x03\x04.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00'
Christian Tismer59202e52013-10-21 03:59:23 +02001280 b'\x00\x02\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00x\x03\x00PK\x01'
1281 b'\x02.\x03.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00\x00\x02\x00\x00'
1282 b'\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
1283 b'\x80\x01\x00\x00\x00\x00xPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00'
1284 b'/\x00\x00\x00!\x00\x00\x00\x00\x00')
Martin v. Löwisb3260f02012-05-01 08:38:01 +02001285 with zipfile.ZipFile(io.BytesIO(data), 'r') as zipf:
1286 self.assertRaises(NotImplementedError, zipf.open, 'x')
1287
Ezio Melottiafd0d112009-07-15 17:17:17 +00001288 def test_null_byte_in_filename(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001289 """Check that a filename containing a null byte is properly
1290 terminated."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001291 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1292 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
1293 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001294
Ezio Melottiafd0d112009-07-15 17:17:17 +00001295 def test_struct_sizes(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001296 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001297 self.assertEqual(zipfile.sizeEndCentDir, 22)
1298 self.assertEqual(zipfile.sizeCentralDir, 46)
1299 self.assertEqual(zipfile.sizeEndCentDir64, 56)
1300 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
1301
Ezio Melottiafd0d112009-07-15 17:17:17 +00001302 def test_comments(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001303 """Check that comments on the archive are handled properly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001304
1305 # check default comment is empty
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001306 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1307 self.assertEqual(zipf.comment, b'')
1308 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1309
1310 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1311 self.assertEqual(zipfr.comment, b'')
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001312
1313 # check a simple short comment
1314 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001315 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1316 zipf.comment = comment
1317 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1318 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1319 self.assertEqual(zipf.comment, comment)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001320
1321 # check a comment of max length
1322 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
1323 comment2 = comment2.encode("ascii")
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001324 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1325 zipf.comment = comment2
1326 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1327
1328 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1329 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001330
1331 # check a comment that is too long is truncated
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001332 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
Serhiy Storchaka9b7a1a12014-01-20 21:57:40 +02001333 with self.assertWarns(UserWarning):
1334 zipf.comment = comment2 + b'oops'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001335 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1336 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1337 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001338
Antoine Pitrouc3991852012-06-30 17:31:37 +02001339 # check that comments are correctly modified in append mode
1340 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1341 zipf.comment = b"original comment"
1342 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1343 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1344 zipf.comment = b"an updated comment"
1345 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1346 self.assertEqual(zipf.comment, b"an updated comment")
1347
1348 # check that comments are correctly shortened in append mode
1349 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1350 zipf.comment = b"original comment that's longer"
1351 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1352 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1353 zipf.comment = b"shorter comment"
1354 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1355 self.assertEqual(zipf.comment, b"shorter comment")
1356
R David Murrayf50b38a2012-04-12 18:44:58 -04001357 def test_unicode_comment(self):
1358 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1359 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1360 with self.assertRaises(TypeError):
1361 zipf.comment = "this is an error"
1362
1363 def test_change_comment_in_empty_archive(self):
1364 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1365 self.assertFalse(zipf.filelist)
1366 zipf.comment = b"this is a comment"
1367 with zipfile.ZipFile(TESTFN, "r") as zipf:
1368 self.assertEqual(zipf.comment, b"this is a comment")
1369
1370 def test_change_comment_in_nonempty_archive(self):
1371 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1372 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1373 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1374 self.assertTrue(zipf.filelist)
1375 zipf.comment = b"this is a comment"
1376 with zipfile.ZipFile(TESTFN, "r") as zipf:
1377 self.assertEqual(zipf.comment, b"this is a comment")
1378
Georg Brandl268e4d42010-10-14 06:59:45 +00001379 def test_empty_zipfile(self):
1380 # Check that creating a file in 'w' or 'a' mode and closing without
1381 # adding any files to the archives creates a valid empty ZIP file
1382 zipf = zipfile.ZipFile(TESTFN, mode="w")
1383 zipf.close()
1384 try:
1385 zipf = zipfile.ZipFile(TESTFN, mode="r")
1386 except zipfile.BadZipFile:
1387 self.fail("Unable to create empty ZIP file in 'w' mode")
1388
1389 zipf = zipfile.ZipFile(TESTFN, mode="a")
1390 zipf.close()
1391 try:
1392 zipf = zipfile.ZipFile(TESTFN, mode="r")
1393 except:
1394 self.fail("Unable to create empty ZIP file in 'a' mode")
1395
1396 def test_open_empty_file(self):
1397 # Issue 1710703: Check that opening a file with less than 22 bytes
Georg Brandl4d540882010-10-28 06:42:33 +00001398 # raises a BadZipFile exception (rather than the previously unhelpful
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001399 # OSError)
Georg Brandl268e4d42010-10-14 06:59:45 +00001400 f = open(TESTFN, 'w')
1401 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001402 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN, 'r')
Georg Brandl268e4d42010-10-14 06:59:45 +00001403
Senthil Kumaran29fa9d42011-10-20 01:46:00 +08001404 def test_create_zipinfo_before_1980(self):
1405 self.assertRaises(ValueError,
1406 zipfile.ZipInfo, 'seventies', (1979, 1, 1, 0, 0, 0))
1407
Gregory P. Smith0af8a862014-05-29 23:42:14 -07001408 def test_zipfile_with_short_extra_field(self):
1409 """If an extra field in the header is less than 4 bytes, skip it."""
1410 zipdata = (
1411 b'PK\x03\x04\x14\x00\x00\x00\x00\x00\x93\x9b\xad@\x8b\x9e'
1412 b'\xd9\xd3\x01\x00\x00\x00\x01\x00\x00\x00\x03\x00\x03\x00ab'
1413 b'c\x00\x00\x00APK\x01\x02\x14\x03\x14\x00\x00\x00\x00'
1414 b'\x00\x93\x9b\xad@\x8b\x9e\xd9\xd3\x01\x00\x00\x00\x01\x00\x00'
1415 b'\x00\x03\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00'
1416 b'\x00\x00\x00abc\x00\x00PK\x05\x06\x00\x00\x00\x00'
1417 b'\x01\x00\x01\x003\x00\x00\x00%\x00\x00\x00\x00\x00'
1418 )
1419 with zipfile.ZipFile(io.BytesIO(zipdata), 'r') as zipf:
1420 # testzip returns the name of the first corrupt file, or None
1421 self.assertIsNone(zipf.testzip())
1422
Guido van Rossumd8faa362007-04-27 19:54:29 +00001423 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001424 unlink(TESTFN)
1425 unlink(TESTFN2)
1426
Thomas Wouterscf297e42007-02-23 15:07:44 +00001427
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001428class AbstractBadCrcTests:
1429 def test_testzip_with_bad_crc(self):
1430 """Tests that files with bad CRCs return their name from testzip."""
1431 zipdata = self.zip_with_bad_crc
1432
1433 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1434 # testzip returns the name of the first corrupt file, or None
1435 self.assertEqual('afile', zipf.testzip())
1436
1437 def test_read_with_bad_crc(self):
1438 """Tests that files with bad CRCs raise a BadZipFile exception when read."""
1439 zipdata = self.zip_with_bad_crc
1440
1441 # Using ZipFile.read()
1442 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1443 self.assertRaises(zipfile.BadZipFile, zipf.read, 'afile')
1444
1445 # Using ZipExtFile.read()
1446 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1447 with zipf.open('afile', 'r') as corrupt_file:
1448 self.assertRaises(zipfile.BadZipFile, corrupt_file.read)
1449
1450 # Same with small reads (in order to exercise the buffering logic)
1451 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1452 with zipf.open('afile', 'r') as corrupt_file:
1453 corrupt_file.MIN_READ_SIZE = 2
1454 with self.assertRaises(zipfile.BadZipFile):
1455 while corrupt_file.read(2):
1456 pass
1457
1458
1459class StoredBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1460 compression = zipfile.ZIP_STORED
1461 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001462 b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
1463 b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
1464 b'ilehello,AworldP'
1465 b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
1466 b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
1467 b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
1468 b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
1469 b'\0\0/\0\0\0\0\0')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001470
1471@requires_zlib
1472class DeflateBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1473 compression = zipfile.ZIP_DEFLATED
1474 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001475 b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
1476 b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1477 b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
1478 b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
1479 b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
1480 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
1481 b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
1482 b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001483
1484@requires_bz2
1485class Bzip2BadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1486 compression = zipfile.ZIP_BZIP2
1487 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001488 b'PK\x03\x04\x14\x03\x00\x00\x0c\x00nu\x0c=FA'
1489 b'KE8\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1490 b'ileBZh91AY&SY\xd4\xa8\xca'
1491 b'\x7f\x00\x00\x0f\x11\x80@\x00\x06D\x90\x80 \x00 \xa5'
1492 b'P\xd9!\x03\x03\x13\x13\x13\x89\xa9\xa9\xc2u5:\x9f'
1493 b'\x8b\xb9"\x9c(HjTe?\x80PK\x01\x02\x14'
1494 b'\x03\x14\x03\x00\x00\x0c\x00nu\x0c=FAKE8'
1495 b'\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\x00'
1496 b'\x00 \x80\x80\x81\x00\x00\x00\x00afilePK'
1497 b'\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00\x00[\x00'
1498 b'\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001499
1500@requires_lzma
1501class LzmaBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1502 compression = zipfile.ZIP_LZMA
1503 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001504 b'PK\x03\x04\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
1505 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1506 b'ile\t\x04\x05\x00]\x00\x00\x00\x04\x004\x19I'
1507 b'\xee\x8d\xe9\x17\x89:3`\tq!.8\x00PK'
1508 b'\x01\x02\x14\x03\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
1509 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00'
1510 b'\x00\x00\x00\x00 \x80\x80\x81\x00\x00\x00\x00afil'
1511 b'ePK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00'
1512 b'\x00>\x00\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001513
1514
Thomas Wouterscf297e42007-02-23 15:07:44 +00001515class DecryptionTests(unittest.TestCase):
Ezio Melotti35386712009-12-31 13:22:41 +00001516 """Check that ZIP decryption works. Since the library does not
1517 support encryption at the moment, we use a pre-generated encrypted
1518 ZIP file."""
Thomas Wouterscf297e42007-02-23 15:07:44 +00001519
1520 data = (
Christian Tismer59202e52013-10-21 03:59:23 +02001521 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
1522 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
1523 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
1524 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
1525 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
1526 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
1527 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +00001528 data2 = (
Christian Tismer59202e52013-10-21 03:59:23 +02001529 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
1530 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
1531 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
1532 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
1533 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
1534 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
1535 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
1536 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +00001537
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001538 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +00001539 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +00001540
1541 def setUp(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001542 with open(TESTFN, "wb") as fp:
1543 fp.write(self.data)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001544 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti35386712009-12-31 13:22:41 +00001545 with open(TESTFN2, "wb") as fp:
1546 fp.write(self.data2)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001547 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001548
1549 def tearDown(self):
1550 self.zip.close()
1551 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001552 self.zip2.close()
1553 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001554
Ezio Melottiafd0d112009-07-15 17:17:17 +00001555 def test_no_password(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001556 # Reading the encrypted file without password
1557 # must generate a RunTime exception
1558 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001559 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001560
Ezio Melottiafd0d112009-07-15 17:17:17 +00001561 def test_bad_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001562 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001563 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001564 self.zip2.setpassword(b"perl")
1565 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001566
Ezio Melotti975077a2011-05-19 22:03:22 +03001567 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +00001568 def test_good_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001569 self.zip.setpassword(b"python")
Ezio Melotti35386712009-12-31 13:22:41 +00001570 self.assertEqual(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001571 self.zip2.setpassword(b"12345")
Ezio Melotti35386712009-12-31 13:22:41 +00001572 self.assertEqual(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001573
R. David Murray8d855d82010-12-21 21:53:37 +00001574 def test_unicode_password(self):
1575 self.assertRaises(TypeError, self.zip.setpassword, "unicode")
1576 self.assertRaises(TypeError, self.zip.read, "test.txt", "python")
1577 self.assertRaises(TypeError, self.zip.open, "test.txt", pwd="python")
1578 self.assertRaises(TypeError, self.zip.extract, "test.txt", pwd="python")
1579
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001580class AbstractTestsWithRandomBinaryFiles:
1581 @classmethod
1582 def setUpClass(cls):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001583 datacount = randint(16, 64)*1024 + randint(1, 1024)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001584 cls.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
1585 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001586
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001587 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001588 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +00001589 with open(TESTFN, "wb") as fp:
1590 fp.write(self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001591
1592 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001593 unlink(TESTFN)
1594 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001595
Ezio Melottiafd0d112009-07-15 17:17:17 +00001596 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001597 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001598 with zipfile.ZipFile(f, "w", compression) as zipfp:
1599 zipfp.write(TESTFN, "another.name")
1600 zipfp.write(TESTFN, TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001601
Ezio Melottiafd0d112009-07-15 17:17:17 +00001602 def zip_test(self, f, compression):
1603 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001604
1605 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001606 with zipfile.ZipFile(f, "r", compression) as zipfp:
1607 testdata = zipfp.read(TESTFN)
1608 self.assertEqual(len(testdata), len(self.data))
1609 self.assertEqual(testdata, self.data)
1610 self.assertEqual(zipfp.read("another.name"), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001611
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001612 def test_read(self):
1613 for f in get_files(self):
1614 self.zip_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001615
Ezio Melottiafd0d112009-07-15 17:17:17 +00001616 def zip_open_test(self, f, compression):
1617 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001618
1619 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001620 with zipfile.ZipFile(f, "r", compression) as zipfp:
1621 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001622 with zipfp.open(TESTFN) as zipopen1:
1623 while True:
1624 read_data = zipopen1.read(256)
1625 if not read_data:
1626 break
1627 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001628
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001629 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001630 with zipfp.open("another.name") as zipopen2:
1631 while True:
1632 read_data = zipopen2.read(256)
1633 if not read_data:
1634 break
1635 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001636
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001637 testdata1 = b''.join(zipdata1)
1638 self.assertEqual(len(testdata1), len(self.data))
1639 self.assertEqual(testdata1, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001640
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001641 testdata2 = b''.join(zipdata2)
Ezio Melotti35386712009-12-31 13:22:41 +00001642 self.assertEqual(len(testdata2), len(self.data))
1643 self.assertEqual(testdata2, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001644
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001645 def test_open(self):
1646 for f in get_files(self):
1647 self.zip_open_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001648
Ezio Melottiafd0d112009-07-15 17:17:17 +00001649 def zip_random_open_test(self, f, compression):
1650 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001651
1652 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001653 with zipfile.ZipFile(f, "r", compression) as zipfp:
1654 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001655 with zipfp.open(TESTFN) as zipopen1:
1656 while True:
1657 read_data = zipopen1.read(randint(1, 1024))
1658 if not read_data:
1659 break
1660 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001661
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001662 testdata = b''.join(zipdata1)
1663 self.assertEqual(len(testdata), len(self.data))
1664 self.assertEqual(testdata, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001665
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001666 def test_random_open(self):
1667 for f in get_files(self):
1668 self.zip_random_open_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001669
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001670
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001671class StoredTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1672 unittest.TestCase):
1673 compression = zipfile.ZIP_STORED
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001674
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001675@requires_zlib
1676class DeflateTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1677 unittest.TestCase):
1678 compression = zipfile.ZIP_DEFLATED
1679
1680@requires_bz2
1681class Bzip2TestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1682 unittest.TestCase):
1683 compression = zipfile.ZIP_BZIP2
1684
1685@requires_lzma
1686class LzmaTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1687 unittest.TestCase):
1688 compression = zipfile.ZIP_LZMA
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001689
Ezio Melotti76430242009-07-11 18:28:48 +00001690
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001691# Privide the tell() method but not seek()
1692class Tellable:
1693 def __init__(self, fp):
1694 self.fp = fp
1695 self.offset = 0
1696
1697 def write(self, data):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02001698 n = self.fp.write(data)
1699 self.offset += n
1700 return n
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001701
1702 def tell(self):
1703 return self.offset
1704
1705 def flush(self):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02001706 self.fp.flush()
1707
1708class Unseekable:
1709 def __init__(self, fp):
1710 self.fp = fp
1711
1712 def write(self, data):
1713 return self.fp.write(data)
1714
1715 def flush(self):
1716 self.fp.flush()
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001717
1718class UnseekableTests(unittest.TestCase):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02001719 def test_writestr(self):
1720 for wrapper in (lambda f: f), Tellable, Unseekable:
1721 with self.subTest(wrapper=wrapper):
1722 f = io.BytesIO()
1723 f.write(b'abc')
1724 bf = io.BufferedWriter(f)
1725 with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) as zipfp:
1726 zipfp.writestr('ones', b'111')
1727 zipfp.writestr('twos', b'222')
1728 self.assertEqual(f.getvalue()[:5], b'abcPK')
1729 with zipfile.ZipFile(f, mode='r') as zipf:
1730 with zipf.open('ones') as zopen:
1731 self.assertEqual(zopen.read(), b'111')
1732 with zipf.open('twos') as zopen:
1733 self.assertEqual(zopen.read(), b'222')
1734
1735 def test_write(self):
1736 for wrapper in (lambda f: f), Tellable, Unseekable:
1737 with self.subTest(wrapper=wrapper):
1738 f = io.BytesIO()
1739 f.write(b'abc')
1740 bf = io.BufferedWriter(f)
1741 with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) as zipfp:
1742 self.addCleanup(unlink, TESTFN)
1743 with open(TESTFN, 'wb') as f2:
1744 f2.write(b'111')
1745 zipfp.write(TESTFN, 'ones')
1746 with open(TESTFN, 'wb') as f2:
1747 f2.write(b'222')
1748 zipfp.write(TESTFN, 'twos')
1749 self.assertEqual(f.getvalue()[:5], b'abcPK')
1750 with zipfile.ZipFile(f, mode='r') as zipf:
1751 with zipf.open('ones') as zopen:
1752 self.assertEqual(zopen.read(), b'111')
1753 with zipf.open('twos') as zopen:
1754 self.assertEqual(zopen.read(), b'222')
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001755
1756
Ezio Melotti975077a2011-05-19 22:03:22 +03001757@requires_zlib
Guido van Rossumd8faa362007-04-27 19:54:29 +00001758class TestsWithMultipleOpens(unittest.TestCase):
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001759 @classmethod
1760 def setUpClass(cls):
1761 cls.data1 = b'111' + getrandbytes(10000)
1762 cls.data2 = b'222' + getrandbytes(10000)
1763
1764 def make_test_archive(self, f):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001765 # Create the ZIP archive
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001766 with zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as zipfp:
1767 zipfp.writestr('ones', self.data1)
1768 zipfp.writestr('twos', self.data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001769
Ezio Melottiafd0d112009-07-15 17:17:17 +00001770 def test_same_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001771 # Verify that (when the ZipFile is in control of creating file objects)
1772 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001773 for f in get_files(self):
1774 self.make_test_archive(f)
1775 with zipfile.ZipFile(f, mode="r") as zipf:
1776 with zipf.open('ones') as zopen1, zipf.open('ones') as zopen2:
1777 data1 = zopen1.read(500)
1778 data2 = zopen2.read(500)
1779 data1 += zopen1.read()
1780 data2 += zopen2.read()
1781 self.assertEqual(data1, data2)
1782 self.assertEqual(data1, self.data1)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001783
Ezio Melottiafd0d112009-07-15 17:17:17 +00001784 def test_different_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001785 # Verify that (when the ZipFile is in control of creating file objects)
1786 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001787 for f in get_files(self):
1788 self.make_test_archive(f)
1789 with zipfile.ZipFile(f, mode="r") as zipf:
1790 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1791 data1 = zopen1.read(500)
1792 data2 = zopen2.read(500)
1793 data1 += zopen1.read()
1794 data2 += zopen2.read()
1795 self.assertEqual(data1, self.data1)
1796 self.assertEqual(data2, self.data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001797
Ezio Melottiafd0d112009-07-15 17:17:17 +00001798 def test_interleaved(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001799 # Verify that (when the ZipFile is in control of creating file objects)
1800 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001801 for f in get_files(self):
1802 self.make_test_archive(f)
1803 with zipfile.ZipFile(f, mode="r") as zipf:
1804 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1805 data1 = zopen1.read(500)
1806 data2 = zopen2.read(500)
1807 data1 += zopen1.read()
1808 data2 += zopen2.read()
1809 self.assertEqual(data1, self.data1)
1810 self.assertEqual(data2, self.data2)
1811
1812 def test_read_after_close(self):
1813 for f in get_files(self):
1814 self.make_test_archive(f)
1815 with contextlib.ExitStack() as stack:
1816 with zipfile.ZipFile(f, 'r') as zipf:
1817 zopen1 = stack.enter_context(zipf.open('ones'))
1818 zopen2 = stack.enter_context(zipf.open('twos'))
Brian Curtin8fb9b862010-11-18 02:15:28 +00001819 data1 = zopen1.read(500)
1820 data2 = zopen2.read(500)
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001821 data1 += zopen1.read()
1822 data2 += zopen2.read()
1823 self.assertEqual(data1, self.data1)
1824 self.assertEqual(data2, self.data2)
1825
1826 def test_read_after_write(self):
1827 for f in get_files(self):
1828 with zipfile.ZipFile(f, 'w', zipfile.ZIP_DEFLATED) as zipf:
1829 zipf.writestr('ones', self.data1)
1830 zipf.writestr('twos', self.data2)
1831 with zipf.open('ones') as zopen1:
1832 data1 = zopen1.read(500)
1833 self.assertEqual(data1, self.data1[:500])
1834 with zipfile.ZipFile(f, 'r') as zipf:
1835 data1 = zipf.read('ones')
1836 data2 = zipf.read('twos')
1837 self.assertEqual(data1, self.data1)
1838 self.assertEqual(data2, self.data2)
1839
1840 def test_write_after_read(self):
1841 for f in get_files(self):
1842 with zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as zipf:
1843 zipf.writestr('ones', self.data1)
1844 with zipf.open('ones') as zopen1:
1845 zopen1.read(500)
1846 zipf.writestr('twos', self.data2)
1847 with zipfile.ZipFile(f, 'r') as zipf:
1848 data1 = zipf.read('ones')
1849 data2 = zipf.read('twos')
1850 self.assertEqual(data1, self.data1)
1851 self.assertEqual(data2, self.data2)
1852
1853 def test_many_opens(self):
1854 # Verify that read() and open() promptly close the file descriptor,
1855 # and don't rely on the garbage collector to free resources.
1856 self.make_test_archive(TESTFN2)
1857 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
1858 for x in range(100):
1859 zipf.read('ones')
1860 with zipf.open('ones') as zopen1:
1861 pass
1862 with open(os.devnull) as f:
1863 self.assertLess(f.fileno(), 100)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001864
1865 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001866 unlink(TESTFN2)
1867
Guido van Rossumd8faa362007-04-27 19:54:29 +00001868
Martin v. Löwis59e47792009-01-24 14:10:07 +00001869class TestWithDirectory(unittest.TestCase):
1870 def setUp(self):
1871 os.mkdir(TESTFN2)
1872
Ezio Melottiafd0d112009-07-15 17:17:17 +00001873 def test_extract_dir(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001874 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
1875 zipf.extractall(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001876 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1877 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1878 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1879
Ezio Melottiafd0d112009-07-15 17:17:17 +00001880 def test_bug_6050(self):
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001881 # Extraction should succeed if directories already exist
1882 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottiafd0d112009-07-15 17:17:17 +00001883 self.test_extract_dir()
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001884
Serhiy Storchaka46a34922014-09-23 22:40:23 +03001885 def test_write_dir(self):
1886 dirpath = os.path.join(TESTFN2, "x")
1887 os.mkdir(dirpath)
1888 mode = os.stat(dirpath).st_mode & 0xFFFF
1889 with zipfile.ZipFile(TESTFN, "w") as zipf:
1890 zipf.write(dirpath)
1891 zinfo = zipf.filelist[0]
1892 self.assertTrue(zinfo.filename.endswith("/x/"))
1893 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1894 zipf.write(dirpath, "y")
1895 zinfo = zipf.filelist[1]
1896 self.assertTrue(zinfo.filename, "y/")
1897 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1898 with zipfile.ZipFile(TESTFN, "r") as zipf:
1899 zinfo = zipf.filelist[0]
1900 self.assertTrue(zinfo.filename.endswith("/x/"))
1901 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1902 zinfo = zipf.filelist[1]
1903 self.assertTrue(zinfo.filename, "y/")
1904 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1905 target = os.path.join(TESTFN2, "target")
1906 os.mkdir(target)
1907 zipf.extractall(target)
1908 self.assertTrue(os.path.isdir(os.path.join(target, "y")))
1909 self.assertEqual(len(os.listdir(target)), 2)
1910
1911 def test_writestr_dir(self):
Martin v. Löwis59e47792009-01-24 14:10:07 +00001912 os.mkdir(os.path.join(TESTFN2, "x"))
Serhiy Storchaka46a34922014-09-23 22:40:23 +03001913 with zipfile.ZipFile(TESTFN, "w") as zipf:
1914 zipf.writestr("x/", b'')
1915 zinfo = zipf.filelist[0]
1916 self.assertEqual(zinfo.filename, "x/")
1917 self.assertEqual(zinfo.external_attr, (0o40775 << 16) | 0x10)
1918 with zipfile.ZipFile(TESTFN, "r") as zipf:
1919 zinfo = zipf.filelist[0]
1920 self.assertTrue(zinfo.filename.endswith("x/"))
1921 self.assertEqual(zinfo.external_attr, (0o40775 << 16) | 0x10)
1922 target = os.path.join(TESTFN2, "target")
1923 os.mkdir(target)
1924 zipf.extractall(target)
1925 self.assertTrue(os.path.isdir(os.path.join(target, "x")))
1926 self.assertEqual(os.listdir(target), ["x"])
Martin v. Löwis59e47792009-01-24 14:10:07 +00001927
1928 def tearDown(self):
Victor Stinner57004c62014-09-04 00:49:01 +02001929 rmtree(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001930 if os.path.exists(TESTFN):
Ezio Melotti76430242009-07-11 18:28:48 +00001931 unlink(TESTFN)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001932
Guido van Rossumd8faa362007-04-27 19:54:29 +00001933
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001934class AbstractUniversalNewlineTests:
1935 @classmethod
1936 def setUpClass(cls):
1937 cls.line_gen = [bytes("Test of zipfile line %d." % i, "ascii")
1938 for i in range(FIXEDTEST_SIZE)]
1939 cls.seps = (b'\r', b'\r\n', b'\n')
1940 cls.arcdata = {}
1941 for n, s in enumerate(cls.seps):
1942 cls.arcdata[s] = s.join(cls.line_gen) + s
1943
Guido van Rossumd8faa362007-04-27 19:54:29 +00001944 def setUp(self):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001945 self.arcfiles = {}
Guido van Rossumd8faa362007-04-27 19:54:29 +00001946 for n, s in enumerate(self.seps):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001947 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001948 with open(self.arcfiles[s], "wb") as f:
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001949 f.write(self.arcdata[s])
Guido van Rossumd8faa362007-04-27 19:54:29 +00001950
Ezio Melottiafd0d112009-07-15 17:17:17 +00001951 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001952 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001953 with zipfile.ZipFile(f, "w", compression) as zipfp:
1954 for fn in self.arcfiles.values():
1955 zipfp.write(fn, fn)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001956
Ezio Melottiafd0d112009-07-15 17:17:17 +00001957 def read_test(self, f, compression):
1958 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001959
1960 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001961 with zipfile.ZipFile(f, "r") as zipfp:
1962 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02001963 with openU(zipfp, fn) as fp:
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001964 zipdata = fp.read()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001965 self.assertEqual(self.arcdata[sep], zipdata)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001966
1967 def test_read(self):
1968 for f in get_files(self):
1969 self.read_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001970
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001971 def readline_read_test(self, f, compression):
1972 self.make_test_archive(f, compression)
1973
1974 # Read the ZIP archive
Brian Curtin8fb9b862010-11-18 02:15:28 +00001975 with zipfile.ZipFile(f, "r") as zipfp:
1976 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02001977 with openU(zipfp, fn) as zipopen:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001978 data = b''
1979 while True:
1980 read = zipopen.readline()
1981 if not read:
1982 break
1983 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001984
Brian Curtin8fb9b862010-11-18 02:15:28 +00001985 read = zipopen.read(5)
1986 if not read:
1987 break
1988 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001989
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001990 self.assertEqual(data, self.arcdata[b'\n'])
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001991
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001992 def test_readline_read(self):
1993 for f in get_files(self):
1994 self.readline_read_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001995
Ezio Melottiafd0d112009-07-15 17:17:17 +00001996 def readline_test(self, f, compression):
1997 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001998
1999 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00002000 with zipfile.ZipFile(f, "r") as zipfp:
2001 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02002002 with openU(zipfp, fn) as zipopen:
Benjamin Petersond285bdb2010-10-31 17:57:22 +00002003 for line in self.line_gen:
2004 linedata = zipopen.readline()
2005 self.assertEqual(linedata, line + b'\n')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03002006
2007 def test_readline(self):
2008 for f in get_files(self):
2009 self.readline_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002010
Ezio Melottiafd0d112009-07-15 17:17:17 +00002011 def readlines_test(self, f, compression):
2012 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002013
2014 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00002015 with zipfile.ZipFile(f, "r") as zipfp:
2016 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02002017 with openU(zipfp, fn) as fp:
Benjamin Petersond285bdb2010-10-31 17:57:22 +00002018 ziplines = fp.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00002019 for line, zipline in zip(self.line_gen, ziplines):
2020 self.assertEqual(zipline, line + b'\n')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03002021
2022 def test_readlines(self):
2023 for f in get_files(self):
2024 self.readlines_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002025
Ezio Melottiafd0d112009-07-15 17:17:17 +00002026 def iterlines_test(self, f, compression):
2027 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002028
2029 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00002030 with zipfile.ZipFile(f, "r") as zipfp:
2031 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02002032 with openU(zipfp, fn) as fp:
Benjamin Petersond285bdb2010-10-31 17:57:22 +00002033 for line, zipline in zip(self.line_gen, fp):
2034 self.assertEqual(zipline, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00002035
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03002036 def test_iterlines(self):
2037 for f in get_files(self):
2038 self.iterlines_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02002039
Guido van Rossumd8faa362007-04-27 19:54:29 +00002040 def tearDown(self):
2041 for sep, fn in self.arcfiles.items():
Victor Stinner88b215e2014-09-04 00:51:09 +02002042 unlink(fn)
Ezio Melotti76430242009-07-11 18:28:48 +00002043 unlink(TESTFN)
2044 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002045
2046
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03002047class StoredUniversalNewlineTests(AbstractUniversalNewlineTests,
2048 unittest.TestCase):
2049 compression = zipfile.ZIP_STORED
2050
2051@requires_zlib
2052class DeflateUniversalNewlineTests(AbstractUniversalNewlineTests,
2053 unittest.TestCase):
2054 compression = zipfile.ZIP_DEFLATED
2055
2056@requires_bz2
2057class Bzip2UniversalNewlineTests(AbstractUniversalNewlineTests,
2058 unittest.TestCase):
2059 compression = zipfile.ZIP_BZIP2
2060
2061@requires_lzma
2062class LzmaUniversalNewlineTests(AbstractUniversalNewlineTests,
2063 unittest.TestCase):
2064 compression = zipfile.ZIP_LZMA
2065
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00002066if __name__ == "__main__":
Brett Cannond5b4e1d2013-06-12 19:57:19 -04002067 unittest.main()