blob: 7f93b68e27a97ac1a7bffc68d5e2cadc7326abee [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 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000115 with zipfp.open(TESTFN) as zipopen1:
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 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000123 with zipfp.open("another.name") as zipopen2:
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:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000149 with zipfp.open(info) as zipopen:
150 data += zipopen.read()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000151 self.assertTrue(data == b"foobar" or data == b"barfoo")
152 data = b""
153 for info in infos:
154 data += zipfp.read(info)
155 self.assertTrue(data == b"foobar" or data == b"barfoo")
Georg Brandlb533e262008-05-25 18:19:30 +0000156
Ezio Melottiafd0d112009-07-15 17:17:17 +0000157 def zip_random_open_test(self, f, compression):
158 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000159
160 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000161 with zipfile.ZipFile(f, "r", compression) as zipfp:
162 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000163 with zipfp.open(TESTFN) as zipopen1:
164 while True:
165 read_data = zipopen1.read(randint(1, 1024))
166 if not read_data:
167 break
168 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000169
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000170 self.assertEqual(b''.join(zipdata1), self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000171 if not isinstance(f, str):
172 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000173
Ezio Melottiafd0d112009-07-15 17:17:17 +0000174 def test_random_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000175 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000176 self.zip_random_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000177
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000178 def test_univeral_readaheads(self):
179 f = io.BytesIO()
180
181 data = b'a\r\n' * 16 * 1024
182 zipfp = zipfile.ZipFile(f, 'w', zipfile.ZIP_STORED)
183 zipfp.writestr(TESTFN, data)
184 zipfp.close()
185
186 data2 = b''
187 zipfp = zipfile.ZipFile(f, 'r')
Brian Curtin8fb9b862010-11-18 02:15:28 +0000188 with zipfp.open(TESTFN, 'rU') as zipopen:
189 for line in zipopen:
190 data2 += line
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000191 zipfp.close()
192
193 self.assertEqual(data, data2.replace(b'\n', b'\r\n'))
194
195 def zip_readline_read_test(self, f, compression):
196 self.make_test_archive(f, compression)
197
198 # Read the ZIP archive
199 zipfp = zipfile.ZipFile(f, "r")
Brian Curtin8fb9b862010-11-18 02:15:28 +0000200 with zipfp.open(TESTFN) as zipopen:
201 data = b''
202 while True:
203 read = zipopen.readline()
204 if not read:
205 break
206 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000207
Brian Curtin8fb9b862010-11-18 02:15:28 +0000208 read = zipopen.read(100)
209 if not read:
210 break
211 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000212
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:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000223 with zipfp.open(TESTFN) as zipopen:
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:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000235 with zipfp.open(TESTFN) as zipopen:
236 ziplines = zipopen.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000237 for line, zipline in zip(self.line_gen, ziplines):
238 self.assertEqual(zipline, line + '\n')
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000239 if not isinstance(f, str):
240 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000241
Ezio Melottiafd0d112009-07-15 17:17:17 +0000242 def zip_iterlines_test(self, f, compression):
243 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000244
245 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000246 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000247 with zipfp.open(TESTFN) as zipopen:
248 for line, zipline in zip(self.line_gen, zipopen):
249 self.assertEqual(zipline, line + '\n')
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000250 if not isinstance(f, str):
251 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000252
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000253 def test_readline_read_stored(self):
254 # Issue #7610: calls to readline() interleaved with calls to read().
255 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
256 self.zip_readline_read_test(f, zipfile.ZIP_STORED)
257
Ezio Melottiafd0d112009-07-15 17:17:17 +0000258 def test_readline_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000259 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000260 self.zip_readline_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000261
Ezio Melottiafd0d112009-07-15 17:17:17 +0000262 def test_readlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000263 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000264 self.zip_readlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000265
Ezio Melottiafd0d112009-07-15 17:17:17 +0000266 def test_iterlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000267 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000268 self.zip_iterlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000269
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000270 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000271 def test_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000272 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000273 self.zip_test(f, zipfile.ZIP_DEFLATED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000274
Guido van Rossumd8faa362007-04-27 19:54:29 +0000275
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000276 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000277 def test_open_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_open_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_random_open_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_random_open_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")
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000287 def test_readline_read_deflated(self):
288 # Issue #7610: calls to readline() interleaved with calls to read().
289 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
290 self.zip_readline_read_test(f, zipfile.ZIP_DEFLATED)
291
292 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000293 def test_readline_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000294 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000295 self.zip_readline_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000296
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000297 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000298 def test_readlines_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000299 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000300 self.zip_readlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000301
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000302 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000303 def test_iterlines_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000304 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000305 self.zip_iterlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000306
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000307 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000308 def test_low_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000309 """Check for cases where compressed data is larger than original."""
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000310 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000311 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
312 zipfp.writestr("strfile", '12')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000313
314 # Get an open object for strfile
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000315 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_DEFLATED) as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000316 with zipfp.open("strfile") as openobj:
317 self.assertEqual(openobj.read(1), b'1')
318 self.assertEqual(openobj.read(1), b'2')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000319
Ezio Melottiafd0d112009-07-15 17:17:17 +0000320 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000321 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
322 zipfp.write(TESTFN, "/absolute")
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000323
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000324 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
325 self.assertEqual(zipfp.namelist(), ["absolute"])
Tim Peters32cbc962006-02-20 21:42:18 +0000326
Ezio Melottiafd0d112009-07-15 17:17:17 +0000327 def test_append_to_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000328 """Test appending to an existing zipfile."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000329 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
330 zipfp.write(TESTFN, TESTFN)
331
332 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
333 zipfp.writestr("strfile", self.data)
334 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000335
Ezio Melottiafd0d112009-07-15 17:17:17 +0000336 def test_append_to_non_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000337 """Test appending to an existing file that is not a zipfile."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000338 # NOTE: this test fails if len(d) < 22 because of the first
339 # line "fpin.seek(-22, 2)" in _EndRecData
Ezio Melotti35386712009-12-31 13:22:41 +0000340 data = b'I am not a ZipFile!'*10
341 with open(TESTFN2, 'wb') as f:
342 f.write(data)
343
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000344 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
345 zipfp.write(TESTFN, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000346
Ezio Melotti35386712009-12-31 13:22:41 +0000347 with open(TESTFN2, 'rb') as f:
348 f.seek(len(data))
349 with zipfile.ZipFile(f, "r") as zipfp:
350 self.assertEqual(zipfp.namelist(), [TESTFN])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000351
Ezio Melottiafd0d112009-07-15 17:17:17 +0000352 def test_write_default_name(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000353 """Check that calling ZipFile.write without arcname specified
354 produces the expected result."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000355 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
356 zipfp.write(TESTFN)
Brian Curtin8fb9b862010-11-18 02:15:28 +0000357 with open(TESTFN, "rb") as f:
358 self.assertEqual(zipfp.read(TESTFN), f.read())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000359
Ezio Melotti78ea2022009-09-12 18:41:20 +0000360 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000361 def test_per_file_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000362 """Check that files within a Zip archive can have different
363 compression options."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000364 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
365 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
366 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
367 sinfo = zipfp.getinfo('storeme')
368 dinfo = zipfp.getinfo('deflateme')
369 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
370 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000371
Ezio Melottiafd0d112009-07-15 17:17:17 +0000372 def test_write_to_readonly(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000373 """Check that trying to call write() on a readonly ZipFile object
374 raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000375 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
376 zipfp.writestr("somefile.txt", "bogus")
377
378 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
379 self.assertRaises(RuntimeError, zipfp.write, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000380
Ezio Melottiafd0d112009-07-15 17:17:17 +0000381 def test_extract(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000382 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
383 for fpath, fdata in SMALL_TEST_DATA:
384 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000385
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000386 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
387 for fpath, fdata in SMALL_TEST_DATA:
388 writtenfile = zipfp.extract(fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000389
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000390 # make sure it was written to the right place
391 if os.path.isabs(fpath):
392 correctfile = os.path.join(os.getcwd(), fpath[1:])
393 else:
394 correctfile = os.path.join(os.getcwd(), fpath)
395 correctfile = os.path.normpath(correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000396
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000397 self.assertEqual(writtenfile, correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000398
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000399 # make sure correct data is in correct file
Brian Curtin8fb9b862010-11-18 02:15:28 +0000400 with open(writtenfile, "rb") as f:
401 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000402
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000403 os.remove(writtenfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000404
405 # remove the test file subdirectories
406 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
407
Ezio Melottiafd0d112009-07-15 17:17:17 +0000408 def test_extract_all(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000409 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
410 for fpath, fdata in SMALL_TEST_DATA:
411 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000412
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000413 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
414 zipfp.extractall()
415 for fpath, fdata in SMALL_TEST_DATA:
416 if os.path.isabs(fpath):
417 outfile = os.path.join(os.getcwd(), fpath[1:])
418 else:
419 outfile = os.path.join(os.getcwd(), fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000420
Brian Curtin8fb9b862010-11-18 02:15:28 +0000421 with open(outfile, "rb") as f:
422 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000423
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000424 os.remove(outfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000425
426 # remove the test file subdirectories
427 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
428
Ronald Oussorenee5c8852010-02-07 20:24:02 +0000429 def test_writestr_compression(self):
430 zipfp = zipfile.ZipFile(TESTFN2, "w")
431 zipfp.writestr("a.txt", "hello world", compress_type=zipfile.ZIP_STORED)
432 if zlib:
433 zipfp.writestr("b.txt", "hello world", compress_type=zipfile.ZIP_DEFLATED)
434
435 info = zipfp.getinfo('a.txt')
436 self.assertEqual(info.compress_type, zipfile.ZIP_STORED)
437
438 if zlib:
439 info = zipfp.getinfo('b.txt')
440 self.assertEqual(info.compress_type, zipfile.ZIP_DEFLATED)
441
442
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000443 def zip_test_writestr_permissions(self, f, compression):
444 # Make sure that writestr creates files with mode 0600,
445 # when it is passed a name rather than a ZipInfo instance.
446
Ezio Melottiafd0d112009-07-15 17:17:17 +0000447 self.make_test_archive(f, compression)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000448 with zipfile.ZipFile(f, "r") as zipfp:
449 zinfo = zipfp.getinfo('strfile')
450 self.assertEqual(zinfo.external_attr, 0o600 << 16)
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000451 if not isinstance(f, str):
452 f.close()
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000453
Ezio Melottiafd0d112009-07-15 17:17:17 +0000454 def test_writestr_permissions(self):
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000455 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
456 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
457
Gregory P. Smithb0d9ca92009-07-07 05:06:04 +0000458 def test_writestr_extended_local_header_issue1202(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000459 with zipfile.ZipFile(TESTFN2, 'w') as orig_zip:
460 for data in 'abcdefghijklmnop':
461 zinfo = zipfile.ZipInfo(data)
462 zinfo.flag_bits |= 0x08 # Include an extended local header.
463 orig_zip.writestr(zinfo, data)
464
465 def test_close(self):
466 """Check that the zipfile is closed after the 'with' block."""
467 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
468 for fpath, fdata in SMALL_TEST_DATA:
469 zipfp.writestr(fpath, fdata)
470 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
471 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
472
473 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
474 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
475 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
476
477 def test_close_on_exception(self):
478 """Check that the zipfile is closed if an exception is raised in the
479 'with' block."""
480 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
481 for fpath, fdata in SMALL_TEST_DATA:
482 zipfp.writestr(fpath, fdata)
483
484 try:
485 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
Georg Brandl4d540882010-10-28 06:42:33 +0000486 raise zipfile.BadZipFile()
487 except zipfile.BadZipFile:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000488 self.assertTrue(zipfp2.fp is None, 'zipfp is not closed')
Gregory P. Smithb0d9ca92009-07-07 05:06:04 +0000489
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000490 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +0000491 unlink(TESTFN)
492 unlink(TESTFN2)
493
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000494
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000495class TestZip64InSmallFiles(unittest.TestCase):
496 # These tests test the ZIP64 functionality without using large files,
497 # see test_zipfile64 for proper tests.
498
499 def setUp(self):
500 self._limit = zipfile.ZIP64_LIMIT
501 zipfile.ZIP64_LIMIT = 5
502
Guido van Rossum9c627722007-08-27 18:31:48 +0000503 line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000504 for i in range(0, FIXEDTEST_SIZE))
505 self.data = b'\n'.join(line_gen)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000506
507 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +0000508 with open(TESTFN, "wb") as fp:
509 fp.write(self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000510
Ezio Melottiafd0d112009-07-15 17:17:17 +0000511 def large_file_exception_test(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.write, TESTFN, "another.name")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000515
Ezio Melottiafd0d112009-07-15 17:17:17 +0000516 def large_file_exception_test2(self, f, compression):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000517 with zipfile.ZipFile(f, "w", compression) as zipfp:
518 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti35386712009-12-31 13:22:41 +0000519 zipfp.writestr, "another.name", self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000520 if not isinstance(f, str):
521 f.close()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000522
Ezio Melottiafd0d112009-07-15 17:17:17 +0000523 def test_large_file_exception(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000524 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000525 self.large_file_exception_test(f, zipfile.ZIP_STORED)
526 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000527
Ezio Melottiafd0d112009-07-15 17:17:17 +0000528 def zip_test(self, f, compression):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000529 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000530 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
531 zipfp.write(TESTFN, "another.name")
532 zipfp.write(TESTFN, TESTFN)
533 zipfp.writestr("strfile", self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000534
535 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000536 with zipfile.ZipFile(f, "r", compression) as zipfp:
537 self.assertEqual(zipfp.read(TESTFN), self.data)
538 self.assertEqual(zipfp.read("another.name"), self.data)
539 self.assertEqual(zipfp.read("strfile"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000540
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000541 # Print the ZIP directory
542 fp = io.StringIO()
543 zipfp.printdir(fp)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000544
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000545 directory = fp.getvalue()
546 lines = directory.splitlines()
Ezio Melotti35386712009-12-31 13:22:41 +0000547 self.assertEqual(len(lines), 4) # Number of files + header
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000548
Benjamin Peterson577473f2010-01-19 00:09:57 +0000549 self.assertIn('File Name', lines[0])
550 self.assertIn('Modified', lines[0])
551 self.assertIn('Size', lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000552
Ezio Melotti35386712009-12-31 13:22:41 +0000553 fn, date, time_, size = lines[1].split()
554 self.assertEqual(fn, 'another.name')
555 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
556 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
557 self.assertEqual(size, str(len(self.data)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000558
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000559 # Check the namelist
560 names = zipfp.namelist()
Ezio Melotti35386712009-12-31 13:22:41 +0000561 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000562 self.assertIn(TESTFN, names)
563 self.assertIn("another.name", names)
564 self.assertIn("strfile", names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000565
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000566 # Check infolist
567 infos = zipfp.infolist()
Ezio Melotti35386712009-12-31 13:22:41 +0000568 names = [i.filename for i in infos]
569 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000570 self.assertIn(TESTFN, names)
571 self.assertIn("another.name", names)
572 self.assertIn("strfile", names)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000573 for i in infos:
Ezio Melotti35386712009-12-31 13:22:41 +0000574 self.assertEqual(i.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000575
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000576 # check getinfo
577 for nm in (TESTFN, "another.name", "strfile"):
578 info = zipfp.getinfo(nm)
Ezio Melotti35386712009-12-31 13:22:41 +0000579 self.assertEqual(info.filename, nm)
580 self.assertEqual(info.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000581
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000582 # Check that testzip doesn't raise an exception
583 zipfp.testzip()
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000584 if not isinstance(f, str):
585 f.close()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000586
Ezio Melottiafd0d112009-07-15 17:17:17 +0000587 def test_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000588 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000589 self.zip_test(f, zipfile.ZIP_STORED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000590
Ezio Melotti76430242009-07-11 18:28:48 +0000591 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000592 def test_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +0000593 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000594 self.zip_test(f, zipfile.ZIP_DEFLATED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000595
Ezio Melottiafd0d112009-07-15 17:17:17 +0000596 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000597 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
598 allowZip64=True) as zipfp:
599 zipfp.write(TESTFN, "/absolute")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000600
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000601 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
602 self.assertEqual(zipfp.namelist(), ["absolute"])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000603
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000604 def tearDown(self):
605 zipfile.ZIP64_LIMIT = self._limit
Ezio Melotti76430242009-07-11 18:28:48 +0000606 unlink(TESTFN)
607 unlink(TESTFN2)
608
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000609
610class PyZipFileTests(unittest.TestCase):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000611 def test_write_pyfile(self):
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000612 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000613 fn = __file__
614 if fn.endswith('.pyc') or fn.endswith('.pyo'):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000615 path_split = fn.split(os.sep)
616 if os.altsep is not None:
617 path_split.extend(fn.split(os.altsep))
618 if '__pycache__' in path_split:
619 fn = imp.source_from_cache(fn)
620 else:
621 fn = fn[:-1]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000622
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000623 zipfp.writepy(fn)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000624
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000625 bn = os.path.basename(fn)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000626 self.assertNotIn(bn, zipfp.namelist())
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000627 self.assertTrue(bn + 'o' in zipfp.namelist() or
628 bn + 'c' in zipfp.namelist())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000629
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000630 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000631 fn = __file__
Ezio Melotti35386712009-12-31 13:22:41 +0000632 if fn.endswith(('.pyc', '.pyo')):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000633 fn = fn[:-1]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000634
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000635 zipfp.writepy(fn, "testpackage")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000636
Ezio Melotti35386712009-12-31 13:22:41 +0000637 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000638 self.assertNotIn(bn, zipfp.namelist())
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000639 self.assertTrue(bn + 'o' in zipfp.namelist() or
640 bn + 'c' in zipfp.namelist())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000641
Ezio Melottiafd0d112009-07-15 17:17:17 +0000642 def test_write_python_package(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000643 import email
644 packagedir = os.path.dirname(email.__file__)
645
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000646 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000647 zipfp.writepy(packagedir)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000648
Ezio Melotti35386712009-12-31 13:22:41 +0000649 # Check for a couple of modules at different levels of the
650 # hierarchy
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000651 names = zipfp.namelist()
652 self.assertTrue('email/__init__.pyo' in names or
653 'email/__init__.pyc' in names)
654 self.assertTrue('email/mime/text.pyo' in names or
655 'email/mime/text.pyc' in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000656
Ezio Melottiafd0d112009-07-15 17:17:17 +0000657 def test_write_python_directory(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000658 os.mkdir(TESTFN2)
659 try:
Ezio Melotti35386712009-12-31 13:22:41 +0000660 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
661 fp.write("print(42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000662
Ezio Melotti35386712009-12-31 13:22:41 +0000663 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
664 fp.write("print(42 * 42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000665
Ezio Melotti35386712009-12-31 13:22:41 +0000666 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
667 fp.write("bla bla bla\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000668
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000669 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
670 zipfp.writepy(TESTFN2)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000671
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000672 names = zipfp.namelist()
673 self.assertTrue('mod1.pyc' in names or 'mod1.pyo' in names)
674 self.assertTrue('mod2.pyc' in names or 'mod2.pyo' in names)
675 self.assertNotIn('mod2.txt', names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000676
677 finally:
678 shutil.rmtree(TESTFN2)
679
Ezio Melottiafd0d112009-07-15 17:17:17 +0000680 def test_write_non_pyfile(self):
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000681 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000682 with open(TESTFN, 'w') as f:
683 f.write('most definitely not a python file')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000684 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
685 os.remove(TESTFN)
686
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000687
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000688class OtherTests(unittest.TestCase):
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000689 zips_with_bad_crc = {
690 zipfile.ZIP_STORED: (
691 b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
692 b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
693 b'ilehello,AworldP'
694 b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
695 b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
696 b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
697 b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
698 b'\0\0/\0\0\0\0\0'),
699 zipfile.ZIP_DEFLATED: (
700 b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
701 b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
702 b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
703 b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
704 b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
705 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
706 b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
707 b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00'),
708 }
709
Ezio Melottiafd0d112009-07-15 17:17:17 +0000710 def test_unicode_filenames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000711 with zipfile.ZipFile(TESTFN, "w") as zf:
712 zf.writestr("foo.txt", "Test for unicode filename")
713 zf.writestr("\xf6.txt", "Test for unicode filename")
Ezio Melottie9615932010-01-24 19:26:24 +0000714 self.assertIsInstance(zf.infolist()[0].filename, str)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000715
716 with zipfile.ZipFile(TESTFN, "r") as zf:
717 self.assertEqual(zf.filelist[0].filename, "foo.txt")
718 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
Martin v. Löwis8570f6a2008-05-05 17:44:38 +0000719
Ezio Melottiafd0d112009-07-15 17:17:17 +0000720 def test_create_non_existent_file_for_append(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +0000721 if os.path.exists(TESTFN):
722 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000723
Thomas Wouterscf297e42007-02-23 15:07:44 +0000724 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000725 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +0000726
Thomas Wouterscf297e42007-02-23 15:07:44 +0000727 try:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000728 with zipfile.ZipFile(TESTFN, 'a') as zf:
729 zf.writestr(filename, content)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000730 except IOError:
731 self.fail('Could not append data to a non-existent zip file.')
732
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000733 self.assertTrue(os.path.exists(TESTFN))
Thomas Wouterscf297e42007-02-23 15:07:44 +0000734
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000735 with zipfile.ZipFile(TESTFN, 'r') as zf:
736 self.assertEqual(zf.read(filename), content)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000737
Ezio Melottiafd0d112009-07-15 17:17:17 +0000738 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000739 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti35386712009-12-31 13:22:41 +0000740 # it opens if there's an error in the file. If it doesn't, the
741 # traceback holds a reference to the ZipFile object and, indirectly,
742 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000743 # On Windows, this causes the os.unlink() call to fail because the
744 # underlying file is still open. This is SF bug #412214.
745 #
Ezio Melotti35386712009-12-31 13:22:41 +0000746 with open(TESTFN, "w") as fp:
747 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000748 try:
749 zf = zipfile.ZipFile(TESTFN)
Georg Brandl4d540882010-10-28 06:42:33 +0000750 except zipfile.BadZipFile:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000751 pass
752
Ezio Melottiafd0d112009-07-15 17:17:17 +0000753 def test_is_zip_erroneous_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000754 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000755 # - passing a filename
756 with open(TESTFN, "w") as fp:
757 fp.write("this is not a legal zip file\n")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000758 chk = zipfile.is_zipfile(TESTFN)
Ezio Melotti35386712009-12-31 13:22:41 +0000759 self.assertFalse(chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000760 # - passing a file object
761 with open(TESTFN, "rb") as fp:
762 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000763 self.assertTrue(not chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000764 # - passing a file-like object
765 fp = io.BytesIO()
766 fp.write(b"this is not a legal zip file\n")
767 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000768 self.assertTrue(not chk)
Ezio Melotti35386712009-12-31 13:22:41 +0000769 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000770 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000771 self.assertTrue(not chk)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000772
Ezio Melottiafd0d112009-07-15 17:17:17 +0000773 def test_is_zip_valid_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000774 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000775 # - passing a filename
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000776 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
777 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
778
Guido van Rossumd8faa362007-04-27 19:54:29 +0000779 chk = zipfile.is_zipfile(TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000780 self.assertTrue(chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000781 # - passing a file object
782 with open(TESTFN, "rb") as fp:
783 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000784 self.assertTrue(chk)
Ezio Melotti35386712009-12-31 13:22:41 +0000785 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000786 zip_contents = fp.read()
787 # - passing a file-like object
788 fp = io.BytesIO()
789 fp.write(zip_contents)
790 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000791 self.assertTrue(chk)
Ezio Melotti35386712009-12-31 13:22:41 +0000792 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000793 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000794 self.assertTrue(chk)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000795
Ezio Melottiafd0d112009-07-15 17:17:17 +0000796 def test_non_existent_file_raises_IOError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000797 # make sure we don't raise an AttributeError when a partially-constructed
798 # ZipFile instance is finalized; this tests for regression on SF tracker
799 # bug #403871.
800
801 # The bug we're testing for caused an AttributeError to be raised
802 # when a ZipFile instance was created for a file that did not
803 # exist; the .fp member was not initialized but was needed by the
804 # __del__() method. Since the AttributeError is in the __del__(),
805 # it is ignored, but the user should be sufficiently annoyed by
806 # the message on the output that regression will be noticed
807 # quickly.
808 self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
809
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +0000810 def test_empty_file_raises_BadZipFile(self):
811 f = open(TESTFN, 'w')
812 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +0000813 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +0000814
Ezio Melotti35386712009-12-31 13:22:41 +0000815 with open(TESTFN, 'w') as fp:
816 fp.write("short file")
Georg Brandl4d540882010-10-28 06:42:33 +0000817 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +0000818
Ezio Melottiafd0d112009-07-15 17:17:17 +0000819 def test_closed_zip_raises_RuntimeError(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000820 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000821 data = io.BytesIO()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000822 with zipfile.ZipFile(data, mode="w") as zipf:
823 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000824
825 # This is correct; calling .read on a closed ZipFile should throw
826 # a RuntimeError, and so should calling .testzip. An earlier
827 # version of .testzip would swallow this exception (and any other)
828 # and report that the first file in the archive was corrupt.
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000829 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
830 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000831 self.assertRaises(RuntimeError, zipf.testzip)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000832 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Brian Curtin8fb9b862010-11-18 02:15:28 +0000833 with open(TESTFN, 'w') as f:
834 f.write('zipfile test data')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000835 self.assertRaises(RuntimeError, zipf.write, TESTFN)
836
Ezio Melottiafd0d112009-07-15 17:17:17 +0000837 def test_bad_constructor_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000838 """Check that bad modes passed to ZipFile constructor are caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000839 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
840
Ezio Melottiafd0d112009-07-15 17:17:17 +0000841 def test_bad_open_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000842 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000843 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
844 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
845
846 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000847 # read the data to make sure the file is there
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000848 zipf.read("foo.txt")
849 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000850
Ezio Melottiafd0d112009-07-15 17:17:17 +0000851 def test_read0(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000852 """Check that calling read(0) on a ZipExtFile object returns an empty
853 string and doesn't advance file pointer."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000854 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
855 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
856 # read the data to make sure the file is there
Brian Curtin8fb9b862010-11-18 02:15:28 +0000857 with zipf.open("foo.txt") as f:
858 for i in range(FIXEDTEST_SIZE):
859 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000860
Brian Curtin8fb9b862010-11-18 02:15:28 +0000861 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000862
Ezio Melottiafd0d112009-07-15 17:17:17 +0000863 def test_open_non_existent_item(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000864 """Check that attempting to call open() for an item that doesn't
865 exist in the archive raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000866 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
867 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000868
Ezio Melottiafd0d112009-07-15 17:17:17 +0000869 def test_bad_compression_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000870 """Check that bad compression methods passed to ZipFile.open are
871 caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000872 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
873
Ezio Melottiafd0d112009-07-15 17:17:17 +0000874 def test_null_byte_in_filename(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000875 """Check that a filename containing a null byte is properly
876 terminated."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000877 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
878 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
879 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000880
Ezio Melottiafd0d112009-07-15 17:17:17 +0000881 def test_struct_sizes(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000882 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000883 self.assertEqual(zipfile.sizeEndCentDir, 22)
884 self.assertEqual(zipfile.sizeCentralDir, 46)
885 self.assertEqual(zipfile.sizeEndCentDir64, 56)
886 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
887
Ezio Melottiafd0d112009-07-15 17:17:17 +0000888 def test_comments(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000889 """Check that comments on the archive are handled properly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000890
891 # check default comment is empty
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000892 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
893 self.assertEqual(zipf.comment, b'')
894 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
895
896 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
897 self.assertEqual(zipfr.comment, b'')
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000898
899 # check a simple short comment
900 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000901 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
902 zipf.comment = comment
903 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
904 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
905 self.assertEqual(zipf.comment, comment)
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000906
907 # check a comment of max length
908 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
909 comment2 = comment2.encode("ascii")
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000910 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
911 zipf.comment = comment2
912 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
913
914 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
915 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000916
917 # check a comment that is too long is truncated
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000918 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
919 zipf.comment = comment2 + b'oops'
920 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
921 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
922 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000923
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000924 def check_testzip_with_bad_crc(self, compression):
925 """Tests that files with bad CRCs return their name from testzip."""
926 zipdata = self.zips_with_bad_crc[compression]
927
928 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
929 # testzip returns the name of the first corrupt file, or None
930 self.assertEqual('afile', zipf.testzip())
931
932 def test_testzip_with_bad_crc_stored(self):
933 self.check_testzip_with_bad_crc(zipfile.ZIP_STORED)
934
935 @skipUnless(zlib, "requires zlib")
936 def test_testzip_with_bad_crc_deflated(self):
937 self.check_testzip_with_bad_crc(zipfile.ZIP_DEFLATED)
938
939 def check_read_with_bad_crc(self, compression):
Georg Brandl4d540882010-10-28 06:42:33 +0000940 """Tests that files with bad CRCs raise a BadZipFile exception when read."""
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000941 zipdata = self.zips_with_bad_crc[compression]
942
943 # Using ZipFile.read()
944 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
Georg Brandl4d540882010-10-28 06:42:33 +0000945 self.assertRaises(zipfile.BadZipFile, zipf.read, 'afile')
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000946
947 # Using ZipExtFile.read()
948 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
949 with zipf.open('afile', 'r') as corrupt_file:
Georg Brandl4d540882010-10-28 06:42:33 +0000950 self.assertRaises(zipfile.BadZipFile, corrupt_file.read)
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000951
952 # Same with small reads (in order to exercise the buffering logic)
953 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
954 with zipf.open('afile', 'r') as corrupt_file:
955 corrupt_file.MIN_READ_SIZE = 2
Georg Brandl4d540882010-10-28 06:42:33 +0000956 with self.assertRaises(zipfile.BadZipFile):
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000957 while corrupt_file.read(2):
958 pass
959
960 def test_read_with_bad_crc_stored(self):
961 self.check_read_with_bad_crc(zipfile.ZIP_STORED)
962
963 @skipUnless(zlib, "requires zlib")
964 def test_read_with_bad_crc_deflated(self):
965 self.check_read_with_bad_crc(zipfile.ZIP_DEFLATED)
966
Antoine Pitrou6464d5f2010-09-12 14:51:20 +0000967 def check_read_return_size(self, compression):
968 # Issue #9837: ZipExtFile.read() shouldn't return more bytes
969 # than requested.
970 for test_size in (1, 4095, 4096, 4097, 16384):
971 file_size = test_size + 1
972 junk = b''.join(struct.pack('B', randint(0, 255))
973 for x in range(file_size))
974 with zipfile.ZipFile(io.BytesIO(), "w", compression) as zipf:
975 zipf.writestr('foo', junk)
976 with zipf.open('foo', 'r') as fp:
977 buf = fp.read(test_size)
978 self.assertEqual(len(buf), test_size)
979
980 def test_read_return_size_stored(self):
981 self.check_read_return_size(zipfile.ZIP_STORED)
982
983 @skipUnless(zlib, "requires zlib")
984 def test_read_return_size_deflated(self):
985 self.check_read_return_size(zipfile.ZIP_DEFLATED)
986
Georg Brandl268e4d42010-10-14 06:59:45 +0000987 def test_empty_zipfile(self):
988 # Check that creating a file in 'w' or 'a' mode and closing without
989 # adding any files to the archives creates a valid empty ZIP file
990 zipf = zipfile.ZipFile(TESTFN, mode="w")
991 zipf.close()
992 try:
993 zipf = zipfile.ZipFile(TESTFN, mode="r")
994 except zipfile.BadZipFile:
995 self.fail("Unable to create empty ZIP file in 'w' mode")
996
997 zipf = zipfile.ZipFile(TESTFN, mode="a")
998 zipf.close()
999 try:
1000 zipf = zipfile.ZipFile(TESTFN, mode="r")
1001 except:
1002 self.fail("Unable to create empty ZIP file in 'a' mode")
1003
1004 def test_open_empty_file(self):
1005 # Issue 1710703: Check that opening a file with less than 22 bytes
Georg Brandl4d540882010-10-28 06:42:33 +00001006 # raises a BadZipFile exception (rather than the previously unhelpful
Georg Brandl268e4d42010-10-14 06:59:45 +00001007 # IOError)
1008 f = open(TESTFN, 'w')
1009 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001010 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN, 'r')
Georg Brandl268e4d42010-10-14 06:59:45 +00001011
Guido van Rossumd8faa362007-04-27 19:54:29 +00001012 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001013 unlink(TESTFN)
1014 unlink(TESTFN2)
1015
Thomas Wouterscf297e42007-02-23 15:07:44 +00001016
1017class DecryptionTests(unittest.TestCase):
Ezio Melotti35386712009-12-31 13:22:41 +00001018 """Check that ZIP decryption works. Since the library does not
1019 support encryption at the moment, we use a pre-generated encrypted
1020 ZIP file."""
Thomas Wouterscf297e42007-02-23 15:07:44 +00001021
1022 data = (
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001023 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
1024 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
1025 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
1026 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
1027 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
1028 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
1029 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +00001030 data2 = (
1031 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
1032 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
1033 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
1034 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
1035 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
1036 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
1037 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
1038 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +00001039
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001040 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +00001041 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +00001042
1043 def setUp(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001044 with open(TESTFN, "wb") as fp:
1045 fp.write(self.data)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001046 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti35386712009-12-31 13:22:41 +00001047 with open(TESTFN2, "wb") as fp:
1048 fp.write(self.data2)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001049 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001050
1051 def tearDown(self):
1052 self.zip.close()
1053 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001054 self.zip2.close()
1055 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001056
Ezio Melottiafd0d112009-07-15 17:17:17 +00001057 def test_no_password(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001058 # Reading the encrypted file without password
1059 # must generate a RunTime exception
1060 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001061 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001062
Ezio Melottiafd0d112009-07-15 17:17:17 +00001063 def test_bad_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001064 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001065 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001066 self.zip2.setpassword(b"perl")
1067 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001068
Ezio Melotti78ea2022009-09-12 18:41:20 +00001069 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001070 def test_good_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001071 self.zip.setpassword(b"python")
Ezio Melotti35386712009-12-31 13:22:41 +00001072 self.assertEqual(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001073 self.zip2.setpassword(b"12345")
Ezio Melotti35386712009-12-31 13:22:41 +00001074 self.assertEqual(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001075
Guido van Rossumd8faa362007-04-27 19:54:29 +00001076
1077class TestsWithRandomBinaryFiles(unittest.TestCase):
1078 def setUp(self):
1079 datacount = randint(16, 64)*1024 + randint(1, 1024)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001080 self.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
1081 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001082
1083 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +00001084 with open(TESTFN, "wb") as fp:
1085 fp.write(self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001086
1087 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001088 unlink(TESTFN)
1089 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001090
Ezio Melottiafd0d112009-07-15 17:17:17 +00001091 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001092 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001093 with zipfile.ZipFile(f, "w", compression) as zipfp:
1094 zipfp.write(TESTFN, "another.name")
1095 zipfp.write(TESTFN, TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001096
Ezio Melottiafd0d112009-07-15 17:17:17 +00001097 def zip_test(self, f, compression):
1098 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001099
1100 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001101 with zipfile.ZipFile(f, "r", compression) as zipfp:
1102 testdata = zipfp.read(TESTFN)
1103 self.assertEqual(len(testdata), len(self.data))
1104 self.assertEqual(testdata, self.data)
1105 self.assertEqual(zipfp.read("another.name"), self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001106 if not isinstance(f, str):
1107 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001108
Ezio Melottiafd0d112009-07-15 17:17:17 +00001109 def test_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001110 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001111 self.zip_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001112
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001113 @skipUnless(zlib, "requires zlib")
1114 def test_deflated(self):
1115 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1116 self.zip_test(f, zipfile.ZIP_DEFLATED)
1117
Ezio Melottiafd0d112009-07-15 17:17:17 +00001118 def zip_open_test(self, f, compression):
1119 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001120
1121 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001122 with zipfile.ZipFile(f, "r", compression) as zipfp:
1123 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001124 with zipfp.open(TESTFN) as zipopen1:
1125 while True:
1126 read_data = zipopen1.read(256)
1127 if not read_data:
1128 break
1129 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001130
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001131 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001132 with zipfp.open("another.name") as zipopen2:
1133 while True:
1134 read_data = zipopen2.read(256)
1135 if not read_data:
1136 break
1137 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001138
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001139 testdata1 = b''.join(zipdata1)
1140 self.assertEqual(len(testdata1), len(self.data))
1141 self.assertEqual(testdata1, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001142
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001143 testdata2 = b''.join(zipdata2)
Ezio Melotti35386712009-12-31 13:22:41 +00001144 self.assertEqual(len(testdata2), len(self.data))
1145 self.assertEqual(testdata2, self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001146 if not isinstance(f, str):
1147 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001148
Ezio Melottiafd0d112009-07-15 17:17:17 +00001149 def test_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001150 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001151 self.zip_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001152
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001153 @skipUnless(zlib, "requires zlib")
1154 def test_open_deflated(self):
1155 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1156 self.zip_open_test(f, zipfile.ZIP_DEFLATED)
1157
Ezio Melottiafd0d112009-07-15 17:17:17 +00001158 def zip_random_open_test(self, f, compression):
1159 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001160
1161 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001162 with zipfile.ZipFile(f, "r", compression) as zipfp:
1163 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001164 with zipfp.open(TESTFN) as zipopen1:
1165 while True:
1166 read_data = zipopen1.read(randint(1, 1024))
1167 if not read_data:
1168 break
1169 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001170
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001171 testdata = b''.join(zipdata1)
1172 self.assertEqual(len(testdata), len(self.data))
1173 self.assertEqual(testdata, self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001174 if not isinstance(f, str):
1175 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001176
Ezio Melottiafd0d112009-07-15 17:17:17 +00001177 def test_random_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001178 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001179 self.zip_random_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001180
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001181 @skipUnless(zlib, "requires zlib")
1182 def test_random_open_deflated(self):
1183 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1184 self.zip_random_open_test(f, zipfile.ZIP_DEFLATED)
1185
Ezio Melotti76430242009-07-11 18:28:48 +00001186
Ezio Melotti78ea2022009-09-12 18:41:20 +00001187@skipUnless(zlib, "requires zlib")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001188class TestsWithMultipleOpens(unittest.TestCase):
1189 def setUp(self):
1190 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001191 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
1192 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
1193 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001194
Ezio Melottiafd0d112009-07-15 17:17:17 +00001195 def test_same_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001196 # Verify that (when the ZipFile is in control of creating file objects)
1197 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001198 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001199 with zipf.open('ones') as zopen1, zipf.open('ones') as zopen2:
1200 data1 = zopen1.read(500)
1201 data2 = zopen2.read(500)
1202 data1 += zopen1.read(500)
1203 data2 += zopen2.read(500)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001204 self.assertEqual(data1, data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001205
Ezio Melottiafd0d112009-07-15 17:17:17 +00001206 def test_different_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001207 # Verify that (when the ZipFile is in control of creating file objects)
1208 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001209 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001210 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1211 data1 = zopen1.read(500)
1212 data2 = zopen2.read(500)
1213 data1 += zopen1.read(500)
1214 data2 += zopen2.read(500)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001215 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
1216 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001217
Ezio Melottiafd0d112009-07-15 17:17:17 +00001218 def test_interleaved(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001219 # Verify that (when the ZipFile is in control of creating file objects)
1220 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001221 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001222 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1223 data1 = zopen1.read(500)
1224 data2 = zopen2.read(500)
1225 data1 += zopen1.read(500)
1226 data2 += zopen2.read(500)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001227 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
1228 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001229
1230 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001231 unlink(TESTFN2)
1232
Guido van Rossumd8faa362007-04-27 19:54:29 +00001233
Martin v. Löwis59e47792009-01-24 14:10:07 +00001234class TestWithDirectory(unittest.TestCase):
1235 def setUp(self):
1236 os.mkdir(TESTFN2)
1237
Ezio Melottiafd0d112009-07-15 17:17:17 +00001238 def test_extract_dir(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001239 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
1240 zipf.extractall(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001241 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1242 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1243 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1244
Ezio Melottiafd0d112009-07-15 17:17:17 +00001245 def test_bug_6050(self):
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001246 # Extraction should succeed if directories already exist
1247 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottiafd0d112009-07-15 17:17:17 +00001248 self.test_extract_dir()
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001249
Ezio Melottiafd0d112009-07-15 17:17:17 +00001250 def test_store_dir(self):
Martin v. Löwis59e47792009-01-24 14:10:07 +00001251 os.mkdir(os.path.join(TESTFN2, "x"))
1252 zipf = zipfile.ZipFile(TESTFN, "w")
1253 zipf.write(os.path.join(TESTFN2, "x"), "x")
1254 self.assertTrue(zipf.filelist[0].filename.endswith("x/"))
1255
1256 def tearDown(self):
1257 shutil.rmtree(TESTFN2)
1258 if os.path.exists(TESTFN):
Ezio Melotti76430242009-07-11 18:28:48 +00001259 unlink(TESTFN)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001260
Guido van Rossumd8faa362007-04-27 19:54:29 +00001261
1262class UniversalNewlineTests(unittest.TestCase):
1263 def setUp(self):
Guido van Rossum9c627722007-08-27 18:31:48 +00001264 self.line_gen = [bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001265 for i in range(FIXEDTEST_SIZE)]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001266 self.seps = ('\r', '\r\n', '\n')
1267 self.arcdata, self.arcfiles = {}, {}
1268 for n, s in enumerate(self.seps):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001269 b = s.encode("ascii")
1270 self.arcdata[s] = b.join(self.line_gen) + b
Guido van Rossumd8faa362007-04-27 19:54:29 +00001271 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001272 f = open(self.arcfiles[s], "wb")
1273 try:
1274 f.write(self.arcdata[s])
1275 finally:
1276 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001277
Ezio Melottiafd0d112009-07-15 17:17:17 +00001278 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001279 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001280 with zipfile.ZipFile(f, "w", compression) as zipfp:
1281 for fn in self.arcfiles.values():
1282 zipfp.write(fn, fn)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001283
Ezio Melottiafd0d112009-07-15 17:17:17 +00001284 def read_test(self, f, compression):
1285 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001286
1287 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001288 with zipfile.ZipFile(f, "r") as zipfp:
1289 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001290 with zipfp.open(fn, "rU") as fp:
1291 zipdata = fp.read()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001292 self.assertEqual(self.arcdata[sep], zipdata)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001293 if not isinstance(f, str):
1294 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001295
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001296 def readline_read_test(self, f, compression):
1297 self.make_test_archive(f, compression)
1298
1299 # Read the ZIP archive
Brian Curtin8fb9b862010-11-18 02:15:28 +00001300 with zipfile.ZipFile(f, "r") as zipfp:
1301 for sep, fn in self.arcfiles.items():
1302 with zipfp.open(fn, "rU") as zipopen:
1303 data = b''
1304 while True:
1305 read = zipopen.readline()
1306 if not read:
1307 break
1308 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001309
Brian Curtin8fb9b862010-11-18 02:15:28 +00001310 read = zipopen.read(5)
1311 if not read:
1312 break
1313 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001314
1315 self.assertEqual(data, self.arcdata['\n'])
1316
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001317 if not isinstance(f, str):
1318 f.close()
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001319
Ezio Melottiafd0d112009-07-15 17:17:17 +00001320 def readline_test(self, f, compression):
1321 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001322
1323 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001324 with zipfile.ZipFile(f, "r") as zipfp:
1325 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001326 with zipfp.open(fn, "rU") as zipopen:
1327 for line in self.line_gen:
1328 linedata = zipopen.readline()
1329 self.assertEqual(linedata, line + b'\n')
1330 if not isinstance(f, str):
1331 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001332
Ezio Melottiafd0d112009-07-15 17:17:17 +00001333 def readlines_test(self, f, compression):
1334 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001335
1336 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001337 with zipfile.ZipFile(f, "r") as zipfp:
1338 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001339 with zipfp.open(fn, "rU") as fp:
1340 ziplines = fp.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001341 for line, zipline in zip(self.line_gen, ziplines):
1342 self.assertEqual(zipline, line + b'\n')
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001343 if not isinstance(f, str):
1344 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001345
Ezio Melottiafd0d112009-07-15 17:17:17 +00001346 def iterlines_test(self, f, compression):
1347 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001348
1349 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001350 with zipfile.ZipFile(f, "r") as zipfp:
1351 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001352 with zipfp.open(fn, "rU") as fp:
1353 for line, zipline in zip(self.line_gen, fp):
1354 self.assertEqual(zipline, line + b'\n')
1355 if not isinstance(f, str):
1356 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001357
Ezio Melottiafd0d112009-07-15 17:17:17 +00001358 def test_read_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001359 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001360 self.read_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001361
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001362 def test_readline_read_stored(self):
1363 # Issue #7610: calls to readline() interleaved with calls to read().
1364 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1365 self.readline_read_test(f, zipfile.ZIP_STORED)
1366
Ezio Melottiafd0d112009-07-15 17:17:17 +00001367 def test_readline_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001368 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001369 self.readline_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001370
Ezio Melottiafd0d112009-07-15 17:17:17 +00001371 def test_readlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001372 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001373 self.readlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001374
Ezio Melottiafd0d112009-07-15 17:17:17 +00001375 def test_iterlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001376 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001377 self.iterlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001378
Ezio Melotti76430242009-07-11 18:28:48 +00001379 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001380 def test_read_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001381 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001382 self.read_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001383
Ezio Melotti76430242009-07-11 18:28:48 +00001384 @skipUnless(zlib, "requires zlib")
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001385 def test_readline_read_deflated(self):
1386 # Issue #7610: calls to readline() interleaved with calls to read().
1387 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1388 self.readline_read_test(f, zipfile.ZIP_DEFLATED)
1389
1390 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001391 def test_readline_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001392 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001393 self.readline_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001394
Ezio Melotti76430242009-07-11 18:28:48 +00001395 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001396 def test_readlines_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001397 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001398 self.readlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001399
Ezio Melotti76430242009-07-11 18:28:48 +00001400 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001401 def test_iterlines_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001402 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001403 self.iterlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001404
1405 def tearDown(self):
1406 for sep, fn in self.arcfiles.items():
1407 os.remove(fn)
Ezio Melotti76430242009-07-11 18:28:48 +00001408 unlink(TESTFN)
1409 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001410
1411
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001412def test_main():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001413 run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
1414 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
Ezio Melotti76430242009-07-11 18:28:48 +00001415 TestWithDirectory, UniversalNewlineTests,
1416 TestsWithRandomBinaryFiles)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001417
1418if __name__ == "__main__":
1419 test_main()