blob: 21fc703d4e726372f4e84004d3c01c1b763b838d [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
Tim Petersa45cacf2004-08-20 03:47:14 +00006
Martin v. Löwis3eb76482007-03-06 10:41:24 +00007import zipfile, os, unittest, sys, shutil, struct
Tim Petersa19a1682001-03-29 04:36:09 +00008
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00009from StringIO import StringIO
10from tempfile import TemporaryFile
Martin v. Löwis3eb76482007-03-06 10:41:24 +000011from random import randint, random
Tim Petersa19a1682001-03-29 04:36:09 +000012
Collin Winter04a51ec2007-03-29 02:28:16 +000013import test.test_support as support
Martin v. Löwis3a8071a2009-01-24 14:04:33 +000014from test.test_support import TESTFN, run_unittest, findfile
Guido van Rossum368f04a2000-04-10 13:23:04 +000015
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000016TESTFN2 = TESTFN + "2"
Martin v. Löwis3a8071a2009-01-24 14:04:33 +000017TESTFNDIR = TESTFN + "d"
Georg Brandl4b3ab6f2007-07-12 09:59:22 +000018FIXEDTEST_SIZE = 1000
Guido van Rossum368f04a2000-04-10 13:23:04 +000019
Georg Brandl62416bc2008-01-07 18:47:44 +000020SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'),
21 ('ziptest2dir/_ziptest2', 'qawsedrftg'),
22 ('/ziptest2dir/ziptest3dir/_ziptest3', 'azsxdcfvgb'),
23 ('ziptest2dir/ziptest3dir/ziptest4dir/_ziptest3', '6y7u8i9o0p')]
24
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000025class TestsWithSourceFile(unittest.TestCase):
26 def setUp(self):
Georg Brandl4b3ab6f2007-07-12 09:59:22 +000027 self.line_gen = ["Zipfile test line %d. random float: %f" % (i, random())
28 for i in xrange(FIXEDTEST_SIZE)]
Martin v. Löwis3eb76482007-03-06 10:41:24 +000029 self.data = '\n'.join(self.line_gen) + '\n'
Fred Drake6e7e4852001-02-28 05:34:16 +000030
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000031 # Make a source file with some lines
32 fp = open(TESTFN, "wb")
33 fp.write(self.data)
34 fp.close()
Tim Peters7d3bad62001-04-04 18:56:49 +000035
Martin v. Löwis3eb76482007-03-06 10:41:24 +000036 def makeTestArchive(self, f, compression):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000037 # Create the ZIP archive
38 zipfp = zipfile.ZipFile(f, "w", compression)
39 zipfp.write(TESTFN, "another"+os.extsep+"name")
40 zipfp.write(TESTFN, TESTFN)
Ronald Oussoren143cefb2006-06-15 08:14:18 +000041 zipfp.writestr("strfile", self.data)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000042 zipfp.close()
Tim Peters7d3bad62001-04-04 18:56:49 +000043
Martin v. Löwis3eb76482007-03-06 10:41:24 +000044 def zipTest(self, f, compression):
45 self.makeTestArchive(f, compression)
46
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000047 # Read the ZIP archive
48 zipfp = zipfile.ZipFile(f, "r", compression)
49 self.assertEqual(zipfp.read(TESTFN), self.data)
50 self.assertEqual(zipfp.read("another"+os.extsep+"name"), self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +000051 self.assertEqual(zipfp.read("strfile"), self.data)
52
53 # Print the ZIP directory
54 fp = StringIO()
55 stdout = sys.stdout
56 try:
57 sys.stdout = fp
58
59 zipfp.printdir()
60 finally:
61 sys.stdout = stdout
Tim Petersa608bb22006-06-15 18:06:29 +000062
Ronald Oussoren143cefb2006-06-15 08:14:18 +000063 directory = fp.getvalue()
64 lines = directory.splitlines()
65 self.assertEquals(len(lines), 4) # Number of files + header
66
67 self.assert_('File Name' in lines[0])
68 self.assert_('Modified' in lines[0])
69 self.assert_('Size' in lines[0])
70
71 fn, date, time, size = lines[1].split()
72 self.assertEquals(fn, 'another.name')
73 # XXX: timestamp is not tested
74 self.assertEquals(size, str(len(self.data)))
75
76 # Check the namelist
77 names = zipfp.namelist()
78 self.assertEquals(len(names), 3)
79 self.assert_(TESTFN in names)
80 self.assert_("another"+os.extsep+"name" in names)
81 self.assert_("strfile" in names)
82
83 # Check infolist
84 infos = zipfp.infolist()
85 names = [ i.filename for i in infos ]
86 self.assertEquals(len(names), 3)
87 self.assert_(TESTFN in names)
88 self.assert_("another"+os.extsep+"name" in names)
89 self.assert_("strfile" in names)
90 for i in infos:
91 self.assertEquals(i.file_size, len(self.data))
92
93 # check getinfo
94 for nm in (TESTFN, "another"+os.extsep+"name", "strfile"):
95 info = zipfp.getinfo(nm)
96 self.assertEquals(info.filename, nm)
97 self.assertEquals(info.file_size, len(self.data))
98
99 # Check that testzip doesn't raise an exception
100 zipfp.testzip()
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000101 zipfp.close()
Tim Peters7d3bad62001-04-04 18:56:49 +0000102
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000103 def testStored(self):
104 for f in (TESTFN2, TemporaryFile(), StringIO()):
105 self.zipTest(f, zipfile.ZIP_STORED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000106
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000107 def zipOpenTest(self, f, compression):
108 self.makeTestArchive(f, compression)
109
110 # Read the ZIP archive
111 zipfp = zipfile.ZipFile(f, "r", compression)
112 zipdata1 = []
113 zipopen1 = zipfp.open(TESTFN)
114 while 1:
115 read_data = zipopen1.read(256)
116 if not read_data:
117 break
118 zipdata1.append(read_data)
119
120 zipdata2 = []
121 zipopen2 = zipfp.open("another"+os.extsep+"name")
122 while 1:
123 read_data = zipopen2.read(256)
124 if not read_data:
125 break
126 zipdata2.append(read_data)
Tim Petersea5962f2007-03-12 18:07:52 +0000127
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000128 self.assertEqual(''.join(zipdata1), self.data)
129 self.assertEqual(''.join(zipdata2), self.data)
130 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000131
132 def testOpenStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000133 for f in (TESTFN2, TemporaryFile(), StringIO()):
134 self.zipOpenTest(f, zipfile.ZIP_STORED)
135
Georg Brandl112aa502008-05-20 08:25:48 +0000136 def testOpenViaZipInfo(self):
137 # Create the ZIP archive
138 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
139 zipfp.writestr("name", "foo")
140 zipfp.writestr("name", "bar")
141 zipfp.close()
142
143 zipfp = zipfile.ZipFile(TESTFN2, "r")
144 infos = zipfp.infolist()
145 data = ""
146 for info in infos:
147 data += zipfp.open(info).read()
148 self.assert_(data == "foobar" or data == "barfoo")
149 data = ""
150 for info in infos:
151 data += zipfp.read(info)
152 self.assert_(data == "foobar" or data == "barfoo")
153 zipfp.close()
154
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000155 def zipRandomOpenTest(self, f, compression):
156 self.makeTestArchive(f, compression)
157
158 # Read the ZIP archive
159 zipfp = zipfile.ZipFile(f, "r", compression)
160 zipdata1 = []
161 zipopen1 = zipfp.open(TESTFN)
162 while 1:
163 read_data = zipopen1.read(randint(1, 1024))
164 if not read_data:
165 break
166 zipdata1.append(read_data)
167
168 self.assertEqual(''.join(zipdata1), self.data)
169 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000170
171 def testRandomOpenStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000172 for f in (TESTFN2, TemporaryFile(), StringIO()):
173 self.zipRandomOpenTest(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +0000174
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000175 def zipReadlineTest(self, f, compression):
176 self.makeTestArchive(f, compression)
177
178 # Read the ZIP archive
179 zipfp = zipfile.ZipFile(f, "r")
180 zipopen = zipfp.open(TESTFN)
181 for line in self.line_gen:
182 linedata = zipopen.readline()
183 self.assertEqual(linedata, line + '\n')
184
185 zipfp.close()
186
187 def zipReadlinesTest(self, f, compression):
188 self.makeTestArchive(f, compression)
189
190 # Read the ZIP archive
191 zipfp = zipfile.ZipFile(f, "r")
192 ziplines = zipfp.open(TESTFN).readlines()
193 for line, zipline in zip(self.line_gen, ziplines):
194 self.assertEqual(zipline, line + '\n')
195
196 zipfp.close()
197
198 def zipIterlinesTest(self, f, compression):
199 self.makeTestArchive(f, compression)
200
201 # Read the ZIP archive
202 zipfp = zipfile.ZipFile(f, "r")
203 for line, zipline in zip(self.line_gen, zipfp.open(TESTFN)):
204 self.assertEqual(zipline, line + '\n')
205
206 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000207
208 def testReadlineStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000209 for f in (TESTFN2, TemporaryFile(), StringIO()):
210 self.zipReadlineTest(f, zipfile.ZIP_STORED)
211
Tim Petersea5962f2007-03-12 18:07:52 +0000212 def testReadlinesStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000213 for f in (TESTFN2, TemporaryFile(), StringIO()):
214 self.zipReadlinesTest(f, zipfile.ZIP_STORED)
215
Tim Petersea5962f2007-03-12 18:07:52 +0000216 def testIterlinesStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000217 for f in (TESTFN2, TemporaryFile(), StringIO()):
218 self.zipIterlinesTest(f, zipfile.ZIP_STORED)
219
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000220 if zlib:
221 def testDeflated(self):
222 for f in (TESTFN2, TemporaryFile(), StringIO()):
223 self.zipTest(f, zipfile.ZIP_DEFLATED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000224
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000225 def testOpenDeflated(self):
226 for f in (TESTFN2, TemporaryFile(), StringIO()):
227 self.zipOpenTest(f, zipfile.ZIP_DEFLATED)
228
229 def testRandomOpenDeflated(self):
230 for f in (TESTFN2, TemporaryFile(), StringIO()):
231 self.zipRandomOpenTest(f, zipfile.ZIP_DEFLATED)
232
Tim Petersea5962f2007-03-12 18:07:52 +0000233 def testReadlineDeflated(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000234 for f in (TESTFN2, TemporaryFile(), StringIO()):
235 self.zipReadlineTest(f, zipfile.ZIP_DEFLATED)
236
Tim Petersea5962f2007-03-12 18:07:52 +0000237 def testReadlinesDeflated(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000238 for f in (TESTFN2, TemporaryFile(), StringIO()):
239 self.zipReadlinesTest(f, zipfile.ZIP_DEFLATED)
240
Tim Petersea5962f2007-03-12 18:07:52 +0000241 def testIterlinesDeflated(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000242 for f in (TESTFN2, TemporaryFile(), StringIO()):
243 self.zipIterlinesTest(f, zipfile.ZIP_DEFLATED)
Tim Petersea5962f2007-03-12 18:07:52 +0000244
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000245 def testLowCompression(self):
246 # Checks for cases where compressed data is larger than original
247 # Create the ZIP archive
248 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED)
249 zipfp.writestr("strfile", '12')
250 zipfp.close()
251
252 # Get an open object for strfile
253 zipfp = zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_DEFLATED)
254 openobj = zipfp.open("strfile")
255 self.assertEqual(openobj.read(1), '1')
256 self.assertEqual(openobj.read(1), '2')
257
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000258 def testAbsoluteArcnames(self):
259 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
260 zipfp.write(TESTFN, "/absolute")
261 zipfp.close()
262
263 zipfp = zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED)
264 self.assertEqual(zipfp.namelist(), ["absolute"])
265 zipfp.close()
Tim Peters32cbc962006-02-20 21:42:18 +0000266
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000267 def testAppendToZipFile(self):
268 # Test appending to an existing zipfile
269 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
270 zipfp.write(TESTFN, TESTFN)
271 zipfp.close()
272 zipfp = zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED)
273 zipfp.writestr("strfile", self.data)
274 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
275 zipfp.close()
276
277 def testAppendToNonZipFile(self):
278 # Test appending to an existing file that is not a zipfile
279 # NOTE: this test fails if len(d) < 22 because of the first
280 # line "fpin.seek(-22, 2)" in _EndRecData
281 d = 'I am not a ZipFile!'*10
282 f = file(TESTFN2, 'wb')
283 f.write(d)
284 f.close()
285 zipfp = zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED)
286 zipfp.write(TESTFN, TESTFN)
287 zipfp.close()
288
289 f = file(TESTFN2, 'rb')
290 f.seek(len(d))
291 zipfp = zipfile.ZipFile(f, "r")
292 self.assertEqual(zipfp.namelist(), [TESTFN])
293 zipfp.close()
294 f.close()
295
296 def test_WriteDefaultName(self):
297 # Check that calling ZipFile.write without arcname specified produces the expected result
298 zipfp = zipfile.ZipFile(TESTFN2, "w")
299 zipfp.write(TESTFN)
300 self.assertEqual(zipfp.read(TESTFN), file(TESTFN).read())
301 zipfp.close()
302
303 def test_PerFileCompression(self):
304 # Check that files within a Zip archive can have different compression options
305 zipfp = zipfile.ZipFile(TESTFN2, "w")
306 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
307 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
308 sinfo = zipfp.getinfo('storeme')
309 dinfo = zipfp.getinfo('deflateme')
310 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
311 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
312 zipfp.close()
313
314 def test_WriteToReadonly(self):
315 # Check that trying to call write() on a readonly ZipFile object
316 # raises a RuntimeError
317 zipf = zipfile.ZipFile(TESTFN2, mode="w")
318 zipf.writestr("somefile.txt", "bogus")
319 zipf.close()
320 zipf = zipfile.ZipFile(TESTFN2, mode="r")
321 self.assertRaises(RuntimeError, zipf.write, TESTFN)
322 zipf.close()
323
Georg Brandl62416bc2008-01-07 18:47:44 +0000324 def testExtract(self):
325 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
326 for fpath, fdata in SMALL_TEST_DATA:
327 zipfp.writestr(fpath, fdata)
328 zipfp.close()
329
330 zipfp = zipfile.ZipFile(TESTFN2, "r")
331 for fpath, fdata in SMALL_TEST_DATA:
332 writtenfile = zipfp.extract(fpath)
333
334 # make sure it was written to the right place
335 if os.path.isabs(fpath):
336 correctfile = os.path.join(os.getcwd(), fpath[1:])
337 else:
338 correctfile = os.path.join(os.getcwd(), fpath)
Christian Heimesa2af2122008-01-26 16:43:35 +0000339 correctfile = os.path.normpath(correctfile)
Georg Brandl62416bc2008-01-07 18:47:44 +0000340
341 self.assertEqual(writtenfile, correctfile)
342
343 # make sure correct data is in correct file
344 self.assertEqual(fdata, file(writtenfile, "rb").read())
345
346 os.remove(writtenfile)
347
348 zipfp.close()
349
350 # remove the test file subdirectories
351 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
352
353 def testExtractAll(self):
354 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
355 for fpath, fdata in SMALL_TEST_DATA:
356 zipfp.writestr(fpath, fdata)
357 zipfp.close()
358
359 zipfp = zipfile.ZipFile(TESTFN2, "r")
360 zipfp.extractall()
361 for fpath, fdata in SMALL_TEST_DATA:
362 if os.path.isabs(fpath):
363 outfile = os.path.join(os.getcwd(), fpath[1:])
364 else:
365 outfile = os.path.join(os.getcwd(), fpath)
366
367 self.assertEqual(fdata, file(outfile, "rb").read())
368
369 os.remove(outfile)
370
371 zipfp.close()
372
373 # remove the test file subdirectories
374 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
375
Antoine Pitrou5fdfa3e2008-07-25 19:42:26 +0000376 def zip_test_writestr_permissions(self, f, compression):
377 # Make sure that writestr creates files with mode 0600,
378 # when it is passed a name rather than a ZipInfo instance.
379
380 self.makeTestArchive(f, compression)
381 zipfp = zipfile.ZipFile(f, "r")
382 zinfo = zipfp.getinfo('strfile')
383 self.assertEqual(zinfo.external_attr, 0600 << 16)
384
385 def test_writestr_permissions(self):
386 for f in (TESTFN2, TemporaryFile(), StringIO()):
387 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
388
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000389 def tearDown(self):
390 os.remove(TESTFN)
391 os.remove(TESTFN2)
392
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000393class TestZip64InSmallFiles(unittest.TestCase):
394 # These tests test the ZIP64 functionality without using large files,
395 # see test_zipfile64 for proper tests.
396
397 def setUp(self):
398 self._limit = zipfile.ZIP64_LIMIT
399 zipfile.ZIP64_LIMIT = 5
400
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000401 line_gen = ("Test of zipfile line %d." % i for i in range(0, FIXEDTEST_SIZE))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000402 self.data = '\n'.join(line_gen)
403
404 # Make a source file with some lines
405 fp = open(TESTFN, "wb")
406 fp.write(self.data)
407 fp.close()
408
409 def largeFileExceptionTest(self, f, compression):
410 zipfp = zipfile.ZipFile(f, "w", compression)
Tim Petersa608bb22006-06-15 18:06:29 +0000411 self.assertRaises(zipfile.LargeZipFile,
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000412 zipfp.write, TESTFN, "another"+os.extsep+"name")
413 zipfp.close()
414
415 def largeFileExceptionTest2(self, f, compression):
416 zipfp = zipfile.ZipFile(f, "w", compression)
Tim Petersa608bb22006-06-15 18:06:29 +0000417 self.assertRaises(zipfile.LargeZipFile,
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000418 zipfp.writestr, "another"+os.extsep+"name", self.data)
419 zipfp.close()
420
421 def testLargeFileException(self):
422 for f in (TESTFN2, TemporaryFile(), StringIO()):
423 self.largeFileExceptionTest(f, zipfile.ZIP_STORED)
424 self.largeFileExceptionTest2(f, zipfile.ZIP_STORED)
425
426 def zipTest(self, f, compression):
427 # Create the ZIP archive
428 zipfp = zipfile.ZipFile(f, "w", compression, allowZip64=True)
429 zipfp.write(TESTFN, "another"+os.extsep+"name")
430 zipfp.write(TESTFN, TESTFN)
431 zipfp.writestr("strfile", self.data)
432 zipfp.close()
433
434 # Read the ZIP archive
435 zipfp = zipfile.ZipFile(f, "r", compression)
436 self.assertEqual(zipfp.read(TESTFN), self.data)
437 self.assertEqual(zipfp.read("another"+os.extsep+"name"), self.data)
438 self.assertEqual(zipfp.read("strfile"), self.data)
439
440 # Print the ZIP directory
441 fp = StringIO()
442 stdout = sys.stdout
443 try:
444 sys.stdout = fp
445
446 zipfp.printdir()
447 finally:
448 sys.stdout = stdout
Tim Petersa608bb22006-06-15 18:06:29 +0000449
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000450 directory = fp.getvalue()
451 lines = directory.splitlines()
452 self.assertEquals(len(lines), 4) # Number of files + header
453
454 self.assert_('File Name' in lines[0])
455 self.assert_('Modified' in lines[0])
456 self.assert_('Size' in lines[0])
457
458 fn, date, time, size = lines[1].split()
459 self.assertEquals(fn, 'another.name')
460 # XXX: timestamp is not tested
461 self.assertEquals(size, str(len(self.data)))
462
463 # Check the namelist
464 names = zipfp.namelist()
465 self.assertEquals(len(names), 3)
466 self.assert_(TESTFN in names)
467 self.assert_("another"+os.extsep+"name" in names)
468 self.assert_("strfile" in names)
469
470 # Check infolist
471 infos = zipfp.infolist()
472 names = [ i.filename for i in infos ]
473 self.assertEquals(len(names), 3)
474 self.assert_(TESTFN in names)
475 self.assert_("another"+os.extsep+"name" in names)
476 self.assert_("strfile" in names)
477 for i in infos:
478 self.assertEquals(i.file_size, len(self.data))
479
480 # check getinfo
481 for nm in (TESTFN, "another"+os.extsep+"name", "strfile"):
482 info = zipfp.getinfo(nm)
483 self.assertEquals(info.filename, nm)
484 self.assertEquals(info.file_size, len(self.data))
485
486 # Check that testzip doesn't raise an exception
487 zipfp.testzip()
488
489
490 zipfp.close()
491
492 def testStored(self):
493 for f in (TESTFN2, TemporaryFile(), StringIO()):
494 self.zipTest(f, zipfile.ZIP_STORED)
495
496
497 if zlib:
498 def testDeflated(self):
499 for f in (TESTFN2, TemporaryFile(), StringIO()):
500 self.zipTest(f, zipfile.ZIP_DEFLATED)
501
502 def testAbsoluteArcnames(self):
503 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED, allowZip64=True)
504 zipfp.write(TESTFN, "/absolute")
505 zipfp.close()
506
507 zipfp = zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED)
508 self.assertEqual(zipfp.namelist(), ["absolute"])
509 zipfp.close()
510
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000511 def tearDown(self):
512 zipfile.ZIP64_LIMIT = self._limit
513 os.remove(TESTFN)
514 os.remove(TESTFN2)
515
516class PyZipFileTests(unittest.TestCase):
517 def testWritePyfile(self):
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)
524
525 bn = 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
531 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
532 fn = __file__
533 if fn.endswith('.pyc') or fn.endswith('.pyo'):
534 fn = fn[:-1]
535
536 zipfp.writepy(fn, "testpackage")
537
538 bn = "%s/%s"%("testpackage", os.path.basename(fn))
539 self.assert_(bn not in zipfp.namelist())
540 self.assert_(bn + 'o' in zipfp.namelist() or bn + 'c' in zipfp.namelist())
541 zipfp.close()
542
543 def testWritePythonPackage(self):
544 import email
545 packagedir = os.path.dirname(email.__file__)
546
547 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
548 zipfp.writepy(packagedir)
549
550 # Check for a couple of modules at different levels of the hieararchy
551 names = zipfp.namelist()
552 self.assert_('email/__init__.pyo' in names or 'email/__init__.pyc' in names)
553 self.assert_('email/mime/text.pyo' in names or 'email/mime/text.pyc' in names)
554
555 def testWritePythonDirectory(self):
556 os.mkdir(TESTFN2)
557 try:
558 fp = open(os.path.join(TESTFN2, "mod1.py"), "w")
559 fp.write("print 42\n")
560 fp.close()
561
562 fp = open(os.path.join(TESTFN2, "mod2.py"), "w")
563 fp.write("print 42 * 42\n")
564 fp.close()
565
566 fp = open(os.path.join(TESTFN2, "mod2.txt"), "w")
567 fp.write("bla bla bla\n")
568 fp.close()
569
570 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
571 zipfp.writepy(TESTFN2)
572
573 names = zipfp.namelist()
574 self.assert_('mod1.pyc' in names or 'mod1.pyo' in names)
575 self.assert_('mod2.pyc' in names or 'mod2.pyo' in names)
576 self.assert_('mod2.txt' not in names)
577
578 finally:
579 shutil.rmtree(TESTFN2)
580
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000581 def testWriteNonPyfile(self):
582 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
583 file(TESTFN, 'w').write('most definitely not a python file')
584 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
585 os.remove(TESTFN)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000586
587
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000588class OtherTests(unittest.TestCase):
Martin v. Löwis471617d2008-05-05 17:16:58 +0000589 def testUnicodeFilenames(self):
590 zf = zipfile.ZipFile(TESTFN, "w")
591 zf.writestr(u"foo.txt", "Test for unicode filename")
Martin v. Löwisc3ad68c2008-05-05 17:47:06 +0000592 zf.writestr(u"\xf6.txt", "Test for unicode filename")
593 self.assertTrue(isinstance(zf.infolist()[0].filename, unicode))
Martin v. Löwis471617d2008-05-05 17:16:58 +0000594 zf.close()
Martin v. Löwisc3ad68c2008-05-05 17:47:06 +0000595 zf = zipfile.ZipFile(TESTFN, "r")
596 self.assertEqual(zf.filelist[0].filename, "foo.txt")
597 self.assertEqual(zf.filelist[1].filename, u"\xf6.txt")
598 zf.close()
Martin v. Löwis471617d2008-05-05 17:16:58 +0000599
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000600 def testCreateNonExistentFileForAppend(self):
601 if os.path.exists(TESTFN):
602 os.unlink(TESTFN)
Tim Petersea5962f2007-03-12 18:07:52 +0000603
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000604 filename = 'testfile.txt'
605 content = 'hello, world. this is some content.'
Tim Petersea5962f2007-03-12 18:07:52 +0000606
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000607 try:
608 zf = zipfile.ZipFile(TESTFN, 'a')
609 zf.writestr(filename, content)
610 zf.close()
611 except IOError, (errno, errmsg):
612 self.fail('Could not append data to a non-existent zip file.')
613
614 self.assert_(os.path.exists(TESTFN))
615
616 zf = zipfile.ZipFile(TESTFN, 'r')
617 self.assertEqual(zf.read(filename), content)
618 zf.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000619
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000620 def testCloseErroneousFile(self):
621 # This test checks that the ZipFile constructor closes the file object
622 # it opens if there's an error in the file. If it doesn't, the traceback
623 # holds a reference to the ZipFile object and, indirectly, the file object.
624 # On Windows, this causes the os.unlink() call to fail because the
625 # underlying file is still open. This is SF bug #412214.
626 #
627 fp = open(TESTFN, "w")
628 fp.write("this is not a legal zip file\n")
629 fp.close()
630 try:
631 zf = zipfile.ZipFile(TESTFN)
632 except zipfile.BadZipfile:
Collin Winter04a51ec2007-03-29 02:28:16 +0000633 pass
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000634
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000635 def testIsZipErroneousFile(self):
Tim Petersea5962f2007-03-12 18:07:52 +0000636 # This test checks that the is_zipfile function correctly identifies
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000637 # a file that is not a zip file
638 fp = open(TESTFN, "w")
639 fp.write("this is not a legal zip file\n")
640 fp.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000641 chk = zipfile.is_zipfile(TESTFN)
Tim Petersea5962f2007-03-12 18:07:52 +0000642 self.assert_(chk is False)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000643
644 def testIsZipValidFile(self):
Tim Petersea5962f2007-03-12 18:07:52 +0000645 # This test checks that the is_zipfile function correctly identifies
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000646 # a file that is a zip file
647 zipf = zipfile.ZipFile(TESTFN, mode="w")
648 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
649 zipf.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000650 chk = zipfile.is_zipfile(TESTFN)
Tim Petersea5962f2007-03-12 18:07:52 +0000651 self.assert_(chk is True)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000652
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000653 def testNonExistentFileRaisesIOError(self):
654 # make sure we don't raise an AttributeError when a partially-constructed
655 # ZipFile instance is finalized; this tests for regression on SF tracker
656 # bug #403871.
657
658 # The bug we're testing for caused an AttributeError to be raised
659 # when a ZipFile instance was created for a file that did not
660 # exist; the .fp member was not initialized but was needed by the
661 # __del__() method. Since the AttributeError is in the __del__(),
662 # it is ignored, but the user should be sufficiently annoyed by
663 # the message on the output that regression will be noticed
664 # quickly.
665 self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
666
667 def testClosedZipRaisesRuntimeError(self):
668 # Verify that testzip() doesn't swallow inappropriate exceptions.
669 data = StringIO()
670 zipf = zipfile.ZipFile(data, mode="w")
671 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
672 zipf.close()
673
674 # This is correct; calling .read on a closed ZipFile should throw
675 # a RuntimeError, and so should calling .testzip. An earlier
676 # version of .testzip would swallow this exception (and any other)
677 # and report that the first file in the archive was corrupt.
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000678 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
679 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000680 self.assertRaises(RuntimeError, zipf.testzip)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000681 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
682 file(TESTFN, 'w').write('zipfile test data')
683 self.assertRaises(RuntimeError, zipf.write, TESTFN)
684
685 def test_BadConstructorMode(self):
686 # Check that bad modes passed to ZipFile constructor are caught
687 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
688
689 def test_BadOpenMode(self):
690 # Check that bad modes passed to ZipFile.open are caught
691 zipf = zipfile.ZipFile(TESTFN, mode="w")
692 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
693 zipf.close()
694 zipf = zipfile.ZipFile(TESTFN, mode="r")
695 # read the data to make sure the file is there
696 zipf.read("foo.txt")
697 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
698 zipf.close()
699
700 def test_Read0(self):
701 # Check that calling read(0) on a ZipExtFile object returns an empty
702 # string and doesn't advance file pointer
703 zipf = zipfile.ZipFile(TESTFN, mode="w")
704 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
705 # read the data to make sure the file is there
706 f = zipf.open("foo.txt")
707 for i in xrange(FIXEDTEST_SIZE):
708 self.assertEqual(f.read(0), '')
709
710 self.assertEqual(f.read(), "O, for a Muse of Fire!")
711 zipf.close()
712
713 def test_OpenNonexistentItem(self):
714 # Check that attempting to call open() for an item that doesn't
715 # exist in the archive raises a RuntimeError
716 zipf = zipfile.ZipFile(TESTFN, mode="w")
717 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
718
719 def test_BadCompressionMode(self):
720 # Check that bad compression methods passed to ZipFile.open are caught
721 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
722
723 def test_NullByteInFilename(self):
724 # Check that a filename containing a null byte is properly terminated
725 zipf = zipfile.ZipFile(TESTFN, mode="w")
726 zipf.writestr("foo.txt\x00qqq", "O, for a Muse of Fire!")
727 self.assertEqual(zipf.namelist(), ['foo.txt'])
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000728
Martin v. Löwis8c436412008-07-03 12:51:14 +0000729 def test_StructSizes(self):
730 # check that ZIP internal structure sizes are calculated correctly
731 self.assertEqual(zipfile.sizeEndCentDir, 22)
732 self.assertEqual(zipfile.sizeCentralDir, 46)
733 self.assertEqual(zipfile.sizeEndCentDir64, 56)
734 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
735
736 def testComments(self):
737 # This test checks that comments on the archive are handled properly
738
739 # check default comment is empty
740 zipf = zipfile.ZipFile(TESTFN, mode="w")
741 self.assertEqual(zipf.comment, '')
742 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
743 zipf.close()
744 zipfr = zipfile.ZipFile(TESTFN, mode="r")
745 self.assertEqual(zipfr.comment, '')
746 zipfr.close()
747
748 # check a simple short comment
749 comment = 'Bravely taking to his feet, he beat a very brave retreat.'
750 zipf = zipfile.ZipFile(TESTFN, mode="w")
751 zipf.comment = comment
752 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
753 zipf.close()
754 zipfr = zipfile.ZipFile(TESTFN, mode="r")
755 self.assertEqual(zipfr.comment, comment)
756 zipfr.close()
757
758 # check a comment of max length
759 comment2 = ''.join(['%d' % (i**3 % 10) for i in xrange((1 << 16)-1)])
760 zipf = zipfile.ZipFile(TESTFN, mode="w")
761 zipf.comment = comment2
762 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
763 zipf.close()
764 zipfr = zipfile.ZipFile(TESTFN, mode="r")
765 self.assertEqual(zipfr.comment, comment2)
766 zipfr.close()
767
768 # check a comment that is too long is truncated
769 zipf = zipfile.ZipFile(TESTFN, mode="w")
770 zipf.comment = comment2 + 'oops'
771 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
772 zipf.close()
773 zipfr = zipfile.ZipFile(TESTFN, mode="r")
774 self.assertEqual(zipfr.comment, comment2)
775 zipfr.close()
776
Collin Winter04a51ec2007-03-29 02:28:16 +0000777 def tearDown(self):
778 support.unlink(TESTFN)
779 support.unlink(TESTFN2)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000780
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000781class DecryptionTests(unittest.TestCase):
782 # This test checks that ZIP decryption works. Since the library does not
783 # support encryption at the moment, we use a pre-generated encrypted
784 # ZIP file
785
786 data = (
787 'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
788 '\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
789 '\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
790 'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
791 '\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
792 '\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
793 '\x00\x00L\x00\x00\x00\x00\x00' )
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000794 data2 = (
795 'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
796 '\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
797 '\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
798 'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
799 '\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
800 '\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
801 'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
802 '\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000803
804 plain = 'zipfile.py encryption test'
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000805 plain2 = '\x00'*512
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000806
807 def setUp(self):
808 fp = open(TESTFN, "wb")
809 fp.write(self.data)
810 fp.close()
811 self.zip = zipfile.ZipFile(TESTFN, "r")
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000812 fp = open(TESTFN2, "wb")
813 fp.write(self.data2)
814 fp.close()
815 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000816
817 def tearDown(self):
818 self.zip.close()
819 os.unlink(TESTFN)
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000820 self.zip2.close()
821 os.unlink(TESTFN2)
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000822
823 def testNoPassword(self):
824 # Reading the encrypted file without password
825 # must generate a RunTime exception
826 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000827 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000828
829 def testBadPassword(self):
830 self.zip.setpassword("perl")
831 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000832 self.zip2.setpassword("perl")
833 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Tim Petersea5962f2007-03-12 18:07:52 +0000834
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000835 def testGoodPassword(self):
836 self.zip.setpassword("python")
837 self.assertEquals(self.zip.read("test.txt"), self.plain)
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000838 self.zip2.setpassword("12345")
839 self.assertEquals(self.zip2.read("zero"), self.plain2)
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000840
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000841
842class TestsWithRandomBinaryFiles(unittest.TestCase):
843 def setUp(self):
844 datacount = randint(16, 64)*1024 + randint(1, 1024)
845 self.data = ''.join((struct.pack('<f', random()*randint(-1000, 1000)) for i in xrange(datacount)))
846
847 # Make a source file with some lines
848 fp = open(TESTFN, "wb")
849 fp.write(self.data)
850 fp.close()
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000851
Collin Winter04a51ec2007-03-29 02:28:16 +0000852 def tearDown(self):
853 support.unlink(TESTFN)
854 support.unlink(TESTFN2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000855
856 def makeTestArchive(self, f, compression):
857 # Create the ZIP archive
858 zipfp = zipfile.ZipFile(f, "w", compression)
859 zipfp.write(TESTFN, "another"+os.extsep+"name")
860 zipfp.write(TESTFN, TESTFN)
861 zipfp.close()
862
863 def zipTest(self, f, compression):
864 self.makeTestArchive(f, compression)
865
866 # Read the ZIP archive
867 zipfp = zipfile.ZipFile(f, "r", compression)
868 testdata = zipfp.read(TESTFN)
869 self.assertEqual(len(testdata), len(self.data))
870 self.assertEqual(testdata, self.data)
871 self.assertEqual(zipfp.read("another"+os.extsep+"name"), self.data)
872 zipfp.close()
873
874 def testStored(self):
875 for f in (TESTFN2, TemporaryFile(), StringIO()):
876 self.zipTest(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +0000877
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000878 def zipOpenTest(self, f, compression):
879 self.makeTestArchive(f, compression)
880
881 # Read the ZIP archive
882 zipfp = zipfile.ZipFile(f, "r", compression)
883 zipdata1 = []
884 zipopen1 = zipfp.open(TESTFN)
885 while 1:
886 read_data = zipopen1.read(256)
887 if not read_data:
888 break
889 zipdata1.append(read_data)
890
891 zipdata2 = []
892 zipopen2 = zipfp.open("another"+os.extsep+"name")
893 while 1:
894 read_data = zipopen2.read(256)
895 if not read_data:
896 break
897 zipdata2.append(read_data)
Tim Petersea5962f2007-03-12 18:07:52 +0000898
899 testdata1 = ''.join(zipdata1)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000900 self.assertEqual(len(testdata1), len(self.data))
901 self.assertEqual(testdata1, self.data)
902
Tim Petersea5962f2007-03-12 18:07:52 +0000903 testdata2 = ''.join(zipdata2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000904 self.assertEqual(len(testdata1), len(self.data))
905 self.assertEqual(testdata1, self.data)
906 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000907
908 def testOpenStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000909 for f in (TESTFN2, TemporaryFile(), StringIO()):
910 self.zipOpenTest(f, zipfile.ZIP_STORED)
911
912 def zipRandomOpenTest(self, f, compression):
913 self.makeTestArchive(f, compression)
914
915 # Read the ZIP archive
916 zipfp = zipfile.ZipFile(f, "r", compression)
917 zipdata1 = []
918 zipopen1 = zipfp.open(TESTFN)
919 while 1:
920 read_data = zipopen1.read(randint(1, 1024))
921 if not read_data:
922 break
923 zipdata1.append(read_data)
924
925 testdata = ''.join(zipdata1)
926 self.assertEqual(len(testdata), len(self.data))
927 self.assertEqual(testdata, self.data)
928 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000929
930 def testRandomOpenStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000931 for f in (TESTFN2, TemporaryFile(), StringIO()):
932 self.zipRandomOpenTest(f, zipfile.ZIP_STORED)
933
934class TestsWithMultipleOpens(unittest.TestCase):
935 def setUp(self):
936 # Create the ZIP archive
937 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED)
938 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
939 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
940 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000941
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000942 def testSameFile(self):
943 # Verify that (when the ZipFile is in control of creating file objects)
944 # multiple open() calls can be made without interfering with each other.
945 zipf = zipfile.ZipFile(TESTFN2, mode="r")
946 zopen1 = zipf.open('ones')
947 zopen2 = zipf.open('ones')
948 data1 = zopen1.read(500)
949 data2 = zopen2.read(500)
950 data1 += zopen1.read(500)
951 data2 += zopen2.read(500)
952 self.assertEqual(data1, data2)
953 zipf.close()
954
955 def testDifferentFile(self):
956 # Verify that (when the ZipFile is in control of creating file objects)
957 # multiple open() calls can be made without interfering with each other.
958 zipf = zipfile.ZipFile(TESTFN2, mode="r")
959 zopen1 = zipf.open('ones')
960 zopen2 = zipf.open('twos')
961 data1 = zopen1.read(500)
962 data2 = zopen2.read(500)
963 data1 += zopen1.read(500)
964 data2 += zopen2.read(500)
965 self.assertEqual(data1, '1'*FIXEDTEST_SIZE)
966 self.assertEqual(data2, '2'*FIXEDTEST_SIZE)
967 zipf.close()
968
969 def testInterleaved(self):
970 # Verify that (when the ZipFile is in control of creating file objects)
971 # multiple open() calls can be made without interfering with each other.
972 zipf = zipfile.ZipFile(TESTFN2, mode="r")
973 zopen1 = zipf.open('ones')
974 data1 = zopen1.read(500)
975 zopen2 = zipf.open('twos')
976 data2 = zopen2.read(500)
977 data1 += zopen1.read(500)
978 data2 += zopen2.read(500)
979 self.assertEqual(data1, '1'*FIXEDTEST_SIZE)
980 self.assertEqual(data2, '2'*FIXEDTEST_SIZE)
981 zipf.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000982
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000983 def tearDown(self):
984 os.remove(TESTFN2)
Tim Petersea5962f2007-03-12 18:07:52 +0000985
Martin v. Löwis3a8071a2009-01-24 14:04:33 +0000986class TestWithDirectory(unittest.TestCase):
987 def setUp(self):
988 os.mkdir(TESTFN2)
989
990 def testExtractDir(self):
991 zipf = zipfile.ZipFile(findfile("zipdir.zip"))
992 zipf.extractall(TESTFN2)
993 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
994 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
995 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
996
997 def testStoreDir(self):
998 os.mkdir(os.path.join(TESTFN2, "x"))
999 zipf = zipfile.ZipFile(TESTFN, "w")
1000 zipf.write(os.path.join(TESTFN2, "x"), "x")
1001 self.assertTrue(zipf.filelist[0].filename.endswith("x/"))
1002
1003 def tearDown(self):
1004 shutil.rmtree(TESTFN2)
1005 if os.path.exists(TESTFN):
1006 os.remove(TESTFN)
1007
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001008
1009class UniversalNewlineTests(unittest.TestCase):
1010 def setUp(self):
1011 self.line_gen = ["Test of zipfile line %d." % i for i in xrange(FIXEDTEST_SIZE)]
1012 self.seps = ('\r', '\r\n', '\n')
1013 self.arcdata, self.arcfiles = {}, {}
1014 for n, s in enumerate(self.seps):
1015 self.arcdata[s] = s.join(self.line_gen) + s
1016 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Brett Cannon6cef0762007-05-25 20:17:15 +00001017 open(self.arcfiles[s], "wb").write(self.arcdata[s])
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001018
1019 def makeTestArchive(self, f, compression):
1020 # Create the ZIP archive
1021 zipfp = zipfile.ZipFile(f, "w", compression)
1022 for fn in self.arcfiles.values():
1023 zipfp.write(fn, fn)
1024 zipfp.close()
1025
1026 def readTest(self, f, compression):
1027 self.makeTestArchive(f, compression)
1028
1029 # Read the ZIP archive
1030 zipfp = zipfile.ZipFile(f, "r")
1031 for sep, fn in self.arcfiles.items():
1032 zipdata = zipfp.open(fn, "rU").read()
1033 self.assertEqual(self.arcdata[sep], zipdata)
1034
1035 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +00001036
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001037 def readlineTest(self, f, compression):
1038 self.makeTestArchive(f, compression)
1039
1040 # Read the ZIP archive
1041 zipfp = zipfile.ZipFile(f, "r")
1042 for sep, fn in self.arcfiles.items():
1043 zipopen = zipfp.open(fn, "rU")
1044 for line in self.line_gen:
1045 linedata = zipopen.readline()
1046 self.assertEqual(linedata, line + '\n')
1047
1048 zipfp.close()
1049
1050 def readlinesTest(self, f, compression):
1051 self.makeTestArchive(f, compression)
1052
1053 # Read the ZIP archive
1054 zipfp = zipfile.ZipFile(f, "r")
1055 for sep, fn in self.arcfiles.items():
1056 ziplines = zipfp.open(fn, "rU").readlines()
1057 for line, zipline in zip(self.line_gen, ziplines):
1058 self.assertEqual(zipline, line + '\n')
1059
1060 zipfp.close()
1061
1062 def iterlinesTest(self, f, compression):
1063 self.makeTestArchive(f, compression)
1064
1065 # Read the ZIP archive
1066 zipfp = zipfile.ZipFile(f, "r")
1067 for sep, fn in self.arcfiles.items():
1068 for line, zipline in zip(self.line_gen, zipfp.open(fn, "rU")):
1069 self.assertEqual(zipline, line + '\n')
1070
1071 zipfp.close()
1072
Tim Petersea5962f2007-03-12 18:07:52 +00001073 def testReadStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001074 for f in (TESTFN2, TemporaryFile(), StringIO()):
1075 self.readTest(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +00001076
1077 def testReadlineStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001078 for f in (TESTFN2, TemporaryFile(), StringIO()):
1079 self.readlineTest(f, zipfile.ZIP_STORED)
1080
Tim Petersea5962f2007-03-12 18:07:52 +00001081 def testReadlinesStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001082 for f in (TESTFN2, TemporaryFile(), StringIO()):
1083 self.readlinesTest(f, zipfile.ZIP_STORED)
1084
Tim Petersea5962f2007-03-12 18:07:52 +00001085 def testIterlinesStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001086 for f in (TESTFN2, TemporaryFile(), StringIO()):
1087 self.iterlinesTest(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +00001088
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001089 if zlib:
Tim Petersea5962f2007-03-12 18:07:52 +00001090 def testReadDeflated(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001091 for f in (TESTFN2, TemporaryFile(), StringIO()):
1092 self.readTest(f, zipfile.ZIP_DEFLATED)
1093
Tim Petersea5962f2007-03-12 18:07:52 +00001094 def testReadlineDeflated(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001095 for f in (TESTFN2, TemporaryFile(), StringIO()):
1096 self.readlineTest(f, zipfile.ZIP_DEFLATED)
1097
Tim Petersea5962f2007-03-12 18:07:52 +00001098 def testReadlinesDeflated(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001099 for f in (TESTFN2, TemporaryFile(), StringIO()):
1100 self.readlinesTest(f, zipfile.ZIP_DEFLATED)
1101
Tim Petersea5962f2007-03-12 18:07:52 +00001102 def testIterlinesDeflated(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001103 for f in (TESTFN2, TemporaryFile(), StringIO()):
1104 self.iterlinesTest(f, zipfile.ZIP_DEFLATED)
1105
1106 def tearDown(self):
1107 for sep, fn in self.arcfiles.items():
1108 os.remove(fn)
Collin Winter04a51ec2007-03-29 02:28:16 +00001109 support.unlink(TESTFN)
1110 support.unlink(TESTFN2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001111
1112
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001113def test_main():
Tim Petersea5962f2007-03-12 18:07:52 +00001114 run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
1115 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
Martin v. Löwis3a8071a2009-01-24 14:04:33 +00001116 TestWithDirectory,
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001117 UniversalNewlineTests, TestsWithRandomBinaryFiles)
1118
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001119if __name__ == "__main__":
1120 test_main()