blob: 4bc2104d1b7c32b5fea127b3a35a66502ada8d05 [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
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000375 def tearDown(self):
376 os.remove(TESTFN)
377 os.remove(TESTFN2)
378
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000379class TestZip64InSmallFiles(unittest.TestCase):
380 # These tests test the ZIP64 functionality without using large files,
381 # see test_zipfile64 for proper tests.
382
383 def setUp(self):
384 self._limit = zipfile.ZIP64_LIMIT
385 zipfile.ZIP64_LIMIT = 5
386
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000387 line_gen = ("Test of zipfile line %d." % i for i in range(0, FIXEDTEST_SIZE))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000388 self.data = '\n'.join(line_gen)
389
390 # Make a source file with some lines
391 fp = open(TESTFN, "wb")
392 fp.write(self.data)
393 fp.close()
394
395 def largeFileExceptionTest(self, f, compression):
396 zipfp = zipfile.ZipFile(f, "w", compression)
Tim Petersa608bb22006-06-15 18:06:29 +0000397 self.assertRaises(zipfile.LargeZipFile,
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000398 zipfp.write, TESTFN, "another"+os.extsep+"name")
399 zipfp.close()
400
401 def largeFileExceptionTest2(self, f, compression):
402 zipfp = zipfile.ZipFile(f, "w", compression)
Tim Petersa608bb22006-06-15 18:06:29 +0000403 self.assertRaises(zipfile.LargeZipFile,
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000404 zipfp.writestr, "another"+os.extsep+"name", self.data)
405 zipfp.close()
406
407 def testLargeFileException(self):
408 for f in (TESTFN2, TemporaryFile(), StringIO()):
409 self.largeFileExceptionTest(f, zipfile.ZIP_STORED)
410 self.largeFileExceptionTest2(f, zipfile.ZIP_STORED)
411
412 def zipTest(self, f, compression):
413 # Create the ZIP archive
414 zipfp = zipfile.ZipFile(f, "w", compression, allowZip64=True)
415 zipfp.write(TESTFN, "another"+os.extsep+"name")
416 zipfp.write(TESTFN, TESTFN)
417 zipfp.writestr("strfile", self.data)
418 zipfp.close()
419
420 # Read the ZIP archive
421 zipfp = zipfile.ZipFile(f, "r", compression)
422 self.assertEqual(zipfp.read(TESTFN), self.data)
423 self.assertEqual(zipfp.read("another"+os.extsep+"name"), self.data)
424 self.assertEqual(zipfp.read("strfile"), self.data)
425
426 # Print the ZIP directory
427 fp = StringIO()
428 stdout = sys.stdout
429 try:
430 sys.stdout = fp
431
432 zipfp.printdir()
433 finally:
434 sys.stdout = stdout
Tim Petersa608bb22006-06-15 18:06:29 +0000435
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000436 directory = fp.getvalue()
437 lines = directory.splitlines()
438 self.assertEquals(len(lines), 4) # Number of files + header
439
440 self.assert_('File Name' in lines[0])
441 self.assert_('Modified' in lines[0])
442 self.assert_('Size' in lines[0])
443
444 fn, date, time, size = lines[1].split()
445 self.assertEquals(fn, 'another.name')
446 # XXX: timestamp is not tested
447 self.assertEquals(size, str(len(self.data)))
448
449 # Check the namelist
450 names = zipfp.namelist()
451 self.assertEquals(len(names), 3)
452 self.assert_(TESTFN in names)
453 self.assert_("another"+os.extsep+"name" in names)
454 self.assert_("strfile" in names)
455
456 # Check infolist
457 infos = zipfp.infolist()
458 names = [ i.filename for i in infos ]
459 self.assertEquals(len(names), 3)
460 self.assert_(TESTFN in names)
461 self.assert_("another"+os.extsep+"name" in names)
462 self.assert_("strfile" in names)
463 for i in infos:
464 self.assertEquals(i.file_size, len(self.data))
465
466 # check getinfo
467 for nm in (TESTFN, "another"+os.extsep+"name", "strfile"):
468 info = zipfp.getinfo(nm)
469 self.assertEquals(info.filename, nm)
470 self.assertEquals(info.file_size, len(self.data))
471
472 # Check that testzip doesn't raise an exception
473 zipfp.testzip()
474
475
476 zipfp.close()
477
478 def testStored(self):
479 for f in (TESTFN2, TemporaryFile(), StringIO()):
480 self.zipTest(f, zipfile.ZIP_STORED)
481
482
483 if zlib:
484 def testDeflated(self):
485 for f in (TESTFN2, TemporaryFile(), StringIO()):
486 self.zipTest(f, zipfile.ZIP_DEFLATED)
487
488 def testAbsoluteArcnames(self):
489 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED, allowZip64=True)
490 zipfp.write(TESTFN, "/absolute")
491 zipfp.close()
492
493 zipfp = zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED)
494 self.assertEqual(zipfp.namelist(), ["absolute"])
495 zipfp.close()
496
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000497 def tearDown(self):
498 zipfile.ZIP64_LIMIT = self._limit
499 os.remove(TESTFN)
500 os.remove(TESTFN2)
501
502class PyZipFileTests(unittest.TestCase):
503 def testWritePyfile(self):
504 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
505 fn = __file__
506 if fn.endswith('.pyc') or fn.endswith('.pyo'):
507 fn = fn[:-1]
508
509 zipfp.writepy(fn)
510
511 bn = os.path.basename(fn)
512 self.assert_(bn not in zipfp.namelist())
513 self.assert_(bn + 'o' in zipfp.namelist() or bn + 'c' in zipfp.namelist())
514 zipfp.close()
515
516
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, "testpackage")
523
524 bn = "%s/%s"%("testpackage", 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 def testWritePythonPackage(self):
530 import email
531 packagedir = os.path.dirname(email.__file__)
532
533 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
534 zipfp.writepy(packagedir)
535
536 # Check for a couple of modules at different levels of the hieararchy
537 names = zipfp.namelist()
538 self.assert_('email/__init__.pyo' in names or 'email/__init__.pyc' in names)
539 self.assert_('email/mime/text.pyo' in names or 'email/mime/text.pyc' in names)
540
541 def testWritePythonDirectory(self):
542 os.mkdir(TESTFN2)
543 try:
544 fp = open(os.path.join(TESTFN2, "mod1.py"), "w")
545 fp.write("print 42\n")
546 fp.close()
547
548 fp = open(os.path.join(TESTFN2, "mod2.py"), "w")
549 fp.write("print 42 * 42\n")
550 fp.close()
551
552 fp = open(os.path.join(TESTFN2, "mod2.txt"), "w")
553 fp.write("bla bla bla\n")
554 fp.close()
555
556 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
557 zipfp.writepy(TESTFN2)
558
559 names = zipfp.namelist()
560 self.assert_('mod1.pyc' in names or 'mod1.pyo' in names)
561 self.assert_('mod2.pyc' in names or 'mod2.pyo' in names)
562 self.assert_('mod2.txt' not in names)
563
564 finally:
565 shutil.rmtree(TESTFN2)
566
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000567 def testWriteNonPyfile(self):
568 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
569 file(TESTFN, 'w').write('most definitely not a python file')
570 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
571 os.remove(TESTFN)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000572
573
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000574class OtherTests(unittest.TestCase):
Martin v. Löwis471617d2008-05-05 17:16:58 +0000575 def testUnicodeFilenames(self):
576 zf = zipfile.ZipFile(TESTFN, "w")
577 zf.writestr(u"foo.txt", "Test for unicode filename")
Martin v. Löwisc3ad68c2008-05-05 17:47:06 +0000578 zf.writestr(u"\xf6.txt", "Test for unicode filename")
579 self.assertTrue(isinstance(zf.infolist()[0].filename, unicode))
Martin v. Löwis471617d2008-05-05 17:16:58 +0000580 zf.close()
Martin v. Löwisc3ad68c2008-05-05 17:47:06 +0000581 zf = zipfile.ZipFile(TESTFN, "r")
582 self.assertEqual(zf.filelist[0].filename, "foo.txt")
583 self.assertEqual(zf.filelist[1].filename, u"\xf6.txt")
584 zf.close()
Martin v. Löwis471617d2008-05-05 17:16:58 +0000585
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000586 def testCreateNonExistentFileForAppend(self):
587 if os.path.exists(TESTFN):
588 os.unlink(TESTFN)
Tim Petersea5962f2007-03-12 18:07:52 +0000589
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000590 filename = 'testfile.txt'
591 content = 'hello, world. this is some content.'
Tim Petersea5962f2007-03-12 18:07:52 +0000592
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000593 try:
594 zf = zipfile.ZipFile(TESTFN, 'a')
595 zf.writestr(filename, content)
596 zf.close()
597 except IOError, (errno, errmsg):
598 self.fail('Could not append data to a non-existent zip file.')
599
600 self.assert_(os.path.exists(TESTFN))
601
602 zf = zipfile.ZipFile(TESTFN, 'r')
603 self.assertEqual(zf.read(filename), content)
604 zf.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000605
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000606 def testCloseErroneousFile(self):
607 # This test checks that the ZipFile constructor closes the file object
608 # it opens if there's an error in the file. If it doesn't, the traceback
609 # holds a reference to the ZipFile object and, indirectly, the file object.
610 # On Windows, this causes the os.unlink() call to fail because the
611 # underlying file is still open. This is SF bug #412214.
612 #
613 fp = open(TESTFN, "w")
614 fp.write("this is not a legal zip file\n")
615 fp.close()
616 try:
617 zf = zipfile.ZipFile(TESTFN)
618 except zipfile.BadZipfile:
Collin Winter04a51ec2007-03-29 02:28:16 +0000619 pass
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000620
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000621 def testIsZipErroneousFile(self):
Tim Petersea5962f2007-03-12 18:07:52 +0000622 # This test checks that the is_zipfile function correctly identifies
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000623 # a file that is not a zip file
624 fp = open(TESTFN, "w")
625 fp.write("this is not a legal zip file\n")
626 fp.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000627 chk = zipfile.is_zipfile(TESTFN)
Tim Petersea5962f2007-03-12 18:07:52 +0000628 self.assert_(chk is False)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000629
630 def testIsZipValidFile(self):
Tim Petersea5962f2007-03-12 18:07:52 +0000631 # This test checks that the is_zipfile function correctly identifies
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000632 # a file that is a zip file
633 zipf = zipfile.ZipFile(TESTFN, mode="w")
634 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
635 zipf.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000636 chk = zipfile.is_zipfile(TESTFN)
Tim Petersea5962f2007-03-12 18:07:52 +0000637 self.assert_(chk is True)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000638
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000639 def testNonExistentFileRaisesIOError(self):
640 # make sure we don't raise an AttributeError when a partially-constructed
641 # ZipFile instance is finalized; this tests for regression on SF tracker
642 # bug #403871.
643
644 # The bug we're testing for caused an AttributeError to be raised
645 # when a ZipFile instance was created for a file that did not
646 # exist; the .fp member was not initialized but was needed by the
647 # __del__() method. Since the AttributeError is in the __del__(),
648 # it is ignored, but the user should be sufficiently annoyed by
649 # the message on the output that regression will be noticed
650 # quickly.
651 self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
652
653 def testClosedZipRaisesRuntimeError(self):
654 # Verify that testzip() doesn't swallow inappropriate exceptions.
655 data = StringIO()
656 zipf = zipfile.ZipFile(data, mode="w")
657 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
658 zipf.close()
659
660 # This is correct; calling .read on a closed ZipFile should throw
661 # a RuntimeError, and so should calling .testzip. An earlier
662 # version of .testzip would swallow this exception (and any other)
663 # and report that the first file in the archive was corrupt.
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000664 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
665 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000666 self.assertRaises(RuntimeError, zipf.testzip)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000667 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
668 file(TESTFN, 'w').write('zipfile test data')
669 self.assertRaises(RuntimeError, zipf.write, TESTFN)
670
671 def test_BadConstructorMode(self):
672 # Check that bad modes passed to ZipFile constructor are caught
673 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
674
675 def test_BadOpenMode(self):
676 # Check that bad modes passed to ZipFile.open are caught
677 zipf = zipfile.ZipFile(TESTFN, mode="w")
678 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
679 zipf.close()
680 zipf = zipfile.ZipFile(TESTFN, mode="r")
681 # read the data to make sure the file is there
682 zipf.read("foo.txt")
683 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
684 zipf.close()
685
686 def test_Read0(self):
687 # Check that calling read(0) on a ZipExtFile object returns an empty
688 # string and doesn't advance file pointer
689 zipf = zipfile.ZipFile(TESTFN, mode="w")
690 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
691 # read the data to make sure the file is there
692 f = zipf.open("foo.txt")
693 for i in xrange(FIXEDTEST_SIZE):
694 self.assertEqual(f.read(0), '')
695
696 self.assertEqual(f.read(), "O, for a Muse of Fire!")
697 zipf.close()
698
699 def test_OpenNonexistentItem(self):
700 # Check that attempting to call open() for an item that doesn't
701 # exist in the archive raises a RuntimeError
702 zipf = zipfile.ZipFile(TESTFN, mode="w")
703 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
704
705 def test_BadCompressionMode(self):
706 # Check that bad compression methods passed to ZipFile.open are caught
707 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
708
709 def test_NullByteInFilename(self):
710 # Check that a filename containing a null byte is properly terminated
711 zipf = zipfile.ZipFile(TESTFN, mode="w")
712 zipf.writestr("foo.txt\x00qqq", "O, for a Muse of Fire!")
713 self.assertEqual(zipf.namelist(), ['foo.txt'])
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000714
Collin Winter04a51ec2007-03-29 02:28:16 +0000715 def tearDown(self):
716 support.unlink(TESTFN)
717 support.unlink(TESTFN2)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000718
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000719class DecryptionTests(unittest.TestCase):
720 # This test checks that ZIP decryption works. Since the library does not
721 # support encryption at the moment, we use a pre-generated encrypted
722 # ZIP file
723
724 data = (
725 'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
726 '\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
727 '\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
728 'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
729 '\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
730 '\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
731 '\x00\x00L\x00\x00\x00\x00\x00' )
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000732 data2 = (
733 'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
734 '\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
735 '\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
736 'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
737 '\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
738 '\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
739 'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
740 '\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000741
742 plain = 'zipfile.py encryption test'
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000743 plain2 = '\x00'*512
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000744
745 def setUp(self):
746 fp = open(TESTFN, "wb")
747 fp.write(self.data)
748 fp.close()
749 self.zip = zipfile.ZipFile(TESTFN, "r")
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000750 fp = open(TESTFN2, "wb")
751 fp.write(self.data2)
752 fp.close()
753 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000754
755 def tearDown(self):
756 self.zip.close()
757 os.unlink(TESTFN)
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000758 self.zip2.close()
759 os.unlink(TESTFN2)
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000760
761 def testNoPassword(self):
762 # Reading the encrypted file without password
763 # must generate a RunTime exception
764 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000765 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000766
767 def testBadPassword(self):
768 self.zip.setpassword("perl")
769 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000770 self.zip2.setpassword("perl")
771 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Tim Petersea5962f2007-03-12 18:07:52 +0000772
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000773 def testGoodPassword(self):
774 self.zip.setpassword("python")
775 self.assertEquals(self.zip.read("test.txt"), self.plain)
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000776 self.zip2.setpassword("12345")
777 self.assertEquals(self.zip2.read("zero"), self.plain2)
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000778
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000779
780class TestsWithRandomBinaryFiles(unittest.TestCase):
781 def setUp(self):
782 datacount = randint(16, 64)*1024 + randint(1, 1024)
783 self.data = ''.join((struct.pack('<f', random()*randint(-1000, 1000)) for i in xrange(datacount)))
784
785 # Make a source file with some lines
786 fp = open(TESTFN, "wb")
787 fp.write(self.data)
788 fp.close()
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000789
Collin Winter04a51ec2007-03-29 02:28:16 +0000790 def tearDown(self):
791 support.unlink(TESTFN)
792 support.unlink(TESTFN2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000793
794 def makeTestArchive(self, f, compression):
795 # Create the ZIP archive
796 zipfp = zipfile.ZipFile(f, "w", compression)
797 zipfp.write(TESTFN, "another"+os.extsep+"name")
798 zipfp.write(TESTFN, TESTFN)
799 zipfp.close()
800
801 def zipTest(self, f, compression):
802 self.makeTestArchive(f, compression)
803
804 # Read the ZIP archive
805 zipfp = zipfile.ZipFile(f, "r", compression)
806 testdata = zipfp.read(TESTFN)
807 self.assertEqual(len(testdata), len(self.data))
808 self.assertEqual(testdata, self.data)
809 self.assertEqual(zipfp.read("another"+os.extsep+"name"), self.data)
810 zipfp.close()
811
812 def testStored(self):
813 for f in (TESTFN2, TemporaryFile(), StringIO()):
814 self.zipTest(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +0000815
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000816 def zipOpenTest(self, f, compression):
817 self.makeTestArchive(f, compression)
818
819 # Read the ZIP archive
820 zipfp = zipfile.ZipFile(f, "r", compression)
821 zipdata1 = []
822 zipopen1 = zipfp.open(TESTFN)
823 while 1:
824 read_data = zipopen1.read(256)
825 if not read_data:
826 break
827 zipdata1.append(read_data)
828
829 zipdata2 = []
830 zipopen2 = zipfp.open("another"+os.extsep+"name")
831 while 1:
832 read_data = zipopen2.read(256)
833 if not read_data:
834 break
835 zipdata2.append(read_data)
Tim Petersea5962f2007-03-12 18:07:52 +0000836
837 testdata1 = ''.join(zipdata1)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000838 self.assertEqual(len(testdata1), len(self.data))
839 self.assertEqual(testdata1, self.data)
840
Tim Petersea5962f2007-03-12 18:07:52 +0000841 testdata2 = ''.join(zipdata2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000842 self.assertEqual(len(testdata1), len(self.data))
843 self.assertEqual(testdata1, self.data)
844 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000845
846 def testOpenStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000847 for f in (TESTFN2, TemporaryFile(), StringIO()):
848 self.zipOpenTest(f, zipfile.ZIP_STORED)
849
850 def zipRandomOpenTest(self, f, compression):
851 self.makeTestArchive(f, compression)
852
853 # Read the ZIP archive
854 zipfp = zipfile.ZipFile(f, "r", compression)
855 zipdata1 = []
856 zipopen1 = zipfp.open(TESTFN)
857 while 1:
858 read_data = zipopen1.read(randint(1, 1024))
859 if not read_data:
860 break
861 zipdata1.append(read_data)
862
863 testdata = ''.join(zipdata1)
864 self.assertEqual(len(testdata), len(self.data))
865 self.assertEqual(testdata, self.data)
866 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000867
868 def testRandomOpenStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000869 for f in (TESTFN2, TemporaryFile(), StringIO()):
870 self.zipRandomOpenTest(f, zipfile.ZIP_STORED)
871
872class TestsWithMultipleOpens(unittest.TestCase):
873 def setUp(self):
874 # Create the ZIP archive
875 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED)
876 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
877 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
878 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000879
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000880 def testSameFile(self):
881 # Verify that (when the ZipFile is in control of creating file objects)
882 # multiple open() calls can be made without interfering with each other.
883 zipf = zipfile.ZipFile(TESTFN2, mode="r")
884 zopen1 = zipf.open('ones')
885 zopen2 = zipf.open('ones')
886 data1 = zopen1.read(500)
887 data2 = zopen2.read(500)
888 data1 += zopen1.read(500)
889 data2 += zopen2.read(500)
890 self.assertEqual(data1, data2)
891 zipf.close()
892
893 def testDifferentFile(self):
894 # Verify that (when the ZipFile is in control of creating file objects)
895 # multiple open() calls can be made without interfering with each other.
896 zipf = zipfile.ZipFile(TESTFN2, mode="r")
897 zopen1 = zipf.open('ones')
898 zopen2 = zipf.open('twos')
899 data1 = zopen1.read(500)
900 data2 = zopen2.read(500)
901 data1 += zopen1.read(500)
902 data2 += zopen2.read(500)
903 self.assertEqual(data1, '1'*FIXEDTEST_SIZE)
904 self.assertEqual(data2, '2'*FIXEDTEST_SIZE)
905 zipf.close()
906
907 def testInterleaved(self):
908 # Verify that (when the ZipFile is in control of creating file objects)
909 # multiple open() calls can be made without interfering with each other.
910 zipf = zipfile.ZipFile(TESTFN2, mode="r")
911 zopen1 = zipf.open('ones')
912 data1 = zopen1.read(500)
913 zopen2 = zipf.open('twos')
914 data2 = zopen2.read(500)
915 data1 += zopen1.read(500)
916 data2 += zopen2.read(500)
917 self.assertEqual(data1, '1'*FIXEDTEST_SIZE)
918 self.assertEqual(data2, '2'*FIXEDTEST_SIZE)
919 zipf.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000920
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000921 def tearDown(self):
922 os.remove(TESTFN2)
Tim Petersea5962f2007-03-12 18:07:52 +0000923
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000924
925class UniversalNewlineTests(unittest.TestCase):
926 def setUp(self):
927 self.line_gen = ["Test of zipfile line %d." % i for i in xrange(FIXEDTEST_SIZE)]
928 self.seps = ('\r', '\r\n', '\n')
929 self.arcdata, self.arcfiles = {}, {}
930 for n, s in enumerate(self.seps):
931 self.arcdata[s] = s.join(self.line_gen) + s
932 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Brett Cannon6cef0762007-05-25 20:17:15 +0000933 open(self.arcfiles[s], "wb").write(self.arcdata[s])
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000934
935 def makeTestArchive(self, f, compression):
936 # Create the ZIP archive
937 zipfp = zipfile.ZipFile(f, "w", compression)
938 for fn in self.arcfiles.values():
939 zipfp.write(fn, fn)
940 zipfp.close()
941
942 def readTest(self, f, compression):
943 self.makeTestArchive(f, compression)
944
945 # Read the ZIP archive
946 zipfp = zipfile.ZipFile(f, "r")
947 for sep, fn in self.arcfiles.items():
948 zipdata = zipfp.open(fn, "rU").read()
949 self.assertEqual(self.arcdata[sep], zipdata)
950
951 zipfp.close()
Tim Petersea5962f2007-03-12 18:07:52 +0000952
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000953 def readlineTest(self, f, compression):
954 self.makeTestArchive(f, compression)
955
956 # Read the ZIP archive
957 zipfp = zipfile.ZipFile(f, "r")
958 for sep, fn in self.arcfiles.items():
959 zipopen = zipfp.open(fn, "rU")
960 for line in self.line_gen:
961 linedata = zipopen.readline()
962 self.assertEqual(linedata, line + '\n')
963
964 zipfp.close()
965
966 def readlinesTest(self, f, compression):
967 self.makeTestArchive(f, compression)
968
969 # Read the ZIP archive
970 zipfp = zipfile.ZipFile(f, "r")
971 for sep, fn in self.arcfiles.items():
972 ziplines = zipfp.open(fn, "rU").readlines()
973 for line, zipline in zip(self.line_gen, ziplines):
974 self.assertEqual(zipline, line + '\n')
975
976 zipfp.close()
977
978 def iterlinesTest(self, f, compression):
979 self.makeTestArchive(f, compression)
980
981 # Read the ZIP archive
982 zipfp = zipfile.ZipFile(f, "r")
983 for sep, fn in self.arcfiles.items():
984 for line, zipline in zip(self.line_gen, zipfp.open(fn, "rU")):
985 self.assertEqual(zipline, line + '\n')
986
987 zipfp.close()
988
Tim Petersea5962f2007-03-12 18:07:52 +0000989 def testReadStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000990 for f in (TESTFN2, TemporaryFile(), StringIO()):
991 self.readTest(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +0000992
993 def testReadlineStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000994 for f in (TESTFN2, TemporaryFile(), StringIO()):
995 self.readlineTest(f, zipfile.ZIP_STORED)
996
Tim Petersea5962f2007-03-12 18:07:52 +0000997 def testReadlinesStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000998 for f in (TESTFN2, TemporaryFile(), StringIO()):
999 self.readlinesTest(f, zipfile.ZIP_STORED)
1000
Tim Petersea5962f2007-03-12 18:07:52 +00001001 def testIterlinesStored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001002 for f in (TESTFN2, TemporaryFile(), StringIO()):
1003 self.iterlinesTest(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +00001004
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001005 if zlib:
Tim Petersea5962f2007-03-12 18:07:52 +00001006 def testReadDeflated(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001007 for f in (TESTFN2, TemporaryFile(), StringIO()):
1008 self.readTest(f, zipfile.ZIP_DEFLATED)
1009
Tim Petersea5962f2007-03-12 18:07:52 +00001010 def testReadlineDeflated(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001011 for f in (TESTFN2, TemporaryFile(), StringIO()):
1012 self.readlineTest(f, zipfile.ZIP_DEFLATED)
1013
Tim Petersea5962f2007-03-12 18:07:52 +00001014 def testReadlinesDeflated(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001015 for f in (TESTFN2, TemporaryFile(), StringIO()):
1016 self.readlinesTest(f, zipfile.ZIP_DEFLATED)
1017
Tim Petersea5962f2007-03-12 18:07:52 +00001018 def testIterlinesDeflated(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001019 for f in (TESTFN2, TemporaryFile(), StringIO()):
1020 self.iterlinesTest(f, zipfile.ZIP_DEFLATED)
1021
1022 def tearDown(self):
1023 for sep, fn in self.arcfiles.items():
1024 os.remove(fn)
Collin Winter04a51ec2007-03-29 02:28:16 +00001025 support.unlink(TESTFN)
1026 support.unlink(TESTFN2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001027
1028
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001029def test_main():
Tim Petersea5962f2007-03-12 18:07:52 +00001030 run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
1031 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001032 UniversalNewlineTests, TestsWithRandomBinaryFiles)
1033
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001034if __name__ == "__main__":
1035 test_main()