blob: 8e2cf553e7e430a9189d427d5c0b9b55ddeae886 [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
Ronald Oussorenee5c8852010-02-07 20:24:02 +0000410 def test_writestr_compression(self):
411 zipfp = zipfile.ZipFile(TESTFN2, "w")
412 zipfp.writestr("a.txt", "hello world", compress_type=zipfile.ZIP_STORED)
413 if zlib:
414 zipfp.writestr("b.txt", "hello world", compress_type=zipfile.ZIP_DEFLATED)
415
416 info = zipfp.getinfo('a.txt')
417 self.assertEqual(info.compress_type, zipfile.ZIP_STORED)
418
419 if zlib:
420 info = zipfp.getinfo('b.txt')
421 self.assertEqual(info.compress_type, zipfile.ZIP_DEFLATED)
422
423
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000424 def zip_test_writestr_permissions(self, f, compression):
425 # Make sure that writestr creates files with mode 0600,
426 # when it is passed a name rather than a ZipInfo instance.
427
Ezio Melottiafd0d112009-07-15 17:17:17 +0000428 self.make_test_archive(f, compression)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000429 with zipfile.ZipFile(f, "r") as zipfp:
430 zinfo = zipfp.getinfo('strfile')
431 self.assertEqual(zinfo.external_attr, 0o600 << 16)
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000432
Ezio Melottiafd0d112009-07-15 17:17:17 +0000433 def test_writestr_permissions(self):
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000434 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
435 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
436
Gregory P. Smithb0d9ca92009-07-07 05:06:04 +0000437 def test_writestr_extended_local_header_issue1202(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000438 with zipfile.ZipFile(TESTFN2, 'w') as orig_zip:
439 for data in 'abcdefghijklmnop':
440 zinfo = zipfile.ZipInfo(data)
441 zinfo.flag_bits |= 0x08 # Include an extended local header.
442 orig_zip.writestr(zinfo, data)
443
444 def test_close(self):
445 """Check that the zipfile is closed after the 'with' block."""
446 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
447 for fpath, fdata in SMALL_TEST_DATA:
448 zipfp.writestr(fpath, fdata)
449 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
450 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
451
452 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
453 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
454 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
455
456 def test_close_on_exception(self):
457 """Check that the zipfile is closed if an exception is raised in the
458 'with' block."""
459 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
460 for fpath, fdata in SMALL_TEST_DATA:
461 zipfp.writestr(fpath, fdata)
462
463 try:
464 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
465 raise zipfile.BadZipfile()
466 except zipfile.BadZipfile:
467 self.assertTrue(zipfp2.fp is None, 'zipfp is not closed')
Gregory P. Smithb0d9ca92009-07-07 05:06:04 +0000468
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000469 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +0000470 unlink(TESTFN)
471 unlink(TESTFN2)
472
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000473
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000474class TestZip64InSmallFiles(unittest.TestCase):
475 # These tests test the ZIP64 functionality without using large files,
476 # see test_zipfile64 for proper tests.
477
478 def setUp(self):
479 self._limit = zipfile.ZIP64_LIMIT
480 zipfile.ZIP64_LIMIT = 5
481
Guido van Rossum9c627722007-08-27 18:31:48 +0000482 line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000483 for i in range(0, FIXEDTEST_SIZE))
484 self.data = b'\n'.join(line_gen)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000485
486 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +0000487 with open(TESTFN, "wb") as fp:
488 fp.write(self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000489
Ezio Melottiafd0d112009-07-15 17:17:17 +0000490 def large_file_exception_test(self, f, compression):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000491 with zipfile.ZipFile(f, "w", compression) as zipfp:
492 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti35386712009-12-31 13:22:41 +0000493 zipfp.write, TESTFN, "another.name")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000494
Ezio Melottiafd0d112009-07-15 17:17:17 +0000495 def large_file_exception_test2(self, f, compression):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000496 with zipfile.ZipFile(f, "w", compression) as zipfp:
497 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti35386712009-12-31 13:22:41 +0000498 zipfp.writestr, "another.name", self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000499
Ezio Melottiafd0d112009-07-15 17:17:17 +0000500 def test_large_file_exception(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000501 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000502 self.large_file_exception_test(f, zipfile.ZIP_STORED)
503 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000504
Ezio Melottiafd0d112009-07-15 17:17:17 +0000505 def zip_test(self, f, compression):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000506 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000507 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
508 zipfp.write(TESTFN, "another.name")
509 zipfp.write(TESTFN, TESTFN)
510 zipfp.writestr("strfile", self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000511
512 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000513 with zipfile.ZipFile(f, "r", compression) as zipfp:
514 self.assertEqual(zipfp.read(TESTFN), self.data)
515 self.assertEqual(zipfp.read("another.name"), self.data)
516 self.assertEqual(zipfp.read("strfile"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000517
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000518 # Print the ZIP directory
519 fp = io.StringIO()
520 zipfp.printdir(fp)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000521
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000522 directory = fp.getvalue()
523 lines = directory.splitlines()
Ezio Melotti35386712009-12-31 13:22:41 +0000524 self.assertEqual(len(lines), 4) # Number of files + header
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000525
Benjamin Peterson577473f2010-01-19 00:09:57 +0000526 self.assertIn('File Name', lines[0])
527 self.assertIn('Modified', lines[0])
528 self.assertIn('Size', lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000529
Ezio Melotti35386712009-12-31 13:22:41 +0000530 fn, date, time_, size = lines[1].split()
531 self.assertEqual(fn, 'another.name')
532 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
533 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
534 self.assertEqual(size, str(len(self.data)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000535
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000536 # Check the namelist
537 names = zipfp.namelist()
Ezio Melotti35386712009-12-31 13:22:41 +0000538 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000539 self.assertIn(TESTFN, names)
540 self.assertIn("another.name", names)
541 self.assertIn("strfile", names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000542
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000543 # Check infolist
544 infos = zipfp.infolist()
Ezio Melotti35386712009-12-31 13:22:41 +0000545 names = [i.filename for i in infos]
546 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000547 self.assertIn(TESTFN, names)
548 self.assertIn("another.name", names)
549 self.assertIn("strfile", names)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000550 for i in infos:
Ezio Melotti35386712009-12-31 13:22:41 +0000551 self.assertEqual(i.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000552
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000553 # check getinfo
554 for nm in (TESTFN, "another.name", "strfile"):
555 info = zipfp.getinfo(nm)
Ezio Melotti35386712009-12-31 13:22:41 +0000556 self.assertEqual(info.filename, nm)
557 self.assertEqual(info.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000558
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000559 # Check that testzip doesn't raise an exception
560 zipfp.testzip()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000561
Ezio Melottiafd0d112009-07-15 17:17:17 +0000562 def test_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000563 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000564 self.zip_test(f, zipfile.ZIP_STORED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000565
Ezio Melotti76430242009-07-11 18:28:48 +0000566 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000567 def test_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +0000568 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000569 self.zip_test(f, zipfile.ZIP_DEFLATED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000570
Ezio Melottiafd0d112009-07-15 17:17:17 +0000571 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000572 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
573 allowZip64=True) as zipfp:
574 zipfp.write(TESTFN, "/absolute")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000575
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000576 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
577 self.assertEqual(zipfp.namelist(), ["absolute"])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000578
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000579 def tearDown(self):
580 zipfile.ZIP64_LIMIT = self._limit
Ezio Melotti76430242009-07-11 18:28:48 +0000581 unlink(TESTFN)
582 unlink(TESTFN2)
583
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000584
585class PyZipFileTests(unittest.TestCase):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000586 def test_write_pyfile(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000587 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
588 fn = __file__
589 if fn.endswith('.pyc') or fn.endswith('.pyo'):
590 fn = fn[:-1]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000591
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000592 zipfp.writepy(fn)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000593
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000594 bn = os.path.basename(fn)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000595 self.assertNotIn(bn, zipfp.namelist())
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000596 self.assertTrue(bn + 'o' in zipfp.namelist() or
597 bn + 'c' in zipfp.namelist())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000598
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000599 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
600 fn = __file__
Ezio Melotti35386712009-12-31 13:22:41 +0000601 if fn.endswith(('.pyc', '.pyo')):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000602 fn = fn[:-1]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000603
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000604 zipfp.writepy(fn, "testpackage")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000605
Ezio Melotti35386712009-12-31 13:22:41 +0000606 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000607 self.assertNotIn(bn, zipfp.namelist())
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000608 self.assertTrue(bn + 'o' in zipfp.namelist() or
609 bn + 'c' in zipfp.namelist())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000610
Ezio Melottiafd0d112009-07-15 17:17:17 +0000611 def test_write_python_package(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000612 import email
613 packagedir = os.path.dirname(email.__file__)
614
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000615 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
616 zipfp.writepy(packagedir)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000617
Ezio Melotti35386712009-12-31 13:22:41 +0000618 # Check for a couple of modules at different levels of the
619 # hierarchy
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000620 names = zipfp.namelist()
621 self.assertTrue('email/__init__.pyo' in names or
622 'email/__init__.pyc' in names)
623 self.assertTrue('email/mime/text.pyo' in names or
624 'email/mime/text.pyc' in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000625
Ezio Melottiafd0d112009-07-15 17:17:17 +0000626 def test_write_python_directory(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000627 os.mkdir(TESTFN2)
628 try:
Ezio Melotti35386712009-12-31 13:22:41 +0000629 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
630 fp.write("print(42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000631
Ezio Melotti35386712009-12-31 13:22:41 +0000632 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
633 fp.write("print(42 * 42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000634
Ezio Melotti35386712009-12-31 13:22:41 +0000635 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
636 fp.write("bla bla bla\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000637
638 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
639 zipfp.writepy(TESTFN2)
640
641 names = zipfp.namelist()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000642 self.assertTrue('mod1.pyc' in names or 'mod1.pyo' in names)
643 self.assertTrue('mod2.pyc' in names or 'mod2.pyo' in names)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000644 self.assertNotIn('mod2.txt', names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000645
646 finally:
647 shutil.rmtree(TESTFN2)
648
Ezio Melottiafd0d112009-07-15 17:17:17 +0000649 def test_write_non_pyfile(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000650 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
651 open(TESTFN, 'w').write('most definitely not a python file')
652 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
653 os.remove(TESTFN)
654
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000655
656
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000657class OtherTests(unittest.TestCase):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000658 def test_unicode_filenames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000659 with zipfile.ZipFile(TESTFN, "w") as zf:
660 zf.writestr("foo.txt", "Test for unicode filename")
661 zf.writestr("\xf6.txt", "Test for unicode filename")
Ezio Melottie9615932010-01-24 19:26:24 +0000662 self.assertIsInstance(zf.infolist()[0].filename, str)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000663
664 with zipfile.ZipFile(TESTFN, "r") as zf:
665 self.assertEqual(zf.filelist[0].filename, "foo.txt")
666 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
Martin v. Löwis8570f6a2008-05-05 17:44:38 +0000667
Ezio Melottiafd0d112009-07-15 17:17:17 +0000668 def test_create_non_existent_file_for_append(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +0000669 if os.path.exists(TESTFN):
670 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000671
Thomas Wouterscf297e42007-02-23 15:07:44 +0000672 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000673 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +0000674
Thomas Wouterscf297e42007-02-23 15:07:44 +0000675 try:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000676 with zipfile.ZipFile(TESTFN, 'a') as zf:
677 zf.writestr(filename, content)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000678 except IOError:
679 self.fail('Could not append data to a non-existent zip file.')
680
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000681 self.assertTrue(os.path.exists(TESTFN))
Thomas Wouterscf297e42007-02-23 15:07:44 +0000682
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000683 with zipfile.ZipFile(TESTFN, 'r') as zf:
684 self.assertEqual(zf.read(filename), content)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000685
Ezio Melottiafd0d112009-07-15 17:17:17 +0000686 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000687 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti35386712009-12-31 13:22:41 +0000688 # it opens if there's an error in the file. If it doesn't, the
689 # traceback holds a reference to the ZipFile object and, indirectly,
690 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000691 # On Windows, this causes the os.unlink() call to fail because the
692 # underlying file is still open. This is SF bug #412214.
693 #
Ezio Melotti35386712009-12-31 13:22:41 +0000694 with open(TESTFN, "w") as fp:
695 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000696 try:
697 zf = zipfile.ZipFile(TESTFN)
698 except zipfile.BadZipfile:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000699 pass
700
Ezio Melottiafd0d112009-07-15 17:17:17 +0000701 def test_is_zip_erroneous_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000702 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000703 # - passing a filename
704 with open(TESTFN, "w") as fp:
705 fp.write("this is not a legal zip file\n")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000706 chk = zipfile.is_zipfile(TESTFN)
Ezio Melotti35386712009-12-31 13:22:41 +0000707 self.assertFalse(chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000708 # - passing a file object
709 with open(TESTFN, "rb") as fp:
710 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000711 self.assertTrue(not chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000712 # - passing a file-like object
713 fp = io.BytesIO()
714 fp.write(b"this is not a legal zip file\n")
715 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000716 self.assertTrue(not chk)
Ezio Melotti35386712009-12-31 13:22:41 +0000717 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000718 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000719 self.assertTrue(not chk)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000720
Ezio Melottiafd0d112009-07-15 17:17:17 +0000721 def test_is_zip_valid_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000722 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000723 # - passing a filename
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000724 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
725 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
726
Guido van Rossumd8faa362007-04-27 19:54:29 +0000727 chk = zipfile.is_zipfile(TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000728 self.assertTrue(chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000729 # - passing a file object
730 with open(TESTFN, "rb") as fp:
731 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000732 self.assertTrue(chk)
Ezio Melotti35386712009-12-31 13:22:41 +0000733 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000734 zip_contents = fp.read()
735 # - passing a file-like object
736 fp = io.BytesIO()
737 fp.write(zip_contents)
738 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000739 self.assertTrue(chk)
Ezio Melotti35386712009-12-31 13:22:41 +0000740 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000741 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000742 self.assertTrue(chk)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000743
Ezio Melottiafd0d112009-07-15 17:17:17 +0000744 def test_non_existent_file_raises_IOError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000745 # make sure we don't raise an AttributeError when a partially-constructed
746 # ZipFile instance is finalized; this tests for regression on SF tracker
747 # bug #403871.
748
749 # The bug we're testing for caused an AttributeError to be raised
750 # when a ZipFile instance was created for a file that did not
751 # exist; the .fp member was not initialized but was needed by the
752 # __del__() method. Since the AttributeError is in the __del__(),
753 # it is ignored, but the user should be sufficiently annoyed by
754 # the message on the output that regression will be noticed
755 # quickly.
756 self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
757
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +0000758 def test_empty_file_raises_BadZipFile(self):
759 f = open(TESTFN, 'w')
760 f.close()
761 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN)
762
Ezio Melotti35386712009-12-31 13:22:41 +0000763 with open(TESTFN, 'w') as fp:
764 fp.write("short file")
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +0000765 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN)
766
Ezio Melottiafd0d112009-07-15 17:17:17 +0000767 def test_closed_zip_raises_RuntimeError(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000768 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000769 data = io.BytesIO()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000770 with zipfile.ZipFile(data, mode="w") as zipf:
771 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000772
773 # This is correct; calling .read on a closed ZipFile should throw
774 # a RuntimeError, and so should calling .testzip. An earlier
775 # version of .testzip would swallow this exception (and any other)
776 # and report that the first file in the archive was corrupt.
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000777 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
778 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000779 self.assertRaises(RuntimeError, zipf.testzip)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000780 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Guido van Rossum814661e2007-07-18 22:07:29 +0000781 open(TESTFN, 'w').write('zipfile test data')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000782 self.assertRaises(RuntimeError, zipf.write, TESTFN)
783
Ezio Melottiafd0d112009-07-15 17:17:17 +0000784 def test_bad_constructor_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000785 """Check that bad modes passed to ZipFile constructor are caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000786 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
787
Ezio Melottiafd0d112009-07-15 17:17:17 +0000788 def test_bad_open_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000789 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000790 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
791 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
792
793 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000794 # read the data to make sure the file is there
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000795 zipf.read("foo.txt")
796 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000797
Ezio Melottiafd0d112009-07-15 17:17:17 +0000798 def test_read0(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000799 """Check that calling read(0) on a ZipExtFile object returns an empty
800 string and doesn't advance file pointer."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000801 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
802 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
803 # read the data to make sure the file is there
804 f = zipf.open("foo.txt")
805 for i in range(FIXEDTEST_SIZE):
806 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000807
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000808 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000809
Ezio Melottiafd0d112009-07-15 17:17:17 +0000810 def test_open_non_existent_item(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000811 """Check that attempting to call open() for an item that doesn't
812 exist in the archive raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000813 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
814 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000815
Ezio Melottiafd0d112009-07-15 17:17:17 +0000816 def test_bad_compression_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000817 """Check that bad compression methods passed to ZipFile.open are
818 caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000819 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
820
Ezio Melottiafd0d112009-07-15 17:17:17 +0000821 def test_null_byte_in_filename(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000822 """Check that a filename containing a null byte is properly
823 terminated."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000824 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
825 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
826 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000827
Ezio Melottiafd0d112009-07-15 17:17:17 +0000828 def test_struct_sizes(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000829 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000830 self.assertEqual(zipfile.sizeEndCentDir, 22)
831 self.assertEqual(zipfile.sizeCentralDir, 46)
832 self.assertEqual(zipfile.sizeEndCentDir64, 56)
833 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
834
Ezio Melottiafd0d112009-07-15 17:17:17 +0000835 def test_comments(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000836 """Check that comments on the archive are handled properly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000837
838 # check default comment is empty
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000839 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
840 self.assertEqual(zipf.comment, b'')
841 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
842
843 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
844 self.assertEqual(zipfr.comment, b'')
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000845
846 # check a simple short comment
847 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000848 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
849 zipf.comment = comment
850 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
851 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
852 self.assertEqual(zipf.comment, comment)
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000853
854 # check a comment of max length
855 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
856 comment2 = comment2.encode("ascii")
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000857 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
858 zipf.comment = comment2
859 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
860
861 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
862 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000863
864 # check a comment that is too long is truncated
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000865 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
866 zipf.comment = comment2 + b'oops'
867 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
868 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
869 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000870
Guido van Rossumd8faa362007-04-27 19:54:29 +0000871 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +0000872 unlink(TESTFN)
873 unlink(TESTFN2)
874
Thomas Wouterscf297e42007-02-23 15:07:44 +0000875
876class DecryptionTests(unittest.TestCase):
Ezio Melotti35386712009-12-31 13:22:41 +0000877 """Check that ZIP decryption works. Since the library does not
878 support encryption at the moment, we use a pre-generated encrypted
879 ZIP file."""
Thomas Wouterscf297e42007-02-23 15:07:44 +0000880
881 data = (
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000882 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
883 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
884 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
885 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
886 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
887 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
888 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +0000889 data2 = (
890 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
891 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
892 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
893 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
894 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
895 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
896 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
897 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +0000898
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000899 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +0000900 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +0000901
902 def setUp(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000903 with open(TESTFN, "wb") as fp:
904 fp.write(self.data)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000905 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti35386712009-12-31 13:22:41 +0000906 with open(TESTFN2, "wb") as fp:
907 fp.write(self.data2)
Christian Heimesfdab48e2008-01-20 09:06:41 +0000908 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000909
910 def tearDown(self):
911 self.zip.close()
912 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +0000913 self.zip2.close()
914 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000915
Ezio Melottiafd0d112009-07-15 17:17:17 +0000916 def test_no_password(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +0000917 # Reading the encrypted file without password
918 # must generate a RunTime exception
919 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000920 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000921
Ezio Melottiafd0d112009-07-15 17:17:17 +0000922 def test_bad_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000923 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +0000924 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000925 self.zip2.setpassword(b"perl")
926 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000927
Ezio Melotti78ea2022009-09-12 18:41:20 +0000928 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000929 def test_good_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000930 self.zip.setpassword(b"python")
Ezio Melotti35386712009-12-31 13:22:41 +0000931 self.assertEqual(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +0000932 self.zip2.setpassword(b"12345")
Ezio Melotti35386712009-12-31 13:22:41 +0000933 self.assertEqual(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000934
Guido van Rossumd8faa362007-04-27 19:54:29 +0000935
936class TestsWithRandomBinaryFiles(unittest.TestCase):
937 def setUp(self):
938 datacount = randint(16, 64)*1024 + randint(1, 1024)
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000939 self.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
940 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000941
942 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +0000943 with open(TESTFN, "wb") as fp:
944 fp.write(self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000945
946 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +0000947 unlink(TESTFN)
948 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000949
Ezio Melottiafd0d112009-07-15 17:17:17 +0000950 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000951 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000952 with zipfile.ZipFile(f, "w", compression) as zipfp:
953 zipfp.write(TESTFN, "another.name")
954 zipfp.write(TESTFN, TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000955
Ezio Melottiafd0d112009-07-15 17:17:17 +0000956 def zip_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 testdata = zipfp.read(TESTFN)
962 self.assertEqual(len(testdata), len(self.data))
963 self.assertEqual(testdata, self.data)
964 self.assertEqual(zipfp.read("another.name"), self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000965
Ezio Melottiafd0d112009-07-15 17:17:17 +0000966 def test_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000967 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000968 self.zip_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000969
Ezio Melottiafd0d112009-07-15 17:17:17 +0000970 def zip_open_test(self, f, compression):
971 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000972
973 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000974 with zipfile.ZipFile(f, "r", compression) as zipfp:
975 zipdata1 = []
976 zipopen1 = zipfp.open(TESTFN)
977 while True:
978 read_data = zipopen1.read(256)
979 if not read_data:
980 break
981 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000982
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000983 zipdata2 = []
984 zipopen2 = zipfp.open("another.name")
985 while True:
986 read_data = zipopen2.read(256)
987 if not read_data:
988 break
989 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000990
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000991 testdata1 = b''.join(zipdata1)
992 self.assertEqual(len(testdata1), len(self.data))
993 self.assertEqual(testdata1, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000994
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000995 testdata2 = b''.join(zipdata2)
Ezio Melotti35386712009-12-31 13:22:41 +0000996 self.assertEqual(len(testdata2), len(self.data))
997 self.assertEqual(testdata2, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000998
Ezio Melottiafd0d112009-07-15 17:17:17 +0000999 def test_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001000 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001001 self.zip_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001002
Ezio Melottiafd0d112009-07-15 17:17:17 +00001003 def zip_random_open_test(self, f, compression):
1004 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001005
1006 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001007 with zipfile.ZipFile(f, "r", compression) as zipfp:
1008 zipdata1 = []
1009 zipopen1 = zipfp.open(TESTFN)
1010 while True:
1011 read_data = zipopen1.read(randint(1, 1024))
1012 if not read_data:
1013 break
1014 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001015
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001016 testdata = b''.join(zipdata1)
1017 self.assertEqual(len(testdata), len(self.data))
1018 self.assertEqual(testdata, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001019
Ezio Melottiafd0d112009-07-15 17:17:17 +00001020 def test_random_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001021 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001022 self.zip_random_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001023
Ezio Melotti76430242009-07-11 18:28:48 +00001024
Ezio Melotti78ea2022009-09-12 18:41:20 +00001025@skipUnless(zlib, "requires zlib")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001026class TestsWithMultipleOpens(unittest.TestCase):
1027 def setUp(self):
1028 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001029 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
1030 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
1031 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001032
Ezio Melottiafd0d112009-07-15 17:17:17 +00001033 def test_same_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001034 # Verify that (when the ZipFile is in control of creating file objects)
1035 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001036 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
1037 zopen1 = zipf.open('ones')
1038 zopen2 = zipf.open('ones')
1039 data1 = zopen1.read(500)
1040 data2 = zopen2.read(500)
1041 data1 += zopen1.read(500)
1042 data2 += zopen2.read(500)
1043 self.assertEqual(data1, data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001044
Ezio Melottiafd0d112009-07-15 17:17:17 +00001045 def test_different_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001046 # Verify that (when the ZipFile is in control of creating file objects)
1047 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001048 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
1049 zopen1 = zipf.open('ones')
1050 zopen2 = zipf.open('twos')
1051 data1 = zopen1.read(500)
1052 data2 = zopen2.read(500)
1053 data1 += zopen1.read(500)
1054 data2 += zopen2.read(500)
1055 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
1056 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001057
Ezio Melottiafd0d112009-07-15 17:17:17 +00001058 def test_interleaved(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001059 # Verify that (when the ZipFile is in control of creating file objects)
1060 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001061 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
1062 zopen1 = zipf.open('ones')
1063 data1 = zopen1.read(500)
1064 zopen2 = zipf.open('twos')
1065 data2 = zopen2.read(500)
1066 data1 += zopen1.read(500)
1067 data2 += zopen2.read(500)
1068 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
1069 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001070
1071 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001072 unlink(TESTFN2)
1073
Guido van Rossumd8faa362007-04-27 19:54:29 +00001074
Martin v. Löwis59e47792009-01-24 14:10:07 +00001075class TestWithDirectory(unittest.TestCase):
1076 def setUp(self):
1077 os.mkdir(TESTFN2)
1078
Ezio Melottiafd0d112009-07-15 17:17:17 +00001079 def test_extract_dir(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001080 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
1081 zipf.extractall(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001082 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1083 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1084 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1085
Ezio Melottiafd0d112009-07-15 17:17:17 +00001086 def test_bug_6050(self):
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001087 # Extraction should succeed if directories already exist
1088 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottiafd0d112009-07-15 17:17:17 +00001089 self.test_extract_dir()
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001090
Ezio Melottiafd0d112009-07-15 17:17:17 +00001091 def test_store_dir(self):
Martin v. Löwis59e47792009-01-24 14:10:07 +00001092 os.mkdir(os.path.join(TESTFN2, "x"))
1093 zipf = zipfile.ZipFile(TESTFN, "w")
1094 zipf.write(os.path.join(TESTFN2, "x"), "x")
1095 self.assertTrue(zipf.filelist[0].filename.endswith("x/"))
1096
1097 def tearDown(self):
1098 shutil.rmtree(TESTFN2)
1099 if os.path.exists(TESTFN):
Ezio Melotti76430242009-07-11 18:28:48 +00001100 unlink(TESTFN)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001101
Guido van Rossumd8faa362007-04-27 19:54:29 +00001102
1103class UniversalNewlineTests(unittest.TestCase):
1104 def setUp(self):
Guido van Rossum9c627722007-08-27 18:31:48 +00001105 self.line_gen = [bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001106 for i in range(FIXEDTEST_SIZE)]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001107 self.seps = ('\r', '\r\n', '\n')
1108 self.arcdata, self.arcfiles = {}, {}
1109 for n, s in enumerate(self.seps):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001110 b = s.encode("ascii")
1111 self.arcdata[s] = b.join(self.line_gen) + b
Guido van Rossumd8faa362007-04-27 19:54:29 +00001112 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001113 f = open(self.arcfiles[s], "wb")
1114 try:
1115 f.write(self.arcdata[s])
1116 finally:
1117 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001118
Ezio Melottiafd0d112009-07-15 17:17:17 +00001119 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001120 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001121 with zipfile.ZipFile(f, "w", compression) as zipfp:
1122 for fn in self.arcfiles.values():
1123 zipfp.write(fn, fn)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001124
Ezio Melottiafd0d112009-07-15 17:17:17 +00001125 def read_test(self, f, compression):
1126 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001127
1128 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001129 with zipfile.ZipFile(f, "r") as zipfp:
1130 for sep, fn in self.arcfiles.items():
1131 zipdata = zipfp.open(fn, "rU").read()
1132 self.assertEqual(self.arcdata[sep], zipdata)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001133
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001134 def readline_read_test(self, f, compression):
1135 self.make_test_archive(f, compression)
1136
1137 # Read the ZIP archive
1138 zipfp = zipfile.ZipFile(f, "r")
1139 for sep, fn in self.arcfiles.items():
1140 zipopen = zipfp.open(fn, "rU")
1141 data = b''
1142 while True:
1143 read = zipopen.readline()
1144 if not read:
1145 break
1146 data += read
1147
1148 read = zipopen.read(5)
1149 if not read:
1150 break
1151 data += read
1152
1153 self.assertEqual(data, self.arcdata['\n'])
1154
1155 zipfp.close()
1156
Ezio Melottiafd0d112009-07-15 17:17:17 +00001157 def readline_test(self, f, compression):
1158 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001159
1160 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001161 with zipfile.ZipFile(f, "r") as zipfp:
1162 for sep, fn in self.arcfiles.items():
1163 zipopen = zipfp.open(fn, "rU")
1164 for line in self.line_gen:
1165 linedata = zipopen.readline()
1166 self.assertEqual(linedata, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001167
Ezio Melottiafd0d112009-07-15 17:17:17 +00001168 def readlines_test(self, f, compression):
1169 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001170
1171 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001172 with zipfile.ZipFile(f, "r") as zipfp:
1173 for sep, fn in self.arcfiles.items():
1174 ziplines = zipfp.open(fn, "rU").readlines()
1175 for line, zipline in zip(self.line_gen, ziplines):
1176 self.assertEqual(zipline, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001177
Ezio Melottiafd0d112009-07-15 17:17:17 +00001178 def iterlines_test(self, f, compression):
1179 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001180
1181 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001182 with zipfile.ZipFile(f, "r") as zipfp:
1183 for sep, fn in self.arcfiles.items():
1184 for line, zipline in zip(self.line_gen, zipfp.open(fn, "rU")):
1185 self.assertEqual(zipline, line + b'\n')
Guido van Rossumd8faa362007-04-27 19:54:29 +00001186
Ezio Melottiafd0d112009-07-15 17:17:17 +00001187 def test_read_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001188 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001189 self.read_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001190
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001191 def test_readline_read_stored(self):
1192 # Issue #7610: calls to readline() interleaved with calls to read().
1193 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1194 self.readline_read_test(f, zipfile.ZIP_STORED)
1195
Ezio Melottiafd0d112009-07-15 17:17:17 +00001196 def test_readline_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001197 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001198 self.readline_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001199
Ezio Melottiafd0d112009-07-15 17:17:17 +00001200 def test_readlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001201 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001202 self.readlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001203
Ezio Melottiafd0d112009-07-15 17:17:17 +00001204 def test_iterlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001205 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001206 self.iterlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001207
Ezio Melotti76430242009-07-11 18:28:48 +00001208 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001209 def test_read_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001210 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001211 self.read_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001212
Ezio Melotti76430242009-07-11 18:28:48 +00001213 @skipUnless(zlib, "requires zlib")
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001214 def test_readline_read_deflated(self):
1215 # Issue #7610: calls to readline() interleaved with calls to read().
1216 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1217 self.readline_read_test(f, zipfile.ZIP_DEFLATED)
1218
1219 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001220 def test_readline_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001221 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001222 self.readline_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001223
Ezio Melotti76430242009-07-11 18:28:48 +00001224 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001225 def test_readlines_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001226 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001227 self.readlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001228
Ezio Melotti76430242009-07-11 18:28:48 +00001229 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001230 def test_iterlines_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001231 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001232 self.iterlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001233
1234 def tearDown(self):
1235 for sep, fn in self.arcfiles.items():
1236 os.remove(fn)
Ezio Melotti76430242009-07-11 18:28:48 +00001237 unlink(TESTFN)
1238 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001239
1240
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001241def test_main():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001242 run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
1243 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
Ezio Melotti76430242009-07-11 18:28:48 +00001244 TestWithDirectory, UniversalNewlineTests,
1245 TestsWithRandomBinaryFiles)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001246
1247if __name__ == "__main__":
1248 test_main()