blob: 51d8b458c87e46db09f1fdb06d8490ad80dc246a [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
Georg Brandl5ba11de2011-01-01 10:09:32 +00009import sys
Barry Warsaw28a691b2010-04-17 00:19:56 +000010import imp
Ezio Melotti35386712009-12-31 13:22:41 +000011import time
Ezio Melotti74c96ec2009-07-08 22:24:06 +000012import shutil
13import struct
14import zipfile
15import unittest
16
Tim Petersa45cacf2004-08-20 03:47:14 +000017
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000018from tempfile import TemporaryFile
Guido van Rossumd8faa362007-04-27 19:54:29 +000019from random import randint, random
Ezio Melotti74c96ec2009-07-08 22:24:06 +000020from unittest import skipUnless
Tim Petersa19a1682001-03-29 04:36:09 +000021
Ezio Melotti76430242009-07-11 18:28:48 +000022from test.support import TESTFN, run_unittest, findfile, unlink
Guido van Rossum368f04a2000-04-10 13:23:04 +000023
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000024TESTFN2 = TESTFN + "2"
Martin v. Löwis59e47792009-01-24 14:10:07 +000025TESTFNDIR = TESTFN + "d"
Guido van Rossumb5a755e2007-07-18 18:15:48 +000026FIXEDTEST_SIZE = 1000
Georg Brandl5ba11de2011-01-01 10:09:32 +000027DATAFILES_DIR = 'zipfile_datafiles'
Guido van Rossum368f04a2000-04-10 13:23:04 +000028
Christian Heimes790c8232008-01-07 21:14:23 +000029SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'),
30 ('ziptest2dir/_ziptest2', 'qawsedrftg'),
31 ('/ziptest2dir/ziptest3dir/_ziptest3', 'azsxdcfvgb'),
32 ('ziptest2dir/ziptest3dir/ziptest4dir/_ziptest3', '6y7u8i9o0p')]
33
Ezio Melotti76430242009-07-11 18:28:48 +000034
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000035class TestsWithSourceFile(unittest.TestCase):
36 def setUp(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +000037 self.line_gen = (bytes("Zipfile test line %d. random float: %f" %
Guido van Rossum9c627722007-08-27 18:31:48 +000038 (i, random()), "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +000039 for i in range(FIXEDTEST_SIZE))
40 self.data = b'\n'.join(self.line_gen) + b'\n'
Fred Drake6e7e4852001-02-28 05:34:16 +000041
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000042 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +000043 with open(TESTFN, "wb") as fp:
44 fp.write(self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000045
Ezio Melottiafd0d112009-07-15 17:17:17 +000046 def make_test_archive(self, f, compression):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000047 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000048 with zipfile.ZipFile(f, "w", compression) as zipfp:
49 zipfp.write(TESTFN, "another.name")
50 zipfp.write(TESTFN, TESTFN)
51 zipfp.writestr("strfile", self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000052
Ezio Melottiafd0d112009-07-15 17:17:17 +000053 def zip_test(self, f, compression):
54 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +000055
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000056 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000057 with zipfile.ZipFile(f, "r", compression) as zipfp:
58 self.assertEqual(zipfp.read(TESTFN), self.data)
59 self.assertEqual(zipfp.read("another.name"), self.data)
60 self.assertEqual(zipfp.read("strfile"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000061
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000062 # Print the ZIP directory
63 fp = io.StringIO()
64 zipfp.printdir(file=fp)
65 directory = fp.getvalue()
66 lines = directory.splitlines()
Ezio Melotti35386712009-12-31 13:22:41 +000067 self.assertEqual(len(lines), 4) # Number of files + header
Thomas Wouters0e3f5912006-08-11 14:57:12 +000068
Benjamin Peterson577473f2010-01-19 00:09:57 +000069 self.assertIn('File Name', lines[0])
70 self.assertIn('Modified', lines[0])
71 self.assertIn('Size', lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +000072
Ezio Melotti35386712009-12-31 13:22:41 +000073 fn, date, time_, size = lines[1].split()
74 self.assertEqual(fn, 'another.name')
75 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
76 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
77 self.assertEqual(size, str(len(self.data)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000078
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000079 # Check the namelist
80 names = zipfp.namelist()
Ezio Melotti35386712009-12-31 13:22:41 +000081 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +000082 self.assertIn(TESTFN, names)
83 self.assertIn("another.name", names)
84 self.assertIn("strfile", names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000085
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000086 # Check infolist
87 infos = zipfp.infolist()
Ezio Melotti35386712009-12-31 13:22:41 +000088 names = [i.filename for i in infos]
89 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +000090 self.assertIn(TESTFN, names)
91 self.assertIn("another.name", names)
92 self.assertIn("strfile", names)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000093 for i in infos:
Ezio Melotti35386712009-12-31 13:22:41 +000094 self.assertEqual(i.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000095
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000096 # check getinfo
97 for nm in (TESTFN, "another.name", "strfile"):
98 info = zipfp.getinfo(nm)
Ezio Melotti35386712009-12-31 13:22:41 +000099 self.assertEqual(info.filename, nm)
100 self.assertEqual(info.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000101
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000102 # Check that testzip doesn't raise an exception
103 zipfp.testzip()
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000104 if not isinstance(f, str):
105 f.close()
Tim Peters7d3bad62001-04-04 18:56:49 +0000106
Ezio Melottiafd0d112009-07-15 17:17:17 +0000107 def test_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000108 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000109 self.zip_test(f, zipfile.ZIP_STORED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000110
Ezio Melottiafd0d112009-07-15 17:17:17 +0000111 def zip_open_test(self, f, compression):
112 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000113
114 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000115 with zipfile.ZipFile(f, "r", compression) as zipfp:
116 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000117 with zipfp.open(TESTFN) as zipopen1:
118 while True:
119 read_data = zipopen1.read(256)
120 if not read_data:
121 break
122 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000123
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000124 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000125 with zipfp.open("another.name") as zipopen2:
126 while True:
127 read_data = zipopen2.read(256)
128 if not read_data:
129 break
130 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000131
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000132 self.assertEqual(b''.join(zipdata1), self.data)
133 self.assertEqual(b''.join(zipdata2), self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000134 if not isinstance(f, str):
135 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000136
Ezio Melottiafd0d112009-07-15 17:17:17 +0000137 def test_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000138 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000139 self.zip_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000140
Ezio Melottiafd0d112009-07-15 17:17:17 +0000141 def test_open_via_zip_info(self):
Georg Brandlb533e262008-05-25 18:19:30 +0000142 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000143 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
144 zipfp.writestr("name", "foo")
145 zipfp.writestr("name", "bar")
Georg Brandlb533e262008-05-25 18:19:30 +0000146
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000147 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
148 infos = zipfp.infolist()
149 data = b""
150 for info in infos:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000151 with zipfp.open(info) as zipopen:
152 data += zipopen.read()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000153 self.assertTrue(data == b"foobar" or data == b"barfoo")
154 data = b""
155 for info in infos:
156 data += zipfp.read(info)
157 self.assertTrue(data == b"foobar" or data == b"barfoo")
Georg Brandlb533e262008-05-25 18:19:30 +0000158
Ezio Melottiafd0d112009-07-15 17:17:17 +0000159 def zip_random_open_test(self, f, compression):
160 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000161
162 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000163 with zipfile.ZipFile(f, "r", compression) as zipfp:
164 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000165 with zipfp.open(TESTFN) as zipopen1:
166 while True:
167 read_data = zipopen1.read(randint(1, 1024))
168 if not read_data:
169 break
170 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000171
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000172 self.assertEqual(b''.join(zipdata1), self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000173 if not isinstance(f, str):
174 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000175
Ezio Melottiafd0d112009-07-15 17:17:17 +0000176 def test_random_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000177 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000178 self.zip_random_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000179
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000180 def test_univeral_readaheads(self):
181 f = io.BytesIO()
182
183 data = b'a\r\n' * 16 * 1024
184 zipfp = zipfile.ZipFile(f, 'w', zipfile.ZIP_STORED)
185 zipfp.writestr(TESTFN, data)
186 zipfp.close()
187
188 data2 = b''
189 zipfp = zipfile.ZipFile(f, 'r')
Brian Curtin8fb9b862010-11-18 02:15:28 +0000190 with zipfp.open(TESTFN, 'rU') as zipopen:
191 for line in zipopen:
192 data2 += line
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000193 zipfp.close()
194
195 self.assertEqual(data, data2.replace(b'\n', b'\r\n'))
196
197 def zip_readline_read_test(self, f, compression):
198 self.make_test_archive(f, compression)
199
200 # Read the ZIP archive
201 zipfp = zipfile.ZipFile(f, "r")
Brian Curtin8fb9b862010-11-18 02:15:28 +0000202 with zipfp.open(TESTFN) as zipopen:
203 data = b''
204 while True:
205 read = zipopen.readline()
206 if not read:
207 break
208 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000209
Brian Curtin8fb9b862010-11-18 02:15:28 +0000210 read = zipopen.read(100)
211 if not read:
212 break
213 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000214
215 self.assertEqual(data, self.data)
216 zipfp.close()
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000217 if not isinstance(f, str):
218 f.close()
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000219
Ezio Melottiafd0d112009-07-15 17:17:17 +0000220 def zip_readline_test(self, f, compression):
221 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000222
223 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000224 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000225 with zipfp.open(TESTFN) as zipopen:
226 for line in self.line_gen:
227 linedata = zipopen.readline()
228 self.assertEqual(linedata, line + '\n')
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000229 if not isinstance(f, str):
230 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000231
Ezio Melottiafd0d112009-07-15 17:17:17 +0000232 def zip_readlines_test(self, f, compression):
233 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000234
235 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000236 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000237 with zipfp.open(TESTFN) as zipopen:
238 ziplines = zipopen.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000239 for line, zipline in zip(self.line_gen, ziplines):
240 self.assertEqual(zipline, line + '\n')
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000241 if not isinstance(f, str):
242 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000243
Ezio Melottiafd0d112009-07-15 17:17:17 +0000244 def zip_iterlines_test(self, f, compression):
245 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000246
247 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000248 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000249 with zipfp.open(TESTFN) as zipopen:
250 for line, zipline in zip(self.line_gen, zipopen):
251 self.assertEqual(zipline, line + '\n')
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000252 if not isinstance(f, str):
253 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000254
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000255 def test_readline_read_stored(self):
256 # Issue #7610: calls to readline() interleaved with calls to read().
257 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
258 self.zip_readline_read_test(f, zipfile.ZIP_STORED)
259
Ezio Melottiafd0d112009-07-15 17:17:17 +0000260 def test_readline_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_readline_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000263
Ezio Melottiafd0d112009-07-15 17:17:17 +0000264 def test_readlines_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_readlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000267
Ezio Melottiafd0d112009-07-15 17:17:17 +0000268 def test_iterlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000269 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000270 self.zip_iterlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000271
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000272 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000273 def test_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000274 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000275 self.zip_test(f, zipfile.ZIP_DEFLATED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000276
Guido van Rossumd8faa362007-04-27 19:54:29 +0000277
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000278 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000279 def test_open_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000280 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000281 self.zip_open_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000282
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000283 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000284 def test_random_open_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000285 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000286 self.zip_random_open_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000287
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000288 @skipUnless(zlib, "requires zlib")
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000289 def test_readline_read_deflated(self):
290 # Issue #7610: calls to readline() interleaved with calls to read().
291 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
292 self.zip_readline_read_test(f, zipfile.ZIP_DEFLATED)
293
294 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000295 def test_readline_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000296 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000297 self.zip_readline_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000298
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000299 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000300 def test_readlines_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000301 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000302 self.zip_readlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000303
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000304 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000305 def test_iterlines_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000306 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000307 self.zip_iterlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000308
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000309 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000310 def test_low_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000311 """Check for cases where compressed data is larger than original."""
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000312 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000313 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
314 zipfp.writestr("strfile", '12')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000315
316 # Get an open object for strfile
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000317 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_DEFLATED) as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000318 with zipfp.open("strfile") as openobj:
319 self.assertEqual(openobj.read(1), b'1')
320 self.assertEqual(openobj.read(1), b'2')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000321
Ezio Melottiafd0d112009-07-15 17:17:17 +0000322 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000323 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
324 zipfp.write(TESTFN, "/absolute")
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000325
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000326 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
327 self.assertEqual(zipfp.namelist(), ["absolute"])
Tim Peters32cbc962006-02-20 21:42:18 +0000328
Ezio Melottiafd0d112009-07-15 17:17:17 +0000329 def test_append_to_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000330 """Test appending to an existing zipfile."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000331 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
332 zipfp.write(TESTFN, TESTFN)
333
334 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
335 zipfp.writestr("strfile", self.data)
336 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000337
Ezio Melottiafd0d112009-07-15 17:17:17 +0000338 def test_append_to_non_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000339 """Test appending to an existing file that is not a zipfile."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000340 # NOTE: this test fails if len(d) < 22 because of the first
341 # line "fpin.seek(-22, 2)" in _EndRecData
Ezio Melotti35386712009-12-31 13:22:41 +0000342 data = b'I am not a ZipFile!'*10
343 with open(TESTFN2, 'wb') as f:
344 f.write(data)
345
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000346 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
347 zipfp.write(TESTFN, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000348
Ezio Melotti35386712009-12-31 13:22:41 +0000349 with open(TESTFN2, 'rb') as f:
350 f.seek(len(data))
351 with zipfile.ZipFile(f, "r") as zipfp:
352 self.assertEqual(zipfp.namelist(), [TESTFN])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000353
R David Murray4fbb9db2011-06-09 15:50:51 -0400354 def test_ignores_newline_at_end(self):
355 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
356 zipfp.write(TESTFN, TESTFN)
357 with open(TESTFN2, 'a') as f:
358 f.write("\r\n\00\00\00")
359 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
360 self.assertIsInstance(zipfp, zipfile.ZipFile)
361
362 def test_ignores_stuff_appended_past_comments(self):
363 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
364 zipfp.comment = b"this is a comment"
365 zipfp.write(TESTFN, TESTFN)
366 with open(TESTFN2, 'a') as f:
367 f.write("abcdef\r\n")
368 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
369 self.assertIsInstance(zipfp, zipfile.ZipFile)
370 self.assertEqual(zipfp.comment, b"this is a comment")
371
Ezio Melottiafd0d112009-07-15 17:17:17 +0000372 def test_write_default_name(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000373 """Check that calling ZipFile.write without arcname specified
374 produces the expected result."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000375 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
376 zipfp.write(TESTFN)
Brian Curtin8fb9b862010-11-18 02:15:28 +0000377 with open(TESTFN, "rb") as f:
378 self.assertEqual(zipfp.read(TESTFN), f.read())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000379
Ezio Melotti78ea2022009-09-12 18:41:20 +0000380 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000381 def test_per_file_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000382 """Check that files within a Zip archive can have different
383 compression options."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000384 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
385 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
386 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
387 sinfo = zipfp.getinfo('storeme')
388 dinfo = zipfp.getinfo('deflateme')
389 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
390 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000391
Ezio Melottiafd0d112009-07-15 17:17:17 +0000392 def test_write_to_readonly(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000393 """Check that trying to call write() on a readonly ZipFile object
394 raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000395 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
396 zipfp.writestr("somefile.txt", "bogus")
397
398 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
399 self.assertRaises(RuntimeError, zipfp.write, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000400
Ezio Melottiafd0d112009-07-15 17:17:17 +0000401 def test_extract(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000402 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
403 for fpath, fdata in SMALL_TEST_DATA:
404 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000405
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000406 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
407 for fpath, fdata in SMALL_TEST_DATA:
408 writtenfile = zipfp.extract(fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000409
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000410 # make sure it was written to the right place
411 if os.path.isabs(fpath):
412 correctfile = os.path.join(os.getcwd(), fpath[1:])
413 else:
414 correctfile = os.path.join(os.getcwd(), fpath)
415 correctfile = os.path.normpath(correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000416
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000417 self.assertEqual(writtenfile, correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000418
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000419 # make sure correct data is in correct file
Brian Curtin8fb9b862010-11-18 02:15:28 +0000420 with open(writtenfile, "rb") as f:
421 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000422
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000423 os.remove(writtenfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000424
425 # remove the test file subdirectories
426 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
427
Ezio Melottiafd0d112009-07-15 17:17:17 +0000428 def test_extract_all(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000429 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
430 for fpath, fdata in SMALL_TEST_DATA:
431 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000432
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000433 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
434 zipfp.extractall()
435 for fpath, fdata in SMALL_TEST_DATA:
436 if os.path.isabs(fpath):
437 outfile = os.path.join(os.getcwd(), fpath[1:])
438 else:
439 outfile = os.path.join(os.getcwd(), fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000440
Brian Curtin8fb9b862010-11-18 02:15:28 +0000441 with open(outfile, "rb") as f:
442 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000443
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000444 os.remove(outfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000445
446 # remove the test file subdirectories
447 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
448
Ronald Oussorenee5c8852010-02-07 20:24:02 +0000449 def test_writestr_compression(self):
450 zipfp = zipfile.ZipFile(TESTFN2, "w")
451 zipfp.writestr("a.txt", "hello world", compress_type=zipfile.ZIP_STORED)
452 if zlib:
453 zipfp.writestr("b.txt", "hello world", compress_type=zipfile.ZIP_DEFLATED)
454
455 info = zipfp.getinfo('a.txt')
456 self.assertEqual(info.compress_type, zipfile.ZIP_STORED)
457
458 if zlib:
459 info = zipfp.getinfo('b.txt')
460 self.assertEqual(info.compress_type, zipfile.ZIP_DEFLATED)
461
462
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000463 def zip_test_writestr_permissions(self, f, compression):
464 # Make sure that writestr creates files with mode 0600,
465 # when it is passed a name rather than a ZipInfo instance.
466
Ezio Melottiafd0d112009-07-15 17:17:17 +0000467 self.make_test_archive(f, compression)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000468 with zipfile.ZipFile(f, "r") as zipfp:
469 zinfo = zipfp.getinfo('strfile')
470 self.assertEqual(zinfo.external_attr, 0o600 << 16)
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000471 if not isinstance(f, str):
472 f.close()
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000473
Ezio Melottiafd0d112009-07-15 17:17:17 +0000474 def test_writestr_permissions(self):
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000475 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
476 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
477
Gregory P. Smithb0d9ca92009-07-07 05:06:04 +0000478 def test_writestr_extended_local_header_issue1202(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000479 with zipfile.ZipFile(TESTFN2, 'w') as orig_zip:
480 for data in 'abcdefghijklmnop':
481 zinfo = zipfile.ZipInfo(data)
482 zinfo.flag_bits |= 0x08 # Include an extended local header.
483 orig_zip.writestr(zinfo, data)
484
485 def test_close(self):
486 """Check that the zipfile is closed after the 'with' block."""
487 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
488 for fpath, fdata in SMALL_TEST_DATA:
489 zipfp.writestr(fpath, fdata)
490 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
491 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
492
493 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
494 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
495 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
496
497 def test_close_on_exception(self):
498 """Check that the zipfile is closed if an exception is raised in the
499 'with' block."""
500 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
501 for fpath, fdata in SMALL_TEST_DATA:
502 zipfp.writestr(fpath, fdata)
503
504 try:
505 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
Georg Brandl4d540882010-10-28 06:42:33 +0000506 raise zipfile.BadZipFile()
507 except zipfile.BadZipFile:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000508 self.assertTrue(zipfp2.fp is None, 'zipfp is not closed')
Gregory P. Smithb0d9ca92009-07-07 05:06:04 +0000509
Senthil Kumaran29fa9d42011-10-20 01:46:00 +0800510 def test_add_file_before_1980(self):
511 # Set atime and mtime to 1970-01-01
512 os.utime(TESTFN, (0, 0))
513 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
514 self.assertRaises(ValueError, zipfp.write, TESTFN)
515
516
Ezio Melottid9a7c4b2011-03-14 18:57:02 +0200517 @skipUnless(zlib, "requires zlib")
Georg Brandl5ba11de2011-01-01 10:09:32 +0000518 def test_unicode_filenames(self):
Georg Brandl04480a82011-01-01 10:42:31 +0000519 # bug #10801
520 fname = findfile('zip_cp437_header.zip')
Georg Brandl5ba11de2011-01-01 10:09:32 +0000521 with zipfile.ZipFile(fname) as zipfp:
Georg Brandl04480a82011-01-01 10:42:31 +0000522 for name in zipfp.namelist():
523 zipfp.open(name).close()
Georg Brandl5ba11de2011-01-01 10:09:32 +0000524
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000525 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +0000526 unlink(TESTFN)
527 unlink(TESTFN2)
528
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000529
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000530class TestZip64InSmallFiles(unittest.TestCase):
531 # These tests test the ZIP64 functionality without using large files,
532 # see test_zipfile64 for proper tests.
533
534 def setUp(self):
535 self._limit = zipfile.ZIP64_LIMIT
536 zipfile.ZIP64_LIMIT = 5
537
Guido van Rossum9c627722007-08-27 18:31:48 +0000538 line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000539 for i in range(0, FIXEDTEST_SIZE))
540 self.data = b'\n'.join(line_gen)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000541
542 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +0000543 with open(TESTFN, "wb") as fp:
544 fp.write(self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000545
Ezio Melottiafd0d112009-07-15 17:17:17 +0000546 def large_file_exception_test(self, f, compression):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000547 with zipfile.ZipFile(f, "w", compression) as zipfp:
548 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti35386712009-12-31 13:22:41 +0000549 zipfp.write, TESTFN, "another.name")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000550
Ezio Melottiafd0d112009-07-15 17:17:17 +0000551 def large_file_exception_test2(self, f, compression):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000552 with zipfile.ZipFile(f, "w", compression) as zipfp:
553 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti35386712009-12-31 13:22:41 +0000554 zipfp.writestr, "another.name", self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000555 if not isinstance(f, str):
556 f.close()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000557
Ezio Melottiafd0d112009-07-15 17:17:17 +0000558 def test_large_file_exception(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000559 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000560 self.large_file_exception_test(f, zipfile.ZIP_STORED)
561 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000562
Ezio Melottiafd0d112009-07-15 17:17:17 +0000563 def zip_test(self, f, compression):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000564 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000565 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
566 zipfp.write(TESTFN, "another.name")
567 zipfp.write(TESTFN, TESTFN)
568 zipfp.writestr("strfile", self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000569
570 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000571 with zipfile.ZipFile(f, "r", compression) as zipfp:
572 self.assertEqual(zipfp.read(TESTFN), self.data)
573 self.assertEqual(zipfp.read("another.name"), self.data)
574 self.assertEqual(zipfp.read("strfile"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000575
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000576 # Print the ZIP directory
577 fp = io.StringIO()
578 zipfp.printdir(fp)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000579
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000580 directory = fp.getvalue()
581 lines = directory.splitlines()
Ezio Melotti35386712009-12-31 13:22:41 +0000582 self.assertEqual(len(lines), 4) # Number of files + header
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000583
Benjamin Peterson577473f2010-01-19 00:09:57 +0000584 self.assertIn('File Name', lines[0])
585 self.assertIn('Modified', lines[0])
586 self.assertIn('Size', lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000587
Ezio Melotti35386712009-12-31 13:22:41 +0000588 fn, date, time_, size = lines[1].split()
589 self.assertEqual(fn, 'another.name')
590 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
591 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
592 self.assertEqual(size, str(len(self.data)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000593
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000594 # Check the namelist
595 names = zipfp.namelist()
Ezio Melotti35386712009-12-31 13:22:41 +0000596 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000597 self.assertIn(TESTFN, names)
598 self.assertIn("another.name", names)
599 self.assertIn("strfile", names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000600
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000601 # Check infolist
602 infos = zipfp.infolist()
Ezio Melotti35386712009-12-31 13:22:41 +0000603 names = [i.filename for i in infos]
604 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000605 self.assertIn(TESTFN, names)
606 self.assertIn("another.name", names)
607 self.assertIn("strfile", names)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000608 for i in infos:
Ezio Melotti35386712009-12-31 13:22:41 +0000609 self.assertEqual(i.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000610
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000611 # check getinfo
612 for nm in (TESTFN, "another.name", "strfile"):
613 info = zipfp.getinfo(nm)
Ezio Melotti35386712009-12-31 13:22:41 +0000614 self.assertEqual(info.filename, nm)
615 self.assertEqual(info.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000616
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000617 # Check that testzip doesn't raise an exception
618 zipfp.testzip()
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000619 if not isinstance(f, str):
620 f.close()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000621
Ezio Melottiafd0d112009-07-15 17:17:17 +0000622 def test_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000623 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000624 self.zip_test(f, zipfile.ZIP_STORED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000625
Ezio Melotti76430242009-07-11 18:28:48 +0000626 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000627 def test_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +0000628 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000629 self.zip_test(f, zipfile.ZIP_DEFLATED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000630
Ezio Melottiafd0d112009-07-15 17:17:17 +0000631 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000632 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
633 allowZip64=True) as zipfp:
634 zipfp.write(TESTFN, "/absolute")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000635
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000636 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
637 self.assertEqual(zipfp.namelist(), ["absolute"])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000638
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000639 def tearDown(self):
640 zipfile.ZIP64_LIMIT = self._limit
Ezio Melotti76430242009-07-11 18:28:48 +0000641 unlink(TESTFN)
642 unlink(TESTFN2)
643
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000644
645class PyZipFileTests(unittest.TestCase):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000646 def test_write_pyfile(self):
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000647 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000648 fn = __file__
649 if fn.endswith('.pyc') or fn.endswith('.pyo'):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000650 path_split = fn.split(os.sep)
651 if os.altsep is not None:
652 path_split.extend(fn.split(os.altsep))
653 if '__pycache__' in path_split:
654 fn = imp.source_from_cache(fn)
655 else:
656 fn = fn[:-1]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000657
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000658 zipfp.writepy(fn)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000659
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000660 bn = os.path.basename(fn)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000661 self.assertNotIn(bn, zipfp.namelist())
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000662 self.assertTrue(bn + 'o' in zipfp.namelist() or
663 bn + 'c' in zipfp.namelist())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000664
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000665 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000666 fn = __file__
Ezio Melotti35386712009-12-31 13:22:41 +0000667 if fn.endswith(('.pyc', '.pyo')):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000668 fn = fn[:-1]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000669
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000670 zipfp.writepy(fn, "testpackage")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000671
Ezio Melotti35386712009-12-31 13:22:41 +0000672 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000673 self.assertNotIn(bn, zipfp.namelist())
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000674 self.assertTrue(bn + 'o' in zipfp.namelist() or
675 bn + 'c' in zipfp.namelist())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000676
Ezio Melottiafd0d112009-07-15 17:17:17 +0000677 def test_write_python_package(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000678 import email
679 packagedir = os.path.dirname(email.__file__)
680
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000681 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000682 zipfp.writepy(packagedir)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000683
Ezio Melotti35386712009-12-31 13:22:41 +0000684 # Check for a couple of modules at different levels of the
685 # hierarchy
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000686 names = zipfp.namelist()
687 self.assertTrue('email/__init__.pyo' in names or
688 'email/__init__.pyc' in names)
689 self.assertTrue('email/mime/text.pyo' in names or
690 'email/mime/text.pyc' in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000691
Georg Brandl8334fd92010-12-04 10:26:46 +0000692 def test_write_with_optimization(self):
693 import email
694 packagedir = os.path.dirname(email.__file__)
695 # use .pyc if running test in optimization mode,
696 # use .pyo if running test in debug mode
697 optlevel = 1 if __debug__ else 0
698 ext = '.pyo' if optlevel == 1 else '.pyc'
699
700 with TemporaryFile() as t, \
701 zipfile.PyZipFile(t, "w", optimize=optlevel) as zipfp:
702 zipfp.writepy(packagedir)
703
704 names = zipfp.namelist()
705 self.assertIn('email/__init__' + ext, names)
706 self.assertIn('email/mime/text' + ext, names)
707
Ezio Melottiafd0d112009-07-15 17:17:17 +0000708 def test_write_python_directory(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000709 os.mkdir(TESTFN2)
710 try:
Ezio Melotti35386712009-12-31 13:22:41 +0000711 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
712 fp.write("print(42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000713
Ezio Melotti35386712009-12-31 13:22:41 +0000714 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
715 fp.write("print(42 * 42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000716
Ezio Melotti35386712009-12-31 13:22:41 +0000717 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
718 fp.write("bla bla bla\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000719
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000720 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
721 zipfp.writepy(TESTFN2)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000722
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000723 names = zipfp.namelist()
724 self.assertTrue('mod1.pyc' in names or 'mod1.pyo' in names)
725 self.assertTrue('mod2.pyc' in names or 'mod2.pyo' in names)
726 self.assertNotIn('mod2.txt', names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000727
728 finally:
729 shutil.rmtree(TESTFN2)
730
Ezio Melottiafd0d112009-07-15 17:17:17 +0000731 def test_write_non_pyfile(self):
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000732 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000733 with open(TESTFN, 'w') as f:
734 f.write('most definitely not a python file')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000735 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
736 os.remove(TESTFN)
737
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000738
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000739class OtherTests(unittest.TestCase):
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000740 zips_with_bad_crc = {
741 zipfile.ZIP_STORED: (
742 b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
743 b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
744 b'ilehello,AworldP'
745 b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
746 b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
747 b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
748 b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
749 b'\0\0/\0\0\0\0\0'),
750 zipfile.ZIP_DEFLATED: (
751 b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
752 b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
753 b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
754 b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
755 b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
756 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
757 b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
758 b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00'),
759 }
760
Ezio Melottiafd0d112009-07-15 17:17:17 +0000761 def test_unicode_filenames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000762 with zipfile.ZipFile(TESTFN, "w") as zf:
763 zf.writestr("foo.txt", "Test for unicode filename")
764 zf.writestr("\xf6.txt", "Test for unicode filename")
Ezio Melottie9615932010-01-24 19:26:24 +0000765 self.assertIsInstance(zf.infolist()[0].filename, str)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000766
767 with zipfile.ZipFile(TESTFN, "r") as zf:
768 self.assertEqual(zf.filelist[0].filename, "foo.txt")
769 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
Martin v. Löwis8570f6a2008-05-05 17:44:38 +0000770
Ezio Melottiafd0d112009-07-15 17:17:17 +0000771 def test_create_non_existent_file_for_append(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +0000772 if os.path.exists(TESTFN):
773 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000774
Thomas Wouterscf297e42007-02-23 15:07:44 +0000775 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000776 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +0000777
Thomas Wouterscf297e42007-02-23 15:07:44 +0000778 try:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000779 with zipfile.ZipFile(TESTFN, 'a') as zf:
780 zf.writestr(filename, content)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000781 except IOError:
782 self.fail('Could not append data to a non-existent zip file.')
783
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000784 self.assertTrue(os.path.exists(TESTFN))
Thomas Wouterscf297e42007-02-23 15:07:44 +0000785
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000786 with zipfile.ZipFile(TESTFN, 'r') as zf:
787 self.assertEqual(zf.read(filename), content)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000788
Ezio Melottiafd0d112009-07-15 17:17:17 +0000789 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000790 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti35386712009-12-31 13:22:41 +0000791 # it opens if there's an error in the file. If it doesn't, the
792 # traceback holds a reference to the ZipFile object and, indirectly,
793 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000794 # On Windows, this causes the os.unlink() call to fail because the
795 # underlying file is still open. This is SF bug #412214.
796 #
Ezio Melotti35386712009-12-31 13:22:41 +0000797 with open(TESTFN, "w") as fp:
798 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000799 try:
800 zf = zipfile.ZipFile(TESTFN)
Georg Brandl4d540882010-10-28 06:42:33 +0000801 except zipfile.BadZipFile:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000802 pass
803
Ezio Melottiafd0d112009-07-15 17:17:17 +0000804 def test_is_zip_erroneous_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000805 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000806 # - passing a filename
807 with open(TESTFN, "w") as fp:
808 fp.write("this is not a legal zip file\n")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000809 chk = zipfile.is_zipfile(TESTFN)
Ezio Melotti35386712009-12-31 13:22:41 +0000810 self.assertFalse(chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000811 # - passing a file object
812 with open(TESTFN, "rb") as fp:
813 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000814 self.assertTrue(not chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000815 # - passing a file-like object
816 fp = io.BytesIO()
817 fp.write(b"this is not a legal zip file\n")
818 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000819 self.assertTrue(not chk)
Ezio Melotti35386712009-12-31 13:22:41 +0000820 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000821 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000822 self.assertTrue(not chk)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000823
Ezio Melottiafd0d112009-07-15 17:17:17 +0000824 def test_is_zip_valid_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000825 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000826 # - passing a filename
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000827 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
828 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
829
Guido van Rossumd8faa362007-04-27 19:54:29 +0000830 chk = zipfile.is_zipfile(TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000831 self.assertTrue(chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000832 # - passing a file object
833 with open(TESTFN, "rb") as fp:
834 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000835 self.assertTrue(chk)
Ezio Melotti35386712009-12-31 13:22:41 +0000836 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000837 zip_contents = fp.read()
838 # - passing a file-like object
839 fp = io.BytesIO()
840 fp.write(zip_contents)
841 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000842 self.assertTrue(chk)
Ezio Melotti35386712009-12-31 13:22:41 +0000843 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000844 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000845 self.assertTrue(chk)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000846
Ezio Melottiafd0d112009-07-15 17:17:17 +0000847 def test_non_existent_file_raises_IOError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000848 # make sure we don't raise an AttributeError when a partially-constructed
849 # ZipFile instance is finalized; this tests for regression on SF tracker
850 # bug #403871.
851
852 # The bug we're testing for caused an AttributeError to be raised
853 # when a ZipFile instance was created for a file that did not
854 # exist; the .fp member was not initialized but was needed by the
855 # __del__() method. Since the AttributeError is in the __del__(),
856 # it is ignored, but the user should be sufficiently annoyed by
857 # the message on the output that regression will be noticed
858 # quickly.
859 self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
860
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +0000861 def test_empty_file_raises_BadZipFile(self):
862 f = open(TESTFN, 'w')
863 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +0000864 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +0000865
Ezio Melotti35386712009-12-31 13:22:41 +0000866 with open(TESTFN, 'w') as fp:
867 fp.write("short file")
Georg Brandl4d540882010-10-28 06:42:33 +0000868 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +0000869
Ezio Melottiafd0d112009-07-15 17:17:17 +0000870 def test_closed_zip_raises_RuntimeError(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000871 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000872 data = io.BytesIO()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000873 with zipfile.ZipFile(data, mode="w") as zipf:
874 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000875
876 # This is correct; calling .read on a closed ZipFile should throw
877 # a RuntimeError, and so should calling .testzip. An earlier
878 # version of .testzip would swallow this exception (and any other)
879 # and report that the first file in the archive was corrupt.
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000880 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
881 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000882 self.assertRaises(RuntimeError, zipf.testzip)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000883 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Brian Curtin8fb9b862010-11-18 02:15:28 +0000884 with open(TESTFN, 'w') as f:
885 f.write('zipfile test data')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000886 self.assertRaises(RuntimeError, zipf.write, TESTFN)
887
Ezio Melottiafd0d112009-07-15 17:17:17 +0000888 def test_bad_constructor_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000889 """Check that bad modes passed to ZipFile constructor are caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000890 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
891
Ezio Melottiafd0d112009-07-15 17:17:17 +0000892 def test_bad_open_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000893 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000894 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
895 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
896
897 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000898 # read the data to make sure the file is there
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000899 zipf.read("foo.txt")
900 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000901
Ezio Melottiafd0d112009-07-15 17:17:17 +0000902 def test_read0(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000903 """Check that calling read(0) on a ZipExtFile object returns an empty
904 string and doesn't advance file pointer."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000905 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
906 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
907 # read the data to make sure the file is there
Brian Curtin8fb9b862010-11-18 02:15:28 +0000908 with zipf.open("foo.txt") as f:
909 for i in range(FIXEDTEST_SIZE):
910 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000911
Brian Curtin8fb9b862010-11-18 02:15:28 +0000912 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000913
Ezio Melottiafd0d112009-07-15 17:17:17 +0000914 def test_open_non_existent_item(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000915 """Check that attempting to call open() for an item that doesn't
916 exist in the archive raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000917 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
918 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000919
Ezio Melottiafd0d112009-07-15 17:17:17 +0000920 def test_bad_compression_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000921 """Check that bad compression methods passed to ZipFile.open are
922 caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000923 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
924
Ezio Melottiafd0d112009-07-15 17:17:17 +0000925 def test_null_byte_in_filename(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000926 """Check that a filename containing a null byte is properly
927 terminated."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000928 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
929 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
930 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000931
Ezio Melottiafd0d112009-07-15 17:17:17 +0000932 def test_struct_sizes(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000933 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000934 self.assertEqual(zipfile.sizeEndCentDir, 22)
935 self.assertEqual(zipfile.sizeCentralDir, 46)
936 self.assertEqual(zipfile.sizeEndCentDir64, 56)
937 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
938
Ezio Melottiafd0d112009-07-15 17:17:17 +0000939 def test_comments(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000940 """Check that comments on the archive are handled properly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000941
942 # check default comment is empty
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000943 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
944 self.assertEqual(zipf.comment, b'')
945 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
946
947 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
948 self.assertEqual(zipfr.comment, b'')
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000949
950 # check a simple short comment
951 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000952 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
953 zipf.comment = comment
954 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
955 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
956 self.assertEqual(zipf.comment, comment)
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000957
958 # check a comment of max length
959 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
960 comment2 = comment2.encode("ascii")
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000961 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
962 zipf.comment = comment2
963 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
964
965 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
966 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000967
968 # check a comment that is too long is truncated
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000969 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
970 zipf.comment = comment2 + b'oops'
971 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
972 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
973 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000974
Antoine Pitrouc3991852012-06-30 17:31:37 +0200975 # check that comments are correctly modified in append mode
976 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
977 zipf.comment = b"original comment"
978 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
979 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
980 zipf.comment = b"an updated comment"
981 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
982 self.assertEqual(zipf.comment, b"an updated comment")
983
984 # check that comments are correctly shortened in append mode
985 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
986 zipf.comment = b"original comment that's longer"
987 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
988 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
989 zipf.comment = b"shorter comment"
990 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
991 self.assertEqual(zipf.comment, b"shorter comment")
992
R David Murray51804e92012-04-12 18:44:42 -0400993 def test_unicode_comment(self):
994 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
995 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
996 with self.assertRaises(TypeError):
997 zipf.comment = "this is an error"
998
999 def test_change_comment_in_empty_archive(self):
1000 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1001 self.assertFalse(zipf.filelist)
1002 zipf.comment = b"this is a comment"
1003 with zipfile.ZipFile(TESTFN, "r") as zipf:
1004 self.assertEqual(zipf.comment, b"this is a comment")
1005
1006 def test_change_comment_in_nonempty_archive(self):
1007 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1008 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1009 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1010 self.assertTrue(zipf.filelist)
1011 zipf.comment = b"this is a comment"
1012 with zipfile.ZipFile(TESTFN, "r") as zipf:
1013 self.assertEqual(zipf.comment, b"this is a comment")
1014
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001015 def check_testzip_with_bad_crc(self, compression):
1016 """Tests that files with bad CRCs return their name from testzip."""
1017 zipdata = self.zips_with_bad_crc[compression]
1018
1019 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1020 # testzip returns the name of the first corrupt file, or None
1021 self.assertEqual('afile', zipf.testzip())
1022
1023 def test_testzip_with_bad_crc_stored(self):
1024 self.check_testzip_with_bad_crc(zipfile.ZIP_STORED)
1025
1026 @skipUnless(zlib, "requires zlib")
1027 def test_testzip_with_bad_crc_deflated(self):
1028 self.check_testzip_with_bad_crc(zipfile.ZIP_DEFLATED)
1029
1030 def check_read_with_bad_crc(self, compression):
Georg Brandl4d540882010-10-28 06:42:33 +00001031 """Tests that files with bad CRCs raise a BadZipFile exception when read."""
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001032 zipdata = self.zips_with_bad_crc[compression]
1033
1034 # Using ZipFile.read()
1035 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
Georg Brandl4d540882010-10-28 06:42:33 +00001036 self.assertRaises(zipfile.BadZipFile, zipf.read, 'afile')
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001037
1038 # Using ZipExtFile.read()
1039 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1040 with zipf.open('afile', 'r') as corrupt_file:
Georg Brandl4d540882010-10-28 06:42:33 +00001041 self.assertRaises(zipfile.BadZipFile, corrupt_file.read)
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001042
1043 # Same with small reads (in order to exercise the buffering logic)
1044 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1045 with zipf.open('afile', 'r') as corrupt_file:
1046 corrupt_file.MIN_READ_SIZE = 2
Georg Brandl4d540882010-10-28 06:42:33 +00001047 with self.assertRaises(zipfile.BadZipFile):
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001048 while corrupt_file.read(2):
1049 pass
1050
1051 def test_read_with_bad_crc_stored(self):
1052 self.check_read_with_bad_crc(zipfile.ZIP_STORED)
1053
1054 @skipUnless(zlib, "requires zlib")
1055 def test_read_with_bad_crc_deflated(self):
1056 self.check_read_with_bad_crc(zipfile.ZIP_DEFLATED)
1057
Antoine Pitrou6464d5f2010-09-12 14:51:20 +00001058 def check_read_return_size(self, compression):
1059 # Issue #9837: ZipExtFile.read() shouldn't return more bytes
1060 # than requested.
1061 for test_size in (1, 4095, 4096, 4097, 16384):
1062 file_size = test_size + 1
1063 junk = b''.join(struct.pack('B', randint(0, 255))
1064 for x in range(file_size))
1065 with zipfile.ZipFile(io.BytesIO(), "w", compression) as zipf:
1066 zipf.writestr('foo', junk)
1067 with zipf.open('foo', 'r') as fp:
1068 buf = fp.read(test_size)
1069 self.assertEqual(len(buf), test_size)
1070
1071 def test_read_return_size_stored(self):
1072 self.check_read_return_size(zipfile.ZIP_STORED)
1073
1074 @skipUnless(zlib, "requires zlib")
1075 def test_read_return_size_deflated(self):
1076 self.check_read_return_size(zipfile.ZIP_DEFLATED)
1077
Georg Brandl268e4d42010-10-14 06:59:45 +00001078 def test_empty_zipfile(self):
1079 # Check that creating a file in 'w' or 'a' mode and closing without
1080 # adding any files to the archives creates a valid empty ZIP file
1081 zipf = zipfile.ZipFile(TESTFN, mode="w")
1082 zipf.close()
1083 try:
1084 zipf = zipfile.ZipFile(TESTFN, mode="r")
1085 except zipfile.BadZipFile:
1086 self.fail("Unable to create empty ZIP file in 'w' mode")
1087
1088 zipf = zipfile.ZipFile(TESTFN, mode="a")
1089 zipf.close()
1090 try:
1091 zipf = zipfile.ZipFile(TESTFN, mode="r")
1092 except:
1093 self.fail("Unable to create empty ZIP file in 'a' mode")
1094
1095 def test_open_empty_file(self):
1096 # Issue 1710703: Check that opening a file with less than 22 bytes
Georg Brandl4d540882010-10-28 06:42:33 +00001097 # raises a BadZipFile exception (rather than the previously unhelpful
Georg Brandl268e4d42010-10-14 06:59:45 +00001098 # IOError)
1099 f = open(TESTFN, 'w')
1100 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001101 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN, 'r')
Georg Brandl268e4d42010-10-14 06:59:45 +00001102
Senthil Kumaran29fa9d42011-10-20 01:46:00 +08001103 def test_create_zipinfo_before_1980(self):
1104 self.assertRaises(ValueError,
1105 zipfile.ZipInfo, 'seventies', (1979, 1, 1, 0, 0, 0))
1106
Guido van Rossumd8faa362007-04-27 19:54:29 +00001107 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001108 unlink(TESTFN)
1109 unlink(TESTFN2)
1110
Thomas Wouterscf297e42007-02-23 15:07:44 +00001111
1112class DecryptionTests(unittest.TestCase):
Ezio Melotti35386712009-12-31 13:22:41 +00001113 """Check that ZIP decryption works. Since the library does not
1114 support encryption at the moment, we use a pre-generated encrypted
1115 ZIP file."""
Thomas Wouterscf297e42007-02-23 15:07:44 +00001116
1117 data = (
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001118 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
1119 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
1120 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
1121 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
1122 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
1123 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
1124 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +00001125 data2 = (
1126 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
1127 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
1128 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
1129 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
1130 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
1131 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
1132 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
1133 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +00001134
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001135 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +00001136 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +00001137
1138 def setUp(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001139 with open(TESTFN, "wb") as fp:
1140 fp.write(self.data)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001141 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti35386712009-12-31 13:22:41 +00001142 with open(TESTFN2, "wb") as fp:
1143 fp.write(self.data2)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001144 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001145
1146 def tearDown(self):
1147 self.zip.close()
1148 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001149 self.zip2.close()
1150 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001151
Ezio Melottiafd0d112009-07-15 17:17:17 +00001152 def test_no_password(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001153 # Reading the encrypted file without password
1154 # must generate a RunTime exception
1155 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001156 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001157
Ezio Melottiafd0d112009-07-15 17:17:17 +00001158 def test_bad_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001159 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001160 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001161 self.zip2.setpassword(b"perl")
1162 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001163
Ezio Melotti78ea2022009-09-12 18:41:20 +00001164 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001165 def test_good_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001166 self.zip.setpassword(b"python")
Ezio Melotti35386712009-12-31 13:22:41 +00001167 self.assertEqual(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001168 self.zip2.setpassword(b"12345")
Ezio Melotti35386712009-12-31 13:22:41 +00001169 self.assertEqual(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001170
R. David Murray8d855d82010-12-21 21:53:37 +00001171 def test_unicode_password(self):
1172 self.assertRaises(TypeError, self.zip.setpassword, "unicode")
1173 self.assertRaises(TypeError, self.zip.read, "test.txt", "python")
1174 self.assertRaises(TypeError, self.zip.open, "test.txt", pwd="python")
1175 self.assertRaises(TypeError, self.zip.extract, "test.txt", pwd="python")
1176
Guido van Rossumd8faa362007-04-27 19:54:29 +00001177
1178class TestsWithRandomBinaryFiles(unittest.TestCase):
1179 def setUp(self):
1180 datacount = randint(16, 64)*1024 + randint(1, 1024)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001181 self.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
1182 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001183
1184 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +00001185 with open(TESTFN, "wb") as fp:
1186 fp.write(self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001187
1188 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001189 unlink(TESTFN)
1190 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001191
Ezio Melottiafd0d112009-07-15 17:17:17 +00001192 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001193 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001194 with zipfile.ZipFile(f, "w", compression) as zipfp:
1195 zipfp.write(TESTFN, "another.name")
1196 zipfp.write(TESTFN, TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001197
Ezio Melottiafd0d112009-07-15 17:17:17 +00001198 def zip_test(self, f, compression):
1199 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001200
1201 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001202 with zipfile.ZipFile(f, "r", compression) as zipfp:
1203 testdata = zipfp.read(TESTFN)
1204 self.assertEqual(len(testdata), len(self.data))
1205 self.assertEqual(testdata, self.data)
1206 self.assertEqual(zipfp.read("another.name"), self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001207 if not isinstance(f, str):
1208 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001209
Ezio Melottiafd0d112009-07-15 17:17:17 +00001210 def test_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001211 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001212 self.zip_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001213
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001214 @skipUnless(zlib, "requires zlib")
1215 def test_deflated(self):
1216 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1217 self.zip_test(f, zipfile.ZIP_DEFLATED)
1218
Ezio Melottiafd0d112009-07-15 17:17:17 +00001219 def zip_open_test(self, f, compression):
1220 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001221
1222 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001223 with zipfile.ZipFile(f, "r", compression) as zipfp:
1224 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001225 with zipfp.open(TESTFN) as zipopen1:
1226 while True:
1227 read_data = zipopen1.read(256)
1228 if not read_data:
1229 break
1230 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001231
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001232 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001233 with zipfp.open("another.name") as zipopen2:
1234 while True:
1235 read_data = zipopen2.read(256)
1236 if not read_data:
1237 break
1238 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001239
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001240 testdata1 = b''.join(zipdata1)
1241 self.assertEqual(len(testdata1), len(self.data))
1242 self.assertEqual(testdata1, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001243
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001244 testdata2 = b''.join(zipdata2)
Ezio Melotti35386712009-12-31 13:22:41 +00001245 self.assertEqual(len(testdata2), len(self.data))
1246 self.assertEqual(testdata2, self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001247 if not isinstance(f, str):
1248 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001249
Ezio Melottiafd0d112009-07-15 17:17:17 +00001250 def test_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001251 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001252 self.zip_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001253
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001254 @skipUnless(zlib, "requires zlib")
1255 def test_open_deflated(self):
1256 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1257 self.zip_open_test(f, zipfile.ZIP_DEFLATED)
1258
Ezio Melottiafd0d112009-07-15 17:17:17 +00001259 def zip_random_open_test(self, f, compression):
1260 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001261
1262 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001263 with zipfile.ZipFile(f, "r", compression) as zipfp:
1264 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001265 with zipfp.open(TESTFN) as zipopen1:
1266 while True:
1267 read_data = zipopen1.read(randint(1, 1024))
1268 if not read_data:
1269 break
1270 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001271
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001272 testdata = b''.join(zipdata1)
1273 self.assertEqual(len(testdata), len(self.data))
1274 self.assertEqual(testdata, self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001275 if not isinstance(f, str):
1276 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001277
Ezio Melottiafd0d112009-07-15 17:17:17 +00001278 def test_random_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001279 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001280 self.zip_random_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001281
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001282 @skipUnless(zlib, "requires zlib")
1283 def test_random_open_deflated(self):
1284 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1285 self.zip_random_open_test(f, zipfile.ZIP_DEFLATED)
1286
Ezio Melotti76430242009-07-11 18:28:48 +00001287
Ezio Melotti78ea2022009-09-12 18:41:20 +00001288@skipUnless(zlib, "requires zlib")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001289class TestsWithMultipleOpens(unittest.TestCase):
1290 def setUp(self):
1291 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001292 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
1293 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
1294 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001295
Ezio Melottiafd0d112009-07-15 17:17:17 +00001296 def test_same_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001297 # Verify that (when the ZipFile is in control of creating file objects)
1298 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001299 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001300 with zipf.open('ones') as zopen1, zipf.open('ones') as zopen2:
1301 data1 = zopen1.read(500)
1302 data2 = zopen2.read(500)
1303 data1 += zopen1.read(500)
1304 data2 += zopen2.read(500)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001305 self.assertEqual(data1, data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001306
Ezio Melottiafd0d112009-07-15 17:17:17 +00001307 def test_different_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001308 # Verify that (when the ZipFile is in control of creating file objects)
1309 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001310 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001311 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1312 data1 = zopen1.read(500)
1313 data2 = zopen2.read(500)
1314 data1 += zopen1.read(500)
1315 data2 += zopen2.read(500)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001316 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
1317 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001318
Ezio Melottiafd0d112009-07-15 17:17:17 +00001319 def test_interleaved(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001320 # Verify that (when the ZipFile is in control of creating file objects)
1321 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001322 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001323 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1324 data1 = zopen1.read(500)
1325 data2 = zopen2.read(500)
1326 data1 += zopen1.read(500)
1327 data2 += zopen2.read(500)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001328 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
1329 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001330
1331 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001332 unlink(TESTFN2)
1333
Guido van Rossumd8faa362007-04-27 19:54:29 +00001334
Martin v. Löwis59e47792009-01-24 14:10:07 +00001335class TestWithDirectory(unittest.TestCase):
1336 def setUp(self):
1337 os.mkdir(TESTFN2)
1338
Ezio Melottiafd0d112009-07-15 17:17:17 +00001339 def test_extract_dir(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001340 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
1341 zipf.extractall(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001342 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1343 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1344 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1345
Ezio Melottiafd0d112009-07-15 17:17:17 +00001346 def test_bug_6050(self):
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001347 # Extraction should succeed if directories already exist
1348 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottiafd0d112009-07-15 17:17:17 +00001349 self.test_extract_dir()
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001350
Ezio Melottiafd0d112009-07-15 17:17:17 +00001351 def test_store_dir(self):
Martin v. Löwis59e47792009-01-24 14:10:07 +00001352 os.mkdir(os.path.join(TESTFN2, "x"))
1353 zipf = zipfile.ZipFile(TESTFN, "w")
1354 zipf.write(os.path.join(TESTFN2, "x"), "x")
1355 self.assertTrue(zipf.filelist[0].filename.endswith("x/"))
1356
1357 def tearDown(self):
1358 shutil.rmtree(TESTFN2)
1359 if os.path.exists(TESTFN):
Ezio Melotti76430242009-07-11 18:28:48 +00001360 unlink(TESTFN)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001361
Guido van Rossumd8faa362007-04-27 19:54:29 +00001362
1363class UniversalNewlineTests(unittest.TestCase):
1364 def setUp(self):
Guido van Rossum9c627722007-08-27 18:31:48 +00001365 self.line_gen = [bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001366 for i in range(FIXEDTEST_SIZE)]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001367 self.seps = ('\r', '\r\n', '\n')
1368 self.arcdata, self.arcfiles = {}, {}
1369 for n, s in enumerate(self.seps):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001370 b = s.encode("ascii")
1371 self.arcdata[s] = b.join(self.line_gen) + b
Guido van Rossumd8faa362007-04-27 19:54:29 +00001372 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001373 f = open(self.arcfiles[s], "wb")
1374 try:
1375 f.write(self.arcdata[s])
1376 finally:
1377 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001378
Ezio Melottiafd0d112009-07-15 17:17:17 +00001379 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001380 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001381 with zipfile.ZipFile(f, "w", compression) as zipfp:
1382 for fn in self.arcfiles.values():
1383 zipfp.write(fn, fn)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001384
Ezio Melottiafd0d112009-07-15 17:17:17 +00001385 def read_test(self, f, compression):
1386 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001387
1388 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001389 with zipfile.ZipFile(f, "r") as zipfp:
1390 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001391 with zipfp.open(fn, "rU") as fp:
1392 zipdata = fp.read()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001393 self.assertEqual(self.arcdata[sep], zipdata)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001394 if not isinstance(f, str):
1395 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001396
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001397 def readline_read_test(self, f, compression):
1398 self.make_test_archive(f, compression)
1399
1400 # Read the ZIP archive
Brian Curtin8fb9b862010-11-18 02:15:28 +00001401 with zipfile.ZipFile(f, "r") as zipfp:
1402 for sep, fn in self.arcfiles.items():
1403 with zipfp.open(fn, "rU") as zipopen:
1404 data = b''
1405 while True:
1406 read = zipopen.readline()
1407 if not read:
1408 break
1409 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001410
Brian Curtin8fb9b862010-11-18 02:15:28 +00001411 read = zipopen.read(5)
1412 if not read:
1413 break
1414 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001415
1416 self.assertEqual(data, self.arcdata['\n'])
1417
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001418 if not isinstance(f, str):
1419 f.close()
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001420
Ezio Melottiafd0d112009-07-15 17:17:17 +00001421 def readline_test(self, f, compression):
1422 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001423
1424 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001425 with zipfile.ZipFile(f, "r") as zipfp:
1426 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001427 with zipfp.open(fn, "rU") as zipopen:
1428 for line in self.line_gen:
1429 linedata = zipopen.readline()
1430 self.assertEqual(linedata, line + b'\n')
1431 if not isinstance(f, str):
1432 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001433
Ezio Melottiafd0d112009-07-15 17:17:17 +00001434 def readlines_test(self, f, compression):
1435 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001436
1437 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001438 with zipfile.ZipFile(f, "r") as zipfp:
1439 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001440 with zipfp.open(fn, "rU") as fp:
1441 ziplines = fp.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001442 for line, zipline in zip(self.line_gen, ziplines):
1443 self.assertEqual(zipline, line + b'\n')
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001444 if not isinstance(f, str):
1445 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001446
Ezio Melottiafd0d112009-07-15 17:17:17 +00001447 def iterlines_test(self, f, compression):
1448 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001449
1450 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001451 with zipfile.ZipFile(f, "r") as zipfp:
1452 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001453 with zipfp.open(fn, "rU") as fp:
1454 for line, zipline in zip(self.line_gen, fp):
1455 self.assertEqual(zipline, line + b'\n')
1456 if not isinstance(f, str):
1457 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001458
Ezio Melottiafd0d112009-07-15 17:17:17 +00001459 def test_read_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001460 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001461 self.read_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001462
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001463 def test_readline_read_stored(self):
1464 # Issue #7610: calls to readline() interleaved with calls to read().
1465 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1466 self.readline_read_test(f, zipfile.ZIP_STORED)
1467
Ezio Melottiafd0d112009-07-15 17:17:17 +00001468 def test_readline_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001469 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001470 self.readline_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001471
Ezio Melottiafd0d112009-07-15 17:17:17 +00001472 def test_readlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001473 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001474 self.readlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001475
Ezio Melottiafd0d112009-07-15 17:17:17 +00001476 def test_iterlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001477 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001478 self.iterlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001479
Ezio Melotti76430242009-07-11 18:28:48 +00001480 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001481 def test_read_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001482 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001483 self.read_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001484
Ezio Melotti76430242009-07-11 18:28:48 +00001485 @skipUnless(zlib, "requires zlib")
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001486 def test_readline_read_deflated(self):
1487 # Issue #7610: calls to readline() interleaved with calls to read().
1488 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1489 self.readline_read_test(f, zipfile.ZIP_DEFLATED)
1490
1491 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001492 def test_readline_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001493 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001494 self.readline_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001495
Ezio Melotti76430242009-07-11 18:28:48 +00001496 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001497 def test_readlines_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001498 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001499 self.readlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001500
Ezio Melotti76430242009-07-11 18:28:48 +00001501 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001502 def test_iterlines_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001503 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001504 self.iterlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001505
1506 def tearDown(self):
1507 for sep, fn in self.arcfiles.items():
1508 os.remove(fn)
Ezio Melotti76430242009-07-11 18:28:48 +00001509 unlink(TESTFN)
1510 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001511
1512
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001513def test_main():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001514 run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
1515 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
Ezio Melotti76430242009-07-11 18:28:48 +00001516 TestWithDirectory, UniversalNewlineTests,
1517 TestsWithRandomBinaryFiles)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001518
1519if __name__ == "__main__":
1520 test_main()