blob: 678ac9fc00f54f1492cdad5edecd0cf6b109a640 [file] [log] [blame]
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001# We can test part of the module without zlib.
Guido van Rossum368f04a2000-04-10 13:23:04 +00002try:
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00003 import zlib
4except ImportError:
5 zlib = None
Guido van Rossumd6ca5462007-05-22 01:29:33 +00006import zipfile, os, unittest, sys, shutil, struct, io
Tim Petersa45cacf2004-08-20 03:47:14 +00007
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00008from tempfile import TemporaryFile
Guido van Rossumd8faa362007-04-27 19:54:29 +00009from random import randint, random
Tim Petersa19a1682001-03-29 04:36:09 +000010
Benjamin Petersonee8712c2008-05-20 21:35:26 +000011import test.support as support
12from test.support import TESTFN, run_unittest
Guido van Rossum368f04a2000-04-10 13:23:04 +000013
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000014TESTFN2 = TESTFN + "2"
Guido van Rossumb5a755e2007-07-18 18:15:48 +000015FIXEDTEST_SIZE = 1000
Guido van Rossum368f04a2000-04-10 13:23:04 +000016
Christian Heimes790c8232008-01-07 21:14:23 +000017SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'),
18 ('ziptest2dir/_ziptest2', 'qawsedrftg'),
19 ('/ziptest2dir/ziptest3dir/_ziptest3', 'azsxdcfvgb'),
20 ('ziptest2dir/ziptest3dir/ziptest4dir/_ziptest3', '6y7u8i9o0p')]
21
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000022class TestsWithSourceFile(unittest.TestCase):
23 def setUp(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +000024 self.line_gen = (bytes("Zipfile test line %d. random float: %f" %
Guido van Rossum9c627722007-08-27 18:31:48 +000025 (i, random()), "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +000026 for i in range(FIXEDTEST_SIZE))
27 self.data = b'\n'.join(self.line_gen) + b'\n'
Fred Drake6e7e4852001-02-28 05:34:16 +000028
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000029 # Make a source file with some lines
30 fp = open(TESTFN, "wb")
31 fp.write(self.data)
32 fp.close()
Tim Peters7d3bad62001-04-04 18:56:49 +000033
Guido van Rossumd8faa362007-04-27 19:54:29 +000034 def makeTestArchive(self, f, compression):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000035 # Create the ZIP archive
36 zipfp = zipfile.ZipFile(f, "w", compression)
Skip Montanaro7a98be22007-08-16 14:35:24 +000037 zipfp.write(TESTFN, "another.name")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000038 zipfp.write(TESTFN, TESTFN)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000039 zipfp.writestr("strfile", self.data)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000040 zipfp.close()
Tim Peters7d3bad62001-04-04 18:56:49 +000041
Guido van Rossumd8faa362007-04-27 19:54:29 +000042 def zipTest(self, f, compression):
43 self.makeTestArchive(f, compression)
44
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000045 # Read the ZIP archive
46 zipfp = zipfile.ZipFile(f, "r", compression)
47 self.assertEqual(zipfp.read(TESTFN), self.data)
Skip Montanaro7a98be22007-08-16 14:35:24 +000048 self.assertEqual(zipfp.read("another.name"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000049 self.assertEqual(zipfp.read("strfile"), self.data)
50
51 # Print the ZIP directory
Guido van Rossumd6ca5462007-05-22 01:29:33 +000052 fp = io.StringIO()
53 zipfp.printdir(file=fp)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000054
55 directory = fp.getvalue()
56 lines = directory.splitlines()
57 self.assertEquals(len(lines), 4) # Number of files + header
58
59 self.assert_('File Name' in lines[0])
60 self.assert_('Modified' in lines[0])
61 self.assert_('Size' in lines[0])
62
63 fn, date, time, size = lines[1].split()
64 self.assertEquals(fn, 'another.name')
65 # XXX: timestamp is not tested
66 self.assertEquals(size, str(len(self.data)))
67
68 # Check the namelist
69 names = zipfp.namelist()
70 self.assertEquals(len(names), 3)
71 self.assert_(TESTFN in names)
Skip Montanaro7a98be22007-08-16 14:35:24 +000072 self.assert_("another.name" in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000073 self.assert_("strfile" in names)
74
75 # Check infolist
76 infos = zipfp.infolist()
77 names = [ i.filename for i in infos ]
78 self.assertEquals(len(names), 3)
79 self.assert_(TESTFN in names)
Skip Montanaro7a98be22007-08-16 14:35:24 +000080 self.assert_("another.name" in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000081 self.assert_("strfile" in names)
82 for i in infos:
83 self.assertEquals(i.file_size, len(self.data))
84
85 # check getinfo
Skip Montanaro7a98be22007-08-16 14:35:24 +000086 for nm in (TESTFN, "another.name", "strfile"):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000087 info = zipfp.getinfo(nm)
88 self.assertEquals(info.filename, nm)
89 self.assertEquals(info.file_size, len(self.data))
90
91 # Check that testzip doesn't raise an exception
92 zipfp.testzip()
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000093 zipfp.close()
Tim Peters7d3bad62001-04-04 18:56:49 +000094
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000095 def testStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +000096 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000097 self.zipTest(f, zipfile.ZIP_STORED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +000098
Guido van Rossumd8faa362007-04-27 19:54:29 +000099 def zipOpenTest(self, f, compression):
100 self.makeTestArchive(f, compression)
101
102 # Read the ZIP archive
103 zipfp = zipfile.ZipFile(f, "r", compression)
104 zipdata1 = []
105 zipopen1 = zipfp.open(TESTFN)
106 while 1:
107 read_data = zipopen1.read(256)
108 if not read_data:
109 break
110 zipdata1.append(read_data)
111
112 zipdata2 = []
Skip Montanaro7a98be22007-08-16 14:35:24 +0000113 zipopen2 = zipfp.open("another.name")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000114 while 1:
115 read_data = zipopen2.read(256)
116 if not read_data:
117 break
118 zipdata2.append(read_data)
119
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000120 self.assertEqual(b''.join(zipdata1), self.data)
121 self.assertEqual(b''.join(zipdata2), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000122 zipfp.close()
123
124 def testOpenStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000125 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000126 self.zipOpenTest(f, zipfile.ZIP_STORED)
127
Georg Brandlb533e262008-05-25 18:19:30 +0000128 def testOpenViaZipInfo(self):
129 # Create the ZIP archive
130 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
131 zipfp.writestr("name", "foo")
132 zipfp.writestr("name", "bar")
133 zipfp.close()
134
135 zipfp = zipfile.ZipFile(TESTFN2, "r")
136 infos = zipfp.infolist()
137 data = b""
138 for info in infos:
139 data += zipfp.open(info).read()
140 self.assert_(data == b"foobar" or data == b"barfoo")
141 data = b""
142 for info in infos:
143 data += zipfp.read(info)
144 self.assert_(data == b"foobar" or data == b"barfoo")
145 zipfp.close()
146
Guido van Rossumd8faa362007-04-27 19:54:29 +0000147 def zipRandomOpenTest(self, f, compression):
148 self.makeTestArchive(f, compression)
149
150 # Read the ZIP archive
151 zipfp = zipfile.ZipFile(f, "r", compression)
152 zipdata1 = []
153 zipopen1 = zipfp.open(TESTFN)
154 while 1:
155 read_data = zipopen1.read(randint(1, 1024))
156 if not read_data:
157 break
158 zipdata1.append(read_data)
159
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000160 self.assertEqual(b''.join(zipdata1), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000161 zipfp.close()
162
163 def testRandomOpenStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000164 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000165 self.zipRandomOpenTest(f, zipfile.ZIP_STORED)
166
167 def zipReadlineTest(self, f, compression):
168 self.makeTestArchive(f, compression)
169
170 # Read the ZIP archive
171 zipfp = zipfile.ZipFile(f, "r")
172 zipopen = zipfp.open(TESTFN)
173 for line in self.line_gen:
174 linedata = zipopen.readline()
175 self.assertEqual(linedata, line + '\n')
176
177 zipfp.close()
178
179 def zipReadlinesTest(self, f, compression):
180 self.makeTestArchive(f, compression)
181
182 # Read the ZIP archive
183 zipfp = zipfile.ZipFile(f, "r")
184 ziplines = zipfp.open(TESTFN).readlines()
185 for line, zipline in zip(self.line_gen, ziplines):
186 self.assertEqual(zipline, line + '\n')
187
188 zipfp.close()
189
190 def zipIterlinesTest(self, f, compression):
191 self.makeTestArchive(f, compression)
192
193 # Read the ZIP archive
194 zipfp = zipfile.ZipFile(f, "r")
195 for line, zipline in zip(self.line_gen, zipfp.open(TESTFN)):
196 self.assertEqual(zipline, line + '\n')
197
198 zipfp.close()
199
200 def testReadlineStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000201 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000202 self.zipReadlineTest(f, zipfile.ZIP_STORED)
203
204 def testReadlinesStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000205 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000206 self.zipReadlinesTest(f, zipfile.ZIP_STORED)
207
208 def testIterlinesStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000209 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000210 self.zipIterlinesTest(f, zipfile.ZIP_STORED)
211
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000212 if zlib:
213 def testDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000214 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000215 self.zipTest(f, zipfile.ZIP_DEFLATED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000216
Guido van Rossumd8faa362007-04-27 19:54:29 +0000217 def testOpenDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000218 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000219 self.zipOpenTest(f, zipfile.ZIP_DEFLATED)
220
221 def testRandomOpenDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000222 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000223 self.zipRandomOpenTest(f, zipfile.ZIP_DEFLATED)
224
225 def testReadlineDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000226 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000227 self.zipReadlineTest(f, zipfile.ZIP_DEFLATED)
228
229 def testReadlinesDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000230 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000231 self.zipReadlinesTest(f, zipfile.ZIP_DEFLATED)
232
233 def testIterlinesDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000234 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000235 self.zipIterlinesTest(f, zipfile.ZIP_DEFLATED)
236
237 def testLowCompression(self):
238 # Checks for cases where compressed data is larger than original
239 # Create the ZIP archive
240 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED)
241 zipfp.writestr("strfile", '12')
242 zipfp.close()
243
244 # Get an open object for strfile
245 zipfp = zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_DEFLATED)
246 openobj = zipfp.open("strfile")
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000247 self.assertEqual(openobj.read(1), b'1')
248 self.assertEqual(openobj.read(1), b'2')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000249
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000250 def testAbsoluteArcnames(self):
251 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
252 zipfp.write(TESTFN, "/absolute")
253 zipfp.close()
254
255 zipfp = zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED)
256 self.assertEqual(zipfp.namelist(), ["absolute"])
257 zipfp.close()
Tim Peters32cbc962006-02-20 21:42:18 +0000258
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000259 def testAppendToZipFile(self):
260 # Test appending to an existing zipfile
261 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
262 zipfp.write(TESTFN, TESTFN)
263 zipfp.close()
264 zipfp = zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED)
265 zipfp.writestr("strfile", self.data)
266 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
267 zipfp.close()
268
269 def testAppendToNonZipFile(self):
270 # Test appending to an existing file that is not a zipfile
271 # NOTE: this test fails if len(d) < 22 because of the first
272 # line "fpin.seek(-22, 2)" in _EndRecData
Guido van Rossum9c627722007-08-27 18:31:48 +0000273 d = b'I am not a ZipFile!'*10
Guido van Rossum814661e2007-07-18 22:07:29 +0000274 f = open(TESTFN2, 'wb')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000275 f.write(d)
276 f.close()
277 zipfp = zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED)
278 zipfp.write(TESTFN, TESTFN)
279 zipfp.close()
280
Guido van Rossum814661e2007-07-18 22:07:29 +0000281 f = open(TESTFN2, 'rb')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000282 f.seek(len(d))
283 zipfp = zipfile.ZipFile(f, "r")
284 self.assertEqual(zipfp.namelist(), [TESTFN])
285 zipfp.close()
286 f.close()
287
288 def test_WriteDefaultName(self):
289 # Check that calling ZipFile.write without arcname specified produces the expected result
290 zipfp = zipfile.ZipFile(TESTFN2, "w")
291 zipfp.write(TESTFN)
Guido van Rossum814661e2007-07-18 22:07:29 +0000292 self.assertEqual(zipfp.read(TESTFN), open(TESTFN, "rb").read())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000293 zipfp.close()
294
295 def test_PerFileCompression(self):
296 # Check that files within a Zip archive can have different compression options
297 zipfp = zipfile.ZipFile(TESTFN2, "w")
298 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
299 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
300 sinfo = zipfp.getinfo('storeme')
301 dinfo = zipfp.getinfo('deflateme')
302 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
303 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
304 zipfp.close()
305
306 def test_WriteToReadonly(self):
307 # Check that trying to call write() on a readonly ZipFile object
308 # raises a RuntimeError
309 zipf = zipfile.ZipFile(TESTFN2, mode="w")
310 zipf.writestr("somefile.txt", "bogus")
311 zipf.close()
312 zipf = zipfile.ZipFile(TESTFN2, mode="r")
313 self.assertRaises(RuntimeError, zipf.write, TESTFN)
314 zipf.close()
315
Christian Heimes790c8232008-01-07 21:14:23 +0000316 def testExtract(self):
317 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
318 for fpath, fdata in SMALL_TEST_DATA:
319 zipfp.writestr(fpath, fdata)
320 zipfp.close()
321
322 zipfp = zipfile.ZipFile(TESTFN2, "r")
323 for fpath, fdata in SMALL_TEST_DATA:
324 writtenfile = zipfp.extract(fpath)
325
326 # make sure it was written to the right place
327 if os.path.isabs(fpath):
328 correctfile = os.path.join(os.getcwd(), fpath[1:])
329 else:
330 correctfile = os.path.join(os.getcwd(), fpath)
Christian Heimesaf98da12008-01-27 15:18:18 +0000331 correctfile = os.path.normpath(correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000332
333 self.assertEqual(writtenfile, correctfile)
334
335 # make sure correct data is in correct file
336 self.assertEqual(fdata.encode(), open(writtenfile, "rb").read())
337
338 os.remove(writtenfile)
339
340 zipfp.close()
341
342 # remove the test file subdirectories
343 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
344
345 def testExtractAll(self):
346 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
347 for fpath, fdata in SMALL_TEST_DATA:
348 zipfp.writestr(fpath, fdata)
349 zipfp.close()
350
351 zipfp = zipfile.ZipFile(TESTFN2, "r")
352 zipfp.extractall()
353 for fpath, fdata in SMALL_TEST_DATA:
354 if os.path.isabs(fpath):
355 outfile = os.path.join(os.getcwd(), fpath[1:])
356 else:
357 outfile = os.path.join(os.getcwd(), fpath)
358
359 self.assertEqual(fdata.encode(), open(outfile, "rb").read())
360
361 os.remove(outfile)
362
363 zipfp.close()
364
365 # remove the test file subdirectories
366 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
367
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000368 def zip_test_writestr_permissions(self, f, compression):
369 # Make sure that writestr creates files with mode 0600,
370 # when it is passed a name rather than a ZipInfo instance.
371
372 self.makeTestArchive(f, compression)
373 zipfp = zipfile.ZipFile(f, "r")
374 zinfo = zipfp.getinfo('strfile')
375 self.assertEqual(zinfo.external_attr, 0o600 << 16)
376
377 def test_writestr_permissions(self):
378 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
379 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
380
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000381 def tearDown(self):
382 os.remove(TESTFN)
383 os.remove(TESTFN2)
384
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000385class TestZip64InSmallFiles(unittest.TestCase):
386 # These tests test the ZIP64 functionality without using large files,
387 # see test_zipfile64 for proper tests.
388
389 def setUp(self):
390 self._limit = zipfile.ZIP64_LIMIT
391 zipfile.ZIP64_LIMIT = 5
392
Guido van Rossum9c627722007-08-27 18:31:48 +0000393 line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000394 for i in range(0, FIXEDTEST_SIZE))
395 self.data = b'\n'.join(line_gen)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000396
397 # Make a source file with some lines
398 fp = open(TESTFN, "wb")
399 fp.write(self.data)
400 fp.close()
401
402 def largeFileExceptionTest(self, f, compression):
403 zipfp = zipfile.ZipFile(f, "w", compression)
404 self.assertRaises(zipfile.LargeZipFile,
Skip Montanaro7a98be22007-08-16 14:35:24 +0000405 zipfp.write, TESTFN, "another.name")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000406 zipfp.close()
407
408 def largeFileExceptionTest2(self, f, compression):
409 zipfp = zipfile.ZipFile(f, "w", compression)
410 self.assertRaises(zipfile.LargeZipFile,
Skip Montanaro7a98be22007-08-16 14:35:24 +0000411 zipfp.writestr, "another.name", self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000412 zipfp.close()
413
414 def testLargeFileException(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000415 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000416 self.largeFileExceptionTest(f, zipfile.ZIP_STORED)
417 self.largeFileExceptionTest2(f, zipfile.ZIP_STORED)
418
419 def zipTest(self, f, compression):
420 # Create the ZIP archive
421 zipfp = zipfile.ZipFile(f, "w", compression, allowZip64=True)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000422 zipfp.write(TESTFN, "another.name")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000423 zipfp.write(TESTFN, TESTFN)
424 zipfp.writestr("strfile", self.data)
425 zipfp.close()
426
427 # Read the ZIP archive
428 zipfp = zipfile.ZipFile(f, "r", compression)
429 self.assertEqual(zipfp.read(TESTFN), self.data)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000430 self.assertEqual(zipfp.read("another.name"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000431 self.assertEqual(zipfp.read("strfile"), self.data)
432
433 # Print the ZIP directory
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000434 fp = io.StringIO()
435 zipfp.printdir(fp)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000436
437 directory = fp.getvalue()
438 lines = directory.splitlines()
439 self.assertEquals(len(lines), 4) # Number of files + header
440
441 self.assert_('File Name' in lines[0])
442 self.assert_('Modified' in lines[0])
443 self.assert_('Size' in lines[0])
444
445 fn, date, time, size = lines[1].split()
446 self.assertEquals(fn, 'another.name')
447 # XXX: timestamp is not tested
448 self.assertEquals(size, str(len(self.data)))
449
450 # Check the namelist
451 names = zipfp.namelist()
452 self.assertEquals(len(names), 3)
453 self.assert_(TESTFN in names)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000454 self.assert_("another.name" in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000455 self.assert_("strfile" in names)
456
457 # Check infolist
458 infos = zipfp.infolist()
459 names = [ i.filename for i in infos ]
460 self.assertEquals(len(names), 3)
461 self.assert_(TESTFN in names)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000462 self.assert_("another.name" in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000463 self.assert_("strfile" in names)
464 for i in infos:
465 self.assertEquals(i.file_size, len(self.data))
466
467 # check getinfo
Skip Montanaro7a98be22007-08-16 14:35:24 +0000468 for nm in (TESTFN, "another.name", "strfile"):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000469 info = zipfp.getinfo(nm)
470 self.assertEquals(info.filename, nm)
471 self.assertEquals(info.file_size, len(self.data))
472
473 # Check that testzip doesn't raise an exception
474 zipfp.testzip()
475
476
477 zipfp.close()
478
479 def testStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000480 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000481 self.zipTest(f, zipfile.ZIP_STORED)
482
483
484 if zlib:
485 def testDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000486 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000487 self.zipTest(f, zipfile.ZIP_DEFLATED)
488
489 def testAbsoluteArcnames(self):
490 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED, allowZip64=True)
491 zipfp.write(TESTFN, "/absolute")
492 zipfp.close()
493
494 zipfp = zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED)
495 self.assertEqual(zipfp.namelist(), ["absolute"])
496 zipfp.close()
497
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000498 def tearDown(self):
499 zipfile.ZIP64_LIMIT = self._limit
500 os.remove(TESTFN)
501 os.remove(TESTFN2)
502
503class PyZipFileTests(unittest.TestCase):
504 def testWritePyfile(self):
505 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
506 fn = __file__
507 if fn.endswith('.pyc') or fn.endswith('.pyo'):
508 fn = fn[:-1]
509
510 zipfp.writepy(fn)
511
512 bn = os.path.basename(fn)
513 self.assert_(bn not in zipfp.namelist())
514 self.assert_(bn + 'o' in zipfp.namelist() or bn + 'c' in zipfp.namelist())
515 zipfp.close()
516
517
518 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
519 fn = __file__
520 if fn.endswith('.pyc') or fn.endswith('.pyo'):
521 fn = fn[:-1]
522
523 zipfp.writepy(fn, "testpackage")
524
525 bn = "%s/%s"%("testpackage", os.path.basename(fn))
526 self.assert_(bn not in zipfp.namelist())
527 self.assert_(bn + 'o' in zipfp.namelist() or bn + 'c' in zipfp.namelist())
528 zipfp.close()
529
530 def testWritePythonPackage(self):
531 import email
532 packagedir = os.path.dirname(email.__file__)
533
534 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
535 zipfp.writepy(packagedir)
536
537 # Check for a couple of modules at different levels of the hieararchy
538 names = zipfp.namelist()
539 self.assert_('email/__init__.pyo' in names or 'email/__init__.pyc' in names)
540 self.assert_('email/mime/text.pyo' in names or 'email/mime/text.pyc' in names)
541
542 def testWritePythonDirectory(self):
543 os.mkdir(TESTFN2)
544 try:
545 fp = open(os.path.join(TESTFN2, "mod1.py"), "w")
Guido van Rossum43fc78d2007-02-09 22:18:41 +0000546 fp.write("print(42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000547 fp.close()
548
549 fp = open(os.path.join(TESTFN2, "mod2.py"), "w")
Guido van Rossum43fc78d2007-02-09 22:18:41 +0000550 fp.write("print(42 * 42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000551 fp.close()
552
553 fp = open(os.path.join(TESTFN2, "mod2.txt"), "w")
554 fp.write("bla bla bla\n")
555 fp.close()
556
557 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
558 zipfp.writepy(TESTFN2)
559
560 names = zipfp.namelist()
561 self.assert_('mod1.pyc' in names or 'mod1.pyo' in names)
562 self.assert_('mod2.pyc' in names or 'mod2.pyo' in names)
563 self.assert_('mod2.txt' not in names)
564
565 finally:
566 shutil.rmtree(TESTFN2)
567
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000568 def testWriteNonPyfile(self):
569 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
Guido van Rossum814661e2007-07-18 22:07:29 +0000570 open(TESTFN, 'w').write('most definitely not a python file')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000571 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
572 os.remove(TESTFN)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000573
574
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000575class OtherTests(unittest.TestCase):
Martin v. Löwis8570f6a2008-05-05 17:44:38 +0000576 def testUnicodeFilenames(self):
577 zf = zipfile.ZipFile(TESTFN, "w")
578 zf.writestr("foo.txt", "Test for unicode filename")
Martin v. Löwis1a9f9002008-05-05 17:50:05 +0000579 zf.writestr("\xf6.txt", "Test for unicode filename")
Martin v. Löwis8570f6a2008-05-05 17:44:38 +0000580 zf.close()
Martin v. Löwis1a9f9002008-05-05 17:50:05 +0000581 zf = zipfile.ZipFile(TESTFN, "r")
582 self.assertEqual(zf.filelist[0].filename, "foo.txt")
583 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
584 zf.close()
Martin v. Löwis8570f6a2008-05-05 17:44:38 +0000585
Thomas Wouterscf297e42007-02-23 15:07:44 +0000586 def testCreateNonExistentFileForAppend(self):
587 if os.path.exists(TESTFN):
588 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000589
Thomas Wouterscf297e42007-02-23 15:07:44 +0000590 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000591 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +0000592
Thomas Wouterscf297e42007-02-23 15:07:44 +0000593 try:
594 zf = zipfile.ZipFile(TESTFN, 'a')
595 zf.writestr(filename, content)
596 zf.close()
597 except IOError:
598 self.fail('Could not append data to a non-existent zip file.')
599
600 self.assert_(os.path.exists(TESTFN))
601
602 zf = zipfile.ZipFile(TESTFN, 'r')
603 self.assertEqual(zf.read(filename), content)
604 zf.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000605
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000606 def testCloseErroneousFile(self):
607 # This test checks that the ZipFile constructor closes the file object
608 # it opens if there's an error in the file. If it doesn't, the traceback
609 # holds a reference to the ZipFile object and, indirectly, the file object.
610 # On Windows, this causes the os.unlink() call to fail because the
611 # underlying file is still open. This is SF bug #412214.
612 #
613 fp = open(TESTFN, "w")
614 fp.write("this is not a legal zip file\n")
615 fp.close()
616 try:
617 zf = zipfile.ZipFile(TESTFN)
618 except zipfile.BadZipfile:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000619 pass
620
621 def testIsZipErroneousFile(self):
622 # This test checks that the is_zipfile function correctly identifies
623 # a file that is not a zip file
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000624
625 # - passing a filename
626 with open(TESTFN, "w") as fp:
627 fp.write("this is not a legal zip file\n")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000628 chk = zipfile.is_zipfile(TESTFN)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000629 self.assert_(not chk)
630 # - passing a file object
631 with open(TESTFN, "rb") as fp:
632 chk = zipfile.is_zipfile(fp)
633 self.assert_(not chk)
634 # - passing a file-like object
635 fp = io.BytesIO()
636 fp.write(b"this is not a legal zip file\n")
637 chk = zipfile.is_zipfile(fp)
638 self.assert_(not chk)
639 fp.seek(0,0)
640 chk = zipfile.is_zipfile(fp)
641 self.assert_(not chk)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000642
643 def testIsZipValidFile(self):
644 # This test checks that the is_zipfile function correctly identifies
645 # a file that is a zip file
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000646
647 # - passing a filename
Guido van Rossumd8faa362007-04-27 19:54:29 +0000648 zipf = zipfile.ZipFile(TESTFN, mode="w")
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000649 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000650 zipf.close()
651 chk = zipfile.is_zipfile(TESTFN)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000652 self.assert_(chk)
653 # - passing a file object
654 with open(TESTFN, "rb") as fp:
655 chk = zipfile.is_zipfile(fp)
656 self.assert_(chk)
657 fp.seek(0,0)
658 zip_contents = fp.read()
659 # - passing a file-like object
660 fp = io.BytesIO()
661 fp.write(zip_contents)
662 chk = zipfile.is_zipfile(fp)
663 self.assert_(chk)
664 fp.seek(0,0)
665 chk = zipfile.is_zipfile(fp)
666 self.assert_(chk)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000667
668 def testNonExistentFileRaisesIOError(self):
669 # make sure we don't raise an AttributeError when a partially-constructed
670 # ZipFile instance is finalized; this tests for regression on SF tracker
671 # bug #403871.
672
673 # The bug we're testing for caused an AttributeError to be raised
674 # when a ZipFile instance was created for a file that did not
675 # exist; the .fp member was not initialized but was needed by the
676 # __del__() method. Since the AttributeError is in the __del__(),
677 # it is ignored, but the user should be sufficiently annoyed by
678 # the message on the output that regression will be noticed
679 # quickly.
680 self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
681
682 def testClosedZipRaisesRuntimeError(self):
683 # Verify that testzip() doesn't swallow inappropriate exceptions.
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000684 data = io.BytesIO()
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000685 zipf = zipfile.ZipFile(data, mode="w")
686 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
687 zipf.close()
688
689 # This is correct; calling .read on a closed ZipFile should throw
690 # a RuntimeError, and so should calling .testzip. An earlier
691 # version of .testzip would swallow this exception (and any other)
692 # and report that the first file in the archive was corrupt.
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000693 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
694 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000695 self.assertRaises(RuntimeError, zipf.testzip)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000696 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Guido van Rossum814661e2007-07-18 22:07:29 +0000697 open(TESTFN, 'w').write('zipfile test data')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000698 self.assertRaises(RuntimeError, zipf.write, TESTFN)
699
700 def test_BadConstructorMode(self):
701 # Check that bad modes passed to ZipFile constructor are caught
702 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
703
704 def test_BadOpenMode(self):
705 # Check that bad modes passed to ZipFile.open are caught
706 zipf = zipfile.ZipFile(TESTFN, mode="w")
707 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
708 zipf.close()
709 zipf = zipfile.ZipFile(TESTFN, mode="r")
710 # read the data to make sure the file is there
711 zipf.read("foo.txt")
712 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
713 zipf.close()
714
715 def test_Read0(self):
716 # Check that calling read(0) on a ZipExtFile object returns an empty
717 # string and doesn't advance file pointer
718 zipf = zipfile.ZipFile(TESTFN, mode="w")
719 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
720 # read the data to make sure the file is there
721 f = zipf.open("foo.txt")
722 for i in range(FIXEDTEST_SIZE):
Guido van Rossum814661e2007-07-18 22:07:29 +0000723 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000724
Guido van Rossum814661e2007-07-18 22:07:29 +0000725 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000726 zipf.close()
727
728 def test_OpenNonexistentItem(self):
729 # Check that attempting to call open() for an item that doesn't
730 # exist in the archive raises a RuntimeError
731 zipf = zipfile.ZipFile(TESTFN, mode="w")
732 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
733
734 def test_BadCompressionMode(self):
735 # Check that bad compression methods passed to ZipFile.open are caught
736 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
737
738 def test_NullByteInFilename(self):
739 # Check that a filename containing a null byte is properly terminated
740 zipf = zipfile.ZipFile(TESTFN, mode="w")
Guido van Rossum814661e2007-07-18 22:07:29 +0000741 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000742 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000743
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000744 def test_StructSizes(self):
745 # check that ZIP internal structure sizes are calculated correctly
746 self.assertEqual(zipfile.sizeEndCentDir, 22)
747 self.assertEqual(zipfile.sizeCentralDir, 46)
748 self.assertEqual(zipfile.sizeEndCentDir64, 56)
749 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
750
751 def testComments(self):
752 # This test checks that comments on the archive are handled properly
753
754 # check default comment is empty
755 zipf = zipfile.ZipFile(TESTFN, mode="w")
756 self.assertEqual(zipf.comment, b'')
757 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
758 zipf.close()
759 zipfr = zipfile.ZipFile(TESTFN, mode="r")
760 self.assertEqual(zipfr.comment, b'')
761 zipfr.close()
762
763 # check a simple short comment
764 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
765 zipf = zipfile.ZipFile(TESTFN, mode="w")
766 zipf.comment = comment
767 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
768 zipf.close()
769 zipfr = zipfile.ZipFile(TESTFN, mode="r")
770 self.assertEqual(zipfr.comment, comment)
771 zipfr.close()
772
773 # check a comment of max length
774 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
775 comment2 = comment2.encode("ascii")
776 zipf = zipfile.ZipFile(TESTFN, mode="w")
777 zipf.comment = comment2
778 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
779 zipf.close()
780 zipfr = zipfile.ZipFile(TESTFN, mode="r")
781 self.assertEqual(zipfr.comment, comment2)
782 zipfr.close()
783
784 # check a comment that is too long is truncated
785 zipf = zipfile.ZipFile(TESTFN, mode="w")
786 zipf.comment = comment2 + b'oops'
787 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
788 zipf.close()
789 zipfr = zipfile.ZipFile(TESTFN, mode="r")
790 self.assertEqual(zipfr.comment, comment2)
791 zipfr.close()
792
Guido van Rossumd8faa362007-04-27 19:54:29 +0000793 def tearDown(self):
794 support.unlink(TESTFN)
795 support.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000796
797class DecryptionTests(unittest.TestCase):
798 # This test checks that ZIP decryption works. Since the library does not
799 # support encryption at the moment, we use a pre-generated encrypted
800 # ZIP file
801
802 data = (
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000803 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
804 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
805 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
806 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
807 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
808 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
809 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +0000810 data2 = (
811 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
812 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
813 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
814 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
815 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
816 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
817 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
818 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +0000819
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000820 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +0000821 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +0000822
823 def setUp(self):
824 fp = open(TESTFN, "wb")
825 fp.write(self.data)
826 fp.close()
827 self.zip = zipfile.ZipFile(TESTFN, "r")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000828 fp = open(TESTFN2, "wb")
829 fp.write(self.data2)
830 fp.close()
831 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000832
833 def tearDown(self):
834 self.zip.close()
835 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +0000836 self.zip2.close()
837 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000838
839 def testNoPassword(self):
840 # Reading the encrypted file without password
841 # must generate a RunTime exception
842 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000843 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000844
845 def testBadPassword(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000846 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000847 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000848 self.zip2.setpassword(b"perl")
849 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000850
Thomas Wouterscf297e42007-02-23 15:07:44 +0000851 def testGoodPassword(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000852 self.zip.setpassword(b"python")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000853 self.assertEquals(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +0000854 self.zip2.setpassword(b"12345")
855 self.assertEquals(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000856
Guido van Rossumd8faa362007-04-27 19:54:29 +0000857
858class TestsWithRandomBinaryFiles(unittest.TestCase):
859 def setUp(self):
860 datacount = randint(16, 64)*1024 + randint(1, 1024)
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000861 self.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
862 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000863
864 # Make a source file with some lines
865 fp = open(TESTFN, "wb")
866 fp.write(self.data)
867 fp.close()
868
869 def tearDown(self):
870 support.unlink(TESTFN)
871 support.unlink(TESTFN2)
872
873 def makeTestArchive(self, f, compression):
874 # Create the ZIP archive
875 zipfp = zipfile.ZipFile(f, "w", compression)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000876 zipfp.write(TESTFN, "another.name")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000877 zipfp.write(TESTFN, TESTFN)
878 zipfp.close()
879
880 def zipTest(self, f, compression):
881 self.makeTestArchive(f, compression)
882
883 # Read the ZIP archive
884 zipfp = zipfile.ZipFile(f, "r", compression)
885 testdata = zipfp.read(TESTFN)
886 self.assertEqual(len(testdata), len(self.data))
887 self.assertEqual(testdata, self.data)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000888 self.assertEqual(zipfp.read("another.name"), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000889 zipfp.close()
890
891 def testStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000892 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000893 self.zipTest(f, zipfile.ZIP_STORED)
894
895 def zipOpenTest(self, f, compression):
896 self.makeTestArchive(f, compression)
897
898 # Read the ZIP archive
899 zipfp = zipfile.ZipFile(f, "r", compression)
900 zipdata1 = []
901 zipopen1 = zipfp.open(TESTFN)
902 while 1:
903 read_data = zipopen1.read(256)
904 if not read_data:
905 break
906 zipdata1.append(read_data)
907
908 zipdata2 = []
Skip Montanaro7a98be22007-08-16 14:35:24 +0000909 zipopen2 = zipfp.open("another.name")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000910 while 1:
911 read_data = zipopen2.read(256)
912 if not read_data:
913 break
914 zipdata2.append(read_data)
915
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000916 testdata1 = b''.join(zipdata1)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000917 self.assertEqual(len(testdata1), len(self.data))
918 self.assertEqual(testdata1, self.data)
919
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000920 testdata2 = b''.join(zipdata2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000921 self.assertEqual(len(testdata1), len(self.data))
922 self.assertEqual(testdata1, self.data)
923 zipfp.close()
924
925 def testOpenStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000926 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000927 self.zipOpenTest(f, zipfile.ZIP_STORED)
928
929 def zipRandomOpenTest(self, f, compression):
930 self.makeTestArchive(f, compression)
931
932 # Read the ZIP archive
933 zipfp = zipfile.ZipFile(f, "r", compression)
934 zipdata1 = []
935 zipopen1 = zipfp.open(TESTFN)
936 while 1:
937 read_data = zipopen1.read(randint(1, 1024))
938 if not read_data:
939 break
940 zipdata1.append(read_data)
941
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000942 testdata = b''.join(zipdata1)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000943 self.assertEqual(len(testdata), len(self.data))
944 self.assertEqual(testdata, self.data)
945 zipfp.close()
946
947 def testRandomOpenStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000948 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000949 self.zipRandomOpenTest(f, zipfile.ZIP_STORED)
950
951class TestsWithMultipleOpens(unittest.TestCase):
952 def setUp(self):
953 # Create the ZIP archive
954 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED)
955 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
956 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
957 zipfp.close()
958
959 def testSameFile(self):
960 # Verify that (when the ZipFile is in control of creating file objects)
961 # multiple open() calls can be made without interfering with each other.
962 zipf = zipfile.ZipFile(TESTFN2, mode="r")
963 zopen1 = zipf.open('ones')
964 zopen2 = zipf.open('ones')
965 data1 = zopen1.read(500)
966 data2 = zopen2.read(500)
967 data1 += zopen1.read(500)
968 data2 += zopen2.read(500)
969 self.assertEqual(data1, data2)
970 zipf.close()
971
972 def testDifferentFile(self):
973 # Verify that (when the ZipFile is in control of creating file objects)
974 # multiple open() calls can be made without interfering with each other.
975 zipf = zipfile.ZipFile(TESTFN2, mode="r")
976 zopen1 = zipf.open('ones')
977 zopen2 = zipf.open('twos')
978 data1 = zopen1.read(500)
979 data2 = zopen2.read(500)
980 data1 += zopen1.read(500)
981 data2 += zopen2.read(500)
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000982 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
983 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000984 zipf.close()
985
986 def testInterleaved(self):
987 # Verify that (when the ZipFile is in control of creating file objects)
988 # multiple open() calls can be made without interfering with each other.
989 zipf = zipfile.ZipFile(TESTFN2, mode="r")
990 zopen1 = zipf.open('ones')
991 data1 = zopen1.read(500)
992 zopen2 = zipf.open('twos')
993 data2 = zopen2.read(500)
994 data1 += zopen1.read(500)
995 data2 += zopen2.read(500)
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000996 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
997 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000998 zipf.close()
999
1000 def tearDown(self):
1001 os.remove(TESTFN2)
1002
1003
1004class UniversalNewlineTests(unittest.TestCase):
1005 def setUp(self):
Guido van Rossum9c627722007-08-27 18:31:48 +00001006 self.line_gen = [bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001007 for i in range(FIXEDTEST_SIZE)]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001008 self.seps = ('\r', '\r\n', '\n')
1009 self.arcdata, self.arcfiles = {}, {}
1010 for n, s in enumerate(self.seps):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001011 b = s.encode("ascii")
1012 self.arcdata[s] = b.join(self.line_gen) + b
Guido van Rossumd8faa362007-04-27 19:54:29 +00001013 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001014 f = open(self.arcfiles[s], "wb")
1015 try:
1016 f.write(self.arcdata[s])
1017 finally:
1018 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001019
1020 def makeTestArchive(self, f, compression):
1021 # Create the ZIP archive
1022 zipfp = zipfile.ZipFile(f, "w", compression)
1023 for fn in self.arcfiles.values():
1024 zipfp.write(fn, fn)
1025 zipfp.close()
1026
1027 def readTest(self, f, compression):
1028 self.makeTestArchive(f, compression)
1029
1030 # Read the ZIP archive
1031 zipfp = zipfile.ZipFile(f, "r")
1032 for sep, fn in self.arcfiles.items():
1033 zipdata = zipfp.open(fn, "rU").read()
1034 self.assertEqual(self.arcdata[sep], zipdata)
1035
1036 zipfp.close()
1037
1038 def readlineTest(self, f, compression):
1039 self.makeTestArchive(f, compression)
1040
1041 # Read the ZIP archive
1042 zipfp = zipfile.ZipFile(f, "r")
1043 for sep, fn in self.arcfiles.items():
1044 zipopen = zipfp.open(fn, "rU")
1045 for line in self.line_gen:
1046 linedata = zipopen.readline()
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001047 self.assertEqual(linedata, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001048
1049 zipfp.close()
1050
1051 def readlinesTest(self, f, compression):
1052 self.makeTestArchive(f, compression)
1053
1054 # Read the ZIP archive
1055 zipfp = zipfile.ZipFile(f, "r")
1056 for sep, fn in self.arcfiles.items():
1057 ziplines = zipfp.open(fn, "rU").readlines()
1058 for line, zipline in zip(self.line_gen, ziplines):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001059 self.assertEqual(zipline, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001060
1061 zipfp.close()
1062
1063 def iterlinesTest(self, f, compression):
1064 self.makeTestArchive(f, compression)
1065
1066 # Read the ZIP archive
1067 zipfp = zipfile.ZipFile(f, "r")
1068 for sep, fn in self.arcfiles.items():
1069 for line, zipline in zip(self.line_gen, zipfp.open(fn, "rU")):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001070 self.assertEqual(zipline, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001071
1072 zipfp.close()
1073
1074 def testReadStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001075 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001076 self.readTest(f, zipfile.ZIP_STORED)
1077
1078 def testReadlineStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001079 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001080 self.readlineTest(f, zipfile.ZIP_STORED)
1081
1082 def testReadlinesStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001083 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001084 self.readlinesTest(f, zipfile.ZIP_STORED)
1085
1086 def testIterlinesStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001087 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001088 self.iterlinesTest(f, zipfile.ZIP_STORED)
1089
1090 if zlib:
1091 def testReadDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001092 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001093 self.readTest(f, zipfile.ZIP_DEFLATED)
1094
1095 def testReadlineDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001096 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001097 self.readlineTest(f, zipfile.ZIP_DEFLATED)
1098
1099 def testReadlinesDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001100 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001101 self.readlinesTest(f, zipfile.ZIP_DEFLATED)
1102
1103 def testIterlinesDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001104 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001105 self.iterlinesTest(f, zipfile.ZIP_DEFLATED)
1106
1107 def tearDown(self):
1108 for sep, fn in self.arcfiles.items():
1109 os.remove(fn)
1110 support.unlink(TESTFN)
1111 support.unlink(TESTFN2)
1112
1113
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001114def test_main():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001115 run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
1116 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
1117 UniversalNewlineTests, TestsWithRandomBinaryFiles)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001118
1119if __name__ == "__main__":
1120 test_main()