blob: e8aec4fdf9ebeef5baadedb94ac09ed2a0b9d6cb [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
Ezio Melottiafd0d112009-07-15 17:17:17 +0000354 def test_write_default_name(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000355 """Check that calling ZipFile.write without arcname specified
356 produces the expected result."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000357 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
358 zipfp.write(TESTFN)
Brian Curtin8fb9b862010-11-18 02:15:28 +0000359 with open(TESTFN, "rb") as f:
360 self.assertEqual(zipfp.read(TESTFN), f.read())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000361
Ezio Melotti78ea2022009-09-12 18:41:20 +0000362 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000363 def test_per_file_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000364 """Check that files within a Zip archive can have different
365 compression options."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000366 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
367 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
368 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
369 sinfo = zipfp.getinfo('storeme')
370 dinfo = zipfp.getinfo('deflateme')
371 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
372 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000373
Ezio Melottiafd0d112009-07-15 17:17:17 +0000374 def test_write_to_readonly(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000375 """Check that trying to call write() on a readonly ZipFile object
376 raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000377 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
378 zipfp.writestr("somefile.txt", "bogus")
379
380 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
381 self.assertRaises(RuntimeError, zipfp.write, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000382
Ezio Melottiafd0d112009-07-15 17:17:17 +0000383 def test_extract(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000384 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
385 for fpath, fdata in SMALL_TEST_DATA:
386 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000387
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000388 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
389 for fpath, fdata in SMALL_TEST_DATA:
390 writtenfile = zipfp.extract(fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000391
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000392 # make sure it was written to the right place
393 if os.path.isabs(fpath):
394 correctfile = os.path.join(os.getcwd(), fpath[1:])
395 else:
396 correctfile = os.path.join(os.getcwd(), fpath)
397 correctfile = os.path.normpath(correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000398
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000399 self.assertEqual(writtenfile, correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000400
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000401 # make sure correct data is in correct file
Brian Curtin8fb9b862010-11-18 02:15:28 +0000402 with open(writtenfile, "rb") as f:
403 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000404
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000405 os.remove(writtenfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000406
407 # remove the test file subdirectories
408 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
409
Ezio Melottiafd0d112009-07-15 17:17:17 +0000410 def test_extract_all(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000411 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
412 for fpath, fdata in SMALL_TEST_DATA:
413 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000414
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000415 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
416 zipfp.extractall()
417 for fpath, fdata in SMALL_TEST_DATA:
418 if os.path.isabs(fpath):
419 outfile = os.path.join(os.getcwd(), fpath[1:])
420 else:
421 outfile = os.path.join(os.getcwd(), fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000422
Brian Curtin8fb9b862010-11-18 02:15:28 +0000423 with open(outfile, "rb") as f:
424 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000425
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000426 os.remove(outfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000427
428 # remove the test file subdirectories
429 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
430
Ronald Oussorenee5c8852010-02-07 20:24:02 +0000431 def test_writestr_compression(self):
432 zipfp = zipfile.ZipFile(TESTFN2, "w")
433 zipfp.writestr("a.txt", "hello world", compress_type=zipfile.ZIP_STORED)
434 if zlib:
435 zipfp.writestr("b.txt", "hello world", compress_type=zipfile.ZIP_DEFLATED)
436
437 info = zipfp.getinfo('a.txt')
438 self.assertEqual(info.compress_type, zipfile.ZIP_STORED)
439
440 if zlib:
441 info = zipfp.getinfo('b.txt')
442 self.assertEqual(info.compress_type, zipfile.ZIP_DEFLATED)
443
444
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000445 def zip_test_writestr_permissions(self, f, compression):
446 # Make sure that writestr creates files with mode 0600,
447 # when it is passed a name rather than a ZipInfo instance.
448
Ezio Melottiafd0d112009-07-15 17:17:17 +0000449 self.make_test_archive(f, compression)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000450 with zipfile.ZipFile(f, "r") as zipfp:
451 zinfo = zipfp.getinfo('strfile')
452 self.assertEqual(zinfo.external_attr, 0o600 << 16)
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000453 if not isinstance(f, str):
454 f.close()
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000455
Ezio Melottiafd0d112009-07-15 17:17:17 +0000456 def test_writestr_permissions(self):
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000457 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
458 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
459
Gregory P. Smithb0d9ca92009-07-07 05:06:04 +0000460 def test_writestr_extended_local_header_issue1202(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000461 with zipfile.ZipFile(TESTFN2, 'w') as orig_zip:
462 for data in 'abcdefghijklmnop':
463 zinfo = zipfile.ZipInfo(data)
464 zinfo.flag_bits |= 0x08 # Include an extended local header.
465 orig_zip.writestr(zinfo, data)
466
467 def test_close(self):
468 """Check that the zipfile is closed after the 'with' block."""
469 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
470 for fpath, fdata in SMALL_TEST_DATA:
471 zipfp.writestr(fpath, fdata)
472 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
473 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
474
475 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
476 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
477 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
478
479 def test_close_on_exception(self):
480 """Check that the zipfile is closed if an exception is raised in the
481 'with' block."""
482 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
483 for fpath, fdata in SMALL_TEST_DATA:
484 zipfp.writestr(fpath, fdata)
485
486 try:
487 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
Georg Brandl4d540882010-10-28 06:42:33 +0000488 raise zipfile.BadZipFile()
489 except zipfile.BadZipFile:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000490 self.assertTrue(zipfp2.fp is None, 'zipfp is not closed')
Gregory P. Smithb0d9ca92009-07-07 05:06:04 +0000491
Georg Brandl5ba11de2011-01-01 10:09:32 +0000492 def test_unicode_filenames(self):
493 if __name__ == '__main__':
494 myfile = sys.argv[0]
495 else:
496 myfile = __file__
497
498 mydir = os.path.dirname(myfile) or os.curdir
499 fname = os.path.join(mydir, 'zip_cp437_header.zip')
500
501 with zipfile.ZipFile(fname) as zipfp:
502 zipfp.extractall()
503
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000504 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +0000505 unlink(TESTFN)
506 unlink(TESTFN2)
507
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000508
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000509class TestZip64InSmallFiles(unittest.TestCase):
510 # These tests test the ZIP64 functionality without using large files,
511 # see test_zipfile64 for proper tests.
512
513 def setUp(self):
514 self._limit = zipfile.ZIP64_LIMIT
515 zipfile.ZIP64_LIMIT = 5
516
Guido van Rossum9c627722007-08-27 18:31:48 +0000517 line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000518 for i in range(0, FIXEDTEST_SIZE))
519 self.data = b'\n'.join(line_gen)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000520
521 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +0000522 with open(TESTFN, "wb") as fp:
523 fp.write(self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000524
Ezio Melottiafd0d112009-07-15 17:17:17 +0000525 def large_file_exception_test(self, f, compression):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000526 with zipfile.ZipFile(f, "w", compression) as zipfp:
527 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti35386712009-12-31 13:22:41 +0000528 zipfp.write, TESTFN, "another.name")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000529
Ezio Melottiafd0d112009-07-15 17:17:17 +0000530 def large_file_exception_test2(self, f, compression):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000531 with zipfile.ZipFile(f, "w", compression) as zipfp:
532 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti35386712009-12-31 13:22:41 +0000533 zipfp.writestr, "another.name", self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000534 if not isinstance(f, str):
535 f.close()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000536
Ezio Melottiafd0d112009-07-15 17:17:17 +0000537 def test_large_file_exception(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000538 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000539 self.large_file_exception_test(f, zipfile.ZIP_STORED)
540 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000541
Ezio Melottiafd0d112009-07-15 17:17:17 +0000542 def zip_test(self, f, compression):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000543 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000544 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
545 zipfp.write(TESTFN, "another.name")
546 zipfp.write(TESTFN, TESTFN)
547 zipfp.writestr("strfile", self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000548
549 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000550 with zipfile.ZipFile(f, "r", compression) as zipfp:
551 self.assertEqual(zipfp.read(TESTFN), self.data)
552 self.assertEqual(zipfp.read("another.name"), self.data)
553 self.assertEqual(zipfp.read("strfile"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000554
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000555 # Print the ZIP directory
556 fp = io.StringIO()
557 zipfp.printdir(fp)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000558
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000559 directory = fp.getvalue()
560 lines = directory.splitlines()
Ezio Melotti35386712009-12-31 13:22:41 +0000561 self.assertEqual(len(lines), 4) # Number of files + header
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000562
Benjamin Peterson577473f2010-01-19 00:09:57 +0000563 self.assertIn('File Name', lines[0])
564 self.assertIn('Modified', lines[0])
565 self.assertIn('Size', lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000566
Ezio Melotti35386712009-12-31 13:22:41 +0000567 fn, date, time_, size = lines[1].split()
568 self.assertEqual(fn, 'another.name')
569 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
570 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
571 self.assertEqual(size, str(len(self.data)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000572
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000573 # Check the namelist
574 names = zipfp.namelist()
Ezio Melotti35386712009-12-31 13:22:41 +0000575 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000576 self.assertIn(TESTFN, names)
577 self.assertIn("another.name", names)
578 self.assertIn("strfile", names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000579
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000580 # Check infolist
581 infos = zipfp.infolist()
Ezio Melotti35386712009-12-31 13:22:41 +0000582 names = [i.filename for i in infos]
583 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000584 self.assertIn(TESTFN, names)
585 self.assertIn("another.name", names)
586 self.assertIn("strfile", names)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000587 for i in infos:
Ezio Melotti35386712009-12-31 13:22:41 +0000588 self.assertEqual(i.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000589
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000590 # check getinfo
591 for nm in (TESTFN, "another.name", "strfile"):
592 info = zipfp.getinfo(nm)
Ezio Melotti35386712009-12-31 13:22:41 +0000593 self.assertEqual(info.filename, nm)
594 self.assertEqual(info.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000595
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000596 # Check that testzip doesn't raise an exception
597 zipfp.testzip()
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000598 if not isinstance(f, str):
599 f.close()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000600
Ezio Melottiafd0d112009-07-15 17:17:17 +0000601 def test_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000602 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000603 self.zip_test(f, zipfile.ZIP_STORED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000604
Ezio Melotti76430242009-07-11 18:28:48 +0000605 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000606 def test_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +0000607 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000608 self.zip_test(f, zipfile.ZIP_DEFLATED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000609
Ezio Melottiafd0d112009-07-15 17:17:17 +0000610 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000611 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
612 allowZip64=True) as zipfp:
613 zipfp.write(TESTFN, "/absolute")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000614
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000615 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
616 self.assertEqual(zipfp.namelist(), ["absolute"])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000617
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000618 def tearDown(self):
619 zipfile.ZIP64_LIMIT = self._limit
Ezio Melotti76430242009-07-11 18:28:48 +0000620 unlink(TESTFN)
621 unlink(TESTFN2)
622
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000623
624class PyZipFileTests(unittest.TestCase):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000625 def test_write_pyfile(self):
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000626 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000627 fn = __file__
628 if fn.endswith('.pyc') or fn.endswith('.pyo'):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000629 path_split = fn.split(os.sep)
630 if os.altsep is not None:
631 path_split.extend(fn.split(os.altsep))
632 if '__pycache__' in path_split:
633 fn = imp.source_from_cache(fn)
634 else:
635 fn = fn[:-1]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000636
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000637 zipfp.writepy(fn)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000638
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000639 bn = os.path.basename(fn)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000640 self.assertNotIn(bn, zipfp.namelist())
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000641 self.assertTrue(bn + 'o' in zipfp.namelist() or
642 bn + 'c' in zipfp.namelist())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000643
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000644 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000645 fn = __file__
Ezio Melotti35386712009-12-31 13:22:41 +0000646 if fn.endswith(('.pyc', '.pyo')):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000647 fn = fn[:-1]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000648
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000649 zipfp.writepy(fn, "testpackage")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000650
Ezio Melotti35386712009-12-31 13:22:41 +0000651 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000652 self.assertNotIn(bn, zipfp.namelist())
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000653 self.assertTrue(bn + 'o' in zipfp.namelist() or
654 bn + 'c' in zipfp.namelist())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000655
Ezio Melottiafd0d112009-07-15 17:17:17 +0000656 def test_write_python_package(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000657 import email
658 packagedir = os.path.dirname(email.__file__)
659
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000660 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000661 zipfp.writepy(packagedir)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000662
Ezio Melotti35386712009-12-31 13:22:41 +0000663 # Check for a couple of modules at different levels of the
664 # hierarchy
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000665 names = zipfp.namelist()
666 self.assertTrue('email/__init__.pyo' in names or
667 'email/__init__.pyc' in names)
668 self.assertTrue('email/mime/text.pyo' in names or
669 'email/mime/text.pyc' in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000670
Georg Brandl8334fd92010-12-04 10:26:46 +0000671 def test_write_with_optimization(self):
672 import email
673 packagedir = os.path.dirname(email.__file__)
674 # use .pyc if running test in optimization mode,
675 # use .pyo if running test in debug mode
676 optlevel = 1 if __debug__ else 0
677 ext = '.pyo' if optlevel == 1 else '.pyc'
678
679 with TemporaryFile() as t, \
680 zipfile.PyZipFile(t, "w", optimize=optlevel) as zipfp:
681 zipfp.writepy(packagedir)
682
683 names = zipfp.namelist()
684 self.assertIn('email/__init__' + ext, names)
685 self.assertIn('email/mime/text' + ext, names)
686
Ezio Melottiafd0d112009-07-15 17:17:17 +0000687 def test_write_python_directory(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000688 os.mkdir(TESTFN2)
689 try:
Ezio Melotti35386712009-12-31 13:22:41 +0000690 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
691 fp.write("print(42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000692
Ezio Melotti35386712009-12-31 13:22:41 +0000693 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
694 fp.write("print(42 * 42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000695
Ezio Melotti35386712009-12-31 13:22:41 +0000696 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
697 fp.write("bla bla bla\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000698
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000699 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
700 zipfp.writepy(TESTFN2)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000701
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000702 names = zipfp.namelist()
703 self.assertTrue('mod1.pyc' in names or 'mod1.pyo' in names)
704 self.assertTrue('mod2.pyc' in names or 'mod2.pyo' in names)
705 self.assertNotIn('mod2.txt', names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000706
707 finally:
708 shutil.rmtree(TESTFN2)
709
Ezio Melottiafd0d112009-07-15 17:17:17 +0000710 def test_write_non_pyfile(self):
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000711 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000712 with open(TESTFN, 'w') as f:
713 f.write('most definitely not a python file')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000714 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
715 os.remove(TESTFN)
716
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000717
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000718class OtherTests(unittest.TestCase):
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000719 zips_with_bad_crc = {
720 zipfile.ZIP_STORED: (
721 b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
722 b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
723 b'ilehello,AworldP'
724 b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
725 b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
726 b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
727 b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
728 b'\0\0/\0\0\0\0\0'),
729 zipfile.ZIP_DEFLATED: (
730 b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
731 b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
732 b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
733 b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
734 b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
735 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
736 b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
737 b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00'),
738 }
739
Ezio Melottiafd0d112009-07-15 17:17:17 +0000740 def test_unicode_filenames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000741 with zipfile.ZipFile(TESTFN, "w") as zf:
742 zf.writestr("foo.txt", "Test for unicode filename")
743 zf.writestr("\xf6.txt", "Test for unicode filename")
Ezio Melottie9615932010-01-24 19:26:24 +0000744 self.assertIsInstance(zf.infolist()[0].filename, str)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000745
746 with zipfile.ZipFile(TESTFN, "r") as zf:
747 self.assertEqual(zf.filelist[0].filename, "foo.txt")
748 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
Martin v. Löwis8570f6a2008-05-05 17:44:38 +0000749
Ezio Melottiafd0d112009-07-15 17:17:17 +0000750 def test_create_non_existent_file_for_append(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +0000751 if os.path.exists(TESTFN):
752 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000753
Thomas Wouterscf297e42007-02-23 15:07:44 +0000754 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000755 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +0000756
Thomas Wouterscf297e42007-02-23 15:07:44 +0000757 try:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000758 with zipfile.ZipFile(TESTFN, 'a') as zf:
759 zf.writestr(filename, content)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000760 except IOError:
761 self.fail('Could not append data to a non-existent zip file.')
762
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000763 self.assertTrue(os.path.exists(TESTFN))
Thomas Wouterscf297e42007-02-23 15:07:44 +0000764
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000765 with zipfile.ZipFile(TESTFN, 'r') as zf:
766 self.assertEqual(zf.read(filename), content)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000767
Ezio Melottiafd0d112009-07-15 17:17:17 +0000768 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000769 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti35386712009-12-31 13:22:41 +0000770 # it opens if there's an error in the file. If it doesn't, the
771 # traceback holds a reference to the ZipFile object and, indirectly,
772 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000773 # On Windows, this causes the os.unlink() call to fail because the
774 # underlying file is still open. This is SF bug #412214.
775 #
Ezio Melotti35386712009-12-31 13:22:41 +0000776 with open(TESTFN, "w") as fp:
777 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000778 try:
779 zf = zipfile.ZipFile(TESTFN)
Georg Brandl4d540882010-10-28 06:42:33 +0000780 except zipfile.BadZipFile:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000781 pass
782
Ezio Melottiafd0d112009-07-15 17:17:17 +0000783 def test_is_zip_erroneous_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000784 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000785 # - passing a filename
786 with open(TESTFN, "w") as fp:
787 fp.write("this is not a legal zip file\n")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000788 chk = zipfile.is_zipfile(TESTFN)
Ezio Melotti35386712009-12-31 13:22:41 +0000789 self.assertFalse(chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000790 # - passing a file object
791 with open(TESTFN, "rb") as fp:
792 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000793 self.assertTrue(not chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000794 # - passing a file-like object
795 fp = io.BytesIO()
796 fp.write(b"this is not a legal zip file\n")
797 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000798 self.assertTrue(not chk)
Ezio Melotti35386712009-12-31 13:22:41 +0000799 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000800 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000801 self.assertTrue(not chk)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000802
Ezio Melottiafd0d112009-07-15 17:17:17 +0000803 def test_is_zip_valid_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000804 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000805 # - passing a filename
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000806 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
807 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
808
Guido van Rossumd8faa362007-04-27 19:54:29 +0000809 chk = zipfile.is_zipfile(TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000810 self.assertTrue(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(chk)
Ezio Melotti35386712009-12-31 13:22:41 +0000815 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000816 zip_contents = fp.read()
817 # - passing a file-like object
818 fp = io.BytesIO()
819 fp.write(zip_contents)
820 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000821 self.assertTrue(chk)
Ezio Melotti35386712009-12-31 13:22:41 +0000822 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000823 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000824 self.assertTrue(chk)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000825
Ezio Melottiafd0d112009-07-15 17:17:17 +0000826 def test_non_existent_file_raises_IOError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000827 # make sure we don't raise an AttributeError when a partially-constructed
828 # ZipFile instance is finalized; this tests for regression on SF tracker
829 # bug #403871.
830
831 # The bug we're testing for caused an AttributeError to be raised
832 # when a ZipFile instance was created for a file that did not
833 # exist; the .fp member was not initialized but was needed by the
834 # __del__() method. Since the AttributeError is in the __del__(),
835 # it is ignored, but the user should be sufficiently annoyed by
836 # the message on the output that regression will be noticed
837 # quickly.
838 self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
839
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +0000840 def test_empty_file_raises_BadZipFile(self):
841 f = open(TESTFN, 'w')
842 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +0000843 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +0000844
Ezio Melotti35386712009-12-31 13:22:41 +0000845 with open(TESTFN, 'w') as fp:
846 fp.write("short file")
Georg Brandl4d540882010-10-28 06:42:33 +0000847 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +0000848
Ezio Melottiafd0d112009-07-15 17:17:17 +0000849 def test_closed_zip_raises_RuntimeError(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000850 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000851 data = io.BytesIO()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000852 with zipfile.ZipFile(data, mode="w") as zipf:
853 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000854
855 # This is correct; calling .read on a closed ZipFile should throw
856 # a RuntimeError, and so should calling .testzip. An earlier
857 # version of .testzip would swallow this exception (and any other)
858 # and report that the first file in the archive was corrupt.
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000859 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
860 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000861 self.assertRaises(RuntimeError, zipf.testzip)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000862 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Brian Curtin8fb9b862010-11-18 02:15:28 +0000863 with open(TESTFN, 'w') as f:
864 f.write('zipfile test data')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000865 self.assertRaises(RuntimeError, zipf.write, TESTFN)
866
Ezio Melottiafd0d112009-07-15 17:17:17 +0000867 def test_bad_constructor_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000868 """Check that bad modes passed to ZipFile constructor are caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000869 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
870
Ezio Melottiafd0d112009-07-15 17:17:17 +0000871 def test_bad_open_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000872 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000873 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
874 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
875
876 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000877 # read the data to make sure the file is there
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000878 zipf.read("foo.txt")
879 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000880
Ezio Melottiafd0d112009-07-15 17:17:17 +0000881 def test_read0(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000882 """Check that calling read(0) on a ZipExtFile object returns an empty
883 string and doesn't advance file pointer."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000884 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
885 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
886 # read the data to make sure the file is there
Brian Curtin8fb9b862010-11-18 02:15:28 +0000887 with zipf.open("foo.txt") as f:
888 for i in range(FIXEDTEST_SIZE):
889 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000890
Brian Curtin8fb9b862010-11-18 02:15:28 +0000891 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000892
Ezio Melottiafd0d112009-07-15 17:17:17 +0000893 def test_open_non_existent_item(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000894 """Check that attempting to call open() for an item that doesn't
895 exist in the archive raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000896 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
897 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000898
Ezio Melottiafd0d112009-07-15 17:17:17 +0000899 def test_bad_compression_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000900 """Check that bad compression methods passed to ZipFile.open are
901 caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000902 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
903
Ezio Melottiafd0d112009-07-15 17:17:17 +0000904 def test_null_byte_in_filename(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000905 """Check that a filename containing a null byte is properly
906 terminated."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000907 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
908 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
909 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000910
Ezio Melottiafd0d112009-07-15 17:17:17 +0000911 def test_struct_sizes(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000912 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000913 self.assertEqual(zipfile.sizeEndCentDir, 22)
914 self.assertEqual(zipfile.sizeCentralDir, 46)
915 self.assertEqual(zipfile.sizeEndCentDir64, 56)
916 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
917
Ezio Melottiafd0d112009-07-15 17:17:17 +0000918 def test_comments(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000919 """Check that comments on the archive are handled properly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000920
921 # check default comment is empty
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000922 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
923 self.assertEqual(zipf.comment, b'')
924 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
925
926 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
927 self.assertEqual(zipfr.comment, b'')
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000928
929 # check a simple short comment
930 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000931 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
932 zipf.comment = comment
933 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
934 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
935 self.assertEqual(zipf.comment, comment)
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000936
937 # check a comment of max length
938 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
939 comment2 = comment2.encode("ascii")
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000940 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
941 zipf.comment = comment2
942 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
943
944 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
945 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000946
947 # check a comment that is too long is truncated
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000948 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
949 zipf.comment = comment2 + b'oops'
950 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
951 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
952 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000953
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000954 def check_testzip_with_bad_crc(self, compression):
955 """Tests that files with bad CRCs return their name from testzip."""
956 zipdata = self.zips_with_bad_crc[compression]
957
958 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
959 # testzip returns the name of the first corrupt file, or None
960 self.assertEqual('afile', zipf.testzip())
961
962 def test_testzip_with_bad_crc_stored(self):
963 self.check_testzip_with_bad_crc(zipfile.ZIP_STORED)
964
965 @skipUnless(zlib, "requires zlib")
966 def test_testzip_with_bad_crc_deflated(self):
967 self.check_testzip_with_bad_crc(zipfile.ZIP_DEFLATED)
968
969 def check_read_with_bad_crc(self, compression):
Georg Brandl4d540882010-10-28 06:42:33 +0000970 """Tests that files with bad CRCs raise a BadZipFile exception when read."""
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000971 zipdata = self.zips_with_bad_crc[compression]
972
973 # Using ZipFile.read()
974 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
Georg Brandl4d540882010-10-28 06:42:33 +0000975 self.assertRaises(zipfile.BadZipFile, zipf.read, 'afile')
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000976
977 # Using ZipExtFile.read()
978 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
979 with zipf.open('afile', 'r') as corrupt_file:
Georg Brandl4d540882010-10-28 06:42:33 +0000980 self.assertRaises(zipfile.BadZipFile, corrupt_file.read)
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000981
982 # Same with small reads (in order to exercise the buffering logic)
983 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
984 with zipf.open('afile', 'r') as corrupt_file:
985 corrupt_file.MIN_READ_SIZE = 2
Georg Brandl4d540882010-10-28 06:42:33 +0000986 with self.assertRaises(zipfile.BadZipFile):
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000987 while corrupt_file.read(2):
988 pass
989
990 def test_read_with_bad_crc_stored(self):
991 self.check_read_with_bad_crc(zipfile.ZIP_STORED)
992
993 @skipUnless(zlib, "requires zlib")
994 def test_read_with_bad_crc_deflated(self):
995 self.check_read_with_bad_crc(zipfile.ZIP_DEFLATED)
996
Antoine Pitrou6464d5f2010-09-12 14:51:20 +0000997 def check_read_return_size(self, compression):
998 # Issue #9837: ZipExtFile.read() shouldn't return more bytes
999 # than requested.
1000 for test_size in (1, 4095, 4096, 4097, 16384):
1001 file_size = test_size + 1
1002 junk = b''.join(struct.pack('B', randint(0, 255))
1003 for x in range(file_size))
1004 with zipfile.ZipFile(io.BytesIO(), "w", compression) as zipf:
1005 zipf.writestr('foo', junk)
1006 with zipf.open('foo', 'r') as fp:
1007 buf = fp.read(test_size)
1008 self.assertEqual(len(buf), test_size)
1009
1010 def test_read_return_size_stored(self):
1011 self.check_read_return_size(zipfile.ZIP_STORED)
1012
1013 @skipUnless(zlib, "requires zlib")
1014 def test_read_return_size_deflated(self):
1015 self.check_read_return_size(zipfile.ZIP_DEFLATED)
1016
Georg Brandl268e4d42010-10-14 06:59:45 +00001017 def test_empty_zipfile(self):
1018 # Check that creating a file in 'w' or 'a' mode and closing without
1019 # adding any files to the archives creates a valid empty ZIP file
1020 zipf = zipfile.ZipFile(TESTFN, mode="w")
1021 zipf.close()
1022 try:
1023 zipf = zipfile.ZipFile(TESTFN, mode="r")
1024 except zipfile.BadZipFile:
1025 self.fail("Unable to create empty ZIP file in 'w' mode")
1026
1027 zipf = zipfile.ZipFile(TESTFN, mode="a")
1028 zipf.close()
1029 try:
1030 zipf = zipfile.ZipFile(TESTFN, mode="r")
1031 except:
1032 self.fail("Unable to create empty ZIP file in 'a' mode")
1033
1034 def test_open_empty_file(self):
1035 # Issue 1710703: Check that opening a file with less than 22 bytes
Georg Brandl4d540882010-10-28 06:42:33 +00001036 # raises a BadZipFile exception (rather than the previously unhelpful
Georg Brandl268e4d42010-10-14 06:59:45 +00001037 # IOError)
1038 f = open(TESTFN, 'w')
1039 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001040 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN, 'r')
Georg Brandl268e4d42010-10-14 06:59:45 +00001041
Guido van Rossumd8faa362007-04-27 19:54:29 +00001042 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001043 unlink(TESTFN)
1044 unlink(TESTFN2)
1045
Thomas Wouterscf297e42007-02-23 15:07:44 +00001046
1047class DecryptionTests(unittest.TestCase):
Ezio Melotti35386712009-12-31 13:22:41 +00001048 """Check that ZIP decryption works. Since the library does not
1049 support encryption at the moment, we use a pre-generated encrypted
1050 ZIP file."""
Thomas Wouterscf297e42007-02-23 15:07:44 +00001051
1052 data = (
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001053 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
1054 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
1055 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
1056 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
1057 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
1058 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
1059 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +00001060 data2 = (
1061 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
1062 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
1063 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
1064 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
1065 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
1066 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
1067 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
1068 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +00001069
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001070 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +00001071 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +00001072
1073 def setUp(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001074 with open(TESTFN, "wb") as fp:
1075 fp.write(self.data)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001076 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti35386712009-12-31 13:22:41 +00001077 with open(TESTFN2, "wb") as fp:
1078 fp.write(self.data2)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001079 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001080
1081 def tearDown(self):
1082 self.zip.close()
1083 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001084 self.zip2.close()
1085 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001086
Ezio Melottiafd0d112009-07-15 17:17:17 +00001087 def test_no_password(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001088 # Reading the encrypted file without password
1089 # must generate a RunTime exception
1090 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001091 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001092
Ezio Melottiafd0d112009-07-15 17:17:17 +00001093 def test_bad_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001094 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001095 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001096 self.zip2.setpassword(b"perl")
1097 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001098
Ezio Melotti78ea2022009-09-12 18:41:20 +00001099 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001100 def test_good_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001101 self.zip.setpassword(b"python")
Ezio Melotti35386712009-12-31 13:22:41 +00001102 self.assertEqual(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001103 self.zip2.setpassword(b"12345")
Ezio Melotti35386712009-12-31 13:22:41 +00001104 self.assertEqual(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001105
R. David Murray8d855d82010-12-21 21:53:37 +00001106 def test_unicode_password(self):
1107 self.assertRaises(TypeError, self.zip.setpassword, "unicode")
1108 self.assertRaises(TypeError, self.zip.read, "test.txt", "python")
1109 self.assertRaises(TypeError, self.zip.open, "test.txt", pwd="python")
1110 self.assertRaises(TypeError, self.zip.extract, "test.txt", pwd="python")
1111
Guido van Rossumd8faa362007-04-27 19:54:29 +00001112
1113class TestsWithRandomBinaryFiles(unittest.TestCase):
1114 def setUp(self):
1115 datacount = randint(16, 64)*1024 + randint(1, 1024)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001116 self.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
1117 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001118
1119 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +00001120 with open(TESTFN, "wb") as fp:
1121 fp.write(self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001122
1123 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001124 unlink(TESTFN)
1125 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001126
Ezio Melottiafd0d112009-07-15 17:17:17 +00001127 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001128 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001129 with zipfile.ZipFile(f, "w", compression) as zipfp:
1130 zipfp.write(TESTFN, "another.name")
1131 zipfp.write(TESTFN, TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001132
Ezio Melottiafd0d112009-07-15 17:17:17 +00001133 def zip_test(self, f, compression):
1134 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001135
1136 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001137 with zipfile.ZipFile(f, "r", compression) as zipfp:
1138 testdata = zipfp.read(TESTFN)
1139 self.assertEqual(len(testdata), len(self.data))
1140 self.assertEqual(testdata, self.data)
1141 self.assertEqual(zipfp.read("another.name"), self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001142 if not isinstance(f, str):
1143 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001144
Ezio Melottiafd0d112009-07-15 17:17:17 +00001145 def test_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001146 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001147 self.zip_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001148
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001149 @skipUnless(zlib, "requires zlib")
1150 def test_deflated(self):
1151 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1152 self.zip_test(f, zipfile.ZIP_DEFLATED)
1153
Ezio Melottiafd0d112009-07-15 17:17:17 +00001154 def zip_open_test(self, f, compression):
1155 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001156
1157 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001158 with zipfile.ZipFile(f, "r", compression) as zipfp:
1159 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001160 with zipfp.open(TESTFN) as zipopen1:
1161 while True:
1162 read_data = zipopen1.read(256)
1163 if not read_data:
1164 break
1165 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001166
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001167 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001168 with zipfp.open("another.name") as zipopen2:
1169 while True:
1170 read_data = zipopen2.read(256)
1171 if not read_data:
1172 break
1173 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001174
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001175 testdata1 = b''.join(zipdata1)
1176 self.assertEqual(len(testdata1), len(self.data))
1177 self.assertEqual(testdata1, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001178
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001179 testdata2 = b''.join(zipdata2)
Ezio Melotti35386712009-12-31 13:22:41 +00001180 self.assertEqual(len(testdata2), len(self.data))
1181 self.assertEqual(testdata2, self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001182 if not isinstance(f, str):
1183 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001184
Ezio Melottiafd0d112009-07-15 17:17:17 +00001185 def test_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001186 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001187 self.zip_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001188
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001189 @skipUnless(zlib, "requires zlib")
1190 def test_open_deflated(self):
1191 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1192 self.zip_open_test(f, zipfile.ZIP_DEFLATED)
1193
Ezio Melottiafd0d112009-07-15 17:17:17 +00001194 def zip_random_open_test(self, f, compression):
1195 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001196
1197 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001198 with zipfile.ZipFile(f, "r", compression) as zipfp:
1199 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001200 with zipfp.open(TESTFN) as zipopen1:
1201 while True:
1202 read_data = zipopen1.read(randint(1, 1024))
1203 if not read_data:
1204 break
1205 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001206
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001207 testdata = b''.join(zipdata1)
1208 self.assertEqual(len(testdata), len(self.data))
1209 self.assertEqual(testdata, self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001210 if not isinstance(f, str):
1211 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001212
Ezio Melottiafd0d112009-07-15 17:17:17 +00001213 def test_random_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001214 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001215 self.zip_random_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001216
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001217 @skipUnless(zlib, "requires zlib")
1218 def test_random_open_deflated(self):
1219 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1220 self.zip_random_open_test(f, zipfile.ZIP_DEFLATED)
1221
Ezio Melotti76430242009-07-11 18:28:48 +00001222
Ezio Melotti78ea2022009-09-12 18:41:20 +00001223@skipUnless(zlib, "requires zlib")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001224class TestsWithMultipleOpens(unittest.TestCase):
1225 def setUp(self):
1226 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001227 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
1228 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
1229 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001230
Ezio Melottiafd0d112009-07-15 17:17:17 +00001231 def test_same_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001232 # Verify that (when the ZipFile is in control of creating file objects)
1233 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001234 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001235 with zipf.open('ones') as zopen1, zipf.open('ones') as zopen2:
1236 data1 = zopen1.read(500)
1237 data2 = zopen2.read(500)
1238 data1 += zopen1.read(500)
1239 data2 += zopen2.read(500)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001240 self.assertEqual(data1, data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001241
Ezio Melottiafd0d112009-07-15 17:17:17 +00001242 def test_different_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001243 # Verify that (when the ZipFile is in control of creating file objects)
1244 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001245 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001246 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1247 data1 = zopen1.read(500)
1248 data2 = zopen2.read(500)
1249 data1 += zopen1.read(500)
1250 data2 += zopen2.read(500)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001251 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
1252 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001253
Ezio Melottiafd0d112009-07-15 17:17:17 +00001254 def test_interleaved(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001255 # Verify that (when the ZipFile is in control of creating file objects)
1256 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001257 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001258 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1259 data1 = zopen1.read(500)
1260 data2 = zopen2.read(500)
1261 data1 += zopen1.read(500)
1262 data2 += zopen2.read(500)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001263 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
1264 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001265
1266 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001267 unlink(TESTFN2)
1268
Guido van Rossumd8faa362007-04-27 19:54:29 +00001269
Martin v. Löwis59e47792009-01-24 14:10:07 +00001270class TestWithDirectory(unittest.TestCase):
1271 def setUp(self):
1272 os.mkdir(TESTFN2)
1273
Ezio Melottiafd0d112009-07-15 17:17:17 +00001274 def test_extract_dir(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001275 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
1276 zipf.extractall(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001277 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1278 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1279 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1280
Ezio Melottiafd0d112009-07-15 17:17:17 +00001281 def test_bug_6050(self):
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001282 # Extraction should succeed if directories already exist
1283 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottiafd0d112009-07-15 17:17:17 +00001284 self.test_extract_dir()
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001285
Ezio Melottiafd0d112009-07-15 17:17:17 +00001286 def test_store_dir(self):
Martin v. Löwis59e47792009-01-24 14:10:07 +00001287 os.mkdir(os.path.join(TESTFN2, "x"))
1288 zipf = zipfile.ZipFile(TESTFN, "w")
1289 zipf.write(os.path.join(TESTFN2, "x"), "x")
1290 self.assertTrue(zipf.filelist[0].filename.endswith("x/"))
1291
1292 def tearDown(self):
1293 shutil.rmtree(TESTFN2)
1294 if os.path.exists(TESTFN):
Ezio Melotti76430242009-07-11 18:28:48 +00001295 unlink(TESTFN)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001296
Guido van Rossumd8faa362007-04-27 19:54:29 +00001297
1298class UniversalNewlineTests(unittest.TestCase):
1299 def setUp(self):
Guido van Rossum9c627722007-08-27 18:31:48 +00001300 self.line_gen = [bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001301 for i in range(FIXEDTEST_SIZE)]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001302 self.seps = ('\r', '\r\n', '\n')
1303 self.arcdata, self.arcfiles = {}, {}
1304 for n, s in enumerate(self.seps):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001305 b = s.encode("ascii")
1306 self.arcdata[s] = b.join(self.line_gen) + b
Guido van Rossumd8faa362007-04-27 19:54:29 +00001307 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001308 f = open(self.arcfiles[s], "wb")
1309 try:
1310 f.write(self.arcdata[s])
1311 finally:
1312 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001313
Ezio Melottiafd0d112009-07-15 17:17:17 +00001314 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001315 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001316 with zipfile.ZipFile(f, "w", compression) as zipfp:
1317 for fn in self.arcfiles.values():
1318 zipfp.write(fn, fn)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001319
Ezio Melottiafd0d112009-07-15 17:17:17 +00001320 def read_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 fp:
1327 zipdata = fp.read()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001328 self.assertEqual(self.arcdata[sep], zipdata)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001329 if not isinstance(f, str):
1330 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001331
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001332 def readline_read_test(self, f, compression):
1333 self.make_test_archive(f, compression)
1334
1335 # Read the ZIP archive
Brian Curtin8fb9b862010-11-18 02:15:28 +00001336 with zipfile.ZipFile(f, "r") as zipfp:
1337 for sep, fn in self.arcfiles.items():
1338 with zipfp.open(fn, "rU") as zipopen:
1339 data = b''
1340 while True:
1341 read = zipopen.readline()
1342 if not read:
1343 break
1344 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001345
Brian Curtin8fb9b862010-11-18 02:15:28 +00001346 read = zipopen.read(5)
1347 if not read:
1348 break
1349 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001350
1351 self.assertEqual(data, self.arcdata['\n'])
1352
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001353 if not isinstance(f, str):
1354 f.close()
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001355
Ezio Melottiafd0d112009-07-15 17:17:17 +00001356 def readline_test(self, f, compression):
1357 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001358
1359 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001360 with zipfile.ZipFile(f, "r") as zipfp:
1361 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001362 with zipfp.open(fn, "rU") as zipopen:
1363 for line in self.line_gen:
1364 linedata = zipopen.readline()
1365 self.assertEqual(linedata, line + b'\n')
1366 if not isinstance(f, str):
1367 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001368
Ezio Melottiafd0d112009-07-15 17:17:17 +00001369 def readlines_test(self, f, compression):
1370 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001371
1372 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001373 with zipfile.ZipFile(f, "r") as zipfp:
1374 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001375 with zipfp.open(fn, "rU") as fp:
1376 ziplines = fp.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001377 for line, zipline in zip(self.line_gen, ziplines):
1378 self.assertEqual(zipline, line + b'\n')
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001379 if not isinstance(f, str):
1380 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001381
Ezio Melottiafd0d112009-07-15 17:17:17 +00001382 def iterlines_test(self, f, compression):
1383 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001384
1385 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001386 with zipfile.ZipFile(f, "r") as zipfp:
1387 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001388 with zipfp.open(fn, "rU") as fp:
1389 for line, zipline in zip(self.line_gen, fp):
1390 self.assertEqual(zipline, line + b'\n')
1391 if not isinstance(f, str):
1392 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001393
Ezio Melottiafd0d112009-07-15 17:17:17 +00001394 def test_read_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001395 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001396 self.read_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001397
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001398 def test_readline_read_stored(self):
1399 # Issue #7610: calls to readline() interleaved with calls to read().
1400 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1401 self.readline_read_test(f, zipfile.ZIP_STORED)
1402
Ezio Melottiafd0d112009-07-15 17:17:17 +00001403 def test_readline_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001404 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001405 self.readline_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001406
Ezio Melottiafd0d112009-07-15 17:17:17 +00001407 def test_readlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001408 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001409 self.readlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001410
Ezio Melottiafd0d112009-07-15 17:17:17 +00001411 def test_iterlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001412 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001413 self.iterlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001414
Ezio Melotti76430242009-07-11 18:28:48 +00001415 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001416 def test_read_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001417 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001418 self.read_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001419
Ezio Melotti76430242009-07-11 18:28:48 +00001420 @skipUnless(zlib, "requires zlib")
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001421 def test_readline_read_deflated(self):
1422 # Issue #7610: calls to readline() interleaved with calls to read().
1423 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1424 self.readline_read_test(f, zipfile.ZIP_DEFLATED)
1425
1426 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001427 def test_readline_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001428 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001429 self.readline_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001430
Ezio Melotti76430242009-07-11 18:28:48 +00001431 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001432 def test_readlines_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001433 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001434 self.readlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001435
Ezio Melotti76430242009-07-11 18:28:48 +00001436 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001437 def test_iterlines_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001438 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001439 self.iterlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001440
1441 def tearDown(self):
1442 for sep, fn in self.arcfiles.items():
1443 os.remove(fn)
Ezio Melotti76430242009-07-11 18:28:48 +00001444 unlink(TESTFN)
1445 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001446
1447
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001448def test_main():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001449 run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
1450 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
Ezio Melotti76430242009-07-11 18:28:48 +00001451 TestWithDirectory, UniversalNewlineTests,
1452 TestsWithRandomBinaryFiles)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001453
1454if __name__ == "__main__":
1455 test_main()