blob: a561d59bc7684077b70ee564b999b7b6fdbaa6dd [file] [log] [blame]
Ezio Melotti74c96ec2009-07-08 22:24:06 +00001import io
2import os
Georg Brandl5ba11de2011-01-01 10:09:32 +00003import sys
Barry Warsaw28a691b2010-04-17 00:19:56 +00004import imp
Ezio Melotti35386712009-12-31 13:22:41 +00005import time
Ezio Melotti74c96ec2009-07-08 22:24:06 +00006import shutil
7import struct
8import zipfile
9import unittest
10
Tim Petersa45cacf2004-08-20 03:47:14 +000011
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000012from tempfile import TemporaryFile
Serhiy Storchakafa6bc292013-07-22 21:00:11 +030013from random import randint, random, getrandbits
Tim Petersa19a1682001-03-29 04:36:09 +000014
Serhiy Storchakafa6bc292013-07-22 21:00:11 +030015from test.support import (TESTFN, findfile, unlink,
Serhiy Storchakac5b75db2013-01-29 20:14:08 +020016 requires_zlib, requires_bz2, requires_lzma,
17 captured_stdout)
Guido van Rossum368f04a2000-04-10 13:23:04 +000018
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000019TESTFN2 = TESTFN + "2"
Martin v. Löwis59e47792009-01-24 14:10:07 +000020TESTFNDIR = TESTFN + "d"
Guido van Rossumb5a755e2007-07-18 18:15:48 +000021FIXEDTEST_SIZE = 1000
Georg Brandl5ba11de2011-01-01 10:09:32 +000022DATAFILES_DIR = 'zipfile_datafiles'
Guido van Rossum368f04a2000-04-10 13:23:04 +000023
Christian Heimes790c8232008-01-07 21:14:23 +000024SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'),
25 ('ziptest2dir/_ziptest2', 'qawsedrftg'),
Gregory P. Smithb47acbf2013-02-01 11:22:43 -080026 ('ziptest2dir/ziptest3dir/_ziptest3', 'azsxdcfvgb'),
Christian Heimes790c8232008-01-07 21:14:23 +000027 ('ziptest2dir/ziptest3dir/ziptest4dir/_ziptest3', '6y7u8i9o0p')]
28
Serhiy Storchakafa6bc292013-07-22 21:00:11 +030029def get_files(test):
30 yield TESTFN2
31 with TemporaryFile() as f:
32 yield f
33 test.assertFalse(f.closed)
34 with io.BytesIO() as f:
35 yield f
36 test.assertFalse(f.closed)
Ezio Melotti76430242009-07-11 18:28:48 +000037
Serhiy Storchakafa6bc292013-07-22 21:00:11 +030038class AbstractTestsWithSourceFile:
39 @classmethod
40 def setUpClass(cls):
41 cls.line_gen = [bytes("Zipfile test line %d. random float: %f\n" %
42 (i, random()), "ascii")
43 for i in range(FIXEDTEST_SIZE)]
44 cls.data = b''.join(cls.line_gen)
45
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000046 def setUp(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000047 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +000048 with open(TESTFN, "wb") as fp:
49 fp.write(self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000050
Ezio Melottiafd0d112009-07-15 17:17:17 +000051 def make_test_archive(self, f, compression):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000052 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000053 with zipfile.ZipFile(f, "w", compression) as zipfp:
54 zipfp.write(TESTFN, "another.name")
55 zipfp.write(TESTFN, TESTFN)
56 zipfp.writestr("strfile", self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000057
Ezio Melottiafd0d112009-07-15 17:17:17 +000058 def zip_test(self, f, compression):
59 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +000060
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000061 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000062 with zipfile.ZipFile(f, "r", compression) as zipfp:
63 self.assertEqual(zipfp.read(TESTFN), self.data)
64 self.assertEqual(zipfp.read("another.name"), self.data)
65 self.assertEqual(zipfp.read("strfile"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000066
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000067 # Print the ZIP directory
68 fp = io.StringIO()
69 zipfp.printdir(file=fp)
70 directory = fp.getvalue()
71 lines = directory.splitlines()
Ezio Melotti35386712009-12-31 13:22:41 +000072 self.assertEqual(len(lines), 4) # Number of files + header
Thomas Wouters0e3f5912006-08-11 14:57:12 +000073
Benjamin Peterson577473f2010-01-19 00:09:57 +000074 self.assertIn('File Name', lines[0])
75 self.assertIn('Modified', lines[0])
76 self.assertIn('Size', lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +000077
Ezio Melotti35386712009-12-31 13:22:41 +000078 fn, date, time_, size = lines[1].split()
79 self.assertEqual(fn, 'another.name')
80 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
81 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
82 self.assertEqual(size, str(len(self.data)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000083
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000084 # Check the namelist
85 names = zipfp.namelist()
Ezio Melotti35386712009-12-31 13:22:41 +000086 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +000087 self.assertIn(TESTFN, names)
88 self.assertIn("another.name", names)
89 self.assertIn("strfile", names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000090
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000091 # Check infolist
92 infos = zipfp.infolist()
Ezio Melotti35386712009-12-31 13:22:41 +000093 names = [i.filename for i in infos]
94 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)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000098 for i in infos:
Ezio Melotti35386712009-12-31 13:22:41 +000099 self.assertEqual(i.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000100
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000101 # check getinfo
102 for nm in (TESTFN, "another.name", "strfile"):
103 info = zipfp.getinfo(nm)
Ezio Melotti35386712009-12-31 13:22:41 +0000104 self.assertEqual(info.filename, nm)
105 self.assertEqual(info.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000106
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000107 # Check that testzip doesn't raise an exception
108 zipfp.testzip()
Tim Peters7d3bad62001-04-04 18:56:49 +0000109
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300110 def test_basic(self):
111 for f in get_files(self):
112 self.zip_test(f, self.compression)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000113
Ezio Melottiafd0d112009-07-15 17:17:17 +0000114 def zip_open_test(self, f, compression):
115 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000116
117 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000118 with zipfile.ZipFile(f, "r", compression) as zipfp:
119 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000120 with zipfp.open(TESTFN) as zipopen1:
121 while True:
122 read_data = zipopen1.read(256)
123 if not read_data:
124 break
125 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000126
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000127 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000128 with zipfp.open("another.name") as zipopen2:
129 while True:
130 read_data = zipopen2.read(256)
131 if not read_data:
132 break
133 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000134
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000135 self.assertEqual(b''.join(zipdata1), self.data)
136 self.assertEqual(b''.join(zipdata2), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000137
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300138 def test_open(self):
139 for f in get_files(self):
140 self.zip_open_test(f, self.compression)
Georg Brandlb533e262008-05-25 18:19:30 +0000141
Ezio Melottiafd0d112009-07-15 17:17:17 +0000142 def zip_random_open_test(self, f, compression):
143 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000144
145 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000146 with zipfile.ZipFile(f, "r", compression) as zipfp:
147 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000148 with zipfp.open(TESTFN) as zipopen1:
149 while True:
150 read_data = zipopen1.read(randint(1, 1024))
151 if not read_data:
152 break
153 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000154
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000155 self.assertEqual(b''.join(zipdata1), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000156
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300157 def test_random_open(self):
158 for f in get_files(self):
159 self.zip_random_open_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000160
Serhiy Storchakad2c07a52013-09-27 22:11:57 +0300161 def zip_read1_test(self, f, compression):
162 self.make_test_archive(f, compression)
163
164 # Read the ZIP archive
165 with zipfile.ZipFile(f, "r") as zipfp, \
166 zipfp.open(TESTFN) as zipopen:
167 zipdata = []
168 while True:
169 read_data = zipopen.read1(-1)
170 if not read_data:
171 break
172 zipdata.append(read_data)
173
174 self.assertEqual(b''.join(zipdata), self.data)
175
176 def test_read1(self):
177 for f in get_files(self):
178 self.zip_read1_test(f, self.compression)
179
180 def zip_read1_10_test(self, f, compression):
181 self.make_test_archive(f, compression)
182
183 # Read the ZIP archive
184 with zipfile.ZipFile(f, "r") as zipfp, \
185 zipfp.open(TESTFN) as zipopen:
186 zipdata = []
187 while True:
188 read_data = zipopen.read1(10)
189 self.assertLessEqual(len(read_data), 10)
190 if not read_data:
191 break
192 zipdata.append(read_data)
193
194 self.assertEqual(b''.join(zipdata), self.data)
195
196 def test_read1_10(self):
197 for f in get_files(self):
198 self.zip_read1_10_test(f, self.compression)
199
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000200 def zip_readline_read_test(self, f, compression):
201 self.make_test_archive(f, compression)
202
203 # Read the ZIP archive
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300204 with zipfile.ZipFile(f, "r") as zipfp, \
205 zipfp.open(TESTFN) as zipopen:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000206 data = b''
207 while True:
208 read = zipopen.readline()
209 if not read:
210 break
211 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000212
Brian Curtin8fb9b862010-11-18 02:15:28 +0000213 read = zipopen.read(100)
214 if not read:
215 break
216 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000217
218 self.assertEqual(data, self.data)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300219
220 def test_readline_read(self):
221 # Issue #7610: calls to readline() interleaved with calls to read().
222 for f in get_files(self):
223 self.zip_readline_read_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000224
Ezio Melottiafd0d112009-07-15 17:17:17 +0000225 def zip_readline_test(self, f, compression):
226 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000227
228 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000229 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000230 with zipfp.open(TESTFN) as zipopen:
231 for line in self.line_gen:
232 linedata = zipopen.readline()
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300233 self.assertEqual(linedata, line)
234
235 def test_readline(self):
236 for f in get_files(self):
237 self.zip_readline_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000238
Ezio Melottiafd0d112009-07-15 17:17:17 +0000239 def zip_readlines_test(self, f, compression):
240 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000241
242 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000243 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000244 with zipfp.open(TESTFN) as zipopen:
245 ziplines = zipopen.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000246 for line, zipline in zip(self.line_gen, ziplines):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300247 self.assertEqual(zipline, line)
248
249 def test_readlines(self):
250 for f in get_files(self):
251 self.zip_readlines_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000252
Ezio Melottiafd0d112009-07-15 17:17:17 +0000253 def zip_iterlines_test(self, f, compression):
254 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000255
256 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000257 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000258 with zipfp.open(TESTFN) as zipopen:
259 for line, zipline in zip(self.line_gen, zipopen):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300260 self.assertEqual(zipline, line)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000261
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300262 def test_iterlines(self):
263 for f in get_files(self):
264 self.zip_iterlines_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000265
Ezio Melottiafd0d112009-07-15 17:17:17 +0000266 def test_low_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000267 """Check for cases where compressed data is larger than original."""
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000268 # Create the ZIP archive
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300269 with zipfile.ZipFile(TESTFN2, "w", self.compression) as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000270 zipfp.writestr("strfile", '12')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000271
272 # Get an open object for strfile
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300273 with zipfile.ZipFile(TESTFN2, "r", self.compression) as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000274 with zipfp.open("strfile") as openobj:
275 self.assertEqual(openobj.read(1), b'1')
276 self.assertEqual(openobj.read(1), b'2')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000277
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300278 def test_writestr_compression(self):
279 zipfp = zipfile.ZipFile(TESTFN2, "w")
280 zipfp.writestr("b.txt", "hello world", compress_type=self.compression)
281 info = zipfp.getinfo('b.txt')
282 self.assertEqual(info.compress_type, self.compression)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200283
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300284 def test_read_return_size(self):
285 # Issue #9837: ZipExtFile.read() shouldn't return more bytes
286 # than requested.
287 for test_size in (1, 4095, 4096, 4097, 16384):
288 file_size = test_size + 1
289 junk = getrandbits(8 * file_size).to_bytes(file_size, 'little')
290 with zipfile.ZipFile(io.BytesIO(), "w", self.compression) as zipf:
291 zipf.writestr('foo', junk)
292 with zipf.open('foo', 'r') as fp:
293 buf = fp.read(test_size)
294 self.assertEqual(len(buf), test_size)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200295
Serhiy Storchaka5ce3f102014-01-09 14:50:20 +0200296 def test_truncated_zipfile(self):
297 fp = io.BytesIO()
298 with zipfile.ZipFile(fp, mode='w') as zipf:
299 zipf.writestr('strfile', self.data, compress_type=self.compression)
300 end_offset = fp.tell()
301 zipfiledata = fp.getvalue()
302
303 fp = io.BytesIO(zipfiledata)
304 with zipfile.ZipFile(fp) as zipf:
305 with zipf.open('strfile') as zipopen:
306 fp.truncate(end_offset - 20)
307 with self.assertRaises(EOFError):
308 zipopen.read()
309
310 fp = io.BytesIO(zipfiledata)
311 with zipfile.ZipFile(fp) as zipf:
312 with zipf.open('strfile') as zipopen:
313 fp.truncate(end_offset - 20)
314 with self.assertRaises(EOFError):
315 while zipopen.read(100):
316 pass
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.read1(100):
324 pass
325
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300326 def tearDown(self):
327 unlink(TESTFN)
328 unlink(TESTFN2)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200329
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200330
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300331class StoredTestsWithSourceFile(AbstractTestsWithSourceFile,
332 unittest.TestCase):
333 compression = zipfile.ZIP_STORED
334 test_low_compression = None
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200335
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300336 def zip_test_writestr_permissions(self, f, compression):
337 # Make sure that writestr creates files with mode 0600,
338 # when it is passed a name rather than a ZipInfo instance.
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200339
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300340 self.make_test_archive(f, compression)
341 with zipfile.ZipFile(f, "r") as zipfp:
342 zinfo = zipfp.getinfo('strfile')
343 self.assertEqual(zinfo.external_attr, 0o600 << 16)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200344
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300345 def test_writestr_permissions(self):
346 for f in get_files(self):
347 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +0200348
Ezio Melottiafd0d112009-07-15 17:17:17 +0000349 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000350 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
351 zipfp.write(TESTFN, "/absolute")
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000352
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000353 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
354 self.assertEqual(zipfp.namelist(), ["absolute"])
Tim Peters32cbc962006-02-20 21:42:18 +0000355
Ezio Melottiafd0d112009-07-15 17:17:17 +0000356 def test_append_to_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000357 """Test appending to an existing zipfile."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000358 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
359 zipfp.write(TESTFN, TESTFN)
360
361 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
362 zipfp.writestr("strfile", self.data)
363 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000364
Ezio Melottiafd0d112009-07-15 17:17:17 +0000365 def test_append_to_non_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000366 """Test appending to an existing file that is not a zipfile."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000367 # NOTE: this test fails if len(d) < 22 because of the first
368 # line "fpin.seek(-22, 2)" in _EndRecData
Ezio Melotti35386712009-12-31 13:22:41 +0000369 data = b'I am not a ZipFile!'*10
370 with open(TESTFN2, 'wb') as f:
371 f.write(data)
372
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000373 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
374 zipfp.write(TESTFN, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000375
Ezio Melotti35386712009-12-31 13:22:41 +0000376 with open(TESTFN2, 'rb') as f:
377 f.seek(len(data))
378 with zipfile.ZipFile(f, "r") as zipfp:
379 self.assertEqual(zipfp.namelist(), [TESTFN])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000380
R David Murray4fbb9db2011-06-09 15:50:51 -0400381 def test_ignores_newline_at_end(self):
382 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
383 zipfp.write(TESTFN, TESTFN)
384 with open(TESTFN2, 'a') as f:
385 f.write("\r\n\00\00\00")
386 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
387 self.assertIsInstance(zipfp, zipfile.ZipFile)
388
389 def test_ignores_stuff_appended_past_comments(self):
390 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
391 zipfp.comment = b"this is a comment"
392 zipfp.write(TESTFN, TESTFN)
393 with open(TESTFN2, 'a') as f:
394 f.write("abcdef\r\n")
395 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
396 self.assertIsInstance(zipfp, zipfile.ZipFile)
397 self.assertEqual(zipfp.comment, b"this is a comment")
398
Ezio Melottiafd0d112009-07-15 17:17:17 +0000399 def test_write_default_name(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000400 """Check that calling ZipFile.write without arcname specified
401 produces the expected result."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000402 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
403 zipfp.write(TESTFN)
Brian Curtin8fb9b862010-11-18 02:15:28 +0000404 with open(TESTFN, "rb") as f:
405 self.assertEqual(zipfp.read(TESTFN), f.read())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000406
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300407 def test_write_to_readonly(self):
408 """Check that trying to call write() on a readonly ZipFile object
409 raises a RuntimeError."""
410 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
411 zipfp.writestr("somefile.txt", "bogus")
412
413 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
414 self.assertRaises(RuntimeError, zipfp.write, TESTFN)
415
416 def test_add_file_before_1980(self):
417 # Set atime and mtime to 1970-01-01
418 os.utime(TESTFN, (0, 0))
419 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
420 self.assertRaises(ValueError, zipfp.write, TESTFN)
421
Serhiy Storchaka5ce3f102014-01-09 14:50:20 +0200422
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300423@requires_zlib
424class DeflateTestsWithSourceFile(AbstractTestsWithSourceFile,
425 unittest.TestCase):
426 compression = zipfile.ZIP_DEFLATED
427
Ezio Melottiafd0d112009-07-15 17:17:17 +0000428 def test_per_file_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000429 """Check that files within a Zip archive can have different
430 compression options."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000431 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
432 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
433 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
434 sinfo = zipfp.getinfo('storeme')
435 dinfo = zipfp.getinfo('deflateme')
436 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
437 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000438
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300439@requires_bz2
440class Bzip2TestsWithSourceFile(AbstractTestsWithSourceFile,
441 unittest.TestCase):
442 compression = zipfile.ZIP_BZIP2
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000443
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300444@requires_lzma
445class LzmaTestsWithSourceFile(AbstractTestsWithSourceFile,
446 unittest.TestCase):
447 compression = zipfile.ZIP_LZMA
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000448
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300449
450class AbstractTestZip64InSmallFiles:
451 # These tests test the ZIP64 functionality without using large files,
452 # see test_zipfile64 for proper tests.
453
454 @classmethod
455 def setUpClass(cls):
456 line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
457 for i in range(0, FIXEDTEST_SIZE))
458 cls.data = b'\n'.join(line_gen)
459
460 def setUp(self):
461 self._limit = zipfile.ZIP64_LIMIT
462 zipfile.ZIP64_LIMIT = 5
463
464 # Make a source file with some lines
465 with open(TESTFN, "wb") as fp:
466 fp.write(self.data)
467
468 def zip_test(self, f, compression):
469 # Create the ZIP archive
470 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
471 zipfp.write(TESTFN, "another.name")
472 zipfp.write(TESTFN, TESTFN)
473 zipfp.writestr("strfile", self.data)
474
475 # Read the ZIP archive
476 with zipfile.ZipFile(f, "r", compression) as zipfp:
477 self.assertEqual(zipfp.read(TESTFN), self.data)
478 self.assertEqual(zipfp.read("another.name"), self.data)
479 self.assertEqual(zipfp.read("strfile"), self.data)
480
481 # Print the ZIP directory
482 fp = io.StringIO()
483 zipfp.printdir(fp)
484
485 directory = fp.getvalue()
486 lines = directory.splitlines()
487 self.assertEqual(len(lines), 4) # Number of files + header
488
489 self.assertIn('File Name', lines[0])
490 self.assertIn('Modified', lines[0])
491 self.assertIn('Size', lines[0])
492
493 fn, date, time_, size = lines[1].split()
494 self.assertEqual(fn, 'another.name')
495 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
496 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
497 self.assertEqual(size, str(len(self.data)))
498
499 # Check the namelist
500 names = zipfp.namelist()
501 self.assertEqual(len(names), 3)
502 self.assertIn(TESTFN, names)
503 self.assertIn("another.name", names)
504 self.assertIn("strfile", names)
505
506 # Check infolist
507 infos = zipfp.infolist()
508 names = [i.filename for i in infos]
509 self.assertEqual(len(names), 3)
510 self.assertIn(TESTFN, names)
511 self.assertIn("another.name", names)
512 self.assertIn("strfile", names)
513 for i in infos:
514 self.assertEqual(i.file_size, len(self.data))
515
516 # check getinfo
517 for nm in (TESTFN, "another.name", "strfile"):
518 info = zipfp.getinfo(nm)
519 self.assertEqual(info.filename, nm)
520 self.assertEqual(info.file_size, len(self.data))
521
522 # Check that testzip doesn't raise an exception
523 zipfp.testzip()
524
525 def test_basic(self):
526 for f in get_files(self):
527 self.zip_test(f, self.compression)
528
529 def tearDown(self):
530 zipfile.ZIP64_LIMIT = self._limit
531 unlink(TESTFN)
532 unlink(TESTFN2)
533
534
535class StoredTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
536 unittest.TestCase):
537 compression = zipfile.ZIP_STORED
538
539 def large_file_exception_test(self, f, compression):
540 with zipfile.ZipFile(f, "w", compression) as zipfp:
541 self.assertRaises(zipfile.LargeZipFile,
542 zipfp.write, TESTFN, "another.name")
543
544 def large_file_exception_test2(self, f, compression):
545 with zipfile.ZipFile(f, "w", compression) as zipfp:
546 self.assertRaises(zipfile.LargeZipFile,
547 zipfp.writestr, "another.name", self.data)
548
549 def test_large_file_exception(self):
550 for f in get_files(self):
551 self.large_file_exception_test(f, zipfile.ZIP_STORED)
552 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
553
554 def test_absolute_arcnames(self):
555 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
556 allowZip64=True) as zipfp:
557 zipfp.write(TESTFN, "/absolute")
558
559 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
560 self.assertEqual(zipfp.namelist(), ["absolute"])
561
562@requires_zlib
563class DeflateTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
564 unittest.TestCase):
565 compression = zipfile.ZIP_DEFLATED
566
567@requires_bz2
568class Bzip2TestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
569 unittest.TestCase):
570 compression = zipfile.ZIP_BZIP2
571
572@requires_lzma
573class LzmaTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
574 unittest.TestCase):
575 compression = zipfile.ZIP_LZMA
576
577
578class PyZipFileTests(unittest.TestCase):
579 def assertCompiledIn(self, name, namelist):
580 if name + 'o' not in namelist:
581 self.assertIn(name + 'c', namelist)
582
583 def test_write_pyfile(self):
584 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
585 fn = __file__
586 if fn.endswith('.pyc') or fn.endswith('.pyo'):
587 path_split = fn.split(os.sep)
588 if os.altsep is not None:
589 path_split.extend(fn.split(os.altsep))
590 if '__pycache__' in path_split:
591 fn = imp.source_from_cache(fn)
592 else:
593 fn = fn[:-1]
594
595 zipfp.writepy(fn)
596
597 bn = os.path.basename(fn)
598 self.assertNotIn(bn, zipfp.namelist())
599 self.assertCompiledIn(bn, zipfp.namelist())
600
601 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
602 fn = __file__
603 if fn.endswith(('.pyc', '.pyo')):
604 fn = fn[:-1]
605
606 zipfp.writepy(fn, "testpackage")
607
608 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
609 self.assertNotIn(bn, zipfp.namelist())
610 self.assertCompiledIn(bn, zipfp.namelist())
611
612 def test_write_python_package(self):
613 import email
614 packagedir = os.path.dirname(email.__file__)
615
616 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
617 zipfp.writepy(packagedir)
618
619 # Check for a couple of modules at different levels of the
620 # hierarchy
621 names = zipfp.namelist()
622 self.assertCompiledIn('email/__init__.py', names)
623 self.assertCompiledIn('email/mime/text.py', names)
624
625 def test_write_with_optimization(self):
626 import email
627 packagedir = os.path.dirname(email.__file__)
628 # use .pyc if running test in optimization mode,
629 # use .pyo if running test in debug mode
630 optlevel = 1 if __debug__ else 0
631 ext = '.pyo' if optlevel == 1 else '.pyc'
632
633 with TemporaryFile() as t, \
634 zipfile.PyZipFile(t, "w", optimize=optlevel) as zipfp:
635 zipfp.writepy(packagedir)
636
637 names = zipfp.namelist()
638 self.assertIn('email/__init__' + ext, names)
639 self.assertIn('email/mime/text' + ext, names)
640
641 def test_write_python_directory(self):
642 os.mkdir(TESTFN2)
643 try:
644 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
645 fp.write("print(42)\n")
646
647 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
648 fp.write("print(42 * 42)\n")
649
650 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
651 fp.write("bla bla bla\n")
652
653 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
654 zipfp.writepy(TESTFN2)
655
656 names = zipfp.namelist()
657 self.assertCompiledIn('mod1.py', names)
658 self.assertCompiledIn('mod2.py', names)
659 self.assertNotIn('mod2.txt', names)
660
661 finally:
662 shutil.rmtree(TESTFN2)
663
664 def test_write_non_pyfile(self):
665 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
666 with open(TESTFN, 'w') as f:
667 f.write('most definitely not a python file')
668 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
669 os.remove(TESTFN)
670
671 def test_write_pyfile_bad_syntax(self):
672 os.mkdir(TESTFN2)
673 try:
674 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
675 fp.write("Bad syntax in python file\n")
676
677 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
678 # syntax errors are printed to stdout
679 with captured_stdout() as s:
680 zipfp.writepy(os.path.join(TESTFN2, "mod1.py"))
681
682 self.assertIn("SyntaxError", s.getvalue())
683
684 # as it will not have compiled the python file, it will
685 # include the .py file not .pyc or .pyo
686 names = zipfp.namelist()
687 self.assertIn('mod1.py', names)
688 self.assertNotIn('mod1.pyc', names)
689 self.assertNotIn('mod1.pyo', names)
690
691 finally:
692 shutil.rmtree(TESTFN2)
693
694
695class ExtractTests(unittest.TestCase):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000696 def test_extract(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000697 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
698 for fpath, fdata in SMALL_TEST_DATA:
699 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000700
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000701 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
702 for fpath, fdata in SMALL_TEST_DATA:
703 writtenfile = zipfp.extract(fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000704
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000705 # make sure it was written to the right place
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800706 correctfile = os.path.join(os.getcwd(), fpath)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000707 correctfile = os.path.normpath(correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000708
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000709 self.assertEqual(writtenfile, correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000710
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000711 # make sure correct data is in correct file
Brian Curtin8fb9b862010-11-18 02:15:28 +0000712 with open(writtenfile, "rb") as f:
713 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000714
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000715 os.remove(writtenfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000716
717 # remove the test file subdirectories
718 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
719
Ezio Melottiafd0d112009-07-15 17:17:17 +0000720 def test_extract_all(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000721 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
722 for fpath, fdata in SMALL_TEST_DATA:
723 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000724
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000725 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
726 zipfp.extractall()
727 for fpath, fdata in SMALL_TEST_DATA:
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800728 outfile = os.path.join(os.getcwd(), fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000729
Brian Curtin8fb9b862010-11-18 02:15:28 +0000730 with open(outfile, "rb") as f:
731 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000732
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000733 os.remove(outfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000734
735 # remove the test file subdirectories
736 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
737
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800738 def check_file(self, filename, content):
739 self.assertTrue(os.path.isfile(filename))
740 with open(filename, 'rb') as f:
741 self.assertEqual(f.read(), content)
742
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800743 def test_sanitize_windows_name(self):
744 san = zipfile.ZipFile._sanitize_windows_name
745 # Passing pathsep in allows this test to work regardless of platform.
746 self.assertEqual(san(r',,?,C:,foo,bar/z', ','), r'_,C_,foo,bar/z')
747 self.assertEqual(san(r'a\b,c<d>e|f"g?h*i', ','), r'a\b,c_d_e_f_g_h_i')
748 self.assertEqual(san('../../foo../../ba..r', '/'), r'foo/ba..r')
749
750 def test_extract_hackers_arcnames_common_cases(self):
751 common_hacknames = [
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800752 ('../foo/bar', 'foo/bar'),
753 ('foo/../bar', 'foo/bar'),
754 ('foo/../../bar', 'foo/bar'),
755 ('foo/bar/..', 'foo/bar'),
756 ('./../foo/bar', 'foo/bar'),
757 ('/foo/bar', 'foo/bar'),
758 ('/foo/../bar', 'foo/bar'),
759 ('/foo/../../bar', 'foo/bar'),
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800760 ]
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800761 self._test_extract_hackers_arcnames(common_hacknames)
762
763 @unittest.skipIf(os.path.sep != '\\', 'Requires \\ as path separator.')
764 def test_extract_hackers_arcnames_windows_only(self):
765 """Test combination of path fixing and windows name sanitization."""
766 windows_hacknames = [
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800767 (r'..\foo\bar', 'foo/bar'),
768 (r'..\/foo\/bar', 'foo/bar'),
769 (r'foo/\..\/bar', 'foo/bar'),
770 (r'foo\/../\bar', 'foo/bar'),
771 (r'C:foo/bar', 'foo/bar'),
772 (r'C:/foo/bar', 'foo/bar'),
773 (r'C://foo/bar', 'foo/bar'),
774 (r'C:\foo\bar', 'foo/bar'),
775 (r'//conky/mountpoint/foo/bar', 'foo/bar'),
776 (r'\\conky\mountpoint\foo\bar', 'foo/bar'),
777 (r'///conky/mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
778 (r'\\\conky\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
779 (r'//conky//mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
780 (r'\\conky\\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
781 (r'//?/C:/foo/bar', 'foo/bar'),
782 (r'\\?\C:\foo\bar', 'foo/bar'),
783 (r'C:/../C:/foo/bar', 'C_/foo/bar'),
784 (r'a:b\c<d>e|f"g?h*i', 'b/c_d_e_f_g_h_i'),
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200785 ('../../foo../../ba..r', 'foo/ba..r'),
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800786 ]
787 self._test_extract_hackers_arcnames(windows_hacknames)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800788
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800789 @unittest.skipIf(os.path.sep != '/', r'Requires / as path separator.')
790 def test_extract_hackers_arcnames_posix_only(self):
791 posix_hacknames = [
792 ('//foo/bar', 'foo/bar'),
793 ('../../foo../../ba..r', 'foo../ba..r'),
794 (r'foo/..\bar', r'foo/..\bar'),
795 ]
796 self._test_extract_hackers_arcnames(posix_hacknames)
797
798 def _test_extract_hackers_arcnames(self, hacknames):
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800799 for arcname, fixedname in hacknames:
800 content = b'foobar' + arcname.encode()
801 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipfp:
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200802 zinfo = zipfile.ZipInfo()
803 # preserve backslashes
804 zinfo.filename = arcname
805 zinfo.external_attr = 0o600 << 16
806 zipfp.writestr(zinfo, content)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800807
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200808 arcname = arcname.replace(os.sep, "/")
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800809 targetpath = os.path.join('target', 'subdir', 'subsub')
810 correctfile = os.path.join(targetpath, *fixedname.split('/'))
811
812 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
813 writtenfile = zipfp.extract(arcname, targetpath)
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200814 self.assertEqual(writtenfile, correctfile,
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800815 msg='extract %r: %r != %r' %
816 (arcname, writtenfile, correctfile))
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800817 self.check_file(correctfile, content)
818 shutil.rmtree('target')
819
820 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
821 zipfp.extractall(targetpath)
822 self.check_file(correctfile, content)
823 shutil.rmtree('target')
824
825 correctfile = os.path.join(os.getcwd(), *fixedname.split('/'))
826
827 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
828 writtenfile = zipfp.extract(arcname)
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200829 self.assertEqual(writtenfile, correctfile,
830 msg="extract %r" % arcname)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800831 self.check_file(correctfile, content)
832 shutil.rmtree(fixedname.split('/')[0])
833
834 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
835 zipfp.extractall()
836 self.check_file(correctfile, content)
837 shutil.rmtree(fixedname.split('/')[0])
838
839 os.remove(TESTFN2)
840
Ronald Oussorenee5c8852010-02-07 20:24:02 +0000841
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300842class OtherTests(unittest.TestCase):
843 def test_open_via_zip_info(self):
844 # Create the ZIP archive
845 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
846 zipfp.writestr("name", "foo")
847 zipfp.writestr("name", "bar")
Ronald Oussorenee5c8852010-02-07 20:24:02 +0000848
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300849 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
850 infos = zipfp.infolist()
851 data = b""
852 for info in infos:
853 with zipfp.open(info) as zipopen:
854 data += zipopen.read()
855 self.assertIn(data, {b"foobar", b"barfoo"})
856 data = b""
857 for info in infos:
858 data += zipfp.read(info)
859 self.assertIn(data, {b"foobar", b"barfoo"})
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200860
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300861 def test_universal_readaheads(self):
862 f = io.BytesIO()
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +0200863
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300864 data = b'a\r\n' * 16 * 1024
865 with zipfile.ZipFile(f, 'w', zipfile.ZIP_STORED) as zipfp:
866 zipfp.writestr(TESTFN, data)
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000867
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300868 data2 = b''
869 with zipfile.ZipFile(f, 'r') as zipfp, \
870 zipfp.open(TESTFN, 'rU') as zipopen:
871 for line in zipopen:
872 data2 += line
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000873
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300874 self.assertEqual(data, data2.replace(b'\n', b'\r\n'))
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000875
Gregory P. Smithb0d9ca92009-07-07 05:06:04 +0000876 def test_writestr_extended_local_header_issue1202(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000877 with zipfile.ZipFile(TESTFN2, 'w') as orig_zip:
878 for data in 'abcdefghijklmnop':
879 zinfo = zipfile.ZipInfo(data)
880 zinfo.flag_bits |= 0x08 # Include an extended local header.
881 orig_zip.writestr(zinfo, data)
882
883 def test_close(self):
884 """Check that the zipfile is closed after the 'with' block."""
885 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
886 for fpath, fdata in SMALL_TEST_DATA:
887 zipfp.writestr(fpath, fdata)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300888 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
889 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000890
891 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300892 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
893 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000894
895 def test_close_on_exception(self):
896 """Check that the zipfile is closed if an exception is raised in the
897 'with' block."""
898 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
899 for fpath, fdata in SMALL_TEST_DATA:
900 zipfp.writestr(fpath, fdata)
901
902 try:
903 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
Georg Brandl4d540882010-10-28 06:42:33 +0000904 raise zipfile.BadZipFile()
905 except zipfile.BadZipFile:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300906 self.assertIsNone(zipfp2.fp, 'zipfp is not closed')
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000907
Martin v. Löwisd099b562012-05-01 14:08:22 +0200908 def test_unsupported_version(self):
909 # File has an extract_version of 120
910 data = (b'PK\x03\x04x\x00\x00\x00\x00\x00!p\xa1@\x00\x00\x00\x00\x00\x00'
911 b'\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00xPK\x01\x02x\x03x\x00\x00\x00\x00'
912 b'\x00!p\xa1@\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00'
913 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00\x00xPK\x05\x06'
914 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 +0300915
Martin v. Löwisd099b562012-05-01 14:08:22 +0200916 self.assertRaises(NotImplementedError, zipfile.ZipFile,
917 io.BytesIO(data), 'r')
918
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300919 @requires_zlib
920 def test_read_unicode_filenames(self):
921 # bug #10801
922 fname = findfile('zip_cp437_header.zip')
923 with zipfile.ZipFile(fname) as zipfp:
924 for name in zipfp.namelist():
925 zipfp.open(name).close()
926
927 def test_write_unicode_filenames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000928 with zipfile.ZipFile(TESTFN, "w") as zf:
929 zf.writestr("foo.txt", "Test for unicode filename")
930 zf.writestr("\xf6.txt", "Test for unicode filename")
Ezio Melottie9615932010-01-24 19:26:24 +0000931 self.assertIsInstance(zf.infolist()[0].filename, str)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000932
933 with zipfile.ZipFile(TESTFN, "r") as zf:
934 self.assertEqual(zf.filelist[0].filename, "foo.txt")
935 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
Martin v. Löwis8570f6a2008-05-05 17:44:38 +0000936
Ezio Melottiafd0d112009-07-15 17:17:17 +0000937 def test_create_non_existent_file_for_append(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +0000938 if os.path.exists(TESTFN):
939 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000940
Thomas Wouterscf297e42007-02-23 15:07:44 +0000941 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000942 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +0000943
Thomas Wouterscf297e42007-02-23 15:07:44 +0000944 try:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000945 with zipfile.ZipFile(TESTFN, 'a') as zf:
946 zf.writestr(filename, content)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000947 except IOError:
948 self.fail('Could not append data to a non-existent zip file.')
949
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000950 self.assertTrue(os.path.exists(TESTFN))
Thomas Wouterscf297e42007-02-23 15:07:44 +0000951
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000952 with zipfile.ZipFile(TESTFN, 'r') as zf:
953 self.assertEqual(zf.read(filename), content)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000954
Ezio Melottiafd0d112009-07-15 17:17:17 +0000955 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000956 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti35386712009-12-31 13:22:41 +0000957 # it opens if there's an error in the file. If it doesn't, the
958 # traceback holds a reference to the ZipFile object and, indirectly,
959 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000960 # On Windows, this causes the os.unlink() call to fail because the
961 # underlying file is still open. This is SF bug #412214.
962 #
Ezio Melotti35386712009-12-31 13:22:41 +0000963 with open(TESTFN, "w") as fp:
964 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000965 try:
966 zf = zipfile.ZipFile(TESTFN)
Georg Brandl4d540882010-10-28 06:42:33 +0000967 except zipfile.BadZipFile:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000968 pass
969
Ezio Melottiafd0d112009-07-15 17:17:17 +0000970 def test_is_zip_erroneous_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000971 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000972 # - passing a filename
973 with open(TESTFN, "w") as fp:
974 fp.write("this is not a legal zip file\n")
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300975 self.assertFalse(zipfile.is_zipfile(TESTFN))
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000976 # - passing a file object
977 with open(TESTFN, "rb") as fp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300978 self.assertFalse(zipfile.is_zipfile(fp))
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000979 # - passing a file-like object
980 fp = io.BytesIO()
981 fp.write(b"this is not a legal zip file\n")
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300982 self.assertFalse(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +0000983 fp.seek(0, 0)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300984 self.assertFalse(zipfile.is_zipfile(fp))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000985
Serhiy Storchakad2b15272013-01-31 15:27:07 +0200986 def test_damaged_zipfile(self):
987 """Check that zipfiles with missing bytes at the end raise BadZipFile."""
988 # - Create a valid zip file
989 fp = io.BytesIO()
990 with zipfile.ZipFile(fp, mode="w") as zipf:
991 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
992 zipfiledata = fp.getvalue()
993
994 # - Now create copies of it missing the last N bytes and make sure
995 # a BadZipFile exception is raised when we try to open it
996 for N in range(len(zipfiledata)):
997 fp = io.BytesIO(zipfiledata[:N])
998 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, fp)
999
Ezio Melottiafd0d112009-07-15 17:17:17 +00001000 def test_is_zip_valid_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001001 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001002 # - passing a filename
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001003 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1004 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
1005
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001006 self.assertTrue(zipfile.is_zipfile(TESTFN))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001007 # - passing a file object
1008 with open(TESTFN, "rb") as fp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001009 self.assertTrue(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001010 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001011 zip_contents = fp.read()
1012 # - passing a file-like object
1013 fp = io.BytesIO()
1014 fp.write(zip_contents)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001015 self.assertTrue(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001016 fp.seek(0, 0)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001017 self.assertTrue(zipfile.is_zipfile(fp))
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001018
Ezio Melottiafd0d112009-07-15 17:17:17 +00001019 def test_non_existent_file_raises_IOError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001020 # make sure we don't raise an AttributeError when a partially-constructed
1021 # ZipFile instance is finalized; this tests for regression on SF tracker
1022 # bug #403871.
1023
1024 # The bug we're testing for caused an AttributeError to be raised
1025 # when a ZipFile instance was created for a file that did not
1026 # exist; the .fp member was not initialized but was needed by the
1027 # __del__() method. Since the AttributeError is in the __del__(),
1028 # it is ignored, but the user should be sufficiently annoyed by
1029 # the message on the output that regression will be noticed
1030 # quickly.
1031 self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
1032
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001033 def test_empty_file_raises_BadZipFile(self):
1034 f = open(TESTFN, 'w')
1035 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001036 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001037
Ezio Melotti35386712009-12-31 13:22:41 +00001038 with open(TESTFN, 'w') as fp:
1039 fp.write("short file")
Georg Brandl4d540882010-10-28 06:42:33 +00001040 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001041
Ezio Melottiafd0d112009-07-15 17:17:17 +00001042 def test_closed_zip_raises_RuntimeError(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001043 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001044 data = io.BytesIO()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001045 with zipfile.ZipFile(data, mode="w") as zipf:
1046 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001047
Andrew Svetlov737fb892012-12-18 21:14:22 +02001048 # This is correct; calling .read on a closed ZipFile should raise
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001049 # a RuntimeError, and so should calling .testzip. An earlier
1050 # version of .testzip would swallow this exception (and any other)
1051 # and report that the first file in the archive was corrupt.
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001052 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
1053 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001054 self.assertRaises(RuntimeError, zipf.testzip)
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001055 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Brian Curtin8fb9b862010-11-18 02:15:28 +00001056 with open(TESTFN, 'w') as f:
1057 f.write('zipfile test data')
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001058 self.assertRaises(RuntimeError, zipf.write, TESTFN)
1059
Ezio Melottiafd0d112009-07-15 17:17:17 +00001060 def test_bad_constructor_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001061 """Check that bad modes passed to ZipFile constructor are caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001062 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
1063
Ezio Melottiafd0d112009-07-15 17:17:17 +00001064 def test_bad_open_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001065 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001066 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1067 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1068
1069 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001070 # read the data to make sure the file is there
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001071 zipf.read("foo.txt")
1072 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001073
Ezio Melottiafd0d112009-07-15 17:17:17 +00001074 def test_read0(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001075 """Check that calling read(0) on a ZipExtFile object returns an empty
1076 string and doesn't advance file pointer."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001077 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1078 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1079 # read the data to make sure the file is there
Brian Curtin8fb9b862010-11-18 02:15:28 +00001080 with zipf.open("foo.txt") as f:
1081 for i in range(FIXEDTEST_SIZE):
1082 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001083
Brian Curtin8fb9b862010-11-18 02:15:28 +00001084 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001085
Ezio Melottiafd0d112009-07-15 17:17:17 +00001086 def test_open_non_existent_item(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001087 """Check that attempting to call open() for an item that doesn't
1088 exist in the archive raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001089 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1090 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001091
Ezio Melottiafd0d112009-07-15 17:17:17 +00001092 def test_bad_compression_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001093 """Check that bad compression methods passed to ZipFile.open are
1094 caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001095 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
1096
Martin v. Löwisb3260f02012-05-01 08:38:01 +02001097 def test_unsupported_compression(self):
1098 # data is declared as shrunk, but actually deflated
1099 data = (b'PK\x03\x04.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00'
1100 b'\x00\x02\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00x\x03\x00PK\x01'
1101 b'\x02.\x03.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00\x00\x02\x00\x00'
1102 b'\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
1103 b'\x80\x01\x00\x00\x00\x00xPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00'
1104 b'/\x00\x00\x00!\x00\x00\x00\x00\x00')
1105 with zipfile.ZipFile(io.BytesIO(data), 'r') as zipf:
1106 self.assertRaises(NotImplementedError, zipf.open, 'x')
1107
Ezio Melottiafd0d112009-07-15 17:17:17 +00001108 def test_null_byte_in_filename(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001109 """Check that a filename containing a null byte is properly
1110 terminated."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001111 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1112 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
1113 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001114
Ezio Melottiafd0d112009-07-15 17:17:17 +00001115 def test_struct_sizes(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001116 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001117 self.assertEqual(zipfile.sizeEndCentDir, 22)
1118 self.assertEqual(zipfile.sizeCentralDir, 46)
1119 self.assertEqual(zipfile.sizeEndCentDir64, 56)
1120 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
1121
Ezio Melottiafd0d112009-07-15 17:17:17 +00001122 def test_comments(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001123 """Check that comments on the archive are handled properly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001124
1125 # check default comment is empty
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001126 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1127 self.assertEqual(zipf.comment, b'')
1128 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1129
1130 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1131 self.assertEqual(zipfr.comment, b'')
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001132
1133 # check a simple short comment
1134 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001135 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1136 zipf.comment = comment
1137 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1138 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1139 self.assertEqual(zipf.comment, comment)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001140
1141 # check a comment of max length
1142 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
1143 comment2 = comment2.encode("ascii")
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001144 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1145 zipf.comment = comment2
1146 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1147
1148 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1149 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001150
1151 # check a comment that is too long is truncated
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001152 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1153 zipf.comment = comment2 + b'oops'
1154 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1155 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1156 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001157
Antoine Pitrouc3991852012-06-30 17:31:37 +02001158 # check that comments are correctly modified in append mode
1159 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1160 zipf.comment = b"original comment"
1161 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1162 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1163 zipf.comment = b"an updated comment"
1164 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1165 self.assertEqual(zipf.comment, b"an updated comment")
1166
1167 # check that comments are correctly shortened in append mode
1168 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1169 zipf.comment = b"original comment that's longer"
1170 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1171 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1172 zipf.comment = b"shorter comment"
1173 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1174 self.assertEqual(zipf.comment, b"shorter comment")
1175
R David Murrayf50b38a2012-04-12 18:44:58 -04001176 def test_unicode_comment(self):
1177 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1178 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1179 with self.assertRaises(TypeError):
1180 zipf.comment = "this is an error"
1181
1182 def test_change_comment_in_empty_archive(self):
1183 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1184 self.assertFalse(zipf.filelist)
1185 zipf.comment = b"this is a comment"
1186 with zipfile.ZipFile(TESTFN, "r") as zipf:
1187 self.assertEqual(zipf.comment, b"this is a comment")
1188
1189 def test_change_comment_in_nonempty_archive(self):
1190 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1191 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1192 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1193 self.assertTrue(zipf.filelist)
1194 zipf.comment = b"this is a comment"
1195 with zipfile.ZipFile(TESTFN, "r") as zipf:
1196 self.assertEqual(zipf.comment, b"this is a comment")
1197
Georg Brandl268e4d42010-10-14 06:59:45 +00001198 def test_empty_zipfile(self):
1199 # Check that creating a file in 'w' or 'a' mode and closing without
1200 # adding any files to the archives creates a valid empty ZIP file
1201 zipf = zipfile.ZipFile(TESTFN, mode="w")
1202 zipf.close()
1203 try:
1204 zipf = zipfile.ZipFile(TESTFN, mode="r")
1205 except zipfile.BadZipFile:
1206 self.fail("Unable to create empty ZIP file in 'w' mode")
1207
1208 zipf = zipfile.ZipFile(TESTFN, mode="a")
1209 zipf.close()
1210 try:
1211 zipf = zipfile.ZipFile(TESTFN, mode="r")
1212 except:
1213 self.fail("Unable to create empty ZIP file in 'a' mode")
1214
1215 def test_open_empty_file(self):
1216 # Issue 1710703: Check that opening a file with less than 22 bytes
Georg Brandl4d540882010-10-28 06:42:33 +00001217 # raises a BadZipFile exception (rather than the previously unhelpful
Georg Brandl268e4d42010-10-14 06:59:45 +00001218 # IOError)
1219 f = open(TESTFN, 'w')
1220 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001221 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN, 'r')
Georg Brandl268e4d42010-10-14 06:59:45 +00001222
Senthil Kumaran29fa9d42011-10-20 01:46:00 +08001223 def test_create_zipinfo_before_1980(self):
1224 self.assertRaises(ValueError,
1225 zipfile.ZipInfo, 'seventies', (1979, 1, 1, 0, 0, 0))
1226
Guido van Rossumd8faa362007-04-27 19:54:29 +00001227 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001228 unlink(TESTFN)
1229 unlink(TESTFN2)
1230
Thomas Wouterscf297e42007-02-23 15:07:44 +00001231
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001232class AbstractBadCrcTests:
1233 def test_testzip_with_bad_crc(self):
1234 """Tests that files with bad CRCs return their name from testzip."""
1235 zipdata = self.zip_with_bad_crc
1236
1237 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1238 # testzip returns the name of the first corrupt file, or None
1239 self.assertEqual('afile', zipf.testzip())
1240
1241 def test_read_with_bad_crc(self):
1242 """Tests that files with bad CRCs raise a BadZipFile exception when read."""
1243 zipdata = self.zip_with_bad_crc
1244
1245 # Using ZipFile.read()
1246 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1247 self.assertRaises(zipfile.BadZipFile, zipf.read, 'afile')
1248
1249 # Using ZipExtFile.read()
1250 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1251 with zipf.open('afile', 'r') as corrupt_file:
1252 self.assertRaises(zipfile.BadZipFile, corrupt_file.read)
1253
1254 # Same with small reads (in order to exercise the buffering logic)
1255 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1256 with zipf.open('afile', 'r') as corrupt_file:
1257 corrupt_file.MIN_READ_SIZE = 2
1258 with self.assertRaises(zipfile.BadZipFile):
1259 while corrupt_file.read(2):
1260 pass
1261
1262
1263class StoredBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1264 compression = zipfile.ZIP_STORED
1265 zip_with_bad_crc = (
1266 b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
1267 b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
1268 b'ilehello,AworldP'
1269 b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
1270 b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
1271 b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
1272 b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
1273 b'\0\0/\0\0\0\0\0')
1274
1275@requires_zlib
1276class DeflateBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1277 compression = zipfile.ZIP_DEFLATED
1278 zip_with_bad_crc = (
1279 b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
1280 b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1281 b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
1282 b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
1283 b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
1284 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
1285 b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
1286 b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00')
1287
1288@requires_bz2
1289class Bzip2BadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1290 compression = zipfile.ZIP_BZIP2
1291 zip_with_bad_crc = (
1292 b'PK\x03\x04\x14\x03\x00\x00\x0c\x00nu\x0c=FA'
1293 b'KE8\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1294 b'ileBZh91AY&SY\xd4\xa8\xca'
1295 b'\x7f\x00\x00\x0f\x11\x80@\x00\x06D\x90\x80 \x00 \xa5'
1296 b'P\xd9!\x03\x03\x13\x13\x13\x89\xa9\xa9\xc2u5:\x9f'
1297 b'\x8b\xb9"\x9c(HjTe?\x80PK\x01\x02\x14'
1298 b'\x03\x14\x03\x00\x00\x0c\x00nu\x0c=FAKE8'
1299 b'\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\x00'
1300 b'\x00 \x80\x80\x81\x00\x00\x00\x00afilePK'
1301 b'\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00\x00[\x00'
1302 b'\x00\x00\x00\x00')
1303
1304@requires_lzma
1305class LzmaBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1306 compression = zipfile.ZIP_LZMA
1307 zip_with_bad_crc = (
1308 b'PK\x03\x04\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
1309 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1310 b'ile\t\x04\x05\x00]\x00\x00\x00\x04\x004\x19I'
1311 b'\xee\x8d\xe9\x17\x89:3`\tq!.8\x00PK'
1312 b'\x01\x02\x14\x03\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
1313 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00'
1314 b'\x00\x00\x00\x00 \x80\x80\x81\x00\x00\x00\x00afil'
1315 b'ePK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00'
1316 b'\x00>\x00\x00\x00\x00\x00')
1317
1318
Thomas Wouterscf297e42007-02-23 15:07:44 +00001319class DecryptionTests(unittest.TestCase):
Ezio Melotti35386712009-12-31 13:22:41 +00001320 """Check that ZIP decryption works. Since the library does not
1321 support encryption at the moment, we use a pre-generated encrypted
1322 ZIP file."""
Thomas Wouterscf297e42007-02-23 15:07:44 +00001323
1324 data = (
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001325 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
1326 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
1327 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
1328 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
1329 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
1330 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
1331 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +00001332 data2 = (
1333 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
1334 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
1335 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
1336 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
1337 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
1338 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
1339 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
1340 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +00001341
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001342 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +00001343 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +00001344
1345 def setUp(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001346 with open(TESTFN, "wb") as fp:
1347 fp.write(self.data)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001348 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti35386712009-12-31 13:22:41 +00001349 with open(TESTFN2, "wb") as fp:
1350 fp.write(self.data2)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001351 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001352
1353 def tearDown(self):
1354 self.zip.close()
1355 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001356 self.zip2.close()
1357 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001358
Ezio Melottiafd0d112009-07-15 17:17:17 +00001359 def test_no_password(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001360 # Reading the encrypted file without password
1361 # must generate a RunTime exception
1362 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001363 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001364
Ezio Melottiafd0d112009-07-15 17:17:17 +00001365 def test_bad_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001366 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001367 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001368 self.zip2.setpassword(b"perl")
1369 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001370
Ezio Melotti975077a2011-05-19 22:03:22 +03001371 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +00001372 def test_good_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001373 self.zip.setpassword(b"python")
Ezio Melotti35386712009-12-31 13:22:41 +00001374 self.assertEqual(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001375 self.zip2.setpassword(b"12345")
Ezio Melotti35386712009-12-31 13:22:41 +00001376 self.assertEqual(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001377
R. David Murray8d855d82010-12-21 21:53:37 +00001378 def test_unicode_password(self):
1379 self.assertRaises(TypeError, self.zip.setpassword, "unicode")
1380 self.assertRaises(TypeError, self.zip.read, "test.txt", "python")
1381 self.assertRaises(TypeError, self.zip.open, "test.txt", pwd="python")
1382 self.assertRaises(TypeError, self.zip.extract, "test.txt", pwd="python")
1383
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001384class AbstractTestsWithRandomBinaryFiles:
1385 @classmethod
1386 def setUpClass(cls):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001387 datacount = randint(16, 64)*1024 + randint(1, 1024)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001388 cls.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
1389 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001390
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001391 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001392 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +00001393 with open(TESTFN, "wb") as fp:
1394 fp.write(self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001395
1396 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001397 unlink(TESTFN)
1398 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001399
Ezio Melottiafd0d112009-07-15 17:17:17 +00001400 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001401 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001402 with zipfile.ZipFile(f, "w", compression) as zipfp:
1403 zipfp.write(TESTFN, "another.name")
1404 zipfp.write(TESTFN, TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001405
Ezio Melottiafd0d112009-07-15 17:17:17 +00001406 def zip_test(self, f, compression):
1407 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001408
1409 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001410 with zipfile.ZipFile(f, "r", compression) as zipfp:
1411 testdata = zipfp.read(TESTFN)
1412 self.assertEqual(len(testdata), len(self.data))
1413 self.assertEqual(testdata, self.data)
1414 self.assertEqual(zipfp.read("another.name"), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001415
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001416 def test_read(self):
1417 for f in get_files(self):
1418 self.zip_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001419
Ezio Melottiafd0d112009-07-15 17:17:17 +00001420 def zip_open_test(self, f, compression):
1421 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001422
1423 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001424 with zipfile.ZipFile(f, "r", compression) as zipfp:
1425 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001426 with zipfp.open(TESTFN) as zipopen1:
1427 while True:
1428 read_data = zipopen1.read(256)
1429 if not read_data:
1430 break
1431 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001432
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001433 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001434 with zipfp.open("another.name") as zipopen2:
1435 while True:
1436 read_data = zipopen2.read(256)
1437 if not read_data:
1438 break
1439 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001440
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001441 testdata1 = b''.join(zipdata1)
1442 self.assertEqual(len(testdata1), len(self.data))
1443 self.assertEqual(testdata1, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001444
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001445 testdata2 = b''.join(zipdata2)
Ezio Melotti35386712009-12-31 13:22:41 +00001446 self.assertEqual(len(testdata2), len(self.data))
1447 self.assertEqual(testdata2, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001448
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001449 def test_open(self):
1450 for f in get_files(self):
1451 self.zip_open_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001452
Ezio Melottiafd0d112009-07-15 17:17:17 +00001453 def zip_random_open_test(self, f, compression):
1454 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001455
1456 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001457 with zipfile.ZipFile(f, "r", compression) as zipfp:
1458 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001459 with zipfp.open(TESTFN) as zipopen1:
1460 while True:
1461 read_data = zipopen1.read(randint(1, 1024))
1462 if not read_data:
1463 break
1464 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001465
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001466 testdata = b''.join(zipdata1)
1467 self.assertEqual(len(testdata), len(self.data))
1468 self.assertEqual(testdata, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001469
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001470 def test_random_open(self):
1471 for f in get_files(self):
1472 self.zip_random_open_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001473
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001474
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001475class StoredTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1476 unittest.TestCase):
1477 compression = zipfile.ZIP_STORED
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001478
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001479@requires_zlib
1480class DeflateTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1481 unittest.TestCase):
1482 compression = zipfile.ZIP_DEFLATED
1483
1484@requires_bz2
1485class Bzip2TestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1486 unittest.TestCase):
1487 compression = zipfile.ZIP_BZIP2
1488
1489@requires_lzma
1490class LzmaTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1491 unittest.TestCase):
1492 compression = zipfile.ZIP_LZMA
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001493
Ezio Melotti76430242009-07-11 18:28:48 +00001494
Ezio Melotti975077a2011-05-19 22:03:22 +03001495@requires_zlib
Guido van Rossumd8faa362007-04-27 19:54:29 +00001496class TestsWithMultipleOpens(unittest.TestCase):
1497 def setUp(self):
1498 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001499 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
1500 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
1501 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001502
Ezio Melottiafd0d112009-07-15 17:17:17 +00001503 def test_same_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001504 # Verify that (when the ZipFile is in control of creating file objects)
1505 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001506 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001507 with zipf.open('ones') as zopen1, zipf.open('ones') as zopen2:
1508 data1 = zopen1.read(500)
1509 data2 = zopen2.read(500)
1510 data1 += zopen1.read(500)
1511 data2 += zopen2.read(500)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001512 self.assertEqual(data1, data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001513
Ezio Melottiafd0d112009-07-15 17:17:17 +00001514 def test_different_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001515 # Verify that (when the ZipFile is in control of creating file objects)
1516 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001517 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001518 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1519 data1 = zopen1.read(500)
1520 data2 = zopen2.read(500)
1521 data1 += zopen1.read(500)
1522 data2 += zopen2.read(500)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001523 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
1524 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001525
Ezio Melottiafd0d112009-07-15 17:17:17 +00001526 def test_interleaved(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001527 # Verify that (when the ZipFile is in control of creating file objects)
1528 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001529 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001530 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1531 data1 = zopen1.read(500)
1532 data2 = zopen2.read(500)
1533 data1 += zopen1.read(500)
1534 data2 += zopen2.read(500)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001535 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
1536 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001537
1538 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001539 unlink(TESTFN2)
1540
Guido van Rossumd8faa362007-04-27 19:54:29 +00001541
Martin v. Löwis59e47792009-01-24 14:10:07 +00001542class TestWithDirectory(unittest.TestCase):
1543 def setUp(self):
1544 os.mkdir(TESTFN2)
1545
Ezio Melottiafd0d112009-07-15 17:17:17 +00001546 def test_extract_dir(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001547 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
1548 zipf.extractall(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001549 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1550 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1551 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1552
Ezio Melottiafd0d112009-07-15 17:17:17 +00001553 def test_bug_6050(self):
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001554 # Extraction should succeed if directories already exist
1555 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottiafd0d112009-07-15 17:17:17 +00001556 self.test_extract_dir()
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001557
Ezio Melottiafd0d112009-07-15 17:17:17 +00001558 def test_store_dir(self):
Martin v. Löwis59e47792009-01-24 14:10:07 +00001559 os.mkdir(os.path.join(TESTFN2, "x"))
1560 zipf = zipfile.ZipFile(TESTFN, "w")
1561 zipf.write(os.path.join(TESTFN2, "x"), "x")
1562 self.assertTrue(zipf.filelist[0].filename.endswith("x/"))
1563
1564 def tearDown(self):
1565 shutil.rmtree(TESTFN2)
1566 if os.path.exists(TESTFN):
Ezio Melotti76430242009-07-11 18:28:48 +00001567 unlink(TESTFN)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001568
Guido van Rossumd8faa362007-04-27 19:54:29 +00001569
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001570class AbstractUniversalNewlineTests:
1571 @classmethod
1572 def setUpClass(cls):
1573 cls.line_gen = [bytes("Test of zipfile line %d." % i, "ascii")
1574 for i in range(FIXEDTEST_SIZE)]
1575 cls.seps = (b'\r', b'\r\n', b'\n')
1576 cls.arcdata = {}
1577 for n, s in enumerate(cls.seps):
1578 cls.arcdata[s] = s.join(cls.line_gen) + s
1579
Guido van Rossumd8faa362007-04-27 19:54:29 +00001580 def setUp(self):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001581 self.arcfiles = {}
Guido van Rossumd8faa362007-04-27 19:54:29 +00001582 for n, s in enumerate(self.seps):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001583 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001584 with open(self.arcfiles[s], "wb") as f:
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001585 f.write(self.arcdata[s])
Guido van Rossumd8faa362007-04-27 19:54:29 +00001586
Ezio Melottiafd0d112009-07-15 17:17:17 +00001587 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001588 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001589 with zipfile.ZipFile(f, "w", compression) as zipfp:
1590 for fn in self.arcfiles.values():
1591 zipfp.write(fn, fn)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001592
Ezio Melottiafd0d112009-07-15 17:17:17 +00001593 def read_test(self, f, compression):
1594 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001595
1596 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001597 with zipfile.ZipFile(f, "r") as zipfp:
1598 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001599 with zipfp.open(fn, "rU") as fp:
1600 zipdata = fp.read()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001601 self.assertEqual(self.arcdata[sep], zipdata)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001602
1603 def test_read(self):
1604 for f in get_files(self):
1605 self.read_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001606
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001607 def readline_read_test(self, f, compression):
1608 self.make_test_archive(f, compression)
1609
1610 # Read the ZIP archive
Brian Curtin8fb9b862010-11-18 02:15:28 +00001611 with zipfile.ZipFile(f, "r") as zipfp:
1612 for sep, fn in self.arcfiles.items():
1613 with zipfp.open(fn, "rU") as zipopen:
1614 data = b''
1615 while True:
1616 read = zipopen.readline()
1617 if not read:
1618 break
1619 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001620
Brian Curtin8fb9b862010-11-18 02:15:28 +00001621 read = zipopen.read(5)
1622 if not read:
1623 break
1624 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001625
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001626 self.assertEqual(data, self.arcdata[b'\n'])
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001627
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001628 def test_readline_read(self):
1629 for f in get_files(self):
1630 self.readline_read_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001631
Ezio Melottiafd0d112009-07-15 17:17:17 +00001632 def readline_test(self, f, compression):
1633 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001634
1635 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001636 with zipfile.ZipFile(f, "r") as zipfp:
1637 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001638 with zipfp.open(fn, "rU") as zipopen:
1639 for line in self.line_gen:
1640 linedata = zipopen.readline()
1641 self.assertEqual(linedata, line + b'\n')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001642
1643 def test_readline(self):
1644 for f in get_files(self):
1645 self.readline_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001646
Ezio Melottiafd0d112009-07-15 17:17:17 +00001647 def readlines_test(self, f, compression):
1648 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001649
1650 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001651 with zipfile.ZipFile(f, "r") as zipfp:
1652 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001653 with zipfp.open(fn, "rU") as fp:
1654 ziplines = fp.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001655 for line, zipline in zip(self.line_gen, ziplines):
1656 self.assertEqual(zipline, line + b'\n')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001657
1658 def test_readlines(self):
1659 for f in get_files(self):
1660 self.readlines_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001661
Ezio Melottiafd0d112009-07-15 17:17:17 +00001662 def iterlines_test(self, f, compression):
1663 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001664
1665 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001666 with zipfile.ZipFile(f, "r") as zipfp:
1667 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001668 with zipfp.open(fn, "rU") as fp:
1669 for line, zipline in zip(self.line_gen, fp):
1670 self.assertEqual(zipline, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001671
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001672 def test_iterlines(self):
1673 for f in get_files(self):
1674 self.iterlines_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001675
Guido van Rossumd8faa362007-04-27 19:54:29 +00001676 def tearDown(self):
1677 for sep, fn in self.arcfiles.items():
1678 os.remove(fn)
Ezio Melotti76430242009-07-11 18:28:48 +00001679 unlink(TESTFN)
1680 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001681
1682
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001683class StoredUniversalNewlineTests(AbstractUniversalNewlineTests,
1684 unittest.TestCase):
1685 compression = zipfile.ZIP_STORED
1686
1687@requires_zlib
1688class DeflateUniversalNewlineTests(AbstractUniversalNewlineTests,
1689 unittest.TestCase):
1690 compression = zipfile.ZIP_DEFLATED
1691
1692@requires_bz2
1693class Bzip2UniversalNewlineTests(AbstractUniversalNewlineTests,
1694 unittest.TestCase):
1695 compression = zipfile.ZIP_BZIP2
1696
1697@requires_lzma
1698class LzmaUniversalNewlineTests(AbstractUniversalNewlineTests,
1699 unittest.TestCase):
1700 compression = zipfile.ZIP_LZMA
1701
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001702
1703if __name__ == "__main__":
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001704 unittest.main()