blob: ee7524e8e5bcb45cebd6474dcfee61b099afdbf0 [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
Victor Stinnerff1d2f42011-05-18 13:43:23 +02006import io
7import os
8import shutil
9import struct
10import sys
11import unittest
12import zipfile
Tim Petersa45cacf2004-08-20 03:47:14 +000013
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000014from tempfile import TemporaryFile
Guido van Rossumd8faa362007-04-27 19:54:29 +000015from random import randint, random
Tim Petersa19a1682001-03-29 04:36:09 +000016
Benjamin Petersonee8712c2008-05-20 21:35:26 +000017import test.support as support
Martin v. Löwis59e47792009-01-24 14:10:07 +000018from test.support import TESTFN, run_unittest, findfile
Guido van Rossum368f04a2000-04-10 13:23:04 +000019
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000020TESTFN2 = TESTFN + "2"
Martin v. Löwis59e47792009-01-24 14:10:07 +000021TESTFNDIR = TESTFN + "d"
Guido van Rossumb5a755e2007-07-18 18:15:48 +000022FIXEDTEST_SIZE = 1000
Victor Stinnerff1d2f42011-05-18 13:43:23 +020023DATAFILES_DIR = 'zipfile_datafiles'
Guido van Rossum368f04a2000-04-10 13:23:04 +000024
Christian Heimes790c8232008-01-07 21:14:23 +000025SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'),
26 ('ziptest2dir/_ziptest2', 'qawsedrftg'),
27 ('/ziptest2dir/ziptest3dir/_ziptest3', 'azsxdcfvgb'),
28 ('ziptest2dir/ziptest3dir/ziptest4dir/_ziptest3', '6y7u8i9o0p')]
29
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000030class TestsWithSourceFile(unittest.TestCase):
31 def setUp(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +000032 self.line_gen = (bytes("Zipfile test line %d. random float: %f" %
Guido van Rossum9c627722007-08-27 18:31:48 +000033 (i, random()), "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +000034 for i in range(FIXEDTEST_SIZE))
35 self.data = b'\n'.join(self.line_gen) + b'\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
Guido van Rossumd8faa362007-04-27 19:54:29 +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)
Skip Montanaro7a98be22007-08-16 14:35:24 +000045 zipfp.write(TESTFN, "another.name")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000046 zipfp.write(TESTFN, TESTFN)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000047 zipfp.writestr("strfile", self.data)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000048 zipfp.close()
Tim Peters7d3bad62001-04-04 18:56:49 +000049
Guido van Rossumd8faa362007-04-27 19:54:29 +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)
Skip Montanaro7a98be22007-08-16 14:35:24 +000056 self.assertEqual(zipfp.read("another.name"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000057 self.assertEqual(zipfp.read("strfile"), self.data)
58
59 # Print the ZIP directory
Guido van Rossumd6ca5462007-05-22 01:29:33 +000060 fp = io.StringIO()
61 zipfp.printdir(file=fp)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000062
63 directory = fp.getvalue()
64 lines = directory.splitlines()
Ezio Melotti19f2aeb2010-11-21 01:30:29 +000065 self.assertEqual(len(lines), 4) # Number of files + header
Thomas Wouters0e3f5912006-08-11 14:57:12 +000066
Georg Brandlab91fde2009-08-13 08:51:18 +000067 self.assertTrue('File Name' in lines[0])
68 self.assertTrue('Modified' in lines[0])
69 self.assertTrue('Size' in lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +000070
71 fn, date, time, size = lines[1].split()
Ezio Melotti19f2aeb2010-11-21 01:30:29 +000072 self.assertEqual(fn, 'another.name')
Thomas Wouters0e3f5912006-08-11 14:57:12 +000073 # XXX: timestamp is not tested
Ezio Melotti19f2aeb2010-11-21 01:30:29 +000074 self.assertEqual(size, str(len(self.data)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000075
76 # Check the namelist
77 names = zipfp.namelist()
Ezio Melotti19f2aeb2010-11-21 01:30:29 +000078 self.assertEqual(len(names), 3)
Georg Brandlab91fde2009-08-13 08:51:18 +000079 self.assertTrue(TESTFN in names)
80 self.assertTrue("another.name" in names)
81 self.assertTrue("strfile" in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000082
83 # Check infolist
84 infos = zipfp.infolist()
85 names = [ i.filename for i in infos ]
Ezio Melotti19f2aeb2010-11-21 01:30:29 +000086 self.assertEqual(len(names), 3)
Georg Brandlab91fde2009-08-13 08:51:18 +000087 self.assertTrue(TESTFN in names)
88 self.assertTrue("another.name" in names)
89 self.assertTrue("strfile" in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000090 for i in infos:
Ezio Melotti19f2aeb2010-11-21 01:30:29 +000091 self.assertEqual(i.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000092
93 # check getinfo
Skip Montanaro7a98be22007-08-16 14:35:24 +000094 for nm in (TESTFN, "another.name", "strfile"):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000095 info = zipfp.getinfo(nm)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +000096 self.assertEqual(info.filename, nm)
97 self.assertEqual(info.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000098
99 # Check that testzip doesn't raise an exception
100 zipfp.testzip()
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000101 zipfp.close()
Tim Peters7d3bad62001-04-04 18:56:49 +0000102
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000103 def testStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000104 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000105 self.zipTest(f, zipfile.ZIP_STORED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000106
Guido van Rossumd8faa362007-04-27 19:54:29 +0000107 def zipOpenTest(self, f, compression):
108 self.makeTestArchive(f, compression)
109
110 # Read the ZIP archive
111 zipfp = zipfile.ZipFile(f, "r", compression)
112 zipdata1 = []
113 zipopen1 = zipfp.open(TESTFN)
114 while 1:
115 read_data = zipopen1.read(256)
116 if not read_data:
117 break
118 zipdata1.append(read_data)
119
120 zipdata2 = []
Skip Montanaro7a98be22007-08-16 14:35:24 +0000121 zipopen2 = zipfp.open("another.name")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000122 while 1:
123 read_data = zipopen2.read(256)
124 if not read_data:
125 break
126 zipdata2.append(read_data)
127
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000128 self.assertEqual(b''.join(zipdata1), self.data)
129 self.assertEqual(b''.join(zipdata2), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000130 zipfp.close()
131
132 def testOpenStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000133 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000134 self.zipOpenTest(f, zipfile.ZIP_STORED)
135
Georg Brandlb533e262008-05-25 18:19:30 +0000136 def testOpenViaZipInfo(self):
137 # Create the ZIP archive
138 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
139 zipfp.writestr("name", "foo")
140 zipfp.writestr("name", "bar")
141 zipfp.close()
142
143 zipfp = zipfile.ZipFile(TESTFN2, "r")
144 infos = zipfp.infolist()
145 data = b""
146 for info in infos:
147 data += zipfp.open(info).read()
Georg Brandlab91fde2009-08-13 08:51:18 +0000148 self.assertTrue(data == b"foobar" or data == b"barfoo")
Georg Brandlb533e262008-05-25 18:19:30 +0000149 data = b""
150 for info in infos:
151 data += zipfp.read(info)
Georg Brandlab91fde2009-08-13 08:51:18 +0000152 self.assertTrue(data == b"foobar" or data == b"barfoo")
Georg Brandlb533e262008-05-25 18:19:30 +0000153 zipfp.close()
154
Guido van Rossumd8faa362007-04-27 19:54:29 +0000155 def zipRandomOpenTest(self, f, compression):
156 self.makeTestArchive(f, compression)
157
158 # Read the ZIP archive
159 zipfp = zipfile.ZipFile(f, "r", compression)
160 zipdata1 = []
161 zipopen1 = zipfp.open(TESTFN)
162 while 1:
163 read_data = zipopen1.read(randint(1, 1024))
164 if not read_data:
165 break
166 zipdata1.append(read_data)
167
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000168 self.assertEqual(b''.join(zipdata1), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000169 zipfp.close()
170
171 def testRandomOpenStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000172 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000173 self.zipRandomOpenTest(f, zipfile.ZIP_STORED)
174
175 def zipReadlineTest(self, f, compression):
176 self.makeTestArchive(f, compression)
177
178 # Read the ZIP archive
179 zipfp = zipfile.ZipFile(f, "r")
180 zipopen = zipfp.open(TESTFN)
181 for line in self.line_gen:
182 linedata = zipopen.readline()
183 self.assertEqual(linedata, line + '\n')
184
185 zipfp.close()
186
187 def zipReadlinesTest(self, f, compression):
188 self.makeTestArchive(f, compression)
189
190 # Read the ZIP archive
191 zipfp = zipfile.ZipFile(f, "r")
192 ziplines = zipfp.open(TESTFN).readlines()
193 for line, zipline in zip(self.line_gen, ziplines):
194 self.assertEqual(zipline, line + '\n')
195
196 zipfp.close()
197
198 def zipIterlinesTest(self, f, compression):
199 self.makeTestArchive(f, compression)
200
201 # Read the ZIP archive
202 zipfp = zipfile.ZipFile(f, "r")
203 for line, zipline in zip(self.line_gen, zipfp.open(TESTFN)):
204 self.assertEqual(zipline, line + '\n')
205
206 zipfp.close()
207
208 def testReadlineStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000209 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000210 self.zipReadlineTest(f, zipfile.ZIP_STORED)
211
212 def testReadlinesStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000213 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000214 self.zipReadlinesTest(f, zipfile.ZIP_STORED)
215
216 def testIterlinesStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000217 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000218 self.zipIterlinesTest(f, zipfile.ZIP_STORED)
219
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000220 if zlib:
221 def testDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000222 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000223 self.zipTest(f, zipfile.ZIP_DEFLATED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000224
Guido van Rossumd8faa362007-04-27 19:54:29 +0000225 def testOpenDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000226 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000227 self.zipOpenTest(f, zipfile.ZIP_DEFLATED)
228
229 def testRandomOpenDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000230 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000231 self.zipRandomOpenTest(f, zipfile.ZIP_DEFLATED)
232
233 def testReadlineDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000234 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000235 self.zipReadlineTest(f, zipfile.ZIP_DEFLATED)
236
237 def testReadlinesDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000238 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000239 self.zipReadlinesTest(f, zipfile.ZIP_DEFLATED)
240
241 def testIterlinesDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000242 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000243 self.zipIterlinesTest(f, zipfile.ZIP_DEFLATED)
244
245 def testLowCompression(self):
246 # Checks for cases where compressed data is larger than original
247 # Create the ZIP archive
248 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED)
249 zipfp.writestr("strfile", '12')
250 zipfp.close()
251
252 # Get an open object for strfile
253 zipfp = zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_DEFLATED)
254 openobj = zipfp.open("strfile")
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000255 self.assertEqual(openobj.read(1), b'1')
256 self.assertEqual(openobj.read(1), b'2')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000257
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000258 def testAbsoluteArcnames(self):
259 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
260 zipfp.write(TESTFN, "/absolute")
261 zipfp.close()
262
263 zipfp = zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED)
264 self.assertEqual(zipfp.namelist(), ["absolute"])
265 zipfp.close()
Tim Peters32cbc962006-02-20 21:42:18 +0000266
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000267 def testAppendToZipFile(self):
268 # Test appending to an existing zipfile
269 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
270 zipfp.write(TESTFN, TESTFN)
271 zipfp.close()
272 zipfp = zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED)
273 zipfp.writestr("strfile", self.data)
274 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
275 zipfp.close()
276
277 def testAppendToNonZipFile(self):
278 # Test appending to an existing file that is not a zipfile
279 # NOTE: this test fails if len(d) < 22 because of the first
280 # line "fpin.seek(-22, 2)" in _EndRecData
Guido van Rossum9c627722007-08-27 18:31:48 +0000281 d = b'I am not a ZipFile!'*10
Guido van Rossum814661e2007-07-18 22:07:29 +0000282 f = open(TESTFN2, 'wb')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000283 f.write(d)
284 f.close()
285 zipfp = zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED)
286 zipfp.write(TESTFN, TESTFN)
287 zipfp.close()
288
Guido van Rossum814661e2007-07-18 22:07:29 +0000289 f = open(TESTFN2, 'rb')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000290 f.seek(len(d))
291 zipfp = zipfile.ZipFile(f, "r")
292 self.assertEqual(zipfp.namelist(), [TESTFN])
293 zipfp.close()
294 f.close()
295
296 def test_WriteDefaultName(self):
297 # Check that calling ZipFile.write without arcname specified produces the expected result
298 zipfp = zipfile.ZipFile(TESTFN2, "w")
299 zipfp.write(TESTFN)
Guido van Rossum814661e2007-07-18 22:07:29 +0000300 self.assertEqual(zipfp.read(TESTFN), open(TESTFN, "rb").read())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000301 zipfp.close()
302
303 def test_PerFileCompression(self):
304 # Check that files within a Zip archive can have different compression options
305 zipfp = zipfile.ZipFile(TESTFN2, "w")
306 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
307 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
308 sinfo = zipfp.getinfo('storeme')
309 dinfo = zipfp.getinfo('deflateme')
310 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
311 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
312 zipfp.close()
313
314 def test_WriteToReadonly(self):
315 # Check that trying to call write() on a readonly ZipFile object
316 # raises a RuntimeError
317 zipf = zipfile.ZipFile(TESTFN2, mode="w")
318 zipf.writestr("somefile.txt", "bogus")
319 zipf.close()
320 zipf = zipfile.ZipFile(TESTFN2, mode="r")
321 self.assertRaises(RuntimeError, zipf.write, TESTFN)
322 zipf.close()
323
Christian Heimes790c8232008-01-07 21:14:23 +0000324 def testExtract(self):
325 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
326 for fpath, fdata in SMALL_TEST_DATA:
327 zipfp.writestr(fpath, fdata)
328 zipfp.close()
329
330 zipfp = zipfile.ZipFile(TESTFN2, "r")
331 for fpath, fdata in SMALL_TEST_DATA:
332 writtenfile = zipfp.extract(fpath)
333
334 # make sure it was written to the right place
335 if os.path.isabs(fpath):
336 correctfile = os.path.join(os.getcwd(), fpath[1:])
337 else:
338 correctfile = os.path.join(os.getcwd(), fpath)
Christian Heimesaf98da12008-01-27 15:18:18 +0000339 correctfile = os.path.normpath(correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000340
341 self.assertEqual(writtenfile, correctfile)
342
343 # make sure correct data is in correct file
344 self.assertEqual(fdata.encode(), open(writtenfile, "rb").read())
345
346 os.remove(writtenfile)
347
348 zipfp.close()
349
350 # remove the test file subdirectories
351 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
352
353 def testExtractAll(self):
354 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
355 for fpath, fdata in SMALL_TEST_DATA:
356 zipfp.writestr(fpath, fdata)
357 zipfp.close()
358
359 zipfp = zipfile.ZipFile(TESTFN2, "r")
360 zipfp.extractall()
361 for fpath, fdata in SMALL_TEST_DATA:
362 if os.path.isabs(fpath):
363 outfile = os.path.join(os.getcwd(), fpath[1:])
364 else:
365 outfile = os.path.join(os.getcwd(), fpath)
366
367 self.assertEqual(fdata.encode(), open(outfile, "rb").read())
368
369 os.remove(outfile)
370
371 zipfp.close()
372
373 # remove the test file subdirectories
374 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
375
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000376 def zip_test_writestr_permissions(self, f, compression):
377 # Make sure that writestr creates files with mode 0600,
378 # when it is passed a name rather than a ZipInfo instance.
379
380 self.makeTestArchive(f, compression)
381 zipfp = zipfile.ZipFile(f, "r")
382 zinfo = zipfp.getinfo('strfile')
383 self.assertEqual(zinfo.external_attr, 0o600 << 16)
384
385 def test_writestr_permissions(self):
386 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
387 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
388
Georg Brandldf475152009-08-13 09:05:38 +0000389 def test_writestr_extended_local_header_issue1202(self):
390 orig_zip = zipfile.ZipFile(TESTFN2, 'w')
391 for data in 'abcdefghijklmnop':
392 zinfo = zipfile.ZipInfo(data)
393 zinfo.flag_bits |= 0x08 # Include an extended local header.
394 orig_zip.writestr(zinfo, data)
395 orig_zip.close()
396
Victor Stinnerff1d2f42011-05-18 13:43:23 +0200397 def test_unicode_filenames(self):
398 if __name__ == '__main__':
399 myfile = sys.argv[0]
400 else:
401 myfile = __file__
402
403 mydir = os.path.dirname(myfile) or os.curdir
404 fname = os.path.join(mydir, 'zip_cp437_header.zip')
405
Victor Stinnerff1d2f42011-05-18 13:43:23 +0200406 zipfp = zipfile.ZipFile(fname)
407 try:
Victor Stinnere6eafa22011-06-10 16:32:54 +0200408 for name in zipfp.namelist():
409 zipfp.open(name).close()
Victor Stinnerff1d2f42011-05-18 13:43:23 +0200410 finally:
411 zipfp.close()
412
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000413 def tearDown(self):
Victor Stinnerff1d2f42011-05-18 13:43:23 +0200414 support.unlink(TESTFN)
415 support.unlink(TESTFN2)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000416
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000417class TestZip64InSmallFiles(unittest.TestCase):
418 # These tests test the ZIP64 functionality without using large files,
419 # see test_zipfile64 for proper tests.
420
421 def setUp(self):
422 self._limit = zipfile.ZIP64_LIMIT
423 zipfile.ZIP64_LIMIT = 5
424
Guido van Rossum9c627722007-08-27 18:31:48 +0000425 line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000426 for i in range(0, FIXEDTEST_SIZE))
427 self.data = b'\n'.join(line_gen)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000428
429 # Make a source file with some lines
430 fp = open(TESTFN, "wb")
431 fp.write(self.data)
432 fp.close()
433
434 def largeFileExceptionTest(self, f, compression):
435 zipfp = zipfile.ZipFile(f, "w", compression)
436 self.assertRaises(zipfile.LargeZipFile,
Skip Montanaro7a98be22007-08-16 14:35:24 +0000437 zipfp.write, TESTFN, "another.name")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000438 zipfp.close()
439
440 def largeFileExceptionTest2(self, f, compression):
441 zipfp = zipfile.ZipFile(f, "w", compression)
442 self.assertRaises(zipfile.LargeZipFile,
Skip Montanaro7a98be22007-08-16 14:35:24 +0000443 zipfp.writestr, "another.name", self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000444 zipfp.close()
445
446 def testLargeFileException(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000447 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000448 self.largeFileExceptionTest(f, zipfile.ZIP_STORED)
449 self.largeFileExceptionTest2(f, zipfile.ZIP_STORED)
450
451 def zipTest(self, f, compression):
452 # Create the ZIP archive
453 zipfp = zipfile.ZipFile(f, "w", compression, allowZip64=True)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000454 zipfp.write(TESTFN, "another.name")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000455 zipfp.write(TESTFN, TESTFN)
456 zipfp.writestr("strfile", self.data)
457 zipfp.close()
458
459 # Read the ZIP archive
460 zipfp = zipfile.ZipFile(f, "r", compression)
461 self.assertEqual(zipfp.read(TESTFN), self.data)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000462 self.assertEqual(zipfp.read("another.name"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000463 self.assertEqual(zipfp.read("strfile"), self.data)
464
465 # Print the ZIP directory
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000466 fp = io.StringIO()
467 zipfp.printdir(fp)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000468
469 directory = fp.getvalue()
470 lines = directory.splitlines()
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000471 self.assertEqual(len(lines), 4) # Number of files + header
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000472
Georg Brandlab91fde2009-08-13 08:51:18 +0000473 self.assertTrue('File Name' in lines[0])
474 self.assertTrue('Modified' in lines[0])
475 self.assertTrue('Size' in lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000476
477 fn, date, time, size = lines[1].split()
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000478 self.assertEqual(fn, 'another.name')
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000479 # XXX: timestamp is not tested
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000480 self.assertEqual(size, str(len(self.data)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000481
482 # Check the namelist
483 names = zipfp.namelist()
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000484 self.assertEqual(len(names), 3)
Georg Brandlab91fde2009-08-13 08:51:18 +0000485 self.assertTrue(TESTFN in names)
486 self.assertTrue("another.name" in names)
487 self.assertTrue("strfile" in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000488
489 # Check infolist
490 infos = zipfp.infolist()
491 names = [ i.filename for i in infos ]
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000492 self.assertEqual(len(names), 3)
Georg Brandlab91fde2009-08-13 08:51:18 +0000493 self.assertTrue(TESTFN in names)
494 self.assertTrue("another.name" in names)
495 self.assertTrue("strfile" in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000496 for i in infos:
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000497 self.assertEqual(i.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000498
499 # check getinfo
Skip Montanaro7a98be22007-08-16 14:35:24 +0000500 for nm in (TESTFN, "another.name", "strfile"):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000501 info = zipfp.getinfo(nm)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000502 self.assertEqual(info.filename, nm)
503 self.assertEqual(info.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000504
505 # Check that testzip doesn't raise an exception
506 zipfp.testzip()
507
508
509 zipfp.close()
510
511 def testStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000512 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000513 self.zipTest(f, zipfile.ZIP_STORED)
514
515
516 if zlib:
517 def testDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000518 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000519 self.zipTest(f, zipfile.ZIP_DEFLATED)
520
521 def testAbsoluteArcnames(self):
522 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED, allowZip64=True)
523 zipfp.write(TESTFN, "/absolute")
524 zipfp.close()
525
526 zipfp = zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED)
527 self.assertEqual(zipfp.namelist(), ["absolute"])
528 zipfp.close()
529
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000530 def tearDown(self):
531 zipfile.ZIP64_LIMIT = self._limit
532 os.remove(TESTFN)
533 os.remove(TESTFN2)
534
535class PyZipFileTests(unittest.TestCase):
536 def testWritePyfile(self):
537 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
538 fn = __file__
539 if fn.endswith('.pyc') or fn.endswith('.pyo'):
540 fn = fn[:-1]
541
542 zipfp.writepy(fn)
543
544 bn = os.path.basename(fn)
Georg Brandlab91fde2009-08-13 08:51:18 +0000545 self.assertTrue(bn not in zipfp.namelist())
546 self.assertTrue(bn + 'o' in zipfp.namelist() or bn + 'c' in zipfp.namelist())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000547 zipfp.close()
548
549
550 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
551 fn = __file__
552 if fn.endswith('.pyc') or fn.endswith('.pyo'):
553 fn = fn[:-1]
554
555 zipfp.writepy(fn, "testpackage")
556
557 bn = "%s/%s"%("testpackage", os.path.basename(fn))
Georg Brandlab91fde2009-08-13 08:51:18 +0000558 self.assertTrue(bn not in zipfp.namelist())
559 self.assertTrue(bn + 'o' in zipfp.namelist() or bn + 'c' in zipfp.namelist())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000560 zipfp.close()
561
562 def testWritePythonPackage(self):
563 import email
564 packagedir = os.path.dirname(email.__file__)
565
566 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
567 zipfp.writepy(packagedir)
568
569 # Check for a couple of modules at different levels of the hieararchy
570 names = zipfp.namelist()
Georg Brandlab91fde2009-08-13 08:51:18 +0000571 self.assertTrue('email/__init__.pyo' in names or 'email/__init__.pyc' in names)
572 self.assertTrue('email/mime/text.pyo' in names or 'email/mime/text.pyc' in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000573
574 def testWritePythonDirectory(self):
575 os.mkdir(TESTFN2)
576 try:
577 fp = open(os.path.join(TESTFN2, "mod1.py"), "w")
Guido van Rossum43fc78d2007-02-09 22:18:41 +0000578 fp.write("print(42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000579 fp.close()
580
581 fp = open(os.path.join(TESTFN2, "mod2.py"), "w")
Guido van Rossum43fc78d2007-02-09 22:18:41 +0000582 fp.write("print(42 * 42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000583 fp.close()
584
585 fp = open(os.path.join(TESTFN2, "mod2.txt"), "w")
586 fp.write("bla bla bla\n")
587 fp.close()
588
589 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
590 zipfp.writepy(TESTFN2)
591
592 names = zipfp.namelist()
Georg Brandlab91fde2009-08-13 08:51:18 +0000593 self.assertTrue('mod1.pyc' in names or 'mod1.pyo' in names)
594 self.assertTrue('mod2.pyc' in names or 'mod2.pyo' in names)
595 self.assertTrue('mod2.txt' not in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000596
597 finally:
598 shutil.rmtree(TESTFN2)
599
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000600 def testWriteNonPyfile(self):
601 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
Guido van Rossum814661e2007-07-18 22:07:29 +0000602 open(TESTFN, 'w').write('most definitely not a python file')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000603 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
604 os.remove(TESTFN)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000605
606
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000607class OtherTests(unittest.TestCase):
Antoine Pitrou5f2a7bc2010-08-12 15:30:13 +0000608 zips_with_bad_crc = {
609 zipfile.ZIP_STORED: (
610 b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
611 b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
612 b'ilehello,AworldP'
613 b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
614 b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
615 b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
616 b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
617 b'\0\0/\0\0\0\0\0'),
618 zipfile.ZIP_DEFLATED: (
619 b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
620 b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
621 b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
622 b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
623 b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
624 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
625 b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
626 b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00'),
627 }
628
Martin v. Löwis8570f6a2008-05-05 17:44:38 +0000629 def testUnicodeFilenames(self):
630 zf = zipfile.ZipFile(TESTFN, "w")
631 zf.writestr("foo.txt", "Test for unicode filename")
Martin v. Löwis1a9f9002008-05-05 17:50:05 +0000632 zf.writestr("\xf6.txt", "Test for unicode filename")
Martin v. Löwis8570f6a2008-05-05 17:44:38 +0000633 zf.close()
Martin v. Löwis1a9f9002008-05-05 17:50:05 +0000634 zf = zipfile.ZipFile(TESTFN, "r")
635 self.assertEqual(zf.filelist[0].filename, "foo.txt")
636 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
637 zf.close()
Martin v. Löwis8570f6a2008-05-05 17:44:38 +0000638
Thomas Wouterscf297e42007-02-23 15:07:44 +0000639 def testCreateNonExistentFileForAppend(self):
640 if os.path.exists(TESTFN):
641 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000642
Thomas Wouterscf297e42007-02-23 15:07:44 +0000643 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000644 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +0000645
Thomas Wouterscf297e42007-02-23 15:07:44 +0000646 try:
647 zf = zipfile.ZipFile(TESTFN, 'a')
648 zf.writestr(filename, content)
649 zf.close()
650 except IOError:
651 self.fail('Could not append data to a non-existent zip file.')
652
Georg Brandlab91fde2009-08-13 08:51:18 +0000653 self.assertTrue(os.path.exists(TESTFN))
Thomas Wouterscf297e42007-02-23 15:07:44 +0000654
655 zf = zipfile.ZipFile(TESTFN, 'r')
656 self.assertEqual(zf.read(filename), content)
657 zf.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000658
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000659 def testCloseErroneousFile(self):
660 # This test checks that the ZipFile constructor closes the file object
661 # it opens if there's an error in the file. If it doesn't, the traceback
662 # holds a reference to the ZipFile object and, indirectly, the file object.
663 # On Windows, this causes the os.unlink() call to fail because the
664 # underlying file is still open. This is SF bug #412214.
665 #
666 fp = open(TESTFN, "w")
667 fp.write("this is not a legal zip file\n")
668 fp.close()
669 try:
670 zf = zipfile.ZipFile(TESTFN)
671 except zipfile.BadZipfile:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000672 pass
673
674 def testIsZipErroneousFile(self):
675 # This test checks that the is_zipfile function correctly identifies
676 # a file that is not a zip file
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000677
678 # - passing a filename
679 with open(TESTFN, "w") as fp:
680 fp.write("this is not a legal zip file\n")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000681 chk = zipfile.is_zipfile(TESTFN)
Georg Brandlab91fde2009-08-13 08:51:18 +0000682 self.assertTrue(not chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000683 # - passing a file object
684 with open(TESTFN, "rb") as fp:
685 chk = zipfile.is_zipfile(fp)
Georg Brandlab91fde2009-08-13 08:51:18 +0000686 self.assertTrue(not chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000687 # - passing a file-like object
688 fp = io.BytesIO()
689 fp.write(b"this is not a legal zip file\n")
690 chk = zipfile.is_zipfile(fp)
Georg Brandlab91fde2009-08-13 08:51:18 +0000691 self.assertTrue(not chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000692 fp.seek(0,0)
693 chk = zipfile.is_zipfile(fp)
Georg Brandlab91fde2009-08-13 08:51:18 +0000694 self.assertTrue(not chk)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000695
696 def testIsZipValidFile(self):
697 # This test checks that the is_zipfile function correctly identifies
698 # a file that is a zip file
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000699
700 # - passing a filename
Guido van Rossumd8faa362007-04-27 19:54:29 +0000701 zipf = zipfile.ZipFile(TESTFN, mode="w")
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000702 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000703 zipf.close()
704 chk = zipfile.is_zipfile(TESTFN)
Georg Brandlab91fde2009-08-13 08:51:18 +0000705 self.assertTrue(chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000706 # - passing a file object
707 with open(TESTFN, "rb") as fp:
708 chk = zipfile.is_zipfile(fp)
Georg Brandlab91fde2009-08-13 08:51:18 +0000709 self.assertTrue(chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000710 fp.seek(0,0)
711 zip_contents = fp.read()
712 # - passing a file-like object
713 fp = io.BytesIO()
714 fp.write(zip_contents)
715 chk = zipfile.is_zipfile(fp)
Georg Brandlab91fde2009-08-13 08:51:18 +0000716 self.assertTrue(chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000717 fp.seek(0,0)
718 chk = zipfile.is_zipfile(fp)
Georg Brandlab91fde2009-08-13 08:51:18 +0000719 self.assertTrue(chk)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000720
721 def testNonExistentFileRaisesIOError(self):
722 # make sure we don't raise an AttributeError when a partially-constructed
723 # ZipFile instance is finalized; this tests for regression on SF tracker
724 # bug #403871.
725
726 # The bug we're testing for caused an AttributeError to be raised
727 # when a ZipFile instance was created for a file that did not
728 # exist; the .fp member was not initialized but was needed by the
729 # __del__() method. Since the AttributeError is in the __del__(),
730 # it is ignored, but the user should be sufficiently annoyed by
731 # the message on the output that regression will be noticed
732 # quickly.
733 self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
734
R. David Murray93a59652010-01-06 20:12:07 +0000735 def test_empty_file_raises_BadZipFile(self):
736 f = open(TESTFN, 'w')
737 f.close()
738 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN)
739
740 f = open(TESTFN, 'w')
741 f.write("short file")
742 f.close()
743 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN)
744
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000745 def testClosedZipRaisesRuntimeError(self):
746 # Verify that testzip() doesn't swallow inappropriate exceptions.
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000747 data = io.BytesIO()
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000748 zipf = zipfile.ZipFile(data, mode="w")
749 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
750 zipf.close()
751
752 # This is correct; calling .read on a closed ZipFile should throw
753 # a RuntimeError, and so should calling .testzip. An earlier
754 # version of .testzip would swallow this exception (and any other)
755 # and report that the first file in the archive was corrupt.
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000756 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
757 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000758 self.assertRaises(RuntimeError, zipf.testzip)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000759 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Guido van Rossum814661e2007-07-18 22:07:29 +0000760 open(TESTFN, 'w').write('zipfile test data')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000761 self.assertRaises(RuntimeError, zipf.write, TESTFN)
762
763 def test_BadConstructorMode(self):
764 # Check that bad modes passed to ZipFile constructor are caught
765 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
766
767 def test_BadOpenMode(self):
768 # Check that bad modes passed to ZipFile.open are caught
769 zipf = zipfile.ZipFile(TESTFN, mode="w")
770 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
771 zipf.close()
772 zipf = zipfile.ZipFile(TESTFN, mode="r")
773 # read the data to make sure the file is there
774 zipf.read("foo.txt")
775 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
776 zipf.close()
777
778 def test_Read0(self):
779 # Check that calling read(0) on a ZipExtFile object returns an empty
780 # string and doesn't advance file pointer
781 zipf = zipfile.ZipFile(TESTFN, mode="w")
782 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
783 # read the data to make sure the file is there
784 f = zipf.open("foo.txt")
785 for i in range(FIXEDTEST_SIZE):
Guido van Rossum814661e2007-07-18 22:07:29 +0000786 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000787
Guido van Rossum814661e2007-07-18 22:07:29 +0000788 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000789 zipf.close()
790
791 def test_OpenNonexistentItem(self):
792 # Check that attempting to call open() for an item that doesn't
793 # exist in the archive raises a RuntimeError
794 zipf = zipfile.ZipFile(TESTFN, mode="w")
795 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
796
797 def test_BadCompressionMode(self):
798 # Check that bad compression methods passed to ZipFile.open are caught
799 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
800
801 def test_NullByteInFilename(self):
802 # Check that a filename containing a null byte is properly terminated
803 zipf = zipfile.ZipFile(TESTFN, mode="w")
Guido van Rossum814661e2007-07-18 22:07:29 +0000804 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000805 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000806
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000807 def test_StructSizes(self):
808 # check that ZIP internal structure sizes are calculated correctly
809 self.assertEqual(zipfile.sizeEndCentDir, 22)
810 self.assertEqual(zipfile.sizeCentralDir, 46)
811 self.assertEqual(zipfile.sizeEndCentDir64, 56)
812 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
813
814 def testComments(self):
815 # This test checks that comments on the archive are handled properly
816
817 # check default comment is empty
818 zipf = zipfile.ZipFile(TESTFN, mode="w")
819 self.assertEqual(zipf.comment, b'')
820 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
821 zipf.close()
822 zipfr = zipfile.ZipFile(TESTFN, mode="r")
823 self.assertEqual(zipfr.comment, b'')
824 zipfr.close()
825
826 # check a simple short comment
827 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
828 zipf = zipfile.ZipFile(TESTFN, mode="w")
829 zipf.comment = comment
830 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
831 zipf.close()
832 zipfr = zipfile.ZipFile(TESTFN, mode="r")
833 self.assertEqual(zipfr.comment, comment)
834 zipfr.close()
835
836 # check a comment of max length
837 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
838 comment2 = comment2.encode("ascii")
839 zipf = zipfile.ZipFile(TESTFN, mode="w")
840 zipf.comment = comment2
841 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
842 zipf.close()
843 zipfr = zipfile.ZipFile(TESTFN, mode="r")
844 self.assertEqual(zipfr.comment, comment2)
845 zipfr.close()
846
847 # check a comment that is too long is truncated
848 zipf = zipfile.ZipFile(TESTFN, mode="w")
849 zipf.comment = comment2 + b'oops'
850 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
851 zipf.close()
852 zipfr = zipfile.ZipFile(TESTFN, mode="r")
853 self.assertEqual(zipfr.comment, comment2)
854 zipfr.close()
855
Antoine Pitrou5f2a7bc2010-08-12 15:30:13 +0000856 def check_testzip_with_bad_crc(self, compression):
857 """Tests that files with bad CRCs return their name from testzip."""
858 zipdata = self.zips_with_bad_crc[compression]
859
860 zipf = zipfile.ZipFile(io.BytesIO(zipdata), mode="r")
861 # testzip returns the name of the first corrupt file, or None
862 self.assertEqual('afile', zipf.testzip())
863 zipf.close()
864
865 def test_testzip_with_bad_crc_stored(self):
866 self.check_testzip_with_bad_crc(zipfile.ZIP_STORED)
867
868 if zlib:
869 def test_testzip_with_bad_crc_deflated(self):
870 self.check_testzip_with_bad_crc(zipfile.ZIP_DEFLATED)
871
872 def check_read_with_bad_crc(self, compression):
873 """Tests that files with bad CRCs raise a BadZipfile exception when read."""
874 zipdata = self.zips_with_bad_crc[compression]
875
876 # Using ZipFile.read()
877 zipf = zipfile.ZipFile(io.BytesIO(zipdata), mode="r")
878 self.assertRaises(zipfile.BadZipfile, zipf.read, 'afile')
879 zipf.close()
880
881 # Using ZipExtFile.read()
882 zipf = zipfile.ZipFile(io.BytesIO(zipdata), mode="r")
883 corrupt_file = zipf.open('afile', 'r')
884 self.assertRaises(zipfile.BadZipfile, corrupt_file.read)
885 corrupt_file.close()
886 zipf.close()
887
888 # Same with small reads (in order to exercise the buffering logic)
889 zipf = zipfile.ZipFile(io.BytesIO(zipdata), mode="r")
890 corrupt_file = zipf.open('afile', 'r')
891 corrupt_file.MIN_READ_SIZE = 2
892 with self.assertRaises(zipfile.BadZipfile):
893 while corrupt_file.read(2):
894 pass
895 corrupt_file.close()
896 zipf.close()
897
898 def test_read_with_bad_crc_stored(self):
899 self.check_read_with_bad_crc(zipfile.ZIP_STORED)
900
901 if zlib:
902 def test_read_with_bad_crc_deflated(self):
903 self.check_read_with_bad_crc(zipfile.ZIP_DEFLATED)
904
Antoine Pitrou1052e392010-09-12 14:55:22 +0000905 def check_read_return_size(self, compression):
906 # Issue #9837: ZipExtFile.read() shouldn't return more bytes
907 # than requested.
908 for test_size in (1, 4095, 4096, 4097, 16384):
909 file_size = test_size + 1
910 junk = b''.join(struct.pack('B', randint(0, 255))
911 for x in range(file_size))
912 zipf = zipfile.ZipFile(io.BytesIO(), "w", compression)
913 try:
914 zipf.writestr('foo', junk)
915 fp = zipf.open('foo', 'r')
916 buf = fp.read(test_size)
917 self.assertEqual(len(buf), test_size)
918 finally:
919 zipf.close()
920
921 def test_read_return_size_stored(self):
922 self.check_read_return_size(zipfile.ZIP_STORED)
923
924 if zlib:
925 def test_read_return_size_deflated(self):
926 self.check_read_return_size(zipfile.ZIP_DEFLATED)
927
Georg Brandlaba97962010-11-26 08:37:46 +0000928 def test_empty_zipfile(self):
929 # Check that creating a file in 'w' or 'a' mode and closing without
930 # adding any files to the archives creates a valid empty ZIP file
931 zipf = zipfile.ZipFile(TESTFN, mode="w")
932 zipf.close()
933 try:
934 zipf = zipfile.ZipFile(TESTFN, mode="r")
Éric Araujoa172e252011-02-02 16:58:43 +0000935 except zipfile.BadZipfile:
Georg Brandlaba97962010-11-26 08:37:46 +0000936 self.fail("Unable to create empty ZIP file in 'w' mode")
937
938 zipf = zipfile.ZipFile(TESTFN, mode="a")
939 zipf.close()
940 try:
941 zipf = zipfile.ZipFile(TESTFN, mode="r")
942 except:
943 self.fail("Unable to create empty ZIP file in 'a' mode")
944
945 def test_open_empty_file(self):
946 # Issue 1710703: Check that opening a file with less than 22 bytes
947 # raises a BadZipfile exception (rather than the previously unhelpful
948 # IOError)
949 f = open(TESTFN, 'w')
950 f.close()
951 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN, 'r')
952
Guido van Rossumd8faa362007-04-27 19:54:29 +0000953 def tearDown(self):
954 support.unlink(TESTFN)
955 support.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000956
957class DecryptionTests(unittest.TestCase):
958 # This test checks that ZIP decryption works. Since the library does not
959 # support encryption at the moment, we use a pre-generated encrypted
960 # ZIP file
961
962 data = (
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000963 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
964 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
965 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
966 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
967 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
968 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
969 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +0000970 data2 = (
971 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
972 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
973 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
974 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
975 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
976 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
977 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
978 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +0000979
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000980 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +0000981 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +0000982
983 def setUp(self):
984 fp = open(TESTFN, "wb")
985 fp.write(self.data)
986 fp.close()
987 self.zip = zipfile.ZipFile(TESTFN, "r")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000988 fp = open(TESTFN2, "wb")
989 fp.write(self.data2)
990 fp.close()
991 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000992
993 def tearDown(self):
994 self.zip.close()
995 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +0000996 self.zip2.close()
997 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000998
999 def testNoPassword(self):
1000 # Reading the encrypted file without password
1001 # must generate a RunTime exception
1002 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001003 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001004
1005 def testBadPassword(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001006 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001007 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001008 self.zip2.setpassword(b"perl")
1009 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001010
Thomas Wouterscf297e42007-02-23 15:07:44 +00001011 def testGoodPassword(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001012 self.zip.setpassword(b"python")
Ezio Melotti19f2aeb2010-11-21 01:30:29 +00001013 self.assertEqual(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001014 self.zip2.setpassword(b"12345")
Ezio Melotti19f2aeb2010-11-21 01:30:29 +00001015 self.assertEqual(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001016
R. David Murray30f9c8c2010-12-21 21:57:54 +00001017 def test_unicode_password(self):
1018 self.assertRaises(TypeError, self.zip.setpassword, "unicode")
1019 self.assertRaises(TypeError, self.zip.read, "test.txt", "python")
1020 self.assertRaises(TypeError, self.zip.open, "test.txt", pwd="python")
1021 self.assertRaises(TypeError, self.zip.extract, "test.txt", pwd="python")
1022
Guido van Rossumd8faa362007-04-27 19:54:29 +00001023
1024class TestsWithRandomBinaryFiles(unittest.TestCase):
1025 def setUp(self):
1026 datacount = randint(16, 64)*1024 + randint(1, 1024)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001027 self.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
1028 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001029
1030 # Make a source file with some lines
1031 fp = open(TESTFN, "wb")
1032 fp.write(self.data)
1033 fp.close()
1034
1035 def tearDown(self):
1036 support.unlink(TESTFN)
1037 support.unlink(TESTFN2)
1038
1039 def makeTestArchive(self, f, compression):
1040 # Create the ZIP archive
1041 zipfp = zipfile.ZipFile(f, "w", compression)
Skip Montanaro7a98be22007-08-16 14:35:24 +00001042 zipfp.write(TESTFN, "another.name")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001043 zipfp.write(TESTFN, TESTFN)
1044 zipfp.close()
1045
1046 def zipTest(self, f, compression):
1047 self.makeTestArchive(f, compression)
1048
1049 # Read the ZIP archive
1050 zipfp = zipfile.ZipFile(f, "r", compression)
1051 testdata = zipfp.read(TESTFN)
1052 self.assertEqual(len(testdata), len(self.data))
1053 self.assertEqual(testdata, self.data)
Skip Montanaro7a98be22007-08-16 14:35:24 +00001054 self.assertEqual(zipfp.read("another.name"), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001055 zipfp.close()
1056
1057 def testStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001058 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001059 self.zipTest(f, zipfile.ZIP_STORED)
1060
1061 def zipOpenTest(self, f, compression):
1062 self.makeTestArchive(f, compression)
1063
1064 # Read the ZIP archive
1065 zipfp = zipfile.ZipFile(f, "r", compression)
1066 zipdata1 = []
1067 zipopen1 = zipfp.open(TESTFN)
1068 while 1:
1069 read_data = zipopen1.read(256)
1070 if not read_data:
1071 break
1072 zipdata1.append(read_data)
1073
1074 zipdata2 = []
Skip Montanaro7a98be22007-08-16 14:35:24 +00001075 zipopen2 = zipfp.open("another.name")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001076 while 1:
1077 read_data = zipopen2.read(256)
1078 if not read_data:
1079 break
1080 zipdata2.append(read_data)
1081
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001082 testdata1 = b''.join(zipdata1)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001083 self.assertEqual(len(testdata1), len(self.data))
1084 self.assertEqual(testdata1, self.data)
1085
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001086 testdata2 = b''.join(zipdata2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001087 self.assertEqual(len(testdata1), len(self.data))
1088 self.assertEqual(testdata1, self.data)
1089 zipfp.close()
1090
1091 def testOpenStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001092 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001093 self.zipOpenTest(f, zipfile.ZIP_STORED)
1094
1095 def zipRandomOpenTest(self, f, compression):
1096 self.makeTestArchive(f, compression)
1097
1098 # Read the ZIP archive
1099 zipfp = zipfile.ZipFile(f, "r", compression)
1100 zipdata1 = []
1101 zipopen1 = zipfp.open(TESTFN)
1102 while 1:
1103 read_data = zipopen1.read(randint(1, 1024))
1104 if not read_data:
1105 break
1106 zipdata1.append(read_data)
1107
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001108 testdata = b''.join(zipdata1)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001109 self.assertEqual(len(testdata), len(self.data))
1110 self.assertEqual(testdata, self.data)
1111 zipfp.close()
1112
1113 def testRandomOpenStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001114 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001115 self.zipRandomOpenTest(f, zipfile.ZIP_STORED)
1116
1117class TestsWithMultipleOpens(unittest.TestCase):
1118 def setUp(self):
1119 # Create the ZIP archive
1120 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED)
1121 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
1122 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
1123 zipfp.close()
1124
1125 def testSameFile(self):
1126 # Verify that (when the ZipFile is in control of creating file objects)
1127 # multiple open() calls can be made without interfering with each other.
1128 zipf = zipfile.ZipFile(TESTFN2, mode="r")
1129 zopen1 = zipf.open('ones')
1130 zopen2 = zipf.open('ones')
1131 data1 = zopen1.read(500)
1132 data2 = zopen2.read(500)
1133 data1 += zopen1.read(500)
1134 data2 += zopen2.read(500)
1135 self.assertEqual(data1, data2)
1136 zipf.close()
1137
1138 def testDifferentFile(self):
1139 # Verify that (when the ZipFile is in control of creating file objects)
1140 # multiple open() calls can be made without interfering with each other.
1141 zipf = zipfile.ZipFile(TESTFN2, mode="r")
1142 zopen1 = zipf.open('ones')
1143 zopen2 = zipf.open('twos')
1144 data1 = zopen1.read(500)
1145 data2 = zopen2.read(500)
1146 data1 += zopen1.read(500)
1147 data2 += zopen2.read(500)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001148 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
1149 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001150 zipf.close()
1151
1152 def testInterleaved(self):
1153 # Verify that (when the ZipFile is in control of creating file objects)
1154 # multiple open() calls can be made without interfering with each other.
1155 zipf = zipfile.ZipFile(TESTFN2, mode="r")
1156 zopen1 = zipf.open('ones')
1157 data1 = zopen1.read(500)
1158 zopen2 = zipf.open('twos')
1159 data2 = zopen2.read(500)
1160 data1 += zopen1.read(500)
1161 data2 += zopen2.read(500)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001162 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
1163 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001164 zipf.close()
1165
1166 def tearDown(self):
1167 os.remove(TESTFN2)
1168
Martin v. Löwis59e47792009-01-24 14:10:07 +00001169class TestWithDirectory(unittest.TestCase):
1170 def setUp(self):
1171 os.mkdir(TESTFN2)
1172
1173 def testExtractDir(self):
1174 zipf = zipfile.ZipFile(findfile("zipdir.zip"))
1175 zipf.extractall(TESTFN2)
1176 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1177 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1178 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1179
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001180 def test_bug_6050(self):
1181 # Extraction should succeed if directories already exist
1182 os.mkdir(os.path.join(TESTFN2, "a"))
1183 self.testExtractDir()
1184
Martin v. Löwis59e47792009-01-24 14:10:07 +00001185 def testStoreDir(self):
1186 os.mkdir(os.path.join(TESTFN2, "x"))
1187 zipf = zipfile.ZipFile(TESTFN, "w")
1188 zipf.write(os.path.join(TESTFN2, "x"), "x")
1189 self.assertTrue(zipf.filelist[0].filename.endswith("x/"))
1190
1191 def tearDown(self):
1192 shutil.rmtree(TESTFN2)
1193 if os.path.exists(TESTFN):
1194 os.remove(TESTFN)
1195
Guido van Rossumd8faa362007-04-27 19:54:29 +00001196
1197class UniversalNewlineTests(unittest.TestCase):
1198 def setUp(self):
Guido van Rossum9c627722007-08-27 18:31:48 +00001199 self.line_gen = [bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001200 for i in range(FIXEDTEST_SIZE)]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001201 self.seps = ('\r', '\r\n', '\n')
1202 self.arcdata, self.arcfiles = {}, {}
1203 for n, s in enumerate(self.seps):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001204 b = s.encode("ascii")
1205 self.arcdata[s] = b.join(self.line_gen) + b
Guido van Rossumd8faa362007-04-27 19:54:29 +00001206 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001207 f = open(self.arcfiles[s], "wb")
1208 try:
1209 f.write(self.arcdata[s])
1210 finally:
1211 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001212
1213 def makeTestArchive(self, f, compression):
1214 # Create the ZIP archive
1215 zipfp = zipfile.ZipFile(f, "w", compression)
1216 for fn in self.arcfiles.values():
1217 zipfp.write(fn, fn)
1218 zipfp.close()
1219
1220 def readTest(self, f, compression):
1221 self.makeTestArchive(f, compression)
1222
1223 # Read the ZIP archive
1224 zipfp = zipfile.ZipFile(f, "r")
1225 for sep, fn in self.arcfiles.items():
1226 zipdata = zipfp.open(fn, "rU").read()
1227 self.assertEqual(self.arcdata[sep], zipdata)
1228
1229 zipfp.close()
1230
1231 def readlineTest(self, f, compression):
1232 self.makeTestArchive(f, compression)
1233
1234 # Read the ZIP archive
1235 zipfp = zipfile.ZipFile(f, "r")
1236 for sep, fn in self.arcfiles.items():
1237 zipopen = zipfp.open(fn, "rU")
1238 for line in self.line_gen:
1239 linedata = zipopen.readline()
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001240 self.assertEqual(linedata, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001241
1242 zipfp.close()
1243
1244 def readlinesTest(self, f, compression):
1245 self.makeTestArchive(f, compression)
1246
1247 # Read the ZIP archive
1248 zipfp = zipfile.ZipFile(f, "r")
1249 for sep, fn in self.arcfiles.items():
1250 ziplines = zipfp.open(fn, "rU").readlines()
1251 for line, zipline in zip(self.line_gen, ziplines):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001252 self.assertEqual(zipline, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001253
1254 zipfp.close()
1255
1256 def iterlinesTest(self, f, compression):
1257 self.makeTestArchive(f, compression)
1258
1259 # Read the ZIP archive
1260 zipfp = zipfile.ZipFile(f, "r")
1261 for sep, fn in self.arcfiles.items():
1262 for line, zipline in zip(self.line_gen, zipfp.open(fn, "rU")):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001263 self.assertEqual(zipline, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001264
1265 zipfp.close()
1266
1267 def testReadStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001268 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001269 self.readTest(f, zipfile.ZIP_STORED)
1270
1271 def testReadlineStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001272 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001273 self.readlineTest(f, zipfile.ZIP_STORED)
1274
1275 def testReadlinesStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001276 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001277 self.readlinesTest(f, zipfile.ZIP_STORED)
1278
1279 def testIterlinesStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001280 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001281 self.iterlinesTest(f, zipfile.ZIP_STORED)
1282
1283 if zlib:
1284 def testReadDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001285 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001286 self.readTest(f, zipfile.ZIP_DEFLATED)
1287
1288 def testReadlineDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001289 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001290 self.readlineTest(f, zipfile.ZIP_DEFLATED)
1291
1292 def testReadlinesDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001293 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001294 self.readlinesTest(f, zipfile.ZIP_DEFLATED)
1295
1296 def testIterlinesDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001297 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001298 self.iterlinesTest(f, zipfile.ZIP_DEFLATED)
1299
1300 def tearDown(self):
1301 for sep, fn in self.arcfiles.items():
1302 os.remove(fn)
1303 support.unlink(TESTFN)
1304 support.unlink(TESTFN2)
1305
1306
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001307def test_main():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001308 run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
1309 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
Martin v. Löwis59e47792009-01-24 14:10:07 +00001310 TestWithDirectory,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001311 UniversalNewlineTests, TestsWithRandomBinaryFiles)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001312
1313if __name__ == "__main__":
1314 test_main()