blob: 0c4c5791c480c943444a958ece096fd1ac11aa5f [file] [log] [blame]
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001import contextlib
Ezio Melotti74c96ec2009-07-08 22:24:06 +00002import io
3import os
Georg Brandl5ba11de2011-01-01 10:09:32 +00004import sys
Brett Cannonb57a0852013-06-15 17:32:30 -04005import importlib.util
Ezio Melotti35386712009-12-31 13:22:41 +00006import time
Ezio Melotti74c96ec2009-07-08 22:24:06 +00007import struct
8import zipfile
9import unittest
10
Tim Petersa45cacf2004-08-20 03:47:14 +000011
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000012from tempfile import TemporaryFile
Serhiy Storchakafa6bc292013-07-22 21:00:11 +030013from random import randint, random, getrandbits
Tim Petersa19a1682001-03-29 04:36:09 +000014
Victor Stinner57004c62014-09-04 00:49:01 +020015from test.support import (TESTFN, findfile, unlink, rmtree,
Serhiy Storchakac5b75db2013-01-29 20:14:08 +020016 requires_zlib, requires_bz2, requires_lzma,
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +020017 captured_stdout, check_warnings)
Guido van Rossum368f04a2000-04-10 13:23:04 +000018
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000019TESTFN2 = TESTFN + "2"
Martin v. Löwis59e47792009-01-24 14:10:07 +000020TESTFNDIR = TESTFN + "d"
Guido van Rossumb5a755e2007-07-18 18:15:48 +000021FIXEDTEST_SIZE = 1000
Georg Brandl5ba11de2011-01-01 10:09:32 +000022DATAFILES_DIR = 'zipfile_datafiles'
Guido van Rossum368f04a2000-04-10 13:23:04 +000023
Christian Heimes790c8232008-01-07 21:14:23 +000024SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'),
25 ('ziptest2dir/_ziptest2', 'qawsedrftg'),
Gregory P. Smithb47acbf2013-02-01 11:22:43 -080026 ('ziptest2dir/ziptest3dir/_ziptest3', 'azsxdcfvgb'),
Christian Heimes790c8232008-01-07 21:14:23 +000027 ('ziptest2dir/ziptest3dir/ziptest4dir/_ziptest3', '6y7u8i9o0p')]
28
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +020029def getrandbytes(size):
30 return getrandbits(8 * size).to_bytes(size, 'little')
31
Serhiy Storchakafa6bc292013-07-22 21:00:11 +030032def get_files(test):
33 yield TESTFN2
34 with TemporaryFile() as f:
35 yield f
36 test.assertFalse(f.closed)
37 with io.BytesIO() as f:
38 yield f
39 test.assertFalse(f.closed)
Ezio Melotti76430242009-07-11 18:28:48 +000040
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +020041def openU(zipfp, fn):
42 with check_warnings(('', DeprecationWarning)):
43 return zipfp.open(fn, 'rU')
44
Serhiy Storchakafa6bc292013-07-22 21:00:11 +030045class AbstractTestsWithSourceFile:
46 @classmethod
47 def setUpClass(cls):
48 cls.line_gen = [bytes("Zipfile test line %d. random float: %f\n" %
49 (i, random()), "ascii")
50 for i in range(FIXEDTEST_SIZE)]
51 cls.data = b''.join(cls.line_gen)
52
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000053 def setUp(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000054 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +000055 with open(TESTFN, "wb") as fp:
56 fp.write(self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000057
Ezio Melottiafd0d112009-07-15 17:17:17 +000058 def make_test_archive(self, f, compression):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000059 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000060 with zipfile.ZipFile(f, "w", compression) as zipfp:
61 zipfp.write(TESTFN, "another.name")
62 zipfp.write(TESTFN, TESTFN)
63 zipfp.writestr("strfile", self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000064
Ezio Melottiafd0d112009-07-15 17:17:17 +000065 def zip_test(self, f, compression):
66 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +000067
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000068 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000069 with zipfile.ZipFile(f, "r", compression) as zipfp:
70 self.assertEqual(zipfp.read(TESTFN), self.data)
71 self.assertEqual(zipfp.read("another.name"), self.data)
72 self.assertEqual(zipfp.read("strfile"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000073
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000074 # Print the ZIP directory
75 fp = io.StringIO()
76 zipfp.printdir(file=fp)
77 directory = fp.getvalue()
78 lines = directory.splitlines()
Ezio Melotti35386712009-12-31 13:22:41 +000079 self.assertEqual(len(lines), 4) # Number of files + header
Thomas Wouters0e3f5912006-08-11 14:57:12 +000080
Benjamin Peterson577473f2010-01-19 00:09:57 +000081 self.assertIn('File Name', lines[0])
82 self.assertIn('Modified', lines[0])
83 self.assertIn('Size', lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +000084
Ezio Melotti35386712009-12-31 13:22:41 +000085 fn, date, time_, size = lines[1].split()
86 self.assertEqual(fn, 'another.name')
87 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
88 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
89 self.assertEqual(size, str(len(self.data)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000090
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000091 # Check the namelist
92 names = zipfp.namelist()
Ezio Melotti35386712009-12-31 13:22:41 +000093 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +000094 self.assertIn(TESTFN, names)
95 self.assertIn("another.name", names)
96 self.assertIn("strfile", names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000097
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000098 # Check infolist
99 infos = zipfp.infolist()
Ezio Melotti35386712009-12-31 13:22:41 +0000100 names = [i.filename for i in infos]
101 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000102 self.assertIn(TESTFN, names)
103 self.assertIn("another.name", names)
104 self.assertIn("strfile", names)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000105 for i in infos:
Ezio Melotti35386712009-12-31 13:22:41 +0000106 self.assertEqual(i.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000107
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000108 # check getinfo
109 for nm in (TESTFN, "another.name", "strfile"):
110 info = zipfp.getinfo(nm)
Ezio Melotti35386712009-12-31 13:22:41 +0000111 self.assertEqual(info.filename, nm)
112 self.assertEqual(info.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000113
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000114 # Check that testzip doesn't raise an exception
115 zipfp.testzip()
Tim Peters7d3bad62001-04-04 18:56:49 +0000116
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300117 def test_basic(self):
118 for f in get_files(self):
119 self.zip_test(f, self.compression)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000120
Ezio Melottiafd0d112009-07-15 17:17:17 +0000121 def zip_open_test(self, f, compression):
122 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000123
124 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000125 with zipfile.ZipFile(f, "r", compression) as zipfp:
126 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000127 with zipfp.open(TESTFN) as zipopen1:
128 while True:
129 read_data = zipopen1.read(256)
130 if not read_data:
131 break
132 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000133
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000134 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000135 with zipfp.open("another.name") as zipopen2:
136 while True:
137 read_data = zipopen2.read(256)
138 if not read_data:
139 break
140 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000141
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000142 self.assertEqual(b''.join(zipdata1), self.data)
143 self.assertEqual(b''.join(zipdata2), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000144
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300145 def test_open(self):
146 for f in get_files(self):
147 self.zip_open_test(f, self.compression)
Georg Brandlb533e262008-05-25 18:19:30 +0000148
Ezio Melottiafd0d112009-07-15 17:17:17 +0000149 def zip_random_open_test(self, f, compression):
150 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000151
152 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000153 with zipfile.ZipFile(f, "r", compression) as zipfp:
154 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000155 with zipfp.open(TESTFN) as zipopen1:
156 while True:
157 read_data = zipopen1.read(randint(1, 1024))
158 if not read_data:
159 break
160 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000161
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000162 self.assertEqual(b''.join(zipdata1), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000163
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300164 def test_random_open(self):
165 for f in get_files(self):
166 self.zip_random_open_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000167
Serhiy Storchakad2c07a52013-09-27 22:11:57 +0300168 def zip_read1_test(self, f, compression):
169 self.make_test_archive(f, compression)
170
171 # Read the ZIP archive
172 with zipfile.ZipFile(f, "r") as zipfp, \
173 zipfp.open(TESTFN) as zipopen:
174 zipdata = []
175 while True:
176 read_data = zipopen.read1(-1)
177 if not read_data:
178 break
179 zipdata.append(read_data)
180
181 self.assertEqual(b''.join(zipdata), self.data)
182
183 def test_read1(self):
184 for f in get_files(self):
185 self.zip_read1_test(f, self.compression)
186
187 def zip_read1_10_test(self, f, compression):
188 self.make_test_archive(f, compression)
189
190 # Read the ZIP archive
191 with zipfile.ZipFile(f, "r") as zipfp, \
192 zipfp.open(TESTFN) as zipopen:
193 zipdata = []
194 while True:
195 read_data = zipopen.read1(10)
196 self.assertLessEqual(len(read_data), 10)
197 if not read_data:
198 break
199 zipdata.append(read_data)
200
201 self.assertEqual(b''.join(zipdata), self.data)
202
203 def test_read1_10(self):
204 for f in get_files(self):
205 self.zip_read1_10_test(f, self.compression)
206
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000207 def zip_readline_read_test(self, f, compression):
208 self.make_test_archive(f, compression)
209
210 # Read the ZIP archive
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300211 with zipfile.ZipFile(f, "r") as zipfp, \
212 zipfp.open(TESTFN) as zipopen:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000213 data = b''
214 while True:
215 read = zipopen.readline()
216 if not read:
217 break
218 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000219
Brian Curtin8fb9b862010-11-18 02:15:28 +0000220 read = zipopen.read(100)
221 if not read:
222 break
223 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000224
225 self.assertEqual(data, self.data)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300226
227 def test_readline_read(self):
228 # Issue #7610: calls to readline() interleaved with calls to read().
229 for f in get_files(self):
230 self.zip_readline_read_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000231
Ezio Melottiafd0d112009-07-15 17:17:17 +0000232 def zip_readline_test(self, f, compression):
233 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000234
235 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000236 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000237 with zipfp.open(TESTFN) as zipopen:
238 for line in self.line_gen:
239 linedata = zipopen.readline()
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300240 self.assertEqual(linedata, line)
241
242 def test_readline(self):
243 for f in get_files(self):
244 self.zip_readline_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000245
Ezio Melottiafd0d112009-07-15 17:17:17 +0000246 def zip_readlines_test(self, f, compression):
247 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000248
249 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000250 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000251 with zipfp.open(TESTFN) as zipopen:
252 ziplines = zipopen.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000253 for line, zipline in zip(self.line_gen, ziplines):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300254 self.assertEqual(zipline, line)
255
256 def test_readlines(self):
257 for f in get_files(self):
258 self.zip_readlines_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000259
Ezio Melottiafd0d112009-07-15 17:17:17 +0000260 def zip_iterlines_test(self, f, compression):
261 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000262
263 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000264 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000265 with zipfp.open(TESTFN) as zipopen:
266 for line, zipline in zip(self.line_gen, zipopen):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300267 self.assertEqual(zipline, line)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000268
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300269 def test_iterlines(self):
270 for f in get_files(self):
271 self.zip_iterlines_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000272
Ezio Melottiafd0d112009-07-15 17:17:17 +0000273 def test_low_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000274 """Check for cases where compressed data is larger than original."""
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000275 # Create the ZIP archive
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300276 with zipfile.ZipFile(TESTFN2, "w", self.compression) as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000277 zipfp.writestr("strfile", '12')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000278
279 # Get an open object for strfile
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300280 with zipfile.ZipFile(TESTFN2, "r", self.compression) as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000281 with zipfp.open("strfile") as openobj:
282 self.assertEqual(openobj.read(1), b'1')
283 self.assertEqual(openobj.read(1), b'2')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000284
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300285 def test_writestr_compression(self):
286 zipfp = zipfile.ZipFile(TESTFN2, "w")
287 zipfp.writestr("b.txt", "hello world", compress_type=self.compression)
288 info = zipfp.getinfo('b.txt')
289 self.assertEqual(info.compress_type, self.compression)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200290
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300291 def test_read_return_size(self):
292 # Issue #9837: ZipExtFile.read() shouldn't return more bytes
293 # than requested.
294 for test_size in (1, 4095, 4096, 4097, 16384):
295 file_size = test_size + 1
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +0200296 junk = getrandbytes(file_size)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300297 with zipfile.ZipFile(io.BytesIO(), "w", self.compression) as zipf:
298 zipf.writestr('foo', junk)
299 with zipf.open('foo', 'r') as fp:
300 buf = fp.read(test_size)
301 self.assertEqual(len(buf), test_size)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200302
Serhiy Storchaka5ce3f102014-01-09 14:50:20 +0200303 def test_truncated_zipfile(self):
304 fp = io.BytesIO()
305 with zipfile.ZipFile(fp, mode='w') as zipf:
306 zipf.writestr('strfile', self.data, compress_type=self.compression)
307 end_offset = fp.tell()
308 zipfiledata = fp.getvalue()
309
310 fp = io.BytesIO(zipfiledata)
311 with zipfile.ZipFile(fp) as zipf:
312 with zipf.open('strfile') as zipopen:
313 fp.truncate(end_offset - 20)
314 with self.assertRaises(EOFError):
315 zipopen.read()
316
317 fp = io.BytesIO(zipfiledata)
318 with zipfile.ZipFile(fp) as zipf:
319 with zipf.open('strfile') as zipopen:
320 fp.truncate(end_offset - 20)
321 with self.assertRaises(EOFError):
322 while zipopen.read(100):
323 pass
324
325 fp = io.BytesIO(zipfiledata)
326 with zipfile.ZipFile(fp) as zipf:
327 with zipf.open('strfile') as zipopen:
328 fp.truncate(end_offset - 20)
329 with self.assertRaises(EOFError):
330 while zipopen.read1(100):
331 pass
332
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300333 def tearDown(self):
334 unlink(TESTFN)
335 unlink(TESTFN2)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200336
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200337
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300338class StoredTestsWithSourceFile(AbstractTestsWithSourceFile,
339 unittest.TestCase):
340 compression = zipfile.ZIP_STORED
341 test_low_compression = None
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200342
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300343 def zip_test_writestr_permissions(self, f, compression):
344 # Make sure that writestr creates files with mode 0600,
345 # when it is passed a name rather than a ZipInfo instance.
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200346
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300347 self.make_test_archive(f, compression)
348 with zipfile.ZipFile(f, "r") as zipfp:
349 zinfo = zipfp.getinfo('strfile')
350 self.assertEqual(zinfo.external_attr, 0o600 << 16)
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200351
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300352 def test_writestr_permissions(self):
353 for f in get_files(self):
354 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +0200355
Ezio Melottiafd0d112009-07-15 17:17:17 +0000356 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000357 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
358 zipfp.write(TESTFN, "/absolute")
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000359
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000360 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
361 self.assertEqual(zipfp.namelist(), ["absolute"])
Tim Peters32cbc962006-02-20 21:42:18 +0000362
Ezio Melottiafd0d112009-07-15 17:17:17 +0000363 def test_append_to_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000364 """Test appending to an existing zipfile."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000365 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
366 zipfp.write(TESTFN, TESTFN)
367
368 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
369 zipfp.writestr("strfile", self.data)
370 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000371
Ezio Melottiafd0d112009-07-15 17:17:17 +0000372 def test_append_to_non_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000373 """Test appending to an existing file that is not a zipfile."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000374 # NOTE: this test fails if len(d) < 22 because of the first
375 # line "fpin.seek(-22, 2)" in _EndRecData
Ezio Melotti35386712009-12-31 13:22:41 +0000376 data = b'I am not a ZipFile!'*10
377 with open(TESTFN2, 'wb') as f:
378 f.write(data)
379
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000380 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
381 zipfp.write(TESTFN, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000382
Ezio Melotti35386712009-12-31 13:22:41 +0000383 with open(TESTFN2, 'rb') as f:
384 f.seek(len(data))
385 with zipfile.ZipFile(f, "r") as zipfp:
386 self.assertEqual(zipfp.namelist(), [TESTFN])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000387
R David Murray4fbb9db2011-06-09 15:50:51 -0400388 def test_ignores_newline_at_end(self):
389 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
390 zipfp.write(TESTFN, TESTFN)
391 with open(TESTFN2, 'a') as f:
392 f.write("\r\n\00\00\00")
393 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
394 self.assertIsInstance(zipfp, zipfile.ZipFile)
395
396 def test_ignores_stuff_appended_past_comments(self):
397 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
398 zipfp.comment = b"this is a comment"
399 zipfp.write(TESTFN, TESTFN)
400 with open(TESTFN2, 'a') as f:
401 f.write("abcdef\r\n")
402 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
403 self.assertIsInstance(zipfp, zipfile.ZipFile)
404 self.assertEqual(zipfp.comment, b"this is a comment")
405
Ezio Melottiafd0d112009-07-15 17:17:17 +0000406 def test_write_default_name(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000407 """Check that calling ZipFile.write without arcname specified
408 produces the expected result."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000409 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
410 zipfp.write(TESTFN)
Brian Curtin8fb9b862010-11-18 02:15:28 +0000411 with open(TESTFN, "rb") as f:
412 self.assertEqual(zipfp.read(TESTFN), f.read())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000413
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300414 def test_write_to_readonly(self):
415 """Check that trying to call write() on a readonly ZipFile object
416 raises a RuntimeError."""
417 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
418 zipfp.writestr("somefile.txt", "bogus")
419
420 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
421 self.assertRaises(RuntimeError, zipfp.write, TESTFN)
422
423 def test_add_file_before_1980(self):
424 # Set atime and mtime to 1970-01-01
425 os.utime(TESTFN, (0, 0))
426 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
427 self.assertRaises(ValueError, zipfp.write, TESTFN)
428
Serhiy Storchaka5ce3f102014-01-09 14:50:20 +0200429
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300430@requires_zlib
431class DeflateTestsWithSourceFile(AbstractTestsWithSourceFile,
432 unittest.TestCase):
433 compression = zipfile.ZIP_DEFLATED
434
Ezio Melottiafd0d112009-07-15 17:17:17 +0000435 def test_per_file_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000436 """Check that files within a Zip archive can have different
437 compression options."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000438 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
439 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
440 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
441 sinfo = zipfp.getinfo('storeme')
442 dinfo = zipfp.getinfo('deflateme')
443 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
444 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000445
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300446@requires_bz2
447class Bzip2TestsWithSourceFile(AbstractTestsWithSourceFile,
448 unittest.TestCase):
449 compression = zipfile.ZIP_BZIP2
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000450
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300451@requires_lzma
452class LzmaTestsWithSourceFile(AbstractTestsWithSourceFile,
453 unittest.TestCase):
454 compression = zipfile.ZIP_LZMA
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000455
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300456
457class AbstractTestZip64InSmallFiles:
458 # These tests test the ZIP64 functionality without using large files,
459 # see test_zipfile64 for proper tests.
460
461 @classmethod
462 def setUpClass(cls):
463 line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
464 for i in range(0, FIXEDTEST_SIZE))
465 cls.data = b'\n'.join(line_gen)
466
467 def setUp(self):
468 self._limit = zipfile.ZIP64_LIMIT
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300469 self._filecount_limit = zipfile.ZIP_FILECOUNT_LIMIT
470 zipfile.ZIP64_LIMIT = 1000
471 zipfile.ZIP_FILECOUNT_LIMIT = 9
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300472
473 # Make a source file with some lines
474 with open(TESTFN, "wb") as fp:
475 fp.write(self.data)
476
477 def zip_test(self, f, compression):
478 # Create the ZIP archive
479 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
480 zipfp.write(TESTFN, "another.name")
481 zipfp.write(TESTFN, TESTFN)
482 zipfp.writestr("strfile", self.data)
483
484 # Read the ZIP archive
485 with zipfile.ZipFile(f, "r", compression) as zipfp:
486 self.assertEqual(zipfp.read(TESTFN), self.data)
487 self.assertEqual(zipfp.read("another.name"), self.data)
488 self.assertEqual(zipfp.read("strfile"), self.data)
489
490 # Print the ZIP directory
491 fp = io.StringIO()
492 zipfp.printdir(fp)
493
494 directory = fp.getvalue()
495 lines = directory.splitlines()
496 self.assertEqual(len(lines), 4) # Number of files + header
497
498 self.assertIn('File Name', lines[0])
499 self.assertIn('Modified', lines[0])
500 self.assertIn('Size', lines[0])
501
502 fn, date, time_, size = lines[1].split()
503 self.assertEqual(fn, 'another.name')
504 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
505 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
506 self.assertEqual(size, str(len(self.data)))
507
508 # Check the namelist
509 names = zipfp.namelist()
510 self.assertEqual(len(names), 3)
511 self.assertIn(TESTFN, names)
512 self.assertIn("another.name", names)
513 self.assertIn("strfile", names)
514
515 # Check infolist
516 infos = zipfp.infolist()
517 names = [i.filename for i in infos]
518 self.assertEqual(len(names), 3)
519 self.assertIn(TESTFN, names)
520 self.assertIn("another.name", names)
521 self.assertIn("strfile", names)
522 for i in infos:
523 self.assertEqual(i.file_size, len(self.data))
524
525 # check getinfo
526 for nm in (TESTFN, "another.name", "strfile"):
527 info = zipfp.getinfo(nm)
528 self.assertEqual(info.filename, nm)
529 self.assertEqual(info.file_size, len(self.data))
530
531 # Check that testzip doesn't raise an exception
532 zipfp.testzip()
533
534 def test_basic(self):
535 for f in get_files(self):
536 self.zip_test(f, self.compression)
537
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300538 def test_too_many_files(self):
539 # This test checks that more than 64k files can be added to an archive,
540 # and that the resulting archive can be read properly by ZipFile
541 zipf = zipfile.ZipFile(TESTFN, "w", self.compression,
542 allowZip64=True)
543 zipf.debug = 100
544 numfiles = 15
545 for i in range(numfiles):
546 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
547 self.assertEqual(len(zipf.namelist()), numfiles)
548 zipf.close()
549
550 zipf2 = zipfile.ZipFile(TESTFN, "r", self.compression)
551 self.assertEqual(len(zipf2.namelist()), numfiles)
552 for i in range(numfiles):
553 content = zipf2.read("foo%08d" % i).decode('ascii')
554 self.assertEqual(content, "%d" % (i**3 % 57))
555 zipf2.close()
556
557 def test_too_many_files_append(self):
558 zipf = zipfile.ZipFile(TESTFN, "w", self.compression,
559 allowZip64=False)
560 zipf.debug = 100
561 numfiles = 9
562 for i in range(numfiles):
563 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
564 self.assertEqual(len(zipf.namelist()), numfiles)
565 with self.assertRaises(zipfile.LargeZipFile):
566 zipf.writestr("foo%08d" % numfiles, b'')
567 self.assertEqual(len(zipf.namelist()), numfiles)
568 zipf.close()
569
570 zipf = zipfile.ZipFile(TESTFN, "a", self.compression,
571 allowZip64=False)
572 zipf.debug = 100
573 self.assertEqual(len(zipf.namelist()), numfiles)
574 with self.assertRaises(zipfile.LargeZipFile):
575 zipf.writestr("foo%08d" % numfiles, b'')
576 self.assertEqual(len(zipf.namelist()), numfiles)
577 zipf.close()
578
579 zipf = zipfile.ZipFile(TESTFN, "a", self.compression,
580 allowZip64=True)
581 zipf.debug = 100
582 self.assertEqual(len(zipf.namelist()), numfiles)
583 numfiles2 = 15
584 for i in range(numfiles, numfiles2):
585 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
586 self.assertEqual(len(zipf.namelist()), numfiles2)
587 zipf.close()
588
589 zipf2 = zipfile.ZipFile(TESTFN, "r", self.compression)
590 self.assertEqual(len(zipf2.namelist()), numfiles2)
591 for i in range(numfiles2):
592 content = zipf2.read("foo%08d" % i).decode('ascii')
593 self.assertEqual(content, "%d" % (i**3 % 57))
594 zipf2.close()
595
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300596 def tearDown(self):
597 zipfile.ZIP64_LIMIT = self._limit
Serhiy Storchaka026a3992014-09-23 22:27:34 +0300598 zipfile.ZIP_FILECOUNT_LIMIT = self._filecount_limit
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300599 unlink(TESTFN)
600 unlink(TESTFN2)
601
602
603class StoredTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
604 unittest.TestCase):
605 compression = zipfile.ZIP_STORED
606
607 def large_file_exception_test(self, f, compression):
Serhiy Storchaka235c5e02013-11-23 15:55:38 +0200608 with zipfile.ZipFile(f, "w", compression, allowZip64=False) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300609 self.assertRaises(zipfile.LargeZipFile,
610 zipfp.write, TESTFN, "another.name")
611
612 def large_file_exception_test2(self, f, compression):
Serhiy Storchaka235c5e02013-11-23 15:55:38 +0200613 with zipfile.ZipFile(f, "w", compression, allowZip64=False) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300614 self.assertRaises(zipfile.LargeZipFile,
615 zipfp.writestr, "another.name", self.data)
616
617 def test_large_file_exception(self):
618 for f in get_files(self):
619 self.large_file_exception_test(f, zipfile.ZIP_STORED)
620 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
621
622 def test_absolute_arcnames(self):
623 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
624 allowZip64=True) as zipfp:
625 zipfp.write(TESTFN, "/absolute")
626
627 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
628 self.assertEqual(zipfp.namelist(), ["absolute"])
629
630@requires_zlib
631class DeflateTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
632 unittest.TestCase):
633 compression = zipfile.ZIP_DEFLATED
634
635@requires_bz2
636class Bzip2TestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
637 unittest.TestCase):
638 compression = zipfile.ZIP_BZIP2
639
640@requires_lzma
641class LzmaTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
642 unittest.TestCase):
643 compression = zipfile.ZIP_LZMA
644
645
646class PyZipFileTests(unittest.TestCase):
647 def assertCompiledIn(self, name, namelist):
648 if name + 'o' not in namelist:
649 self.assertIn(name + 'c', namelist)
650
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200651 def requiresWriteAccess(self, path):
Berker Peksage1efc072015-02-16 04:36:18 +0200652 # effective_ids unavailable on windows
653 if not os.access(path, os.W_OK,
654 effective_ids=os.access in os.supports_effective_ids):
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200655 self.skipTest('requires write access to the installed location')
656
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300657 def test_write_pyfile(self):
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200658 self.requiresWriteAccess(os.path.dirname(__file__))
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300659 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
660 fn = __file__
661 if fn.endswith('.pyc') or fn.endswith('.pyo'):
662 path_split = fn.split(os.sep)
663 if os.altsep is not None:
664 path_split.extend(fn.split(os.altsep))
665 if '__pycache__' in path_split:
Serhiy Storchaka9068e4d2013-07-22 21:02:14 +0300666 fn = importlib.util.source_from_cache(fn)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300667 else:
668 fn = fn[:-1]
669
670 zipfp.writepy(fn)
671
672 bn = os.path.basename(fn)
673 self.assertNotIn(bn, zipfp.namelist())
674 self.assertCompiledIn(bn, zipfp.namelist())
675
676 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
677 fn = __file__
678 if fn.endswith(('.pyc', '.pyo')):
679 fn = fn[:-1]
680
681 zipfp.writepy(fn, "testpackage")
682
683 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
684 self.assertNotIn(bn, zipfp.namelist())
685 self.assertCompiledIn(bn, zipfp.namelist())
686
687 def test_write_python_package(self):
688 import email
689 packagedir = os.path.dirname(email.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200690 self.requiresWriteAccess(packagedir)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300691
692 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
693 zipfp.writepy(packagedir)
694
695 # Check for a couple of modules at different levels of the
696 # hierarchy
697 names = zipfp.namelist()
698 self.assertCompiledIn('email/__init__.py', names)
699 self.assertCompiledIn('email/mime/text.py', names)
700
Christian Tismer59202e52013-10-21 03:59:23 +0200701 def test_write_filtered_python_package(self):
702 import test
703 packagedir = os.path.dirname(test.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200704 self.requiresWriteAccess(packagedir)
Christian Tismer59202e52013-10-21 03:59:23 +0200705
706 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
707
Christian Tismer59202e52013-10-21 03:59:23 +0200708 # first make sure that the test folder gives error messages
Georg Brandla6065422013-10-21 08:29:29 +0200709 # (on the badsyntax_... files)
710 with captured_stdout() as reportSIO:
711 zipfp.writepy(packagedir)
Christian Tismer59202e52013-10-21 03:59:23 +0200712 reportStr = reportSIO.getvalue()
713 self.assertTrue('SyntaxError' in reportStr)
714
Christian Tismer410d9312013-10-22 04:09:28 +0200715 # then check that the filter works on the whole package
Georg Brandla6065422013-10-21 08:29:29 +0200716 with captured_stdout() as reportSIO:
717 zipfp.writepy(packagedir, filterfunc=lambda whatever: False)
Christian Tismer59202e52013-10-21 03:59:23 +0200718 reportStr = reportSIO.getvalue()
719 self.assertTrue('SyntaxError' not in reportStr)
720
Christian Tismer410d9312013-10-22 04:09:28 +0200721 # then check that the filter works on individual files
Larry Hastings7e63b362015-05-08 06:54:58 -0700722 def filter(path):
723 return not os.path.basename(path).startswith("bad")
Serhiy Storchakac46d1fa2014-01-20 21:59:33 +0200724 with captured_stdout() as reportSIO, self.assertWarns(UserWarning):
Larry Hastings7e63b362015-05-08 06:54:58 -0700725 zipfp.writepy(packagedir, filterfunc=filter)
Christian Tismer410d9312013-10-22 04:09:28 +0200726 reportStr = reportSIO.getvalue()
727 if reportStr:
728 print(reportStr)
729 self.assertTrue('SyntaxError' not in reportStr)
730
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300731 def test_write_with_optimization(self):
732 import email
733 packagedir = os.path.dirname(email.__file__)
Serhiy Storchakadb724fe2015-02-14 23:04:35 +0200734 self.requiresWriteAccess(packagedir)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300735 # use .pyc if running test in optimization mode,
736 # use .pyo if running test in debug mode
737 optlevel = 1 if __debug__ else 0
738 ext = '.pyo' if optlevel == 1 else '.pyc'
739
740 with TemporaryFile() as t, \
Christian Tismer59202e52013-10-21 03:59:23 +0200741 zipfile.PyZipFile(t, "w", optimize=optlevel) as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300742 zipfp.writepy(packagedir)
743
744 names = zipfp.namelist()
745 self.assertIn('email/__init__' + ext, names)
746 self.assertIn('email/mime/text' + ext, names)
747
748 def test_write_python_directory(self):
749 os.mkdir(TESTFN2)
750 try:
751 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
752 fp.write("print(42)\n")
753
754 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
755 fp.write("print(42 * 42)\n")
756
757 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
758 fp.write("bla bla bla\n")
759
760 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
761 zipfp.writepy(TESTFN2)
762
763 names = zipfp.namelist()
764 self.assertCompiledIn('mod1.py', names)
765 self.assertCompiledIn('mod2.py', names)
766 self.assertNotIn('mod2.txt', names)
767
768 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200769 rmtree(TESTFN2)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300770
Christian Tismer410d9312013-10-22 04:09:28 +0200771 def test_write_python_directory_filtered(self):
772 os.mkdir(TESTFN2)
773 try:
774 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
775 fp.write("print(42)\n")
776
777 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
778 fp.write("print(42 * 42)\n")
779
780 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
781 zipfp.writepy(TESTFN2, filterfunc=lambda fn:
782 not fn.endswith('mod2.py'))
783
784 names = zipfp.namelist()
785 self.assertCompiledIn('mod1.py', names)
786 self.assertNotIn('mod2.py', names)
787
788 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200789 rmtree(TESTFN2)
Christian Tismer410d9312013-10-22 04:09:28 +0200790
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300791 def test_write_non_pyfile(self):
792 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
793 with open(TESTFN, 'w') as f:
794 f.write('most definitely not a python file')
795 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
Victor Stinner88b215e2014-09-04 00:51:09 +0200796 unlink(TESTFN)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300797
798 def test_write_pyfile_bad_syntax(self):
799 os.mkdir(TESTFN2)
800 try:
801 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
802 fp.write("Bad syntax in python file\n")
803
804 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
805 # syntax errors are printed to stdout
806 with captured_stdout() as s:
807 zipfp.writepy(os.path.join(TESTFN2, "mod1.py"))
808
809 self.assertIn("SyntaxError", s.getvalue())
810
811 # as it will not have compiled the python file, it will
812 # include the .py file not .pyc or .pyo
813 names = zipfp.namelist()
814 self.assertIn('mod1.py', names)
815 self.assertNotIn('mod1.pyc', names)
816 self.assertNotIn('mod1.pyo', names)
817
818 finally:
Victor Stinner57004c62014-09-04 00:49:01 +0200819 rmtree(TESTFN2)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300820
821
822class ExtractTests(unittest.TestCase):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000823 def test_extract(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000824 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
825 for fpath, fdata in SMALL_TEST_DATA:
826 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000827
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000828 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
829 for fpath, fdata in SMALL_TEST_DATA:
830 writtenfile = zipfp.extract(fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000831
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000832 # make sure it was written to the right place
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800833 correctfile = os.path.join(os.getcwd(), fpath)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000834 correctfile = os.path.normpath(correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000835
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000836 self.assertEqual(writtenfile, correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000837
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000838 # make sure correct data is in correct file
Brian Curtin8fb9b862010-11-18 02:15:28 +0000839 with open(writtenfile, "rb") as f:
840 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000841
Victor Stinner88b215e2014-09-04 00:51:09 +0200842 unlink(writtenfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000843
844 # remove the test file subdirectories
Victor Stinner57004c62014-09-04 00:49:01 +0200845 rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
Christian Heimes790c8232008-01-07 21:14:23 +0000846
Ezio Melottiafd0d112009-07-15 17:17:17 +0000847 def test_extract_all(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000848 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
849 for fpath, fdata in SMALL_TEST_DATA:
850 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000851
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000852 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
853 zipfp.extractall()
854 for fpath, fdata in SMALL_TEST_DATA:
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800855 outfile = os.path.join(os.getcwd(), fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000856
Brian Curtin8fb9b862010-11-18 02:15:28 +0000857 with open(outfile, "rb") as f:
858 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000859
Victor Stinner88b215e2014-09-04 00:51:09 +0200860 unlink(outfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000861
862 # remove the test file subdirectories
Victor Stinner57004c62014-09-04 00:49:01 +0200863 rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
Christian Heimes790c8232008-01-07 21:14:23 +0000864
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800865 def check_file(self, filename, content):
866 self.assertTrue(os.path.isfile(filename))
867 with open(filename, 'rb') as f:
868 self.assertEqual(f.read(), content)
869
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800870 def test_sanitize_windows_name(self):
871 san = zipfile.ZipFile._sanitize_windows_name
872 # Passing pathsep in allows this test to work regardless of platform.
873 self.assertEqual(san(r',,?,C:,foo,bar/z', ','), r'_,C_,foo,bar/z')
874 self.assertEqual(san(r'a\b,c<d>e|f"g?h*i', ','), r'a\b,c_d_e_f_g_h_i')
875 self.assertEqual(san('../../foo../../ba..r', '/'), r'foo/ba..r')
876
877 def test_extract_hackers_arcnames_common_cases(self):
878 common_hacknames = [
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800879 ('../foo/bar', 'foo/bar'),
880 ('foo/../bar', 'foo/bar'),
881 ('foo/../../bar', 'foo/bar'),
882 ('foo/bar/..', 'foo/bar'),
883 ('./../foo/bar', 'foo/bar'),
884 ('/foo/bar', 'foo/bar'),
885 ('/foo/../bar', 'foo/bar'),
886 ('/foo/../../bar', 'foo/bar'),
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800887 ]
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800888 self._test_extract_hackers_arcnames(common_hacknames)
889
890 @unittest.skipIf(os.path.sep != '\\', 'Requires \\ as path separator.')
891 def test_extract_hackers_arcnames_windows_only(self):
892 """Test combination of path fixing and windows name sanitization."""
893 windows_hacknames = [
Christian Tismer59202e52013-10-21 03:59:23 +0200894 (r'..\foo\bar', 'foo/bar'),
895 (r'..\/foo\/bar', 'foo/bar'),
896 (r'foo/\..\/bar', 'foo/bar'),
897 (r'foo\/../\bar', 'foo/bar'),
898 (r'C:foo/bar', 'foo/bar'),
899 (r'C:/foo/bar', 'foo/bar'),
900 (r'C://foo/bar', 'foo/bar'),
901 (r'C:\foo\bar', 'foo/bar'),
902 (r'//conky/mountpoint/foo/bar', 'foo/bar'),
903 (r'\\conky\mountpoint\foo\bar', 'foo/bar'),
904 (r'///conky/mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
905 (r'\\\conky\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
906 (r'//conky//mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
907 (r'\\conky\\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
908 (r'//?/C:/foo/bar', 'foo/bar'),
909 (r'\\?\C:\foo\bar', 'foo/bar'),
910 (r'C:/../C:/foo/bar', 'C_/foo/bar'),
911 (r'a:b\c<d>e|f"g?h*i', 'b/c_d_e_f_g_h_i'),
912 ('../../foo../../ba..r', 'foo/ba..r'),
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800913 ]
914 self._test_extract_hackers_arcnames(windows_hacknames)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800915
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800916 @unittest.skipIf(os.path.sep != '/', r'Requires / as path separator.')
917 def test_extract_hackers_arcnames_posix_only(self):
918 posix_hacknames = [
919 ('//foo/bar', 'foo/bar'),
920 ('../../foo../../ba..r', 'foo../ba..r'),
921 (r'foo/..\bar', r'foo/..\bar'),
922 ]
923 self._test_extract_hackers_arcnames(posix_hacknames)
924
925 def _test_extract_hackers_arcnames(self, hacknames):
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800926 for arcname, fixedname in hacknames:
927 content = b'foobar' + arcname.encode()
928 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipfp:
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200929 zinfo = zipfile.ZipInfo()
930 # preserve backslashes
931 zinfo.filename = arcname
932 zinfo.external_attr = 0o600 << 16
933 zipfp.writestr(zinfo, content)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800934
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200935 arcname = arcname.replace(os.sep, "/")
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800936 targetpath = os.path.join('target', 'subdir', 'subsub')
937 correctfile = os.path.join(targetpath, *fixedname.split('/'))
938
939 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
940 writtenfile = zipfp.extract(arcname, targetpath)
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200941 self.assertEqual(writtenfile, correctfile,
Gregory P. Smith09aa7522013-02-03 00:36:32 -0800942 msg='extract %r: %r != %r' %
943 (arcname, writtenfile, correctfile))
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800944 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +0200945 rmtree('target')
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800946
947 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
948 zipfp.extractall(targetpath)
949 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +0200950 rmtree('target')
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800951
952 correctfile = os.path.join(os.getcwd(), *fixedname.split('/'))
953
954 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
955 writtenfile = zipfp.extract(arcname)
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200956 self.assertEqual(writtenfile, correctfile,
957 msg="extract %r" % arcname)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800958 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +0200959 rmtree(fixedname.split('/')[0])
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800960
961 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
962 zipfp.extractall()
963 self.check_file(correctfile, content)
Victor Stinner57004c62014-09-04 00:49:01 +0200964 rmtree(fixedname.split('/')[0])
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800965
Victor Stinner88b215e2014-09-04 00:51:09 +0200966 unlink(TESTFN2)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800967
Ronald Oussorenee5c8852010-02-07 20:24:02 +0000968
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300969class OtherTests(unittest.TestCase):
970 def test_open_via_zip_info(self):
971 # Create the ZIP archive
972 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
973 zipfp.writestr("name", "foo")
Serhiy Storchaka9b7a1a12014-01-20 21:57:40 +0200974 with self.assertWarns(UserWarning):
975 zipfp.writestr("name", "bar")
976 self.assertEqual(zipfp.namelist(), ["name"] * 2)
Ronald Oussorenee5c8852010-02-07 20:24:02 +0000977
Serhiy Storchakafa6bc292013-07-22 21:00:11 +0300978 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
979 infos = zipfp.infolist()
980 data = b""
981 for info in infos:
982 with zipfp.open(info) as zipopen:
983 data += zipopen.read()
984 self.assertIn(data, {b"foobar", b"barfoo"})
985 data = b""
986 for info in infos:
987 data += zipfp.read(info)
988 self.assertIn(data, {b"foobar", b"barfoo"})
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200989
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +0200990 def test_universal_deprecation(self):
991 f = io.BytesIO()
992 with zipfile.ZipFile(f, "w") as zipfp:
993 zipfp.writestr('spam.txt', b'ababagalamaga')
994
995 with zipfile.ZipFile(f, "r") as zipfp:
996 for mode in 'U', 'rU':
997 with self.assertWarns(DeprecationWarning):
998 zipopen = zipfp.open('spam.txt', mode)
999 zipopen.close()
1000
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001001 def test_universal_readaheads(self):
1002 f = io.BytesIO()
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001003
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001004 data = b'a\r\n' * 16 * 1024
1005 with zipfile.ZipFile(f, 'w', zipfile.ZIP_STORED) as zipfp:
1006 zipfp.writestr(TESTFN, data)
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +00001007
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001008 data2 = b''
1009 with zipfile.ZipFile(f, 'r') as zipfp, \
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02001010 openU(zipfp, TESTFN) as zipopen:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001011 for line in zipopen:
1012 data2 += line
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +00001013
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001014 self.assertEqual(data, data2.replace(b'\n', b'\r\n'))
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +00001015
Gregory P. Smithb0d9ca922009-07-07 05:06:04 +00001016 def test_writestr_extended_local_header_issue1202(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001017 with zipfile.ZipFile(TESTFN2, 'w') as orig_zip:
1018 for data in 'abcdefghijklmnop':
1019 zinfo = zipfile.ZipInfo(data)
1020 zinfo.flag_bits |= 0x08 # Include an extended local header.
1021 orig_zip.writestr(zinfo, data)
1022
1023 def test_close(self):
1024 """Check that the zipfile is closed after the 'with' block."""
1025 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
1026 for fpath, fdata in SMALL_TEST_DATA:
1027 zipfp.writestr(fpath, fdata)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001028 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
1029 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001030
1031 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001032 self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
1033 self.assertIsNone(zipfp.fp, 'zipfp is not closed')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001034
1035 def test_close_on_exception(self):
1036 """Check that the zipfile is closed if an exception is raised in the
1037 'with' block."""
1038 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
1039 for fpath, fdata in SMALL_TEST_DATA:
1040 zipfp.writestr(fpath, fdata)
1041
1042 try:
1043 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
Georg Brandl4d540882010-10-28 06:42:33 +00001044 raise zipfile.BadZipFile()
1045 except zipfile.BadZipFile:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001046 self.assertIsNone(zipfp2.fp, 'zipfp is not closed')
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001047
Martin v. Löwisd099b562012-05-01 14:08:22 +02001048 def test_unsupported_version(self):
1049 # File has an extract_version of 120
1050 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 +02001051 b'\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00xPK\x01\x02x\x03x\x00\x00\x00\x00'
1052 b'\x00!p\xa1@\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00'
1053 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00\x00xPK\x05\x06'
1054 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 +03001055
Martin v. Löwisd099b562012-05-01 14:08:22 +02001056 self.assertRaises(NotImplementedError, zipfile.ZipFile,
1057 io.BytesIO(data), 'r')
1058
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001059 @requires_zlib
1060 def test_read_unicode_filenames(self):
1061 # bug #10801
1062 fname = findfile('zip_cp437_header.zip')
1063 with zipfile.ZipFile(fname) as zipfp:
1064 for name in zipfp.namelist():
1065 zipfp.open(name).close()
1066
1067 def test_write_unicode_filenames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001068 with zipfile.ZipFile(TESTFN, "w") as zf:
1069 zf.writestr("foo.txt", "Test for unicode filename")
1070 zf.writestr("\xf6.txt", "Test for unicode filename")
Ezio Melottie9615932010-01-24 19:26:24 +00001071 self.assertIsInstance(zf.infolist()[0].filename, str)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001072
1073 with zipfile.ZipFile(TESTFN, "r") as zf:
1074 self.assertEqual(zf.filelist[0].filename, "foo.txt")
1075 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
Martin v. Löwis8570f6a2008-05-05 17:44:38 +00001076
Ezio Melottiafd0d112009-07-15 17:17:17 +00001077 def test_create_non_existent_file_for_append(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001078 if os.path.exists(TESTFN):
1079 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001080
Thomas Wouterscf297e42007-02-23 15:07:44 +00001081 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001082 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +00001083
Thomas Wouterscf297e42007-02-23 15:07:44 +00001084 try:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001085 with zipfile.ZipFile(TESTFN, 'a') as zf:
1086 zf.writestr(filename, content)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001087 except OSError:
Thomas Wouterscf297e42007-02-23 15:07:44 +00001088 self.fail('Could not append data to a non-existent zip file.')
1089
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001090 self.assertTrue(os.path.exists(TESTFN))
Thomas Wouterscf297e42007-02-23 15:07:44 +00001091
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001092 with zipfile.ZipFile(TESTFN, 'r') as zf:
1093 self.assertEqual(zf.read(filename), content)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001094
Ezio Melottiafd0d112009-07-15 17:17:17 +00001095 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001096 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti35386712009-12-31 13:22:41 +00001097 # it opens if there's an error in the file. If it doesn't, the
1098 # traceback holds a reference to the ZipFile object and, indirectly,
1099 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001100 # On Windows, this causes the os.unlink() call to fail because the
1101 # underlying file is still open. This is SF bug #412214.
1102 #
Ezio Melotti35386712009-12-31 13:22:41 +00001103 with open(TESTFN, "w") as fp:
1104 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001105 try:
1106 zf = zipfile.ZipFile(TESTFN)
Georg Brandl4d540882010-10-28 06:42:33 +00001107 except zipfile.BadZipFile:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001108 pass
1109
Ezio Melottiafd0d112009-07-15 17:17:17 +00001110 def test_is_zip_erroneous_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001111 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001112 # - passing a filename
1113 with open(TESTFN, "w") as fp:
1114 fp.write("this is not a legal zip file\n")
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001115 self.assertFalse(zipfile.is_zipfile(TESTFN))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001116 # - passing a file object
1117 with open(TESTFN, "rb") as fp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001118 self.assertFalse(zipfile.is_zipfile(fp))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001119 # - passing a file-like object
1120 fp = io.BytesIO()
1121 fp.write(b"this is not a legal zip file\n")
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001122 self.assertFalse(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001123 fp.seek(0, 0)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001124 self.assertFalse(zipfile.is_zipfile(fp))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001125
Serhiy Storchakad2b15272013-01-31 15:27:07 +02001126 def test_damaged_zipfile(self):
1127 """Check that zipfiles with missing bytes at the end raise BadZipFile."""
1128 # - Create a valid zip file
1129 fp = io.BytesIO()
1130 with zipfile.ZipFile(fp, mode="w") as zipf:
1131 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
1132 zipfiledata = fp.getvalue()
1133
1134 # - Now create copies of it missing the last N bytes and make sure
1135 # a BadZipFile exception is raised when we try to open it
1136 for N in range(len(zipfiledata)):
1137 fp = io.BytesIO(zipfiledata[:N])
1138 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, fp)
1139
Ezio Melottiafd0d112009-07-15 17:17:17 +00001140 def test_is_zip_valid_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001141 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001142 # - passing a filename
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001143 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1144 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
1145
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001146 self.assertTrue(zipfile.is_zipfile(TESTFN))
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001147 # - passing a file object
1148 with open(TESTFN, "rb") as fp:
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001149 self.assertTrue(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001150 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001151 zip_contents = fp.read()
1152 # - passing a file-like object
1153 fp = io.BytesIO()
1154 fp.write(zip_contents)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001155 self.assertTrue(zipfile.is_zipfile(fp))
Ezio Melotti35386712009-12-31 13:22:41 +00001156 fp.seek(0, 0)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001157 self.assertTrue(zipfile.is_zipfile(fp))
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001158
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001159 def test_non_existent_file_raises_OSError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001160 # make sure we don't raise an AttributeError when a partially-constructed
1161 # ZipFile instance is finalized; this tests for regression on SF tracker
1162 # bug #403871.
1163
1164 # The bug we're testing for caused an AttributeError to be raised
1165 # when a ZipFile instance was created for a file that did not
1166 # exist; the .fp member was not initialized but was needed by the
1167 # __del__() method. Since the AttributeError is in the __del__(),
1168 # it is ignored, but the user should be sufficiently annoyed by
1169 # the message on the output that regression will be noticed
1170 # quickly.
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001171 self.assertRaises(OSError, zipfile.ZipFile, TESTFN)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001172
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001173 def test_empty_file_raises_BadZipFile(self):
1174 f = open(TESTFN, 'w')
1175 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001176 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001177
Ezio Melotti35386712009-12-31 13:22:41 +00001178 with open(TESTFN, 'w') as fp:
1179 fp.write("short file")
Georg Brandl4d540882010-10-28 06:42:33 +00001180 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001181
Ezio Melottiafd0d112009-07-15 17:17:17 +00001182 def test_closed_zip_raises_RuntimeError(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001183 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001184 data = io.BytesIO()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001185 with zipfile.ZipFile(data, mode="w") as zipf:
1186 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001187
Andrew Svetlov737fb892012-12-18 21:14:22 +02001188 # This is correct; calling .read on a closed ZipFile should raise
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001189 # a RuntimeError, and so should calling .testzip. An earlier
1190 # version of .testzip would swallow this exception (and any other)
1191 # and report that the first file in the archive was corrupt.
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001192 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
1193 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001194 self.assertRaises(RuntimeError, zipf.testzip)
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001195 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Brian Curtin8fb9b862010-11-18 02:15:28 +00001196 with open(TESTFN, 'w') as f:
1197 f.write('zipfile test data')
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001198 self.assertRaises(RuntimeError, zipf.write, TESTFN)
1199
Ezio Melottiafd0d112009-07-15 17:17:17 +00001200 def test_bad_constructor_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001201 """Check that bad modes passed to ZipFile constructor are caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001202 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
1203
Ezio Melottiafd0d112009-07-15 17:17:17 +00001204 def test_bad_open_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001205 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001206 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1207 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1208
1209 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001210 # read the data to make sure the file is there
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001211 zipf.read("foo.txt")
1212 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001213
Ezio Melottiafd0d112009-07-15 17:17:17 +00001214 def test_read0(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001215 """Check that calling read(0) on a ZipExtFile object returns an empty
1216 string and doesn't advance file pointer."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001217 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1218 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1219 # read the data to make sure the file is there
Brian Curtin8fb9b862010-11-18 02:15:28 +00001220 with zipf.open("foo.txt") as f:
1221 for i in range(FIXEDTEST_SIZE):
1222 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001223
Brian Curtin8fb9b862010-11-18 02:15:28 +00001224 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001225
Ezio Melottiafd0d112009-07-15 17:17:17 +00001226 def test_open_non_existent_item(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001227 """Check that attempting to call open() for an item that doesn't
1228 exist in the archive raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001229 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1230 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001231
Ezio Melottiafd0d112009-07-15 17:17:17 +00001232 def test_bad_compression_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001233 """Check that bad compression methods passed to ZipFile.open are
1234 caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001235 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
1236
Martin v. Löwisb3260f02012-05-01 08:38:01 +02001237 def test_unsupported_compression(self):
1238 # data is declared as shrunk, but actually deflated
1239 data = (b'PK\x03\x04.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00'
Christian Tismer59202e52013-10-21 03:59:23 +02001240 b'\x00\x02\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00x\x03\x00PK\x01'
1241 b'\x02.\x03.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00\x00\x02\x00\x00'
1242 b'\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
1243 b'\x80\x01\x00\x00\x00\x00xPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00'
1244 b'/\x00\x00\x00!\x00\x00\x00\x00\x00')
Martin v. Löwisb3260f02012-05-01 08:38:01 +02001245 with zipfile.ZipFile(io.BytesIO(data), 'r') as zipf:
1246 self.assertRaises(NotImplementedError, zipf.open, 'x')
1247
Ezio Melottiafd0d112009-07-15 17:17:17 +00001248 def test_null_byte_in_filename(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001249 """Check that a filename containing a null byte is properly
1250 terminated."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001251 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1252 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
1253 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001254
Ezio Melottiafd0d112009-07-15 17:17:17 +00001255 def test_struct_sizes(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001256 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001257 self.assertEqual(zipfile.sizeEndCentDir, 22)
1258 self.assertEqual(zipfile.sizeCentralDir, 46)
1259 self.assertEqual(zipfile.sizeEndCentDir64, 56)
1260 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
1261
Ezio Melottiafd0d112009-07-15 17:17:17 +00001262 def test_comments(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001263 """Check that comments on the archive are handled properly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001264
1265 # check default comment is empty
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001266 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1267 self.assertEqual(zipf.comment, b'')
1268 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1269
1270 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1271 self.assertEqual(zipfr.comment, b'')
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001272
1273 # check a simple short comment
1274 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001275 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1276 zipf.comment = comment
1277 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1278 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1279 self.assertEqual(zipf.comment, comment)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001280
1281 # check a comment of max length
1282 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
1283 comment2 = comment2.encode("ascii")
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001284 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1285 zipf.comment = comment2
1286 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1287
1288 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1289 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001290
1291 # check a comment that is too long is truncated
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001292 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
Serhiy Storchaka9b7a1a12014-01-20 21:57:40 +02001293 with self.assertWarns(UserWarning):
1294 zipf.comment = comment2 + b'oops'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001295 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1296 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1297 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001298
Antoine Pitrouc3991852012-06-30 17:31:37 +02001299 # check that comments are correctly modified in append mode
1300 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1301 zipf.comment = b"original comment"
1302 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1303 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1304 zipf.comment = b"an updated comment"
1305 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1306 self.assertEqual(zipf.comment, b"an updated comment")
1307
1308 # check that comments are correctly shortened in append mode
1309 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1310 zipf.comment = b"original comment that's longer"
1311 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1312 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1313 zipf.comment = b"shorter comment"
1314 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1315 self.assertEqual(zipf.comment, b"shorter comment")
1316
R David Murrayf50b38a2012-04-12 18:44:58 -04001317 def test_unicode_comment(self):
1318 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1319 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1320 with self.assertRaises(TypeError):
1321 zipf.comment = "this is an error"
1322
1323 def test_change_comment_in_empty_archive(self):
1324 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1325 self.assertFalse(zipf.filelist)
1326 zipf.comment = b"this is a comment"
1327 with zipfile.ZipFile(TESTFN, "r") as zipf:
1328 self.assertEqual(zipf.comment, b"this is a comment")
1329
1330 def test_change_comment_in_nonempty_archive(self):
1331 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1332 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1333 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1334 self.assertTrue(zipf.filelist)
1335 zipf.comment = b"this is a comment"
1336 with zipfile.ZipFile(TESTFN, "r") as zipf:
1337 self.assertEqual(zipf.comment, b"this is a comment")
1338
Georg Brandl268e4d42010-10-14 06:59:45 +00001339 def test_empty_zipfile(self):
1340 # Check that creating a file in 'w' or 'a' mode and closing without
1341 # adding any files to the archives creates a valid empty ZIP file
1342 zipf = zipfile.ZipFile(TESTFN, mode="w")
1343 zipf.close()
1344 try:
1345 zipf = zipfile.ZipFile(TESTFN, mode="r")
1346 except zipfile.BadZipFile:
1347 self.fail("Unable to create empty ZIP file in 'w' mode")
1348
1349 zipf = zipfile.ZipFile(TESTFN, mode="a")
1350 zipf.close()
1351 try:
1352 zipf = zipfile.ZipFile(TESTFN, mode="r")
1353 except:
1354 self.fail("Unable to create empty ZIP file in 'a' mode")
1355
1356 def test_open_empty_file(self):
1357 # Issue 1710703: Check that opening a file with less than 22 bytes
Georg Brandl4d540882010-10-28 06:42:33 +00001358 # raises a BadZipFile exception (rather than the previously unhelpful
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001359 # OSError)
Georg Brandl268e4d42010-10-14 06:59:45 +00001360 f = open(TESTFN, 'w')
1361 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001362 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN, 'r')
Georg Brandl268e4d42010-10-14 06:59:45 +00001363
Senthil Kumaran29fa9d42011-10-20 01:46:00 +08001364 def test_create_zipinfo_before_1980(self):
1365 self.assertRaises(ValueError,
1366 zipfile.ZipInfo, 'seventies', (1979, 1, 1, 0, 0, 0))
1367
Gregory P. Smith0af8a862014-05-29 23:42:14 -07001368 def test_zipfile_with_short_extra_field(self):
1369 """If an extra field in the header is less than 4 bytes, skip it."""
1370 zipdata = (
1371 b'PK\x03\x04\x14\x00\x00\x00\x00\x00\x93\x9b\xad@\x8b\x9e'
1372 b'\xd9\xd3\x01\x00\x00\x00\x01\x00\x00\x00\x03\x00\x03\x00ab'
1373 b'c\x00\x00\x00APK\x01\x02\x14\x03\x14\x00\x00\x00\x00'
1374 b'\x00\x93\x9b\xad@\x8b\x9e\xd9\xd3\x01\x00\x00\x00\x01\x00\x00'
1375 b'\x00\x03\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00'
1376 b'\x00\x00\x00abc\x00\x00PK\x05\x06\x00\x00\x00\x00'
1377 b'\x01\x00\x01\x003\x00\x00\x00%\x00\x00\x00\x00\x00'
1378 )
1379 with zipfile.ZipFile(io.BytesIO(zipdata), 'r') as zipf:
1380 # testzip returns the name of the first corrupt file, or None
1381 self.assertIsNone(zipf.testzip())
1382
Guido van Rossumd8faa362007-04-27 19:54:29 +00001383 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001384 unlink(TESTFN)
1385 unlink(TESTFN2)
1386
Thomas Wouterscf297e42007-02-23 15:07:44 +00001387
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001388class AbstractBadCrcTests:
1389 def test_testzip_with_bad_crc(self):
1390 """Tests that files with bad CRCs return their name from testzip."""
1391 zipdata = self.zip_with_bad_crc
1392
1393 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1394 # testzip returns the name of the first corrupt file, or None
1395 self.assertEqual('afile', zipf.testzip())
1396
1397 def test_read_with_bad_crc(self):
1398 """Tests that files with bad CRCs raise a BadZipFile exception when read."""
1399 zipdata = self.zip_with_bad_crc
1400
1401 # Using ZipFile.read()
1402 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1403 self.assertRaises(zipfile.BadZipFile, zipf.read, 'afile')
1404
1405 # Using ZipExtFile.read()
1406 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1407 with zipf.open('afile', 'r') as corrupt_file:
1408 self.assertRaises(zipfile.BadZipFile, corrupt_file.read)
1409
1410 # Same with small reads (in order to exercise the buffering logic)
1411 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1412 with zipf.open('afile', 'r') as corrupt_file:
1413 corrupt_file.MIN_READ_SIZE = 2
1414 with self.assertRaises(zipfile.BadZipFile):
1415 while corrupt_file.read(2):
1416 pass
1417
1418
1419class StoredBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1420 compression = zipfile.ZIP_STORED
1421 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001422 b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
1423 b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
1424 b'ilehello,AworldP'
1425 b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
1426 b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
1427 b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
1428 b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
1429 b'\0\0/\0\0\0\0\0')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001430
1431@requires_zlib
1432class DeflateBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1433 compression = zipfile.ZIP_DEFLATED
1434 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001435 b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
1436 b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1437 b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
1438 b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
1439 b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
1440 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
1441 b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
1442 b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001443
1444@requires_bz2
1445class Bzip2BadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1446 compression = zipfile.ZIP_BZIP2
1447 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001448 b'PK\x03\x04\x14\x03\x00\x00\x0c\x00nu\x0c=FA'
1449 b'KE8\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1450 b'ileBZh91AY&SY\xd4\xa8\xca'
1451 b'\x7f\x00\x00\x0f\x11\x80@\x00\x06D\x90\x80 \x00 \xa5'
1452 b'P\xd9!\x03\x03\x13\x13\x13\x89\xa9\xa9\xc2u5:\x9f'
1453 b'\x8b\xb9"\x9c(HjTe?\x80PK\x01\x02\x14'
1454 b'\x03\x14\x03\x00\x00\x0c\x00nu\x0c=FAKE8'
1455 b'\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\x00'
1456 b'\x00 \x80\x80\x81\x00\x00\x00\x00afilePK'
1457 b'\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00\x00[\x00'
1458 b'\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001459
1460@requires_lzma
1461class LzmaBadCrcTests(AbstractBadCrcTests, unittest.TestCase):
1462 compression = zipfile.ZIP_LZMA
1463 zip_with_bad_crc = (
Christian Tismer59202e52013-10-21 03:59:23 +02001464 b'PK\x03\x04\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
1465 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
1466 b'ile\t\x04\x05\x00]\x00\x00\x00\x04\x004\x19I'
1467 b'\xee\x8d\xe9\x17\x89:3`\tq!.8\x00PK'
1468 b'\x01\x02\x14\x03\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
1469 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00'
1470 b'\x00\x00\x00\x00 \x80\x80\x81\x00\x00\x00\x00afil'
1471 b'ePK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00'
1472 b'\x00>\x00\x00\x00\x00\x00')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001473
1474
Thomas Wouterscf297e42007-02-23 15:07:44 +00001475class DecryptionTests(unittest.TestCase):
Ezio Melotti35386712009-12-31 13:22:41 +00001476 """Check that ZIP decryption works. Since the library does not
1477 support encryption at the moment, we use a pre-generated encrypted
1478 ZIP file."""
Thomas Wouterscf297e42007-02-23 15:07:44 +00001479
1480 data = (
Christian Tismer59202e52013-10-21 03:59:23 +02001481 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
1482 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
1483 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
1484 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
1485 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
1486 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
1487 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +00001488 data2 = (
Christian Tismer59202e52013-10-21 03:59:23 +02001489 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
1490 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
1491 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
1492 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
1493 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
1494 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
1495 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
1496 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +00001497
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001498 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +00001499 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +00001500
1501 def setUp(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001502 with open(TESTFN, "wb") as fp:
1503 fp.write(self.data)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001504 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti35386712009-12-31 13:22:41 +00001505 with open(TESTFN2, "wb") as fp:
1506 fp.write(self.data2)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001507 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001508
1509 def tearDown(self):
1510 self.zip.close()
1511 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001512 self.zip2.close()
1513 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001514
Ezio Melottiafd0d112009-07-15 17:17:17 +00001515 def test_no_password(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001516 # Reading the encrypted file without password
1517 # must generate a RunTime exception
1518 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001519 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001520
Ezio Melottiafd0d112009-07-15 17:17:17 +00001521 def test_bad_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001522 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001523 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001524 self.zip2.setpassword(b"perl")
1525 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001526
Ezio Melotti975077a2011-05-19 22:03:22 +03001527 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +00001528 def test_good_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001529 self.zip.setpassword(b"python")
Ezio Melotti35386712009-12-31 13:22:41 +00001530 self.assertEqual(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001531 self.zip2.setpassword(b"12345")
Ezio Melotti35386712009-12-31 13:22:41 +00001532 self.assertEqual(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001533
R. David Murray8d855d82010-12-21 21:53:37 +00001534 def test_unicode_password(self):
1535 self.assertRaises(TypeError, self.zip.setpassword, "unicode")
1536 self.assertRaises(TypeError, self.zip.read, "test.txt", "python")
1537 self.assertRaises(TypeError, self.zip.open, "test.txt", pwd="python")
1538 self.assertRaises(TypeError, self.zip.extract, "test.txt", pwd="python")
1539
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001540class AbstractTestsWithRandomBinaryFiles:
1541 @classmethod
1542 def setUpClass(cls):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001543 datacount = randint(16, 64)*1024 + randint(1, 1024)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001544 cls.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
1545 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001546
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001547 def setUp(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001548 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +00001549 with open(TESTFN, "wb") as fp:
1550 fp.write(self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001551
1552 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001553 unlink(TESTFN)
1554 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001555
Ezio Melottiafd0d112009-07-15 17:17:17 +00001556 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001557 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001558 with zipfile.ZipFile(f, "w", compression) as zipfp:
1559 zipfp.write(TESTFN, "another.name")
1560 zipfp.write(TESTFN, TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001561
Ezio Melottiafd0d112009-07-15 17:17:17 +00001562 def zip_test(self, f, compression):
1563 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001564
1565 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001566 with zipfile.ZipFile(f, "r", compression) as zipfp:
1567 testdata = zipfp.read(TESTFN)
1568 self.assertEqual(len(testdata), len(self.data))
1569 self.assertEqual(testdata, self.data)
1570 self.assertEqual(zipfp.read("another.name"), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001571
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001572 def test_read(self):
1573 for f in get_files(self):
1574 self.zip_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001575
Ezio Melottiafd0d112009-07-15 17:17:17 +00001576 def zip_open_test(self, f, compression):
1577 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001578
1579 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001580 with zipfile.ZipFile(f, "r", compression) as zipfp:
1581 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001582 with zipfp.open(TESTFN) as zipopen1:
1583 while True:
1584 read_data = zipopen1.read(256)
1585 if not read_data:
1586 break
1587 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001588
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001589 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001590 with zipfp.open("another.name") as zipopen2:
1591 while True:
1592 read_data = zipopen2.read(256)
1593 if not read_data:
1594 break
1595 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001596
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001597 testdata1 = b''.join(zipdata1)
1598 self.assertEqual(len(testdata1), len(self.data))
1599 self.assertEqual(testdata1, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001600
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001601 testdata2 = b''.join(zipdata2)
Ezio Melotti35386712009-12-31 13:22:41 +00001602 self.assertEqual(len(testdata2), len(self.data))
1603 self.assertEqual(testdata2, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001604
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001605 def test_open(self):
1606 for f in get_files(self):
1607 self.zip_open_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001608
Ezio Melottiafd0d112009-07-15 17:17:17 +00001609 def zip_random_open_test(self, f, compression):
1610 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001611
1612 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001613 with zipfile.ZipFile(f, "r", compression) as zipfp:
1614 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001615 with zipfp.open(TESTFN) as zipopen1:
1616 while True:
1617 read_data = zipopen1.read(randint(1, 1024))
1618 if not read_data:
1619 break
1620 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001621
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001622 testdata = b''.join(zipdata1)
1623 self.assertEqual(len(testdata), len(self.data))
1624 self.assertEqual(testdata, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001625
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001626 def test_random_open(self):
1627 for f in get_files(self):
1628 self.zip_random_open_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001629
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001630
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001631class StoredTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1632 unittest.TestCase):
1633 compression = zipfile.ZIP_STORED
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001634
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001635@requires_zlib
1636class DeflateTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1637 unittest.TestCase):
1638 compression = zipfile.ZIP_DEFLATED
1639
1640@requires_bz2
1641class Bzip2TestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1642 unittest.TestCase):
1643 compression = zipfile.ZIP_BZIP2
1644
1645@requires_lzma
1646class LzmaTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
1647 unittest.TestCase):
1648 compression = zipfile.ZIP_LZMA
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001649
Ezio Melotti76430242009-07-11 18:28:48 +00001650
Ezio Melotti975077a2011-05-19 22:03:22 +03001651@requires_zlib
Guido van Rossumd8faa362007-04-27 19:54:29 +00001652class TestsWithMultipleOpens(unittest.TestCase):
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001653 @classmethod
1654 def setUpClass(cls):
1655 cls.data1 = b'111' + getrandbytes(10000)
1656 cls.data2 = b'222' + getrandbytes(10000)
1657
1658 def make_test_archive(self, f):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001659 # Create the ZIP archive
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001660 with zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as zipfp:
1661 zipfp.writestr('ones', self.data1)
1662 zipfp.writestr('twos', self.data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001663
Ezio Melottiafd0d112009-07-15 17:17:17 +00001664 def test_same_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001665 # Verify that (when the ZipFile is in control of creating file objects)
1666 # multiple open() calls can be made without interfering with each other.
Serhiy Storchakab76bcc42015-01-26 13:45:39 +02001667 self.make_test_archive(TESTFN2)
1668 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
1669 with zipf.open('ones') as zopen1, zipf.open('ones') as zopen2:
1670 data1 = zopen1.read(500)
1671 data2 = zopen2.read(500)
1672 data1 += zopen1.read()
1673 data2 += zopen2.read()
1674 self.assertEqual(data1, data2)
1675 self.assertEqual(data1, self.data1)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001676
Ezio Melottiafd0d112009-07-15 17:17:17 +00001677 def test_different_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001678 # Verify that (when the ZipFile is in control of creating file objects)
1679 # multiple open() calls can be made without interfering with each other.
Serhiy Storchakab76bcc42015-01-26 13:45:39 +02001680 self.make_test_archive(TESTFN2)
1681 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
1682 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001683 data1 = zopen1.read(500)
1684 data2 = zopen2.read(500)
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001685 data1 += zopen1.read()
1686 data2 += zopen2.read()
1687 self.assertEqual(data1, self.data1)
1688 self.assertEqual(data2, self.data2)
1689
Serhiy Storchakab76bcc42015-01-26 13:45:39 +02001690 def test_interleaved(self):
1691 # Verify that (when the ZipFile is in control of creating file objects)
1692 # multiple open() calls can be made without interfering with each other.
1693 self.make_test_archive(TESTFN2)
1694 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
1695 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1696 data1 = zopen1.read(500)
1697 data2 = zopen2.read(500)
1698 data1 += zopen1.read()
1699 data2 += zopen2.read()
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001700 self.assertEqual(data1, self.data1)
1701 self.assertEqual(data2, self.data2)
1702
Serhiy Storchakab76bcc42015-01-26 13:45:39 +02001703 def test_read_after_close(self):
1704 self.make_test_archive(TESTFN2)
1705 with contextlib.ExitStack() as stack:
1706 with zipfile.ZipFile(TESTFN2, 'r') as zipf:
1707 zopen1 = stack.enter_context(zipf.open('ones'))
1708 zopen2 = stack.enter_context(zipf.open('twos'))
1709 data1 = zopen1.read(500)
1710 data2 = zopen2.read(500)
1711 data1 += zopen1.read()
1712 data2 += zopen2.read()
1713 self.assertEqual(data1, self.data1)
1714 self.assertEqual(data2, self.data2)
1715
1716 def test_read_after_write(self):
1717 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_DEFLATED) as zipf:
1718 zipf.writestr('ones', self.data1)
1719 zipf.writestr('twos', self.data2)
1720 with zipf.open('ones') as zopen1:
1721 data1 = zopen1.read(500)
1722 self.assertEqual(data1, self.data1[:500])
1723 with zipfile.ZipFile(TESTFN2, 'r') as zipf:
1724 data1 = zipf.read('ones')
1725 data2 = zipf.read('twos')
1726 self.assertEqual(data1, self.data1)
1727 self.assertEqual(data2, self.data2)
1728
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001729 def test_write_after_read(self):
Serhiy Storchakab76bcc42015-01-26 13:45:39 +02001730 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipf:
1731 zipf.writestr('ones', self.data1)
1732 with zipf.open('ones') as zopen1:
1733 zopen1.read(500)
1734 zipf.writestr('twos', self.data2)
1735 with zipfile.ZipFile(TESTFN2, 'r') as zipf:
1736 data1 = zipf.read('ones')
1737 data2 = zipf.read('twos')
1738 self.assertEqual(data1, self.data1)
1739 self.assertEqual(data2, self.data2)
Serhiy Storchaka1ad088f2014-12-03 09:11:57 +02001740
1741 def test_many_opens(self):
1742 # Verify that read() and open() promptly close the file descriptor,
1743 # and don't rely on the garbage collector to free resources.
1744 self.make_test_archive(TESTFN2)
1745 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
1746 for x in range(100):
1747 zipf.read('ones')
1748 with zipf.open('ones') as zopen1:
1749 pass
1750 with open(os.devnull) as f:
1751 self.assertLess(f.fileno(), 100)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001752
1753 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001754 unlink(TESTFN2)
1755
Guido van Rossumd8faa362007-04-27 19:54:29 +00001756
Martin v. Löwis59e47792009-01-24 14:10:07 +00001757class TestWithDirectory(unittest.TestCase):
1758 def setUp(self):
1759 os.mkdir(TESTFN2)
1760
Ezio Melottiafd0d112009-07-15 17:17:17 +00001761 def test_extract_dir(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001762 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
1763 zipf.extractall(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001764 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1765 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1766 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1767
Ezio Melottiafd0d112009-07-15 17:17:17 +00001768 def test_bug_6050(self):
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001769 # Extraction should succeed if directories already exist
1770 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottiafd0d112009-07-15 17:17:17 +00001771 self.test_extract_dir()
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001772
Serhiy Storchaka46a34922014-09-23 22:40:23 +03001773 def test_write_dir(self):
1774 dirpath = os.path.join(TESTFN2, "x")
1775 os.mkdir(dirpath)
1776 mode = os.stat(dirpath).st_mode & 0xFFFF
1777 with zipfile.ZipFile(TESTFN, "w") as zipf:
1778 zipf.write(dirpath)
1779 zinfo = zipf.filelist[0]
1780 self.assertTrue(zinfo.filename.endswith("/x/"))
1781 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1782 zipf.write(dirpath, "y")
1783 zinfo = zipf.filelist[1]
1784 self.assertTrue(zinfo.filename, "y/")
1785 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1786 with zipfile.ZipFile(TESTFN, "r") as zipf:
1787 zinfo = zipf.filelist[0]
1788 self.assertTrue(zinfo.filename.endswith("/x/"))
1789 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1790 zinfo = zipf.filelist[1]
1791 self.assertTrue(zinfo.filename, "y/")
1792 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1793 target = os.path.join(TESTFN2, "target")
1794 os.mkdir(target)
1795 zipf.extractall(target)
1796 self.assertTrue(os.path.isdir(os.path.join(target, "y")))
1797 self.assertEqual(len(os.listdir(target)), 2)
1798
1799 def test_writestr_dir(self):
Martin v. Löwis59e47792009-01-24 14:10:07 +00001800 os.mkdir(os.path.join(TESTFN2, "x"))
Serhiy Storchaka46a34922014-09-23 22:40:23 +03001801 with zipfile.ZipFile(TESTFN, "w") as zipf:
1802 zipf.writestr("x/", b'')
1803 zinfo = zipf.filelist[0]
1804 self.assertEqual(zinfo.filename, "x/")
1805 self.assertEqual(zinfo.external_attr, (0o40775 << 16) | 0x10)
1806 with zipfile.ZipFile(TESTFN, "r") as zipf:
1807 zinfo = zipf.filelist[0]
1808 self.assertTrue(zinfo.filename.endswith("x/"))
1809 self.assertEqual(zinfo.external_attr, (0o40775 << 16) | 0x10)
1810 target = os.path.join(TESTFN2, "target")
1811 os.mkdir(target)
1812 zipf.extractall(target)
1813 self.assertTrue(os.path.isdir(os.path.join(target, "x")))
1814 self.assertEqual(os.listdir(target), ["x"])
Martin v. Löwis59e47792009-01-24 14:10:07 +00001815
1816 def tearDown(self):
Victor Stinner57004c62014-09-04 00:49:01 +02001817 rmtree(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001818 if os.path.exists(TESTFN):
Ezio Melotti76430242009-07-11 18:28:48 +00001819 unlink(TESTFN)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001820
Guido van Rossumd8faa362007-04-27 19:54:29 +00001821
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001822class AbstractUniversalNewlineTests:
1823 @classmethod
1824 def setUpClass(cls):
1825 cls.line_gen = [bytes("Test of zipfile line %d." % i, "ascii")
1826 for i in range(FIXEDTEST_SIZE)]
1827 cls.seps = (b'\r', b'\r\n', b'\n')
1828 cls.arcdata = {}
1829 for n, s in enumerate(cls.seps):
1830 cls.arcdata[s] = s.join(cls.line_gen) + s
1831
Guido van Rossumd8faa362007-04-27 19:54:29 +00001832 def setUp(self):
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001833 self.arcfiles = {}
Guido van Rossumd8faa362007-04-27 19:54:29 +00001834 for n, s in enumerate(self.seps):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001835 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001836 with open(self.arcfiles[s], "wb") as f:
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001837 f.write(self.arcdata[s])
Guido van Rossumd8faa362007-04-27 19:54:29 +00001838
Ezio Melottiafd0d112009-07-15 17:17:17 +00001839 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001840 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001841 with zipfile.ZipFile(f, "w", compression) as zipfp:
1842 for fn in self.arcfiles.values():
1843 zipfp.write(fn, fn)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001844
Ezio Melottiafd0d112009-07-15 17:17:17 +00001845 def read_test(self, f, compression):
1846 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001847
1848 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001849 with zipfile.ZipFile(f, "r") as zipfp:
1850 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02001851 with openU(zipfp, fn) as fp:
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001852 zipdata = fp.read()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001853 self.assertEqual(self.arcdata[sep], zipdata)
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001854
1855 def test_read(self):
1856 for f in get_files(self):
1857 self.read_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001858
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001859 def readline_read_test(self, f, compression):
1860 self.make_test_archive(f, compression)
1861
1862 # Read the ZIP archive
Brian Curtin8fb9b862010-11-18 02:15:28 +00001863 with zipfile.ZipFile(f, "r") as zipfp:
1864 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02001865 with openU(zipfp, fn) as zipopen:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001866 data = b''
1867 while True:
1868 read = zipopen.readline()
1869 if not read:
1870 break
1871 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001872
Brian Curtin8fb9b862010-11-18 02:15:28 +00001873 read = zipopen.read(5)
1874 if not read:
1875 break
1876 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001877
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001878 self.assertEqual(data, self.arcdata[b'\n'])
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001879
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001880 def test_readline_read(self):
1881 for f in get_files(self):
1882 self.readline_read_test(f, self.compression)
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001883
Ezio Melottiafd0d112009-07-15 17:17:17 +00001884 def readline_test(self, f, compression):
1885 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001886
1887 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001888 with zipfile.ZipFile(f, "r") as zipfp:
1889 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02001890 with openU(zipfp, fn) as zipopen:
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001891 for line in self.line_gen:
1892 linedata = zipopen.readline()
1893 self.assertEqual(linedata, line + b'\n')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001894
1895 def test_readline(self):
1896 for f in get_files(self):
1897 self.readline_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001898
Ezio Melottiafd0d112009-07-15 17:17:17 +00001899 def readlines_test(self, f, compression):
1900 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001901
1902 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001903 with zipfile.ZipFile(f, "r") as zipfp:
1904 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02001905 with openU(zipfp, fn) as fp:
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001906 ziplines = fp.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001907 for line, zipline in zip(self.line_gen, ziplines):
1908 self.assertEqual(zipline, line + b'\n')
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001909
1910 def test_readlines(self):
1911 for f in get_files(self):
1912 self.readlines_test(f, self.compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001913
Ezio Melottiafd0d112009-07-15 17:17:17 +00001914 def iterlines_test(self, f, compression):
1915 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001916
1917 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001918 with zipfile.ZipFile(f, "r") as zipfp:
1919 for sep, fn in self.arcfiles.items():
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +02001920 with openU(zipfp, fn) as fp:
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001921 for line, zipline in zip(self.line_gen, fp):
1922 self.assertEqual(zipline, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001923
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001924 def test_iterlines(self):
1925 for f in get_files(self):
1926 self.iterlines_test(f, self.compression)
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001927
Guido van Rossumd8faa362007-04-27 19:54:29 +00001928 def tearDown(self):
1929 for sep, fn in self.arcfiles.items():
Victor Stinner88b215e2014-09-04 00:51:09 +02001930 unlink(fn)
Ezio Melotti76430242009-07-11 18:28:48 +00001931 unlink(TESTFN)
1932 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001933
1934
Serhiy Storchakafa6bc292013-07-22 21:00:11 +03001935class StoredUniversalNewlineTests(AbstractUniversalNewlineTests,
1936 unittest.TestCase):
1937 compression = zipfile.ZIP_STORED
1938
1939@requires_zlib
1940class DeflateUniversalNewlineTests(AbstractUniversalNewlineTests,
1941 unittest.TestCase):
1942 compression = zipfile.ZIP_DEFLATED
1943
1944@requires_bz2
1945class Bzip2UniversalNewlineTests(AbstractUniversalNewlineTests,
1946 unittest.TestCase):
1947 compression = zipfile.ZIP_BZIP2
1948
1949@requires_lzma
1950class LzmaUniversalNewlineTests(AbstractUniversalNewlineTests,
1951 unittest.TestCase):
1952 compression = zipfile.ZIP_LZMA
1953
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001954if __name__ == "__main__":
Brett Cannond5b4e1d2013-06-12 19:57:19 -04001955 unittest.main()