blob: 741cee96678f21482ef4bb61b73920e563582ec3 [file] [log] [blame]
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001# We can test part of the module without zlib.
Guido van Rossum368f04a2000-04-10 13:23:04 +00002try:
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00003 import zlib
4except ImportError:
5 zlib = None
Ezio Melotti74c96ec2009-07-08 22:24:06 +00006
7import io
8import os
Georg Brandl5ba11de2011-01-01 10:09:32 +00009import sys
Barry Warsaw28a691b2010-04-17 00:19:56 +000010import imp
Ezio Melotti35386712009-12-31 13:22:41 +000011import time
Ezio Melotti74c96ec2009-07-08 22:24:06 +000012import shutil
13import struct
14import zipfile
15import unittest
16
Tim Petersa45cacf2004-08-20 03:47:14 +000017
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000018from tempfile import TemporaryFile
Guido van Rossumd8faa362007-04-27 19:54:29 +000019from random import randint, random
Ezio Melotti74c96ec2009-07-08 22:24:06 +000020from unittest import skipUnless
Tim Petersa19a1682001-03-29 04:36:09 +000021
Serhiy Storchaka45c43752013-01-29 20:10:28 +020022from test.support import (TESTFN, run_unittest, findfile, unlink,
23 captured_stdout)
Guido van Rossum368f04a2000-04-10 13:23:04 +000024
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000025TESTFN2 = TESTFN + "2"
Martin v. Löwis59e47792009-01-24 14:10:07 +000026TESTFNDIR = TESTFN + "d"
Guido van Rossumb5a755e2007-07-18 18:15:48 +000027FIXEDTEST_SIZE = 1000
Georg Brandl5ba11de2011-01-01 10:09:32 +000028DATAFILES_DIR = 'zipfile_datafiles'
Guido van Rossum368f04a2000-04-10 13:23:04 +000029
Christian Heimes790c8232008-01-07 21:14:23 +000030SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'),
31 ('ziptest2dir/_ziptest2', 'qawsedrftg'),
32 ('/ziptest2dir/ziptest3dir/_ziptest3', 'azsxdcfvgb'),
33 ('ziptest2dir/ziptest3dir/ziptest4dir/_ziptest3', '6y7u8i9o0p')]
34
Ezio Melotti76430242009-07-11 18:28:48 +000035
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000036class TestsWithSourceFile(unittest.TestCase):
37 def setUp(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +000038 self.line_gen = (bytes("Zipfile test line %d. random float: %f" %
Guido van Rossum9c627722007-08-27 18:31:48 +000039 (i, random()), "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +000040 for i in range(FIXEDTEST_SIZE))
41 self.data = b'\n'.join(self.line_gen) + b'\n'
Fred Drake6e7e4852001-02-28 05:34:16 +000042
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000043 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +000044 with open(TESTFN, "wb") as fp:
45 fp.write(self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000046
Ezio Melottiafd0d112009-07-15 17:17:17 +000047 def make_test_archive(self, f, compression):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000048 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000049 with zipfile.ZipFile(f, "w", compression) as zipfp:
50 zipfp.write(TESTFN, "another.name")
51 zipfp.write(TESTFN, TESTFN)
52 zipfp.writestr("strfile", self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000053
Ezio Melottiafd0d112009-07-15 17:17:17 +000054 def zip_test(self, f, compression):
55 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +000056
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000057 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000058 with zipfile.ZipFile(f, "r", compression) as zipfp:
59 self.assertEqual(zipfp.read(TESTFN), self.data)
60 self.assertEqual(zipfp.read("another.name"), self.data)
61 self.assertEqual(zipfp.read("strfile"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000062
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000063 # Print the ZIP directory
64 fp = io.StringIO()
65 zipfp.printdir(file=fp)
66 directory = fp.getvalue()
67 lines = directory.splitlines()
Ezio Melotti35386712009-12-31 13:22:41 +000068 self.assertEqual(len(lines), 4) # Number of files + header
Thomas Wouters0e3f5912006-08-11 14:57:12 +000069
Benjamin Peterson577473f2010-01-19 00:09:57 +000070 self.assertIn('File Name', lines[0])
71 self.assertIn('Modified', lines[0])
72 self.assertIn('Size', lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +000073
Ezio Melotti35386712009-12-31 13:22:41 +000074 fn, date, time_, size = lines[1].split()
75 self.assertEqual(fn, 'another.name')
76 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
77 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
78 self.assertEqual(size, str(len(self.data)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000079
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000080 # Check the namelist
81 names = zipfp.namelist()
Ezio Melotti35386712009-12-31 13:22:41 +000082 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +000083 self.assertIn(TESTFN, names)
84 self.assertIn("another.name", names)
85 self.assertIn("strfile", names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000086
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000087 # Check infolist
88 infos = zipfp.infolist()
Ezio Melotti35386712009-12-31 13:22:41 +000089 names = [i.filename for i in infos]
90 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +000091 self.assertIn(TESTFN, names)
92 self.assertIn("another.name", names)
93 self.assertIn("strfile", names)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000094 for i in infos:
Ezio Melotti35386712009-12-31 13:22:41 +000095 self.assertEqual(i.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000096
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000097 # check getinfo
98 for nm in (TESTFN, "another.name", "strfile"):
99 info = zipfp.getinfo(nm)
Ezio Melotti35386712009-12-31 13:22:41 +0000100 self.assertEqual(info.filename, nm)
101 self.assertEqual(info.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000102
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000103 # Check that testzip doesn't raise an exception
104 zipfp.testzip()
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000105 if not isinstance(f, str):
106 f.close()
Tim Peters7d3bad62001-04-04 18:56:49 +0000107
Ezio Melottiafd0d112009-07-15 17:17:17 +0000108 def test_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000109 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000110 self.zip_test(f, zipfile.ZIP_STORED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000111
Ezio Melottiafd0d112009-07-15 17:17:17 +0000112 def zip_open_test(self, f, compression):
113 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000114
115 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000116 with zipfile.ZipFile(f, "r", compression) as zipfp:
117 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000118 with zipfp.open(TESTFN) as zipopen1:
119 while True:
120 read_data = zipopen1.read(256)
121 if not read_data:
122 break
123 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000124
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000125 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000126 with zipfp.open("another.name") as zipopen2:
127 while True:
128 read_data = zipopen2.read(256)
129 if not read_data:
130 break
131 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000132
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000133 self.assertEqual(b''.join(zipdata1), self.data)
134 self.assertEqual(b''.join(zipdata2), self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000135 if not isinstance(f, str):
136 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000137
Ezio Melottiafd0d112009-07-15 17:17:17 +0000138 def test_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000139 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000140 self.zip_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000141
Ezio Melottiafd0d112009-07-15 17:17:17 +0000142 def test_open_via_zip_info(self):
Georg Brandlb533e262008-05-25 18:19:30 +0000143 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000144 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
145 zipfp.writestr("name", "foo")
146 zipfp.writestr("name", "bar")
Georg Brandlb533e262008-05-25 18:19:30 +0000147
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000148 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
149 infos = zipfp.infolist()
150 data = b""
151 for info in infos:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000152 with zipfp.open(info) as zipopen:
153 data += zipopen.read()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000154 self.assertTrue(data == b"foobar" or data == b"barfoo")
155 data = b""
156 for info in infos:
157 data += zipfp.read(info)
158 self.assertTrue(data == b"foobar" or data == b"barfoo")
Georg Brandlb533e262008-05-25 18:19:30 +0000159
Ezio Melottiafd0d112009-07-15 17:17:17 +0000160 def zip_random_open_test(self, f, compression):
161 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000162
163 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000164 with zipfile.ZipFile(f, "r", compression) as zipfp:
165 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000166 with zipfp.open(TESTFN) as zipopen1:
167 while True:
168 read_data = zipopen1.read(randint(1, 1024))
169 if not read_data:
170 break
171 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000172
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000173 self.assertEqual(b''.join(zipdata1), self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000174 if not isinstance(f, str):
175 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000176
Ezio Melottiafd0d112009-07-15 17:17:17 +0000177 def test_random_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000178 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000179 self.zip_random_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000180
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000181 def test_univeral_readaheads(self):
182 f = io.BytesIO()
183
184 data = b'a\r\n' * 16 * 1024
185 zipfp = zipfile.ZipFile(f, 'w', zipfile.ZIP_STORED)
186 zipfp.writestr(TESTFN, data)
187 zipfp.close()
188
189 data2 = b''
190 zipfp = zipfile.ZipFile(f, 'r')
Brian Curtin8fb9b862010-11-18 02:15:28 +0000191 with zipfp.open(TESTFN, 'rU') as zipopen:
192 for line in zipopen:
193 data2 += line
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000194 zipfp.close()
195
196 self.assertEqual(data, data2.replace(b'\n', b'\r\n'))
197
198 def zip_readline_read_test(self, f, compression):
199 self.make_test_archive(f, compression)
200
201 # Read the ZIP archive
202 zipfp = zipfile.ZipFile(f, "r")
Brian Curtin8fb9b862010-11-18 02:15:28 +0000203 with zipfp.open(TESTFN) as zipopen:
204 data = b''
205 while True:
206 read = zipopen.readline()
207 if not read:
208 break
209 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000210
Brian Curtin8fb9b862010-11-18 02:15:28 +0000211 read = zipopen.read(100)
212 if not read:
213 break
214 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000215
216 self.assertEqual(data, self.data)
217 zipfp.close()
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000218 if not isinstance(f, str):
219 f.close()
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000220
Ezio Melottiafd0d112009-07-15 17:17:17 +0000221 def zip_readline_test(self, f, compression):
222 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000223
224 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000225 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000226 with zipfp.open(TESTFN) as zipopen:
227 for line in self.line_gen:
228 linedata = zipopen.readline()
229 self.assertEqual(linedata, line + '\n')
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000230 if not isinstance(f, str):
231 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000232
Ezio Melottiafd0d112009-07-15 17:17:17 +0000233 def zip_readlines_test(self, f, compression):
234 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000235
236 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000237 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000238 with zipfp.open(TESTFN) as zipopen:
239 ziplines = zipopen.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000240 for line, zipline in zip(self.line_gen, ziplines):
241 self.assertEqual(zipline, line + '\n')
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000242 if not isinstance(f, str):
243 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000244
Ezio Melottiafd0d112009-07-15 17:17:17 +0000245 def zip_iterlines_test(self, f, compression):
246 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000247
248 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000249 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000250 with zipfp.open(TESTFN) as zipopen:
251 for line, zipline in zip(self.line_gen, zipopen):
252 self.assertEqual(zipline, line + '\n')
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000253 if not isinstance(f, str):
254 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000255
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000256 def test_readline_read_stored(self):
257 # Issue #7610: calls to readline() interleaved with calls to read().
258 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
259 self.zip_readline_read_test(f, zipfile.ZIP_STORED)
260
Ezio Melottiafd0d112009-07-15 17:17:17 +0000261 def test_readline_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000262 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000263 self.zip_readline_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000264
Ezio Melottiafd0d112009-07-15 17:17:17 +0000265 def test_readlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000266 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000267 self.zip_readlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000268
Ezio Melottiafd0d112009-07-15 17:17:17 +0000269 def test_iterlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000270 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000271 self.zip_iterlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000272
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000273 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000274 def test_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000275 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000276 self.zip_test(f, zipfile.ZIP_DEFLATED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000277
Guido van Rossumd8faa362007-04-27 19:54:29 +0000278
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000279 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000280 def test_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_open_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000283
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000284 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000285 def test_random_open_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000286 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000287 self.zip_random_open_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000288
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000289 @skipUnless(zlib, "requires zlib")
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000290 def test_readline_read_deflated(self):
291 # Issue #7610: calls to readline() interleaved with calls to read().
292 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
293 self.zip_readline_read_test(f, zipfile.ZIP_DEFLATED)
294
295 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000296 def test_readline_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_readline_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000299
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000300 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000301 def test_readlines_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_readlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000304
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000305 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000306 def test_iterlines_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000307 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000308 self.zip_iterlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000309
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000310 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000311 def test_low_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000312 """Check for cases where compressed data is larger than original."""
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000313 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000314 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
315 zipfp.writestr("strfile", '12')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000316
317 # Get an open object for strfile
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000318 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_DEFLATED) as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000319 with zipfp.open("strfile") as openobj:
320 self.assertEqual(openobj.read(1), b'1')
321 self.assertEqual(openobj.read(1), b'2')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000322
Ezio Melottiafd0d112009-07-15 17:17:17 +0000323 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000324 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
325 zipfp.write(TESTFN, "/absolute")
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000326
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000327 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
328 self.assertEqual(zipfp.namelist(), ["absolute"])
Tim Peters32cbc962006-02-20 21:42:18 +0000329
Ezio Melottiafd0d112009-07-15 17:17:17 +0000330 def test_append_to_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000331 """Test appending to an existing zipfile."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000332 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
333 zipfp.write(TESTFN, TESTFN)
334
335 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
336 zipfp.writestr("strfile", self.data)
337 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000338
Ezio Melottiafd0d112009-07-15 17:17:17 +0000339 def test_append_to_non_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000340 """Test appending to an existing file that is not a zipfile."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000341 # NOTE: this test fails if len(d) < 22 because of the first
342 # line "fpin.seek(-22, 2)" in _EndRecData
Ezio Melotti35386712009-12-31 13:22:41 +0000343 data = b'I am not a ZipFile!'*10
344 with open(TESTFN2, 'wb') as f:
345 f.write(data)
346
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000347 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
348 zipfp.write(TESTFN, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000349
Ezio Melotti35386712009-12-31 13:22:41 +0000350 with open(TESTFN2, 'rb') as f:
351 f.seek(len(data))
352 with zipfile.ZipFile(f, "r") as zipfp:
353 self.assertEqual(zipfp.namelist(), [TESTFN])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000354
R David Murray4fbb9db2011-06-09 15:50:51 -0400355 def test_ignores_newline_at_end(self):
356 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
357 zipfp.write(TESTFN, TESTFN)
358 with open(TESTFN2, 'a') as f:
359 f.write("\r\n\00\00\00")
360 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
361 self.assertIsInstance(zipfp, zipfile.ZipFile)
362
363 def test_ignores_stuff_appended_past_comments(self):
364 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
365 zipfp.comment = b"this is a comment"
366 zipfp.write(TESTFN, TESTFN)
367 with open(TESTFN2, 'a') as f:
368 f.write("abcdef\r\n")
369 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
370 self.assertIsInstance(zipfp, zipfile.ZipFile)
371 self.assertEqual(zipfp.comment, b"this is a comment")
372
Ezio Melottiafd0d112009-07-15 17:17:17 +0000373 def test_write_default_name(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000374 """Check that calling ZipFile.write without arcname specified
375 produces the expected result."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000376 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
377 zipfp.write(TESTFN)
Brian Curtin8fb9b862010-11-18 02:15:28 +0000378 with open(TESTFN, "rb") as f:
379 self.assertEqual(zipfp.read(TESTFN), f.read())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000380
Ezio Melotti78ea2022009-09-12 18:41:20 +0000381 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000382 def test_per_file_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000383 """Check that files within a Zip archive can have different
384 compression options."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000385 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
386 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
387 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
388 sinfo = zipfp.getinfo('storeme')
389 dinfo = zipfp.getinfo('deflateme')
390 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
391 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000392
Ezio Melottiafd0d112009-07-15 17:17:17 +0000393 def test_write_to_readonly(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000394 """Check that trying to call write() on a readonly ZipFile object
395 raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000396 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
397 zipfp.writestr("somefile.txt", "bogus")
398
399 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
400 self.assertRaises(RuntimeError, zipfp.write, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000401
Ezio Melottiafd0d112009-07-15 17:17:17 +0000402 def test_extract(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000403 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
404 for fpath, fdata in SMALL_TEST_DATA:
405 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000406
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000407 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
408 for fpath, fdata in SMALL_TEST_DATA:
409 writtenfile = zipfp.extract(fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000410
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000411 # make sure it was written to the right place
412 if os.path.isabs(fpath):
413 correctfile = os.path.join(os.getcwd(), fpath[1:])
414 else:
415 correctfile = os.path.join(os.getcwd(), fpath)
416 correctfile = os.path.normpath(correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000417
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000418 self.assertEqual(writtenfile, correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000419
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000420 # make sure correct data is in correct file
Brian Curtin8fb9b862010-11-18 02:15:28 +0000421 with open(writtenfile, "rb") as f:
422 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000423
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000424 os.remove(writtenfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000425
426 # remove the test file subdirectories
427 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
428
Ezio Melottiafd0d112009-07-15 17:17:17 +0000429 def test_extract_all(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000430 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
431 for fpath, fdata in SMALL_TEST_DATA:
432 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000433
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000434 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
435 zipfp.extractall()
436 for fpath, fdata in SMALL_TEST_DATA:
437 if os.path.isabs(fpath):
438 outfile = os.path.join(os.getcwd(), fpath[1:])
439 else:
440 outfile = os.path.join(os.getcwd(), fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000441
Brian Curtin8fb9b862010-11-18 02:15:28 +0000442 with open(outfile, "rb") as f:
443 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000444
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000445 os.remove(outfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000446
447 # remove the test file subdirectories
448 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
449
Ronald Oussorenee5c8852010-02-07 20:24:02 +0000450 def test_writestr_compression(self):
451 zipfp = zipfile.ZipFile(TESTFN2, "w")
452 zipfp.writestr("a.txt", "hello world", compress_type=zipfile.ZIP_STORED)
453 if zlib:
454 zipfp.writestr("b.txt", "hello world", compress_type=zipfile.ZIP_DEFLATED)
455
456 info = zipfp.getinfo('a.txt')
457 self.assertEqual(info.compress_type, zipfile.ZIP_STORED)
458
459 if zlib:
460 info = zipfp.getinfo('b.txt')
461 self.assertEqual(info.compress_type, zipfile.ZIP_DEFLATED)
462
463
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000464 def zip_test_writestr_permissions(self, f, compression):
465 # Make sure that writestr creates files with mode 0600,
466 # when it is passed a name rather than a ZipInfo instance.
467
Ezio Melottiafd0d112009-07-15 17:17:17 +0000468 self.make_test_archive(f, compression)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000469 with zipfile.ZipFile(f, "r") as zipfp:
470 zinfo = zipfp.getinfo('strfile')
471 self.assertEqual(zinfo.external_attr, 0o600 << 16)
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000472 if not isinstance(f, str):
473 f.close()
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000474
Ezio Melottiafd0d112009-07-15 17:17:17 +0000475 def test_writestr_permissions(self):
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000476 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
477 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
478
Gregory P. Smithb0d9ca92009-07-07 05:06:04 +0000479 def test_writestr_extended_local_header_issue1202(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000480 with zipfile.ZipFile(TESTFN2, 'w') as orig_zip:
481 for data in 'abcdefghijklmnop':
482 zinfo = zipfile.ZipInfo(data)
483 zinfo.flag_bits |= 0x08 # Include an extended local header.
484 orig_zip.writestr(zinfo, data)
485
486 def test_close(self):
487 """Check that the zipfile is closed after the 'with' block."""
488 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
489 for fpath, fdata in SMALL_TEST_DATA:
490 zipfp.writestr(fpath, fdata)
491 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
492 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
493
494 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
495 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
496 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
497
498 def test_close_on_exception(self):
499 """Check that the zipfile is closed if an exception is raised in the
500 'with' block."""
501 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
502 for fpath, fdata in SMALL_TEST_DATA:
503 zipfp.writestr(fpath, fdata)
504
505 try:
506 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
Georg Brandl4d540882010-10-28 06:42:33 +0000507 raise zipfile.BadZipFile()
508 except zipfile.BadZipFile:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000509 self.assertTrue(zipfp2.fp is None, 'zipfp is not closed')
Gregory P. Smithb0d9ca92009-07-07 05:06:04 +0000510
Senthil Kumaran29fa9d42011-10-20 01:46:00 +0800511 def test_add_file_before_1980(self):
512 # Set atime and mtime to 1970-01-01
513 os.utime(TESTFN, (0, 0))
514 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
515 self.assertRaises(ValueError, zipfp.write, TESTFN)
516
517
Ezio Melottid9a7c4b2011-03-14 18:57:02 +0200518 @skipUnless(zlib, "requires zlib")
Georg Brandl5ba11de2011-01-01 10:09:32 +0000519 def test_unicode_filenames(self):
Georg Brandl04480a82011-01-01 10:42:31 +0000520 # bug #10801
521 fname = findfile('zip_cp437_header.zip')
Georg Brandl5ba11de2011-01-01 10:09:32 +0000522 with zipfile.ZipFile(fname) as zipfp:
Georg Brandl04480a82011-01-01 10:42:31 +0000523 for name in zipfp.namelist():
524 zipfp.open(name).close()
Georg Brandl5ba11de2011-01-01 10:09:32 +0000525
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000526 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +0000527 unlink(TESTFN)
528 unlink(TESTFN2)
529
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000530
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000531class TestZip64InSmallFiles(unittest.TestCase):
532 # These tests test the ZIP64 functionality without using large files,
533 # see test_zipfile64 for proper tests.
534
535 def setUp(self):
536 self._limit = zipfile.ZIP64_LIMIT
537 zipfile.ZIP64_LIMIT = 5
538
Guido van Rossum9c627722007-08-27 18:31:48 +0000539 line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000540 for i in range(0, FIXEDTEST_SIZE))
541 self.data = b'\n'.join(line_gen)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000542
543 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +0000544 with open(TESTFN, "wb") as fp:
545 fp.write(self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000546
Ezio Melottiafd0d112009-07-15 17:17:17 +0000547 def large_file_exception_test(self, f, compression):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000548 with zipfile.ZipFile(f, "w", compression) as zipfp:
549 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti35386712009-12-31 13:22:41 +0000550 zipfp.write, TESTFN, "another.name")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000551
Ezio Melottiafd0d112009-07-15 17:17:17 +0000552 def large_file_exception_test2(self, f, compression):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000553 with zipfile.ZipFile(f, "w", compression) as zipfp:
554 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti35386712009-12-31 13:22:41 +0000555 zipfp.writestr, "another.name", self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000556 if not isinstance(f, str):
557 f.close()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000558
Ezio Melottiafd0d112009-07-15 17:17:17 +0000559 def test_large_file_exception(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000560 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000561 self.large_file_exception_test(f, zipfile.ZIP_STORED)
562 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000563
Ezio Melottiafd0d112009-07-15 17:17:17 +0000564 def zip_test(self, f, compression):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000565 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000566 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
567 zipfp.write(TESTFN, "another.name")
568 zipfp.write(TESTFN, TESTFN)
569 zipfp.writestr("strfile", self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000570
571 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000572 with zipfile.ZipFile(f, "r", compression) as zipfp:
573 self.assertEqual(zipfp.read(TESTFN), self.data)
574 self.assertEqual(zipfp.read("another.name"), self.data)
575 self.assertEqual(zipfp.read("strfile"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000576
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000577 # Print the ZIP directory
578 fp = io.StringIO()
579 zipfp.printdir(fp)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000580
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000581 directory = fp.getvalue()
582 lines = directory.splitlines()
Ezio Melotti35386712009-12-31 13:22:41 +0000583 self.assertEqual(len(lines), 4) # Number of files + header
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000584
Benjamin Peterson577473f2010-01-19 00:09:57 +0000585 self.assertIn('File Name', lines[0])
586 self.assertIn('Modified', lines[0])
587 self.assertIn('Size', lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000588
Ezio Melotti35386712009-12-31 13:22:41 +0000589 fn, date, time_, size = lines[1].split()
590 self.assertEqual(fn, 'another.name')
591 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
592 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
593 self.assertEqual(size, str(len(self.data)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000594
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000595 # Check the namelist
596 names = zipfp.namelist()
Ezio Melotti35386712009-12-31 13:22:41 +0000597 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000598 self.assertIn(TESTFN, names)
599 self.assertIn("another.name", names)
600 self.assertIn("strfile", names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000601
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000602 # Check infolist
603 infos = zipfp.infolist()
Ezio Melotti35386712009-12-31 13:22:41 +0000604 names = [i.filename for i in infos]
605 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000606 self.assertIn(TESTFN, names)
607 self.assertIn("another.name", names)
608 self.assertIn("strfile", names)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000609 for i in infos:
Ezio Melotti35386712009-12-31 13:22:41 +0000610 self.assertEqual(i.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000611
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000612 # check getinfo
613 for nm in (TESTFN, "another.name", "strfile"):
614 info = zipfp.getinfo(nm)
Ezio Melotti35386712009-12-31 13:22:41 +0000615 self.assertEqual(info.filename, nm)
616 self.assertEqual(info.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000617
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000618 # Check that testzip doesn't raise an exception
619 zipfp.testzip()
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000620 if not isinstance(f, str):
621 f.close()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000622
Ezio Melottiafd0d112009-07-15 17:17:17 +0000623 def test_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000624 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000625 self.zip_test(f, zipfile.ZIP_STORED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000626
Ezio Melotti76430242009-07-11 18:28:48 +0000627 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +0000628 def test_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +0000629 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000630 self.zip_test(f, zipfile.ZIP_DEFLATED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000631
Ezio Melottiafd0d112009-07-15 17:17:17 +0000632 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000633 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
634 allowZip64=True) as zipfp:
635 zipfp.write(TESTFN, "/absolute")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000636
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000637 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
638 self.assertEqual(zipfp.namelist(), ["absolute"])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000639
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000640 def tearDown(self):
641 zipfile.ZIP64_LIMIT = self._limit
Ezio Melotti76430242009-07-11 18:28:48 +0000642 unlink(TESTFN)
643 unlink(TESTFN2)
644
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000645
646class PyZipFileTests(unittest.TestCase):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000647 def test_write_pyfile(self):
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000648 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000649 fn = __file__
650 if fn.endswith('.pyc') or fn.endswith('.pyo'):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000651 path_split = fn.split(os.sep)
652 if os.altsep is not None:
653 path_split.extend(fn.split(os.altsep))
654 if '__pycache__' in path_split:
655 fn = imp.source_from_cache(fn)
656 else:
657 fn = fn[:-1]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000658
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000659 zipfp.writepy(fn)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000660
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000661 bn = os.path.basename(fn)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000662 self.assertNotIn(bn, zipfp.namelist())
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000663 self.assertTrue(bn + 'o' in zipfp.namelist() or
664 bn + 'c' in zipfp.namelist())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000665
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000666 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000667 fn = __file__
Ezio Melotti35386712009-12-31 13:22:41 +0000668 if fn.endswith(('.pyc', '.pyo')):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000669 fn = fn[:-1]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000670
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000671 zipfp.writepy(fn, "testpackage")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000672
Ezio Melotti35386712009-12-31 13:22:41 +0000673 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000674 self.assertNotIn(bn, zipfp.namelist())
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000675 self.assertTrue(bn + 'o' in zipfp.namelist() or
676 bn + 'c' in zipfp.namelist())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000677
Ezio Melottiafd0d112009-07-15 17:17:17 +0000678 def test_write_python_package(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000679 import email
680 packagedir = os.path.dirname(email.__file__)
681
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000682 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000683 zipfp.writepy(packagedir)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000684
Ezio Melotti35386712009-12-31 13:22:41 +0000685 # Check for a couple of modules at different levels of the
686 # hierarchy
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000687 names = zipfp.namelist()
688 self.assertTrue('email/__init__.pyo' in names or
689 'email/__init__.pyc' in names)
690 self.assertTrue('email/mime/text.pyo' in names or
691 'email/mime/text.pyc' in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000692
Georg Brandl8334fd92010-12-04 10:26:46 +0000693 def test_write_with_optimization(self):
694 import email
695 packagedir = os.path.dirname(email.__file__)
696 # use .pyc if running test in optimization mode,
697 # use .pyo if running test in debug mode
698 optlevel = 1 if __debug__ else 0
699 ext = '.pyo' if optlevel == 1 else '.pyc'
700
701 with TemporaryFile() as t, \
702 zipfile.PyZipFile(t, "w", optimize=optlevel) as zipfp:
703 zipfp.writepy(packagedir)
704
705 names = zipfp.namelist()
706 self.assertIn('email/__init__' + ext, names)
707 self.assertIn('email/mime/text' + ext, names)
708
Ezio Melottiafd0d112009-07-15 17:17:17 +0000709 def test_write_python_directory(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000710 os.mkdir(TESTFN2)
711 try:
Ezio Melotti35386712009-12-31 13:22:41 +0000712 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
713 fp.write("print(42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000714
Ezio Melotti35386712009-12-31 13:22:41 +0000715 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
716 fp.write("print(42 * 42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000717
Ezio Melotti35386712009-12-31 13:22:41 +0000718 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
719 fp.write("bla bla bla\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000720
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000721 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
722 zipfp.writepy(TESTFN2)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000723
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000724 names = zipfp.namelist()
725 self.assertTrue('mod1.pyc' in names or 'mod1.pyo' in names)
726 self.assertTrue('mod2.pyc' in names or 'mod2.pyo' in names)
727 self.assertNotIn('mod2.txt', names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000728
729 finally:
730 shutil.rmtree(TESTFN2)
731
Ezio Melottiafd0d112009-07-15 17:17:17 +0000732 def test_write_non_pyfile(self):
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000733 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000734 with open(TESTFN, 'w') as f:
735 f.write('most definitely not a python file')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000736 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
737 os.remove(TESTFN)
738
Serhiy Storchaka45c43752013-01-29 20:10:28 +0200739 def test_write_pyfile_bad_syntax(self):
740 os.mkdir(TESTFN2)
741 try:
742 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
743 fp.write("Bad syntax in python file\n")
744
745 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
746 # syntax errors are printed to stdout
747 with captured_stdout() as s:
748 zipfp.writepy(os.path.join(TESTFN2, "mod1.py"))
749
750 self.assertIn("SyntaxError", s.getvalue())
751
752 # as it will not have compiled the python file, it will
753 # include the .py file not .pyc or .pyo
754 names = zipfp.namelist()
755 self.assertIn('mod1.py', names)
756 self.assertNotIn('mod1.pyc', names)
757 self.assertNotIn('mod1.pyo', names)
758
759 finally:
760 shutil.rmtree(TESTFN2)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000761
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000762class OtherTests(unittest.TestCase):
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000763 zips_with_bad_crc = {
764 zipfile.ZIP_STORED: (
765 b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
766 b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
767 b'ilehello,AworldP'
768 b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
769 b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
770 b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
771 b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
772 b'\0\0/\0\0\0\0\0'),
773 zipfile.ZIP_DEFLATED: (
774 b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
775 b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
776 b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
777 b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
778 b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
779 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
780 b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
781 b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00'),
782 }
783
Ezio Melottiafd0d112009-07-15 17:17:17 +0000784 def test_unicode_filenames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000785 with zipfile.ZipFile(TESTFN, "w") as zf:
786 zf.writestr("foo.txt", "Test for unicode filename")
787 zf.writestr("\xf6.txt", "Test for unicode filename")
Ezio Melottie9615932010-01-24 19:26:24 +0000788 self.assertIsInstance(zf.infolist()[0].filename, str)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000789
790 with zipfile.ZipFile(TESTFN, "r") as zf:
791 self.assertEqual(zf.filelist[0].filename, "foo.txt")
792 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
Martin v. Löwis8570f6a2008-05-05 17:44:38 +0000793
Ezio Melottiafd0d112009-07-15 17:17:17 +0000794 def test_create_non_existent_file_for_append(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +0000795 if os.path.exists(TESTFN):
796 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000797
Thomas Wouterscf297e42007-02-23 15:07:44 +0000798 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000799 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +0000800
Thomas Wouterscf297e42007-02-23 15:07:44 +0000801 try:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000802 with zipfile.ZipFile(TESTFN, 'a') as zf:
803 zf.writestr(filename, content)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000804 except IOError:
805 self.fail('Could not append data to a non-existent zip file.')
806
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000807 self.assertTrue(os.path.exists(TESTFN))
Thomas Wouterscf297e42007-02-23 15:07:44 +0000808
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000809 with zipfile.ZipFile(TESTFN, 'r') as zf:
810 self.assertEqual(zf.read(filename), content)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000811
Ezio Melottiafd0d112009-07-15 17:17:17 +0000812 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000813 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti35386712009-12-31 13:22:41 +0000814 # it opens if there's an error in the file. If it doesn't, the
815 # traceback holds a reference to the ZipFile object and, indirectly,
816 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000817 # On Windows, this causes the os.unlink() call to fail because the
818 # underlying file is still open. This is SF bug #412214.
819 #
Ezio Melotti35386712009-12-31 13:22:41 +0000820 with open(TESTFN, "w") as fp:
821 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000822 try:
823 zf = zipfile.ZipFile(TESTFN)
Georg Brandl4d540882010-10-28 06:42:33 +0000824 except zipfile.BadZipFile:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000825 pass
826
Ezio Melottiafd0d112009-07-15 17:17:17 +0000827 def test_is_zip_erroneous_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000828 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000829 # - passing a filename
830 with open(TESTFN, "w") as fp:
831 fp.write("this is not a legal zip file\n")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000832 chk = zipfile.is_zipfile(TESTFN)
Ezio Melotti35386712009-12-31 13:22:41 +0000833 self.assertFalse(chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000834 # - passing a file object
835 with open(TESTFN, "rb") as fp:
836 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000837 self.assertTrue(not chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000838 # - passing a file-like object
839 fp = io.BytesIO()
840 fp.write(b"this is not a legal zip file\n")
841 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000842 self.assertTrue(not chk)
Ezio Melotti35386712009-12-31 13:22:41 +0000843 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000844 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000845 self.assertTrue(not chk)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000846
Serhiy Storchakad2b15272013-01-31 15:27:07 +0200847 def test_damaged_zipfile(self):
848 """Check that zipfiles with missing bytes at the end raise BadZipFile."""
849 # - Create a valid zip file
850 fp = io.BytesIO()
851 with zipfile.ZipFile(fp, mode="w") as zipf:
852 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
853 zipfiledata = fp.getvalue()
854
855 # - Now create copies of it missing the last N bytes and make sure
856 # a BadZipFile exception is raised when we try to open it
857 for N in range(len(zipfiledata)):
858 fp = io.BytesIO(zipfiledata[:N])
859 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, fp)
860
Ezio Melottiafd0d112009-07-15 17:17:17 +0000861 def test_is_zip_valid_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000862 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000863 # - passing a filename
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000864 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
865 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
866
Guido van Rossumd8faa362007-04-27 19:54:29 +0000867 chk = zipfile.is_zipfile(TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000868 self.assertTrue(chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000869 # - passing a file object
870 with open(TESTFN, "rb") as fp:
871 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000872 self.assertTrue(chk)
Ezio Melotti35386712009-12-31 13:22:41 +0000873 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000874 zip_contents = fp.read()
875 # - passing a file-like object
876 fp = io.BytesIO()
877 fp.write(zip_contents)
878 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000879 self.assertTrue(chk)
Ezio Melotti35386712009-12-31 13:22:41 +0000880 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000881 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000882 self.assertTrue(chk)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000883
Ezio Melottiafd0d112009-07-15 17:17:17 +0000884 def test_non_existent_file_raises_IOError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000885 # make sure we don't raise an AttributeError when a partially-constructed
886 # ZipFile instance is finalized; this tests for regression on SF tracker
887 # bug #403871.
888
889 # The bug we're testing for caused an AttributeError to be raised
890 # when a ZipFile instance was created for a file that did not
891 # exist; the .fp member was not initialized but was needed by the
892 # __del__() method. Since the AttributeError is in the __del__(),
893 # it is ignored, but the user should be sufficiently annoyed by
894 # the message on the output that regression will be noticed
895 # quickly.
896 self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
897
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +0000898 def test_empty_file_raises_BadZipFile(self):
899 f = open(TESTFN, 'w')
900 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +0000901 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +0000902
Ezio Melotti35386712009-12-31 13:22:41 +0000903 with open(TESTFN, 'w') as fp:
904 fp.write("short file")
Georg Brandl4d540882010-10-28 06:42:33 +0000905 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +0000906
Ezio Melottiafd0d112009-07-15 17:17:17 +0000907 def test_closed_zip_raises_RuntimeError(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000908 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000909 data = io.BytesIO()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000910 with zipfile.ZipFile(data, mode="w") as zipf:
911 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000912
Andrew Svetlov737fb892012-12-18 21:14:22 +0200913 # This is correct; calling .read on a closed ZipFile should raise
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000914 # a RuntimeError, and so should calling .testzip. An earlier
915 # version of .testzip would swallow this exception (and any other)
916 # and report that the first file in the archive was corrupt.
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000917 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
918 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000919 self.assertRaises(RuntimeError, zipf.testzip)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000920 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Brian Curtin8fb9b862010-11-18 02:15:28 +0000921 with open(TESTFN, 'w') as f:
922 f.write('zipfile test data')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000923 self.assertRaises(RuntimeError, zipf.write, TESTFN)
924
Ezio Melottiafd0d112009-07-15 17:17:17 +0000925 def test_bad_constructor_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000926 """Check that bad modes passed to ZipFile constructor are caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000927 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
928
Ezio Melottiafd0d112009-07-15 17:17:17 +0000929 def test_bad_open_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000930 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000931 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
932 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
933
934 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000935 # read the data to make sure the file is there
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000936 zipf.read("foo.txt")
937 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000938
Ezio Melottiafd0d112009-07-15 17:17:17 +0000939 def test_read0(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000940 """Check that calling read(0) on a ZipExtFile object returns an empty
941 string and doesn't advance file pointer."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000942 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
943 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
944 # read the data to make sure the file is there
Brian Curtin8fb9b862010-11-18 02:15:28 +0000945 with zipf.open("foo.txt") as f:
946 for i in range(FIXEDTEST_SIZE):
947 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000948
Brian Curtin8fb9b862010-11-18 02:15:28 +0000949 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000950
Ezio Melottiafd0d112009-07-15 17:17:17 +0000951 def test_open_non_existent_item(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000952 """Check that attempting to call open() for an item that doesn't
953 exist in the archive raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000954 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
955 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000956
Ezio Melottiafd0d112009-07-15 17:17:17 +0000957 def test_bad_compression_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000958 """Check that bad compression methods passed to ZipFile.open are
959 caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000960 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
961
Ezio Melotti6a5fc4c2012-11-18 13:20:36 +0200962 def test_unsupported_compression(self):
963 # data is declared as shrunk, but actually deflated
964 data = (b'PK\x03\x04.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00'
965 b'\x00\x02\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00x\x03\x00PK\x01'
966 b'\x02.\x03.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00\x00\x02\x00\x00'
967 b'\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
968 b'\x80\x01\x00\x00\x00\x00xPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00'
969 b'/\x00\x00\x00!\x00\x00\x00\x00\x00')
970 with zipfile.ZipFile(io.BytesIO(data), 'r') as zipf:
971 self.assertRaises(NotImplementedError, zipf.open, 'x')
972
Ezio Melottiafd0d112009-07-15 17:17:17 +0000973 def test_null_byte_in_filename(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000974 """Check that a filename containing a null byte is properly
975 terminated."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000976 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
977 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
978 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000979
Ezio Melottiafd0d112009-07-15 17:17:17 +0000980 def test_struct_sizes(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000981 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000982 self.assertEqual(zipfile.sizeEndCentDir, 22)
983 self.assertEqual(zipfile.sizeCentralDir, 46)
984 self.assertEqual(zipfile.sizeEndCentDir64, 56)
985 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
986
Ezio Melottiafd0d112009-07-15 17:17:17 +0000987 def test_comments(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000988 """Check that comments on the archive are handled properly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000989
990 # check default comment is empty
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000991 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
992 self.assertEqual(zipf.comment, b'')
993 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
994
995 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
996 self.assertEqual(zipfr.comment, b'')
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000997
998 # check a simple short comment
999 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001000 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1001 zipf.comment = comment
1002 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1003 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1004 self.assertEqual(zipf.comment, comment)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001005
1006 # check a comment of max length
1007 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
1008 comment2 = comment2.encode("ascii")
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001009 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1010 zipf.comment = comment2
1011 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1012
1013 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1014 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001015
1016 # check a comment that is too long is truncated
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001017 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1018 zipf.comment = comment2 + b'oops'
1019 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1020 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
1021 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +00001022
Antoine Pitrouc3991852012-06-30 17:31:37 +02001023 # check that comments are correctly modified in append mode
1024 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1025 zipf.comment = b"original comment"
1026 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1027 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1028 zipf.comment = b"an updated comment"
1029 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1030 self.assertEqual(zipf.comment, b"an updated comment")
1031
1032 # check that comments are correctly shortened in append mode
1033 with zipfile.ZipFile(TESTFN,mode="w") as zipf:
1034 zipf.comment = b"original comment that's longer"
1035 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1036 with zipfile.ZipFile(TESTFN,mode="a") as zipf:
1037 zipf.comment = b"shorter comment"
1038 with zipfile.ZipFile(TESTFN,mode="r") as zipf:
1039 self.assertEqual(zipf.comment, b"shorter comment")
1040
R David Murray51804e92012-04-12 18:44:42 -04001041 def test_unicode_comment(self):
1042 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1043 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1044 with self.assertRaises(TypeError):
1045 zipf.comment = "this is an error"
1046
1047 def test_change_comment_in_empty_archive(self):
1048 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1049 self.assertFalse(zipf.filelist)
1050 zipf.comment = b"this is a comment"
1051 with zipfile.ZipFile(TESTFN, "r") as zipf:
1052 self.assertEqual(zipf.comment, b"this is a comment")
1053
1054 def test_change_comment_in_nonempty_archive(self):
1055 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1056 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1057 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1058 self.assertTrue(zipf.filelist)
1059 zipf.comment = b"this is a comment"
1060 with zipfile.ZipFile(TESTFN, "r") as zipf:
1061 self.assertEqual(zipf.comment, b"this is a comment")
1062
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001063 def check_testzip_with_bad_crc(self, compression):
1064 """Tests that files with bad CRCs return their name from testzip."""
1065 zipdata = self.zips_with_bad_crc[compression]
1066
1067 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1068 # testzip returns the name of the first corrupt file, or None
1069 self.assertEqual('afile', zipf.testzip())
1070
1071 def test_testzip_with_bad_crc_stored(self):
1072 self.check_testzip_with_bad_crc(zipfile.ZIP_STORED)
1073
1074 @skipUnless(zlib, "requires zlib")
1075 def test_testzip_with_bad_crc_deflated(self):
1076 self.check_testzip_with_bad_crc(zipfile.ZIP_DEFLATED)
1077
1078 def check_read_with_bad_crc(self, compression):
Georg Brandl4d540882010-10-28 06:42:33 +00001079 """Tests that files with bad CRCs raise a BadZipFile exception when read."""
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001080 zipdata = self.zips_with_bad_crc[compression]
1081
1082 # Using ZipFile.read()
1083 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
Georg Brandl4d540882010-10-28 06:42:33 +00001084 self.assertRaises(zipfile.BadZipFile, zipf.read, 'afile')
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001085
1086 # Using ZipExtFile.read()
1087 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1088 with zipf.open('afile', 'r') as corrupt_file:
Georg Brandl4d540882010-10-28 06:42:33 +00001089 self.assertRaises(zipfile.BadZipFile, corrupt_file.read)
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001090
1091 # Same with small reads (in order to exercise the buffering logic)
1092 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1093 with zipf.open('afile', 'r') as corrupt_file:
1094 corrupt_file.MIN_READ_SIZE = 2
Georg Brandl4d540882010-10-28 06:42:33 +00001095 with self.assertRaises(zipfile.BadZipFile):
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001096 while corrupt_file.read(2):
1097 pass
1098
1099 def test_read_with_bad_crc_stored(self):
1100 self.check_read_with_bad_crc(zipfile.ZIP_STORED)
1101
1102 @skipUnless(zlib, "requires zlib")
1103 def test_read_with_bad_crc_deflated(self):
1104 self.check_read_with_bad_crc(zipfile.ZIP_DEFLATED)
1105
Antoine Pitrou6464d5f2010-09-12 14:51:20 +00001106 def check_read_return_size(self, compression):
1107 # Issue #9837: ZipExtFile.read() shouldn't return more bytes
1108 # than requested.
1109 for test_size in (1, 4095, 4096, 4097, 16384):
1110 file_size = test_size + 1
1111 junk = b''.join(struct.pack('B', randint(0, 255))
1112 for x in range(file_size))
1113 with zipfile.ZipFile(io.BytesIO(), "w", compression) as zipf:
1114 zipf.writestr('foo', junk)
1115 with zipf.open('foo', 'r') as fp:
1116 buf = fp.read(test_size)
1117 self.assertEqual(len(buf), test_size)
1118
1119 def test_read_return_size_stored(self):
1120 self.check_read_return_size(zipfile.ZIP_STORED)
1121
1122 @skipUnless(zlib, "requires zlib")
1123 def test_read_return_size_deflated(self):
1124 self.check_read_return_size(zipfile.ZIP_DEFLATED)
1125
Georg Brandl268e4d42010-10-14 06:59:45 +00001126 def test_empty_zipfile(self):
1127 # Check that creating a file in 'w' or 'a' mode and closing without
1128 # adding any files to the archives creates a valid empty ZIP file
1129 zipf = zipfile.ZipFile(TESTFN, mode="w")
1130 zipf.close()
1131 try:
1132 zipf = zipfile.ZipFile(TESTFN, mode="r")
1133 except zipfile.BadZipFile:
1134 self.fail("Unable to create empty ZIP file in 'w' mode")
1135
1136 zipf = zipfile.ZipFile(TESTFN, mode="a")
1137 zipf.close()
1138 try:
1139 zipf = zipfile.ZipFile(TESTFN, mode="r")
1140 except:
1141 self.fail("Unable to create empty ZIP file in 'a' mode")
1142
1143 def test_open_empty_file(self):
1144 # Issue 1710703: Check that opening a file with less than 22 bytes
Georg Brandl4d540882010-10-28 06:42:33 +00001145 # raises a BadZipFile exception (rather than the previously unhelpful
Georg Brandl268e4d42010-10-14 06:59:45 +00001146 # IOError)
1147 f = open(TESTFN, 'w')
1148 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001149 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN, 'r')
Georg Brandl268e4d42010-10-14 06:59:45 +00001150
Senthil Kumaran29fa9d42011-10-20 01:46:00 +08001151 def test_create_zipinfo_before_1980(self):
1152 self.assertRaises(ValueError,
1153 zipfile.ZipInfo, 'seventies', (1979, 1, 1, 0, 0, 0))
1154
Guido van Rossumd8faa362007-04-27 19:54:29 +00001155 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001156 unlink(TESTFN)
1157 unlink(TESTFN2)
1158
Thomas Wouterscf297e42007-02-23 15:07:44 +00001159
1160class DecryptionTests(unittest.TestCase):
Ezio Melotti35386712009-12-31 13:22:41 +00001161 """Check that ZIP decryption works. Since the library does not
1162 support encryption at the moment, we use a pre-generated encrypted
1163 ZIP file."""
Thomas Wouterscf297e42007-02-23 15:07:44 +00001164
1165 data = (
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001166 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
1167 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
1168 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
1169 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
1170 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
1171 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
1172 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +00001173 data2 = (
1174 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
1175 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
1176 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
1177 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
1178 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
1179 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
1180 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
1181 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +00001182
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001183 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +00001184 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +00001185
1186 def setUp(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001187 with open(TESTFN, "wb") as fp:
1188 fp.write(self.data)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001189 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti35386712009-12-31 13:22:41 +00001190 with open(TESTFN2, "wb") as fp:
1191 fp.write(self.data2)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001192 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001193
1194 def tearDown(self):
1195 self.zip.close()
1196 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001197 self.zip2.close()
1198 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001199
Ezio Melottiafd0d112009-07-15 17:17:17 +00001200 def test_no_password(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001201 # Reading the encrypted file without password
1202 # must generate a RunTime exception
1203 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001204 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001205
Ezio Melottiafd0d112009-07-15 17:17:17 +00001206 def test_bad_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001207 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001208 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001209 self.zip2.setpassword(b"perl")
1210 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001211
Ezio Melotti78ea2022009-09-12 18:41:20 +00001212 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001213 def test_good_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001214 self.zip.setpassword(b"python")
Ezio Melotti35386712009-12-31 13:22:41 +00001215 self.assertEqual(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001216 self.zip2.setpassword(b"12345")
Ezio Melotti35386712009-12-31 13:22:41 +00001217 self.assertEqual(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001218
R. David Murray8d855d82010-12-21 21:53:37 +00001219 def test_unicode_password(self):
1220 self.assertRaises(TypeError, self.zip.setpassword, "unicode")
1221 self.assertRaises(TypeError, self.zip.read, "test.txt", "python")
1222 self.assertRaises(TypeError, self.zip.open, "test.txt", pwd="python")
1223 self.assertRaises(TypeError, self.zip.extract, "test.txt", pwd="python")
1224
Guido van Rossumd8faa362007-04-27 19:54:29 +00001225
1226class TestsWithRandomBinaryFiles(unittest.TestCase):
1227 def setUp(self):
1228 datacount = randint(16, 64)*1024 + randint(1, 1024)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001229 self.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
1230 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001231
1232 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +00001233 with open(TESTFN, "wb") as fp:
1234 fp.write(self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001235
1236 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001237 unlink(TESTFN)
1238 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001239
Ezio Melottiafd0d112009-07-15 17:17:17 +00001240 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001241 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001242 with zipfile.ZipFile(f, "w", compression) as zipfp:
1243 zipfp.write(TESTFN, "another.name")
1244 zipfp.write(TESTFN, TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001245
Ezio Melottiafd0d112009-07-15 17:17:17 +00001246 def zip_test(self, f, compression):
1247 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001248
1249 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001250 with zipfile.ZipFile(f, "r", compression) as zipfp:
1251 testdata = zipfp.read(TESTFN)
1252 self.assertEqual(len(testdata), len(self.data))
1253 self.assertEqual(testdata, self.data)
1254 self.assertEqual(zipfp.read("another.name"), self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001255 if not isinstance(f, str):
1256 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001257
Ezio Melottiafd0d112009-07-15 17:17:17 +00001258 def test_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001259 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001260 self.zip_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001261
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001262 @skipUnless(zlib, "requires zlib")
1263 def test_deflated(self):
1264 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1265 self.zip_test(f, zipfile.ZIP_DEFLATED)
1266
Ezio Melottiafd0d112009-07-15 17:17:17 +00001267 def zip_open_test(self, f, compression):
1268 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001269
1270 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001271 with zipfile.ZipFile(f, "r", compression) as zipfp:
1272 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001273 with zipfp.open(TESTFN) as zipopen1:
1274 while True:
1275 read_data = zipopen1.read(256)
1276 if not read_data:
1277 break
1278 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001279
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001280 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001281 with zipfp.open("another.name") as zipopen2:
1282 while True:
1283 read_data = zipopen2.read(256)
1284 if not read_data:
1285 break
1286 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001287
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001288 testdata1 = b''.join(zipdata1)
1289 self.assertEqual(len(testdata1), len(self.data))
1290 self.assertEqual(testdata1, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001291
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001292 testdata2 = b''.join(zipdata2)
Ezio Melotti35386712009-12-31 13:22:41 +00001293 self.assertEqual(len(testdata2), len(self.data))
1294 self.assertEqual(testdata2, self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001295 if not isinstance(f, str):
1296 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001297
Ezio Melottiafd0d112009-07-15 17:17:17 +00001298 def test_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001299 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001300 self.zip_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001301
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001302 @skipUnless(zlib, "requires zlib")
1303 def test_open_deflated(self):
1304 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1305 self.zip_open_test(f, zipfile.ZIP_DEFLATED)
1306
Ezio Melottiafd0d112009-07-15 17:17:17 +00001307 def zip_random_open_test(self, f, compression):
1308 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001309
1310 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001311 with zipfile.ZipFile(f, "r", compression) as zipfp:
1312 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001313 with zipfp.open(TESTFN) as zipopen1:
1314 while True:
1315 read_data = zipopen1.read(randint(1, 1024))
1316 if not read_data:
1317 break
1318 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001319
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001320 testdata = b''.join(zipdata1)
1321 self.assertEqual(len(testdata), len(self.data))
1322 self.assertEqual(testdata, self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001323 if not isinstance(f, str):
1324 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001325
Ezio Melottiafd0d112009-07-15 17:17:17 +00001326 def test_random_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001327 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001328 self.zip_random_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001329
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001330 @skipUnless(zlib, "requires zlib")
1331 def test_random_open_deflated(self):
1332 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1333 self.zip_random_open_test(f, zipfile.ZIP_DEFLATED)
1334
Ezio Melotti76430242009-07-11 18:28:48 +00001335
Ezio Melotti78ea2022009-09-12 18:41:20 +00001336@skipUnless(zlib, "requires zlib")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001337class TestsWithMultipleOpens(unittest.TestCase):
1338 def setUp(self):
1339 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001340 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
1341 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
1342 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001343
Ezio Melottiafd0d112009-07-15 17:17:17 +00001344 def test_same_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001345 # Verify that (when the ZipFile is in control of creating file objects)
1346 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001347 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001348 with zipf.open('ones') as zopen1, zipf.open('ones') as zopen2:
1349 data1 = zopen1.read(500)
1350 data2 = zopen2.read(500)
1351 data1 += zopen1.read(500)
1352 data2 += zopen2.read(500)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001353 self.assertEqual(data1, data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001354
Ezio Melottiafd0d112009-07-15 17:17:17 +00001355 def test_different_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001356 # Verify that (when the ZipFile is in control of creating file objects)
1357 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001358 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001359 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1360 data1 = zopen1.read(500)
1361 data2 = zopen2.read(500)
1362 data1 += zopen1.read(500)
1363 data2 += zopen2.read(500)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001364 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
1365 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001366
Ezio Melottiafd0d112009-07-15 17:17:17 +00001367 def test_interleaved(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001368 # Verify that (when the ZipFile is in control of creating file objects)
1369 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001370 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001371 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1372 data1 = zopen1.read(500)
1373 data2 = zopen2.read(500)
1374 data1 += zopen1.read(500)
1375 data2 += zopen2.read(500)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001376 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
1377 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001378
1379 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001380 unlink(TESTFN2)
1381
Guido van Rossumd8faa362007-04-27 19:54:29 +00001382
Martin v. Löwis59e47792009-01-24 14:10:07 +00001383class TestWithDirectory(unittest.TestCase):
1384 def setUp(self):
1385 os.mkdir(TESTFN2)
1386
Ezio Melottiafd0d112009-07-15 17:17:17 +00001387 def test_extract_dir(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001388 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
1389 zipf.extractall(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001390 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1391 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1392 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1393
Ezio Melottiafd0d112009-07-15 17:17:17 +00001394 def test_bug_6050(self):
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001395 # Extraction should succeed if directories already exist
1396 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottiafd0d112009-07-15 17:17:17 +00001397 self.test_extract_dir()
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001398
Ezio Melottiafd0d112009-07-15 17:17:17 +00001399 def test_store_dir(self):
Martin v. Löwis59e47792009-01-24 14:10:07 +00001400 os.mkdir(os.path.join(TESTFN2, "x"))
1401 zipf = zipfile.ZipFile(TESTFN, "w")
1402 zipf.write(os.path.join(TESTFN2, "x"), "x")
1403 self.assertTrue(zipf.filelist[0].filename.endswith("x/"))
1404
1405 def tearDown(self):
1406 shutil.rmtree(TESTFN2)
1407 if os.path.exists(TESTFN):
Ezio Melotti76430242009-07-11 18:28:48 +00001408 unlink(TESTFN)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001409
Guido van Rossumd8faa362007-04-27 19:54:29 +00001410
1411class UniversalNewlineTests(unittest.TestCase):
1412 def setUp(self):
Guido van Rossum9c627722007-08-27 18:31:48 +00001413 self.line_gen = [bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001414 for i in range(FIXEDTEST_SIZE)]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001415 self.seps = ('\r', '\r\n', '\n')
1416 self.arcdata, self.arcfiles = {}, {}
1417 for n, s in enumerate(self.seps):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001418 b = s.encode("ascii")
1419 self.arcdata[s] = b.join(self.line_gen) + b
Guido van Rossumd8faa362007-04-27 19:54:29 +00001420 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001421 f = open(self.arcfiles[s], "wb")
1422 try:
1423 f.write(self.arcdata[s])
1424 finally:
1425 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001426
Ezio Melottiafd0d112009-07-15 17:17:17 +00001427 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001428 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001429 with zipfile.ZipFile(f, "w", compression) as zipfp:
1430 for fn in self.arcfiles.values():
1431 zipfp.write(fn, fn)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001432
Ezio Melottiafd0d112009-07-15 17:17:17 +00001433 def read_test(self, f, compression):
1434 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001435
1436 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001437 with zipfile.ZipFile(f, "r") as zipfp:
1438 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001439 with zipfp.open(fn, "rU") as fp:
1440 zipdata = fp.read()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001441 self.assertEqual(self.arcdata[sep], zipdata)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001442 if not isinstance(f, str):
1443 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001444
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001445 def readline_read_test(self, f, compression):
1446 self.make_test_archive(f, compression)
1447
1448 # Read the ZIP archive
Brian Curtin8fb9b862010-11-18 02:15:28 +00001449 with zipfile.ZipFile(f, "r") as zipfp:
1450 for sep, fn in self.arcfiles.items():
1451 with zipfp.open(fn, "rU") as zipopen:
1452 data = b''
1453 while True:
1454 read = zipopen.readline()
1455 if not read:
1456 break
1457 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001458
Brian Curtin8fb9b862010-11-18 02:15:28 +00001459 read = zipopen.read(5)
1460 if not read:
1461 break
1462 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001463
1464 self.assertEqual(data, self.arcdata['\n'])
1465
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001466 if not isinstance(f, str):
1467 f.close()
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001468
Ezio Melottiafd0d112009-07-15 17:17:17 +00001469 def readline_test(self, f, compression):
1470 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001471
1472 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001473 with zipfile.ZipFile(f, "r") as zipfp:
1474 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001475 with zipfp.open(fn, "rU") as zipopen:
1476 for line in self.line_gen:
1477 linedata = zipopen.readline()
1478 self.assertEqual(linedata, line + b'\n')
1479 if not isinstance(f, str):
1480 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001481
Ezio Melottiafd0d112009-07-15 17:17:17 +00001482 def readlines_test(self, f, compression):
1483 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001484
1485 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001486 with zipfile.ZipFile(f, "r") as zipfp:
1487 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001488 with zipfp.open(fn, "rU") as fp:
1489 ziplines = fp.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001490 for line, zipline in zip(self.line_gen, ziplines):
1491 self.assertEqual(zipline, line + b'\n')
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001492 if not isinstance(f, str):
1493 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001494
Ezio Melottiafd0d112009-07-15 17:17:17 +00001495 def iterlines_test(self, f, compression):
1496 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001497
1498 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001499 with zipfile.ZipFile(f, "r") as zipfp:
1500 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001501 with zipfp.open(fn, "rU") as fp:
1502 for line, zipline in zip(self.line_gen, fp):
1503 self.assertEqual(zipline, line + b'\n')
1504 if not isinstance(f, str):
1505 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001506
Ezio Melottiafd0d112009-07-15 17:17:17 +00001507 def test_read_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001508 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001509 self.read_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001510
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001511 def test_readline_read_stored(self):
1512 # Issue #7610: calls to readline() interleaved with calls to read().
1513 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1514 self.readline_read_test(f, zipfile.ZIP_STORED)
1515
Ezio Melottiafd0d112009-07-15 17:17:17 +00001516 def test_readline_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001517 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001518 self.readline_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001519
Ezio Melottiafd0d112009-07-15 17:17:17 +00001520 def test_readlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001521 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001522 self.readlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001523
Ezio Melottiafd0d112009-07-15 17:17:17 +00001524 def test_iterlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001525 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001526 self.iterlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001527
Ezio Melotti76430242009-07-11 18:28:48 +00001528 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001529 def test_read_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001530 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001531 self.read_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001532
Ezio Melotti76430242009-07-11 18:28:48 +00001533 @skipUnless(zlib, "requires zlib")
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001534 def test_readline_read_deflated(self):
1535 # Issue #7610: calls to readline() interleaved with calls to read().
1536 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1537 self.readline_read_test(f, zipfile.ZIP_DEFLATED)
1538
1539 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001540 def test_readline_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001541 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001542 self.readline_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001543
Ezio Melotti76430242009-07-11 18:28:48 +00001544 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001545 def test_readlines_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001546 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001547 self.readlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001548
Ezio Melotti76430242009-07-11 18:28:48 +00001549 @skipUnless(zlib, "requires zlib")
Ezio Melottiafd0d112009-07-15 17:17:17 +00001550 def test_iterlines_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001551 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001552 self.iterlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001553
1554 def tearDown(self):
1555 for sep, fn in self.arcfiles.items():
1556 os.remove(fn)
Ezio Melotti76430242009-07-11 18:28:48 +00001557 unlink(TESTFN)
1558 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001559
1560
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001561def test_main():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001562 run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
1563 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
Ezio Melotti76430242009-07-11 18:28:48 +00001564 TestWithDirectory, UniversalNewlineTests,
1565 TestsWithRandomBinaryFiles)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001566
1567if __name__ == "__main__":
1568 test_main()