blob: 9aa11ac7c2f32f1e061c130067d5013d3d8ec2d9 [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
Ezio Melotti35386712009-12-31 13:22:41 +00009import time
Ezio Melotti74c96ec2009-07-08 22:24:06 +000010import shutil
11import struct
12import zipfile
13import unittest
14
Tim Petersa45cacf2004-08-20 03:47:14 +000015
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000016from tempfile import TemporaryFile
Guido van Rossumd8faa362007-04-27 19:54:29 +000017from random import randint, random
Ezio Melotti74c96ec2009-07-08 22:24:06 +000018from unittest import skipUnless
Tim Petersa19a1682001-03-29 04:36:09 +000019
Ezio Melotti76430242009-07-11 18:28:48 +000020from test.support import TESTFN, run_unittest, findfile, unlink
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
Ezio Melotti76430242009-07-11 18:28:48 +000031
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000032class TestsWithSourceFile(unittest.TestCase):
33 def setUp(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +000034 self.line_gen = (bytes("Zipfile test line %d. random float: %f" %
Guido van Rossum9c627722007-08-27 18:31:48 +000035 (i, random()), "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +000036 for i in range(FIXEDTEST_SIZE))
37 self.data = b'\n'.join(self.line_gen) + b'\n'
Fred Drake6e7e4852001-02-28 05:34:16 +000038
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000039 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +000040 with open(TESTFN, "wb") as fp:
41 fp.write(self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000042
Ezio Melottiafd0d112009-07-15 17:17:17 +000043 def make_test_archive(self, f, compression):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000044 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000045 with zipfile.ZipFile(f, "w", compression) as zipfp:
46 zipfp.write(TESTFN, "another.name")
47 zipfp.write(TESTFN, TESTFN)
48 zipfp.writestr("strfile", self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000049
Ezio Melottiafd0d112009-07-15 17:17:17 +000050 def zip_test(self, f, compression):
51 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +000052
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000053 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000054 with zipfile.ZipFile(f, "r", compression) as zipfp:
55 self.assertEqual(zipfp.read(TESTFN), self.data)
56 self.assertEqual(zipfp.read("another.name"), self.data)
57 self.assertEqual(zipfp.read("strfile"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000058
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000059 # Print the ZIP directory
60 fp = io.StringIO()
61 zipfp.printdir(file=fp)
62 directory = fp.getvalue()
63 lines = directory.splitlines()
Ezio Melotti35386712009-12-31 13:22:41 +000064 self.assertEqual(len(lines), 4) # Number of files + header
Thomas Wouters0e3f5912006-08-11 14:57:12 +000065
Benjamin Peterson577473f2010-01-19 00:09:57 +000066 self.assertIn('File Name', lines[0])
67 self.assertIn('Modified', lines[0])
68 self.assertIn('Size', lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +000069
Ezio Melotti35386712009-12-31 13:22:41 +000070 fn, date, time_, size = lines[1].split()
71 self.assertEqual(fn, 'another.name')
72 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
73 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
74 self.assertEqual(size, str(len(self.data)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000075
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000076 # Check the namelist
77 names = zipfp.namelist()
Ezio Melotti35386712009-12-31 13:22:41 +000078 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +000079 self.assertIn(TESTFN, names)
80 self.assertIn("another.name", names)
81 self.assertIn("strfile", names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000082
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000083 # Check infolist
84 infos = zipfp.infolist()
Ezio Melotti35386712009-12-31 13:22:41 +000085 names = [i.filename for i in infos]
86 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +000087 self.assertIn(TESTFN, names)
88 self.assertIn("another.name", names)
89 self.assertIn("strfile", names)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000090 for i in infos:
Ezio Melotti35386712009-12-31 13:22:41 +000091 self.assertEqual(i.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000092
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000093 # check getinfo
94 for nm in (TESTFN, "another.name", "strfile"):
95 info = zipfp.getinfo(nm)
Ezio Melotti35386712009-12-31 13:22:41 +000096 self.assertEqual(info.filename, nm)
97 self.assertEqual(info.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000098
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000099 # Check that testzip doesn't raise an exception
100 zipfp.testzip()
Tim Peters7d3bad62001-04-04 18:56:49 +0000101
Ezio Melottiafd0d112009-07-15 17:17:17 +0000102 def test_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000103 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000104 self.zip_test(f, zipfile.ZIP_STORED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000105
Ezio Melottiafd0d112009-07-15 17:17:17 +0000106 def zip_open_test(self, f, compression):
107 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000108
109 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000110 with zipfile.ZipFile(f, "r", compression) as zipfp:
111 zipdata1 = []
112 zipopen1 = zipfp.open(TESTFN)
113 while True:
114 read_data = zipopen1.read(256)
115 if not read_data:
116 break
117 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000118
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000119 zipdata2 = []
120 zipopen2 = zipfp.open("another.name")
121 while True:
122 read_data = zipopen2.read(256)
123 if not read_data:
124 break
125 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000126
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000127 self.assertEqual(b''.join(zipdata1), self.data)
128 self.assertEqual(b''.join(zipdata2), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000129
Ezio Melottiafd0d112009-07-15 17:17:17 +0000130 def test_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000131 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000132 self.zip_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000133
Ezio Melottiafd0d112009-07-15 17:17:17 +0000134 def test_open_via_zip_info(self):
Georg Brandlb533e262008-05-25 18:19:30 +0000135 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000136 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
137 zipfp.writestr("name", "foo")
138 zipfp.writestr("name", "bar")
Georg Brandlb533e262008-05-25 18:19:30 +0000139
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000140 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
141 infos = zipfp.infolist()
142 data = b""
143 for info in infos:
144 data += zipfp.open(info).read()
145 self.assertTrue(data == b"foobar" or data == b"barfoo")
146 data = b""
147 for info in infos:
148 data += zipfp.read(info)
149 self.assertTrue(data == b"foobar" or data == b"barfoo")
Georg Brandlb533e262008-05-25 18:19:30 +0000150
Ezio Melottiafd0d112009-07-15 17:17:17 +0000151 def zip_random_open_test(self, f, compression):
152 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000153
154 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000155 with zipfile.ZipFile(f, "r", compression) as zipfp:
156 zipdata1 = []
157 zipopen1 = zipfp.open(TESTFN)
158 while True:
159 read_data = zipopen1.read(randint(1, 1024))
160 if not read_data:
161 break
162 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000163
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000164 self.assertEqual(b''.join(zipdata1), self.data)
165
Guido van Rossumd8faa362007-04-27 19:54:29 +0000166
Ezio Melottiafd0d112009-07-15 17:17:17 +0000167 def test_random_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000168 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000169 self.zip_random_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000170
Ezio Melottiafd0d112009-07-15 17:17:17 +0000171 def zip_readline_test(self, f, compression):
172 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000173
174 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000175 with zipfile.ZipFile(f, "r") as zipfp:
176 zipopen = zipfp.open(TESTFN)
177 for line in self.line_gen:
178 linedata = zipopen.readline()
179 self.assertEqual(linedata, line + '\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000180
Ezio Melottiafd0d112009-07-15 17:17:17 +0000181 def zip_readlines_test(self, f, compression):
182 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000183
184 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000185 with zipfile.ZipFile(f, "r") as zipfp:
186 ziplines = zipfp.open(TESTFN).readlines()
187 for line, zipline in zip(self.line_gen, ziplines):
188 self.assertEqual(zipline, line + '\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000189
Ezio Melottiafd0d112009-07-15 17:17:17 +0000190 def zip_iterlines_test(self, f, compression):
191 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000192
193 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000194 with zipfile.ZipFile(f, "r") as zipfp:
195 for line, zipline in zip(self.line_gen, zipfp.open(TESTFN)):
196 self.assertEqual(zipline, line + '\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000197
Ezio Melottiafd0d112009-07-15 17:17:17 +0000198 def test_readline_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000199 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000200 self.zip_readline_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000201
Ezio Melottiafd0d112009-07-15 17:17:17 +0000202 def test_readlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000203 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000204 self.zip_readlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000205
Ezio Melottiafd0d112009-07-15 17:17:17 +0000206 def test_iterlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000207 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000208 self.zip_iterlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000209
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000210 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000211 def test_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000212 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000213 self.zip_test(f, zipfile.ZIP_DEFLATED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000214
Guido van Rossumd8faa362007-04-27 19:54:29 +0000215
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000216 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000217 def test_open_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000218 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000219 self.zip_open_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000220
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000221 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000222 def test_random_open_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000223 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000224 self.zip_random_open_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000225
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000226 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000227 def test_readline_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000228 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000229 self.zip_readline_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000230
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000231 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000232 def test_readlines_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000233 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000234 self.zip_readlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000235
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000236 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000237 def test_iterlines_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000238 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000239 self.zip_iterlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000240
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000241 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000242 def test_low_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000243 """Check for cases where compressed data is larger than original."""
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000244 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000245 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
246 zipfp.writestr("strfile", '12')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000247
248 # Get an open object for strfile
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000249 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_DEFLATED) as zipfp:
250 openobj = zipfp.open("strfile")
251 self.assertEqual(openobj.read(1), b'1')
252 self.assertEqual(openobj.read(1), b'2')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000253
Ezio Melottiafd0d112009-07-15 17:17:17 +0000254 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000255 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
256 zipfp.write(TESTFN, "/absolute")
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000257
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000258 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
259 self.assertEqual(zipfp.namelist(), ["absolute"])
Tim Peters32cbc962006-02-20 21:42:18 +0000260
Ezio Melottiafd0d112009-07-15 17:17:17 +0000261 def test_append_to_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000262 """Test appending to an existing zipfile."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000263 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
264 zipfp.write(TESTFN, TESTFN)
265
266 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
267 zipfp.writestr("strfile", self.data)
268 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000269
Ezio Melottiafd0d112009-07-15 17:17:17 +0000270 def test_append_to_non_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000271 """Test appending to an existing file that is not a zipfile."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000272 # NOTE: this test fails if len(d) < 22 because of the first
273 # line "fpin.seek(-22, 2)" in _EndRecData
Ezio Melotti35386712009-12-31 13:22:41 +0000274 data = b'I am not a ZipFile!'*10
275 with open(TESTFN2, 'wb') as f:
276 f.write(data)
277
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000278 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
279 zipfp.write(TESTFN, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000280
Ezio Melotti35386712009-12-31 13:22:41 +0000281 with open(TESTFN2, 'rb') as f:
282 f.seek(len(data))
283 with zipfile.ZipFile(f, "r") as zipfp:
284 self.assertEqual(zipfp.namelist(), [TESTFN])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000285
Ezio Melottiafd0d112009-07-15 17:17:17 +0000286 def test_write_default_name(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000287 """Check that calling ZipFile.write without arcname specified
288 produces the expected result."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000289 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
290 zipfp.write(TESTFN)
291 self.assertEqual(zipfp.read(TESTFN), open(TESTFN, "rb").read())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000292
Ezio Melotti78ea2022009-09-12 18:41:20 +0000293 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000294 def test_per_file_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000295 """Check that files within a Zip archive can have different
296 compression options."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000297 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
298 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
299 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
300 sinfo = zipfp.getinfo('storeme')
301 dinfo = zipfp.getinfo('deflateme')
302 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
303 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000304
Ezio Melottiafd0d112009-07-15 17:17:17 +0000305 def test_write_to_readonly(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000306 """Check that trying to call write() on a readonly ZipFile object
307 raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000308 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
309 zipfp.writestr("somefile.txt", "bogus")
310
311 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
312 self.assertRaises(RuntimeError, zipfp.write, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000313
Ezio Melottiafd0d112009-07-15 17:17:17 +0000314 def test_extract(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000315 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
316 for fpath, fdata in SMALL_TEST_DATA:
317 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000318
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000319 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
320 for fpath, fdata in SMALL_TEST_DATA:
321 writtenfile = zipfp.extract(fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000322
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000323 # make sure it was written to the right place
324 if os.path.isabs(fpath):
325 correctfile = os.path.join(os.getcwd(), fpath[1:])
326 else:
327 correctfile = os.path.join(os.getcwd(), fpath)
328 correctfile = os.path.normpath(correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000329
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000330 self.assertEqual(writtenfile, correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000331
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000332 # make sure correct data is in correct file
333 self.assertEqual(fdata.encode(), open(writtenfile, "rb").read())
Christian Heimes790c8232008-01-07 21:14:23 +0000334
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000335 os.remove(writtenfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000336
337 # remove the test file subdirectories
338 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
339
Ezio Melottiafd0d112009-07-15 17:17:17 +0000340 def test_extract_all(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000341 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
342 for fpath, fdata in SMALL_TEST_DATA:
343 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000344
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000345 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
346 zipfp.extractall()
347 for fpath, fdata in SMALL_TEST_DATA:
348 if os.path.isabs(fpath):
349 outfile = os.path.join(os.getcwd(), fpath[1:])
350 else:
351 outfile = os.path.join(os.getcwd(), fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000352
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000353 self.assertEqual(fdata.encode(), open(outfile, "rb").read())
Christian Heimes790c8232008-01-07 21:14:23 +0000354
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000355 os.remove(outfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000356
357 # remove the test file subdirectories
358 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
359
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000360 def zip_test_writestr_permissions(self, f, compression):
361 # Make sure that writestr creates files with mode 0600,
362 # when it is passed a name rather than a ZipInfo instance.
363
Ezio Melottiafd0d112009-07-15 17:17:17 +0000364 self.make_test_archive(f, compression)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000365 with zipfile.ZipFile(f, "r") as zipfp:
366 zinfo = zipfp.getinfo('strfile')
367 self.assertEqual(zinfo.external_attr, 0o600 << 16)
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000368
Ezio Melottiafd0d112009-07-15 17:17:17 +0000369 def test_writestr_permissions(self):
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000370 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
371 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
372
Gregory P. Smithb0d9ca92009-07-07 05:06:04 +0000373 def test_writestr_extended_local_header_issue1202(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000374 with zipfile.ZipFile(TESTFN2, 'w') as orig_zip:
375 for data in 'abcdefghijklmnop':
376 zinfo = zipfile.ZipInfo(data)
377 zinfo.flag_bits |= 0x08 # Include an extended local header.
378 orig_zip.writestr(zinfo, data)
379
380 def test_close(self):
381 """Check that the zipfile is closed after the 'with' block."""
382 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
383 for fpath, fdata in SMALL_TEST_DATA:
384 zipfp.writestr(fpath, fdata)
385 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
386 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
387
388 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
389 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
390 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
391
392 def test_close_on_exception(self):
393 """Check that the zipfile is closed if an exception is raised in the
394 'with' block."""
395 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
396 for fpath, fdata in SMALL_TEST_DATA:
397 zipfp.writestr(fpath, fdata)
398
399 try:
400 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
401 raise zipfile.BadZipfile()
402 except zipfile.BadZipfile:
403 self.assertTrue(zipfp2.fp is None, 'zipfp is not closed')
Gregory P. Smithb0d9ca92009-07-07 05:06:04 +0000404
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000405 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +0000406 unlink(TESTFN)
407 unlink(TESTFN2)
408
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
Ezio Melotti35386712009-12-31 13:22:41 +0000423 with open(TESTFN, "wb") as fp:
424 fp.write(self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000425
Ezio Melottiafd0d112009-07-15 17:17:17 +0000426 def large_file_exception_test(self, f, compression):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000427 with zipfile.ZipFile(f, "w", compression) as zipfp:
428 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti35386712009-12-31 13:22:41 +0000429 zipfp.write, TESTFN, "another.name")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000430
Ezio Melottiafd0d112009-07-15 17:17:17 +0000431 def large_file_exception_test2(self, f, compression):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000432 with zipfile.ZipFile(f, "w", compression) as zipfp:
433 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti35386712009-12-31 13:22:41 +0000434 zipfp.writestr, "another.name", self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000435
Ezio Melottiafd0d112009-07-15 17:17:17 +0000436 def test_large_file_exception(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000437 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000438 self.large_file_exception_test(f, zipfile.ZIP_STORED)
439 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000440
Ezio Melottiafd0d112009-07-15 17:17:17 +0000441 def zip_test(self, f, compression):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000442 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000443 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
444 zipfp.write(TESTFN, "another.name")
445 zipfp.write(TESTFN, TESTFN)
446 zipfp.writestr("strfile", self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000447
448 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000449 with zipfile.ZipFile(f, "r", compression) as zipfp:
450 self.assertEqual(zipfp.read(TESTFN), self.data)
451 self.assertEqual(zipfp.read("another.name"), self.data)
452 self.assertEqual(zipfp.read("strfile"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000453
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000454 # Print the ZIP directory
455 fp = io.StringIO()
456 zipfp.printdir(fp)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000457
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000458 directory = fp.getvalue()
459 lines = directory.splitlines()
Ezio Melotti35386712009-12-31 13:22:41 +0000460 self.assertEqual(len(lines), 4) # Number of files + header
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000461
Benjamin Peterson577473f2010-01-19 00:09:57 +0000462 self.assertIn('File Name', lines[0])
463 self.assertIn('Modified', lines[0])
464 self.assertIn('Size', lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000465
Ezio Melotti35386712009-12-31 13:22:41 +0000466 fn, date, time_, size = lines[1].split()
467 self.assertEqual(fn, 'another.name')
468 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
469 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
470 self.assertEqual(size, str(len(self.data)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000471
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000472 # Check the namelist
473 names = zipfp.namelist()
Ezio Melotti35386712009-12-31 13:22:41 +0000474 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000475 self.assertIn(TESTFN, names)
476 self.assertIn("another.name", names)
477 self.assertIn("strfile", names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000478
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000479 # Check infolist
480 infos = zipfp.infolist()
Ezio Melotti35386712009-12-31 13:22:41 +0000481 names = [i.filename for i in infos]
482 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000483 self.assertIn(TESTFN, names)
484 self.assertIn("another.name", names)
485 self.assertIn("strfile", names)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000486 for i in infos:
Ezio Melotti35386712009-12-31 13:22:41 +0000487 self.assertEqual(i.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000488
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000489 # check getinfo
490 for nm in (TESTFN, "another.name", "strfile"):
491 info = zipfp.getinfo(nm)
Ezio Melotti35386712009-12-31 13:22:41 +0000492 self.assertEqual(info.filename, nm)
493 self.assertEqual(info.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000494
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000495 # Check that testzip doesn't raise an exception
496 zipfp.testzip()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000497
Ezio Melottiafd0d112009-07-15 17:17:17 +0000498 def test_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000499 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000500 self.zip_test(f, zipfile.ZIP_STORED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000501
Ezio Melotti76430242009-07-11 18:28:48 +0000502 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000503 def test_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +0000504 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000505 self.zip_test(f, zipfile.ZIP_DEFLATED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000506
Ezio Melottiafd0d112009-07-15 17:17:17 +0000507 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000508 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
509 allowZip64=True) as zipfp:
510 zipfp.write(TESTFN, "/absolute")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000511
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000512 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
513 self.assertEqual(zipfp.namelist(), ["absolute"])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000514
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000515 def tearDown(self):
516 zipfile.ZIP64_LIMIT = self._limit
Ezio Melotti76430242009-07-11 18:28:48 +0000517 unlink(TESTFN)
518 unlink(TESTFN2)
519
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000520
521class PyZipFileTests(unittest.TestCase):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000522 def test_write_pyfile(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000523 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
524 fn = __file__
525 if fn.endswith('.pyc') or fn.endswith('.pyo'):
526 fn = fn[:-1]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000527
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000528 zipfp.writepy(fn)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000529
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000530 bn = os.path.basename(fn)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000531 self.assertNotIn(bn, zipfp.namelist())
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000532 self.assertTrue(bn + 'o' in zipfp.namelist() or
533 bn + 'c' in zipfp.namelist())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000534
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000535 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
536 fn = __file__
Ezio Melotti35386712009-12-31 13:22:41 +0000537 if fn.endswith(('.pyc', '.pyo')):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000538 fn = fn[:-1]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000539
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000540 zipfp.writepy(fn, "testpackage")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000541
Ezio Melotti35386712009-12-31 13:22:41 +0000542 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000543 self.assertNotIn(bn, zipfp.namelist())
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000544 self.assertTrue(bn + 'o' in zipfp.namelist() or
545 bn + 'c' in zipfp.namelist())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000546
Ezio Melottiafd0d112009-07-15 17:17:17 +0000547 def test_write_python_package(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000548 import email
549 packagedir = os.path.dirname(email.__file__)
550
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000551 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
552 zipfp.writepy(packagedir)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000553
Ezio Melotti35386712009-12-31 13:22:41 +0000554 # Check for a couple of modules at different levels of the
555 # hierarchy
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000556 names = zipfp.namelist()
557 self.assertTrue('email/__init__.pyo' in names or
558 'email/__init__.pyc' in names)
559 self.assertTrue('email/mime/text.pyo' in names or
560 'email/mime/text.pyc' in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000561
Ezio Melottiafd0d112009-07-15 17:17:17 +0000562 def test_write_python_directory(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000563 os.mkdir(TESTFN2)
564 try:
Ezio Melotti35386712009-12-31 13:22:41 +0000565 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
566 fp.write("print(42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000567
Ezio Melotti35386712009-12-31 13:22:41 +0000568 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
569 fp.write("print(42 * 42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000570
Ezio Melotti35386712009-12-31 13:22:41 +0000571 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
572 fp.write("bla bla bla\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000573
574 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
575 zipfp.writepy(TESTFN2)
576
577 names = zipfp.namelist()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000578 self.assertTrue('mod1.pyc' in names or 'mod1.pyo' in names)
579 self.assertTrue('mod2.pyc' in names or 'mod2.pyo' in names)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000580 self.assertNotIn('mod2.txt', names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000581
582 finally:
583 shutil.rmtree(TESTFN2)
584
Ezio Melottiafd0d112009-07-15 17:17:17 +0000585 def test_write_non_pyfile(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000586 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
587 open(TESTFN, 'w').write('most definitely not a python file')
588 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
589 os.remove(TESTFN)
590
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000591
592
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000593class OtherTests(unittest.TestCase):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000594 def test_unicode_filenames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000595 with zipfile.ZipFile(TESTFN, "w") as zf:
596 zf.writestr("foo.txt", "Test for unicode filename")
597 zf.writestr("\xf6.txt", "Test for unicode filename")
598
599 with zipfile.ZipFile(TESTFN, "r") as zf:
600 self.assertEqual(zf.filelist[0].filename, "foo.txt")
601 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
Martin v. Löwis8570f6a2008-05-05 17:44:38 +0000602
Ezio Melottiafd0d112009-07-15 17:17:17 +0000603 def test_create_non_existent_file_for_append(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +0000604 if os.path.exists(TESTFN):
605 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000606
Thomas Wouterscf297e42007-02-23 15:07:44 +0000607 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000608 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +0000609
Thomas Wouterscf297e42007-02-23 15:07:44 +0000610 try:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000611 with zipfile.ZipFile(TESTFN, 'a') as zf:
612 zf.writestr(filename, content)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000613 except IOError:
614 self.fail('Could not append data to a non-existent zip file.')
615
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000616 self.assertTrue(os.path.exists(TESTFN))
Thomas Wouterscf297e42007-02-23 15:07:44 +0000617
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000618 with zipfile.ZipFile(TESTFN, 'r') as zf:
619 self.assertEqual(zf.read(filename), content)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000620
Ezio Melottiafd0d112009-07-15 17:17:17 +0000621 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000622 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti35386712009-12-31 13:22:41 +0000623 # it opens if there's an error in the file. If it doesn't, the
624 # traceback holds a reference to the ZipFile object and, indirectly,
625 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000626 # On Windows, this causes the os.unlink() call to fail because the
627 # underlying file is still open. This is SF bug #412214.
628 #
Ezio Melotti35386712009-12-31 13:22:41 +0000629 with open(TESTFN, "w") as fp:
630 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000631 try:
632 zf = zipfile.ZipFile(TESTFN)
633 except zipfile.BadZipfile:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000634 pass
635
Ezio Melottiafd0d112009-07-15 17:17:17 +0000636 def test_is_zip_erroneous_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000637 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000638 # - passing a filename
639 with open(TESTFN, "w") as fp:
640 fp.write("this is not a legal zip file\n")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000641 chk = zipfile.is_zipfile(TESTFN)
Ezio Melotti35386712009-12-31 13:22:41 +0000642 self.assertFalse(chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000643 # - passing a file object
644 with open(TESTFN, "rb") as fp:
645 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000646 self.assertTrue(not chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000647 # - passing a file-like object
648 fp = io.BytesIO()
649 fp.write(b"this is not a legal zip file\n")
650 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000651 self.assertTrue(not chk)
Ezio Melotti35386712009-12-31 13:22:41 +0000652 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000653 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000654 self.assertTrue(not chk)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000655
Ezio Melottiafd0d112009-07-15 17:17:17 +0000656 def test_is_zip_valid_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000657 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000658 # - passing a filename
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000659 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
660 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
661
Guido van Rossumd8faa362007-04-27 19:54:29 +0000662 chk = zipfile.is_zipfile(TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000663 self.assertTrue(chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000664 # - passing a file object
665 with open(TESTFN, "rb") as fp:
666 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000667 self.assertTrue(chk)
Ezio Melotti35386712009-12-31 13:22:41 +0000668 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000669 zip_contents = fp.read()
670 # - passing a file-like object
671 fp = io.BytesIO()
672 fp.write(zip_contents)
673 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000674 self.assertTrue(chk)
Ezio Melotti35386712009-12-31 13:22:41 +0000675 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000676 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000677 self.assertTrue(chk)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000678
Ezio Melottiafd0d112009-07-15 17:17:17 +0000679 def test_non_existent_file_raises_IOError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000680 # make sure we don't raise an AttributeError when a partially-constructed
681 # ZipFile instance is finalized; this tests for regression on SF tracker
682 # bug #403871.
683
684 # The bug we're testing for caused an AttributeError to be raised
685 # when a ZipFile instance was created for a file that did not
686 # exist; the .fp member was not initialized but was needed by the
687 # __del__() method. Since the AttributeError is in the __del__(),
688 # it is ignored, but the user should be sufficiently annoyed by
689 # the message on the output that regression will be noticed
690 # quickly.
691 self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
692
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +0000693 def test_empty_file_raises_BadZipFile(self):
694 f = open(TESTFN, 'w')
695 f.close()
696 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN)
697
Ezio Melotti35386712009-12-31 13:22:41 +0000698 with open(TESTFN, 'w') as fp:
699 fp.write("short file")
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +0000700 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN)
701
Ezio Melottiafd0d112009-07-15 17:17:17 +0000702 def test_closed_zip_raises_RuntimeError(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000703 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000704 data = io.BytesIO()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000705 with zipfile.ZipFile(data, mode="w") as zipf:
706 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000707
708 # This is correct; calling .read on a closed ZipFile should throw
709 # a RuntimeError, and so should calling .testzip. An earlier
710 # version of .testzip would swallow this exception (and any other)
711 # and report that the first file in the archive was corrupt.
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000712 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
713 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000714 self.assertRaises(RuntimeError, zipf.testzip)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000715 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Guido van Rossum814661e2007-07-18 22:07:29 +0000716 open(TESTFN, 'w').write('zipfile test data')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000717 self.assertRaises(RuntimeError, zipf.write, TESTFN)
718
Ezio Melottiafd0d112009-07-15 17:17:17 +0000719 def test_bad_constructor_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000720 """Check that bad modes passed to ZipFile constructor are caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000721 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
722
Ezio Melottiafd0d112009-07-15 17:17:17 +0000723 def test_bad_open_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000724 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000725 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
726 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
727
728 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000729 # read the data to make sure the file is there
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000730 zipf.read("foo.txt")
731 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000732
Ezio Melottiafd0d112009-07-15 17:17:17 +0000733 def test_read0(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000734 """Check that calling read(0) on a ZipExtFile object returns an empty
735 string and doesn't advance file pointer."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000736 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
737 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
738 # read the data to make sure the file is there
739 f = zipf.open("foo.txt")
740 for i in range(FIXEDTEST_SIZE):
741 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000742
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000743 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000744
Ezio Melottiafd0d112009-07-15 17:17:17 +0000745 def test_open_non_existent_item(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000746 """Check that attempting to call open() for an item that doesn't
747 exist in the archive raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000748 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
749 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000750
Ezio Melottiafd0d112009-07-15 17:17:17 +0000751 def test_bad_compression_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000752 """Check that bad compression methods passed to ZipFile.open are
753 caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000754 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
755
Ezio Melottiafd0d112009-07-15 17:17:17 +0000756 def test_null_byte_in_filename(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000757 """Check that a filename containing a null byte is properly
758 terminated."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000759 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
760 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
761 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000762
Ezio Melottiafd0d112009-07-15 17:17:17 +0000763 def test_struct_sizes(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000764 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000765 self.assertEqual(zipfile.sizeEndCentDir, 22)
766 self.assertEqual(zipfile.sizeCentralDir, 46)
767 self.assertEqual(zipfile.sizeEndCentDir64, 56)
768 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
769
Ezio Melottiafd0d112009-07-15 17:17:17 +0000770 def test_comments(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000771 """Check that comments on the archive are handled properly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000772
773 # check default comment is empty
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000774 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
775 self.assertEqual(zipf.comment, b'')
776 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
777
778 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
779 self.assertEqual(zipfr.comment, b'')
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000780
781 # check a simple short comment
782 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000783 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
784 zipf.comment = comment
785 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
786 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
787 self.assertEqual(zipf.comment, comment)
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000788
789 # check a comment of max length
790 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
791 comment2 = comment2.encode("ascii")
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000792 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
793 zipf.comment = comment2
794 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
795
796 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
797 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000798
799 # check a comment that is too long is truncated
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000800 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
801 zipf.comment = comment2 + b'oops'
802 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
803 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
804 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000805
Guido van Rossumd8faa362007-04-27 19:54:29 +0000806 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +0000807 unlink(TESTFN)
808 unlink(TESTFN2)
809
Thomas Wouterscf297e42007-02-23 15:07:44 +0000810
811class DecryptionTests(unittest.TestCase):
Ezio Melotti35386712009-12-31 13:22:41 +0000812 """Check that ZIP decryption works. Since the library does not
813 support encryption at the moment, we use a pre-generated encrypted
814 ZIP file."""
Thomas Wouterscf297e42007-02-23 15:07:44 +0000815
816 data = (
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000817 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
818 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
819 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
820 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
821 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
822 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
823 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +0000824 data2 = (
825 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
826 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
827 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
828 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
829 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
830 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
831 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
832 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +0000833
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000834 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +0000835 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +0000836
837 def setUp(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000838 with open(TESTFN, "wb") as fp:
839 fp.write(self.data)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000840 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti35386712009-12-31 13:22:41 +0000841 with open(TESTFN2, "wb") as fp:
842 fp.write(self.data2)
Christian Heimesfdab48e2008-01-20 09:06:41 +0000843 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000844
845 def tearDown(self):
846 self.zip.close()
847 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +0000848 self.zip2.close()
849 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000850
Ezio Melottiafd0d112009-07-15 17:17:17 +0000851 def test_no_password(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +0000852 # Reading the encrypted file without password
853 # must generate a RunTime exception
854 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000855 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000856
Ezio Melottiafd0d112009-07-15 17:17:17 +0000857 def test_bad_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000858 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000859 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000860 self.zip2.setpassword(b"perl")
861 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000862
Ezio Melotti78ea2022009-09-12 18:41:20 +0000863 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000864 def test_good_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000865 self.zip.setpassword(b"python")
Ezio Melotti35386712009-12-31 13:22:41 +0000866 self.assertEqual(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +0000867 self.zip2.setpassword(b"12345")
Ezio Melotti35386712009-12-31 13:22:41 +0000868 self.assertEqual(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000869
Guido van Rossumd8faa362007-04-27 19:54:29 +0000870
871class TestsWithRandomBinaryFiles(unittest.TestCase):
872 def setUp(self):
873 datacount = randint(16, 64)*1024 + randint(1, 1024)
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000874 self.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
875 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000876
877 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +0000878 with open(TESTFN, "wb") as fp:
879 fp.write(self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000880
881 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +0000882 unlink(TESTFN)
883 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000884
Ezio Melottiafd0d112009-07-15 17:17:17 +0000885 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000886 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000887 with zipfile.ZipFile(f, "w", compression) as zipfp:
888 zipfp.write(TESTFN, "another.name")
889 zipfp.write(TESTFN, TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000890
Ezio Melottiafd0d112009-07-15 17:17:17 +0000891 def zip_test(self, f, compression):
892 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000893
894 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000895 with zipfile.ZipFile(f, "r", compression) as zipfp:
896 testdata = zipfp.read(TESTFN)
897 self.assertEqual(len(testdata), len(self.data))
898 self.assertEqual(testdata, self.data)
899 self.assertEqual(zipfp.read("another.name"), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000900
Ezio Melottiafd0d112009-07-15 17:17:17 +0000901 def test_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000902 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000903 self.zip_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000904
Ezio Melottiafd0d112009-07-15 17:17:17 +0000905 def zip_open_test(self, f, compression):
906 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000907
908 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000909 with zipfile.ZipFile(f, "r", compression) as zipfp:
910 zipdata1 = []
911 zipopen1 = zipfp.open(TESTFN)
912 while True:
913 read_data = zipopen1.read(256)
914 if not read_data:
915 break
916 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000917
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000918 zipdata2 = []
919 zipopen2 = zipfp.open("another.name")
920 while True:
921 read_data = zipopen2.read(256)
922 if not read_data:
923 break
924 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000925
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000926 testdata1 = b''.join(zipdata1)
927 self.assertEqual(len(testdata1), len(self.data))
928 self.assertEqual(testdata1, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000929
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000930 testdata2 = b''.join(zipdata2)
Ezio Melotti35386712009-12-31 13:22:41 +0000931 self.assertEqual(len(testdata2), len(self.data))
932 self.assertEqual(testdata2, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000933
Ezio Melottiafd0d112009-07-15 17:17:17 +0000934 def test_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000935 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000936 self.zip_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000937
Ezio Melottiafd0d112009-07-15 17:17:17 +0000938 def zip_random_open_test(self, f, compression):
939 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000940
941 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000942 with zipfile.ZipFile(f, "r", compression) as zipfp:
943 zipdata1 = []
944 zipopen1 = zipfp.open(TESTFN)
945 while True:
946 read_data = zipopen1.read(randint(1, 1024))
947 if not read_data:
948 break
949 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000950
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000951 testdata = b''.join(zipdata1)
952 self.assertEqual(len(testdata), len(self.data))
953 self.assertEqual(testdata, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000954
Ezio Melottiafd0d112009-07-15 17:17:17 +0000955 def test_random_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000956 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000957 self.zip_random_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000958
Ezio Melotti76430242009-07-11 18:28:48 +0000959
Ezio Melotti78ea2022009-09-12 18:41:20 +0000960@skipUnless(zlib, "requires zlib")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000961class TestsWithMultipleOpens(unittest.TestCase):
962 def setUp(self):
963 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000964 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
965 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
966 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000967
Ezio Melottiafd0d112009-07-15 17:17:17 +0000968 def test_same_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000969 # Verify that (when the ZipFile is in control of creating file objects)
970 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000971 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
972 zopen1 = zipf.open('ones')
973 zopen2 = zipf.open('ones')
974 data1 = zopen1.read(500)
975 data2 = zopen2.read(500)
976 data1 += zopen1.read(500)
977 data2 += zopen2.read(500)
978 self.assertEqual(data1, data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000979
Ezio Melottiafd0d112009-07-15 17:17:17 +0000980 def test_different_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000981 # Verify that (when the ZipFile is in control of creating file objects)
982 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000983 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
984 zopen1 = zipf.open('ones')
985 zopen2 = zipf.open('twos')
986 data1 = zopen1.read(500)
987 data2 = zopen2.read(500)
988 data1 += zopen1.read(500)
989 data2 += zopen2.read(500)
990 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
991 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000992
Ezio Melottiafd0d112009-07-15 17:17:17 +0000993 def test_interleaved(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000994 # Verify that (when the ZipFile is in control of creating file objects)
995 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000996 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
997 zopen1 = zipf.open('ones')
998 data1 = zopen1.read(500)
999 zopen2 = zipf.open('twos')
1000 data2 = zopen2.read(500)
1001 data1 += zopen1.read(500)
1002 data2 += zopen2.read(500)
1003 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
1004 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001005
1006 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001007 unlink(TESTFN2)
1008
Guido van Rossumd8faa362007-04-27 19:54:29 +00001009
Martin v. Löwis59e47792009-01-24 14:10:07 +00001010class TestWithDirectory(unittest.TestCase):
1011 def setUp(self):
1012 os.mkdir(TESTFN2)
1013
Ezio Melottiafd0d112009-07-15 17:17:17 +00001014 def test_extract_dir(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001015 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
1016 zipf.extractall(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001017 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1018 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1019 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1020
Ezio Melottiafd0d112009-07-15 17:17:17 +00001021 def test_bug_6050(self):
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001022 # Extraction should succeed if directories already exist
1023 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottiafd0d112009-07-15 17:17:17 +00001024 self.test_extract_dir()
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001025
Ezio Melottiafd0d112009-07-15 17:17:17 +00001026 def test_store_dir(self):
Martin v. Löwis59e47792009-01-24 14:10:07 +00001027 os.mkdir(os.path.join(TESTFN2, "x"))
1028 zipf = zipfile.ZipFile(TESTFN, "w")
1029 zipf.write(os.path.join(TESTFN2, "x"), "x")
1030 self.assertTrue(zipf.filelist[0].filename.endswith("x/"))
1031
1032 def tearDown(self):
1033 shutil.rmtree(TESTFN2)
1034 if os.path.exists(TESTFN):
Ezio Melotti76430242009-07-11 18:28:48 +00001035 unlink(TESTFN)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001036
Guido van Rossumd8faa362007-04-27 19:54:29 +00001037
1038class UniversalNewlineTests(unittest.TestCase):
1039 def setUp(self):
Guido van Rossum9c627722007-08-27 18:31:48 +00001040 self.line_gen = [bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001041 for i in range(FIXEDTEST_SIZE)]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001042 self.seps = ('\r', '\r\n', '\n')
1043 self.arcdata, self.arcfiles = {}, {}
1044 for n, s in enumerate(self.seps):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001045 b = s.encode("ascii")
1046 self.arcdata[s] = b.join(self.line_gen) + b
Guido van Rossumd8faa362007-04-27 19:54:29 +00001047 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001048 f = open(self.arcfiles[s], "wb")
1049 try:
1050 f.write(self.arcdata[s])
1051 finally:
1052 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001053
Ezio Melottiafd0d112009-07-15 17:17:17 +00001054 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001055 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001056 with zipfile.ZipFile(f, "w", compression) as zipfp:
1057 for fn in self.arcfiles.values():
1058 zipfp.write(fn, fn)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001059
Ezio Melottiafd0d112009-07-15 17:17:17 +00001060 def read_test(self, f, compression):
1061 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001062
1063 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001064 with zipfile.ZipFile(f, "r") as zipfp:
1065 for sep, fn in self.arcfiles.items():
1066 zipdata = zipfp.open(fn, "rU").read()
1067 self.assertEqual(self.arcdata[sep], zipdata)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001068
Ezio Melottiafd0d112009-07-15 17:17:17 +00001069 def readline_test(self, f, compression):
1070 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001071
1072 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001073 with zipfile.ZipFile(f, "r") as zipfp:
1074 for sep, fn in self.arcfiles.items():
1075 zipopen = zipfp.open(fn, "rU")
1076 for line in self.line_gen:
1077 linedata = zipopen.readline()
1078 self.assertEqual(linedata, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001079
Ezio Melottiafd0d112009-07-15 17:17:17 +00001080 def readlines_test(self, f, compression):
1081 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001082
1083 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001084 with zipfile.ZipFile(f, "r") as zipfp:
1085 for sep, fn in self.arcfiles.items():
1086 ziplines = zipfp.open(fn, "rU").readlines()
1087 for line, zipline in zip(self.line_gen, ziplines):
1088 self.assertEqual(zipline, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001089
Ezio Melottiafd0d112009-07-15 17:17:17 +00001090 def iterlines_test(self, f, compression):
1091 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001092
1093 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001094 with zipfile.ZipFile(f, "r") as zipfp:
1095 for sep, fn in self.arcfiles.items():
1096 for line, zipline in zip(self.line_gen, zipfp.open(fn, "rU")):
1097 self.assertEqual(zipline, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001098
Ezio Melottiafd0d112009-07-15 17:17:17 +00001099 def test_read_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001100 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001101 self.read_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001102
Ezio Melottiafd0d112009-07-15 17:17:17 +00001103 def test_readline_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001104 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001105 self.readline_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001106
Ezio Melottiafd0d112009-07-15 17:17:17 +00001107 def test_readlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001108 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001109 self.readlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001110
Ezio Melottiafd0d112009-07-15 17:17:17 +00001111 def test_iterlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001112 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001113 self.iterlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001114
Ezio Melotti76430242009-07-11 18:28:48 +00001115 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001116 def test_read_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001117 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001118 self.read_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001119
Ezio Melotti76430242009-07-11 18:28:48 +00001120 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001121 def test_readline_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001122 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001123 self.readline_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001124
Ezio Melotti76430242009-07-11 18:28:48 +00001125 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001126 def test_readlines_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001127 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001128 self.readlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001129
Ezio Melotti76430242009-07-11 18:28:48 +00001130 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001131 def test_iterlines_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001132 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001133 self.iterlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001134
1135 def tearDown(self):
1136 for sep, fn in self.arcfiles.items():
1137 os.remove(fn)
Ezio Melotti76430242009-07-11 18:28:48 +00001138 unlink(TESTFN)
1139 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001140
1141
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001142def test_main():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001143 run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
1144 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
Ezio Melotti76430242009-07-11 18:28:48 +00001145 TestWithDirectory, UniversalNewlineTests,
1146 TestsWithRandomBinaryFiles)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001147
1148if __name__ == "__main__":
1149 test_main()