blob: 8589342a80f8823ec90ae1b8024a9e872e2f081b [file] [log] [blame]
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001import contextlib
Ezio Melotti74c96ec2009-07-08 22:24:06 +00002import io
3import os
Georg Brandl5ba11de2011-01-01 10:09:32 +00004import sys
Brett Cannonb57a0852013-06-15 17:32:30 -04005import importlib.util
Serhiy Storchaka503f9082016-02-08 00:02:25 +02006import posixpath
Ezio Melotti35386712009-12-31 13:22:41 +00007import time
Ezio Melotti74c96ec2009-07-08 22:24:06 +00008import struct
9import zipfile
10import unittest
11
Tim Petersa45cacf2004-08-20 03:47:14 +000012
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000013from tempfile import TemporaryFile
Serhiy Storchakafa6bc292013-07-22 21:00:11 +030014from random import randint, random, getrandbits
Tim Petersa19a1682001-03-29 04:36:09 +000015
Victor Stinner57004c62014-09-04 00:49:01 +020016from test.support import (TESTFN, findfile, unlink, rmtree,
Serhiy Storchakac5b75db2013-01-29 20:14:08 +020017 requires_zlib, requires_bz2, requires_lzma,
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +020018 captured_stdout, check_warnings)
Guido van Rossum368f04a2000-04-10 13:23:04 +000019
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000020TESTFN2 = TESTFN + "2"
Martin v. Löwis59e47792009-01-24 14:10:07 +000021TESTFNDIR = TESTFN + "d"
Guido van Rossumb5a755e2007-07-18 18:15:48 +000022FIXEDTEST_SIZE = 1000
Georg Brandl5ba11de2011-01-01 10:09:32 +000023DATAFILES_DIR = 'zipfile_datafiles'
Guido van Rossum368f04a2000-04-10 13:23:04 +000024
Christian Heimes790c8232008-01-07 21:14:23 +000025SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'),
26 ('ziptest2dir/_ziptest2', 'qawsedrftg'),
Gregory P. Smithb47acbf2013-02-01 11:22:43 -080027 ('ziptest2dir/ziptest3dir/_ziptest3', 'azsxdcfvgb'),
Christian Heimes790c8232008-01-07 21:14:23 +000028 ('ziptest2dir/ziptest3dir/ziptest4dir/_ziptest3', '6y7u8i9o0p')]
29
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +020030def getrandbytes(size):
31 return getrandbits(8 * size).to_bytes(size, 'little')
32
Serhiy Storchakafa6bc292013-07-22 21:00:11 +030033def get_files(test):
34 yield TESTFN2
35 with TemporaryFile() as f:
36 yield f
37 test.assertFalse(f.closed)
38 with io.BytesIO() as f:
39 yield f
40 test.assertFalse(f.closed)
Ezio Melotti76430242009-07-11 18:28:48 +000041
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +020042def openU(zipfp, fn):
43 with check_warnings(('', DeprecationWarning)):
44 return zipfp.open(fn, 'rU')
45
Serhiy Storchakafa6bc292013-07-22 21:00:11 +030046class AbstractTestsWithSourceFile:
47 @classmethod
48 def setUpClass(cls):
49 cls.line_gen = [bytes("Zipfile test line %d. random float: %f\n" %
50 (i, random()), "ascii")
51 for i in range(FIXEDTEST_SIZE)]
52 cls.data = b''.join(cls.line_gen)
53
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000054 def setUp(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000055 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +000056 with open(TESTFN, "wb") as fp:
57 fp.write(self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000058
Ezio Melottiafd0d112009-07-15 17:17:17 +000059 def make_test_archive(self, f, compression):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000060 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000061 with zipfile.ZipFile(f, "w", compression) as zipfp:
62 zipfp.write(TESTFN, "another.name")
63 zipfp.write(TESTFN, TESTFN)
64 zipfp.writestr("strfile", self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000065
Ezio Melottiafd0d112009-07-15 17:17:17 +000066 def zip_test(self, f, compression):
67 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +000068
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000069 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000070 with zipfile.ZipFile(f, "r", compression) as zipfp:
71 self.assertEqual(zipfp.read(TESTFN), self.data)
72 self.assertEqual(zipfp.read("another.name"), self.data)
73 self.assertEqual(zipfp.read("strfile"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000074
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000075 # Print the ZIP directory
76 fp = io.StringIO()
77 zipfp.printdir(file=fp)
78 directory = fp.getvalue()
79 lines = directory.splitlines()
Ezio Melotti35386712009-12-31 13:22:41 +000080 self.assertEqual(len(lines), 4) # Number of files + header
Thomas Wouters0e3f5912006-08-11 14:57:12 +000081
Benjamin Peterson577473f2010-01-19 00:09:57 +000082 self.assertIn('File Name', lines[0])
83 self.assertIn('Modified', lines[0])
84 self.assertIn('Size', lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +000085
Ezio Melotti35386712009-12-31 13:22:41 +000086 fn, date, time_, size = lines[1].split()
87 self.assertEqual(fn, 'another.name')
88 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
89 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
90 self.assertEqual(size, str(len(self.data)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000091
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000092 # Check the namelist
93 names = zipfp.namelist()
Ezio Melotti35386712009-12-31 13:22:41 +000094 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +000095 self.assertIn(TESTFN, names)
96 self.assertIn("another.name", names)
97 self.assertIn("strfile", names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000098
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000099 # Check infolist
100 infos = zipfp.infolist()
Ezio Melotti35386712009-12-31 13:22:41 +0000101 names = [i.filename for i in infos]
102 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000103 self.assertIn(TESTFN, names)
104 self.assertIn("another.name", names)
105 self.assertIn("strfile", names)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000106 for i in infos:
Ezio Melotti35386712009-12-31 13:22:41 +0000107 self.assertEqual(i.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000108
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000109 # check getinfo
110 for nm in (TESTFN, "another.name", "strfile"):
111 info = zipfp.getinfo(nm)
Ezio Melotti35386712009-12-31 13:22:41 +0000112 self.assertEqual(info.filename, nm)
113 self.assertEqual(info.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000114
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000115 # Check that testzip doesn't raise an exception
116 zipfp.testzip()
Tim Peters7d3bad62001-04-04 18:56:49 +0000117
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300118 def test_basic(self):
119 for f in get_files(self):
120 self.zip_test(f, self.compression)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000121
Ezio Melottiafd0d112009-07-15 17:17:17 +0000122 def zip_open_test(self, f, compression):
123 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000124
125 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000126 with zipfile.ZipFile(f, "r", compression) as zipfp:
127 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000128 with zipfp.open(TESTFN) as zipopen1:
129 while True:
130 read_data = zipopen1.read(256)
131 if not read_data:
132 break
133 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000134
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000135 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000136 with zipfp.open("another.name") as zipopen2:
137 while True:
138 read_data = zipopen2.read(256)
139 if not read_data:
140 break
141 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000142
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000143 self.assertEqual(b''.join(zipdata1), self.data)
144 self.assertEqual(b''.join(zipdata2), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000145
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300146 def test_open(self):
147 for f in get_files(self):
148 self.zip_open_test(f, self.compression)
Georg Brandlb533e262008-05-25 18:19:30 +0000149
Ezio Melottiafd0d112009-07-15 17:17:17 +0000150 def zip_random_open_test(self, f, compression):
151 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000152
153 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000154 with zipfile.ZipFile(f, "r", compression) as zipfp:
155 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000156 with zipfp.open(TESTFN) as zipopen1:
157 while True:
158 read_data = zipopen1.read(randint(1, 1024))
159 if not read_data:
160 break
161 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000162
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000163 self.assertEqual(b''.join(zipdata1), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000164
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300165 def test_random_open(self):
166 for f in get_files(self):
167 self.zip_random_open_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000168
Serhiy Storchakad2c07a52013-09-27 22:11:57 +0300169 def zip_read1_test(self, f, compression):
170 self.make_test_archive(f, compression)
171
172 # Read the ZIP archive
173 with zipfile.ZipFile(f, "r") as zipfp, \
174 zipfp.open(TESTFN) as zipopen:
175 zipdata = []
176 while True:
177 read_data = zipopen.read1(-1)
178 if not read_data:
179 break
180 zipdata.append(read_data)
181
182 self.assertEqual(b''.join(zipdata), self.data)
183
184 def test_read1(self):
185 for f in get_files(self):
186 self.zip_read1_test(f, self.compression)
187
188 def zip_read1_10_test(self, f, compression):
189 self.make_test_archive(f, compression)
190
191 # Read the ZIP archive
192 with zipfile.ZipFile(f, "r") as zipfp, \
193 zipfp.open(TESTFN) as zipopen:
194 zipdata = []
195 while True:
196 read_data = zipopen.read1(10)
197 self.assertLessEqual(len(read_data), 10)
198 if not read_data:
199 break
200 zipdata.append(read_data)
201
202 self.assertEqual(b''.join(zipdata), self.data)
203
204 def test_read1_10(self):
205 for f in get_files(self):
206 self.zip_read1_10_test(f, self.compression)
207
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000208 def zip_readline_read_test(self, f, compression):
209 self.make_test_archive(f, compression)
210
211 # Read the ZIP archive
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300212 with zipfile.ZipFile(f, "r") as zipfp, \
213 zipfp.open(TESTFN) as zipopen:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000214 data = b''
215 while True:
216 read = zipopen.readline()
217 if not read:
218 break
219 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000220
Brian Curtin8fb9b862010-11-18 02:15:28 +0000221 read = zipopen.read(100)
222 if not read:
223 break
224 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000225
226 self.assertEqual(data, self.data)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300227
228 def test_readline_read(self):
229 # Issue #7610: calls to readline() interleaved with calls to read().
230 for f in get_files(self):
231 self.zip_readline_read_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000232
Ezio Melottiafd0d112009-07-15 17:17:17 +0000233 def zip_readline_test(self, f, compression):
234 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000235
236 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000237 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000238 with zipfp.open(TESTFN) as zipopen:
239 for line in self.line_gen:
240 linedata = zipopen.readline()
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300241 self.assertEqual(linedata, line)
242
243 def test_readline(self):
244 for f in get_files(self):
245 self.zip_readline_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000246
Ezio Melottiafd0d112009-07-15 17:17:17 +0000247 def zip_readlines_test(self, f, compression):
248 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000249
250 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000251 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000252 with zipfp.open(TESTFN) as zipopen:
253 ziplines = zipopen.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000254 for line, zipline in zip(self.line_gen, ziplines):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300255 self.assertEqual(zipline, line)
256
257 def test_readlines(self):
258 for f in get_files(self):
259 self.zip_readlines_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000260
Ezio Melottiafd0d112009-07-15 17:17:17 +0000261 def zip_iterlines_test(self, f, compression):
262 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000263
264 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000265 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000266 with zipfp.open(TESTFN) as zipopen:
267 for line, zipline in zip(self.line_gen, zipopen):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300268 self.assertEqual(zipline, line)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000269
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300270 def test_iterlines(self):
271 for f in get_files(self):
272 self.zip_iterlines_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000273
Ezio Melottiafd0d112009-07-15 17:17:17 +0000274 def test_low_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000275 """Check for cases where compressed data is larger than original."""
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000276 # Create the ZIP archive
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300277 with zipfile.ZipFile(TESTFN2, "w", self.compression) as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000278 zipfp.writestr("strfile", '12')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000279
280 # Get an open object for strfile
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300281 with zipfile.ZipFile(TESTFN2, "r", self.compression) as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000282 with zipfp.open("strfile") as openobj:
283 self.assertEqual(openobj.read(1), b'1')
284 self.assertEqual(openobj.read(1), b'2')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000285
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300286 def test_writestr_compression(self):
287 zipfp = zipfile.ZipFile(TESTFN2, "w")
288 zipfp.writestr("b.txt", "hello world", compress_type=self.compression)
289 info = zipfp.getinfo('b.txt')
290 self.assertEqual(info.compress_type, self.compression)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200291
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300292 def test_read_return_size(self):
293 # Issue #9837: ZipExtFile.read() shouldn't return more bytes
294 # than requested.
295 for test_size in (1, 4095, 4096, 4097, 16384):
296 file_size = test_size + 1
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +0200297 junk = getrandbytes(file_size)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300298 with zipfile.ZipFile(io.BytesIO(), "w", self.compression) as zipf:
299 zipf.writestr('foo', junk)
300 with zipf.open('foo', 'r') as fp:
301 buf = fp.read(test_size)
302 self.assertEqual(len(buf), test_size)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200303
Serhiy Storchaka5ce3f102014-01-09 14:50:20 +0200304 def test_truncated_zipfile(self):
305 fp = io.BytesIO()
306 with zipfile.ZipFile(fp, mode='w') as zipf:
307 zipf.writestr('strfile', self.data, compress_type=self.compression)
308 end_offset = fp.tell()
309 zipfiledata = fp.getvalue()
310
311 fp = io.BytesIO(zipfiledata)
312 with zipfile.ZipFile(fp) as zipf:
313 with zipf.open('strfile') as zipopen:
314 fp.truncate(end_offset - 20)
315 with self.assertRaises(EOFError):
316 zipopen.read()
317
318 fp = io.BytesIO(zipfiledata)
319 with zipfile.ZipFile(fp) as zipf:
320 with zipf.open('strfile') as zipopen:
321 fp.truncate(end_offset - 20)
322 with self.assertRaises(EOFError):
323 while zipopen.read(100):
324 pass
325
326 fp = io.BytesIO(zipfiledata)
327 with zipfile.ZipFile(fp) as zipf:
328 with zipf.open('strfile') as zipopen:
329 fp.truncate(end_offset - 20)
330 with self.assertRaises(EOFError):
331 while zipopen.read1(100):
332 pass
333
Serhiy Storchaka51a43702014-10-29 22:42:06 +0200334 def test_repr(self):
335 fname = 'file.name'
336 for f in get_files(self):
337 with zipfile.ZipFile(f, 'w', self.compression) as zipfp:
338 zipfp.write(TESTFN, fname)
339 r = repr(zipfp)
340 self.assertIn("mode='w'", r)
341
342 with zipfile.ZipFile(f, 'r') as zipfp:
343 r = repr(zipfp)
344 if isinstance(f, str):
345 self.assertIn('filename=%r' % f, r)
346 else:
347 self.assertIn('file=%r' % f, r)
348 self.assertIn("mode='r'", r)
349 r = repr(zipfp.getinfo(fname))
350 self.assertIn('filename=%r' % fname, r)
351 self.assertIn('filemode=', r)
352 self.assertIn('file_size=', r)
353 if self.compression != zipfile.ZIP_STORED:
354 self.assertIn('compress_type=', r)
355 self.assertIn('compress_size=', r)
356 with zipfp.open(fname) as zipopen:
357 r = repr(zipopen)
358 self.assertIn('name=%r' % fname, r)
359 self.assertIn("mode='r'", r)
360 if self.compression != zipfile.ZIP_STORED:
361 self.assertIn('compress_type=', r)
362 self.assertIn('[closed]', repr(zipopen))
363 self.assertIn('[closed]', repr(zipfp))
364
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300365 def tearDown(self):
366 unlink(TESTFN)
367 unlink(TESTFN2)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200368
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200369
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300370class StoredTestsWithSourceFile(AbstractTestsWithSourceFile,
371 unittest.TestCase):
372 compression = zipfile.ZIP_STORED
373 test_low_compression = None
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200374
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300375 def zip_test_writestr_permissions(self, f, compression):
376 # Make sure that writestr creates files with mode 0600,
377 # when it is passed a name rather than a ZipInfo instance.
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200378
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300379 self.make_test_archive(f, compression)
380 with zipfile.ZipFile(f, "r") as zipfp:
381 zinfo = zipfp.getinfo('strfile')
382 self.assertEqual(zinfo.external_attr, 0o600 << 16)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200383
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300384 def test_writestr_permissions(self):
385 for f in get_files(self):
386 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +0200387
Ezio Melottiafd0d112009-07-15 17:17:17 +0000388 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000389 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
390 zipfp.write(TESTFN, "/absolute")
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000391
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000392 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
393 self.assertEqual(zipfp.namelist(), ["absolute"])
Tim Peters32cbc962006-02-20 21:42:18 +0000394
Ezio Melottiafd0d112009-07-15 17:17:17 +0000395 def test_append_to_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000396 """Test appending to an existing zipfile."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000397 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
398 zipfp.write(TESTFN, TESTFN)
399
400 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
401 zipfp.writestr("strfile", self.data)
402 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000403
Ezio Melottiafd0d112009-07-15 17:17:17 +0000404 def test_append_to_non_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000405 """Test appending to an existing file that is not a zipfile."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000406 # NOTE: this test fails if len(d) < 22 because of the first
407 # line "fpin.seek(-22, 2)" in _EndRecData
Ezio Melotti35386712009-12-31 13:22:41 +0000408 data = b'I am not a ZipFile!'*10
409 with open(TESTFN2, 'wb') as f:
410 f.write(data)
411
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000412 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
413 zipfp.write(TESTFN, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000414
Ezio Melotti35386712009-12-31 13:22:41 +0000415 with open(TESTFN2, 'rb') as f:
416 f.seek(len(data))
417 with zipfile.ZipFile(f, "r") as zipfp:
418 self.assertEqual(zipfp.namelist(), [TESTFN])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000419
R David Murray4fbb9db2011-06-09 15:50:51 -0400420 def test_ignores_newline_at_end(self):
421 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
422 zipfp.write(TESTFN, TESTFN)
423 with open(TESTFN2, 'a') as f:
424 f.write("\r\n\00\00\00")
425 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
426 self.assertIsInstance(zipfp, zipfile.ZipFile)
427
428 def test_ignores_stuff_appended_past_comments(self):
429 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
430 zipfp.comment = b"this is a comment"
431 zipfp.write(TESTFN, TESTFN)
432 with open(TESTFN2, 'a') as f:
433 f.write("abcdef\r\n")
434 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
435 self.assertIsInstance(zipfp, zipfile.ZipFile)
436 self.assertEqual(zipfp.comment, b"this is a comment")
437
Ezio Melottiafd0d112009-07-15 17:17:17 +0000438 def test_write_default_name(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000439 """Check that calling ZipFile.write without arcname specified
440 produces the expected result."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000441 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
442 zipfp.write(TESTFN)
Brian Curtin8fb9b862010-11-18 02:15:28 +0000443 with open(TESTFN, "rb") as f:
444 self.assertEqual(zipfp.read(TESTFN), f.read())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000445
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300446 def test_write_to_readonly(self):
447 """Check that trying to call write() on a readonly ZipFile object
448 raises a RuntimeError."""
449 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
450 zipfp.writestr("somefile.txt", "bogus")
451
452 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
453 self.assertRaises(RuntimeError, zipfp.write, TESTFN)
454
455 def test_add_file_before_1980(self):
456 # Set atime and mtime to 1970-01-01
457 os.utime(TESTFN, (0, 0))
458 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
459 self.assertRaises(ValueError, zipfp.write, TESTFN)
460
Serhiy Storchaka5ce3f102014-01-09 14:50:20 +0200461
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300462@requires_zlib
463class DeflateTestsWithSourceFile(AbstractTestsWithSourceFile,
464 unittest.TestCase):
465 compression = zipfile.ZIP_DEFLATED
466
Ezio Melottiafd0d112009-07-15 17:17:17 +0000467 def test_per_file_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000468 """Check that files within a Zip archive can have different
469 compression options."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000470 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
471 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
472 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
473 sinfo = zipfp.getinfo('storeme')
474 dinfo = zipfp.getinfo('deflateme')
475 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
476 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000477
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300478@requires_bz2
479class Bzip2TestsWithSourceFile(AbstractTestsWithSourceFile,
480 unittest.TestCase):
481 compression = zipfile.ZIP_BZIP2
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000482
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300483@requires_lzma
484class LzmaTestsWithSourceFile(AbstractTestsWithSourceFile,
485 unittest.TestCase):
486 compression = zipfile.ZIP_LZMA
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000487
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300488
489class AbstractTestZip64InSmallFiles:
490 # These tests test the ZIP64 functionality without using large files,
491 # see test_zipfile64 for proper tests.
492
493 @classmethod
494 def setUpClass(cls):
495 line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
496 for i in range(0, FIXEDTEST_SIZE))
497 cls.data = b'\n'.join(line_gen)
498
499 def setUp(self):
500 self._limit = zipfile.ZIP64_LIMIT
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300501 self._filecount_limit = zipfile.ZIP_FILECOUNT_LIMIT
502 zipfile.ZIP64_LIMIT = 1000
503 zipfile.ZIP_FILECOUNT_LIMIT = 9
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300504
505 # Make a source file with some lines
506 with open(TESTFN, "wb") as fp:
507 fp.write(self.data)
508
509 def zip_test(self, f, compression):
510 # Create the ZIP archive
511 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
512 zipfp.write(TESTFN, "another.name")
513 zipfp.write(TESTFN, TESTFN)
514 zipfp.writestr("strfile", self.data)
515
516 # Read the ZIP archive
517 with zipfile.ZipFile(f, "r", compression) as zipfp:
518 self.assertEqual(zipfp.read(TESTFN), self.data)
519 self.assertEqual(zipfp.read("another.name"), self.data)
520 self.assertEqual(zipfp.read("strfile"), self.data)
521
522 # Print the ZIP directory
523 fp = io.StringIO()
524 zipfp.printdir(fp)
525
526 directory = fp.getvalue()
527 lines = directory.splitlines()
528 self.assertEqual(len(lines), 4) # Number of files + header
529
530 self.assertIn('File Name', lines[0])
531 self.assertIn('Modified', lines[0])
532 self.assertIn('Size', lines[0])
533
534 fn, date, time_, size = lines[1].split()
535 self.assertEqual(fn, 'another.name')
536 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
537 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
538 self.assertEqual(size, str(len(self.data)))
539
540 # Check the namelist
541 names = zipfp.namelist()
542 self.assertEqual(len(names), 3)
543 self.assertIn(TESTFN, names)
544 self.assertIn("another.name", names)
545 self.assertIn("strfile", names)
546
547 # Check infolist
548 infos = zipfp.infolist()
549 names = [i.filename for i in infos]
550 self.assertEqual(len(names), 3)
551 self.assertIn(TESTFN, names)
552 self.assertIn("another.name", names)
553 self.assertIn("strfile", names)
554 for i in infos:
555 self.assertEqual(i.file_size, len(self.data))
556
557 # check getinfo
558 for nm in (TESTFN, "another.name", "strfile"):
559 info = zipfp.getinfo(nm)
560 self.assertEqual(info.filename, nm)
561 self.assertEqual(info.file_size, len(self.data))
562
563 # Check that testzip doesn't raise an exception
564 zipfp.testzip()
565
566 def test_basic(self):
567 for f in get_files(self):
568 self.zip_test(f, self.compression)
569
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300570 def test_too_many_files(self):
571 # This test checks that more than 64k files can be added to an archive,
572 # and that the resulting archive can be read properly by ZipFile
573 zipf = zipfile.ZipFile(TESTFN, "w", self.compression,
574 allowZip64=True)
575 zipf.debug = 100
576 numfiles = 15
577 for i in range(numfiles):
578 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
579 self.assertEqual(len(zipf.namelist()), numfiles)
580 zipf.close()
581
582 zipf2 = zipfile.ZipFile(TESTFN, "r", self.compression)
583 self.assertEqual(len(zipf2.namelist()), numfiles)
584 for i in range(numfiles):
585 content = zipf2.read("foo%08d" % i).decode('ascii')
586 self.assertEqual(content, "%d" % (i**3 % 57))
587 zipf2.close()
588
589 def test_too_many_files_append(self):
590 zipf = zipfile.ZipFile(TESTFN, "w", self.compression,
591 allowZip64=False)
592 zipf.debug = 100
593 numfiles = 9
594 for i in range(numfiles):
595 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
596 self.assertEqual(len(zipf.namelist()), numfiles)
597 with self.assertRaises(zipfile.LargeZipFile):
598 zipf.writestr("foo%08d" % numfiles, b'')
599 self.assertEqual(len(zipf.namelist()), numfiles)
600 zipf.close()
601
602 zipf = zipfile.ZipFile(TESTFN, "a", self.compression,
603 allowZip64=False)
604 zipf.debug = 100
605 self.assertEqual(len(zipf.namelist()), numfiles)
606 with self.assertRaises(zipfile.LargeZipFile):
607 zipf.writestr("foo%08d" % numfiles, b'')
608 self.assertEqual(len(zipf.namelist()), numfiles)
609 zipf.close()
610
611 zipf = zipfile.ZipFile(TESTFN, "a", self.compression,
612 allowZip64=True)
613 zipf.debug = 100
614 self.assertEqual(len(zipf.namelist()), numfiles)
615 numfiles2 = 15
616 for i in range(numfiles, numfiles2):
617 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
618 self.assertEqual(len(zipf.namelist()), numfiles2)
619 zipf.close()
620
621 zipf2 = zipfile.ZipFile(TESTFN, "r", self.compression)
622 self.assertEqual(len(zipf2.namelist()), numfiles2)
623 for i in range(numfiles2):
624 content = zipf2.read("foo%08d" % i).decode('ascii')
625 self.assertEqual(content, "%d" % (i**3 % 57))
626 zipf2.close()
627
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300628 def tearDown(self):
629 zipfile.ZIP64_LIMIT = self._limit
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300630 zipfile.ZIP_FILECOUNT_LIMIT = self._filecount_limit
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300631 unlink(TESTFN)
632 unlink(TESTFN2)
633
634
635class StoredTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
636 unittest.TestCase):
637 compression = zipfile.ZIP_STORED
638
639 def large_file_exception_test(self, f, compression):
Serhiy Storchaka235c5e02013-11-23 15:55:38 +0200640 with zipfile.ZipFile(f, "w", compression, allowZip64=False) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300641 self.assertRaises(zipfile.LargeZipFile,
642 zipfp.write, TESTFN, "another.name")
643
644 def large_file_exception_test2(self, f, compression):
Serhiy Storchaka235c5e02013-11-23 15:55:38 +0200645 with zipfile.ZipFile(f, "w", compression, allowZip64=False) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300646 self.assertRaises(zipfile.LargeZipFile,
647 zipfp.writestr, "another.name", self.data)
648
649 def test_large_file_exception(self):
650 for f in get_files(self):
651 self.large_file_exception_test(f, zipfile.ZIP_STORED)
652 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
653
654 def test_absolute_arcnames(self):
655 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
656 allowZip64=True) as zipfp:
657 zipfp.write(TESTFN, "/absolute")
658
659 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
660 self.assertEqual(zipfp.namelist(), ["absolute"])
661
662@requires_zlib
663class DeflateTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
664 unittest.TestCase):
665 compression = zipfile.ZIP_DEFLATED
666
667@requires_bz2
668class Bzip2TestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
669 unittest.TestCase):
670 compression = zipfile.ZIP_BZIP2
671
672@requires_lzma
673class LzmaTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
674 unittest.TestCase):
675 compression = zipfile.ZIP_LZMA
676
677
678class PyZipFileTests(unittest.TestCase):
679 def assertCompiledIn(self, name, namelist):
680 if name + 'o' not in namelist:
681 self.assertIn(name + 'c', namelist)
682
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200683 def requiresWriteAccess(self, path):
Berker Peksage1efc072015-02-16 04:36:18 +0200684 # effective_ids unavailable on windows
685 if not os.access(path, os.W_OK,
686 effective_ids=os.access in os.supports_effective_ids):
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200687 self.skipTest('requires write access to the installed location')
Serhiy Storchakad86a6ef2015-09-19 10:55:20 +0300688 filename = os.path.join(path, 'test_zipfile.try')
689 try:
690 fd = os.open(filename, os.O_WRONLY | os.O_CREAT)
691 os.close(fd)
692 except Exception:
693 self.skipTest('requires write access to the installed location')
694 unlink(filename)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200695
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300696 def test_write_pyfile(self):
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200697 self.requiresWriteAccess(os.path.dirname(__file__))
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300698 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
699 fn = __file__
Brett Cannonf299abd2015-04-13 14:21:02 -0400700 if fn.endswith('.pyc'):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300701 path_split = fn.split(os.sep)
702 if os.altsep is not None:
703 path_split.extend(fn.split(os.altsep))
704 if '__pycache__' in path_split:
Serhiy Storchaka9068e4d2013-07-22 21:02:14 +0300705 fn = importlib.util.source_from_cache(fn)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300706 else:
707 fn = fn[:-1]
708
709 zipfp.writepy(fn)
710
711 bn = os.path.basename(fn)
712 self.assertNotIn(bn, zipfp.namelist())
713 self.assertCompiledIn(bn, zipfp.namelist())
714
715 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
716 fn = __file__
Brett Cannonf299abd2015-04-13 14:21:02 -0400717 if fn.endswith('.pyc'):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300718 fn = fn[:-1]
719
720 zipfp.writepy(fn, "testpackage")
721
722 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
723 self.assertNotIn(bn, zipfp.namelist())
724 self.assertCompiledIn(bn, zipfp.namelist())
725
726 def test_write_python_package(self):
727 import email
728 packagedir = os.path.dirname(email.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200729 self.requiresWriteAccess(packagedir)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300730
731 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
732 zipfp.writepy(packagedir)
733
734 # Check for a couple of modules at different levels of the
735 # hierarchy
736 names = zipfp.namelist()
737 self.assertCompiledIn('email/__init__.py', names)
738 self.assertCompiledIn('email/mime/text.py', names)
739
Christian Tismer59202e52013-10-21 03:59:23 +0200740 def test_write_filtered_python_package(self):
741 import test
742 packagedir = os.path.dirname(test.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200743 self.requiresWriteAccess(packagedir)
Christian Tismer59202e52013-10-21 03:59:23 +0200744
745 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
746
Christian Tismer59202e52013-10-21 03:59:23 +0200747 # first make sure that the test folder gives error messages
Georg Brandla6065422013-10-21 08:29:29 +0200748 # (on the badsyntax_... files)
749 with captured_stdout() as reportSIO:
750 zipfp.writepy(packagedir)
Christian Tismer59202e52013-10-21 03:59:23 +0200751 reportStr = reportSIO.getvalue()
752 self.assertTrue('SyntaxError' in reportStr)
753
Christian Tismer410d9312013-10-22 04:09:28 +0200754 # then check that the filter works on the whole package
Georg Brandla6065422013-10-21 08:29:29 +0200755 with captured_stdout() as reportSIO:
756 zipfp.writepy(packagedir, filterfunc=lambda whatever: False)
Christian Tismer59202e52013-10-21 03:59:23 +0200757 reportStr = reportSIO.getvalue()
758 self.assertTrue('SyntaxError' not in reportStr)
759
Christian Tismer410d9312013-10-22 04:09:28 +0200760 # then check that the filter works on individual files
Larry Hastings7e63b362015-05-08 06:54:58 -0700761 def filter(path):
762 return not os.path.basename(path).startswith("bad")
Serhiy Storchakac46d1fa2014-01-20 21:59:33 +0200763 with captured_stdout() as reportSIO, self.assertWarns(UserWarning):
Larry Hastings7e63b362015-05-08 06:54:58 -0700764 zipfp.writepy(packagedir, filterfunc=filter)
Christian Tismer410d9312013-10-22 04:09:28 +0200765 reportStr = reportSIO.getvalue()
766 if reportStr:
767 print(reportStr)
768 self.assertTrue('SyntaxError' not in reportStr)
769
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300770 def test_write_with_optimization(self):
771 import email
772 packagedir = os.path.dirname(email.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200773 self.requiresWriteAccess(packagedir)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300774 optlevel = 1 if __debug__ else 0
Brett Cannonf299abd2015-04-13 14:21:02 -0400775 ext = '.pyc'
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300776
777 with TemporaryFile() as t, \
Christian Tismer59202e52013-10-21 03:59:23 +0200778 zipfile.PyZipFile(t, "w", optimize=optlevel) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300779 zipfp.writepy(packagedir)
780
781 names = zipfp.namelist()
782 self.assertIn('email/__init__' + ext, names)
783 self.assertIn('email/mime/text' + ext, names)
784
785 def test_write_python_directory(self):
786 os.mkdir(TESTFN2)
787 try:
788 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
789 fp.write("print(42)\n")
790
791 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
792 fp.write("print(42 * 42)\n")
793
794 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
795 fp.write("bla bla bla\n")
796
797 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
798 zipfp.writepy(TESTFN2)
799
800 names = zipfp.namelist()
801 self.assertCompiledIn('mod1.py', names)
802 self.assertCompiledIn('mod2.py', names)
803 self.assertNotIn('mod2.txt', names)
804
805 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200806 rmtree(TESTFN2)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300807
Christian Tismer410d9312013-10-22 04:09:28 +0200808 def test_write_python_directory_filtered(self):
809 os.mkdir(TESTFN2)
810 try:
811 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
812 fp.write("print(42)\n")
813
814 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
815 fp.write("print(42 * 42)\n")
816
817 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
818 zipfp.writepy(TESTFN2, filterfunc=lambda fn:
819 not fn.endswith('mod2.py'))
820
821 names = zipfp.namelist()
822 self.assertCompiledIn('mod1.py', names)
823 self.assertNotIn('mod2.py', names)
824
825 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200826 rmtree(TESTFN2)
Christian Tismer410d9312013-10-22 04:09:28 +0200827
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300828 def test_write_non_pyfile(self):
829 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
830 with open(TESTFN, 'w') as f:
831 f.write('most definitely not a python file')
832 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
Victor Stinner88b215e2014-09-04 00:51:09 +0200833 unlink(TESTFN)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300834
835 def test_write_pyfile_bad_syntax(self):
836 os.mkdir(TESTFN2)
837 try:
838 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
839 fp.write("Bad syntax in python file\n")
840
841 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
842 # syntax errors are printed to stdout
843 with captured_stdout() as s:
844 zipfp.writepy(os.path.join(TESTFN2, "mod1.py"))
845
846 self.assertIn("SyntaxError", s.getvalue())
847
848 # as it will not have compiled the python file, it will
Brett Cannonf299abd2015-04-13 14:21:02 -0400849 # include the .py file not .pyc
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300850 names = zipfp.namelist()
851 self.assertIn('mod1.py', names)
852 self.assertNotIn('mod1.pyc', names)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300853
854 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200855 rmtree(TESTFN2)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300856
857
858class ExtractTests(unittest.TestCase):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000859 def test_extract(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000860 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
861 for fpath, fdata in SMALL_TEST_DATA:
862 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000863
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000864 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
865 for fpath, fdata in SMALL_TEST_DATA:
866 writtenfile = zipfp.extract(fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000867
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000868 # make sure it was written to the right place
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800869 correctfile = os.path.join(os.getcwd(), fpath)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000870 correctfile = os.path.normpath(correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000871
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000872 self.assertEqual(writtenfile, correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000873
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000874 # make sure correct data is in correct file
Brian Curtin8fb9b862010-11-18 02:15:28 +0000875 with open(writtenfile, "rb") as f:
876 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000877
Victor Stinner88b215e2014-09-04 00:51:09 +0200878 unlink(writtenfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000879
880 # remove the test file subdirectories
Victor Stinner57004c62014-09-04 00:49:01 +0200881 rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
Christian Heimes790c8232008-01-07 21:14:23 +0000882
Ezio Melottiafd0d112009-07-15 17:17:17 +0000883 def test_extract_all(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000884 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
885 for fpath, fdata in SMALL_TEST_DATA:
886 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000887
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000888 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
889 zipfp.extractall()
890 for fpath, fdata in SMALL_TEST_DATA:
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800891 outfile = os.path.join(os.getcwd(), fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000892
Brian Curtin8fb9b862010-11-18 02:15:28 +0000893 with open(outfile, "rb") as f:
894 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000895
Victor Stinner88b215e2014-09-04 00:51:09 +0200896 unlink(outfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000897
898 # remove the test file subdirectories
Victor Stinner57004c62014-09-04 00:49:01 +0200899 rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
Christian Heimes790c8232008-01-07 21:14:23 +0000900
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800901 def check_file(self, filename, content):
902 self.assertTrue(os.path.isfile(filename))
903 with open(filename, 'rb') as f:
904 self.assertEqual(f.read(), content)
905
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800906 def test_sanitize_windows_name(self):
907 san = zipfile.ZipFile._sanitize_windows_name
908 # Passing pathsep in allows this test to work regardless of platform.
909 self.assertEqual(san(r',,?,C:,foo,bar/z', ','), r'_,C_,foo,bar/z')
910 self.assertEqual(san(r'a\b,c<d>e|f"g?h*i', ','), r'a\b,c_d_e_f_g_h_i')
911 self.assertEqual(san('../../foo../../ba..r', '/'), r'foo/ba..r')
912
913 def test_extract_hackers_arcnames_common_cases(self):
914 common_hacknames = [
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800915 ('../foo/bar', 'foo/bar'),
916 ('foo/../bar', 'foo/bar'),
917 ('foo/../../bar', 'foo/bar'),
918 ('foo/bar/..', 'foo/bar'),
919 ('./../foo/bar', 'foo/bar'),
920 ('/foo/bar', 'foo/bar'),
921 ('/foo/../bar', 'foo/bar'),
922 ('/foo/../../bar', 'foo/bar'),
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800923 ]
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800924 self._test_extract_hackers_arcnames(common_hacknames)
925
926 @unittest.skipIf(os.path.sep != '\\', 'Requires \\ as path separator.')
927 def test_extract_hackers_arcnames_windows_only(self):
928 """Test combination of path fixing and windows name sanitization."""
929 windows_hacknames = [
Christian Tismer59202e52013-10-21 03:59:23 +0200930 (r'..\foo\bar', 'foo/bar'),
931 (r'..\/foo\/bar', 'foo/bar'),
932 (r'foo/\..\/bar', 'foo/bar'),
933 (r'foo\/../\bar', 'foo/bar'),
934 (r'C:foo/bar', 'foo/bar'),
935 (r'C:/foo/bar', 'foo/bar'),
936 (r'C://foo/bar', 'foo/bar'),
937 (r'C:\foo\bar', 'foo/bar'),
938 (r'//conky/mountpoint/foo/bar', 'foo/bar'),
939 (r'\\conky\mountpoint\foo\bar', 'foo/bar'),
940 (r'///conky/mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
941 (r'\\\conky\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
942 (r'//conky//mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
943 (r'\\conky\\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
944 (r'//?/C:/foo/bar', 'foo/bar'),
945 (r'\\?\C:\foo\bar', 'foo/bar'),
946 (r'C:/../C:/foo/bar', 'C_/foo/bar'),
947 (r'a:b\c<d>e|f"g?h*i', 'b/c_d_e_f_g_h_i'),
948 ('../../foo../../ba..r', 'foo/ba..r'),
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800949 ]
950 self._test_extract_hackers_arcnames(windows_hacknames)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800951
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800952 @unittest.skipIf(os.path.sep != '/', r'Requires / as path separator.')
953 def test_extract_hackers_arcnames_posix_only(self):
954 posix_hacknames = [
955 ('//foo/bar', 'foo/bar'),
956 ('../../foo../../ba..r', 'foo../ba..r'),
957 (r'foo/..\bar', r'foo/..\bar'),
958 ]
959 self._test_extract_hackers_arcnames(posix_hacknames)
960
961 def _test_extract_hackers_arcnames(self, hacknames):
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800962 for arcname, fixedname in hacknames:
963 content = b'foobar' + arcname.encode()
964 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipfp:
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200965 zinfo = zipfile.ZipInfo()
966 # preserve backslashes
967 zinfo.filename = arcname
968 zinfo.external_attr = 0o600 << 16
969 zipfp.writestr(zinfo, content)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800970
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200971 arcname = arcname.replace(os.sep, "/")
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800972 targetpath = os.path.join('target', 'subdir', 'subsub')
973 correctfile = os.path.join(targetpath, *fixedname.split('/'))
974
975 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
976 writtenfile = zipfp.extract(arcname, targetpath)
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200977 self.assertEqual(writtenfile, correctfile,
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800978 msg='extract %r: %r != %r' %
979 (arcname, writtenfile, correctfile))
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800980 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +0200981 rmtree('target')
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800982
983 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
984 zipfp.extractall(targetpath)
985 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +0200986 rmtree('target')
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800987
988 correctfile = os.path.join(os.getcwd(), *fixedname.split('/'))
989
990 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
991 writtenfile = zipfp.extract(arcname)
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200992 self.assertEqual(writtenfile, correctfile,
993 msg="extract %r" % arcname)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800994 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +0200995 rmtree(fixedname.split('/')[0])
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800996
997 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
998 zipfp.extractall()
999 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +02001000 rmtree(fixedname.split('/')[0])
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001001
Victor Stinner88b215e2014-09-04 00:51:09 +02001002 unlink(TESTFN2)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -08001003
Ronald Oussorenee5c8852010-02-07 20:24:02 +00001004
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001005class OtherTests(unittest.TestCase):
1006 def test_open_via_zip_info(self):
1007 # Create the ZIP archive
1008 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
1009 zipfp.writestr("name", "foo")
Serhiy Storchaka9b7a1a12014-01-20 21:57:40 +02001010 with self.assertWarns(UserWarning):
1011 zipfp.writestr("name", "bar")
1012 self.assertEqual(zipfp.namelist(), ["name"] * 2)
Ronald Oussorenee5c8852010-02-07 20:24:02 +00001013
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001014 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1015 infos = zipfp.infolist()
1016 data = b""
1017 for info in infos:
1018 with zipfp.open(info) as zipopen:
1019 data += zipopen.read()
1020 self.assertIn(data, {b"foobar", b"barfoo"})
1021 data = b""
1022 for info in infos:
1023 data += zipfp.read(info)
1024 self.assertIn(data, {b"foobar", b"barfoo"})
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001025
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02001026 def test_universal_deprecation(self):
1027 f = io.BytesIO()
1028 with zipfile.ZipFile(f, "w") as zipfp:
1029 zipfp.writestr('spam.txt', b'ababagalamaga')
1030
1031 with zipfile.ZipFile(f, "r") as zipfp:
1032 for mode in 'U', 'rU':
1033 with self.assertWarns(DeprecationWarning):
1034 zipopen = zipfp.open('spam.txt', mode)
1035 zipopen.close()
1036
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001037 def test_universal_readaheads(self):
1038 f = io.BytesIO()
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001039
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001040 data = b'a\r\n' * 16 * 1024
1041 with zipfile.ZipFile(f, 'w', zipfile.ZIP_STORED) as zipfp:
1042 zipfp.writestr(TESTFN, data)
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +00001043
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001044 data2 = b''
1045 with zipfile.ZipFile(f, 'r') as zipfp, \
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02001046 openU(zipfp, TESTFN) as zipopen:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001047 for line in zipopen:
1048 data2 += line
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +00001049
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001050 self.assertEqual(data, data2.replace(b'\n', b'\r\n'))
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +00001051
Gregory P. Smithb0d9ca922009-07-07 05:06:04 +00001052 def test_writestr_extended_local_header_issue1202(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001053 with zipfile.ZipFile(TESTFN2, 'w') as orig_zip:
1054 for data in 'abcdefghijklmnop':
1055 zinfo = zipfile.ZipInfo(data)
1056 zinfo.flag_bits |= 0x08 # Include an extended local header.
1057 orig_zip.writestr(zinfo, data)
1058
1059 def test_close(self):
1060 """Check that the zipfile is closed after the 'with' block."""
1061 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
1062 for fpath, fdata in SMALL_TEST_DATA:
1063 zipfp.writestr(fpath, fdata)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001064 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
1065 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001066
1067 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001068 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
1069 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001070
1071 def test_close_on_exception(self):
1072 """Check that the zipfile is closed if an exception is raised in the
1073 'with' block."""
1074 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
1075 for fpath, fdata in SMALL_TEST_DATA:
1076 zipfp.writestr(fpath, fdata)
1077
1078 try:
1079 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
Georg Brandl4d540882010-10-28 06:42:33 +00001080 raise zipfile.BadZipFile()
1081 except zipfile.BadZipFile:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001082 self.assertIsNone(zipfp2.fp, 'zipfp is not closed')
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001083
Martin v. Löwisd099b562012-05-01 14:08:22 +02001084 def test_unsupported_version(self):
1085 # File has an extract_version of 120
1086 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 +02001087 b'\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00xPK\x01\x02x\x03x\x00\x00\x00\x00'
1088 b'\x00!p\xa1@\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00'
1089 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00\x00xPK\x05\x06'
1090 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 +03001091
Martin v. Löwisd099b562012-05-01 14:08:22 +02001092 self.assertRaises(NotImplementedError, zipfile.ZipFile,
1093 io.BytesIO(data), 'r')
1094
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001095 @requires_zlib
1096 def test_read_unicode_filenames(self):
1097 # bug #10801
1098 fname = findfile('zip_cp437_header.zip')
1099 with zipfile.ZipFile(fname) as zipfp:
1100 for name in zipfp.namelist():
1101 zipfp.open(name).close()
1102
1103 def test_write_unicode_filenames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001104 with zipfile.ZipFile(TESTFN, "w") as zf:
1105 zf.writestr("foo.txt", "Test for unicode filename")
1106 zf.writestr("\xf6.txt", "Test for unicode filename")
Ezio Melottie9615932010-01-24 19:26:24 +00001107 self.assertIsInstance(zf.infolist()[0].filename, str)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001108
1109 with zipfile.ZipFile(TESTFN, "r") as zf:
1110 self.assertEqual(zf.filelist[0].filename, "foo.txt")
1111 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
Martin v. Löwis8570f6a2008-05-05 17:44:38 +00001112
Serhiy Storchaka764fc9b2015-03-25 10:09:41 +02001113 def test_exclusive_create_zip_file(self):
1114 """Test exclusive creating a new zipfile."""
1115 unlink(TESTFN2)
1116 filename = 'testfile.txt'
1117 content = b'hello, world. this is some content.'
1118 with zipfile.ZipFile(TESTFN2, "x", zipfile.ZIP_STORED) as zipfp:
1119 zipfp.writestr(filename, content)
1120 with self.assertRaises(FileExistsError):
1121 zipfile.ZipFile(TESTFN2, "x", zipfile.ZIP_STORED)
1122 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
1123 self.assertEqual(zipfp.namelist(), [filename])
1124 self.assertEqual(zipfp.read(filename), content)
1125
Ezio Melottiafd0d112009-07-15 17:17:17 +00001126 def test_create_non_existent_file_for_append(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001127 if os.path.exists(TESTFN):
1128 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001129
Thomas Wouterscf297e42007-02-23 15:07:44 +00001130 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001131 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +00001132
Thomas Wouterscf297e42007-02-23 15:07:44 +00001133 try:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001134 with zipfile.ZipFile(TESTFN, 'a') as zf:
1135 zf.writestr(filename, content)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001136 except OSError:
Thomas Wouterscf297e42007-02-23 15:07:44 +00001137 self.fail('Could not append data to a non-existent zip file.')
1138
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001139 self.assertTrue(os.path.exists(TESTFN))
Thomas Wouterscf297e42007-02-23 15:07:44 +00001140
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001141 with zipfile.ZipFile(TESTFN, 'r') as zf:
1142 self.assertEqual(zf.read(filename), content)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001143
Ezio Melottiafd0d112009-07-15 17:17:17 +00001144 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001145 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti35386712009-12-31 13:22:41 +00001146 # it opens if there's an error in the file. If it doesn't, the
1147 # traceback holds a reference to the ZipFile object and, indirectly,
1148 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001149 # On Windows, this causes the os.unlink() call to fail because the
1150 # underlying file is still open. This is SF bug #412214.
1151 #
Ezio Melotti35386712009-12-31 13:22:41 +00001152 with open(TESTFN, "w") as fp:
1153 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001154 try:
1155 zf = zipfile.ZipFile(TESTFN)
Georg Brandl4d540882010-10-28 06:42:33 +00001156 except zipfile.BadZipFile:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001157 pass
1158
Ezio Melottiafd0d112009-07-15 17:17:17 +00001159 def test_is_zip_erroneous_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001160 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001161 # - passing a filename
1162 with open(TESTFN, "w") as fp:
1163 fp.write("this is not a legal zip file\n")
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001164 self.assertFalse(zipfile.is_zipfile(TESTFN))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001165 # - passing a file object
1166 with open(TESTFN, "rb") as fp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001167 self.assertFalse(zipfile.is_zipfile(fp))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001168 # - passing a file-like object
1169 fp = io.BytesIO()
1170 fp.write(b"this is not a legal zip file\n")
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001171 self.assertFalse(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001172 fp.seek(0, 0)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001173 self.assertFalse(zipfile.is_zipfile(fp))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001174
Serhiy Storchakad2b15272013-01-31 15:27:07 +02001175 def test_damaged_zipfile(self):
1176 """Check that zipfiles with missing bytes at the end raise BadZipFile."""
1177 # - Create a valid zip file
1178 fp = io.BytesIO()
1179 with zipfile.ZipFile(fp, mode="w") as zipf:
1180 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
1181 zipfiledata = fp.getvalue()
1182
1183 # - Now create copies of it missing the last N bytes and make sure
1184 # a BadZipFile exception is raised when we try to open it
1185 for N in range(len(zipfiledata)):
1186 fp = io.BytesIO(zipfiledata[:N])
1187 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, fp)
1188
Ezio Melottiafd0d112009-07-15 17:17:17 +00001189 def test_is_zip_valid_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001190 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001191 # - passing a filename
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001192 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1193 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
1194
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001195 self.assertTrue(zipfile.is_zipfile(TESTFN))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001196 # - passing a file object
1197 with open(TESTFN, "rb") as fp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001198 self.assertTrue(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001199 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001200 zip_contents = fp.read()
1201 # - passing a file-like object
1202 fp = io.BytesIO()
1203 fp.write(zip_contents)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001204 self.assertTrue(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001205 fp.seek(0, 0)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001206 self.assertTrue(zipfile.is_zipfile(fp))
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001207
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001208 def test_non_existent_file_raises_OSError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001209 # make sure we don't raise an AttributeError when a partially-constructed
1210 # ZipFile instance is finalized; this tests for regression on SF tracker
1211 # bug #403871.
1212
1213 # The bug we're testing for caused an AttributeError to be raised
1214 # when a ZipFile instance was created for a file that did not
1215 # exist; the .fp member was not initialized but was needed by the
1216 # __del__() method. Since the AttributeError is in the __del__(),
1217 # it is ignored, but the user should be sufficiently annoyed by
1218 # the message on the output that regression will be noticed
1219 # quickly.
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001220 self.assertRaises(OSError, zipfile.ZipFile, TESTFN)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001221
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001222 def test_empty_file_raises_BadZipFile(self):
1223 f = open(TESTFN, 'w')
1224 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001225 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001226
Ezio Melotti35386712009-12-31 13:22:41 +00001227 with open(TESTFN, 'w') as fp:
1228 fp.write("short file")
Georg Brandl4d540882010-10-28 06:42:33 +00001229 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001230
Ezio Melottiafd0d112009-07-15 17:17:17 +00001231 def test_closed_zip_raises_RuntimeError(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001232 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001233 data = io.BytesIO()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001234 with zipfile.ZipFile(data, mode="w") as zipf:
1235 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001236
Andrew Svetlov737fb892012-12-18 21:14:22 +02001237 # This is correct; calling .read on a closed ZipFile should raise
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001238 # a RuntimeError, and so should calling .testzip. An earlier
1239 # version of .testzip would swallow this exception (and any other)
1240 # and report that the first file in the archive was corrupt.
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001241 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
1242 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001243 self.assertRaises(RuntimeError, zipf.testzip)
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001244 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Brian Curtin8fb9b862010-11-18 02:15:28 +00001245 with open(TESTFN, 'w') as f:
1246 f.write('zipfile test data')
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001247 self.assertRaises(RuntimeError, zipf.write, TESTFN)
1248
Ezio Melottiafd0d112009-07-15 17:17:17 +00001249 def test_bad_constructor_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001250 """Check that bad modes passed to ZipFile constructor are caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001251 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
1252
Ezio Melottiafd0d112009-07-15 17:17:17 +00001253 def test_bad_open_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001254 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001255 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1256 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1257
1258 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001259 # read the data to make sure the file is there
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001260 zipf.read("foo.txt")
1261 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001262
Ezio Melottiafd0d112009-07-15 17:17:17 +00001263 def test_read0(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001264 """Check that calling read(0) on a ZipExtFile object returns an empty
1265 string and doesn't advance file pointer."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001266 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1267 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1268 # read the data to make sure the file is there
Brian Curtin8fb9b862010-11-18 02:15:28 +00001269 with zipf.open("foo.txt") as f:
1270 for i in range(FIXEDTEST_SIZE):
1271 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001272
Brian Curtin8fb9b862010-11-18 02:15:28 +00001273 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001274
Ezio Melottiafd0d112009-07-15 17:17:17 +00001275 def test_open_non_existent_item(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001276 """Check that attempting to call open() for an item that doesn't
1277 exist in the archive raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001278 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1279 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001280
Ezio Melottiafd0d112009-07-15 17:17:17 +00001281 def test_bad_compression_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001282 """Check that bad compression methods passed to ZipFile.open are
1283 caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001284 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
1285
Martin v. Löwisb3260f02012-05-01 08:38:01 +02001286 def test_unsupported_compression(self):
1287 # data is declared as shrunk, but actually deflated
1288 data = (b'PK\x03\x04.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00'
Christian Tismer59202e52013-10-21 03:59:23 +02001289 b'\x00\x02\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00x\x03\x00PK\x01'
1290 b'\x02.\x03.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00\x00\x02\x00\x00'
1291 b'\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
1292 b'\x80\x01\x00\x00\x00\x00xPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00'
1293 b'/\x00\x00\x00!\x00\x00\x00\x00\x00')
Martin v. Löwisb3260f02012-05-01 08:38:01 +02001294 with zipfile.ZipFile(io.BytesIO(data), 'r') as zipf:
1295 self.assertRaises(NotImplementedError, zipf.open, 'x')
1296
Ezio Melottiafd0d112009-07-15 17:17:17 +00001297 def test_null_byte_in_filename(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001298 """Check that a filename containing a null byte is properly
1299 terminated."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001300 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1301 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
1302 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001303
Ezio Melottiafd0d112009-07-15 17:17:17 +00001304 def test_struct_sizes(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001305 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001306 self.assertEqual(zipfile.sizeEndCentDir, 22)
1307 self.assertEqual(zipfile.sizeCentralDir, 46)
1308 self.assertEqual(zipfile.sizeEndCentDir64, 56)
1309 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
1310
Ezio Melottiafd0d112009-07-15 17:17:17 +00001311 def test_comments(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001312 """Check that comments on the archive are handled properly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001313
1314 # check default comment is empty
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001315 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1316 self.assertEqual(zipf.comment, b'')
1317 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1318
1319 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1320 self.assertEqual(zipfr.comment, b'')
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001321
1322 # check a simple short comment
1323 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001324 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1325 zipf.comment = comment
1326 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1327 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1328 self.assertEqual(zipf.comment, comment)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001329
1330 # check a comment of max length
1331 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
1332 comment2 = comment2.encode("ascii")
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001333 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1334 zipf.comment = comment2
1335 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1336
1337 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1338 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001339
1340 # check a comment that is too long is truncated
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001341 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
Serhiy Storchaka9b7a1a12014-01-20 21:57:40 +02001342 with self.assertWarns(UserWarning):
1343 zipf.comment = comment2 + b'oops'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001344 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1345 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1346 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001347
Antoine Pitrouc3991852012-06-30 17:31:37 +02001348 # check that comments are correctly modified in append mode
1349 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1350 zipf.comment = b"original comment"
1351 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1352 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1353 zipf.comment = b"an updated comment"
1354 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1355 self.assertEqual(zipf.comment, b"an updated comment")
1356
1357 # check that comments are correctly shortened in append mode
1358 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1359 zipf.comment = b"original comment that's longer"
1360 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1361 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1362 zipf.comment = b"shorter comment"
1363 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1364 self.assertEqual(zipf.comment, b"shorter comment")
1365
R David Murrayf50b38a2012-04-12 18:44:58 -04001366 def test_unicode_comment(self):
1367 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1368 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1369 with self.assertRaises(TypeError):
1370 zipf.comment = "this is an error"
1371
1372 def test_change_comment_in_empty_archive(self):
1373 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1374 self.assertFalse(zipf.filelist)
1375 zipf.comment = b"this is a comment"
1376 with zipfile.ZipFile(TESTFN, "r") as zipf:
1377 self.assertEqual(zipf.comment, b"this is a comment")
1378
1379 def test_change_comment_in_nonempty_archive(self):
1380 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1381 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1382 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1383 self.assertTrue(zipf.filelist)
1384 zipf.comment = b"this is a comment"
1385 with zipfile.ZipFile(TESTFN, "r") as zipf:
1386 self.assertEqual(zipf.comment, b"this is a comment")
1387
Georg Brandl268e4d42010-10-14 06:59:45 +00001388 def test_empty_zipfile(self):
1389 # Check that creating a file in 'w' or 'a' mode and closing without
1390 # adding any files to the archives creates a valid empty ZIP file
1391 zipf = zipfile.ZipFile(TESTFN, mode="w")
1392 zipf.close()
1393 try:
1394 zipf = zipfile.ZipFile(TESTFN, mode="r")
1395 except zipfile.BadZipFile:
1396 self.fail("Unable to create empty ZIP file in 'w' mode")
1397
1398 zipf = zipfile.ZipFile(TESTFN, mode="a")
1399 zipf.close()
1400 try:
1401 zipf = zipfile.ZipFile(TESTFN, mode="r")
1402 except:
1403 self.fail("Unable to create empty ZIP file in 'a' mode")
1404
1405 def test_open_empty_file(self):
1406 # Issue 1710703: Check that opening a file with less than 22 bytes
Georg Brandl4d540882010-10-28 06:42:33 +00001407 # raises a BadZipFile exception (rather than the previously unhelpful
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001408 # OSError)
Georg Brandl268e4d42010-10-14 06:59:45 +00001409 f = open(TESTFN, 'w')
1410 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001411 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN, 'r')
Georg Brandl268e4d42010-10-14 06:59:45 +00001412
Senthil Kumaran29fa9d42011-10-20 01:46:00 +08001413 def test_create_zipinfo_before_1980(self):
1414 self.assertRaises(ValueError,
1415 zipfile.ZipInfo, 'seventies', (1979, 1, 1, 0, 0, 0))
1416
Gregory P. Smith0af8a862014-05-29 23:42:14 -07001417 def test_zipfile_with_short_extra_field(self):
1418 """If an extra field in the header is less than 4 bytes, skip it."""
1419 zipdata = (
1420 b'PK\x03\x04\x14\x00\x00\x00\x00\x00\x93\x9b\xad@\x8b\x9e'
1421 b'\xd9\xd3\x01\x00\x00\x00\x01\x00\x00\x00\x03\x00\x03\x00ab'
1422 b'c\x00\x00\x00APK\x01\x02\x14\x03\x14\x00\x00\x00\x00'
1423 b'\x00\x93\x9b\xad@\x8b\x9e\xd9\xd3\x01\x00\x00\x00\x01\x00\x00'
1424 b'\x00\x03\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00'
1425 b'\x00\x00\x00abc\x00\x00PK\x05\x06\x00\x00\x00\x00'
1426 b'\x01\x00\x01\x003\x00\x00\x00%\x00\x00\x00\x00\x00'
1427 )
1428 with zipfile.ZipFile(io.BytesIO(zipdata), 'r') as zipf:
1429 # testzip returns the name of the first corrupt file, or None
1430 self.assertIsNone(zipf.testzip())
1431
Guido van Rossumd8faa362007-04-27 19:54:29 +00001432 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001433 unlink(TESTFN)
1434 unlink(TESTFN2)
1435
Thomas Wouterscf297e42007-02-23 15:07:44 +00001436
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001437class AbstractBadCrcTests:
1438 def test_testzip_with_bad_crc(self):
1439 """Tests that files with bad CRCs return their name from testzip."""
1440 zipdata = self.zip_with_bad_crc
1441
1442 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1443 # testzip returns the name of the first corrupt file, or None
1444 self.assertEqual('afile', zipf.testzip())
1445
1446 def test_read_with_bad_crc(self):
1447 """Tests that files with bad CRCs raise a BadZipFile exception when read."""
1448 zipdata = self.zip_with_bad_crc
1449
1450 # Using ZipFile.read()
1451 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1452 self.assertRaises(zipfile.BadZipFile, zipf.read, 'afile')
1453
1454 # Using ZipExtFile.read()
1455 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1456 with zipf.open('afile', 'r') as corrupt_file:
1457 self.assertRaises(zipfile.BadZipFile, corrupt_file.read)
1458
1459 # Same with small reads (in order to exercise the buffering logic)
1460 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1461 with zipf.open('afile', 'r') as corrupt_file:
1462 corrupt_file.MIN_READ_SIZE = 2
1463 with self.assertRaises(zipfile.BadZipFile):
1464 while corrupt_file.read(2):
1465 pass
1466
1467
1468class StoredBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1469 compression = zipfile.ZIP_STORED
1470 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001471 b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
1472 b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
1473 b'ilehello,AworldP'
1474 b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
1475 b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
1476 b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
1477 b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
1478 b'\0\0/\0\0\0\0\0')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001479
1480@requires_zlib
1481class DeflateBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1482 compression = zipfile.ZIP_DEFLATED
1483 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001484 b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
1485 b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1486 b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
1487 b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
1488 b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
1489 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
1490 b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
1491 b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001492
1493@requires_bz2
1494class Bzip2BadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1495 compression = zipfile.ZIP_BZIP2
1496 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001497 b'PK\x03\x04\x14\x03\x00\x00\x0c\x00nu\x0c=FA'
1498 b'KE8\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1499 b'ileBZh91AY&SY\xd4\xa8\xca'
1500 b'\x7f\x00\x00\x0f\x11\x80@\x00\x06D\x90\x80 \x00 \xa5'
1501 b'P\xd9!\x03\x03\x13\x13\x13\x89\xa9\xa9\xc2u5:\x9f'
1502 b'\x8b\xb9"\x9c(HjTe?\x80PK\x01\x02\x14'
1503 b'\x03\x14\x03\x00\x00\x0c\x00nu\x0c=FAKE8'
1504 b'\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\x00'
1505 b'\x00 \x80\x80\x81\x00\x00\x00\x00afilePK'
1506 b'\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00\x00[\x00'
1507 b'\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001508
1509@requires_lzma
1510class LzmaBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1511 compression = zipfile.ZIP_LZMA
1512 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001513 b'PK\x03\x04\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
1514 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1515 b'ile\t\x04\x05\x00]\x00\x00\x00\x04\x004\x19I'
1516 b'\xee\x8d\xe9\x17\x89:3`\tq!.8\x00PK'
1517 b'\x01\x02\x14\x03\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
1518 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00'
1519 b'\x00\x00\x00\x00 \x80\x80\x81\x00\x00\x00\x00afil'
1520 b'ePK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00'
1521 b'\x00>\x00\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001522
1523
Thomas Wouterscf297e42007-02-23 15:07:44 +00001524class DecryptionTests(unittest.TestCase):
Ezio Melotti35386712009-12-31 13:22:41 +00001525 """Check that ZIP decryption works. Since the library does not
1526 support encryption at the moment, we use a pre-generated encrypted
1527 ZIP file."""
Thomas Wouterscf297e42007-02-23 15:07:44 +00001528
1529 data = (
Christian Tismer59202e52013-10-21 03:59:23 +02001530 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
1531 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
1532 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
1533 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
1534 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
1535 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
1536 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +00001537 data2 = (
Christian Tismer59202e52013-10-21 03:59:23 +02001538 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
1539 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
1540 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
1541 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
1542 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
1543 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
1544 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
1545 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +00001546
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001547 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +00001548 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +00001549
1550 def setUp(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001551 with open(TESTFN, "wb") as fp:
1552 fp.write(self.data)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001553 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti35386712009-12-31 13:22:41 +00001554 with open(TESTFN2, "wb") as fp:
1555 fp.write(self.data2)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001556 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001557
1558 def tearDown(self):
1559 self.zip.close()
1560 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001561 self.zip2.close()
1562 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001563
Ezio Melottiafd0d112009-07-15 17:17:17 +00001564 def test_no_password(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001565 # Reading the encrypted file without password
1566 # must generate a RunTime exception
1567 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001568 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001569
Ezio Melottiafd0d112009-07-15 17:17:17 +00001570 def test_bad_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001571 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001572 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001573 self.zip2.setpassword(b"perl")
1574 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001575
Ezio Melotti975077a2011-05-19 22:03:22 +03001576 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +00001577 def test_good_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001578 self.zip.setpassword(b"python")
Ezio Melotti35386712009-12-31 13:22:41 +00001579 self.assertEqual(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001580 self.zip2.setpassword(b"12345")
Ezio Melotti35386712009-12-31 13:22:41 +00001581 self.assertEqual(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001582
R. David Murray8d855d82010-12-21 21:53:37 +00001583 def test_unicode_password(self):
1584 self.assertRaises(TypeError, self.zip.setpassword, "unicode")
1585 self.assertRaises(TypeError, self.zip.read, "test.txt", "python")
1586 self.assertRaises(TypeError, self.zip.open, "test.txt", pwd="python")
1587 self.assertRaises(TypeError, self.zip.extract, "test.txt", pwd="python")
1588
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001589class AbstractTestsWithRandomBinaryFiles:
1590 @classmethod
1591 def setUpClass(cls):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001592 datacount = randint(16, 64)*1024 + randint(1, 1024)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001593 cls.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
1594 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001595
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001596 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001597 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +00001598 with open(TESTFN, "wb") as fp:
1599 fp.write(self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001600
1601 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001602 unlink(TESTFN)
1603 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001604
Ezio Melottiafd0d112009-07-15 17:17:17 +00001605 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001606 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001607 with zipfile.ZipFile(f, "w", compression) as zipfp:
1608 zipfp.write(TESTFN, "another.name")
1609 zipfp.write(TESTFN, TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001610
Ezio Melottiafd0d112009-07-15 17:17:17 +00001611 def zip_test(self, f, compression):
1612 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001613
1614 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001615 with zipfile.ZipFile(f, "r", compression) as zipfp:
1616 testdata = zipfp.read(TESTFN)
1617 self.assertEqual(len(testdata), len(self.data))
1618 self.assertEqual(testdata, self.data)
1619 self.assertEqual(zipfp.read("another.name"), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001620
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001621 def test_read(self):
1622 for f in get_files(self):
1623 self.zip_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001624
Ezio Melottiafd0d112009-07-15 17:17:17 +00001625 def zip_open_test(self, f, compression):
1626 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001627
1628 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001629 with zipfile.ZipFile(f, "r", compression) as zipfp:
1630 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001631 with zipfp.open(TESTFN) as zipopen1:
1632 while True:
1633 read_data = zipopen1.read(256)
1634 if not read_data:
1635 break
1636 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001637
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001638 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001639 with zipfp.open("another.name") as zipopen2:
1640 while True:
1641 read_data = zipopen2.read(256)
1642 if not read_data:
1643 break
1644 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001645
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001646 testdata1 = b''.join(zipdata1)
1647 self.assertEqual(len(testdata1), len(self.data))
1648 self.assertEqual(testdata1, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001649
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001650 testdata2 = b''.join(zipdata2)
Ezio Melotti35386712009-12-31 13:22:41 +00001651 self.assertEqual(len(testdata2), len(self.data))
1652 self.assertEqual(testdata2, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001653
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001654 def test_open(self):
1655 for f in get_files(self):
1656 self.zip_open_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001657
Ezio Melottiafd0d112009-07-15 17:17:17 +00001658 def zip_random_open_test(self, f, compression):
1659 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001660
1661 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001662 with zipfile.ZipFile(f, "r", compression) as zipfp:
1663 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001664 with zipfp.open(TESTFN) as zipopen1:
1665 while True:
1666 read_data = zipopen1.read(randint(1, 1024))
1667 if not read_data:
1668 break
1669 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001670
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001671 testdata = b''.join(zipdata1)
1672 self.assertEqual(len(testdata), len(self.data))
1673 self.assertEqual(testdata, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001674
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001675 def test_random_open(self):
1676 for f in get_files(self):
1677 self.zip_random_open_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001678
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001679
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001680class StoredTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1681 unittest.TestCase):
1682 compression = zipfile.ZIP_STORED
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001683
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001684@requires_zlib
1685class DeflateTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1686 unittest.TestCase):
1687 compression = zipfile.ZIP_DEFLATED
1688
1689@requires_bz2
1690class Bzip2TestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1691 unittest.TestCase):
1692 compression = zipfile.ZIP_BZIP2
1693
1694@requires_lzma
1695class LzmaTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1696 unittest.TestCase):
1697 compression = zipfile.ZIP_LZMA
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001698
Ezio Melotti76430242009-07-11 18:28:48 +00001699
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001700# Privide the tell() method but not seek()
1701class Tellable:
1702 def __init__(self, fp):
1703 self.fp = fp
1704 self.offset = 0
1705
1706 def write(self, data):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02001707 n = self.fp.write(data)
1708 self.offset += n
1709 return n
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001710
1711 def tell(self):
1712 return self.offset
1713
1714 def flush(self):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02001715 self.fp.flush()
1716
1717class Unseekable:
1718 def __init__(self, fp):
1719 self.fp = fp
1720
1721 def write(self, data):
1722 return self.fp.write(data)
1723
1724 def flush(self):
1725 self.fp.flush()
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001726
1727class UnseekableTests(unittest.TestCase):
Serhiy Storchaka77d89972015-03-23 01:09:35 +02001728 def test_writestr(self):
1729 for wrapper in (lambda f: f), Tellable, Unseekable:
1730 with self.subTest(wrapper=wrapper):
1731 f = io.BytesIO()
1732 f.write(b'abc')
1733 bf = io.BufferedWriter(f)
1734 with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) as zipfp:
1735 zipfp.writestr('ones', b'111')
1736 zipfp.writestr('twos', b'222')
1737 self.assertEqual(f.getvalue()[:5], b'abcPK')
1738 with zipfile.ZipFile(f, mode='r') as zipf:
1739 with zipf.open('ones') as zopen:
1740 self.assertEqual(zopen.read(), b'111')
1741 with zipf.open('twos') as zopen:
1742 self.assertEqual(zopen.read(), b'222')
1743
1744 def test_write(self):
1745 for wrapper in (lambda f: f), Tellable, Unseekable:
1746 with self.subTest(wrapper=wrapper):
1747 f = io.BytesIO()
1748 f.write(b'abc')
1749 bf = io.BufferedWriter(f)
1750 with zipfile.ZipFile(wrapper(bf), 'w', zipfile.ZIP_STORED) as zipfp:
1751 self.addCleanup(unlink, TESTFN)
1752 with open(TESTFN, 'wb') as f2:
1753 f2.write(b'111')
1754 zipfp.write(TESTFN, 'ones')
1755 with open(TESTFN, 'wb') as f2:
1756 f2.write(b'222')
1757 zipfp.write(TESTFN, 'twos')
1758 self.assertEqual(f.getvalue()[:5], b'abcPK')
1759 with zipfile.ZipFile(f, mode='r') as zipf:
1760 with zipf.open('ones') as zopen:
1761 self.assertEqual(zopen.read(), b'111')
1762 with zipf.open('twos') as zopen:
1763 self.assertEqual(zopen.read(), b'222')
Serhiy Storchakaa14f7d22015-01-26 14:01:27 +02001764
1765
Ezio Melotti975077a2011-05-19 22:03:22 +03001766@requires_zlib
Guido van Rossumd8faa362007-04-27 19:54:29 +00001767class TestsWithMultipleOpens(unittest.TestCase):
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001768 @classmethod
1769 def setUpClass(cls):
1770 cls.data1 = b'111' + getrandbytes(10000)
1771 cls.data2 = b'222' + getrandbytes(10000)
1772
1773 def make_test_archive(self, f):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001774 # Create the ZIP archive
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001775 with zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as zipfp:
1776 zipfp.writestr('ones', self.data1)
1777 zipfp.writestr('twos', self.data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001778
Ezio Melottiafd0d112009-07-15 17:17:17 +00001779 def test_same_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001780 # Verify that (when the ZipFile is in control of creating file objects)
1781 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001782 for f in get_files(self):
1783 self.make_test_archive(f)
1784 with zipfile.ZipFile(f, mode="r") as zipf:
1785 with zipf.open('ones') as zopen1, zipf.open('ones') as zopen2:
1786 data1 = zopen1.read(500)
1787 data2 = zopen2.read(500)
1788 data1 += zopen1.read()
1789 data2 += zopen2.read()
1790 self.assertEqual(data1, data2)
1791 self.assertEqual(data1, self.data1)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001792
Ezio Melottiafd0d112009-07-15 17:17:17 +00001793 def test_different_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001794 # Verify that (when the ZipFile is in control of creating file objects)
1795 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001796 for f in get_files(self):
1797 self.make_test_archive(f)
1798 with zipfile.ZipFile(f, mode="r") as zipf:
1799 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1800 data1 = zopen1.read(500)
1801 data2 = zopen2.read(500)
1802 data1 += zopen1.read()
1803 data2 += zopen2.read()
1804 self.assertEqual(data1, self.data1)
1805 self.assertEqual(data2, self.data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001806
Ezio Melottiafd0d112009-07-15 17:17:17 +00001807 def test_interleaved(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001808 # Verify that (when the ZipFile is in control of creating file objects)
1809 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001810 for f in get_files(self):
1811 self.make_test_archive(f)
1812 with zipfile.ZipFile(f, mode="r") as zipf:
1813 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1814 data1 = zopen1.read(500)
1815 data2 = zopen2.read(500)
1816 data1 += zopen1.read()
1817 data2 += zopen2.read()
1818 self.assertEqual(data1, self.data1)
1819 self.assertEqual(data2, self.data2)
1820
1821 def test_read_after_close(self):
1822 for f in get_files(self):
1823 self.make_test_archive(f)
1824 with contextlib.ExitStack() as stack:
1825 with zipfile.ZipFile(f, 'r') as zipf:
1826 zopen1 = stack.enter_context(zipf.open('ones'))
1827 zopen2 = stack.enter_context(zipf.open('twos'))
Brian Curtin8fb9b862010-11-18 02:15:28 +00001828 data1 = zopen1.read(500)
1829 data2 = zopen2.read(500)
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001830 data1 += zopen1.read()
1831 data2 += zopen2.read()
1832 self.assertEqual(data1, self.data1)
1833 self.assertEqual(data2, self.data2)
1834
1835 def test_read_after_write(self):
1836 for f in get_files(self):
1837 with zipfile.ZipFile(f, 'w', zipfile.ZIP_DEFLATED) as zipf:
1838 zipf.writestr('ones', self.data1)
1839 zipf.writestr('twos', self.data2)
1840 with zipf.open('ones') as zopen1:
1841 data1 = zopen1.read(500)
1842 self.assertEqual(data1, self.data1[:500])
1843 with zipfile.ZipFile(f, 'r') as zipf:
1844 data1 = zipf.read('ones')
1845 data2 = zipf.read('twos')
1846 self.assertEqual(data1, self.data1)
1847 self.assertEqual(data2, self.data2)
1848
1849 def test_write_after_read(self):
1850 for f in get_files(self):
1851 with zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as zipf:
1852 zipf.writestr('ones', self.data1)
1853 with zipf.open('ones') as zopen1:
1854 zopen1.read(500)
1855 zipf.writestr('twos', self.data2)
1856 with zipfile.ZipFile(f, 'r') as zipf:
1857 data1 = zipf.read('ones')
1858 data2 = zipf.read('twos')
1859 self.assertEqual(data1, self.data1)
1860 self.assertEqual(data2, self.data2)
1861
1862 def test_many_opens(self):
1863 # Verify that read() and open() promptly close the file descriptor,
1864 # and don't rely on the garbage collector to free resources.
1865 self.make_test_archive(TESTFN2)
1866 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
1867 for x in range(100):
1868 zipf.read('ones')
1869 with zipf.open('ones') as zopen1:
1870 pass
1871 with open(os.devnull) as f:
1872 self.assertLess(f.fileno(), 100)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001873
1874 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001875 unlink(TESTFN2)
1876
Guido van Rossumd8faa362007-04-27 19:54:29 +00001877
Martin v. Löwis59e47792009-01-24 14:10:07 +00001878class TestWithDirectory(unittest.TestCase):
1879 def setUp(self):
1880 os.mkdir(TESTFN2)
1881
Ezio Melottiafd0d112009-07-15 17:17:17 +00001882 def test_extract_dir(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001883 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
1884 zipf.extractall(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001885 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1886 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1887 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1888
Ezio Melottiafd0d112009-07-15 17:17:17 +00001889 def test_bug_6050(self):
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001890 # Extraction should succeed if directories already exist
1891 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottiafd0d112009-07-15 17:17:17 +00001892 self.test_extract_dir()
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001893
Serhiy Storchaka46a34922014-09-23 22:40:23 +03001894 def test_write_dir(self):
1895 dirpath = os.path.join(TESTFN2, "x")
1896 os.mkdir(dirpath)
1897 mode = os.stat(dirpath).st_mode & 0xFFFF
1898 with zipfile.ZipFile(TESTFN, "w") as zipf:
1899 zipf.write(dirpath)
1900 zinfo = zipf.filelist[0]
1901 self.assertTrue(zinfo.filename.endswith("/x/"))
1902 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1903 zipf.write(dirpath, "y")
1904 zinfo = zipf.filelist[1]
1905 self.assertTrue(zinfo.filename, "y/")
1906 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1907 with zipfile.ZipFile(TESTFN, "r") as zipf:
1908 zinfo = zipf.filelist[0]
1909 self.assertTrue(zinfo.filename.endswith("/x/"))
1910 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1911 zinfo = zipf.filelist[1]
1912 self.assertTrue(zinfo.filename, "y/")
1913 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1914 target = os.path.join(TESTFN2, "target")
1915 os.mkdir(target)
1916 zipf.extractall(target)
1917 self.assertTrue(os.path.isdir(os.path.join(target, "y")))
1918 self.assertEqual(len(os.listdir(target)), 2)
1919
1920 def test_writestr_dir(self):
Martin v. Löwis59e47792009-01-24 14:10:07 +00001921 os.mkdir(os.path.join(TESTFN2, "x"))
Serhiy Storchaka46a34922014-09-23 22:40:23 +03001922 with zipfile.ZipFile(TESTFN, "w") as zipf:
1923 zipf.writestr("x/", b'')
1924 zinfo = zipf.filelist[0]
1925 self.assertEqual(zinfo.filename, "x/")
1926 self.assertEqual(zinfo.external_attr, (0o40775 << 16) | 0x10)
1927 with zipfile.ZipFile(TESTFN, "r") as zipf:
1928 zinfo = zipf.filelist[0]
1929 self.assertTrue(zinfo.filename.endswith("x/"))
1930 self.assertEqual(zinfo.external_attr, (0o40775 << 16) | 0x10)
1931 target = os.path.join(TESTFN2, "target")
1932 os.mkdir(target)
1933 zipf.extractall(target)
1934 self.assertTrue(os.path.isdir(os.path.join(target, "x")))
1935 self.assertEqual(os.listdir(target), ["x"])
Martin v. Löwis59e47792009-01-24 14:10:07 +00001936
1937 def tearDown(self):
Victor Stinner57004c62014-09-04 00:49:01 +02001938 rmtree(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001939 if os.path.exists(TESTFN):
Ezio Melotti76430242009-07-11 18:28:48 +00001940 unlink(TESTFN)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001941
Guido van Rossumd8faa362007-04-27 19:54:29 +00001942
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001943class AbstractUniversalNewlineTests:
1944 @classmethod
1945 def setUpClass(cls):
1946 cls.line_gen = [bytes("Test of zipfile line %d." % i, "ascii")
1947 for i in range(FIXEDTEST_SIZE)]
1948 cls.seps = (b'\r', b'\r\n', b'\n')
1949 cls.arcdata = {}
1950 for n, s in enumerate(cls.seps):
1951 cls.arcdata[s] = s.join(cls.line_gen) + s
1952
Guido van Rossumd8faa362007-04-27 19:54:29 +00001953 def setUp(self):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001954 self.arcfiles = {}
Guido van Rossumd8faa362007-04-27 19:54:29 +00001955 for n, s in enumerate(self.seps):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001956 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001957 with open(self.arcfiles[s], "wb") as f:
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001958 f.write(self.arcdata[s])
Guido van Rossumd8faa362007-04-27 19:54:29 +00001959
Ezio Melottiafd0d112009-07-15 17:17:17 +00001960 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001961 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001962 with zipfile.ZipFile(f, "w", compression) as zipfp:
1963 for fn in self.arcfiles.values():
1964 zipfp.write(fn, fn)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001965
Ezio Melottiafd0d112009-07-15 17:17:17 +00001966 def read_test(self, f, compression):
1967 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001968
1969 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001970 with zipfile.ZipFile(f, "r") as zipfp:
1971 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02001972 with openU(zipfp, fn) as fp:
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001973 zipdata = fp.read()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001974 self.assertEqual(self.arcdata[sep], zipdata)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001975
1976 def test_read(self):
1977 for f in get_files(self):
1978 self.read_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001979
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001980 def readline_read_test(self, f, compression):
1981 self.make_test_archive(f, compression)
1982
1983 # Read the ZIP archive
Brian Curtin8fb9b862010-11-18 02:15:28 +00001984 with zipfile.ZipFile(f, "r") as zipfp:
1985 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02001986 with openU(zipfp, fn) as zipopen:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001987 data = b''
1988 while True:
1989 read = zipopen.readline()
1990 if not read:
1991 break
1992 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001993
Brian Curtin8fb9b862010-11-18 02:15:28 +00001994 read = zipopen.read(5)
1995 if not read:
1996 break
1997 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001998
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001999 self.assertEqual(data, self.arcdata[b'\n'])
Antoine Pitroua32f9a22010-01-27 21:18:57 +00002000
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03002001 def test_readline_read(self):
2002 for f in get_files(self):
2003 self.readline_read_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +00002004
Ezio Melottiafd0d112009-07-15 17:17:17 +00002005 def readline_test(self, f, compression):
2006 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002007
2008 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00002009 with zipfile.ZipFile(f, "r") as zipfp:
2010 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02002011 with openU(zipfp, fn) as zipopen:
Benjamin Petersond285bdb2010-10-31 17:57:22 +00002012 for line in self.line_gen:
2013 linedata = zipopen.readline()
2014 self.assertEqual(linedata, line + b'\n')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03002015
2016 def test_readline(self):
2017 for f in get_files(self):
2018 self.readline_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002019
Ezio Melottiafd0d112009-07-15 17:17:17 +00002020 def readlines_test(self, f, compression):
2021 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002022
2023 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00002024 with zipfile.ZipFile(f, "r") as zipfp:
2025 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02002026 with openU(zipfp, fn) as fp:
Benjamin Petersond285bdb2010-10-31 17:57:22 +00002027 ziplines = fp.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00002028 for line, zipline in zip(self.line_gen, ziplines):
2029 self.assertEqual(zipline, line + b'\n')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03002030
2031 def test_readlines(self):
2032 for f in get_files(self):
2033 self.readlines_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002034
Ezio Melottiafd0d112009-07-15 17:17:17 +00002035 def iterlines_test(self, f, compression):
2036 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002037
2038 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00002039 with zipfile.ZipFile(f, "r") as zipfp:
2040 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02002041 with openU(zipfp, fn) as fp:
Benjamin Petersond285bdb2010-10-31 17:57:22 +00002042 for line, zipline in zip(self.line_gen, fp):
2043 self.assertEqual(zipline, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00002044
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03002045 def test_iterlines(self):
2046 for f in get_files(self):
2047 self.iterlines_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02002048
Guido van Rossumd8faa362007-04-27 19:54:29 +00002049 def tearDown(self):
2050 for sep, fn in self.arcfiles.items():
Victor Stinner88b215e2014-09-04 00:51:09 +02002051 unlink(fn)
Ezio Melotti76430242009-07-11 18:28:48 +00002052 unlink(TESTFN)
2053 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002054
2055
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03002056class StoredUniversalNewlineTests(AbstractUniversalNewlineTests,
2057 unittest.TestCase):
2058 compression = zipfile.ZIP_STORED
2059
2060@requires_zlib
2061class DeflateUniversalNewlineTests(AbstractUniversalNewlineTests,
2062 unittest.TestCase):
2063 compression = zipfile.ZIP_DEFLATED
2064
2065@requires_bz2
2066class Bzip2UniversalNewlineTests(AbstractUniversalNewlineTests,
2067 unittest.TestCase):
2068 compression = zipfile.ZIP_BZIP2
2069
2070@requires_lzma
2071class LzmaUniversalNewlineTests(AbstractUniversalNewlineTests,
2072 unittest.TestCase):
2073 compression = zipfile.ZIP_LZMA
2074
Serhiy Storchaka503f9082016-02-08 00:02:25 +02002075class ZipInfoTests(unittest.TestCase):
2076 def test_from_file(self):
2077 zi = zipfile.ZipInfo.from_file(__file__)
2078 self.assertEqual(posixpath.basename(zi.filename), 'test_zipfile.py')
2079 self.assertFalse(zi.is_dir())
2080
2081 def test_from_dir(self):
2082 dirpath = os.path.dirname(os.path.abspath(__file__))
2083 zi = zipfile.ZipInfo.from_file(dirpath, 'stdlib_tests')
2084 self.assertEqual(zi.filename, 'stdlib_tests/')
2085 self.assertTrue(zi.is_dir())
2086 self.assertEqual(zi.compress_type, zipfile.ZIP_STORED)
2087 self.assertEqual(zi.file_size, 0)
2088
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00002089if __name__ == "__main__":
Brett Cannond5b4e1d2013-06-12 19:57:19 -04002090 unittest.main()