blob: c1e20b286544b534b7219b8db5ec7d482260b429 [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
Serhiy Storchaka45c43752013-01-29 20:10:28 +020016from test.support import (TESTFN, run_unittest, findfile, unlink,
Serhiy Storchakac5b75db2013-01-29 20:14:08 +020017 requires_zlib, requires_bz2, requires_lzma,
18 captured_stdout)
Guido van Rossum368f04a2000-04-10 13:23:04 +000019
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000020TESTFN2 = TESTFN + "2"
Martin v. Löwis59e47792009-01-24 14:10:07 +000021TESTFNDIR = TESTFN + "d"
Guido van Rossumb5a755e2007-07-18 18:15:48 +000022FIXEDTEST_SIZE = 1000
Georg Brandl5ba11de2011-01-01 10:09:32 +000023DATAFILES_DIR = 'zipfile_datafiles'
Guido van Rossum368f04a2000-04-10 13:23:04 +000024
Christian Heimes790c8232008-01-07 21:14:23 +000025SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'),
26 ('ziptest2dir/_ziptest2', 'qawsedrftg'),
Gregory P. Smithb47acbf2013-02-01 11:22:43 -080027 ('ziptest2dir/ziptest3dir/_ziptest3', 'azsxdcfvgb'),
Christian Heimes790c8232008-01-07 21:14:23 +000028 ('ziptest2dir/ziptest3dir/ziptest4dir/_ziptest3', '6y7u8i9o0p')]
29
Ezio Melotti76430242009-07-11 18:28:48 +000030
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000031class TestsWithSourceFile(unittest.TestCase):
32 def setUp(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +000033 self.line_gen = (bytes("Zipfile test line %d. random float: %f" %
Guido van Rossum9c627722007-08-27 18:31:48 +000034 (i, random()), "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +000035 for i in range(FIXEDTEST_SIZE))
36 self.data = b'\n'.join(self.line_gen) + b'\n'
Fred Drake6e7e4852001-02-28 05:34:16 +000037
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000038 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +000039 with open(TESTFN, "wb") as fp:
40 fp.write(self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000041
Ezio Melottiafd0d112009-07-15 17:17:17 +000042 def make_test_archive(self, f, compression):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000043 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000044 with zipfile.ZipFile(f, "w", compression) as zipfp:
45 zipfp.write(TESTFN, "another.name")
46 zipfp.write(TESTFN, TESTFN)
47 zipfp.writestr("strfile", self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000048
Ezio Melottiafd0d112009-07-15 17:17:17 +000049 def zip_test(self, f, compression):
50 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +000051
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000052 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000053 with zipfile.ZipFile(f, "r", compression) as zipfp:
54 self.assertEqual(zipfp.read(TESTFN), self.data)
55 self.assertEqual(zipfp.read("another.name"), self.data)
56 self.assertEqual(zipfp.read("strfile"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000057
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000058 # Print the ZIP directory
59 fp = io.StringIO()
60 zipfp.printdir(file=fp)
61 directory = fp.getvalue()
62 lines = directory.splitlines()
Ezio Melotti35386712009-12-31 13:22:41 +000063 self.assertEqual(len(lines), 4) # Number of files + header
Thomas Wouters0e3f5912006-08-11 14:57:12 +000064
Benjamin Peterson577473f2010-01-19 00:09:57 +000065 self.assertIn('File Name', lines[0])
66 self.assertIn('Modified', lines[0])
67 self.assertIn('Size', lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +000068
Ezio Melotti35386712009-12-31 13:22:41 +000069 fn, date, time_, size = lines[1].split()
70 self.assertEqual(fn, 'another.name')
71 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
72 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
73 self.assertEqual(size, str(len(self.data)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000074
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000075 # Check the namelist
76 names = zipfp.namelist()
Ezio Melotti35386712009-12-31 13:22:41 +000077 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +000078 self.assertIn(TESTFN, names)
79 self.assertIn("another.name", names)
80 self.assertIn("strfile", names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000081
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000082 # Check infolist
83 infos = zipfp.infolist()
Ezio Melotti35386712009-12-31 13:22:41 +000084 names = [i.filename for i in infos]
85 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +000086 self.assertIn(TESTFN, names)
87 self.assertIn("another.name", names)
88 self.assertIn("strfile", names)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000089 for i in infos:
Ezio Melotti35386712009-12-31 13:22:41 +000090 self.assertEqual(i.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000091
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000092 # check getinfo
93 for nm in (TESTFN, "another.name", "strfile"):
94 info = zipfp.getinfo(nm)
Ezio Melotti35386712009-12-31 13:22:41 +000095 self.assertEqual(info.filename, nm)
96 self.assertEqual(info.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000097
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000098 # Check that testzip doesn't raise an exception
99 zipfp.testzip()
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000100 if not isinstance(f, str):
101 f.close()
Tim Peters7d3bad62001-04-04 18:56:49 +0000102
Ezio Melottiafd0d112009-07-15 17:17:17 +0000103 def test_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000104 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000105 self.zip_test(f, zipfile.ZIP_STORED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000106
Ezio Melottiafd0d112009-07-15 17:17:17 +0000107 def zip_open_test(self, f, compression):
108 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000109
110 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000111 with zipfile.ZipFile(f, "r", compression) as zipfp:
112 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000113 with zipfp.open(TESTFN) as zipopen1:
114 while True:
115 read_data = zipopen1.read(256)
116 if not read_data:
117 break
118 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000119
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000120 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000121 with zipfp.open("another.name") as zipopen2:
122 while True:
123 read_data = zipopen2.read(256)
124 if not read_data:
125 break
126 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000127
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000128 self.assertEqual(b''.join(zipdata1), self.data)
129 self.assertEqual(b''.join(zipdata2), self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000130 if not isinstance(f, str):
131 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000132
Ezio Melottiafd0d112009-07-15 17:17:17 +0000133 def test_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000134 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000135 self.zip_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000136
Ezio Melottiafd0d112009-07-15 17:17:17 +0000137 def test_open_via_zip_info(self):
Georg Brandlb533e262008-05-25 18:19:30 +0000138 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000139 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
140 zipfp.writestr("name", "foo")
141 zipfp.writestr("name", "bar")
Georg Brandlb533e262008-05-25 18:19:30 +0000142
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000143 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
144 infos = zipfp.infolist()
145 data = b""
146 for info in infos:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000147 with zipfp.open(info) as zipopen:
148 data += zipopen.read()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000149 self.assertTrue(data == b"foobar" or data == b"barfoo")
150 data = b""
151 for info in infos:
152 data += zipfp.read(info)
153 self.assertTrue(data == b"foobar" or data == b"barfoo")
Georg Brandlb533e262008-05-25 18:19:30 +0000154
Ezio Melottiafd0d112009-07-15 17:17:17 +0000155 def zip_random_open_test(self, f, compression):
156 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000157
158 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000159 with zipfile.ZipFile(f, "r", compression) as zipfp:
160 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000161 with zipfp.open(TESTFN) as zipopen1:
162 while True:
163 read_data = zipopen1.read(randint(1, 1024))
164 if not read_data:
165 break
166 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000167
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000168 self.assertEqual(b''.join(zipdata1), self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000169 if not isinstance(f, str):
170 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000171
Ezio Melottiafd0d112009-07-15 17:17:17 +0000172 def test_random_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000173 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000174 self.zip_random_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000175
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000176 def test_univeral_readaheads(self):
177 f = io.BytesIO()
178
179 data = b'a\r\n' * 16 * 1024
180 zipfp = zipfile.ZipFile(f, 'w', zipfile.ZIP_STORED)
181 zipfp.writestr(TESTFN, data)
182 zipfp.close()
183
184 data2 = b''
185 zipfp = zipfile.ZipFile(f, 'r')
Brian Curtin8fb9b862010-11-18 02:15:28 +0000186 with zipfp.open(TESTFN, 'rU') as zipopen:
187 for line in zipopen:
188 data2 += line
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000189 zipfp.close()
190
191 self.assertEqual(data, data2.replace(b'\n', b'\r\n'))
192
193 def zip_readline_read_test(self, f, compression):
194 self.make_test_archive(f, compression)
195
196 # Read the ZIP archive
197 zipfp = zipfile.ZipFile(f, "r")
Brian Curtin8fb9b862010-11-18 02:15:28 +0000198 with zipfp.open(TESTFN) as zipopen:
199 data = b''
200 while True:
201 read = zipopen.readline()
202 if not read:
203 break
204 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000205
Brian Curtin8fb9b862010-11-18 02:15:28 +0000206 read = zipopen.read(100)
207 if not read:
208 break
209 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000210
211 self.assertEqual(data, self.data)
212 zipfp.close()
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000213 if not isinstance(f, str):
214 f.close()
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000215
Ezio Melottiafd0d112009-07-15 17:17:17 +0000216 def zip_readline_test(self, f, compression):
217 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000218
219 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000220 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000221 with zipfp.open(TESTFN) as zipopen:
222 for line in self.line_gen:
223 linedata = zipopen.readline()
224 self.assertEqual(linedata, line + '\n')
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000225 if not isinstance(f, str):
226 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000227
Ezio Melottiafd0d112009-07-15 17:17:17 +0000228 def zip_readlines_test(self, f, compression):
229 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000230
231 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000232 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000233 with zipfp.open(TESTFN) as zipopen:
234 ziplines = zipopen.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000235 for line, zipline in zip(self.line_gen, ziplines):
236 self.assertEqual(zipline, line + '\n')
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000237 if not isinstance(f, str):
238 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000239
Ezio Melottiafd0d112009-07-15 17:17:17 +0000240 def zip_iterlines_test(self, f, compression):
241 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000242
243 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000244 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000245 with zipfp.open(TESTFN) as zipopen:
246 for line, zipline in zip(self.line_gen, zipopen):
247 self.assertEqual(zipline, line + '\n')
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000248 if not isinstance(f, str):
249 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000250
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000251 def test_readline_read_stored(self):
252 # Issue #7610: calls to readline() interleaved with calls to read().
253 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
254 self.zip_readline_read_test(f, zipfile.ZIP_STORED)
255
Ezio Melottiafd0d112009-07-15 17:17:17 +0000256 def test_readline_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000257 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000258 self.zip_readline_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000259
Ezio Melottiafd0d112009-07-15 17:17:17 +0000260 def test_readlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000261 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000262 self.zip_readlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000263
Ezio Melottiafd0d112009-07-15 17:17:17 +0000264 def test_iterlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000265 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000266 self.zip_iterlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000267
Ezio Melotti975077a2011-05-19 22:03:22 +0300268 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +0000269 def test_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000270 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000271 self.zip_test(f, zipfile.ZIP_DEFLATED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000272
Guido van Rossumd8faa362007-04-27 19:54:29 +0000273
Ezio Melotti975077a2011-05-19 22:03:22 +0300274 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +0000275 def test_open_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000276 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000277 self.zip_open_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000278
Ezio Melotti975077a2011-05-19 22:03:22 +0300279 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +0000280 def test_random_open_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000281 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000282 self.zip_random_open_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000283
Ezio Melotti975077a2011-05-19 22:03:22 +0300284 @requires_zlib
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000285 def test_readline_read_deflated(self):
286 # Issue #7610: calls to readline() interleaved with calls to read().
287 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
288 self.zip_readline_read_test(f, zipfile.ZIP_DEFLATED)
289
Ezio Melotti975077a2011-05-19 22:03:22 +0300290 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +0000291 def test_readline_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000292 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000293 self.zip_readline_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000294
Ezio Melotti975077a2011-05-19 22:03:22 +0300295 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +0000296 def test_readlines_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000297 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000298 self.zip_readlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000299
Ezio Melotti975077a2011-05-19 22:03:22 +0300300 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +0000301 def test_iterlines_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000302 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000303 self.zip_iterlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000304
Ezio Melotti975077a2011-05-19 22:03:22 +0300305 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +0000306 def test_low_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000307 """Check for cases where compressed data is larger than original."""
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000308 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000309 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
310 zipfp.writestr("strfile", '12')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000311
312 # Get an open object for strfile
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000313 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_DEFLATED) as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000314 with zipfp.open("strfile") as openobj:
315 self.assertEqual(openobj.read(1), b'1')
316 self.assertEqual(openobj.read(1), b'2')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000317
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200318 @requires_bz2
319 def test_bzip2(self):
320 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
321 self.zip_test(f, zipfile.ZIP_BZIP2)
322
323 @requires_bz2
324 def test_open_bzip2(self):
325 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
326 self.zip_open_test(f, zipfile.ZIP_BZIP2)
327
328 @requires_bz2
329 def test_random_open_bzip2(self):
330 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
331 self.zip_random_open_test(f, zipfile.ZIP_BZIP2)
332
333 @requires_bz2
334 def test_readline_read_bzip2(self):
335 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
336 self.zip_readline_read_test(f, zipfile.ZIP_BZIP2)
337
338 @requires_bz2
339 def test_readline_bzip2(self):
340 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
341 self.zip_readline_test(f, zipfile.ZIP_BZIP2)
342
343 @requires_bz2
344 def test_readlines_bzip2(self):
345 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
346 self.zip_readlines_test(f, zipfile.ZIP_BZIP2)
347
348 @requires_bz2
349 def test_iterlines_bzip2(self):
350 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
351 self.zip_iterlines_test(f, zipfile.ZIP_BZIP2)
352
353 @requires_bz2
354 def test_low_compression_bzip2(self):
355 """Check for cases where compressed data is larger than original."""
356 # Create the ZIP archive
357 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_BZIP2) as zipfp:
358 zipfp.writestr("strfile", '12')
359
360 # Get an open object for strfile
361 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_BZIP2) as zipfp:
362 with zipfp.open("strfile") as openobj:
363 self.assertEqual(openobj.read(1), b'1')
364 self.assertEqual(openobj.read(1), b'2')
365
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +0200366 @requires_lzma
367 def test_lzma(self):
368 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
369 self.zip_test(f, zipfile.ZIP_LZMA)
370
371 @requires_lzma
372 def test_open_lzma(self):
373 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
374 self.zip_open_test(f, zipfile.ZIP_LZMA)
375
376 @requires_lzma
377 def test_random_open_lzma(self):
378 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
379 self.zip_random_open_test(f, zipfile.ZIP_LZMA)
380
381 @requires_lzma
382 def test_readline_read_lzma(self):
383 # Issue #7610: calls to readline() interleaved with calls to read().
384 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
385 self.zip_readline_read_test(f, zipfile.ZIP_LZMA)
386
387 @requires_lzma
388 def test_readline_lzma(self):
389 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
390 self.zip_readline_test(f, zipfile.ZIP_LZMA)
391
392 @requires_lzma
393 def test_readlines_lzma(self):
394 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
395 self.zip_readlines_test(f, zipfile.ZIP_LZMA)
396
397 @requires_lzma
398 def test_iterlines_lzma(self):
399 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
400 self.zip_iterlines_test(f, zipfile.ZIP_LZMA)
401
402 @requires_lzma
403 def test_low_compression_lzma(self):
404 """Check for cases where compressed data is larger than original."""
405 # Create the ZIP archive
406 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_LZMA) as zipfp:
407 zipfp.writestr("strfile", '12')
408
409 # Get an open object for strfile
410 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_LZMA) as zipfp:
411 with zipfp.open("strfile") as openobj:
412 self.assertEqual(openobj.read(1), b'1')
413 self.assertEqual(openobj.read(1), b'2')
414
Ezio Melottiafd0d112009-07-15 17:17:17 +0000415 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000416 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
417 zipfp.write(TESTFN, "/absolute")
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000418
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000419 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
420 self.assertEqual(zipfp.namelist(), ["absolute"])
Tim Peters32cbc962006-02-20 21:42:18 +0000421
Ezio Melottiafd0d112009-07-15 17:17:17 +0000422 def test_append_to_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000423 """Test appending to an existing zipfile."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000424 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
425 zipfp.write(TESTFN, TESTFN)
426
427 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
428 zipfp.writestr("strfile", self.data)
429 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000430
Ezio Melottiafd0d112009-07-15 17:17:17 +0000431 def test_append_to_non_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000432 """Test appending to an existing file that is not a zipfile."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000433 # NOTE: this test fails if len(d) < 22 because of the first
434 # line "fpin.seek(-22, 2)" in _EndRecData
Ezio Melotti35386712009-12-31 13:22:41 +0000435 data = b'I am not a ZipFile!'*10
436 with open(TESTFN2, 'wb') as f:
437 f.write(data)
438
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000439 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
440 zipfp.write(TESTFN, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000441
Ezio Melotti35386712009-12-31 13:22:41 +0000442 with open(TESTFN2, 'rb') as f:
443 f.seek(len(data))
444 with zipfile.ZipFile(f, "r") as zipfp:
445 self.assertEqual(zipfp.namelist(), [TESTFN])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000446
R David Murray4fbb9db2011-06-09 15:50:51 -0400447 def test_ignores_newline_at_end(self):
448 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
449 zipfp.write(TESTFN, TESTFN)
450 with open(TESTFN2, 'a') as f:
451 f.write("\r\n\00\00\00")
452 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
453 self.assertIsInstance(zipfp, zipfile.ZipFile)
454
455 def test_ignores_stuff_appended_past_comments(self):
456 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
457 zipfp.comment = b"this is a comment"
458 zipfp.write(TESTFN, TESTFN)
459 with open(TESTFN2, 'a') as f:
460 f.write("abcdef\r\n")
461 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
462 self.assertIsInstance(zipfp, zipfile.ZipFile)
463 self.assertEqual(zipfp.comment, b"this is a comment")
464
Ezio Melottiafd0d112009-07-15 17:17:17 +0000465 def test_write_default_name(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000466 """Check that calling ZipFile.write without arcname specified
467 produces the expected result."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000468 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
469 zipfp.write(TESTFN)
Brian Curtin8fb9b862010-11-18 02:15:28 +0000470 with open(TESTFN, "rb") as f:
471 self.assertEqual(zipfp.read(TESTFN), f.read())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000472
Ezio Melotti975077a2011-05-19 22:03:22 +0300473 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +0000474 def test_per_file_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000475 """Check that files within a Zip archive can have different
476 compression options."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000477 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
478 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
479 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
480 sinfo = zipfp.getinfo('storeme')
481 dinfo = zipfp.getinfo('deflateme')
482 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
483 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000484
Ezio Melottiafd0d112009-07-15 17:17:17 +0000485 def test_write_to_readonly(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000486 """Check that trying to call write() on a readonly ZipFile object
487 raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000488 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
489 zipfp.writestr("somefile.txt", "bogus")
490
491 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
492 self.assertRaises(RuntimeError, zipfp.write, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000493
Ezio Melottiafd0d112009-07-15 17:17:17 +0000494 def test_extract(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000495 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
496 for fpath, fdata in SMALL_TEST_DATA:
497 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000498
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000499 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
500 for fpath, fdata in SMALL_TEST_DATA:
501 writtenfile = zipfp.extract(fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000502
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000503 # make sure it was written to the right place
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800504 correctfile = os.path.join(os.getcwd(), fpath)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000505 correctfile = os.path.normpath(correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000506
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000507 self.assertEqual(writtenfile, correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000508
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000509 # make sure correct data is in correct file
Brian Curtin8fb9b862010-11-18 02:15:28 +0000510 with open(writtenfile, "rb") as f:
511 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000512
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000513 os.remove(writtenfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000514
515 # remove the test file subdirectories
516 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
517
Ezio Melottiafd0d112009-07-15 17:17:17 +0000518 def test_extract_all(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000519 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
520 for fpath, fdata in SMALL_TEST_DATA:
521 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000522
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000523 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
524 zipfp.extractall()
525 for fpath, fdata in SMALL_TEST_DATA:
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800526 outfile = os.path.join(os.getcwd(), fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000527
Brian Curtin8fb9b862010-11-18 02:15:28 +0000528 with open(outfile, "rb") as f:
529 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000530
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000531 os.remove(outfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000532
533 # remove the test file subdirectories
534 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
535
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800536 def check_file(self, filename, content):
537 self.assertTrue(os.path.isfile(filename))
538 with open(filename, 'rb') as f:
539 self.assertEqual(f.read(), content)
540
541 def test_extract_hackers_arcnames(self):
542 hacknames = [
543 ('../foo/bar', 'foo/bar'),
544 ('foo/../bar', 'foo/bar'),
545 ('foo/../../bar', 'foo/bar'),
546 ('foo/bar/..', 'foo/bar'),
547 ('./../foo/bar', 'foo/bar'),
548 ('/foo/bar', 'foo/bar'),
549 ('/foo/../bar', 'foo/bar'),
550 ('/foo/../../bar', 'foo/bar'),
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800551 ]
552 if os.path.sep == '\\': # Windows.
553 hacknames.extend([
554 (r'..\foo\bar', 'foo/bar'),
555 (r'..\/foo\/bar', 'foo/bar'),
556 (r'foo/\..\/bar', 'foo/bar'),
557 (r'foo\/../\bar', 'foo/bar'),
558 (r'C:foo/bar', 'foo/bar'),
559 (r'C:/foo/bar', 'foo/bar'),
560 (r'C://foo/bar', 'foo/bar'),
561 (r'C:\foo\bar', 'foo/bar'),
562 (r'//conky/mountpoint/foo/bar', 'foo/bar'),
563 (r'\\conky\mountpoint\foo\bar', 'foo/bar'),
564 (r'///conky/mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
565 (r'\\\conky\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
566 (r'//conky//mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
567 (r'\\conky\\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
568 (r'//?/C:/foo/bar', 'foo/bar'),
569 (r'\\?\C:\foo\bar', 'foo/bar'),
570 (r'C:/../C:/foo/bar', 'C_/foo/bar'),
571 (r'a:b\c<d>e|f"g?h*i', 'b/c_d_e_f_g_h_i'),
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200572 ('../../foo../../ba..r', 'foo/ba..r'),
573 ])
574 else: # Unix
575 hacknames.extend([
576 ('//foo/bar', 'foo/bar'),
577 ('../../foo../../ba..r', 'foo../ba..r'),
578 (r'foo/..\bar', r'foo/..\bar'),
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800579 ])
580
581 for arcname, fixedname in hacknames:
582 content = b'foobar' + arcname.encode()
583 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipfp:
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200584 zinfo = zipfile.ZipInfo()
585 # preserve backslashes
586 zinfo.filename = arcname
587 zinfo.external_attr = 0o600 << 16
588 zipfp.writestr(zinfo, content)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800589
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200590 arcname = arcname.replace(os.sep, "/")
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800591 targetpath = os.path.join('target', 'subdir', 'subsub')
592 correctfile = os.path.join(targetpath, *fixedname.split('/'))
593
594 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
595 writtenfile = zipfp.extract(arcname, targetpath)
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200596 self.assertEqual(writtenfile, correctfile,
597 msg="extract %r" % arcname)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800598 self.check_file(correctfile, content)
599 shutil.rmtree('target')
600
601 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
602 zipfp.extractall(targetpath)
603 self.check_file(correctfile, content)
604 shutil.rmtree('target')
605
606 correctfile = os.path.join(os.getcwd(), *fixedname.split('/'))
607
608 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
609 writtenfile = zipfp.extract(arcname)
Serhiy Storchakae5e64442013-02-02 19:50:59 +0200610 self.assertEqual(writtenfile, correctfile,
611 msg="extract %r" % arcname)
Gregory P. Smithb47acbf2013-02-01 11:22:43 -0800612 self.check_file(correctfile, content)
613 shutil.rmtree(fixedname.split('/')[0])
614
615 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
616 zipfp.extractall()
617 self.check_file(correctfile, content)
618 shutil.rmtree(fixedname.split('/')[0])
619
620 os.remove(TESTFN2)
621
Ezio Melotti975077a2011-05-19 22:03:22 +0300622 def test_writestr_compression_stored(self):
Ronald Oussorenee5c8852010-02-07 20:24:02 +0000623 zipfp = zipfile.ZipFile(TESTFN2, "w")
624 zipfp.writestr("a.txt", "hello world", compress_type=zipfile.ZIP_STORED)
Ronald Oussorenee5c8852010-02-07 20:24:02 +0000625 info = zipfp.getinfo('a.txt')
626 self.assertEqual(info.compress_type, zipfile.ZIP_STORED)
627
Ezio Melotti975077a2011-05-19 22:03:22 +0300628 @requires_zlib
629 def test_writestr_compression_deflated(self):
630 zipfp = zipfile.ZipFile(TESTFN2, "w")
631 zipfp.writestr("b.txt", "hello world", compress_type=zipfile.ZIP_DEFLATED)
632 info = zipfp.getinfo('b.txt')
633 self.assertEqual(info.compress_type, zipfile.ZIP_DEFLATED)
Ronald Oussorenee5c8852010-02-07 20:24:02 +0000634
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200635 @requires_bz2
636 def test_writestr_compression_bzip2(self):
637 zipfp = zipfile.ZipFile(TESTFN2, "w")
638 zipfp.writestr("b.txt", "hello world", compress_type=zipfile.ZIP_BZIP2)
639 info = zipfp.getinfo('b.txt')
640 self.assertEqual(info.compress_type, zipfile.ZIP_BZIP2)
641
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +0200642 @requires_lzma
643 def test_writestr_compression_lzma(self):
644 zipfp = zipfile.ZipFile(TESTFN2, "w")
645 zipfp.writestr("b.txt", "hello world", compress_type=zipfile.ZIP_LZMA)
646 info = zipfp.getinfo('b.txt')
647 self.assertEqual(info.compress_type, zipfile.ZIP_LZMA)
648
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000649 def zip_test_writestr_permissions(self, f, compression):
650 # Make sure that writestr creates files with mode 0600,
651 # when it is passed a name rather than a ZipInfo instance.
652
Ezio Melottiafd0d112009-07-15 17:17:17 +0000653 self.make_test_archive(f, compression)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000654 with zipfile.ZipFile(f, "r") as zipfp:
655 zinfo = zipfp.getinfo('strfile')
656 self.assertEqual(zinfo.external_attr, 0o600 << 16)
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000657 if not isinstance(f, str):
658 f.close()
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000659
Ezio Melottiafd0d112009-07-15 17:17:17 +0000660 def test_writestr_permissions(self):
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000661 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
662 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
663
Gregory P. Smithb0d9ca92009-07-07 05:06:04 +0000664 def test_writestr_extended_local_header_issue1202(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000665 with zipfile.ZipFile(TESTFN2, 'w') as orig_zip:
666 for data in 'abcdefghijklmnop':
667 zinfo = zipfile.ZipInfo(data)
668 zinfo.flag_bits |= 0x08 # Include an extended local header.
669 orig_zip.writestr(zinfo, data)
670
671 def test_close(self):
672 """Check that the zipfile is closed after the 'with' block."""
673 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
674 for fpath, fdata in SMALL_TEST_DATA:
675 zipfp.writestr(fpath, fdata)
676 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
677 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
678
679 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
680 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
681 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
682
683 def test_close_on_exception(self):
684 """Check that the zipfile is closed if an exception is raised in the
685 'with' block."""
686 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
687 for fpath, fdata in SMALL_TEST_DATA:
688 zipfp.writestr(fpath, fdata)
689
690 try:
691 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
Georg Brandl4d540882010-10-28 06:42:33 +0000692 raise zipfile.BadZipFile()
693 except zipfile.BadZipFile:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000694 self.assertTrue(zipfp2.fp is None, 'zipfp is not closed')
Gregory P. Smithb0d9ca92009-07-07 05:06:04 +0000695
Senthil Kumaran29fa9d42011-10-20 01:46:00 +0800696 def test_add_file_before_1980(self):
697 # Set atime and mtime to 1970-01-01
698 os.utime(TESTFN, (0, 0))
699 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
700 self.assertRaises(ValueError, zipfp.write, TESTFN)
701
702
Senthil Kumaran7e3062b2011-10-20 01:52:41 +0800703
704
705
706
707
Ezio Melotti975077a2011-05-19 22:03:22 +0300708 @requires_zlib
Georg Brandl5ba11de2011-01-01 10:09:32 +0000709 def test_unicode_filenames(self):
Georg Brandl04480a82011-01-01 10:42:31 +0000710 # bug #10801
711 fname = findfile('zip_cp437_header.zip')
Georg Brandl5ba11de2011-01-01 10:09:32 +0000712 with zipfile.ZipFile(fname) as zipfp:
Georg Brandl04480a82011-01-01 10:42:31 +0000713 for name in zipfp.namelist():
714 zipfp.open(name).close()
Georg Brandl5ba11de2011-01-01 10:09:32 +0000715
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000716 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +0000717 unlink(TESTFN)
718 unlink(TESTFN2)
719
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000720
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000721class TestZip64InSmallFiles(unittest.TestCase):
722 # These tests test the ZIP64 functionality without using large files,
723 # see test_zipfile64 for proper tests.
724
725 def setUp(self):
726 self._limit = zipfile.ZIP64_LIMIT
727 zipfile.ZIP64_LIMIT = 5
728
Guido van Rossum9c627722007-08-27 18:31:48 +0000729 line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000730 for i in range(0, FIXEDTEST_SIZE))
731 self.data = b'\n'.join(line_gen)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000732
733 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +0000734 with open(TESTFN, "wb") as fp:
735 fp.write(self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000736
Ezio Melottiafd0d112009-07-15 17:17:17 +0000737 def large_file_exception_test(self, f, compression):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000738 with zipfile.ZipFile(f, "w", compression) as zipfp:
739 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti35386712009-12-31 13:22:41 +0000740 zipfp.write, TESTFN, "another.name")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000741
Ezio Melottiafd0d112009-07-15 17:17:17 +0000742 def large_file_exception_test2(self, f, compression):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000743 with zipfile.ZipFile(f, "w", compression) as zipfp:
744 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti35386712009-12-31 13:22:41 +0000745 zipfp.writestr, "another.name", self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000746 if not isinstance(f, str):
747 f.close()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000748
Ezio Melottiafd0d112009-07-15 17:17:17 +0000749 def test_large_file_exception(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000750 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000751 self.large_file_exception_test(f, zipfile.ZIP_STORED)
752 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000753
Ezio Melottiafd0d112009-07-15 17:17:17 +0000754 def zip_test(self, f, compression):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000755 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000756 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
757 zipfp.write(TESTFN, "another.name")
758 zipfp.write(TESTFN, TESTFN)
759 zipfp.writestr("strfile", self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000760
761 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000762 with zipfile.ZipFile(f, "r", compression) as zipfp:
763 self.assertEqual(zipfp.read(TESTFN), self.data)
764 self.assertEqual(zipfp.read("another.name"), self.data)
765 self.assertEqual(zipfp.read("strfile"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000766
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000767 # Print the ZIP directory
768 fp = io.StringIO()
769 zipfp.printdir(fp)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000770
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000771 directory = fp.getvalue()
772 lines = directory.splitlines()
Ezio Melotti35386712009-12-31 13:22:41 +0000773 self.assertEqual(len(lines), 4) # Number of files + header
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000774
Benjamin Peterson577473f2010-01-19 00:09:57 +0000775 self.assertIn('File Name', lines[0])
776 self.assertIn('Modified', lines[0])
777 self.assertIn('Size', lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000778
Ezio Melotti35386712009-12-31 13:22:41 +0000779 fn, date, time_, size = lines[1].split()
780 self.assertEqual(fn, 'another.name')
781 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
782 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
783 self.assertEqual(size, str(len(self.data)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000784
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000785 # Check the namelist
786 names = zipfp.namelist()
Ezio Melotti35386712009-12-31 13:22:41 +0000787 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000788 self.assertIn(TESTFN, names)
789 self.assertIn("another.name", names)
790 self.assertIn("strfile", names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000791
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000792 # Check infolist
793 infos = zipfp.infolist()
Ezio Melotti35386712009-12-31 13:22:41 +0000794 names = [i.filename for i in infos]
795 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000796 self.assertIn(TESTFN, names)
797 self.assertIn("another.name", names)
798 self.assertIn("strfile", names)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000799 for i in infos:
Ezio Melotti35386712009-12-31 13:22:41 +0000800 self.assertEqual(i.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000801
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000802 # check getinfo
803 for nm in (TESTFN, "another.name", "strfile"):
804 info = zipfp.getinfo(nm)
Ezio Melotti35386712009-12-31 13:22:41 +0000805 self.assertEqual(info.filename, nm)
806 self.assertEqual(info.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000807
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000808 # Check that testzip doesn't raise an exception
809 zipfp.testzip()
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000810 if not isinstance(f, str):
811 f.close()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000812
Ezio Melottiafd0d112009-07-15 17:17:17 +0000813 def test_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000814 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000815 self.zip_test(f, zipfile.ZIP_STORED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000816
Ezio Melotti975077a2011-05-19 22:03:22 +0300817 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +0000818 def test_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +0000819 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000820 self.zip_test(f, zipfile.ZIP_DEFLATED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000821
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200822 @requires_bz2
823 def test_bzip2(self):
824 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
825 self.zip_test(f, zipfile.ZIP_BZIP2)
826
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +0200827 @requires_lzma
828 def test_lzma(self):
829 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
830 self.zip_test(f, zipfile.ZIP_LZMA)
831
Ezio Melottiafd0d112009-07-15 17:17:17 +0000832 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000833 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
834 allowZip64=True) as zipfp:
835 zipfp.write(TESTFN, "/absolute")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000836
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000837 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
838 self.assertEqual(zipfp.namelist(), ["absolute"])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000839
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000840 def tearDown(self):
841 zipfile.ZIP64_LIMIT = self._limit
Ezio Melotti76430242009-07-11 18:28:48 +0000842 unlink(TESTFN)
843 unlink(TESTFN2)
844
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000845
846class PyZipFileTests(unittest.TestCase):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000847 def test_write_pyfile(self):
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000848 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000849 fn = __file__
850 if fn.endswith('.pyc') or fn.endswith('.pyo'):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000851 path_split = fn.split(os.sep)
852 if os.altsep is not None:
853 path_split.extend(fn.split(os.altsep))
854 if '__pycache__' in path_split:
855 fn = imp.source_from_cache(fn)
856 else:
857 fn = fn[:-1]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000858
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000859 zipfp.writepy(fn)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000860
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000861 bn = os.path.basename(fn)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000862 self.assertNotIn(bn, zipfp.namelist())
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000863 self.assertTrue(bn + 'o' in zipfp.namelist() or
864 bn + 'c' in zipfp.namelist())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000865
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000866 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000867 fn = __file__
Ezio Melotti35386712009-12-31 13:22:41 +0000868 if fn.endswith(('.pyc', '.pyo')):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000869 fn = fn[:-1]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000870
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000871 zipfp.writepy(fn, "testpackage")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000872
Ezio Melotti35386712009-12-31 13:22:41 +0000873 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000874 self.assertNotIn(bn, zipfp.namelist())
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000875 self.assertTrue(bn + 'o' in zipfp.namelist() or
876 bn + 'c' in zipfp.namelist())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000877
Ezio Melottiafd0d112009-07-15 17:17:17 +0000878 def test_write_python_package(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000879 import email
880 packagedir = os.path.dirname(email.__file__)
881
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000882 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000883 zipfp.writepy(packagedir)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000884
Ezio Melotti35386712009-12-31 13:22:41 +0000885 # Check for a couple of modules at different levels of the
886 # hierarchy
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000887 names = zipfp.namelist()
888 self.assertTrue('email/__init__.pyo' in names or
889 'email/__init__.pyc' in names)
890 self.assertTrue('email/mime/text.pyo' in names or
891 'email/mime/text.pyc' in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000892
Georg Brandl8334fd92010-12-04 10:26:46 +0000893 def test_write_with_optimization(self):
894 import email
895 packagedir = os.path.dirname(email.__file__)
896 # use .pyc if running test in optimization mode,
897 # use .pyo if running test in debug mode
898 optlevel = 1 if __debug__ else 0
899 ext = '.pyo' if optlevel == 1 else '.pyc'
900
901 with TemporaryFile() as t, \
902 zipfile.PyZipFile(t, "w", optimize=optlevel) as zipfp:
903 zipfp.writepy(packagedir)
904
905 names = zipfp.namelist()
906 self.assertIn('email/__init__' + ext, names)
907 self.assertIn('email/mime/text' + ext, names)
908
Ezio Melottiafd0d112009-07-15 17:17:17 +0000909 def test_write_python_directory(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000910 os.mkdir(TESTFN2)
911 try:
Ezio Melotti35386712009-12-31 13:22:41 +0000912 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
913 fp.write("print(42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000914
Ezio Melotti35386712009-12-31 13:22:41 +0000915 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
916 fp.write("print(42 * 42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000917
Ezio Melotti35386712009-12-31 13:22:41 +0000918 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
919 fp.write("bla bla bla\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000920
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000921 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
922 zipfp.writepy(TESTFN2)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000923
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000924 names = zipfp.namelist()
925 self.assertTrue('mod1.pyc' in names or 'mod1.pyo' in names)
926 self.assertTrue('mod2.pyc' in names or 'mod2.pyo' in names)
927 self.assertNotIn('mod2.txt', names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000928
929 finally:
930 shutil.rmtree(TESTFN2)
931
Ezio Melottiafd0d112009-07-15 17:17:17 +0000932 def test_write_non_pyfile(self):
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000933 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000934 with open(TESTFN, 'w') as f:
935 f.write('most definitely not a python file')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000936 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
937 os.remove(TESTFN)
938
Serhiy Storchaka45c43752013-01-29 20:10:28 +0200939 def test_write_pyfile_bad_syntax(self):
940 os.mkdir(TESTFN2)
941 try:
942 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
943 fp.write("Bad syntax in python file\n")
944
945 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
946 # syntax errors are printed to stdout
947 with captured_stdout() as s:
948 zipfp.writepy(os.path.join(TESTFN2, "mod1.py"))
949
950 self.assertIn("SyntaxError", s.getvalue())
951
952 # as it will not have compiled the python file, it will
953 # include the .py file not .pyc or .pyo
954 names = zipfp.namelist()
955 self.assertIn('mod1.py', names)
956 self.assertNotIn('mod1.pyc', names)
957 self.assertNotIn('mod1.pyo', names)
958
959 finally:
960 shutil.rmtree(TESTFN2)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000961
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000962class OtherTests(unittest.TestCase):
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000963 zips_with_bad_crc = {
964 zipfile.ZIP_STORED: (
965 b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
966 b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
967 b'ilehello,AworldP'
968 b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
969 b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
970 b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
971 b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
972 b'\0\0/\0\0\0\0\0'),
973 zipfile.ZIP_DEFLATED: (
974 b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
975 b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
976 b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
977 b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
978 b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
979 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
980 b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
981 b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00'),
Martin v. Löwisf6b16a42012-05-01 07:58:44 +0200982 zipfile.ZIP_BZIP2: (
983 b'PK\x03\x04\x14\x03\x00\x00\x0c\x00nu\x0c=FA'
984 b'KE8\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
985 b'ileBZh91AY&SY\xd4\xa8\xca'
986 b'\x7f\x00\x00\x0f\x11\x80@\x00\x06D\x90\x80 \x00 \xa5'
987 b'P\xd9!\x03\x03\x13\x13\x13\x89\xa9\xa9\xc2u5:\x9f'
988 b'\x8b\xb9"\x9c(HjTe?\x80PK\x01\x02\x14'
989 b'\x03\x14\x03\x00\x00\x0c\x00nu\x0c=FAKE8'
990 b'\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\x00'
991 b'\x00 \x80\x80\x81\x00\x00\x00\x00afilePK'
992 b'\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00\x00[\x00'
993 b'\x00\x00\x00\x00'),
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +0200994 zipfile.ZIP_LZMA: (
995 b'PK\x03\x04\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
996 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
997 b'ile\t\x04\x05\x00]\x00\x00\x00\x04\x004\x19I'
998 b'\xee\x8d\xe9\x17\x89:3`\tq!.8\x00PK'
999 b'\x01\x02\x14\x03\x14\x03\x00\x00\x0e\x00nu\x0c=FA'
1000 b'KE\x1b\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00\x00\x00'
1001 b'\x00\x00\x00\x00 \x80\x80\x81\x00\x00\x00\x00afil'
1002 b'ePK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x003\x00\x00'
1003 b'\x00>\x00\x00\x00\x00\x00'),
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001004 }
1005
Martin v. Löwisd099b562012-05-01 14:08:22 +02001006 def test_unsupported_version(self):
1007 # File has an extract_version of 120
1008 data = (b'PK\x03\x04x\x00\x00\x00\x00\x00!p\xa1@\x00\x00\x00\x00\x00\x00'
1009 b'\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00xPK\x01\x02x\x03x\x00\x00\x00\x00'
1010 b'\x00!p\xa1@\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00'
1011 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00\x00xPK\x05\x06'
1012 b'\x00\x00\x00\x00\x01\x00\x01\x00/\x00\x00\x00\x1f\x00\x00\x00\x00\x00')
1013 self.assertRaises(NotImplementedError, zipfile.ZipFile,
1014 io.BytesIO(data), 'r')
1015
Ezio Melottiafd0d112009-07-15 17:17:17 +00001016 def test_unicode_filenames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001017 with zipfile.ZipFile(TESTFN, "w") as zf:
1018 zf.writestr("foo.txt", "Test for unicode filename")
1019 zf.writestr("\xf6.txt", "Test for unicode filename")
Ezio Melottie9615932010-01-24 19:26:24 +00001020 self.assertIsInstance(zf.infolist()[0].filename, str)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001021
1022 with zipfile.ZipFile(TESTFN, "r") as zf:
1023 self.assertEqual(zf.filelist[0].filename, "foo.txt")
1024 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
Martin v. Löwis8570f6a2008-05-05 17:44:38 +00001025
Ezio Melottiafd0d112009-07-15 17:17:17 +00001026 def test_create_non_existent_file_for_append(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001027 if os.path.exists(TESTFN):
1028 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001029
Thomas Wouterscf297e42007-02-23 15:07:44 +00001030 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001031 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +00001032
Thomas Wouterscf297e42007-02-23 15:07:44 +00001033 try:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001034 with zipfile.ZipFile(TESTFN, 'a') as zf:
1035 zf.writestr(filename, content)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001036 except IOError:
1037 self.fail('Could not append data to a non-existent zip file.')
1038
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001039 self.assertTrue(os.path.exists(TESTFN))
Thomas Wouterscf297e42007-02-23 15:07:44 +00001040
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001041 with zipfile.ZipFile(TESTFN, 'r') as zf:
1042 self.assertEqual(zf.read(filename), content)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001043
Ezio Melottiafd0d112009-07-15 17:17:17 +00001044 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001045 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti35386712009-12-31 13:22:41 +00001046 # it opens if there's an error in the file. If it doesn't, the
1047 # traceback holds a reference to the ZipFile object and, indirectly,
1048 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001049 # On Windows, this causes the os.unlink() call to fail because the
1050 # underlying file is still open. This is SF bug #412214.
1051 #
Ezio Melotti35386712009-12-31 13:22:41 +00001052 with open(TESTFN, "w") as fp:
1053 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001054 try:
1055 zf = zipfile.ZipFile(TESTFN)
Georg Brandl4d540882010-10-28 06:42:33 +00001056 except zipfile.BadZipFile:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001057 pass
1058
Ezio Melottiafd0d112009-07-15 17:17:17 +00001059 def test_is_zip_erroneous_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001060 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001061 # - passing a filename
1062 with open(TESTFN, "w") as fp:
1063 fp.write("this is not a legal zip file\n")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001064 chk = zipfile.is_zipfile(TESTFN)
Ezio Melotti35386712009-12-31 13:22:41 +00001065 self.assertFalse(chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001066 # - passing a file object
1067 with open(TESTFN, "rb") as fp:
1068 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001069 self.assertTrue(not chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001070 # - passing a file-like object
1071 fp = io.BytesIO()
1072 fp.write(b"this is not a legal zip file\n")
1073 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001074 self.assertTrue(not chk)
Ezio Melotti35386712009-12-31 13:22:41 +00001075 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001076 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001077 self.assertTrue(not chk)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001078
Serhiy Storchakad2b15272013-01-31 15:27:07 +02001079 def test_damaged_zipfile(self):
1080 """Check that zipfiles with missing bytes at the end raise BadZipFile."""
1081 # - Create a valid zip file
1082 fp = io.BytesIO()
1083 with zipfile.ZipFile(fp, mode="w") as zipf:
1084 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
1085 zipfiledata = fp.getvalue()
1086
1087 # - Now create copies of it missing the last N bytes and make sure
1088 # a BadZipFile exception is raised when we try to open it
1089 for N in range(len(zipfiledata)):
1090 fp = io.BytesIO(zipfiledata[:N])
1091 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, fp)
1092
Ezio Melottiafd0d112009-07-15 17:17:17 +00001093 def test_is_zip_valid_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001094 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001095 # - passing a filename
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001096 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1097 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
1098
Guido van Rossumd8faa362007-04-27 19:54:29 +00001099 chk = zipfile.is_zipfile(TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001100 self.assertTrue(chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001101 # - passing a file object
1102 with open(TESTFN, "rb") as fp:
1103 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001104 self.assertTrue(chk)
Ezio Melotti35386712009-12-31 13:22:41 +00001105 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001106 zip_contents = fp.read()
1107 # - passing a file-like object
1108 fp = io.BytesIO()
1109 fp.write(zip_contents)
1110 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001111 self.assertTrue(chk)
Ezio Melotti35386712009-12-31 13:22:41 +00001112 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +00001113 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001114 self.assertTrue(chk)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001115
Ezio Melottiafd0d112009-07-15 17:17:17 +00001116 def test_non_existent_file_raises_IOError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001117 # make sure we don't raise an AttributeError when a partially-constructed
1118 # ZipFile instance is finalized; this tests for regression on SF tracker
1119 # bug #403871.
1120
1121 # The bug we're testing for caused an AttributeError to be raised
1122 # when a ZipFile instance was created for a file that did not
1123 # exist; the .fp member was not initialized but was needed by the
1124 # __del__() method. Since the AttributeError is in the __del__(),
1125 # it is ignored, but the user should be sufficiently annoyed by
1126 # the message on the output that regression will be noticed
1127 # quickly.
1128 self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
1129
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001130 def test_empty_file_raises_BadZipFile(self):
1131 f = open(TESTFN, 'w')
1132 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001133 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001134
Ezio Melotti35386712009-12-31 13:22:41 +00001135 with open(TESTFN, 'w') as fp:
1136 fp.write("short file")
Georg Brandl4d540882010-10-28 06:42:33 +00001137 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +00001138
Ezio Melottiafd0d112009-07-15 17:17:17 +00001139 def test_closed_zip_raises_RuntimeError(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001140 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001141 data = io.BytesIO()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001142 with zipfile.ZipFile(data, mode="w") as zipf:
1143 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001144
Andrew Svetlov737fb892012-12-18 21:14:22 +02001145 # This is correct; calling .read on a closed ZipFile should raise
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001146 # a RuntimeError, and so should calling .testzip. An earlier
1147 # version of .testzip would swallow this exception (and any other)
1148 # and report that the first file in the archive was corrupt.
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001149 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
1150 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001151 self.assertRaises(RuntimeError, zipf.testzip)
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001152 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Brian Curtin8fb9b862010-11-18 02:15:28 +00001153 with open(TESTFN, 'w') as f:
1154 f.write('zipfile test data')
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001155 self.assertRaises(RuntimeError, zipf.write, TESTFN)
1156
Ezio Melottiafd0d112009-07-15 17:17:17 +00001157 def test_bad_constructor_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001158 """Check that bad modes passed to ZipFile constructor are caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001159 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
1160
Ezio Melottiafd0d112009-07-15 17:17:17 +00001161 def test_bad_open_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001162 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001163 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1164 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1165
1166 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001167 # read the data to make sure the file is there
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001168 zipf.read("foo.txt")
1169 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001170
Ezio Melottiafd0d112009-07-15 17:17:17 +00001171 def test_read0(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001172 """Check that calling read(0) on a ZipExtFile object returns an empty
1173 string and doesn't advance file pointer."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001174 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1175 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1176 # read the data to make sure the file is there
Brian Curtin8fb9b862010-11-18 02:15:28 +00001177 with zipf.open("foo.txt") as f:
1178 for i in range(FIXEDTEST_SIZE):
1179 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001180
Brian Curtin8fb9b862010-11-18 02:15:28 +00001181 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001182
Ezio Melottiafd0d112009-07-15 17:17:17 +00001183 def test_open_non_existent_item(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001184 """Check that attempting to call open() for an item that doesn't
1185 exist in the archive raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001186 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1187 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001188
Ezio Melottiafd0d112009-07-15 17:17:17 +00001189 def test_bad_compression_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001190 """Check that bad compression methods passed to ZipFile.open are
1191 caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001192 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
1193
Martin v. Löwisb3260f02012-05-01 08:38:01 +02001194 def test_unsupported_compression(self):
1195 # data is declared as shrunk, but actually deflated
1196 data = (b'PK\x03\x04.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00'
1197 b'\x00\x02\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00x\x03\x00PK\x01'
1198 b'\x02.\x03.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00\x00\x02\x00\x00'
1199 b'\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
1200 b'\x80\x01\x00\x00\x00\x00xPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00'
1201 b'/\x00\x00\x00!\x00\x00\x00\x00\x00')
1202 with zipfile.ZipFile(io.BytesIO(data), 'r') as zipf:
1203 self.assertRaises(NotImplementedError, zipf.open, 'x')
1204
Ezio Melottiafd0d112009-07-15 17:17:17 +00001205 def test_null_byte_in_filename(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001206 """Check that a filename containing a null byte is properly
1207 terminated."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001208 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1209 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
1210 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001211
Ezio Melottiafd0d112009-07-15 17:17:17 +00001212 def test_struct_sizes(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001213 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001214 self.assertEqual(zipfile.sizeEndCentDir, 22)
1215 self.assertEqual(zipfile.sizeCentralDir, 46)
1216 self.assertEqual(zipfile.sizeEndCentDir64, 56)
1217 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
1218
Ezio Melottiafd0d112009-07-15 17:17:17 +00001219 def test_comments(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001220 """Check that comments on the archive are handled properly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001221
1222 # check default comment is empty
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001223 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1224 self.assertEqual(zipf.comment, b'')
1225 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1226
1227 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1228 self.assertEqual(zipfr.comment, b'')
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001229
1230 # check a simple short comment
1231 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001232 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1233 zipf.comment = comment
1234 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1235 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1236 self.assertEqual(zipf.comment, comment)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001237
1238 # check a comment of max length
1239 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
1240 comment2 = comment2.encode("ascii")
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001241 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1242 zipf.comment = comment2
1243 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1244
1245 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1246 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001247
1248 # check a comment that is too long is truncated
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001249 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1250 zipf.comment = comment2 + b'oops'
1251 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1252 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1253 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001254
Antoine Pitrouc3991852012-06-30 17:31:37 +02001255 # check that comments are correctly modified in append mode
1256 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1257 zipf.comment = b"original comment"
1258 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1259 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1260 zipf.comment = b"an updated comment"
1261 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1262 self.assertEqual(zipf.comment, b"an updated comment")
1263
1264 # check that comments are correctly shortened in append mode
1265 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1266 zipf.comment = b"original comment that's longer"
1267 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1268 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1269 zipf.comment = b"shorter comment"
1270 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1271 self.assertEqual(zipf.comment, b"shorter comment")
1272
R David Murrayf50b38a2012-04-12 18:44:58 -04001273 def test_unicode_comment(self):
1274 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1275 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1276 with self.assertRaises(TypeError):
1277 zipf.comment = "this is an error"
1278
1279 def test_change_comment_in_empty_archive(self):
1280 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1281 self.assertFalse(zipf.filelist)
1282 zipf.comment = b"this is a comment"
1283 with zipfile.ZipFile(TESTFN, "r") as zipf:
1284 self.assertEqual(zipf.comment, b"this is a comment")
1285
1286 def test_change_comment_in_nonempty_archive(self):
1287 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1288 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1289 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1290 self.assertTrue(zipf.filelist)
1291 zipf.comment = b"this is a comment"
1292 with zipfile.ZipFile(TESTFN, "r") as zipf:
1293 self.assertEqual(zipf.comment, b"this is a comment")
1294
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001295 def check_testzip_with_bad_crc(self, compression):
1296 """Tests that files with bad CRCs return their name from testzip."""
1297 zipdata = self.zips_with_bad_crc[compression]
1298
1299 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1300 # testzip returns the name of the first corrupt file, or None
1301 self.assertEqual('afile', zipf.testzip())
1302
1303 def test_testzip_with_bad_crc_stored(self):
1304 self.check_testzip_with_bad_crc(zipfile.ZIP_STORED)
1305
Ezio Melotti975077a2011-05-19 22:03:22 +03001306 @requires_zlib
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001307 def test_testzip_with_bad_crc_deflated(self):
1308 self.check_testzip_with_bad_crc(zipfile.ZIP_DEFLATED)
1309
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001310 @requires_bz2
1311 def test_testzip_with_bad_crc_bzip2(self):
1312 self.check_testzip_with_bad_crc(zipfile.ZIP_BZIP2)
1313
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001314 @requires_lzma
1315 def test_testzip_with_bad_crc_lzma(self):
1316 self.check_testzip_with_bad_crc(zipfile.ZIP_LZMA)
1317
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001318 def check_read_with_bad_crc(self, compression):
Georg Brandl4d540882010-10-28 06:42:33 +00001319 """Tests that files with bad CRCs raise a BadZipFile exception when read."""
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001320 zipdata = self.zips_with_bad_crc[compression]
1321
1322 # Using ZipFile.read()
1323 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
Georg Brandl4d540882010-10-28 06:42:33 +00001324 self.assertRaises(zipfile.BadZipFile, zipf.read, 'afile')
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001325
1326 # Using ZipExtFile.read()
1327 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1328 with zipf.open('afile', 'r') as corrupt_file:
Georg Brandl4d540882010-10-28 06:42:33 +00001329 self.assertRaises(zipfile.BadZipFile, corrupt_file.read)
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001330
1331 # Same with small reads (in order to exercise the buffering logic)
1332 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1333 with zipf.open('afile', 'r') as corrupt_file:
1334 corrupt_file.MIN_READ_SIZE = 2
Georg Brandl4d540882010-10-28 06:42:33 +00001335 with self.assertRaises(zipfile.BadZipFile):
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001336 while corrupt_file.read(2):
1337 pass
1338
1339 def test_read_with_bad_crc_stored(self):
1340 self.check_read_with_bad_crc(zipfile.ZIP_STORED)
1341
Ezio Melotti975077a2011-05-19 22:03:22 +03001342 @requires_zlib
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001343 def test_read_with_bad_crc_deflated(self):
1344 self.check_read_with_bad_crc(zipfile.ZIP_DEFLATED)
1345
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001346 @requires_bz2
1347 def test_read_with_bad_crc_bzip2(self):
1348 self.check_read_with_bad_crc(zipfile.ZIP_BZIP2)
1349
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001350 @requires_lzma
1351 def test_read_with_bad_crc_lzma(self):
1352 self.check_read_with_bad_crc(zipfile.ZIP_LZMA)
1353
Antoine Pitrou6464d5f2010-09-12 14:51:20 +00001354 def check_read_return_size(self, compression):
1355 # Issue #9837: ZipExtFile.read() shouldn't return more bytes
1356 # than requested.
1357 for test_size in (1, 4095, 4096, 4097, 16384):
1358 file_size = test_size + 1
1359 junk = b''.join(struct.pack('B', randint(0, 255))
1360 for x in range(file_size))
1361 with zipfile.ZipFile(io.BytesIO(), "w", compression) as zipf:
1362 zipf.writestr('foo', junk)
1363 with zipf.open('foo', 'r') as fp:
1364 buf = fp.read(test_size)
1365 self.assertEqual(len(buf), test_size)
1366
1367 def test_read_return_size_stored(self):
1368 self.check_read_return_size(zipfile.ZIP_STORED)
1369
Ezio Melotti975077a2011-05-19 22:03:22 +03001370 @requires_zlib
Antoine Pitrou6464d5f2010-09-12 14:51:20 +00001371 def test_read_return_size_deflated(self):
1372 self.check_read_return_size(zipfile.ZIP_DEFLATED)
1373
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001374 @requires_bz2
1375 def test_read_return_size_bzip2(self):
1376 self.check_read_return_size(zipfile.ZIP_BZIP2)
1377
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001378 @requires_lzma
1379 def test_read_return_size_lzma(self):
1380 self.check_read_return_size(zipfile.ZIP_LZMA)
1381
Georg Brandl268e4d42010-10-14 06:59:45 +00001382 def test_empty_zipfile(self):
1383 # Check that creating a file in 'w' or 'a' mode and closing without
1384 # adding any files to the archives creates a valid empty ZIP file
1385 zipf = zipfile.ZipFile(TESTFN, mode="w")
1386 zipf.close()
1387 try:
1388 zipf = zipfile.ZipFile(TESTFN, mode="r")
1389 except zipfile.BadZipFile:
1390 self.fail("Unable to create empty ZIP file in 'w' mode")
1391
1392 zipf = zipfile.ZipFile(TESTFN, mode="a")
1393 zipf.close()
1394 try:
1395 zipf = zipfile.ZipFile(TESTFN, mode="r")
1396 except:
1397 self.fail("Unable to create empty ZIP file in 'a' mode")
1398
1399 def test_open_empty_file(self):
1400 # Issue 1710703: Check that opening a file with less than 22 bytes
Georg Brandl4d540882010-10-28 06:42:33 +00001401 # raises a BadZipFile exception (rather than the previously unhelpful
Georg Brandl268e4d42010-10-14 06:59:45 +00001402 # IOError)
1403 f = open(TESTFN, 'w')
1404 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001405 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN, 'r')
Georg Brandl268e4d42010-10-14 06:59:45 +00001406
Senthil Kumaran29fa9d42011-10-20 01:46:00 +08001407 def test_create_zipinfo_before_1980(self):
1408 self.assertRaises(ValueError,
1409 zipfile.ZipInfo, 'seventies', (1979, 1, 1, 0, 0, 0))
1410
Guido van Rossumd8faa362007-04-27 19:54:29 +00001411 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001412 unlink(TESTFN)
1413 unlink(TESTFN2)
1414
Thomas Wouterscf297e42007-02-23 15:07:44 +00001415
1416class DecryptionTests(unittest.TestCase):
Ezio Melotti35386712009-12-31 13:22:41 +00001417 """Check that ZIP decryption works. Since the library does not
1418 support encryption at the moment, we use a pre-generated encrypted
1419 ZIP file."""
Thomas Wouterscf297e42007-02-23 15:07:44 +00001420
1421 data = (
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001422 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
1423 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
1424 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
1425 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
1426 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
1427 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
1428 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +00001429 data2 = (
1430 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
1431 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
1432 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
1433 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
1434 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
1435 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
1436 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
1437 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +00001438
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001439 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +00001440 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +00001441
1442 def setUp(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001443 with open(TESTFN, "wb") as fp:
1444 fp.write(self.data)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001445 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti35386712009-12-31 13:22:41 +00001446 with open(TESTFN2, "wb") as fp:
1447 fp.write(self.data2)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001448 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001449
1450 def tearDown(self):
1451 self.zip.close()
1452 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001453 self.zip2.close()
1454 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001455
Ezio Melottiafd0d112009-07-15 17:17:17 +00001456 def test_no_password(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001457 # Reading the encrypted file without password
1458 # must generate a RunTime exception
1459 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001460 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001461
Ezio Melottiafd0d112009-07-15 17:17:17 +00001462 def test_bad_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001463 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001464 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001465 self.zip2.setpassword(b"perl")
1466 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001467
Ezio Melotti975077a2011-05-19 22:03:22 +03001468 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +00001469 def test_good_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001470 self.zip.setpassword(b"python")
Ezio Melotti35386712009-12-31 13:22:41 +00001471 self.assertEqual(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001472 self.zip2.setpassword(b"12345")
Ezio Melotti35386712009-12-31 13:22:41 +00001473 self.assertEqual(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001474
R. David Murray8d855d82010-12-21 21:53:37 +00001475 def test_unicode_password(self):
1476 self.assertRaises(TypeError, self.zip.setpassword, "unicode")
1477 self.assertRaises(TypeError, self.zip.read, "test.txt", "python")
1478 self.assertRaises(TypeError, self.zip.open, "test.txt", pwd="python")
1479 self.assertRaises(TypeError, self.zip.extract, "test.txt", pwd="python")
1480
Guido van Rossumd8faa362007-04-27 19:54:29 +00001481
1482class TestsWithRandomBinaryFiles(unittest.TestCase):
1483 def setUp(self):
1484 datacount = randint(16, 64)*1024 + randint(1, 1024)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001485 self.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
1486 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001487
1488 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +00001489 with open(TESTFN, "wb") as fp:
1490 fp.write(self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001491
1492 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001493 unlink(TESTFN)
1494 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001495
Ezio Melottiafd0d112009-07-15 17:17:17 +00001496 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001497 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001498 with zipfile.ZipFile(f, "w", compression) as zipfp:
1499 zipfp.write(TESTFN, "another.name")
1500 zipfp.write(TESTFN, TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001501
Ezio Melottiafd0d112009-07-15 17:17:17 +00001502 def zip_test(self, f, compression):
1503 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001504
1505 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001506 with zipfile.ZipFile(f, "r", compression) as zipfp:
1507 testdata = zipfp.read(TESTFN)
1508 self.assertEqual(len(testdata), len(self.data))
1509 self.assertEqual(testdata, self.data)
1510 self.assertEqual(zipfp.read("another.name"), self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001511 if not isinstance(f, str):
1512 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001513
Ezio Melottiafd0d112009-07-15 17:17:17 +00001514 def test_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001515 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001516 self.zip_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001517
Ezio Melotti975077a2011-05-19 22:03:22 +03001518 @requires_zlib
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001519 def test_deflated(self):
1520 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1521 self.zip_test(f, zipfile.ZIP_DEFLATED)
1522
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001523 @requires_bz2
1524 def test_bzip2(self):
1525 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1526 self.zip_test(f, zipfile.ZIP_BZIP2)
1527
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001528 @requires_lzma
1529 def test_lzma(self):
1530 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1531 self.zip_test(f, zipfile.ZIP_LZMA)
1532
Ezio Melottiafd0d112009-07-15 17:17:17 +00001533 def zip_open_test(self, f, compression):
1534 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001535
1536 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001537 with zipfile.ZipFile(f, "r", compression) as zipfp:
1538 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001539 with zipfp.open(TESTFN) as zipopen1:
1540 while True:
1541 read_data = zipopen1.read(256)
1542 if not read_data:
1543 break
1544 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001545
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001546 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001547 with zipfp.open("another.name") as zipopen2:
1548 while True:
1549 read_data = zipopen2.read(256)
1550 if not read_data:
1551 break
1552 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001553
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001554 testdata1 = b''.join(zipdata1)
1555 self.assertEqual(len(testdata1), len(self.data))
1556 self.assertEqual(testdata1, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001557
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001558 testdata2 = b''.join(zipdata2)
Ezio Melotti35386712009-12-31 13:22:41 +00001559 self.assertEqual(len(testdata2), len(self.data))
1560 self.assertEqual(testdata2, self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001561 if not isinstance(f, str):
1562 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001563
Ezio Melottiafd0d112009-07-15 17:17:17 +00001564 def test_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001565 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001566 self.zip_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001567
Ezio Melotti975077a2011-05-19 22:03:22 +03001568 @requires_zlib
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001569 def test_open_deflated(self):
1570 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1571 self.zip_open_test(f, zipfile.ZIP_DEFLATED)
1572
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001573 @requires_bz2
1574 def test_open_bzip2(self):
1575 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1576 self.zip_open_test(f, zipfile.ZIP_BZIP2)
1577
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001578 @requires_lzma
1579 def test_open_lzma(self):
1580 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1581 self.zip_open_test(f, zipfile.ZIP_LZMA)
1582
Ezio Melottiafd0d112009-07-15 17:17:17 +00001583 def zip_random_open_test(self, f, compression):
1584 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001585
1586 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001587 with zipfile.ZipFile(f, "r", compression) as zipfp:
1588 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001589 with zipfp.open(TESTFN) as zipopen1:
1590 while True:
1591 read_data = zipopen1.read(randint(1, 1024))
1592 if not read_data:
1593 break
1594 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001595
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001596 testdata = b''.join(zipdata1)
1597 self.assertEqual(len(testdata), len(self.data))
1598 self.assertEqual(testdata, self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001599 if not isinstance(f, str):
1600 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001601
Ezio Melottiafd0d112009-07-15 17:17:17 +00001602 def test_random_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001603 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001604 self.zip_random_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001605
Ezio Melotti975077a2011-05-19 22:03:22 +03001606 @requires_zlib
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001607 def test_random_open_deflated(self):
1608 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1609 self.zip_random_open_test(f, zipfile.ZIP_DEFLATED)
1610
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001611 @requires_bz2
1612 def test_random_open_bzip2(self):
1613 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1614 self.zip_random_open_test(f, zipfile.ZIP_BZIP2)
1615
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001616 @requires_lzma
1617 def test_random_open_lzma(self):
1618 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1619 self.zip_random_open_test(f, zipfile.ZIP_LZMA)
1620
Ezio Melotti76430242009-07-11 18:28:48 +00001621
Ezio Melotti975077a2011-05-19 22:03:22 +03001622@requires_zlib
Guido van Rossumd8faa362007-04-27 19:54:29 +00001623class TestsWithMultipleOpens(unittest.TestCase):
1624 def setUp(self):
1625 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001626 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
1627 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
1628 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001629
Ezio Melottiafd0d112009-07-15 17:17:17 +00001630 def test_same_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001631 # Verify that (when the ZipFile is in control of creating file objects)
1632 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001633 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001634 with zipf.open('ones') as zopen1, zipf.open('ones') as zopen2:
1635 data1 = zopen1.read(500)
1636 data2 = zopen2.read(500)
1637 data1 += zopen1.read(500)
1638 data2 += zopen2.read(500)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001639 self.assertEqual(data1, data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001640
Ezio Melottiafd0d112009-07-15 17:17:17 +00001641 def test_different_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001642 # Verify that (when the ZipFile is in control of creating file objects)
1643 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001644 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001645 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1646 data1 = zopen1.read(500)
1647 data2 = zopen2.read(500)
1648 data1 += zopen1.read(500)
1649 data2 += zopen2.read(500)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001650 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
1651 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001652
Ezio Melottiafd0d112009-07-15 17:17:17 +00001653 def test_interleaved(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001654 # Verify that (when the ZipFile is in control of creating file objects)
1655 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001656 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001657 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1658 data1 = zopen1.read(500)
1659 data2 = zopen2.read(500)
1660 data1 += zopen1.read(500)
1661 data2 += zopen2.read(500)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001662 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
1663 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001664
1665 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001666 unlink(TESTFN2)
1667
Guido van Rossumd8faa362007-04-27 19:54:29 +00001668
Martin v. Löwis59e47792009-01-24 14:10:07 +00001669class TestWithDirectory(unittest.TestCase):
1670 def setUp(self):
1671 os.mkdir(TESTFN2)
1672
Ezio Melottiafd0d112009-07-15 17:17:17 +00001673 def test_extract_dir(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001674 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
1675 zipf.extractall(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001676 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1677 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1678 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1679
Ezio Melottiafd0d112009-07-15 17:17:17 +00001680 def test_bug_6050(self):
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001681 # Extraction should succeed if directories already exist
1682 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottiafd0d112009-07-15 17:17:17 +00001683 self.test_extract_dir()
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001684
Ezio Melottiafd0d112009-07-15 17:17:17 +00001685 def test_store_dir(self):
Martin v. Löwis59e47792009-01-24 14:10:07 +00001686 os.mkdir(os.path.join(TESTFN2, "x"))
1687 zipf = zipfile.ZipFile(TESTFN, "w")
1688 zipf.write(os.path.join(TESTFN2, "x"), "x")
1689 self.assertTrue(zipf.filelist[0].filename.endswith("x/"))
1690
1691 def tearDown(self):
1692 shutil.rmtree(TESTFN2)
1693 if os.path.exists(TESTFN):
Ezio Melotti76430242009-07-11 18:28:48 +00001694 unlink(TESTFN)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001695
Guido van Rossumd8faa362007-04-27 19:54:29 +00001696
1697class UniversalNewlineTests(unittest.TestCase):
1698 def setUp(self):
Guido van Rossum9c627722007-08-27 18:31:48 +00001699 self.line_gen = [bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001700 for i in range(FIXEDTEST_SIZE)]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001701 self.seps = ('\r', '\r\n', '\n')
1702 self.arcdata, self.arcfiles = {}, {}
1703 for n, s in enumerate(self.seps):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001704 b = s.encode("ascii")
1705 self.arcdata[s] = b.join(self.line_gen) + b
Guido van Rossumd8faa362007-04-27 19:54:29 +00001706 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001707 f = open(self.arcfiles[s], "wb")
1708 try:
1709 f.write(self.arcdata[s])
1710 finally:
1711 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001712
Ezio Melottiafd0d112009-07-15 17:17:17 +00001713 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001714 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001715 with zipfile.ZipFile(f, "w", compression) as zipfp:
1716 for fn in self.arcfiles.values():
1717 zipfp.write(fn, fn)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001718
Ezio Melottiafd0d112009-07-15 17:17:17 +00001719 def read_test(self, f, compression):
1720 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001721
1722 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001723 with zipfile.ZipFile(f, "r") as zipfp:
1724 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001725 with zipfp.open(fn, "rU") as fp:
1726 zipdata = fp.read()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001727 self.assertEqual(self.arcdata[sep], zipdata)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001728 if not isinstance(f, str):
1729 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001730
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001731 def readline_read_test(self, f, compression):
1732 self.make_test_archive(f, compression)
1733
1734 # Read the ZIP archive
Brian Curtin8fb9b862010-11-18 02:15:28 +00001735 with zipfile.ZipFile(f, "r") as zipfp:
1736 for sep, fn in self.arcfiles.items():
1737 with zipfp.open(fn, "rU") as zipopen:
1738 data = b''
1739 while True:
1740 read = zipopen.readline()
1741 if not read:
1742 break
1743 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001744
Brian Curtin8fb9b862010-11-18 02:15:28 +00001745 read = zipopen.read(5)
1746 if not read:
1747 break
1748 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001749
1750 self.assertEqual(data, self.arcdata['\n'])
1751
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001752 if not isinstance(f, str):
1753 f.close()
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001754
Ezio Melottiafd0d112009-07-15 17:17:17 +00001755 def readline_test(self, f, compression):
1756 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001757
1758 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001759 with zipfile.ZipFile(f, "r") as zipfp:
1760 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001761 with zipfp.open(fn, "rU") as zipopen:
1762 for line in self.line_gen:
1763 linedata = zipopen.readline()
1764 self.assertEqual(linedata, line + b'\n')
1765 if not isinstance(f, str):
1766 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001767
Ezio Melottiafd0d112009-07-15 17:17:17 +00001768 def readlines_test(self, f, compression):
1769 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001770
1771 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001772 with zipfile.ZipFile(f, "r") as zipfp:
1773 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001774 with zipfp.open(fn, "rU") as fp:
1775 ziplines = fp.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001776 for line, zipline in zip(self.line_gen, ziplines):
1777 self.assertEqual(zipline, line + b'\n')
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001778 if not isinstance(f, str):
1779 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001780
Ezio Melottiafd0d112009-07-15 17:17:17 +00001781 def iterlines_test(self, f, compression):
1782 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001783
1784 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001785 with zipfile.ZipFile(f, "r") as zipfp:
1786 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001787 with zipfp.open(fn, "rU") as fp:
1788 for line, zipline in zip(self.line_gen, fp):
1789 self.assertEqual(zipline, line + b'\n')
1790 if not isinstance(f, str):
1791 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001792
Ezio Melottiafd0d112009-07-15 17:17:17 +00001793 def test_read_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001794 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001795 self.read_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001796
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001797 def test_readline_read_stored(self):
1798 # Issue #7610: calls to readline() interleaved with calls to read().
1799 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1800 self.readline_read_test(f, zipfile.ZIP_STORED)
1801
Ezio Melottiafd0d112009-07-15 17:17:17 +00001802 def test_readline_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001803 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001804 self.readline_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001805
Ezio Melottiafd0d112009-07-15 17:17:17 +00001806 def test_readlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001807 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001808 self.readlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001809
Ezio Melottiafd0d112009-07-15 17:17:17 +00001810 def test_iterlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001811 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001812 self.iterlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001813
Ezio Melotti975077a2011-05-19 22:03:22 +03001814 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +00001815 def test_read_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001816 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001817 self.read_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001818
Ezio Melotti975077a2011-05-19 22:03:22 +03001819 @requires_zlib
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001820 def test_readline_read_deflated(self):
1821 # Issue #7610: calls to readline() interleaved with calls to read().
1822 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1823 self.readline_read_test(f, zipfile.ZIP_DEFLATED)
1824
Ezio Melotti975077a2011-05-19 22:03:22 +03001825 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +00001826 def test_readline_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001827 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001828 self.readline_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001829
Ezio Melotti975077a2011-05-19 22:03:22 +03001830 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +00001831 def test_readlines_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001832 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001833 self.readlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001834
Ezio Melotti975077a2011-05-19 22:03:22 +03001835 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +00001836 def test_iterlines_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001837 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001838 self.iterlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001839
Martin v. Löwisf6b16a42012-05-01 07:58:44 +02001840 @requires_bz2
1841 def test_read_bzip2(self):
1842 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1843 self.read_test(f, zipfile.ZIP_BZIP2)
1844
1845 @requires_bz2
1846 def test_readline_read_bzip2(self):
1847 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1848 self.readline_read_test(f, zipfile.ZIP_BZIP2)
1849
1850 @requires_bz2
1851 def test_readline_bzip2(self):
1852 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1853 self.readline_test(f, zipfile.ZIP_BZIP2)
1854
1855 @requires_bz2
1856 def test_readlines_bzip2(self):
1857 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1858 self.readlines_test(f, zipfile.ZIP_BZIP2)
1859
1860 @requires_bz2
1861 def test_iterlines_bzip2(self):
1862 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1863 self.iterlines_test(f, zipfile.ZIP_BZIP2)
1864
Martin v. Löwis7fb79fc2012-05-13 10:06:36 +02001865 @requires_lzma
1866 def test_read_lzma(self):
1867 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1868 self.read_test(f, zipfile.ZIP_LZMA)
1869
1870 @requires_lzma
1871 def test_readline_read_lzma(self):
1872 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1873 self.readline_read_test(f, zipfile.ZIP_LZMA)
1874
1875 @requires_lzma
1876 def test_readline_lzma(self):
1877 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1878 self.readline_test(f, zipfile.ZIP_LZMA)
1879
1880 @requires_lzma
1881 def test_readlines_lzma(self):
1882 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1883 self.readlines_test(f, zipfile.ZIP_LZMA)
1884
1885 @requires_lzma
1886 def test_iterlines_lzma(self):
1887 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1888 self.iterlines_test(f, zipfile.ZIP_LZMA)
1889
Guido van Rossumd8faa362007-04-27 19:54:29 +00001890 def tearDown(self):
1891 for sep, fn in self.arcfiles.items():
1892 os.remove(fn)
Ezio Melotti76430242009-07-11 18:28:48 +00001893 unlink(TESTFN)
1894 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001895
1896
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001897def test_main():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001898 run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
1899 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
Ezio Melotti76430242009-07-11 18:28:48 +00001900 TestWithDirectory, UniversalNewlineTests,
1901 TestsWithRandomBinaryFiles)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001902
1903if __name__ == "__main__":
1904 test_main()