blob: 9e565fb153f89930db387c21daefd716baf61b33 [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
624 fp = open(TESTFN, "w")
625 fp.write("this is not a legal zip file\n")
626 fp.close()
627 chk = zipfile.is_zipfile(TESTFN)
628 self.assert_(chk is False)
629
630 def testIsZipValidFile(self):
631 # This test checks that the is_zipfile function correctly identifies
632 # a file that is a zip file
633 zipf = zipfile.ZipFile(TESTFN, mode="w")
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000634 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000635 zipf.close()
636 chk = zipfile.is_zipfile(TESTFN)
637 self.assert_(chk is True)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000638
639 def testNonExistentFileRaisesIOError(self):
640 # make sure we don't raise an AttributeError when a partially-constructed
641 # ZipFile instance is finalized; this tests for regression on SF tracker
642 # bug #403871.
643
644 # The bug we're testing for caused an AttributeError to be raised
645 # when a ZipFile instance was created for a file that did not
646 # exist; the .fp member was not initialized but was needed by the
647 # __del__() method. Since the AttributeError is in the __del__(),
648 # it is ignored, but the user should be sufficiently annoyed by
649 # the message on the output that regression will be noticed
650 # quickly.
651 self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
652
653 def testClosedZipRaisesRuntimeError(self):
654 # Verify that testzip() doesn't swallow inappropriate exceptions.
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000655 data = io.BytesIO()
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000656 zipf = zipfile.ZipFile(data, mode="w")
657 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
658 zipf.close()
659
660 # This is correct; calling .read on a closed ZipFile should throw
661 # a RuntimeError, and so should calling .testzip. An earlier
662 # version of .testzip would swallow this exception (and any other)
663 # and report that the first file in the archive was corrupt.
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000664 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
665 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000666 self.assertRaises(RuntimeError, zipf.testzip)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000667 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Guido van Rossum814661e2007-07-18 22:07:29 +0000668 open(TESTFN, 'w').write('zipfile test data')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000669 self.assertRaises(RuntimeError, zipf.write, TESTFN)
670
671 def test_BadConstructorMode(self):
672 # Check that bad modes passed to ZipFile constructor are caught
673 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
674
675 def test_BadOpenMode(self):
676 # Check that bad modes passed to ZipFile.open are caught
677 zipf = zipfile.ZipFile(TESTFN, mode="w")
678 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
679 zipf.close()
680 zipf = zipfile.ZipFile(TESTFN, mode="r")
681 # read the data to make sure the file is there
682 zipf.read("foo.txt")
683 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
684 zipf.close()
685
686 def test_Read0(self):
687 # Check that calling read(0) on a ZipExtFile object returns an empty
688 # string and doesn't advance file pointer
689 zipf = zipfile.ZipFile(TESTFN, mode="w")
690 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
691 # read the data to make sure the file is there
692 f = zipf.open("foo.txt")
693 for i in range(FIXEDTEST_SIZE):
Guido van Rossum814661e2007-07-18 22:07:29 +0000694 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000695
Guido van Rossum814661e2007-07-18 22:07:29 +0000696 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000697 zipf.close()
698
699 def test_OpenNonexistentItem(self):
700 # Check that attempting to call open() for an item that doesn't
701 # exist in the archive raises a RuntimeError
702 zipf = zipfile.ZipFile(TESTFN, mode="w")
703 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
704
705 def test_BadCompressionMode(self):
706 # Check that bad compression methods passed to ZipFile.open are caught
707 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
708
709 def test_NullByteInFilename(self):
710 # Check that a filename containing a null byte is properly terminated
711 zipf = zipfile.ZipFile(TESTFN, mode="w")
Guido van Rossum814661e2007-07-18 22:07:29 +0000712 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000713 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000714
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000715 def test_StructSizes(self):
716 # check that ZIP internal structure sizes are calculated correctly
717 self.assertEqual(zipfile.sizeEndCentDir, 22)
718 self.assertEqual(zipfile.sizeCentralDir, 46)
719 self.assertEqual(zipfile.sizeEndCentDir64, 56)
720 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
721
722 def testComments(self):
723 # This test checks that comments on the archive are handled properly
724
725 # check default comment is empty
726 zipf = zipfile.ZipFile(TESTFN, mode="w")
727 self.assertEqual(zipf.comment, b'')
728 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
729 zipf.close()
730 zipfr = zipfile.ZipFile(TESTFN, mode="r")
731 self.assertEqual(zipfr.comment, b'')
732 zipfr.close()
733
734 # check a simple short comment
735 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
736 zipf = zipfile.ZipFile(TESTFN, mode="w")
737 zipf.comment = comment
738 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
739 zipf.close()
740 zipfr = zipfile.ZipFile(TESTFN, mode="r")
741 self.assertEqual(zipfr.comment, comment)
742 zipfr.close()
743
744 # check a comment of max length
745 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
746 comment2 = comment2.encode("ascii")
747 zipf = zipfile.ZipFile(TESTFN, mode="w")
748 zipf.comment = comment2
749 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
750 zipf.close()
751 zipfr = zipfile.ZipFile(TESTFN, mode="r")
752 self.assertEqual(zipfr.comment, comment2)
753 zipfr.close()
754
755 # check a comment that is too long is truncated
756 zipf = zipfile.ZipFile(TESTFN, mode="w")
757 zipf.comment = comment2 + b'oops'
758 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
759 zipf.close()
760 zipfr = zipfile.ZipFile(TESTFN, mode="r")
761 self.assertEqual(zipfr.comment, comment2)
762 zipfr.close()
763
Guido van Rossumd8faa362007-04-27 19:54:29 +0000764 def tearDown(self):
765 support.unlink(TESTFN)
766 support.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000767
768class DecryptionTests(unittest.TestCase):
769 # This test checks that ZIP decryption works. Since the library does not
770 # support encryption at the moment, we use a pre-generated encrypted
771 # ZIP file
772
773 data = (
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000774 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
775 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
776 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
777 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
778 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
779 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
780 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +0000781 data2 = (
782 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
783 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
784 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
785 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
786 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
787 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
788 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
789 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +0000790
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000791 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +0000792 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +0000793
794 def setUp(self):
795 fp = open(TESTFN, "wb")
796 fp.write(self.data)
797 fp.close()
798 self.zip = zipfile.ZipFile(TESTFN, "r")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000799 fp = open(TESTFN2, "wb")
800 fp.write(self.data2)
801 fp.close()
802 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000803
804 def tearDown(self):
805 self.zip.close()
806 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +0000807 self.zip2.close()
808 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000809
810 def testNoPassword(self):
811 # Reading the encrypted file without password
812 # must generate a RunTime exception
813 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000814 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000815
816 def testBadPassword(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000817 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000818 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000819 self.zip2.setpassword(b"perl")
820 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000821
Thomas Wouterscf297e42007-02-23 15:07:44 +0000822 def testGoodPassword(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000823 self.zip.setpassword(b"python")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000824 self.assertEquals(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +0000825 self.zip2.setpassword(b"12345")
826 self.assertEquals(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000827
Guido van Rossumd8faa362007-04-27 19:54:29 +0000828
829class TestsWithRandomBinaryFiles(unittest.TestCase):
830 def setUp(self):
831 datacount = randint(16, 64)*1024 + randint(1, 1024)
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000832 self.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
833 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000834
835 # Make a source file with some lines
836 fp = open(TESTFN, "wb")
837 fp.write(self.data)
838 fp.close()
839
840 def tearDown(self):
841 support.unlink(TESTFN)
842 support.unlink(TESTFN2)
843
844 def makeTestArchive(self, f, compression):
845 # Create the ZIP archive
846 zipfp = zipfile.ZipFile(f, "w", compression)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000847 zipfp.write(TESTFN, "another.name")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000848 zipfp.write(TESTFN, TESTFN)
849 zipfp.close()
850
851 def zipTest(self, f, compression):
852 self.makeTestArchive(f, compression)
853
854 # Read the ZIP archive
855 zipfp = zipfile.ZipFile(f, "r", compression)
856 testdata = zipfp.read(TESTFN)
857 self.assertEqual(len(testdata), len(self.data))
858 self.assertEqual(testdata, self.data)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000859 self.assertEqual(zipfp.read("another.name"), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000860 zipfp.close()
861
862 def testStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000863 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000864 self.zipTest(f, zipfile.ZIP_STORED)
865
866 def zipOpenTest(self, f, compression):
867 self.makeTestArchive(f, compression)
868
869 # Read the ZIP archive
870 zipfp = zipfile.ZipFile(f, "r", compression)
871 zipdata1 = []
872 zipopen1 = zipfp.open(TESTFN)
873 while 1:
874 read_data = zipopen1.read(256)
875 if not read_data:
876 break
877 zipdata1.append(read_data)
878
879 zipdata2 = []
Skip Montanaro7a98be22007-08-16 14:35:24 +0000880 zipopen2 = zipfp.open("another.name")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000881 while 1:
882 read_data = zipopen2.read(256)
883 if not read_data:
884 break
885 zipdata2.append(read_data)
886
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000887 testdata1 = b''.join(zipdata1)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000888 self.assertEqual(len(testdata1), len(self.data))
889 self.assertEqual(testdata1, self.data)
890
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000891 testdata2 = b''.join(zipdata2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000892 self.assertEqual(len(testdata1), len(self.data))
893 self.assertEqual(testdata1, self.data)
894 zipfp.close()
895
896 def testOpenStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000897 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000898 self.zipOpenTest(f, zipfile.ZIP_STORED)
899
900 def zipRandomOpenTest(self, f, compression):
901 self.makeTestArchive(f, compression)
902
903 # Read the ZIP archive
904 zipfp = zipfile.ZipFile(f, "r", compression)
905 zipdata1 = []
906 zipopen1 = zipfp.open(TESTFN)
907 while 1:
908 read_data = zipopen1.read(randint(1, 1024))
909 if not read_data:
910 break
911 zipdata1.append(read_data)
912
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000913 testdata = b''.join(zipdata1)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000914 self.assertEqual(len(testdata), len(self.data))
915 self.assertEqual(testdata, self.data)
916 zipfp.close()
917
918 def testRandomOpenStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000919 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000920 self.zipRandomOpenTest(f, zipfile.ZIP_STORED)
921
922class TestsWithMultipleOpens(unittest.TestCase):
923 def setUp(self):
924 # Create the ZIP archive
925 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED)
926 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
927 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
928 zipfp.close()
929
930 def testSameFile(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('ones')
936 data1 = zopen1.read(500)
937 data2 = zopen2.read(500)
938 data1 += zopen1.read(500)
939 data2 += zopen2.read(500)
940 self.assertEqual(data1, data2)
941 zipf.close()
942
943 def testDifferentFile(self):
944 # Verify that (when the ZipFile is in control of creating file objects)
945 # multiple open() calls can be made without interfering with each other.
946 zipf = zipfile.ZipFile(TESTFN2, mode="r")
947 zopen1 = zipf.open('ones')
948 zopen2 = zipf.open('twos')
949 data1 = zopen1.read(500)
950 data2 = zopen2.read(500)
951 data1 += zopen1.read(500)
952 data2 += zopen2.read(500)
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000953 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
954 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000955 zipf.close()
956
957 def testInterleaved(self):
958 # Verify that (when the ZipFile is in control of creating file objects)
959 # multiple open() calls can be made without interfering with each other.
960 zipf = zipfile.ZipFile(TESTFN2, mode="r")
961 zopen1 = zipf.open('ones')
962 data1 = zopen1.read(500)
963 zopen2 = zipf.open('twos')
964 data2 = zopen2.read(500)
965 data1 += zopen1.read(500)
966 data2 += zopen2.read(500)
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000967 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
968 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000969 zipf.close()
970
971 def tearDown(self):
972 os.remove(TESTFN2)
973
974
975class UniversalNewlineTests(unittest.TestCase):
976 def setUp(self):
Guido van Rossum9c627722007-08-27 18:31:48 +0000977 self.line_gen = [bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000978 for i in range(FIXEDTEST_SIZE)]
Guido van Rossumd8faa362007-04-27 19:54:29 +0000979 self.seps = ('\r', '\r\n', '\n')
980 self.arcdata, self.arcfiles = {}, {}
981 for n, s in enumerate(self.seps):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000982 b = s.encode("ascii")
983 self.arcdata[s] = b.join(self.line_gen) + b
Guido van Rossumd8faa362007-04-27 19:54:29 +0000984 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000985 f = open(self.arcfiles[s], "wb")
986 try:
987 f.write(self.arcdata[s])
988 finally:
989 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000990
991 def makeTestArchive(self, f, compression):
992 # Create the ZIP archive
993 zipfp = zipfile.ZipFile(f, "w", compression)
994 for fn in self.arcfiles.values():
995 zipfp.write(fn, fn)
996 zipfp.close()
997
998 def readTest(self, f, compression):
999 self.makeTestArchive(f, compression)
1000
1001 # Read the ZIP archive
1002 zipfp = zipfile.ZipFile(f, "r")
1003 for sep, fn in self.arcfiles.items():
1004 zipdata = zipfp.open(fn, "rU").read()
1005 self.assertEqual(self.arcdata[sep], zipdata)
1006
1007 zipfp.close()
1008
1009 def readlineTest(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 zipopen = zipfp.open(fn, "rU")
1016 for line in self.line_gen:
1017 linedata = zipopen.readline()
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001018 self.assertEqual(linedata, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001019
1020 zipfp.close()
1021
1022 def readlinesTest(self, f, compression):
1023 self.makeTestArchive(f, compression)
1024
1025 # Read the ZIP archive
1026 zipfp = zipfile.ZipFile(f, "r")
1027 for sep, fn in self.arcfiles.items():
1028 ziplines = zipfp.open(fn, "rU").readlines()
1029 for line, zipline in zip(self.line_gen, ziplines):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001030 self.assertEqual(zipline, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001031
1032 zipfp.close()
1033
1034 def iterlinesTest(self, f, compression):
1035 self.makeTestArchive(f, compression)
1036
1037 # Read the ZIP archive
1038 zipfp = zipfile.ZipFile(f, "r")
1039 for sep, fn in self.arcfiles.items():
1040 for line, zipline in zip(self.line_gen, zipfp.open(fn, "rU")):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001041 self.assertEqual(zipline, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001042
1043 zipfp.close()
1044
1045 def testReadStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001046 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001047 self.readTest(f, zipfile.ZIP_STORED)
1048
1049 def testReadlineStored(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.readlineTest(f, zipfile.ZIP_STORED)
1052
1053 def testReadlinesStored(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.readlinesTest(f, zipfile.ZIP_STORED)
1056
1057 def testIterlinesStored(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.iterlinesTest(f, zipfile.ZIP_STORED)
1060
1061 if zlib:
1062 def testReadDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001063 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001064 self.readTest(f, zipfile.ZIP_DEFLATED)
1065
1066 def testReadlineDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001067 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001068 self.readlineTest(f, zipfile.ZIP_DEFLATED)
1069
1070 def testReadlinesDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001071 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001072 self.readlinesTest(f, zipfile.ZIP_DEFLATED)
1073
1074 def testIterlinesDeflated(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.iterlinesTest(f, zipfile.ZIP_DEFLATED)
1077
1078 def tearDown(self):
1079 for sep, fn in self.arcfiles.items():
1080 os.remove(fn)
1081 support.unlink(TESTFN)
1082 support.unlink(TESTFN2)
1083
1084
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001085def test_main():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001086 run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
1087 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
1088 UniversalNewlineTests, TestsWithRandomBinaryFiles)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001089
1090if __name__ == "__main__":
1091 test_main()