blob: 1bef5750a1520769750f26c02cee2c0225ffe1b1 [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 shutil
7import 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
Serhiy Storchakafa6bc292013-07-22 21:00:11 +030015from test.support import (TESTFN, findfile, unlink,
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 Storchakafa6bc292013-07-22 21:00:11 +030029def get_files(test):
30 yield TESTFN2
31 with TemporaryFile() as f:
32 yield f
33 test.assertFalse(f.closed)
34 with io.BytesIO() as f:
35 yield f
36 test.assertFalse(f.closed)
Ezio Melotti76430242009-07-11 18:28:48 +000037
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +020038def openU(zipfp, fn):
39 with check_warnings(('', DeprecationWarning)):
40 return zipfp.open(fn, 'rU')
41
Serhiy Storchakafa6bc292013-07-22 21:00:11 +030042class AbstractTestsWithSourceFile:
43 @classmethod
44 def setUpClass(cls):
45 cls.line_gen = [bytes("Zipfile test line %d. random float: %f\n" %
46 (i, random()), "ascii")
47 for i in range(FIXEDTEST_SIZE)]
48 cls.data = b''.join(cls.line_gen)
49
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000050 def setUp(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000051 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +000052 with open(TESTFN, "wb") as fp:
53 fp.write(self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000054
Ezio Melottiafd0d112009-07-15 17:17:17 +000055 def make_test_archive(self, f, compression):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000056 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000057 with zipfile.ZipFile(f, "w", compression) as zipfp:
58 zipfp.write(TESTFN, "another.name")
59 zipfp.write(TESTFN, TESTFN)
60 zipfp.writestr("strfile", self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000061
Ezio Melottiafd0d112009-07-15 17:17:17 +000062 def zip_test(self, f, compression):
63 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +000064
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000065 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000066 with zipfile.ZipFile(f, "r", compression) as zipfp:
67 self.assertEqual(zipfp.read(TESTFN), self.data)
68 self.assertEqual(zipfp.read("another.name"), self.data)
69 self.assertEqual(zipfp.read("strfile"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000070
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000071 # Print the ZIP directory
72 fp = io.StringIO()
73 zipfp.printdir(file=fp)
74 directory = fp.getvalue()
75 lines = directory.splitlines()
Ezio Melotti35386712009-12-31 13:22:41 +000076 self.assertEqual(len(lines), 4) # Number of files + header
Thomas Wouters0e3f5912006-08-11 14:57:12 +000077
Benjamin Peterson577473f2010-01-19 00:09:57 +000078 self.assertIn('File Name', lines[0])
79 self.assertIn('Modified', lines[0])
80 self.assertIn('Size', lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +000081
Ezio Melotti35386712009-12-31 13:22:41 +000082 fn, date, time_, size = lines[1].split()
83 self.assertEqual(fn, 'another.name')
84 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
85 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
86 self.assertEqual(size, str(len(self.data)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000087
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000088 # Check the namelist
89 names = zipfp.namelist()
Ezio Melotti35386712009-12-31 13:22:41 +000090 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +000091 self.assertIn(TESTFN, names)
92 self.assertIn("another.name", names)
93 self.assertIn("strfile", names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000094
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000095 # Check infolist
96 infos = zipfp.infolist()
Ezio Melotti35386712009-12-31 13:22:41 +000097 names = [i.filename for i in infos]
98 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +000099 self.assertIn(TESTFN, names)
100 self.assertIn("another.name", names)
101 self.assertIn("strfile", names)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000102 for i in infos:
Ezio Melotti35386712009-12-31 13:22:41 +0000103 self.assertEqual(i.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000104
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000105 # check getinfo
106 for nm in (TESTFN, "another.name", "strfile"):
107 info = zipfp.getinfo(nm)
Ezio Melotti35386712009-12-31 13:22:41 +0000108 self.assertEqual(info.filename, nm)
109 self.assertEqual(info.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000110
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000111 # Check that testzip doesn't raise an exception
112 zipfp.testzip()
Tim Peters7d3bad62001-04-04 18:56:49 +0000113
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300114 def test_basic(self):
115 for f in get_files(self):
116 self.zip_test(f, self.compression)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000117
Ezio Melottiafd0d112009-07-15 17:17:17 +0000118 def zip_open_test(self, f, compression):
119 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000120
121 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000122 with zipfile.ZipFile(f, "r", compression) as zipfp:
123 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000124 with zipfp.open(TESTFN) as zipopen1:
125 while True:
126 read_data = zipopen1.read(256)
127 if not read_data:
128 break
129 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000130
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000131 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000132 with zipfp.open("another.name") as zipopen2:
133 while True:
134 read_data = zipopen2.read(256)
135 if not read_data:
136 break
137 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000138
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000139 self.assertEqual(b''.join(zipdata1), self.data)
140 self.assertEqual(b''.join(zipdata2), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000141
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300142 def test_open(self):
143 for f in get_files(self):
144 self.zip_open_test(f, self.compression)
Georg Brandlb533e262008-05-25 18:19:30 +0000145
Ezio Melottiafd0d112009-07-15 17:17:17 +0000146 def zip_random_open_test(self, f, compression):
147 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000148
149 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000150 with zipfile.ZipFile(f, "r", compression) as zipfp:
151 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000152 with zipfp.open(TESTFN) as zipopen1:
153 while True:
154 read_data = zipopen1.read(randint(1, 1024))
155 if not read_data:
156 break
157 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000158
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000159 self.assertEqual(b''.join(zipdata1), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000160
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300161 def test_random_open(self):
162 for f in get_files(self):
163 self.zip_random_open_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000164
Serhiy Storchakad2c07a52013-09-27 22:11:57 +0300165 def zip_read1_test(self, f, compression):
166 self.make_test_archive(f, compression)
167
168 # Read the ZIP archive
169 with zipfile.ZipFile(f, "r") as zipfp, \
170 zipfp.open(TESTFN) as zipopen:
171 zipdata = []
172 while True:
173 read_data = zipopen.read1(-1)
174 if not read_data:
175 break
176 zipdata.append(read_data)
177
178 self.assertEqual(b''.join(zipdata), self.data)
179
180 def test_read1(self):
181 for f in get_files(self):
182 self.zip_read1_test(f, self.compression)
183
184 def zip_read1_10_test(self, f, compression):
185 self.make_test_archive(f, compression)
186
187 # Read the ZIP archive
188 with zipfile.ZipFile(f, "r") as zipfp, \
189 zipfp.open(TESTFN) as zipopen:
190 zipdata = []
191 while True:
192 read_data = zipopen.read1(10)
193 self.assertLessEqual(len(read_data), 10)
194 if not read_data:
195 break
196 zipdata.append(read_data)
197
198 self.assertEqual(b''.join(zipdata), self.data)
199
200 def test_read1_10(self):
201 for f in get_files(self):
202 self.zip_read1_10_test(f, self.compression)
203
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000204 def zip_readline_read_test(self, f, compression):
205 self.make_test_archive(f, compression)
206
207 # Read the ZIP archive
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300208 with zipfile.ZipFile(f, "r") as zipfp, \
209 zipfp.open(TESTFN) as zipopen:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000210 data = b''
211 while True:
212 read = zipopen.readline()
213 if not read:
214 break
215 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000216
Brian Curtin8fb9b862010-11-18 02:15:28 +0000217 read = zipopen.read(100)
218 if not read:
219 break
220 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000221
222 self.assertEqual(data, self.data)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300223
224 def test_readline_read(self):
225 # Issue #7610: calls to readline() interleaved with calls to read().
226 for f in get_files(self):
227 self.zip_readline_read_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000228
Ezio Melottiafd0d112009-07-15 17:17:17 +0000229 def zip_readline_test(self, f, compression):
230 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000231
232 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000233 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000234 with zipfp.open(TESTFN) as zipopen:
235 for line in self.line_gen:
236 linedata = zipopen.readline()
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300237 self.assertEqual(linedata, line)
238
239 def test_readline(self):
240 for f in get_files(self):
241 self.zip_readline_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000242
Ezio Melottiafd0d112009-07-15 17:17:17 +0000243 def zip_readlines_test(self, f, compression):
244 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000245
246 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000247 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000248 with zipfp.open(TESTFN) as zipopen:
249 ziplines = zipopen.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000250 for line, zipline in zip(self.line_gen, ziplines):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300251 self.assertEqual(zipline, line)
252
253 def test_readlines(self):
254 for f in get_files(self):
255 self.zip_readlines_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000256
Ezio Melottiafd0d112009-07-15 17:17:17 +0000257 def zip_iterlines_test(self, f, compression):
258 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000259
260 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000261 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000262 with zipfp.open(TESTFN) as zipopen:
263 for line, zipline in zip(self.line_gen, zipopen):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300264 self.assertEqual(zipline, line)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000265
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300266 def test_iterlines(self):
267 for f in get_files(self):
268 self.zip_iterlines_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000269
Ezio Melottiafd0d112009-07-15 17:17:17 +0000270 def test_low_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000271 """Check for cases where compressed data is larger than original."""
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000272 # Create the ZIP archive
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300273 with zipfile.ZipFile(TESTFN2, "w", self.compression) as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000274 zipfp.writestr("strfile", '12')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000275
276 # Get an open object for strfile
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300277 with zipfile.ZipFile(TESTFN2, "r", self.compression) as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000278 with zipfp.open("strfile") as openobj:
279 self.assertEqual(openobj.read(1), b'1')
280 self.assertEqual(openobj.read(1), b'2')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000281
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300282 def test_writestr_compression(self):
283 zipfp = zipfile.ZipFile(TESTFN2, "w")
284 zipfp.writestr("b.txt", "hello world", compress_type=self.compression)
285 info = zipfp.getinfo('b.txt')
286 self.assertEqual(info.compress_type, self.compression)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200287
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300288 def test_read_return_size(self):
289 # Issue #9837: ZipExtFile.read() shouldn't return more bytes
290 # than requested.
291 for test_size in (1, 4095, 4096, 4097, 16384):
292 file_size = test_size + 1
293 junk = getrandbits(8 * file_size).to_bytes(file_size, 'little')
294 with zipfile.ZipFile(io.BytesIO(), "w", self.compression) as zipf:
295 zipf.writestr('foo', junk)
296 with zipf.open('foo', 'r') as fp:
297 buf = fp.read(test_size)
298 self.assertEqual(len(buf), test_size)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200299
Serhiy Storchaka5ce3f102014-01-09 14:50:20 +0200300 def test_truncated_zipfile(self):
301 fp = io.BytesIO()
302 with zipfile.ZipFile(fp, mode='w') as zipf:
303 zipf.writestr('strfile', self.data, compress_type=self.compression)
304 end_offset = fp.tell()
305 zipfiledata = fp.getvalue()
306
307 fp = io.BytesIO(zipfiledata)
308 with zipfile.ZipFile(fp) as zipf:
309 with zipf.open('strfile') as zipopen:
310 fp.truncate(end_offset - 20)
311 with self.assertRaises(EOFError):
312 zipopen.read()
313
314 fp = io.BytesIO(zipfiledata)
315 with zipfile.ZipFile(fp) as zipf:
316 with zipf.open('strfile') as zipopen:
317 fp.truncate(end_offset - 20)
318 with self.assertRaises(EOFError):
319 while zipopen.read(100):
320 pass
321
322 fp = io.BytesIO(zipfiledata)
323 with zipfile.ZipFile(fp) as zipf:
324 with zipf.open('strfile') as zipopen:
325 fp.truncate(end_offset - 20)
326 with self.assertRaises(EOFError):
327 while zipopen.read1(100):
328 pass
329
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300330 def tearDown(self):
331 unlink(TESTFN)
332 unlink(TESTFN2)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200333
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200334
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300335class StoredTestsWithSourceFile(AbstractTestsWithSourceFile,
336 unittest.TestCase):
337 compression = zipfile.ZIP_STORED
338 test_low_compression = None
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200339
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300340 def zip_test_writestr_permissions(self, f, compression):
341 # Make sure that writestr creates files with mode 0600,
342 # when it is passed a name rather than a ZipInfo instance.
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200343
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300344 self.make_test_archive(f, compression)
345 with zipfile.ZipFile(f, "r") as zipfp:
346 zinfo = zipfp.getinfo('strfile')
347 self.assertEqual(zinfo.external_attr, 0o600 << 16)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200348
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300349 def test_writestr_permissions(self):
350 for f in get_files(self):
351 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +0200352
Ezio Melottiafd0d112009-07-15 17:17:17 +0000353 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000354 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
355 zipfp.write(TESTFN, "/absolute")
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000356
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000357 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
358 self.assertEqual(zipfp.namelist(), ["absolute"])
Tim Peters32cbc962006-02-20 21:42:18 +0000359
Ezio Melottiafd0d112009-07-15 17:17:17 +0000360 def test_append_to_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000361 """Test appending to an existing zipfile."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000362 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
363 zipfp.write(TESTFN, TESTFN)
364
365 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
366 zipfp.writestr("strfile", self.data)
367 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000368
Ezio Melottiafd0d112009-07-15 17:17:17 +0000369 def test_append_to_non_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000370 """Test appending to an existing file that is not a zipfile."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000371 # NOTE: this test fails if len(d) < 22 because of the first
372 # line "fpin.seek(-22, 2)" in _EndRecData
Ezio Melotti35386712009-12-31 13:22:41 +0000373 data = b'I am not a ZipFile!'*10
374 with open(TESTFN2, 'wb') as f:
375 f.write(data)
376
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000377 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
378 zipfp.write(TESTFN, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000379
Ezio Melotti35386712009-12-31 13:22:41 +0000380 with open(TESTFN2, 'rb') as f:
381 f.seek(len(data))
382 with zipfile.ZipFile(f, "r") as zipfp:
383 self.assertEqual(zipfp.namelist(), [TESTFN])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000384
R David Murray4fbb9db2011-06-09 15:50:51 -0400385 def test_ignores_newline_at_end(self):
386 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
387 zipfp.write(TESTFN, TESTFN)
388 with open(TESTFN2, 'a') as f:
389 f.write("\r\n\00\00\00")
390 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
391 self.assertIsInstance(zipfp, zipfile.ZipFile)
392
393 def test_ignores_stuff_appended_past_comments(self):
394 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
395 zipfp.comment = b"this is a comment"
396 zipfp.write(TESTFN, TESTFN)
397 with open(TESTFN2, 'a') as f:
398 f.write("abcdef\r\n")
399 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
400 self.assertIsInstance(zipfp, zipfile.ZipFile)
401 self.assertEqual(zipfp.comment, b"this is a comment")
402
Ezio Melottiafd0d112009-07-15 17:17:17 +0000403 def test_write_default_name(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000404 """Check that calling ZipFile.write without arcname specified
405 produces the expected result."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000406 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
407 zipfp.write(TESTFN)
Brian Curtin8fb9b862010-11-18 02:15:28 +0000408 with open(TESTFN, "rb") as f:
409 self.assertEqual(zipfp.read(TESTFN), f.read())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000410
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300411 def test_write_to_readonly(self):
412 """Check that trying to call write() on a readonly ZipFile object
413 raises a RuntimeError."""
414 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
415 zipfp.writestr("somefile.txt", "bogus")
416
417 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
418 self.assertRaises(RuntimeError, zipfp.write, TESTFN)
419
420 def test_add_file_before_1980(self):
421 # Set atime and mtime to 1970-01-01
422 os.utime(TESTFN, (0, 0))
423 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
424 self.assertRaises(ValueError, zipfp.write, TESTFN)
425
Serhiy Storchaka5ce3f102014-01-09 14:50:20 +0200426
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300427@requires_zlib
428class DeflateTestsWithSourceFile(AbstractTestsWithSourceFile,
429 unittest.TestCase):
430 compression = zipfile.ZIP_DEFLATED
431
Ezio Melottiafd0d112009-07-15 17:17:17 +0000432 def test_per_file_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000433 """Check that files within a Zip archive can have different
434 compression options."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000435 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
436 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
437 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
438 sinfo = zipfp.getinfo('storeme')
439 dinfo = zipfp.getinfo('deflateme')
440 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
441 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000442
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300443@requires_bz2
444class Bzip2TestsWithSourceFile(AbstractTestsWithSourceFile,
445 unittest.TestCase):
446 compression = zipfile.ZIP_BZIP2
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000447
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300448@requires_lzma
449class LzmaTestsWithSourceFile(AbstractTestsWithSourceFile,
450 unittest.TestCase):
451 compression = zipfile.ZIP_LZMA
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000452
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300453
454class AbstractTestZip64InSmallFiles:
455 # These tests test the ZIP64 functionality without using large files,
456 # see test_zipfile64 for proper tests.
457
458 @classmethod
459 def setUpClass(cls):
460 line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
461 for i in range(0, FIXEDTEST_SIZE))
462 cls.data = b'\n'.join(line_gen)
463
464 def setUp(self):
465 self._limit = zipfile.ZIP64_LIMIT
466 zipfile.ZIP64_LIMIT = 5
467
468 # Make a source file with some lines
469 with open(TESTFN, "wb") as fp:
470 fp.write(self.data)
471
472 def zip_test(self, f, compression):
473 # Create the ZIP archive
474 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
475 zipfp.write(TESTFN, "another.name")
476 zipfp.write(TESTFN, TESTFN)
477 zipfp.writestr("strfile", self.data)
478
479 # Read the ZIP archive
480 with zipfile.ZipFile(f, "r", compression) as zipfp:
481 self.assertEqual(zipfp.read(TESTFN), self.data)
482 self.assertEqual(zipfp.read("another.name"), self.data)
483 self.assertEqual(zipfp.read("strfile"), self.data)
484
485 # Print the ZIP directory
486 fp = io.StringIO()
487 zipfp.printdir(fp)
488
489 directory = fp.getvalue()
490 lines = directory.splitlines()
491 self.assertEqual(len(lines), 4) # Number of files + header
492
493 self.assertIn('File Name', lines[0])
494 self.assertIn('Modified', lines[0])
495 self.assertIn('Size', lines[0])
496
497 fn, date, time_, size = lines[1].split()
498 self.assertEqual(fn, 'another.name')
499 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
500 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
501 self.assertEqual(size, str(len(self.data)))
502
503 # Check the namelist
504 names = zipfp.namelist()
505 self.assertEqual(len(names), 3)
506 self.assertIn(TESTFN, names)
507 self.assertIn("another.name", names)
508 self.assertIn("strfile", names)
509
510 # Check infolist
511 infos = zipfp.infolist()
512 names = [i.filename for i in infos]
513 self.assertEqual(len(names), 3)
514 self.assertIn(TESTFN, names)
515 self.assertIn("another.name", names)
516 self.assertIn("strfile", names)
517 for i in infos:
518 self.assertEqual(i.file_size, len(self.data))
519
520 # check getinfo
521 for nm in (TESTFN, "another.name", "strfile"):
522 info = zipfp.getinfo(nm)
523 self.assertEqual(info.filename, nm)
524 self.assertEqual(info.file_size, len(self.data))
525
526 # Check that testzip doesn't raise an exception
527 zipfp.testzip()
528
529 def test_basic(self):
530 for f in get_files(self):
531 self.zip_test(f, self.compression)
532
533 def tearDown(self):
534 zipfile.ZIP64_LIMIT = self._limit
535 unlink(TESTFN)
536 unlink(TESTFN2)
537
538
539class StoredTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
540 unittest.TestCase):
541 compression = zipfile.ZIP_STORED
542
543 def large_file_exception_test(self, f, compression):
Serhiy Storchaka235c5e02013-11-23 15:55:38 +0200544 with zipfile.ZipFile(f, "w", compression, allowZip64=False) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300545 self.assertRaises(zipfile.LargeZipFile,
546 zipfp.write, TESTFN, "another.name")
547
548 def large_file_exception_test2(self, f, compression):
Serhiy Storchaka235c5e02013-11-23 15:55:38 +0200549 with zipfile.ZipFile(f, "w", compression, allowZip64=False) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300550 self.assertRaises(zipfile.LargeZipFile,
551 zipfp.writestr, "another.name", self.data)
552
553 def test_large_file_exception(self):
554 for f in get_files(self):
555 self.large_file_exception_test(f, zipfile.ZIP_STORED)
556 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
557
558 def test_absolute_arcnames(self):
559 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
560 allowZip64=True) as zipfp:
561 zipfp.write(TESTFN, "/absolute")
562
563 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
564 self.assertEqual(zipfp.namelist(), ["absolute"])
565
566@requires_zlib
567class DeflateTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
568 unittest.TestCase):
569 compression = zipfile.ZIP_DEFLATED
570
571@requires_bz2
572class Bzip2TestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
573 unittest.TestCase):
574 compression = zipfile.ZIP_BZIP2
575
576@requires_lzma
577class LzmaTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
578 unittest.TestCase):
579 compression = zipfile.ZIP_LZMA
580
581
582class PyZipFileTests(unittest.TestCase):
583 def assertCompiledIn(self, name, namelist):
584 if name + 'o' not in namelist:
585 self.assertIn(name + 'c', namelist)
586
587 def test_write_pyfile(self):
588 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
589 fn = __file__
590 if fn.endswith('.pyc') or fn.endswith('.pyo'):
591 path_split = fn.split(os.sep)
592 if os.altsep is not None:
593 path_split.extend(fn.split(os.altsep))
594 if '__pycache__' in path_split:
Serhiy Storchaka9068e4d2013-07-22 21:02:14 +0300595 fn = importlib.util.source_from_cache(fn)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300596 else:
597 fn = fn[:-1]
598
599 zipfp.writepy(fn)
600
601 bn = os.path.basename(fn)
602 self.assertNotIn(bn, zipfp.namelist())
603 self.assertCompiledIn(bn, zipfp.namelist())
604
605 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
606 fn = __file__
607 if fn.endswith(('.pyc', '.pyo')):
608 fn = fn[:-1]
609
610 zipfp.writepy(fn, "testpackage")
611
612 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
613 self.assertNotIn(bn, zipfp.namelist())
614 self.assertCompiledIn(bn, zipfp.namelist())
615
616 def test_write_python_package(self):
617 import email
618 packagedir = os.path.dirname(email.__file__)
619
620 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
621 zipfp.writepy(packagedir)
622
623 # Check for a couple of modules at different levels of the
624 # hierarchy
625 names = zipfp.namelist()
626 self.assertCompiledIn('email/__init__.py', names)
627 self.assertCompiledIn('email/mime/text.py', names)
628
Christian Tismer59202e52013-10-21 03:59:23 +0200629 def test_write_filtered_python_package(self):
630 import test
631 packagedir = os.path.dirname(test.__file__)
632
633 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
634
Christian Tismer59202e52013-10-21 03:59:23 +0200635 # first make sure that the test folder gives error messages
Georg Brandla6065422013-10-21 08:29:29 +0200636 # (on the badsyntax_... files)
637 with captured_stdout() as reportSIO:
638 zipfp.writepy(packagedir)
Christian Tismer59202e52013-10-21 03:59:23 +0200639 reportStr = reportSIO.getvalue()
640 self.assertTrue('SyntaxError' in reportStr)
641
Christian Tismer410d9312013-10-22 04:09:28 +0200642 # then check that the filter works on the whole package
Georg Brandla6065422013-10-21 08:29:29 +0200643 with captured_stdout() as reportSIO:
644 zipfp.writepy(packagedir, filterfunc=lambda whatever: False)
Christian Tismer59202e52013-10-21 03:59:23 +0200645 reportStr = reportSIO.getvalue()
646 self.assertTrue('SyntaxError' not in reportStr)
647
Christian Tismer410d9312013-10-22 04:09:28 +0200648 # then check that the filter works on individual files
Serhiy Storchakac46d1fa2014-01-20 21:59:33 +0200649 with captured_stdout() as reportSIO, self.assertWarns(UserWarning):
Christian Tismer410d9312013-10-22 04:09:28 +0200650 zipfp.writepy(packagedir, filterfunc=lambda fn:
651 'bad' not in fn)
652 reportStr = reportSIO.getvalue()
653 if reportStr:
654 print(reportStr)
655 self.assertTrue('SyntaxError' not in reportStr)
656
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300657 def test_write_with_optimization(self):
658 import email
659 packagedir = os.path.dirname(email.__file__)
660 # use .pyc if running test in optimization mode,
661 # use .pyo if running test in debug mode
662 optlevel = 1 if __debug__ else 0
663 ext = '.pyo' if optlevel == 1 else '.pyc'
664
665 with TemporaryFile() as t, \
Christian Tismer59202e52013-10-21 03:59:23 +0200666 zipfile.PyZipFile(t, "w", optimize=optlevel) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300667 zipfp.writepy(packagedir)
668
669 names = zipfp.namelist()
670 self.assertIn('email/__init__' + ext, names)
671 self.assertIn('email/mime/text' + ext, names)
672
673 def test_write_python_directory(self):
674 os.mkdir(TESTFN2)
675 try:
676 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
677 fp.write("print(42)\n")
678
679 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
680 fp.write("print(42 * 42)\n")
681
682 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
683 fp.write("bla bla bla\n")
684
685 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
686 zipfp.writepy(TESTFN2)
687
688 names = zipfp.namelist()
689 self.assertCompiledIn('mod1.py', names)
690 self.assertCompiledIn('mod2.py', names)
691 self.assertNotIn('mod2.txt', names)
692
693 finally:
694 shutil.rmtree(TESTFN2)
695
Christian Tismer410d9312013-10-22 04:09:28 +0200696 def test_write_python_directory_filtered(self):
697 os.mkdir(TESTFN2)
698 try:
699 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
700 fp.write("print(42)\n")
701
702 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
703 fp.write("print(42 * 42)\n")
704
705 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
706 zipfp.writepy(TESTFN2, filterfunc=lambda fn:
707 not fn.endswith('mod2.py'))
708
709 names = zipfp.namelist()
710 self.assertCompiledIn('mod1.py', names)
711 self.assertNotIn('mod2.py', names)
712
713 finally:
714 shutil.rmtree(TESTFN2)
715
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300716 def test_write_non_pyfile(self):
717 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
718 with open(TESTFN, 'w') as f:
719 f.write('most definitely not a python file')
720 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
721 os.remove(TESTFN)
722
723 def test_write_pyfile_bad_syntax(self):
724 os.mkdir(TESTFN2)
725 try:
726 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
727 fp.write("Bad syntax in python file\n")
728
729 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
730 # syntax errors are printed to stdout
731 with captured_stdout() as s:
732 zipfp.writepy(os.path.join(TESTFN2, "mod1.py"))
733
734 self.assertIn("SyntaxError", s.getvalue())
735
736 # as it will not have compiled the python file, it will
737 # include the .py file not .pyc or .pyo
738 names = zipfp.namelist()
739 self.assertIn('mod1.py', names)
740 self.assertNotIn('mod1.pyc', names)
741 self.assertNotIn('mod1.pyo', names)
742
743 finally:
744 shutil.rmtree(TESTFN2)
745
746
747class ExtractTests(unittest.TestCase):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000748 def test_extract(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000749 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
750 for fpath, fdata in SMALL_TEST_DATA:
751 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000752
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000753 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
754 for fpath, fdata in SMALL_TEST_DATA:
755 writtenfile = zipfp.extract(fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000756
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000757 # make sure it was written to the right place
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800758 correctfile = os.path.join(os.getcwd(), fpath)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000759 correctfile = os.path.normpath(correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000760
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000761 self.assertEqual(writtenfile, correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000762
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000763 # make sure correct data is in correct file
Brian Curtin8fb9b862010-11-18 02:15:28 +0000764 with open(writtenfile, "rb") as f:
765 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000766
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000767 os.remove(writtenfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000768
769 # remove the test file subdirectories
770 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
771
Ezio Melottiafd0d112009-07-15 17:17:17 +0000772 def test_extract_all(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000773 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
774 for fpath, fdata in SMALL_TEST_DATA:
775 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000776
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000777 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
778 zipfp.extractall()
779 for fpath, fdata in SMALL_TEST_DATA:
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800780 outfile = os.path.join(os.getcwd(), fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000781
Brian Curtin8fb9b862010-11-18 02:15:28 +0000782 with open(outfile, "rb") as f:
783 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000784
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000785 os.remove(outfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000786
787 # remove the test file subdirectories
788 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
789
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800790 def check_file(self, filename, content):
791 self.assertTrue(os.path.isfile(filename))
792 with open(filename, 'rb') as f:
793 self.assertEqual(f.read(), content)
794
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800795 def test_sanitize_windows_name(self):
796 san = zipfile.ZipFile._sanitize_windows_name
797 # Passing pathsep in allows this test to work regardless of platform.
798 self.assertEqual(san(r',,?,C:,foo,bar/z', ','), r'_,C_,foo,bar/z')
799 self.assertEqual(san(r'a\b,c<d>e|f"g?h*i', ','), r'a\b,c_d_e_f_g_h_i')
800 self.assertEqual(san('../../foo../../ba..r', '/'), r'foo/ba..r')
801
802 def test_extract_hackers_arcnames_common_cases(self):
803 common_hacknames = [
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800804 ('../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'),
811 ('/foo/../../bar', 'foo/bar'),
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800812 ]
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800813 self._test_extract_hackers_arcnames(common_hacknames)
814
815 @unittest.skipIf(os.path.sep != '\\', 'Requires \\ as path separator.')
816 def test_extract_hackers_arcnames_windows_only(self):
817 """Test combination of path fixing and windows name sanitization."""
818 windows_hacknames = [
Christian Tismer59202e52013-10-21 03:59:23 +0200819 (r'..\foo\bar', 'foo/bar'),
820 (r'..\/foo\/bar', 'foo/bar'),
821 (r'foo/\..\/bar', 'foo/bar'),
822 (r'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'C:\foo\bar', 'foo/bar'),
827 (r'//conky/mountpoint/foo/bar', 'foo/bar'),
828 (r'\\conky\mountpoint\foo\bar', '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'\\conky\\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
833 (r'//?/C:/foo/bar', 'foo/bar'),
834 (r'\\?\C:\foo\bar', 'foo/bar'),
835 (r'C:/../C:/foo/bar', 'C_/foo/bar'),
836 (r'a:b\c<d>e|f"g?h*i', 'b/c_d_e_f_g_h_i'),
837 ('../../foo../../ba..r', 'foo/ba..r'),
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800838 ]
839 self._test_extract_hackers_arcnames(windows_hacknames)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800840
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800841 @unittest.skipIf(os.path.sep != '/', r'Requires / as path separator.')
842 def test_extract_hackers_arcnames_posix_only(self):
843 posix_hacknames = [
844 ('//foo/bar', 'foo/bar'),
845 ('../../foo../../ba..r', 'foo../ba..r'),
846 (r'foo/..\bar', r'foo/..\bar'),
847 ]
848 self._test_extract_hackers_arcnames(posix_hacknames)
849
850 def _test_extract_hackers_arcnames(self, hacknames):
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800851 for arcname, fixedname in hacknames:
852 content = b'foobar' + arcname.encode()
853 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipfp:
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200854 zinfo = zipfile.ZipInfo()
855 # preserve backslashes
856 zinfo.filename = arcname
857 zinfo.external_attr = 0o600 << 16
858 zipfp.writestr(zinfo, content)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800859
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200860 arcname = arcname.replace(os.sep, "/")
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800861 targetpath = os.path.join('target', 'subdir', 'subsub')
862 correctfile = os.path.join(targetpath, *fixedname.split('/'))
863
864 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
865 writtenfile = zipfp.extract(arcname, targetpath)
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200866 self.assertEqual(writtenfile, correctfile,
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800867 msg='extract %r: %r != %r' %
868 (arcname, writtenfile, correctfile))
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800869 self.check_file(correctfile, content)
870 shutil.rmtree('target')
871
872 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
873 zipfp.extractall(targetpath)
874 self.check_file(correctfile, content)
875 shutil.rmtree('target')
876
877 correctfile = os.path.join(os.getcwd(), *fixedname.split('/'))
878
879 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
880 writtenfile = zipfp.extract(arcname)
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200881 self.assertEqual(writtenfile, correctfile,
882 msg="extract %r" % arcname)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800883 self.check_file(correctfile, content)
884 shutil.rmtree(fixedname.split('/')[0])
885
886 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
887 zipfp.extractall()
888 self.check_file(correctfile, content)
889 shutil.rmtree(fixedname.split('/')[0])
890
891 os.remove(TESTFN2)
892
Ronald Oussorenee5c8852010-02-07 20:24:02 +0000893
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300894class OtherTests(unittest.TestCase):
895 def test_open_via_zip_info(self):
896 # Create the ZIP archive
897 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
898 zipfp.writestr("name", "foo")
Serhiy Storchaka9b7a1a12014-01-20 21:57:40 +0200899 with self.assertWarns(UserWarning):
900 zipfp.writestr("name", "bar")
901 self.assertEqual(zipfp.namelist(), ["name"] * 2)
Ronald Oussorenee5c8852010-02-07 20:24:02 +0000902
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300903 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
904 infos = zipfp.infolist()
905 data = b""
906 for info in infos:
907 with zipfp.open(info) as zipopen:
908 data += zipopen.read()
909 self.assertIn(data, {b"foobar", b"barfoo"})
910 data = b""
911 for info in infos:
912 data += zipfp.read(info)
913 self.assertIn(data, {b"foobar", b"barfoo"})
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200914
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +0200915 def test_universal_deprecation(self):
916 f = io.BytesIO()
917 with zipfile.ZipFile(f, "w") as zipfp:
918 zipfp.writestr('spam.txt', b'ababagalamaga')
919
920 with zipfile.ZipFile(f, "r") as zipfp:
921 for mode in 'U', 'rU':
922 with self.assertWarns(DeprecationWarning):
923 zipopen = zipfp.open('spam.txt', mode)
924 zipopen.close()
925
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300926 def test_universal_readaheads(self):
927 f = io.BytesIO()
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +0200928
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300929 data = b'a\r\n' * 16 * 1024
930 with zipfile.ZipFile(f, 'w', zipfile.ZIP_STORED) as zipfp:
931 zipfp.writestr(TESTFN, data)
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000932
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300933 data2 = b''
934 with zipfile.ZipFile(f, 'r') as zipfp, \
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +0200935 openU(zipfp, TESTFN) as zipopen:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300936 for line in zipopen:
937 data2 += line
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000938
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300939 self.assertEqual(data, data2.replace(b'\n', b'\r\n'))
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000940
Gregory P. Smithb0d9ca922009-07-07 05:06:04 +0000941 def test_writestr_extended_local_header_issue1202(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000942 with zipfile.ZipFile(TESTFN2, 'w') as orig_zip:
943 for data in 'abcdefghijklmnop':
944 zinfo = zipfile.ZipInfo(data)
945 zinfo.flag_bits |= 0x08 # Include an extended local header.
946 orig_zip.writestr(zinfo, data)
947
948 def test_close(self):
949 """Check that the zipfile is closed after the 'with' block."""
950 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
951 for fpath, fdata in SMALL_TEST_DATA:
952 zipfp.writestr(fpath, fdata)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300953 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
954 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000955
956 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300957 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
958 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000959
960 def test_close_on_exception(self):
961 """Check that the zipfile is closed if an exception is raised in the
962 'with' block."""
963 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
964 for fpath, fdata in SMALL_TEST_DATA:
965 zipfp.writestr(fpath, fdata)
966
967 try:
968 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
Georg Brandl4d540882010-10-28 06:42:33 +0000969 raise zipfile.BadZipFile()
970 except zipfile.BadZipFile:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300971 self.assertIsNone(zipfp2.fp, 'zipfp is not closed')
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000972
Martin v. Löwisd099b562012-05-01 14:08:22 +0200973 def test_unsupported_version(self):
974 # File has an extract_version of 120
975 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 +0200976 b'\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00xPK\x01\x02x\x03x\x00\x00\x00\x00'
977 b'\x00!p\xa1@\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00'
978 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00\x00xPK\x05\x06'
979 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 +0300980
Martin v. Löwisd099b562012-05-01 14:08:22 +0200981 self.assertRaises(NotImplementedError, zipfile.ZipFile,
982 io.BytesIO(data), 'r')
983
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300984 @requires_zlib
985 def test_read_unicode_filenames(self):
986 # bug #10801
987 fname = findfile('zip_cp437_header.zip')
988 with zipfile.ZipFile(fname) as zipfp:
989 for name in zipfp.namelist():
990 zipfp.open(name).close()
991
992 def test_write_unicode_filenames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000993 with zipfile.ZipFile(TESTFN, "w") as zf:
994 zf.writestr("foo.txt", "Test for unicode filename")
995 zf.writestr("\xf6.txt", "Test for unicode filename")
Ezio Melottie9615932010-01-24 19:26:24 +0000996 self.assertIsInstance(zf.infolist()[0].filename, str)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000997
998 with zipfile.ZipFile(TESTFN, "r") as zf:
999 self.assertEqual(zf.filelist[0].filename, "foo.txt")
1000 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
Martin v. Löwis8570f6a2008-05-05 17:44:38 +00001001
Ezio Melottiafd0d112009-07-15 17:17:17 +00001002 def test_create_non_existent_file_for_append(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001003 if os.path.exists(TESTFN):
1004 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001005
Thomas Wouterscf297e42007-02-23 15:07:44 +00001006 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001007 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +00001008
Thomas Wouterscf297e42007-02-23 15:07:44 +00001009 try:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001010 with zipfile.ZipFile(TESTFN, 'a') as zf:
1011 zf.writestr(filename, content)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001012 except OSError:
Thomas Wouterscf297e42007-02-23 15:07:44 +00001013 self.fail('Could not append data to a non-existent zip file.')
1014
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001015 self.assertTrue(os.path.exists(TESTFN))
Thomas Wouterscf297e42007-02-23 15:07:44 +00001016
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001017 with zipfile.ZipFile(TESTFN, 'r') as zf:
1018 self.assertEqual(zf.read(filename), content)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001019
Ezio Melottiafd0d112009-07-15 17:17:17 +00001020 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001021 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti35386712009-12-31 13:22:41 +00001022 # it opens if there's an error in the file. If it doesn't, the
1023 # traceback holds a reference to the ZipFile object and, indirectly,
1024 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001025 # On Windows, this causes the os.unlink() call to fail because the
1026 # underlying file is still open. This is SF bug #412214.
1027 #
Ezio Melotti35386712009-12-31 13:22:41 +00001028 with open(TESTFN, "w") as fp:
1029 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001030 try:
1031 zf = zipfile.ZipFile(TESTFN)
Georg Brandl4d540882010-10-28 06:42:33 +00001032 except zipfile.BadZipFile:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001033 pass
1034
Ezio Melottiafd0d112009-07-15 17:17:17 +00001035 def test_is_zip_erroneous_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001036 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001037 # - passing a filename
1038 with open(TESTFN, "w") as fp:
1039 fp.write("this is not a legal zip file\n")
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001040 self.assertFalse(zipfile.is_zipfile(TESTFN))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001041 # - passing a file object
1042 with open(TESTFN, "rb") as fp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001043 self.assertFalse(zipfile.is_zipfile(fp))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001044 # - passing a file-like object
1045 fp = io.BytesIO()
1046 fp.write(b"this is not a legal zip file\n")
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001047 self.assertFalse(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001048 fp.seek(0, 0)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001049 self.assertFalse(zipfile.is_zipfile(fp))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001050
Serhiy Storchakad2b15272013-01-31 15:27:07 +02001051 def test_damaged_zipfile(self):
1052 """Check that zipfiles with missing bytes at the end raise BadZipFile."""
1053 # - Create a valid zip file
1054 fp = io.BytesIO()
1055 with zipfile.ZipFile(fp, mode="w") as zipf:
1056 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
1057 zipfiledata = fp.getvalue()
1058
1059 # - Now create copies of it missing the last N bytes and make sure
1060 # a BadZipFile exception is raised when we try to open it
1061 for N in range(len(zipfiledata)):
1062 fp = io.BytesIO(zipfiledata[:N])
1063 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, fp)
1064
Ezio Melottiafd0d112009-07-15 17:17:17 +00001065 def test_is_zip_valid_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001066 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001067 # - passing a filename
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001068 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1069 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
1070
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001071 self.assertTrue(zipfile.is_zipfile(TESTFN))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001072 # - passing a file object
1073 with open(TESTFN, "rb") as fp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001074 self.assertTrue(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001075 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001076 zip_contents = fp.read()
1077 # - passing a file-like object
1078 fp = io.BytesIO()
1079 fp.write(zip_contents)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001080 self.assertTrue(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001081 fp.seek(0, 0)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001082 self.assertTrue(zipfile.is_zipfile(fp))
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001083
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001084 def test_non_existent_file_raises_OSError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001085 # make sure we don't raise an AttributeError when a partially-constructed
1086 # ZipFile instance is finalized; this tests for regression on SF tracker
1087 # bug #403871.
1088
1089 # The bug we're testing for caused an AttributeError to be raised
1090 # when a ZipFile instance was created for a file that did not
1091 # exist; the .fp member was not initialized but was needed by the
1092 # __del__() method. Since the AttributeError is in the __del__(),
1093 # it is ignored, but the user should be sufficiently annoyed by
1094 # the message on the output that regression will be noticed
1095 # quickly.
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001096 self.assertRaises(OSError, zipfile.ZipFile, TESTFN)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001097
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001098 def test_empty_file_raises_BadZipFile(self):
1099 f = open(TESTFN, 'w')
1100 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001101 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001102
Ezio Melotti35386712009-12-31 13:22:41 +00001103 with open(TESTFN, 'w') as fp:
1104 fp.write("short file")
Georg Brandl4d540882010-10-28 06:42:33 +00001105 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001106
Ezio Melottiafd0d112009-07-15 17:17:17 +00001107 def test_closed_zip_raises_RuntimeError(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001108 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001109 data = io.BytesIO()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001110 with zipfile.ZipFile(data, mode="w") as zipf:
1111 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001112
Andrew Svetlov737fb892012-12-18 21:14:22 +02001113 # This is correct; calling .read on a closed ZipFile should raise
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001114 # a RuntimeError, and so should calling .testzip. An earlier
1115 # version of .testzip would swallow this exception (and any other)
1116 # and report that the first file in the archive was corrupt.
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001117 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
1118 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001119 self.assertRaises(RuntimeError, zipf.testzip)
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001120 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Brian Curtin8fb9b862010-11-18 02:15:28 +00001121 with open(TESTFN, 'w') as f:
1122 f.write('zipfile test data')
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001123 self.assertRaises(RuntimeError, zipf.write, TESTFN)
1124
Ezio Melottiafd0d112009-07-15 17:17:17 +00001125 def test_bad_constructor_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001126 """Check that bad modes passed to ZipFile constructor are caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001127 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
1128
Ezio Melottiafd0d112009-07-15 17:17:17 +00001129 def test_bad_open_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001130 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001131 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1132 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1133
1134 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001135 # read the data to make sure the file is there
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001136 zipf.read("foo.txt")
1137 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001138
Ezio Melottiafd0d112009-07-15 17:17:17 +00001139 def test_read0(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001140 """Check that calling read(0) on a ZipExtFile object returns an empty
1141 string and doesn't advance file pointer."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001142 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1143 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1144 # read the data to make sure the file is there
Brian Curtin8fb9b862010-11-18 02:15:28 +00001145 with zipf.open("foo.txt") as f:
1146 for i in range(FIXEDTEST_SIZE):
1147 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001148
Brian Curtin8fb9b862010-11-18 02:15:28 +00001149 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001150
Ezio Melottiafd0d112009-07-15 17:17:17 +00001151 def test_open_non_existent_item(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001152 """Check that attempting to call open() for an item that doesn't
1153 exist in the archive raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001154 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1155 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001156
Ezio Melottiafd0d112009-07-15 17:17:17 +00001157 def test_bad_compression_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001158 """Check that bad compression methods passed to ZipFile.open are
1159 caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001160 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
1161
Martin v. Löwisb3260f02012-05-01 08:38:01 +02001162 def test_unsupported_compression(self):
1163 # data is declared as shrunk, but actually deflated
1164 data = (b'PK\x03\x04.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00'
Christian Tismer59202e52013-10-21 03:59:23 +02001165 b'\x00\x02\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00x\x03\x00PK\x01'
1166 b'\x02.\x03.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00\x00\x02\x00\x00'
1167 b'\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
1168 b'\x80\x01\x00\x00\x00\x00xPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00'
1169 b'/\x00\x00\x00!\x00\x00\x00\x00\x00')
Martin v. Löwisb3260f02012-05-01 08:38:01 +02001170 with zipfile.ZipFile(io.BytesIO(data), 'r') as zipf:
1171 self.assertRaises(NotImplementedError, zipf.open, 'x')
1172
Ezio Melottiafd0d112009-07-15 17:17:17 +00001173 def test_null_byte_in_filename(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001174 """Check that a filename containing a null byte is properly
1175 terminated."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001176 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1177 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
1178 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001179
Ezio Melottiafd0d112009-07-15 17:17:17 +00001180 def test_struct_sizes(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001181 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001182 self.assertEqual(zipfile.sizeEndCentDir, 22)
1183 self.assertEqual(zipfile.sizeCentralDir, 46)
1184 self.assertEqual(zipfile.sizeEndCentDir64, 56)
1185 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
1186
Ezio Melottiafd0d112009-07-15 17:17:17 +00001187 def test_comments(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001188 """Check that comments on the archive are handled properly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001189
1190 # check default comment is empty
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001191 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1192 self.assertEqual(zipf.comment, b'')
1193 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1194
1195 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1196 self.assertEqual(zipfr.comment, b'')
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001197
1198 # check a simple short comment
1199 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001200 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1201 zipf.comment = comment
1202 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1203 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1204 self.assertEqual(zipf.comment, comment)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001205
1206 # check a comment of max length
1207 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
1208 comment2 = comment2.encode("ascii")
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001209 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1210 zipf.comment = comment2
1211 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1212
1213 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1214 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001215
1216 # check a comment that is too long is truncated
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001217 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
Serhiy Storchaka9b7a1a12014-01-20 21:57:40 +02001218 with self.assertWarns(UserWarning):
1219 zipf.comment = comment2 + b'oops'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001220 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1221 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1222 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001223
Antoine Pitrouc3991852012-06-30 17:31:37 +02001224 # check that comments are correctly modified in append mode
1225 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1226 zipf.comment = b"original comment"
1227 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1228 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1229 zipf.comment = b"an updated comment"
1230 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1231 self.assertEqual(zipf.comment, b"an updated comment")
1232
1233 # check that comments are correctly shortened in append mode
1234 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1235 zipf.comment = b"original comment that's longer"
1236 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1237 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1238 zipf.comment = b"shorter comment"
1239 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1240 self.assertEqual(zipf.comment, b"shorter comment")
1241
R David Murrayf50b38a2012-04-12 18:44:58 -04001242 def test_unicode_comment(self):
1243 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1244 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1245 with self.assertRaises(TypeError):
1246 zipf.comment = "this is an error"
1247
1248 def test_change_comment_in_empty_archive(self):
1249 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1250 self.assertFalse(zipf.filelist)
1251 zipf.comment = b"this is a comment"
1252 with zipfile.ZipFile(TESTFN, "r") as zipf:
1253 self.assertEqual(zipf.comment, b"this is a comment")
1254
1255 def test_change_comment_in_nonempty_archive(self):
1256 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1257 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1258 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1259 self.assertTrue(zipf.filelist)
1260 zipf.comment = b"this is a comment"
1261 with zipfile.ZipFile(TESTFN, "r") as zipf:
1262 self.assertEqual(zipf.comment, b"this is a comment")
1263
Georg Brandl268e4d42010-10-14 06:59:45 +00001264 def test_empty_zipfile(self):
1265 # Check that creating a file in 'w' or 'a' mode and closing without
1266 # adding any files to the archives creates a valid empty ZIP file
1267 zipf = zipfile.ZipFile(TESTFN, mode="w")
1268 zipf.close()
1269 try:
1270 zipf = zipfile.ZipFile(TESTFN, mode="r")
1271 except zipfile.BadZipFile:
1272 self.fail("Unable to create empty ZIP file in 'w' mode")
1273
1274 zipf = zipfile.ZipFile(TESTFN, mode="a")
1275 zipf.close()
1276 try:
1277 zipf = zipfile.ZipFile(TESTFN, mode="r")
1278 except:
1279 self.fail("Unable to create empty ZIP file in 'a' mode")
1280
1281 def test_open_empty_file(self):
1282 # Issue 1710703: Check that opening a file with less than 22 bytes
Georg Brandl4d540882010-10-28 06:42:33 +00001283 # raises a BadZipFile exception (rather than the previously unhelpful
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001284 # OSError)
Georg Brandl268e4d42010-10-14 06:59:45 +00001285 f = open(TESTFN, 'w')
1286 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001287 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN, 'r')
Georg Brandl268e4d42010-10-14 06:59:45 +00001288
Senthil Kumaran29fa9d42011-10-20 01:46:00 +08001289 def test_create_zipinfo_before_1980(self):
1290 self.assertRaises(ValueError,
1291 zipfile.ZipInfo, 'seventies', (1979, 1, 1, 0, 0, 0))
1292
Guido van Rossumd8faa362007-04-27 19:54:29 +00001293 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001294 unlink(TESTFN)
1295 unlink(TESTFN2)
1296
Thomas Wouterscf297e42007-02-23 15:07:44 +00001297
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001298class AbstractBadCrcTests:
1299 def test_testzip_with_bad_crc(self):
1300 """Tests that files with bad CRCs return their name from testzip."""
1301 zipdata = self.zip_with_bad_crc
1302
1303 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1304 # testzip returns the name of the first corrupt file, or None
1305 self.assertEqual('afile', zipf.testzip())
1306
1307 def test_read_with_bad_crc(self):
1308 """Tests that files with bad CRCs raise a BadZipFile exception when read."""
1309 zipdata = self.zip_with_bad_crc
1310
1311 # Using ZipFile.read()
1312 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1313 self.assertRaises(zipfile.BadZipFile, zipf.read, 'afile')
1314
1315 # Using ZipExtFile.read()
1316 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1317 with zipf.open('afile', 'r') as corrupt_file:
1318 self.assertRaises(zipfile.BadZipFile, corrupt_file.read)
1319
1320 # Same with small reads (in order to exercise the buffering logic)
1321 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1322 with zipf.open('afile', 'r') as corrupt_file:
1323 corrupt_file.MIN_READ_SIZE = 2
1324 with self.assertRaises(zipfile.BadZipFile):
1325 while corrupt_file.read(2):
1326 pass
1327
1328
1329class StoredBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1330 compression = zipfile.ZIP_STORED
1331 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001332 b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
1333 b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
1334 b'ilehello,AworldP'
1335 b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
1336 b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
1337 b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
1338 b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
1339 b'\0\0/\0\0\0\0\0')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001340
1341@requires_zlib
1342class DeflateBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1343 compression = zipfile.ZIP_DEFLATED
1344 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001345 b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
1346 b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1347 b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
1348 b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
1349 b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
1350 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
1351 b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
1352 b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001353
1354@requires_bz2
1355class Bzip2BadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1356 compression = zipfile.ZIP_BZIP2
1357 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001358 b'PK\x03\x04\x14\x03\x00\x00\x0c\x00nu\x0c=FA'
1359 b'KE8\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1360 b'ileBZh91AY&SY\xd4\xa8\xca'
1361 b'\x7f\x00\x00\x0f\x11\x80@\x00\x06D\x90\x80 \x00 \xa5'
1362 b'P\xd9!\x03\x03\x13\x13\x13\x89\xa9\xa9\xc2u5:\x9f'
1363 b'\x8b\xb9"\x9c(HjTe?\x80PK\x01\x02\x14'
1364 b'\x03\x14\x03\x00\x00\x0c\x00nu\x0c=FAKE8'
1365 b'\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\x00'
1366 b'\x00 \x80\x80\x81\x00\x00\x00\x00afilePK'
1367 b'\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00\x00[\x00'
1368 b'\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001369
1370@requires_lzma
1371class LzmaBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1372 compression = zipfile.ZIP_LZMA
1373 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001374 b'PK\x03\x04\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
1375 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1376 b'ile\t\x04\x05\x00]\x00\x00\x00\x04\x004\x19I'
1377 b'\xee\x8d\xe9\x17\x89:3`\tq!.8\x00PK'
1378 b'\x01\x02\x14\x03\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
1379 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00'
1380 b'\x00\x00\x00\x00 \x80\x80\x81\x00\x00\x00\x00afil'
1381 b'ePK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00'
1382 b'\x00>\x00\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001383
1384
Thomas Wouterscf297e42007-02-23 15:07:44 +00001385class DecryptionTests(unittest.TestCase):
Ezio Melotti35386712009-12-31 13:22:41 +00001386 """Check that ZIP decryption works. Since the library does not
1387 support encryption at the moment, we use a pre-generated encrypted
1388 ZIP file."""
Thomas Wouterscf297e42007-02-23 15:07:44 +00001389
1390 data = (
Christian Tismer59202e52013-10-21 03:59:23 +02001391 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
1392 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
1393 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
1394 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
1395 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
1396 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
1397 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +00001398 data2 = (
Christian Tismer59202e52013-10-21 03:59:23 +02001399 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
1400 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
1401 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
1402 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
1403 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
1404 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
1405 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
1406 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +00001407
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001408 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +00001409 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +00001410
1411 def setUp(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001412 with open(TESTFN, "wb") as fp:
1413 fp.write(self.data)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001414 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti35386712009-12-31 13:22:41 +00001415 with open(TESTFN2, "wb") as fp:
1416 fp.write(self.data2)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001417 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001418
1419 def tearDown(self):
1420 self.zip.close()
1421 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001422 self.zip2.close()
1423 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001424
Ezio Melottiafd0d112009-07-15 17:17:17 +00001425 def test_no_password(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001426 # Reading the encrypted file without password
1427 # must generate a RunTime exception
1428 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001429 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001430
Ezio Melottiafd0d112009-07-15 17:17:17 +00001431 def test_bad_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001432 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001433 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001434 self.zip2.setpassword(b"perl")
1435 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001436
Ezio Melotti975077a2011-05-19 22:03:22 +03001437 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +00001438 def test_good_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001439 self.zip.setpassword(b"python")
Ezio Melotti35386712009-12-31 13:22:41 +00001440 self.assertEqual(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001441 self.zip2.setpassword(b"12345")
Ezio Melotti35386712009-12-31 13:22:41 +00001442 self.assertEqual(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001443
R. David Murray8d855d82010-12-21 21:53:37 +00001444 def test_unicode_password(self):
1445 self.assertRaises(TypeError, self.zip.setpassword, "unicode")
1446 self.assertRaises(TypeError, self.zip.read, "test.txt", "python")
1447 self.assertRaises(TypeError, self.zip.open, "test.txt", pwd="python")
1448 self.assertRaises(TypeError, self.zip.extract, "test.txt", pwd="python")
1449
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001450class AbstractTestsWithRandomBinaryFiles:
1451 @classmethod
1452 def setUpClass(cls):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001453 datacount = randint(16, 64)*1024 + randint(1, 1024)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001454 cls.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
1455 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001456
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001457 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001458 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +00001459 with open(TESTFN, "wb") as fp:
1460 fp.write(self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001461
1462 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001463 unlink(TESTFN)
1464 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001465
Ezio Melottiafd0d112009-07-15 17:17:17 +00001466 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001467 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001468 with zipfile.ZipFile(f, "w", compression) as zipfp:
1469 zipfp.write(TESTFN, "another.name")
1470 zipfp.write(TESTFN, TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001471
Ezio Melottiafd0d112009-07-15 17:17:17 +00001472 def zip_test(self, f, compression):
1473 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001474
1475 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001476 with zipfile.ZipFile(f, "r", compression) as zipfp:
1477 testdata = zipfp.read(TESTFN)
1478 self.assertEqual(len(testdata), len(self.data))
1479 self.assertEqual(testdata, self.data)
1480 self.assertEqual(zipfp.read("another.name"), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001481
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001482 def test_read(self):
1483 for f in get_files(self):
1484 self.zip_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001485
Ezio Melottiafd0d112009-07-15 17:17:17 +00001486 def zip_open_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 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001492 with zipfp.open(TESTFN) as zipopen1:
1493 while True:
1494 read_data = zipopen1.read(256)
1495 if not read_data:
1496 break
1497 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001498
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001499 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001500 with zipfp.open("another.name") as zipopen2:
1501 while True:
1502 read_data = zipopen2.read(256)
1503 if not read_data:
1504 break
1505 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001506
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001507 testdata1 = b''.join(zipdata1)
1508 self.assertEqual(len(testdata1), len(self.data))
1509 self.assertEqual(testdata1, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001510
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001511 testdata2 = b''.join(zipdata2)
Ezio Melotti35386712009-12-31 13:22:41 +00001512 self.assertEqual(len(testdata2), len(self.data))
1513 self.assertEqual(testdata2, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001514
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001515 def test_open(self):
1516 for f in get_files(self):
1517 self.zip_open_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001518
Ezio Melottiafd0d112009-07-15 17:17:17 +00001519 def zip_random_open_test(self, f, compression):
1520 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001521
1522 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001523 with zipfile.ZipFile(f, "r", compression) as zipfp:
1524 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001525 with zipfp.open(TESTFN) as zipopen1:
1526 while True:
1527 read_data = zipopen1.read(randint(1, 1024))
1528 if not read_data:
1529 break
1530 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001531
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001532 testdata = b''.join(zipdata1)
1533 self.assertEqual(len(testdata), len(self.data))
1534 self.assertEqual(testdata, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001535
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001536 def test_random_open(self):
1537 for f in get_files(self):
1538 self.zip_random_open_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001539
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001540
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001541class StoredTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1542 unittest.TestCase):
1543 compression = zipfile.ZIP_STORED
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001544
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001545@requires_zlib
1546class DeflateTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1547 unittest.TestCase):
1548 compression = zipfile.ZIP_DEFLATED
1549
1550@requires_bz2
1551class Bzip2TestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1552 unittest.TestCase):
1553 compression = zipfile.ZIP_BZIP2
1554
1555@requires_lzma
1556class LzmaTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1557 unittest.TestCase):
1558 compression = zipfile.ZIP_LZMA
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001559
Ezio Melotti76430242009-07-11 18:28:48 +00001560
Ezio Melotti975077a2011-05-19 22:03:22 +03001561@requires_zlib
Guido van Rossumd8faa362007-04-27 19:54:29 +00001562class TestsWithMultipleOpens(unittest.TestCase):
1563 def setUp(self):
1564 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001565 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
1566 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
1567 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001568
Ezio Melottiafd0d112009-07-15 17:17:17 +00001569 def test_same_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001570 # Verify that (when the ZipFile is in control of creating file objects)
1571 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001572 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001573 with zipf.open('ones') as zopen1, zipf.open('ones') as zopen2:
1574 data1 = zopen1.read(500)
1575 data2 = zopen2.read(500)
1576 data1 += zopen1.read(500)
1577 data2 += zopen2.read(500)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001578 self.assertEqual(data1, data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001579
Ezio Melottiafd0d112009-07-15 17:17:17 +00001580 def test_different_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001581 # Verify that (when the ZipFile is in control of creating file objects)
1582 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001583 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001584 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1585 data1 = zopen1.read(500)
1586 data2 = zopen2.read(500)
1587 data1 += zopen1.read(500)
1588 data2 += zopen2.read(500)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001589 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
1590 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001591
Ezio Melottiafd0d112009-07-15 17:17:17 +00001592 def test_interleaved(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001593 # Verify that (when the ZipFile is in control of creating file objects)
1594 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001595 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001596 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1597 data1 = zopen1.read(500)
1598 data2 = zopen2.read(500)
1599 data1 += zopen1.read(500)
1600 data2 += zopen2.read(500)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001601 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
1602 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001603
1604 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001605 unlink(TESTFN2)
1606
Guido van Rossumd8faa362007-04-27 19:54:29 +00001607
Martin v. Löwis59e47792009-01-24 14:10:07 +00001608class TestWithDirectory(unittest.TestCase):
1609 def setUp(self):
1610 os.mkdir(TESTFN2)
1611
Ezio Melottiafd0d112009-07-15 17:17:17 +00001612 def test_extract_dir(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001613 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
1614 zipf.extractall(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001615 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1616 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1617 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1618
Ezio Melottiafd0d112009-07-15 17:17:17 +00001619 def test_bug_6050(self):
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001620 # Extraction should succeed if directories already exist
1621 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottiafd0d112009-07-15 17:17:17 +00001622 self.test_extract_dir()
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001623
Ezio Melottiafd0d112009-07-15 17:17:17 +00001624 def test_store_dir(self):
Martin v. Löwis59e47792009-01-24 14:10:07 +00001625 os.mkdir(os.path.join(TESTFN2, "x"))
1626 zipf = zipfile.ZipFile(TESTFN, "w")
1627 zipf.write(os.path.join(TESTFN2, "x"), "x")
1628 self.assertTrue(zipf.filelist[0].filename.endswith("x/"))
1629
1630 def tearDown(self):
1631 shutil.rmtree(TESTFN2)
1632 if os.path.exists(TESTFN):
Ezio Melotti76430242009-07-11 18:28:48 +00001633 unlink(TESTFN)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001634
Guido van Rossumd8faa362007-04-27 19:54:29 +00001635
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001636class AbstractUniversalNewlineTests:
1637 @classmethod
1638 def setUpClass(cls):
1639 cls.line_gen = [bytes("Test of zipfile line %d." % i, "ascii")
1640 for i in range(FIXEDTEST_SIZE)]
1641 cls.seps = (b'\r', b'\r\n', b'\n')
1642 cls.arcdata = {}
1643 for n, s in enumerate(cls.seps):
1644 cls.arcdata[s] = s.join(cls.line_gen) + s
1645
Guido van Rossumd8faa362007-04-27 19:54:29 +00001646 def setUp(self):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001647 self.arcfiles = {}
Guido van Rossumd8faa362007-04-27 19:54:29 +00001648 for n, s in enumerate(self.seps):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001649 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001650 with open(self.arcfiles[s], "wb") as f:
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001651 f.write(self.arcdata[s])
Guido van Rossumd8faa362007-04-27 19:54:29 +00001652
Ezio Melottiafd0d112009-07-15 17:17:17 +00001653 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001654 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001655 with zipfile.ZipFile(f, "w", compression) as zipfp:
1656 for fn in self.arcfiles.values():
1657 zipfp.write(fn, fn)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001658
Ezio Melottiafd0d112009-07-15 17:17:17 +00001659 def read_test(self, f, compression):
1660 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001661
1662 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001663 with zipfile.ZipFile(f, "r") as zipfp:
1664 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02001665 with openU(zipfp, fn) as fp:
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001666 zipdata = fp.read()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001667 self.assertEqual(self.arcdata[sep], zipdata)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001668
1669 def test_read(self):
1670 for f in get_files(self):
1671 self.read_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001672
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001673 def readline_read_test(self, f, compression):
1674 self.make_test_archive(f, compression)
1675
1676 # Read the ZIP archive
Brian Curtin8fb9b862010-11-18 02:15:28 +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 zipopen:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001680 data = b''
1681 while True:
1682 read = zipopen.readline()
1683 if not read:
1684 break
1685 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001686
Brian Curtin8fb9b862010-11-18 02:15:28 +00001687 read = zipopen.read(5)
1688 if not read:
1689 break
1690 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001691
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001692 self.assertEqual(data, self.arcdata[b'\n'])
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001693
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001694 def test_readline_read(self):
1695 for f in get_files(self):
1696 self.readline_read_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001697
Ezio Melottiafd0d112009-07-15 17:17:17 +00001698 def readline_test(self, f, compression):
1699 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001700
1701 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001702 with zipfile.ZipFile(f, "r") as zipfp:
1703 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02001704 with openU(zipfp, fn) as zipopen:
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001705 for line in self.line_gen:
1706 linedata = zipopen.readline()
1707 self.assertEqual(linedata, line + b'\n')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001708
1709 def test_readline(self):
1710 for f in get_files(self):
1711 self.readline_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001712
Ezio Melottiafd0d112009-07-15 17:17:17 +00001713 def readlines_test(self, f, compression):
1714 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001715
1716 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001717 with zipfile.ZipFile(f, "r") as zipfp:
1718 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02001719 with openU(zipfp, fn) as fp:
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001720 ziplines = fp.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001721 for line, zipline in zip(self.line_gen, ziplines):
1722 self.assertEqual(zipline, line + b'\n')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001723
1724 def test_readlines(self):
1725 for f in get_files(self):
1726 self.readlines_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001727
Ezio Melottiafd0d112009-07-15 17:17:17 +00001728 def iterlines_test(self, f, compression):
1729 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001730
1731 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001732 with zipfile.ZipFile(f, "r") as zipfp:
1733 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02001734 with openU(zipfp, fn) as fp:
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001735 for line, zipline in zip(self.line_gen, fp):
1736 self.assertEqual(zipline, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001737
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001738 def test_iterlines(self):
1739 for f in get_files(self):
1740 self.iterlines_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001741
Guido van Rossumd8faa362007-04-27 19:54:29 +00001742 def tearDown(self):
1743 for sep, fn in self.arcfiles.items():
1744 os.remove(fn)
Ezio Melotti76430242009-07-11 18:28:48 +00001745 unlink(TESTFN)
1746 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001747
1748
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001749class StoredUniversalNewlineTests(AbstractUniversalNewlineTests,
1750 unittest.TestCase):
1751 compression = zipfile.ZIP_STORED
1752
1753@requires_zlib
1754class DeflateUniversalNewlineTests(AbstractUniversalNewlineTests,
1755 unittest.TestCase):
1756 compression = zipfile.ZIP_DEFLATED
1757
1758@requires_bz2
1759class Bzip2UniversalNewlineTests(AbstractUniversalNewlineTests,
1760 unittest.TestCase):
1761 compression = zipfile.ZIP_BZIP2
1762
1763@requires_lzma
1764class LzmaUniversalNewlineTests(AbstractUniversalNewlineTests,
1765 unittest.TestCase):
1766 compression = zipfile.ZIP_LZMA
1767
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001768if __name__ == "__main__":
Brett Cannond5b4e1d2013-06-12 19:57:19 -04001769 unittest.main()