blob: a925560fef929e8023627b776c80431f54c85dbb [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
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000171 def test_univeral_readaheads(self):
172 f = io.BytesIO()
173
174 data = b'a\r\n' * 16 * 1024
175 zipfp = zipfile.ZipFile(f, 'w', zipfile.ZIP_STORED)
176 zipfp.writestr(TESTFN, data)
177 zipfp.close()
178
179 data2 = b''
180 zipfp = zipfile.ZipFile(f, 'r')
181 zipopen = zipfp.open(TESTFN, 'rU')
182 for line in zipopen:
183 data2 += line
184 zipfp.close()
185
186 self.assertEqual(data, data2.replace(b'\n', b'\r\n'))
187
188 def zip_readline_read_test(self, f, compression):
189 self.make_test_archive(f, compression)
190
191 # Read the ZIP archive
192 zipfp = zipfile.ZipFile(f, "r")
193 zipopen = zipfp.open(TESTFN)
194
195 data = b''
196 while True:
197 read = zipopen.readline()
198 if not read:
199 break
200 data += read
201
202 read = zipopen.read(100)
203 if not read:
204 break
205 data += read
206
207 self.assertEqual(data, self.data)
208 zipfp.close()
209
Ezio Melottiafd0d112009-07-15 17:17:17 +0000210 def zip_readline_test(self, f, compression):
211 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000212
213 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000214 with zipfile.ZipFile(f, "r") as zipfp:
215 zipopen = zipfp.open(TESTFN)
216 for line in self.line_gen:
217 linedata = zipopen.readline()
218 self.assertEqual(linedata, line + '\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000219
Ezio Melottiafd0d112009-07-15 17:17:17 +0000220 def zip_readlines_test(self, f, compression):
221 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000222
223 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000224 with zipfile.ZipFile(f, "r") as zipfp:
225 ziplines = zipfp.open(TESTFN).readlines()
226 for line, zipline in zip(self.line_gen, ziplines):
227 self.assertEqual(zipline, line + '\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000228
Ezio Melottiafd0d112009-07-15 17:17:17 +0000229 def zip_iterlines_test(self, f, compression):
230 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000231
232 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000233 with zipfile.ZipFile(f, "r") as zipfp:
234 for line, zipline in zip(self.line_gen, zipfp.open(TESTFN)):
235 self.assertEqual(zipline, line + '\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000236
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000237 def test_readline_read_stored(self):
238 # Issue #7610: calls to readline() interleaved with calls to read().
239 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
240 self.zip_readline_read_test(f, zipfile.ZIP_STORED)
241
Ezio Melottiafd0d112009-07-15 17:17:17 +0000242 def test_readline_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000243 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000244 self.zip_readline_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000245
Ezio Melottiafd0d112009-07-15 17:17:17 +0000246 def test_readlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000247 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000248 self.zip_readlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000249
Ezio Melottiafd0d112009-07-15 17:17:17 +0000250 def test_iterlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000251 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000252 self.zip_iterlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000253
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000254 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000255 def test_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000256 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000257 self.zip_test(f, zipfile.ZIP_DEFLATED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000258
Guido van Rossumd8faa362007-04-27 19:54:29 +0000259
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000260 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000261 def test_open_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000262 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000263 self.zip_open_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000264
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000265 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000266 def test_random_open_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000267 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000268 self.zip_random_open_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000269
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000270 @skipUnless(zlib, "requires zlib")
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000271 def test_readline_read_deflated(self):
272 # Issue #7610: calls to readline() interleaved with calls to read().
273 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
274 self.zip_readline_read_test(f, zipfile.ZIP_DEFLATED)
275
276 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000277 def test_readline_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000278 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000279 self.zip_readline_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000280
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000281 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000282 def test_readlines_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000283 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000284 self.zip_readlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000285
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000286 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000287 def test_iterlines_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000288 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000289 self.zip_iterlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000290
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000291 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000292 def test_low_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000293 """Check for cases where compressed data is larger than original."""
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000294 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000295 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
296 zipfp.writestr("strfile", '12')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000297
298 # Get an open object for strfile
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000299 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_DEFLATED) as zipfp:
300 openobj = zipfp.open("strfile")
301 self.assertEqual(openobj.read(1), b'1')
302 self.assertEqual(openobj.read(1), b'2')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000303
Ezio Melottiafd0d112009-07-15 17:17:17 +0000304 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000305 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
306 zipfp.write(TESTFN, "/absolute")
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000307
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000308 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
309 self.assertEqual(zipfp.namelist(), ["absolute"])
Tim Peters32cbc962006-02-20 21:42:18 +0000310
Ezio Melottiafd0d112009-07-15 17:17:17 +0000311 def test_append_to_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000312 """Test appending to an existing zipfile."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000313 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
314 zipfp.write(TESTFN, TESTFN)
315
316 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
317 zipfp.writestr("strfile", self.data)
318 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000319
Ezio Melottiafd0d112009-07-15 17:17:17 +0000320 def test_append_to_non_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000321 """Test appending to an existing file that is not a zipfile."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000322 # NOTE: this test fails if len(d) < 22 because of the first
323 # line "fpin.seek(-22, 2)" in _EndRecData
Ezio Melotti35386712009-12-31 13:22:41 +0000324 data = b'I am not a ZipFile!'*10
325 with open(TESTFN2, 'wb') as f:
326 f.write(data)
327
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000328 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
329 zipfp.write(TESTFN, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000330
Ezio Melotti35386712009-12-31 13:22:41 +0000331 with open(TESTFN2, 'rb') as f:
332 f.seek(len(data))
333 with zipfile.ZipFile(f, "r") as zipfp:
334 self.assertEqual(zipfp.namelist(), [TESTFN])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000335
Ezio Melottiafd0d112009-07-15 17:17:17 +0000336 def test_write_default_name(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000337 """Check that calling ZipFile.write without arcname specified
338 produces the expected result."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000339 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
340 zipfp.write(TESTFN)
341 self.assertEqual(zipfp.read(TESTFN), open(TESTFN, "rb").read())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000342
Ezio Melotti78ea2022009-09-12 18:41:20 +0000343 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000344 def test_per_file_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000345 """Check that files within a Zip archive can have different
346 compression options."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000347 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
348 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
349 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
350 sinfo = zipfp.getinfo('storeme')
351 dinfo = zipfp.getinfo('deflateme')
352 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
353 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000354
Ezio Melottiafd0d112009-07-15 17:17:17 +0000355 def test_write_to_readonly(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000356 """Check that trying to call write() on a readonly ZipFile object
357 raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000358 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
359 zipfp.writestr("somefile.txt", "bogus")
360
361 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
362 self.assertRaises(RuntimeError, zipfp.write, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000363
Ezio Melottiafd0d112009-07-15 17:17:17 +0000364 def test_extract(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000365 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
366 for fpath, fdata in SMALL_TEST_DATA:
367 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000368
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000369 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
370 for fpath, fdata in SMALL_TEST_DATA:
371 writtenfile = zipfp.extract(fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000372
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000373 # make sure it was written to the right place
374 if os.path.isabs(fpath):
375 correctfile = os.path.join(os.getcwd(), fpath[1:])
376 else:
377 correctfile = os.path.join(os.getcwd(), fpath)
378 correctfile = os.path.normpath(correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000379
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000380 self.assertEqual(writtenfile, correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000381
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000382 # make sure correct data is in correct file
383 self.assertEqual(fdata.encode(), open(writtenfile, "rb").read())
Christian Heimes790c8232008-01-07 21:14:23 +0000384
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000385 os.remove(writtenfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000386
387 # remove the test file subdirectories
388 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
389
Ezio Melottiafd0d112009-07-15 17:17:17 +0000390 def test_extract_all(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000391 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
392 for fpath, fdata in SMALL_TEST_DATA:
393 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000394
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000395 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
396 zipfp.extractall()
397 for fpath, fdata in SMALL_TEST_DATA:
398 if os.path.isabs(fpath):
399 outfile = os.path.join(os.getcwd(), fpath[1:])
400 else:
401 outfile = os.path.join(os.getcwd(), fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000402
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000403 self.assertEqual(fdata.encode(), open(outfile, "rb").read())
Christian Heimes790c8232008-01-07 21:14:23 +0000404
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000405 os.remove(outfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000406
407 # remove the test file subdirectories
408 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
409
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000410 def zip_test_writestr_permissions(self, f, compression):
411 # Make sure that writestr creates files with mode 0600,
412 # when it is passed a name rather than a ZipInfo instance.
413
Ezio Melottiafd0d112009-07-15 17:17:17 +0000414 self.make_test_archive(f, compression)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000415 with zipfile.ZipFile(f, "r") as zipfp:
416 zinfo = zipfp.getinfo('strfile')
417 self.assertEqual(zinfo.external_attr, 0o600 << 16)
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000418
Ezio Melottiafd0d112009-07-15 17:17:17 +0000419 def test_writestr_permissions(self):
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000420 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
421 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
422
Gregory P. Smithb0d9ca92009-07-07 05:06:04 +0000423 def test_writestr_extended_local_header_issue1202(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000424 with zipfile.ZipFile(TESTFN2, 'w') as orig_zip:
425 for data in 'abcdefghijklmnop':
426 zinfo = zipfile.ZipInfo(data)
427 zinfo.flag_bits |= 0x08 # Include an extended local header.
428 orig_zip.writestr(zinfo, data)
429
430 def test_close(self):
431 """Check that the zipfile is closed after the 'with' block."""
432 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
433 for fpath, fdata in SMALL_TEST_DATA:
434 zipfp.writestr(fpath, fdata)
435 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
436 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
437
438 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
439 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
440 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
441
442 def test_close_on_exception(self):
443 """Check that the zipfile is closed if an exception is raised in the
444 'with' block."""
445 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
446 for fpath, fdata in SMALL_TEST_DATA:
447 zipfp.writestr(fpath, fdata)
448
449 try:
450 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
451 raise zipfile.BadZipfile()
452 except zipfile.BadZipfile:
453 self.assertTrue(zipfp2.fp is None, 'zipfp is not closed')
Gregory P. Smithb0d9ca92009-07-07 05:06:04 +0000454
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000455 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +0000456 unlink(TESTFN)
457 unlink(TESTFN2)
458
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000459
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000460class TestZip64InSmallFiles(unittest.TestCase):
461 # These tests test the ZIP64 functionality without using large files,
462 # see test_zipfile64 for proper tests.
463
464 def setUp(self):
465 self._limit = zipfile.ZIP64_LIMIT
466 zipfile.ZIP64_LIMIT = 5
467
Guido van Rossum9c627722007-08-27 18:31:48 +0000468 line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000469 for i in range(0, FIXEDTEST_SIZE))
470 self.data = b'\n'.join(line_gen)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000471
472 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +0000473 with open(TESTFN, "wb") as fp:
474 fp.write(self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000475
Ezio Melottiafd0d112009-07-15 17:17:17 +0000476 def large_file_exception_test(self, f, compression):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000477 with zipfile.ZipFile(f, "w", compression) as zipfp:
478 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti35386712009-12-31 13:22:41 +0000479 zipfp.write, TESTFN, "another.name")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000480
Ezio Melottiafd0d112009-07-15 17:17:17 +0000481 def large_file_exception_test2(self, f, compression):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000482 with zipfile.ZipFile(f, "w", compression) as zipfp:
483 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti35386712009-12-31 13:22:41 +0000484 zipfp.writestr, "another.name", self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000485
Ezio Melottiafd0d112009-07-15 17:17:17 +0000486 def test_large_file_exception(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000487 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000488 self.large_file_exception_test(f, zipfile.ZIP_STORED)
489 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000490
Ezio Melottiafd0d112009-07-15 17:17:17 +0000491 def zip_test(self, f, compression):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000492 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000493 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
494 zipfp.write(TESTFN, "another.name")
495 zipfp.write(TESTFN, TESTFN)
496 zipfp.writestr("strfile", self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000497
498 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000499 with zipfile.ZipFile(f, "r", compression) as zipfp:
500 self.assertEqual(zipfp.read(TESTFN), self.data)
501 self.assertEqual(zipfp.read("another.name"), self.data)
502 self.assertEqual(zipfp.read("strfile"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000503
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000504 # Print the ZIP directory
505 fp = io.StringIO()
506 zipfp.printdir(fp)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000507
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000508 directory = fp.getvalue()
509 lines = directory.splitlines()
Ezio Melotti35386712009-12-31 13:22:41 +0000510 self.assertEqual(len(lines), 4) # Number of files + header
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000511
Benjamin Peterson577473f2010-01-19 00:09:57 +0000512 self.assertIn('File Name', lines[0])
513 self.assertIn('Modified', lines[0])
514 self.assertIn('Size', lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000515
Ezio Melotti35386712009-12-31 13:22:41 +0000516 fn, date, time_, size = lines[1].split()
517 self.assertEqual(fn, 'another.name')
518 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
519 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
520 self.assertEqual(size, str(len(self.data)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000521
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000522 # Check the namelist
523 names = zipfp.namelist()
Ezio Melotti35386712009-12-31 13:22:41 +0000524 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000525 self.assertIn(TESTFN, names)
526 self.assertIn("another.name", names)
527 self.assertIn("strfile", names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000528
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000529 # Check infolist
530 infos = zipfp.infolist()
Ezio Melotti35386712009-12-31 13:22:41 +0000531 names = [i.filename for i in infos]
532 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000533 self.assertIn(TESTFN, names)
534 self.assertIn("another.name", names)
535 self.assertIn("strfile", names)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000536 for i in infos:
Ezio Melotti35386712009-12-31 13:22:41 +0000537 self.assertEqual(i.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000538
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000539 # check getinfo
540 for nm in (TESTFN, "another.name", "strfile"):
541 info = zipfp.getinfo(nm)
Ezio Melotti35386712009-12-31 13:22:41 +0000542 self.assertEqual(info.filename, nm)
543 self.assertEqual(info.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000544
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000545 # Check that testzip doesn't raise an exception
546 zipfp.testzip()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000547
Ezio Melottiafd0d112009-07-15 17:17:17 +0000548 def test_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000549 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000550 self.zip_test(f, zipfile.ZIP_STORED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000551
Ezio Melotti76430242009-07-11 18:28:48 +0000552 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000553 def test_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +0000554 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000555 self.zip_test(f, zipfile.ZIP_DEFLATED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000556
Ezio Melottiafd0d112009-07-15 17:17:17 +0000557 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000558 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
559 allowZip64=True) as zipfp:
560 zipfp.write(TESTFN, "/absolute")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000561
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000562 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
563 self.assertEqual(zipfp.namelist(), ["absolute"])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000564
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000565 def tearDown(self):
566 zipfile.ZIP64_LIMIT = self._limit
Ezio Melotti76430242009-07-11 18:28:48 +0000567 unlink(TESTFN)
568 unlink(TESTFN2)
569
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000570
571class PyZipFileTests(unittest.TestCase):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000572 def test_write_pyfile(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000573 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
574 fn = __file__
575 if fn.endswith('.pyc') or fn.endswith('.pyo'):
576 fn = fn[:-1]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000577
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000578 zipfp.writepy(fn)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000579
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000580 bn = os.path.basename(fn)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000581 self.assertNotIn(bn, zipfp.namelist())
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000582 self.assertTrue(bn + 'o' in zipfp.namelist() or
583 bn + 'c' in zipfp.namelist())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000584
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000585 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
586 fn = __file__
Ezio Melotti35386712009-12-31 13:22:41 +0000587 if fn.endswith(('.pyc', '.pyo')):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000588 fn = fn[:-1]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000589
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000590 zipfp.writepy(fn, "testpackage")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000591
Ezio Melotti35386712009-12-31 13:22:41 +0000592 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000593 self.assertNotIn(bn, zipfp.namelist())
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000594 self.assertTrue(bn + 'o' in zipfp.namelist() or
595 bn + 'c' in zipfp.namelist())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000596
Ezio Melottiafd0d112009-07-15 17:17:17 +0000597 def test_write_python_package(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000598 import email
599 packagedir = os.path.dirname(email.__file__)
600
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000601 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
602 zipfp.writepy(packagedir)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000603
Ezio Melotti35386712009-12-31 13:22:41 +0000604 # Check for a couple of modules at different levels of the
605 # hierarchy
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000606 names = zipfp.namelist()
607 self.assertTrue('email/__init__.pyo' in names or
608 'email/__init__.pyc' in names)
609 self.assertTrue('email/mime/text.pyo' in names or
610 'email/mime/text.pyc' in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000611
Ezio Melottiafd0d112009-07-15 17:17:17 +0000612 def test_write_python_directory(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000613 os.mkdir(TESTFN2)
614 try:
Ezio Melotti35386712009-12-31 13:22:41 +0000615 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
616 fp.write("print(42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000617
Ezio Melotti35386712009-12-31 13:22:41 +0000618 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
619 fp.write("print(42 * 42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000620
Ezio Melotti35386712009-12-31 13:22:41 +0000621 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
622 fp.write("bla bla bla\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000623
624 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
625 zipfp.writepy(TESTFN2)
626
627 names = zipfp.namelist()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000628 self.assertTrue('mod1.pyc' in names or 'mod1.pyo' in names)
629 self.assertTrue('mod2.pyc' in names or 'mod2.pyo' in names)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000630 self.assertNotIn('mod2.txt', names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000631
632 finally:
633 shutil.rmtree(TESTFN2)
634
Ezio Melottiafd0d112009-07-15 17:17:17 +0000635 def test_write_non_pyfile(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000636 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
637 open(TESTFN, 'w').write('most definitely not a python file')
638 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
639 os.remove(TESTFN)
640
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000641
642
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000643class OtherTests(unittest.TestCase):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000644 def test_unicode_filenames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000645 with zipfile.ZipFile(TESTFN, "w") as zf:
646 zf.writestr("foo.txt", "Test for unicode filename")
647 zf.writestr("\xf6.txt", "Test for unicode filename")
Ezio Melottie9615932010-01-24 19:26:24 +0000648 self.assertIsInstance(zf.infolist()[0].filename, str)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000649
650 with zipfile.ZipFile(TESTFN, "r") as zf:
651 self.assertEqual(zf.filelist[0].filename, "foo.txt")
652 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
Martin v. Löwis8570f6a2008-05-05 17:44:38 +0000653
Ezio Melottiafd0d112009-07-15 17:17:17 +0000654 def test_create_non_existent_file_for_append(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +0000655 if os.path.exists(TESTFN):
656 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000657
Thomas Wouterscf297e42007-02-23 15:07:44 +0000658 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000659 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +0000660
Thomas Wouterscf297e42007-02-23 15:07:44 +0000661 try:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000662 with zipfile.ZipFile(TESTFN, 'a') as zf:
663 zf.writestr(filename, content)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000664 except IOError:
665 self.fail('Could not append data to a non-existent zip file.')
666
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000667 self.assertTrue(os.path.exists(TESTFN))
Thomas Wouterscf297e42007-02-23 15:07:44 +0000668
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000669 with zipfile.ZipFile(TESTFN, 'r') as zf:
670 self.assertEqual(zf.read(filename), content)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000671
Ezio Melottiafd0d112009-07-15 17:17:17 +0000672 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000673 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti35386712009-12-31 13:22:41 +0000674 # it opens if there's an error in the file. If it doesn't, the
675 # traceback holds a reference to the ZipFile object and, indirectly,
676 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000677 # On Windows, this causes the os.unlink() call to fail because the
678 # underlying file is still open. This is SF bug #412214.
679 #
Ezio Melotti35386712009-12-31 13:22:41 +0000680 with open(TESTFN, "w") as fp:
681 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000682 try:
683 zf = zipfile.ZipFile(TESTFN)
684 except zipfile.BadZipfile:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000685 pass
686
Ezio Melottiafd0d112009-07-15 17:17:17 +0000687 def test_is_zip_erroneous_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000688 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000689 # - passing a filename
690 with open(TESTFN, "w") as fp:
691 fp.write("this is not a legal zip file\n")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000692 chk = zipfile.is_zipfile(TESTFN)
Ezio Melotti35386712009-12-31 13:22:41 +0000693 self.assertFalse(chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000694 # - passing a file object
695 with open(TESTFN, "rb") as fp:
696 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000697 self.assertTrue(not chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000698 # - passing a file-like object
699 fp = io.BytesIO()
700 fp.write(b"this is not a legal zip file\n")
701 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000702 self.assertTrue(not chk)
Ezio Melotti35386712009-12-31 13:22:41 +0000703 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000704 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000705 self.assertTrue(not chk)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000706
Ezio Melottiafd0d112009-07-15 17:17:17 +0000707 def test_is_zip_valid_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000708 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000709 # - passing a filename
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000710 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
711 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
712
Guido van Rossumd8faa362007-04-27 19:54:29 +0000713 chk = zipfile.is_zipfile(TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000714 self.assertTrue(chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000715 # - passing a file object
716 with open(TESTFN, "rb") as fp:
717 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000718 self.assertTrue(chk)
Ezio Melotti35386712009-12-31 13:22:41 +0000719 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000720 zip_contents = fp.read()
721 # - passing a file-like object
722 fp = io.BytesIO()
723 fp.write(zip_contents)
724 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000725 self.assertTrue(chk)
Ezio Melotti35386712009-12-31 13:22:41 +0000726 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000727 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000728 self.assertTrue(chk)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000729
Ezio Melottiafd0d112009-07-15 17:17:17 +0000730 def test_non_existent_file_raises_IOError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000731 # make sure we don't raise an AttributeError when a partially-constructed
732 # ZipFile instance is finalized; this tests for regression on SF tracker
733 # bug #403871.
734
735 # The bug we're testing for caused an AttributeError to be raised
736 # when a ZipFile instance was created for a file that did not
737 # exist; the .fp member was not initialized but was needed by the
738 # __del__() method. Since the AttributeError is in the __del__(),
739 # it is ignored, but the user should be sufficiently annoyed by
740 # the message on the output that regression will be noticed
741 # quickly.
742 self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
743
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +0000744 def test_empty_file_raises_BadZipFile(self):
745 f = open(TESTFN, 'w')
746 f.close()
747 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN)
748
Ezio Melotti35386712009-12-31 13:22:41 +0000749 with open(TESTFN, 'w') as fp:
750 fp.write("short file")
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +0000751 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN)
752
Ezio Melottiafd0d112009-07-15 17:17:17 +0000753 def test_closed_zip_raises_RuntimeError(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000754 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000755 data = io.BytesIO()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000756 with zipfile.ZipFile(data, mode="w") as zipf:
757 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000758
759 # This is correct; calling .read on a closed ZipFile should throw
760 # a RuntimeError, and so should calling .testzip. An earlier
761 # version of .testzip would swallow this exception (and any other)
762 # and report that the first file in the archive was corrupt.
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000763 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
764 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000765 self.assertRaises(RuntimeError, zipf.testzip)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000766 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Guido van Rossum814661e2007-07-18 22:07:29 +0000767 open(TESTFN, 'w').write('zipfile test data')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000768 self.assertRaises(RuntimeError, zipf.write, TESTFN)
769
Ezio Melottiafd0d112009-07-15 17:17:17 +0000770 def test_bad_constructor_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000771 """Check that bad modes passed to ZipFile constructor are caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000772 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
773
Ezio Melottiafd0d112009-07-15 17:17:17 +0000774 def test_bad_open_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000775 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000776 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
777 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
778
779 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000780 # read the data to make sure the file is there
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000781 zipf.read("foo.txt")
782 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000783
Ezio Melottiafd0d112009-07-15 17:17:17 +0000784 def test_read0(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000785 """Check that calling read(0) on a ZipExtFile object returns an empty
786 string and doesn't advance file pointer."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000787 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
788 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
789 # read the data to make sure the file is there
790 f = zipf.open("foo.txt")
791 for i in range(FIXEDTEST_SIZE):
792 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000793
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000794 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000795
Ezio Melottiafd0d112009-07-15 17:17:17 +0000796 def test_open_non_existent_item(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000797 """Check that attempting to call open() for an item that doesn't
798 exist in the archive raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000799 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
800 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000801
Ezio Melottiafd0d112009-07-15 17:17:17 +0000802 def test_bad_compression_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000803 """Check that bad compression methods passed to ZipFile.open are
804 caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000805 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
806
Ezio Melottiafd0d112009-07-15 17:17:17 +0000807 def test_null_byte_in_filename(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000808 """Check that a filename containing a null byte is properly
809 terminated."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000810 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
811 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
812 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000813
Ezio Melottiafd0d112009-07-15 17:17:17 +0000814 def test_struct_sizes(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000815 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000816 self.assertEqual(zipfile.sizeEndCentDir, 22)
817 self.assertEqual(zipfile.sizeCentralDir, 46)
818 self.assertEqual(zipfile.sizeEndCentDir64, 56)
819 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
820
Ezio Melottiafd0d112009-07-15 17:17:17 +0000821 def test_comments(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000822 """Check that comments on the archive are handled properly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000823
824 # check default comment is empty
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000825 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
826 self.assertEqual(zipf.comment, b'')
827 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
828
829 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
830 self.assertEqual(zipfr.comment, b'')
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000831
832 # check a simple short comment
833 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000834 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
835 zipf.comment = comment
836 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
837 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
838 self.assertEqual(zipf.comment, comment)
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000839
840 # check a comment of max length
841 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
842 comment2 = comment2.encode("ascii")
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000843 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
844 zipf.comment = comment2
845 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
846
847 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
848 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000849
850 # check a comment that is too long is truncated
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000851 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
852 zipf.comment = comment2 + b'oops'
853 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
854 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
855 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000856
Guido van Rossumd8faa362007-04-27 19:54:29 +0000857 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +0000858 unlink(TESTFN)
859 unlink(TESTFN2)
860
Thomas Wouterscf297e42007-02-23 15:07:44 +0000861
862class DecryptionTests(unittest.TestCase):
Ezio Melotti35386712009-12-31 13:22:41 +0000863 """Check that ZIP decryption works. Since the library does not
864 support encryption at the moment, we use a pre-generated encrypted
865 ZIP file."""
Thomas Wouterscf297e42007-02-23 15:07:44 +0000866
867 data = (
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000868 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
869 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
870 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
871 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
872 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
873 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
874 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +0000875 data2 = (
876 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
877 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
878 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
879 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
880 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
881 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
882 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
883 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +0000884
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000885 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +0000886 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +0000887
888 def setUp(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000889 with open(TESTFN, "wb") as fp:
890 fp.write(self.data)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000891 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti35386712009-12-31 13:22:41 +0000892 with open(TESTFN2, "wb") as fp:
893 fp.write(self.data2)
Christian Heimesfdab48e2008-01-20 09:06:41 +0000894 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000895
896 def tearDown(self):
897 self.zip.close()
898 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +0000899 self.zip2.close()
900 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000901
Ezio Melottiafd0d112009-07-15 17:17:17 +0000902 def test_no_password(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +0000903 # Reading the encrypted file without password
904 # must generate a RunTime exception
905 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000906 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000907
Ezio Melottiafd0d112009-07-15 17:17:17 +0000908 def test_bad_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000909 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000910 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000911 self.zip2.setpassword(b"perl")
912 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000913
Ezio Melotti78ea2022009-09-12 18:41:20 +0000914 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000915 def test_good_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000916 self.zip.setpassword(b"python")
Ezio Melotti35386712009-12-31 13:22:41 +0000917 self.assertEqual(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +0000918 self.zip2.setpassword(b"12345")
Ezio Melotti35386712009-12-31 13:22:41 +0000919 self.assertEqual(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000920
Guido van Rossumd8faa362007-04-27 19:54:29 +0000921
922class TestsWithRandomBinaryFiles(unittest.TestCase):
923 def setUp(self):
924 datacount = randint(16, 64)*1024 + randint(1, 1024)
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000925 self.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
926 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000927
928 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +0000929 with open(TESTFN, "wb") as fp:
930 fp.write(self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000931
932 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +0000933 unlink(TESTFN)
934 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000935
Ezio Melottiafd0d112009-07-15 17:17:17 +0000936 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000937 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000938 with zipfile.ZipFile(f, "w", compression) as zipfp:
939 zipfp.write(TESTFN, "another.name")
940 zipfp.write(TESTFN, TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000941
Ezio Melottiafd0d112009-07-15 17:17:17 +0000942 def zip_test(self, f, compression):
943 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000944
945 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000946 with zipfile.ZipFile(f, "r", compression) as zipfp:
947 testdata = zipfp.read(TESTFN)
948 self.assertEqual(len(testdata), len(self.data))
949 self.assertEqual(testdata, self.data)
950 self.assertEqual(zipfp.read("another.name"), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000951
Ezio Melottiafd0d112009-07-15 17:17:17 +0000952 def test_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000953 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000954 self.zip_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000955
Ezio Melottiafd0d112009-07-15 17:17:17 +0000956 def zip_open_test(self, f, compression):
957 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000958
959 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000960 with zipfile.ZipFile(f, "r", compression) as zipfp:
961 zipdata1 = []
962 zipopen1 = zipfp.open(TESTFN)
963 while True:
964 read_data = zipopen1.read(256)
965 if not read_data:
966 break
967 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000968
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000969 zipdata2 = []
970 zipopen2 = zipfp.open("another.name")
971 while True:
972 read_data = zipopen2.read(256)
973 if not read_data:
974 break
975 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000976
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000977 testdata1 = b''.join(zipdata1)
978 self.assertEqual(len(testdata1), len(self.data))
979 self.assertEqual(testdata1, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000980
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000981 testdata2 = b''.join(zipdata2)
Ezio Melotti35386712009-12-31 13:22:41 +0000982 self.assertEqual(len(testdata2), len(self.data))
983 self.assertEqual(testdata2, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000984
Ezio Melottiafd0d112009-07-15 17:17:17 +0000985 def test_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000986 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000987 self.zip_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000988
Ezio Melottiafd0d112009-07-15 17:17:17 +0000989 def zip_random_open_test(self, f, compression):
990 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000991
992 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000993 with zipfile.ZipFile(f, "r", compression) as zipfp:
994 zipdata1 = []
995 zipopen1 = zipfp.open(TESTFN)
996 while True:
997 read_data = zipopen1.read(randint(1, 1024))
998 if not read_data:
999 break
1000 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001001
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001002 testdata = b''.join(zipdata1)
1003 self.assertEqual(len(testdata), len(self.data))
1004 self.assertEqual(testdata, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001005
Ezio Melottiafd0d112009-07-15 17:17:17 +00001006 def test_random_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001007 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001008 self.zip_random_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001009
Ezio Melotti76430242009-07-11 18:28:48 +00001010
Ezio Melotti78ea2022009-09-12 18:41:20 +00001011@skipUnless(zlib, "requires zlib")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001012class TestsWithMultipleOpens(unittest.TestCase):
1013 def setUp(self):
1014 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001015 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
1016 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
1017 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001018
Ezio Melottiafd0d112009-07-15 17:17:17 +00001019 def test_same_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001020 # Verify that (when the ZipFile is in control of creating file objects)
1021 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001022 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
1023 zopen1 = zipf.open('ones')
1024 zopen2 = zipf.open('ones')
1025 data1 = zopen1.read(500)
1026 data2 = zopen2.read(500)
1027 data1 += zopen1.read(500)
1028 data2 += zopen2.read(500)
1029 self.assertEqual(data1, data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001030
Ezio Melottiafd0d112009-07-15 17:17:17 +00001031 def test_different_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001032 # Verify that (when the ZipFile is in control of creating file objects)
1033 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001034 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
1035 zopen1 = zipf.open('ones')
1036 zopen2 = zipf.open('twos')
1037 data1 = zopen1.read(500)
1038 data2 = zopen2.read(500)
1039 data1 += zopen1.read(500)
1040 data2 += zopen2.read(500)
1041 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
1042 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001043
Ezio Melottiafd0d112009-07-15 17:17:17 +00001044 def test_interleaved(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001045 # Verify that (when the ZipFile is in control of creating file objects)
1046 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001047 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
1048 zopen1 = zipf.open('ones')
1049 data1 = zopen1.read(500)
1050 zopen2 = zipf.open('twos')
1051 data2 = zopen2.read(500)
1052 data1 += zopen1.read(500)
1053 data2 += zopen2.read(500)
1054 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
1055 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001056
1057 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001058 unlink(TESTFN2)
1059
Guido van Rossumd8faa362007-04-27 19:54:29 +00001060
Martin v. Löwis59e47792009-01-24 14:10:07 +00001061class TestWithDirectory(unittest.TestCase):
1062 def setUp(self):
1063 os.mkdir(TESTFN2)
1064
Ezio Melottiafd0d112009-07-15 17:17:17 +00001065 def test_extract_dir(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001066 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
1067 zipf.extractall(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001068 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1069 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1070 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1071
Ezio Melottiafd0d112009-07-15 17:17:17 +00001072 def test_bug_6050(self):
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001073 # Extraction should succeed if directories already exist
1074 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottiafd0d112009-07-15 17:17:17 +00001075 self.test_extract_dir()
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001076
Ezio Melottiafd0d112009-07-15 17:17:17 +00001077 def test_store_dir(self):
Martin v. Löwis59e47792009-01-24 14:10:07 +00001078 os.mkdir(os.path.join(TESTFN2, "x"))
1079 zipf = zipfile.ZipFile(TESTFN, "w")
1080 zipf.write(os.path.join(TESTFN2, "x"), "x")
1081 self.assertTrue(zipf.filelist[0].filename.endswith("x/"))
1082
1083 def tearDown(self):
1084 shutil.rmtree(TESTFN2)
1085 if os.path.exists(TESTFN):
Ezio Melotti76430242009-07-11 18:28:48 +00001086 unlink(TESTFN)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001087
Guido van Rossumd8faa362007-04-27 19:54:29 +00001088
1089class UniversalNewlineTests(unittest.TestCase):
1090 def setUp(self):
Guido van Rossum9c627722007-08-27 18:31:48 +00001091 self.line_gen = [bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001092 for i in range(FIXEDTEST_SIZE)]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001093 self.seps = ('\r', '\r\n', '\n')
1094 self.arcdata, self.arcfiles = {}, {}
1095 for n, s in enumerate(self.seps):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001096 b = s.encode("ascii")
1097 self.arcdata[s] = b.join(self.line_gen) + b
Guido van Rossumd8faa362007-04-27 19:54:29 +00001098 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001099 f = open(self.arcfiles[s], "wb")
1100 try:
1101 f.write(self.arcdata[s])
1102 finally:
1103 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001104
Ezio Melottiafd0d112009-07-15 17:17:17 +00001105 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001106 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001107 with zipfile.ZipFile(f, "w", compression) as zipfp:
1108 for fn in self.arcfiles.values():
1109 zipfp.write(fn, fn)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001110
Ezio Melottiafd0d112009-07-15 17:17:17 +00001111 def read_test(self, f, compression):
1112 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001113
1114 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001115 with zipfile.ZipFile(f, "r") as zipfp:
1116 for sep, fn in self.arcfiles.items():
1117 zipdata = zipfp.open(fn, "rU").read()
1118 self.assertEqual(self.arcdata[sep], zipdata)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001119
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001120 def readline_read_test(self, f, compression):
1121 self.make_test_archive(f, compression)
1122
1123 # Read the ZIP archive
1124 zipfp = zipfile.ZipFile(f, "r")
1125 for sep, fn in self.arcfiles.items():
1126 zipopen = zipfp.open(fn, "rU")
1127 data = b''
1128 while True:
1129 read = zipopen.readline()
1130 if not read:
1131 break
1132 data += read
1133
1134 read = zipopen.read(5)
1135 if not read:
1136 break
1137 data += read
1138
1139 self.assertEqual(data, self.arcdata['\n'])
1140
1141 zipfp.close()
1142
Ezio Melottiafd0d112009-07-15 17:17:17 +00001143 def readline_test(self, f, compression):
1144 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001145
1146 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001147 with zipfile.ZipFile(f, "r") as zipfp:
1148 for sep, fn in self.arcfiles.items():
1149 zipopen = zipfp.open(fn, "rU")
1150 for line in self.line_gen:
1151 linedata = zipopen.readline()
1152 self.assertEqual(linedata, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001153
Ezio Melottiafd0d112009-07-15 17:17:17 +00001154 def readlines_test(self, f, compression):
1155 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001156
1157 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001158 with zipfile.ZipFile(f, "r") as zipfp:
1159 for sep, fn in self.arcfiles.items():
1160 ziplines = zipfp.open(fn, "rU").readlines()
1161 for line, zipline in zip(self.line_gen, ziplines):
1162 self.assertEqual(zipline, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001163
Ezio Melottiafd0d112009-07-15 17:17:17 +00001164 def iterlines_test(self, f, compression):
1165 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001166
1167 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001168 with zipfile.ZipFile(f, "r") as zipfp:
1169 for sep, fn in self.arcfiles.items():
1170 for line, zipline in zip(self.line_gen, zipfp.open(fn, "rU")):
1171 self.assertEqual(zipline, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001172
Ezio Melottiafd0d112009-07-15 17:17:17 +00001173 def test_read_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001174 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001175 self.read_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001176
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001177 def test_readline_read_stored(self):
1178 # Issue #7610: calls to readline() interleaved with calls to read().
1179 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1180 self.readline_read_test(f, zipfile.ZIP_STORED)
1181
Ezio Melottiafd0d112009-07-15 17:17:17 +00001182 def test_readline_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001183 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001184 self.readline_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001185
Ezio Melottiafd0d112009-07-15 17:17:17 +00001186 def test_readlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001187 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001188 self.readlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001189
Ezio Melottiafd0d112009-07-15 17:17:17 +00001190 def test_iterlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001191 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001192 self.iterlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001193
Ezio Melotti76430242009-07-11 18:28:48 +00001194 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001195 def test_read_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001196 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001197 self.read_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001198
Ezio Melotti76430242009-07-11 18:28:48 +00001199 @skipUnless(zlib, "requires zlib")
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001200 def test_readline_read_deflated(self):
1201 # Issue #7610: calls to readline() interleaved with calls to read().
1202 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1203 self.readline_read_test(f, zipfile.ZIP_DEFLATED)
1204
1205 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001206 def test_readline_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001207 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001208 self.readline_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001209
Ezio Melotti76430242009-07-11 18:28:48 +00001210 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001211 def test_readlines_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001212 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001213 self.readlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001214
Ezio Melotti76430242009-07-11 18:28:48 +00001215 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001216 def test_iterlines_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001217 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001218 self.iterlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001219
1220 def tearDown(self):
1221 for sep, fn in self.arcfiles.items():
1222 os.remove(fn)
Ezio Melotti76430242009-07-11 18:28:48 +00001223 unlink(TESTFN)
1224 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001225
1226
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001227def test_main():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001228 run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
1229 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
Ezio Melotti76430242009-07-11 18:28:48 +00001230 TestWithDirectory, UniversalNewlineTests,
1231 TestsWithRandomBinaryFiles)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001232
1233if __name__ == "__main__":
1234 test_main()