blob: 9cc586028a2fe20803d3737143b4a055091d79f7 [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
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000014from test.test_support import TESTFN, run_unittest
Guido van Rossum368f04a2000-04-10 13:23:04 +000015
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000016TESTFN2 = TESTFN + "2"
Georg Brandl4b3ab6f2007-07-12 09:59:22 +000017FIXEDTEST_SIZE = 1000
Guido van Rossum368f04a2000-04-10 13:23:04 +000018
Georg Brandl62416bc2008-01-07 18:47:44 +000019SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'),
20 ('ziptest2dir/_ziptest2', 'qawsedrftg'),
21 ('/ziptest2dir/ziptest3dir/_ziptest3', 'azsxdcfvgb'),
22 ('ziptest2dir/ziptest3dir/ziptest4dir/_ziptest3', '6y7u8i9o0p')]
23
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000024class TestsWithSourceFile(unittest.TestCase):
25 def setUp(self):
Georg Brandl4b3ab6f2007-07-12 09:59:22 +000026 self.line_gen = ["Zipfile test line %d. random float: %f" % (i, random())
27 for i in xrange(FIXEDTEST_SIZE)]
Martin v. Löwis3eb76482007-03-06 10:41:24 +000028 self.data = '\n'.join(self.line_gen) + '\n'
Fred Drake6e7e4852001-02-28 05:34:16 +000029
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000030 # Make a source file with some lines
31 fp = open(TESTFN, "wb")
32 fp.write(self.data)
33 fp.close()
Tim Peters7d3bad62001-04-04 18:56:49 +000034
Martin v. Löwis3eb76482007-03-06 10:41:24 +000035 def makeTestArchive(self, f, compression):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000036 # Create the ZIP archive
37 zipfp = zipfile.ZipFile(f, "w", compression)
38 zipfp.write(TESTFN, "another"+os.extsep+"name")
39 zipfp.write(TESTFN, TESTFN)
Ronald Oussoren143cefb2006-06-15 08:14:18 +000040 zipfp.writestr("strfile", self.data)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000041 zipfp.close()
Tim Peters7d3bad62001-04-04 18:56:49 +000042
Martin v. Löwis3eb76482007-03-06 10:41:24 +000043 def zipTest(self, f, compression):
44 self.makeTestArchive(f, compression)
45
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000046 # Read the ZIP archive
47 zipfp = zipfile.ZipFile(f, "r", compression)
48 self.assertEqual(zipfp.read(TESTFN), self.data)
49 self.assertEqual(zipfp.read("another"+os.extsep+"name"), self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +000050 self.assertEqual(zipfp.read("strfile"), self.data)
51
52 # Print the ZIP directory
53 fp = StringIO()
54 stdout = sys.stdout
55 try:
56 sys.stdout = fp
57
58 zipfp.printdir()
59 finally:
60 sys.stdout = stdout
Tim Petersa608bb22006-06-15 18:06:29 +000061
Ronald Oussoren143cefb2006-06-15 08:14:18 +000062 directory = fp.getvalue()
63 lines = directory.splitlines()
64 self.assertEquals(len(lines), 4) # Number of files + header
65
66 self.assert_('File Name' in lines[0])
67 self.assert_('Modified' in lines[0])
68 self.assert_('Size' in lines[0])
69
70 fn, date, time, size = lines[1].split()
71 self.assertEquals(fn, 'another.name')
72 # XXX: timestamp is not tested
73 self.assertEquals(size, str(len(self.data)))
74
75 # Check the namelist
76 names = zipfp.namelist()
77 self.assertEquals(len(names), 3)
78 self.assert_(TESTFN in names)
79 self.assert_("another"+os.extsep+"name" in names)
80 self.assert_("strfile" in names)
81
82 # Check infolist
83 infos = zipfp.infolist()
84 names = [ i.filename for i in infos ]
85 self.assertEquals(len(names), 3)
86 self.assert_(TESTFN in names)
87 self.assert_("another"+os.extsep+"name" in names)
88 self.assert_("strfile" in names)
89 for i in infos:
90 self.assertEquals(i.file_size, len(self.data))
91
92 # check getinfo
93 for nm in (TESTFN, "another"+os.extsep+"name", "strfile"):
94 info = zipfp.getinfo(nm)
95 self.assertEquals(info.filename, nm)
96 self.assertEquals(info.file_size, len(self.data))
97
98 # Check that testzip doesn't raise an exception
99 zipfp.testzip()
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000100 zipfp.close()
Tim Peters7d3bad62001-04-04 18:56:49 +0000101
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000102 def testStored(self):
103 for f in (TESTFN2, TemporaryFile(), StringIO()):
104 self.zipTest(f, zipfile.ZIP_STORED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000105
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000106 def zipOpenTest(self, f, compression):
107 self.makeTestArchive(f, compression)
108
109 # Read the ZIP archive
110 zipfp = zipfile.ZipFile(f, "r", compression)
111 zipdata1 = []
112 zipopen1 = zipfp.open(TESTFN)
113 while 1:
114 read_data = zipopen1.read(256)
115 if not read_data:
116 break
117 zipdata1.append(read_data)
118
119 zipdata2 = []
120 zipopen2 = zipfp.open("another"+os.extsep+"name")
121 while 1:
122 read_data = zipopen2.read(256)
123 if not read_data:
124 break
125 zipdata2.append(read_data)
Tim Petersea5962f2007-03-12 18:07:52 +0000126
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000127 self.assertEqual(''.join(zipdata1), self.data)
128 self.assertEqual(''.join(zipdata2), self.data)
129 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000130
131 def testOpenStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000132 for f in (TESTFN2, TemporaryFile(), StringIO()):
133 self.zipOpenTest(f, zipfile.ZIP_STORED)
134
Georg Brandl112aa502008-05-20 08:25:48 +0000135 def testOpenViaZipInfo(self):
136 # Create the ZIP archive
137 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
138 zipfp.writestr("name", "foo")
139 zipfp.writestr("name", "bar")
140 zipfp.close()
141
142 zipfp = zipfile.ZipFile(TESTFN2, "r")
143 infos = zipfp.infolist()
144 data = ""
145 for info in infos:
146 data += zipfp.open(info).read()
147 self.assert_(data == "foobar" or data == "barfoo")
148 data = ""
149 for info in infos:
150 data += zipfp.read(info)
151 self.assert_(data == "foobar" or data == "barfoo")
152 zipfp.close()
153
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000154 def zipRandomOpenTest(self, f, compression):
155 self.makeTestArchive(f, compression)
156
157 # Read the ZIP archive
158 zipfp = zipfile.ZipFile(f, "r", compression)
159 zipdata1 = []
160 zipopen1 = zipfp.open(TESTFN)
161 while 1:
162 read_data = zipopen1.read(randint(1, 1024))
163 if not read_data:
164 break
165 zipdata1.append(read_data)
166
167 self.assertEqual(''.join(zipdata1), self.data)
168 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000169
170 def testRandomOpenStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000171 for f in (TESTFN2, TemporaryFile(), StringIO()):
172 self.zipRandomOpenTest(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +0000173
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000174 def zipReadlineTest(self, f, compression):
175 self.makeTestArchive(f, compression)
176
177 # Read the ZIP archive
178 zipfp = zipfile.ZipFile(f, "r")
179 zipopen = zipfp.open(TESTFN)
180 for line in self.line_gen:
181 linedata = zipopen.readline()
182 self.assertEqual(linedata, line + '\n')
183
184 zipfp.close()
185
186 def zipReadlinesTest(self, f, compression):
187 self.makeTestArchive(f, compression)
188
189 # Read the ZIP archive
190 zipfp = zipfile.ZipFile(f, "r")
191 ziplines = zipfp.open(TESTFN).readlines()
192 for line, zipline in zip(self.line_gen, ziplines):
193 self.assertEqual(zipline, line + '\n')
194
195 zipfp.close()
196
197 def zipIterlinesTest(self, f, compression):
198 self.makeTestArchive(f, compression)
199
200 # Read the ZIP archive
201 zipfp = zipfile.ZipFile(f, "r")
202 for line, zipline in zip(self.line_gen, zipfp.open(TESTFN)):
203 self.assertEqual(zipline, line + '\n')
204
205 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000206
207 def testReadlineStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000208 for f in (TESTFN2, TemporaryFile(), StringIO()):
209 self.zipReadlineTest(f, zipfile.ZIP_STORED)
210
Tim Petersea5962f2007-03-12 18:07:52 +0000211 def testReadlinesStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000212 for f in (TESTFN2, TemporaryFile(), StringIO()):
213 self.zipReadlinesTest(f, zipfile.ZIP_STORED)
214
Tim Petersea5962f2007-03-12 18:07:52 +0000215 def testIterlinesStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000216 for f in (TESTFN2, TemporaryFile(), StringIO()):
217 self.zipIterlinesTest(f, zipfile.ZIP_STORED)
218
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000219 if zlib:
220 def testDeflated(self):
221 for f in (TESTFN2, TemporaryFile(), StringIO()):
222 self.zipTest(f, zipfile.ZIP_DEFLATED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000223
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000224 def testOpenDeflated(self):
225 for f in (TESTFN2, TemporaryFile(), StringIO()):
226 self.zipOpenTest(f, zipfile.ZIP_DEFLATED)
227
228 def testRandomOpenDeflated(self):
229 for f in (TESTFN2, TemporaryFile(), StringIO()):
230 self.zipRandomOpenTest(f, zipfile.ZIP_DEFLATED)
231
Tim Petersea5962f2007-03-12 18:07:52 +0000232 def testReadlineDeflated(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000233 for f in (TESTFN2, TemporaryFile(), StringIO()):
234 self.zipReadlineTest(f, zipfile.ZIP_DEFLATED)
235
Tim Petersea5962f2007-03-12 18:07:52 +0000236 def testReadlinesDeflated(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000237 for f in (TESTFN2, TemporaryFile(), StringIO()):
238 self.zipReadlinesTest(f, zipfile.ZIP_DEFLATED)
239
Tim Petersea5962f2007-03-12 18:07:52 +0000240 def testIterlinesDeflated(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000241 for f in (TESTFN2, TemporaryFile(), StringIO()):
242 self.zipIterlinesTest(f, zipfile.ZIP_DEFLATED)
Tim Petersea5962f2007-03-12 18:07:52 +0000243
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000244 def testLowCompression(self):
245 # Checks for cases where compressed data is larger than original
246 # Create the ZIP archive
247 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED)
248 zipfp.writestr("strfile", '12')
249 zipfp.close()
250
251 # Get an open object for strfile
252 zipfp = zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_DEFLATED)
253 openobj = zipfp.open("strfile")
254 self.assertEqual(openobj.read(1), '1')
255 self.assertEqual(openobj.read(1), '2')
256
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000257 def testAbsoluteArcnames(self):
258 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
259 zipfp.write(TESTFN, "/absolute")
260 zipfp.close()
261
262 zipfp = zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED)
263 self.assertEqual(zipfp.namelist(), ["absolute"])
264 zipfp.close()
Tim Peters32cbc962006-02-20 21:42:18 +0000265
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000266 def testAppendToZipFile(self):
267 # Test appending to an existing zipfile
268 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
269 zipfp.write(TESTFN, TESTFN)
270 zipfp.close()
271 zipfp = zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED)
272 zipfp.writestr("strfile", self.data)
273 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
274 zipfp.close()
275
276 def testAppendToNonZipFile(self):
277 # Test appending to an existing file that is not a zipfile
278 # NOTE: this test fails if len(d) < 22 because of the first
279 # line "fpin.seek(-22, 2)" in _EndRecData
280 d = 'I am not a ZipFile!'*10
281 f = file(TESTFN2, 'wb')
282 f.write(d)
283 f.close()
284 zipfp = zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED)
285 zipfp.write(TESTFN, TESTFN)
286 zipfp.close()
287
288 f = file(TESTFN2, 'rb')
289 f.seek(len(d))
290 zipfp = zipfile.ZipFile(f, "r")
291 self.assertEqual(zipfp.namelist(), [TESTFN])
292 zipfp.close()
293 f.close()
294
295 def test_WriteDefaultName(self):
296 # Check that calling ZipFile.write without arcname specified produces the expected result
297 zipfp = zipfile.ZipFile(TESTFN2, "w")
298 zipfp.write(TESTFN)
299 self.assertEqual(zipfp.read(TESTFN), file(TESTFN).read())
300 zipfp.close()
301
302 def test_PerFileCompression(self):
303 # Check that files within a Zip archive can have different compression options
304 zipfp = zipfile.ZipFile(TESTFN2, "w")
305 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
306 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
307 sinfo = zipfp.getinfo('storeme')
308 dinfo = zipfp.getinfo('deflateme')
309 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
310 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
311 zipfp.close()
312
313 def test_WriteToReadonly(self):
314 # Check that trying to call write() on a readonly ZipFile object
315 # raises a RuntimeError
316 zipf = zipfile.ZipFile(TESTFN2, mode="w")
317 zipf.writestr("somefile.txt", "bogus")
318 zipf.close()
319 zipf = zipfile.ZipFile(TESTFN2, mode="r")
320 self.assertRaises(RuntimeError, zipf.write, TESTFN)
321 zipf.close()
322
Georg Brandl62416bc2008-01-07 18:47:44 +0000323 def testExtract(self):
324 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
325 for fpath, fdata in SMALL_TEST_DATA:
326 zipfp.writestr(fpath, fdata)
327 zipfp.close()
328
329 zipfp = zipfile.ZipFile(TESTFN2, "r")
330 for fpath, fdata in SMALL_TEST_DATA:
331 writtenfile = zipfp.extract(fpath)
332
333 # make sure it was written to the right place
334 if os.path.isabs(fpath):
335 correctfile = os.path.join(os.getcwd(), fpath[1:])
336 else:
337 correctfile = os.path.join(os.getcwd(), fpath)
Christian Heimesa2af2122008-01-26 16:43:35 +0000338 correctfile = os.path.normpath(correctfile)
Georg Brandl62416bc2008-01-07 18:47:44 +0000339
340 self.assertEqual(writtenfile, correctfile)
341
342 # make sure correct data is in correct file
343 self.assertEqual(fdata, file(writtenfile, "rb").read())
344
345 os.remove(writtenfile)
346
347 zipfp.close()
348
349 # remove the test file subdirectories
350 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
351
352 def testExtractAll(self):
353 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
354 for fpath, fdata in SMALL_TEST_DATA:
355 zipfp.writestr(fpath, fdata)
356 zipfp.close()
357
358 zipfp = zipfile.ZipFile(TESTFN2, "r")
359 zipfp.extractall()
360 for fpath, fdata in SMALL_TEST_DATA:
361 if os.path.isabs(fpath):
362 outfile = os.path.join(os.getcwd(), fpath[1:])
363 else:
364 outfile = os.path.join(os.getcwd(), fpath)
365
366 self.assertEqual(fdata, file(outfile, "rb").read())
367
368 os.remove(outfile)
369
370 zipfp.close()
371
372 # remove the test file subdirectories
373 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
374
Antoine Pitrou5fdfa3e2008-07-25 19:42:26 +0000375 def zip_test_writestr_permissions(self, f, compression):
376 # Make sure that writestr creates files with mode 0600,
377 # when it is passed a name rather than a ZipInfo instance.
378
379 self.makeTestArchive(f, compression)
380 zipfp = zipfile.ZipFile(f, "r")
381 zinfo = zipfp.getinfo('strfile')
382 self.assertEqual(zinfo.external_attr, 0600 << 16)
383
384 def test_writestr_permissions(self):
385 for f in (TESTFN2, TemporaryFile(), StringIO()):
386 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
387
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000388 def tearDown(self):
389 os.remove(TESTFN)
390 os.remove(TESTFN2)
391
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000392class TestZip64InSmallFiles(unittest.TestCase):
393 # These tests test the ZIP64 functionality without using large files,
394 # see test_zipfile64 for proper tests.
395
396 def setUp(self):
397 self._limit = zipfile.ZIP64_LIMIT
398 zipfile.ZIP64_LIMIT = 5
399
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000400 line_gen = ("Test of zipfile line %d." % i for i in range(0, FIXEDTEST_SIZE))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000401 self.data = '\n'.join(line_gen)
402
403 # Make a source file with some lines
404 fp = open(TESTFN, "wb")
405 fp.write(self.data)
406 fp.close()
407
408 def largeFileExceptionTest(self, f, compression):
409 zipfp = zipfile.ZipFile(f, "w", compression)
Tim Petersa608bb22006-06-15 18:06:29 +0000410 self.assertRaises(zipfile.LargeZipFile,
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000411 zipfp.write, TESTFN, "another"+os.extsep+"name")
412 zipfp.close()
413
414 def largeFileExceptionTest2(self, f, compression):
415 zipfp = zipfile.ZipFile(f, "w", compression)
Tim Petersa608bb22006-06-15 18:06:29 +0000416 self.assertRaises(zipfile.LargeZipFile,
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000417 zipfp.writestr, "another"+os.extsep+"name", self.data)
418 zipfp.close()
419
420 def testLargeFileException(self):
421 for f in (TESTFN2, TemporaryFile(), StringIO()):
422 self.largeFileExceptionTest(f, zipfile.ZIP_STORED)
423 self.largeFileExceptionTest2(f, zipfile.ZIP_STORED)
424
425 def zipTest(self, f, compression):
426 # Create the ZIP archive
427 zipfp = zipfile.ZipFile(f, "w", compression, allowZip64=True)
428 zipfp.write(TESTFN, "another"+os.extsep+"name")
429 zipfp.write(TESTFN, TESTFN)
430 zipfp.writestr("strfile", self.data)
431 zipfp.close()
432
433 # Read the ZIP archive
434 zipfp = zipfile.ZipFile(f, "r", compression)
435 self.assertEqual(zipfp.read(TESTFN), self.data)
436 self.assertEqual(zipfp.read("another"+os.extsep+"name"), self.data)
437 self.assertEqual(zipfp.read("strfile"), self.data)
438
439 # Print the ZIP directory
440 fp = StringIO()
441 stdout = sys.stdout
442 try:
443 sys.stdout = fp
444
445 zipfp.printdir()
446 finally:
447 sys.stdout = stdout
Tim Petersa608bb22006-06-15 18:06:29 +0000448
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000449 directory = fp.getvalue()
450 lines = directory.splitlines()
451 self.assertEquals(len(lines), 4) # Number of files + header
452
453 self.assert_('File Name' in lines[0])
454 self.assert_('Modified' in lines[0])
455 self.assert_('Size' in lines[0])
456
457 fn, date, time, size = lines[1].split()
458 self.assertEquals(fn, 'another.name')
459 # XXX: timestamp is not tested
460 self.assertEquals(size, str(len(self.data)))
461
462 # Check the namelist
463 names = zipfp.namelist()
464 self.assertEquals(len(names), 3)
465 self.assert_(TESTFN in names)
466 self.assert_("another"+os.extsep+"name" in names)
467 self.assert_("strfile" in names)
468
469 # Check infolist
470 infos = zipfp.infolist()
471 names = [ i.filename for i in infos ]
472 self.assertEquals(len(names), 3)
473 self.assert_(TESTFN in names)
474 self.assert_("another"+os.extsep+"name" in names)
475 self.assert_("strfile" in names)
476 for i in infos:
477 self.assertEquals(i.file_size, len(self.data))
478
479 # check getinfo
480 for nm in (TESTFN, "another"+os.extsep+"name", "strfile"):
481 info = zipfp.getinfo(nm)
482 self.assertEquals(info.filename, nm)
483 self.assertEquals(info.file_size, len(self.data))
484
485 # Check that testzip doesn't raise an exception
486 zipfp.testzip()
487
488
489 zipfp.close()
490
491 def testStored(self):
492 for f in (TESTFN2, TemporaryFile(), StringIO()):
493 self.zipTest(f, zipfile.ZIP_STORED)
494
495
496 if zlib:
497 def testDeflated(self):
498 for f in (TESTFN2, TemporaryFile(), StringIO()):
499 self.zipTest(f, zipfile.ZIP_DEFLATED)
500
501 def testAbsoluteArcnames(self):
502 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED, allowZip64=True)
503 zipfp.write(TESTFN, "/absolute")
504 zipfp.close()
505
506 zipfp = zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED)
507 self.assertEqual(zipfp.namelist(), ["absolute"])
508 zipfp.close()
509
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000510 def tearDown(self):
511 zipfile.ZIP64_LIMIT = self._limit
512 os.remove(TESTFN)
513 os.remove(TESTFN2)
514
515class PyZipFileTests(unittest.TestCase):
516 def testWritePyfile(self):
517 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
518 fn = __file__
519 if fn.endswith('.pyc') or fn.endswith('.pyo'):
520 fn = fn[:-1]
521
522 zipfp.writepy(fn)
523
524 bn = os.path.basename(fn)
525 self.assert_(bn not in zipfp.namelist())
526 self.assert_(bn + 'o' in zipfp.namelist() or bn + 'c' in zipfp.namelist())
527 zipfp.close()
528
529
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, "testpackage")
536
537 bn = "%s/%s"%("testpackage", os.path.basename(fn))
538 self.assert_(bn not in zipfp.namelist())
539 self.assert_(bn + 'o' in zipfp.namelist() or bn + 'c' in zipfp.namelist())
540 zipfp.close()
541
542 def testWritePythonPackage(self):
543 import email
544 packagedir = os.path.dirname(email.__file__)
545
546 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
547 zipfp.writepy(packagedir)
548
549 # Check for a couple of modules at different levels of the hieararchy
550 names = zipfp.namelist()
551 self.assert_('email/__init__.pyo' in names or 'email/__init__.pyc' in names)
552 self.assert_('email/mime/text.pyo' in names or 'email/mime/text.pyc' in names)
553
554 def testWritePythonDirectory(self):
555 os.mkdir(TESTFN2)
556 try:
557 fp = open(os.path.join(TESTFN2, "mod1.py"), "w")
558 fp.write("print 42\n")
559 fp.close()
560
561 fp = open(os.path.join(TESTFN2, "mod2.py"), "w")
562 fp.write("print 42 * 42\n")
563 fp.close()
564
565 fp = open(os.path.join(TESTFN2, "mod2.txt"), "w")
566 fp.write("bla bla bla\n")
567 fp.close()
568
569 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
570 zipfp.writepy(TESTFN2)
571
572 names = zipfp.namelist()
573 self.assert_('mod1.pyc' in names or 'mod1.pyo' in names)
574 self.assert_('mod2.pyc' in names or 'mod2.pyo' in names)
575 self.assert_('mod2.txt' not in names)
576
577 finally:
578 shutil.rmtree(TESTFN2)
579
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000580 def testWriteNonPyfile(self):
581 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
582 file(TESTFN, 'w').write('most definitely not a python file')
583 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
584 os.remove(TESTFN)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000585
586
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000587class OtherTests(unittest.TestCase):
Martin v. Löwis471617d2008-05-05 17:16:58 +0000588 def testUnicodeFilenames(self):
589 zf = zipfile.ZipFile(TESTFN, "w")
590 zf.writestr(u"foo.txt", "Test for unicode filename")
Martin v. Löwisc3ad68c2008-05-05 17:47:06 +0000591 zf.writestr(u"\xf6.txt", "Test for unicode filename")
592 self.assertTrue(isinstance(zf.infolist()[0].filename, unicode))
Martin v. Löwis471617d2008-05-05 17:16:58 +0000593 zf.close()
Martin v. Löwisc3ad68c2008-05-05 17:47:06 +0000594 zf = zipfile.ZipFile(TESTFN, "r")
595 self.assertEqual(zf.filelist[0].filename, "foo.txt")
596 self.assertEqual(zf.filelist[1].filename, u"\xf6.txt")
597 zf.close()
Martin v. Löwis471617d2008-05-05 17:16:58 +0000598
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000599 def testCreateNonExistentFileForAppend(self):
600 if os.path.exists(TESTFN):
601 os.unlink(TESTFN)
Tim Petersea5962f2007-03-12 18:07:52 +0000602
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000603 filename = 'testfile.txt'
604 content = 'hello, world. this is some content.'
Tim Petersea5962f2007-03-12 18:07:52 +0000605
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000606 try:
607 zf = zipfile.ZipFile(TESTFN, 'a')
608 zf.writestr(filename, content)
609 zf.close()
610 except IOError, (errno, errmsg):
611 self.fail('Could not append data to a non-existent zip file.')
612
613 self.assert_(os.path.exists(TESTFN))
614
615 zf = zipfile.ZipFile(TESTFN, 'r')
616 self.assertEqual(zf.read(filename), content)
617 zf.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000618
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000619 def testCloseErroneousFile(self):
620 # This test checks that the ZipFile constructor closes the file object
621 # it opens if there's an error in the file. If it doesn't, the traceback
622 # holds a reference to the ZipFile object and, indirectly, the file object.
623 # On Windows, this causes the os.unlink() call to fail because the
624 # underlying file is still open. This is SF bug #412214.
625 #
626 fp = open(TESTFN, "w")
627 fp.write("this is not a legal zip file\n")
628 fp.close()
629 try:
630 zf = zipfile.ZipFile(TESTFN)
631 except zipfile.BadZipfile:
Collin Winter04a51ec2007-03-29 02:28:16 +0000632 pass
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000633
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000634 def testIsZipErroneousFile(self):
Tim Petersea5962f2007-03-12 18:07:52 +0000635 # This test checks that the is_zipfile function correctly identifies
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000636 # a file that is not a zip file
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000637
638 # - passing a filename
639 with open(TESTFN, "w") as fp:
640 fp.write("this is not a legal zip file\n")
Tim Petersea5962f2007-03-12 18:07:52 +0000641 chk = zipfile.is_zipfile(TESTFN)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000642 self.assert_(not chk)
643 # - passing a file object
644 with open(TESTFN, "rb") as fp:
645 chk = zipfile.is_zipfile(fp)
646 self.assert_(not chk)
647 # - passing a file-like object
648 fp = StringIO()
649 fp.write("this is not a legal zip file\n")
650 chk = zipfile.is_zipfile(fp)
651 self.assert_(not chk)
652 fp.seek(0,0)
653 chk = zipfile.is_zipfile(fp)
654 self.assert_(not chk)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000655
656 def testIsZipValidFile(self):
Tim Petersea5962f2007-03-12 18:07:52 +0000657 # This test checks that the is_zipfile function correctly identifies
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000658 # a file that is a zip file
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000659
660 # - passing a filename
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000661 zipf = zipfile.ZipFile(TESTFN, mode="w")
662 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
663 zipf.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000664 chk = zipfile.is_zipfile(TESTFN)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000665 self.assert_(chk)
666 # - passing a file object
667 with open(TESTFN, "rb") as fp:
668 chk = zipfile.is_zipfile(fp)
669 self.assert_(chk)
670 fp.seek(0,0)
671 zip_contents = fp.read()
672 # - passing a file-like object
673 fp = StringIO()
674 fp.write(zip_contents)
675 chk = zipfile.is_zipfile(fp)
676 self.assert_(chk)
677 fp.seek(0,0)
678 chk = zipfile.is_zipfile(fp)
679 self.assert_(chk)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000680
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000681 def testNonExistentFileRaisesIOError(self):
682 # make sure we don't raise an AttributeError when a partially-constructed
683 # ZipFile instance is finalized; this tests for regression on SF tracker
684 # bug #403871.
685
686 # The bug we're testing for caused an AttributeError to be raised
687 # when a ZipFile instance was created for a file that did not
688 # exist; the .fp member was not initialized but was needed by the
689 # __del__() method. Since the AttributeError is in the __del__(),
690 # it is ignored, but the user should be sufficiently annoyed by
691 # the message on the output that regression will be noticed
692 # quickly.
693 self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
694
695 def testClosedZipRaisesRuntimeError(self):
696 # Verify that testzip() doesn't swallow inappropriate exceptions.
697 data = StringIO()
698 zipf = zipfile.ZipFile(data, mode="w")
699 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
700 zipf.close()
701
702 # This is correct; calling .read on a closed ZipFile should throw
703 # a RuntimeError, and so should calling .testzip. An earlier
704 # version of .testzip would swallow this exception (and any other)
705 # and report that the first file in the archive was corrupt.
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000706 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
707 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000708 self.assertRaises(RuntimeError, zipf.testzip)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000709 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
710 file(TESTFN, 'w').write('zipfile test data')
711 self.assertRaises(RuntimeError, zipf.write, TESTFN)
712
713 def test_BadConstructorMode(self):
714 # Check that bad modes passed to ZipFile constructor are caught
715 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
716
717 def test_BadOpenMode(self):
718 # Check that bad modes passed to ZipFile.open are caught
719 zipf = zipfile.ZipFile(TESTFN, mode="w")
720 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
721 zipf.close()
722 zipf = zipfile.ZipFile(TESTFN, mode="r")
723 # read the data to make sure the file is there
724 zipf.read("foo.txt")
725 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
726 zipf.close()
727
728 def test_Read0(self):
729 # Check that calling read(0) on a ZipExtFile object returns an empty
730 # string and doesn't advance file pointer
731 zipf = zipfile.ZipFile(TESTFN, mode="w")
732 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
733 # read the data to make sure the file is there
734 f = zipf.open("foo.txt")
735 for i in xrange(FIXEDTEST_SIZE):
736 self.assertEqual(f.read(0), '')
737
738 self.assertEqual(f.read(), "O, for a Muse of Fire!")
739 zipf.close()
740
741 def test_OpenNonexistentItem(self):
742 # Check that attempting to call open() for an item that doesn't
743 # exist in the archive raises a RuntimeError
744 zipf = zipfile.ZipFile(TESTFN, mode="w")
745 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
746
747 def test_BadCompressionMode(self):
748 # Check that bad compression methods passed to ZipFile.open are caught
749 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
750
751 def test_NullByteInFilename(self):
752 # Check that a filename containing a null byte is properly terminated
753 zipf = zipfile.ZipFile(TESTFN, mode="w")
754 zipf.writestr("foo.txt\x00qqq", "O, for a Muse of Fire!")
755 self.assertEqual(zipf.namelist(), ['foo.txt'])
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000756
Martin v. Löwis8c436412008-07-03 12:51:14 +0000757 def test_StructSizes(self):
758 # check that ZIP internal structure sizes are calculated correctly
759 self.assertEqual(zipfile.sizeEndCentDir, 22)
760 self.assertEqual(zipfile.sizeCentralDir, 46)
761 self.assertEqual(zipfile.sizeEndCentDir64, 56)
762 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
763
764 def testComments(self):
765 # This test checks that comments on the archive are handled properly
766
767 # check default comment is empty
768 zipf = zipfile.ZipFile(TESTFN, mode="w")
769 self.assertEqual(zipf.comment, '')
770 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
771 zipf.close()
772 zipfr = zipfile.ZipFile(TESTFN, mode="r")
773 self.assertEqual(zipfr.comment, '')
774 zipfr.close()
775
776 # check a simple short comment
777 comment = 'Bravely taking to his feet, he beat a very brave retreat.'
778 zipf = zipfile.ZipFile(TESTFN, mode="w")
779 zipf.comment = comment
780 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
781 zipf.close()
782 zipfr = zipfile.ZipFile(TESTFN, mode="r")
783 self.assertEqual(zipfr.comment, comment)
784 zipfr.close()
785
786 # check a comment of max length
787 comment2 = ''.join(['%d' % (i**3 % 10) for i in xrange((1 << 16)-1)])
788 zipf = zipfile.ZipFile(TESTFN, mode="w")
789 zipf.comment = comment2
790 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
791 zipf.close()
792 zipfr = zipfile.ZipFile(TESTFN, mode="r")
793 self.assertEqual(zipfr.comment, comment2)
794 zipfr.close()
795
796 # check a comment that is too long is truncated
797 zipf = zipfile.ZipFile(TESTFN, mode="w")
798 zipf.comment = comment2 + 'oops'
799 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
800 zipf.close()
801 zipfr = zipfile.ZipFile(TESTFN, mode="r")
802 self.assertEqual(zipfr.comment, comment2)
803 zipfr.close()
804
Collin Winter04a51ec2007-03-29 02:28:16 +0000805 def tearDown(self):
806 support.unlink(TESTFN)
807 support.unlink(TESTFN2)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000808
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000809class DecryptionTests(unittest.TestCase):
810 # This test checks that ZIP decryption works. Since the library does not
811 # support encryption at the moment, we use a pre-generated encrypted
812 # ZIP file
813
814 data = (
815 'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
816 '\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
817 '\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
818 'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
819 '\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
820 '\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
821 '\x00\x00L\x00\x00\x00\x00\x00' )
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000822 data2 = (
823 'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
824 '\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
825 '\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
826 'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
827 '\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
828 '\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
829 'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
830 '\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000831
832 plain = 'zipfile.py encryption test'
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000833 plain2 = '\x00'*512
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000834
835 def setUp(self):
836 fp = open(TESTFN, "wb")
837 fp.write(self.data)
838 fp.close()
839 self.zip = zipfile.ZipFile(TESTFN, "r")
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000840 fp = open(TESTFN2, "wb")
841 fp.write(self.data2)
842 fp.close()
843 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000844
845 def tearDown(self):
846 self.zip.close()
847 os.unlink(TESTFN)
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000848 self.zip2.close()
849 os.unlink(TESTFN2)
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000850
851 def testNoPassword(self):
852 # Reading the encrypted file without password
853 # must generate a RunTime exception
854 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000855 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000856
857 def testBadPassword(self):
858 self.zip.setpassword("perl")
859 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000860 self.zip2.setpassword("perl")
861 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Tim Petersea5962f2007-03-12 18:07:52 +0000862
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000863 def testGoodPassword(self):
864 self.zip.setpassword("python")
865 self.assertEquals(self.zip.read("test.txt"), self.plain)
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000866 self.zip2.setpassword("12345")
867 self.assertEquals(self.zip2.read("zero"), self.plain2)
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000868
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000869
870class TestsWithRandomBinaryFiles(unittest.TestCase):
871 def setUp(self):
872 datacount = randint(16, 64)*1024 + randint(1, 1024)
873 self.data = ''.join((struct.pack('<f', random()*randint(-1000, 1000)) for i in xrange(datacount)))
874
875 # Make a source file with some lines
876 fp = open(TESTFN, "wb")
877 fp.write(self.data)
878 fp.close()
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000879
Collin Winter04a51ec2007-03-29 02:28:16 +0000880 def tearDown(self):
881 support.unlink(TESTFN)
882 support.unlink(TESTFN2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000883
884 def makeTestArchive(self, f, compression):
885 # Create the ZIP archive
886 zipfp = zipfile.ZipFile(f, "w", compression)
887 zipfp.write(TESTFN, "another"+os.extsep+"name")
888 zipfp.write(TESTFN, TESTFN)
889 zipfp.close()
890
891 def zipTest(self, f, compression):
892 self.makeTestArchive(f, compression)
893
894 # Read the ZIP archive
895 zipfp = zipfile.ZipFile(f, "r", compression)
896 testdata = zipfp.read(TESTFN)
897 self.assertEqual(len(testdata), len(self.data))
898 self.assertEqual(testdata, self.data)
899 self.assertEqual(zipfp.read("another"+os.extsep+"name"), self.data)
900 zipfp.close()
901
902 def testStored(self):
903 for f in (TESTFN2, TemporaryFile(), StringIO()):
904 self.zipTest(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +0000905
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000906 def zipOpenTest(self, f, compression):
907 self.makeTestArchive(f, compression)
908
909 # Read the ZIP archive
910 zipfp = zipfile.ZipFile(f, "r", compression)
911 zipdata1 = []
912 zipopen1 = zipfp.open(TESTFN)
913 while 1:
914 read_data = zipopen1.read(256)
915 if not read_data:
916 break
917 zipdata1.append(read_data)
918
919 zipdata2 = []
920 zipopen2 = zipfp.open("another"+os.extsep+"name")
921 while 1:
922 read_data = zipopen2.read(256)
923 if not read_data:
924 break
925 zipdata2.append(read_data)
Tim Petersea5962f2007-03-12 18:07:52 +0000926
927 testdata1 = ''.join(zipdata1)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000928 self.assertEqual(len(testdata1), len(self.data))
929 self.assertEqual(testdata1, self.data)
930
Tim Petersea5962f2007-03-12 18:07:52 +0000931 testdata2 = ''.join(zipdata2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000932 self.assertEqual(len(testdata1), len(self.data))
933 self.assertEqual(testdata1, self.data)
934 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000935
936 def testOpenStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000937 for f in (TESTFN2, TemporaryFile(), StringIO()):
938 self.zipOpenTest(f, zipfile.ZIP_STORED)
939
940 def zipRandomOpenTest(self, f, compression):
941 self.makeTestArchive(f, compression)
942
943 # Read the ZIP archive
944 zipfp = zipfile.ZipFile(f, "r", compression)
945 zipdata1 = []
946 zipopen1 = zipfp.open(TESTFN)
947 while 1:
948 read_data = zipopen1.read(randint(1, 1024))
949 if not read_data:
950 break
951 zipdata1.append(read_data)
952
953 testdata = ''.join(zipdata1)
954 self.assertEqual(len(testdata), len(self.data))
955 self.assertEqual(testdata, self.data)
956 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000957
958 def testRandomOpenStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000959 for f in (TESTFN2, TemporaryFile(), StringIO()):
960 self.zipRandomOpenTest(f, zipfile.ZIP_STORED)
961
962class TestsWithMultipleOpens(unittest.TestCase):
963 def setUp(self):
964 # Create the ZIP archive
965 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED)
966 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
967 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
968 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000969
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000970 def testSameFile(self):
971 # Verify that (when the ZipFile is in control of creating file objects)
972 # multiple open() calls can be made without interfering with each other.
973 zipf = zipfile.ZipFile(TESTFN2, mode="r")
974 zopen1 = zipf.open('ones')
975 zopen2 = zipf.open('ones')
976 data1 = zopen1.read(500)
977 data2 = zopen2.read(500)
978 data1 += zopen1.read(500)
979 data2 += zopen2.read(500)
980 self.assertEqual(data1, data2)
981 zipf.close()
982
983 def testDifferentFile(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('twos')
989 data1 = zopen1.read(500)
990 data2 = zopen2.read(500)
991 data1 += zopen1.read(500)
992 data2 += zopen2.read(500)
993 self.assertEqual(data1, '1'*FIXEDTEST_SIZE)
994 self.assertEqual(data2, '2'*FIXEDTEST_SIZE)
995 zipf.close()
996
997 def testInterleaved(self):
998 # Verify that (when the ZipFile is in control of creating file objects)
999 # multiple open() calls can be made without interfering with each other.
1000 zipf = zipfile.ZipFile(TESTFN2, mode="r")
1001 zopen1 = zipf.open('ones')
1002 data1 = zopen1.read(500)
1003 zopen2 = zipf.open('twos')
1004 data2 = zopen2.read(500)
1005 data1 += zopen1.read(500)
1006 data2 += zopen2.read(500)
1007 self.assertEqual(data1, '1'*FIXEDTEST_SIZE)
1008 self.assertEqual(data2, '2'*FIXEDTEST_SIZE)
1009 zipf.close()
Tim Petersea5962f2007-03-12 18:07:52 +00001010
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001011 def tearDown(self):
1012 os.remove(TESTFN2)
Tim Petersea5962f2007-03-12 18:07:52 +00001013
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001014
1015class UniversalNewlineTests(unittest.TestCase):
1016 def setUp(self):
1017 self.line_gen = ["Test of zipfile line %d." % i for i in xrange(FIXEDTEST_SIZE)]
1018 self.seps = ('\r', '\r\n', '\n')
1019 self.arcdata, self.arcfiles = {}, {}
1020 for n, s in enumerate(self.seps):
1021 self.arcdata[s] = s.join(self.line_gen) + s
1022 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Brett Cannon6cef0762007-05-25 20:17:15 +00001023 open(self.arcfiles[s], "wb").write(self.arcdata[s])
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001024
1025 def makeTestArchive(self, f, compression):
1026 # Create the ZIP archive
1027 zipfp = zipfile.ZipFile(f, "w", compression)
1028 for fn in self.arcfiles.values():
1029 zipfp.write(fn, fn)
1030 zipfp.close()
1031
1032 def readTest(self, f, compression):
1033 self.makeTestArchive(f, compression)
1034
1035 # Read the ZIP archive
1036 zipfp = zipfile.ZipFile(f, "r")
1037 for sep, fn in self.arcfiles.items():
1038 zipdata = zipfp.open(fn, "rU").read()
1039 self.assertEqual(self.arcdata[sep], zipdata)
1040
1041 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +00001042
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001043 def readlineTest(self, f, compression):
1044 self.makeTestArchive(f, compression)
1045
1046 # Read the ZIP archive
1047 zipfp = zipfile.ZipFile(f, "r")
1048 for sep, fn in self.arcfiles.items():
1049 zipopen = zipfp.open(fn, "rU")
1050 for line in self.line_gen:
1051 linedata = zipopen.readline()
1052 self.assertEqual(linedata, line + '\n')
1053
1054 zipfp.close()
1055
1056 def readlinesTest(self, f, compression):
1057 self.makeTestArchive(f, compression)
1058
1059 # Read the ZIP archive
1060 zipfp = zipfile.ZipFile(f, "r")
1061 for sep, fn in self.arcfiles.items():
1062 ziplines = zipfp.open(fn, "rU").readlines()
1063 for line, zipline in zip(self.line_gen, ziplines):
1064 self.assertEqual(zipline, line + '\n')
1065
1066 zipfp.close()
1067
1068 def iterlinesTest(self, f, compression):
1069 self.makeTestArchive(f, compression)
1070
1071 # Read the ZIP archive
1072 zipfp = zipfile.ZipFile(f, "r")
1073 for sep, fn in self.arcfiles.items():
1074 for line, zipline in zip(self.line_gen, zipfp.open(fn, "rU")):
1075 self.assertEqual(zipline, line + '\n')
1076
1077 zipfp.close()
1078
Tim Petersea5962f2007-03-12 18:07:52 +00001079 def testReadStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001080 for f in (TESTFN2, TemporaryFile(), StringIO()):
1081 self.readTest(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +00001082
1083 def testReadlineStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001084 for f in (TESTFN2, TemporaryFile(), StringIO()):
1085 self.readlineTest(f, zipfile.ZIP_STORED)
1086
Tim Petersea5962f2007-03-12 18:07:52 +00001087 def testReadlinesStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001088 for f in (TESTFN2, TemporaryFile(), StringIO()):
1089 self.readlinesTest(f, zipfile.ZIP_STORED)
1090
Tim Petersea5962f2007-03-12 18:07:52 +00001091 def testIterlinesStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001092 for f in (TESTFN2, TemporaryFile(), StringIO()):
1093 self.iterlinesTest(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +00001094
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001095 if zlib:
Tim Petersea5962f2007-03-12 18:07:52 +00001096 def testReadDeflated(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001097 for f in (TESTFN2, TemporaryFile(), StringIO()):
1098 self.readTest(f, zipfile.ZIP_DEFLATED)
1099
Tim Petersea5962f2007-03-12 18:07:52 +00001100 def testReadlineDeflated(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001101 for f in (TESTFN2, TemporaryFile(), StringIO()):
1102 self.readlineTest(f, zipfile.ZIP_DEFLATED)
1103
Tim Petersea5962f2007-03-12 18:07:52 +00001104 def testReadlinesDeflated(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001105 for f in (TESTFN2, TemporaryFile(), StringIO()):
1106 self.readlinesTest(f, zipfile.ZIP_DEFLATED)
1107
Tim Petersea5962f2007-03-12 18:07:52 +00001108 def testIterlinesDeflated(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001109 for f in (TESTFN2, TemporaryFile(), StringIO()):
1110 self.iterlinesTest(f, zipfile.ZIP_DEFLATED)
1111
1112 def tearDown(self):
1113 for sep, fn in self.arcfiles.items():
1114 os.remove(fn)
Collin Winter04a51ec2007-03-29 02:28:16 +00001115 support.unlink(TESTFN)
1116 support.unlink(TESTFN2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001117
1118
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001119def test_main():
Tim Petersea5962f2007-03-12 18:07:52 +00001120 run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
1121 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001122 UniversalNewlineTests, TestsWithRandomBinaryFiles)
1123
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001124if __name__ == "__main__":
1125 test_main()