blob: d67938f165f9d76a59007b603114582ef6fa2766 [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
Barry Warsaw28a691b2010-04-17 00:19:56 +00009import imp
Ezio Melotti35386712009-12-31 13:22:41 +000010import time
Ezio Melotti74c96ec2009-07-08 22:24:06 +000011import shutil
12import struct
13import zipfile
14import unittest
15
Tim Petersa45cacf2004-08-20 03:47:14 +000016
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000017from tempfile import TemporaryFile
Guido van Rossumd8faa362007-04-27 19:54:29 +000018from random import randint, random
Ezio Melotti74c96ec2009-07-08 22:24:06 +000019from unittest import skipUnless
Tim Petersa19a1682001-03-29 04:36:09 +000020
Ezio Melotti76430242009-07-11 18:28:48 +000021from test.support import TESTFN, run_unittest, findfile, unlink
Guido van Rossum368f04a2000-04-10 13:23:04 +000022
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000023TESTFN2 = TESTFN + "2"
Martin v. Löwis59e47792009-01-24 14:10:07 +000024TESTFNDIR = TESTFN + "d"
Guido van Rossumb5a755e2007-07-18 18:15:48 +000025FIXEDTEST_SIZE = 1000
Guido van Rossum368f04a2000-04-10 13:23:04 +000026
Christian Heimes790c8232008-01-07 21:14:23 +000027SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'),
28 ('ziptest2dir/_ziptest2', 'qawsedrftg'),
29 ('/ziptest2dir/ziptest3dir/_ziptest3', 'azsxdcfvgb'),
30 ('ziptest2dir/ziptest3dir/ziptest4dir/_ziptest3', '6y7u8i9o0p')]
31
Ezio Melotti76430242009-07-11 18:28:48 +000032
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000033class TestsWithSourceFile(unittest.TestCase):
34 def setUp(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +000035 self.line_gen = (bytes("Zipfile test line %d. random float: %f" %
Guido van Rossum9c627722007-08-27 18:31:48 +000036 (i, random()), "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +000037 for i in range(FIXEDTEST_SIZE))
38 self.data = b'\n'.join(self.line_gen) + b'\n'
Fred Drake6e7e4852001-02-28 05:34:16 +000039
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000040 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +000041 with open(TESTFN, "wb") as fp:
42 fp.write(self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000043
Ezio Melottiafd0d112009-07-15 17:17:17 +000044 def make_test_archive(self, f, compression):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000045 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000046 with zipfile.ZipFile(f, "w", compression) as zipfp:
47 zipfp.write(TESTFN, "another.name")
48 zipfp.write(TESTFN, TESTFN)
49 zipfp.writestr("strfile", self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000050
Ezio Melottiafd0d112009-07-15 17:17:17 +000051 def zip_test(self, f, compression):
52 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +000053
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000054 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000055 with zipfile.ZipFile(f, "r", compression) as zipfp:
56 self.assertEqual(zipfp.read(TESTFN), self.data)
57 self.assertEqual(zipfp.read("another.name"), self.data)
58 self.assertEqual(zipfp.read("strfile"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000059
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000060 # Print the ZIP directory
61 fp = io.StringIO()
62 zipfp.printdir(file=fp)
63 directory = fp.getvalue()
64 lines = directory.splitlines()
Ezio Melotti35386712009-12-31 13:22:41 +000065 self.assertEqual(len(lines), 4) # Number of files + header
Thomas Wouters0e3f5912006-08-11 14:57:12 +000066
Benjamin Peterson577473f2010-01-19 00:09:57 +000067 self.assertIn('File Name', lines[0])
68 self.assertIn('Modified', lines[0])
69 self.assertIn('Size', lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +000070
Ezio Melotti35386712009-12-31 13:22:41 +000071 fn, date, time_, size = lines[1].split()
72 self.assertEqual(fn, 'another.name')
73 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
74 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
75 self.assertEqual(size, str(len(self.data)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000076
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000077 # Check the namelist
78 names = zipfp.namelist()
Ezio Melotti35386712009-12-31 13:22:41 +000079 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +000080 self.assertIn(TESTFN, names)
81 self.assertIn("another.name", names)
82 self.assertIn("strfile", names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000083
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000084 # Check infolist
85 infos = zipfp.infolist()
Ezio Melotti35386712009-12-31 13:22:41 +000086 names = [i.filename for i in infos]
87 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +000088 self.assertIn(TESTFN, names)
89 self.assertIn("another.name", names)
90 self.assertIn("strfile", names)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000091 for i in infos:
Ezio Melotti35386712009-12-31 13:22:41 +000092 self.assertEqual(i.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000093
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000094 # check getinfo
95 for nm in (TESTFN, "another.name", "strfile"):
96 info = zipfp.getinfo(nm)
Ezio Melotti35386712009-12-31 13:22:41 +000097 self.assertEqual(info.filename, nm)
98 self.assertEqual(info.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000099
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000100 # Check that testzip doesn't raise an exception
101 zipfp.testzip()
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000102 if not isinstance(f, str):
103 f.close()
Tim Peters7d3bad62001-04-04 18:56:49 +0000104
Ezio Melottiafd0d112009-07-15 17:17:17 +0000105 def test_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000106 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000107 self.zip_test(f, zipfile.ZIP_STORED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000108
Ezio Melottiafd0d112009-07-15 17:17:17 +0000109 def zip_open_test(self, f, compression):
110 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000111
112 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000113 with zipfile.ZipFile(f, "r", compression) as zipfp:
114 zipdata1 = []
115 zipopen1 = zipfp.open(TESTFN)
116 while True:
117 read_data = zipopen1.read(256)
118 if not read_data:
119 break
120 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000121
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000122 zipdata2 = []
123 zipopen2 = zipfp.open("another.name")
124 while True:
125 read_data = zipopen2.read(256)
126 if not read_data:
127 break
128 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000129
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000130 self.assertEqual(b''.join(zipdata1), self.data)
131 self.assertEqual(b''.join(zipdata2), self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000132 if not isinstance(f, str):
133 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000134
Ezio Melottiafd0d112009-07-15 17:17:17 +0000135 def test_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000136 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000137 self.zip_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000138
Ezio Melottiafd0d112009-07-15 17:17:17 +0000139 def test_open_via_zip_info(self):
Georg Brandlb533e262008-05-25 18:19:30 +0000140 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000141 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
142 zipfp.writestr("name", "foo")
143 zipfp.writestr("name", "bar")
Georg Brandlb533e262008-05-25 18:19:30 +0000144
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000145 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
146 infos = zipfp.infolist()
147 data = b""
148 for info in infos:
149 data += zipfp.open(info).read()
150 self.assertTrue(data == b"foobar" or data == b"barfoo")
151 data = b""
152 for info in infos:
153 data += zipfp.read(info)
154 self.assertTrue(data == b"foobar" or data == b"barfoo")
Georg Brandlb533e262008-05-25 18:19:30 +0000155
Ezio Melottiafd0d112009-07-15 17:17:17 +0000156 def zip_random_open_test(self, f, compression):
157 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000158
159 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000160 with zipfile.ZipFile(f, "r", compression) as zipfp:
161 zipdata1 = []
162 zipopen1 = zipfp.open(TESTFN)
163 while True:
164 read_data = zipopen1.read(randint(1, 1024))
165 if not read_data:
166 break
167 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000168
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000169 self.assertEqual(b''.join(zipdata1), self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000170 if not isinstance(f, str):
171 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000172
Ezio Melottiafd0d112009-07-15 17:17:17 +0000173 def test_random_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000174 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000175 self.zip_random_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000176
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000177 def test_univeral_readaheads(self):
178 f = io.BytesIO()
179
180 data = b'a\r\n' * 16 * 1024
181 zipfp = zipfile.ZipFile(f, 'w', zipfile.ZIP_STORED)
182 zipfp.writestr(TESTFN, data)
183 zipfp.close()
184
185 data2 = b''
186 zipfp = zipfile.ZipFile(f, 'r')
187 zipopen = zipfp.open(TESTFN, 'rU')
188 for line in zipopen:
189 data2 += line
190 zipfp.close()
191
192 self.assertEqual(data, data2.replace(b'\n', b'\r\n'))
193
194 def zip_readline_read_test(self, f, compression):
195 self.make_test_archive(f, compression)
196
197 # Read the ZIP archive
198 zipfp = zipfile.ZipFile(f, "r")
199 zipopen = zipfp.open(TESTFN)
200
201 data = b''
202 while True:
203 read = zipopen.readline()
204 if not read:
205 break
206 data += read
207
208 read = zipopen.read(100)
209 if not read:
210 break
211 data += read
212
213 self.assertEqual(data, self.data)
214 zipfp.close()
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000215 if not isinstance(f, str):
216 f.close()
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000217
Ezio Melottiafd0d112009-07-15 17:17:17 +0000218 def zip_readline_test(self, f, compression):
219 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000220
221 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000222 with zipfile.ZipFile(f, "r") as zipfp:
223 zipopen = zipfp.open(TESTFN)
224 for line in self.line_gen:
225 linedata = zipopen.readline()
226 self.assertEqual(linedata, line + '\n')
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000227 if not isinstance(f, str):
228 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000229
Ezio Melottiafd0d112009-07-15 17:17:17 +0000230 def zip_readlines_test(self, f, compression):
231 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000232
233 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000234 with zipfile.ZipFile(f, "r") as zipfp:
235 ziplines = zipfp.open(TESTFN).readlines()
236 for line, zipline in zip(self.line_gen, ziplines):
237 self.assertEqual(zipline, line + '\n')
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000238 if not isinstance(f, str):
239 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000240
Ezio Melottiafd0d112009-07-15 17:17:17 +0000241 def zip_iterlines_test(self, f, compression):
242 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000243
244 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000245 with zipfile.ZipFile(f, "r") as zipfp:
246 for line, zipline in zip(self.line_gen, zipfp.open(TESTFN)):
247 self.assertEqual(zipline, line + '\n')
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000248 if not isinstance(f, str):
249 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000250
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000251 def test_readline_read_stored(self):
252 # Issue #7610: calls to readline() interleaved with calls to read().
253 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
254 self.zip_readline_read_test(f, zipfile.ZIP_STORED)
255
Ezio Melottiafd0d112009-07-15 17:17:17 +0000256 def test_readline_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000257 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000258 self.zip_readline_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000259
Ezio Melottiafd0d112009-07-15 17:17:17 +0000260 def test_readlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000261 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000262 self.zip_readlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000263
Ezio Melottiafd0d112009-07-15 17:17:17 +0000264 def test_iterlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000265 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000266 self.zip_iterlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000267
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000268 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000269 def test_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000270 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000271 self.zip_test(f, zipfile.ZIP_DEFLATED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000272
Guido van Rossumd8faa362007-04-27 19:54:29 +0000273
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000274 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000275 def test_open_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000276 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000277 self.zip_open_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000278
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000279 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000280 def test_random_open_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000281 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000282 self.zip_random_open_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000283
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000284 @skipUnless(zlib, "requires zlib")
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000285 def test_readline_read_deflated(self):
286 # Issue #7610: calls to readline() interleaved with calls to read().
287 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
288 self.zip_readline_read_test(f, zipfile.ZIP_DEFLATED)
289
290 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000291 def test_readline_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000292 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000293 self.zip_readline_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000294
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000295 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000296 def test_readlines_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000297 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000298 self.zip_readlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000299
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000300 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000301 def test_iterlines_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000302 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000303 self.zip_iterlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000304
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000305 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000306 def test_low_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000307 """Check for cases where compressed data is larger than original."""
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000308 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000309 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
310 zipfp.writestr("strfile", '12')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000311
312 # Get an open object for strfile
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000313 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_DEFLATED) as zipfp:
314 openobj = zipfp.open("strfile")
315 self.assertEqual(openobj.read(1), b'1')
316 self.assertEqual(openobj.read(1), b'2')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000317
Ezio Melottiafd0d112009-07-15 17:17:17 +0000318 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000319 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
320 zipfp.write(TESTFN, "/absolute")
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000321
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000322 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
323 self.assertEqual(zipfp.namelist(), ["absolute"])
Tim Peters32cbc962006-02-20 21:42:18 +0000324
Ezio Melottiafd0d112009-07-15 17:17:17 +0000325 def test_append_to_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000326 """Test appending to an existing zipfile."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000327 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
328 zipfp.write(TESTFN, TESTFN)
329
330 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
331 zipfp.writestr("strfile", self.data)
332 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000333
Ezio Melottiafd0d112009-07-15 17:17:17 +0000334 def test_append_to_non_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000335 """Test appending to an existing file that is not a zipfile."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000336 # NOTE: this test fails if len(d) < 22 because of the first
337 # line "fpin.seek(-22, 2)" in _EndRecData
Ezio Melotti35386712009-12-31 13:22:41 +0000338 data = b'I am not a ZipFile!'*10
339 with open(TESTFN2, 'wb') as f:
340 f.write(data)
341
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000342 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
343 zipfp.write(TESTFN, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000344
Ezio Melotti35386712009-12-31 13:22:41 +0000345 with open(TESTFN2, 'rb') as f:
346 f.seek(len(data))
347 with zipfile.ZipFile(f, "r") as zipfp:
348 self.assertEqual(zipfp.namelist(), [TESTFN])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000349
Ezio Melottiafd0d112009-07-15 17:17:17 +0000350 def test_write_default_name(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000351 """Check that calling ZipFile.write without arcname specified
352 produces the expected result."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000353 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
354 zipfp.write(TESTFN)
355 self.assertEqual(zipfp.read(TESTFN), open(TESTFN, "rb").read())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000356
Ezio Melotti78ea2022009-09-12 18:41:20 +0000357 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000358 def test_per_file_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000359 """Check that files within a Zip archive can have different
360 compression options."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000361 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
362 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
363 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
364 sinfo = zipfp.getinfo('storeme')
365 dinfo = zipfp.getinfo('deflateme')
366 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
367 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000368
Ezio Melottiafd0d112009-07-15 17:17:17 +0000369 def test_write_to_readonly(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000370 """Check that trying to call write() on a readonly ZipFile object
371 raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000372 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
373 zipfp.writestr("somefile.txt", "bogus")
374
375 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
376 self.assertRaises(RuntimeError, zipfp.write, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000377
Ezio Melottiafd0d112009-07-15 17:17:17 +0000378 def test_extract(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000379 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
380 for fpath, fdata in SMALL_TEST_DATA:
381 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000382
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000383 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
384 for fpath, fdata in SMALL_TEST_DATA:
385 writtenfile = zipfp.extract(fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000386
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000387 # make sure it was written to the right place
388 if os.path.isabs(fpath):
389 correctfile = os.path.join(os.getcwd(), fpath[1:])
390 else:
391 correctfile = os.path.join(os.getcwd(), fpath)
392 correctfile = os.path.normpath(correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000393
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000394 self.assertEqual(writtenfile, correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000395
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000396 # make sure correct data is in correct file
397 self.assertEqual(fdata.encode(), open(writtenfile, "rb").read())
Christian Heimes790c8232008-01-07 21:14:23 +0000398
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000399 os.remove(writtenfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000400
401 # remove the test file subdirectories
402 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
403
Ezio Melottiafd0d112009-07-15 17:17:17 +0000404 def test_extract_all(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000405 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
406 for fpath, fdata in SMALL_TEST_DATA:
407 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000408
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000409 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
410 zipfp.extractall()
411 for fpath, fdata in SMALL_TEST_DATA:
412 if os.path.isabs(fpath):
413 outfile = os.path.join(os.getcwd(), fpath[1:])
414 else:
415 outfile = os.path.join(os.getcwd(), fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000416
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000417 self.assertEqual(fdata.encode(), open(outfile, "rb").read())
Christian Heimes790c8232008-01-07 21:14:23 +0000418
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000419 os.remove(outfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000420
421 # remove the test file subdirectories
422 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
423
Ronald Oussorenee5c8852010-02-07 20:24:02 +0000424 def test_writestr_compression(self):
425 zipfp = zipfile.ZipFile(TESTFN2, "w")
426 zipfp.writestr("a.txt", "hello world", compress_type=zipfile.ZIP_STORED)
427 if zlib:
428 zipfp.writestr("b.txt", "hello world", compress_type=zipfile.ZIP_DEFLATED)
429
430 info = zipfp.getinfo('a.txt')
431 self.assertEqual(info.compress_type, zipfile.ZIP_STORED)
432
433 if zlib:
434 info = zipfp.getinfo('b.txt')
435 self.assertEqual(info.compress_type, zipfile.ZIP_DEFLATED)
436
437
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000438 def zip_test_writestr_permissions(self, f, compression):
439 # Make sure that writestr creates files with mode 0600,
440 # when it is passed a name rather than a ZipInfo instance.
441
Ezio Melottiafd0d112009-07-15 17:17:17 +0000442 self.make_test_archive(f, compression)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000443 with zipfile.ZipFile(f, "r") as zipfp:
444 zinfo = zipfp.getinfo('strfile')
445 self.assertEqual(zinfo.external_attr, 0o600 << 16)
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000446 if not isinstance(f, str):
447 f.close()
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000448
Ezio Melottiafd0d112009-07-15 17:17:17 +0000449 def test_writestr_permissions(self):
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000450 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
451 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
452
Gregory P. Smithb0d9ca92009-07-07 05:06:04 +0000453 def test_writestr_extended_local_header_issue1202(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000454 with zipfile.ZipFile(TESTFN2, 'w') as orig_zip:
455 for data in 'abcdefghijklmnop':
456 zinfo = zipfile.ZipInfo(data)
457 zinfo.flag_bits |= 0x08 # Include an extended local header.
458 orig_zip.writestr(zinfo, data)
459
460 def test_close(self):
461 """Check that the zipfile is closed after the 'with' block."""
462 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
463 for fpath, fdata in SMALL_TEST_DATA:
464 zipfp.writestr(fpath, fdata)
465 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
466 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
467
468 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
469 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
470 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
471
472 def test_close_on_exception(self):
473 """Check that the zipfile is closed if an exception is raised in the
474 'with' block."""
475 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
476 for fpath, fdata in SMALL_TEST_DATA:
477 zipfp.writestr(fpath, fdata)
478
479 try:
480 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
Georg Brandl4d540882010-10-28 06:42:33 +0000481 raise zipfile.BadZipFile()
482 except zipfile.BadZipFile:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000483 self.assertTrue(zipfp2.fp is None, 'zipfp is not closed')
Gregory P. Smithb0d9ca92009-07-07 05:06:04 +0000484
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000485 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +0000486 unlink(TESTFN)
487 unlink(TESTFN2)
488
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000489
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000490class TestZip64InSmallFiles(unittest.TestCase):
491 # These tests test the ZIP64 functionality without using large files,
492 # see test_zipfile64 for proper tests.
493
494 def setUp(self):
495 self._limit = zipfile.ZIP64_LIMIT
496 zipfile.ZIP64_LIMIT = 5
497
Guido van Rossum9c627722007-08-27 18:31:48 +0000498 line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000499 for i in range(0, FIXEDTEST_SIZE))
500 self.data = b'\n'.join(line_gen)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000501
502 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +0000503 with open(TESTFN, "wb") as fp:
504 fp.write(self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000505
Ezio Melottiafd0d112009-07-15 17:17:17 +0000506 def large_file_exception_test(self, f, compression):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000507 with zipfile.ZipFile(f, "w", compression) as zipfp:
508 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti35386712009-12-31 13:22:41 +0000509 zipfp.write, TESTFN, "another.name")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000510
Ezio Melottiafd0d112009-07-15 17:17:17 +0000511 def large_file_exception_test2(self, f, compression):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000512 with zipfile.ZipFile(f, "w", compression) as zipfp:
513 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti35386712009-12-31 13:22:41 +0000514 zipfp.writestr, "another.name", self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000515 if not isinstance(f, str):
516 f.close()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000517
Ezio Melottiafd0d112009-07-15 17:17:17 +0000518 def test_large_file_exception(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000519 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000520 self.large_file_exception_test(f, zipfile.ZIP_STORED)
521 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000522
Ezio Melottiafd0d112009-07-15 17:17:17 +0000523 def zip_test(self, f, compression):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000524 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000525 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
526 zipfp.write(TESTFN, "another.name")
527 zipfp.write(TESTFN, TESTFN)
528 zipfp.writestr("strfile", self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000529
530 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000531 with zipfile.ZipFile(f, "r", compression) as zipfp:
532 self.assertEqual(zipfp.read(TESTFN), self.data)
533 self.assertEqual(zipfp.read("another.name"), self.data)
534 self.assertEqual(zipfp.read("strfile"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000535
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000536 # Print the ZIP directory
537 fp = io.StringIO()
538 zipfp.printdir(fp)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000539
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000540 directory = fp.getvalue()
541 lines = directory.splitlines()
Ezio Melotti35386712009-12-31 13:22:41 +0000542 self.assertEqual(len(lines), 4) # Number of files + header
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000543
Benjamin Peterson577473f2010-01-19 00:09:57 +0000544 self.assertIn('File Name', lines[0])
545 self.assertIn('Modified', lines[0])
546 self.assertIn('Size', lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000547
Ezio Melotti35386712009-12-31 13:22:41 +0000548 fn, date, time_, size = lines[1].split()
549 self.assertEqual(fn, 'another.name')
550 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
551 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
552 self.assertEqual(size, str(len(self.data)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000553
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000554 # Check the namelist
555 names = zipfp.namelist()
Ezio Melotti35386712009-12-31 13:22:41 +0000556 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000557 self.assertIn(TESTFN, names)
558 self.assertIn("another.name", names)
559 self.assertIn("strfile", names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000560
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000561 # Check infolist
562 infos = zipfp.infolist()
Ezio Melotti35386712009-12-31 13:22:41 +0000563 names = [i.filename for i in infos]
564 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000565 self.assertIn(TESTFN, names)
566 self.assertIn("another.name", names)
567 self.assertIn("strfile", names)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000568 for i in infos:
Ezio Melotti35386712009-12-31 13:22:41 +0000569 self.assertEqual(i.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000570
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000571 # check getinfo
572 for nm in (TESTFN, "another.name", "strfile"):
573 info = zipfp.getinfo(nm)
Ezio Melotti35386712009-12-31 13:22:41 +0000574 self.assertEqual(info.filename, nm)
575 self.assertEqual(info.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000576
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000577 # Check that testzip doesn't raise an exception
578 zipfp.testzip()
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000579 if not isinstance(f, str):
580 f.close()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000581
Ezio Melottiafd0d112009-07-15 17:17:17 +0000582 def test_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000583 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000584 self.zip_test(f, zipfile.ZIP_STORED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000585
Ezio Melotti76430242009-07-11 18:28:48 +0000586 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000587 def test_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +0000588 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000589 self.zip_test(f, zipfile.ZIP_DEFLATED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000590
Ezio Melottiafd0d112009-07-15 17:17:17 +0000591 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000592 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
593 allowZip64=True) as zipfp:
594 zipfp.write(TESTFN, "/absolute")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000595
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000596 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
597 self.assertEqual(zipfp.namelist(), ["absolute"])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000598
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000599 def tearDown(self):
600 zipfile.ZIP64_LIMIT = self._limit
Ezio Melotti76430242009-07-11 18:28:48 +0000601 unlink(TESTFN)
602 unlink(TESTFN2)
603
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000604
605class PyZipFileTests(unittest.TestCase):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000606 def test_write_pyfile(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000607 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
608 fn = __file__
609 if fn.endswith('.pyc') or fn.endswith('.pyo'):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000610 path_split = fn.split(os.sep)
611 if os.altsep is not None:
612 path_split.extend(fn.split(os.altsep))
613 if '__pycache__' in path_split:
614 fn = imp.source_from_cache(fn)
615 else:
616 fn = fn[:-1]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000617
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000618 zipfp.writepy(fn)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000619
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000620 bn = os.path.basename(fn)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000621 self.assertNotIn(bn, zipfp.namelist())
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000622 self.assertTrue(bn + 'o' in zipfp.namelist() or
623 bn + 'c' in zipfp.namelist())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000624
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000625 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
626 fn = __file__
Ezio Melotti35386712009-12-31 13:22:41 +0000627 if fn.endswith(('.pyc', '.pyo')):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000628 fn = fn[:-1]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000629
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000630 zipfp.writepy(fn, "testpackage")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000631
Ezio Melotti35386712009-12-31 13:22:41 +0000632 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000633 self.assertNotIn(bn, zipfp.namelist())
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000634 self.assertTrue(bn + 'o' in zipfp.namelist() or
635 bn + 'c' in zipfp.namelist())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000636
Ezio Melottiafd0d112009-07-15 17:17:17 +0000637 def test_write_python_package(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000638 import email
639 packagedir = os.path.dirname(email.__file__)
640
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000641 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
642 zipfp.writepy(packagedir)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000643
Ezio Melotti35386712009-12-31 13:22:41 +0000644 # Check for a couple of modules at different levels of the
645 # hierarchy
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000646 names = zipfp.namelist()
647 self.assertTrue('email/__init__.pyo' in names or
648 'email/__init__.pyc' in names)
649 self.assertTrue('email/mime/text.pyo' in names or
650 'email/mime/text.pyc' in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000651
Ezio Melottiafd0d112009-07-15 17:17:17 +0000652 def test_write_python_directory(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000653 os.mkdir(TESTFN2)
654 try:
Ezio Melotti35386712009-12-31 13:22:41 +0000655 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
656 fp.write("print(42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000657
Ezio Melotti35386712009-12-31 13:22:41 +0000658 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
659 fp.write("print(42 * 42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000660
Ezio Melotti35386712009-12-31 13:22:41 +0000661 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
662 fp.write("bla bla bla\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000663
664 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
665 zipfp.writepy(TESTFN2)
666
667 names = zipfp.namelist()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000668 self.assertTrue('mod1.pyc' in names or 'mod1.pyo' in names)
669 self.assertTrue('mod2.pyc' in names or 'mod2.pyo' in names)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000670 self.assertNotIn('mod2.txt', names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000671
672 finally:
673 shutil.rmtree(TESTFN2)
674
Ezio Melottiafd0d112009-07-15 17:17:17 +0000675 def test_write_non_pyfile(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000676 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
677 open(TESTFN, 'w').write('most definitely not a python file')
678 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
679 os.remove(TESTFN)
680
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000681
682
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000683class OtherTests(unittest.TestCase):
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000684 zips_with_bad_crc = {
685 zipfile.ZIP_STORED: (
686 b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
687 b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
688 b'ilehello,AworldP'
689 b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
690 b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
691 b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
692 b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
693 b'\0\0/\0\0\0\0\0'),
694 zipfile.ZIP_DEFLATED: (
695 b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
696 b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
697 b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
698 b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
699 b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
700 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
701 b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
702 b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00'),
703 }
704
Ezio Melottiafd0d112009-07-15 17:17:17 +0000705 def test_unicode_filenames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000706 with zipfile.ZipFile(TESTFN, "w") as zf:
707 zf.writestr("foo.txt", "Test for unicode filename")
708 zf.writestr("\xf6.txt", "Test for unicode filename")
Ezio Melottie9615932010-01-24 19:26:24 +0000709 self.assertIsInstance(zf.infolist()[0].filename, str)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000710
711 with zipfile.ZipFile(TESTFN, "r") as zf:
712 self.assertEqual(zf.filelist[0].filename, "foo.txt")
713 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
Martin v. Löwis8570f6a2008-05-05 17:44:38 +0000714
Ezio Melottiafd0d112009-07-15 17:17:17 +0000715 def test_create_non_existent_file_for_append(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +0000716 if os.path.exists(TESTFN):
717 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000718
Thomas Wouterscf297e42007-02-23 15:07:44 +0000719 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000720 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +0000721
Thomas Wouterscf297e42007-02-23 15:07:44 +0000722 try:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000723 with zipfile.ZipFile(TESTFN, 'a') as zf:
724 zf.writestr(filename, content)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000725 except IOError:
726 self.fail('Could not append data to a non-existent zip file.')
727
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000728 self.assertTrue(os.path.exists(TESTFN))
Thomas Wouterscf297e42007-02-23 15:07:44 +0000729
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000730 with zipfile.ZipFile(TESTFN, 'r') as zf:
731 self.assertEqual(zf.read(filename), content)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000732
Ezio Melottiafd0d112009-07-15 17:17:17 +0000733 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000734 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti35386712009-12-31 13:22:41 +0000735 # it opens if there's an error in the file. If it doesn't, the
736 # traceback holds a reference to the ZipFile object and, indirectly,
737 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000738 # On Windows, this causes the os.unlink() call to fail because the
739 # underlying file is still open. This is SF bug #412214.
740 #
Ezio Melotti35386712009-12-31 13:22:41 +0000741 with open(TESTFN, "w") as fp:
742 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000743 try:
744 zf = zipfile.ZipFile(TESTFN)
Georg Brandl4d540882010-10-28 06:42:33 +0000745 except zipfile.BadZipFile:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000746 pass
747
Ezio Melottiafd0d112009-07-15 17:17:17 +0000748 def test_is_zip_erroneous_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000749 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000750 # - passing a filename
751 with open(TESTFN, "w") as fp:
752 fp.write("this is not a legal zip file\n")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000753 chk = zipfile.is_zipfile(TESTFN)
Ezio Melotti35386712009-12-31 13:22:41 +0000754 self.assertFalse(chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000755 # - passing a file object
756 with open(TESTFN, "rb") as fp:
757 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000758 self.assertTrue(not chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000759 # - passing a file-like object
760 fp = io.BytesIO()
761 fp.write(b"this is not a legal zip file\n")
762 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000763 self.assertTrue(not chk)
Ezio Melotti35386712009-12-31 13:22:41 +0000764 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000765 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000766 self.assertTrue(not chk)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000767
Ezio Melottiafd0d112009-07-15 17:17:17 +0000768 def test_is_zip_valid_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000769 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000770 # - passing a filename
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000771 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
772 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
773
Guido van Rossumd8faa362007-04-27 19:54:29 +0000774 chk = zipfile.is_zipfile(TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000775 self.assertTrue(chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000776 # - passing a file object
777 with open(TESTFN, "rb") as fp:
778 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000779 self.assertTrue(chk)
Ezio Melotti35386712009-12-31 13:22:41 +0000780 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000781 zip_contents = fp.read()
782 # - passing a file-like object
783 fp = io.BytesIO()
784 fp.write(zip_contents)
785 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000786 self.assertTrue(chk)
Ezio Melotti35386712009-12-31 13:22:41 +0000787 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000788 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000789 self.assertTrue(chk)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000790
Ezio Melottiafd0d112009-07-15 17:17:17 +0000791 def test_non_existent_file_raises_IOError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000792 # make sure we don't raise an AttributeError when a partially-constructed
793 # ZipFile instance is finalized; this tests for regression on SF tracker
794 # bug #403871.
795
796 # The bug we're testing for caused an AttributeError to be raised
797 # when a ZipFile instance was created for a file that did not
798 # exist; the .fp member was not initialized but was needed by the
799 # __del__() method. Since the AttributeError is in the __del__(),
800 # it is ignored, but the user should be sufficiently annoyed by
801 # the message on the output that regression will be noticed
802 # quickly.
803 self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
804
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +0000805 def test_empty_file_raises_BadZipFile(self):
806 f = open(TESTFN, 'w')
807 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +0000808 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +0000809
Ezio Melotti35386712009-12-31 13:22:41 +0000810 with open(TESTFN, 'w') as fp:
811 fp.write("short file")
Georg Brandl4d540882010-10-28 06:42:33 +0000812 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +0000813
Ezio Melottiafd0d112009-07-15 17:17:17 +0000814 def test_closed_zip_raises_RuntimeError(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000815 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000816 data = io.BytesIO()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000817 with zipfile.ZipFile(data, mode="w") as zipf:
818 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000819
820 # This is correct; calling .read on a closed ZipFile should throw
821 # a RuntimeError, and so should calling .testzip. An earlier
822 # version of .testzip would swallow this exception (and any other)
823 # and report that the first file in the archive was corrupt.
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000824 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
825 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000826 self.assertRaises(RuntimeError, zipf.testzip)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000827 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Guido van Rossum814661e2007-07-18 22:07:29 +0000828 open(TESTFN, 'w').write('zipfile test data')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000829 self.assertRaises(RuntimeError, zipf.write, TESTFN)
830
Ezio Melottiafd0d112009-07-15 17:17:17 +0000831 def test_bad_constructor_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000832 """Check that bad modes passed to ZipFile constructor are caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000833 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
834
Ezio Melottiafd0d112009-07-15 17:17:17 +0000835 def test_bad_open_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000836 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000837 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
838 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
839
840 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000841 # read the data to make sure the file is there
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000842 zipf.read("foo.txt")
843 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000844
Ezio Melottiafd0d112009-07-15 17:17:17 +0000845 def test_read0(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000846 """Check that calling read(0) on a ZipExtFile object returns an empty
847 string and doesn't advance file pointer."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000848 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
849 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
850 # read the data to make sure the file is there
851 f = zipf.open("foo.txt")
852 for i in range(FIXEDTEST_SIZE):
853 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000854
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000855 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000856
Ezio Melottiafd0d112009-07-15 17:17:17 +0000857 def test_open_non_existent_item(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000858 """Check that attempting to call open() for an item that doesn't
859 exist in the archive raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000860 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
861 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000862
Ezio Melottiafd0d112009-07-15 17:17:17 +0000863 def test_bad_compression_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000864 """Check that bad compression methods passed to ZipFile.open are
865 caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000866 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
867
Ezio Melottiafd0d112009-07-15 17:17:17 +0000868 def test_null_byte_in_filename(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000869 """Check that a filename containing a null byte is properly
870 terminated."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000871 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
872 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
873 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000874
Ezio Melottiafd0d112009-07-15 17:17:17 +0000875 def test_struct_sizes(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000876 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000877 self.assertEqual(zipfile.sizeEndCentDir, 22)
878 self.assertEqual(zipfile.sizeCentralDir, 46)
879 self.assertEqual(zipfile.sizeEndCentDir64, 56)
880 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
881
Ezio Melottiafd0d112009-07-15 17:17:17 +0000882 def test_comments(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000883 """Check that comments on the archive are handled properly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000884
885 # check default comment is empty
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000886 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
887 self.assertEqual(zipf.comment, b'')
888 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
889
890 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
891 self.assertEqual(zipfr.comment, b'')
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000892
893 # check a simple short comment
894 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000895 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
896 zipf.comment = comment
897 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
898 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
899 self.assertEqual(zipf.comment, comment)
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000900
901 # check a comment of max length
902 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
903 comment2 = comment2.encode("ascii")
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000904 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
905 zipf.comment = comment2
906 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
907
908 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
909 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000910
911 # check a comment that is too long is truncated
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000912 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
913 zipf.comment = comment2 + b'oops'
914 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
915 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
916 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000917
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000918 def check_testzip_with_bad_crc(self, compression):
919 """Tests that files with bad CRCs return their name from testzip."""
920 zipdata = self.zips_with_bad_crc[compression]
921
922 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
923 # testzip returns the name of the first corrupt file, or None
924 self.assertEqual('afile', zipf.testzip())
925
926 def test_testzip_with_bad_crc_stored(self):
927 self.check_testzip_with_bad_crc(zipfile.ZIP_STORED)
928
929 @skipUnless(zlib, "requires zlib")
930 def test_testzip_with_bad_crc_deflated(self):
931 self.check_testzip_with_bad_crc(zipfile.ZIP_DEFLATED)
932
933 def check_read_with_bad_crc(self, compression):
Georg Brandl4d540882010-10-28 06:42:33 +0000934 """Tests that files with bad CRCs raise a BadZipFile exception when read."""
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000935 zipdata = self.zips_with_bad_crc[compression]
936
937 # Using ZipFile.read()
938 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
Georg Brandl4d540882010-10-28 06:42:33 +0000939 self.assertRaises(zipfile.BadZipFile, zipf.read, 'afile')
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000940
941 # Using ZipExtFile.read()
942 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
943 with zipf.open('afile', 'r') as corrupt_file:
Georg Brandl4d540882010-10-28 06:42:33 +0000944 self.assertRaises(zipfile.BadZipFile, corrupt_file.read)
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000945
946 # Same with small reads (in order to exercise the buffering logic)
947 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
948 with zipf.open('afile', 'r') as corrupt_file:
949 corrupt_file.MIN_READ_SIZE = 2
Georg Brandl4d540882010-10-28 06:42:33 +0000950 with self.assertRaises(zipfile.BadZipFile):
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000951 while corrupt_file.read(2):
952 pass
953
954 def test_read_with_bad_crc_stored(self):
955 self.check_read_with_bad_crc(zipfile.ZIP_STORED)
956
957 @skipUnless(zlib, "requires zlib")
958 def test_read_with_bad_crc_deflated(self):
959 self.check_read_with_bad_crc(zipfile.ZIP_DEFLATED)
960
Antoine Pitrou6464d5f2010-09-12 14:51:20 +0000961 def check_read_return_size(self, compression):
962 # Issue #9837: ZipExtFile.read() shouldn't return more bytes
963 # than requested.
964 for test_size in (1, 4095, 4096, 4097, 16384):
965 file_size = test_size + 1
966 junk = b''.join(struct.pack('B', randint(0, 255))
967 for x in range(file_size))
968 with zipfile.ZipFile(io.BytesIO(), "w", compression) as zipf:
969 zipf.writestr('foo', junk)
970 with zipf.open('foo', 'r') as fp:
971 buf = fp.read(test_size)
972 self.assertEqual(len(buf), test_size)
973
974 def test_read_return_size_stored(self):
975 self.check_read_return_size(zipfile.ZIP_STORED)
976
977 @skipUnless(zlib, "requires zlib")
978 def test_read_return_size_deflated(self):
979 self.check_read_return_size(zipfile.ZIP_DEFLATED)
980
Georg Brandl268e4d42010-10-14 06:59:45 +0000981 def test_empty_zipfile(self):
982 # Check that creating a file in 'w' or 'a' mode and closing without
983 # adding any files to the archives creates a valid empty ZIP file
984 zipf = zipfile.ZipFile(TESTFN, mode="w")
985 zipf.close()
986 try:
987 zipf = zipfile.ZipFile(TESTFN, mode="r")
988 except zipfile.BadZipFile:
989 self.fail("Unable to create empty ZIP file in 'w' mode")
990
991 zipf = zipfile.ZipFile(TESTFN, mode="a")
992 zipf.close()
993 try:
994 zipf = zipfile.ZipFile(TESTFN, mode="r")
995 except:
996 self.fail("Unable to create empty ZIP file in 'a' mode")
997
998 def test_open_empty_file(self):
999 # Issue 1710703: Check that opening a file with less than 22 bytes
Georg Brandl4d540882010-10-28 06:42:33 +00001000 # raises a BadZipFile exception (rather than the previously unhelpful
Georg Brandl268e4d42010-10-14 06:59:45 +00001001 # IOError)
1002 f = open(TESTFN, 'w')
1003 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001004 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN, 'r')
Georg Brandl268e4d42010-10-14 06:59:45 +00001005
Guido van Rossumd8faa362007-04-27 19:54:29 +00001006 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001007 unlink(TESTFN)
1008 unlink(TESTFN2)
1009
Thomas Wouterscf297e42007-02-23 15:07:44 +00001010
1011class DecryptionTests(unittest.TestCase):
Ezio Melotti35386712009-12-31 13:22:41 +00001012 """Check that ZIP decryption works. Since the library does not
1013 support encryption at the moment, we use a pre-generated encrypted
1014 ZIP file."""
Thomas Wouterscf297e42007-02-23 15:07:44 +00001015
1016 data = (
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001017 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
1018 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
1019 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
1020 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
1021 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
1022 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
1023 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +00001024 data2 = (
1025 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
1026 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
1027 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
1028 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
1029 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
1030 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
1031 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
1032 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +00001033
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001034 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +00001035 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +00001036
1037 def setUp(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001038 with open(TESTFN, "wb") as fp:
1039 fp.write(self.data)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001040 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti35386712009-12-31 13:22:41 +00001041 with open(TESTFN2, "wb") as fp:
1042 fp.write(self.data2)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001043 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001044
1045 def tearDown(self):
1046 self.zip.close()
1047 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001048 self.zip2.close()
1049 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001050
Ezio Melottiafd0d112009-07-15 17:17:17 +00001051 def test_no_password(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001052 # Reading the encrypted file without password
1053 # must generate a RunTime exception
1054 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001055 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001056
Ezio Melottiafd0d112009-07-15 17:17:17 +00001057 def test_bad_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001058 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001059 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001060 self.zip2.setpassword(b"perl")
1061 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001062
Ezio Melotti78ea2022009-09-12 18:41:20 +00001063 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001064 def test_good_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001065 self.zip.setpassword(b"python")
Ezio Melotti35386712009-12-31 13:22:41 +00001066 self.assertEqual(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001067 self.zip2.setpassword(b"12345")
Ezio Melotti35386712009-12-31 13:22:41 +00001068 self.assertEqual(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001069
Guido van Rossumd8faa362007-04-27 19:54:29 +00001070
1071class TestsWithRandomBinaryFiles(unittest.TestCase):
1072 def setUp(self):
1073 datacount = randint(16, 64)*1024 + randint(1, 1024)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001074 self.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
1075 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001076
1077 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +00001078 with open(TESTFN, "wb") as fp:
1079 fp.write(self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001080
1081 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001082 unlink(TESTFN)
1083 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001084
Ezio Melottiafd0d112009-07-15 17:17:17 +00001085 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001086 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001087 with zipfile.ZipFile(f, "w", compression) as zipfp:
1088 zipfp.write(TESTFN, "another.name")
1089 zipfp.write(TESTFN, TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001090
Ezio Melottiafd0d112009-07-15 17:17:17 +00001091 def zip_test(self, f, compression):
1092 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001093
1094 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001095 with zipfile.ZipFile(f, "r", compression) as zipfp:
1096 testdata = zipfp.read(TESTFN)
1097 self.assertEqual(len(testdata), len(self.data))
1098 self.assertEqual(testdata, self.data)
1099 self.assertEqual(zipfp.read("another.name"), self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001100 if not isinstance(f, str):
1101 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001102
Ezio Melottiafd0d112009-07-15 17:17:17 +00001103 def test_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001104 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001105 self.zip_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001106
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001107 @skipUnless(zlib, "requires zlib")
1108 def test_deflated(self):
1109 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1110 self.zip_test(f, zipfile.ZIP_DEFLATED)
1111
Ezio Melottiafd0d112009-07-15 17:17:17 +00001112 def zip_open_test(self, f, compression):
1113 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001114
1115 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001116 with zipfile.ZipFile(f, "r", compression) as zipfp:
1117 zipdata1 = []
1118 zipopen1 = zipfp.open(TESTFN)
1119 while True:
1120 read_data = zipopen1.read(256)
1121 if not read_data:
1122 break
1123 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001124
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001125 zipdata2 = []
1126 zipopen2 = zipfp.open("another.name")
1127 while True:
1128 read_data = zipopen2.read(256)
1129 if not read_data:
1130 break
1131 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001132
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001133 testdata1 = b''.join(zipdata1)
1134 self.assertEqual(len(testdata1), len(self.data))
1135 self.assertEqual(testdata1, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001136
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001137 testdata2 = b''.join(zipdata2)
Ezio Melotti35386712009-12-31 13:22:41 +00001138 self.assertEqual(len(testdata2), len(self.data))
1139 self.assertEqual(testdata2, self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001140 if not isinstance(f, str):
1141 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001142
Ezio Melottiafd0d112009-07-15 17:17:17 +00001143 def test_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001144 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001145 self.zip_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001146
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001147 @skipUnless(zlib, "requires zlib")
1148 def test_open_deflated(self):
1149 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1150 self.zip_open_test(f, zipfile.ZIP_DEFLATED)
1151
Ezio Melottiafd0d112009-07-15 17:17:17 +00001152 def zip_random_open_test(self, f, compression):
1153 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001154
1155 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001156 with zipfile.ZipFile(f, "r", compression) as zipfp:
1157 zipdata1 = []
1158 zipopen1 = zipfp.open(TESTFN)
1159 while True:
1160 read_data = zipopen1.read(randint(1, 1024))
1161 if not read_data:
1162 break
1163 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001164
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001165 testdata = b''.join(zipdata1)
1166 self.assertEqual(len(testdata), len(self.data))
1167 self.assertEqual(testdata, self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001168 if not isinstance(f, str):
1169 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001170
Ezio Melottiafd0d112009-07-15 17:17:17 +00001171 def test_random_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001172 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001173 self.zip_random_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001174
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001175 @skipUnless(zlib, "requires zlib")
1176 def test_random_open_deflated(self):
1177 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1178 self.zip_random_open_test(f, zipfile.ZIP_DEFLATED)
1179
Ezio Melotti76430242009-07-11 18:28:48 +00001180
Ezio Melotti78ea2022009-09-12 18:41:20 +00001181@skipUnless(zlib, "requires zlib")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001182class TestsWithMultipleOpens(unittest.TestCase):
1183 def setUp(self):
1184 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001185 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
1186 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
1187 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001188
Ezio Melottiafd0d112009-07-15 17:17:17 +00001189 def test_same_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001190 # Verify that (when the ZipFile is in control of creating file objects)
1191 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001192 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
1193 zopen1 = zipf.open('ones')
1194 zopen2 = zipf.open('ones')
1195 data1 = zopen1.read(500)
1196 data2 = zopen2.read(500)
1197 data1 += zopen1.read(500)
1198 data2 += zopen2.read(500)
1199 self.assertEqual(data1, data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001200
Ezio Melottiafd0d112009-07-15 17:17:17 +00001201 def test_different_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001202 # Verify that (when the ZipFile is in control of creating file objects)
1203 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001204 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
1205 zopen1 = zipf.open('ones')
1206 zopen2 = zipf.open('twos')
1207 data1 = zopen1.read(500)
1208 data2 = zopen2.read(500)
1209 data1 += zopen1.read(500)
1210 data2 += zopen2.read(500)
1211 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
1212 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001213
Ezio Melottiafd0d112009-07-15 17:17:17 +00001214 def test_interleaved(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001215 # Verify that (when the ZipFile is in control of creating file objects)
1216 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001217 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
1218 zopen1 = zipf.open('ones')
1219 data1 = zopen1.read(500)
1220 zopen2 = zipf.open('twos')
1221 data2 = zopen2.read(500)
1222 data1 += zopen1.read(500)
1223 data2 += zopen2.read(500)
1224 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
1225 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001226
1227 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001228 unlink(TESTFN2)
1229
Guido van Rossumd8faa362007-04-27 19:54:29 +00001230
Martin v. Löwis59e47792009-01-24 14:10:07 +00001231class TestWithDirectory(unittest.TestCase):
1232 def setUp(self):
1233 os.mkdir(TESTFN2)
1234
Ezio Melottiafd0d112009-07-15 17:17:17 +00001235 def test_extract_dir(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001236 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
1237 zipf.extractall(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001238 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1239 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1240 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1241
Ezio Melottiafd0d112009-07-15 17:17:17 +00001242 def test_bug_6050(self):
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001243 # Extraction should succeed if directories already exist
1244 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottiafd0d112009-07-15 17:17:17 +00001245 self.test_extract_dir()
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001246
Ezio Melottiafd0d112009-07-15 17:17:17 +00001247 def test_store_dir(self):
Martin v. Löwis59e47792009-01-24 14:10:07 +00001248 os.mkdir(os.path.join(TESTFN2, "x"))
1249 zipf = zipfile.ZipFile(TESTFN, "w")
1250 zipf.write(os.path.join(TESTFN2, "x"), "x")
1251 self.assertTrue(zipf.filelist[0].filename.endswith("x/"))
1252
1253 def tearDown(self):
1254 shutil.rmtree(TESTFN2)
1255 if os.path.exists(TESTFN):
Ezio Melotti76430242009-07-11 18:28:48 +00001256 unlink(TESTFN)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001257
Guido van Rossumd8faa362007-04-27 19:54:29 +00001258
1259class UniversalNewlineTests(unittest.TestCase):
1260 def setUp(self):
Guido van Rossum9c627722007-08-27 18:31:48 +00001261 self.line_gen = [bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001262 for i in range(FIXEDTEST_SIZE)]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001263 self.seps = ('\r', '\r\n', '\n')
1264 self.arcdata, self.arcfiles = {}, {}
1265 for n, s in enumerate(self.seps):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001266 b = s.encode("ascii")
1267 self.arcdata[s] = b.join(self.line_gen) + b
Guido van Rossumd8faa362007-04-27 19:54:29 +00001268 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001269 f = open(self.arcfiles[s], "wb")
1270 try:
1271 f.write(self.arcdata[s])
1272 finally:
1273 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001274
Ezio Melottiafd0d112009-07-15 17:17:17 +00001275 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001276 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001277 with zipfile.ZipFile(f, "w", compression) as zipfp:
1278 for fn in self.arcfiles.values():
1279 zipfp.write(fn, fn)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001280
Ezio Melottiafd0d112009-07-15 17:17:17 +00001281 def read_test(self, f, compression):
1282 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001283
1284 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001285 with zipfile.ZipFile(f, "r") as zipfp:
1286 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001287 with zipfp.open(fn, "rU") as fp:
1288 zipdata = fp.read()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001289 self.assertEqual(self.arcdata[sep], zipdata)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001290 if not isinstance(f, str):
1291 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001292
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001293 def readline_read_test(self, f, compression):
1294 self.make_test_archive(f, compression)
1295
1296 # Read the ZIP archive
1297 zipfp = zipfile.ZipFile(f, "r")
1298 for sep, fn in self.arcfiles.items():
1299 zipopen = zipfp.open(fn, "rU")
1300 data = b''
1301 while True:
1302 read = zipopen.readline()
1303 if not read:
1304 break
1305 data += read
1306
1307 read = zipopen.read(5)
1308 if not read:
1309 break
1310 data += read
1311
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001312 zipopen.close()
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001313 self.assertEqual(data, self.arcdata['\n'])
1314
1315 zipfp.close()
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001316 if not isinstance(f, str):
1317 f.close()
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001318
Ezio Melottiafd0d112009-07-15 17:17:17 +00001319 def readline_test(self, f, compression):
1320 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001321
1322 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001323 with zipfile.ZipFile(f, "r") as zipfp:
1324 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001325 with zipfp.open(fn, "rU") as zipopen:
1326 for line in self.line_gen:
1327 linedata = zipopen.readline()
1328 self.assertEqual(linedata, line + b'\n')
1329 if not isinstance(f, str):
1330 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001331
Ezio Melottiafd0d112009-07-15 17:17:17 +00001332 def readlines_test(self, f, compression):
1333 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001334
1335 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001336 with zipfile.ZipFile(f, "r") as zipfp:
1337 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001338 with zipfp.open(fn, "rU") as fp:
1339 ziplines = fp.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001340 for line, zipline in zip(self.line_gen, ziplines):
1341 self.assertEqual(zipline, line + b'\n')
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001342 if not isinstance(f, str):
1343 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001344
Ezio Melottiafd0d112009-07-15 17:17:17 +00001345 def iterlines_test(self, f, compression):
1346 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001347
1348 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001349 with zipfile.ZipFile(f, "r") as zipfp:
1350 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001351 with zipfp.open(fn, "rU") as fp:
1352 for line, zipline in zip(self.line_gen, fp):
1353 self.assertEqual(zipline, line + b'\n')
1354 if not isinstance(f, str):
1355 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001356
Ezio Melottiafd0d112009-07-15 17:17:17 +00001357 def test_read_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001358 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001359 self.read_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001360
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001361 def test_readline_read_stored(self):
1362 # Issue #7610: calls to readline() interleaved with calls to read().
1363 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1364 self.readline_read_test(f, zipfile.ZIP_STORED)
1365
Ezio Melottiafd0d112009-07-15 17:17:17 +00001366 def test_readline_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001367 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001368 self.readline_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001369
Ezio Melottiafd0d112009-07-15 17:17:17 +00001370 def test_readlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001371 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001372 self.readlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001373
Ezio Melottiafd0d112009-07-15 17:17:17 +00001374 def test_iterlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001375 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001376 self.iterlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001377
Ezio Melotti76430242009-07-11 18:28:48 +00001378 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001379 def test_read_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001380 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001381 self.read_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001382
Ezio Melotti76430242009-07-11 18:28:48 +00001383 @skipUnless(zlib, "requires zlib")
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001384 def test_readline_read_deflated(self):
1385 # Issue #7610: calls to readline() interleaved with calls to read().
1386 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1387 self.readline_read_test(f, zipfile.ZIP_DEFLATED)
1388
1389 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001390 def test_readline_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001391 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001392 self.readline_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001393
Ezio Melotti76430242009-07-11 18:28:48 +00001394 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001395 def test_readlines_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001396 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001397 self.readlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001398
Ezio Melotti76430242009-07-11 18:28:48 +00001399 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001400 def test_iterlines_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001401 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001402 self.iterlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001403
1404 def tearDown(self):
1405 for sep, fn in self.arcfiles.items():
1406 os.remove(fn)
Ezio Melotti76430242009-07-11 18:28:48 +00001407 unlink(TESTFN)
1408 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001409
1410
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001411def test_main():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001412 run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
1413 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
Ezio Melotti76430242009-07-11 18:28:48 +00001414 TestWithDirectory, UniversalNewlineTests,
1415 TestsWithRandomBinaryFiles)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001416
1417if __name__ == "__main__":
1418 test_main()