blob: 4b9a2b08dba942aafdbb08f885d94faf2b978f65 [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
Ezio Melotti74c96ec2009-07-08 22:24:06 +00006
7import io
8import os
9import shutil
10import struct
11import zipfile
12import unittest
13
Tim Petersa45cacf2004-08-20 03:47:14 +000014
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000015from tempfile import TemporaryFile
Guido van Rossumd8faa362007-04-27 19:54:29 +000016from random import randint, random
Ezio Melotti74c96ec2009-07-08 22:24:06 +000017from unittest import skipUnless
Tim Petersa19a1682001-03-29 04:36:09 +000018
Ezio Melotti74c96ec2009-07-08 22:24:06 +000019from test import support
Martin v. Löwis59e47792009-01-24 14:10:07 +000020from test.support import TESTFN, run_unittest, findfile
Guido van Rossum368f04a2000-04-10 13:23:04 +000021
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000022TESTFN2 = TESTFN + "2"
Martin v. Löwis59e47792009-01-24 14:10:07 +000023TESTFNDIR = TESTFN + "d"
Guido van Rossumb5a755e2007-07-18 18:15:48 +000024FIXEDTEST_SIZE = 1000
Guido van Rossum368f04a2000-04-10 13:23:04 +000025
Christian Heimes790c8232008-01-07 21:14:23 +000026SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'),
27 ('ziptest2dir/_ziptest2', 'qawsedrftg'),
28 ('/ziptest2dir/ziptest3dir/_ziptest3', 'azsxdcfvgb'),
29 ('ziptest2dir/ziptest3dir/ziptest4dir/_ziptest3', '6y7u8i9o0p')]
30
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000031class TestsWithSourceFile(unittest.TestCase):
32 def setUp(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +000033 self.line_gen = (bytes("Zipfile test line %d. random float: %f" %
Guido van Rossum9c627722007-08-27 18:31:48 +000034 (i, random()), "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +000035 for i in range(FIXEDTEST_SIZE))
36 self.data = b'\n'.join(self.line_gen) + b'\n'
Fred Drake6e7e4852001-02-28 05:34:16 +000037
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000038 # Make a source file with some lines
39 fp = open(TESTFN, "wb")
40 fp.write(self.data)
41 fp.close()
Tim Peters7d3bad62001-04-04 18:56:49 +000042
Guido van Rossumd8faa362007-04-27 19:54:29 +000043 def makeTestArchive(self, f, compression):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000044 # Create the ZIP archive
45 zipfp = zipfile.ZipFile(f, "w", compression)
Skip Montanaro7a98be22007-08-16 14:35:24 +000046 zipfp.write(TESTFN, "another.name")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000047 zipfp.write(TESTFN, TESTFN)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000048 zipfp.writestr("strfile", self.data)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000049 zipfp.close()
Tim Peters7d3bad62001-04-04 18:56:49 +000050
Guido van Rossumd8faa362007-04-27 19:54:29 +000051 def zipTest(self, f, compression):
52 self.makeTestArchive(f, compression)
53
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000054 # Read the ZIP archive
55 zipfp = zipfile.ZipFile(f, "r", compression)
56 self.assertEqual(zipfp.read(TESTFN), self.data)
Skip Montanaro7a98be22007-08-16 14:35:24 +000057 self.assertEqual(zipfp.read("another.name"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000058 self.assertEqual(zipfp.read("strfile"), self.data)
59
60 # Print the ZIP directory
Guido van Rossumd6ca5462007-05-22 01:29:33 +000061 fp = io.StringIO()
62 zipfp.printdir(file=fp)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000063
64 directory = fp.getvalue()
65 lines = directory.splitlines()
66 self.assertEquals(len(lines), 4) # Number of files + header
67
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000068 self.assertTrue('File Name' in lines[0])
69 self.assertTrue('Modified' in lines[0])
70 self.assertTrue('Size' in lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +000071
72 fn, date, time, size = lines[1].split()
73 self.assertEquals(fn, 'another.name')
74 # XXX: timestamp is not tested
75 self.assertEquals(size, str(len(self.data)))
76
77 # Check the namelist
78 names = zipfp.namelist()
79 self.assertEquals(len(names), 3)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000080 self.assertTrue(TESTFN in names)
81 self.assertTrue("another.name" in names)
82 self.assertTrue("strfile" in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000083
84 # Check infolist
85 infos = zipfp.infolist()
86 names = [ i.filename for i in infos ]
87 self.assertEquals(len(names), 3)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000088 self.assertTrue(TESTFN in names)
89 self.assertTrue("another.name" in names)
90 self.assertTrue("strfile" in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000091 for i in infos:
92 self.assertEquals(i.file_size, len(self.data))
93
94 # check getinfo
Skip Montanaro7a98be22007-08-16 14:35:24 +000095 for nm in (TESTFN, "another.name", "strfile"):
Thomas Wouters0e3f5912006-08-11 14:57:12 +000096 info = zipfp.getinfo(nm)
97 self.assertEquals(info.filename, nm)
98 self.assertEquals(info.file_size, len(self.data))
99
100 # Check that testzip doesn't raise an exception
101 zipfp.testzip()
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000102 zipfp.close()
Tim Peters7d3bad62001-04-04 18:56:49 +0000103
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000104 def testStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000105 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000106 self.zipTest(f, zipfile.ZIP_STORED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000107
Guido van Rossumd8faa362007-04-27 19:54:29 +0000108 def zipOpenTest(self, f, compression):
109 self.makeTestArchive(f, compression)
110
111 # Read the ZIP archive
112 zipfp = zipfile.ZipFile(f, "r", compression)
113 zipdata1 = []
114 zipopen1 = zipfp.open(TESTFN)
115 while 1:
116 read_data = zipopen1.read(256)
117 if not read_data:
118 break
119 zipdata1.append(read_data)
120
121 zipdata2 = []
Skip Montanaro7a98be22007-08-16 14:35:24 +0000122 zipopen2 = zipfp.open("another.name")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000123 while 1:
124 read_data = zipopen2.read(256)
125 if not read_data:
126 break
127 zipdata2.append(read_data)
128
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000129 self.assertEqual(b''.join(zipdata1), self.data)
130 self.assertEqual(b''.join(zipdata2), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000131 zipfp.close()
132
133 def testOpenStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000134 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000135 self.zipOpenTest(f, zipfile.ZIP_STORED)
136
Georg Brandlb533e262008-05-25 18:19:30 +0000137 def testOpenViaZipInfo(self):
138 # Create the ZIP archive
139 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
140 zipfp.writestr("name", "foo")
141 zipfp.writestr("name", "bar")
142 zipfp.close()
143
144 zipfp = zipfile.ZipFile(TESTFN2, "r")
145 infos = zipfp.infolist()
146 data = b""
147 for info in infos:
148 data += zipfp.open(info).read()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000149 self.assertTrue(data == b"foobar" or data == b"barfoo")
Georg Brandlb533e262008-05-25 18:19:30 +0000150 data = b""
151 for info in infos:
152 data += zipfp.read(info)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000153 self.assertTrue(data == b"foobar" or data == b"barfoo")
Georg Brandlb533e262008-05-25 18:19:30 +0000154 zipfp.close()
155
Guido van Rossumd8faa362007-04-27 19:54:29 +0000156 def zipRandomOpenTest(self, f, compression):
157 self.makeTestArchive(f, compression)
158
159 # Read the ZIP archive
160 zipfp = zipfile.ZipFile(f, "r", compression)
161 zipdata1 = []
162 zipopen1 = zipfp.open(TESTFN)
163 while 1:
164 read_data = zipopen1.read(randint(1, 1024))
165 if not read_data:
166 break
167 zipdata1.append(read_data)
168
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000169 self.assertEqual(b''.join(zipdata1), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000170 zipfp.close()
171
172 def testRandomOpenStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000173 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000174 self.zipRandomOpenTest(f, zipfile.ZIP_STORED)
175
176 def zipReadlineTest(self, f, compression):
177 self.makeTestArchive(f, compression)
178
179 # Read the ZIP archive
180 zipfp = zipfile.ZipFile(f, "r")
181 zipopen = zipfp.open(TESTFN)
182 for line in self.line_gen:
183 linedata = zipopen.readline()
184 self.assertEqual(linedata, line + '\n')
185
186 zipfp.close()
187
188 def zipReadlinesTest(self, f, compression):
189 self.makeTestArchive(f, compression)
190
191 # Read the ZIP archive
192 zipfp = zipfile.ZipFile(f, "r")
193 ziplines = zipfp.open(TESTFN).readlines()
194 for line, zipline in zip(self.line_gen, ziplines):
195 self.assertEqual(zipline, line + '\n')
196
197 zipfp.close()
198
199 def zipIterlinesTest(self, f, compression):
200 self.makeTestArchive(f, compression)
201
202 # Read the ZIP archive
203 zipfp = zipfile.ZipFile(f, "r")
204 for line, zipline in zip(self.line_gen, zipfp.open(TESTFN)):
205 self.assertEqual(zipline, line + '\n')
206
207 zipfp.close()
208
209 def testReadlineStored(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.zipReadlineTest(f, zipfile.ZIP_STORED)
212
213 def testReadlinesStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000214 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000215 self.zipReadlinesTest(f, zipfile.ZIP_STORED)
216
217 def testIterlinesStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000218 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000219 self.zipIterlinesTest(f, zipfile.ZIP_STORED)
220
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000221 @skipUnless(zlib, "requires zlib")
222 def testDeflated(self):
223 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
224 self.zipTest(f, zipfile.ZIP_DEFLATED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000225
Guido van Rossumd8faa362007-04-27 19:54:29 +0000226
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000227 @skipUnless(zlib, "requires zlib")
228 def testOpenDeflated(self):
229 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
230 self.zipOpenTest(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000231
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000232 @skipUnless(zlib, "requires zlib")
233 def testRandomOpenDeflated(self):
234 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
235 self.zipRandomOpenTest(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000236
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000237 @skipUnless(zlib, "requires zlib")
238 def testReadlineDeflated(self):
239 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
240 self.zipReadlineTest(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000241
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000242 @skipUnless(zlib, "requires zlib")
243 def testReadlinesDeflated(self):
244 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
245 self.zipReadlinesTest(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000246
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000247 @skipUnless(zlib, "requires zlib")
248 def testIterlinesDeflated(self):
249 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
250 self.zipIterlinesTest(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000251
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000252 @skipUnless(zlib, "requires zlib")
253 def testLowCompression(self):
254 # Checks for cases where compressed data is larger than original
255 # Create the ZIP archive
256 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED)
257 zipfp.writestr("strfile", '12')
258 zipfp.close()
259
260 # Get an open object for strfile
261 zipfp = zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_DEFLATED)
262 openobj = zipfp.open("strfile")
263 self.assertEqual(openobj.read(1), b'1')
264 self.assertEqual(openobj.read(1), b'2')
265
Guido van Rossumd8faa362007-04-27 19:54:29 +0000266
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000267 def testAbsoluteArcnames(self):
268 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
269 zipfp.write(TESTFN, "/absolute")
270 zipfp.close()
271
272 zipfp = zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED)
273 self.assertEqual(zipfp.namelist(), ["absolute"])
274 zipfp.close()
Tim Peters32cbc962006-02-20 21:42:18 +0000275
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000276 def testAppendToZipFile(self):
277 # Test appending to an existing zipfile
278 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
279 zipfp.write(TESTFN, TESTFN)
280 zipfp.close()
281 zipfp = zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED)
282 zipfp.writestr("strfile", self.data)
283 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
284 zipfp.close()
285
286 def testAppendToNonZipFile(self):
287 # Test appending to an existing file that is not a zipfile
288 # NOTE: this test fails if len(d) < 22 because of the first
289 # line "fpin.seek(-22, 2)" in _EndRecData
Guido van Rossum9c627722007-08-27 18:31:48 +0000290 d = b'I am not a ZipFile!'*10
Guido van Rossum814661e2007-07-18 22:07:29 +0000291 f = open(TESTFN2, 'wb')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000292 f.write(d)
293 f.close()
294 zipfp = zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED)
295 zipfp.write(TESTFN, TESTFN)
296 zipfp.close()
297
Guido van Rossum814661e2007-07-18 22:07:29 +0000298 f = open(TESTFN2, 'rb')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000299 f.seek(len(d))
300 zipfp = zipfile.ZipFile(f, "r")
301 self.assertEqual(zipfp.namelist(), [TESTFN])
302 zipfp.close()
303 f.close()
304
305 def test_WriteDefaultName(self):
306 # Check that calling ZipFile.write without arcname specified produces the expected result
307 zipfp = zipfile.ZipFile(TESTFN2, "w")
308 zipfp.write(TESTFN)
Guido van Rossum814661e2007-07-18 22:07:29 +0000309 self.assertEqual(zipfp.read(TESTFN), open(TESTFN, "rb").read())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000310 zipfp.close()
311
312 def test_PerFileCompression(self):
313 # Check that files within a Zip archive can have different compression options
314 zipfp = zipfile.ZipFile(TESTFN2, "w")
315 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
316 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
317 sinfo = zipfp.getinfo('storeme')
318 dinfo = zipfp.getinfo('deflateme')
319 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
320 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
321 zipfp.close()
322
323 def test_WriteToReadonly(self):
324 # Check that trying to call write() on a readonly ZipFile object
325 # raises a RuntimeError
326 zipf = zipfile.ZipFile(TESTFN2, mode="w")
327 zipf.writestr("somefile.txt", "bogus")
328 zipf.close()
329 zipf = zipfile.ZipFile(TESTFN2, mode="r")
330 self.assertRaises(RuntimeError, zipf.write, TESTFN)
331 zipf.close()
332
Christian Heimes790c8232008-01-07 21:14:23 +0000333 def testExtract(self):
334 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
335 for fpath, fdata in SMALL_TEST_DATA:
336 zipfp.writestr(fpath, fdata)
337 zipfp.close()
338
339 zipfp = zipfile.ZipFile(TESTFN2, "r")
340 for fpath, fdata in SMALL_TEST_DATA:
341 writtenfile = zipfp.extract(fpath)
342
343 # make sure it was written to the right place
344 if os.path.isabs(fpath):
345 correctfile = os.path.join(os.getcwd(), fpath[1:])
346 else:
347 correctfile = os.path.join(os.getcwd(), fpath)
Christian Heimesaf98da12008-01-27 15:18:18 +0000348 correctfile = os.path.normpath(correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000349
350 self.assertEqual(writtenfile, correctfile)
351
352 # make sure correct data is in correct file
353 self.assertEqual(fdata.encode(), open(writtenfile, "rb").read())
354
355 os.remove(writtenfile)
356
357 zipfp.close()
358
359 # remove the test file subdirectories
360 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
361
362 def testExtractAll(self):
363 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED)
364 for fpath, fdata in SMALL_TEST_DATA:
365 zipfp.writestr(fpath, fdata)
366 zipfp.close()
367
368 zipfp = zipfile.ZipFile(TESTFN2, "r")
369 zipfp.extractall()
370 for fpath, fdata in SMALL_TEST_DATA:
371 if os.path.isabs(fpath):
372 outfile = os.path.join(os.getcwd(), fpath[1:])
373 else:
374 outfile = os.path.join(os.getcwd(), fpath)
375
376 self.assertEqual(fdata.encode(), open(outfile, "rb").read())
377
378 os.remove(outfile)
379
380 zipfp.close()
381
382 # remove the test file subdirectories
383 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
384
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000385 def zip_test_writestr_permissions(self, f, compression):
386 # Make sure that writestr creates files with mode 0600,
387 # when it is passed a name rather than a ZipInfo instance.
388
389 self.makeTestArchive(f, compression)
390 zipfp = zipfile.ZipFile(f, "r")
391 zinfo = zipfp.getinfo('strfile')
392 self.assertEqual(zinfo.external_attr, 0o600 << 16)
393
394 def test_writestr_permissions(self):
395 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
396 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
397
Gregory P. Smithb0d9ca92009-07-07 05:06:04 +0000398 def test_writestr_extended_local_header_issue1202(self):
399 orig_zip = zipfile.ZipFile(TESTFN2, 'w')
400 for data in 'abcdefghijklmnop':
401 zinfo = zipfile.ZipInfo(data)
402 zinfo.flag_bits |= 0x08 # Include an extended local header.
403 orig_zip.writestr(zinfo, data)
404 orig_zip.close()
405
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000406 def tearDown(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000407 support.unlink(TESTFN)
408 support.unlink(TESTFN2)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000409
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000410class TestZip64InSmallFiles(unittest.TestCase):
411 # These tests test the ZIP64 functionality without using large files,
412 # see test_zipfile64 for proper tests.
413
414 def setUp(self):
415 self._limit = zipfile.ZIP64_LIMIT
416 zipfile.ZIP64_LIMIT = 5
417
Guido van Rossum9c627722007-08-27 18:31:48 +0000418 line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000419 for i in range(0, FIXEDTEST_SIZE))
420 self.data = b'\n'.join(line_gen)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000421
422 # Make a source file with some lines
423 fp = open(TESTFN, "wb")
424 fp.write(self.data)
425 fp.close()
426
427 def largeFileExceptionTest(self, f, compression):
428 zipfp = zipfile.ZipFile(f, "w", compression)
429 self.assertRaises(zipfile.LargeZipFile,
Skip Montanaro7a98be22007-08-16 14:35:24 +0000430 zipfp.write, TESTFN, "another.name")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000431 zipfp.close()
432
433 def largeFileExceptionTest2(self, f, compression):
434 zipfp = zipfile.ZipFile(f, "w", compression)
435 self.assertRaises(zipfile.LargeZipFile,
Skip Montanaro7a98be22007-08-16 14:35:24 +0000436 zipfp.writestr, "another.name", self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000437 zipfp.close()
438
439 def testLargeFileException(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000440 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000441 self.largeFileExceptionTest(f, zipfile.ZIP_STORED)
442 self.largeFileExceptionTest2(f, zipfile.ZIP_STORED)
443
444 def zipTest(self, f, compression):
445 # Create the ZIP archive
446 zipfp = zipfile.ZipFile(f, "w", compression, allowZip64=True)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000447 zipfp.write(TESTFN, "another.name")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000448 zipfp.write(TESTFN, TESTFN)
449 zipfp.writestr("strfile", self.data)
450 zipfp.close()
451
452 # Read the ZIP archive
453 zipfp = zipfile.ZipFile(f, "r", compression)
454 self.assertEqual(zipfp.read(TESTFN), self.data)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000455 self.assertEqual(zipfp.read("another.name"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000456 self.assertEqual(zipfp.read("strfile"), self.data)
457
458 # Print the ZIP directory
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000459 fp = io.StringIO()
460 zipfp.printdir(fp)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000461
462 directory = fp.getvalue()
463 lines = directory.splitlines()
464 self.assertEquals(len(lines), 4) # Number of files + header
465
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000466 self.assertTrue('File Name' in lines[0])
467 self.assertTrue('Modified' in lines[0])
468 self.assertTrue('Size' in lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000469
470 fn, date, time, size = lines[1].split()
471 self.assertEquals(fn, 'another.name')
472 # XXX: timestamp is not tested
473 self.assertEquals(size, str(len(self.data)))
474
475 # Check the namelist
476 names = zipfp.namelist()
477 self.assertEquals(len(names), 3)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000478 self.assertTrue(TESTFN in names)
479 self.assertTrue("another.name" in names)
480 self.assertTrue("strfile" in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000481
482 # Check infolist
483 infos = zipfp.infolist()
484 names = [ i.filename for i in infos ]
485 self.assertEquals(len(names), 3)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000486 self.assertTrue(TESTFN in names)
487 self.assertTrue("another.name" in names)
488 self.assertTrue("strfile" in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000489 for i in infos:
490 self.assertEquals(i.file_size, len(self.data))
491
492 # check getinfo
Skip Montanaro7a98be22007-08-16 14:35:24 +0000493 for nm in (TESTFN, "another.name", "strfile"):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000494 info = zipfp.getinfo(nm)
495 self.assertEquals(info.filename, nm)
496 self.assertEquals(info.file_size, len(self.data))
497
498 # Check that testzip doesn't raise an exception
499 zipfp.testzip()
500
501
502 zipfp.close()
503
504 def testStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000505 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000506 self.zipTest(f, zipfile.ZIP_STORED)
507
508
509 if zlib:
510 def testDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000511 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000512 self.zipTest(f, zipfile.ZIP_DEFLATED)
513
514 def testAbsoluteArcnames(self):
515 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED, allowZip64=True)
516 zipfp.write(TESTFN, "/absolute")
517 zipfp.close()
518
519 zipfp = zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED)
520 self.assertEqual(zipfp.namelist(), ["absolute"])
521 zipfp.close()
522
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000523 def tearDown(self):
524 zipfile.ZIP64_LIMIT = self._limit
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000525 support.unlink(TESTFN)
526 support.unlink(TESTFN2)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000527
528class PyZipFileTests(unittest.TestCase):
529 def testWritePyfile(self):
530 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
531 fn = __file__
532 if fn.endswith('.pyc') or fn.endswith('.pyo'):
533 fn = fn[:-1]
534
535 zipfp.writepy(fn)
536
537 bn = os.path.basename(fn)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000538 self.assertTrue(bn not in zipfp.namelist())
539 self.assertTrue(bn + 'o' in zipfp.namelist() or bn + 'c' in zipfp.namelist())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000540 zipfp.close()
541
542
543 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
544 fn = __file__
545 if fn.endswith('.pyc') or fn.endswith('.pyo'):
546 fn = fn[:-1]
547
548 zipfp.writepy(fn, "testpackage")
549
550 bn = "%s/%s"%("testpackage", os.path.basename(fn))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000551 self.assertTrue(bn not in zipfp.namelist())
552 self.assertTrue(bn + 'o' in zipfp.namelist() or bn + 'c' in zipfp.namelist())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000553 zipfp.close()
554
555 def testWritePythonPackage(self):
556 import email
557 packagedir = os.path.dirname(email.__file__)
558
559 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
560 zipfp.writepy(packagedir)
561
562 # Check for a couple of modules at different levels of the hieararchy
563 names = zipfp.namelist()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000564 self.assertTrue('email/__init__.pyo' in names or 'email/__init__.pyc' in names)
565 self.assertTrue('email/mime/text.pyo' in names or 'email/mime/text.pyc' in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000566
567 def testWritePythonDirectory(self):
568 os.mkdir(TESTFN2)
569 try:
570 fp = open(os.path.join(TESTFN2, "mod1.py"), "w")
Guido van Rossum43fc78d2007-02-09 22:18:41 +0000571 fp.write("print(42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000572 fp.close()
573
574 fp = open(os.path.join(TESTFN2, "mod2.py"), "w")
Guido van Rossum43fc78d2007-02-09 22:18:41 +0000575 fp.write("print(42 * 42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000576 fp.close()
577
578 fp = open(os.path.join(TESTFN2, "mod2.txt"), "w")
579 fp.write("bla bla bla\n")
580 fp.close()
581
582 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
583 zipfp.writepy(TESTFN2)
584
585 names = zipfp.namelist()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000586 self.assertTrue('mod1.pyc' in names or 'mod1.pyo' in names)
587 self.assertTrue('mod2.pyc' in names or 'mod2.pyo' in names)
588 self.assertTrue('mod2.txt' not in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000589
590 finally:
591 shutil.rmtree(TESTFN2)
592
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000593 def testWriteNonPyfile(self):
594 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
Guido van Rossum814661e2007-07-18 22:07:29 +0000595 open(TESTFN, 'w').write('most definitely not a python file')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000596 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
597 os.remove(TESTFN)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000598
599
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000600class OtherTests(unittest.TestCase):
Martin v. Löwis8570f6a2008-05-05 17:44:38 +0000601 def testUnicodeFilenames(self):
602 zf = zipfile.ZipFile(TESTFN, "w")
603 zf.writestr("foo.txt", "Test for unicode filename")
Martin v. Löwis1a9f9002008-05-05 17:50:05 +0000604 zf.writestr("\xf6.txt", "Test for unicode filename")
Martin v. Löwis8570f6a2008-05-05 17:44:38 +0000605 zf.close()
Martin v. Löwis1a9f9002008-05-05 17:50:05 +0000606 zf = zipfile.ZipFile(TESTFN, "r")
607 self.assertEqual(zf.filelist[0].filename, "foo.txt")
608 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
609 zf.close()
Martin v. Löwis8570f6a2008-05-05 17:44:38 +0000610
Thomas Wouterscf297e42007-02-23 15:07:44 +0000611 def testCreateNonExistentFileForAppend(self):
612 if os.path.exists(TESTFN):
613 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000614
Thomas Wouterscf297e42007-02-23 15:07:44 +0000615 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000616 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +0000617
Thomas Wouterscf297e42007-02-23 15:07:44 +0000618 try:
619 zf = zipfile.ZipFile(TESTFN, 'a')
620 zf.writestr(filename, content)
621 zf.close()
622 except IOError:
623 self.fail('Could not append data to a non-existent zip file.')
624
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000625 self.assertTrue(os.path.exists(TESTFN))
Thomas Wouterscf297e42007-02-23 15:07:44 +0000626
627 zf = zipfile.ZipFile(TESTFN, 'r')
628 self.assertEqual(zf.read(filename), content)
629 zf.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000630
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000631 def testCloseErroneousFile(self):
632 # This test checks that the ZipFile constructor closes the file object
633 # it opens if there's an error in the file. If it doesn't, the traceback
634 # holds a reference to the ZipFile object and, indirectly, the file object.
635 # On Windows, this causes the os.unlink() call to fail because the
636 # underlying file is still open. This is SF bug #412214.
637 #
638 fp = open(TESTFN, "w")
639 fp.write("this is not a legal zip file\n")
640 fp.close()
641 try:
642 zf = zipfile.ZipFile(TESTFN)
643 except zipfile.BadZipfile:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000644 pass
645
646 def testIsZipErroneousFile(self):
647 # This test checks that the is_zipfile function correctly identifies
648 # a file that is not a zip file
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000649
650 # - passing a filename
651 with open(TESTFN, "w") as fp:
652 fp.write("this is not a legal zip file\n")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000653 chk = zipfile.is_zipfile(TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000654 self.assertTrue(not chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000655 # - passing a file object
656 with open(TESTFN, "rb") as fp:
657 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000658 self.assertTrue(not chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000659 # - passing a file-like object
660 fp = io.BytesIO()
661 fp.write(b"this is not a legal zip file\n")
662 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000663 self.assertTrue(not chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000664 fp.seek(0,0)
665 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000666 self.assertTrue(not chk)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000667
668 def testIsZipValidFile(self):
669 # This test checks that the is_zipfile function correctly identifies
670 # a file that is a zip file
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000671
672 # - passing a filename
Guido van Rossumd8faa362007-04-27 19:54:29 +0000673 zipf = zipfile.ZipFile(TESTFN, mode="w")
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000674 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000675 zipf.close()
676 chk = zipfile.is_zipfile(TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000677 self.assertTrue(chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000678 # - passing a file object
679 with open(TESTFN, "rb") as fp:
680 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000681 self.assertTrue(chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000682 fp.seek(0,0)
683 zip_contents = fp.read()
684 # - passing a file-like object
685 fp = io.BytesIO()
686 fp.write(zip_contents)
687 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000688 self.assertTrue(chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000689 fp.seek(0,0)
690 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000691 self.assertTrue(chk)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000692
693 def testNonExistentFileRaisesIOError(self):
694 # make sure we don't raise an AttributeError when a partially-constructed
695 # ZipFile instance is finalized; this tests for regression on SF tracker
696 # bug #403871.
697
698 # The bug we're testing for caused an AttributeError to be raised
699 # when a ZipFile instance was created for a file that did not
700 # exist; the .fp member was not initialized but was needed by the
701 # __del__() method. Since the AttributeError is in the __del__(),
702 # it is ignored, but the user should be sufficiently annoyed by
703 # the message on the output that regression will be noticed
704 # quickly.
705 self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
706
707 def testClosedZipRaisesRuntimeError(self):
708 # Verify that testzip() doesn't swallow inappropriate exceptions.
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000709 data = io.BytesIO()
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000710 zipf = zipfile.ZipFile(data, mode="w")
711 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
712 zipf.close()
713
714 # This is correct; calling .read on a closed ZipFile should throw
715 # a RuntimeError, and so should calling .testzip. An earlier
716 # version of .testzip would swallow this exception (and any other)
717 # and report that the first file in the archive was corrupt.
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000718 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
719 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000720 self.assertRaises(RuntimeError, zipf.testzip)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000721 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Guido van Rossum814661e2007-07-18 22:07:29 +0000722 open(TESTFN, 'w').write('zipfile test data')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000723 self.assertRaises(RuntimeError, zipf.write, TESTFN)
724
725 def test_BadConstructorMode(self):
726 # Check that bad modes passed to ZipFile constructor are caught
727 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
728
729 def test_BadOpenMode(self):
730 # Check that bad modes passed to ZipFile.open are caught
731 zipf = zipfile.ZipFile(TESTFN, mode="w")
732 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
733 zipf.close()
734 zipf = zipfile.ZipFile(TESTFN, mode="r")
735 # read the data to make sure the file is there
736 zipf.read("foo.txt")
737 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
738 zipf.close()
739
740 def test_Read0(self):
741 # Check that calling read(0) on a ZipExtFile object returns an empty
742 # string and doesn't advance file pointer
743 zipf = zipfile.ZipFile(TESTFN, mode="w")
744 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
745 # read the data to make sure the file is there
746 f = zipf.open("foo.txt")
747 for i in range(FIXEDTEST_SIZE):
Guido van Rossum814661e2007-07-18 22:07:29 +0000748 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000749
Guido van Rossum814661e2007-07-18 22:07:29 +0000750 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000751 zipf.close()
752
753 def test_OpenNonexistentItem(self):
754 # Check that attempting to call open() for an item that doesn't
755 # exist in the archive raises a RuntimeError
756 zipf = zipfile.ZipFile(TESTFN, mode="w")
757 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
758
759 def test_BadCompressionMode(self):
760 # Check that bad compression methods passed to ZipFile.open are caught
761 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
762
763 def test_NullByteInFilename(self):
764 # Check that a filename containing a null byte is properly terminated
765 zipf = zipfile.ZipFile(TESTFN, mode="w")
Guido van Rossum814661e2007-07-18 22:07:29 +0000766 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000767 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000768
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000769 def test_StructSizes(self):
770 # check that ZIP internal structure sizes are calculated correctly
771 self.assertEqual(zipfile.sizeEndCentDir, 22)
772 self.assertEqual(zipfile.sizeCentralDir, 46)
773 self.assertEqual(zipfile.sizeEndCentDir64, 56)
774 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
775
776 def testComments(self):
777 # This test checks that comments on the archive are handled properly
778
779 # check default comment is empty
780 zipf = zipfile.ZipFile(TESTFN, mode="w")
781 self.assertEqual(zipf.comment, b'')
782 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
783 zipf.close()
784 zipfr = zipfile.ZipFile(TESTFN, mode="r")
785 self.assertEqual(zipfr.comment, b'')
786 zipfr.close()
787
788 # check a simple short comment
789 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
790 zipf = zipfile.ZipFile(TESTFN, mode="w")
791 zipf.comment = comment
792 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
793 zipf.close()
794 zipfr = zipfile.ZipFile(TESTFN, mode="r")
795 self.assertEqual(zipfr.comment, comment)
796 zipfr.close()
797
798 # check a comment of max length
799 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
800 comment2 = comment2.encode("ascii")
801 zipf = zipfile.ZipFile(TESTFN, mode="w")
802 zipf.comment = comment2
803 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
804 zipf.close()
805 zipfr = zipfile.ZipFile(TESTFN, mode="r")
806 self.assertEqual(zipfr.comment, comment2)
807 zipfr.close()
808
809 # check a comment that is too long is truncated
810 zipf = zipfile.ZipFile(TESTFN, mode="w")
811 zipf.comment = comment2 + b'oops'
812 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
813 zipf.close()
814 zipfr = zipfile.ZipFile(TESTFN, mode="r")
815 self.assertEqual(zipfr.comment, comment2)
816 zipfr.close()
817
Guido van Rossumd8faa362007-04-27 19:54:29 +0000818 def tearDown(self):
819 support.unlink(TESTFN)
820 support.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000821
822class DecryptionTests(unittest.TestCase):
823 # This test checks that ZIP decryption works. Since the library does not
824 # support encryption at the moment, we use a pre-generated encrypted
825 # ZIP file
826
827 data = (
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000828 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
829 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
830 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
831 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
832 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
833 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
834 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +0000835 data2 = (
836 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
837 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
838 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
839 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
840 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
841 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
842 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
843 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +0000844
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000845 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +0000846 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +0000847
848 def setUp(self):
849 fp = open(TESTFN, "wb")
850 fp.write(self.data)
851 fp.close()
852 self.zip = zipfile.ZipFile(TESTFN, "r")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000853 fp = open(TESTFN2, "wb")
854 fp.write(self.data2)
855 fp.close()
856 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000857
858 def tearDown(self):
859 self.zip.close()
860 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +0000861 self.zip2.close()
862 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000863
864 def testNoPassword(self):
865 # Reading the encrypted file without password
866 # must generate a RunTime exception
867 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000868 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000869
870 def testBadPassword(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000871 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000872 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000873 self.zip2.setpassword(b"perl")
874 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000875
Thomas Wouterscf297e42007-02-23 15:07:44 +0000876 def testGoodPassword(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000877 self.zip.setpassword(b"python")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000878 self.assertEquals(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +0000879 self.zip2.setpassword(b"12345")
880 self.assertEquals(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000881
Guido van Rossumd8faa362007-04-27 19:54:29 +0000882
883class TestsWithRandomBinaryFiles(unittest.TestCase):
884 def setUp(self):
885 datacount = randint(16, 64)*1024 + randint(1, 1024)
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000886 self.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
887 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000888
889 # Make a source file with some lines
890 fp = open(TESTFN, "wb")
891 fp.write(self.data)
892 fp.close()
893
894 def tearDown(self):
895 support.unlink(TESTFN)
896 support.unlink(TESTFN2)
897
898 def makeTestArchive(self, f, compression):
899 # Create the ZIP archive
900 zipfp = zipfile.ZipFile(f, "w", compression)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000901 zipfp.write(TESTFN, "another.name")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000902 zipfp.write(TESTFN, TESTFN)
903 zipfp.close()
904
905 def zipTest(self, f, compression):
906 self.makeTestArchive(f, compression)
907
908 # Read the ZIP archive
909 zipfp = zipfile.ZipFile(f, "r", compression)
910 testdata = zipfp.read(TESTFN)
911 self.assertEqual(len(testdata), len(self.data))
912 self.assertEqual(testdata, self.data)
Skip Montanaro7a98be22007-08-16 14:35:24 +0000913 self.assertEqual(zipfp.read("another.name"), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000914 zipfp.close()
915
916 def testStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000917 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000918 self.zipTest(f, zipfile.ZIP_STORED)
919
920 def zipOpenTest(self, f, compression):
921 self.makeTestArchive(f, compression)
922
923 # Read the ZIP archive
924 zipfp = zipfile.ZipFile(f, "r", compression)
925 zipdata1 = []
926 zipopen1 = zipfp.open(TESTFN)
927 while 1:
928 read_data = zipopen1.read(256)
929 if not read_data:
930 break
931 zipdata1.append(read_data)
932
933 zipdata2 = []
Skip Montanaro7a98be22007-08-16 14:35:24 +0000934 zipopen2 = zipfp.open("another.name")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000935 while 1:
936 read_data = zipopen2.read(256)
937 if not read_data:
938 break
939 zipdata2.append(read_data)
940
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000941 testdata1 = b''.join(zipdata1)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000942 self.assertEqual(len(testdata1), len(self.data))
943 self.assertEqual(testdata1, self.data)
944
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000945 testdata2 = b''.join(zipdata2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000946 self.assertEqual(len(testdata1), len(self.data))
947 self.assertEqual(testdata1, self.data)
948 zipfp.close()
949
950 def testOpenStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000951 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000952 self.zipOpenTest(f, zipfile.ZIP_STORED)
953
954 def zipRandomOpenTest(self, f, compression):
955 self.makeTestArchive(f, compression)
956
957 # Read the ZIP archive
958 zipfp = zipfile.ZipFile(f, "r", compression)
959 zipdata1 = []
960 zipopen1 = zipfp.open(TESTFN)
961 while 1:
962 read_data = zipopen1.read(randint(1, 1024))
963 if not read_data:
964 break
965 zipdata1.append(read_data)
966
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000967 testdata = b''.join(zipdata1)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000968 self.assertEqual(len(testdata), len(self.data))
969 self.assertEqual(testdata, self.data)
970 zipfp.close()
971
972 def testRandomOpenStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000973 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000974 self.zipRandomOpenTest(f, zipfile.ZIP_STORED)
975
976class TestsWithMultipleOpens(unittest.TestCase):
977 def setUp(self):
978 # Create the ZIP archive
979 zipfp = zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED)
980 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
981 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
982 zipfp.close()
983
984 def testSameFile(self):
985 # Verify that (when the ZipFile is in control of creating file objects)
986 # multiple open() calls can be made without interfering with each other.
987 zipf = zipfile.ZipFile(TESTFN2, mode="r")
988 zopen1 = zipf.open('ones')
989 zopen2 = zipf.open('ones')
990 data1 = zopen1.read(500)
991 data2 = zopen2.read(500)
992 data1 += zopen1.read(500)
993 data2 += zopen2.read(500)
994 self.assertEqual(data1, data2)
995 zipf.close()
996
997 def testDifferentFile(self):
998 # Verify that (when the ZipFile is in control of creating file objects)
999 # multiple open() calls can be made without interfering with each other.
1000 zipf = zipfile.ZipFile(TESTFN2, mode="r")
1001 zopen1 = zipf.open('ones')
1002 zopen2 = zipf.open('twos')
1003 data1 = zopen1.read(500)
1004 data2 = zopen2.read(500)
1005 data1 += zopen1.read(500)
1006 data2 += zopen2.read(500)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001007 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
1008 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001009 zipf.close()
1010
1011 def testInterleaved(self):
1012 # Verify that (when the ZipFile is in control of creating file objects)
1013 # multiple open() calls can be made without interfering with each other.
1014 zipf = zipfile.ZipFile(TESTFN2, mode="r")
1015 zopen1 = zipf.open('ones')
1016 data1 = zopen1.read(500)
1017 zopen2 = zipf.open('twos')
1018 data2 = zopen2.read(500)
1019 data1 += zopen1.read(500)
1020 data2 += zopen2.read(500)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001021 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
1022 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001023 zipf.close()
1024
1025 def tearDown(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +00001026 support.unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001027
Martin v. Löwis59e47792009-01-24 14:10:07 +00001028class TestWithDirectory(unittest.TestCase):
1029 def setUp(self):
1030 os.mkdir(TESTFN2)
1031
1032 def testExtractDir(self):
1033 zipf = zipfile.ZipFile(findfile("zipdir.zip"))
1034 zipf.extractall(TESTFN2)
1035 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1036 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1037 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1038
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001039 def test_bug_6050(self):
1040 # Extraction should succeed if directories already exist
1041 os.mkdir(os.path.join(TESTFN2, "a"))
1042 self.testExtractDir()
1043
Martin v. Löwis59e47792009-01-24 14:10:07 +00001044 def testStoreDir(self):
1045 os.mkdir(os.path.join(TESTFN2, "x"))
1046 zipf = zipfile.ZipFile(TESTFN, "w")
1047 zipf.write(os.path.join(TESTFN2, "x"), "x")
1048 self.assertTrue(zipf.filelist[0].filename.endswith("x/"))
1049
1050 def tearDown(self):
1051 shutil.rmtree(TESTFN2)
1052 if os.path.exists(TESTFN):
Ezio Melotti74c96ec2009-07-08 22:24:06 +00001053 support.unlink(TESTFN)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001054
Guido van Rossumd8faa362007-04-27 19:54:29 +00001055
1056class UniversalNewlineTests(unittest.TestCase):
1057 def setUp(self):
Guido van Rossum9c627722007-08-27 18:31:48 +00001058 self.line_gen = [bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001059 for i in range(FIXEDTEST_SIZE)]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001060 self.seps = ('\r', '\r\n', '\n')
1061 self.arcdata, self.arcfiles = {}, {}
1062 for n, s in enumerate(self.seps):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001063 b = s.encode("ascii")
1064 self.arcdata[s] = b.join(self.line_gen) + b
Guido van Rossumd8faa362007-04-27 19:54:29 +00001065 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001066 f = open(self.arcfiles[s], "wb")
1067 try:
1068 f.write(self.arcdata[s])
1069 finally:
1070 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001071
1072 def makeTestArchive(self, f, compression):
1073 # Create the ZIP archive
1074 zipfp = zipfile.ZipFile(f, "w", compression)
1075 for fn in self.arcfiles.values():
1076 zipfp.write(fn, fn)
1077 zipfp.close()
1078
1079 def readTest(self, f, compression):
1080 self.makeTestArchive(f, compression)
1081
1082 # Read the ZIP archive
1083 zipfp = zipfile.ZipFile(f, "r")
1084 for sep, fn in self.arcfiles.items():
1085 zipdata = zipfp.open(fn, "rU").read()
1086 self.assertEqual(self.arcdata[sep], zipdata)
1087
1088 zipfp.close()
1089
1090 def readlineTest(self, f, compression):
1091 self.makeTestArchive(f, compression)
1092
1093 # Read the ZIP archive
1094 zipfp = zipfile.ZipFile(f, "r")
1095 for sep, fn in self.arcfiles.items():
1096 zipopen = zipfp.open(fn, "rU")
1097 for line in self.line_gen:
1098 linedata = zipopen.readline()
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001099 self.assertEqual(linedata, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001100
1101 zipfp.close()
1102
1103 def readlinesTest(self, f, compression):
1104 self.makeTestArchive(f, compression)
1105
1106 # Read the ZIP archive
1107 zipfp = zipfile.ZipFile(f, "r")
1108 for sep, fn in self.arcfiles.items():
1109 ziplines = zipfp.open(fn, "rU").readlines()
1110 for line, zipline in zip(self.line_gen, ziplines):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001111 self.assertEqual(zipline, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001112
1113 zipfp.close()
1114
1115 def iterlinesTest(self, f, compression):
1116 self.makeTestArchive(f, compression)
1117
1118 # Read the ZIP archive
1119 zipfp = zipfile.ZipFile(f, "r")
1120 for sep, fn in self.arcfiles.items():
1121 for line, zipline in zip(self.line_gen, zipfp.open(fn, "rU")):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001122 self.assertEqual(zipline, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001123
1124 zipfp.close()
1125
1126 def testReadStored(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.readTest(f, zipfile.ZIP_STORED)
1129
1130 def testReadlineStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001131 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001132 self.readlineTest(f, zipfile.ZIP_STORED)
1133
1134 def testReadlinesStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001135 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001136 self.readlinesTest(f, zipfile.ZIP_STORED)
1137
1138 def testIterlinesStored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001139 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001140 self.iterlinesTest(f, zipfile.ZIP_STORED)
1141
1142 if zlib:
1143 def testReadDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001144 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001145 self.readTest(f, zipfile.ZIP_DEFLATED)
1146
1147 def testReadlineDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001148 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001149 self.readlineTest(f, zipfile.ZIP_DEFLATED)
1150
1151 def testReadlinesDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001152 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001153 self.readlinesTest(f, zipfile.ZIP_DEFLATED)
1154
1155 def testIterlinesDeflated(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001156 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001157 self.iterlinesTest(f, zipfile.ZIP_DEFLATED)
1158
1159 def tearDown(self):
1160 for sep, fn in self.arcfiles.items():
1161 os.remove(fn)
1162 support.unlink(TESTFN)
1163 support.unlink(TESTFN2)
1164
1165
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001166def test_main():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001167 run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
1168 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
Martin v. Löwis59e47792009-01-24 14:10:07 +00001169 TestWithDirectory,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001170 UniversalNewlineTests, TestsWithRandomBinaryFiles)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001171
1172if __name__ == "__main__":
1173 test_main()