blob: 8dae2ebbeb0852c7e9457567969eeb867c27536d [file] [log] [blame]
Ezio Melotti74c96ec2009-07-08 22:24:06 +00001import io
2import os
Georg Brandl5ba11de2011-01-01 10:09:32 +00003import sys
Brett Cannonb57a0852013-06-15 17:32:30 -04004import importlib.util
Ezio Melotti35386712009-12-31 13:22:41 +00005import time
Ezio Melotti74c96ec2009-07-08 22:24:06 +00006import struct
7import zipfile
8import unittest
9
Tim Petersa45cacf2004-08-20 03:47:14 +000010
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000011from tempfile import TemporaryFile
Serhiy Storchakafa6bc292013-07-22 21:00:11 +030012from random import randint, random, getrandbits
Tim Petersa19a1682001-03-29 04:36:09 +000013
Victor Stinner57004c62014-09-04 00:49:01 +020014from test.support import (TESTFN, findfile, unlink, rmtree,
Serhiy Storchakac5b75db2013-01-29 20:14:08 +020015 requires_zlib, requires_bz2, requires_lzma,
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +020016 captured_stdout, check_warnings)
Guido van Rossum368f04a2000-04-10 13:23:04 +000017
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000018TESTFN2 = TESTFN + "2"
Martin v. Löwis59e47792009-01-24 14:10:07 +000019TESTFNDIR = TESTFN + "d"
Guido van Rossumb5a755e2007-07-18 18:15:48 +000020FIXEDTEST_SIZE = 1000
Georg Brandl5ba11de2011-01-01 10:09:32 +000021DATAFILES_DIR = 'zipfile_datafiles'
Guido van Rossum368f04a2000-04-10 13:23:04 +000022
Christian Heimes790c8232008-01-07 21:14:23 +000023SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'),
24 ('ziptest2dir/_ziptest2', 'qawsedrftg'),
Gregory P. Smithb47acbf2013-02-01 11:22:43 -080025 ('ziptest2dir/ziptest3dir/_ziptest3', 'azsxdcfvgb'),
Christian Heimes790c8232008-01-07 21:14:23 +000026 ('ziptest2dir/ziptest3dir/ziptest4dir/_ziptest3', '6y7u8i9o0p')]
27
Serhiy Storchakafa6bc292013-07-22 21:00:11 +030028def get_files(test):
29 yield TESTFN2
30 with TemporaryFile() as f:
31 yield f
32 test.assertFalse(f.closed)
33 with io.BytesIO() as f:
34 yield f
35 test.assertFalse(f.closed)
Ezio Melotti76430242009-07-11 18:28:48 +000036
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +020037def openU(zipfp, fn):
38 with check_warnings(('', DeprecationWarning)):
39 return zipfp.open(fn, 'rU')
40
Serhiy Storchakafa6bc292013-07-22 21:00:11 +030041class AbstractTestsWithSourceFile:
42 @classmethod
43 def setUpClass(cls):
44 cls.line_gen = [bytes("Zipfile test line %d. random float: %f\n" %
45 (i, random()), "ascii")
46 for i in range(FIXEDTEST_SIZE)]
47 cls.data = b''.join(cls.line_gen)
48
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000049 def setUp(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000050 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +000051 with open(TESTFN, "wb") as fp:
52 fp.write(self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000053
Ezio Melottiafd0d112009-07-15 17:17:17 +000054 def make_test_archive(self, f, compression):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000055 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000056 with zipfile.ZipFile(f, "w", compression) as zipfp:
57 zipfp.write(TESTFN, "another.name")
58 zipfp.write(TESTFN, TESTFN)
59 zipfp.writestr("strfile", self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000060
Ezio Melottiafd0d112009-07-15 17:17:17 +000061 def zip_test(self, f, compression):
62 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +000063
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000064 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000065 with zipfile.ZipFile(f, "r", compression) as zipfp:
66 self.assertEqual(zipfp.read(TESTFN), self.data)
67 self.assertEqual(zipfp.read("another.name"), self.data)
68 self.assertEqual(zipfp.read("strfile"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000069
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000070 # Print the ZIP directory
71 fp = io.StringIO()
72 zipfp.printdir(file=fp)
73 directory = fp.getvalue()
74 lines = directory.splitlines()
Ezio Melotti35386712009-12-31 13:22:41 +000075 self.assertEqual(len(lines), 4) # Number of files + header
Thomas Wouters0e3f5912006-08-11 14:57:12 +000076
Benjamin Peterson577473f2010-01-19 00:09:57 +000077 self.assertIn('File Name', lines[0])
78 self.assertIn('Modified', lines[0])
79 self.assertIn('Size', lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +000080
Ezio Melotti35386712009-12-31 13:22:41 +000081 fn, date, time_, size = lines[1].split()
82 self.assertEqual(fn, 'another.name')
83 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
84 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
85 self.assertEqual(size, str(len(self.data)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000086
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000087 # Check the namelist
88 names = zipfp.namelist()
Ezio Melotti35386712009-12-31 13:22:41 +000089 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +000090 self.assertIn(TESTFN, names)
91 self.assertIn("another.name", names)
92 self.assertIn("strfile", names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000093
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000094 # Check infolist
95 infos = zipfp.infolist()
Ezio Melotti35386712009-12-31 13:22:41 +000096 names = [i.filename for i in infos]
97 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +000098 self.assertIn(TESTFN, names)
99 self.assertIn("another.name", names)
100 self.assertIn("strfile", names)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000101 for i in infos:
Ezio Melotti35386712009-12-31 13:22:41 +0000102 self.assertEqual(i.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000103
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000104 # check getinfo
105 for nm in (TESTFN, "another.name", "strfile"):
106 info = zipfp.getinfo(nm)
Ezio Melotti35386712009-12-31 13:22:41 +0000107 self.assertEqual(info.filename, nm)
108 self.assertEqual(info.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000109
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000110 # Check that testzip doesn't raise an exception
111 zipfp.testzip()
Tim Peters7d3bad62001-04-04 18:56:49 +0000112
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300113 def test_basic(self):
114 for f in get_files(self):
115 self.zip_test(f, self.compression)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000116
Ezio Melottiafd0d112009-07-15 17:17:17 +0000117 def zip_open_test(self, f, compression):
118 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000119
120 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000121 with zipfile.ZipFile(f, "r", compression) as zipfp:
122 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000123 with zipfp.open(TESTFN) as zipopen1:
124 while True:
125 read_data = zipopen1.read(256)
126 if not read_data:
127 break
128 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000129
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000130 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000131 with zipfp.open("another.name") as zipopen2:
132 while True:
133 read_data = zipopen2.read(256)
134 if not read_data:
135 break
136 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000137
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000138 self.assertEqual(b''.join(zipdata1), self.data)
139 self.assertEqual(b''.join(zipdata2), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000140
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300141 def test_open(self):
142 for f in get_files(self):
143 self.zip_open_test(f, self.compression)
Georg Brandlb533e262008-05-25 18:19:30 +0000144
Ezio Melottiafd0d112009-07-15 17:17:17 +0000145 def zip_random_open_test(self, f, compression):
146 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000147
148 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000149 with zipfile.ZipFile(f, "r", compression) as zipfp:
150 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000151 with zipfp.open(TESTFN) as zipopen1:
152 while True:
153 read_data = zipopen1.read(randint(1, 1024))
154 if not read_data:
155 break
156 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000157
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000158 self.assertEqual(b''.join(zipdata1), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000159
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300160 def test_random_open(self):
161 for f in get_files(self):
162 self.zip_random_open_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000163
Serhiy Storchakad2c07a52013-09-27 22:11:57 +0300164 def zip_read1_test(self, f, compression):
165 self.make_test_archive(f, compression)
166
167 # Read the ZIP archive
168 with zipfile.ZipFile(f, "r") as zipfp, \
169 zipfp.open(TESTFN) as zipopen:
170 zipdata = []
171 while True:
172 read_data = zipopen.read1(-1)
173 if not read_data:
174 break
175 zipdata.append(read_data)
176
177 self.assertEqual(b''.join(zipdata), self.data)
178
179 def test_read1(self):
180 for f in get_files(self):
181 self.zip_read1_test(f, self.compression)
182
183 def zip_read1_10_test(self, f, compression):
184 self.make_test_archive(f, compression)
185
186 # Read the ZIP archive
187 with zipfile.ZipFile(f, "r") as zipfp, \
188 zipfp.open(TESTFN) as zipopen:
189 zipdata = []
190 while True:
191 read_data = zipopen.read1(10)
192 self.assertLessEqual(len(read_data), 10)
193 if not read_data:
194 break
195 zipdata.append(read_data)
196
197 self.assertEqual(b''.join(zipdata), self.data)
198
199 def test_read1_10(self):
200 for f in get_files(self):
201 self.zip_read1_10_test(f, self.compression)
202
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000203 def zip_readline_read_test(self, f, compression):
204 self.make_test_archive(f, compression)
205
206 # Read the ZIP archive
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300207 with zipfile.ZipFile(f, "r") as zipfp, \
208 zipfp.open(TESTFN) as zipopen:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000209 data = b''
210 while True:
211 read = zipopen.readline()
212 if not read:
213 break
214 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000215
Brian Curtin8fb9b862010-11-18 02:15:28 +0000216 read = zipopen.read(100)
217 if not read:
218 break
219 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000220
221 self.assertEqual(data, self.data)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300222
223 def test_readline_read(self):
224 # Issue #7610: calls to readline() interleaved with calls to read().
225 for f in get_files(self):
226 self.zip_readline_read_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000227
Ezio Melottiafd0d112009-07-15 17:17:17 +0000228 def zip_readline_test(self, f, compression):
229 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000230
231 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000232 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000233 with zipfp.open(TESTFN) as zipopen:
234 for line in self.line_gen:
235 linedata = zipopen.readline()
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300236 self.assertEqual(linedata, line)
237
238 def test_readline(self):
239 for f in get_files(self):
240 self.zip_readline_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000241
Ezio Melottiafd0d112009-07-15 17:17:17 +0000242 def zip_readlines_test(self, f, compression):
243 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000244
245 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000246 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000247 with zipfp.open(TESTFN) as zipopen:
248 ziplines = zipopen.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000249 for line, zipline in zip(self.line_gen, ziplines):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300250 self.assertEqual(zipline, line)
251
252 def test_readlines(self):
253 for f in get_files(self):
254 self.zip_readlines_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000255
Ezio Melottiafd0d112009-07-15 17:17:17 +0000256 def zip_iterlines_test(self, f, compression):
257 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000258
259 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000260 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000261 with zipfp.open(TESTFN) as zipopen:
262 for line, zipline in zip(self.line_gen, zipopen):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300263 self.assertEqual(zipline, line)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000264
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300265 def test_iterlines(self):
266 for f in get_files(self):
267 self.zip_iterlines_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000268
Ezio Melottiafd0d112009-07-15 17:17:17 +0000269 def test_low_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000270 """Check for cases where compressed data is larger than original."""
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000271 # Create the ZIP archive
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300272 with zipfile.ZipFile(TESTFN2, "w", self.compression) as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000273 zipfp.writestr("strfile", '12')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000274
275 # Get an open object for strfile
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300276 with zipfile.ZipFile(TESTFN2, "r", self.compression) as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000277 with zipfp.open("strfile") as openobj:
278 self.assertEqual(openobj.read(1), b'1')
279 self.assertEqual(openobj.read(1), b'2')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000280
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300281 def test_writestr_compression(self):
282 zipfp = zipfile.ZipFile(TESTFN2, "w")
283 zipfp.writestr("b.txt", "hello world", compress_type=self.compression)
284 info = zipfp.getinfo('b.txt')
285 self.assertEqual(info.compress_type, self.compression)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200286
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300287 def test_read_return_size(self):
288 # Issue #9837: ZipExtFile.read() shouldn't return more bytes
289 # than requested.
290 for test_size in (1, 4095, 4096, 4097, 16384):
291 file_size = test_size + 1
292 junk = getrandbits(8 * file_size).to_bytes(file_size, 'little')
293 with zipfile.ZipFile(io.BytesIO(), "w", self.compression) as zipf:
294 zipf.writestr('foo', junk)
295 with zipf.open('foo', 'r') as fp:
296 buf = fp.read(test_size)
297 self.assertEqual(len(buf), test_size)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200298
Serhiy Storchaka5ce3f102014-01-09 14:50:20 +0200299 def test_truncated_zipfile(self):
300 fp = io.BytesIO()
301 with zipfile.ZipFile(fp, mode='w') as zipf:
302 zipf.writestr('strfile', self.data, compress_type=self.compression)
303 end_offset = fp.tell()
304 zipfiledata = fp.getvalue()
305
306 fp = io.BytesIO(zipfiledata)
307 with zipfile.ZipFile(fp) as zipf:
308 with zipf.open('strfile') as zipopen:
309 fp.truncate(end_offset - 20)
310 with self.assertRaises(EOFError):
311 zipopen.read()
312
313 fp = io.BytesIO(zipfiledata)
314 with zipfile.ZipFile(fp) as zipf:
315 with zipf.open('strfile') as zipopen:
316 fp.truncate(end_offset - 20)
317 with self.assertRaises(EOFError):
318 while zipopen.read(100):
319 pass
320
321 fp = io.BytesIO(zipfiledata)
322 with zipfile.ZipFile(fp) as zipf:
323 with zipf.open('strfile') as zipopen:
324 fp.truncate(end_offset - 20)
325 with self.assertRaises(EOFError):
326 while zipopen.read1(100):
327 pass
328
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300329 def tearDown(self):
330 unlink(TESTFN)
331 unlink(TESTFN2)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200332
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200333
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300334class StoredTestsWithSourceFile(AbstractTestsWithSourceFile,
335 unittest.TestCase):
336 compression = zipfile.ZIP_STORED
337 test_low_compression = None
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200338
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300339 def zip_test_writestr_permissions(self, f, compression):
340 # Make sure that writestr creates files with mode 0600,
341 # when it is passed a name rather than a ZipInfo instance.
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200342
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300343 self.make_test_archive(f, compression)
344 with zipfile.ZipFile(f, "r") as zipfp:
345 zinfo = zipfp.getinfo('strfile')
346 self.assertEqual(zinfo.external_attr, 0o600 << 16)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200347
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300348 def test_writestr_permissions(self):
349 for f in get_files(self):
350 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +0200351
Ezio Melottiafd0d112009-07-15 17:17:17 +0000352 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000353 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
354 zipfp.write(TESTFN, "/absolute")
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000355
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000356 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
357 self.assertEqual(zipfp.namelist(), ["absolute"])
Tim Peters32cbc962006-02-20 21:42:18 +0000358
Ezio Melottiafd0d112009-07-15 17:17:17 +0000359 def test_append_to_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000360 """Test appending to an existing zipfile."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000361 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
362 zipfp.write(TESTFN, TESTFN)
363
364 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
365 zipfp.writestr("strfile", self.data)
366 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000367
Ezio Melottiafd0d112009-07-15 17:17:17 +0000368 def test_append_to_non_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000369 """Test appending to an existing file that is not a zipfile."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000370 # NOTE: this test fails if len(d) < 22 because of the first
371 # line "fpin.seek(-22, 2)" in _EndRecData
Ezio Melotti35386712009-12-31 13:22:41 +0000372 data = b'I am not a ZipFile!'*10
373 with open(TESTFN2, 'wb') as f:
374 f.write(data)
375
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000376 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
377 zipfp.write(TESTFN, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000378
Ezio Melotti35386712009-12-31 13:22:41 +0000379 with open(TESTFN2, 'rb') as f:
380 f.seek(len(data))
381 with zipfile.ZipFile(f, "r") as zipfp:
382 self.assertEqual(zipfp.namelist(), [TESTFN])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000383
R David Murray4fbb9db2011-06-09 15:50:51 -0400384 def test_ignores_newline_at_end(self):
385 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
386 zipfp.write(TESTFN, TESTFN)
387 with open(TESTFN2, 'a') as f:
388 f.write("\r\n\00\00\00")
389 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
390 self.assertIsInstance(zipfp, zipfile.ZipFile)
391
392 def test_ignores_stuff_appended_past_comments(self):
393 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
394 zipfp.comment = b"this is a comment"
395 zipfp.write(TESTFN, TESTFN)
396 with open(TESTFN2, 'a') as f:
397 f.write("abcdef\r\n")
398 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
399 self.assertIsInstance(zipfp, zipfile.ZipFile)
400 self.assertEqual(zipfp.comment, b"this is a comment")
401
Ezio Melottiafd0d112009-07-15 17:17:17 +0000402 def test_write_default_name(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000403 """Check that calling ZipFile.write without arcname specified
404 produces the expected result."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000405 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
406 zipfp.write(TESTFN)
Brian Curtin8fb9b862010-11-18 02:15:28 +0000407 with open(TESTFN, "rb") as f:
408 self.assertEqual(zipfp.read(TESTFN), f.read())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000409
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300410 def test_write_to_readonly(self):
411 """Check that trying to call write() on a readonly ZipFile object
412 raises a RuntimeError."""
413 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
414 zipfp.writestr("somefile.txt", "bogus")
415
416 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
417 self.assertRaises(RuntimeError, zipfp.write, TESTFN)
418
419 def test_add_file_before_1980(self):
420 # Set atime and mtime to 1970-01-01
421 os.utime(TESTFN, (0, 0))
422 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
423 self.assertRaises(ValueError, zipfp.write, TESTFN)
424
Serhiy Storchaka5ce3f102014-01-09 14:50:20 +0200425
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300426@requires_zlib
427class DeflateTestsWithSourceFile(AbstractTestsWithSourceFile,
428 unittest.TestCase):
429 compression = zipfile.ZIP_DEFLATED
430
Ezio Melottiafd0d112009-07-15 17:17:17 +0000431 def test_per_file_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000432 """Check that files within a Zip archive can have different
433 compression options."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000434 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
435 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
436 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
437 sinfo = zipfp.getinfo('storeme')
438 dinfo = zipfp.getinfo('deflateme')
439 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
440 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000441
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300442@requires_bz2
443class Bzip2TestsWithSourceFile(AbstractTestsWithSourceFile,
444 unittest.TestCase):
445 compression = zipfile.ZIP_BZIP2
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000446
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300447@requires_lzma
448class LzmaTestsWithSourceFile(AbstractTestsWithSourceFile,
449 unittest.TestCase):
450 compression = zipfile.ZIP_LZMA
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000451
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300452
453class AbstractTestZip64InSmallFiles:
454 # These tests test the ZIP64 functionality without using large files,
455 # see test_zipfile64 for proper tests.
456
457 @classmethod
458 def setUpClass(cls):
459 line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
460 for i in range(0, FIXEDTEST_SIZE))
461 cls.data = b'\n'.join(line_gen)
462
463 def setUp(self):
464 self._limit = zipfile.ZIP64_LIMIT
465 zipfile.ZIP64_LIMIT = 5
466
467 # Make a source file with some lines
468 with open(TESTFN, "wb") as fp:
469 fp.write(self.data)
470
471 def zip_test(self, f, compression):
472 # Create the ZIP archive
473 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
474 zipfp.write(TESTFN, "another.name")
475 zipfp.write(TESTFN, TESTFN)
476 zipfp.writestr("strfile", self.data)
477
478 # Read the ZIP archive
479 with zipfile.ZipFile(f, "r", compression) as zipfp:
480 self.assertEqual(zipfp.read(TESTFN), self.data)
481 self.assertEqual(zipfp.read("another.name"), self.data)
482 self.assertEqual(zipfp.read("strfile"), self.data)
483
484 # Print the ZIP directory
485 fp = io.StringIO()
486 zipfp.printdir(fp)
487
488 directory = fp.getvalue()
489 lines = directory.splitlines()
490 self.assertEqual(len(lines), 4) # Number of files + header
491
492 self.assertIn('File Name', lines[0])
493 self.assertIn('Modified', lines[0])
494 self.assertIn('Size', lines[0])
495
496 fn, date, time_, size = lines[1].split()
497 self.assertEqual(fn, 'another.name')
498 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
499 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
500 self.assertEqual(size, str(len(self.data)))
501
502 # Check the namelist
503 names = zipfp.namelist()
504 self.assertEqual(len(names), 3)
505 self.assertIn(TESTFN, names)
506 self.assertIn("another.name", names)
507 self.assertIn("strfile", names)
508
509 # Check infolist
510 infos = zipfp.infolist()
511 names = [i.filename for i in infos]
512 self.assertEqual(len(names), 3)
513 self.assertIn(TESTFN, names)
514 self.assertIn("another.name", names)
515 self.assertIn("strfile", names)
516 for i in infos:
517 self.assertEqual(i.file_size, len(self.data))
518
519 # check getinfo
520 for nm in (TESTFN, "another.name", "strfile"):
521 info = zipfp.getinfo(nm)
522 self.assertEqual(info.filename, nm)
523 self.assertEqual(info.file_size, len(self.data))
524
525 # Check that testzip doesn't raise an exception
526 zipfp.testzip()
527
528 def test_basic(self):
529 for f in get_files(self):
530 self.zip_test(f, self.compression)
531
532 def tearDown(self):
533 zipfile.ZIP64_LIMIT = self._limit
534 unlink(TESTFN)
535 unlink(TESTFN2)
536
537
538class StoredTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
539 unittest.TestCase):
540 compression = zipfile.ZIP_STORED
541
542 def large_file_exception_test(self, f, compression):
Serhiy Storchaka235c5e02013-11-23 15:55:38 +0200543 with zipfile.ZipFile(f, "w", compression, allowZip64=False) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300544 self.assertRaises(zipfile.LargeZipFile,
545 zipfp.write, TESTFN, "another.name")
546
547 def large_file_exception_test2(self, f, compression):
Serhiy Storchaka235c5e02013-11-23 15:55:38 +0200548 with zipfile.ZipFile(f, "w", compression, allowZip64=False) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300549 self.assertRaises(zipfile.LargeZipFile,
550 zipfp.writestr, "another.name", self.data)
551
552 def test_large_file_exception(self):
553 for f in get_files(self):
554 self.large_file_exception_test(f, zipfile.ZIP_STORED)
555 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
556
557 def test_absolute_arcnames(self):
558 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
559 allowZip64=True) as zipfp:
560 zipfp.write(TESTFN, "/absolute")
561
562 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
563 self.assertEqual(zipfp.namelist(), ["absolute"])
564
565@requires_zlib
566class DeflateTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
567 unittest.TestCase):
568 compression = zipfile.ZIP_DEFLATED
569
570@requires_bz2
571class Bzip2TestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
572 unittest.TestCase):
573 compression = zipfile.ZIP_BZIP2
574
575@requires_lzma
576class LzmaTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
577 unittest.TestCase):
578 compression = zipfile.ZIP_LZMA
579
580
581class PyZipFileTests(unittest.TestCase):
582 def assertCompiledIn(self, name, namelist):
583 if name + 'o' not in namelist:
584 self.assertIn(name + 'c', namelist)
585
586 def test_write_pyfile(self):
587 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
588 fn = __file__
589 if fn.endswith('.pyc') or fn.endswith('.pyo'):
590 path_split = fn.split(os.sep)
591 if os.altsep is not None:
592 path_split.extend(fn.split(os.altsep))
593 if '__pycache__' in path_split:
Serhiy Storchaka9068e4d2013-07-22 21:02:14 +0300594 fn = importlib.util.source_from_cache(fn)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300595 else:
596 fn = fn[:-1]
597
598 zipfp.writepy(fn)
599
600 bn = os.path.basename(fn)
601 self.assertNotIn(bn, zipfp.namelist())
602 self.assertCompiledIn(bn, zipfp.namelist())
603
604 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
605 fn = __file__
606 if fn.endswith(('.pyc', '.pyo')):
607 fn = fn[:-1]
608
609 zipfp.writepy(fn, "testpackage")
610
611 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
612 self.assertNotIn(bn, zipfp.namelist())
613 self.assertCompiledIn(bn, zipfp.namelist())
614
615 def test_write_python_package(self):
616 import email
617 packagedir = os.path.dirname(email.__file__)
618
619 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
620 zipfp.writepy(packagedir)
621
622 # Check for a couple of modules at different levels of the
623 # hierarchy
624 names = zipfp.namelist()
625 self.assertCompiledIn('email/__init__.py', names)
626 self.assertCompiledIn('email/mime/text.py', names)
627
Christian Tismer59202e52013-10-21 03:59:23 +0200628 def test_write_filtered_python_package(self):
629 import test
630 packagedir = os.path.dirname(test.__file__)
631
632 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
633
Christian Tismer59202e52013-10-21 03:59:23 +0200634 # first make sure that the test folder gives error messages
Georg Brandla6065422013-10-21 08:29:29 +0200635 # (on the badsyntax_... files)
636 with captured_stdout() as reportSIO:
637 zipfp.writepy(packagedir)
Christian Tismer59202e52013-10-21 03:59:23 +0200638 reportStr = reportSIO.getvalue()
639 self.assertTrue('SyntaxError' in reportStr)
640
Christian Tismer410d9312013-10-22 04:09:28 +0200641 # then check that the filter works on the whole package
Georg Brandla6065422013-10-21 08:29:29 +0200642 with captured_stdout() as reportSIO:
643 zipfp.writepy(packagedir, filterfunc=lambda whatever: False)
Christian Tismer59202e52013-10-21 03:59:23 +0200644 reportStr = reportSIO.getvalue()
645 self.assertTrue('SyntaxError' not in reportStr)
646
Christian Tismer410d9312013-10-22 04:09:28 +0200647 # then check that the filter works on individual files
Serhiy Storchakac46d1fa2014-01-20 21:59:33 +0200648 with captured_stdout() as reportSIO, self.assertWarns(UserWarning):
Christian Tismer410d9312013-10-22 04:09:28 +0200649 zipfp.writepy(packagedir, filterfunc=lambda fn:
650 'bad' not in fn)
651 reportStr = reportSIO.getvalue()
652 if reportStr:
653 print(reportStr)
654 self.assertTrue('SyntaxError' not in reportStr)
655
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300656 def test_write_with_optimization(self):
657 import email
658 packagedir = os.path.dirname(email.__file__)
659 # use .pyc if running test in optimization mode,
660 # use .pyo if running test in debug mode
661 optlevel = 1 if __debug__ else 0
662 ext = '.pyo' if optlevel == 1 else '.pyc'
663
664 with TemporaryFile() as t, \
Christian Tismer59202e52013-10-21 03:59:23 +0200665 zipfile.PyZipFile(t, "w", optimize=optlevel) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300666 zipfp.writepy(packagedir)
667
668 names = zipfp.namelist()
669 self.assertIn('email/__init__' + ext, names)
670 self.assertIn('email/mime/text' + ext, names)
671
672 def test_write_python_directory(self):
673 os.mkdir(TESTFN2)
674 try:
675 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
676 fp.write("print(42)\n")
677
678 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
679 fp.write("print(42 * 42)\n")
680
681 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
682 fp.write("bla bla bla\n")
683
684 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
685 zipfp.writepy(TESTFN2)
686
687 names = zipfp.namelist()
688 self.assertCompiledIn('mod1.py', names)
689 self.assertCompiledIn('mod2.py', names)
690 self.assertNotIn('mod2.txt', names)
691
692 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200693 rmtree(TESTFN2)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300694
Christian Tismer410d9312013-10-22 04:09:28 +0200695 def test_write_python_directory_filtered(self):
696 os.mkdir(TESTFN2)
697 try:
698 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
699 fp.write("print(42)\n")
700
701 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
702 fp.write("print(42 * 42)\n")
703
704 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
705 zipfp.writepy(TESTFN2, filterfunc=lambda fn:
706 not fn.endswith('mod2.py'))
707
708 names = zipfp.namelist()
709 self.assertCompiledIn('mod1.py', names)
710 self.assertNotIn('mod2.py', names)
711
712 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200713 rmtree(TESTFN2)
Christian Tismer410d9312013-10-22 04:09:28 +0200714
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300715 def test_write_non_pyfile(self):
716 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
717 with open(TESTFN, 'w') as f:
718 f.write('most definitely not a python file')
719 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
Victor Stinner88b215e2014-09-04 00:51:09 +0200720 unlink(TESTFN)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300721
722 def test_write_pyfile_bad_syntax(self):
723 os.mkdir(TESTFN2)
724 try:
725 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
726 fp.write("Bad syntax in python file\n")
727
728 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
729 # syntax errors are printed to stdout
730 with captured_stdout() as s:
731 zipfp.writepy(os.path.join(TESTFN2, "mod1.py"))
732
733 self.assertIn("SyntaxError", s.getvalue())
734
735 # as it will not have compiled the python file, it will
736 # include the .py file not .pyc or .pyo
737 names = zipfp.namelist()
738 self.assertIn('mod1.py', names)
739 self.assertNotIn('mod1.pyc', names)
740 self.assertNotIn('mod1.pyo', names)
741
742 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200743 rmtree(TESTFN2)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300744
745
746class ExtractTests(unittest.TestCase):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000747 def test_extract(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000748 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
749 for fpath, fdata in SMALL_TEST_DATA:
750 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000751
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000752 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
753 for fpath, fdata in SMALL_TEST_DATA:
754 writtenfile = zipfp.extract(fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000755
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000756 # make sure it was written to the right place
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800757 correctfile = os.path.join(os.getcwd(), fpath)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000758 correctfile = os.path.normpath(correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000759
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000760 self.assertEqual(writtenfile, correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000761
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000762 # make sure correct data is in correct file
Brian Curtin8fb9b862010-11-18 02:15:28 +0000763 with open(writtenfile, "rb") as f:
764 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000765
Victor Stinner88b215e2014-09-04 00:51:09 +0200766 unlink(writtenfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000767
768 # remove the test file subdirectories
Victor Stinner57004c62014-09-04 00:49:01 +0200769 rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
Christian Heimes790c8232008-01-07 21:14:23 +0000770
Ezio Melottiafd0d112009-07-15 17:17:17 +0000771 def test_extract_all(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000772 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
773 for fpath, fdata in SMALL_TEST_DATA:
774 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000775
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000776 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
777 zipfp.extractall()
778 for fpath, fdata in SMALL_TEST_DATA:
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800779 outfile = os.path.join(os.getcwd(), fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000780
Brian Curtin8fb9b862010-11-18 02:15:28 +0000781 with open(outfile, "rb") as f:
782 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000783
Victor Stinner88b215e2014-09-04 00:51:09 +0200784 unlink(outfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000785
786 # remove the test file subdirectories
Victor Stinner57004c62014-09-04 00:49:01 +0200787 rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
Christian Heimes790c8232008-01-07 21:14:23 +0000788
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800789 def check_file(self, filename, content):
790 self.assertTrue(os.path.isfile(filename))
791 with open(filename, 'rb') as f:
792 self.assertEqual(f.read(), content)
793
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800794 def test_sanitize_windows_name(self):
795 san = zipfile.ZipFile._sanitize_windows_name
796 # Passing pathsep in allows this test to work regardless of platform.
797 self.assertEqual(san(r',,?,C:,foo,bar/z', ','), r'_,C_,foo,bar/z')
798 self.assertEqual(san(r'a\b,c<d>e|f"g?h*i', ','), r'a\b,c_d_e_f_g_h_i')
799 self.assertEqual(san('../../foo../../ba..r', '/'), r'foo/ba..r')
800
801 def test_extract_hackers_arcnames_common_cases(self):
802 common_hacknames = [
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800803 ('../foo/bar', 'foo/bar'),
804 ('foo/../bar', 'foo/bar'),
805 ('foo/../../bar', 'foo/bar'),
806 ('foo/bar/..', 'foo/bar'),
807 ('./../foo/bar', 'foo/bar'),
808 ('/foo/bar', 'foo/bar'),
809 ('/foo/../bar', 'foo/bar'),
810 ('/foo/../../bar', 'foo/bar'),
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800811 ]
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800812 self._test_extract_hackers_arcnames(common_hacknames)
813
814 @unittest.skipIf(os.path.sep != '\\', 'Requires \\ as path separator.')
815 def test_extract_hackers_arcnames_windows_only(self):
816 """Test combination of path fixing and windows name sanitization."""
817 windows_hacknames = [
Christian Tismer59202e52013-10-21 03:59:23 +0200818 (r'..\foo\bar', 'foo/bar'),
819 (r'..\/foo\/bar', 'foo/bar'),
820 (r'foo/\..\/bar', 'foo/bar'),
821 (r'foo\/../\bar', 'foo/bar'),
822 (r'C:foo/bar', 'foo/bar'),
823 (r'C:/foo/bar', 'foo/bar'),
824 (r'C://foo/bar', 'foo/bar'),
825 (r'C:\foo\bar', 'foo/bar'),
826 (r'//conky/mountpoint/foo/bar', 'foo/bar'),
827 (r'\\conky\mountpoint\foo\bar', 'foo/bar'),
828 (r'///conky/mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
829 (r'\\\conky\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
830 (r'//conky//mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
831 (r'\\conky\\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
832 (r'//?/C:/foo/bar', 'foo/bar'),
833 (r'\\?\C:\foo\bar', 'foo/bar'),
834 (r'C:/../C:/foo/bar', 'C_/foo/bar'),
835 (r'a:b\c<d>e|f"g?h*i', 'b/c_d_e_f_g_h_i'),
836 ('../../foo../../ba..r', 'foo/ba..r'),
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800837 ]
838 self._test_extract_hackers_arcnames(windows_hacknames)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800839
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800840 @unittest.skipIf(os.path.sep != '/', r'Requires / as path separator.')
841 def test_extract_hackers_arcnames_posix_only(self):
842 posix_hacknames = [
843 ('//foo/bar', 'foo/bar'),
844 ('../../foo../../ba..r', 'foo../ba..r'),
845 (r'foo/..\bar', r'foo/..\bar'),
846 ]
847 self._test_extract_hackers_arcnames(posix_hacknames)
848
849 def _test_extract_hackers_arcnames(self, hacknames):
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800850 for arcname, fixedname in hacknames:
851 content = b'foobar' + arcname.encode()
852 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipfp:
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200853 zinfo = zipfile.ZipInfo()
854 # preserve backslashes
855 zinfo.filename = arcname
856 zinfo.external_attr = 0o600 << 16
857 zipfp.writestr(zinfo, content)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800858
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200859 arcname = arcname.replace(os.sep, "/")
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800860 targetpath = os.path.join('target', 'subdir', 'subsub')
861 correctfile = os.path.join(targetpath, *fixedname.split('/'))
862
863 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
864 writtenfile = zipfp.extract(arcname, targetpath)
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200865 self.assertEqual(writtenfile, correctfile,
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800866 msg='extract %r: %r != %r' %
867 (arcname, writtenfile, correctfile))
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800868 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +0200869 rmtree('target')
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800870
871 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
872 zipfp.extractall(targetpath)
873 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +0200874 rmtree('target')
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800875
876 correctfile = os.path.join(os.getcwd(), *fixedname.split('/'))
877
878 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
879 writtenfile = zipfp.extract(arcname)
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200880 self.assertEqual(writtenfile, correctfile,
881 msg="extract %r" % arcname)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800882 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +0200883 rmtree(fixedname.split('/')[0])
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800884
885 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
886 zipfp.extractall()
887 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +0200888 rmtree(fixedname.split('/')[0])
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800889
Victor Stinner88b215e2014-09-04 00:51:09 +0200890 unlink(TESTFN2)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800891
Ronald Oussorenee5c8852010-02-07 20:24:02 +0000892
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300893class OtherTests(unittest.TestCase):
894 def test_open_via_zip_info(self):
895 # Create the ZIP archive
896 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
897 zipfp.writestr("name", "foo")
Serhiy Storchaka9b7a1a12014-01-20 21:57:40 +0200898 with self.assertWarns(UserWarning):
899 zipfp.writestr("name", "bar")
900 self.assertEqual(zipfp.namelist(), ["name"] * 2)
Ronald Oussorenee5c8852010-02-07 20:24:02 +0000901
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300902 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
903 infos = zipfp.infolist()
904 data = b""
905 for info in infos:
906 with zipfp.open(info) as zipopen:
907 data += zipopen.read()
908 self.assertIn(data, {b"foobar", b"barfoo"})
909 data = b""
910 for info in infos:
911 data += zipfp.read(info)
912 self.assertIn(data, {b"foobar", b"barfoo"})
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200913
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +0200914 def test_universal_deprecation(self):
915 f = io.BytesIO()
916 with zipfile.ZipFile(f, "w") as zipfp:
917 zipfp.writestr('spam.txt', b'ababagalamaga')
918
919 with zipfile.ZipFile(f, "r") as zipfp:
920 for mode in 'U', 'rU':
921 with self.assertWarns(DeprecationWarning):
922 zipopen = zipfp.open('spam.txt', mode)
923 zipopen.close()
924
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300925 def test_universal_readaheads(self):
926 f = io.BytesIO()
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +0200927
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300928 data = b'a\r\n' * 16 * 1024
929 with zipfile.ZipFile(f, 'w', zipfile.ZIP_STORED) as zipfp:
930 zipfp.writestr(TESTFN, data)
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000931
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300932 data2 = b''
933 with zipfile.ZipFile(f, 'r') as zipfp, \
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +0200934 openU(zipfp, TESTFN) as zipopen:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300935 for line in zipopen:
936 data2 += line
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000937
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300938 self.assertEqual(data, data2.replace(b'\n', b'\r\n'))
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000939
Gregory P. Smithb0d9ca922009-07-07 05:06:04 +0000940 def test_writestr_extended_local_header_issue1202(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000941 with zipfile.ZipFile(TESTFN2, 'w') as orig_zip:
942 for data in 'abcdefghijklmnop':
943 zinfo = zipfile.ZipInfo(data)
944 zinfo.flag_bits |= 0x08 # Include an extended local header.
945 orig_zip.writestr(zinfo, data)
946
947 def test_close(self):
948 """Check that the zipfile is closed after the 'with' block."""
949 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
950 for fpath, fdata in SMALL_TEST_DATA:
951 zipfp.writestr(fpath, fdata)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300952 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
953 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000954
955 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300956 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
957 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000958
959 def test_close_on_exception(self):
960 """Check that the zipfile is closed if an exception is raised in the
961 'with' block."""
962 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
963 for fpath, fdata in SMALL_TEST_DATA:
964 zipfp.writestr(fpath, fdata)
965
966 try:
967 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
Georg Brandl4d540882010-10-28 06:42:33 +0000968 raise zipfile.BadZipFile()
969 except zipfile.BadZipFile:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300970 self.assertIsNone(zipfp2.fp, 'zipfp is not closed')
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000971
Martin v. Löwisd099b562012-05-01 14:08:22 +0200972 def test_unsupported_version(self):
973 # File has an extract_version of 120
974 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 +0200975 b'\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00xPK\x01\x02x\x03x\x00\x00\x00\x00'
976 b'\x00!p\xa1@\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00'
977 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00\x00xPK\x05\x06'
978 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 +0300979
Martin v. Löwisd099b562012-05-01 14:08:22 +0200980 self.assertRaises(NotImplementedError, zipfile.ZipFile,
981 io.BytesIO(data), 'r')
982
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300983 @requires_zlib
984 def test_read_unicode_filenames(self):
985 # bug #10801
986 fname = findfile('zip_cp437_header.zip')
987 with zipfile.ZipFile(fname) as zipfp:
988 for name in zipfp.namelist():
989 zipfp.open(name).close()
990
991 def test_write_unicode_filenames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000992 with zipfile.ZipFile(TESTFN, "w") as zf:
993 zf.writestr("foo.txt", "Test for unicode filename")
994 zf.writestr("\xf6.txt", "Test for unicode filename")
Ezio Melottie9615932010-01-24 19:26:24 +0000995 self.assertIsInstance(zf.infolist()[0].filename, str)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000996
997 with zipfile.ZipFile(TESTFN, "r") as zf:
998 self.assertEqual(zf.filelist[0].filename, "foo.txt")
999 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
Martin v. Löwis8570f6a2008-05-05 17:44:38 +00001000
Ezio Melottiafd0d112009-07-15 17:17:17 +00001001 def test_create_non_existent_file_for_append(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001002 if os.path.exists(TESTFN):
1003 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001004
Thomas Wouterscf297e42007-02-23 15:07:44 +00001005 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001006 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +00001007
Thomas Wouterscf297e42007-02-23 15:07:44 +00001008 try:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001009 with zipfile.ZipFile(TESTFN, 'a') as zf:
1010 zf.writestr(filename, content)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001011 except OSError:
Thomas Wouterscf297e42007-02-23 15:07:44 +00001012 self.fail('Could not append data to a non-existent zip file.')
1013
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001014 self.assertTrue(os.path.exists(TESTFN))
Thomas Wouterscf297e42007-02-23 15:07:44 +00001015
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001016 with zipfile.ZipFile(TESTFN, 'r') as zf:
1017 self.assertEqual(zf.read(filename), content)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001018
Ezio Melottiafd0d112009-07-15 17:17:17 +00001019 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001020 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti35386712009-12-31 13:22:41 +00001021 # it opens if there's an error in the file. If it doesn't, the
1022 # traceback holds a reference to the ZipFile object and, indirectly,
1023 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001024 # On Windows, this causes the os.unlink() call to fail because the
1025 # underlying file is still open. This is SF bug #412214.
1026 #
Ezio Melotti35386712009-12-31 13:22:41 +00001027 with open(TESTFN, "w") as fp:
1028 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001029 try:
1030 zf = zipfile.ZipFile(TESTFN)
Georg Brandl4d540882010-10-28 06:42:33 +00001031 except zipfile.BadZipFile:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001032 pass
1033
Ezio Melottiafd0d112009-07-15 17:17:17 +00001034 def test_is_zip_erroneous_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001035 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001036 # - passing a filename
1037 with open(TESTFN, "w") as fp:
1038 fp.write("this is not a legal zip file\n")
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001039 self.assertFalse(zipfile.is_zipfile(TESTFN))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001040 # - passing a file object
1041 with open(TESTFN, "rb") as fp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001042 self.assertFalse(zipfile.is_zipfile(fp))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001043 # - passing a file-like object
1044 fp = io.BytesIO()
1045 fp.write(b"this is not a legal zip file\n")
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001046 self.assertFalse(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001047 fp.seek(0, 0)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001048 self.assertFalse(zipfile.is_zipfile(fp))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001049
Serhiy Storchakad2b15272013-01-31 15:27:07 +02001050 def test_damaged_zipfile(self):
1051 """Check that zipfiles with missing bytes at the end raise BadZipFile."""
1052 # - Create a valid zip file
1053 fp = io.BytesIO()
1054 with zipfile.ZipFile(fp, mode="w") as zipf:
1055 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
1056 zipfiledata = fp.getvalue()
1057
1058 # - Now create copies of it missing the last N bytes and make sure
1059 # a BadZipFile exception is raised when we try to open it
1060 for N in range(len(zipfiledata)):
1061 fp = io.BytesIO(zipfiledata[:N])
1062 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, fp)
1063
Ezio Melottiafd0d112009-07-15 17:17:17 +00001064 def test_is_zip_valid_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001065 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001066 # - passing a filename
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001067 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1068 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
1069
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001070 self.assertTrue(zipfile.is_zipfile(TESTFN))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001071 # - passing a file object
1072 with open(TESTFN, "rb") as fp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001073 self.assertTrue(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001074 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001075 zip_contents = fp.read()
1076 # - passing a file-like object
1077 fp = io.BytesIO()
1078 fp.write(zip_contents)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001079 self.assertTrue(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001080 fp.seek(0, 0)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001081 self.assertTrue(zipfile.is_zipfile(fp))
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001082
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001083 def test_non_existent_file_raises_OSError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001084 # make sure we don't raise an AttributeError when a partially-constructed
1085 # ZipFile instance is finalized; this tests for regression on SF tracker
1086 # bug #403871.
1087
1088 # The bug we're testing for caused an AttributeError to be raised
1089 # when a ZipFile instance was created for a file that did not
1090 # exist; the .fp member was not initialized but was needed by the
1091 # __del__() method. Since the AttributeError is in the __del__(),
1092 # it is ignored, but the user should be sufficiently annoyed by
1093 # the message on the output that regression will be noticed
1094 # quickly.
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001095 self.assertRaises(OSError, zipfile.ZipFile, TESTFN)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001096
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001097 def test_empty_file_raises_BadZipFile(self):
1098 f = open(TESTFN, 'w')
1099 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001100 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001101
Ezio Melotti35386712009-12-31 13:22:41 +00001102 with open(TESTFN, 'w') as fp:
1103 fp.write("short file")
Georg Brandl4d540882010-10-28 06:42:33 +00001104 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001105
Ezio Melottiafd0d112009-07-15 17:17:17 +00001106 def test_closed_zip_raises_RuntimeError(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001107 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001108 data = io.BytesIO()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001109 with zipfile.ZipFile(data, mode="w") as zipf:
1110 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001111
Andrew Svetlov737fb892012-12-18 21:14:22 +02001112 # This is correct; calling .read on a closed ZipFile should raise
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001113 # a RuntimeError, and so should calling .testzip. An earlier
1114 # version of .testzip would swallow this exception (and any other)
1115 # and report that the first file in the archive was corrupt.
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001116 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
1117 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001118 self.assertRaises(RuntimeError, zipf.testzip)
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001119 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Brian Curtin8fb9b862010-11-18 02:15:28 +00001120 with open(TESTFN, 'w') as f:
1121 f.write('zipfile test data')
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001122 self.assertRaises(RuntimeError, zipf.write, TESTFN)
1123
Ezio Melottiafd0d112009-07-15 17:17:17 +00001124 def test_bad_constructor_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001125 """Check that bad modes passed to ZipFile constructor are caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001126 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
1127
Ezio Melottiafd0d112009-07-15 17:17:17 +00001128 def test_bad_open_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001129 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001130 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1131 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1132
1133 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001134 # read the data to make sure the file is there
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001135 zipf.read("foo.txt")
1136 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001137
Ezio Melottiafd0d112009-07-15 17:17:17 +00001138 def test_read0(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001139 """Check that calling read(0) on a ZipExtFile object returns an empty
1140 string and doesn't advance file pointer."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001141 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1142 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1143 # read the data to make sure the file is there
Brian Curtin8fb9b862010-11-18 02:15:28 +00001144 with zipf.open("foo.txt") as f:
1145 for i in range(FIXEDTEST_SIZE):
1146 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001147
Brian Curtin8fb9b862010-11-18 02:15:28 +00001148 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001149
Ezio Melottiafd0d112009-07-15 17:17:17 +00001150 def test_open_non_existent_item(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001151 """Check that attempting to call open() for an item that doesn't
1152 exist in the archive raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001153 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1154 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001155
Ezio Melottiafd0d112009-07-15 17:17:17 +00001156 def test_bad_compression_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001157 """Check that bad compression methods passed to ZipFile.open are
1158 caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001159 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
1160
Martin v. Löwisb3260f02012-05-01 08:38:01 +02001161 def test_unsupported_compression(self):
1162 # data is declared as shrunk, but actually deflated
1163 data = (b'PK\x03\x04.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00'
Christian Tismer59202e52013-10-21 03:59:23 +02001164 b'\x00\x02\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00x\x03\x00PK\x01'
1165 b'\x02.\x03.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00\x00\x02\x00\x00'
1166 b'\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
1167 b'\x80\x01\x00\x00\x00\x00xPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00'
1168 b'/\x00\x00\x00!\x00\x00\x00\x00\x00')
Martin v. Löwisb3260f02012-05-01 08:38:01 +02001169 with zipfile.ZipFile(io.BytesIO(data), 'r') as zipf:
1170 self.assertRaises(NotImplementedError, zipf.open, 'x')
1171
Ezio Melottiafd0d112009-07-15 17:17:17 +00001172 def test_null_byte_in_filename(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001173 """Check that a filename containing a null byte is properly
1174 terminated."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001175 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1176 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
1177 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001178
Ezio Melottiafd0d112009-07-15 17:17:17 +00001179 def test_struct_sizes(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001180 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001181 self.assertEqual(zipfile.sizeEndCentDir, 22)
1182 self.assertEqual(zipfile.sizeCentralDir, 46)
1183 self.assertEqual(zipfile.sizeEndCentDir64, 56)
1184 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
1185
Ezio Melottiafd0d112009-07-15 17:17:17 +00001186 def test_comments(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001187 """Check that comments on the archive are handled properly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001188
1189 # check default comment is empty
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001190 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1191 self.assertEqual(zipf.comment, b'')
1192 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1193
1194 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1195 self.assertEqual(zipfr.comment, b'')
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001196
1197 # check a simple short comment
1198 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001199 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1200 zipf.comment = comment
1201 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1202 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1203 self.assertEqual(zipf.comment, comment)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001204
1205 # check a comment of max length
1206 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
1207 comment2 = comment2.encode("ascii")
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001208 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1209 zipf.comment = comment2
1210 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1211
1212 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1213 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001214
1215 # check a comment that is too long is truncated
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001216 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
Serhiy Storchaka9b7a1a12014-01-20 21:57:40 +02001217 with self.assertWarns(UserWarning):
1218 zipf.comment = comment2 + b'oops'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001219 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1220 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1221 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001222
Antoine Pitrouc3991852012-06-30 17:31:37 +02001223 # check that comments are correctly modified in append mode
1224 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1225 zipf.comment = b"original comment"
1226 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1227 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1228 zipf.comment = b"an updated comment"
1229 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1230 self.assertEqual(zipf.comment, b"an updated comment")
1231
1232 # check that comments are correctly shortened in append mode
1233 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1234 zipf.comment = b"original comment that's longer"
1235 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1236 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1237 zipf.comment = b"shorter comment"
1238 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1239 self.assertEqual(zipf.comment, b"shorter comment")
1240
R David Murrayf50b38a2012-04-12 18:44:58 -04001241 def test_unicode_comment(self):
1242 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1243 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1244 with self.assertRaises(TypeError):
1245 zipf.comment = "this is an error"
1246
1247 def test_change_comment_in_empty_archive(self):
1248 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1249 self.assertFalse(zipf.filelist)
1250 zipf.comment = b"this is a comment"
1251 with zipfile.ZipFile(TESTFN, "r") as zipf:
1252 self.assertEqual(zipf.comment, b"this is a comment")
1253
1254 def test_change_comment_in_nonempty_archive(self):
1255 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1256 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1257 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1258 self.assertTrue(zipf.filelist)
1259 zipf.comment = b"this is a comment"
1260 with zipfile.ZipFile(TESTFN, "r") as zipf:
1261 self.assertEqual(zipf.comment, b"this is a comment")
1262
Georg Brandl268e4d42010-10-14 06:59:45 +00001263 def test_empty_zipfile(self):
1264 # Check that creating a file in 'w' or 'a' mode and closing without
1265 # adding any files to the archives creates a valid empty ZIP file
1266 zipf = zipfile.ZipFile(TESTFN, mode="w")
1267 zipf.close()
1268 try:
1269 zipf = zipfile.ZipFile(TESTFN, mode="r")
1270 except zipfile.BadZipFile:
1271 self.fail("Unable to create empty ZIP file in 'w' mode")
1272
1273 zipf = zipfile.ZipFile(TESTFN, mode="a")
1274 zipf.close()
1275 try:
1276 zipf = zipfile.ZipFile(TESTFN, mode="r")
1277 except:
1278 self.fail("Unable to create empty ZIP file in 'a' mode")
1279
1280 def test_open_empty_file(self):
1281 # Issue 1710703: Check that opening a file with less than 22 bytes
Georg Brandl4d540882010-10-28 06:42:33 +00001282 # raises a BadZipFile exception (rather than the previously unhelpful
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001283 # OSError)
Georg Brandl268e4d42010-10-14 06:59:45 +00001284 f = open(TESTFN, 'w')
1285 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001286 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN, 'r')
Georg Brandl268e4d42010-10-14 06:59:45 +00001287
Senthil Kumaran29fa9d42011-10-20 01:46:00 +08001288 def test_create_zipinfo_before_1980(self):
1289 self.assertRaises(ValueError,
1290 zipfile.ZipInfo, 'seventies', (1979, 1, 1, 0, 0, 0))
1291
Gregory P. Smith0af8a862014-05-29 23:42:14 -07001292 def test_zipfile_with_short_extra_field(self):
1293 """If an extra field in the header is less than 4 bytes, skip it."""
1294 zipdata = (
1295 b'PK\x03\x04\x14\x00\x00\x00\x00\x00\x93\x9b\xad@\x8b\x9e'
1296 b'\xd9\xd3\x01\x00\x00\x00\x01\x00\x00\x00\x03\x00\x03\x00ab'
1297 b'c\x00\x00\x00APK\x01\x02\x14\x03\x14\x00\x00\x00\x00'
1298 b'\x00\x93\x9b\xad@\x8b\x9e\xd9\xd3\x01\x00\x00\x00\x01\x00\x00'
1299 b'\x00\x03\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00'
1300 b'\x00\x00\x00abc\x00\x00PK\x05\x06\x00\x00\x00\x00'
1301 b'\x01\x00\x01\x003\x00\x00\x00%\x00\x00\x00\x00\x00'
1302 )
1303 with zipfile.ZipFile(io.BytesIO(zipdata), 'r') as zipf:
1304 # testzip returns the name of the first corrupt file, or None
1305 self.assertIsNone(zipf.testzip())
1306
Guido van Rossumd8faa362007-04-27 19:54:29 +00001307 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001308 unlink(TESTFN)
1309 unlink(TESTFN2)
1310
Thomas Wouterscf297e42007-02-23 15:07:44 +00001311
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001312class AbstractBadCrcTests:
1313 def test_testzip_with_bad_crc(self):
1314 """Tests that files with bad CRCs return their name from testzip."""
1315 zipdata = self.zip_with_bad_crc
1316
1317 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1318 # testzip returns the name of the first corrupt file, or None
1319 self.assertEqual('afile', zipf.testzip())
1320
1321 def test_read_with_bad_crc(self):
1322 """Tests that files with bad CRCs raise a BadZipFile exception when read."""
1323 zipdata = self.zip_with_bad_crc
1324
1325 # Using ZipFile.read()
1326 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1327 self.assertRaises(zipfile.BadZipFile, zipf.read, 'afile')
1328
1329 # Using ZipExtFile.read()
1330 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1331 with zipf.open('afile', 'r') as corrupt_file:
1332 self.assertRaises(zipfile.BadZipFile, corrupt_file.read)
1333
1334 # Same with small reads (in order to exercise the buffering logic)
1335 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1336 with zipf.open('afile', 'r') as corrupt_file:
1337 corrupt_file.MIN_READ_SIZE = 2
1338 with self.assertRaises(zipfile.BadZipFile):
1339 while corrupt_file.read(2):
1340 pass
1341
1342
1343class StoredBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1344 compression = zipfile.ZIP_STORED
1345 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001346 b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
1347 b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
1348 b'ilehello,AworldP'
1349 b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
1350 b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
1351 b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
1352 b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
1353 b'\0\0/\0\0\0\0\0')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001354
1355@requires_zlib
1356class DeflateBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1357 compression = zipfile.ZIP_DEFLATED
1358 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001359 b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
1360 b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1361 b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
1362 b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
1363 b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
1364 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
1365 b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
1366 b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001367
1368@requires_bz2
1369class Bzip2BadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1370 compression = zipfile.ZIP_BZIP2
1371 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001372 b'PK\x03\x04\x14\x03\x00\x00\x0c\x00nu\x0c=FA'
1373 b'KE8\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1374 b'ileBZh91AY&SY\xd4\xa8\xca'
1375 b'\x7f\x00\x00\x0f\x11\x80@\x00\x06D\x90\x80 \x00 \xa5'
1376 b'P\xd9!\x03\x03\x13\x13\x13\x89\xa9\xa9\xc2u5:\x9f'
1377 b'\x8b\xb9"\x9c(HjTe?\x80PK\x01\x02\x14'
1378 b'\x03\x14\x03\x00\x00\x0c\x00nu\x0c=FAKE8'
1379 b'\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\x00'
1380 b'\x00 \x80\x80\x81\x00\x00\x00\x00afilePK'
1381 b'\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00\x00[\x00'
1382 b'\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001383
1384@requires_lzma
1385class LzmaBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1386 compression = zipfile.ZIP_LZMA
1387 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001388 b'PK\x03\x04\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
1389 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1390 b'ile\t\x04\x05\x00]\x00\x00\x00\x04\x004\x19I'
1391 b'\xee\x8d\xe9\x17\x89:3`\tq!.8\x00PK'
1392 b'\x01\x02\x14\x03\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
1393 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00'
1394 b'\x00\x00\x00\x00 \x80\x80\x81\x00\x00\x00\x00afil'
1395 b'ePK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00'
1396 b'\x00>\x00\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001397
1398
Thomas Wouterscf297e42007-02-23 15:07:44 +00001399class DecryptionTests(unittest.TestCase):
Ezio Melotti35386712009-12-31 13:22:41 +00001400 """Check that ZIP decryption works. Since the library does not
1401 support encryption at the moment, we use a pre-generated encrypted
1402 ZIP file."""
Thomas Wouterscf297e42007-02-23 15:07:44 +00001403
1404 data = (
Christian Tismer59202e52013-10-21 03:59:23 +02001405 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
1406 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
1407 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
1408 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
1409 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
1410 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
1411 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +00001412 data2 = (
Christian Tismer59202e52013-10-21 03:59:23 +02001413 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
1414 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
1415 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
1416 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
1417 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
1418 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
1419 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
1420 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +00001421
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001422 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +00001423 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +00001424
1425 def setUp(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001426 with open(TESTFN, "wb") as fp:
1427 fp.write(self.data)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001428 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti35386712009-12-31 13:22:41 +00001429 with open(TESTFN2, "wb") as fp:
1430 fp.write(self.data2)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001431 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001432
1433 def tearDown(self):
1434 self.zip.close()
1435 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001436 self.zip2.close()
1437 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001438
Ezio Melottiafd0d112009-07-15 17:17:17 +00001439 def test_no_password(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001440 # Reading the encrypted file without password
1441 # must generate a RunTime exception
1442 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001443 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001444
Ezio Melottiafd0d112009-07-15 17:17:17 +00001445 def test_bad_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001446 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001447 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001448 self.zip2.setpassword(b"perl")
1449 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001450
Ezio Melotti975077a2011-05-19 22:03:22 +03001451 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +00001452 def test_good_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001453 self.zip.setpassword(b"python")
Ezio Melotti35386712009-12-31 13:22:41 +00001454 self.assertEqual(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001455 self.zip2.setpassword(b"12345")
Ezio Melotti35386712009-12-31 13:22:41 +00001456 self.assertEqual(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001457
R. David Murray8d855d82010-12-21 21:53:37 +00001458 def test_unicode_password(self):
1459 self.assertRaises(TypeError, self.zip.setpassword, "unicode")
1460 self.assertRaises(TypeError, self.zip.read, "test.txt", "python")
1461 self.assertRaises(TypeError, self.zip.open, "test.txt", pwd="python")
1462 self.assertRaises(TypeError, self.zip.extract, "test.txt", pwd="python")
1463
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001464class AbstractTestsWithRandomBinaryFiles:
1465 @classmethod
1466 def setUpClass(cls):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001467 datacount = randint(16, 64)*1024 + randint(1, 1024)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001468 cls.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
1469 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001470
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001471 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001472 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +00001473 with open(TESTFN, "wb") as fp:
1474 fp.write(self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001475
1476 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001477 unlink(TESTFN)
1478 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001479
Ezio Melottiafd0d112009-07-15 17:17:17 +00001480 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001481 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001482 with zipfile.ZipFile(f, "w", compression) as zipfp:
1483 zipfp.write(TESTFN, "another.name")
1484 zipfp.write(TESTFN, TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001485
Ezio Melottiafd0d112009-07-15 17:17:17 +00001486 def zip_test(self, f, compression):
1487 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001488
1489 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001490 with zipfile.ZipFile(f, "r", compression) as zipfp:
1491 testdata = zipfp.read(TESTFN)
1492 self.assertEqual(len(testdata), len(self.data))
1493 self.assertEqual(testdata, self.data)
1494 self.assertEqual(zipfp.read("another.name"), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001495
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001496 def test_read(self):
1497 for f in get_files(self):
1498 self.zip_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001499
Ezio Melottiafd0d112009-07-15 17:17:17 +00001500 def zip_open_test(self, f, compression):
1501 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001502
1503 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001504 with zipfile.ZipFile(f, "r", compression) as zipfp:
1505 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001506 with zipfp.open(TESTFN) as zipopen1:
1507 while True:
1508 read_data = zipopen1.read(256)
1509 if not read_data:
1510 break
1511 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001512
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001513 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001514 with zipfp.open("another.name") as zipopen2:
1515 while True:
1516 read_data = zipopen2.read(256)
1517 if not read_data:
1518 break
1519 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001520
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001521 testdata1 = b''.join(zipdata1)
1522 self.assertEqual(len(testdata1), len(self.data))
1523 self.assertEqual(testdata1, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001524
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001525 testdata2 = b''.join(zipdata2)
Ezio Melotti35386712009-12-31 13:22:41 +00001526 self.assertEqual(len(testdata2), len(self.data))
1527 self.assertEqual(testdata2, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001528
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001529 def test_open(self):
1530 for f in get_files(self):
1531 self.zip_open_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001532
Ezio Melottiafd0d112009-07-15 17:17:17 +00001533 def zip_random_open_test(self, f, compression):
1534 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001535
1536 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001537 with zipfile.ZipFile(f, "r", compression) as zipfp:
1538 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001539 with zipfp.open(TESTFN) as zipopen1:
1540 while True:
1541 read_data = zipopen1.read(randint(1, 1024))
1542 if not read_data:
1543 break
1544 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001545
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001546 testdata = b''.join(zipdata1)
1547 self.assertEqual(len(testdata), len(self.data))
1548 self.assertEqual(testdata, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001549
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001550 def test_random_open(self):
1551 for f in get_files(self):
1552 self.zip_random_open_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001553
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001554
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001555class StoredTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1556 unittest.TestCase):
1557 compression = zipfile.ZIP_STORED
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001558
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001559@requires_zlib
1560class DeflateTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1561 unittest.TestCase):
1562 compression = zipfile.ZIP_DEFLATED
1563
1564@requires_bz2
1565class Bzip2TestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1566 unittest.TestCase):
1567 compression = zipfile.ZIP_BZIP2
1568
1569@requires_lzma
1570class LzmaTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1571 unittest.TestCase):
1572 compression = zipfile.ZIP_LZMA
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001573
Ezio Melotti76430242009-07-11 18:28:48 +00001574
Ezio Melotti975077a2011-05-19 22:03:22 +03001575@requires_zlib
Guido van Rossumd8faa362007-04-27 19:54:29 +00001576class TestsWithMultipleOpens(unittest.TestCase):
1577 def setUp(self):
1578 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001579 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
1580 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
1581 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001582
Ezio Melottiafd0d112009-07-15 17:17:17 +00001583 def test_same_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001584 # Verify that (when the ZipFile is in control of creating file objects)
1585 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001586 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001587 with zipf.open('ones') as zopen1, zipf.open('ones') as zopen2:
1588 data1 = zopen1.read(500)
1589 data2 = zopen2.read(500)
1590 data1 += zopen1.read(500)
1591 data2 += zopen2.read(500)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001592 self.assertEqual(data1, data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001593
Ezio Melottiafd0d112009-07-15 17:17:17 +00001594 def test_different_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001595 # Verify that (when the ZipFile is in control of creating file objects)
1596 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001597 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001598 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1599 data1 = zopen1.read(500)
1600 data2 = zopen2.read(500)
1601 data1 += zopen1.read(500)
1602 data2 += zopen2.read(500)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001603 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
1604 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001605
Ezio Melottiafd0d112009-07-15 17:17:17 +00001606 def test_interleaved(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001607 # Verify that (when the ZipFile is in control of creating file objects)
1608 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001609 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001610 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1611 data1 = zopen1.read(500)
1612 data2 = zopen2.read(500)
1613 data1 += zopen1.read(500)
1614 data2 += zopen2.read(500)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001615 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
1616 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001617
1618 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001619 unlink(TESTFN2)
1620
Guido van Rossumd8faa362007-04-27 19:54:29 +00001621
Martin v. Löwis59e47792009-01-24 14:10:07 +00001622class TestWithDirectory(unittest.TestCase):
1623 def setUp(self):
1624 os.mkdir(TESTFN2)
1625
Ezio Melottiafd0d112009-07-15 17:17:17 +00001626 def test_extract_dir(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001627 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
1628 zipf.extractall(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001629 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1630 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1631 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1632
Ezio Melottiafd0d112009-07-15 17:17:17 +00001633 def test_bug_6050(self):
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001634 # Extraction should succeed if directories already exist
1635 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottiafd0d112009-07-15 17:17:17 +00001636 self.test_extract_dir()
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001637
Ezio Melottiafd0d112009-07-15 17:17:17 +00001638 def test_store_dir(self):
Martin v. Löwis59e47792009-01-24 14:10:07 +00001639 os.mkdir(os.path.join(TESTFN2, "x"))
1640 zipf = zipfile.ZipFile(TESTFN, "w")
1641 zipf.write(os.path.join(TESTFN2, "x"), "x")
1642 self.assertTrue(zipf.filelist[0].filename.endswith("x/"))
1643
1644 def tearDown(self):
Victor Stinner57004c62014-09-04 00:49:01 +02001645 rmtree(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001646 if os.path.exists(TESTFN):
Ezio Melotti76430242009-07-11 18:28:48 +00001647 unlink(TESTFN)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001648
Guido van Rossumd8faa362007-04-27 19:54:29 +00001649
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001650class AbstractUniversalNewlineTests:
1651 @classmethod
1652 def setUpClass(cls):
1653 cls.line_gen = [bytes("Test of zipfile line %d." % i, "ascii")
1654 for i in range(FIXEDTEST_SIZE)]
1655 cls.seps = (b'\r', b'\r\n', b'\n')
1656 cls.arcdata = {}
1657 for n, s in enumerate(cls.seps):
1658 cls.arcdata[s] = s.join(cls.line_gen) + s
1659
Guido van Rossumd8faa362007-04-27 19:54:29 +00001660 def setUp(self):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001661 self.arcfiles = {}
Guido van Rossumd8faa362007-04-27 19:54:29 +00001662 for n, s in enumerate(self.seps):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001663 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001664 with open(self.arcfiles[s], "wb") as f:
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001665 f.write(self.arcdata[s])
Guido van Rossumd8faa362007-04-27 19:54:29 +00001666
Ezio Melottiafd0d112009-07-15 17:17:17 +00001667 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001668 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001669 with zipfile.ZipFile(f, "w", compression) as zipfp:
1670 for fn in self.arcfiles.values():
1671 zipfp.write(fn, fn)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001672
Ezio Melottiafd0d112009-07-15 17:17:17 +00001673 def read_test(self, f, compression):
1674 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001675
1676 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001677 with zipfile.ZipFile(f, "r") as zipfp:
1678 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02001679 with openU(zipfp, fn) as fp:
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001680 zipdata = fp.read()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001681 self.assertEqual(self.arcdata[sep], zipdata)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001682
1683 def test_read(self):
1684 for f in get_files(self):
1685 self.read_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001686
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001687 def readline_read_test(self, f, compression):
1688 self.make_test_archive(f, compression)
1689
1690 # Read the ZIP archive
Brian Curtin8fb9b862010-11-18 02:15:28 +00001691 with zipfile.ZipFile(f, "r") as zipfp:
1692 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02001693 with openU(zipfp, fn) as zipopen:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001694 data = b''
1695 while True:
1696 read = zipopen.readline()
1697 if not read:
1698 break
1699 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001700
Brian Curtin8fb9b862010-11-18 02:15:28 +00001701 read = zipopen.read(5)
1702 if not read:
1703 break
1704 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001705
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001706 self.assertEqual(data, self.arcdata[b'\n'])
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001707
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001708 def test_readline_read(self):
1709 for f in get_files(self):
1710 self.readline_read_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001711
Ezio Melottiafd0d112009-07-15 17:17:17 +00001712 def readline_test(self, f, compression):
1713 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001714
1715 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001716 with zipfile.ZipFile(f, "r") as zipfp:
1717 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02001718 with openU(zipfp, fn) as zipopen:
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001719 for line in self.line_gen:
1720 linedata = zipopen.readline()
1721 self.assertEqual(linedata, line + b'\n')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001722
1723 def test_readline(self):
1724 for f in get_files(self):
1725 self.readline_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001726
Ezio Melottiafd0d112009-07-15 17:17:17 +00001727 def readlines_test(self, f, compression):
1728 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001729
1730 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001731 with zipfile.ZipFile(f, "r") as zipfp:
1732 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02001733 with openU(zipfp, fn) as fp:
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001734 ziplines = fp.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001735 for line, zipline in zip(self.line_gen, ziplines):
1736 self.assertEqual(zipline, line + b'\n')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001737
1738 def test_readlines(self):
1739 for f in get_files(self):
1740 self.readlines_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001741
Ezio Melottiafd0d112009-07-15 17:17:17 +00001742 def iterlines_test(self, f, compression):
1743 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001744
1745 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001746 with zipfile.ZipFile(f, "r") as zipfp:
1747 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02001748 with openU(zipfp, fn) as fp:
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001749 for line, zipline in zip(self.line_gen, fp):
1750 self.assertEqual(zipline, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001751
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001752 def test_iterlines(self):
1753 for f in get_files(self):
1754 self.iterlines_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001755
Guido van Rossumd8faa362007-04-27 19:54:29 +00001756 def tearDown(self):
1757 for sep, fn in self.arcfiles.items():
Victor Stinner88b215e2014-09-04 00:51:09 +02001758 unlink(fn)
Ezio Melotti76430242009-07-11 18:28:48 +00001759 unlink(TESTFN)
1760 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001761
1762
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001763class StoredUniversalNewlineTests(AbstractUniversalNewlineTests,
1764 unittest.TestCase):
1765 compression = zipfile.ZIP_STORED
1766
1767@requires_zlib
1768class DeflateUniversalNewlineTests(AbstractUniversalNewlineTests,
1769 unittest.TestCase):
1770 compression = zipfile.ZIP_DEFLATED
1771
1772@requires_bz2
1773class Bzip2UniversalNewlineTests(AbstractUniversalNewlineTests,
1774 unittest.TestCase):
1775 compression = zipfile.ZIP_BZIP2
1776
1777@requires_lzma
1778class LzmaUniversalNewlineTests(AbstractUniversalNewlineTests,
1779 unittest.TestCase):
1780 compression = zipfile.ZIP_LZMA
1781
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001782if __name__ == "__main__":
Brett Cannond5b4e1d2013-06-12 19:57:19 -04001783 unittest.main()