blob: 8ddfbddc3709fddbe61f0604a857aecef0802418 [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
Ezio Melottie7a0cc22009-07-04 14:58:27 +00007import os
8import sys
9import shutil
10import struct
11import zipfile
12import unittest
Tim Petersa19a1682001-03-29 04:36:09 +000013
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000014from StringIO import StringIO
15from tempfile import TemporaryFile
Martin v. Löwis3eb76482007-03-06 10:41:24 +000016from random import randint, random
Ezio Melottie7a0cc22009-07-04 14:58:27 +000017from unittest import skipUnless
Tim Petersa19a1682001-03-29 04:36:09 +000018
Collin Winter04a51ec2007-03-29 02:28:16 +000019import test.test_support as support
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +000020from test.test_support import TESTFN, run_unittest, findfile
Guido van Rossum368f04a2000-04-10 13:23:04 +000021
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000022TESTFN2 = TESTFN + "2"
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +000023TESTFNDIR = TESTFN + "d"
Georg Brandl4b3ab6f2007-07-12 09:59:22 +000024FIXEDTEST_SIZE = 1000
Guido van Rossum368f04a2000-04-10 13:23:04 +000025
Georg Brandl62416bc2008-01-07 18:47:44 +000026SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'),
27 ('ziptest2dir/_ziptest2', 'qawsedrftg'),
28 ('/ziptest2dir/ziptest3dir/_ziptest3', 'azsxdcfvgb'),
29 ('ziptest2dir/ziptest3dir/ziptest4dir/_ziptest3', '6y7u8i9o0p')]
30
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000031class TestsWithSourceFile(unittest.TestCase):
32 def setUp(self):
Georg Brandl4b3ab6f2007-07-12 09:59:22 +000033 self.line_gen = ["Zipfile test line %d. random float: %f" % (i, random())
34 for i in xrange(FIXEDTEST_SIZE)]
Martin v. Löwis3eb76482007-03-06 10:41:24 +000035 self.data = '\n'.join(self.line_gen) + '\n'
Fred Drake6e7e4852001-02-28 05:34:16 +000036
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000037 # Make a source file with some lines
38 fp = open(TESTFN, "wb")
39 fp.write(self.data)
40 fp.close()
Tim Peters7d3bad62001-04-04 18:56:49 +000041
Martin v. Löwis3eb76482007-03-06 10:41:24 +000042 def makeTestArchive(self, f, compression):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000043 # Create the ZIP archive
44 zipfp = zipfile.ZipFile(f, "w", compression)
45 zipfp.write(TESTFN, "another"+os.extsep+"name")
46 zipfp.write(TESTFN, TESTFN)
Ronald Oussoren143cefb2006-06-15 08:14:18 +000047 zipfp.writestr("strfile", self.data)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000048 zipfp.close()
Tim Peters7d3bad62001-04-04 18:56:49 +000049
Martin v. Löwis3eb76482007-03-06 10:41:24 +000050 def zipTest(self, f, compression):
51 self.makeTestArchive(f, compression)
52
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000053 # Read the ZIP archive
54 zipfp = zipfile.ZipFile(f, "r", compression)
55 self.assertEqual(zipfp.read(TESTFN), self.data)
56 self.assertEqual(zipfp.read("another"+os.extsep+"name"), self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +000057 self.assertEqual(zipfp.read("strfile"), self.data)
58
59 # Print the ZIP directory
60 fp = StringIO()
61 stdout = sys.stdout
62 try:
63 sys.stdout = fp
64
65 zipfp.printdir()
66 finally:
67 sys.stdout = stdout
Tim Petersa608bb22006-06-15 18:06:29 +000068
Ronald Oussoren143cefb2006-06-15 08:14:18 +000069 directory = fp.getvalue()
70 lines = directory.splitlines()
71 self.assertEquals(len(lines), 4) # Number of files + header
72
Benjamin Peterson5c8da862009-06-30 22:57:08 +000073 self.assertTrue('File Name' in lines[0])
74 self.assertTrue('Modified' in lines[0])
75 self.assertTrue('Size' in lines[0])
Ronald Oussoren143cefb2006-06-15 08:14:18 +000076
77 fn, date, time, size = lines[1].split()
78 self.assertEquals(fn, 'another.name')
79 # XXX: timestamp is not tested
80 self.assertEquals(size, str(len(self.data)))
81
82 # Check the namelist
83 names = zipfp.namelist()
84 self.assertEquals(len(names), 3)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000085 self.assertTrue(TESTFN in names)
86 self.assertTrue("another"+os.extsep+"name" in names)
87 self.assertTrue("strfile" in names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +000088
89 # Check infolist
90 infos = zipfp.infolist()
91 names = [ i.filename for i in infos ]
92 self.assertEquals(len(names), 3)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000093 self.assertTrue(TESTFN in names)
94 self.assertTrue("another"+os.extsep+"name" in names)
95 self.assertTrue("strfile" in names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +000096 for i in infos:
97 self.assertEquals(i.file_size, len(self.data))
98
99 # check getinfo
100 for nm in (TESTFN, "another"+os.extsep+"name", "strfile"):
101 info = zipfp.getinfo(nm)
102 self.assertEquals(info.filename, nm)
103 self.assertEquals(info.file_size, len(self.data))
104
105 # Check that testzip doesn't raise an exception
106 zipfp.testzip()
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000107 zipfp.close()
Tim Peters7d3bad62001-04-04 18:56:49 +0000108
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000109 def testStored(self):
110 for f in (TESTFN2, TemporaryFile(), StringIO()):
111 self.zipTest(f, zipfile.ZIP_STORED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000112
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000113 def zipOpenTest(self, f, compression):
114 self.makeTestArchive(f, compression)
115
116 # Read the ZIP archive
117 zipfp = zipfile.ZipFile(f, "r", compression)
118 zipdata1 = []
119 zipopen1 = zipfp.open(TESTFN)
120 while 1:
121 read_data = zipopen1.read(256)
122 if not read_data:
123 break
124 zipdata1.append(read_data)
125
126 zipdata2 = []
127 zipopen2 = zipfp.open("another"+os.extsep+"name")
128 while 1:
129 read_data = zipopen2.read(256)
130 if not read_data:
131 break
132 zipdata2.append(read_data)
Tim Petersea5962f2007-03-12 18:07:52 +0000133
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000134 self.assertEqual(''.join(zipdata1), self.data)
135 self.assertEqual(''.join(zipdata2), self.data)
136 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000137
138 def testOpenStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000139 for f in (TESTFN2, TemporaryFile(), StringIO()):
140 self.zipOpenTest(f, zipfile.ZIP_STORED)
141
Georg Brandl112aa502008-05-20 08:25:48 +0000142 def testOpenViaZipInfo(self):
143 # Create the ZIP archive
144 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
145 zipfp.writestr("name", "foo")
146 zipfp.writestr("name", "bar")
147 zipfp.close()
148
149 zipfp = zipfile.ZipFile(TESTFN2, "r")
150 infos = zipfp.infolist()
151 data = ""
152 for info in infos:
153 data += zipfp.open(info).read()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000154 self.assertTrue(data == "foobar" or data == "barfoo")
Georg Brandl112aa502008-05-20 08:25:48 +0000155 data = ""
156 for info in infos:
157 data += zipfp.read(info)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000158 self.assertTrue(data == "foobar" or data == "barfoo")
Georg Brandl112aa502008-05-20 08:25:48 +0000159 zipfp.close()
160
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000161 def zipRandomOpenTest(self, f, compression):
162 self.makeTestArchive(f, compression)
163
164 # Read the ZIP archive
165 zipfp = zipfile.ZipFile(f, "r", compression)
166 zipdata1 = []
167 zipopen1 = zipfp.open(TESTFN)
168 while 1:
169 read_data = zipopen1.read(randint(1, 1024))
170 if not read_data:
171 break
172 zipdata1.append(read_data)
173
174 self.assertEqual(''.join(zipdata1), self.data)
175 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000176
177 def testRandomOpenStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000178 for f in (TESTFN2, TemporaryFile(), StringIO()):
179 self.zipRandomOpenTest(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +0000180
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000181 def zipReadlineTest(self, f, compression):
182 self.makeTestArchive(f, compression)
183
184 # Read the ZIP archive
185 zipfp = zipfile.ZipFile(f, "r")
186 zipopen = zipfp.open(TESTFN)
187 for line in self.line_gen:
188 linedata = zipopen.readline()
189 self.assertEqual(linedata, line + '\n')
190
191 zipfp.close()
192
193 def zipReadlinesTest(self, f, compression):
194 self.makeTestArchive(f, compression)
195
196 # Read the ZIP archive
197 zipfp = zipfile.ZipFile(f, "r")
198 ziplines = zipfp.open(TESTFN).readlines()
199 for line, zipline in zip(self.line_gen, ziplines):
200 self.assertEqual(zipline, line + '\n')
201
202 zipfp.close()
203
204 def zipIterlinesTest(self, f, compression):
205 self.makeTestArchive(f, compression)
206
207 # Read the ZIP archive
208 zipfp = zipfile.ZipFile(f, "r")
209 for line, zipline in zip(self.line_gen, zipfp.open(TESTFN)):
210 self.assertEqual(zipline, line + '\n')
211
212 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000213
214 def testReadlineStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000215 for f in (TESTFN2, TemporaryFile(), StringIO()):
216 self.zipReadlineTest(f, zipfile.ZIP_STORED)
217
Tim Petersea5962f2007-03-12 18:07:52 +0000218 def testReadlinesStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000219 for f in (TESTFN2, TemporaryFile(), StringIO()):
220 self.zipReadlinesTest(f, zipfile.ZIP_STORED)
221
Tim Petersea5962f2007-03-12 18:07:52 +0000222 def testIterlinesStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000223 for f in (TESTFN2, TemporaryFile(), StringIO()):
224 self.zipIterlinesTest(f, zipfile.ZIP_STORED)
225
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000226 @skipUnless(zlib, "requires zlib")
227 def testDeflated(self):
228 for f in (TESTFN2, TemporaryFile(), StringIO()):
229 self.zipTest(f, zipfile.ZIP_DEFLATED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000230
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000231 @skipUnless(zlib, "requires zlib")
232 def testOpenDeflated(self):
233 for f in (TESTFN2, TemporaryFile(), StringIO()):
234 self.zipOpenTest(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000235
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000236 @skipUnless(zlib, "requires zlib")
237 def testRandomOpenDeflated(self):
238 for f in (TESTFN2, TemporaryFile(), StringIO()):
239 self.zipRandomOpenTest(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000240
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000241 @skipUnless(zlib, "requires zlib")
242 def testReadlineDeflated(self):
243 for f in (TESTFN2, TemporaryFile(), StringIO()):
244 self.zipReadlineTest(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000245
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000246 @skipUnless(zlib, "requires zlib")
247 def testReadlinesDeflated(self):
248 for f in (TESTFN2, TemporaryFile(), StringIO()):
249 self.zipReadlinesTest(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000250
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000251 @skipUnless(zlib, "requires zlib")
252 def testIterlinesDeflated(self):
253 for f in (TESTFN2, TemporaryFile(), StringIO()):
254 self.zipIterlinesTest(f, zipfile.ZIP_DEFLATED)
Tim Petersea5962f2007-03-12 18:07:52 +0000255
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000256 @skipUnless(zlib, "requires zlib")
257 def testLowCompression(self):
258 # Checks for cases where compressed data is larger than original
259 # Create the ZIP archive
260 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED)
261 zipfp.writestr("strfile", '12')
262 zipfp.close()
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000263
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000264 # Get an open object for strfile
265 zipfp = zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_DEFLATED)
266 openobj = zipfp.open("strfile")
267 self.assertEqual(openobj.read(1), '1')
268 self.assertEqual(openobj.read(1), '2')
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000269
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000270 def testAbsoluteArcnames(self):
271 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
272 zipfp.write(TESTFN, "/absolute")
273 zipfp.close()
274
275 zipfp = zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED)
276 self.assertEqual(zipfp.namelist(), ["absolute"])
277 zipfp.close()
Tim Peters32cbc962006-02-20 21:42:18 +0000278
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000279 def testAppendToZipFile(self):
280 # Test appending to an existing zipfile
281 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
282 zipfp.write(TESTFN, TESTFN)
283 zipfp.close()
284 zipfp = zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED)
285 zipfp.writestr("strfile", self.data)
286 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
287 zipfp.close()
288
289 def testAppendToNonZipFile(self):
290 # Test appending to an existing file that is not a zipfile
291 # NOTE: this test fails if len(d) < 22 because of the first
292 # line "fpin.seek(-22, 2)" in _EndRecData
293 d = 'I am not a ZipFile!'*10
294 f = file(TESTFN2, 'wb')
295 f.write(d)
296 f.close()
297 zipfp = zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED)
298 zipfp.write(TESTFN, TESTFN)
299 zipfp.close()
300
301 f = file(TESTFN2, 'rb')
302 f.seek(len(d))
303 zipfp = zipfile.ZipFile(f, "r")
304 self.assertEqual(zipfp.namelist(), [TESTFN])
305 zipfp.close()
306 f.close()
307
308 def test_WriteDefaultName(self):
309 # Check that calling ZipFile.write without arcname specified produces the expected result
310 zipfp = zipfile.ZipFile(TESTFN2, "w")
311 zipfp.write(TESTFN)
312 self.assertEqual(zipfp.read(TESTFN), file(TESTFN).read())
313 zipfp.close()
314
315 def test_PerFileCompression(self):
316 # Check that files within a Zip archive can have different compression options
317 zipfp = zipfile.ZipFile(TESTFN2, "w")
318 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
319 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
320 sinfo = zipfp.getinfo('storeme')
321 dinfo = zipfp.getinfo('deflateme')
322 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
323 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
324 zipfp.close()
325
326 def test_WriteToReadonly(self):
327 # Check that trying to call write() on a readonly ZipFile object
328 # raises a RuntimeError
329 zipf = zipfile.ZipFile(TESTFN2, mode="w")
330 zipf.writestr("somefile.txt", "bogus")
331 zipf.close()
332 zipf = zipfile.ZipFile(TESTFN2, mode="r")
333 self.assertRaises(RuntimeError, zipf.write, TESTFN)
334 zipf.close()
335
Georg Brandl62416bc2008-01-07 18:47:44 +0000336 def testExtract(self):
337 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
338 for fpath, fdata in SMALL_TEST_DATA:
339 zipfp.writestr(fpath, fdata)
340 zipfp.close()
341
342 zipfp = zipfile.ZipFile(TESTFN2, "r")
343 for fpath, fdata in SMALL_TEST_DATA:
344 writtenfile = zipfp.extract(fpath)
345
346 # make sure it was written to the right place
347 if os.path.isabs(fpath):
348 correctfile = os.path.join(os.getcwd(), fpath[1:])
349 else:
350 correctfile = os.path.join(os.getcwd(), fpath)
Christian Heimesa2af2122008-01-26 16:43:35 +0000351 correctfile = os.path.normpath(correctfile)
Georg Brandl62416bc2008-01-07 18:47:44 +0000352
353 self.assertEqual(writtenfile, correctfile)
354
355 # make sure correct data is in correct file
356 self.assertEqual(fdata, file(writtenfile, "rb").read())
357
358 os.remove(writtenfile)
359
360 zipfp.close()
361
362 # remove the test file subdirectories
363 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
364
365 def testExtractAll(self):
366 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
367 for fpath, fdata in SMALL_TEST_DATA:
368 zipfp.writestr(fpath, fdata)
369 zipfp.close()
370
371 zipfp = zipfile.ZipFile(TESTFN2, "r")
372 zipfp.extractall()
373 for fpath, fdata in SMALL_TEST_DATA:
374 if os.path.isabs(fpath):
375 outfile = os.path.join(os.getcwd(), fpath[1:])
376 else:
377 outfile = os.path.join(os.getcwd(), fpath)
378
379 self.assertEqual(fdata, file(outfile, "rb").read())
380
381 os.remove(outfile)
382
383 zipfp.close()
384
385 # remove the test file subdirectories
386 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
387
Antoine Pitrou5fdfa3e2008-07-25 19:42:26 +0000388 def zip_test_writestr_permissions(self, f, compression):
389 # Make sure that writestr creates files with mode 0600,
390 # when it is passed a name rather than a ZipInfo instance.
391
392 self.makeTestArchive(f, compression)
393 zipfp = zipfile.ZipFile(f, "r")
394 zinfo = zipfp.getinfo('strfile')
395 self.assertEqual(zinfo.external_attr, 0600 << 16)
396
397 def test_writestr_permissions(self):
398 for f in (TESTFN2, TemporaryFile(), StringIO()):
399 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
400
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000401 def tearDown(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000402 support.unlink(TESTFN)
403 support.unlink(TESTFN2)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000404
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000405class TestZip64InSmallFiles(unittest.TestCase):
406 # These tests test the ZIP64 functionality without using large files,
407 # see test_zipfile64 for proper tests.
408
409 def setUp(self):
410 self._limit = zipfile.ZIP64_LIMIT
411 zipfile.ZIP64_LIMIT = 5
412
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000413 line_gen = ("Test of zipfile line %d." % i for i in range(0, FIXEDTEST_SIZE))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000414 self.data = '\n'.join(line_gen)
415
416 # Make a source file with some lines
417 fp = open(TESTFN, "wb")
418 fp.write(self.data)
419 fp.close()
420
421 def largeFileExceptionTest(self, f, compression):
422 zipfp = zipfile.ZipFile(f, "w", compression)
Tim Petersa608bb22006-06-15 18:06:29 +0000423 self.assertRaises(zipfile.LargeZipFile,
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000424 zipfp.write, TESTFN, "another"+os.extsep+"name")
425 zipfp.close()
426
427 def largeFileExceptionTest2(self, f, compression):
428 zipfp = zipfile.ZipFile(f, "w", compression)
Tim Petersa608bb22006-06-15 18:06:29 +0000429 self.assertRaises(zipfile.LargeZipFile,
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000430 zipfp.writestr, "another"+os.extsep+"name", self.data)
431 zipfp.close()
432
433 def testLargeFileException(self):
434 for f in (TESTFN2, TemporaryFile(), StringIO()):
435 self.largeFileExceptionTest(f, zipfile.ZIP_STORED)
436 self.largeFileExceptionTest2(f, zipfile.ZIP_STORED)
437
438 def zipTest(self, f, compression):
439 # Create the ZIP archive
440 zipfp = zipfile.ZipFile(f, "w", compression, allowZip64=True)
441 zipfp.write(TESTFN, "another"+os.extsep+"name")
442 zipfp.write(TESTFN, TESTFN)
443 zipfp.writestr("strfile", self.data)
444 zipfp.close()
445
446 # Read the ZIP archive
447 zipfp = zipfile.ZipFile(f, "r", compression)
448 self.assertEqual(zipfp.read(TESTFN), self.data)
449 self.assertEqual(zipfp.read("another"+os.extsep+"name"), self.data)
450 self.assertEqual(zipfp.read("strfile"), self.data)
451
452 # Print the ZIP directory
453 fp = StringIO()
454 stdout = sys.stdout
455 try:
456 sys.stdout = fp
457
458 zipfp.printdir()
459 finally:
460 sys.stdout = stdout
Tim Petersa608bb22006-06-15 18:06:29 +0000461
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000462 directory = fp.getvalue()
463 lines = directory.splitlines()
464 self.assertEquals(len(lines), 4) # Number of files + header
465
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000466 self.assertTrue('File Name' in lines[0])
467 self.assertTrue('Modified' in lines[0])
468 self.assertTrue('Size' in lines[0])
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000469
470 fn, date, time, size = lines[1].split()
471 self.assertEquals(fn, 'another.name')
472 # XXX: timestamp is not tested
473 self.assertEquals(size, str(len(self.data)))
474
475 # Check the namelist
476 names = zipfp.namelist()
477 self.assertEquals(len(names), 3)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000478 self.assertTrue(TESTFN in names)
479 self.assertTrue("another"+os.extsep+"name" in names)
480 self.assertTrue("strfile" in names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000481
482 # Check infolist
483 infos = zipfp.infolist()
484 names = [ i.filename for i in infos ]
485 self.assertEquals(len(names), 3)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000486 self.assertTrue(TESTFN in names)
487 self.assertTrue("another"+os.extsep+"name" in names)
488 self.assertTrue("strfile" in names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000489 for i in infos:
490 self.assertEquals(i.file_size, len(self.data))
491
492 # check getinfo
493 for nm in (TESTFN, "another"+os.extsep+"name", "strfile"):
494 info = zipfp.getinfo(nm)
495 self.assertEquals(info.filename, nm)
496 self.assertEquals(info.file_size, len(self.data))
497
498 # Check that testzip doesn't raise an exception
499 zipfp.testzip()
500
501
502 zipfp.close()
503
504 def testStored(self):
505 for f in (TESTFN2, TemporaryFile(), StringIO()):
506 self.zipTest(f, zipfile.ZIP_STORED)
507
508
509 if zlib:
510 def testDeflated(self):
511 for f in (TESTFN2, TemporaryFile(), StringIO()):
512 self.zipTest(f, zipfile.ZIP_DEFLATED)
513
514 def testAbsoluteArcnames(self):
515 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED, allowZip64=True)
516 zipfp.write(TESTFN, "/absolute")
517 zipfp.close()
518
519 zipfp = zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED)
520 self.assertEqual(zipfp.namelist(), ["absolute"])
521 zipfp.close()
522
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000523 def tearDown(self):
524 zipfile.ZIP64_LIMIT = self._limit
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000525 support.unlink(TESTFN)
526 support.unlink(TESTFN2)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000527
528class PyZipFileTests(unittest.TestCase):
529 def testWritePyfile(self):
530 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
531 fn = __file__
532 if fn.endswith('.pyc') or fn.endswith('.pyo'):
533 fn = fn[:-1]
534
535 zipfp.writepy(fn)
536
537 bn = os.path.basename(fn)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000538 self.assertTrue(bn not in zipfp.namelist())
539 self.assertTrue(bn + 'o' in zipfp.namelist() or bn + 'c' in zipfp.namelist())
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000540 zipfp.close()
541
542
543 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
544 fn = __file__
545 if fn.endswith('.pyc') or fn.endswith('.pyo'):
546 fn = fn[:-1]
547
548 zipfp.writepy(fn, "testpackage")
549
550 bn = "%s/%s"%("testpackage", os.path.basename(fn))
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000551 self.assertTrue(bn not in zipfp.namelist())
552 self.assertTrue(bn + 'o' in zipfp.namelist() or bn + 'c' in zipfp.namelist())
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000553 zipfp.close()
554
555 def testWritePythonPackage(self):
556 import email
557 packagedir = os.path.dirname(email.__file__)
558
559 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
560 zipfp.writepy(packagedir)
561
562 # Check for a couple of modules at different levels of the hieararchy
563 names = zipfp.namelist()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000564 self.assertTrue('email/__init__.pyo' in names or 'email/__init__.pyc' in names)
565 self.assertTrue('email/mime/text.pyo' in names or 'email/mime/text.pyc' in names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000566
567 def testWritePythonDirectory(self):
568 os.mkdir(TESTFN2)
569 try:
570 fp = open(os.path.join(TESTFN2, "mod1.py"), "w")
571 fp.write("print 42\n")
572 fp.close()
573
574 fp = open(os.path.join(TESTFN2, "mod2.py"), "w")
575 fp.write("print 42 * 42\n")
576 fp.close()
577
578 fp = open(os.path.join(TESTFN2, "mod2.txt"), "w")
579 fp.write("bla bla bla\n")
580 fp.close()
581
582 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
583 zipfp.writepy(TESTFN2)
584
585 names = zipfp.namelist()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000586 self.assertTrue('mod1.pyc' in names or 'mod1.pyo' in names)
587 self.assertTrue('mod2.pyc' in names or 'mod2.pyo' in names)
588 self.assertTrue('mod2.txt' not in names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000589
590 finally:
591 shutil.rmtree(TESTFN2)
592
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000593 def testWriteNonPyfile(self):
594 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
595 file(TESTFN, 'w').write('most definitely not a python file')
596 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
597 os.remove(TESTFN)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000598
599
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000600class OtherTests(unittest.TestCase):
Martin v. Löwis471617d2008-05-05 17:16:58 +0000601 def testUnicodeFilenames(self):
602 zf = zipfile.ZipFile(TESTFN, "w")
603 zf.writestr(u"foo.txt", "Test for unicode filename")
Martin v. Löwisc3ad68c2008-05-05 17:47:06 +0000604 zf.writestr(u"\xf6.txt", "Test for unicode filename")
605 self.assertTrue(isinstance(zf.infolist()[0].filename, unicode))
Martin v. Löwis471617d2008-05-05 17:16:58 +0000606 zf.close()
Martin v. Löwisc3ad68c2008-05-05 17:47:06 +0000607 zf = zipfile.ZipFile(TESTFN, "r")
608 self.assertEqual(zf.filelist[0].filename, "foo.txt")
609 self.assertEqual(zf.filelist[1].filename, u"\xf6.txt")
610 zf.close()
Martin v. Löwis471617d2008-05-05 17:16:58 +0000611
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000612 def testCreateNonExistentFileForAppend(self):
613 if os.path.exists(TESTFN):
614 os.unlink(TESTFN)
Tim Petersea5962f2007-03-12 18:07:52 +0000615
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000616 filename = 'testfile.txt'
617 content = 'hello, world. this is some content.'
Tim Petersea5962f2007-03-12 18:07:52 +0000618
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000619 try:
620 zf = zipfile.ZipFile(TESTFN, 'a')
621 zf.writestr(filename, content)
622 zf.close()
623 except IOError, (errno, errmsg):
624 self.fail('Could not append data to a non-existent zip file.')
625
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000626 self.assertTrue(os.path.exists(TESTFN))
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000627
628 zf = zipfile.ZipFile(TESTFN, 'r')
629 self.assertEqual(zf.read(filename), content)
630 zf.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000631
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000632 def testCloseErroneousFile(self):
633 # This test checks that the ZipFile constructor closes the file object
634 # it opens if there's an error in the file. If it doesn't, the traceback
635 # holds a reference to the ZipFile object and, indirectly, the file object.
636 # On Windows, this causes the os.unlink() call to fail because the
637 # underlying file is still open. This is SF bug #412214.
638 #
639 fp = open(TESTFN, "w")
640 fp.write("this is not a legal zip file\n")
641 fp.close()
642 try:
643 zf = zipfile.ZipFile(TESTFN)
644 except zipfile.BadZipfile:
Collin Winter04a51ec2007-03-29 02:28:16 +0000645 pass
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000646
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000647 def testIsZipErroneousFile(self):
Tim Petersea5962f2007-03-12 18:07:52 +0000648 # This test checks that the is_zipfile function correctly identifies
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000649 # a file that is not a zip file
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000650
651 # - passing a filename
652 with open(TESTFN, "w") as fp:
653 fp.write("this is not a legal zip file\n")
Tim Petersea5962f2007-03-12 18:07:52 +0000654 chk = zipfile.is_zipfile(TESTFN)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000655 self.assertTrue(not chk)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000656 # - passing a file object
657 with open(TESTFN, "rb") as fp:
658 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000659 self.assertTrue(not chk)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000660 # - passing a file-like object
661 fp = StringIO()
662 fp.write("this is not a legal zip file\n")
663 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000664 self.assertTrue(not chk)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000665 fp.seek(0,0)
666 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000667 self.assertTrue(not chk)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000668
669 def testIsZipValidFile(self):
Tim Petersea5962f2007-03-12 18:07:52 +0000670 # This test checks that the is_zipfile function correctly identifies
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000671 # a file that is a zip file
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000672
673 # - passing a filename
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000674 zipf = zipfile.ZipFile(TESTFN, mode="w")
675 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
676 zipf.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000677 chk = zipfile.is_zipfile(TESTFN)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000678 self.assertTrue(chk)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000679 # - passing a file object
680 with open(TESTFN, "rb") as fp:
681 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000682 self.assertTrue(chk)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000683 fp.seek(0,0)
684 zip_contents = fp.read()
685 # - passing a file-like object
686 fp = StringIO()
687 fp.write(zip_contents)
688 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000689 self.assertTrue(chk)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000690 fp.seek(0,0)
691 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000692 self.assertTrue(chk)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000693
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000694 def testNonExistentFileRaisesIOError(self):
695 # make sure we don't raise an AttributeError when a partially-constructed
696 # ZipFile instance is finalized; this tests for regression on SF tracker
697 # bug #403871.
698
699 # The bug we're testing for caused an AttributeError to be raised
700 # when a ZipFile instance was created for a file that did not
701 # exist; the .fp member was not initialized but was needed by the
702 # __del__() method. Since the AttributeError is in the __del__(),
703 # it is ignored, but the user should be sufficiently annoyed by
704 # the message on the output that regression will be noticed
705 # quickly.
706 self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
707
708 def testClosedZipRaisesRuntimeError(self):
709 # Verify that testzip() doesn't swallow inappropriate exceptions.
710 data = StringIO()
711 zipf = zipfile.ZipFile(data, mode="w")
712 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
713 zipf.close()
714
715 # This is correct; calling .read on a closed ZipFile should throw
716 # a RuntimeError, and so should calling .testzip. An earlier
717 # version of .testzip would swallow this exception (and any other)
718 # and report that the first file in the archive was corrupt.
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000719 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
720 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000721 self.assertRaises(RuntimeError, zipf.testzip)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000722 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
723 file(TESTFN, 'w').write('zipfile test data')
724 self.assertRaises(RuntimeError, zipf.write, TESTFN)
725
726 def test_BadConstructorMode(self):
727 # Check that bad modes passed to ZipFile constructor are caught
728 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
729
730 def test_BadOpenMode(self):
731 # Check that bad modes passed to ZipFile.open are caught
732 zipf = zipfile.ZipFile(TESTFN, mode="w")
733 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
734 zipf.close()
735 zipf = zipfile.ZipFile(TESTFN, mode="r")
736 # read the data to make sure the file is there
737 zipf.read("foo.txt")
738 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
739 zipf.close()
740
741 def test_Read0(self):
742 # Check that calling read(0) on a ZipExtFile object returns an empty
743 # string and doesn't advance file pointer
744 zipf = zipfile.ZipFile(TESTFN, mode="w")
745 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
746 # read the data to make sure the file is there
747 f = zipf.open("foo.txt")
748 for i in xrange(FIXEDTEST_SIZE):
749 self.assertEqual(f.read(0), '')
750
751 self.assertEqual(f.read(), "O, for a Muse of Fire!")
752 zipf.close()
753
754 def test_OpenNonexistentItem(self):
755 # Check that attempting to call open() for an item that doesn't
756 # exist in the archive raises a RuntimeError
757 zipf = zipfile.ZipFile(TESTFN, mode="w")
758 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
759
760 def test_BadCompressionMode(self):
761 # Check that bad compression methods passed to ZipFile.open are caught
762 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
763
764 def test_NullByteInFilename(self):
765 # Check that a filename containing a null byte is properly terminated
766 zipf = zipfile.ZipFile(TESTFN, mode="w")
767 zipf.writestr("foo.txt\x00qqq", "O, for a Muse of Fire!")
768 self.assertEqual(zipf.namelist(), ['foo.txt'])
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000769
Martin v. Löwis8c436412008-07-03 12:51:14 +0000770 def test_StructSizes(self):
771 # check that ZIP internal structure sizes are calculated correctly
772 self.assertEqual(zipfile.sizeEndCentDir, 22)
773 self.assertEqual(zipfile.sizeCentralDir, 46)
774 self.assertEqual(zipfile.sizeEndCentDir64, 56)
775 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
776
777 def testComments(self):
778 # This test checks that comments on the archive are handled properly
779
780 # check default comment is empty
781 zipf = zipfile.ZipFile(TESTFN, mode="w")
782 self.assertEqual(zipf.comment, '')
783 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
784 zipf.close()
785 zipfr = zipfile.ZipFile(TESTFN, mode="r")
786 self.assertEqual(zipfr.comment, '')
787 zipfr.close()
788
789 # check a simple short comment
790 comment = 'Bravely taking to his feet, he beat a very brave retreat.'
791 zipf = zipfile.ZipFile(TESTFN, mode="w")
792 zipf.comment = comment
793 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
794 zipf.close()
795 zipfr = zipfile.ZipFile(TESTFN, mode="r")
796 self.assertEqual(zipfr.comment, comment)
797 zipfr.close()
798
799 # check a comment of max length
800 comment2 = ''.join(['%d' % (i**3 % 10) for i in xrange((1 << 16)-1)])
801 zipf = zipfile.ZipFile(TESTFN, mode="w")
802 zipf.comment = comment2
803 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
804 zipf.close()
805 zipfr = zipfile.ZipFile(TESTFN, mode="r")
806 self.assertEqual(zipfr.comment, comment2)
807 zipfr.close()
808
809 # check a comment that is too long is truncated
810 zipf = zipfile.ZipFile(TESTFN, mode="w")
811 zipf.comment = comment2 + 'oops'
812 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
813 zipf.close()
814 zipfr = zipfile.ZipFile(TESTFN, mode="r")
815 self.assertEqual(zipfr.comment, comment2)
816 zipfr.close()
817
Collin Winter04a51ec2007-03-29 02:28:16 +0000818 def tearDown(self):
819 support.unlink(TESTFN)
820 support.unlink(TESTFN2)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000821
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000822class DecryptionTests(unittest.TestCase):
823 # This test checks that ZIP decryption works. Since the library does not
824 # support encryption at the moment, we use a pre-generated encrypted
825 # ZIP file
826
827 data = (
828 'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
829 '\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
830 '\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
831 'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
832 '\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
833 '\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
834 '\x00\x00L\x00\x00\x00\x00\x00' )
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000835 data2 = (
836 'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
837 '\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
838 '\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
839 'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
840 '\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
841 '\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
842 'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
843 '\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000844
845 plain = 'zipfile.py encryption test'
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000846 plain2 = '\x00'*512
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000847
848 def setUp(self):
849 fp = open(TESTFN, "wb")
850 fp.write(self.data)
851 fp.close()
852 self.zip = zipfile.ZipFile(TESTFN, "r")
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000853 fp = open(TESTFN2, "wb")
854 fp.write(self.data2)
855 fp.close()
856 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000857
858 def tearDown(self):
859 self.zip.close()
860 os.unlink(TESTFN)
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000861 self.zip2.close()
862 os.unlink(TESTFN2)
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000863
864 def testNoPassword(self):
865 # Reading the encrypted file without password
866 # must generate a RunTime exception
867 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000868 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000869
870 def testBadPassword(self):
871 self.zip.setpassword("perl")
872 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000873 self.zip2.setpassword("perl")
874 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Tim Petersea5962f2007-03-12 18:07:52 +0000875
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000876 def testGoodPassword(self):
877 self.zip.setpassword("python")
878 self.assertEquals(self.zip.read("test.txt"), self.plain)
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000879 self.zip2.setpassword("12345")
880 self.assertEquals(self.zip2.read("zero"), self.plain2)
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000881
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000882
883class TestsWithRandomBinaryFiles(unittest.TestCase):
884 def setUp(self):
885 datacount = randint(16, 64)*1024 + randint(1, 1024)
886 self.data = ''.join((struct.pack('<f', random()*randint(-1000, 1000)) for i in xrange(datacount)))
887
888 # Make a source file with some lines
889 fp = open(TESTFN, "wb")
890 fp.write(self.data)
891 fp.close()
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000892
Collin Winter04a51ec2007-03-29 02:28:16 +0000893 def tearDown(self):
894 support.unlink(TESTFN)
895 support.unlink(TESTFN2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000896
897 def makeTestArchive(self, f, compression):
898 # Create the ZIP archive
899 zipfp = zipfile.ZipFile(f, "w", compression)
900 zipfp.write(TESTFN, "another"+os.extsep+"name")
901 zipfp.write(TESTFN, TESTFN)
902 zipfp.close()
903
904 def zipTest(self, f, compression):
905 self.makeTestArchive(f, compression)
906
907 # Read the ZIP archive
908 zipfp = zipfile.ZipFile(f, "r", compression)
909 testdata = zipfp.read(TESTFN)
910 self.assertEqual(len(testdata), len(self.data))
911 self.assertEqual(testdata, self.data)
912 self.assertEqual(zipfp.read("another"+os.extsep+"name"), self.data)
913 zipfp.close()
914
915 def testStored(self):
916 for f in (TESTFN2, TemporaryFile(), StringIO()):
917 self.zipTest(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +0000918
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000919 def zipOpenTest(self, f, compression):
920 self.makeTestArchive(f, compression)
921
922 # Read the ZIP archive
923 zipfp = zipfile.ZipFile(f, "r", compression)
924 zipdata1 = []
925 zipopen1 = zipfp.open(TESTFN)
926 while 1:
927 read_data = zipopen1.read(256)
928 if not read_data:
929 break
930 zipdata1.append(read_data)
931
932 zipdata2 = []
933 zipopen2 = zipfp.open("another"+os.extsep+"name")
934 while 1:
935 read_data = zipopen2.read(256)
936 if not read_data:
937 break
938 zipdata2.append(read_data)
Tim Petersea5962f2007-03-12 18:07:52 +0000939
940 testdata1 = ''.join(zipdata1)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000941 self.assertEqual(len(testdata1), len(self.data))
942 self.assertEqual(testdata1, self.data)
943
Tim Petersea5962f2007-03-12 18:07:52 +0000944 testdata2 = ''.join(zipdata2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000945 self.assertEqual(len(testdata1), len(self.data))
946 self.assertEqual(testdata1, self.data)
947 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000948
949 def testOpenStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000950 for f in (TESTFN2, TemporaryFile(), StringIO()):
951 self.zipOpenTest(f, zipfile.ZIP_STORED)
952
953 def zipRandomOpenTest(self, f, compression):
954 self.makeTestArchive(f, compression)
955
956 # Read the ZIP archive
957 zipfp = zipfile.ZipFile(f, "r", compression)
958 zipdata1 = []
959 zipopen1 = zipfp.open(TESTFN)
960 while 1:
961 read_data = zipopen1.read(randint(1, 1024))
962 if not read_data:
963 break
964 zipdata1.append(read_data)
965
966 testdata = ''.join(zipdata1)
967 self.assertEqual(len(testdata), len(self.data))
968 self.assertEqual(testdata, self.data)
969 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000970
971 def testRandomOpenStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000972 for f in (TESTFN2, TemporaryFile(), StringIO()):
973 self.zipRandomOpenTest(f, zipfile.ZIP_STORED)
974
975class TestsWithMultipleOpens(unittest.TestCase):
976 def setUp(self):
977 # Create the ZIP archive
978 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED)
979 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
980 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
981 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000982
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000983 def testSameFile(self):
984 # Verify that (when the ZipFile is in control of creating file objects)
985 # multiple open() calls can be made without interfering with each other.
986 zipf = zipfile.ZipFile(TESTFN2, mode="r")
987 zopen1 = zipf.open('ones')
988 zopen2 = zipf.open('ones')
989 data1 = zopen1.read(500)
990 data2 = zopen2.read(500)
991 data1 += zopen1.read(500)
992 data2 += zopen2.read(500)
993 self.assertEqual(data1, data2)
994 zipf.close()
995
996 def testDifferentFile(self):
997 # Verify that (when the ZipFile is in control of creating file objects)
998 # multiple open() calls can be made without interfering with each other.
999 zipf = zipfile.ZipFile(TESTFN2, mode="r")
1000 zopen1 = zipf.open('ones')
1001 zopen2 = zipf.open('twos')
1002 data1 = zopen1.read(500)
1003 data2 = zopen2.read(500)
1004 data1 += zopen1.read(500)
1005 data2 += zopen2.read(500)
1006 self.assertEqual(data1, '1'*FIXEDTEST_SIZE)
1007 self.assertEqual(data2, '2'*FIXEDTEST_SIZE)
1008 zipf.close()
1009
1010 def testInterleaved(self):
1011 # Verify that (when the ZipFile is in control of creating file objects)
1012 # multiple open() calls can be made without interfering with each other.
1013 zipf = zipfile.ZipFile(TESTFN2, mode="r")
1014 zopen1 = zipf.open('ones')
1015 data1 = zopen1.read(500)
1016 zopen2 = zipf.open('twos')
1017 data2 = zopen2.read(500)
1018 data1 += zopen1.read(500)
1019 data2 += zopen2.read(500)
1020 self.assertEqual(data1, '1'*FIXEDTEST_SIZE)
1021 self.assertEqual(data2, '2'*FIXEDTEST_SIZE)
1022 zipf.close()
Tim Petersea5962f2007-03-12 18:07:52 +00001023
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001024 def tearDown(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +00001025 support.unlink(TESTFN2)
Tim Petersea5962f2007-03-12 18:07:52 +00001026
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001027class TestWithDirectory(unittest.TestCase):
1028 def setUp(self):
1029 os.mkdir(TESTFN2)
1030
1031 def testExtractDir(self):
1032 zipf = zipfile.ZipFile(findfile("zipdir.zip"))
1033 zipf.extractall(TESTFN2)
1034 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1035 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1036 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1037
Martin v. Löwis0b09c422009-05-24 19:30:52 +00001038 def test_bug_6050(self):
1039 # Extraction should succeed if directories already exist
1040 os.mkdir(os.path.join(TESTFN2, "a"))
1041 self.testExtractDir()
1042
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001043 def testStoreDir(self):
1044 os.mkdir(os.path.join(TESTFN2, "x"))
1045 zipf = zipfile.ZipFile(TESTFN, "w")
1046 zipf.write(os.path.join(TESTFN2, "x"), "x")
1047 self.assertTrue(zipf.filelist[0].filename.endswith("x/"))
1048
1049 def tearDown(self):
1050 shutil.rmtree(TESTFN2)
1051 if os.path.exists(TESTFN):
Ezio Melottie7a0cc22009-07-04 14:58:27 +00001052 support.unlink(TESTFN)
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001053
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001054
1055class UniversalNewlineTests(unittest.TestCase):
1056 def setUp(self):
1057 self.line_gen = ["Test of zipfile line %d." % i for i in xrange(FIXEDTEST_SIZE)]
1058 self.seps = ('\r', '\r\n', '\n')
1059 self.arcdata, self.arcfiles = {}, {}
1060 for n, s in enumerate(self.seps):
1061 self.arcdata[s] = s.join(self.line_gen) + s
1062 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Brett Cannon6cef0762007-05-25 20:17:15 +00001063 open(self.arcfiles[s], "wb").write(self.arcdata[s])
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001064
1065 def makeTestArchive(self, f, compression):
1066 # Create the ZIP archive
1067 zipfp = zipfile.ZipFile(f, "w", compression)
1068 for fn in self.arcfiles.values():
1069 zipfp.write(fn, fn)
1070 zipfp.close()
1071
1072 def readTest(self, f, compression):
1073 self.makeTestArchive(f, compression)
1074
1075 # Read the ZIP archive
1076 zipfp = zipfile.ZipFile(f, "r")
1077 for sep, fn in self.arcfiles.items():
1078 zipdata = zipfp.open(fn, "rU").read()
1079 self.assertEqual(self.arcdata[sep], zipdata)
1080
1081 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +00001082
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001083 def readlineTest(self, f, compression):
1084 self.makeTestArchive(f, compression)
1085
1086 # Read the ZIP archive
1087 zipfp = zipfile.ZipFile(f, "r")
1088 for sep, fn in self.arcfiles.items():
1089 zipopen = zipfp.open(fn, "rU")
1090 for line in self.line_gen:
1091 linedata = zipopen.readline()
1092 self.assertEqual(linedata, line + '\n')
1093
1094 zipfp.close()
1095
1096 def readlinesTest(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 ziplines = zipfp.open(fn, "rU").readlines()
1103 for line, zipline in zip(self.line_gen, ziplines):
1104 self.assertEqual(zipline, line + '\n')
1105
1106 zipfp.close()
1107
1108 def iterlinesTest(self, f, compression):
1109 self.makeTestArchive(f, compression)
1110
1111 # Read the ZIP archive
1112 zipfp = zipfile.ZipFile(f, "r")
1113 for sep, fn in self.arcfiles.items():
1114 for line, zipline in zip(self.line_gen, zipfp.open(fn, "rU")):
1115 self.assertEqual(zipline, line + '\n')
1116
1117 zipfp.close()
1118
Tim Petersea5962f2007-03-12 18:07:52 +00001119 def testReadStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001120 for f in (TESTFN2, TemporaryFile(), StringIO()):
1121 self.readTest(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +00001122
1123 def testReadlineStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001124 for f in (TESTFN2, TemporaryFile(), StringIO()):
1125 self.readlineTest(f, zipfile.ZIP_STORED)
1126
Tim Petersea5962f2007-03-12 18:07:52 +00001127 def testReadlinesStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001128 for f in (TESTFN2, TemporaryFile(), StringIO()):
1129 self.readlinesTest(f, zipfile.ZIP_STORED)
1130
Tim Petersea5962f2007-03-12 18:07:52 +00001131 def testIterlinesStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001132 for f in (TESTFN2, TemporaryFile(), StringIO()):
1133 self.iterlinesTest(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +00001134
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001135 if zlib:
Tim Petersea5962f2007-03-12 18:07:52 +00001136 def testReadDeflated(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001137 for f in (TESTFN2, TemporaryFile(), StringIO()):
1138 self.readTest(f, zipfile.ZIP_DEFLATED)
1139
Tim Petersea5962f2007-03-12 18:07:52 +00001140 def testReadlineDeflated(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001141 for f in (TESTFN2, TemporaryFile(), StringIO()):
1142 self.readlineTest(f, zipfile.ZIP_DEFLATED)
1143
Tim Petersea5962f2007-03-12 18:07:52 +00001144 def testReadlinesDeflated(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001145 for f in (TESTFN2, TemporaryFile(), StringIO()):
1146 self.readlinesTest(f, zipfile.ZIP_DEFLATED)
1147
Tim Petersea5962f2007-03-12 18:07:52 +00001148 def testIterlinesDeflated(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001149 for f in (TESTFN2, TemporaryFile(), StringIO()):
1150 self.iterlinesTest(f, zipfile.ZIP_DEFLATED)
1151
1152 def tearDown(self):
1153 for sep, fn in self.arcfiles.items():
1154 os.remove(fn)
Collin Winter04a51ec2007-03-29 02:28:16 +00001155 support.unlink(TESTFN)
1156 support.unlink(TESTFN2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001157
1158
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001159def test_main():
Tim Petersea5962f2007-03-12 18:07:52 +00001160 run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
1161 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001162 TestWithDirectory,
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001163 UniversalNewlineTests, TestsWithRandomBinaryFiles)
1164
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001165if __name__ == "__main__":
1166 test_main()