blob: a2c3a2c3fe00abe74a7a01a968d306895386f132 [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
R. David Murray981130b2010-01-06 20:08:02 +0000667 def test_empty_file_raises_BadZipFile(self):
668 f = open(TESTFN, 'w')
669 f.close()
670 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN)
671
672 f = open(TESTFN, 'w')
673 f.write("short file")
674 f.close()
675 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN)
676
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000677 def testClosedZipRaisesRuntimeError(self):
678 # Verify that testzip() doesn't swallow inappropriate exceptions.
679 data = StringIO()
680 zipf = zipfile.ZipFile(data, mode="w")
681 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
682 zipf.close()
683
684 # This is correct; calling .read on a closed ZipFile should throw
685 # a RuntimeError, and so should calling .testzip. An earlier
686 # version of .testzip would swallow this exception (and any other)
687 # and report that the first file in the archive was corrupt.
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000688 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
689 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000690 self.assertRaises(RuntimeError, zipf.testzip)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000691 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
692 file(TESTFN, 'w').write('zipfile test data')
693 self.assertRaises(RuntimeError, zipf.write, TESTFN)
694
695 def test_BadConstructorMode(self):
696 # Check that bad modes passed to ZipFile constructor are caught
697 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
698
699 def test_BadOpenMode(self):
700 # Check that bad modes passed to ZipFile.open are caught
701 zipf = zipfile.ZipFile(TESTFN, mode="w")
702 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
703 zipf.close()
704 zipf = zipfile.ZipFile(TESTFN, mode="r")
705 # read the data to make sure the file is there
706 zipf.read("foo.txt")
707 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
708 zipf.close()
709
710 def test_Read0(self):
711 # Check that calling read(0) on a ZipExtFile object returns an empty
712 # string and doesn't advance file pointer
713 zipf = zipfile.ZipFile(TESTFN, mode="w")
714 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
715 # read the data to make sure the file is there
716 f = zipf.open("foo.txt")
717 for i in xrange(FIXEDTEST_SIZE):
718 self.assertEqual(f.read(0), '')
719
720 self.assertEqual(f.read(), "O, for a Muse of Fire!")
721 zipf.close()
722
723 def test_OpenNonexistentItem(self):
724 # Check that attempting to call open() for an item that doesn't
725 # exist in the archive raises a RuntimeError
726 zipf = zipfile.ZipFile(TESTFN, mode="w")
727 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
728
729 def test_BadCompressionMode(self):
730 # Check that bad compression methods passed to ZipFile.open are caught
731 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
732
733 def test_NullByteInFilename(self):
734 # Check that a filename containing a null byte is properly terminated
735 zipf = zipfile.ZipFile(TESTFN, mode="w")
736 zipf.writestr("foo.txt\x00qqq", "O, for a Muse of Fire!")
737 self.assertEqual(zipf.namelist(), ['foo.txt'])
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000738
Martin v. Löwis8c436412008-07-03 12:51:14 +0000739 def test_StructSizes(self):
740 # check that ZIP internal structure sizes are calculated correctly
741 self.assertEqual(zipfile.sizeEndCentDir, 22)
742 self.assertEqual(zipfile.sizeCentralDir, 46)
743 self.assertEqual(zipfile.sizeEndCentDir64, 56)
744 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
745
746 def testComments(self):
747 # This test checks that comments on the archive are handled properly
748
749 # check default comment is empty
750 zipf = zipfile.ZipFile(TESTFN, mode="w")
751 self.assertEqual(zipf.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, '')
756 zipfr.close()
757
758 # check a simple short comment
759 comment = 'Bravely taking to his feet, he beat a very brave retreat.'
760 zipf = zipfile.ZipFile(TESTFN, mode="w")
761 zipf.comment = comment
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, comment)
766 zipfr.close()
767
768 # check a comment of max length
769 comment2 = ''.join(['%d' % (i**3 % 10) for i in xrange((1 << 16)-1)])
770 zipf = zipfile.ZipFile(TESTFN, mode="w")
771 zipf.comment = comment2
772 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
773 zipf.close()
774 zipfr = zipfile.ZipFile(TESTFN, mode="r")
775 self.assertEqual(zipfr.comment, comment2)
776 zipfr.close()
777
778 # check a comment that is too long is truncated
779 zipf = zipfile.ZipFile(TESTFN, mode="w")
780 zipf.comment = comment2 + 'oops'
781 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
782 zipf.close()
783 zipfr = zipfile.ZipFile(TESTFN, mode="r")
784 self.assertEqual(zipfr.comment, comment2)
785 zipfr.close()
786
Collin Winter04a51ec2007-03-29 02:28:16 +0000787 def tearDown(self):
788 support.unlink(TESTFN)
789 support.unlink(TESTFN2)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000790
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000791class DecryptionTests(unittest.TestCase):
792 # This test checks that ZIP decryption works. Since the library does not
793 # support encryption at the moment, we use a pre-generated encrypted
794 # ZIP file
795
796 data = (
797 'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
798 '\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
799 '\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
800 'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
801 '\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
802 '\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
803 '\x00\x00L\x00\x00\x00\x00\x00' )
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000804 data2 = (
805 'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
806 '\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
807 '\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
808 'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
809 '\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
810 '\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
811 'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
812 '\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000813
814 plain = 'zipfile.py encryption test'
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000815 plain2 = '\x00'*512
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000816
817 def setUp(self):
818 fp = open(TESTFN, "wb")
819 fp.write(self.data)
820 fp.close()
821 self.zip = zipfile.ZipFile(TESTFN, "r")
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000822 fp = open(TESTFN2, "wb")
823 fp.write(self.data2)
824 fp.close()
825 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000826
827 def tearDown(self):
828 self.zip.close()
829 os.unlink(TESTFN)
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000830 self.zip2.close()
831 os.unlink(TESTFN2)
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000832
833 def testNoPassword(self):
834 # Reading the encrypted file without password
835 # must generate a RunTime exception
836 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000837 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000838
839 def testBadPassword(self):
840 self.zip.setpassword("perl")
841 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000842 self.zip2.setpassword("perl")
843 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Tim Petersea5962f2007-03-12 18:07:52 +0000844
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000845 def testGoodPassword(self):
846 self.zip.setpassword("python")
847 self.assertEquals(self.zip.read("test.txt"), self.plain)
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000848 self.zip2.setpassword("12345")
849 self.assertEquals(self.zip2.read("zero"), self.plain2)
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000850
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000851
852class TestsWithRandomBinaryFiles(unittest.TestCase):
853 def setUp(self):
854 datacount = randint(16, 64)*1024 + randint(1, 1024)
855 self.data = ''.join((struct.pack('<f', random()*randint(-1000, 1000)) for i in xrange(datacount)))
856
857 # Make a source file with some lines
858 fp = open(TESTFN, "wb")
859 fp.write(self.data)
860 fp.close()
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000861
Collin Winter04a51ec2007-03-29 02:28:16 +0000862 def tearDown(self):
863 support.unlink(TESTFN)
864 support.unlink(TESTFN2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000865
866 def makeTestArchive(self, f, compression):
867 # Create the ZIP archive
868 zipfp = zipfile.ZipFile(f, "w", compression)
869 zipfp.write(TESTFN, "another"+os.extsep+"name")
870 zipfp.write(TESTFN, TESTFN)
871 zipfp.close()
872
873 def zipTest(self, f, compression):
874 self.makeTestArchive(f, compression)
875
876 # Read the ZIP archive
877 zipfp = zipfile.ZipFile(f, "r", compression)
878 testdata = zipfp.read(TESTFN)
879 self.assertEqual(len(testdata), len(self.data))
880 self.assertEqual(testdata, self.data)
881 self.assertEqual(zipfp.read("another"+os.extsep+"name"), self.data)
882 zipfp.close()
883
884 def testStored(self):
885 for f in (TESTFN2, TemporaryFile(), StringIO()):
886 self.zipTest(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +0000887
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000888 def zipOpenTest(self, f, compression):
889 self.makeTestArchive(f, compression)
890
891 # Read the ZIP archive
892 zipfp = zipfile.ZipFile(f, "r", compression)
893 zipdata1 = []
894 zipopen1 = zipfp.open(TESTFN)
895 while 1:
896 read_data = zipopen1.read(256)
897 if not read_data:
898 break
899 zipdata1.append(read_data)
900
901 zipdata2 = []
902 zipopen2 = zipfp.open("another"+os.extsep+"name")
903 while 1:
904 read_data = zipopen2.read(256)
905 if not read_data:
906 break
907 zipdata2.append(read_data)
Tim Petersea5962f2007-03-12 18:07:52 +0000908
909 testdata1 = ''.join(zipdata1)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000910 self.assertEqual(len(testdata1), len(self.data))
911 self.assertEqual(testdata1, self.data)
912
Tim Petersea5962f2007-03-12 18:07:52 +0000913 testdata2 = ''.join(zipdata2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000914 self.assertEqual(len(testdata1), len(self.data))
915 self.assertEqual(testdata1, self.data)
916 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000917
918 def testOpenStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000919 for f in (TESTFN2, TemporaryFile(), StringIO()):
920 self.zipOpenTest(f, zipfile.ZIP_STORED)
921
922 def zipRandomOpenTest(self, f, compression):
923 self.makeTestArchive(f, compression)
924
925 # Read the ZIP archive
926 zipfp = zipfile.ZipFile(f, "r", compression)
927 zipdata1 = []
928 zipopen1 = zipfp.open(TESTFN)
929 while 1:
930 read_data = zipopen1.read(randint(1, 1024))
931 if not read_data:
932 break
933 zipdata1.append(read_data)
934
935 testdata = ''.join(zipdata1)
936 self.assertEqual(len(testdata), len(self.data))
937 self.assertEqual(testdata, self.data)
938 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000939
940 def testRandomOpenStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000941 for f in (TESTFN2, TemporaryFile(), StringIO()):
942 self.zipRandomOpenTest(f, zipfile.ZIP_STORED)
943
944class TestsWithMultipleOpens(unittest.TestCase):
945 def setUp(self):
946 # Create the ZIP archive
947 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED)
948 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
949 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
950 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000951
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000952 def testSameFile(self):
953 # Verify that (when the ZipFile is in control of creating file objects)
954 # multiple open() calls can be made without interfering with each other.
955 zipf = zipfile.ZipFile(TESTFN2, mode="r")
956 zopen1 = zipf.open('ones')
957 zopen2 = zipf.open('ones')
958 data1 = zopen1.read(500)
959 data2 = zopen2.read(500)
960 data1 += zopen1.read(500)
961 data2 += zopen2.read(500)
962 self.assertEqual(data1, data2)
963 zipf.close()
964
965 def testDifferentFile(self):
966 # Verify that (when the ZipFile is in control of creating file objects)
967 # multiple open() calls can be made without interfering with each other.
968 zipf = zipfile.ZipFile(TESTFN2, mode="r")
969 zopen1 = zipf.open('ones')
970 zopen2 = zipf.open('twos')
971 data1 = zopen1.read(500)
972 data2 = zopen2.read(500)
973 data1 += zopen1.read(500)
974 data2 += zopen2.read(500)
975 self.assertEqual(data1, '1'*FIXEDTEST_SIZE)
976 self.assertEqual(data2, '2'*FIXEDTEST_SIZE)
977 zipf.close()
978
979 def testInterleaved(self):
980 # Verify that (when the ZipFile is in control of creating file objects)
981 # multiple open() calls can be made without interfering with each other.
982 zipf = zipfile.ZipFile(TESTFN2, mode="r")
983 zopen1 = zipf.open('ones')
984 data1 = zopen1.read(500)
985 zopen2 = zipf.open('twos')
986 data2 = zopen2.read(500)
987 data1 += zopen1.read(500)
988 data2 += zopen2.read(500)
989 self.assertEqual(data1, '1'*FIXEDTEST_SIZE)
990 self.assertEqual(data2, '2'*FIXEDTEST_SIZE)
991 zipf.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000992
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000993 def tearDown(self):
994 os.remove(TESTFN2)
Tim Petersea5962f2007-03-12 18:07:52 +0000995
Martin v. Löwis3a8071a2009-01-24 14:04:33 +0000996class TestWithDirectory(unittest.TestCase):
997 def setUp(self):
998 os.mkdir(TESTFN2)
999
1000 def testExtractDir(self):
1001 zipf = zipfile.ZipFile(findfile("zipdir.zip"))
1002 zipf.extractall(TESTFN2)
1003 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1004 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1005 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1006
Martin v. Löwise7e46f82009-05-24 19:42:14 +00001007 def test_bug_6050(self):
1008 # Extraction should succeed if directories already exist
1009 os.mkdir(os.path.join(TESTFN2, "a"))
1010 self.testExtractDir()
1011
Martin v. Löwis3a8071a2009-01-24 14:04:33 +00001012 def testStoreDir(self):
1013 os.mkdir(os.path.join(TESTFN2, "x"))
1014 zipf = zipfile.ZipFile(TESTFN, "w")
1015 zipf.write(os.path.join(TESTFN2, "x"), "x")
1016 self.assertTrue(zipf.filelist[0].filename.endswith("x/"))
1017
1018 def tearDown(self):
1019 shutil.rmtree(TESTFN2)
1020 if os.path.exists(TESTFN):
1021 os.remove(TESTFN)
1022
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001023
1024class UniversalNewlineTests(unittest.TestCase):
1025 def setUp(self):
1026 self.line_gen = ["Test of zipfile line %d." % i for i in xrange(FIXEDTEST_SIZE)]
1027 self.seps = ('\r', '\r\n', '\n')
1028 self.arcdata, self.arcfiles = {}, {}
1029 for n, s in enumerate(self.seps):
1030 self.arcdata[s] = s.join(self.line_gen) + s
1031 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Brett Cannon6cef0762007-05-25 20:17:15 +00001032 open(self.arcfiles[s], "wb").write(self.arcdata[s])
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001033
1034 def makeTestArchive(self, f, compression):
1035 # Create the ZIP archive
1036 zipfp = zipfile.ZipFile(f, "w", compression)
1037 for fn in self.arcfiles.values():
1038 zipfp.write(fn, fn)
1039 zipfp.close()
1040
1041 def readTest(self, f, compression):
1042 self.makeTestArchive(f, compression)
1043
1044 # Read the ZIP archive
1045 zipfp = zipfile.ZipFile(f, "r")
1046 for sep, fn in self.arcfiles.items():
1047 zipdata = zipfp.open(fn, "rU").read()
1048 self.assertEqual(self.arcdata[sep], zipdata)
1049
1050 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +00001051
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001052 def readlineTest(self, f, compression):
1053 self.makeTestArchive(f, compression)
1054
1055 # Read the ZIP archive
1056 zipfp = zipfile.ZipFile(f, "r")
1057 for sep, fn in self.arcfiles.items():
1058 zipopen = zipfp.open(fn, "rU")
1059 for line in self.line_gen:
1060 linedata = zipopen.readline()
1061 self.assertEqual(linedata, line + '\n')
1062
1063 zipfp.close()
1064
1065 def readlinesTest(self, f, compression):
1066 self.makeTestArchive(f, compression)
1067
1068 # Read the ZIP archive
1069 zipfp = zipfile.ZipFile(f, "r")
1070 for sep, fn in self.arcfiles.items():
1071 ziplines = zipfp.open(fn, "rU").readlines()
1072 for line, zipline in zip(self.line_gen, ziplines):
1073 self.assertEqual(zipline, line + '\n')
1074
1075 zipfp.close()
1076
1077 def iterlinesTest(self, f, compression):
1078 self.makeTestArchive(f, compression)
1079
1080 # Read the ZIP archive
1081 zipfp = zipfile.ZipFile(f, "r")
1082 for sep, fn in self.arcfiles.items():
1083 for line, zipline in zip(self.line_gen, zipfp.open(fn, "rU")):
1084 self.assertEqual(zipline, line + '\n')
1085
1086 zipfp.close()
1087
Tim Petersea5962f2007-03-12 18:07:52 +00001088 def testReadStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001089 for f in (TESTFN2, TemporaryFile(), StringIO()):
1090 self.readTest(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +00001091
1092 def testReadlineStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001093 for f in (TESTFN2, TemporaryFile(), StringIO()):
1094 self.readlineTest(f, zipfile.ZIP_STORED)
1095
Tim Petersea5962f2007-03-12 18:07:52 +00001096 def testReadlinesStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001097 for f in (TESTFN2, TemporaryFile(), StringIO()):
1098 self.readlinesTest(f, zipfile.ZIP_STORED)
1099
Tim Petersea5962f2007-03-12 18:07:52 +00001100 def testIterlinesStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001101 for f in (TESTFN2, TemporaryFile(), StringIO()):
1102 self.iterlinesTest(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +00001103
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001104 if zlib:
Tim Petersea5962f2007-03-12 18:07:52 +00001105 def testReadDeflated(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001106 for f in (TESTFN2, TemporaryFile(), StringIO()):
1107 self.readTest(f, zipfile.ZIP_DEFLATED)
1108
Tim Petersea5962f2007-03-12 18:07:52 +00001109 def testReadlineDeflated(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001110 for f in (TESTFN2, TemporaryFile(), StringIO()):
1111 self.readlineTest(f, zipfile.ZIP_DEFLATED)
1112
Tim Petersea5962f2007-03-12 18:07:52 +00001113 def testReadlinesDeflated(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001114 for f in (TESTFN2, TemporaryFile(), StringIO()):
1115 self.readlinesTest(f, zipfile.ZIP_DEFLATED)
1116
Tim Petersea5962f2007-03-12 18:07:52 +00001117 def testIterlinesDeflated(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001118 for f in (TESTFN2, TemporaryFile(), StringIO()):
1119 self.iterlinesTest(f, zipfile.ZIP_DEFLATED)
1120
1121 def tearDown(self):
1122 for sep, fn in self.arcfiles.items():
1123 os.remove(fn)
Collin Winter04a51ec2007-03-29 02:28:16 +00001124 support.unlink(TESTFN)
1125 support.unlink(TESTFN2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001126
1127
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001128def test_main():
Tim Petersea5962f2007-03-12 18:07:52 +00001129 run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
1130 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
Martin v. Löwis3a8071a2009-01-24 14:04:33 +00001131 TestWithDirectory,
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001132 UniversalNewlineTests, TestsWithRandomBinaryFiles)
1133
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001134if __name__ == "__main__":
1135 test_main()