blob: 0b0727dd58f417449cf48ead94bf4764a977bad8 [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öwis0dfcfc82009-01-24 14:00: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öwis0dfcfc82009-01-24 14:00: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
Benjamin Peterson5c8da862009-06-30 22:57:08 +000067 self.assertTrue('File Name' in lines[0])
68 self.assertTrue('Modified' in lines[0])
69 self.assertTrue('Size' in lines[0])
Ronald Oussoren143cefb2006-06-15 08:14:18 +000070
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)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000079 self.assertTrue(TESTFN in names)
80 self.assertTrue("another"+os.extsep+"name" in names)
81 self.assertTrue("strfile" in names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +000082
83 # Check infolist
84 infos = zipfp.infolist()
85 names = [ i.filename for i in infos ]
86 self.assertEquals(len(names), 3)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000087 self.assertTrue(TESTFN in names)
88 self.assertTrue("another"+os.extsep+"name" in names)
89 self.assertTrue("strfile" in names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +000090 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()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000148 self.assertTrue(data == "foobar" or data == "barfoo")
Georg Brandl112aa502008-05-20 08:25:48 +0000149 data = ""
150 for info in infos:
151 data += zipfp.read(info)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000152 self.assertTrue(data == "foobar" or data == "barfoo")
Georg Brandl112aa502008-05-20 08:25:48 +0000153 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
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000454 self.assertTrue('File Name' in lines[0])
455 self.assertTrue('Modified' in lines[0])
456 self.assertTrue('Size' in lines[0])
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000457
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)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000466 self.assertTrue(TESTFN in names)
467 self.assertTrue("another"+os.extsep+"name" in names)
468 self.assertTrue("strfile" in names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000469
470 # Check infolist
471 infos = zipfp.infolist()
472 names = [ i.filename for i in infos ]
473 self.assertEquals(len(names), 3)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000474 self.assertTrue(TESTFN in names)
475 self.assertTrue("another"+os.extsep+"name" in names)
476 self.assertTrue("strfile" in names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000477 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)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000526 self.assertTrue(bn not in zipfp.namelist())
527 self.assertTrue(bn + 'o' in zipfp.namelist() or bn + 'c' in zipfp.namelist())
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000528 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))
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000539 self.assertTrue(bn not in zipfp.namelist())
540 self.assertTrue(bn + 'o' in zipfp.namelist() or bn + 'c' in zipfp.namelist())
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000541 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()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000552 self.assertTrue('email/__init__.pyo' in names or 'email/__init__.pyc' in names)
553 self.assertTrue('email/mime/text.pyo' in names or 'email/mime/text.pyc' in names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000554
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()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000574 self.assertTrue('mod1.pyc' in names or 'mod1.pyo' in names)
575 self.assertTrue('mod2.pyc' in names or 'mod2.pyo' in names)
576 self.assertTrue('mod2.txt' not in names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000577
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
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000614 self.assertTrue(os.path.exists(TESTFN))
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000615
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
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000638
639 # - passing a filename
640 with open(TESTFN, "w") as fp:
641 fp.write("this is not a legal zip file\n")
Tim Petersea5962f2007-03-12 18:07:52 +0000642 chk = zipfile.is_zipfile(TESTFN)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000643 self.assertTrue(not chk)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000644 # - passing a file object
645 with open(TESTFN, "rb") as fp:
646 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000647 self.assertTrue(not chk)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000648 # - passing a file-like object
649 fp = StringIO()
650 fp.write("this is not a legal zip file\n")
651 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000652 self.assertTrue(not chk)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000653 fp.seek(0,0)
654 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000655 self.assertTrue(not chk)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000656
657 def testIsZipValidFile(self):
Tim Petersea5962f2007-03-12 18:07:52 +0000658 # This test checks that the is_zipfile function correctly identifies
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000659 # a file that is a zip file
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000660
661 # - passing a filename
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000662 zipf = zipfile.ZipFile(TESTFN, mode="w")
663 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
664 zipf.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000665 chk = zipfile.is_zipfile(TESTFN)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000666 self.assertTrue(chk)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000667 # - passing a file object
668 with open(TESTFN, "rb") as fp:
669 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000670 self.assertTrue(chk)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000671 fp.seek(0,0)
672 zip_contents = fp.read()
673 # - passing a file-like object
674 fp = StringIO()
675 fp.write(zip_contents)
676 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000677 self.assertTrue(chk)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000678 fp.seek(0,0)
679 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000680 self.assertTrue(chk)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000681
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000682 def testNonExistentFileRaisesIOError(self):
683 # make sure we don't raise an AttributeError when a partially-constructed
684 # ZipFile instance is finalized; this tests for regression on SF tracker
685 # bug #403871.
686
687 # The bug we're testing for caused an AttributeError to be raised
688 # when a ZipFile instance was created for a file that did not
689 # exist; the .fp member was not initialized but was needed by the
690 # __del__() method. Since the AttributeError is in the __del__(),
691 # it is ignored, but the user should be sufficiently annoyed by
692 # the message on the output that regression will be noticed
693 # quickly.
694 self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
695
696 def testClosedZipRaisesRuntimeError(self):
697 # Verify that testzip() doesn't swallow inappropriate exceptions.
698 data = StringIO()
699 zipf = zipfile.ZipFile(data, mode="w")
700 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
701 zipf.close()
702
703 # This is correct; calling .read on a closed ZipFile should throw
704 # a RuntimeError, and so should calling .testzip. An earlier
705 # version of .testzip would swallow this exception (and any other)
706 # and report that the first file in the archive was corrupt.
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000707 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
708 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000709 self.assertRaises(RuntimeError, zipf.testzip)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000710 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
711 file(TESTFN, 'w').write('zipfile test data')
712 self.assertRaises(RuntimeError, zipf.write, TESTFN)
713
714 def test_BadConstructorMode(self):
715 # Check that bad modes passed to ZipFile constructor are caught
716 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
717
718 def test_BadOpenMode(self):
719 # Check that bad modes passed to ZipFile.open are caught
720 zipf = zipfile.ZipFile(TESTFN, mode="w")
721 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
722 zipf.close()
723 zipf = zipfile.ZipFile(TESTFN, mode="r")
724 # read the data to make sure the file is there
725 zipf.read("foo.txt")
726 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
727 zipf.close()
728
729 def test_Read0(self):
730 # Check that calling read(0) on a ZipExtFile object returns an empty
731 # string and doesn't advance file pointer
732 zipf = zipfile.ZipFile(TESTFN, mode="w")
733 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
734 # read the data to make sure the file is there
735 f = zipf.open("foo.txt")
736 for i in xrange(FIXEDTEST_SIZE):
737 self.assertEqual(f.read(0), '')
738
739 self.assertEqual(f.read(), "O, for a Muse of Fire!")
740 zipf.close()
741
742 def test_OpenNonexistentItem(self):
743 # Check that attempting to call open() for an item that doesn't
744 # exist in the archive raises a RuntimeError
745 zipf = zipfile.ZipFile(TESTFN, mode="w")
746 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
747
748 def test_BadCompressionMode(self):
749 # Check that bad compression methods passed to ZipFile.open are caught
750 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
751
752 def test_NullByteInFilename(self):
753 # Check that a filename containing a null byte is properly terminated
754 zipf = zipfile.ZipFile(TESTFN, mode="w")
755 zipf.writestr("foo.txt\x00qqq", "O, for a Muse of Fire!")
756 self.assertEqual(zipf.namelist(), ['foo.txt'])
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000757
Martin v. Löwis8c436412008-07-03 12:51:14 +0000758 def test_StructSizes(self):
759 # check that ZIP internal structure sizes are calculated correctly
760 self.assertEqual(zipfile.sizeEndCentDir, 22)
761 self.assertEqual(zipfile.sizeCentralDir, 46)
762 self.assertEqual(zipfile.sizeEndCentDir64, 56)
763 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
764
765 def testComments(self):
766 # This test checks that comments on the archive are handled properly
767
768 # check default comment is empty
769 zipf = zipfile.ZipFile(TESTFN, mode="w")
770 self.assertEqual(zipf.comment, '')
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, '')
775 zipfr.close()
776
777 # check a simple short comment
778 comment = 'Bravely taking to his feet, he beat a very brave retreat.'
779 zipf = zipfile.ZipFile(TESTFN, mode="w")
780 zipf.comment = comment
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, comment)
785 zipfr.close()
786
787 # check a comment of max length
788 comment2 = ''.join(['%d' % (i**3 % 10) for i in xrange((1 << 16)-1)])
789 zipf = zipfile.ZipFile(TESTFN, mode="w")
790 zipf.comment = comment2
791 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
792 zipf.close()
793 zipfr = zipfile.ZipFile(TESTFN, mode="r")
794 self.assertEqual(zipfr.comment, comment2)
795 zipfr.close()
796
797 # check a comment that is too long is truncated
798 zipf = zipfile.ZipFile(TESTFN, mode="w")
799 zipf.comment = comment2 + 'oops'
800 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
801 zipf.close()
802 zipfr = zipfile.ZipFile(TESTFN, mode="r")
803 self.assertEqual(zipfr.comment, comment2)
804 zipfr.close()
805
Collin Winter04a51ec2007-03-29 02:28:16 +0000806 def tearDown(self):
807 support.unlink(TESTFN)
808 support.unlink(TESTFN2)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000809
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000810class DecryptionTests(unittest.TestCase):
811 # This test checks that ZIP decryption works. Since the library does not
812 # support encryption at the moment, we use a pre-generated encrypted
813 # ZIP file
814
815 data = (
816 'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
817 '\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
818 '\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
819 'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
820 '\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
821 '\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
822 '\x00\x00L\x00\x00\x00\x00\x00' )
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000823 data2 = (
824 'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
825 '\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
826 '\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
827 'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
828 '\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
829 '\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
830 'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
831 '\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000832
833 plain = 'zipfile.py encryption test'
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000834 plain2 = '\x00'*512
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000835
836 def setUp(self):
837 fp = open(TESTFN, "wb")
838 fp.write(self.data)
839 fp.close()
840 self.zip = zipfile.ZipFile(TESTFN, "r")
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000841 fp = open(TESTFN2, "wb")
842 fp.write(self.data2)
843 fp.close()
844 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000845
846 def tearDown(self):
847 self.zip.close()
848 os.unlink(TESTFN)
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000849 self.zip2.close()
850 os.unlink(TESTFN2)
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000851
852 def testNoPassword(self):
853 # Reading the encrypted file without password
854 # must generate a RunTime exception
855 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000856 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000857
858 def testBadPassword(self):
859 self.zip.setpassword("perl")
860 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000861 self.zip2.setpassword("perl")
862 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Tim Petersea5962f2007-03-12 18:07:52 +0000863
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000864 def testGoodPassword(self):
865 self.zip.setpassword("python")
866 self.assertEquals(self.zip.read("test.txt"), self.plain)
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000867 self.zip2.setpassword("12345")
868 self.assertEquals(self.zip2.read("zero"), self.plain2)
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000869
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000870
871class TestsWithRandomBinaryFiles(unittest.TestCase):
872 def setUp(self):
873 datacount = randint(16, 64)*1024 + randint(1, 1024)
874 self.data = ''.join((struct.pack('<f', random()*randint(-1000, 1000)) for i in xrange(datacount)))
875
876 # Make a source file with some lines
877 fp = open(TESTFN, "wb")
878 fp.write(self.data)
879 fp.close()
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000880
Collin Winter04a51ec2007-03-29 02:28:16 +0000881 def tearDown(self):
882 support.unlink(TESTFN)
883 support.unlink(TESTFN2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000884
885 def makeTestArchive(self, f, compression):
886 # Create the ZIP archive
887 zipfp = zipfile.ZipFile(f, "w", compression)
888 zipfp.write(TESTFN, "another"+os.extsep+"name")
889 zipfp.write(TESTFN, TESTFN)
890 zipfp.close()
891
892 def zipTest(self, f, compression):
893 self.makeTestArchive(f, compression)
894
895 # Read the ZIP archive
896 zipfp = zipfile.ZipFile(f, "r", compression)
897 testdata = zipfp.read(TESTFN)
898 self.assertEqual(len(testdata), len(self.data))
899 self.assertEqual(testdata, self.data)
900 self.assertEqual(zipfp.read("another"+os.extsep+"name"), self.data)
901 zipfp.close()
902
903 def testStored(self):
904 for f in (TESTFN2, TemporaryFile(), StringIO()):
905 self.zipTest(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +0000906
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000907 def zipOpenTest(self, f, compression):
908 self.makeTestArchive(f, compression)
909
910 # Read the ZIP archive
911 zipfp = zipfile.ZipFile(f, "r", compression)
912 zipdata1 = []
913 zipopen1 = zipfp.open(TESTFN)
914 while 1:
915 read_data = zipopen1.read(256)
916 if not read_data:
917 break
918 zipdata1.append(read_data)
919
920 zipdata2 = []
921 zipopen2 = zipfp.open("another"+os.extsep+"name")
922 while 1:
923 read_data = zipopen2.read(256)
924 if not read_data:
925 break
926 zipdata2.append(read_data)
Tim Petersea5962f2007-03-12 18:07:52 +0000927
928 testdata1 = ''.join(zipdata1)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000929 self.assertEqual(len(testdata1), len(self.data))
930 self.assertEqual(testdata1, self.data)
931
Tim Petersea5962f2007-03-12 18:07:52 +0000932 testdata2 = ''.join(zipdata2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000933 self.assertEqual(len(testdata1), len(self.data))
934 self.assertEqual(testdata1, self.data)
935 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000936
937 def testOpenStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000938 for f in (TESTFN2, TemporaryFile(), StringIO()):
939 self.zipOpenTest(f, zipfile.ZIP_STORED)
940
941 def zipRandomOpenTest(self, f, compression):
942 self.makeTestArchive(f, compression)
943
944 # Read the ZIP archive
945 zipfp = zipfile.ZipFile(f, "r", compression)
946 zipdata1 = []
947 zipopen1 = zipfp.open(TESTFN)
948 while 1:
949 read_data = zipopen1.read(randint(1, 1024))
950 if not read_data:
951 break
952 zipdata1.append(read_data)
953
954 testdata = ''.join(zipdata1)
955 self.assertEqual(len(testdata), len(self.data))
956 self.assertEqual(testdata, self.data)
957 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000958
959 def testRandomOpenStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000960 for f in (TESTFN2, TemporaryFile(), StringIO()):
961 self.zipRandomOpenTest(f, zipfile.ZIP_STORED)
962
963class TestsWithMultipleOpens(unittest.TestCase):
964 def setUp(self):
965 # Create the ZIP archive
966 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED)
967 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
968 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
969 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000970
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000971 def testSameFile(self):
972 # Verify that (when the ZipFile is in control of creating file objects)
973 # multiple open() calls can be made without interfering with each other.
974 zipf = zipfile.ZipFile(TESTFN2, mode="r")
975 zopen1 = zipf.open('ones')
976 zopen2 = zipf.open('ones')
977 data1 = zopen1.read(500)
978 data2 = zopen2.read(500)
979 data1 += zopen1.read(500)
980 data2 += zopen2.read(500)
981 self.assertEqual(data1, data2)
982 zipf.close()
983
984 def testDifferentFile(self):
985 # Verify that (when the ZipFile is in control of creating file objects)
986 # multiple open() calls can be made without interfering with each other.
987 zipf = zipfile.ZipFile(TESTFN2, mode="r")
988 zopen1 = zipf.open('ones')
989 zopen2 = zipf.open('twos')
990 data1 = zopen1.read(500)
991 data2 = zopen2.read(500)
992 data1 += zopen1.read(500)
993 data2 += zopen2.read(500)
994 self.assertEqual(data1, '1'*FIXEDTEST_SIZE)
995 self.assertEqual(data2, '2'*FIXEDTEST_SIZE)
996 zipf.close()
997
998 def testInterleaved(self):
999 # Verify that (when the ZipFile is in control of creating file objects)
1000 # multiple open() calls can be made without interfering with each other.
1001 zipf = zipfile.ZipFile(TESTFN2, mode="r")
1002 zopen1 = zipf.open('ones')
1003 data1 = zopen1.read(500)
1004 zopen2 = zipf.open('twos')
1005 data2 = zopen2.read(500)
1006 data1 += zopen1.read(500)
1007 data2 += zopen2.read(500)
1008 self.assertEqual(data1, '1'*FIXEDTEST_SIZE)
1009 self.assertEqual(data2, '2'*FIXEDTEST_SIZE)
1010 zipf.close()
Tim Petersea5962f2007-03-12 18:07:52 +00001011
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001012 def tearDown(self):
1013 os.remove(TESTFN2)
Tim Petersea5962f2007-03-12 18:07:52 +00001014
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001015class TestWithDirectory(unittest.TestCase):
1016 def setUp(self):
1017 os.mkdir(TESTFN2)
1018
1019 def testExtractDir(self):
1020 zipf = zipfile.ZipFile(findfile("zipdir.zip"))
1021 zipf.extractall(TESTFN2)
1022 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1023 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1024 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1025
Martin v. Löwis0b09c422009-05-24 19:30:52 +00001026 def test_bug_6050(self):
1027 # Extraction should succeed if directories already exist
1028 os.mkdir(os.path.join(TESTFN2, "a"))
1029 self.testExtractDir()
1030
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001031 def testStoreDir(self):
1032 os.mkdir(os.path.join(TESTFN2, "x"))
1033 zipf = zipfile.ZipFile(TESTFN, "w")
1034 zipf.write(os.path.join(TESTFN2, "x"), "x")
1035 self.assertTrue(zipf.filelist[0].filename.endswith("x/"))
1036
1037 def tearDown(self):
1038 shutil.rmtree(TESTFN2)
1039 if os.path.exists(TESTFN):
1040 os.remove(TESTFN)
1041
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001042
1043class UniversalNewlineTests(unittest.TestCase):
1044 def setUp(self):
1045 self.line_gen = ["Test of zipfile line %d." % i for i in xrange(FIXEDTEST_SIZE)]
1046 self.seps = ('\r', '\r\n', '\n')
1047 self.arcdata, self.arcfiles = {}, {}
1048 for n, s in enumerate(self.seps):
1049 self.arcdata[s] = s.join(self.line_gen) + s
1050 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Brett Cannon6cef0762007-05-25 20:17:15 +00001051 open(self.arcfiles[s], "wb").write(self.arcdata[s])
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001052
1053 def makeTestArchive(self, f, compression):
1054 # Create the ZIP archive
1055 zipfp = zipfile.ZipFile(f, "w", compression)
1056 for fn in self.arcfiles.values():
1057 zipfp.write(fn, fn)
1058 zipfp.close()
1059
1060 def readTest(self, f, compression):
1061 self.makeTestArchive(f, compression)
1062
1063 # Read the ZIP archive
1064 zipfp = zipfile.ZipFile(f, "r")
1065 for sep, fn in self.arcfiles.items():
1066 zipdata = zipfp.open(fn, "rU").read()
1067 self.assertEqual(self.arcdata[sep], zipdata)
1068
1069 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +00001070
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001071 def readlineTest(self, f, compression):
1072 self.makeTestArchive(f, compression)
1073
1074 # Read the ZIP archive
1075 zipfp = zipfile.ZipFile(f, "r")
1076 for sep, fn in self.arcfiles.items():
1077 zipopen = zipfp.open(fn, "rU")
1078 for line in self.line_gen:
1079 linedata = zipopen.readline()
1080 self.assertEqual(linedata, line + '\n')
1081
1082 zipfp.close()
1083
1084 def readlinesTest(self, f, compression):
1085 self.makeTestArchive(f, compression)
1086
1087 # Read the ZIP archive
1088 zipfp = zipfile.ZipFile(f, "r")
1089 for sep, fn in self.arcfiles.items():
1090 ziplines = zipfp.open(fn, "rU").readlines()
1091 for line, zipline in zip(self.line_gen, ziplines):
1092 self.assertEqual(zipline, line + '\n')
1093
1094 zipfp.close()
1095
1096 def iterlinesTest(self, f, compression):
1097 self.makeTestArchive(f, compression)
1098
1099 # Read the ZIP archive
1100 zipfp = zipfile.ZipFile(f, "r")
1101 for sep, fn in self.arcfiles.items():
1102 for line, zipline in zip(self.line_gen, zipfp.open(fn, "rU")):
1103 self.assertEqual(zipline, line + '\n')
1104
1105 zipfp.close()
1106
Tim Petersea5962f2007-03-12 18:07:52 +00001107 def testReadStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001108 for f in (TESTFN2, TemporaryFile(), StringIO()):
1109 self.readTest(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +00001110
1111 def testReadlineStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001112 for f in (TESTFN2, TemporaryFile(), StringIO()):
1113 self.readlineTest(f, zipfile.ZIP_STORED)
1114
Tim Petersea5962f2007-03-12 18:07:52 +00001115 def testReadlinesStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001116 for f in (TESTFN2, TemporaryFile(), StringIO()):
1117 self.readlinesTest(f, zipfile.ZIP_STORED)
1118
Tim Petersea5962f2007-03-12 18:07:52 +00001119 def testIterlinesStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001120 for f in (TESTFN2, TemporaryFile(), StringIO()):
1121 self.iterlinesTest(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +00001122
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001123 if zlib:
Tim Petersea5962f2007-03-12 18:07:52 +00001124 def testReadDeflated(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001125 for f in (TESTFN2, TemporaryFile(), StringIO()):
1126 self.readTest(f, zipfile.ZIP_DEFLATED)
1127
Tim Petersea5962f2007-03-12 18:07:52 +00001128 def testReadlineDeflated(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001129 for f in (TESTFN2, TemporaryFile(), StringIO()):
1130 self.readlineTest(f, zipfile.ZIP_DEFLATED)
1131
Tim Petersea5962f2007-03-12 18:07:52 +00001132 def testReadlinesDeflated(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001133 for f in (TESTFN2, TemporaryFile(), StringIO()):
1134 self.readlinesTest(f, zipfile.ZIP_DEFLATED)
1135
Tim Petersea5962f2007-03-12 18:07:52 +00001136 def testIterlinesDeflated(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001137 for f in (TESTFN2, TemporaryFile(), StringIO()):
1138 self.iterlinesTest(f, zipfile.ZIP_DEFLATED)
1139
1140 def tearDown(self):
1141 for sep, fn in self.arcfiles.items():
1142 os.remove(fn)
Collin Winter04a51ec2007-03-29 02:28:16 +00001143 support.unlink(TESTFN)
1144 support.unlink(TESTFN2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001145
1146
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001147def test_main():
Tim Petersea5962f2007-03-12 18:07:52 +00001148 run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
1149 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001150 TestWithDirectory,
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001151 UniversalNewlineTests, TestsWithRandomBinaryFiles)
1152
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001153if __name__ == "__main__":
1154 test_main()