blob: 0b3a69443a53ff54165e0f5f0d4e355a29b884c2 [file] [log] [blame]
Ezio Melotti74c96ec2009-07-08 22:24:06 +00001import io
2import os
Georg Brandl5ba11de2011-01-01 10:09:32 +00003import sys
Barry Warsaw28a691b2010-04-17 00:19:56 +00004import imp
Ezio Melotti35386712009-12-31 13:22:41 +00005import time
Ezio Melotti74c96ec2009-07-08 22:24:06 +00006import shutil
7import struct
8import zipfile
9import unittest
10
Tim Petersa45cacf2004-08-20 03:47:14 +000011
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000012from tempfile import TemporaryFile
Guido van Rossumd8faa362007-04-27 19:54:29 +000013from random import randint, random
Ezio Melotti74c96ec2009-07-08 22:24:06 +000014from unittest import skipUnless
Tim Petersa19a1682001-03-29 04:36:09 +000015
Ezio Melotti975077a2011-05-19 22:03:22 +030016from test.support import TESTFN, run_unittest, findfile, unlink, requires_zlib
Guido van Rossum368f04a2000-04-10 13:23:04 +000017
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000018TESTFN2 = TESTFN + "2"
Martin v. Löwis59e47792009-01-24 14:10:07 +000019TESTFNDIR = TESTFN + "d"
Guido van Rossumb5a755e2007-07-18 18:15:48 +000020FIXEDTEST_SIZE = 1000
Georg Brandl5ba11de2011-01-01 10:09:32 +000021DATAFILES_DIR = 'zipfile_datafiles'
Guido van Rossum368f04a2000-04-10 13:23:04 +000022
Christian Heimes790c8232008-01-07 21:14:23 +000023SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'),
24 ('ziptest2dir/_ziptest2', 'qawsedrftg'),
25 ('/ziptest2dir/ziptest3dir/_ziptest3', 'azsxdcfvgb'),
26 ('ziptest2dir/ziptest3dir/ziptest4dir/_ziptest3', '6y7u8i9o0p')]
27
Ezio Melotti76430242009-07-11 18:28:48 +000028
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000029class TestsWithSourceFile(unittest.TestCase):
30 def setUp(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +000031 self.line_gen = (bytes("Zipfile test line %d. random float: %f" %
Guido van Rossum9c627722007-08-27 18:31:48 +000032 (i, random()), "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +000033 for i in range(FIXEDTEST_SIZE))
34 self.data = b'\n'.join(self.line_gen) + b'\n'
Fred Drake6e7e4852001-02-28 05:34:16 +000035
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000036 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +000037 with open(TESTFN, "wb") as fp:
38 fp.write(self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000039
Ezio Melottiafd0d112009-07-15 17:17:17 +000040 def make_test_archive(self, f, compression):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000041 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000042 with zipfile.ZipFile(f, "w", compression) as zipfp:
43 zipfp.write(TESTFN, "another.name")
44 zipfp.write(TESTFN, TESTFN)
45 zipfp.writestr("strfile", self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000046
Ezio Melottiafd0d112009-07-15 17:17:17 +000047 def zip_test(self, f, compression):
48 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +000049
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000050 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000051 with zipfile.ZipFile(f, "r", compression) as zipfp:
52 self.assertEqual(zipfp.read(TESTFN), self.data)
53 self.assertEqual(zipfp.read("another.name"), self.data)
54 self.assertEqual(zipfp.read("strfile"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000055
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000056 # Print the ZIP directory
57 fp = io.StringIO()
58 zipfp.printdir(file=fp)
59 directory = fp.getvalue()
60 lines = directory.splitlines()
Ezio Melotti35386712009-12-31 13:22:41 +000061 self.assertEqual(len(lines), 4) # Number of files + header
Thomas Wouters0e3f5912006-08-11 14:57:12 +000062
Benjamin Peterson577473f2010-01-19 00:09:57 +000063 self.assertIn('File Name', lines[0])
64 self.assertIn('Modified', lines[0])
65 self.assertIn('Size', lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +000066
Ezio Melotti35386712009-12-31 13:22:41 +000067 fn, date, time_, size = lines[1].split()
68 self.assertEqual(fn, 'another.name')
69 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
70 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
71 self.assertEqual(size, str(len(self.data)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000072
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000073 # Check the namelist
74 names = zipfp.namelist()
Ezio Melotti35386712009-12-31 13:22:41 +000075 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +000076 self.assertIn(TESTFN, names)
77 self.assertIn("another.name", names)
78 self.assertIn("strfile", names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000079
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000080 # Check infolist
81 infos = zipfp.infolist()
Ezio Melotti35386712009-12-31 13:22:41 +000082 names = [i.filename for i in infos]
83 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +000084 self.assertIn(TESTFN, names)
85 self.assertIn("another.name", names)
86 self.assertIn("strfile", names)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000087 for i in infos:
Ezio Melotti35386712009-12-31 13:22:41 +000088 self.assertEqual(i.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000089
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000090 # check getinfo
91 for nm in (TESTFN, "another.name", "strfile"):
92 info = zipfp.getinfo(nm)
Ezio Melotti35386712009-12-31 13:22:41 +000093 self.assertEqual(info.filename, nm)
94 self.assertEqual(info.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +000095
Ezio Melottifaa6b7f2009-12-30 12:34:59 +000096 # Check that testzip doesn't raise an exception
97 zipfp.testzip()
Benjamin Petersond285bdb2010-10-31 17:57:22 +000098 if not isinstance(f, str):
99 f.close()
Tim Peters7d3bad62001-04-04 18:56:49 +0000100
Ezio Melottiafd0d112009-07-15 17:17:17 +0000101 def test_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000102 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000103 self.zip_test(f, zipfile.ZIP_STORED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000104
Ezio Melottiafd0d112009-07-15 17:17:17 +0000105 def zip_open_test(self, f, compression):
106 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000107
108 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000109 with zipfile.ZipFile(f, "r", compression) as zipfp:
110 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000111 with zipfp.open(TESTFN) as zipopen1:
112 while True:
113 read_data = zipopen1.read(256)
114 if not read_data:
115 break
116 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000117
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000118 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000119 with zipfp.open("another.name") as zipopen2:
120 while True:
121 read_data = zipopen2.read(256)
122 if not read_data:
123 break
124 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000125
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000126 self.assertEqual(b''.join(zipdata1), self.data)
127 self.assertEqual(b''.join(zipdata2), self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000128 if not isinstance(f, str):
129 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000130
Ezio Melottiafd0d112009-07-15 17:17:17 +0000131 def test_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000132 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000133 self.zip_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000134
Ezio Melottiafd0d112009-07-15 17:17:17 +0000135 def test_open_via_zip_info(self):
Georg Brandlb533e262008-05-25 18:19:30 +0000136 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000137 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
138 zipfp.writestr("name", "foo")
139 zipfp.writestr("name", "bar")
Georg Brandlb533e262008-05-25 18:19:30 +0000140
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000141 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
142 infos = zipfp.infolist()
143 data = b""
144 for info in infos:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000145 with zipfp.open(info) as zipopen:
146 data += zipopen.read()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000147 self.assertTrue(data == b"foobar" or data == b"barfoo")
148 data = b""
149 for info in infos:
150 data += zipfp.read(info)
151 self.assertTrue(data == b"foobar" or data == b"barfoo")
Georg Brandlb533e262008-05-25 18:19:30 +0000152
Ezio Melottiafd0d112009-07-15 17:17:17 +0000153 def zip_random_open_test(self, f, compression):
154 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000155
156 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000157 with zipfile.ZipFile(f, "r", compression) as zipfp:
158 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +0000159 with zipfp.open(TESTFN) as zipopen1:
160 while True:
161 read_data = zipopen1.read(randint(1, 1024))
162 if not read_data:
163 break
164 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000165
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000166 self.assertEqual(b''.join(zipdata1), self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000167 if not isinstance(f, str):
168 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000169
Ezio Melottiafd0d112009-07-15 17:17:17 +0000170 def test_random_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000171 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000172 self.zip_random_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000173
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000174 def test_univeral_readaheads(self):
175 f = io.BytesIO()
176
177 data = b'a\r\n' * 16 * 1024
178 zipfp = zipfile.ZipFile(f, 'w', zipfile.ZIP_STORED)
179 zipfp.writestr(TESTFN, data)
180 zipfp.close()
181
182 data2 = b''
183 zipfp = zipfile.ZipFile(f, 'r')
Brian Curtin8fb9b862010-11-18 02:15:28 +0000184 with zipfp.open(TESTFN, 'rU') as zipopen:
185 for line in zipopen:
186 data2 += line
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000187 zipfp.close()
188
189 self.assertEqual(data, data2.replace(b'\n', b'\r\n'))
190
191 def zip_readline_read_test(self, f, compression):
192 self.make_test_archive(f, compression)
193
194 # Read the ZIP archive
195 zipfp = zipfile.ZipFile(f, "r")
Brian Curtin8fb9b862010-11-18 02:15:28 +0000196 with zipfp.open(TESTFN) as zipopen:
197 data = b''
198 while True:
199 read = zipopen.readline()
200 if not read:
201 break
202 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000203
Brian Curtin8fb9b862010-11-18 02:15:28 +0000204 read = zipopen.read(100)
205 if not read:
206 break
207 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000208
209 self.assertEqual(data, self.data)
210 zipfp.close()
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000211 if not isinstance(f, str):
212 f.close()
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000213
Ezio Melottiafd0d112009-07-15 17:17:17 +0000214 def zip_readline_test(self, f, compression):
215 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000216
217 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000218 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000219 with zipfp.open(TESTFN) as zipopen:
220 for line in self.line_gen:
221 linedata = zipopen.readline()
222 self.assertEqual(linedata, line + '\n')
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000223 if not isinstance(f, str):
224 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000225
Ezio Melottiafd0d112009-07-15 17:17:17 +0000226 def zip_readlines_test(self, f, compression):
227 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000228
229 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000230 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000231 with zipfp.open(TESTFN) as zipopen:
232 ziplines = zipopen.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000233 for line, zipline in zip(self.line_gen, ziplines):
234 self.assertEqual(zipline, line + '\n')
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000235 if not isinstance(f, str):
236 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000237
Ezio Melottiafd0d112009-07-15 17:17:17 +0000238 def zip_iterlines_test(self, f, compression):
239 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000240
241 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000242 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000243 with zipfp.open(TESTFN) as zipopen:
244 for line, zipline in zip(self.line_gen, zipopen):
245 self.assertEqual(zipline, line + '\n')
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000246 if not isinstance(f, str):
247 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000248
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000249 def test_readline_read_stored(self):
250 # Issue #7610: calls to readline() interleaved with calls to read().
251 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
252 self.zip_readline_read_test(f, zipfile.ZIP_STORED)
253
Ezio Melottiafd0d112009-07-15 17:17:17 +0000254 def test_readline_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000255 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000256 self.zip_readline_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000257
Ezio Melottiafd0d112009-07-15 17:17:17 +0000258 def test_readlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000259 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000260 self.zip_readlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000261
Ezio Melottiafd0d112009-07-15 17:17:17 +0000262 def test_iterlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000263 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000264 self.zip_iterlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000265
Ezio Melotti975077a2011-05-19 22:03:22 +0300266 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +0000267 def test_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000268 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000269 self.zip_test(f, zipfile.ZIP_DEFLATED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000270
Guido van Rossumd8faa362007-04-27 19:54:29 +0000271
Ezio Melotti975077a2011-05-19 22:03:22 +0300272 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +0000273 def test_open_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000274 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000275 self.zip_open_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000276
Ezio Melotti975077a2011-05-19 22:03:22 +0300277 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +0000278 def test_random_open_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000279 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000280 self.zip_random_open_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000281
Ezio Melotti975077a2011-05-19 22:03:22 +0300282 @requires_zlib
Antoine Pitroua32f9a22010-01-27 21:18:57 +0000283 def test_readline_read_deflated(self):
284 # Issue #7610: calls to readline() interleaved with calls to read().
285 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
286 self.zip_readline_read_test(f, zipfile.ZIP_DEFLATED)
287
Ezio Melotti975077a2011-05-19 22:03:22 +0300288 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +0000289 def test_readline_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000290 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000291 self.zip_readline_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000292
Ezio Melotti975077a2011-05-19 22:03:22 +0300293 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +0000294 def test_readlines_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000295 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000296 self.zip_readlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000297
Ezio Melotti975077a2011-05-19 22:03:22 +0300298 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +0000299 def test_iterlines_deflated(self):
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000300 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000301 self.zip_iterlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000302
Ezio Melotti975077a2011-05-19 22:03:22 +0300303 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +0000304 def test_low_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000305 """Check for cases where compressed data is larger than original."""
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000306 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000307 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
308 zipfp.writestr("strfile", '12')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000309
310 # Get an open object for strfile
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000311 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_DEFLATED) as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000312 with zipfp.open("strfile") as openobj:
313 self.assertEqual(openobj.read(1), b'1')
314 self.assertEqual(openobj.read(1), b'2')
Ezio Melotti74c96ec2009-07-08 22:24:06 +0000315
Ezio Melottiafd0d112009-07-15 17:17:17 +0000316 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000317 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
318 zipfp.write(TESTFN, "/absolute")
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000319
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000320 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
321 self.assertEqual(zipfp.namelist(), ["absolute"])
Tim Peters32cbc962006-02-20 21:42:18 +0000322
Ezio Melottiafd0d112009-07-15 17:17:17 +0000323 def test_append_to_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000324 """Test appending to an existing zipfile."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000325 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
326 zipfp.write(TESTFN, TESTFN)
327
328 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
329 zipfp.writestr("strfile", self.data)
330 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000331
Ezio Melottiafd0d112009-07-15 17:17:17 +0000332 def test_append_to_non_zip_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000333 """Test appending to an existing file that is not a zipfile."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000334 # NOTE: this test fails if len(d) < 22 because of the first
335 # line "fpin.seek(-22, 2)" in _EndRecData
Ezio Melotti35386712009-12-31 13:22:41 +0000336 data = b'I am not a ZipFile!'*10
337 with open(TESTFN2, 'wb') as f:
338 f.write(data)
339
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000340 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
341 zipfp.write(TESTFN, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000342
Ezio Melotti35386712009-12-31 13:22:41 +0000343 with open(TESTFN2, 'rb') as f:
344 f.seek(len(data))
345 with zipfile.ZipFile(f, "r") as zipfp:
346 self.assertEqual(zipfp.namelist(), [TESTFN])
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000347
R David Murray4fbb9db2011-06-09 15:50:51 -0400348 def test_ignores_newline_at_end(self):
349 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
350 zipfp.write(TESTFN, TESTFN)
351 with open(TESTFN2, 'a') as f:
352 f.write("\r\n\00\00\00")
353 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
354 self.assertIsInstance(zipfp, zipfile.ZipFile)
355
356 def test_ignores_stuff_appended_past_comments(self):
357 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
358 zipfp.comment = b"this is a comment"
359 zipfp.write(TESTFN, TESTFN)
360 with open(TESTFN2, 'a') as f:
361 f.write("abcdef\r\n")
362 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
363 self.assertIsInstance(zipfp, zipfile.ZipFile)
364 self.assertEqual(zipfp.comment, b"this is a comment")
365
Ezio Melottiafd0d112009-07-15 17:17:17 +0000366 def test_write_default_name(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000367 """Check that calling ZipFile.write without arcname specified
368 produces the expected result."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000369 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
370 zipfp.write(TESTFN)
Brian Curtin8fb9b862010-11-18 02:15:28 +0000371 with open(TESTFN, "rb") as f:
372 self.assertEqual(zipfp.read(TESTFN), f.read())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000373
Ezio Melotti975077a2011-05-19 22:03:22 +0300374 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +0000375 def test_per_file_compression(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000376 """Check that files within a Zip archive can have different
377 compression options."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000378 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
379 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
380 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
381 sinfo = zipfp.getinfo('storeme')
382 dinfo = zipfp.getinfo('deflateme')
383 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
384 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000385
Ezio Melottiafd0d112009-07-15 17:17:17 +0000386 def test_write_to_readonly(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000387 """Check that trying to call write() on a readonly ZipFile object
388 raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000389 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
390 zipfp.writestr("somefile.txt", "bogus")
391
392 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
393 self.assertRaises(RuntimeError, zipfp.write, TESTFN)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000394
Ezio Melottiafd0d112009-07-15 17:17:17 +0000395 def test_extract(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000396 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
397 for fpath, fdata in SMALL_TEST_DATA:
398 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000399
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000400 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
401 for fpath, fdata in SMALL_TEST_DATA:
402 writtenfile = zipfp.extract(fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000403
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000404 # make sure it was written to the right place
405 if os.path.isabs(fpath):
406 correctfile = os.path.join(os.getcwd(), fpath[1:])
407 else:
408 correctfile = os.path.join(os.getcwd(), fpath)
409 correctfile = os.path.normpath(correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000410
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000411 self.assertEqual(writtenfile, correctfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000412
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000413 # make sure correct data is in correct file
Brian Curtin8fb9b862010-11-18 02:15:28 +0000414 with open(writtenfile, "rb") as f:
415 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000416
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000417 os.remove(writtenfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000418
419 # remove the test file subdirectories
420 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
421
Ezio Melottiafd0d112009-07-15 17:17:17 +0000422 def test_extract_all(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000423 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
424 for fpath, fdata in SMALL_TEST_DATA:
425 zipfp.writestr(fpath, fdata)
Christian Heimes790c8232008-01-07 21:14:23 +0000426
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000427 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
428 zipfp.extractall()
429 for fpath, fdata in SMALL_TEST_DATA:
430 if os.path.isabs(fpath):
431 outfile = os.path.join(os.getcwd(), fpath[1:])
432 else:
433 outfile = os.path.join(os.getcwd(), fpath)
Christian Heimes790c8232008-01-07 21:14:23 +0000434
Brian Curtin8fb9b862010-11-18 02:15:28 +0000435 with open(outfile, "rb") as f:
436 self.assertEqual(fdata.encode(), f.read())
Christian Heimes790c8232008-01-07 21:14:23 +0000437
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000438 os.remove(outfile)
Christian Heimes790c8232008-01-07 21:14:23 +0000439
440 # remove the test file subdirectories
441 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
442
Ezio Melotti975077a2011-05-19 22:03:22 +0300443 def test_writestr_compression_stored(self):
Ronald Oussorenee5c8852010-02-07 20:24:02 +0000444 zipfp = zipfile.ZipFile(TESTFN2, "w")
445 zipfp.writestr("a.txt", "hello world", compress_type=zipfile.ZIP_STORED)
Ronald Oussorenee5c8852010-02-07 20:24:02 +0000446 info = zipfp.getinfo('a.txt')
447 self.assertEqual(info.compress_type, zipfile.ZIP_STORED)
448
Ezio Melotti975077a2011-05-19 22:03:22 +0300449 @requires_zlib
450 def test_writestr_compression_deflated(self):
451 zipfp = zipfile.ZipFile(TESTFN2, "w")
452 zipfp.writestr("b.txt", "hello world", compress_type=zipfile.ZIP_DEFLATED)
453 info = zipfp.getinfo('b.txt')
454 self.assertEqual(info.compress_type, zipfile.ZIP_DEFLATED)
Ronald Oussorenee5c8852010-02-07 20:24:02 +0000455
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000456 def zip_test_writestr_permissions(self, f, compression):
457 # Make sure that writestr creates files with mode 0600,
458 # when it is passed a name rather than a ZipInfo instance.
459
Ezio Melottiafd0d112009-07-15 17:17:17 +0000460 self.make_test_archive(f, compression)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000461 with zipfile.ZipFile(f, "r") as zipfp:
462 zinfo = zipfp.getinfo('strfile')
463 self.assertEqual(zinfo.external_attr, 0o600 << 16)
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000464 if not isinstance(f, str):
465 f.close()
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000466
Ezio Melottiafd0d112009-07-15 17:17:17 +0000467 def test_writestr_permissions(self):
Antoine Pitrou6e1df8d2008-07-25 19:58:18 +0000468 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
469 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
470
Gregory P. Smithb0d9ca92009-07-07 05:06:04 +0000471 def test_writestr_extended_local_header_issue1202(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000472 with zipfile.ZipFile(TESTFN2, 'w') as orig_zip:
473 for data in 'abcdefghijklmnop':
474 zinfo = zipfile.ZipInfo(data)
475 zinfo.flag_bits |= 0x08 # Include an extended local header.
476 orig_zip.writestr(zinfo, data)
477
478 def test_close(self):
479 """Check that the zipfile is closed after the 'with' block."""
480 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
481 for fpath, fdata in SMALL_TEST_DATA:
482 zipfp.writestr(fpath, fdata)
483 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
484 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
485
486 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
487 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
488 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
489
490 def test_close_on_exception(self):
491 """Check that the zipfile is closed if an exception is raised in the
492 'with' block."""
493 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
494 for fpath, fdata in SMALL_TEST_DATA:
495 zipfp.writestr(fpath, fdata)
496
497 try:
498 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
Georg Brandl4d540882010-10-28 06:42:33 +0000499 raise zipfile.BadZipFile()
500 except zipfile.BadZipFile:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000501 self.assertTrue(zipfp2.fp is None, 'zipfp is not closed')
Gregory P. Smithb0d9ca92009-07-07 05:06:04 +0000502
Senthil Kumaran29fa9d42011-10-20 01:46:00 +0800503 def test_add_file_before_1980(self):
504 # Set atime and mtime to 1970-01-01
505 os.utime(TESTFN, (0, 0))
506 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
507 self.assertRaises(ValueError, zipfp.write, TESTFN)
508
509
Senthil Kumaran7e3062b2011-10-20 01:52:41 +0800510
511
512
513
514
Ezio Melotti975077a2011-05-19 22:03:22 +0300515 @requires_zlib
Georg Brandl5ba11de2011-01-01 10:09:32 +0000516 def test_unicode_filenames(self):
Georg Brandl04480a82011-01-01 10:42:31 +0000517 # bug #10801
518 fname = findfile('zip_cp437_header.zip')
Georg Brandl5ba11de2011-01-01 10:09:32 +0000519 with zipfile.ZipFile(fname) as zipfp:
Georg Brandl04480a82011-01-01 10:42:31 +0000520 for name in zipfp.namelist():
521 zipfp.open(name).close()
Georg Brandl5ba11de2011-01-01 10:09:32 +0000522
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000523 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +0000524 unlink(TESTFN)
525 unlink(TESTFN2)
526
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000527
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000528class TestZip64InSmallFiles(unittest.TestCase):
529 # These tests test the ZIP64 functionality without using large files,
530 # see test_zipfile64 for proper tests.
531
532 def setUp(self):
533 self._limit = zipfile.ZIP64_LIMIT
534 zipfile.ZIP64_LIMIT = 5
535
Guido van Rossum9c627722007-08-27 18:31:48 +0000536 line_gen = (bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000537 for i in range(0, FIXEDTEST_SIZE))
538 self.data = b'\n'.join(line_gen)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000539
540 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +0000541 with open(TESTFN, "wb") as fp:
542 fp.write(self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000543
Ezio Melottiafd0d112009-07-15 17:17:17 +0000544 def large_file_exception_test(self, f, compression):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000545 with zipfile.ZipFile(f, "w", compression) as zipfp:
546 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti35386712009-12-31 13:22:41 +0000547 zipfp.write, TESTFN, "another.name")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000548
Ezio Melottiafd0d112009-07-15 17:17:17 +0000549 def large_file_exception_test2(self, f, compression):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000550 with zipfile.ZipFile(f, "w", compression) as zipfp:
551 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti35386712009-12-31 13:22:41 +0000552 zipfp.writestr, "another.name", self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000553 if not isinstance(f, str):
554 f.close()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000555
Ezio Melottiafd0d112009-07-15 17:17:17 +0000556 def test_large_file_exception(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000557 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000558 self.large_file_exception_test(f, zipfile.ZIP_STORED)
559 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000560
Ezio Melottiafd0d112009-07-15 17:17:17 +0000561 def zip_test(self, f, compression):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000562 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000563 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
564 zipfp.write(TESTFN, "another.name")
565 zipfp.write(TESTFN, TESTFN)
566 zipfp.writestr("strfile", self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000567
568 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000569 with zipfile.ZipFile(f, "r", compression) as zipfp:
570 self.assertEqual(zipfp.read(TESTFN), self.data)
571 self.assertEqual(zipfp.read("another.name"), self.data)
572 self.assertEqual(zipfp.read("strfile"), self.data)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000573
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000574 # Print the ZIP directory
575 fp = io.StringIO()
576 zipfp.printdir(fp)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000577
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000578 directory = fp.getvalue()
579 lines = directory.splitlines()
Ezio Melotti35386712009-12-31 13:22:41 +0000580 self.assertEqual(len(lines), 4) # Number of files + header
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000581
Benjamin Peterson577473f2010-01-19 00:09:57 +0000582 self.assertIn('File Name', lines[0])
583 self.assertIn('Modified', lines[0])
584 self.assertIn('Size', lines[0])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000585
Ezio Melotti35386712009-12-31 13:22:41 +0000586 fn, date, time_, size = lines[1].split()
587 self.assertEqual(fn, 'another.name')
588 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
589 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
590 self.assertEqual(size, str(len(self.data)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000591
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000592 # Check the namelist
593 names = zipfp.namelist()
Ezio Melotti35386712009-12-31 13:22:41 +0000594 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000595 self.assertIn(TESTFN, names)
596 self.assertIn("another.name", names)
597 self.assertIn("strfile", names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000598
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000599 # Check infolist
600 infos = zipfp.infolist()
Ezio Melotti35386712009-12-31 13:22:41 +0000601 names = [i.filename for i in infos]
602 self.assertEqual(len(names), 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000603 self.assertIn(TESTFN, names)
604 self.assertIn("another.name", names)
605 self.assertIn("strfile", names)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000606 for i in infos:
Ezio Melotti35386712009-12-31 13:22:41 +0000607 self.assertEqual(i.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000608
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000609 # check getinfo
610 for nm in (TESTFN, "another.name", "strfile"):
611 info = zipfp.getinfo(nm)
Ezio Melotti35386712009-12-31 13:22:41 +0000612 self.assertEqual(info.filename, nm)
613 self.assertEqual(info.file_size, len(self.data))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000614
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000615 # Check that testzip doesn't raise an exception
616 zipfp.testzip()
Benjamin Petersond285bdb2010-10-31 17:57:22 +0000617 if not isinstance(f, str):
618 f.close()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000619
Ezio Melottiafd0d112009-07-15 17:17:17 +0000620 def test_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000621 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000622 self.zip_test(f, zipfile.ZIP_STORED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000623
Ezio Melotti975077a2011-05-19 22:03:22 +0300624 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +0000625 def test_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +0000626 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000627 self.zip_test(f, zipfile.ZIP_DEFLATED)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000628
Ezio Melottiafd0d112009-07-15 17:17:17 +0000629 def test_absolute_arcnames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000630 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
631 allowZip64=True) as zipfp:
632 zipfp.write(TESTFN, "/absolute")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000633
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000634 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
635 self.assertEqual(zipfp.namelist(), ["absolute"])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000636
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000637 def tearDown(self):
638 zipfile.ZIP64_LIMIT = self._limit
Ezio Melotti76430242009-07-11 18:28:48 +0000639 unlink(TESTFN)
640 unlink(TESTFN2)
641
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000642
643class PyZipFileTests(unittest.TestCase):
Ezio Melottiafd0d112009-07-15 17:17:17 +0000644 def test_write_pyfile(self):
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000645 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000646 fn = __file__
647 if fn.endswith('.pyc') or fn.endswith('.pyo'):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000648 path_split = fn.split(os.sep)
649 if os.altsep is not None:
650 path_split.extend(fn.split(os.altsep))
651 if '__pycache__' in path_split:
652 fn = imp.source_from_cache(fn)
653 else:
654 fn = fn[:-1]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000655
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000656 zipfp.writepy(fn)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000657
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000658 bn = os.path.basename(fn)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000659 self.assertNotIn(bn, zipfp.namelist())
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000660 self.assertTrue(bn + 'o' in zipfp.namelist() or
661 bn + 'c' in zipfp.namelist())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000662
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000663 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000664 fn = __file__
Ezio Melotti35386712009-12-31 13:22:41 +0000665 if fn.endswith(('.pyc', '.pyo')):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000666 fn = fn[:-1]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000667
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000668 zipfp.writepy(fn, "testpackage")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000669
Ezio Melotti35386712009-12-31 13:22:41 +0000670 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000671 self.assertNotIn(bn, zipfp.namelist())
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000672 self.assertTrue(bn + 'o' in zipfp.namelist() or
673 bn + 'c' in zipfp.namelist())
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000674
Ezio Melottiafd0d112009-07-15 17:17:17 +0000675 def test_write_python_package(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000676 import email
677 packagedir = os.path.dirname(email.__file__)
678
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000679 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000680 zipfp.writepy(packagedir)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000681
Ezio Melotti35386712009-12-31 13:22:41 +0000682 # Check for a couple of modules at different levels of the
683 # hierarchy
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000684 names = zipfp.namelist()
685 self.assertTrue('email/__init__.pyo' in names or
686 'email/__init__.pyc' in names)
687 self.assertTrue('email/mime/text.pyo' in names or
688 'email/mime/text.pyc' in names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000689
Georg Brandl8334fd92010-12-04 10:26:46 +0000690 def test_write_with_optimization(self):
691 import email
692 packagedir = os.path.dirname(email.__file__)
693 # use .pyc if running test in optimization mode,
694 # use .pyo if running test in debug mode
695 optlevel = 1 if __debug__ else 0
696 ext = '.pyo' if optlevel == 1 else '.pyc'
697
698 with TemporaryFile() as t, \
699 zipfile.PyZipFile(t, "w", optimize=optlevel) as zipfp:
700 zipfp.writepy(packagedir)
701
702 names = zipfp.namelist()
703 self.assertIn('email/__init__' + ext, names)
704 self.assertIn('email/mime/text' + ext, names)
705
Ezio Melottiafd0d112009-07-15 17:17:17 +0000706 def test_write_python_directory(self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000707 os.mkdir(TESTFN2)
708 try:
Ezio Melotti35386712009-12-31 13:22:41 +0000709 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
710 fp.write("print(42)\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000711
Ezio Melotti35386712009-12-31 13:22:41 +0000712 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
713 fp.write("print(42 * 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.txt"), "w") as fp:
716 fp.write("bla bla bla\n")
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000717
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000718 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
719 zipfp.writepy(TESTFN2)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000720
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000721 names = zipfp.namelist()
722 self.assertTrue('mod1.pyc' in names or 'mod1.pyo' in names)
723 self.assertTrue('mod2.pyc' in names or 'mod2.pyo' in names)
724 self.assertNotIn('mod2.txt', names)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000725
726 finally:
727 shutil.rmtree(TESTFN2)
728
Ezio Melottiafd0d112009-07-15 17:17:17 +0000729 def test_write_non_pyfile(self):
Łukasz Langaa9f054b2010-11-23 00:15:02 +0000730 with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
Brian Curtin8fb9b862010-11-18 02:15:28 +0000731 with open(TESTFN, 'w') as f:
732 f.write('most definitely not a python file')
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000733 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
734 os.remove(TESTFN)
735
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000736
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000737class OtherTests(unittest.TestCase):
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000738 zips_with_bad_crc = {
739 zipfile.ZIP_STORED: (
740 b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
741 b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
742 b'ilehello,AworldP'
743 b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
744 b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
745 b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
746 b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
747 b'\0\0/\0\0\0\0\0'),
748 zipfile.ZIP_DEFLATED: (
749 b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
750 b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
751 b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
752 b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
753 b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
754 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
755 b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
756 b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00'),
757 }
758
Ezio Melottiafd0d112009-07-15 17:17:17 +0000759 def test_unicode_filenames(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000760 with zipfile.ZipFile(TESTFN, "w") as zf:
761 zf.writestr("foo.txt", "Test for unicode filename")
762 zf.writestr("\xf6.txt", "Test for unicode filename")
Ezio Melottie9615932010-01-24 19:26:24 +0000763 self.assertIsInstance(zf.infolist()[0].filename, str)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000764
765 with zipfile.ZipFile(TESTFN, "r") as zf:
766 self.assertEqual(zf.filelist[0].filename, "foo.txt")
767 self.assertEqual(zf.filelist[1].filename, "\xf6.txt")
Martin v. Löwis8570f6a2008-05-05 17:44:38 +0000768
Ezio Melottiafd0d112009-07-15 17:17:17 +0000769 def test_create_non_existent_file_for_append(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +0000770 if os.path.exists(TESTFN):
771 os.unlink(TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000772
Thomas Wouterscf297e42007-02-23 15:07:44 +0000773 filename = 'testfile.txt'
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000774 content = b'hello, world. this is some content.'
Guido van Rossumd8faa362007-04-27 19:54:29 +0000775
Thomas Wouterscf297e42007-02-23 15:07:44 +0000776 try:
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000777 with zipfile.ZipFile(TESTFN, 'a') as zf:
778 zf.writestr(filename, content)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000779 except IOError:
780 self.fail('Could not append data to a non-existent zip file.')
781
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000782 self.assertTrue(os.path.exists(TESTFN))
Thomas Wouterscf297e42007-02-23 15:07:44 +0000783
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000784 with zipfile.ZipFile(TESTFN, 'r') as zf:
785 self.assertEqual(zf.read(filename), content)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000786
Ezio Melottiafd0d112009-07-15 17:17:17 +0000787 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000788 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti35386712009-12-31 13:22:41 +0000789 # it opens if there's an error in the file. If it doesn't, the
790 # traceback holds a reference to the ZipFile object and, indirectly,
791 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000792 # On Windows, this causes the os.unlink() call to fail because the
793 # underlying file is still open. This is SF bug #412214.
794 #
Ezio Melotti35386712009-12-31 13:22:41 +0000795 with open(TESTFN, "w") as fp:
796 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000797 try:
798 zf = zipfile.ZipFile(TESTFN)
Georg Brandl4d540882010-10-28 06:42:33 +0000799 except zipfile.BadZipFile:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000800 pass
801
Ezio Melottiafd0d112009-07-15 17:17:17 +0000802 def test_is_zip_erroneous_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000803 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000804 # - passing a filename
805 with open(TESTFN, "w") as fp:
806 fp.write("this is not a legal zip file\n")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000807 chk = zipfile.is_zipfile(TESTFN)
Ezio Melotti35386712009-12-31 13:22:41 +0000808 self.assertFalse(chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000809 # - passing a file object
810 with open(TESTFN, "rb") as fp:
811 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000812 self.assertTrue(not chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000813 # - passing a file-like object
814 fp = io.BytesIO()
815 fp.write(b"this is not a legal zip file\n")
816 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000817 self.assertTrue(not chk)
Ezio Melotti35386712009-12-31 13:22:41 +0000818 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000819 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000820 self.assertTrue(not chk)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000821
Ezio Melottiafd0d112009-07-15 17:17:17 +0000822 def test_is_zip_valid_file(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000823 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000824 # - passing a filename
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000825 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
826 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
827
Guido van Rossumd8faa362007-04-27 19:54:29 +0000828 chk = zipfile.is_zipfile(TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000829 self.assertTrue(chk)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000830 # - passing a file object
831 with open(TESTFN, "rb") as fp:
832 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000833 self.assertTrue(chk)
Ezio Melotti35386712009-12-31 13:22:41 +0000834 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000835 zip_contents = fp.read()
836 # - passing a file-like object
837 fp = io.BytesIO()
838 fp.write(zip_contents)
839 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000840 self.assertTrue(chk)
Ezio Melotti35386712009-12-31 13:22:41 +0000841 fp.seek(0, 0)
Antoine Pitroudb5fe662008-12-27 15:50:40 +0000842 chk = zipfile.is_zipfile(fp)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000843 self.assertTrue(chk)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000844
Ezio Melottiafd0d112009-07-15 17:17:17 +0000845 def test_non_existent_file_raises_IOError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000846 # make sure we don't raise an AttributeError when a partially-constructed
847 # ZipFile instance is finalized; this tests for regression on SF tracker
848 # bug #403871.
849
850 # The bug we're testing for caused an AttributeError to be raised
851 # when a ZipFile instance was created for a file that did not
852 # exist; the .fp member was not initialized but was needed by the
853 # __del__() method. Since the AttributeError is in the __del__(),
854 # it is ignored, but the user should be sufficiently annoyed by
855 # the message on the output that regression will be noticed
856 # quickly.
857 self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
858
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +0000859 def test_empty_file_raises_BadZipFile(self):
860 f = open(TESTFN, 'w')
861 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +0000862 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +0000863
Ezio Melotti35386712009-12-31 13:22:41 +0000864 with open(TESTFN, 'w') as fp:
865 fp.write("short file")
Georg Brandl4d540882010-10-28 06:42:33 +0000866 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN)
Amaury Forgeot d'Arcbc347802009-07-28 22:18:57 +0000867
Ezio Melottiafd0d112009-07-15 17:17:17 +0000868 def test_closed_zip_raises_RuntimeError(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000869 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Guido van Rossumd6ca5462007-05-22 01:29:33 +0000870 data = io.BytesIO()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000871 with zipfile.ZipFile(data, mode="w") as zipf:
872 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000873
874 # This is correct; calling .read on a closed ZipFile should throw
875 # a RuntimeError, and so should calling .testzip. An earlier
876 # version of .testzip would swallow this exception (and any other)
877 # and report that the first file in the archive was corrupt.
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000878 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
879 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000880 self.assertRaises(RuntimeError, zipf.testzip)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000881 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Brian Curtin8fb9b862010-11-18 02:15:28 +0000882 with open(TESTFN, 'w') as f:
883 f.write('zipfile test data')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000884 self.assertRaises(RuntimeError, zipf.write, TESTFN)
885
Ezio Melottiafd0d112009-07-15 17:17:17 +0000886 def test_bad_constructor_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000887 """Check that bad modes passed to ZipFile constructor are caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000888 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
889
Ezio Melottiafd0d112009-07-15 17:17:17 +0000890 def test_bad_open_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000891 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000892 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
893 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
894
895 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000896 # read the data to make sure the file is there
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000897 zipf.read("foo.txt")
898 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000899
Ezio Melottiafd0d112009-07-15 17:17:17 +0000900 def test_read0(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000901 """Check that calling read(0) on a ZipExtFile object returns an empty
902 string and doesn't advance file pointer."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000903 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
904 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
905 # read the data to make sure the file is there
Brian Curtin8fb9b862010-11-18 02:15:28 +0000906 with zipf.open("foo.txt") as f:
907 for i in range(FIXEDTEST_SIZE):
908 self.assertEqual(f.read(0), b'')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000909
Brian Curtin8fb9b862010-11-18 02:15:28 +0000910 self.assertEqual(f.read(), b"O, for a Muse of Fire!")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000911
Ezio Melottiafd0d112009-07-15 17:17:17 +0000912 def test_open_non_existent_item(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000913 """Check that attempting to call open() for an item that doesn't
914 exist in the archive raises a RuntimeError."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000915 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
916 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000917
Ezio Melottiafd0d112009-07-15 17:17:17 +0000918 def test_bad_compression_mode(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000919 """Check that bad compression methods passed to ZipFile.open are
920 caught."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000921 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
922
Ezio Melottiafd0d112009-07-15 17:17:17 +0000923 def test_null_byte_in_filename(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000924 """Check that a filename containing a null byte is properly
925 terminated."""
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000926 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
927 zipf.writestr("foo.txt\x00qqq", b"O, for a Muse of Fire!")
928 self.assertEqual(zipf.namelist(), ['foo.txt'])
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000929
Ezio Melottiafd0d112009-07-15 17:17:17 +0000930 def test_struct_sizes(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000931 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000932 self.assertEqual(zipfile.sizeEndCentDir, 22)
933 self.assertEqual(zipfile.sizeCentralDir, 46)
934 self.assertEqual(zipfile.sizeEndCentDir64, 56)
935 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
936
Ezio Melottiafd0d112009-07-15 17:17:17 +0000937 def test_comments(self):
Ezio Melotti35386712009-12-31 13:22:41 +0000938 """Check that comments on the archive are handled properly."""
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000939
940 # check default comment is empty
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000941 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
942 self.assertEqual(zipf.comment, b'')
943 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
944
945 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
946 self.assertEqual(zipfr.comment, b'')
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000947
948 # check a simple short comment
949 comment = b'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000950 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
951 zipf.comment = comment
952 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
953 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
954 self.assertEqual(zipf.comment, comment)
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000955
956 # check a comment of max length
957 comment2 = ''.join(['%d' % (i**3 % 10) for i in range((1 << 16)-1)])
958 comment2 = comment2.encode("ascii")
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000959 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
960 zipf.comment = comment2
961 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
962
963 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
964 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000965
966 # check a comment that is too long is truncated
Ezio Melottifaa6b7f2009-12-30 12:34:59 +0000967 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
968 zipf.comment = comment2 + b'oops'
969 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
970 with zipfile.ZipFile(TESTFN, mode="r") as zipfr:
971 self.assertEqual(zipfr.comment, comment2)
Martin v. Löwisb09b8442008-07-03 14:13:42 +0000972
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000973 def check_testzip_with_bad_crc(self, compression):
974 """Tests that files with bad CRCs return their name from testzip."""
975 zipdata = self.zips_with_bad_crc[compression]
976
977 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
978 # testzip returns the name of the first corrupt file, or None
979 self.assertEqual('afile', zipf.testzip())
980
981 def test_testzip_with_bad_crc_stored(self):
982 self.check_testzip_with_bad_crc(zipfile.ZIP_STORED)
983
Ezio Melotti975077a2011-05-19 22:03:22 +0300984 @requires_zlib
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000985 def test_testzip_with_bad_crc_deflated(self):
986 self.check_testzip_with_bad_crc(zipfile.ZIP_DEFLATED)
987
988 def check_read_with_bad_crc(self, compression):
Georg Brandl4d540882010-10-28 06:42:33 +0000989 """Tests that files with bad CRCs raise a BadZipFile exception when read."""
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000990 zipdata = self.zips_with_bad_crc[compression]
991
992 # Using ZipFile.read()
993 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
Georg Brandl4d540882010-10-28 06:42:33 +0000994 self.assertRaises(zipfile.BadZipFile, zipf.read, 'afile')
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +0000995
996 # Using ZipExtFile.read()
997 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
998 with zipf.open('afile', 'r') as corrupt_file:
Georg Brandl4d540882010-10-28 06:42:33 +0000999 self.assertRaises(zipfile.BadZipFile, corrupt_file.read)
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001000
1001 # Same with small reads (in order to exercise the buffering logic)
1002 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1003 with zipf.open('afile', 'r') as corrupt_file:
1004 corrupt_file.MIN_READ_SIZE = 2
Georg Brandl4d540882010-10-28 06:42:33 +00001005 with self.assertRaises(zipfile.BadZipFile):
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001006 while corrupt_file.read(2):
1007 pass
1008
1009 def test_read_with_bad_crc_stored(self):
1010 self.check_read_with_bad_crc(zipfile.ZIP_STORED)
1011
Ezio Melotti975077a2011-05-19 22:03:22 +03001012 @requires_zlib
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001013 def test_read_with_bad_crc_deflated(self):
1014 self.check_read_with_bad_crc(zipfile.ZIP_DEFLATED)
1015
Antoine Pitrou6464d5f2010-09-12 14:51:20 +00001016 def check_read_return_size(self, compression):
1017 # Issue #9837: ZipExtFile.read() shouldn't return more bytes
1018 # than requested.
1019 for test_size in (1, 4095, 4096, 4097, 16384):
1020 file_size = test_size + 1
1021 junk = b''.join(struct.pack('B', randint(0, 255))
1022 for x in range(file_size))
1023 with zipfile.ZipFile(io.BytesIO(), "w", compression) as zipf:
1024 zipf.writestr('foo', junk)
1025 with zipf.open('foo', 'r') as fp:
1026 buf = fp.read(test_size)
1027 self.assertEqual(len(buf), test_size)
1028
1029 def test_read_return_size_stored(self):
1030 self.check_read_return_size(zipfile.ZIP_STORED)
1031
Ezio Melotti975077a2011-05-19 22:03:22 +03001032 @requires_zlib
Antoine Pitrou6464d5f2010-09-12 14:51:20 +00001033 def test_read_return_size_deflated(self):
1034 self.check_read_return_size(zipfile.ZIP_DEFLATED)
1035
Georg Brandl268e4d42010-10-14 06:59:45 +00001036 def test_empty_zipfile(self):
1037 # Check that creating a file in 'w' or 'a' mode and closing without
1038 # adding any files to the archives creates a valid empty ZIP file
1039 zipf = zipfile.ZipFile(TESTFN, mode="w")
1040 zipf.close()
1041 try:
1042 zipf = zipfile.ZipFile(TESTFN, mode="r")
1043 except zipfile.BadZipFile:
1044 self.fail("Unable to create empty ZIP file in 'w' mode")
1045
1046 zipf = zipfile.ZipFile(TESTFN, mode="a")
1047 zipf.close()
1048 try:
1049 zipf = zipfile.ZipFile(TESTFN, mode="r")
1050 except:
1051 self.fail("Unable to create empty ZIP file in 'a' mode")
1052
1053 def test_open_empty_file(self):
1054 # Issue 1710703: Check that opening a file with less than 22 bytes
Georg Brandl4d540882010-10-28 06:42:33 +00001055 # raises a BadZipFile exception (rather than the previously unhelpful
Georg Brandl268e4d42010-10-14 06:59:45 +00001056 # IOError)
1057 f = open(TESTFN, 'w')
1058 f.close()
Georg Brandl4d540882010-10-28 06:42:33 +00001059 self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, TESTFN, 'r')
Georg Brandl268e4d42010-10-14 06:59:45 +00001060
Senthil Kumaran29fa9d42011-10-20 01:46:00 +08001061 def test_create_zipinfo_before_1980(self):
1062 self.assertRaises(ValueError,
1063 zipfile.ZipInfo, 'seventies', (1979, 1, 1, 0, 0, 0))
1064
Guido van Rossumd8faa362007-04-27 19:54:29 +00001065 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001066 unlink(TESTFN)
1067 unlink(TESTFN2)
1068
Thomas Wouterscf297e42007-02-23 15:07:44 +00001069
1070class DecryptionTests(unittest.TestCase):
Ezio Melotti35386712009-12-31 13:22:41 +00001071 """Check that ZIP decryption works. Since the library does not
1072 support encryption at the moment, we use a pre-generated encrypted
1073 ZIP file."""
Thomas Wouterscf297e42007-02-23 15:07:44 +00001074
1075 data = (
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001076 b'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
1077 b'\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
1078 b'\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
1079 b'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
1080 b'\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
1081 b'\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
1082 b'\x00\x00L\x00\x00\x00\x00\x00' )
Christian Heimesfdab48e2008-01-20 09:06:41 +00001083 data2 = (
1084 b'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
1085 b'\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
1086 b'\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
1087 b'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
1088 b'\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
1089 b'\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
1090 b'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
1091 b'\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Thomas Wouterscf297e42007-02-23 15:07:44 +00001092
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001093 plain = b'zipfile.py encryption test'
Christian Heimesfdab48e2008-01-20 09:06:41 +00001094 plain2 = b'\x00'*512
Thomas Wouterscf297e42007-02-23 15:07:44 +00001095
1096 def setUp(self):
Ezio Melotti35386712009-12-31 13:22:41 +00001097 with open(TESTFN, "wb") as fp:
1098 fp.write(self.data)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001099 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti35386712009-12-31 13:22:41 +00001100 with open(TESTFN2, "wb") as fp:
1101 fp.write(self.data2)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001102 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001103
1104 def tearDown(self):
1105 self.zip.close()
1106 os.unlink(TESTFN)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001107 self.zip2.close()
1108 os.unlink(TESTFN2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001109
Ezio Melottiafd0d112009-07-15 17:17:17 +00001110 def test_no_password(self):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001111 # Reading the encrypted file without password
1112 # must generate a RunTime exception
1113 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001114 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001115
Ezio Melottiafd0d112009-07-15 17:17:17 +00001116 def test_bad_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001117 self.zip.setpassword(b"perl")
Thomas Wouterscf297e42007-02-23 15:07:44 +00001118 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Christian Heimesfdab48e2008-01-20 09:06:41 +00001119 self.zip2.setpassword(b"perl")
1120 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001121
Ezio Melotti975077a2011-05-19 22:03:22 +03001122 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +00001123 def test_good_password(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001124 self.zip.setpassword(b"python")
Ezio Melotti35386712009-12-31 13:22:41 +00001125 self.assertEqual(self.zip.read("test.txt"), self.plain)
Christian Heimesfdab48e2008-01-20 09:06:41 +00001126 self.zip2.setpassword(b"12345")
Ezio Melotti35386712009-12-31 13:22:41 +00001127 self.assertEqual(self.zip2.read("zero"), self.plain2)
Thomas Wouterscf297e42007-02-23 15:07:44 +00001128
R. David Murray8d855d82010-12-21 21:53:37 +00001129 def test_unicode_password(self):
1130 self.assertRaises(TypeError, self.zip.setpassword, "unicode")
1131 self.assertRaises(TypeError, self.zip.read, "test.txt", "python")
1132 self.assertRaises(TypeError, self.zip.open, "test.txt", pwd="python")
1133 self.assertRaises(TypeError, self.zip.extract, "test.txt", pwd="python")
1134
Guido van Rossumd8faa362007-04-27 19:54:29 +00001135
1136class TestsWithRandomBinaryFiles(unittest.TestCase):
1137 def setUp(self):
1138 datacount = randint(16, 64)*1024 + randint(1, 1024)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001139 self.data = b''.join(struct.pack('<f', random()*randint(-1000, 1000))
1140 for i in range(datacount))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001141
1142 # Make a source file with some lines
Ezio Melotti35386712009-12-31 13:22:41 +00001143 with open(TESTFN, "wb") as fp:
1144 fp.write(self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001145
1146 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001147 unlink(TESTFN)
1148 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001149
Ezio Melottiafd0d112009-07-15 17:17:17 +00001150 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001151 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001152 with zipfile.ZipFile(f, "w", compression) as zipfp:
1153 zipfp.write(TESTFN, "another.name")
1154 zipfp.write(TESTFN, TESTFN)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001155
Ezio Melottiafd0d112009-07-15 17:17:17 +00001156 def zip_test(self, f, compression):
1157 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001158
1159 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001160 with zipfile.ZipFile(f, "r", compression) as zipfp:
1161 testdata = zipfp.read(TESTFN)
1162 self.assertEqual(len(testdata), len(self.data))
1163 self.assertEqual(testdata, self.data)
1164 self.assertEqual(zipfp.read("another.name"), self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001165 if not isinstance(f, str):
1166 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001167
Ezio Melottiafd0d112009-07-15 17:17:17 +00001168 def test_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001169 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001170 self.zip_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001171
Ezio Melotti975077a2011-05-19 22:03:22 +03001172 @requires_zlib
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001173 def test_deflated(self):
1174 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1175 self.zip_test(f, zipfile.ZIP_DEFLATED)
1176
Ezio Melottiafd0d112009-07-15 17:17:17 +00001177 def zip_open_test(self, f, compression):
1178 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001179
1180 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001181 with zipfile.ZipFile(f, "r", compression) as zipfp:
1182 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001183 with zipfp.open(TESTFN) as zipopen1:
1184 while True:
1185 read_data = zipopen1.read(256)
1186 if not read_data:
1187 break
1188 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001189
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001190 zipdata2 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001191 with zipfp.open("another.name") as zipopen2:
1192 while True:
1193 read_data = zipopen2.read(256)
1194 if not read_data:
1195 break
1196 zipdata2.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001197
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001198 testdata1 = b''.join(zipdata1)
1199 self.assertEqual(len(testdata1), len(self.data))
1200 self.assertEqual(testdata1, self.data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001201
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001202 testdata2 = b''.join(zipdata2)
Ezio Melotti35386712009-12-31 13:22:41 +00001203 self.assertEqual(len(testdata2), len(self.data))
1204 self.assertEqual(testdata2, self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001205 if not isinstance(f, str):
1206 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001207
Ezio Melottiafd0d112009-07-15 17:17:17 +00001208 def test_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001209 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001210 self.zip_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001211
Ezio Melotti975077a2011-05-19 22:03:22 +03001212 @requires_zlib
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001213 def test_open_deflated(self):
1214 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1215 self.zip_open_test(f, zipfile.ZIP_DEFLATED)
1216
Ezio Melottiafd0d112009-07-15 17:17:17 +00001217 def zip_random_open_test(self, f, compression):
1218 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001219
1220 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001221 with zipfile.ZipFile(f, "r", compression) as zipfp:
1222 zipdata1 = []
Brian Curtin8fb9b862010-11-18 02:15:28 +00001223 with zipfp.open(TESTFN) as zipopen1:
1224 while True:
1225 read_data = zipopen1.read(randint(1, 1024))
1226 if not read_data:
1227 break
1228 zipdata1.append(read_data)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001229
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001230 testdata = b''.join(zipdata1)
1231 self.assertEqual(len(testdata), len(self.data))
1232 self.assertEqual(testdata, self.data)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001233 if not isinstance(f, str):
1234 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001235
Ezio Melottiafd0d112009-07-15 17:17:17 +00001236 def test_random_open_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001237 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001238 self.zip_random_open_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001239
Ezio Melotti975077a2011-05-19 22:03:22 +03001240 @requires_zlib
Antoine Pitrou7c8bcb62010-08-12 15:11:50 +00001241 def test_random_open_deflated(self):
1242 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1243 self.zip_random_open_test(f, zipfile.ZIP_DEFLATED)
1244
Ezio Melotti76430242009-07-11 18:28:48 +00001245
Ezio Melotti975077a2011-05-19 22:03:22 +03001246@requires_zlib
Guido van Rossumd8faa362007-04-27 19:54:29 +00001247class TestsWithMultipleOpens(unittest.TestCase):
1248 def setUp(self):
1249 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001250 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
1251 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
1252 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001253
Ezio Melottiafd0d112009-07-15 17:17:17 +00001254 def test_same_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001255 # Verify that (when the ZipFile is in control of creating file objects)
1256 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001257 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001258 with zipf.open('ones') as zopen1, zipf.open('ones') as zopen2:
1259 data1 = zopen1.read(500)
1260 data2 = zopen2.read(500)
1261 data1 += zopen1.read(500)
1262 data2 += zopen2.read(500)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001263 self.assertEqual(data1, data2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001264
Ezio Melottiafd0d112009-07-15 17:17:17 +00001265 def test_different_file(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001266 # Verify that (when the ZipFile is in control of creating file objects)
1267 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001268 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001269 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1270 data1 = zopen1.read(500)
1271 data2 = zopen2.read(500)
1272 data1 += zopen1.read(500)
1273 data2 += zopen2.read(500)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001274 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
1275 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001276
Ezio Melottiafd0d112009-07-15 17:17:17 +00001277 def test_interleaved(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001278 # Verify that (when the ZipFile is in control of creating file objects)
1279 # multiple open() calls can be made without interfering with each other.
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001280 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin8fb9b862010-11-18 02:15:28 +00001281 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1282 data1 = zopen1.read(500)
1283 data2 = zopen2.read(500)
1284 data1 += zopen1.read(500)
1285 data2 += zopen2.read(500)
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001286 self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
1287 self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001288
1289 def tearDown(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001290 unlink(TESTFN2)
1291
Guido van Rossumd8faa362007-04-27 19:54:29 +00001292
Martin v. Löwis59e47792009-01-24 14:10:07 +00001293class TestWithDirectory(unittest.TestCase):
1294 def setUp(self):
1295 os.mkdir(TESTFN2)
1296
Ezio Melottiafd0d112009-07-15 17:17:17 +00001297 def test_extract_dir(self):
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001298 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
1299 zipf.extractall(TESTFN2)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001300 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1301 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1302 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1303
Ezio Melottiafd0d112009-07-15 17:17:17 +00001304 def test_bug_6050(self):
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001305 # Extraction should succeed if directories already exist
1306 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottiafd0d112009-07-15 17:17:17 +00001307 self.test_extract_dir()
Martin v. Löwis70ccd162009-05-24 19:47:22 +00001308
Ezio Melottiafd0d112009-07-15 17:17:17 +00001309 def test_store_dir(self):
Martin v. Löwis59e47792009-01-24 14:10:07 +00001310 os.mkdir(os.path.join(TESTFN2, "x"))
1311 zipf = zipfile.ZipFile(TESTFN, "w")
1312 zipf.write(os.path.join(TESTFN2, "x"), "x")
1313 self.assertTrue(zipf.filelist[0].filename.endswith("x/"))
1314
1315 def tearDown(self):
1316 shutil.rmtree(TESTFN2)
1317 if os.path.exists(TESTFN):
Ezio Melotti76430242009-07-11 18:28:48 +00001318 unlink(TESTFN)
Martin v. Löwis59e47792009-01-24 14:10:07 +00001319
Guido van Rossumd8faa362007-04-27 19:54:29 +00001320
1321class UniversalNewlineTests(unittest.TestCase):
1322 def setUp(self):
Guido van Rossum9c627722007-08-27 18:31:48 +00001323 self.line_gen = [bytes("Test of zipfile line %d." % i, "ascii")
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001324 for i in range(FIXEDTEST_SIZE)]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001325 self.seps = ('\r', '\r\n', '\n')
1326 self.arcdata, self.arcfiles = {}, {}
1327 for n, s in enumerate(self.seps):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001328 b = s.encode("ascii")
1329 self.arcdata[s] = b.join(self.line_gen) + b
Guido van Rossumd8faa362007-04-27 19:54:29 +00001330 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001331 f = open(self.arcfiles[s], "wb")
1332 try:
1333 f.write(self.arcdata[s])
1334 finally:
1335 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001336
Ezio Melottiafd0d112009-07-15 17:17:17 +00001337 def make_test_archive(self, f, compression):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001338 # Create the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001339 with zipfile.ZipFile(f, "w", compression) as zipfp:
1340 for fn in self.arcfiles.values():
1341 zipfp.write(fn, fn)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001342
Ezio Melottiafd0d112009-07-15 17:17:17 +00001343 def read_test(self, f, compression):
1344 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001345
1346 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001347 with zipfile.ZipFile(f, "r") as zipfp:
1348 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001349 with zipfp.open(fn, "rU") as fp:
1350 zipdata = fp.read()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001351 self.assertEqual(self.arcdata[sep], zipdata)
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001352 if not isinstance(f, str):
1353 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001354
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001355 def readline_read_test(self, f, compression):
1356 self.make_test_archive(f, compression)
1357
1358 # Read the ZIP archive
Brian Curtin8fb9b862010-11-18 02:15:28 +00001359 with zipfile.ZipFile(f, "r") as zipfp:
1360 for sep, fn in self.arcfiles.items():
1361 with zipfp.open(fn, "rU") as zipopen:
1362 data = b''
1363 while True:
1364 read = zipopen.readline()
1365 if not read:
1366 break
1367 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001368
Brian Curtin8fb9b862010-11-18 02:15:28 +00001369 read = zipopen.read(5)
1370 if not read:
1371 break
1372 data += read
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001373
1374 self.assertEqual(data, self.arcdata['\n'])
1375
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001376 if not isinstance(f, str):
1377 f.close()
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001378
Ezio Melottiafd0d112009-07-15 17:17:17 +00001379 def readline_test(self, f, compression):
1380 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001381
1382 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001383 with zipfile.ZipFile(f, "r") as zipfp:
1384 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001385 with zipfp.open(fn, "rU") as zipopen:
1386 for line in self.line_gen:
1387 linedata = zipopen.readline()
1388 self.assertEqual(linedata, line + b'\n')
1389 if not isinstance(f, str):
1390 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001391
Ezio Melottiafd0d112009-07-15 17:17:17 +00001392 def readlines_test(self, f, compression):
1393 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001394
1395 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001396 with zipfile.ZipFile(f, "r") as zipfp:
1397 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001398 with zipfp.open(fn, "rU") as fp:
1399 ziplines = fp.readlines()
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001400 for line, zipline in zip(self.line_gen, ziplines):
1401 self.assertEqual(zipline, line + b'\n')
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001402 if not isinstance(f, str):
1403 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001404
Ezio Melottiafd0d112009-07-15 17:17:17 +00001405 def iterlines_test(self, f, compression):
1406 self.make_test_archive(f, compression)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001407
1408 # Read the ZIP archive
Ezio Melottifaa6b7f2009-12-30 12:34:59 +00001409 with zipfile.ZipFile(f, "r") as zipfp:
1410 for sep, fn in self.arcfiles.items():
Benjamin Petersond285bdb2010-10-31 17:57:22 +00001411 with zipfp.open(fn, "rU") as fp:
1412 for line, zipline in zip(self.line_gen, fp):
1413 self.assertEqual(zipline, line + b'\n')
1414 if not isinstance(f, str):
1415 f.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001416
Ezio Melottiafd0d112009-07-15 17:17:17 +00001417 def test_read_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001418 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001419 self.read_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001420
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001421 def test_readline_read_stored(self):
1422 # Issue #7610: calls to readline() interleaved with calls to read().
1423 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1424 self.readline_read_test(f, zipfile.ZIP_STORED)
1425
Ezio Melottiafd0d112009-07-15 17:17:17 +00001426 def test_readline_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001427 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001428 self.readline_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001429
Ezio Melottiafd0d112009-07-15 17:17:17 +00001430 def test_readlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001431 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001432 self.readlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001433
Ezio Melottiafd0d112009-07-15 17:17:17 +00001434 def test_iterlines_stored(self):
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001435 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001436 self.iterlines_test(f, zipfile.ZIP_STORED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001437
Ezio Melotti975077a2011-05-19 22:03:22 +03001438 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +00001439 def test_read_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001440 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001441 self.read_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001442
Ezio Melotti975077a2011-05-19 22:03:22 +03001443 @requires_zlib
Antoine Pitroua32f9a22010-01-27 21:18:57 +00001444 def test_readline_read_deflated(self):
1445 # Issue #7610: calls to readline() interleaved with calls to read().
1446 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1447 self.readline_read_test(f, zipfile.ZIP_DEFLATED)
1448
Ezio Melotti975077a2011-05-19 22:03:22 +03001449 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +00001450 def test_readline_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001451 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001452 self.readline_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001453
Ezio Melotti975077a2011-05-19 22:03:22 +03001454 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +00001455 def test_readlines_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001456 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001457 self.readlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001458
Ezio Melotti975077a2011-05-19 22:03:22 +03001459 @requires_zlib
Ezio Melottiafd0d112009-07-15 17:17:17 +00001460 def test_iterlines_deflated(self):
Ezio Melotti76430242009-07-11 18:28:48 +00001461 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
Ezio Melottiafd0d112009-07-15 17:17:17 +00001462 self.iterlines_test(f, zipfile.ZIP_DEFLATED)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001463
1464 def tearDown(self):
1465 for sep, fn in self.arcfiles.items():
1466 os.remove(fn)
Ezio Melotti76430242009-07-11 18:28:48 +00001467 unlink(TESTFN)
1468 unlink(TESTFN2)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001469
1470
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001471def test_main():
Guido van Rossumd8faa362007-04-27 19:54:29 +00001472 run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
1473 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
Ezio Melotti76430242009-07-11 18:28:48 +00001474 TestWithDirectory, UniversalNewlineTests,
1475 TestsWithRandomBinaryFiles)
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001476
1477if __name__ == "__main__":
1478 test_main()