blob: a647fc6e2c8a9e6fca6720f0b79a88f325011c80 [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
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000368 def tearDown(self):
369 os.remove(TESTFN)
370 os.remove(TESTFN2)
371
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000372class TestZip64InSmallFiles(unittest.TestCase):
373 # These tests test the ZIP64 functionality without using large files,
374 # see test_zipfile64 for proper tests.
375
376 def setUp(self):
377 self._limit = zipfile.ZIP64_LIMIT
378 zipfile.ZIP64_LIMIT = 5
379
Guido van Rossum9c627722007-08-27 18:31:48 +0000380 line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000381 for i in range(0, FIXEDTEST_SIZE))
382 self.data = b'\n'.join(line_gen)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000383
384 # Make a source file with some lines
385 fp = open(TESTFN, "wb")
386 fp.write(self.data)
387 fp.close()
388
389 def largeFileExceptionTest(self, f, compression):
390 zipfp = zipfile.ZipFile(f, "w", compression)
391 self.assertRaises(zipfile.LargeZipFile,
Skip Montanaro7a98be22007-08-16 14:35:24 +0000392 zipfp.write, TESTFN, "another.name")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000393 zipfp.close()
394
395 def largeFileExceptionTest2(self, f, compression):
396 zipfp = zipfile.ZipFile(f, "w", compression)
397 self.assertRaises(zipfile.LargeZipFile,
Skip Montanaro7a98be22007-08-16 14:35:24 +0000398 zipfp.writestr, "another.name", self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000399 zipfp.close()
400
401 def testLargeFileException(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000402 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000403 self.largeFileExceptionTest(f, zipfile.ZIP_STORED)
404 self.largeFileExceptionTest2(f, zipfile.ZIP_STORED)
405
406 def zipTest(self, f, compression):
407 # Create the ZIP archive
408 zipfp = zipfile.ZipFile(f, "w", compression, allowZip64=True)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000409 zipfp.write(TESTFN, "another.name")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000410 zipfp.write(TESTFN, TESTFN)
411 zipfp.writestr("strfile", self.data)
412 zipfp.close()
413
414 # Read the ZIP archive
415 zipfp = zipfile.ZipFile(f, "r", compression)
416 self.assertEqual(zipfp.read(TESTFN), self.data)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000417 self.assertEqual(zipfp.read("another.name"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000418 self.assertEqual(zipfp.read("strfile"), self.data)
419
420 # Print the ZIP directory
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000421 fp = io.StringIO()
422 zipfp.printdir(fp)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000423
424 directory = fp.getvalue()
425 lines = directory.splitlines()
426 self.assertEquals(len(lines), 4) # Number of files + header
427
428 self.assert_('File Name' in lines[0])
429 self.assert_('Modified' in lines[0])
430 self.assert_('Size' in lines[0])
431
432 fn, date, time, size = lines[1].split()
433 self.assertEquals(fn, 'another.name')
434 # XXX: timestamp is not tested
435 self.assertEquals(size, str(len(self.data)))
436
437 # Check the namelist
438 names = zipfp.namelist()
439 self.assertEquals(len(names), 3)
440 self.assert_(TESTFN in names)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000441 self.assert_("another.name" in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000442 self.assert_("strfile" in names)
443
444 # Check infolist
445 infos = zipfp.infolist()
446 names = [ i.filename for i in infos ]
447 self.assertEquals(len(names), 3)
448 self.assert_(TESTFN in names)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000449 self.assert_("another.name" in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000450 self.assert_("strfile" in names)
451 for i in infos:
452 self.assertEquals(i.file_size, len(self.data))
453
454 # check getinfo
Skip Montanaro7a98be22007-08-16 14:35:24 +0000455 for nm in (TESTFN, "another.name", "strfile"):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000456 info = zipfp.getinfo(nm)
457 self.assertEquals(info.filename, nm)
458 self.assertEquals(info.file_size, len(self.data))
459
460 # Check that testzip doesn't raise an exception
461 zipfp.testzip()
462
463
464 zipfp.close()
465
466 def testStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000467 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000468 self.zipTest(f, zipfile.ZIP_STORED)
469
470
471 if zlib:
472 def testDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000473 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000474 self.zipTest(f, zipfile.ZIP_DEFLATED)
475
476 def testAbsoluteArcnames(self):
477 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED, allowZip64=True)
478 zipfp.write(TESTFN, "/absolute")
479 zipfp.close()
480
481 zipfp = zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED)
482 self.assertEqual(zipfp.namelist(), ["absolute"])
483 zipfp.close()
484
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000485 def tearDown(self):
486 zipfile.ZIP64_LIMIT = self._limit
487 os.remove(TESTFN)
488 os.remove(TESTFN2)
489
490class PyZipFileTests(unittest.TestCase):
491 def testWritePyfile(self):
492 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
493 fn = __file__
494 if fn.endswith('.pyc') or fn.endswith('.pyo'):
495 fn = fn[:-1]
496
497 zipfp.writepy(fn)
498
499 bn = os.path.basename(fn)
500 self.assert_(bn not in zipfp.namelist())
501 self.assert_(bn + 'o' in zipfp.namelist() or bn + 'c' in zipfp.namelist())
502 zipfp.close()
503
504
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, "testpackage")
511
512 bn = "%s/%s"%("testpackage", 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 def testWritePythonPackage(self):
518 import email
519 packagedir = os.path.dirname(email.__file__)
520
521 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
522 zipfp.writepy(packagedir)
523
524 # Check for a couple of modules at different levels of the hieararchy
525 names = zipfp.namelist()
526 self.assert_('email/__init__.pyo' in names or 'email/__init__.pyc' in names)
527 self.assert_('email/mime/text.pyo' in names or 'email/mime/text.pyc' in names)
528
529 def testWritePythonDirectory(self):
530 os.mkdir(TESTFN2)
531 try:
532 fp = open(os.path.join(TESTFN2, "mod1.py"), "w")
Guido van Rossum43fc78d2007-02-09 22:18:41 +0000533 fp.write("print(42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000534 fp.close()
535
536 fp = open(os.path.join(TESTFN2, "mod2.py"), "w")
Guido van Rossum43fc78d2007-02-09 22:18:41 +0000537 fp.write("print(42 * 42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000538 fp.close()
539
540 fp = open(os.path.join(TESTFN2, "mod2.txt"), "w")
541 fp.write("bla bla bla\n")
542 fp.close()
543
544 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
545 zipfp.writepy(TESTFN2)
546
547 names = zipfp.namelist()
548 self.assert_('mod1.pyc' in names or 'mod1.pyo' in names)
549 self.assert_('mod2.pyc' in names or 'mod2.pyo' in names)
550 self.assert_('mod2.txt' not in names)
551
552 finally:
553 shutil.rmtree(TESTFN2)
554
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000555 def testWriteNonPyfile(self):
556 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
Guido van Rossum814661e2007-07-18 22:07:29 +0000557 open(TESTFN, 'w').write('most definitely not a python file')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000558 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
559 os.remove(TESTFN)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000560
561
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000562class OtherTests(unittest.TestCase):
Martin v. Löwis8570f6a2008-05-05 17:44:38 +0000563 def testUnicodeFilenames(self):
564 zf = zipfile.ZipFile(TESTFN, "w")
565 zf.writestr("foo.txt", "Test for unicode filename")
Martin v. Löwis1a9f9002008-05-05 17:50:05 +0000566 zf.writestr("\xf6.txt", "Test for unicode filename")
Martin v. Löwis8570f6a2008-05-05 17:44:38 +0000567 zf.close()
Martin v. Löwis1a9f9002008-05-05 17:50:05 +0000568 zf = zipfile.ZipFile(TESTFN, "r")
569 self.assertEqual(zf.filelist[0].filename, "foo.txt")
570 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
571 zf.close()
Martin v. Löwis8570f6a2008-05-05 17:44:38 +0000572
Thomas Wouterscf297e42007-02-23 15:07:44 +0000573 def testCreateNonExistentFileForAppend(self):
574 if os.path.exists(TESTFN):
575 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000576
Thomas Wouterscf297e42007-02-23 15:07:44 +0000577 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000578 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +0000579
Thomas Wouterscf297e42007-02-23 15:07:44 +0000580 try:
581 zf = zipfile.ZipFile(TESTFN, 'a')
582 zf.writestr(filename, content)
583 zf.close()
584 except IOError:
585 self.fail('Could not append data to a non-existent zip file.')
586
587 self.assert_(os.path.exists(TESTFN))
588
589 zf = zipfile.ZipFile(TESTFN, 'r')
590 self.assertEqual(zf.read(filename), content)
591 zf.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000592
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000593 def testCloseErroneousFile(self):
594 # This test checks that the ZipFile constructor closes the file object
595 # it opens if there's an error in the file. If it doesn't, the traceback
596 # holds a reference to the ZipFile object and, indirectly, the file object.
597 # On Windows, this causes the os.unlink() call to fail because the
598 # underlying file is still open. This is SF bug #412214.
599 #
600 fp = open(TESTFN, "w")
601 fp.write("this is not a legal zip file\n")
602 fp.close()
603 try:
604 zf = zipfile.ZipFile(TESTFN)
605 except zipfile.BadZipfile:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000606 pass
607
608 def testIsZipErroneousFile(self):
609 # This test checks that the is_zipfile function correctly identifies
610 # a file that is not a zip file
611 fp = open(TESTFN, "w")
612 fp.write("this is not a legal zip file\n")
613 fp.close()
614 chk = zipfile.is_zipfile(TESTFN)
615 self.assert_(chk is False)
616
617 def testIsZipValidFile(self):
618 # This test checks that the is_zipfile function correctly identifies
619 # a file that is a zip file
620 zipf = zipfile.ZipFile(TESTFN, mode="w")
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000621 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000622 zipf.close()
623 chk = zipfile.is_zipfile(TESTFN)
624 self.assert_(chk is True)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000625
626 def testNonExistentFileRaisesIOError(self):
627 # make sure we don't raise an AttributeError when a partially-constructed
628 # ZipFile instance is finalized; this tests for regression on SF tracker
629 # bug #403871.
630
631 # The bug we're testing for caused an AttributeError to be raised
632 # when a ZipFile instance was created for a file that did not
633 # exist; the .fp member was not initialized but was needed by the
634 # __del__() method. Since the AttributeError is in the __del__(),
635 # it is ignored, but the user should be sufficiently annoyed by
636 # the message on the output that regression will be noticed
637 # quickly.
638 self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
639
640 def testClosedZipRaisesRuntimeError(self):
641 # Verify that testzip() doesn't swallow inappropriate exceptions.
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000642 data = io.BytesIO()
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000643 zipf = zipfile.ZipFile(data, mode="w")
644 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
645 zipf.close()
646
647 # This is correct; calling .read on a closed ZipFile should throw
648 # a RuntimeError, and so should calling .testzip. An earlier
649 # version of .testzip would swallow this exception (and any other)
650 # and report that the first file in the archive was corrupt.
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000651 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
652 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000653 self.assertRaises(RuntimeError, zipf.testzip)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000654 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Guido van Rossum814661e2007-07-18 22:07:29 +0000655 open(TESTFN, 'w').write('zipfile test data')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000656 self.assertRaises(RuntimeError, zipf.write, TESTFN)
657
658 def test_BadConstructorMode(self):
659 # Check that bad modes passed to ZipFile constructor are caught
660 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
661
662 def test_BadOpenMode(self):
663 # Check that bad modes passed to ZipFile.open are caught
664 zipf = zipfile.ZipFile(TESTFN, mode="w")
665 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
666 zipf.close()
667 zipf = zipfile.ZipFile(TESTFN, mode="r")
668 # read the data to make sure the file is there
669 zipf.read("foo.txt")
670 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
671 zipf.close()
672
673 def test_Read0(self):
674 # Check that calling read(0) on a ZipExtFile object returns an empty
675 # string and doesn't advance file pointer
676 zipf = zipfile.ZipFile(TESTFN, mode="w")
677 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
678 # read the data to make sure the file is there
679 f = zipf.open("foo.txt")
680 for i in range(FIXEDTEST_SIZE):
Guido van Rossum814661e2007-07-18 22:07:29 +0000681 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000682
Guido van Rossum814661e2007-07-18 22:07:29 +0000683 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000684 zipf.close()
685
686 def test_OpenNonexistentItem(self):
687 # Check that attempting to call open() for an item that doesn't
688 # exist in the archive raises a RuntimeError
689 zipf = zipfile.ZipFile(TESTFN, mode="w")
690 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
691
692 def test_BadCompressionMode(self):
693 # Check that bad compression methods passed to ZipFile.open are caught
694 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
695
696 def test_NullByteInFilename(self):
697 # Check that a filename containing a null byte is properly terminated
698 zipf = zipfile.ZipFile(TESTFN, mode="w")
Guido van Rossum814661e2007-07-18 22:07:29 +0000699 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000700 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000701
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000702 def test_StructSizes(self):
703 # check that ZIP internal structure sizes are calculated correctly
704 self.assertEqual(zipfile.sizeEndCentDir, 22)
705 self.assertEqual(zipfile.sizeCentralDir, 46)
706 self.assertEqual(zipfile.sizeEndCentDir64, 56)
707 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
708
709 def testComments(self):
710 # This test checks that comments on the archive are handled properly
711
712 # check default comment is empty
713 zipf = zipfile.ZipFile(TESTFN, mode="w")
714 self.assertEqual(zipf.comment, b'')
715 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
716 zipf.close()
717 zipfr = zipfile.ZipFile(TESTFN, mode="r")
718 self.assertEqual(zipfr.comment, b'')
719 zipfr.close()
720
721 # check a simple short comment
722 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
723 zipf = zipfile.ZipFile(TESTFN, mode="w")
724 zipf.comment = comment
725 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
726 zipf.close()
727 zipfr = zipfile.ZipFile(TESTFN, mode="r")
728 self.assertEqual(zipfr.comment, comment)
729 zipfr.close()
730
731 # check a comment of max length
732 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
733 comment2 = comment2.encode("ascii")
734 zipf = zipfile.ZipFile(TESTFN, mode="w")
735 zipf.comment = comment2
736 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
737 zipf.close()
738 zipfr = zipfile.ZipFile(TESTFN, mode="r")
739 self.assertEqual(zipfr.comment, comment2)
740 zipfr.close()
741
742 # check a comment that is too long is truncated
743 zipf = zipfile.ZipFile(TESTFN, mode="w")
744 zipf.comment = comment2 + b'oops'
745 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
746 zipf.close()
747 zipfr = zipfile.ZipFile(TESTFN, mode="r")
748 self.assertEqual(zipfr.comment, comment2)
749 zipfr.close()
750
Guido van Rossumd8faa362007-04-27 19:54:29 +0000751 def tearDown(self):
752 support.unlink(TESTFN)
753 support.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000754
755class DecryptionTests(unittest.TestCase):
756 # This test checks that ZIP decryption works. Since the library does not
757 # support encryption at the moment, we use a pre-generated encrypted
758 # ZIP file
759
760 data = (
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000761 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
762 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
763 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
764 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
765 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
766 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
767 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +0000768 data2 = (
769 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
770 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
771 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
772 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
773 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
774 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
775 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
776 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +0000777
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000778 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +0000779 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +0000780
781 def setUp(self):
782 fp = open(TESTFN, "wb")
783 fp.write(self.data)
784 fp.close()
785 self.zip = zipfile.ZipFile(TESTFN, "r")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000786 fp = open(TESTFN2, "wb")
787 fp.write(self.data2)
788 fp.close()
789 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000790
791 def tearDown(self):
792 self.zip.close()
793 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +0000794 self.zip2.close()
795 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000796
797 def testNoPassword(self):
798 # Reading the encrypted file without password
799 # must generate a RunTime exception
800 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000801 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000802
803 def testBadPassword(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000804 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000805 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000806 self.zip2.setpassword(b"perl")
807 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000808
Thomas Wouterscf297e42007-02-23 15:07:44 +0000809 def testGoodPassword(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000810 self.zip.setpassword(b"python")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000811 self.assertEquals(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +0000812 self.zip2.setpassword(b"12345")
813 self.assertEquals(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000814
Guido van Rossumd8faa362007-04-27 19:54:29 +0000815
816class TestsWithRandomBinaryFiles(unittest.TestCase):
817 def setUp(self):
818 datacount = randint(16, 64)*1024 + randint(1, 1024)
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000819 self.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
820 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000821
822 # Make a source file with some lines
823 fp = open(TESTFN, "wb")
824 fp.write(self.data)
825 fp.close()
826
827 def tearDown(self):
828 support.unlink(TESTFN)
829 support.unlink(TESTFN2)
830
831 def makeTestArchive(self, f, compression):
832 # Create the ZIP archive
833 zipfp = zipfile.ZipFile(f, "w", compression)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000834 zipfp.write(TESTFN, "another.name")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000835 zipfp.write(TESTFN, TESTFN)
836 zipfp.close()
837
838 def zipTest(self, f, compression):
839 self.makeTestArchive(f, compression)
840
841 # Read the ZIP archive
842 zipfp = zipfile.ZipFile(f, "r", compression)
843 testdata = zipfp.read(TESTFN)
844 self.assertEqual(len(testdata), len(self.data))
845 self.assertEqual(testdata, self.data)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000846 self.assertEqual(zipfp.read("another.name"), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000847 zipfp.close()
848
849 def testStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000850 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000851 self.zipTest(f, zipfile.ZIP_STORED)
852
853 def zipOpenTest(self, f, compression):
854 self.makeTestArchive(f, compression)
855
856 # Read the ZIP archive
857 zipfp = zipfile.ZipFile(f, "r", compression)
858 zipdata1 = []
859 zipopen1 = zipfp.open(TESTFN)
860 while 1:
861 read_data = zipopen1.read(256)
862 if not read_data:
863 break
864 zipdata1.append(read_data)
865
866 zipdata2 = []
Skip Montanaro7a98be22007-08-16 14:35:24 +0000867 zipopen2 = zipfp.open("another.name")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000868 while 1:
869 read_data = zipopen2.read(256)
870 if not read_data:
871 break
872 zipdata2.append(read_data)
873
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000874 testdata1 = b''.join(zipdata1)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000875 self.assertEqual(len(testdata1), len(self.data))
876 self.assertEqual(testdata1, self.data)
877
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000878 testdata2 = b''.join(zipdata2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000879 self.assertEqual(len(testdata1), len(self.data))
880 self.assertEqual(testdata1, self.data)
881 zipfp.close()
882
883 def testOpenStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000884 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000885 self.zipOpenTest(f, zipfile.ZIP_STORED)
886
887 def zipRandomOpenTest(self, f, compression):
888 self.makeTestArchive(f, compression)
889
890 # Read the ZIP archive
891 zipfp = zipfile.ZipFile(f, "r", compression)
892 zipdata1 = []
893 zipopen1 = zipfp.open(TESTFN)
894 while 1:
895 read_data = zipopen1.read(randint(1, 1024))
896 if not read_data:
897 break
898 zipdata1.append(read_data)
899
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000900 testdata = b''.join(zipdata1)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000901 self.assertEqual(len(testdata), len(self.data))
902 self.assertEqual(testdata, self.data)
903 zipfp.close()
904
905 def testRandomOpenStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000906 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000907 self.zipRandomOpenTest(f, zipfile.ZIP_STORED)
908
909class TestsWithMultipleOpens(unittest.TestCase):
910 def setUp(self):
911 # Create the ZIP archive
912 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED)
913 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
914 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
915 zipfp.close()
916
917 def testSameFile(self):
918 # Verify that (when the ZipFile is in control of creating file objects)
919 # multiple open() calls can be made without interfering with each other.
920 zipf = zipfile.ZipFile(TESTFN2, mode="r")
921 zopen1 = zipf.open('ones')
922 zopen2 = zipf.open('ones')
923 data1 = zopen1.read(500)
924 data2 = zopen2.read(500)
925 data1 += zopen1.read(500)
926 data2 += zopen2.read(500)
927 self.assertEqual(data1, data2)
928 zipf.close()
929
930 def testDifferentFile(self):
931 # Verify that (when the ZipFile is in control of creating file objects)
932 # multiple open() calls can be made without interfering with each other.
933 zipf = zipfile.ZipFile(TESTFN2, mode="r")
934 zopen1 = zipf.open('ones')
935 zopen2 = zipf.open('twos')
936 data1 = zopen1.read(500)
937 data2 = zopen2.read(500)
938 data1 += zopen1.read(500)
939 data2 += zopen2.read(500)
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000940 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
941 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000942 zipf.close()
943
944 def testInterleaved(self):
945 # Verify that (when the ZipFile is in control of creating file objects)
946 # multiple open() calls can be made without interfering with each other.
947 zipf = zipfile.ZipFile(TESTFN2, mode="r")
948 zopen1 = zipf.open('ones')
949 data1 = zopen1.read(500)
950 zopen2 = zipf.open('twos')
951 data2 = zopen2.read(500)
952 data1 += zopen1.read(500)
953 data2 += zopen2.read(500)
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000954 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
955 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000956 zipf.close()
957
958 def tearDown(self):
959 os.remove(TESTFN2)
960
961
962class UniversalNewlineTests(unittest.TestCase):
963 def setUp(self):
Guido van Rossum9c627722007-08-27 18:31:48 +0000964 self.line_gen = [bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000965 for i in range(FIXEDTEST_SIZE)]
Guido van Rossumd8faa362007-04-27 19:54:29 +0000966 self.seps = ('\r', '\r\n', '\n')
967 self.arcdata, self.arcfiles = {}, {}
968 for n, s in enumerate(self.seps):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000969 b = s.encode("ascii")
970 self.arcdata[s] = b.join(self.line_gen) + b
Guido van Rossumd8faa362007-04-27 19:54:29 +0000971 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000972 f = open(self.arcfiles[s], "wb")
973 try:
974 f.write(self.arcdata[s])
975 finally:
976 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000977
978 def makeTestArchive(self, f, compression):
979 # Create the ZIP archive
980 zipfp = zipfile.ZipFile(f, "w", compression)
981 for fn in self.arcfiles.values():
982 zipfp.write(fn, fn)
983 zipfp.close()
984
985 def readTest(self, f, compression):
986 self.makeTestArchive(f, compression)
987
988 # Read the ZIP archive
989 zipfp = zipfile.ZipFile(f, "r")
990 for sep, fn in self.arcfiles.items():
991 zipdata = zipfp.open(fn, "rU").read()
992 self.assertEqual(self.arcdata[sep], zipdata)
993
994 zipfp.close()
995
996 def readlineTest(self, f, compression):
997 self.makeTestArchive(f, compression)
998
999 # Read the ZIP archive
1000 zipfp = zipfile.ZipFile(f, "r")
1001 for sep, fn in self.arcfiles.items():
1002 zipopen = zipfp.open(fn, "rU")
1003 for line in self.line_gen:
1004 linedata = zipopen.readline()
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001005 self.assertEqual(linedata, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001006
1007 zipfp.close()
1008
1009 def readlinesTest(self, f, compression):
1010 self.makeTestArchive(f, compression)
1011
1012 # Read the ZIP archive
1013 zipfp = zipfile.ZipFile(f, "r")
1014 for sep, fn in self.arcfiles.items():
1015 ziplines = zipfp.open(fn, "rU").readlines()
1016 for line, zipline in zip(self.line_gen, ziplines):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001017 self.assertEqual(zipline, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001018
1019 zipfp.close()
1020
1021 def iterlinesTest(self, f, compression):
1022 self.makeTestArchive(f, compression)
1023
1024 # Read the ZIP archive
1025 zipfp = zipfile.ZipFile(f, "r")
1026 for sep, fn in self.arcfiles.items():
1027 for line, zipline in zip(self.line_gen, zipfp.open(fn, "rU")):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001028 self.assertEqual(zipline, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001029
1030 zipfp.close()
1031
1032 def testReadStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001033 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001034 self.readTest(f, zipfile.ZIP_STORED)
1035
1036 def testReadlineStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001037 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001038 self.readlineTest(f, zipfile.ZIP_STORED)
1039
1040 def testReadlinesStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001041 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001042 self.readlinesTest(f, zipfile.ZIP_STORED)
1043
1044 def testIterlinesStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001045 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001046 self.iterlinesTest(f, zipfile.ZIP_STORED)
1047
1048 if zlib:
1049 def testReadDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001050 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001051 self.readTest(f, zipfile.ZIP_DEFLATED)
1052
1053 def testReadlineDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001054 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001055 self.readlineTest(f, zipfile.ZIP_DEFLATED)
1056
1057 def testReadlinesDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001058 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001059 self.readlinesTest(f, zipfile.ZIP_DEFLATED)
1060
1061 def testIterlinesDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001062 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001063 self.iterlinesTest(f, zipfile.ZIP_DEFLATED)
1064
1065 def tearDown(self):
1066 for sep, fn in self.arcfiles.items():
1067 os.remove(fn)
1068 support.unlink(TESTFN)
1069 support.unlink(TESTFN2)
1070
1071
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001072def test_main():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001073 run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
1074 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
1075 UniversalNewlineTests, TestsWithRandomBinaryFiles)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001076
1077if __name__ == "__main__":
1078 test_main()