blob: 3b04ce2ecfa527b0f1a89c6435cf6210fc0f097b [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
Guido van Rossumd6ca5462007-05-22 01:29:33 +00006import zipfile, os, unittest, sys, shutil, struct, io
Tim Petersa45cacf2004-08-20 03:47:14 +00007
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00008from tempfile import TemporaryFile
Guido van Rossumd8faa362007-04-27 19:54:29 +00009from random import randint, random
Tim Petersa19a1682001-03-29 04:36:09 +000010
Benjamin Petersonee8712c2008-05-20 21:35:26 +000011import test.support as support
Martin v. Löwis59e47792009-01-24 14:10:07 +000012from test.support import TESTFN, run_unittest, findfile
Guido van Rossum368f04a2000-04-10 13:23:04 +000013
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000014TESTFN2 = TESTFN + "2"
Martin v. Löwis59e47792009-01-24 14:10:07 +000015TESTFNDIR = TESTFN + "d"
Guido van Rossumb5a755e2007-07-18 18:15:48 +000016FIXEDTEST_SIZE = 1000
Guido van Rossum368f04a2000-04-10 13:23:04 +000017
Christian Heimes790c8232008-01-07 21:14:23 +000018SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'),
19 ('ziptest2dir/_ziptest2', 'qawsedrftg'),
20 ('/ziptest2dir/ziptest3dir/_ziptest3', 'azsxdcfvgb'),
21 ('ziptest2dir/ziptest3dir/ziptest4dir/_ziptest3', '6y7u8i9o0p')]
22
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000023class TestsWithSourceFile(unittest.TestCase):
24 def setUp(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +000025 self.line_gen = (bytes("Zipfile test line %d. random float: %f" %
Guido van Rossum9c627722007-08-27 18:31:48 +000026 (i, random()), "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +000027 for i in range(FIXEDTEST_SIZE))
28 self.data = b'\n'.join(self.line_gen) + b'\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
Guido van Rossumd8faa362007-04-27 19:54:29 +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)
Skip Montanaro7a98be22007-08-16 14:35:24 +000038 zipfp.write(TESTFN, "another.name")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000039 zipfp.write(TESTFN, TESTFN)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000040 zipfp.writestr("strfile", self.data)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000041 zipfp.close()
Tim Peters7d3bad62001-04-04 18:56:49 +000042
Guido van Rossumd8faa362007-04-27 19:54:29 +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)
Skip Montanaro7a98be22007-08-16 14:35:24 +000049 self.assertEqual(zipfp.read("another.name"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000050 self.assertEqual(zipfp.read("strfile"), self.data)
51
52 # Print the ZIP directory
Guido van Rossumd6ca5462007-05-22 01:29:33 +000053 fp = io.StringIO()
54 zipfp.printdir(file=fp)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000055
56 directory = fp.getvalue()
57 lines = directory.splitlines()
58 self.assertEquals(len(lines), 4) # Number of files + header
59
60 self.assert_('File Name' in lines[0])
61 self.assert_('Modified' in lines[0])
62 self.assert_('Size' in lines[0])
63
64 fn, date, time, size = lines[1].split()
65 self.assertEquals(fn, 'another.name')
66 # XXX: timestamp is not tested
67 self.assertEquals(size, str(len(self.data)))
68
69 # Check the namelist
70 names = zipfp.namelist()
71 self.assertEquals(len(names), 3)
72 self.assert_(TESTFN in names)
Skip Montanaro7a98be22007-08-16 14:35:24 +000073 self.assert_("another.name" in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000074 self.assert_("strfile" in names)
75
76 # Check infolist
77 infos = zipfp.infolist()
78 names = [ i.filename for i in infos ]
79 self.assertEquals(len(names), 3)
80 self.assert_(TESTFN in names)
Skip Montanaro7a98be22007-08-16 14:35:24 +000081 self.assert_("another.name" in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000082 self.assert_("strfile" in names)
83 for i in infos:
84 self.assertEquals(i.file_size, len(self.data))
85
86 # check getinfo
Skip Montanaro7a98be22007-08-16 14:35:24 +000087 for nm in (TESTFN, "another.name", "strfile"):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000088 info = zipfp.getinfo(nm)
89 self.assertEquals(info.filename, nm)
90 self.assertEquals(info.file_size, len(self.data))
91
92 # Check that testzip doesn't raise an exception
93 zipfp.testzip()
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000094 zipfp.close()
Tim Peters7d3bad62001-04-04 18:56:49 +000095
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000096 def testStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +000097 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000098 self.zipTest(f, zipfile.ZIP_STORED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +000099
Guido van Rossumd8faa362007-04-27 19:54:29 +0000100 def zipOpenTest(self, f, compression):
101 self.makeTestArchive(f, compression)
102
103 # Read the ZIP archive
104 zipfp = zipfile.ZipFile(f, "r", compression)
105 zipdata1 = []
106 zipopen1 = zipfp.open(TESTFN)
107 while 1:
108 read_data = zipopen1.read(256)
109 if not read_data:
110 break
111 zipdata1.append(read_data)
112
113 zipdata2 = []
Skip Montanaro7a98be22007-08-16 14:35:24 +0000114 zipopen2 = zipfp.open("another.name")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000115 while 1:
116 read_data = zipopen2.read(256)
117 if not read_data:
118 break
119 zipdata2.append(read_data)
120
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000121 self.assertEqual(b''.join(zipdata1), self.data)
122 self.assertEqual(b''.join(zipdata2), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000123 zipfp.close()
124
125 def testOpenStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000126 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000127 self.zipOpenTest(f, zipfile.ZIP_STORED)
128
Georg Brandlb533e262008-05-25 18:19:30 +0000129 def testOpenViaZipInfo(self):
130 # Create the ZIP archive
131 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
132 zipfp.writestr("name", "foo")
133 zipfp.writestr("name", "bar")
134 zipfp.close()
135
136 zipfp = zipfile.ZipFile(TESTFN2, "r")
137 infos = zipfp.infolist()
138 data = b""
139 for info in infos:
140 data += zipfp.open(info).read()
141 self.assert_(data == b"foobar" or data == b"barfoo")
142 data = b""
143 for info in infos:
144 data += zipfp.read(info)
145 self.assert_(data == b"foobar" or data == b"barfoo")
146 zipfp.close()
147
Guido van Rossumd8faa362007-04-27 19:54:29 +0000148 def zipRandomOpenTest(self, f, compression):
149 self.makeTestArchive(f, compression)
150
151 # Read the ZIP archive
152 zipfp = zipfile.ZipFile(f, "r", compression)
153 zipdata1 = []
154 zipopen1 = zipfp.open(TESTFN)
155 while 1:
156 read_data = zipopen1.read(randint(1, 1024))
157 if not read_data:
158 break
159 zipdata1.append(read_data)
160
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000161 self.assertEqual(b''.join(zipdata1), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000162 zipfp.close()
163
164 def testRandomOpenStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000165 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000166 self.zipRandomOpenTest(f, zipfile.ZIP_STORED)
167
168 def zipReadlineTest(self, f, compression):
169 self.makeTestArchive(f, compression)
170
171 # Read the ZIP archive
172 zipfp = zipfile.ZipFile(f, "r")
173 zipopen = zipfp.open(TESTFN)
174 for line in self.line_gen:
175 linedata = zipopen.readline()
176 self.assertEqual(linedata, line + '\n')
177
178 zipfp.close()
179
180 def zipReadlinesTest(self, f, compression):
181 self.makeTestArchive(f, compression)
182
183 # Read the ZIP archive
184 zipfp = zipfile.ZipFile(f, "r")
185 ziplines = zipfp.open(TESTFN).readlines()
186 for line, zipline in zip(self.line_gen, ziplines):
187 self.assertEqual(zipline, line + '\n')
188
189 zipfp.close()
190
191 def zipIterlinesTest(self, f, compression):
192 self.makeTestArchive(f, compression)
193
194 # Read the ZIP archive
195 zipfp = zipfile.ZipFile(f, "r")
196 for line, zipline in zip(self.line_gen, zipfp.open(TESTFN)):
197 self.assertEqual(zipline, line + '\n')
198
199 zipfp.close()
200
201 def testReadlineStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000202 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000203 self.zipReadlineTest(f, zipfile.ZIP_STORED)
204
205 def testReadlinesStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000206 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000207 self.zipReadlinesTest(f, zipfile.ZIP_STORED)
208
209 def testIterlinesStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000210 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000211 self.zipIterlinesTest(f, zipfile.ZIP_STORED)
212
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000213 if zlib:
214 def testDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000215 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000216 self.zipTest(f, zipfile.ZIP_DEFLATED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000217
Guido van Rossumd8faa362007-04-27 19:54:29 +0000218 def testOpenDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000219 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000220 self.zipOpenTest(f, zipfile.ZIP_DEFLATED)
221
222 def testRandomOpenDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000223 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000224 self.zipRandomOpenTest(f, zipfile.ZIP_DEFLATED)
225
226 def testReadlineDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000227 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000228 self.zipReadlineTest(f, zipfile.ZIP_DEFLATED)
229
230 def testReadlinesDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000231 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000232 self.zipReadlinesTest(f, zipfile.ZIP_DEFLATED)
233
234 def testIterlinesDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000235 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000236 self.zipIterlinesTest(f, zipfile.ZIP_DEFLATED)
237
238 def testLowCompression(self):
239 # Checks for cases where compressed data is larger than original
240 # Create the ZIP archive
241 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED)
242 zipfp.writestr("strfile", '12')
243 zipfp.close()
244
245 # Get an open object for strfile
246 zipfp = zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_DEFLATED)
247 openobj = zipfp.open("strfile")
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000248 self.assertEqual(openobj.read(1), b'1')
249 self.assertEqual(openobj.read(1), b'2')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000250
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000251 def testAbsoluteArcnames(self):
252 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
253 zipfp.write(TESTFN, "/absolute")
254 zipfp.close()
255
256 zipfp = zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED)
257 self.assertEqual(zipfp.namelist(), ["absolute"])
258 zipfp.close()
Tim Peters32cbc962006-02-20 21:42:18 +0000259
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000260 def testAppendToZipFile(self):
261 # Test appending to an existing zipfile
262 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
263 zipfp.write(TESTFN, TESTFN)
264 zipfp.close()
265 zipfp = zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED)
266 zipfp.writestr("strfile", self.data)
267 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
268 zipfp.close()
269
270 def testAppendToNonZipFile(self):
271 # Test appending to an existing file that is not a zipfile
272 # NOTE: this test fails if len(d) < 22 because of the first
273 # line "fpin.seek(-22, 2)" in _EndRecData
Guido van Rossum9c627722007-08-27 18:31:48 +0000274 d = b'I am not a ZipFile!'*10
Guido van Rossum814661e2007-07-18 22:07:29 +0000275 f = open(TESTFN2, 'wb')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000276 f.write(d)
277 f.close()
278 zipfp = zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED)
279 zipfp.write(TESTFN, TESTFN)
280 zipfp.close()
281
Guido van Rossum814661e2007-07-18 22:07:29 +0000282 f = open(TESTFN2, 'rb')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000283 f.seek(len(d))
284 zipfp = zipfile.ZipFile(f, "r")
285 self.assertEqual(zipfp.namelist(), [TESTFN])
286 zipfp.close()
287 f.close()
288
289 def test_WriteDefaultName(self):
290 # Check that calling ZipFile.write without arcname specified produces the expected result
291 zipfp = zipfile.ZipFile(TESTFN2, "w")
292 zipfp.write(TESTFN)
Guido van Rossum814661e2007-07-18 22:07:29 +0000293 self.assertEqual(zipfp.read(TESTFN), open(TESTFN, "rb").read())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000294 zipfp.close()
295
296 def test_PerFileCompression(self):
297 # Check that files within a Zip archive can have different compression options
298 zipfp = zipfile.ZipFile(TESTFN2, "w")
299 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
300 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
301 sinfo = zipfp.getinfo('storeme')
302 dinfo = zipfp.getinfo('deflateme')
303 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
304 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
305 zipfp.close()
306
307 def test_WriteToReadonly(self):
308 # Check that trying to call write() on a readonly ZipFile object
309 # raises a RuntimeError
310 zipf = zipfile.ZipFile(TESTFN2, mode="w")
311 zipf.writestr("somefile.txt", "bogus")
312 zipf.close()
313 zipf = zipfile.ZipFile(TESTFN2, mode="r")
314 self.assertRaises(RuntimeError, zipf.write, TESTFN)
315 zipf.close()
316
Christian Heimes790c8232008-01-07 21:14:23 +0000317 def testExtract(self):
318 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
319 for fpath, fdata in SMALL_TEST_DATA:
320 zipfp.writestr(fpath, fdata)
321 zipfp.close()
322
323 zipfp = zipfile.ZipFile(TESTFN2, "r")
324 for fpath, fdata in SMALL_TEST_DATA:
325 writtenfile = zipfp.extract(fpath)
326
327 # make sure it was written to the right place
328 if os.path.isabs(fpath):
329 correctfile = os.path.join(os.getcwd(), fpath[1:])
330 else:
331 correctfile = os.path.join(os.getcwd(), fpath)
Christian Heimesaf98da12008-01-27 15:18:18 +0000332 correctfile = os.path.normpath(correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000333
334 self.assertEqual(writtenfile, correctfile)
335
336 # make sure correct data is in correct file
337 self.assertEqual(fdata.encode(), open(writtenfile, "rb").read())
338
339 os.remove(writtenfile)
340
341 zipfp.close()
342
343 # remove the test file subdirectories
344 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
345
346 def testExtractAll(self):
347 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
348 for fpath, fdata in SMALL_TEST_DATA:
349 zipfp.writestr(fpath, fdata)
350 zipfp.close()
351
352 zipfp = zipfile.ZipFile(TESTFN2, "r")
353 zipfp.extractall()
354 for fpath, fdata in SMALL_TEST_DATA:
355 if os.path.isabs(fpath):
356 outfile = os.path.join(os.getcwd(), fpath[1:])
357 else:
358 outfile = os.path.join(os.getcwd(), fpath)
359
360 self.assertEqual(fdata.encode(), open(outfile, "rb").read())
361
362 os.remove(outfile)
363
364 zipfp.close()
365
366 # remove the test file subdirectories
367 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
368
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000369 def zip_test_writestr_permissions(self, f, compression):
370 # Make sure that writestr creates files with mode 0600,
371 # when it is passed a name rather than a ZipInfo instance.
372
373 self.makeTestArchive(f, compression)
374 zipfp = zipfile.ZipFile(f, "r")
375 zinfo = zipfp.getinfo('strfile')
376 self.assertEqual(zinfo.external_attr, 0o600 << 16)
377
378 def test_writestr_permissions(self):
379 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
380 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
381
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000382 def tearDown(self):
383 os.remove(TESTFN)
384 os.remove(TESTFN2)
385
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000386class TestZip64InSmallFiles(unittest.TestCase):
387 # These tests test the ZIP64 functionality without using large files,
388 # see test_zipfile64 for proper tests.
389
390 def setUp(self):
391 self._limit = zipfile.ZIP64_LIMIT
392 zipfile.ZIP64_LIMIT = 5
393
Guido van Rossum9c627722007-08-27 18:31:48 +0000394 line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000395 for i in range(0, FIXEDTEST_SIZE))
396 self.data = b'\n'.join(line_gen)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000397
398 # Make a source file with some lines
399 fp = open(TESTFN, "wb")
400 fp.write(self.data)
401 fp.close()
402
403 def largeFileExceptionTest(self, f, compression):
404 zipfp = zipfile.ZipFile(f, "w", compression)
405 self.assertRaises(zipfile.LargeZipFile,
Skip Montanaro7a98be22007-08-16 14:35:24 +0000406 zipfp.write, TESTFN, "another.name")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000407 zipfp.close()
408
409 def largeFileExceptionTest2(self, f, compression):
410 zipfp = zipfile.ZipFile(f, "w", compression)
411 self.assertRaises(zipfile.LargeZipFile,
Skip Montanaro7a98be22007-08-16 14:35:24 +0000412 zipfp.writestr, "another.name", self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000413 zipfp.close()
414
415 def testLargeFileException(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000416 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000417 self.largeFileExceptionTest(f, zipfile.ZIP_STORED)
418 self.largeFileExceptionTest2(f, zipfile.ZIP_STORED)
419
420 def zipTest(self, f, compression):
421 # Create the ZIP archive
422 zipfp = zipfile.ZipFile(f, "w", compression, allowZip64=True)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000423 zipfp.write(TESTFN, "another.name")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000424 zipfp.write(TESTFN, TESTFN)
425 zipfp.writestr("strfile", self.data)
426 zipfp.close()
427
428 # Read the ZIP archive
429 zipfp = zipfile.ZipFile(f, "r", compression)
430 self.assertEqual(zipfp.read(TESTFN), self.data)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000431 self.assertEqual(zipfp.read("another.name"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000432 self.assertEqual(zipfp.read("strfile"), self.data)
433
434 # Print the ZIP directory
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000435 fp = io.StringIO()
436 zipfp.printdir(fp)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000437
438 directory = fp.getvalue()
439 lines = directory.splitlines()
440 self.assertEquals(len(lines), 4) # Number of files + header
441
442 self.assert_('File Name' in lines[0])
443 self.assert_('Modified' in lines[0])
444 self.assert_('Size' in lines[0])
445
446 fn, date, time, size = lines[1].split()
447 self.assertEquals(fn, 'another.name')
448 # XXX: timestamp is not tested
449 self.assertEquals(size, str(len(self.data)))
450
451 # Check the namelist
452 names = zipfp.namelist()
453 self.assertEquals(len(names), 3)
454 self.assert_(TESTFN in names)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000455 self.assert_("another.name" in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000456 self.assert_("strfile" in names)
457
458 # Check infolist
459 infos = zipfp.infolist()
460 names = [ i.filename for i in infos ]
461 self.assertEquals(len(names), 3)
462 self.assert_(TESTFN in names)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000463 self.assert_("another.name" in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000464 self.assert_("strfile" in names)
465 for i in infos:
466 self.assertEquals(i.file_size, len(self.data))
467
468 # check getinfo
Skip Montanaro7a98be22007-08-16 14:35:24 +0000469 for nm in (TESTFN, "another.name", "strfile"):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000470 info = zipfp.getinfo(nm)
471 self.assertEquals(info.filename, nm)
472 self.assertEquals(info.file_size, len(self.data))
473
474 # Check that testzip doesn't raise an exception
475 zipfp.testzip()
476
477
478 zipfp.close()
479
480 def testStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000481 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000482 self.zipTest(f, zipfile.ZIP_STORED)
483
484
485 if zlib:
486 def testDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000487 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000488 self.zipTest(f, zipfile.ZIP_DEFLATED)
489
490 def testAbsoluteArcnames(self):
491 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED, allowZip64=True)
492 zipfp.write(TESTFN, "/absolute")
493 zipfp.close()
494
495 zipfp = zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED)
496 self.assertEqual(zipfp.namelist(), ["absolute"])
497 zipfp.close()
498
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000499 def tearDown(self):
500 zipfile.ZIP64_LIMIT = self._limit
501 os.remove(TESTFN)
502 os.remove(TESTFN2)
503
504class PyZipFileTests(unittest.TestCase):
505 def testWritePyfile(self):
506 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
507 fn = __file__
508 if fn.endswith('.pyc') or fn.endswith('.pyo'):
509 fn = fn[:-1]
510
511 zipfp.writepy(fn)
512
513 bn = os.path.basename(fn)
514 self.assert_(bn not in zipfp.namelist())
515 self.assert_(bn + 'o' in zipfp.namelist() or bn + 'c' in zipfp.namelist())
516 zipfp.close()
517
518
519 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
520 fn = __file__
521 if fn.endswith('.pyc') or fn.endswith('.pyo'):
522 fn = fn[:-1]
523
524 zipfp.writepy(fn, "testpackage")
525
526 bn = "%s/%s"%("testpackage", os.path.basename(fn))
527 self.assert_(bn not in zipfp.namelist())
528 self.assert_(bn + 'o' in zipfp.namelist() or bn + 'c' in zipfp.namelist())
529 zipfp.close()
530
531 def testWritePythonPackage(self):
532 import email
533 packagedir = os.path.dirname(email.__file__)
534
535 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
536 zipfp.writepy(packagedir)
537
538 # Check for a couple of modules at different levels of the hieararchy
539 names = zipfp.namelist()
540 self.assert_('email/__init__.pyo' in names or 'email/__init__.pyc' in names)
541 self.assert_('email/mime/text.pyo' in names or 'email/mime/text.pyc' in names)
542
543 def testWritePythonDirectory(self):
544 os.mkdir(TESTFN2)
545 try:
546 fp = open(os.path.join(TESTFN2, "mod1.py"), "w")
Guido van Rossum43fc78d2007-02-09 22:18:41 +0000547 fp.write("print(42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000548 fp.close()
549
550 fp = open(os.path.join(TESTFN2, "mod2.py"), "w")
Guido van Rossum43fc78d2007-02-09 22:18:41 +0000551 fp.write("print(42 * 42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000552 fp.close()
553
554 fp = open(os.path.join(TESTFN2, "mod2.txt"), "w")
555 fp.write("bla bla bla\n")
556 fp.close()
557
558 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
559 zipfp.writepy(TESTFN2)
560
561 names = zipfp.namelist()
562 self.assert_('mod1.pyc' in names or 'mod1.pyo' in names)
563 self.assert_('mod2.pyc' in names or 'mod2.pyo' in names)
564 self.assert_('mod2.txt' not in names)
565
566 finally:
567 shutil.rmtree(TESTFN2)
568
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000569 def testWriteNonPyfile(self):
570 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
Guido van Rossum814661e2007-07-18 22:07:29 +0000571 open(TESTFN, 'w').write('most definitely not a python file')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000572 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
573 os.remove(TESTFN)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000574
575
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000576class OtherTests(unittest.TestCase):
Martin v. Löwis8570f6a2008-05-05 17:44:38 +0000577 def testUnicodeFilenames(self):
578 zf = zipfile.ZipFile(TESTFN, "w")
579 zf.writestr("foo.txt", "Test for unicode filename")
Martin v. Löwis1a9f9002008-05-05 17:50:05 +0000580 zf.writestr("\xf6.txt", "Test for unicode filename")
Martin v. Löwis8570f6a2008-05-05 17:44:38 +0000581 zf.close()
Martin v. Löwis1a9f9002008-05-05 17:50:05 +0000582 zf = zipfile.ZipFile(TESTFN, "r")
583 self.assertEqual(zf.filelist[0].filename, "foo.txt")
584 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
585 zf.close()
Martin v. Löwis8570f6a2008-05-05 17:44:38 +0000586
Thomas Wouterscf297e42007-02-23 15:07:44 +0000587 def testCreateNonExistentFileForAppend(self):
588 if os.path.exists(TESTFN):
589 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000590
Thomas Wouterscf297e42007-02-23 15:07:44 +0000591 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000592 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +0000593
Thomas Wouterscf297e42007-02-23 15:07:44 +0000594 try:
595 zf = zipfile.ZipFile(TESTFN, 'a')
596 zf.writestr(filename, content)
597 zf.close()
598 except IOError:
599 self.fail('Could not append data to a non-existent zip file.')
600
601 self.assert_(os.path.exists(TESTFN))
602
603 zf = zipfile.ZipFile(TESTFN, 'r')
604 self.assertEqual(zf.read(filename), content)
605 zf.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000606
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000607 def testCloseErroneousFile(self):
608 # This test checks that the ZipFile constructor closes the file object
609 # it opens if there's an error in the file. If it doesn't, the traceback
610 # holds a reference to the ZipFile object and, indirectly, the file object.
611 # On Windows, this causes the os.unlink() call to fail because the
612 # underlying file is still open. This is SF bug #412214.
613 #
614 fp = open(TESTFN, "w")
615 fp.write("this is not a legal zip file\n")
616 fp.close()
617 try:
618 zf = zipfile.ZipFile(TESTFN)
619 except zipfile.BadZipfile:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000620 pass
621
622 def testIsZipErroneousFile(self):
623 # This test checks that the is_zipfile function correctly identifies
624 # a file that is not a zip file
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000625
626 # - passing a filename
627 with open(TESTFN, "w") as fp:
628 fp.write("this is not a legal zip file\n")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000629 chk = zipfile.is_zipfile(TESTFN)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000630 self.assert_(not chk)
631 # - passing a file object
632 with open(TESTFN, "rb") as fp:
633 chk = zipfile.is_zipfile(fp)
634 self.assert_(not chk)
635 # - passing a file-like object
636 fp = io.BytesIO()
637 fp.write(b"this is not a legal zip file\n")
638 chk = zipfile.is_zipfile(fp)
639 self.assert_(not chk)
640 fp.seek(0,0)
641 chk = zipfile.is_zipfile(fp)
642 self.assert_(not chk)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000643
644 def testIsZipValidFile(self):
645 # This test checks that the is_zipfile function correctly identifies
646 # a file that is a zip file
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000647
648 # - passing a filename
Guido van Rossumd8faa362007-04-27 19:54:29 +0000649 zipf = zipfile.ZipFile(TESTFN, mode="w")
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000650 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000651 zipf.close()
652 chk = zipfile.is_zipfile(TESTFN)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000653 self.assert_(chk)
654 # - passing a file object
655 with open(TESTFN, "rb") as fp:
656 chk = zipfile.is_zipfile(fp)
657 self.assert_(chk)
658 fp.seek(0,0)
659 zip_contents = fp.read()
660 # - passing a file-like object
661 fp = io.BytesIO()
662 fp.write(zip_contents)
663 chk = zipfile.is_zipfile(fp)
664 self.assert_(chk)
665 fp.seek(0,0)
666 chk = zipfile.is_zipfile(fp)
667 self.assert_(chk)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000668
669 def testNonExistentFileRaisesIOError(self):
670 # make sure we don't raise an AttributeError when a partially-constructed
671 # ZipFile instance is finalized; this tests for regression on SF tracker
672 # bug #403871.
673
674 # The bug we're testing for caused an AttributeError to be raised
675 # when a ZipFile instance was created for a file that did not
676 # exist; the .fp member was not initialized but was needed by the
677 # __del__() method. Since the AttributeError is in the __del__(),
678 # it is ignored, but the user should be sufficiently annoyed by
679 # the message on the output that regression will be noticed
680 # quickly.
681 self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
682
683 def testClosedZipRaisesRuntimeError(self):
684 # Verify that testzip() doesn't swallow inappropriate exceptions.
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000685 data = io.BytesIO()
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000686 zipf = zipfile.ZipFile(data, mode="w")
687 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
688 zipf.close()
689
690 # This is correct; calling .read on a closed ZipFile should throw
691 # a RuntimeError, and so should calling .testzip. An earlier
692 # version of .testzip would swallow this exception (and any other)
693 # and report that the first file in the archive was corrupt.
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000694 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
695 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000696 self.assertRaises(RuntimeError, zipf.testzip)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000697 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Guido van Rossum814661e2007-07-18 22:07:29 +0000698 open(TESTFN, 'w').write('zipfile test data')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000699 self.assertRaises(RuntimeError, zipf.write, TESTFN)
700
701 def test_BadConstructorMode(self):
702 # Check that bad modes passed to ZipFile constructor are caught
703 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
704
705 def test_BadOpenMode(self):
706 # Check that bad modes passed to ZipFile.open are caught
707 zipf = zipfile.ZipFile(TESTFN, mode="w")
708 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
709 zipf.close()
710 zipf = zipfile.ZipFile(TESTFN, mode="r")
711 # read the data to make sure the file is there
712 zipf.read("foo.txt")
713 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
714 zipf.close()
715
716 def test_Read0(self):
717 # Check that calling read(0) on a ZipExtFile object returns an empty
718 # string and doesn't advance file pointer
719 zipf = zipfile.ZipFile(TESTFN, mode="w")
720 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
721 # read the data to make sure the file is there
722 f = zipf.open("foo.txt")
723 for i in range(FIXEDTEST_SIZE):
Guido van Rossum814661e2007-07-18 22:07:29 +0000724 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000725
Guido van Rossum814661e2007-07-18 22:07:29 +0000726 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000727 zipf.close()
728
729 def test_OpenNonexistentItem(self):
730 # Check that attempting to call open() for an item that doesn't
731 # exist in the archive raises a RuntimeError
732 zipf = zipfile.ZipFile(TESTFN, mode="w")
733 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
734
735 def test_BadCompressionMode(self):
736 # Check that bad compression methods passed to ZipFile.open are caught
737 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
738
739 def test_NullByteInFilename(self):
740 # Check that a filename containing a null byte is properly terminated
741 zipf = zipfile.ZipFile(TESTFN, mode="w")
Guido van Rossum814661e2007-07-18 22:07:29 +0000742 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000743 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000744
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000745 def test_StructSizes(self):
746 # check that ZIP internal structure sizes are calculated correctly
747 self.assertEqual(zipfile.sizeEndCentDir, 22)
748 self.assertEqual(zipfile.sizeCentralDir, 46)
749 self.assertEqual(zipfile.sizeEndCentDir64, 56)
750 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
751
752 def testComments(self):
753 # This test checks that comments on the archive are handled properly
754
755 # check default comment is empty
756 zipf = zipfile.ZipFile(TESTFN, mode="w")
757 self.assertEqual(zipf.comment, b'')
758 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
759 zipf.close()
760 zipfr = zipfile.ZipFile(TESTFN, mode="r")
761 self.assertEqual(zipfr.comment, b'')
762 zipfr.close()
763
764 # check a simple short comment
765 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
766 zipf = zipfile.ZipFile(TESTFN, mode="w")
767 zipf.comment = comment
768 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
769 zipf.close()
770 zipfr = zipfile.ZipFile(TESTFN, mode="r")
771 self.assertEqual(zipfr.comment, comment)
772 zipfr.close()
773
774 # check a comment of max length
775 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
776 comment2 = comment2.encode("ascii")
777 zipf = zipfile.ZipFile(TESTFN, mode="w")
778 zipf.comment = comment2
779 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
780 zipf.close()
781 zipfr = zipfile.ZipFile(TESTFN, mode="r")
782 self.assertEqual(zipfr.comment, comment2)
783 zipfr.close()
784
785 # check a comment that is too long is truncated
786 zipf = zipfile.ZipFile(TESTFN, mode="w")
787 zipf.comment = comment2 + b'oops'
788 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
789 zipf.close()
790 zipfr = zipfile.ZipFile(TESTFN, mode="r")
791 self.assertEqual(zipfr.comment, comment2)
792 zipfr.close()
793
Guido van Rossumd8faa362007-04-27 19:54:29 +0000794 def tearDown(self):
795 support.unlink(TESTFN)
796 support.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000797
798class DecryptionTests(unittest.TestCase):
799 # This test checks that ZIP decryption works. Since the library does not
800 # support encryption at the moment, we use a pre-generated encrypted
801 # ZIP file
802
803 data = (
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000804 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
805 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
806 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
807 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
808 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
809 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
810 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +0000811 data2 = (
812 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
813 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
814 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
815 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
816 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
817 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
818 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
819 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +0000820
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000821 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +0000822 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +0000823
824 def setUp(self):
825 fp = open(TESTFN, "wb")
826 fp.write(self.data)
827 fp.close()
828 self.zip = zipfile.ZipFile(TESTFN, "r")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000829 fp = open(TESTFN2, "wb")
830 fp.write(self.data2)
831 fp.close()
832 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000833
834 def tearDown(self):
835 self.zip.close()
836 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +0000837 self.zip2.close()
838 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000839
840 def testNoPassword(self):
841 # Reading the encrypted file without password
842 # must generate a RunTime exception
843 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000844 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000845
846 def testBadPassword(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000847 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000848 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000849 self.zip2.setpassword(b"perl")
850 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000851
Thomas Wouterscf297e42007-02-23 15:07:44 +0000852 def testGoodPassword(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000853 self.zip.setpassword(b"python")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000854 self.assertEquals(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +0000855 self.zip2.setpassword(b"12345")
856 self.assertEquals(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000857
Guido van Rossumd8faa362007-04-27 19:54:29 +0000858
859class TestsWithRandomBinaryFiles(unittest.TestCase):
860 def setUp(self):
861 datacount = randint(16, 64)*1024 + randint(1, 1024)
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000862 self.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
863 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000864
865 # Make a source file with some lines
866 fp = open(TESTFN, "wb")
867 fp.write(self.data)
868 fp.close()
869
870 def tearDown(self):
871 support.unlink(TESTFN)
872 support.unlink(TESTFN2)
873
874 def makeTestArchive(self, f, compression):
875 # Create the ZIP archive
876 zipfp = zipfile.ZipFile(f, "w", compression)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000877 zipfp.write(TESTFN, "another.name")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000878 zipfp.write(TESTFN, TESTFN)
879 zipfp.close()
880
881 def zipTest(self, f, compression):
882 self.makeTestArchive(f, compression)
883
884 # Read the ZIP archive
885 zipfp = zipfile.ZipFile(f, "r", compression)
886 testdata = zipfp.read(TESTFN)
887 self.assertEqual(len(testdata), len(self.data))
888 self.assertEqual(testdata, self.data)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000889 self.assertEqual(zipfp.read("another.name"), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000890 zipfp.close()
891
892 def testStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000893 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000894 self.zipTest(f, zipfile.ZIP_STORED)
895
896 def zipOpenTest(self, f, compression):
897 self.makeTestArchive(f, compression)
898
899 # Read the ZIP archive
900 zipfp = zipfile.ZipFile(f, "r", compression)
901 zipdata1 = []
902 zipopen1 = zipfp.open(TESTFN)
903 while 1:
904 read_data = zipopen1.read(256)
905 if not read_data:
906 break
907 zipdata1.append(read_data)
908
909 zipdata2 = []
Skip Montanaro7a98be22007-08-16 14:35:24 +0000910 zipopen2 = zipfp.open("another.name")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000911 while 1:
912 read_data = zipopen2.read(256)
913 if not read_data:
914 break
915 zipdata2.append(read_data)
916
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000917 testdata1 = b''.join(zipdata1)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000918 self.assertEqual(len(testdata1), len(self.data))
919 self.assertEqual(testdata1, self.data)
920
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000921 testdata2 = b''.join(zipdata2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000922 self.assertEqual(len(testdata1), len(self.data))
923 self.assertEqual(testdata1, self.data)
924 zipfp.close()
925
926 def testOpenStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000927 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000928 self.zipOpenTest(f, zipfile.ZIP_STORED)
929
930 def zipRandomOpenTest(self, f, compression):
931 self.makeTestArchive(f, compression)
932
933 # Read the ZIP archive
934 zipfp = zipfile.ZipFile(f, "r", compression)
935 zipdata1 = []
936 zipopen1 = zipfp.open(TESTFN)
937 while 1:
938 read_data = zipopen1.read(randint(1, 1024))
939 if not read_data:
940 break
941 zipdata1.append(read_data)
942
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000943 testdata = b''.join(zipdata1)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000944 self.assertEqual(len(testdata), len(self.data))
945 self.assertEqual(testdata, self.data)
946 zipfp.close()
947
948 def testRandomOpenStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000949 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000950 self.zipRandomOpenTest(f, zipfile.ZIP_STORED)
951
952class TestsWithMultipleOpens(unittest.TestCase):
953 def setUp(self):
954 # Create the ZIP archive
955 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED)
956 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
957 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
958 zipfp.close()
959
960 def testSameFile(self):
961 # Verify that (when the ZipFile is in control of creating file objects)
962 # multiple open() calls can be made without interfering with each other.
963 zipf = zipfile.ZipFile(TESTFN2, mode="r")
964 zopen1 = zipf.open('ones')
965 zopen2 = zipf.open('ones')
966 data1 = zopen1.read(500)
967 data2 = zopen2.read(500)
968 data1 += zopen1.read(500)
969 data2 += zopen2.read(500)
970 self.assertEqual(data1, data2)
971 zipf.close()
972
973 def testDifferentFile(self):
974 # Verify that (when the ZipFile is in control of creating file objects)
975 # multiple open() calls can be made without interfering with each other.
976 zipf = zipfile.ZipFile(TESTFN2, mode="r")
977 zopen1 = zipf.open('ones')
978 zopen2 = zipf.open('twos')
979 data1 = zopen1.read(500)
980 data2 = zopen2.read(500)
981 data1 += zopen1.read(500)
982 data2 += zopen2.read(500)
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000983 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
984 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000985 zipf.close()
986
987 def testInterleaved(self):
988 # Verify that (when the ZipFile is in control of creating file objects)
989 # multiple open() calls can be made without interfering with each other.
990 zipf = zipfile.ZipFile(TESTFN2, mode="r")
991 zopen1 = zipf.open('ones')
992 data1 = zopen1.read(500)
993 zopen2 = zipf.open('twos')
994 data2 = zopen2.read(500)
995 data1 += zopen1.read(500)
996 data2 += zopen2.read(500)
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000997 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
998 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000999 zipf.close()
1000
1001 def tearDown(self):
1002 os.remove(TESTFN2)
1003
Martin v. Löwis59e47792009-01-24 14:10:07 +00001004class TestWithDirectory(unittest.TestCase):
1005 def setUp(self):
1006 os.mkdir(TESTFN2)
1007
1008 def testExtractDir(self):
1009 zipf = zipfile.ZipFile(findfile("zipdir.zip"))
1010 zipf.extractall(TESTFN2)
1011 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1012 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1013 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1014
1015 def testStoreDir(self):
1016 os.mkdir(os.path.join(TESTFN2, "x"))
1017 zipf = zipfile.ZipFile(TESTFN, "w")
1018 zipf.write(os.path.join(TESTFN2, "x"), "x")
1019 self.assertTrue(zipf.filelist[0].filename.endswith("x/"))
1020
1021 def tearDown(self):
1022 shutil.rmtree(TESTFN2)
1023 if os.path.exists(TESTFN):
1024 os.remove(TESTFN)
1025
Guido van Rossumd8faa362007-04-27 19:54:29 +00001026
1027class UniversalNewlineTests(unittest.TestCase):
1028 def setUp(self):
Guido van Rossum9c627722007-08-27 18:31:48 +00001029 self.line_gen = [bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001030 for i in range(FIXEDTEST_SIZE)]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001031 self.seps = ('\r', '\r\n', '\n')
1032 self.arcdata, self.arcfiles = {}, {}
1033 for n, s in enumerate(self.seps):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001034 b = s.encode("ascii")
1035 self.arcdata[s] = b.join(self.line_gen) + b
Guido van Rossumd8faa362007-04-27 19:54:29 +00001036 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001037 f = open(self.arcfiles[s], "wb")
1038 try:
1039 f.write(self.arcdata[s])
1040 finally:
1041 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001042
1043 def makeTestArchive(self, f, compression):
1044 # Create the ZIP archive
1045 zipfp = zipfile.ZipFile(f, "w", compression)
1046 for fn in self.arcfiles.values():
1047 zipfp.write(fn, fn)
1048 zipfp.close()
1049
1050 def readTest(self, f, compression):
1051 self.makeTestArchive(f, compression)
1052
1053 # Read the ZIP archive
1054 zipfp = zipfile.ZipFile(f, "r")
1055 for sep, fn in self.arcfiles.items():
1056 zipdata = zipfp.open(fn, "rU").read()
1057 self.assertEqual(self.arcdata[sep], zipdata)
1058
1059 zipfp.close()
1060
1061 def readlineTest(self, f, compression):
1062 self.makeTestArchive(f, compression)
1063
1064 # Read the ZIP archive
1065 zipfp = zipfile.ZipFile(f, "r")
1066 for sep, fn in self.arcfiles.items():
1067 zipopen = zipfp.open(fn, "rU")
1068 for line in self.line_gen:
1069 linedata = zipopen.readline()
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001070 self.assertEqual(linedata, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001071
1072 zipfp.close()
1073
1074 def readlinesTest(self, f, compression):
1075 self.makeTestArchive(f, compression)
1076
1077 # Read the ZIP archive
1078 zipfp = zipfile.ZipFile(f, "r")
1079 for sep, fn in self.arcfiles.items():
1080 ziplines = zipfp.open(fn, "rU").readlines()
1081 for line, zipline in zip(self.line_gen, ziplines):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001082 self.assertEqual(zipline, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001083
1084 zipfp.close()
1085
1086 def iterlinesTest(self, f, compression):
1087 self.makeTestArchive(f, compression)
1088
1089 # Read the ZIP archive
1090 zipfp = zipfile.ZipFile(f, "r")
1091 for sep, fn in self.arcfiles.items():
1092 for line, zipline in zip(self.line_gen, zipfp.open(fn, "rU")):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001093 self.assertEqual(zipline, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001094
1095 zipfp.close()
1096
1097 def testReadStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001098 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001099 self.readTest(f, zipfile.ZIP_STORED)
1100
1101 def testReadlineStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001102 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001103 self.readlineTest(f, zipfile.ZIP_STORED)
1104
1105 def testReadlinesStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001106 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001107 self.readlinesTest(f, zipfile.ZIP_STORED)
1108
1109 def testIterlinesStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001110 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001111 self.iterlinesTest(f, zipfile.ZIP_STORED)
1112
1113 if zlib:
1114 def testReadDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001115 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001116 self.readTest(f, zipfile.ZIP_DEFLATED)
1117
1118 def testReadlineDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001119 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001120 self.readlineTest(f, zipfile.ZIP_DEFLATED)
1121
1122 def testReadlinesDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001123 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001124 self.readlinesTest(f, zipfile.ZIP_DEFLATED)
1125
1126 def testIterlinesDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001127 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001128 self.iterlinesTest(f, zipfile.ZIP_DEFLATED)
1129
1130 def tearDown(self):
1131 for sep, fn in self.arcfiles.items():
1132 os.remove(fn)
1133 support.unlink(TESTFN)
1134 support.unlink(TESTFN2)
1135
1136
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001137def test_main():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001138 run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
1139 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
Martin v. Löwis59e47792009-01-24 14:10:07 +00001140 TestWithDirectory,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001141 UniversalNewlineTests, TestsWithRandomBinaryFiles)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001142
1143if __name__ == "__main__":
1144 test_main()