blob: 4dcb69059cc4d9c47470378ad0ea954df666249f [file] [log] [blame]
Ezio Melotti74c96ec2009-07-08 22:24:06 +00001import io
2import os
Georg Brandl5ba11de2011-01-01 10:09:32 +00003import sys
Barry Warsaw28a691b2010-04-17 00:19:56 +00004import imp
Ezio Melotti35386712009-12-31 13:22:41 +00005import time
Ezio Melotti74c96ec2009-07-08 22:24:06 +00006import shutil
7import struct
8import zipfile
9import unittest
10
Tim Petersa45cacf2004-08-20 03:47:14 +000011
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000012from tempfile import TemporaryFile
Guido van Rossumd8faa362007-04-27 19:54:29 +000013from random import randint, random
Ezio Melotti74c96ec2009-07-08 22:24:06 +000014from unittest import skipUnless
Tim Petersa19a1682001-03-29 04:36:09 +000015
Ezio Melotti975077a2011-05-19 22:03:22 +030016from test.support import TESTFN, run_unittest, findfile, unlink, requires_zlib
Guido van Rossum368f04a2000-04-10 13:23:04 +000017
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000018TESTFN2 = TESTFN + "2"
Martin v. Löwis59e47792009-01-24 14:10:07 +000019TESTFNDIR = TESTFN + "d"
Guido van Rossumb5a755e2007-07-18 18:15:48 +000020FIXEDTEST_SIZE = 1000
Georg Brandl5ba11de2011-01-01 10:09:32 +000021DATAFILES_DIR = 'zipfile_datafiles'
Guido van Rossum368f04a2000-04-10 13:23:04 +000022
Christian Heimes790c8232008-01-07 21:14:23 +000023SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'),
24 ('ziptest2dir/_ziptest2', 'qawsedrftg'),
25 ('/ziptest2dir/ziptest3dir/_ziptest3', 'azsxdcfvgb'),
26 ('ziptest2dir/ziptest3dir/ziptest4dir/_ziptest3', '6y7u8i9o0p')]
27
Ezio Melotti76430242009-07-11 18:28:48 +000028
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000029class TestsWithSourceFile(unittest.TestCase):
30 def setUp(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +000031 self.line_gen = (bytes("Zipfile test line %d. random float: %f" %
Guido van Rossum9c627722007-08-27 18:31:48 +000032 (i, random()), "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +000033 for i in range(FIXEDTEST_SIZE))
34 self.data = b'\n'.join(self.line_gen) + b'\n'
Fred Drake6e7e4852001-02-28 05:34:16 +000035
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000036 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +000037 with open(TESTFN, "wb") as fp:
38 fp.write(self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000039
Ezio Melottiafd0d112009-07-15 17:17:17 +000040 def make_test_archive(self, f, compression):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000041 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000042 with zipfile.ZipFile(f, "w", compression) as zipfp:
43 zipfp.write(TESTFN, "another.name")
44 zipfp.write(TESTFN, TESTFN)
45 zipfp.writestr("strfile", self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000046
Ezio Melottiafd0d112009-07-15 17:17:17 +000047 def zip_test(self, f, compression):
48 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +000049
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000050 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000051 with zipfile.ZipFile(f, "r", compression) as zipfp:
52 self.assertEqual(zipfp.read(TESTFN), self.data)
53 self.assertEqual(zipfp.read("another.name"), self.data)
54 self.assertEqual(zipfp.read("strfile"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000055
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000056 # Print the ZIP directory
57 fp = io.StringIO()
58 zipfp.printdir(file=fp)
59 directory = fp.getvalue()
60 lines = directory.splitlines()
Ezio Melotti35386712009-12-31 13:22:41 +000061 self.assertEqual(len(lines), 4) # Number of files + header
Thomas Wouters0e3f5912006-08-11 14:57:12 +000062
Benjamin Peterson577473f2010-01-19 00:09:57 +000063 self.assertIn('File Name', lines[0])
64 self.assertIn('Modified', lines[0])
65 self.assertIn('Size', lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +000066
Ezio Melotti35386712009-12-31 13:22:41 +000067 fn, date, time_, size = lines[1].split()
68 self.assertEqual(fn, 'another.name')
69 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
70 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
71 self.assertEqual(size, str(len(self.data)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000072
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000073 # Check the namelist
74 names = zipfp.namelist()
Ezio Melotti35386712009-12-31 13:22:41 +000075 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +000076 self.assertIn(TESTFN, names)
77 self.assertIn("another.name", names)
78 self.assertIn("strfile", names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000079
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000080 # Check infolist
81 infos = zipfp.infolist()
Ezio Melotti35386712009-12-31 13:22:41 +000082 names = [i.filename for i in infos]
83 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +000084 self.assertIn(TESTFN, names)
85 self.assertIn("another.name", names)
86 self.assertIn("strfile", names)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000087 for i in infos:
Ezio Melotti35386712009-12-31 13:22:41 +000088 self.assertEqual(i.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000089
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000090 # check getinfo
91 for nm in (TESTFN, "another.name", "strfile"):
92 info = zipfp.getinfo(nm)
Ezio Melotti35386712009-12-31 13:22:41 +000093 self.assertEqual(info.filename, nm)
94 self.assertEqual(info.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000095
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000096 # Check that testzip doesn't raise an exception
97 zipfp.testzip()
Benjamin Petersond285bdb2010-10-31 17:57:22 +000098 if not isinstance(f, str):
99 f.close()
Tim Peters7d3bad62001-04-04 18:56:49 +0000100
Ezio Melottiafd0d112009-07-15 17:17:17 +0000101 def test_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000102 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000103 self.zip_test(f, zipfile.ZIP_STORED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000104
Ezio Melottiafd0d112009-07-15 17:17:17 +0000105 def zip_open_test(self, f, compression):
106 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000107
108 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000109 with zipfile.ZipFile(f, "r", compression) as zipfp:
110 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000111 with zipfp.open(TESTFN) as zipopen1:
112 while True:
113 read_data = zipopen1.read(256)
114 if not read_data:
115 break
116 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000117
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000118 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000119 with zipfp.open("another.name") as zipopen2:
120 while True:
121 read_data = zipopen2.read(256)
122 if not read_data:
123 break
124 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000125
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000126 self.assertEqual(b''.join(zipdata1), self.data)
127 self.assertEqual(b''.join(zipdata2), self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000128 if not isinstance(f, str):
129 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000130
Ezio Melottiafd0d112009-07-15 17:17:17 +0000131 def test_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000132 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000133 self.zip_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000134
Ezio Melottiafd0d112009-07-15 17:17:17 +0000135 def test_open_via_zip_info(self):
Georg Brandlb533e262008-05-25 18:19:30 +0000136 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000137 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
138 zipfp.writestr("name", "foo")
139 zipfp.writestr("name", "bar")
Georg Brandlb533e262008-05-25 18:19:30 +0000140
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000141 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
142 infos = zipfp.infolist()
143 data = b""
144 for info in infos:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000145 with zipfp.open(info) as zipopen:
146 data += zipopen.read()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000147 self.assertTrue(data == b"foobar" or data == b"barfoo")
148 data = b""
149 for info in infos:
150 data += zipfp.read(info)
151 self.assertTrue(data == b"foobar" or data == b"barfoo")
Georg Brandlb533e262008-05-25 18:19:30 +0000152
Ezio Melottiafd0d112009-07-15 17:17:17 +0000153 def zip_random_open_test(self, f, compression):
154 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000155
156 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000157 with zipfile.ZipFile(f, "r", compression) as zipfp:
158 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000159 with zipfp.open(TESTFN) as zipopen1:
160 while True:
161 read_data = zipopen1.read(randint(1, 1024))
162 if not read_data:
163 break
164 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000165
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000166 self.assertEqual(b''.join(zipdata1), self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000167 if not isinstance(f, str):
168 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000169
Ezio Melottiafd0d112009-07-15 17:17:17 +0000170 def test_random_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000171 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000172 self.zip_random_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000173
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000174 def test_univeral_readaheads(self):
175 f = io.BytesIO()
176
177 data = b'a\r\n' * 16 * 1024
178 zipfp = zipfile.ZipFile(f, 'w', zipfile.ZIP_STORED)
179 zipfp.writestr(TESTFN, data)
180 zipfp.close()
181
182 data2 = b''
183 zipfp = zipfile.ZipFile(f, 'r')
Brian Curtin8fb9b862010-11-18 02:15:28 +0000184 with zipfp.open(TESTFN, 'rU') as zipopen:
185 for line in zipopen:
186 data2 += line
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000187 zipfp.close()
188
189 self.assertEqual(data, data2.replace(b'\n', b'\r\n'))
190
191 def zip_readline_read_test(self, f, compression):
192 self.make_test_archive(f, compression)
193
194 # Read the ZIP archive
195 zipfp = zipfile.ZipFile(f, "r")
Brian Curtin8fb9b862010-11-18 02:15:28 +0000196 with zipfp.open(TESTFN) as zipopen:
197 data = b''
198 while True:
199 read = zipopen.readline()
200 if not read:
201 break
202 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000203
Brian Curtin8fb9b862010-11-18 02:15:28 +0000204 read = zipopen.read(100)
205 if not read:
206 break
207 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000208
209 self.assertEqual(data, self.data)
210 zipfp.close()
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000211 if not isinstance(f, str):
212 f.close()
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000213
Ezio Melottiafd0d112009-07-15 17:17:17 +0000214 def zip_readline_test(self, f, compression):
215 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000216
217 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000218 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000219 with zipfp.open(TESTFN) as zipopen:
220 for line in self.line_gen:
221 linedata = zipopen.readline()
222 self.assertEqual(linedata, line + '\n')
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000223 if not isinstance(f, str):
224 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000225
Ezio Melottiafd0d112009-07-15 17:17:17 +0000226 def zip_readlines_test(self, f, compression):
227 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000228
229 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000230 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000231 with zipfp.open(TESTFN) as zipopen:
232 ziplines = zipopen.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000233 for line, zipline in zip(self.line_gen, ziplines):
234 self.assertEqual(zipline, line + '\n')
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000235 if not isinstance(f, str):
236 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000237
Ezio Melottiafd0d112009-07-15 17:17:17 +0000238 def zip_iterlines_test(self, f, compression):
239 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000240
241 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000242 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000243 with zipfp.open(TESTFN) as zipopen:
244 for line, zipline in zip(self.line_gen, zipopen):
245 self.assertEqual(zipline, line + '\n')
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000246 if not isinstance(f, str):
247 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000248
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000249 def test_readline_read_stored(self):
250 # Issue #7610: calls to readline() interleaved with calls to read().
251 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
252 self.zip_readline_read_test(f, zipfile.ZIP_STORED)
253
Ezio Melottiafd0d112009-07-15 17:17:17 +0000254 def test_readline_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000255 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000256 self.zip_readline_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000257
Ezio Melottiafd0d112009-07-15 17:17:17 +0000258 def test_readlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000259 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000260 self.zip_readlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000261
Ezio Melottiafd0d112009-07-15 17:17:17 +0000262 def test_iterlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000263 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000264 self.zip_iterlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000265
Ezio Melotti975077a2011-05-19 22:03:22 +0300266 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +0000267 def test_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000268 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000269 self.zip_test(f, zipfile.ZIP_DEFLATED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000270
Guido van Rossumd8faa362007-04-27 19:54:29 +0000271
Ezio Melotti975077a2011-05-19 22:03:22 +0300272 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +0000273 def test_open_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_open_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000276
Ezio Melotti975077a2011-05-19 22:03:22 +0300277 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +0000278 def test_random_open_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000279 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000280 self.zip_random_open_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000281
Ezio Melotti975077a2011-05-19 22:03:22 +0300282 @requires_zlib
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000283 def test_readline_read_deflated(self):
284 # Issue #7610: calls to readline() interleaved with calls to read().
285 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
286 self.zip_readline_read_test(f, zipfile.ZIP_DEFLATED)
287
Ezio Melotti975077a2011-05-19 22:03:22 +0300288 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +0000289 def test_readline_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000290 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000291 self.zip_readline_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000292
Ezio Melotti975077a2011-05-19 22:03:22 +0300293 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +0000294 def test_readlines_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000295 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000296 self.zip_readlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000297
Ezio Melotti975077a2011-05-19 22:03:22 +0300298 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +0000299 def test_iterlines_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000300 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000301 self.zip_iterlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000302
Ezio Melotti975077a2011-05-19 22:03:22 +0300303 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +0000304 def test_low_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000305 """Check for cases where compressed data is larger than original."""
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000306 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000307 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
308 zipfp.writestr("strfile", '12')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000309
310 # Get an open object for strfile
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000311 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_DEFLATED) as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000312 with zipfp.open("strfile") as openobj:
313 self.assertEqual(openobj.read(1), b'1')
314 self.assertEqual(openobj.read(1), b'2')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000315
Ezio Melottiafd0d112009-07-15 17:17:17 +0000316 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000317 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
318 zipfp.write(TESTFN, "/absolute")
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000319
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000320 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
321 self.assertEqual(zipfp.namelist(), ["absolute"])
Tim Peters32cbc962006-02-20 21:42:18 +0000322
Ezio Melottiafd0d112009-07-15 17:17:17 +0000323 def test_append_to_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000324 """Test appending to an existing zipfile."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000325 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
326 zipfp.write(TESTFN, TESTFN)
327
328 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
329 zipfp.writestr("strfile", self.data)
330 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000331
Ezio Melottiafd0d112009-07-15 17:17:17 +0000332 def test_append_to_non_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000333 """Test appending to an existing file that is not a zipfile."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000334 # NOTE: this test fails if len(d) < 22 because of the first
335 # line "fpin.seek(-22, 2)" in _EndRecData
Ezio Melotti35386712009-12-31 13:22:41 +0000336 data = b'I am not a ZipFile!'*10
337 with open(TESTFN2, 'wb') as f:
338 f.write(data)
339
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000340 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
341 zipfp.write(TESTFN, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000342
Ezio Melotti35386712009-12-31 13:22:41 +0000343 with open(TESTFN2, 'rb') as f:
344 f.seek(len(data))
345 with zipfile.ZipFile(f, "r") as zipfp:
346 self.assertEqual(zipfp.namelist(), [TESTFN])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000347
R David Murray4fbb9db2011-06-09 15:50:51 -0400348 def test_ignores_newline_at_end(self):
349 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
350 zipfp.write(TESTFN, TESTFN)
351 with open(TESTFN2, 'a') as f:
352 f.write("\r\n\00\00\00")
353 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
354 self.assertIsInstance(zipfp, zipfile.ZipFile)
355
356 def test_ignores_stuff_appended_past_comments(self):
357 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
358 zipfp.comment = b"this is a comment"
359 zipfp.write(TESTFN, TESTFN)
360 with open(TESTFN2, 'a') as f:
361 f.write("abcdef\r\n")
362 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
363 self.assertIsInstance(zipfp, zipfile.ZipFile)
364 self.assertEqual(zipfp.comment, b"this is a comment")
365
Ezio Melottiafd0d112009-07-15 17:17:17 +0000366 def test_write_default_name(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000367 """Check that calling ZipFile.write without arcname specified
368 produces the expected result."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000369 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
370 zipfp.write(TESTFN)
Brian Curtin8fb9b862010-11-18 02:15:28 +0000371 with open(TESTFN, "rb") as f:
372 self.assertEqual(zipfp.read(TESTFN), f.read())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000373
Ezio Melotti975077a2011-05-19 22:03:22 +0300374 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +0000375 def test_per_file_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000376 """Check that files within a Zip archive can have different
377 compression options."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000378 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
379 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
380 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
381 sinfo = zipfp.getinfo('storeme')
382 dinfo = zipfp.getinfo('deflateme')
383 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
384 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000385
Ezio Melottiafd0d112009-07-15 17:17:17 +0000386 def test_write_to_readonly(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000387 """Check that trying to call write() on a readonly ZipFile object
388 raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000389 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
390 zipfp.writestr("somefile.txt", "bogus")
391
392 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
393 self.assertRaises(RuntimeError, zipfp.write, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000394
Ezio Melottiafd0d112009-07-15 17:17:17 +0000395 def test_extract(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000396 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
397 for fpath, fdata in SMALL_TEST_DATA:
398 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000399
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000400 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
401 for fpath, fdata in SMALL_TEST_DATA:
402 writtenfile = zipfp.extract(fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000403
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000404 # make sure it was written to the right place
405 if os.path.isabs(fpath):
406 correctfile = os.path.join(os.getcwd(), fpath[1:])
407 else:
408 correctfile = os.path.join(os.getcwd(), fpath)
409 correctfile = os.path.normpath(correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000410
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000411 self.assertEqual(writtenfile, correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000412
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000413 # make sure correct data is in correct file
Brian Curtin8fb9b862010-11-18 02:15:28 +0000414 with open(writtenfile, "rb") as f:
415 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000416
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000417 os.remove(writtenfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000418
419 # remove the test file subdirectories
420 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
421
Ezio Melottiafd0d112009-07-15 17:17:17 +0000422 def test_extract_all(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000423 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
424 for fpath, fdata in SMALL_TEST_DATA:
425 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000426
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000427 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
428 zipfp.extractall()
429 for fpath, fdata in SMALL_TEST_DATA:
430 if os.path.isabs(fpath):
431 outfile = os.path.join(os.getcwd(), fpath[1:])
432 else:
433 outfile = os.path.join(os.getcwd(), fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000434
Brian Curtin8fb9b862010-11-18 02:15:28 +0000435 with open(outfile, "rb") as f:
436 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000437
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000438 os.remove(outfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000439
440 # remove the test file subdirectories
441 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
442
Ezio Melotti975077a2011-05-19 22:03:22 +0300443 def test_writestr_compression_stored(self):
Ronald Oussorenee5c8852010-02-07 20:24:02 +0000444 zipfp = zipfile.ZipFile(TESTFN2, "w")
445 zipfp.writestr("a.txt", "hello world", compress_type=zipfile.ZIP_STORED)
Ronald Oussorenee5c8852010-02-07 20:24:02 +0000446 info = zipfp.getinfo('a.txt')
447 self.assertEqual(info.compress_type, zipfile.ZIP_STORED)
448
Ezio Melotti975077a2011-05-19 22:03:22 +0300449 @requires_zlib
450 def test_writestr_compression_deflated(self):
451 zipfp = zipfile.ZipFile(TESTFN2, "w")
452 zipfp.writestr("b.txt", "hello world", compress_type=zipfile.ZIP_DEFLATED)
453 info = zipfp.getinfo('b.txt')
454 self.assertEqual(info.compress_type, zipfile.ZIP_DEFLATED)
Ronald Oussorenee5c8852010-02-07 20:24:02 +0000455
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000456 def zip_test_writestr_permissions(self, f, compression):
457 # Make sure that writestr creates files with mode 0600,
458 # when it is passed a name rather than a ZipInfo instance.
459
Ezio Melottiafd0d112009-07-15 17:17:17 +0000460 self.make_test_archive(f, compression)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000461 with zipfile.ZipFile(f, "r") as zipfp:
462 zinfo = zipfp.getinfo('strfile')
463 self.assertEqual(zinfo.external_attr, 0o600 << 16)
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000464 if not isinstance(f, str):
465 f.close()
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000466
Ezio Melottiafd0d112009-07-15 17:17:17 +0000467 def test_writestr_permissions(self):
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000468 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
469 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
470
Gregory P. Smithb0d9ca92009-07-07 05:06:04 +0000471 def test_writestr_extended_local_header_issue1202(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000472 with zipfile.ZipFile(TESTFN2, 'w') as orig_zip:
473 for data in 'abcdefghijklmnop':
474 zinfo = zipfile.ZipInfo(data)
475 zinfo.flag_bits |= 0x08 # Include an extended local header.
476 orig_zip.writestr(zinfo, data)
477
478 def test_close(self):
479 """Check that the zipfile is closed after the 'with' block."""
480 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
481 for fpath, fdata in SMALL_TEST_DATA:
482 zipfp.writestr(fpath, fdata)
483 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
484 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
485
486 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
487 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
488 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
489
490 def test_close_on_exception(self):
491 """Check that the zipfile is closed if an exception is raised in the
492 'with' block."""
493 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
494 for fpath, fdata in SMALL_TEST_DATA:
495 zipfp.writestr(fpath, fdata)
496
497 try:
498 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
Georg Brandl4d540882010-10-28 06:42:33 +0000499 raise zipfile.BadZipFile()
500 except zipfile.BadZipFile:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000501 self.assertTrue(zipfp2.fp is None, 'zipfp is not closed')
Gregory P. Smithb0d9ca92009-07-07 05:06:04 +0000502
Ezio Melotti975077a2011-05-19 22:03:22 +0300503 @requires_zlib
Georg Brandl5ba11de2011-01-01 10:09:32 +0000504 def test_unicode_filenames(self):
Georg Brandl04480a82011-01-01 10:42:31 +0000505 # bug #10801
506 fname = findfile('zip_cp437_header.zip')
Georg Brandl5ba11de2011-01-01 10:09:32 +0000507 with zipfile.ZipFile(fname) as zipfp:
Georg Brandl04480a82011-01-01 10:42:31 +0000508 for name in zipfp.namelist():
509 zipfp.open(name).close()
Georg Brandl5ba11de2011-01-01 10:09:32 +0000510
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000511 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +0000512 unlink(TESTFN)
513 unlink(TESTFN2)
514
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000515
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000516class TestZip64InSmallFiles(unittest.TestCase):
517 # These tests test the ZIP64 functionality without using large files,
518 # see test_zipfile64 for proper tests.
519
520 def setUp(self):
521 self._limit = zipfile.ZIP64_LIMIT
522 zipfile.ZIP64_LIMIT = 5
523
Guido van Rossum9c627722007-08-27 18:31:48 +0000524 line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000525 for i in range(0, FIXEDTEST_SIZE))
526 self.data = b'\n'.join(line_gen)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000527
528 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +0000529 with open(TESTFN, "wb") as fp:
530 fp.write(self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000531
Ezio Melottiafd0d112009-07-15 17:17:17 +0000532 def large_file_exception_test(self, f, compression):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000533 with zipfile.ZipFile(f, "w", compression) as zipfp:
534 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti35386712009-12-31 13:22:41 +0000535 zipfp.write, TESTFN, "another.name")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000536
Ezio Melottiafd0d112009-07-15 17:17:17 +0000537 def large_file_exception_test2(self, f, compression):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000538 with zipfile.ZipFile(f, "w", compression) as zipfp:
539 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti35386712009-12-31 13:22:41 +0000540 zipfp.writestr, "another.name", self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000541 if not isinstance(f, str):
542 f.close()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000543
Ezio Melottiafd0d112009-07-15 17:17:17 +0000544 def test_large_file_exception(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000545 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000546 self.large_file_exception_test(f, zipfile.ZIP_STORED)
547 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000548
Ezio Melottiafd0d112009-07-15 17:17:17 +0000549 def zip_test(self, f, compression):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000550 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000551 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
552 zipfp.write(TESTFN, "another.name")
553 zipfp.write(TESTFN, TESTFN)
554 zipfp.writestr("strfile", self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000555
556 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000557 with zipfile.ZipFile(f, "r", compression) as zipfp:
558 self.assertEqual(zipfp.read(TESTFN), self.data)
559 self.assertEqual(zipfp.read("another.name"), self.data)
560 self.assertEqual(zipfp.read("strfile"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000561
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000562 # Print the ZIP directory
563 fp = io.StringIO()
564 zipfp.printdir(fp)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000565
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000566 directory = fp.getvalue()
567 lines = directory.splitlines()
Ezio Melotti35386712009-12-31 13:22:41 +0000568 self.assertEqual(len(lines), 4) # Number of files + header
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000569
Benjamin Peterson577473f2010-01-19 00:09:57 +0000570 self.assertIn('File Name', lines[0])
571 self.assertIn('Modified', lines[0])
572 self.assertIn('Size', lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000573
Ezio Melotti35386712009-12-31 13:22:41 +0000574 fn, date, time_, size = lines[1].split()
575 self.assertEqual(fn, 'another.name')
576 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
577 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
578 self.assertEqual(size, str(len(self.data)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000579
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000580 # Check the namelist
581 names = zipfp.namelist()
Ezio Melotti35386712009-12-31 13:22:41 +0000582 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000583 self.assertIn(TESTFN, names)
584 self.assertIn("another.name", names)
585 self.assertIn("strfile", names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000586
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000587 # Check infolist
588 infos = zipfp.infolist()
Ezio Melotti35386712009-12-31 13:22:41 +0000589 names = [i.filename for i in infos]
590 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000591 self.assertIn(TESTFN, names)
592 self.assertIn("another.name", names)
593 self.assertIn("strfile", names)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000594 for i in infos:
Ezio Melotti35386712009-12-31 13:22:41 +0000595 self.assertEqual(i.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000596
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000597 # check getinfo
598 for nm in (TESTFN, "another.name", "strfile"):
599 info = zipfp.getinfo(nm)
Ezio Melotti35386712009-12-31 13:22:41 +0000600 self.assertEqual(info.filename, nm)
601 self.assertEqual(info.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000602
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000603 # Check that testzip doesn't raise an exception
604 zipfp.testzip()
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000605 if not isinstance(f, str):
606 f.close()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000607
Ezio Melottiafd0d112009-07-15 17:17:17 +0000608 def test_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000609 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000610 self.zip_test(f, zipfile.ZIP_STORED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000611
Ezio Melotti975077a2011-05-19 22:03:22 +0300612 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +0000613 def test_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +0000614 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000615 self.zip_test(f, zipfile.ZIP_DEFLATED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000616
Ezio Melottiafd0d112009-07-15 17:17:17 +0000617 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000618 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
619 allowZip64=True) as zipfp:
620 zipfp.write(TESTFN, "/absolute")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000621
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000622 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
623 self.assertEqual(zipfp.namelist(), ["absolute"])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000624
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000625 def tearDown(self):
626 zipfile.ZIP64_LIMIT = self._limit
Ezio Melotti76430242009-07-11 18:28:48 +0000627 unlink(TESTFN)
628 unlink(TESTFN2)
629
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000630
631class PyZipFileTests(unittest.TestCase):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000632 def test_write_pyfile(self):
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000633 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000634 fn = __file__
635 if fn.endswith('.pyc') or fn.endswith('.pyo'):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000636 path_split = fn.split(os.sep)
637 if os.altsep is not None:
638 path_split.extend(fn.split(os.altsep))
639 if '__pycache__' in path_split:
640 fn = imp.source_from_cache(fn)
641 else:
642 fn = fn[:-1]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000643
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000644 zipfp.writepy(fn)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000645
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000646 bn = os.path.basename(fn)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000647 self.assertNotIn(bn, zipfp.namelist())
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000648 self.assertTrue(bn + 'o' in zipfp.namelist() or
649 bn + 'c' in zipfp.namelist())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000650
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000651 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000652 fn = __file__
Ezio Melotti35386712009-12-31 13:22:41 +0000653 if fn.endswith(('.pyc', '.pyo')):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000654 fn = fn[:-1]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000655
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000656 zipfp.writepy(fn, "testpackage")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000657
Ezio Melotti35386712009-12-31 13:22:41 +0000658 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000659 self.assertNotIn(bn, zipfp.namelist())
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000660 self.assertTrue(bn + 'o' in zipfp.namelist() or
661 bn + 'c' in zipfp.namelist())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000662
Ezio Melottiafd0d112009-07-15 17:17:17 +0000663 def test_write_python_package(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000664 import email
665 packagedir = os.path.dirname(email.__file__)
666
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000667 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000668 zipfp.writepy(packagedir)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000669
Ezio Melotti35386712009-12-31 13:22:41 +0000670 # Check for a couple of modules at different levels of the
671 # hierarchy
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000672 names = zipfp.namelist()
673 self.assertTrue('email/__init__.pyo' in names or
674 'email/__init__.pyc' in names)
675 self.assertTrue('email/mime/text.pyo' in names or
676 'email/mime/text.pyc' in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000677
Georg Brandl8334fd92010-12-04 10:26:46 +0000678 def test_write_with_optimization(self):
679 import email
680 packagedir = os.path.dirname(email.__file__)
681 # use .pyc if running test in optimization mode,
682 # use .pyo if running test in debug mode
683 optlevel = 1 if __debug__ else 0
684 ext = '.pyo' if optlevel == 1 else '.pyc'
685
686 with TemporaryFile() as t, \
687 zipfile.PyZipFile(t, "w", optimize=optlevel) as zipfp:
688 zipfp.writepy(packagedir)
689
690 names = zipfp.namelist()
691 self.assertIn('email/__init__' + ext, names)
692 self.assertIn('email/mime/text' + ext, names)
693
Ezio Melottiafd0d112009-07-15 17:17:17 +0000694 def test_write_python_directory(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000695 os.mkdir(TESTFN2)
696 try:
Ezio Melotti35386712009-12-31 13:22:41 +0000697 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
698 fp.write("print(42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000699
Ezio Melotti35386712009-12-31 13:22:41 +0000700 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
701 fp.write("print(42 * 42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000702
Ezio Melotti35386712009-12-31 13:22:41 +0000703 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
704 fp.write("bla bla bla\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000705
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000706 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
707 zipfp.writepy(TESTFN2)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000708
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000709 names = zipfp.namelist()
710 self.assertTrue('mod1.pyc' in names or 'mod1.pyo' in names)
711 self.assertTrue('mod2.pyc' in names or 'mod2.pyo' in names)
712 self.assertNotIn('mod2.txt', names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000713
714 finally:
715 shutil.rmtree(TESTFN2)
716
Ezio Melottiafd0d112009-07-15 17:17:17 +0000717 def test_write_non_pyfile(self):
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000718 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000719 with open(TESTFN, 'w') as f:
720 f.write('most definitely not a python file')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000721 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
722 os.remove(TESTFN)
723
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000724
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000725class OtherTests(unittest.TestCase):
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000726 zips_with_bad_crc = {
727 zipfile.ZIP_STORED: (
728 b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
729 b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
730 b'ilehello,AworldP'
731 b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
732 b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
733 b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
734 b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
735 b'\0\0/\0\0\0\0\0'),
736 zipfile.ZIP_DEFLATED: (
737 b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
738 b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
739 b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
740 b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
741 b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
742 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
743 b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
744 b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00'),
745 }
746
Ezio Melottiafd0d112009-07-15 17:17:17 +0000747 def test_unicode_filenames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000748 with zipfile.ZipFile(TESTFN, "w") as zf:
749 zf.writestr("foo.txt", "Test for unicode filename")
750 zf.writestr("\xf6.txt", "Test for unicode filename")
Ezio Melottie9615932010-01-24 19:26:24 +0000751 self.assertIsInstance(zf.infolist()[0].filename, str)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000752
753 with zipfile.ZipFile(TESTFN, "r") as zf:
754 self.assertEqual(zf.filelist[0].filename, "foo.txt")
755 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
Martin v. Löwis8570f6a2008-05-05 17:44:38 +0000756
Ezio Melottiafd0d112009-07-15 17:17:17 +0000757 def test_create_non_existent_file_for_append(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +0000758 if os.path.exists(TESTFN):
759 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000760
Thomas Wouterscf297e42007-02-23 15:07:44 +0000761 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000762 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +0000763
Thomas Wouterscf297e42007-02-23 15:07:44 +0000764 try:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000765 with zipfile.ZipFile(TESTFN, 'a') as zf:
766 zf.writestr(filename, content)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000767 except IOError:
768 self.fail('Could not append data to a non-existent zip file.')
769
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000770 self.assertTrue(os.path.exists(TESTFN))
Thomas Wouterscf297e42007-02-23 15:07:44 +0000771
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000772 with zipfile.ZipFile(TESTFN, 'r') as zf:
773 self.assertEqual(zf.read(filename), content)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000774
Ezio Melottiafd0d112009-07-15 17:17:17 +0000775 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000776 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti35386712009-12-31 13:22:41 +0000777 # it opens if there's an error in the file. If it doesn't, the
778 # traceback holds a reference to the ZipFile object and, indirectly,
779 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000780 # On Windows, this causes the os.unlink() call to fail because the
781 # underlying file is still open. This is SF bug #412214.
782 #
Ezio Melotti35386712009-12-31 13:22:41 +0000783 with open(TESTFN, "w") as fp:
784 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000785 try:
786 zf = zipfile.ZipFile(TESTFN)
Georg Brandl4d540882010-10-28 06:42:33 +0000787 except zipfile.BadZipFile:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000788 pass
789
Ezio Melottiafd0d112009-07-15 17:17:17 +0000790 def test_is_zip_erroneous_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000791 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000792 # - passing a filename
793 with open(TESTFN, "w") as fp:
794 fp.write("this is not a legal zip file\n")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000795 chk = zipfile.is_zipfile(TESTFN)
Ezio Melotti35386712009-12-31 13:22:41 +0000796 self.assertFalse(chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000797 # - passing a file object
798 with open(TESTFN, "rb") as fp:
799 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000800 self.assertTrue(not chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000801 # - passing a file-like object
802 fp = io.BytesIO()
803 fp.write(b"this is not a legal zip file\n")
804 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000805 self.assertTrue(not chk)
Ezio Melotti35386712009-12-31 13:22:41 +0000806 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000807 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000808 self.assertTrue(not chk)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000809
Ezio Melottiafd0d112009-07-15 17:17:17 +0000810 def test_is_zip_valid_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000811 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000812 # - passing a filename
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000813 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
814 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
815
Guido van Rossumd8faa362007-04-27 19:54:29 +0000816 chk = zipfile.is_zipfile(TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000817 self.assertTrue(chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000818 # - passing a file object
819 with open(TESTFN, "rb") as fp:
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 zip_contents = fp.read()
824 # - passing a file-like object
825 fp = io.BytesIO()
826 fp.write(zip_contents)
827 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000828 self.assertTrue(chk)
Ezio Melotti35386712009-12-31 13:22:41 +0000829 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000830 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000831 self.assertTrue(chk)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000832
Ezio Melottiafd0d112009-07-15 17:17:17 +0000833 def test_non_existent_file_raises_IOError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000834 # make sure we don't raise an AttributeError when a partially-constructed
835 # ZipFile instance is finalized; this tests for regression on SF tracker
836 # bug #403871.
837
838 # The bug we're testing for caused an AttributeError to be raised
839 # when a ZipFile instance was created for a file that did not
840 # exist; the .fp member was not initialized but was needed by the
841 # __del__() method. Since the AttributeError is in the __del__(),
842 # it is ignored, but the user should be sufficiently annoyed by
843 # the message on the output that regression will be noticed
844 # quickly.
845 self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
846
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +0000847 def test_empty_file_raises_BadZipFile(self):
848 f = open(TESTFN, 'w')
849 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +0000850 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +0000851
Ezio Melotti35386712009-12-31 13:22:41 +0000852 with open(TESTFN, 'w') as fp:
853 fp.write("short file")
Georg Brandl4d540882010-10-28 06:42:33 +0000854 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +0000855
Ezio Melottiafd0d112009-07-15 17:17:17 +0000856 def test_closed_zip_raises_RuntimeError(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000857 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000858 data = io.BytesIO()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000859 with zipfile.ZipFile(data, mode="w") as zipf:
860 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000861
862 # This is correct; calling .read on a closed ZipFile should throw
863 # a RuntimeError, and so should calling .testzip. An earlier
864 # version of .testzip would swallow this exception (and any other)
865 # and report that the first file in the archive was corrupt.
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000866 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
867 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000868 self.assertRaises(RuntimeError, zipf.testzip)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000869 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Brian Curtin8fb9b862010-11-18 02:15:28 +0000870 with open(TESTFN, 'w') as f:
871 f.write('zipfile test data')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000872 self.assertRaises(RuntimeError, zipf.write, TESTFN)
873
Ezio Melottiafd0d112009-07-15 17:17:17 +0000874 def test_bad_constructor_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000875 """Check that bad modes passed to ZipFile constructor are caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000876 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
877
Ezio Melottiafd0d112009-07-15 17:17:17 +0000878 def test_bad_open_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000879 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000880 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
881 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
882
883 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000884 # read the data to make sure the file is there
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000885 zipf.read("foo.txt")
886 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000887
Ezio Melottiafd0d112009-07-15 17:17:17 +0000888 def test_read0(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000889 """Check that calling read(0) on a ZipExtFile object returns an empty
890 string and doesn't advance file pointer."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000891 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
892 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
893 # read the data to make sure the file is there
Brian Curtin8fb9b862010-11-18 02:15:28 +0000894 with zipf.open("foo.txt") as f:
895 for i in range(FIXEDTEST_SIZE):
896 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000897
Brian Curtin8fb9b862010-11-18 02:15:28 +0000898 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000899
Ezio Melottiafd0d112009-07-15 17:17:17 +0000900 def test_open_non_existent_item(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000901 """Check that attempting to call open() for an item that doesn't
902 exist in the archive raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000903 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
904 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000905
Ezio Melottiafd0d112009-07-15 17:17:17 +0000906 def test_bad_compression_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000907 """Check that bad compression methods passed to ZipFile.open are
908 caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000909 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
910
Ezio Melottiafd0d112009-07-15 17:17:17 +0000911 def test_null_byte_in_filename(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000912 """Check that a filename containing a null byte is properly
913 terminated."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000914 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
915 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
916 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000917
Ezio Melottiafd0d112009-07-15 17:17:17 +0000918 def test_struct_sizes(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000919 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000920 self.assertEqual(zipfile.sizeEndCentDir, 22)
921 self.assertEqual(zipfile.sizeCentralDir, 46)
922 self.assertEqual(zipfile.sizeEndCentDir64, 56)
923 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
924
Ezio Melottiafd0d112009-07-15 17:17:17 +0000925 def test_comments(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000926 """Check that comments on the archive are handled properly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000927
928 # check default comment is empty
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000929 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
930 self.assertEqual(zipf.comment, b'')
931 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
932
933 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
934 self.assertEqual(zipfr.comment, b'')
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000935
936 # check a simple short comment
937 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000938 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
939 zipf.comment = comment
940 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
941 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
942 self.assertEqual(zipf.comment, comment)
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000943
944 # check a comment of max length
945 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
946 comment2 = comment2.encode("ascii")
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000947 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
948 zipf.comment = comment2
949 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
950
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
954 # check a comment that is too long is truncated
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000955 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
956 zipf.comment = comment2 + b'oops'
957 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
958 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
959 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000960
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000961 def check_testzip_with_bad_crc(self, compression):
962 """Tests that files with bad CRCs return their name from testzip."""
963 zipdata = self.zips_with_bad_crc[compression]
964
965 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
966 # testzip returns the name of the first corrupt file, or None
967 self.assertEqual('afile', zipf.testzip())
968
969 def test_testzip_with_bad_crc_stored(self):
970 self.check_testzip_with_bad_crc(zipfile.ZIP_STORED)
971
Ezio Melotti975077a2011-05-19 22:03:22 +0300972 @requires_zlib
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000973 def test_testzip_with_bad_crc_deflated(self):
974 self.check_testzip_with_bad_crc(zipfile.ZIP_DEFLATED)
975
976 def check_read_with_bad_crc(self, compression):
Georg Brandl4d540882010-10-28 06:42:33 +0000977 """Tests that files with bad CRCs raise a BadZipFile exception when read."""
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000978 zipdata = self.zips_with_bad_crc[compression]
979
980 # Using ZipFile.read()
981 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
Georg Brandl4d540882010-10-28 06:42:33 +0000982 self.assertRaises(zipfile.BadZipFile, zipf.read, 'afile')
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000983
984 # Using ZipExtFile.read()
985 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
986 with zipf.open('afile', 'r') as corrupt_file:
Georg Brandl4d540882010-10-28 06:42:33 +0000987 self.assertRaises(zipfile.BadZipFile, corrupt_file.read)
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000988
989 # Same with small reads (in order to exercise the buffering logic)
990 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
991 with zipf.open('afile', 'r') as corrupt_file:
992 corrupt_file.MIN_READ_SIZE = 2
Georg Brandl4d540882010-10-28 06:42:33 +0000993 with self.assertRaises(zipfile.BadZipFile):
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000994 while corrupt_file.read(2):
995 pass
996
997 def test_read_with_bad_crc_stored(self):
998 self.check_read_with_bad_crc(zipfile.ZIP_STORED)
999
Ezio Melotti975077a2011-05-19 22:03:22 +03001000 @requires_zlib
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001001 def test_read_with_bad_crc_deflated(self):
1002 self.check_read_with_bad_crc(zipfile.ZIP_DEFLATED)
1003
Antoine Pitrou6464d5f2010-09-12 14:51:20 +00001004 def check_read_return_size(self, compression):
1005 # Issue #9837: ZipExtFile.read() shouldn't return more bytes
1006 # than requested.
1007 for test_size in (1, 4095, 4096, 4097, 16384):
1008 file_size = test_size + 1
1009 junk = b''.join(struct.pack('B', randint(0, 255))
1010 for x in range(file_size))
1011 with zipfile.ZipFile(io.BytesIO(), "w", compression) as zipf:
1012 zipf.writestr('foo', junk)
1013 with zipf.open('foo', 'r') as fp:
1014 buf = fp.read(test_size)
1015 self.assertEqual(len(buf), test_size)
1016
1017 def test_read_return_size_stored(self):
1018 self.check_read_return_size(zipfile.ZIP_STORED)
1019
Ezio Melotti975077a2011-05-19 22:03:22 +03001020 @requires_zlib
Antoine Pitrou6464d5f2010-09-12 14:51:20 +00001021 def test_read_return_size_deflated(self):
1022 self.check_read_return_size(zipfile.ZIP_DEFLATED)
1023
Georg Brandl268e4d42010-10-14 06:59:45 +00001024 def test_empty_zipfile(self):
1025 # Check that creating a file in 'w' or 'a' mode and closing without
1026 # adding any files to the archives creates a valid empty ZIP file
1027 zipf = zipfile.ZipFile(TESTFN, mode="w")
1028 zipf.close()
1029 try:
1030 zipf = zipfile.ZipFile(TESTFN, mode="r")
1031 except zipfile.BadZipFile:
1032 self.fail("Unable to create empty ZIP file in 'w' mode")
1033
1034 zipf = zipfile.ZipFile(TESTFN, mode="a")
1035 zipf.close()
1036 try:
1037 zipf = zipfile.ZipFile(TESTFN, mode="r")
1038 except:
1039 self.fail("Unable to create empty ZIP file in 'a' mode")
1040
1041 def test_open_empty_file(self):
1042 # Issue 1710703: Check that opening a file with less than 22 bytes
Georg Brandl4d540882010-10-28 06:42:33 +00001043 # raises a BadZipFile exception (rather than the previously unhelpful
Georg Brandl268e4d42010-10-14 06:59:45 +00001044 # IOError)
1045 f = open(TESTFN, 'w')
1046 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001047 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN, 'r')
Georg Brandl268e4d42010-10-14 06:59:45 +00001048
Guido van Rossumd8faa362007-04-27 19:54:29 +00001049 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001050 unlink(TESTFN)
1051 unlink(TESTFN2)
1052
Thomas Wouterscf297e42007-02-23 15:07:44 +00001053
1054class DecryptionTests(unittest.TestCase):
Ezio Melotti35386712009-12-31 13:22:41 +00001055 """Check that ZIP decryption works. Since the library does not
1056 support encryption at the moment, we use a pre-generated encrypted
1057 ZIP file."""
Thomas Wouterscf297e42007-02-23 15:07:44 +00001058
1059 data = (
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001060 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
1061 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
1062 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
1063 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
1064 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
1065 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
1066 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +00001067 data2 = (
1068 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
1069 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
1070 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
1071 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
1072 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
1073 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
1074 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
1075 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +00001076
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001077 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +00001078 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +00001079
1080 def setUp(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001081 with open(TESTFN, "wb") as fp:
1082 fp.write(self.data)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001083 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti35386712009-12-31 13:22:41 +00001084 with open(TESTFN2, "wb") as fp:
1085 fp.write(self.data2)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001086 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001087
1088 def tearDown(self):
1089 self.zip.close()
1090 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001091 self.zip2.close()
1092 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001093
Ezio Melottiafd0d112009-07-15 17:17:17 +00001094 def test_no_password(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001095 # Reading the encrypted file without password
1096 # must generate a RunTime exception
1097 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001098 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001099
Ezio Melottiafd0d112009-07-15 17:17:17 +00001100 def test_bad_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001101 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001102 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001103 self.zip2.setpassword(b"perl")
1104 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001105
Ezio Melotti975077a2011-05-19 22:03:22 +03001106 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +00001107 def test_good_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001108 self.zip.setpassword(b"python")
Ezio Melotti35386712009-12-31 13:22:41 +00001109 self.assertEqual(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001110 self.zip2.setpassword(b"12345")
Ezio Melotti35386712009-12-31 13:22:41 +00001111 self.assertEqual(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001112
R. David Murray8d855d82010-12-21 21:53:37 +00001113 def test_unicode_password(self):
1114 self.assertRaises(TypeError, self.zip.setpassword, "unicode")
1115 self.assertRaises(TypeError, self.zip.read, "test.txt", "python")
1116 self.assertRaises(TypeError, self.zip.open, "test.txt", pwd="python")
1117 self.assertRaises(TypeError, self.zip.extract, "test.txt", pwd="python")
1118
Guido van Rossumd8faa362007-04-27 19:54:29 +00001119
1120class TestsWithRandomBinaryFiles(unittest.TestCase):
1121 def setUp(self):
1122 datacount = randint(16, 64)*1024 + randint(1, 1024)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001123 self.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
1124 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001125
1126 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +00001127 with open(TESTFN, "wb") as fp:
1128 fp.write(self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001129
1130 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001131 unlink(TESTFN)
1132 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001133
Ezio Melottiafd0d112009-07-15 17:17:17 +00001134 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001135 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001136 with zipfile.ZipFile(f, "w", compression) as zipfp:
1137 zipfp.write(TESTFN, "another.name")
1138 zipfp.write(TESTFN, TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001139
Ezio Melottiafd0d112009-07-15 17:17:17 +00001140 def zip_test(self, f, compression):
1141 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001142
1143 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001144 with zipfile.ZipFile(f, "r", compression) as zipfp:
1145 testdata = zipfp.read(TESTFN)
1146 self.assertEqual(len(testdata), len(self.data))
1147 self.assertEqual(testdata, self.data)
1148 self.assertEqual(zipfp.read("another.name"), self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001149 if not isinstance(f, str):
1150 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001151
Ezio Melottiafd0d112009-07-15 17:17:17 +00001152 def test_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001153 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001154 self.zip_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001155
Ezio Melotti975077a2011-05-19 22:03:22 +03001156 @requires_zlib
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001157 def test_deflated(self):
1158 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1159 self.zip_test(f, zipfile.ZIP_DEFLATED)
1160
Ezio Melottiafd0d112009-07-15 17:17:17 +00001161 def zip_open_test(self, f, compression):
1162 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001163
1164 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001165 with zipfile.ZipFile(f, "r", compression) as zipfp:
1166 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001167 with zipfp.open(TESTFN) as zipopen1:
1168 while True:
1169 read_data = zipopen1.read(256)
1170 if not read_data:
1171 break
1172 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001173
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001174 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001175 with zipfp.open("another.name") as zipopen2:
1176 while True:
1177 read_data = zipopen2.read(256)
1178 if not read_data:
1179 break
1180 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001181
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001182 testdata1 = b''.join(zipdata1)
1183 self.assertEqual(len(testdata1), len(self.data))
1184 self.assertEqual(testdata1, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001185
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001186 testdata2 = b''.join(zipdata2)
Ezio Melotti35386712009-12-31 13:22:41 +00001187 self.assertEqual(len(testdata2), len(self.data))
1188 self.assertEqual(testdata2, self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001189 if not isinstance(f, str):
1190 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001191
Ezio Melottiafd0d112009-07-15 17:17:17 +00001192 def test_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001193 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001194 self.zip_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001195
Ezio Melotti975077a2011-05-19 22:03:22 +03001196 @requires_zlib
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001197 def test_open_deflated(self):
1198 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1199 self.zip_open_test(f, zipfile.ZIP_DEFLATED)
1200
Ezio Melottiafd0d112009-07-15 17:17:17 +00001201 def zip_random_open_test(self, f, compression):
1202 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001203
1204 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001205 with zipfile.ZipFile(f, "r", compression) as zipfp:
1206 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001207 with zipfp.open(TESTFN) as zipopen1:
1208 while True:
1209 read_data = zipopen1.read(randint(1, 1024))
1210 if not read_data:
1211 break
1212 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001213
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001214 testdata = b''.join(zipdata1)
1215 self.assertEqual(len(testdata), len(self.data))
1216 self.assertEqual(testdata, self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001217 if not isinstance(f, str):
1218 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001219
Ezio Melottiafd0d112009-07-15 17:17:17 +00001220 def test_random_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001221 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001222 self.zip_random_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001223
Ezio Melotti975077a2011-05-19 22:03:22 +03001224 @requires_zlib
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001225 def test_random_open_deflated(self):
1226 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1227 self.zip_random_open_test(f, zipfile.ZIP_DEFLATED)
1228
Ezio Melotti76430242009-07-11 18:28:48 +00001229
Ezio Melotti975077a2011-05-19 22:03:22 +03001230@requires_zlib
Guido van Rossumd8faa362007-04-27 19:54:29 +00001231class TestsWithMultipleOpens(unittest.TestCase):
1232 def setUp(self):
1233 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001234 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
1235 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
1236 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001237
Ezio Melottiafd0d112009-07-15 17:17:17 +00001238 def test_same_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001239 # Verify that (when the ZipFile is in control of creating file objects)
1240 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001241 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001242 with zipf.open('ones') as zopen1, zipf.open('ones') as zopen2:
1243 data1 = zopen1.read(500)
1244 data2 = zopen2.read(500)
1245 data1 += zopen1.read(500)
1246 data2 += zopen2.read(500)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001247 self.assertEqual(data1, data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001248
Ezio Melottiafd0d112009-07-15 17:17:17 +00001249 def test_different_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001250 # Verify that (when the ZipFile is in control of creating file objects)
1251 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001252 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001253 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1254 data1 = zopen1.read(500)
1255 data2 = zopen2.read(500)
1256 data1 += zopen1.read(500)
1257 data2 += zopen2.read(500)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001258 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
1259 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001260
Ezio Melottiafd0d112009-07-15 17:17:17 +00001261 def test_interleaved(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001262 # Verify that (when the ZipFile is in control of creating file objects)
1263 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001264 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001265 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1266 data1 = zopen1.read(500)
1267 data2 = zopen2.read(500)
1268 data1 += zopen1.read(500)
1269 data2 += zopen2.read(500)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001270 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
1271 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001272
1273 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001274 unlink(TESTFN2)
1275
Guido van Rossumd8faa362007-04-27 19:54:29 +00001276
Martin v. Löwis59e47792009-01-24 14:10:07 +00001277class TestWithDirectory(unittest.TestCase):
1278 def setUp(self):
1279 os.mkdir(TESTFN2)
1280
Ezio Melottiafd0d112009-07-15 17:17:17 +00001281 def test_extract_dir(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001282 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
1283 zipf.extractall(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001284 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1285 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1286 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1287
Ezio Melottiafd0d112009-07-15 17:17:17 +00001288 def test_bug_6050(self):
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001289 # Extraction should succeed if directories already exist
1290 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottiafd0d112009-07-15 17:17:17 +00001291 self.test_extract_dir()
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001292
Ezio Melottiafd0d112009-07-15 17:17:17 +00001293 def test_store_dir(self):
Martin v. Löwis59e47792009-01-24 14:10:07 +00001294 os.mkdir(os.path.join(TESTFN2, "x"))
1295 zipf = zipfile.ZipFile(TESTFN, "w")
1296 zipf.write(os.path.join(TESTFN2, "x"), "x")
1297 self.assertTrue(zipf.filelist[0].filename.endswith("x/"))
1298
1299 def tearDown(self):
1300 shutil.rmtree(TESTFN2)
1301 if os.path.exists(TESTFN):
Ezio Melotti76430242009-07-11 18:28:48 +00001302 unlink(TESTFN)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001303
Guido van Rossumd8faa362007-04-27 19:54:29 +00001304
1305class UniversalNewlineTests(unittest.TestCase):
1306 def setUp(self):
Guido van Rossum9c627722007-08-27 18:31:48 +00001307 self.line_gen = [bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001308 for i in range(FIXEDTEST_SIZE)]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001309 self.seps = ('\r', '\r\n', '\n')
1310 self.arcdata, self.arcfiles = {}, {}
1311 for n, s in enumerate(self.seps):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001312 b = s.encode("ascii")
1313 self.arcdata[s] = b.join(self.line_gen) + b
Guido van Rossumd8faa362007-04-27 19:54:29 +00001314 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001315 f = open(self.arcfiles[s], "wb")
1316 try:
1317 f.write(self.arcdata[s])
1318 finally:
1319 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001320
Ezio Melottiafd0d112009-07-15 17:17:17 +00001321 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001322 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001323 with zipfile.ZipFile(f, "w", compression) as zipfp:
1324 for fn in self.arcfiles.values():
1325 zipfp.write(fn, fn)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001326
Ezio Melottiafd0d112009-07-15 17:17:17 +00001327 def read_test(self, f, compression):
1328 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001329
1330 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001331 with zipfile.ZipFile(f, "r") as zipfp:
1332 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001333 with zipfp.open(fn, "rU") as fp:
1334 zipdata = fp.read()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001335 self.assertEqual(self.arcdata[sep], zipdata)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001336 if not isinstance(f, str):
1337 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001338
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001339 def readline_read_test(self, f, compression):
1340 self.make_test_archive(f, compression)
1341
1342 # Read the ZIP archive
Brian Curtin8fb9b862010-11-18 02:15:28 +00001343 with zipfile.ZipFile(f, "r") as zipfp:
1344 for sep, fn in self.arcfiles.items():
1345 with zipfp.open(fn, "rU") as zipopen:
1346 data = b''
1347 while True:
1348 read = zipopen.readline()
1349 if not read:
1350 break
1351 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001352
Brian Curtin8fb9b862010-11-18 02:15:28 +00001353 read = zipopen.read(5)
1354 if not read:
1355 break
1356 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001357
1358 self.assertEqual(data, self.arcdata['\n'])
1359
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001360 if not isinstance(f, str):
1361 f.close()
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001362
Ezio Melottiafd0d112009-07-15 17:17:17 +00001363 def readline_test(self, f, compression):
1364 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001365
1366 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001367 with zipfile.ZipFile(f, "r") as zipfp:
1368 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001369 with zipfp.open(fn, "rU") as zipopen:
1370 for line in self.line_gen:
1371 linedata = zipopen.readline()
1372 self.assertEqual(linedata, line + b'\n')
1373 if not isinstance(f, str):
1374 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001375
Ezio Melottiafd0d112009-07-15 17:17:17 +00001376 def readlines_test(self, f, compression):
1377 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001378
1379 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001380 with zipfile.ZipFile(f, "r") as zipfp:
1381 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001382 with zipfp.open(fn, "rU") as fp:
1383 ziplines = fp.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001384 for line, zipline in zip(self.line_gen, ziplines):
1385 self.assertEqual(zipline, line + b'\n')
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001386 if not isinstance(f, str):
1387 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001388
Ezio Melottiafd0d112009-07-15 17:17:17 +00001389 def iterlines_test(self, f, compression):
1390 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001391
1392 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001393 with zipfile.ZipFile(f, "r") as zipfp:
1394 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001395 with zipfp.open(fn, "rU") as fp:
1396 for line, zipline in zip(self.line_gen, fp):
1397 self.assertEqual(zipline, line + b'\n')
1398 if not isinstance(f, str):
1399 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001400
Ezio Melottiafd0d112009-07-15 17:17:17 +00001401 def test_read_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001402 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001403 self.read_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001404
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001405 def test_readline_read_stored(self):
1406 # Issue #7610: calls to readline() interleaved with calls to read().
1407 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1408 self.readline_read_test(f, zipfile.ZIP_STORED)
1409
Ezio Melottiafd0d112009-07-15 17:17:17 +00001410 def test_readline_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001411 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001412 self.readline_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001413
Ezio Melottiafd0d112009-07-15 17:17:17 +00001414 def test_readlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001415 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001416 self.readlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001417
Ezio Melottiafd0d112009-07-15 17:17:17 +00001418 def test_iterlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001419 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001420 self.iterlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001421
Ezio Melotti975077a2011-05-19 22:03:22 +03001422 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +00001423 def test_read_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001424 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001425 self.read_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001426
Ezio Melotti975077a2011-05-19 22:03:22 +03001427 @requires_zlib
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001428 def test_readline_read_deflated(self):
1429 # Issue #7610: calls to readline() interleaved with calls to read().
1430 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1431 self.readline_read_test(f, zipfile.ZIP_DEFLATED)
1432
Ezio Melotti975077a2011-05-19 22:03:22 +03001433 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +00001434 def test_readline_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001435 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001436 self.readline_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001437
Ezio Melotti975077a2011-05-19 22:03:22 +03001438 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +00001439 def test_readlines_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001440 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001441 self.readlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001442
Ezio Melotti975077a2011-05-19 22:03:22 +03001443 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +00001444 def test_iterlines_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001445 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001446 self.iterlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001447
1448 def tearDown(self):
1449 for sep, fn in self.arcfiles.items():
1450 os.remove(fn)
Ezio Melotti76430242009-07-11 18:28:48 +00001451 unlink(TESTFN)
1452 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001453
1454
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001455def test_main():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001456 run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
1457 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
Ezio Melotti76430242009-07-11 18:28:48 +00001458 TestWithDirectory, UniversalNewlineTests,
1459 TestsWithRandomBinaryFiles)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001460
1461if __name__ == "__main__":
1462 test_main()