blob: 95d3536fa051c7371c6b13c684c082e14ca5b546 [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
Tim Petersa45cacf2004-08-20 03:47:14 +00006
Ezio Melottie7a0cc22009-07-04 14:58:27 +00007import os
Antoine Pitroue1436d12010-08-12 15:25:51 +00008import io
Ezio Melottie7a0cc22009-07-04 14:58:27 +00009import sys
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000010import time
Ezio Melottie7a0cc22009-07-04 14:58:27 +000011import struct
12import zipfile
13import unittest
Tim Petersa19a1682001-03-29 04:36:09 +000014
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000015from StringIO import StringIO
16from tempfile import TemporaryFile
Serhiy Storchaka45aa7712014-12-03 09:11:12 +020017from random import randint, random, getrandbits
Ezio Melottie7a0cc22009-07-04 14:58:27 +000018from unittest import skipUnless
Tim Petersa19a1682001-03-29 04:36:09 +000019
Serhiy Storchakadb03e6b2013-05-08 21:52:31 +030020from test.test_support import TESTFN, TESTFN_UNICODE, TESTFN_ENCODING, \
Benjamin Peterson352eb4f2014-04-03 10:31:25 -040021 run_unittest, findfile, unlink, rmtree, check_warnings
Serhiy Storchakadb03e6b2013-05-08 21:52:31 +030022try:
23 TESTFN_UNICODE.encode(TESTFN_ENCODING)
24except (UnicodeError, TypeError):
25 # Either the file system encoding is None, or the file name
26 # cannot be encoded in the file system encoding.
27 TESTFN_UNICODE = None
Guido van Rossum368f04a2000-04-10 13:23:04 +000028
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000029TESTFN2 = TESTFN + "2"
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +000030TESTFNDIR = TESTFN + "d"
Georg Brandl4b3ab6f2007-07-12 09:59:22 +000031FIXEDTEST_SIZE = 1000
Guido van Rossum368f04a2000-04-10 13:23:04 +000032
Georg Brandl62416bc2008-01-07 18:47:44 +000033SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'),
34 ('ziptest2dir/_ziptest2', 'qawsedrftg'),
Gregory P. Smith608cc452013-02-01 11:40:18 -080035 ('ziptest2dir/ziptest3dir/_ziptest3', 'azsxdcfvgb'),
Georg Brandl62416bc2008-01-07 18:47:44 +000036 ('ziptest2dir/ziptest3dir/ziptest4dir/_ziptest3', '6y7u8i9o0p')]
37
Serhiy Storchaka45aa7712014-12-03 09:11:12 +020038def getrandbytes(size):
39 return getrandbits(8 * size).to_bytes(size, 'little')
40
41def getrandbytes(size):
42 return bytes(bytearray.fromhex('%0*x' % (2 * size, getrandbits(8 * size))))
43
44def get_files(test):
45 yield TESTFN2
46 with TemporaryFile() as f:
47 yield f
48 test.assertFalse(f.closed)
49 with io.BytesIO() as f:
50 yield f
51 test.assertFalse(f.closed)
Ezio Melotti6cbfc122009-07-10 20:25:56 +000052
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000053class TestsWithSourceFile(unittest.TestCase):
54 def setUp(self):
Georg Brandl4b3ab6f2007-07-12 09:59:22 +000055 self.line_gen = ["Zipfile test line %d. random float: %f" % (i, random())
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000056 for i in xrange(FIXEDTEST_SIZE)]
Martin v. Löwis3eb76482007-03-06 10:41:24 +000057 self.data = '\n'.join(self.line_gen) + '\n'
Fred Drake6e7e4852001-02-28 05:34:16 +000058
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000059 # Make a source file with some lines
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000060 with open(TESTFN, "wb") as fp:
61 fp.write(self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000062
Ezio Melottid5a23e32009-07-15 17:07:04 +000063 def make_test_archive(self, f, compression):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000064 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +000065 with zipfile.ZipFile(f, "w", compression) as zipfp:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000066 zipfp.write(TESTFN, "another.name")
Ezio Melotti569e61f2009-12-30 06:14:51 +000067 zipfp.write(TESTFN, TESTFN)
68 zipfp.writestr("strfile", self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000069
Ezio Melottid5a23e32009-07-15 17:07:04 +000070 def zip_test(self, f, compression):
71 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +000072
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000073 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +000074 with zipfile.ZipFile(f, "r", compression) as zipfp:
75 self.assertEqual(zipfp.read(TESTFN), self.data)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000076 self.assertEqual(zipfp.read("another.name"), self.data)
Ezio Melotti569e61f2009-12-30 06:14:51 +000077 self.assertEqual(zipfp.read("strfile"), self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +000078
Ezio Melotti569e61f2009-12-30 06:14:51 +000079 # Print the ZIP directory
80 fp = StringIO()
81 stdout = sys.stdout
82 try:
83 sys.stdout = fp
84 zipfp.printdir()
85 finally:
86 sys.stdout = stdout
Tim Petersa608bb22006-06-15 18:06:29 +000087
Ezio Melotti569e61f2009-12-30 06:14:51 +000088 directory = fp.getvalue()
89 lines = directory.splitlines()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000090 self.assertEqual(len(lines), 4) # Number of files + header
Ronald Oussoren143cefb2006-06-15 08:14:18 +000091
Ezio Melottiaa980582010-01-23 23:04:36 +000092 self.assertIn('File Name', lines[0])
93 self.assertIn('Modified', lines[0])
94 self.assertIn('Size', lines[0])
Ronald Oussoren143cefb2006-06-15 08:14:18 +000095
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000096 fn, date, time_, size = lines[1].split()
97 self.assertEqual(fn, 'another.name')
98 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
99 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
100 self.assertEqual(size, str(len(self.data)))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000101
Ezio Melotti569e61f2009-12-30 06:14:51 +0000102 # Check the namelist
103 names = zipfp.namelist()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000104 self.assertEqual(len(names), 3)
Ezio Melottiaa980582010-01-23 23:04:36 +0000105 self.assertIn(TESTFN, names)
106 self.assertIn("another.name", names)
107 self.assertIn("strfile", names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000108
Ezio Melotti569e61f2009-12-30 06:14:51 +0000109 # Check infolist
110 infos = zipfp.infolist()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000111 names = [i.filename for i in infos]
112 self.assertEqual(len(names), 3)
Ezio Melottiaa980582010-01-23 23:04:36 +0000113 self.assertIn(TESTFN, names)
114 self.assertIn("another.name", names)
115 self.assertIn("strfile", names)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000116 for i in infos:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000117 self.assertEqual(i.file_size, len(self.data))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000118
Ezio Melotti569e61f2009-12-30 06:14:51 +0000119 # check getinfo
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000120 for nm in (TESTFN, "another.name", "strfile"):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000121 info = zipfp.getinfo(nm)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000122 self.assertEqual(info.filename, nm)
123 self.assertEqual(info.file_size, len(self.data))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000124
Ezio Melotti569e61f2009-12-30 06:14:51 +0000125 # Check that testzip doesn't raise an exception
126 zipfp.testzip()
Tim Peters7d3bad62001-04-04 18:56:49 +0000127
Ezio Melottid5a23e32009-07-15 17:07:04 +0000128 def test_stored(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000129 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000130 self.zip_test(f, zipfile.ZIP_STORED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000131
Ezio Melottid5a23e32009-07-15 17:07:04 +0000132 def zip_open_test(self, f, compression):
133 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000134
135 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000136 with zipfile.ZipFile(f, "r", compression) as zipfp:
137 zipdata1 = []
Brian Curtin0d654332011-04-19 21:15:55 -0500138 with zipfp.open(TESTFN) as zipopen1:
139 while True:
140 read_data = zipopen1.read(256)
141 if not read_data:
142 break
143 zipdata1.append(read_data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000144
Ezio Melotti569e61f2009-12-30 06:14:51 +0000145 zipdata2 = []
Brian Curtin0d654332011-04-19 21:15:55 -0500146 with zipfp.open("another.name") as zipopen2:
147 while True:
148 read_data = zipopen2.read(256)
149 if not read_data:
150 break
151 zipdata2.append(read_data)
Tim Petersea5962f2007-03-12 18:07:52 +0000152
Ezio Melotti569e61f2009-12-30 06:14:51 +0000153 self.assertEqual(''.join(zipdata1), self.data)
154 self.assertEqual(''.join(zipdata2), self.data)
Tim Petersea5962f2007-03-12 18:07:52 +0000155
Ezio Melottid5a23e32009-07-15 17:07:04 +0000156 def test_open_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000157 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000158 self.zip_open_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000159
Ezio Melottid5a23e32009-07-15 17:07:04 +0000160 def test_open_via_zip_info(self):
Georg Brandl112aa502008-05-20 08:25:48 +0000161 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000162 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
163 zipfp.writestr("name", "foo")
Serhiy Storchaka49259352014-01-20 21:57:09 +0200164 with check_warnings(('', UserWarning)):
165 zipfp.writestr("name", "bar")
166 self.assertEqual(zipfp.namelist(), ["name"] * 2)
Georg Brandl112aa502008-05-20 08:25:48 +0000167
Ezio Melotti569e61f2009-12-30 06:14:51 +0000168 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
169 infos = zipfp.infolist()
170 data = ""
171 for info in infos:
Brian Curtin0d654332011-04-19 21:15:55 -0500172 with zipfp.open(info) as f:
173 data += f.read()
Ezio Melotti569e61f2009-12-30 06:14:51 +0000174 self.assertTrue(data == "foobar" or data == "barfoo")
175 data = ""
176 for info in infos:
177 data += zipfp.read(info)
178 self.assertTrue(data == "foobar" or data == "barfoo")
Georg Brandl112aa502008-05-20 08:25:48 +0000179
Ezio Melottid5a23e32009-07-15 17:07:04 +0000180 def zip_random_open_test(self, f, compression):
181 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000182
183 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000184 with zipfile.ZipFile(f, "r", compression) as zipfp:
185 zipdata1 = []
Brian Curtin0d654332011-04-19 21:15:55 -0500186 with zipfp.open(TESTFN) as zipopen1:
187 while True:
188 read_data = zipopen1.read(randint(1, 1024))
189 if not read_data:
190 break
191 zipdata1.append(read_data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000192
Ezio Melotti569e61f2009-12-30 06:14:51 +0000193 self.assertEqual(''.join(zipdata1), self.data)
Tim Petersea5962f2007-03-12 18:07:52 +0000194
Ezio Melottid5a23e32009-07-15 17:07:04 +0000195 def test_random_open_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000196 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000197 self.zip_random_open_test(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +0000198
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000199 def test_univeral_readaheads(self):
200 f = StringIO()
201
202 data = 'a\r\n' * 16 * 1024
Brian Curtin0d654332011-04-19 21:15:55 -0500203 with zipfile.ZipFile(f, 'w', zipfile.ZIP_STORED) as zipfp:
204 zipfp.writestr(TESTFN, data)
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000205
206 data2 = ''
Brian Curtin0d654332011-04-19 21:15:55 -0500207 with zipfile.ZipFile(f, 'r') as zipfp:
208 with zipfp.open(TESTFN, 'rU') as zipopen:
209 for line in zipopen:
210 data2 += line
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000211
212 self.assertEqual(data, data2.replace('\n', '\r\n'))
213
214 def zip_readline_read_test(self, f, compression):
215 self.make_test_archive(f, compression)
216
217 # Read the ZIP archive
Brian Curtin0d654332011-04-19 21:15:55 -0500218 with zipfile.ZipFile(f, "r") as zipfp:
219 with zipfp.open(TESTFN) as zipopen:
220 data = ''
221 while True:
222 read = zipopen.readline()
223 if not read:
224 break
225 data += read
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000226
Brian Curtin0d654332011-04-19 21:15:55 -0500227 read = zipopen.read(100)
228 if not read:
229 break
230 data += read
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000231
232 self.assertEqual(data, self.data)
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000233
Ezio Melottid5a23e32009-07-15 17:07:04 +0000234 def zip_readline_test(self, f, compression):
235 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000236
237 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000238 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin0d654332011-04-19 21:15:55 -0500239 with zipfp.open(TESTFN) as zipopen:
240 for line in self.line_gen:
241 linedata = zipopen.readline()
242 self.assertEqual(linedata, line + '\n')
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000243
Ezio Melottid5a23e32009-07-15 17:07:04 +0000244 def zip_readlines_test(self, f, compression):
245 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000246
247 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000248 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin0d654332011-04-19 21:15:55 -0500249 with zipfp.open(TESTFN) as zo:
250 ziplines = zo.readlines()
251 for line, zipline in zip(self.line_gen, ziplines):
252 self.assertEqual(zipline, line + '\n')
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000253
Ezio Melottid5a23e32009-07-15 17:07:04 +0000254 def zip_iterlines_test(self, f, compression):
255 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000256
257 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000258 with zipfile.ZipFile(f, "r") as zipfp:
259 for line, zipline in zip(self.line_gen, zipfp.open(TESTFN)):
260 self.assertEqual(zipline, line + '\n')
Tim Petersea5962f2007-03-12 18:07:52 +0000261
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000262 def test_readline_read_stored(self):
263 # Issue #7610: calls to readline() interleaved with calls to read().
264 for f in (TESTFN2, TemporaryFile(), StringIO()):
265 self.zip_readline_read_test(f, zipfile.ZIP_STORED)
266
Ezio Melottid5a23e32009-07-15 17:07:04 +0000267 def test_readline_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000268 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000269 self.zip_readline_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000270
Ezio Melottid5a23e32009-07-15 17:07:04 +0000271 def test_readlines_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000272 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000273 self.zip_readlines_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000274
Ezio Melottid5a23e32009-07-15 17:07:04 +0000275 def test_iterlines_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000276 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000277 self.zip_iterlines_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000278
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000279 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000280 def test_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000281 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000282 self.zip_test(f, zipfile.ZIP_DEFLATED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000283
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000284 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000285 def test_open_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000286 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000287 self.zip_open_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000288
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000289 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000290 def test_random_open_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000291 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000292 self.zip_random_open_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000293
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000294 @skipUnless(zlib, "requires zlib")
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000295 def test_readline_read_deflated(self):
296 # Issue #7610: calls to readline() interleaved with calls to read().
297 for f in (TESTFN2, TemporaryFile(), StringIO()):
298 self.zip_readline_read_test(f, zipfile.ZIP_DEFLATED)
299
300 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000301 def test_readline_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000302 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000303 self.zip_readline_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000304
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000305 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000306 def test_readlines_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000307 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000308 self.zip_readlines_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000309
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000310 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000311 def test_iterlines_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000312 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000313 self.zip_iterlines_test(f, zipfile.ZIP_DEFLATED)
Tim Petersea5962f2007-03-12 18:07:52 +0000314
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000315 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000316 def test_low_compression(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000317 """Check for cases where compressed data is larger than original."""
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000318 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000319 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
320 zipfp.writestr("strfile", '12')
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000321
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000322 # Get an open object for strfile
Ezio Melotti569e61f2009-12-30 06:14:51 +0000323 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_DEFLATED) as zipfp:
Brian Curtin0d654332011-04-19 21:15:55 -0500324 with zipfp.open("strfile") as openobj:
325 self.assertEqual(openobj.read(1), '1')
326 self.assertEqual(openobj.read(1), '2')
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000327
Ezio Melottid5a23e32009-07-15 17:07:04 +0000328 def test_absolute_arcnames(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000329 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
330 zipfp.write(TESTFN, "/absolute")
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000331
Ezio Melotti569e61f2009-12-30 06:14:51 +0000332 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
333 self.assertEqual(zipfp.namelist(), ["absolute"])
Tim Peters32cbc962006-02-20 21:42:18 +0000334
Ezio Melottid5a23e32009-07-15 17:07:04 +0000335 def test_append_to_zip_file(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000336 """Test appending to an existing zipfile."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000337 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
338 zipfp.write(TESTFN, TESTFN)
339
340 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
341 zipfp.writestr("strfile", self.data)
342 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000343
Ezio Melottid5a23e32009-07-15 17:07:04 +0000344 def test_append_to_non_zip_file(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000345 """Test appending to an existing file that is not a zipfile."""
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000346 # NOTE: this test fails if len(d) < 22 because of the first
347 # line "fpin.seek(-22, 2)" in _EndRecData
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000348 data = 'I am not a ZipFile!'*10
349 with open(TESTFN2, 'wb') as f:
350 f.write(data)
351
Ezio Melotti569e61f2009-12-30 06:14:51 +0000352 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
353 zipfp.write(TESTFN, TESTFN)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000354
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000355 with open(TESTFN2, 'rb') as f:
356 f.seek(len(data))
357 with zipfile.ZipFile(f, "r") as zipfp:
358 self.assertEqual(zipfp.namelist(), [TESTFN])
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000359
R David Murray873c5832011-06-09 16:01:09 -0400360 def test_ignores_newline_at_end(self):
361 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
362 zipfp.write(TESTFN, TESTFN)
363 with open(TESTFN2, 'a') as f:
364 f.write("\r\n\00\00\00")
365 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
366 self.assertIsInstance(zipfp, zipfile.ZipFile)
367
368 def test_ignores_stuff_appended_past_comments(self):
369 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
370 zipfp.comment = b"this is a comment"
371 zipfp.write(TESTFN, TESTFN)
372 with open(TESTFN2, 'a') as f:
373 f.write("abcdef\r\n")
374 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
375 self.assertIsInstance(zipfp, zipfile.ZipFile)
376 self.assertEqual(zipfp.comment, b"this is a comment")
377
Ezio Melottid5a23e32009-07-15 17:07:04 +0000378 def test_write_default_name(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000379 """Check that calling ZipFile.write without arcname specified
380 produces the expected result."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000381 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
382 zipfp.write(TESTFN)
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400383 with open(TESTFN,'r') as fid:
384 self.assertEqual(zipfp.read(TESTFN), fid.read())
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000385
Ezio Melotti1036a7f2009-09-12 14:43:43 +0000386 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000387 def test_per_file_compression(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000388 """Check that files within a Zip archive can have different
389 compression options."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000390 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
391 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
392 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
393 sinfo = zipfp.getinfo('storeme')
394 dinfo = zipfp.getinfo('deflateme')
395 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
396 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000397
Ezio Melottid5a23e32009-07-15 17:07:04 +0000398 def test_write_to_readonly(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000399 """Check that trying to call write() on a readonly ZipFile object
400 raises a RuntimeError."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000401 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
402 zipfp.writestr("somefile.txt", "bogus")
403
404 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
405 self.assertRaises(RuntimeError, zipfp.write, TESTFN)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000406
Ezio Melottid5a23e32009-07-15 17:07:04 +0000407 def test_extract(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000408 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
409 for fpath, fdata in SMALL_TEST_DATA:
410 zipfp.writestr(fpath, fdata)
Georg Brandl62416bc2008-01-07 18:47:44 +0000411
Ezio Melotti569e61f2009-12-30 06:14:51 +0000412 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
413 for fpath, fdata in SMALL_TEST_DATA:
414 writtenfile = zipfp.extract(fpath)
Georg Brandl62416bc2008-01-07 18:47:44 +0000415
Ezio Melotti569e61f2009-12-30 06:14:51 +0000416 # make sure it was written to the right place
Gregory P. Smith608cc452013-02-01 11:40:18 -0800417 correctfile = os.path.join(os.getcwd(), fpath)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000418 correctfile = os.path.normpath(correctfile)
Georg Brandl62416bc2008-01-07 18:47:44 +0000419
Ezio Melotti569e61f2009-12-30 06:14:51 +0000420 self.assertEqual(writtenfile, correctfile)
Georg Brandl62416bc2008-01-07 18:47:44 +0000421
Ezio Melotti569e61f2009-12-30 06:14:51 +0000422 # make sure correct data is in correct file
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400423 with open(writtenfile, "rb") as fid:
424 self.assertEqual(fdata, fid.read())
Ezio Melotti569e61f2009-12-30 06:14:51 +0000425 os.remove(writtenfile)
Georg Brandl62416bc2008-01-07 18:47:44 +0000426
427 # remove the test file subdirectories
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400428 rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
Georg Brandl62416bc2008-01-07 18:47:44 +0000429
Ezio Melottid5a23e32009-07-15 17:07:04 +0000430 def test_extract_all(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000431 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
432 for fpath, fdata in SMALL_TEST_DATA:
433 zipfp.writestr(fpath, fdata)
Georg Brandl62416bc2008-01-07 18:47:44 +0000434
Ezio Melotti569e61f2009-12-30 06:14:51 +0000435 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
436 zipfp.extractall()
437 for fpath, fdata in SMALL_TEST_DATA:
Gregory P. Smith608cc452013-02-01 11:40:18 -0800438 outfile = os.path.join(os.getcwd(), fpath)
Georg Brandl62416bc2008-01-07 18:47:44 +0000439
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400440 with open(outfile, "rb") as fid:
441 self.assertEqual(fdata, fid.read())
Ezio Melotti569e61f2009-12-30 06:14:51 +0000442 os.remove(outfile)
Georg Brandl62416bc2008-01-07 18:47:44 +0000443
444 # remove the test file subdirectories
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400445 rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
Georg Brandl62416bc2008-01-07 18:47:44 +0000446
Gregory P. Smith608cc452013-02-01 11:40:18 -0800447 def check_file(self, filename, content):
448 self.assertTrue(os.path.isfile(filename))
449 with open(filename, 'rb') as f:
450 self.assertEqual(f.read(), content)
451
Serhiy Storchakadb03e6b2013-05-08 21:52:31 +0300452 @skipUnless(TESTFN_UNICODE, "No Unicode filesystem semantics on this platform.")
Serhiy Storchaka6fa83f92013-04-13 12:28:17 +0300453 def test_extract_unicode_filenames(self):
454 fnames = [u'foo.txt', os.path.basename(TESTFN_UNICODE)]
455 content = 'Test for unicode filename'
456 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
457 for fname in fnames:
458 zipfp.writestr(fname, content)
459
460 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
461 for fname in fnames:
462 writtenfile = zipfp.extract(fname)
463
464 # make sure it was written to the right place
465 correctfile = os.path.join(os.getcwd(), fname)
466 correctfile = os.path.normpath(correctfile)
467 self.assertEqual(writtenfile, correctfile)
468
469 self.check_file(writtenfile, content)
470 os.remove(writtenfile)
471
Gregory P. Smith608cc452013-02-01 11:40:18 -0800472 def test_extract_hackers_arcnames(self):
473 hacknames = [
474 ('../foo/bar', 'foo/bar'),
475 ('foo/../bar', 'foo/bar'),
476 ('foo/../../bar', 'foo/bar'),
477 ('foo/bar/..', 'foo/bar'),
478 ('./../foo/bar', 'foo/bar'),
479 ('/foo/bar', 'foo/bar'),
480 ('/foo/../bar', 'foo/bar'),
481 ('/foo/../../bar', 'foo/bar'),
Gregory P. Smith608cc452013-02-01 11:40:18 -0800482 ]
483 if os.path.sep == '\\':
484 hacknames.extend([
485 (r'..\foo\bar', 'foo/bar'),
486 (r'..\/foo\/bar', 'foo/bar'),
487 (r'foo/\..\/bar', 'foo/bar'),
488 (r'foo\/../\bar', 'foo/bar'),
489 (r'C:foo/bar', 'foo/bar'),
490 (r'C:/foo/bar', 'foo/bar'),
491 (r'C://foo/bar', 'foo/bar'),
492 (r'C:\foo\bar', 'foo/bar'),
Benjamin Petersonc4597552014-06-22 20:26:07 -0700493 (r'//conky/mountpoint/foo/bar', 'foo/bar'),
494 (r'\\conky\mountpoint\foo\bar', 'foo/bar'),
Gregory P. Smith608cc452013-02-01 11:40:18 -0800495 (r'///conky/mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
496 (r'\\\conky\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
497 (r'//conky//mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
498 (r'\\conky\\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
Benjamin Petersonc4597552014-06-22 20:26:07 -0700499 (r'//?/C:/foo/bar', 'foo/bar'),
500 (r'\\?\C:\foo\bar', 'foo/bar'),
Gregory P. Smith608cc452013-02-01 11:40:18 -0800501 (r'C:/../C:/foo/bar', 'C_/foo/bar'),
502 (r'a:b\c<d>e|f"g?h*i', 'b/c_d_e_f_g_h_i'),
Serhiy Storchaka13e56c72013-02-02 17:46:33 +0200503 ('../../foo../../ba..r', 'foo/ba..r'),
504 ])
505 else: # Unix
506 hacknames.extend([
507 ('//foo/bar', 'foo/bar'),
508 ('../../foo../../ba..r', 'foo../ba..r'),
Serhiy Storchaka05fd7442013-02-02 18:34:57 +0200509 (r'foo/..\bar', r'foo/..\bar'),
Gregory P. Smith608cc452013-02-01 11:40:18 -0800510 ])
511
512 for arcname, fixedname in hacknames:
513 content = b'foobar' + arcname.encode()
514 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipfp:
Serhiy Storchaka05fd7442013-02-02 18:34:57 +0200515 zinfo = zipfile.ZipInfo()
516 # preserve backslashes
517 zinfo.filename = arcname
518 zinfo.external_attr = 0o600 << 16
519 zipfp.writestr(zinfo, content)
Gregory P. Smith608cc452013-02-01 11:40:18 -0800520
Serhiy Storchaka2a051fa2013-02-02 19:25:57 +0200521 arcname = arcname.replace(os.sep, "/")
Gregory P. Smith608cc452013-02-01 11:40:18 -0800522 targetpath = os.path.join('target', 'subdir', 'subsub')
523 correctfile = os.path.join(targetpath, *fixedname.split('/'))
524
525 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
526 writtenfile = zipfp.extract(arcname, targetpath)
Serhiy Storchaka13e56c72013-02-02 17:46:33 +0200527 self.assertEqual(writtenfile, correctfile,
528 msg="extract %r" % arcname)
Gregory P. Smith608cc452013-02-01 11:40:18 -0800529 self.check_file(correctfile, content)
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400530 rmtree('target')
Gregory P. Smith608cc452013-02-01 11:40:18 -0800531
532 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
533 zipfp.extractall(targetpath)
534 self.check_file(correctfile, content)
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400535 rmtree('target')
Gregory P. Smith608cc452013-02-01 11:40:18 -0800536
537 correctfile = os.path.join(os.getcwd(), *fixedname.split('/'))
538
539 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
540 writtenfile = zipfp.extract(arcname)
Serhiy Storchaka13e56c72013-02-02 17:46:33 +0200541 self.assertEqual(writtenfile, correctfile,
542 msg="extract %r" % arcname)
Gregory P. Smith608cc452013-02-01 11:40:18 -0800543 self.check_file(correctfile, content)
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400544 rmtree(fixedname.split('/')[0])
Gregory P. Smith608cc452013-02-01 11:40:18 -0800545
546 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
547 zipfp.extractall()
548 self.check_file(correctfile, content)
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400549 rmtree(fixedname.split('/')[0])
Gregory P. Smith608cc452013-02-01 11:40:18 -0800550
551 os.remove(TESTFN2)
552
Ronald Oussorendd25e862010-02-07 20:18:02 +0000553 def test_writestr_compression(self):
554 zipfp = zipfile.ZipFile(TESTFN2, "w")
555 zipfp.writestr("a.txt", "hello world", compress_type=zipfile.ZIP_STORED)
556 if zlib:
557 zipfp.writestr("b.txt", "hello world", compress_type=zipfile.ZIP_DEFLATED)
558
559 info = zipfp.getinfo('a.txt')
560 self.assertEqual(info.compress_type, zipfile.ZIP_STORED)
561
562 if zlib:
563 info = zipfp.getinfo('b.txt')
564 self.assertEqual(info.compress_type, zipfile.ZIP_DEFLATED)
565
566
Antoine Pitrou5fdfa3e2008-07-25 19:42:26 +0000567 def zip_test_writestr_permissions(self, f, compression):
568 # Make sure that writestr creates files with mode 0600,
569 # when it is passed a name rather than a ZipInfo instance.
570
Ezio Melottid5a23e32009-07-15 17:07:04 +0000571 self.make_test_archive(f, compression)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000572 with zipfile.ZipFile(f, "r") as zipfp:
573 zinfo = zipfp.getinfo('strfile')
574 self.assertEqual(zinfo.external_attr, 0600 << 16)
Antoine Pitrou5fdfa3e2008-07-25 19:42:26 +0000575
Ezio Melottid5a23e32009-07-15 17:07:04 +0000576 def test_writestr_permissions(self):
Antoine Pitrou5fdfa3e2008-07-25 19:42:26 +0000577 for f in (TESTFN2, TemporaryFile(), StringIO()):
578 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
579
Ezio Melotti569e61f2009-12-30 06:14:51 +0000580 def test_close(self):
581 """Check that the zipfile is closed after the 'with' block."""
582 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
583 for fpath, fdata in SMALL_TEST_DATA:
584 zipfp.writestr(fpath, fdata)
585 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
586 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
587
588 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
589 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
590 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
591
592 def test_close_on_exception(self):
593 """Check that the zipfile is closed if an exception is raised in the
594 'with' block."""
595 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
596 for fpath, fdata in SMALL_TEST_DATA:
597 zipfp.writestr(fpath, fdata)
598
599 try:
600 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
601 raise zipfile.BadZipfile()
602 except zipfile.BadZipfile:
603 self.assertTrue(zipfp2.fp is None, 'zipfp is not closed')
604
Senthil Kumaranddd40312011-10-20 01:38:35 +0800605 def test_add_file_before_1980(self):
606 # Set atime and mtime to 1970-01-01
607 os.utime(TESTFN, (0, 0))
608 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
609 self.assertRaises(ValueError, zipfp.write, TESTFN)
610
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000611 def tearDown(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000612 unlink(TESTFN)
613 unlink(TESTFN2)
614
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000615
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000616class TestZip64InSmallFiles(unittest.TestCase):
617 # These tests test the ZIP64 functionality without using large files,
618 # see test_zipfile64 for proper tests.
619
620 def setUp(self):
621 self._limit = zipfile.ZIP64_LIMIT
Serhiy Storchaka1af262c2014-09-23 22:26:45 +0300622 self._filecount_limit = zipfile.ZIP_FILECOUNT_LIMIT
623 zipfile.ZIP64_LIMIT = 1000
624 zipfile.ZIP_FILECOUNT_LIMIT = 9
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000625
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000626 line_gen = ("Test of zipfile line %d." % i
627 for i in range(0, FIXEDTEST_SIZE))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000628 self.data = '\n'.join(line_gen)
629
630 # Make a source file with some lines
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000631 with open(TESTFN, "wb") as fp:
632 fp.write(self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000633
Ezio Melottid5a23e32009-07-15 17:07:04 +0000634 def large_file_exception_test(self, f, compression):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000635 with zipfile.ZipFile(f, "w", compression) as zipfp:
636 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000637 zipfp.write, TESTFN, "another.name")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000638
Ezio Melottid5a23e32009-07-15 17:07:04 +0000639 def large_file_exception_test2(self, f, compression):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000640 with zipfile.ZipFile(f, "w", compression) as zipfp:
641 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000642 zipfp.writestr, "another.name", self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000643
Ezio Melottid5a23e32009-07-15 17:07:04 +0000644 def test_large_file_exception(self):
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000645 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000646 self.large_file_exception_test(f, zipfile.ZIP_STORED)
647 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000648
Ezio Melottid5a23e32009-07-15 17:07:04 +0000649 def zip_test(self, f, compression):
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000650 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000651 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000652 zipfp.write(TESTFN, "another.name")
Ezio Melotti569e61f2009-12-30 06:14:51 +0000653 zipfp.write(TESTFN, TESTFN)
654 zipfp.writestr("strfile", self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000655
656 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000657 with zipfile.ZipFile(f, "r", compression) as zipfp:
658 self.assertEqual(zipfp.read(TESTFN), self.data)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000659 self.assertEqual(zipfp.read("another.name"), self.data)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000660 self.assertEqual(zipfp.read("strfile"), self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000661
Ezio Melotti569e61f2009-12-30 06:14:51 +0000662 # Print the ZIP directory
663 fp = StringIO()
664 stdout = sys.stdout
665 try:
666 sys.stdout = fp
667 zipfp.printdir()
668 finally:
669 sys.stdout = stdout
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000670
Ezio Melotti569e61f2009-12-30 06:14:51 +0000671 directory = fp.getvalue()
672 lines = directory.splitlines()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000673 self.assertEqual(len(lines), 4) # Number of files + header
Tim Petersa608bb22006-06-15 18:06:29 +0000674
Ezio Melottiaa980582010-01-23 23:04:36 +0000675 self.assertIn('File Name', lines[0])
676 self.assertIn('Modified', lines[0])
677 self.assertIn('Size', lines[0])
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000678
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000679 fn, date, time_, size = lines[1].split()
680 self.assertEqual(fn, 'another.name')
681 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
682 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
683 self.assertEqual(size, str(len(self.data)))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000684
Ezio Melotti569e61f2009-12-30 06:14:51 +0000685 # Check the namelist
686 names = zipfp.namelist()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000687 self.assertEqual(len(names), 3)
Ezio Melottiaa980582010-01-23 23:04:36 +0000688 self.assertIn(TESTFN, names)
689 self.assertIn("another.name", names)
690 self.assertIn("strfile", names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000691
Ezio Melotti569e61f2009-12-30 06:14:51 +0000692 # Check infolist
693 infos = zipfp.infolist()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000694 names = [i.filename for i in infos]
695 self.assertEqual(len(names), 3)
Ezio Melottiaa980582010-01-23 23:04:36 +0000696 self.assertIn(TESTFN, names)
697 self.assertIn("another.name", names)
698 self.assertIn("strfile", names)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000699 for i in infos:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000700 self.assertEqual(i.file_size, len(self.data))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000701
Ezio Melotti569e61f2009-12-30 06:14:51 +0000702 # check getinfo
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000703 for nm in (TESTFN, "another.name", "strfile"):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000704 info = zipfp.getinfo(nm)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000705 self.assertEqual(info.filename, nm)
706 self.assertEqual(info.file_size, len(self.data))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000707
Ezio Melotti569e61f2009-12-30 06:14:51 +0000708 # Check that testzip doesn't raise an exception
709 zipfp.testzip()
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000710
Ezio Melottid5a23e32009-07-15 17:07:04 +0000711 def test_stored(self):
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000712 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000713 self.zip_test(f, zipfile.ZIP_STORED)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000714
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000715 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000716 def test_deflated(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000717 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000718 self.zip_test(f, zipfile.ZIP_DEFLATED)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000719
Ezio Melottid5a23e32009-07-15 17:07:04 +0000720 def test_absolute_arcnames(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000721 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
722 allowZip64=True) as zipfp:
723 zipfp.write(TESTFN, "/absolute")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000724
Ezio Melotti569e61f2009-12-30 06:14:51 +0000725 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
726 self.assertEqual(zipfp.namelist(), ["absolute"])
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000727
Serhiy Storchaka1af262c2014-09-23 22:26:45 +0300728 def test_too_many_files(self):
729 # This test checks that more than 64k files can be added to an archive,
730 # and that the resulting archive can be read properly by ZipFile
731 zipf = zipfile.ZipFile(TESTFN, mode="w", allowZip64=True)
732 zipf.debug = 100
733 numfiles = 15
734 for i in range(numfiles):
735 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
736 self.assertEqual(len(zipf.namelist()), numfiles)
737 zipf.close()
738
739 zipf2 = zipfile.ZipFile(TESTFN, mode="r")
740 self.assertEqual(len(zipf2.namelist()), numfiles)
741 for i in range(numfiles):
742 content = zipf2.read("foo%08d" % i)
743 self.assertEqual(content, "%d" % (i**3 % 57))
744 zipf2.close()
745
746 def test_too_many_files_append(self):
747 zipf = zipfile.ZipFile(TESTFN, mode="w", allowZip64=False)
748 zipf.debug = 100
749 numfiles = 9
750 for i in range(numfiles):
751 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
752 self.assertEqual(len(zipf.namelist()), numfiles)
753 with self.assertRaises(zipfile.LargeZipFile):
754 zipf.writestr("foo%08d" % numfiles, b'')
755 self.assertEqual(len(zipf.namelist()), numfiles)
756 zipf.close()
757
758 zipf = zipfile.ZipFile(TESTFN, mode="a", allowZip64=False)
759 zipf.debug = 100
760 self.assertEqual(len(zipf.namelist()), numfiles)
761 with self.assertRaises(zipfile.LargeZipFile):
762 zipf.writestr("foo%08d" % numfiles, b'')
763 self.assertEqual(len(zipf.namelist()), numfiles)
764 zipf.close()
765
766 zipf = zipfile.ZipFile(TESTFN, mode="a", allowZip64=True)
767 zipf.debug = 100
768 self.assertEqual(len(zipf.namelist()), numfiles)
769 numfiles2 = 15
770 for i in range(numfiles, numfiles2):
771 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
772 self.assertEqual(len(zipf.namelist()), numfiles2)
773 zipf.close()
774
775 zipf2 = zipfile.ZipFile(TESTFN, mode="r")
776 self.assertEqual(len(zipf2.namelist()), numfiles2)
777 for i in range(numfiles2):
778 content = zipf2.read("foo%08d" % i)
779 self.assertEqual(content, "%d" % (i**3 % 57))
780 zipf2.close()
781
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000782 def tearDown(self):
783 zipfile.ZIP64_LIMIT = self._limit
Serhiy Storchaka1af262c2014-09-23 22:26:45 +0300784 zipfile.ZIP_FILECOUNT_LIMIT = self._filecount_limit
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000785 unlink(TESTFN)
786 unlink(TESTFN2)
787
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000788
789class PyZipFileTests(unittest.TestCase):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000790 def test_write_pyfile(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000791 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
792 fn = __file__
793 if fn.endswith('.pyc') or fn.endswith('.pyo'):
794 fn = fn[:-1]
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000795
Ezio Melotti569e61f2009-12-30 06:14:51 +0000796 zipfp.writepy(fn)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000797
Ezio Melotti569e61f2009-12-30 06:14:51 +0000798 bn = os.path.basename(fn)
Ezio Melottiaa980582010-01-23 23:04:36 +0000799 self.assertNotIn(bn, zipfp.namelist())
Ezio Melotti569e61f2009-12-30 06:14:51 +0000800 self.assertTrue(bn + 'o' in zipfp.namelist() or
801 bn + 'c' in zipfp.namelist())
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000802
Ezio Melotti569e61f2009-12-30 06:14:51 +0000803 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
804 fn = __file__
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000805 if fn.endswith(('.pyc', '.pyo')):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000806 fn = fn[:-1]
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000807
Ezio Melotti569e61f2009-12-30 06:14:51 +0000808 zipfp.writepy(fn, "testpackage")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000809
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000810 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
Ezio Melottiaa980582010-01-23 23:04:36 +0000811 self.assertNotIn(bn, zipfp.namelist())
Ezio Melotti569e61f2009-12-30 06:14:51 +0000812 self.assertTrue(bn + 'o' in zipfp.namelist() or
813 bn + 'c' in zipfp.namelist())
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000814
Ezio Melottid5a23e32009-07-15 17:07:04 +0000815 def test_write_python_package(self):
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000816 import email
817 packagedir = os.path.dirname(email.__file__)
818
Ezio Melotti569e61f2009-12-30 06:14:51 +0000819 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
820 zipfp.writepy(packagedir)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000821
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000822 # Check for a couple of modules at different levels of the
823 # hierarchy
Ezio Melotti569e61f2009-12-30 06:14:51 +0000824 names = zipfp.namelist()
825 self.assertTrue('email/__init__.pyo' in names or
826 'email/__init__.pyc' in names)
827 self.assertTrue('email/mime/text.pyo' in names or
828 'email/mime/text.pyc' in names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000829
Ezio Melottid5a23e32009-07-15 17:07:04 +0000830 def test_write_python_directory(self):
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000831 os.mkdir(TESTFN2)
832 try:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000833 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
Ezio Melotti763f1e82009-12-31 13:27:41 +0000834 fp.write("print(42)\n")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000835
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000836 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
Ezio Melotti763f1e82009-12-31 13:27:41 +0000837 fp.write("print(42 * 42)\n")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000838
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000839 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
840 fp.write("bla bla bla\n")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000841
842 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
843 zipfp.writepy(TESTFN2)
844
845 names = zipfp.namelist()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000846 self.assertTrue('mod1.pyc' in names or 'mod1.pyo' in names)
847 self.assertTrue('mod2.pyc' in names or 'mod2.pyo' in names)
Ezio Melottiaa980582010-01-23 23:04:36 +0000848 self.assertNotIn('mod2.txt', names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000849
850 finally:
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400851 rmtree(TESTFN2)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000852
Ezio Melottid5a23e32009-07-15 17:07:04 +0000853 def test_write_non_pyfile(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000854 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400855 with open(TESTFN, 'w') as fid:
856 fid.write('most definitely not a python file')
Ezio Melotti569e61f2009-12-30 06:14:51 +0000857 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
858 os.remove(TESTFN)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000859
860
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000861class OtherTests(unittest.TestCase):
Antoine Pitroue1436d12010-08-12 15:25:51 +0000862 zips_with_bad_crc = {
863 zipfile.ZIP_STORED: (
864 b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
865 b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
866 b'ilehello,AworldP'
867 b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
868 b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
869 b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
870 b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
871 b'\0\0/\0\0\0\0\0'),
872 zipfile.ZIP_DEFLATED: (
873 b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
874 b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
875 b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
876 b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
877 b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
878 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
879 b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
880 b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00'),
881 }
882
Ezio Melottid5a23e32009-07-15 17:07:04 +0000883 def test_unicode_filenames(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000884 with zipfile.ZipFile(TESTFN, "w") as zf:
885 zf.writestr(u"foo.txt", "Test for unicode filename")
886 zf.writestr(u"\xf6.txt", "Test for unicode filename")
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000887 self.assertIsInstance(zf.infolist()[0].filename, unicode)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000888
889 with zipfile.ZipFile(TESTFN, "r") as zf:
890 self.assertEqual(zf.filelist[0].filename, "foo.txt")
891 self.assertEqual(zf.filelist[1].filename, u"\xf6.txt")
Martin v. Löwis471617d2008-05-05 17:16:58 +0000892
Ezio Melottid5a23e32009-07-15 17:07:04 +0000893 def test_create_non_existent_file_for_append(self):
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000894 if os.path.exists(TESTFN):
895 os.unlink(TESTFN)
Tim Petersea5962f2007-03-12 18:07:52 +0000896
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000897 filename = 'testfile.txt'
898 content = 'hello, world. this is some content.'
Tim Petersea5962f2007-03-12 18:07:52 +0000899
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000900 try:
Ezio Melotti569e61f2009-12-30 06:14:51 +0000901 with zipfile.ZipFile(TESTFN, 'a') as zf:
902 zf.writestr(filename, content)
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000903 except IOError:
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000904 self.fail('Could not append data to a non-existent zip file.')
905
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000906 self.assertTrue(os.path.exists(TESTFN))
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000907
Ezio Melotti569e61f2009-12-30 06:14:51 +0000908 with zipfile.ZipFile(TESTFN, 'r') as zf:
909 self.assertEqual(zf.read(filename), content)
Tim Petersea5962f2007-03-12 18:07:52 +0000910
Ezio Melottid5a23e32009-07-15 17:07:04 +0000911 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000912 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000913 # it opens if there's an error in the file. If it doesn't, the
914 # traceback holds a reference to the ZipFile object and, indirectly,
915 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000916 # On Windows, this causes the os.unlink() call to fail because the
917 # underlying file is still open. This is SF bug #412214.
918 #
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000919 with open(TESTFN, "w") as fp:
920 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000921 try:
922 zf = zipfile.ZipFile(TESTFN)
923 except zipfile.BadZipfile:
Collin Winter04a51ec2007-03-29 02:28:16 +0000924 pass
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000925
Ezio Melottid5a23e32009-07-15 17:07:04 +0000926 def test_is_zip_erroneous_file(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000927 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000928 # - passing a filename
929 with open(TESTFN, "w") as fp:
930 fp.write("this is not a legal zip file\n")
Tim Petersea5962f2007-03-12 18:07:52 +0000931 chk = zipfile.is_zipfile(TESTFN)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000932 self.assertFalse(chk)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000933 # - passing a file object
934 with open(TESTFN, "rb") as fp:
935 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000936 self.assertTrue(not chk)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000937 # - passing a file-like object
938 fp = StringIO()
939 fp.write("this is not a legal zip file\n")
940 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000941 self.assertTrue(not chk)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000942 fp.seek(0, 0)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000943 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000944 self.assertTrue(not chk)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000945
Serhiy Storchaka0be506a2013-01-31 15:26:55 +0200946 def test_damaged_zipfile(self):
947 """Check that zipfiles with missing bytes at the end raise BadZipFile."""
948 # - Create a valid zip file
949 fp = io.BytesIO()
950 with zipfile.ZipFile(fp, mode="w") as zipf:
951 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
952 zipfiledata = fp.getvalue()
953
954 # - Now create copies of it missing the last N bytes and make sure
955 # a BadZipFile exception is raised when we try to open it
956 for N in range(len(zipfiledata)):
957 fp = io.BytesIO(zipfiledata[:N])
958 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, fp)
959
Ezio Melottid5a23e32009-07-15 17:07:04 +0000960 def test_is_zip_valid_file(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000961 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000962 # - passing a filename
Ezio Melotti569e61f2009-12-30 06:14:51 +0000963 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
964 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Tim Petersea5962f2007-03-12 18:07:52 +0000965 chk = zipfile.is_zipfile(TESTFN)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000966 self.assertTrue(chk)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000967 # - passing a file object
968 with open(TESTFN, "rb") as fp:
969 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000970 self.assertTrue(chk)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000971 fp.seek(0, 0)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000972 zip_contents = fp.read()
973 # - passing a file-like object
974 fp = StringIO()
975 fp.write(zip_contents)
976 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000977 self.assertTrue(chk)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000978 fp.seek(0, 0)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000979 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000980 self.assertTrue(chk)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000981
Ezio Melottid5a23e32009-07-15 17:07:04 +0000982 def test_non_existent_file_raises_IOError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000983 # make sure we don't raise an AttributeError when a partially-constructed
984 # ZipFile instance is finalized; this tests for regression on SF tracker
985 # bug #403871.
986
987 # The bug we're testing for caused an AttributeError to be raised
988 # when a ZipFile instance was created for a file that did not
989 # exist; the .fp member was not initialized but was needed by the
990 # __del__() method. Since the AttributeError is in the __del__(),
991 # it is ignored, but the user should be sufficiently annoyed by
992 # the message on the output that regression will be noticed
993 # quickly.
994 self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
995
Amaury Forgeot d'Arc3e5b0272009-07-28 22:15:30 +0000996 def test_empty_file_raises_BadZipFile(self):
Brian Curtin0d654332011-04-19 21:15:55 -0500997 with open(TESTFN, 'w') as f:
998 pass
Amaury Forgeot d'Arc3e5b0272009-07-28 22:15:30 +0000999 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN)
1000
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001001 with open(TESTFN, 'w') as fp:
1002 fp.write("short file")
Amaury Forgeot d'Arc3e5b0272009-07-28 22:15:30 +00001003 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN)
1004
Ezio Melottid5a23e32009-07-15 17:07:04 +00001005 def test_closed_zip_raises_RuntimeError(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001006 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001007 data = StringIO()
Ezio Melotti569e61f2009-12-30 06:14:51 +00001008 with zipfile.ZipFile(data, mode="w") as zipf:
1009 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001010
Andrew Svetlov4bb142b2012-12-18 21:27:37 +02001011 # This is correct; calling .read on a closed ZipFile should raise
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001012 # a RuntimeError, and so should calling .testzip. An earlier
1013 # version of .testzip would swallow this exception (and any other)
1014 # and report that the first file in the archive was corrupt.
Georg Brandl4b3ab6f2007-07-12 09:59:22 +00001015 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
1016 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001017 self.assertRaises(RuntimeError, zipf.testzip)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +00001018 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Benjamin Peterson352eb4f2014-04-03 10:31:25 -04001019 with open(TESTFN, 'w') as fid:
1020 fid.write('zipfile test data')
1021 self.assertRaises(RuntimeError, zipf.write, TESTFN)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +00001022
Ezio Melottid5a23e32009-07-15 17:07:04 +00001023 def test_bad_constructor_mode(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001024 """Check that bad modes passed to ZipFile constructor are caught."""
Georg Brandl4b3ab6f2007-07-12 09:59:22 +00001025 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
1026
Ezio Melottid5a23e32009-07-15 17:07:04 +00001027 def test_bad_open_mode(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001028 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melotti569e61f2009-12-30 06:14:51 +00001029 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1030 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1031
1032 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Georg Brandl4b3ab6f2007-07-12 09:59:22 +00001033 # read the data to make sure the file is there
Ezio Melotti569e61f2009-12-30 06:14:51 +00001034 zipf.read("foo.txt")
1035 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
Georg Brandl4b3ab6f2007-07-12 09:59:22 +00001036
Ezio Melottid5a23e32009-07-15 17:07:04 +00001037 def test_read0(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001038 """Check that calling read(0) on a ZipExtFile object returns an empty
1039 string and doesn't advance file pointer."""
Ezio Melotti569e61f2009-12-30 06:14:51 +00001040 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1041 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1042 # read the data to make sure the file is there
Brian Curtin0d654332011-04-19 21:15:55 -05001043 with zipf.open("foo.txt") as f:
1044 for i in xrange(FIXEDTEST_SIZE):
1045 self.assertEqual(f.read(0), '')
Georg Brandl4b3ab6f2007-07-12 09:59:22 +00001046
Brian Curtin0d654332011-04-19 21:15:55 -05001047 self.assertEqual(f.read(), "O, for a Muse of Fire!")
Georg Brandl4b3ab6f2007-07-12 09:59:22 +00001048
Ezio Melottid5a23e32009-07-15 17:07:04 +00001049 def test_open_non_existent_item(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001050 """Check that attempting to call open() for an item that doesn't
1051 exist in the archive raises a RuntimeError."""
Ezio Melotti569e61f2009-12-30 06:14:51 +00001052 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1053 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Georg Brandl4b3ab6f2007-07-12 09:59:22 +00001054
Ezio Melottid5a23e32009-07-15 17:07:04 +00001055 def test_bad_compression_mode(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001056 """Check that bad compression methods passed to ZipFile.open are
1057 caught."""
Georg Brandl4b3ab6f2007-07-12 09:59:22 +00001058 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
1059
Ezio Melotti9e949722012-11-18 13:18:06 +02001060 def test_unsupported_compression(self):
1061 # data is declared as shrunk, but actually deflated
1062 data = (b'PK\x03\x04.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00'
1063 b'\x00\x02\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00x\x03\x00PK\x01'
1064 b'\x02.\x03.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00\x00\x02\x00\x00'
1065 b'\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
1066 b'\x80\x01\x00\x00\x00\x00xPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00'
1067 b'/\x00\x00\x00!\x00\x00\x00\x00\x00')
1068 with zipfile.ZipFile(io.BytesIO(data), 'r') as zipf:
1069 self.assertRaises(NotImplementedError, zipf.open, 'x')
1070
Ezio Melottid5a23e32009-07-15 17:07:04 +00001071 def test_null_byte_in_filename(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001072 """Check that a filename containing a null byte is properly
1073 terminated."""
Ezio Melotti569e61f2009-12-30 06:14:51 +00001074 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1075 zipf.writestr("foo.txt\x00qqq", "O, for a Muse of Fire!")
1076 self.assertEqual(zipf.namelist(), ['foo.txt'])
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00001077
Ezio Melottid5a23e32009-07-15 17:07:04 +00001078 def test_struct_sizes(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001079 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwis8c436412008-07-03 12:51:14 +00001080 self.assertEqual(zipfile.sizeEndCentDir, 22)
1081 self.assertEqual(zipfile.sizeCentralDir, 46)
1082 self.assertEqual(zipfile.sizeEndCentDir64, 56)
1083 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
1084
Ezio Melottid5a23e32009-07-15 17:07:04 +00001085 def test_comments(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001086 """Check that comments on the archive are handled properly."""
Martin v. Löwis8c436412008-07-03 12:51:14 +00001087
1088 # check default comment is empty
Ezio Melotti569e61f2009-12-30 06:14:51 +00001089 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1090 self.assertEqual(zipf.comment, '')
1091 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1092
1093 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
1094 self.assertEqual(zipf.comment, '')
Martin v. Löwis8c436412008-07-03 12:51:14 +00001095
1096 # check a simple short comment
1097 comment = 'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melotti569e61f2009-12-30 06:14:51 +00001098 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1099 zipf.comment = comment
1100 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1101 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
1102 self.assertEqual(zipf.comment, comment)
Martin v. Löwis8c436412008-07-03 12:51:14 +00001103
1104 # check a comment of max length
1105 comment2 = ''.join(['%d' % (i**3 % 10) for i in xrange((1 << 16)-1)])
Ezio Melotti569e61f2009-12-30 06:14:51 +00001106 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1107 zipf.comment = comment2
1108 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1109
1110 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
1111 self.assertEqual(zipf.comment, comment2)
Martin v. Löwis8c436412008-07-03 12:51:14 +00001112
1113 # check a comment that is too long is truncated
Ezio Melotti569e61f2009-12-30 06:14:51 +00001114 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
Serhiy Storchaka49259352014-01-20 21:57:09 +02001115 with check_warnings(('', UserWarning)):
1116 zipf.comment = comment2 + 'oops'
Ezio Melotti569e61f2009-12-30 06:14:51 +00001117 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1118 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
1119 self.assertEqual(zipf.comment, comment2)
Martin v. Löwis8c436412008-07-03 12:51:14 +00001120
R David Murray3f4ccba2012-04-12 18:42:47 -04001121 def test_change_comment_in_empty_archive(self):
1122 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1123 self.assertFalse(zipf.filelist)
1124 zipf.comment = b"this is a comment"
1125 with zipfile.ZipFile(TESTFN, "r") as zipf:
1126 self.assertEqual(zipf.comment, b"this is a comment")
1127
1128 def test_change_comment_in_nonempty_archive(self):
1129 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1130 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1131 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1132 self.assertTrue(zipf.filelist)
1133 zipf.comment = b"this is a comment"
1134 with zipfile.ZipFile(TESTFN, "r") as zipf:
1135 self.assertEqual(zipf.comment, b"this is a comment")
1136
Antoine Pitroue1436d12010-08-12 15:25:51 +00001137 def check_testzip_with_bad_crc(self, compression):
1138 """Tests that files with bad CRCs return their name from testzip."""
1139 zipdata = self.zips_with_bad_crc[compression]
1140
1141 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1142 # testzip returns the name of the first corrupt file, or None
1143 self.assertEqual('afile', zipf.testzip())
1144
1145 def test_testzip_with_bad_crc_stored(self):
1146 self.check_testzip_with_bad_crc(zipfile.ZIP_STORED)
1147
1148 @skipUnless(zlib, "requires zlib")
1149 def test_testzip_with_bad_crc_deflated(self):
1150 self.check_testzip_with_bad_crc(zipfile.ZIP_DEFLATED)
1151
1152 def check_read_with_bad_crc(self, compression):
1153 """Tests that files with bad CRCs raise a BadZipfile exception when read."""
1154 zipdata = self.zips_with_bad_crc[compression]
1155
1156 # Using ZipFile.read()
1157 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1158 self.assertRaises(zipfile.BadZipfile, zipf.read, 'afile')
1159
1160 # Using ZipExtFile.read()
1161 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1162 with zipf.open('afile', 'r') as corrupt_file:
1163 self.assertRaises(zipfile.BadZipfile, corrupt_file.read)
1164
1165 # Same with small reads (in order to exercise the buffering logic)
1166 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1167 with zipf.open('afile', 'r') as corrupt_file:
1168 corrupt_file.MIN_READ_SIZE = 2
1169 with self.assertRaises(zipfile.BadZipfile):
1170 while corrupt_file.read(2):
1171 pass
1172
1173 def test_read_with_bad_crc_stored(self):
1174 self.check_read_with_bad_crc(zipfile.ZIP_STORED)
1175
1176 @skipUnless(zlib, "requires zlib")
1177 def test_read_with_bad_crc_deflated(self):
1178 self.check_read_with_bad_crc(zipfile.ZIP_DEFLATED)
1179
Antoine Pitroue4195e82010-09-12 14:56:27 +00001180 def check_read_return_size(self, compression):
1181 # Issue #9837: ZipExtFile.read() shouldn't return more bytes
1182 # than requested.
1183 for test_size in (1, 4095, 4096, 4097, 16384):
1184 file_size = test_size + 1
Serhiy Storchaka45aa7712014-12-03 09:11:12 +02001185 junk = getrandbytes(file_size)
Antoine Pitroue4195e82010-09-12 14:56:27 +00001186 with zipfile.ZipFile(io.BytesIO(), "w", compression) as zipf:
1187 zipf.writestr('foo', junk)
1188 with zipf.open('foo', 'r') as fp:
1189 buf = fp.read(test_size)
1190 self.assertEqual(len(buf), test_size)
1191
1192 def test_read_return_size_stored(self):
1193 self.check_read_return_size(zipfile.ZIP_STORED)
1194
1195 @skipUnless(zlib, "requires zlib")
1196 def test_read_return_size_deflated(self):
1197 self.check_read_return_size(zipfile.ZIP_DEFLATED)
1198
Georg Brandl86e0c892010-11-26 07:22:28 +00001199 def test_empty_zipfile(self):
1200 # Check that creating a file in 'w' or 'a' mode and closing without
1201 # adding any files to the archives creates a valid empty ZIP file
Brian Curtin0d654332011-04-19 21:15:55 -05001202 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1203 pass
Georg Brandl86e0c892010-11-26 07:22:28 +00001204 try:
1205 zipf = zipfile.ZipFile(TESTFN, mode="r")
Benjamin Peterson352eb4f2014-04-03 10:31:25 -04001206 zipf.close()
Éric Araujo67843b32011-02-02 17:03:38 +00001207 except zipfile.BadZipfile:
Georg Brandl86e0c892010-11-26 07:22:28 +00001208 self.fail("Unable to create empty ZIP file in 'w' mode")
1209
Brian Curtin0d654332011-04-19 21:15:55 -05001210 with zipfile.ZipFile(TESTFN, mode="a") as zipf:
1211 pass
Georg Brandl86e0c892010-11-26 07:22:28 +00001212 try:
1213 zipf = zipfile.ZipFile(TESTFN, mode="r")
Benjamin Peterson352eb4f2014-04-03 10:31:25 -04001214 zipf.close()
Georg Brandl86e0c892010-11-26 07:22:28 +00001215 except:
1216 self.fail("Unable to create empty ZIP file in 'a' mode")
1217
1218 def test_open_empty_file(self):
1219 # Issue 1710703: Check that opening a file with less than 22 bytes
1220 # raises a BadZipfile exception (rather than the previously unhelpful
1221 # IOError)
Brian Curtin0d654332011-04-19 21:15:55 -05001222 with open(TESTFN, 'w') as f:
1223 pass
Georg Brandl86e0c892010-11-26 07:22:28 +00001224 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN, 'r')
1225
Senthil Kumaranddd40312011-10-20 01:38:35 +08001226 def test_create_zipinfo_before_1980(self):
1227 self.assertRaises(ValueError,
1228 zipfile.ZipInfo, 'seventies', (1979, 1, 1, 0, 0, 0))
1229
Gregory P. Smith0344a062014-05-29 23:41:52 -07001230 def test_zipfile_with_short_extra_field(self):
1231 """If an extra field in the header is less than 4 bytes, skip it."""
1232 zipdata = (
1233 b'PK\x03\x04\x14\x00\x00\x00\x00\x00\x93\x9b\xad@\x8b\x9e'
1234 b'\xd9\xd3\x01\x00\x00\x00\x01\x00\x00\x00\x03\x00\x03\x00ab'
1235 b'c\x00\x00\x00APK\x01\x02\x14\x03\x14\x00\x00\x00\x00'
1236 b'\x00\x93\x9b\xad@\x8b\x9e\xd9\xd3\x01\x00\x00\x00\x01\x00\x00'
1237 b'\x00\x03\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00'
1238 b'\x00\x00\x00abc\x00\x00PK\x05\x06\x00\x00\x00\x00'
1239 b'\x01\x00\x01\x003\x00\x00\x00%\x00\x00\x00\x00\x00'
1240 )
1241 with zipfile.ZipFile(io.BytesIO(zipdata), 'r') as zipf:
1242 # testzip returns the name of the first corrupt file, or None
1243 self.assertIsNone(zipf.testzip())
1244
Collin Winter04a51ec2007-03-29 02:28:16 +00001245 def tearDown(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001246 unlink(TESTFN)
1247 unlink(TESTFN2)
1248
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001249
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001250class DecryptionTests(unittest.TestCase):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001251 """Check that ZIP decryption works. Since the library does not
1252 support encryption at the moment, we use a pre-generated encrypted
1253 ZIP file."""
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001254
1255 data = (
1256 'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
1257 '\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
1258 '\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
1259 'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
1260 '\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
1261 '\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
1262 '\x00\x00L\x00\x00\x00\x00\x00' )
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001263 data2 = (
1264 'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
1265 '\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
1266 '\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
1267 'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
1268 '\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
1269 '\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
1270 'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
1271 '\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001272
1273 plain = 'zipfile.py encryption test'
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001274 plain2 = '\x00'*512
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001275
1276 def setUp(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001277 with open(TESTFN, "wb") as fp:
1278 fp.write(self.data)
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001279 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001280 with open(TESTFN2, "wb") as fp:
1281 fp.write(self.data2)
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001282 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001283
1284 def tearDown(self):
1285 self.zip.close()
1286 os.unlink(TESTFN)
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001287 self.zip2.close()
1288 os.unlink(TESTFN2)
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001289
Ezio Melottid5a23e32009-07-15 17:07:04 +00001290 def test_no_password(self):
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001291 # Reading the encrypted file without password
1292 # must generate a RunTime exception
1293 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001294 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001295
Ezio Melottid5a23e32009-07-15 17:07:04 +00001296 def test_bad_password(self):
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001297 self.zip.setpassword("perl")
1298 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001299 self.zip2.setpassword("perl")
1300 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Tim Petersea5962f2007-03-12 18:07:52 +00001301
Ezio Melotti1036a7f2009-09-12 14:43:43 +00001302 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +00001303 def test_good_password(self):
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001304 self.zip.setpassword("python")
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001305 self.assertEqual(self.zip.read("test.txt"), self.plain)
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001306 self.zip2.setpassword("12345")
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001307 self.assertEqual(self.zip2.read("zero"), self.plain2)
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001308
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001309
1310class TestsWithRandomBinaryFiles(unittest.TestCase):
1311 def setUp(self):
1312 datacount = randint(16, 64)*1024 + randint(1, 1024)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001313 self.data = ''.join(struct.pack('<f', random()*randint(-1000, 1000))
Ezio Melotti763f1e82009-12-31 13:27:41 +00001314 for i in xrange(datacount))
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001315
1316 # Make a source file with some lines
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001317 with open(TESTFN, "wb") as fp:
1318 fp.write(self.data)
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00001319
Collin Winter04a51ec2007-03-29 02:28:16 +00001320 def tearDown(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001321 unlink(TESTFN)
1322 unlink(TESTFN2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001323
Ezio Melottid5a23e32009-07-15 17:07:04 +00001324 def make_test_archive(self, f, compression):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001325 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001326 with zipfile.ZipFile(f, "w", compression) as zipfp:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001327 zipfp.write(TESTFN, "another.name")
Ezio Melotti569e61f2009-12-30 06:14:51 +00001328 zipfp.write(TESTFN, TESTFN)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001329
Ezio Melottid5a23e32009-07-15 17:07:04 +00001330 def zip_test(self, f, compression):
1331 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001332
1333 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001334 with zipfile.ZipFile(f, "r", compression) as zipfp:
1335 testdata = zipfp.read(TESTFN)
1336 self.assertEqual(len(testdata), len(self.data))
1337 self.assertEqual(testdata, self.data)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001338 self.assertEqual(zipfp.read("another.name"), self.data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001339
Ezio Melottid5a23e32009-07-15 17:07:04 +00001340 def test_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001341 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001342 self.zip_test(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +00001343
Antoine Pitroue1436d12010-08-12 15:25:51 +00001344 @skipUnless(zlib, "requires zlib")
1345 def test_deflated(self):
1346 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1347 self.zip_test(f, zipfile.ZIP_DEFLATED)
1348
Ezio Melottid5a23e32009-07-15 17:07:04 +00001349 def zip_open_test(self, f, compression):
1350 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001351
1352 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001353 with zipfile.ZipFile(f, "r", compression) as zipfp:
1354 zipdata1 = []
Brian Curtin0d654332011-04-19 21:15:55 -05001355 with zipfp.open(TESTFN) as zipopen1:
1356 while True:
1357 read_data = zipopen1.read(256)
1358 if not read_data:
1359 break
1360 zipdata1.append(read_data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001361
Ezio Melotti569e61f2009-12-30 06:14:51 +00001362 zipdata2 = []
Brian Curtin0d654332011-04-19 21:15:55 -05001363 with zipfp.open("another.name") as zipopen2:
1364 while True:
1365 read_data = zipopen2.read(256)
1366 if not read_data:
1367 break
1368 zipdata2.append(read_data)
Tim Petersea5962f2007-03-12 18:07:52 +00001369
Ezio Melotti569e61f2009-12-30 06:14:51 +00001370 testdata1 = ''.join(zipdata1)
1371 self.assertEqual(len(testdata1), len(self.data))
1372 self.assertEqual(testdata1, self.data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001373
Ezio Melotti569e61f2009-12-30 06:14:51 +00001374 testdata2 = ''.join(zipdata2)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001375 self.assertEqual(len(testdata2), len(self.data))
1376 self.assertEqual(testdata2, self.data)
Tim Petersea5962f2007-03-12 18:07:52 +00001377
Ezio Melottid5a23e32009-07-15 17:07:04 +00001378 def test_open_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001379 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001380 self.zip_open_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001381
Antoine Pitroue1436d12010-08-12 15:25:51 +00001382 @skipUnless(zlib, "requires zlib")
1383 def test_open_deflated(self):
1384 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1385 self.zip_open_test(f, zipfile.ZIP_DEFLATED)
1386
Ezio Melottid5a23e32009-07-15 17:07:04 +00001387 def zip_random_open_test(self, f, compression):
1388 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001389
1390 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001391 with zipfile.ZipFile(f, "r", compression) as zipfp:
1392 zipdata1 = []
Brian Curtin0d654332011-04-19 21:15:55 -05001393 with zipfp.open(TESTFN) as zipopen1:
1394 while True:
1395 read_data = zipopen1.read(randint(1, 1024))
1396 if not read_data:
1397 break
1398 zipdata1.append(read_data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001399
Ezio Melotti569e61f2009-12-30 06:14:51 +00001400 testdata = ''.join(zipdata1)
1401 self.assertEqual(len(testdata), len(self.data))
1402 self.assertEqual(testdata, self.data)
Tim Petersea5962f2007-03-12 18:07:52 +00001403
Ezio Melottid5a23e32009-07-15 17:07:04 +00001404 def test_random_open_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001405 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001406 self.zip_random_open_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001407
Antoine Pitroue1436d12010-08-12 15:25:51 +00001408 @skipUnless(zlib, "requires zlib")
1409 def test_random_open_deflated(self):
1410 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1411 self.zip_random_open_test(f, zipfile.ZIP_DEFLATED)
1412
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001413
Ezio Melotti1036a7f2009-09-12 14:43:43 +00001414@skipUnless(zlib, "requires zlib")
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001415class TestsWithMultipleOpens(unittest.TestCase):
Serhiy Storchaka45aa7712014-12-03 09:11:12 +02001416 @classmethod
1417 def setUpClass(cls):
1418 cls.data1 = b'111' + getrandbytes(10000)
1419 cls.data2 = b'222' + getrandbytes(10000)
1420
1421 def make_test_archive(self, f):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001422 # Create the ZIP archive
Serhiy Storchaka45aa7712014-12-03 09:11:12 +02001423 with zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as zipfp:
1424 zipfp.writestr('ones', self.data1)
1425 zipfp.writestr('twos', self.data2)
Tim Petersea5962f2007-03-12 18:07:52 +00001426
Ezio Melottid5a23e32009-07-15 17:07:04 +00001427 def test_same_file(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001428 # Verify that (when the ZipFile is in control of creating file objects)
1429 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka45aa7712014-12-03 09:11:12 +02001430 for f in get_files(self):
1431 self.make_test_archive(f)
1432 with zipfile.ZipFile(f, mode="r") as zipf:
1433 with zipf.open('ones') as zopen1, zipf.open('ones') as zopen2:
1434 data1 = zopen1.read(500)
1435 data2 = zopen2.read(500)
1436 data1 += zopen1.read()
1437 data2 += zopen2.read()
1438 self.assertEqual(data1, data2)
1439 self.assertEqual(data1, self.data1)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001440
Ezio Melottid5a23e32009-07-15 17:07:04 +00001441 def test_different_file(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001442 # Verify that (when the ZipFile is in control of creating file objects)
1443 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka45aa7712014-12-03 09:11:12 +02001444 for f in get_files(self):
1445 self.make_test_archive(f)
1446 with zipfile.ZipFile(f, mode="r") as zipf:
1447 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1448 data1 = zopen1.read(500)
1449 data2 = zopen2.read(500)
1450 data1 += zopen1.read()
1451 data2 += zopen2.read()
1452 self.assertEqual(data1, self.data1)
1453 self.assertEqual(data2, self.data2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001454
Ezio Melottid5a23e32009-07-15 17:07:04 +00001455 def test_interleaved(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001456 # Verify that (when the ZipFile is in control of creating file objects)
1457 # multiple open() calls can be made without interfering with each other.
Serhiy Storchaka45aa7712014-12-03 09:11:12 +02001458 for f in get_files(self):
1459 self.make_test_archive(f)
1460 with zipfile.ZipFile(f, mode="r") as zipf:
1461 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1462 data1 = zopen1.read(500)
1463 data2 = zopen2.read(500)
1464 data1 += zopen1.read()
1465 data2 += zopen2.read()
1466 self.assertEqual(data1, self.data1)
1467 self.assertEqual(data2, self.data2)
1468
1469 def test_read_after_close(self):
1470 for f in get_files(self):
1471 self.make_test_archive(f)
1472 zopen1 = zopen2 = None
1473 try:
1474 with zipfile.ZipFile(f, 'r') as zipf:
1475 zopen1 = zipf.open('ones')
1476 zopen2 = zipf.open('twos')
Brian Curtin0d654332011-04-19 21:15:55 -05001477 data1 = zopen1.read(500)
1478 data2 = zopen2.read(500)
Serhiy Storchaka45aa7712014-12-03 09:11:12 +02001479 data1 += zopen1.read()
1480 data2 += zopen2.read()
1481 finally:
1482 if zopen1:
1483 zopen1.close()
1484 if zopen2:
1485 zopen2.close()
1486 self.assertEqual(data1, self.data1)
1487 self.assertEqual(data2, self.data2)
1488
1489 def test_read_after_write(self):
1490 for f in get_files(self):
1491 with zipfile.ZipFile(f, 'w', zipfile.ZIP_DEFLATED) as zipf:
1492 zipf.writestr('ones', self.data1)
1493 zipf.writestr('twos', self.data2)
1494 with zipf.open('ones') as zopen1:
1495 data1 = zopen1.read(500)
1496 self.assertEqual(data1, self.data1[:500])
1497 with zipfile.ZipFile(f, 'r') as zipf:
1498 data1 = zipf.read('ones')
1499 data2 = zipf.read('twos')
1500 self.assertEqual(data1, self.data1)
1501 self.assertEqual(data2, self.data2)
1502
1503 def test_write_after_read(self):
1504 for f in get_files(self):
1505 with zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as zipf:
1506 zipf.writestr('ones', self.data1)
1507 with zipf.open('ones') as zopen1:
1508 zopen1.read(500)
1509 zipf.writestr('twos', self.data2)
1510 with zipfile.ZipFile(f, 'r') as zipf:
1511 data1 = zipf.read('ones')
1512 data2 = zipf.read('twos')
1513 self.assertEqual(data1, self.data1)
1514 self.assertEqual(data2, self.data2)
Tim Petersea5962f2007-03-12 18:07:52 +00001515
Benjamin Peterson352eb4f2014-04-03 10:31:25 -04001516 def test_many_opens(self):
1517 # Verify that read() and open() promptly close the file descriptor,
1518 # and don't rely on the garbage collector to free resources.
Serhiy Storchaka45aa7712014-12-03 09:11:12 +02001519 self.make_test_archive(TESTFN2)
Benjamin Peterson352eb4f2014-04-03 10:31:25 -04001520 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
1521 for x in range(100):
1522 zipf.read('ones')
1523 with zipf.open('ones') as zopen1:
1524 pass
1525 with open(os.devnull) as f:
1526 self.assertLess(f.fileno(), 100)
1527
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001528 def tearDown(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001529 unlink(TESTFN2)
1530
Tim Petersea5962f2007-03-12 18:07:52 +00001531
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001532class TestWithDirectory(unittest.TestCase):
1533 def setUp(self):
1534 os.mkdir(TESTFN2)
1535
Ezio Melottid5a23e32009-07-15 17:07:04 +00001536 def test_extract_dir(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +00001537 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
1538 zipf.extractall(TESTFN2)
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001539 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1540 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1541 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1542
Ezio Melottid5a23e32009-07-15 17:07:04 +00001543 def test_bug_6050(self):
Martin v. Löwis0b09c422009-05-24 19:30:52 +00001544 # Extraction should succeed if directories already exist
1545 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottid5a23e32009-07-15 17:07:04 +00001546 self.test_extract_dir()
Martin v. Löwis0b09c422009-05-24 19:30:52 +00001547
Serhiy Storchaka6d343e72014-09-23 22:39:59 +03001548 def test_write_dir(self):
1549 dirpath = os.path.join(TESTFN2, "x")
1550 os.mkdir(dirpath)
1551 mode = os.stat(dirpath).st_mode & 0xFFFF
1552 with zipfile.ZipFile(TESTFN, "w") as zipf:
1553 zipf.write(dirpath)
1554 zinfo = zipf.filelist[0]
1555 self.assertTrue(zinfo.filename.endswith("/x/"))
1556 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1557 zipf.write(dirpath, "y")
1558 zinfo = zipf.filelist[1]
1559 self.assertTrue(zinfo.filename, "y/")
1560 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1561 with zipfile.ZipFile(TESTFN, "r") as zipf:
1562 zinfo = zipf.filelist[0]
1563 self.assertTrue(zinfo.filename.endswith("/x/"))
1564 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1565 zinfo = zipf.filelist[1]
1566 self.assertTrue(zinfo.filename, "y/")
1567 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1568 target = os.path.join(TESTFN2, "target")
1569 os.mkdir(target)
1570 zipf.extractall(target)
1571 self.assertTrue(os.path.isdir(os.path.join(target, "y")))
1572 self.assertEqual(len(os.listdir(target)), 2)
1573
1574 def test_writestr_dir(self):
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001575 os.mkdir(os.path.join(TESTFN2, "x"))
Benjamin Peterson352eb4f2014-04-03 10:31:25 -04001576 with zipfile.ZipFile(TESTFN, "w") as zipf:
Serhiy Storchaka6d343e72014-09-23 22:39:59 +03001577 zipf.writestr("x/", b'')
1578 zinfo = zipf.filelist[0]
1579 self.assertEqual(zinfo.filename, "x/")
1580 self.assertEqual(zinfo.external_attr, (0o40775 << 16) | 0x10)
1581 with zipfile.ZipFile(TESTFN, "r") as zipf:
1582 zinfo = zipf.filelist[0]
1583 self.assertTrue(zinfo.filename.endswith("x/"))
1584 self.assertEqual(zinfo.external_attr, (0o40775 << 16) | 0x10)
1585 target = os.path.join(TESTFN2, "target")
1586 os.mkdir(target)
1587 zipf.extractall(target)
1588 self.assertTrue(os.path.isdir(os.path.join(target, "x")))
1589 self.assertEqual(os.listdir(target), ["x"])
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001590
1591 def tearDown(self):
Benjamin Peterson352eb4f2014-04-03 10:31:25 -04001592 rmtree(TESTFN2)
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001593 if os.path.exists(TESTFN):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001594 unlink(TESTFN)
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001595
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001596
1597class UniversalNewlineTests(unittest.TestCase):
1598 def setUp(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001599 self.line_gen = ["Test of zipfile line %d." % i
1600 for i in xrange(FIXEDTEST_SIZE)]
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001601 self.seps = ('\r', '\r\n', '\n')
1602 self.arcdata, self.arcfiles = {}, {}
1603 for n, s in enumerate(self.seps):
1604 self.arcdata[s] = s.join(self.line_gen) + s
1605 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Benjamin Peterson352eb4f2014-04-03 10:31:25 -04001606 with open(self.arcfiles[s], "wb") as fid:
1607 fid.write(self.arcdata[s])
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001608
Ezio Melottid5a23e32009-07-15 17:07:04 +00001609 def make_test_archive(self, f, compression):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001610 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001611 with zipfile.ZipFile(f, "w", compression) as zipfp:
1612 for fn in self.arcfiles.values():
1613 zipfp.write(fn, fn)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001614
Ezio Melottid5a23e32009-07-15 17:07:04 +00001615 def read_test(self, f, compression):
1616 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001617
1618 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001619 with zipfile.ZipFile(f, "r") as zipfp:
1620 for sep, fn in self.arcfiles.items():
Brian Curtin0d654332011-04-19 21:15:55 -05001621 with zipfp.open(fn, "rU") as fp:
1622 zipdata = fp.read()
Ezio Melotti569e61f2009-12-30 06:14:51 +00001623 self.assertEqual(self.arcdata[sep], zipdata)
Tim Petersea5962f2007-03-12 18:07:52 +00001624
Antoine Pitrou94c33eb2010-01-27 20:59:50 +00001625 def readline_read_test(self, f, compression):
1626 self.make_test_archive(f, compression)
1627
1628 # Read the ZIP archive
1629 zipfp = zipfile.ZipFile(f, "r")
1630 for sep, fn in self.arcfiles.items():
Brian Curtin0d654332011-04-19 21:15:55 -05001631 with zipfp.open(fn, "rU") as zipopen:
1632 data = ''
1633 while True:
1634 read = zipopen.readline()
1635 if not read:
1636 break
1637 data += read
Antoine Pitrou94c33eb2010-01-27 20:59:50 +00001638
Brian Curtin0d654332011-04-19 21:15:55 -05001639 read = zipopen.read(5)
1640 if not read:
1641 break
1642 data += read
Antoine Pitrou94c33eb2010-01-27 20:59:50 +00001643
1644 self.assertEqual(data, self.arcdata['\n'])
1645
1646 zipfp.close()
1647
Ezio Melottid5a23e32009-07-15 17:07:04 +00001648 def readline_test(self, f, compression):
1649 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001650
1651 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001652 with zipfile.ZipFile(f, "r") as zipfp:
1653 for sep, fn in self.arcfiles.items():
Brian Curtin0d654332011-04-19 21:15:55 -05001654 with zipfp.open(fn, "rU") as zipopen:
1655 for line in self.line_gen:
1656 linedata = zipopen.readline()
1657 self.assertEqual(linedata, line + '\n')
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001658
Ezio Melottid5a23e32009-07-15 17:07:04 +00001659 def readlines_test(self, f, compression):
1660 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001661
1662 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001663 with zipfile.ZipFile(f, "r") as zipfp:
1664 for sep, fn in self.arcfiles.items():
Brian Curtin0d654332011-04-19 21:15:55 -05001665 with zipfp.open(fn, "rU") as fp:
1666 ziplines = fp.readlines()
Ezio Melotti569e61f2009-12-30 06:14:51 +00001667 for line, zipline in zip(self.line_gen, ziplines):
1668 self.assertEqual(zipline, line + '\n')
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001669
Ezio Melottid5a23e32009-07-15 17:07:04 +00001670 def iterlines_test(self, f, compression):
1671 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001672
1673 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001674 with zipfile.ZipFile(f, "r") as zipfp:
1675 for sep, fn in self.arcfiles.items():
Benjamin Peterson352eb4f2014-04-03 10:31:25 -04001676 with zipfp.open(fn, "rU") as fid:
1677 for line, zipline in zip(self.line_gen, fid):
1678 self.assertEqual(zipline, line + '\n')
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001679
Ezio Melottid5a23e32009-07-15 17:07:04 +00001680 def test_read_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001681 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001682 self.read_test(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +00001683
Antoine Pitrou94c33eb2010-01-27 20:59:50 +00001684 def test_readline_read_stored(self):
1685 # Issue #7610: calls to readline() interleaved with calls to read().
1686 for f in (TESTFN2, TemporaryFile(), StringIO()):
1687 self.readline_read_test(f, zipfile.ZIP_STORED)
1688
Ezio Melottid5a23e32009-07-15 17:07:04 +00001689 def test_readline_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001690 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001691 self.readline_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001692
Ezio Melottid5a23e32009-07-15 17:07:04 +00001693 def test_readlines_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001694 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001695 self.readlines_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001696
Ezio Melottid5a23e32009-07-15 17:07:04 +00001697 def test_iterlines_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001698 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001699 self.iterlines_test(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +00001700
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001701 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +00001702 def test_read_deflated(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001703 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001704 self.read_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001705
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001706 @skipUnless(zlib, "requires zlib")
Antoine Pitrou94c33eb2010-01-27 20:59:50 +00001707 def test_readline_read_deflated(self):
1708 # Issue #7610: calls to readline() interleaved with calls to read().
1709 for f in (TESTFN2, TemporaryFile(), StringIO()):
1710 self.readline_read_test(f, zipfile.ZIP_DEFLATED)
1711
1712 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +00001713 def test_readline_deflated(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001714 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001715 self.readline_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001716
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001717 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +00001718 def test_readlines_deflated(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001719 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001720 self.readlines_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001721
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001722 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +00001723 def test_iterlines_deflated(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001724 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001725 self.iterlines_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001726
1727 def tearDown(self):
1728 for sep, fn in self.arcfiles.items():
1729 os.remove(fn)
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001730 unlink(TESTFN)
1731 unlink(TESTFN2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001732
1733
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001734def test_main():
Tim Petersea5962f2007-03-12 18:07:52 +00001735 run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
1736 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001737 TestWithDirectory, UniversalNewlineTests,
1738 TestsWithRandomBinaryFiles)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001739
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001740if __name__ == "__main__":
1741 test_main()