blob: c69892b2bd2f0d935cad302dd53d65be877a5135 [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
Guido van Rossumd8faa362007-04-27 19:54:29 +000011import test.test_support as support
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000012from test.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
128 def zipRandomOpenTest(self, f, compression):
129 self.makeTestArchive(f, compression)
130
131 # Read the ZIP archive
132 zipfp = zipfile.ZipFile(f, "r", compression)
133 zipdata1 = []
134 zipopen1 = zipfp.open(TESTFN)
135 while 1:
136 read_data = zipopen1.read(randint(1, 1024))
137 if not read_data:
138 break
139 zipdata1.append(read_data)
140
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000141 self.assertEqual(b''.join(zipdata1), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000142 zipfp.close()
143
144 def testRandomOpenStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000145 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000146 self.zipRandomOpenTest(f, zipfile.ZIP_STORED)
147
148 def zipReadlineTest(self, f, compression):
149 self.makeTestArchive(f, compression)
150
151 # Read the ZIP archive
152 zipfp = zipfile.ZipFile(f, "r")
153 zipopen = zipfp.open(TESTFN)
154 for line in self.line_gen:
155 linedata = zipopen.readline()
156 self.assertEqual(linedata, line + '\n')
157
158 zipfp.close()
159
160 def zipReadlinesTest(self, f, compression):
161 self.makeTestArchive(f, compression)
162
163 # Read the ZIP archive
164 zipfp = zipfile.ZipFile(f, "r")
165 ziplines = zipfp.open(TESTFN).readlines()
166 for line, zipline in zip(self.line_gen, ziplines):
167 self.assertEqual(zipline, line + '\n')
168
169 zipfp.close()
170
171 def zipIterlinesTest(self, f, compression):
172 self.makeTestArchive(f, compression)
173
174 # Read the ZIP archive
175 zipfp = zipfile.ZipFile(f, "r")
176 for line, zipline in zip(self.line_gen, zipfp.open(TESTFN)):
177 self.assertEqual(zipline, line + '\n')
178
179 zipfp.close()
180
181 def testReadlineStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000182 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000183 self.zipReadlineTest(f, zipfile.ZIP_STORED)
184
185 def testReadlinesStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000186 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000187 self.zipReadlinesTest(f, zipfile.ZIP_STORED)
188
189 def testIterlinesStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000190 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000191 self.zipIterlinesTest(f, zipfile.ZIP_STORED)
192
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000193 if zlib:
194 def testDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000195 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000196 self.zipTest(f, zipfile.ZIP_DEFLATED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000197
Guido van Rossumd8faa362007-04-27 19:54:29 +0000198 def testOpenDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000199 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000200 self.zipOpenTest(f, zipfile.ZIP_DEFLATED)
201
202 def testRandomOpenDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000203 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000204 self.zipRandomOpenTest(f, zipfile.ZIP_DEFLATED)
205
206 def testReadlineDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000207 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000208 self.zipReadlineTest(f, zipfile.ZIP_DEFLATED)
209
210 def testReadlinesDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000211 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000212 self.zipReadlinesTest(f, zipfile.ZIP_DEFLATED)
213
214 def testIterlinesDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000215 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000216 self.zipIterlinesTest(f, zipfile.ZIP_DEFLATED)
217
218 def testLowCompression(self):
219 # Checks for cases where compressed data is larger than original
220 # Create the ZIP archive
221 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED)
222 zipfp.writestr("strfile", '12')
223 zipfp.close()
224
225 # Get an open object for strfile
226 zipfp = zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_DEFLATED)
227 openobj = zipfp.open("strfile")
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000228 self.assertEqual(openobj.read(1), b'1')
229 self.assertEqual(openobj.read(1), b'2')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000230
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000231 def testAbsoluteArcnames(self):
232 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
233 zipfp.write(TESTFN, "/absolute")
234 zipfp.close()
235
236 zipfp = zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED)
237 self.assertEqual(zipfp.namelist(), ["absolute"])
238 zipfp.close()
Tim Peters32cbc962006-02-20 21:42:18 +0000239
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000240 def testAppendToZipFile(self):
241 # Test appending to an existing zipfile
242 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
243 zipfp.write(TESTFN, TESTFN)
244 zipfp.close()
245 zipfp = zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED)
246 zipfp.writestr("strfile", self.data)
247 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
248 zipfp.close()
249
250 def testAppendToNonZipFile(self):
251 # Test appending to an existing file that is not a zipfile
252 # NOTE: this test fails if len(d) < 22 because of the first
253 # line "fpin.seek(-22, 2)" in _EndRecData
Guido van Rossum9c627722007-08-27 18:31:48 +0000254 d = b'I am not a ZipFile!'*10
Guido van Rossum814661e2007-07-18 22:07:29 +0000255 f = open(TESTFN2, 'wb')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000256 f.write(d)
257 f.close()
258 zipfp = zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED)
259 zipfp.write(TESTFN, TESTFN)
260 zipfp.close()
261
Guido van Rossum814661e2007-07-18 22:07:29 +0000262 f = open(TESTFN2, 'rb')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000263 f.seek(len(d))
264 zipfp = zipfile.ZipFile(f, "r")
265 self.assertEqual(zipfp.namelist(), [TESTFN])
266 zipfp.close()
267 f.close()
268
269 def test_WriteDefaultName(self):
270 # Check that calling ZipFile.write without arcname specified produces the expected result
271 zipfp = zipfile.ZipFile(TESTFN2, "w")
272 zipfp.write(TESTFN)
Guido van Rossum814661e2007-07-18 22:07:29 +0000273 self.assertEqual(zipfp.read(TESTFN), open(TESTFN, "rb").read())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000274 zipfp.close()
275
276 def test_PerFileCompression(self):
277 # Check that files within a Zip archive can have different compression options
278 zipfp = zipfile.ZipFile(TESTFN2, "w")
279 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
280 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
281 sinfo = zipfp.getinfo('storeme')
282 dinfo = zipfp.getinfo('deflateme')
283 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
284 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
285 zipfp.close()
286
287 def test_WriteToReadonly(self):
288 # Check that trying to call write() on a readonly ZipFile object
289 # raises a RuntimeError
290 zipf = zipfile.ZipFile(TESTFN2, mode="w")
291 zipf.writestr("somefile.txt", "bogus")
292 zipf.close()
293 zipf = zipfile.ZipFile(TESTFN2, mode="r")
294 self.assertRaises(RuntimeError, zipf.write, TESTFN)
295 zipf.close()
296
Christian Heimes790c8232008-01-07 21:14:23 +0000297 def testExtract(self):
298 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
299 for fpath, fdata in SMALL_TEST_DATA:
300 zipfp.writestr(fpath, fdata)
301 zipfp.close()
302
303 zipfp = zipfile.ZipFile(TESTFN2, "r")
304 for fpath, fdata in SMALL_TEST_DATA:
305 writtenfile = zipfp.extract(fpath)
306
307 # make sure it was written to the right place
308 if os.path.isabs(fpath):
309 correctfile = os.path.join(os.getcwd(), fpath[1:])
310 else:
311 correctfile = os.path.join(os.getcwd(), fpath)
Christian Heimesaf98da12008-01-27 15:18:18 +0000312 correctfile = os.path.normpath(correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000313
314 self.assertEqual(writtenfile, correctfile)
315
316 # make sure correct data is in correct file
317 self.assertEqual(fdata.encode(), open(writtenfile, "rb").read())
318
319 os.remove(writtenfile)
320
321 zipfp.close()
322
323 # remove the test file subdirectories
324 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
325
326 def testExtractAll(self):
327 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
328 for fpath, fdata in SMALL_TEST_DATA:
329 zipfp.writestr(fpath, fdata)
330 zipfp.close()
331
332 zipfp = zipfile.ZipFile(TESTFN2, "r")
333 zipfp.extractall()
334 for fpath, fdata in SMALL_TEST_DATA:
335 if os.path.isabs(fpath):
336 outfile = os.path.join(os.getcwd(), fpath[1:])
337 else:
338 outfile = os.path.join(os.getcwd(), fpath)
339
340 self.assertEqual(fdata.encode(), open(outfile, "rb").read())
341
342 os.remove(outfile)
343
344 zipfp.close()
345
346 # remove the test file subdirectories
347 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
348
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000349 def tearDown(self):
350 os.remove(TESTFN)
351 os.remove(TESTFN2)
352
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000353class TestZip64InSmallFiles(unittest.TestCase):
354 # These tests test the ZIP64 functionality without using large files,
355 # see test_zipfile64 for proper tests.
356
357 def setUp(self):
358 self._limit = zipfile.ZIP64_LIMIT
359 zipfile.ZIP64_LIMIT = 5
360
Guido van Rossum9c627722007-08-27 18:31:48 +0000361 line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000362 for i in range(0, FIXEDTEST_SIZE))
363 self.data = b'\n'.join(line_gen)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000364
365 # Make a source file with some lines
366 fp = open(TESTFN, "wb")
367 fp.write(self.data)
368 fp.close()
369
370 def largeFileExceptionTest(self, f, compression):
371 zipfp = zipfile.ZipFile(f, "w", compression)
372 self.assertRaises(zipfile.LargeZipFile,
Skip Montanaro7a98be22007-08-16 14:35:24 +0000373 zipfp.write, TESTFN, "another.name")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000374 zipfp.close()
375
376 def largeFileExceptionTest2(self, f, compression):
377 zipfp = zipfile.ZipFile(f, "w", compression)
378 self.assertRaises(zipfile.LargeZipFile,
Skip Montanaro7a98be22007-08-16 14:35:24 +0000379 zipfp.writestr, "another.name", self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000380 zipfp.close()
381
382 def testLargeFileException(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000383 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000384 self.largeFileExceptionTest(f, zipfile.ZIP_STORED)
385 self.largeFileExceptionTest2(f, zipfile.ZIP_STORED)
386
387 def zipTest(self, f, compression):
388 # Create the ZIP archive
389 zipfp = zipfile.ZipFile(f, "w", compression, allowZip64=True)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000390 zipfp.write(TESTFN, "another.name")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000391 zipfp.write(TESTFN, TESTFN)
392 zipfp.writestr("strfile", self.data)
393 zipfp.close()
394
395 # Read the ZIP archive
396 zipfp = zipfile.ZipFile(f, "r", compression)
397 self.assertEqual(zipfp.read(TESTFN), self.data)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000398 self.assertEqual(zipfp.read("another.name"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000399 self.assertEqual(zipfp.read("strfile"), self.data)
400
401 # Print the ZIP directory
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000402 fp = io.StringIO()
403 zipfp.printdir(fp)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000404
405 directory = fp.getvalue()
406 lines = directory.splitlines()
407 self.assertEquals(len(lines), 4) # Number of files + header
408
409 self.assert_('File Name' in lines[0])
410 self.assert_('Modified' in lines[0])
411 self.assert_('Size' in lines[0])
412
413 fn, date, time, size = lines[1].split()
414 self.assertEquals(fn, 'another.name')
415 # XXX: timestamp is not tested
416 self.assertEquals(size, str(len(self.data)))
417
418 # Check the namelist
419 names = zipfp.namelist()
420 self.assertEquals(len(names), 3)
421 self.assert_(TESTFN in names)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000422 self.assert_("another.name" in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000423 self.assert_("strfile" in names)
424
425 # Check infolist
426 infos = zipfp.infolist()
427 names = [ i.filename for i in infos ]
428 self.assertEquals(len(names), 3)
429 self.assert_(TESTFN in names)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000430 self.assert_("another.name" in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000431 self.assert_("strfile" in names)
432 for i in infos:
433 self.assertEquals(i.file_size, len(self.data))
434
435 # check getinfo
Skip Montanaro7a98be22007-08-16 14:35:24 +0000436 for nm in (TESTFN, "another.name", "strfile"):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000437 info = zipfp.getinfo(nm)
438 self.assertEquals(info.filename, nm)
439 self.assertEquals(info.file_size, len(self.data))
440
441 # Check that testzip doesn't raise an exception
442 zipfp.testzip()
443
444
445 zipfp.close()
446
447 def testStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000448 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000449 self.zipTest(f, zipfile.ZIP_STORED)
450
451
452 if zlib:
453 def testDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000454 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000455 self.zipTest(f, zipfile.ZIP_DEFLATED)
456
457 def testAbsoluteArcnames(self):
458 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED, allowZip64=True)
459 zipfp.write(TESTFN, "/absolute")
460 zipfp.close()
461
462 zipfp = zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED)
463 self.assertEqual(zipfp.namelist(), ["absolute"])
464 zipfp.close()
465
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000466 def tearDown(self):
467 zipfile.ZIP64_LIMIT = self._limit
468 os.remove(TESTFN)
469 os.remove(TESTFN2)
470
471class PyZipFileTests(unittest.TestCase):
472 def testWritePyfile(self):
473 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
474 fn = __file__
475 if fn.endswith('.pyc') or fn.endswith('.pyo'):
476 fn = fn[:-1]
477
478 zipfp.writepy(fn)
479
480 bn = os.path.basename(fn)
481 self.assert_(bn not in zipfp.namelist())
482 self.assert_(bn + 'o' in zipfp.namelist() or bn + 'c' in zipfp.namelist())
483 zipfp.close()
484
485
486 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
487 fn = __file__
488 if fn.endswith('.pyc') or fn.endswith('.pyo'):
489 fn = fn[:-1]
490
491 zipfp.writepy(fn, "testpackage")
492
493 bn = "%s/%s"%("testpackage", os.path.basename(fn))
494 self.assert_(bn not in zipfp.namelist())
495 self.assert_(bn + 'o' in zipfp.namelist() or bn + 'c' in zipfp.namelist())
496 zipfp.close()
497
498 def testWritePythonPackage(self):
499 import email
500 packagedir = os.path.dirname(email.__file__)
501
502 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
503 zipfp.writepy(packagedir)
504
505 # Check for a couple of modules at different levels of the hieararchy
506 names = zipfp.namelist()
507 self.assert_('email/__init__.pyo' in names or 'email/__init__.pyc' in names)
508 self.assert_('email/mime/text.pyo' in names or 'email/mime/text.pyc' in names)
509
510 def testWritePythonDirectory(self):
511 os.mkdir(TESTFN2)
512 try:
513 fp = open(os.path.join(TESTFN2, "mod1.py"), "w")
Guido van Rossum43fc78d2007-02-09 22:18:41 +0000514 fp.write("print(42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000515 fp.close()
516
517 fp = open(os.path.join(TESTFN2, "mod2.py"), "w")
Guido van Rossum43fc78d2007-02-09 22:18:41 +0000518 fp.write("print(42 * 42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000519 fp.close()
520
521 fp = open(os.path.join(TESTFN2, "mod2.txt"), "w")
522 fp.write("bla bla bla\n")
523 fp.close()
524
525 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
526 zipfp.writepy(TESTFN2)
527
528 names = zipfp.namelist()
529 self.assert_('mod1.pyc' in names or 'mod1.pyo' in names)
530 self.assert_('mod2.pyc' in names or 'mod2.pyo' in names)
531 self.assert_('mod2.txt' not in names)
532
533 finally:
534 shutil.rmtree(TESTFN2)
535
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000536 def testWriteNonPyfile(self):
537 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
Guido van Rossum814661e2007-07-18 22:07:29 +0000538 open(TESTFN, 'w').write('most definitely not a python file')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000539 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
540 os.remove(TESTFN)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000541
542
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000543class OtherTests(unittest.TestCase):
Martin v. Löwis8570f6a2008-05-05 17:44:38 +0000544 def testUnicodeFilenames(self):
545 zf = zipfile.ZipFile(TESTFN, "w")
546 zf.writestr("foo.txt", "Test for unicode filename")
547 zf.writestr("fo\xf6.txt", "Test for unicode filename")
548 zf.close()
549 zf = zipfile.ZipFile(TESTFN, "w")
550
551
Thomas Wouterscf297e42007-02-23 15:07:44 +0000552 def testCreateNonExistentFileForAppend(self):
553 if os.path.exists(TESTFN):
554 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000555
Thomas Wouterscf297e42007-02-23 15:07:44 +0000556 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000557 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +0000558
Thomas Wouterscf297e42007-02-23 15:07:44 +0000559 try:
560 zf = zipfile.ZipFile(TESTFN, 'a')
561 zf.writestr(filename, content)
562 zf.close()
563 except IOError:
564 self.fail('Could not append data to a non-existent zip file.')
565
566 self.assert_(os.path.exists(TESTFN))
567
568 zf = zipfile.ZipFile(TESTFN, 'r')
569 self.assertEqual(zf.read(filename), content)
570 zf.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000571
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000572 def testCloseErroneousFile(self):
573 # This test checks that the ZipFile constructor closes the file object
574 # it opens if there's an error in the file. If it doesn't, the traceback
575 # holds a reference to the ZipFile object and, indirectly, the file object.
576 # On Windows, this causes the os.unlink() call to fail because the
577 # underlying file is still open. This is SF bug #412214.
578 #
579 fp = open(TESTFN, "w")
580 fp.write("this is not a legal zip file\n")
581 fp.close()
582 try:
583 zf = zipfile.ZipFile(TESTFN)
584 except zipfile.BadZipfile:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000585 pass
586
587 def testIsZipErroneousFile(self):
588 # This test checks that the is_zipfile function correctly identifies
589 # a file that is not a zip file
590 fp = open(TESTFN, "w")
591 fp.write("this is not a legal zip file\n")
592 fp.close()
593 chk = zipfile.is_zipfile(TESTFN)
594 self.assert_(chk is False)
595
596 def testIsZipValidFile(self):
597 # This test checks that the is_zipfile function correctly identifies
598 # a file that is a zip file
599 zipf = zipfile.ZipFile(TESTFN, mode="w")
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000600 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000601 zipf.close()
602 chk = zipfile.is_zipfile(TESTFN)
603 self.assert_(chk is True)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000604
605 def testNonExistentFileRaisesIOError(self):
606 # make sure we don't raise an AttributeError when a partially-constructed
607 # ZipFile instance is finalized; this tests for regression on SF tracker
608 # bug #403871.
609
610 # The bug we're testing for caused an AttributeError to be raised
611 # when a ZipFile instance was created for a file that did not
612 # exist; the .fp member was not initialized but was needed by the
613 # __del__() method. Since the AttributeError is in the __del__(),
614 # it is ignored, but the user should be sufficiently annoyed by
615 # the message on the output that regression will be noticed
616 # quickly.
617 self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
618
619 def testClosedZipRaisesRuntimeError(self):
620 # Verify that testzip() doesn't swallow inappropriate exceptions.
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000621 data = io.BytesIO()
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000622 zipf = zipfile.ZipFile(data, mode="w")
623 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
624 zipf.close()
625
626 # This is correct; calling .read on a closed ZipFile should throw
627 # a RuntimeError, and so should calling .testzip. An earlier
628 # version of .testzip would swallow this exception (and any other)
629 # and report that the first file in the archive was corrupt.
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000630 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
631 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000632 self.assertRaises(RuntimeError, zipf.testzip)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000633 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Guido van Rossum814661e2007-07-18 22:07:29 +0000634 open(TESTFN, 'w').write('zipfile test data')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000635 self.assertRaises(RuntimeError, zipf.write, TESTFN)
636
637 def test_BadConstructorMode(self):
638 # Check that bad modes passed to ZipFile constructor are caught
639 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
640
641 def test_BadOpenMode(self):
642 # Check that bad modes passed to ZipFile.open are caught
643 zipf = zipfile.ZipFile(TESTFN, mode="w")
644 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
645 zipf.close()
646 zipf = zipfile.ZipFile(TESTFN, mode="r")
647 # read the data to make sure the file is there
648 zipf.read("foo.txt")
649 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
650 zipf.close()
651
652 def test_Read0(self):
653 # Check that calling read(0) on a ZipExtFile object returns an empty
654 # string and doesn't advance file pointer
655 zipf = zipfile.ZipFile(TESTFN, mode="w")
656 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
657 # read the data to make sure the file is there
658 f = zipf.open("foo.txt")
659 for i in range(FIXEDTEST_SIZE):
Guido van Rossum814661e2007-07-18 22:07:29 +0000660 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000661
Guido van Rossum814661e2007-07-18 22:07:29 +0000662 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000663 zipf.close()
664
665 def test_OpenNonexistentItem(self):
666 # Check that attempting to call open() for an item that doesn't
667 # exist in the archive raises a RuntimeError
668 zipf = zipfile.ZipFile(TESTFN, mode="w")
669 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
670
671 def test_BadCompressionMode(self):
672 # Check that bad compression methods passed to ZipFile.open are caught
673 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
674
675 def test_NullByteInFilename(self):
676 # Check that a filename containing a null byte is properly terminated
677 zipf = zipfile.ZipFile(TESTFN, mode="w")
Guido van Rossum814661e2007-07-18 22:07:29 +0000678 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000679 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000680
Guido van Rossumd8faa362007-04-27 19:54:29 +0000681 def tearDown(self):
682 support.unlink(TESTFN)
683 support.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000684
685class DecryptionTests(unittest.TestCase):
686 # This test checks that ZIP decryption works. Since the library does not
687 # support encryption at the moment, we use a pre-generated encrypted
688 # ZIP file
689
690 data = (
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000691 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
692 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
693 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
694 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
695 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
696 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
697 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +0000698 data2 = (
699 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
700 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
701 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
702 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
703 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
704 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
705 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
706 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +0000707
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000708 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +0000709 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +0000710
711 def setUp(self):
712 fp = open(TESTFN, "wb")
713 fp.write(self.data)
714 fp.close()
715 self.zip = zipfile.ZipFile(TESTFN, "r")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000716 fp = open(TESTFN2, "wb")
717 fp.write(self.data2)
718 fp.close()
719 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000720
721 def tearDown(self):
722 self.zip.close()
723 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +0000724 self.zip2.close()
725 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000726
727 def testNoPassword(self):
728 # Reading the encrypted file without password
729 # must generate a RunTime exception
730 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000731 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000732
733 def testBadPassword(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000734 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000735 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000736 self.zip2.setpassword(b"perl")
737 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000738
Thomas Wouterscf297e42007-02-23 15:07:44 +0000739 def testGoodPassword(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000740 self.zip.setpassword(b"python")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000741 self.assertEquals(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +0000742 self.zip2.setpassword(b"12345")
743 self.assertEquals(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000744
Guido van Rossumd8faa362007-04-27 19:54:29 +0000745
746class TestsWithRandomBinaryFiles(unittest.TestCase):
747 def setUp(self):
748 datacount = randint(16, 64)*1024 + randint(1, 1024)
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000749 self.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
750 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000751
752 # Make a source file with some lines
753 fp = open(TESTFN, "wb")
754 fp.write(self.data)
755 fp.close()
756
757 def tearDown(self):
758 support.unlink(TESTFN)
759 support.unlink(TESTFN2)
760
761 def makeTestArchive(self, f, compression):
762 # Create the ZIP archive
763 zipfp = zipfile.ZipFile(f, "w", compression)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000764 zipfp.write(TESTFN, "another.name")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000765 zipfp.write(TESTFN, TESTFN)
766 zipfp.close()
767
768 def zipTest(self, f, compression):
769 self.makeTestArchive(f, compression)
770
771 # Read the ZIP archive
772 zipfp = zipfile.ZipFile(f, "r", compression)
773 testdata = zipfp.read(TESTFN)
774 self.assertEqual(len(testdata), len(self.data))
775 self.assertEqual(testdata, self.data)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000776 self.assertEqual(zipfp.read("another.name"), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000777 zipfp.close()
778
779 def testStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000780 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000781 self.zipTest(f, zipfile.ZIP_STORED)
782
783 def zipOpenTest(self, f, compression):
784 self.makeTestArchive(f, compression)
785
786 # Read the ZIP archive
787 zipfp = zipfile.ZipFile(f, "r", compression)
788 zipdata1 = []
789 zipopen1 = zipfp.open(TESTFN)
790 while 1:
791 read_data = zipopen1.read(256)
792 if not read_data:
793 break
794 zipdata1.append(read_data)
795
796 zipdata2 = []
Skip Montanaro7a98be22007-08-16 14:35:24 +0000797 zipopen2 = zipfp.open("another.name")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000798 while 1:
799 read_data = zipopen2.read(256)
800 if not read_data:
801 break
802 zipdata2.append(read_data)
803
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000804 testdata1 = b''.join(zipdata1)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000805 self.assertEqual(len(testdata1), len(self.data))
806 self.assertEqual(testdata1, self.data)
807
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000808 testdata2 = b''.join(zipdata2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000809 self.assertEqual(len(testdata1), len(self.data))
810 self.assertEqual(testdata1, self.data)
811 zipfp.close()
812
813 def testOpenStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000814 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000815 self.zipOpenTest(f, zipfile.ZIP_STORED)
816
817 def zipRandomOpenTest(self, f, compression):
818 self.makeTestArchive(f, compression)
819
820 # Read the ZIP archive
821 zipfp = zipfile.ZipFile(f, "r", compression)
822 zipdata1 = []
823 zipopen1 = zipfp.open(TESTFN)
824 while 1:
825 read_data = zipopen1.read(randint(1, 1024))
826 if not read_data:
827 break
828 zipdata1.append(read_data)
829
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000830 testdata = b''.join(zipdata1)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000831 self.assertEqual(len(testdata), len(self.data))
832 self.assertEqual(testdata, self.data)
833 zipfp.close()
834
835 def testRandomOpenStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000836 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000837 self.zipRandomOpenTest(f, zipfile.ZIP_STORED)
838
839class TestsWithMultipleOpens(unittest.TestCase):
840 def setUp(self):
841 # Create the ZIP archive
842 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED)
843 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
844 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
845 zipfp.close()
846
847 def testSameFile(self):
848 # Verify that (when the ZipFile is in control of creating file objects)
849 # multiple open() calls can be made without interfering with each other.
850 zipf = zipfile.ZipFile(TESTFN2, mode="r")
851 zopen1 = zipf.open('ones')
852 zopen2 = zipf.open('ones')
853 data1 = zopen1.read(500)
854 data2 = zopen2.read(500)
855 data1 += zopen1.read(500)
856 data2 += zopen2.read(500)
857 self.assertEqual(data1, data2)
858 zipf.close()
859
860 def testDifferentFile(self):
861 # Verify that (when the ZipFile is in control of creating file objects)
862 # multiple open() calls can be made without interfering with each other.
863 zipf = zipfile.ZipFile(TESTFN2, mode="r")
864 zopen1 = zipf.open('ones')
865 zopen2 = zipf.open('twos')
866 data1 = zopen1.read(500)
867 data2 = zopen2.read(500)
868 data1 += zopen1.read(500)
869 data2 += zopen2.read(500)
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000870 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
871 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000872 zipf.close()
873
874 def testInterleaved(self):
875 # Verify that (when the ZipFile is in control of creating file objects)
876 # multiple open() calls can be made without interfering with each other.
877 zipf = zipfile.ZipFile(TESTFN2, mode="r")
878 zopen1 = zipf.open('ones')
879 data1 = zopen1.read(500)
880 zopen2 = zipf.open('twos')
881 data2 = zopen2.read(500)
882 data1 += zopen1.read(500)
883 data2 += zopen2.read(500)
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000884 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
885 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000886 zipf.close()
887
888 def tearDown(self):
889 os.remove(TESTFN2)
890
891
892class UniversalNewlineTests(unittest.TestCase):
893 def setUp(self):
Guido van Rossum9c627722007-08-27 18:31:48 +0000894 self.line_gen = [bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000895 for i in range(FIXEDTEST_SIZE)]
Guido van Rossumd8faa362007-04-27 19:54:29 +0000896 self.seps = ('\r', '\r\n', '\n')
897 self.arcdata, self.arcfiles = {}, {}
898 for n, s in enumerate(self.seps):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000899 b = s.encode("ascii")
900 self.arcdata[s] = b.join(self.line_gen) + b
Guido van Rossumd8faa362007-04-27 19:54:29 +0000901 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000902 f = open(self.arcfiles[s], "wb")
903 try:
904 f.write(self.arcdata[s])
905 finally:
906 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000907
908 def makeTestArchive(self, f, compression):
909 # Create the ZIP archive
910 zipfp = zipfile.ZipFile(f, "w", compression)
911 for fn in self.arcfiles.values():
912 zipfp.write(fn, fn)
913 zipfp.close()
914
915 def readTest(self, f, compression):
916 self.makeTestArchive(f, compression)
917
918 # Read the ZIP archive
919 zipfp = zipfile.ZipFile(f, "r")
920 for sep, fn in self.arcfiles.items():
921 zipdata = zipfp.open(fn, "rU").read()
922 self.assertEqual(self.arcdata[sep], zipdata)
923
924 zipfp.close()
925
926 def readlineTest(self, f, compression):
927 self.makeTestArchive(f, compression)
928
929 # Read the ZIP archive
930 zipfp = zipfile.ZipFile(f, "r")
931 for sep, fn in self.arcfiles.items():
932 zipopen = zipfp.open(fn, "rU")
933 for line in self.line_gen:
934 linedata = zipopen.readline()
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000935 self.assertEqual(linedata, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000936
937 zipfp.close()
938
939 def readlinesTest(self, f, compression):
940 self.makeTestArchive(f, compression)
941
942 # Read the ZIP archive
943 zipfp = zipfile.ZipFile(f, "r")
944 for sep, fn in self.arcfiles.items():
945 ziplines = zipfp.open(fn, "rU").readlines()
946 for line, zipline in zip(self.line_gen, ziplines):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000947 self.assertEqual(zipline, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000948
949 zipfp.close()
950
951 def iterlinesTest(self, f, compression):
952 self.makeTestArchive(f, compression)
953
954 # Read the ZIP archive
955 zipfp = zipfile.ZipFile(f, "r")
956 for sep, fn in self.arcfiles.items():
957 for line, zipline in zip(self.line_gen, zipfp.open(fn, "rU")):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000958 self.assertEqual(zipline, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000959
960 zipfp.close()
961
962 def testReadStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000963 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000964 self.readTest(f, zipfile.ZIP_STORED)
965
966 def testReadlineStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000967 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000968 self.readlineTest(f, zipfile.ZIP_STORED)
969
970 def testReadlinesStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000971 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000972 self.readlinesTest(f, zipfile.ZIP_STORED)
973
974 def testIterlinesStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000975 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000976 self.iterlinesTest(f, zipfile.ZIP_STORED)
977
978 if zlib:
979 def testReadDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000980 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000981 self.readTest(f, zipfile.ZIP_DEFLATED)
982
983 def testReadlineDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000984 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000985 self.readlineTest(f, zipfile.ZIP_DEFLATED)
986
987 def testReadlinesDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000988 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000989 self.readlinesTest(f, zipfile.ZIP_DEFLATED)
990
991 def testIterlinesDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000992 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000993 self.iterlinesTest(f, zipfile.ZIP_DEFLATED)
994
995 def tearDown(self):
996 for sep, fn in self.arcfiles.items():
997 os.remove(fn)
998 support.unlink(TESTFN)
999 support.unlink(TESTFN2)
1000
1001
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001002def test_main():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001003 run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
1004 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
1005 UniversalNewlineTests, TestsWithRandomBinaryFiles)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001006
1007if __name__ == "__main__":
1008 test_main()