blob: 71c6605829cb5ba17d8902de0be9d403a6420324 [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):
Serhiy Storchaka45aa7712014-12-03 09:11:12 +020039 return bytes(bytearray.fromhex('%0*x' % (2 * size, getrandbits(8 * size))))
40
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000041class TestsWithSourceFile(unittest.TestCase):
42 def setUp(self):
Georg Brandl4b3ab6f2007-07-12 09:59:22 +000043 self.line_gen = ["Zipfile test line %d. random float: %f" % (i, random())
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000044 for i in xrange(FIXEDTEST_SIZE)]
Martin v. Löwis3eb76482007-03-06 10:41:24 +000045 self.data = '\n'.join(self.line_gen) + '\n'
Fred Drake6e7e4852001-02-28 05:34:16 +000046
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000047 # Make a source file with some lines
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000048 with open(TESTFN, "wb") as fp:
49 fp.write(self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000050
Ezio Melottid5a23e32009-07-15 17:07:04 +000051 def make_test_archive(self, f, compression):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000052 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +000053 with zipfile.ZipFile(f, "w", compression) as zipfp:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000054 zipfp.write(TESTFN, "another.name")
Ezio Melotti569e61f2009-12-30 06:14:51 +000055 zipfp.write(TESTFN, TESTFN)
56 zipfp.writestr("strfile", self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000057
Ezio Melottid5a23e32009-07-15 17:07:04 +000058 def zip_test(self, f, compression):
59 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +000060
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000061 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +000062 with zipfile.ZipFile(f, "r", compression) as zipfp:
63 self.assertEqual(zipfp.read(TESTFN), self.data)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000064 self.assertEqual(zipfp.read("another.name"), self.data)
Ezio Melotti569e61f2009-12-30 06:14:51 +000065 self.assertEqual(zipfp.read("strfile"), self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +000066
Ezio Melotti569e61f2009-12-30 06:14:51 +000067 # Print the ZIP directory
68 fp = StringIO()
69 stdout = sys.stdout
70 try:
71 sys.stdout = fp
72 zipfp.printdir()
73 finally:
74 sys.stdout = stdout
Tim Petersa608bb22006-06-15 18:06:29 +000075
Ezio Melotti569e61f2009-12-30 06:14:51 +000076 directory = fp.getvalue()
77 lines = directory.splitlines()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000078 self.assertEqual(len(lines), 4) # Number of files + header
Ronald Oussoren143cefb2006-06-15 08:14:18 +000079
Ezio Melottiaa980582010-01-23 23:04:36 +000080 self.assertIn('File Name', lines[0])
81 self.assertIn('Modified', lines[0])
82 self.assertIn('Size', lines[0])
Ronald Oussoren143cefb2006-06-15 08:14:18 +000083
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000084 fn, date, time_, size = lines[1].split()
85 self.assertEqual(fn, 'another.name')
86 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
87 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
88 self.assertEqual(size, str(len(self.data)))
Ronald Oussoren143cefb2006-06-15 08:14:18 +000089
Ezio Melotti569e61f2009-12-30 06:14:51 +000090 # Check the namelist
91 names = zipfp.namelist()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000092 self.assertEqual(len(names), 3)
Ezio Melottiaa980582010-01-23 23:04:36 +000093 self.assertIn(TESTFN, names)
94 self.assertIn("another.name", names)
95 self.assertIn("strfile", names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +000096
Ezio Melotti569e61f2009-12-30 06:14:51 +000097 # Check infolist
98 infos = zipfp.infolist()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000099 names = [i.filename for i in infos]
100 self.assertEqual(len(names), 3)
Ezio Melottiaa980582010-01-23 23:04:36 +0000101 self.assertIn(TESTFN, names)
102 self.assertIn("another.name", names)
103 self.assertIn("strfile", names)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000104 for i in infos:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000105 self.assertEqual(i.file_size, len(self.data))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000106
Ezio Melotti569e61f2009-12-30 06:14:51 +0000107 # check getinfo
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000108 for nm in (TESTFN, "another.name", "strfile"):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000109 info = zipfp.getinfo(nm)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000110 self.assertEqual(info.filename, nm)
111 self.assertEqual(info.file_size, len(self.data))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000112
Ezio Melotti569e61f2009-12-30 06:14:51 +0000113 # Check that testzip doesn't raise an exception
114 zipfp.testzip()
Tim Peters7d3bad62001-04-04 18:56:49 +0000115
Ezio Melottid5a23e32009-07-15 17:07:04 +0000116 def test_stored(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000117 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000118 self.zip_test(f, zipfile.ZIP_STORED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000119
Ezio Melottid5a23e32009-07-15 17:07:04 +0000120 def zip_open_test(self, f, compression):
121 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000122
123 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000124 with zipfile.ZipFile(f, "r", compression) as zipfp:
125 zipdata1 = []
Brian Curtin0d654332011-04-19 21:15:55 -0500126 with zipfp.open(TESTFN) as zipopen1:
127 while True:
128 read_data = zipopen1.read(256)
129 if not read_data:
130 break
131 zipdata1.append(read_data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000132
Ezio Melotti569e61f2009-12-30 06:14:51 +0000133 zipdata2 = []
Brian Curtin0d654332011-04-19 21:15:55 -0500134 with zipfp.open("another.name") as zipopen2:
135 while True:
136 read_data = zipopen2.read(256)
137 if not read_data:
138 break
139 zipdata2.append(read_data)
Tim Petersea5962f2007-03-12 18:07:52 +0000140
Ezio Melotti569e61f2009-12-30 06:14:51 +0000141 self.assertEqual(''.join(zipdata1), self.data)
142 self.assertEqual(''.join(zipdata2), self.data)
Tim Petersea5962f2007-03-12 18:07:52 +0000143
Ezio Melottid5a23e32009-07-15 17:07:04 +0000144 def test_open_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000145 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000146 self.zip_open_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000147
Ezio Melottid5a23e32009-07-15 17:07:04 +0000148 def test_open_via_zip_info(self):
Georg Brandl112aa502008-05-20 08:25:48 +0000149 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000150 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
151 zipfp.writestr("name", "foo")
Serhiy Storchaka49259352014-01-20 21:57:09 +0200152 with check_warnings(('', UserWarning)):
153 zipfp.writestr("name", "bar")
154 self.assertEqual(zipfp.namelist(), ["name"] * 2)
Georg Brandl112aa502008-05-20 08:25:48 +0000155
Ezio Melotti569e61f2009-12-30 06:14:51 +0000156 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
157 infos = zipfp.infolist()
158 data = ""
159 for info in infos:
Brian Curtin0d654332011-04-19 21:15:55 -0500160 with zipfp.open(info) as f:
161 data += f.read()
Ezio Melotti569e61f2009-12-30 06:14:51 +0000162 self.assertTrue(data == "foobar" or data == "barfoo")
163 data = ""
164 for info in infos:
165 data += zipfp.read(info)
166 self.assertTrue(data == "foobar" or data == "barfoo")
Georg Brandl112aa502008-05-20 08:25:48 +0000167
Ezio Melottid5a23e32009-07-15 17:07:04 +0000168 def zip_random_open_test(self, f, compression):
169 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000170
171 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000172 with zipfile.ZipFile(f, "r", compression) as zipfp:
173 zipdata1 = []
Brian Curtin0d654332011-04-19 21:15:55 -0500174 with zipfp.open(TESTFN) as zipopen1:
175 while True:
176 read_data = zipopen1.read(randint(1, 1024))
177 if not read_data:
178 break
179 zipdata1.append(read_data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000180
Ezio Melotti569e61f2009-12-30 06:14:51 +0000181 self.assertEqual(''.join(zipdata1), self.data)
Tim Petersea5962f2007-03-12 18:07:52 +0000182
Ezio Melottid5a23e32009-07-15 17:07:04 +0000183 def test_random_open_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000184 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000185 self.zip_random_open_test(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +0000186
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000187 def test_univeral_readaheads(self):
188 f = StringIO()
189
190 data = 'a\r\n' * 16 * 1024
Brian Curtin0d654332011-04-19 21:15:55 -0500191 with zipfile.ZipFile(f, 'w', zipfile.ZIP_STORED) as zipfp:
192 zipfp.writestr(TESTFN, data)
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000193
194 data2 = ''
Brian Curtin0d654332011-04-19 21:15:55 -0500195 with zipfile.ZipFile(f, 'r') as zipfp:
196 with zipfp.open(TESTFN, 'rU') as zipopen:
197 for line in zipopen:
198 data2 += line
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000199
200 self.assertEqual(data, data2.replace('\n', '\r\n'))
201
202 def zip_readline_read_test(self, f, compression):
203 self.make_test_archive(f, compression)
204
205 # Read the ZIP archive
Brian Curtin0d654332011-04-19 21:15:55 -0500206 with zipfile.ZipFile(f, "r") as zipfp:
207 with zipfp.open(TESTFN) as zipopen:
208 data = ''
209 while True:
210 read = zipopen.readline()
211 if not read:
212 break
213 data += read
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000214
Brian Curtin0d654332011-04-19 21:15:55 -0500215 read = zipopen.read(100)
216 if not read:
217 break
218 data += read
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000219
220 self.assertEqual(data, self.data)
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000221
Ezio Melottid5a23e32009-07-15 17:07:04 +0000222 def zip_readline_test(self, f, compression):
223 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000224
225 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000226 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin0d654332011-04-19 21:15:55 -0500227 with zipfp.open(TESTFN) as zipopen:
228 for line in self.line_gen:
229 linedata = zipopen.readline()
230 self.assertEqual(linedata, line + '\n')
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000231
Ezio Melottid5a23e32009-07-15 17:07:04 +0000232 def zip_readlines_test(self, f, compression):
233 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000234
235 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000236 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin0d654332011-04-19 21:15:55 -0500237 with zipfp.open(TESTFN) as zo:
238 ziplines = zo.readlines()
239 for line, zipline in zip(self.line_gen, ziplines):
240 self.assertEqual(zipline, line + '\n')
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000241
Ezio Melottid5a23e32009-07-15 17:07:04 +0000242 def zip_iterlines_test(self, f, compression):
243 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000244
245 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000246 with zipfile.ZipFile(f, "r") as zipfp:
247 for line, zipline in zip(self.line_gen, zipfp.open(TESTFN)):
248 self.assertEqual(zipline, line + '\n')
Tim Petersea5962f2007-03-12 18:07:52 +0000249
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000250 def test_readline_read_stored(self):
251 # Issue #7610: calls to readline() interleaved with calls to read().
252 for f in (TESTFN2, TemporaryFile(), StringIO()):
253 self.zip_readline_read_test(f, zipfile.ZIP_STORED)
254
Ezio Melottid5a23e32009-07-15 17:07:04 +0000255 def test_readline_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000256 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000257 self.zip_readline_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000258
Ezio Melottid5a23e32009-07-15 17:07:04 +0000259 def test_readlines_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000260 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000261 self.zip_readlines_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000262
Ezio Melottid5a23e32009-07-15 17:07:04 +0000263 def test_iterlines_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000264 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000265 self.zip_iterlines_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000266
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000267 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000268 def test_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000269 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000270 self.zip_test(f, zipfile.ZIP_DEFLATED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000271
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000272 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000273 def test_open_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000274 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000275 self.zip_open_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000276
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000277 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000278 def test_random_open_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000279 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000280 self.zip_random_open_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000281
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000282 @skipUnless(zlib, "requires zlib")
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000283 def test_readline_read_deflated(self):
284 # Issue #7610: calls to readline() interleaved with calls to read().
285 for f in (TESTFN2, TemporaryFile(), StringIO()):
286 self.zip_readline_read_test(f, zipfile.ZIP_DEFLATED)
287
288 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000289 def test_readline_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000290 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000291 self.zip_readline_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000292
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000293 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000294 def test_readlines_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000295 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000296 self.zip_readlines_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000297
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000298 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000299 def test_iterlines_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000300 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000301 self.zip_iterlines_test(f, zipfile.ZIP_DEFLATED)
Tim Petersea5962f2007-03-12 18:07:52 +0000302
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000303 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000304 def test_low_compression(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000305 """Check for cases where compressed data is larger than original."""
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000306 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000307 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
308 zipfp.writestr("strfile", '12')
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000309
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000310 # Get an open object for strfile
Ezio Melotti569e61f2009-12-30 06:14:51 +0000311 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_DEFLATED) as zipfp:
Brian Curtin0d654332011-04-19 21:15:55 -0500312 with zipfp.open("strfile") as openobj:
313 self.assertEqual(openobj.read(1), '1')
314 self.assertEqual(openobj.read(1), '2')
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000315
Ezio Melottid5a23e32009-07-15 17:07:04 +0000316 def test_absolute_arcnames(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000317 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
318 zipfp.write(TESTFN, "/absolute")
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000319
Ezio Melotti569e61f2009-12-30 06:14:51 +0000320 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
321 self.assertEqual(zipfp.namelist(), ["absolute"])
Tim Peters32cbc962006-02-20 21:42:18 +0000322
Ezio Melottid5a23e32009-07-15 17:07:04 +0000323 def test_append_to_zip_file(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000324 """Test appending to an existing zipfile."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000325 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
326 zipfp.write(TESTFN, TESTFN)
327
328 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
329 zipfp.writestr("strfile", self.data)
330 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000331
Ezio Melottid5a23e32009-07-15 17:07:04 +0000332 def test_append_to_non_zip_file(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000333 """Test appending to an existing file that is not a zipfile."""
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000334 # NOTE: this test fails if len(d) < 22 because of the first
335 # line "fpin.seek(-22, 2)" in _EndRecData
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000336 data = 'I am not a ZipFile!'*10
337 with open(TESTFN2, 'wb') as f:
338 f.write(data)
339
Ezio Melotti569e61f2009-12-30 06:14:51 +0000340 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
341 zipfp.write(TESTFN, TESTFN)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000342
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000343 with open(TESTFN2, 'rb') as f:
344 f.seek(len(data))
345 with zipfile.ZipFile(f, "r") as zipfp:
346 self.assertEqual(zipfp.namelist(), [TESTFN])
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000347
R David Murray873c5832011-06-09 16:01:09 -0400348 def test_ignores_newline_at_end(self):
349 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
350 zipfp.write(TESTFN, TESTFN)
351 with open(TESTFN2, 'a') as f:
352 f.write("\r\n\00\00\00")
353 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
354 self.assertIsInstance(zipfp, zipfile.ZipFile)
355
356 def test_ignores_stuff_appended_past_comments(self):
357 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
358 zipfp.comment = b"this is a comment"
359 zipfp.write(TESTFN, TESTFN)
360 with open(TESTFN2, 'a') as f:
361 f.write("abcdef\r\n")
362 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
363 self.assertIsInstance(zipfp, zipfile.ZipFile)
364 self.assertEqual(zipfp.comment, b"this is a comment")
365
Ezio Melottid5a23e32009-07-15 17:07:04 +0000366 def test_write_default_name(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000367 """Check that calling ZipFile.write without arcname specified
368 produces the expected result."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000369 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
370 zipfp.write(TESTFN)
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400371 with open(TESTFN,'r') as fid:
372 self.assertEqual(zipfp.read(TESTFN), fid.read())
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000373
Ezio Melotti1036a7f2009-09-12 14:43:43 +0000374 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000375 def test_per_file_compression(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000376 """Check that files within a Zip archive can have different
377 compression options."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000378 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
379 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
380 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
381 sinfo = zipfp.getinfo('storeme')
382 dinfo = zipfp.getinfo('deflateme')
383 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
384 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000385
Ezio Melottid5a23e32009-07-15 17:07:04 +0000386 def test_write_to_readonly(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000387 """Check that trying to call write() on a readonly ZipFile object
388 raises a RuntimeError."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000389 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
390 zipfp.writestr("somefile.txt", "bogus")
391
392 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
393 self.assertRaises(RuntimeError, zipfp.write, TESTFN)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000394
Ezio Melottid5a23e32009-07-15 17:07:04 +0000395 def test_extract(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000396 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
397 for fpath, fdata in SMALL_TEST_DATA:
398 zipfp.writestr(fpath, fdata)
Georg Brandl62416bc2008-01-07 18:47:44 +0000399
Ezio Melotti569e61f2009-12-30 06:14:51 +0000400 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
401 for fpath, fdata in SMALL_TEST_DATA:
402 writtenfile = zipfp.extract(fpath)
Georg Brandl62416bc2008-01-07 18:47:44 +0000403
Ezio Melotti569e61f2009-12-30 06:14:51 +0000404 # make sure it was written to the right place
Gregory P. Smith608cc452013-02-01 11:40:18 -0800405 correctfile = os.path.join(os.getcwd(), fpath)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000406 correctfile = os.path.normpath(correctfile)
Georg Brandl62416bc2008-01-07 18:47:44 +0000407
Ezio Melotti569e61f2009-12-30 06:14:51 +0000408 self.assertEqual(writtenfile, correctfile)
Georg Brandl62416bc2008-01-07 18:47:44 +0000409
Ezio Melotti569e61f2009-12-30 06:14:51 +0000410 # make sure correct data is in correct file
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400411 with open(writtenfile, "rb") as fid:
412 self.assertEqual(fdata, fid.read())
Ezio Melotti569e61f2009-12-30 06:14:51 +0000413 os.remove(writtenfile)
Georg Brandl62416bc2008-01-07 18:47:44 +0000414
415 # remove the test file subdirectories
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400416 rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
Georg Brandl62416bc2008-01-07 18:47:44 +0000417
Ezio Melottid5a23e32009-07-15 17:07:04 +0000418 def test_extract_all(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000419 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
420 for fpath, fdata in SMALL_TEST_DATA:
421 zipfp.writestr(fpath, fdata)
Georg Brandl62416bc2008-01-07 18:47:44 +0000422
Ezio Melotti569e61f2009-12-30 06:14:51 +0000423 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
424 zipfp.extractall()
425 for fpath, fdata in SMALL_TEST_DATA:
Gregory P. Smith608cc452013-02-01 11:40:18 -0800426 outfile = os.path.join(os.getcwd(), fpath)
Georg Brandl62416bc2008-01-07 18:47:44 +0000427
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400428 with open(outfile, "rb") as fid:
429 self.assertEqual(fdata, fid.read())
Ezio Melotti569e61f2009-12-30 06:14:51 +0000430 os.remove(outfile)
Georg Brandl62416bc2008-01-07 18:47:44 +0000431
432 # remove the test file subdirectories
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400433 rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
Georg Brandl62416bc2008-01-07 18:47:44 +0000434
Gregory P. Smith608cc452013-02-01 11:40:18 -0800435 def check_file(self, filename, content):
436 self.assertTrue(os.path.isfile(filename))
437 with open(filename, 'rb') as f:
438 self.assertEqual(f.read(), content)
439
Serhiy Storchakadb03e6b2013-05-08 21:52:31 +0300440 @skipUnless(TESTFN_UNICODE, "No Unicode filesystem semantics on this platform.")
Serhiy Storchaka6fa83f92013-04-13 12:28:17 +0300441 def test_extract_unicode_filenames(self):
442 fnames = [u'foo.txt', os.path.basename(TESTFN_UNICODE)]
443 content = 'Test for unicode filename'
444 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
445 for fname in fnames:
446 zipfp.writestr(fname, content)
447
448 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
449 for fname in fnames:
450 writtenfile = zipfp.extract(fname)
451
452 # make sure it was written to the right place
453 correctfile = os.path.join(os.getcwd(), fname)
454 correctfile = os.path.normpath(correctfile)
455 self.assertEqual(writtenfile, correctfile)
456
457 self.check_file(writtenfile, content)
458 os.remove(writtenfile)
459
Gregory P. Smith608cc452013-02-01 11:40:18 -0800460 def test_extract_hackers_arcnames(self):
461 hacknames = [
462 ('../foo/bar', 'foo/bar'),
463 ('foo/../bar', 'foo/bar'),
464 ('foo/../../bar', 'foo/bar'),
465 ('foo/bar/..', 'foo/bar'),
466 ('./../foo/bar', 'foo/bar'),
467 ('/foo/bar', 'foo/bar'),
468 ('/foo/../bar', 'foo/bar'),
469 ('/foo/../../bar', 'foo/bar'),
Gregory P. Smith608cc452013-02-01 11:40:18 -0800470 ]
471 if os.path.sep == '\\':
472 hacknames.extend([
473 (r'..\foo\bar', 'foo/bar'),
474 (r'..\/foo\/bar', 'foo/bar'),
475 (r'foo/\..\/bar', 'foo/bar'),
476 (r'foo\/../\bar', 'foo/bar'),
477 (r'C:foo/bar', 'foo/bar'),
478 (r'C:/foo/bar', 'foo/bar'),
479 (r'C://foo/bar', 'foo/bar'),
480 (r'C:\foo\bar', 'foo/bar'),
Benjamin Petersonc4597552014-06-22 20:26:07 -0700481 (r'//conky/mountpoint/foo/bar', 'foo/bar'),
482 (r'\\conky\mountpoint\foo\bar', 'foo/bar'),
Gregory P. Smith608cc452013-02-01 11:40:18 -0800483 (r'///conky/mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
484 (r'\\\conky\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
485 (r'//conky//mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
486 (r'\\conky\\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
Benjamin Petersonc4597552014-06-22 20:26:07 -0700487 (r'//?/C:/foo/bar', 'foo/bar'),
488 (r'\\?\C:\foo\bar', 'foo/bar'),
Gregory P. Smith608cc452013-02-01 11:40:18 -0800489 (r'C:/../C:/foo/bar', 'C_/foo/bar'),
490 (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 +0200491 ('../../foo../../ba..r', 'foo/ba..r'),
492 ])
493 else: # Unix
494 hacknames.extend([
495 ('//foo/bar', 'foo/bar'),
496 ('../../foo../../ba..r', 'foo../ba..r'),
Serhiy Storchaka05fd7442013-02-02 18:34:57 +0200497 (r'foo/..\bar', r'foo/..\bar'),
Gregory P. Smith608cc452013-02-01 11:40:18 -0800498 ])
499
500 for arcname, fixedname in hacknames:
501 content = b'foobar' + arcname.encode()
502 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipfp:
Serhiy Storchaka05fd7442013-02-02 18:34:57 +0200503 zinfo = zipfile.ZipInfo()
504 # preserve backslashes
505 zinfo.filename = arcname
506 zinfo.external_attr = 0o600 << 16
507 zipfp.writestr(zinfo, content)
Gregory P. Smith608cc452013-02-01 11:40:18 -0800508
Serhiy Storchaka2a051fa2013-02-02 19:25:57 +0200509 arcname = arcname.replace(os.sep, "/")
Gregory P. Smith608cc452013-02-01 11:40:18 -0800510 targetpath = os.path.join('target', 'subdir', 'subsub')
511 correctfile = os.path.join(targetpath, *fixedname.split('/'))
512
513 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
514 writtenfile = zipfp.extract(arcname, targetpath)
Serhiy Storchaka13e56c72013-02-02 17:46:33 +0200515 self.assertEqual(writtenfile, correctfile,
516 msg="extract %r" % arcname)
Gregory P. Smith608cc452013-02-01 11:40:18 -0800517 self.check_file(correctfile, content)
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400518 rmtree('target')
Gregory P. Smith608cc452013-02-01 11:40:18 -0800519
520 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
521 zipfp.extractall(targetpath)
522 self.check_file(correctfile, content)
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400523 rmtree('target')
Gregory P. Smith608cc452013-02-01 11:40:18 -0800524
525 correctfile = os.path.join(os.getcwd(), *fixedname.split('/'))
526
527 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
528 writtenfile = zipfp.extract(arcname)
Serhiy Storchaka13e56c72013-02-02 17:46:33 +0200529 self.assertEqual(writtenfile, correctfile,
530 msg="extract %r" % arcname)
Gregory P. Smith608cc452013-02-01 11:40:18 -0800531 self.check_file(correctfile, content)
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400532 rmtree(fixedname.split('/')[0])
Gregory P. Smith608cc452013-02-01 11:40:18 -0800533
534 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
535 zipfp.extractall()
536 self.check_file(correctfile, content)
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400537 rmtree(fixedname.split('/')[0])
Gregory P. Smith608cc452013-02-01 11:40:18 -0800538
539 os.remove(TESTFN2)
540
Ronald Oussorendd25e862010-02-07 20:18:02 +0000541 def test_writestr_compression(self):
542 zipfp = zipfile.ZipFile(TESTFN2, "w")
543 zipfp.writestr("a.txt", "hello world", compress_type=zipfile.ZIP_STORED)
544 if zlib:
545 zipfp.writestr("b.txt", "hello world", compress_type=zipfile.ZIP_DEFLATED)
546
547 info = zipfp.getinfo('a.txt')
548 self.assertEqual(info.compress_type, zipfile.ZIP_STORED)
549
550 if zlib:
551 info = zipfp.getinfo('b.txt')
552 self.assertEqual(info.compress_type, zipfile.ZIP_DEFLATED)
553
554
Antoine Pitrou5fdfa3e2008-07-25 19:42:26 +0000555 def zip_test_writestr_permissions(self, f, compression):
556 # Make sure that writestr creates files with mode 0600,
557 # when it is passed a name rather than a ZipInfo instance.
558
Ezio Melottid5a23e32009-07-15 17:07:04 +0000559 self.make_test_archive(f, compression)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000560 with zipfile.ZipFile(f, "r") as zipfp:
561 zinfo = zipfp.getinfo('strfile')
562 self.assertEqual(zinfo.external_attr, 0600 << 16)
Antoine Pitrou5fdfa3e2008-07-25 19:42:26 +0000563
Ezio Melottid5a23e32009-07-15 17:07:04 +0000564 def test_writestr_permissions(self):
Antoine Pitrou5fdfa3e2008-07-25 19:42:26 +0000565 for f in (TESTFN2, TemporaryFile(), StringIO()):
566 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
567
Ezio Melotti569e61f2009-12-30 06:14:51 +0000568 def test_close(self):
569 """Check that the zipfile is closed after the 'with' block."""
570 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
571 for fpath, fdata in SMALL_TEST_DATA:
572 zipfp.writestr(fpath, fdata)
573 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
574 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
575
576 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
577 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
578 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
579
580 def test_close_on_exception(self):
581 """Check that the zipfile is closed if an exception is raised in the
582 'with' block."""
583 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
584 for fpath, fdata in SMALL_TEST_DATA:
585 zipfp.writestr(fpath, fdata)
586
587 try:
588 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
589 raise zipfile.BadZipfile()
590 except zipfile.BadZipfile:
591 self.assertTrue(zipfp2.fp is None, 'zipfp is not closed')
592
Senthil Kumaranddd40312011-10-20 01:38:35 +0800593 def test_add_file_before_1980(self):
594 # Set atime and mtime to 1970-01-01
595 os.utime(TESTFN, (0, 0))
596 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
597 self.assertRaises(ValueError, zipfp.write, TESTFN)
598
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000599 def tearDown(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000600 unlink(TESTFN)
601 unlink(TESTFN2)
602
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000603
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000604class TestZip64InSmallFiles(unittest.TestCase):
605 # These tests test the ZIP64 functionality without using large files,
606 # see test_zipfile64 for proper tests.
607
608 def setUp(self):
609 self._limit = zipfile.ZIP64_LIMIT
Serhiy Storchaka1af262c2014-09-23 22:26:45 +0300610 self._filecount_limit = zipfile.ZIP_FILECOUNT_LIMIT
611 zipfile.ZIP64_LIMIT = 1000
612 zipfile.ZIP_FILECOUNT_LIMIT = 9
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000613
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000614 line_gen = ("Test of zipfile line %d." % i
615 for i in range(0, FIXEDTEST_SIZE))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000616 self.data = '\n'.join(line_gen)
617
618 # Make a source file with some lines
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000619 with open(TESTFN, "wb") as fp:
620 fp.write(self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000621
Ezio Melottid5a23e32009-07-15 17:07:04 +0000622 def large_file_exception_test(self, f, compression):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000623 with zipfile.ZipFile(f, "w", compression) as zipfp:
624 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000625 zipfp.write, TESTFN, "another.name")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000626
Ezio Melottid5a23e32009-07-15 17:07:04 +0000627 def large_file_exception_test2(self, f, compression):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000628 with zipfile.ZipFile(f, "w", compression) as zipfp:
629 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000630 zipfp.writestr, "another.name", self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000631
Ezio Melottid5a23e32009-07-15 17:07:04 +0000632 def test_large_file_exception(self):
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000633 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000634 self.large_file_exception_test(f, zipfile.ZIP_STORED)
635 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000636
Ezio Melottid5a23e32009-07-15 17:07:04 +0000637 def zip_test(self, f, compression):
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000638 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000639 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000640 zipfp.write(TESTFN, "another.name")
Ezio Melotti569e61f2009-12-30 06:14:51 +0000641 zipfp.write(TESTFN, TESTFN)
642 zipfp.writestr("strfile", self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000643
644 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000645 with zipfile.ZipFile(f, "r", compression) as zipfp:
646 self.assertEqual(zipfp.read(TESTFN), self.data)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000647 self.assertEqual(zipfp.read("another.name"), self.data)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000648 self.assertEqual(zipfp.read("strfile"), self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000649
Ezio Melotti569e61f2009-12-30 06:14:51 +0000650 # Print the ZIP directory
651 fp = StringIO()
652 stdout = sys.stdout
653 try:
654 sys.stdout = fp
655 zipfp.printdir()
656 finally:
657 sys.stdout = stdout
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000658
Ezio Melotti569e61f2009-12-30 06:14:51 +0000659 directory = fp.getvalue()
660 lines = directory.splitlines()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000661 self.assertEqual(len(lines), 4) # Number of files + header
Tim Petersa608bb22006-06-15 18:06:29 +0000662
Ezio Melottiaa980582010-01-23 23:04:36 +0000663 self.assertIn('File Name', lines[0])
664 self.assertIn('Modified', lines[0])
665 self.assertIn('Size', lines[0])
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000666
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000667 fn, date, time_, size = lines[1].split()
668 self.assertEqual(fn, 'another.name')
669 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
670 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
671 self.assertEqual(size, str(len(self.data)))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000672
Ezio Melotti569e61f2009-12-30 06:14:51 +0000673 # Check the namelist
674 names = zipfp.namelist()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000675 self.assertEqual(len(names), 3)
Ezio Melottiaa980582010-01-23 23:04:36 +0000676 self.assertIn(TESTFN, names)
677 self.assertIn("another.name", names)
678 self.assertIn("strfile", names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000679
Ezio Melotti569e61f2009-12-30 06:14:51 +0000680 # Check infolist
681 infos = zipfp.infolist()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000682 names = [i.filename for i in infos]
683 self.assertEqual(len(names), 3)
Ezio Melottiaa980582010-01-23 23:04:36 +0000684 self.assertIn(TESTFN, names)
685 self.assertIn("another.name", names)
686 self.assertIn("strfile", names)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000687 for i in infos:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000688 self.assertEqual(i.file_size, len(self.data))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000689
Ezio Melotti569e61f2009-12-30 06:14:51 +0000690 # check getinfo
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000691 for nm in (TESTFN, "another.name", "strfile"):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000692 info = zipfp.getinfo(nm)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000693 self.assertEqual(info.filename, nm)
694 self.assertEqual(info.file_size, len(self.data))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000695
Ezio Melotti569e61f2009-12-30 06:14:51 +0000696 # Check that testzip doesn't raise an exception
697 zipfp.testzip()
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000698
Ezio Melottid5a23e32009-07-15 17:07:04 +0000699 def test_stored(self):
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000700 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000701 self.zip_test(f, zipfile.ZIP_STORED)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000702
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000703 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000704 def test_deflated(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000705 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000706 self.zip_test(f, zipfile.ZIP_DEFLATED)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000707
Ezio Melottid5a23e32009-07-15 17:07:04 +0000708 def test_absolute_arcnames(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000709 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
710 allowZip64=True) as zipfp:
711 zipfp.write(TESTFN, "/absolute")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000712
Ezio Melotti569e61f2009-12-30 06:14:51 +0000713 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
714 self.assertEqual(zipfp.namelist(), ["absolute"])
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000715
Serhiy Storchaka1af262c2014-09-23 22:26:45 +0300716 def test_too_many_files(self):
717 # This test checks that more than 64k files can be added to an archive,
718 # and that the resulting archive can be read properly by ZipFile
719 zipf = zipfile.ZipFile(TESTFN, mode="w", allowZip64=True)
720 zipf.debug = 100
721 numfiles = 15
722 for i in range(numfiles):
723 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
724 self.assertEqual(len(zipf.namelist()), numfiles)
725 zipf.close()
726
727 zipf2 = zipfile.ZipFile(TESTFN, mode="r")
728 self.assertEqual(len(zipf2.namelist()), numfiles)
729 for i in range(numfiles):
730 content = zipf2.read("foo%08d" % i)
731 self.assertEqual(content, "%d" % (i**3 % 57))
732 zipf2.close()
733
734 def test_too_many_files_append(self):
735 zipf = zipfile.ZipFile(TESTFN, mode="w", allowZip64=False)
736 zipf.debug = 100
737 numfiles = 9
738 for i in range(numfiles):
739 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
740 self.assertEqual(len(zipf.namelist()), numfiles)
741 with self.assertRaises(zipfile.LargeZipFile):
742 zipf.writestr("foo%08d" % numfiles, b'')
743 self.assertEqual(len(zipf.namelist()), numfiles)
744 zipf.close()
745
746 zipf = zipfile.ZipFile(TESTFN, mode="a", allowZip64=False)
747 zipf.debug = 100
748 self.assertEqual(len(zipf.namelist()), numfiles)
749 with self.assertRaises(zipfile.LargeZipFile):
750 zipf.writestr("foo%08d" % numfiles, b'')
751 self.assertEqual(len(zipf.namelist()), numfiles)
752 zipf.close()
753
754 zipf = zipfile.ZipFile(TESTFN, mode="a", allowZip64=True)
755 zipf.debug = 100
756 self.assertEqual(len(zipf.namelist()), numfiles)
757 numfiles2 = 15
758 for i in range(numfiles, numfiles2):
759 zipf.writestr("foo%08d" % i, "%d" % (i**3 % 57))
760 self.assertEqual(len(zipf.namelist()), numfiles2)
761 zipf.close()
762
763 zipf2 = zipfile.ZipFile(TESTFN, mode="r")
764 self.assertEqual(len(zipf2.namelist()), numfiles2)
765 for i in range(numfiles2):
766 content = zipf2.read("foo%08d" % i)
767 self.assertEqual(content, "%d" % (i**3 % 57))
768 zipf2.close()
769
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000770 def tearDown(self):
771 zipfile.ZIP64_LIMIT = self._limit
Serhiy Storchaka1af262c2014-09-23 22:26:45 +0300772 zipfile.ZIP_FILECOUNT_LIMIT = self._filecount_limit
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000773 unlink(TESTFN)
774 unlink(TESTFN2)
775
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000776
777class PyZipFileTests(unittest.TestCase):
Serhiy Storchaka4c2bada2015-02-14 23:17:13 +0200778 def requiresWriteAccess(self, path):
779 if not os.access(path, os.W_OK):
780 self.skipTest('requires write access to the installed location')
781
Ezio Melottid5a23e32009-07-15 17:07:04 +0000782 def test_write_pyfile(self):
Serhiy Storchaka4c2bada2015-02-14 23:17:13 +0200783 self.requiresWriteAccess(os.path.dirname(__file__))
Ezio Melotti569e61f2009-12-30 06:14:51 +0000784 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
785 fn = __file__
786 if fn.endswith('.pyc') or fn.endswith('.pyo'):
787 fn = fn[:-1]
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000788
Ezio Melotti569e61f2009-12-30 06:14:51 +0000789 zipfp.writepy(fn)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000790
Ezio Melotti569e61f2009-12-30 06:14:51 +0000791 bn = os.path.basename(fn)
Ezio Melottiaa980582010-01-23 23:04:36 +0000792 self.assertNotIn(bn, zipfp.namelist())
Ezio Melotti569e61f2009-12-30 06:14:51 +0000793 self.assertTrue(bn + 'o' in zipfp.namelist() or
794 bn + 'c' in zipfp.namelist())
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000795
Ezio Melotti569e61f2009-12-30 06:14:51 +0000796 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
797 fn = __file__
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000798 if fn.endswith(('.pyc', '.pyo')):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000799 fn = fn[:-1]
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000800
Ezio Melotti569e61f2009-12-30 06:14:51 +0000801 zipfp.writepy(fn, "testpackage")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000802
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000803 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
Ezio Melottiaa980582010-01-23 23:04:36 +0000804 self.assertNotIn(bn, zipfp.namelist())
Ezio Melotti569e61f2009-12-30 06:14:51 +0000805 self.assertTrue(bn + 'o' in zipfp.namelist() or
806 bn + 'c' in zipfp.namelist())
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000807
Ezio Melottid5a23e32009-07-15 17:07:04 +0000808 def test_write_python_package(self):
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000809 import email
810 packagedir = os.path.dirname(email.__file__)
Serhiy Storchaka4c2bada2015-02-14 23:17:13 +0200811 self.requiresWriteAccess(packagedir)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000812
Ezio Melotti569e61f2009-12-30 06:14:51 +0000813 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
814 zipfp.writepy(packagedir)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000815
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000816 # Check for a couple of modules at different levels of the
817 # hierarchy
Ezio Melotti569e61f2009-12-30 06:14:51 +0000818 names = zipfp.namelist()
819 self.assertTrue('email/__init__.pyo' in names or
820 'email/__init__.pyc' in names)
821 self.assertTrue('email/mime/text.pyo' in names or
822 'email/mime/text.pyc' in names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000823
Ezio Melottid5a23e32009-07-15 17:07:04 +0000824 def test_write_python_directory(self):
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000825 os.mkdir(TESTFN2)
826 try:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000827 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
Ezio Melotti763f1e82009-12-31 13:27:41 +0000828 fp.write("print(42)\n")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000829
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000830 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
Ezio Melotti763f1e82009-12-31 13:27:41 +0000831 fp.write("print(42 * 42)\n")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000832
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000833 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
834 fp.write("bla bla bla\n")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000835
836 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
837 zipfp.writepy(TESTFN2)
838
839 names = zipfp.namelist()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000840 self.assertTrue('mod1.pyc' in names or 'mod1.pyo' in names)
841 self.assertTrue('mod2.pyc' in names or 'mod2.pyo' in names)
Ezio Melottiaa980582010-01-23 23:04:36 +0000842 self.assertNotIn('mod2.txt', names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000843
844 finally:
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400845 rmtree(TESTFN2)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000846
Ezio Melottid5a23e32009-07-15 17:07:04 +0000847 def test_write_non_pyfile(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000848 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400849 with open(TESTFN, 'w') as fid:
850 fid.write('most definitely not a python file')
Ezio Melotti569e61f2009-12-30 06:14:51 +0000851 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
852 os.remove(TESTFN)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000853
854
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000855class OtherTests(unittest.TestCase):
Antoine Pitroue1436d12010-08-12 15:25:51 +0000856 zips_with_bad_crc = {
857 zipfile.ZIP_STORED: (
858 b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
859 b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
860 b'ilehello,AworldP'
861 b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
862 b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
863 b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
864 b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
865 b'\0\0/\0\0\0\0\0'),
866 zipfile.ZIP_DEFLATED: (
867 b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
868 b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
869 b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
870 b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
871 b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
872 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
873 b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
874 b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00'),
875 }
876
Ezio Melottid5a23e32009-07-15 17:07:04 +0000877 def test_unicode_filenames(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000878 with zipfile.ZipFile(TESTFN, "w") as zf:
879 zf.writestr(u"foo.txt", "Test for unicode filename")
880 zf.writestr(u"\xf6.txt", "Test for unicode filename")
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000881 self.assertIsInstance(zf.infolist()[0].filename, unicode)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000882
883 with zipfile.ZipFile(TESTFN, "r") as zf:
884 self.assertEqual(zf.filelist[0].filename, "foo.txt")
885 self.assertEqual(zf.filelist[1].filename, u"\xf6.txt")
Martin v. Löwis471617d2008-05-05 17:16:58 +0000886
Ezio Melottid5a23e32009-07-15 17:07:04 +0000887 def test_create_non_existent_file_for_append(self):
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000888 if os.path.exists(TESTFN):
889 os.unlink(TESTFN)
Tim Petersea5962f2007-03-12 18:07:52 +0000890
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000891 filename = 'testfile.txt'
892 content = 'hello, world. this is some content.'
Tim Petersea5962f2007-03-12 18:07:52 +0000893
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000894 try:
Ezio Melotti569e61f2009-12-30 06:14:51 +0000895 with zipfile.ZipFile(TESTFN, 'a') as zf:
896 zf.writestr(filename, content)
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000897 except IOError:
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000898 self.fail('Could not append data to a non-existent zip file.')
899
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000900 self.assertTrue(os.path.exists(TESTFN))
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000901
Ezio Melotti569e61f2009-12-30 06:14:51 +0000902 with zipfile.ZipFile(TESTFN, 'r') as zf:
903 self.assertEqual(zf.read(filename), content)
Tim Petersea5962f2007-03-12 18:07:52 +0000904
Ezio Melottid5a23e32009-07-15 17:07:04 +0000905 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000906 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000907 # it opens if there's an error in the file. If it doesn't, the
908 # traceback holds a reference to the ZipFile object and, indirectly,
909 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000910 # On Windows, this causes the os.unlink() call to fail because the
911 # underlying file is still open. This is SF bug #412214.
912 #
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000913 with open(TESTFN, "w") as fp:
914 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000915 try:
916 zf = zipfile.ZipFile(TESTFN)
917 except zipfile.BadZipfile:
Collin Winter04a51ec2007-03-29 02:28:16 +0000918 pass
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000919
Ezio Melottid5a23e32009-07-15 17:07:04 +0000920 def test_is_zip_erroneous_file(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000921 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000922 # - passing a filename
923 with open(TESTFN, "w") as fp:
924 fp.write("this is not a legal zip file\n")
Tim Petersea5962f2007-03-12 18:07:52 +0000925 chk = zipfile.is_zipfile(TESTFN)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000926 self.assertFalse(chk)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000927 # - passing a file object
928 with open(TESTFN, "rb") as fp:
929 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000930 self.assertTrue(not chk)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000931 # - passing a file-like object
932 fp = StringIO()
933 fp.write("this is not a legal zip file\n")
934 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000935 self.assertTrue(not chk)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000936 fp.seek(0, 0)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000937 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000938 self.assertTrue(not chk)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000939
Serhiy Storchaka0be506a2013-01-31 15:26:55 +0200940 def test_damaged_zipfile(self):
941 """Check that zipfiles with missing bytes at the end raise BadZipFile."""
942 # - Create a valid zip file
943 fp = io.BytesIO()
944 with zipfile.ZipFile(fp, mode="w") as zipf:
945 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
946 zipfiledata = fp.getvalue()
947
948 # - Now create copies of it missing the last N bytes and make sure
949 # a BadZipFile exception is raised when we try to open it
950 for N in range(len(zipfiledata)):
951 fp = io.BytesIO(zipfiledata[:N])
952 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, fp)
953
Ezio Melottid5a23e32009-07-15 17:07:04 +0000954 def test_is_zip_valid_file(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000955 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000956 # - passing a filename
Ezio Melotti569e61f2009-12-30 06:14:51 +0000957 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
958 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Tim Petersea5962f2007-03-12 18:07:52 +0000959 chk = zipfile.is_zipfile(TESTFN)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000960 self.assertTrue(chk)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000961 # - passing a file object
962 with open(TESTFN, "rb") as fp:
963 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000964 self.assertTrue(chk)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000965 fp.seek(0, 0)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000966 zip_contents = fp.read()
967 # - passing a file-like object
968 fp = StringIO()
969 fp.write(zip_contents)
970 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000971 self.assertTrue(chk)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000972 fp.seek(0, 0)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000973 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000974 self.assertTrue(chk)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000975
Ezio Melottid5a23e32009-07-15 17:07:04 +0000976 def test_non_existent_file_raises_IOError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000977 # make sure we don't raise an AttributeError when a partially-constructed
978 # ZipFile instance is finalized; this tests for regression on SF tracker
979 # bug #403871.
980
981 # The bug we're testing for caused an AttributeError to be raised
982 # when a ZipFile instance was created for a file that did not
983 # exist; the .fp member was not initialized but was needed by the
984 # __del__() method. Since the AttributeError is in the __del__(),
985 # it is ignored, but the user should be sufficiently annoyed by
986 # the message on the output that regression will be noticed
987 # quickly.
988 self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
989
Amaury Forgeot d'Arc3e5b0272009-07-28 22:15:30 +0000990 def test_empty_file_raises_BadZipFile(self):
Brian Curtin0d654332011-04-19 21:15:55 -0500991 with open(TESTFN, 'w') as f:
992 pass
Amaury Forgeot d'Arc3e5b0272009-07-28 22:15:30 +0000993 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN)
994
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000995 with open(TESTFN, 'w') as fp:
996 fp.write("short file")
Amaury Forgeot d'Arc3e5b0272009-07-28 22:15:30 +0000997 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN)
998
Ezio Melottid5a23e32009-07-15 17:07:04 +0000999 def test_closed_zip_raises_RuntimeError(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001000 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001001 data = StringIO()
Ezio Melotti569e61f2009-12-30 06:14:51 +00001002 with zipfile.ZipFile(data, mode="w") as zipf:
1003 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001004
Andrew Svetlov4bb142b2012-12-18 21:27:37 +02001005 # This is correct; calling .read on a closed ZipFile should raise
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001006 # a RuntimeError, and so should calling .testzip. An earlier
1007 # version of .testzip would swallow this exception (and any other)
1008 # and report that the first file in the archive was corrupt.
Georg Brandl4b3ab6f2007-07-12 09:59:22 +00001009 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
1010 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001011 self.assertRaises(RuntimeError, zipf.testzip)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +00001012 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Benjamin Peterson352eb4f2014-04-03 10:31:25 -04001013 with open(TESTFN, 'w') as fid:
1014 fid.write('zipfile test data')
1015 self.assertRaises(RuntimeError, zipf.write, TESTFN)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +00001016
Ezio Melottid5a23e32009-07-15 17:07:04 +00001017 def test_bad_constructor_mode(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001018 """Check that bad modes passed to ZipFile constructor are caught."""
Georg Brandl4b3ab6f2007-07-12 09:59:22 +00001019 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
1020
Ezio Melottid5a23e32009-07-15 17:07:04 +00001021 def test_bad_open_mode(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001022 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melotti569e61f2009-12-30 06:14:51 +00001023 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1024 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1025
1026 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Georg Brandl4b3ab6f2007-07-12 09:59:22 +00001027 # read the data to make sure the file is there
Ezio Melotti569e61f2009-12-30 06:14:51 +00001028 zipf.read("foo.txt")
1029 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
Georg Brandl4b3ab6f2007-07-12 09:59:22 +00001030
Ezio Melottid5a23e32009-07-15 17:07:04 +00001031 def test_read0(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001032 """Check that calling read(0) on a ZipExtFile object returns an empty
1033 string and doesn't advance file pointer."""
Ezio Melotti569e61f2009-12-30 06:14:51 +00001034 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1035 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1036 # read the data to make sure the file is there
Brian Curtin0d654332011-04-19 21:15:55 -05001037 with zipf.open("foo.txt") as f:
1038 for i in xrange(FIXEDTEST_SIZE):
1039 self.assertEqual(f.read(0), '')
Georg Brandl4b3ab6f2007-07-12 09:59:22 +00001040
Brian Curtin0d654332011-04-19 21:15:55 -05001041 self.assertEqual(f.read(), "O, for a Muse of Fire!")
Georg Brandl4b3ab6f2007-07-12 09:59:22 +00001042
Ezio Melottid5a23e32009-07-15 17:07:04 +00001043 def test_open_non_existent_item(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001044 """Check that attempting to call open() for an item that doesn't
1045 exist in the archive raises a RuntimeError."""
Ezio Melotti569e61f2009-12-30 06:14:51 +00001046 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1047 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Georg Brandl4b3ab6f2007-07-12 09:59:22 +00001048
Ezio Melottid5a23e32009-07-15 17:07:04 +00001049 def test_bad_compression_mode(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001050 """Check that bad compression methods passed to ZipFile.open are
1051 caught."""
Georg Brandl4b3ab6f2007-07-12 09:59:22 +00001052 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
1053
Ezio Melotti9e949722012-11-18 13:18:06 +02001054 def test_unsupported_compression(self):
1055 # data is declared as shrunk, but actually deflated
1056 data = (b'PK\x03\x04.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00'
1057 b'\x00\x02\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00x\x03\x00PK\x01'
1058 b'\x02.\x03.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00\x00\x02\x00\x00'
1059 b'\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
1060 b'\x80\x01\x00\x00\x00\x00xPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00'
1061 b'/\x00\x00\x00!\x00\x00\x00\x00\x00')
1062 with zipfile.ZipFile(io.BytesIO(data), 'r') as zipf:
1063 self.assertRaises(NotImplementedError, zipf.open, 'x')
1064
Ezio Melottid5a23e32009-07-15 17:07:04 +00001065 def test_null_byte_in_filename(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001066 """Check that a filename containing a null byte is properly
1067 terminated."""
Ezio Melotti569e61f2009-12-30 06:14:51 +00001068 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1069 zipf.writestr("foo.txt\x00qqq", "O, for a Muse of Fire!")
1070 self.assertEqual(zipf.namelist(), ['foo.txt'])
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00001071
Ezio Melottid5a23e32009-07-15 17:07:04 +00001072 def test_struct_sizes(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001073 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwis8c436412008-07-03 12:51:14 +00001074 self.assertEqual(zipfile.sizeEndCentDir, 22)
1075 self.assertEqual(zipfile.sizeCentralDir, 46)
1076 self.assertEqual(zipfile.sizeEndCentDir64, 56)
1077 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
1078
Ezio Melottid5a23e32009-07-15 17:07:04 +00001079 def test_comments(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001080 """Check that comments on the archive are handled properly."""
Martin v. Löwis8c436412008-07-03 12:51:14 +00001081
1082 # check default comment is empty
Ezio Melotti569e61f2009-12-30 06:14:51 +00001083 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1084 self.assertEqual(zipf.comment, '')
1085 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1086
1087 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
1088 self.assertEqual(zipf.comment, '')
Martin v. Löwis8c436412008-07-03 12:51:14 +00001089
1090 # check a simple short comment
1091 comment = 'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melotti569e61f2009-12-30 06:14:51 +00001092 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1093 zipf.comment = comment
1094 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1095 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
1096 self.assertEqual(zipf.comment, comment)
Martin v. Löwis8c436412008-07-03 12:51:14 +00001097
1098 # check a comment of max length
1099 comment2 = ''.join(['%d' % (i**3 % 10) for i in xrange((1 << 16)-1)])
Ezio Melotti569e61f2009-12-30 06:14:51 +00001100 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1101 zipf.comment = comment2
1102 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1103
1104 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
1105 self.assertEqual(zipf.comment, comment2)
Martin v. Löwis8c436412008-07-03 12:51:14 +00001106
1107 # check a comment that is too long is truncated
Ezio Melotti569e61f2009-12-30 06:14:51 +00001108 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
Serhiy Storchaka49259352014-01-20 21:57:09 +02001109 with check_warnings(('', UserWarning)):
1110 zipf.comment = comment2 + 'oops'
Ezio Melotti569e61f2009-12-30 06:14:51 +00001111 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1112 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
1113 self.assertEqual(zipf.comment, comment2)
Martin v. Löwis8c436412008-07-03 12:51:14 +00001114
R David Murray3f4ccba2012-04-12 18:42:47 -04001115 def test_change_comment_in_empty_archive(self):
1116 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1117 self.assertFalse(zipf.filelist)
1118 zipf.comment = b"this is a comment"
1119 with zipfile.ZipFile(TESTFN, "r") as zipf:
1120 self.assertEqual(zipf.comment, b"this is a comment")
1121
1122 def test_change_comment_in_nonempty_archive(self):
1123 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1124 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1125 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1126 self.assertTrue(zipf.filelist)
1127 zipf.comment = b"this is a comment"
1128 with zipfile.ZipFile(TESTFN, "r") as zipf:
1129 self.assertEqual(zipf.comment, b"this is a comment")
1130
Antoine Pitroue1436d12010-08-12 15:25:51 +00001131 def check_testzip_with_bad_crc(self, compression):
1132 """Tests that files with bad CRCs return their name from testzip."""
1133 zipdata = self.zips_with_bad_crc[compression]
1134
1135 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1136 # testzip returns the name of the first corrupt file, or None
1137 self.assertEqual('afile', zipf.testzip())
1138
1139 def test_testzip_with_bad_crc_stored(self):
1140 self.check_testzip_with_bad_crc(zipfile.ZIP_STORED)
1141
1142 @skipUnless(zlib, "requires zlib")
1143 def test_testzip_with_bad_crc_deflated(self):
1144 self.check_testzip_with_bad_crc(zipfile.ZIP_DEFLATED)
1145
1146 def check_read_with_bad_crc(self, compression):
1147 """Tests that files with bad CRCs raise a BadZipfile exception when read."""
1148 zipdata = self.zips_with_bad_crc[compression]
1149
1150 # Using ZipFile.read()
1151 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1152 self.assertRaises(zipfile.BadZipfile, zipf.read, 'afile')
1153
1154 # Using ZipExtFile.read()
1155 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1156 with zipf.open('afile', 'r') as corrupt_file:
1157 self.assertRaises(zipfile.BadZipfile, corrupt_file.read)
1158
1159 # Same with small reads (in order to exercise the buffering logic)
1160 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1161 with zipf.open('afile', 'r') as corrupt_file:
1162 corrupt_file.MIN_READ_SIZE = 2
1163 with self.assertRaises(zipfile.BadZipfile):
1164 while corrupt_file.read(2):
1165 pass
1166
1167 def test_read_with_bad_crc_stored(self):
1168 self.check_read_with_bad_crc(zipfile.ZIP_STORED)
1169
1170 @skipUnless(zlib, "requires zlib")
1171 def test_read_with_bad_crc_deflated(self):
1172 self.check_read_with_bad_crc(zipfile.ZIP_DEFLATED)
1173
Antoine Pitroue4195e82010-09-12 14:56:27 +00001174 def check_read_return_size(self, compression):
1175 # Issue #9837: ZipExtFile.read() shouldn't return more bytes
1176 # than requested.
1177 for test_size in (1, 4095, 4096, 4097, 16384):
1178 file_size = test_size + 1
Serhiy Storchaka45aa7712014-12-03 09:11:12 +02001179 junk = getrandbytes(file_size)
Antoine Pitroue4195e82010-09-12 14:56:27 +00001180 with zipfile.ZipFile(io.BytesIO(), "w", compression) as zipf:
1181 zipf.writestr('foo', junk)
1182 with zipf.open('foo', 'r') as fp:
1183 buf = fp.read(test_size)
1184 self.assertEqual(len(buf), test_size)
1185
1186 def test_read_return_size_stored(self):
1187 self.check_read_return_size(zipfile.ZIP_STORED)
1188
1189 @skipUnless(zlib, "requires zlib")
1190 def test_read_return_size_deflated(self):
1191 self.check_read_return_size(zipfile.ZIP_DEFLATED)
1192
Georg Brandl86e0c892010-11-26 07:22:28 +00001193 def test_empty_zipfile(self):
1194 # Check that creating a file in 'w' or 'a' mode and closing without
1195 # adding any files to the archives creates a valid empty ZIP file
Brian Curtin0d654332011-04-19 21:15:55 -05001196 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1197 pass
Georg Brandl86e0c892010-11-26 07:22:28 +00001198 try:
1199 zipf = zipfile.ZipFile(TESTFN, mode="r")
Benjamin Peterson352eb4f2014-04-03 10:31:25 -04001200 zipf.close()
Éric Araujo67843b32011-02-02 17:03:38 +00001201 except zipfile.BadZipfile:
Georg Brandl86e0c892010-11-26 07:22:28 +00001202 self.fail("Unable to create empty ZIP file in 'w' mode")
1203
Brian Curtin0d654332011-04-19 21:15:55 -05001204 with zipfile.ZipFile(TESTFN, mode="a") as zipf:
1205 pass
Georg Brandl86e0c892010-11-26 07:22:28 +00001206 try:
1207 zipf = zipfile.ZipFile(TESTFN, mode="r")
Benjamin Peterson352eb4f2014-04-03 10:31:25 -04001208 zipf.close()
Georg Brandl86e0c892010-11-26 07:22:28 +00001209 except:
1210 self.fail("Unable to create empty ZIP file in 'a' mode")
1211
1212 def test_open_empty_file(self):
1213 # Issue 1710703: Check that opening a file with less than 22 bytes
1214 # raises a BadZipfile exception (rather than the previously unhelpful
1215 # IOError)
Brian Curtin0d654332011-04-19 21:15:55 -05001216 with open(TESTFN, 'w') as f:
1217 pass
Georg Brandl86e0c892010-11-26 07:22:28 +00001218 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN, 'r')
1219
Senthil Kumaranddd40312011-10-20 01:38:35 +08001220 def test_create_zipinfo_before_1980(self):
1221 self.assertRaises(ValueError,
1222 zipfile.ZipInfo, 'seventies', (1979, 1, 1, 0, 0, 0))
1223
Gregory P. Smith0344a062014-05-29 23:41:52 -07001224 def test_zipfile_with_short_extra_field(self):
1225 """If an extra field in the header is less than 4 bytes, skip it."""
1226 zipdata = (
1227 b'PK\x03\x04\x14\x00\x00\x00\x00\x00\x93\x9b\xad@\x8b\x9e'
1228 b'\xd9\xd3\x01\x00\x00\x00\x01\x00\x00\x00\x03\x00\x03\x00ab'
1229 b'c\x00\x00\x00APK\x01\x02\x14\x03\x14\x00\x00\x00\x00'
1230 b'\x00\x93\x9b\xad@\x8b\x9e\xd9\xd3\x01\x00\x00\x00\x01\x00\x00'
1231 b'\x00\x03\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00'
1232 b'\x00\x00\x00abc\x00\x00PK\x05\x06\x00\x00\x00\x00'
1233 b'\x01\x00\x01\x003\x00\x00\x00%\x00\x00\x00\x00\x00'
1234 )
1235 with zipfile.ZipFile(io.BytesIO(zipdata), 'r') as zipf:
1236 # testzip returns the name of the first corrupt file, or None
1237 self.assertIsNone(zipf.testzip())
1238
Collin Winter04a51ec2007-03-29 02:28:16 +00001239 def tearDown(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001240 unlink(TESTFN)
1241 unlink(TESTFN2)
1242
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001243
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001244class DecryptionTests(unittest.TestCase):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001245 """Check that ZIP decryption works. Since the library does not
1246 support encryption at the moment, we use a pre-generated encrypted
1247 ZIP file."""
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001248
1249 data = (
1250 'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
1251 '\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
1252 '\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
1253 'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
1254 '\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
1255 '\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
1256 '\x00\x00L\x00\x00\x00\x00\x00' )
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001257 data2 = (
1258 'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
1259 '\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
1260 '\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
1261 'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
1262 '\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
1263 '\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
1264 'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
1265 '\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001266
1267 plain = 'zipfile.py encryption test'
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001268 plain2 = '\x00'*512
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001269
1270 def setUp(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001271 with open(TESTFN, "wb") as fp:
1272 fp.write(self.data)
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001273 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001274 with open(TESTFN2, "wb") as fp:
1275 fp.write(self.data2)
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001276 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001277
1278 def tearDown(self):
1279 self.zip.close()
1280 os.unlink(TESTFN)
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001281 self.zip2.close()
1282 os.unlink(TESTFN2)
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001283
Ezio Melottid5a23e32009-07-15 17:07:04 +00001284 def test_no_password(self):
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001285 # Reading the encrypted file without password
1286 # must generate a RunTime exception
1287 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001288 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001289
Ezio Melottid5a23e32009-07-15 17:07:04 +00001290 def test_bad_password(self):
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001291 self.zip.setpassword("perl")
1292 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001293 self.zip2.setpassword("perl")
1294 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Tim Petersea5962f2007-03-12 18:07:52 +00001295
Ezio Melotti1036a7f2009-09-12 14:43:43 +00001296 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +00001297 def test_good_password(self):
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001298 self.zip.setpassword("python")
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001299 self.assertEqual(self.zip.read("test.txt"), self.plain)
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001300 self.zip2.setpassword("12345")
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001301 self.assertEqual(self.zip2.read("zero"), self.plain2)
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001302
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001303
1304class TestsWithRandomBinaryFiles(unittest.TestCase):
1305 def setUp(self):
1306 datacount = randint(16, 64)*1024 + randint(1, 1024)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001307 self.data = ''.join(struct.pack('<f', random()*randint(-1000, 1000))
Ezio Melotti763f1e82009-12-31 13:27:41 +00001308 for i in xrange(datacount))
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001309
1310 # Make a source file with some lines
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001311 with open(TESTFN, "wb") as fp:
1312 fp.write(self.data)
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00001313
Collin Winter04a51ec2007-03-29 02:28:16 +00001314 def tearDown(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001315 unlink(TESTFN)
1316 unlink(TESTFN2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001317
Ezio Melottid5a23e32009-07-15 17:07:04 +00001318 def make_test_archive(self, f, compression):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001319 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001320 with zipfile.ZipFile(f, "w", compression) as zipfp:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001321 zipfp.write(TESTFN, "another.name")
Ezio Melotti569e61f2009-12-30 06:14:51 +00001322 zipfp.write(TESTFN, TESTFN)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001323
Ezio Melottid5a23e32009-07-15 17:07:04 +00001324 def zip_test(self, f, compression):
1325 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001326
1327 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001328 with zipfile.ZipFile(f, "r", compression) as zipfp:
1329 testdata = zipfp.read(TESTFN)
1330 self.assertEqual(len(testdata), len(self.data))
1331 self.assertEqual(testdata, self.data)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001332 self.assertEqual(zipfp.read("another.name"), self.data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001333
Ezio Melottid5a23e32009-07-15 17:07:04 +00001334 def test_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001335 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001336 self.zip_test(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +00001337
Antoine Pitroue1436d12010-08-12 15:25:51 +00001338 @skipUnless(zlib, "requires zlib")
1339 def test_deflated(self):
1340 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1341 self.zip_test(f, zipfile.ZIP_DEFLATED)
1342
Ezio Melottid5a23e32009-07-15 17:07:04 +00001343 def zip_open_test(self, f, compression):
1344 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001345
1346 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001347 with zipfile.ZipFile(f, "r", compression) as zipfp:
1348 zipdata1 = []
Brian Curtin0d654332011-04-19 21:15:55 -05001349 with zipfp.open(TESTFN) as zipopen1:
1350 while True:
1351 read_data = zipopen1.read(256)
1352 if not read_data:
1353 break
1354 zipdata1.append(read_data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001355
Ezio Melotti569e61f2009-12-30 06:14:51 +00001356 zipdata2 = []
Brian Curtin0d654332011-04-19 21:15:55 -05001357 with zipfp.open("another.name") as zipopen2:
1358 while True:
1359 read_data = zipopen2.read(256)
1360 if not read_data:
1361 break
1362 zipdata2.append(read_data)
Tim Petersea5962f2007-03-12 18:07:52 +00001363
Ezio Melotti569e61f2009-12-30 06:14:51 +00001364 testdata1 = ''.join(zipdata1)
1365 self.assertEqual(len(testdata1), len(self.data))
1366 self.assertEqual(testdata1, self.data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001367
Ezio Melotti569e61f2009-12-30 06:14:51 +00001368 testdata2 = ''.join(zipdata2)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001369 self.assertEqual(len(testdata2), len(self.data))
1370 self.assertEqual(testdata2, self.data)
Tim Petersea5962f2007-03-12 18:07:52 +00001371
Ezio Melottid5a23e32009-07-15 17:07:04 +00001372 def test_open_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001373 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001374 self.zip_open_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001375
Antoine Pitroue1436d12010-08-12 15:25:51 +00001376 @skipUnless(zlib, "requires zlib")
1377 def test_open_deflated(self):
1378 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1379 self.zip_open_test(f, zipfile.ZIP_DEFLATED)
1380
Ezio Melottid5a23e32009-07-15 17:07:04 +00001381 def zip_random_open_test(self, f, compression):
1382 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001383
1384 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001385 with zipfile.ZipFile(f, "r", compression) as zipfp:
1386 zipdata1 = []
Brian Curtin0d654332011-04-19 21:15:55 -05001387 with zipfp.open(TESTFN) as zipopen1:
1388 while True:
1389 read_data = zipopen1.read(randint(1, 1024))
1390 if not read_data:
1391 break
1392 zipdata1.append(read_data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001393
Ezio Melotti569e61f2009-12-30 06:14:51 +00001394 testdata = ''.join(zipdata1)
1395 self.assertEqual(len(testdata), len(self.data))
1396 self.assertEqual(testdata, self.data)
Tim Petersea5962f2007-03-12 18:07:52 +00001397
Ezio Melottid5a23e32009-07-15 17:07:04 +00001398 def test_random_open_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001399 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001400 self.zip_random_open_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001401
Antoine Pitroue1436d12010-08-12 15:25:51 +00001402 @skipUnless(zlib, "requires zlib")
1403 def test_random_open_deflated(self):
1404 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1405 self.zip_random_open_test(f, zipfile.ZIP_DEFLATED)
1406
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001407
Ezio Melotti1036a7f2009-09-12 14:43:43 +00001408@skipUnless(zlib, "requires zlib")
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001409class TestsWithMultipleOpens(unittest.TestCase):
Serhiy Storchaka45aa7712014-12-03 09:11:12 +02001410 @classmethod
1411 def setUpClass(cls):
1412 cls.data1 = b'111' + getrandbytes(10000)
1413 cls.data2 = b'222' + getrandbytes(10000)
1414
1415 def make_test_archive(self, f):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001416 # Create the ZIP archive
Serhiy Storchaka45aa7712014-12-03 09:11:12 +02001417 with zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as zipfp:
1418 zipfp.writestr('ones', self.data1)
1419 zipfp.writestr('twos', self.data2)
Tim Petersea5962f2007-03-12 18:07:52 +00001420
Ezio Melottid5a23e32009-07-15 17:07:04 +00001421 def test_same_file(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001422 # Verify that (when the ZipFile is in control of creating file objects)
1423 # multiple open() calls can be made without interfering with each other.
Serhiy Storchakac328d112015-01-26 13:45:04 +02001424 self.make_test_archive(TESTFN2)
1425 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
1426 with zipf.open('ones') as zopen1, zipf.open('ones') as zopen2:
Brian Curtin0d654332011-04-19 21:15:55 -05001427 data1 = zopen1.read(500)
1428 data2 = zopen2.read(500)
Serhiy Storchaka45aa7712014-12-03 09:11:12 +02001429 data1 += zopen1.read()
1430 data2 += zopen2.read()
Serhiy Storchakac328d112015-01-26 13:45:04 +02001431 self.assertEqual(data1, data2)
1432 self.assertEqual(data1, self.data1)
1433
1434 def test_different_file(self):
1435 # Verify that (when the ZipFile is in control of creating file objects)
1436 # multiple open() calls can be made without interfering with each other.
1437 self.make_test_archive(TESTFN2)
1438 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
1439 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1440 data1 = zopen1.read(500)
1441 data2 = zopen2.read(500)
1442 data1 += zopen1.read()
1443 data2 += zopen2.read()
Serhiy Storchaka45aa7712014-12-03 09:11:12 +02001444 self.assertEqual(data1, self.data1)
1445 self.assertEqual(data2, self.data2)
1446
Serhiy Storchakac328d112015-01-26 13:45:04 +02001447 def test_interleaved(self):
1448 # Verify that (when the ZipFile is in control of creating file objects)
1449 # multiple open() calls can be made without interfering with each other.
1450 self.make_test_archive(TESTFN2)
1451 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
1452 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1453 data1 = zopen1.read(500)
1454 data2 = zopen2.read(500)
1455 data1 += zopen1.read()
1456 data2 += zopen2.read()
1457 self.assertEqual(data1, self.data1)
1458 self.assertEqual(data2, self.data2)
1459
1460 def test_read_after_close(self):
1461 self.make_test_archive(TESTFN2)
1462 zopen1 = zopen2 = None
1463 try:
1464 with zipfile.ZipFile(TESTFN2, 'r') as zipf:
1465 zopen1 = zipf.open('ones')
1466 zopen2 = zipf.open('twos')
1467 data1 = zopen1.read(500)
1468 data2 = zopen2.read(500)
1469 data1 += zopen1.read()
1470 data2 += zopen2.read()
1471 finally:
1472 if zopen1:
1473 zopen1.close()
1474 if zopen2:
1475 zopen2.close()
1476 self.assertEqual(data1, self.data1)
1477 self.assertEqual(data2, self.data2)
1478
Serhiy Storchaka45aa7712014-12-03 09:11:12 +02001479 def test_read_after_write(self):
Serhiy Storchakac328d112015-01-26 13:45:04 +02001480 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_DEFLATED) as zipf:
1481 zipf.writestr('ones', self.data1)
1482 zipf.writestr('twos', self.data2)
1483 with zipf.open('ones') as zopen1:
1484 data1 = zopen1.read(500)
1485 self.assertEqual(data1, self.data1[:500])
1486 with zipfile.ZipFile(TESTFN2, 'r') as zipf:
1487 data1 = zipf.read('ones')
1488 data2 = zipf.read('twos')
1489 self.assertEqual(data1, self.data1)
1490 self.assertEqual(data2, self.data2)
Serhiy Storchaka45aa7712014-12-03 09:11:12 +02001491
1492 def test_write_after_read(self):
Serhiy Storchakac328d112015-01-26 13:45:04 +02001493 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipf:
1494 zipf.writestr('ones', self.data1)
1495 with zipf.open('ones') as zopen1:
1496 zopen1.read(500)
1497 zipf.writestr('twos', self.data2)
1498 with zipfile.ZipFile(TESTFN2, 'r') as zipf:
1499 data1 = zipf.read('ones')
1500 data2 = zipf.read('twos')
1501 self.assertEqual(data1, self.data1)
1502 self.assertEqual(data2, self.data2)
Tim Petersea5962f2007-03-12 18:07:52 +00001503
Benjamin Peterson352eb4f2014-04-03 10:31:25 -04001504 def test_many_opens(self):
1505 # Verify that read() and open() promptly close the file descriptor,
1506 # and don't rely on the garbage collector to free resources.
Serhiy Storchaka45aa7712014-12-03 09:11:12 +02001507 self.make_test_archive(TESTFN2)
Benjamin Peterson352eb4f2014-04-03 10:31:25 -04001508 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
1509 for x in range(100):
1510 zipf.read('ones')
1511 with zipf.open('ones') as zopen1:
1512 pass
1513 with open(os.devnull) as f:
1514 self.assertLess(f.fileno(), 100)
1515
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001516 def tearDown(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001517 unlink(TESTFN2)
1518
Tim Petersea5962f2007-03-12 18:07:52 +00001519
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001520class TestWithDirectory(unittest.TestCase):
1521 def setUp(self):
1522 os.mkdir(TESTFN2)
1523
Ezio Melottid5a23e32009-07-15 17:07:04 +00001524 def test_extract_dir(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +00001525 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
1526 zipf.extractall(TESTFN2)
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001527 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1528 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1529 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1530
Ezio Melottid5a23e32009-07-15 17:07:04 +00001531 def test_bug_6050(self):
Martin v. Löwis0b09c422009-05-24 19:30:52 +00001532 # Extraction should succeed if directories already exist
1533 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottid5a23e32009-07-15 17:07:04 +00001534 self.test_extract_dir()
Martin v. Löwis0b09c422009-05-24 19:30:52 +00001535
Serhiy Storchaka6d343e72014-09-23 22:39:59 +03001536 def test_write_dir(self):
1537 dirpath = os.path.join(TESTFN2, "x")
1538 os.mkdir(dirpath)
1539 mode = os.stat(dirpath).st_mode & 0xFFFF
1540 with zipfile.ZipFile(TESTFN, "w") as zipf:
1541 zipf.write(dirpath)
1542 zinfo = zipf.filelist[0]
1543 self.assertTrue(zinfo.filename.endswith("/x/"))
1544 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1545 zipf.write(dirpath, "y")
1546 zinfo = zipf.filelist[1]
1547 self.assertTrue(zinfo.filename, "y/")
1548 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1549 with zipfile.ZipFile(TESTFN, "r") as zipf:
1550 zinfo = zipf.filelist[0]
1551 self.assertTrue(zinfo.filename.endswith("/x/"))
1552 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1553 zinfo = zipf.filelist[1]
1554 self.assertTrue(zinfo.filename, "y/")
1555 self.assertEqual(zinfo.external_attr, (mode << 16) | 0x10)
1556 target = os.path.join(TESTFN2, "target")
1557 os.mkdir(target)
1558 zipf.extractall(target)
1559 self.assertTrue(os.path.isdir(os.path.join(target, "y")))
1560 self.assertEqual(len(os.listdir(target)), 2)
1561
1562 def test_writestr_dir(self):
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001563 os.mkdir(os.path.join(TESTFN2, "x"))
Benjamin Peterson352eb4f2014-04-03 10:31:25 -04001564 with zipfile.ZipFile(TESTFN, "w") as zipf:
Serhiy Storchaka6d343e72014-09-23 22:39:59 +03001565 zipf.writestr("x/", b'')
1566 zinfo = zipf.filelist[0]
1567 self.assertEqual(zinfo.filename, "x/")
1568 self.assertEqual(zinfo.external_attr, (0o40775 << 16) | 0x10)
1569 with zipfile.ZipFile(TESTFN, "r") as zipf:
1570 zinfo = zipf.filelist[0]
1571 self.assertTrue(zinfo.filename.endswith("x/"))
1572 self.assertEqual(zinfo.external_attr, (0o40775 << 16) | 0x10)
1573 target = os.path.join(TESTFN2, "target")
1574 os.mkdir(target)
1575 zipf.extractall(target)
1576 self.assertTrue(os.path.isdir(os.path.join(target, "x")))
1577 self.assertEqual(os.listdir(target), ["x"])
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001578
1579 def tearDown(self):
Benjamin Peterson352eb4f2014-04-03 10:31:25 -04001580 rmtree(TESTFN2)
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001581 if os.path.exists(TESTFN):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001582 unlink(TESTFN)
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001583
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001584
1585class UniversalNewlineTests(unittest.TestCase):
1586 def setUp(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001587 self.line_gen = ["Test of zipfile line %d." % i
1588 for i in xrange(FIXEDTEST_SIZE)]
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001589 self.seps = ('\r', '\r\n', '\n')
1590 self.arcdata, self.arcfiles = {}, {}
1591 for n, s in enumerate(self.seps):
1592 self.arcdata[s] = s.join(self.line_gen) + s
1593 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Benjamin Peterson352eb4f2014-04-03 10:31:25 -04001594 with open(self.arcfiles[s], "wb") as fid:
1595 fid.write(self.arcdata[s])
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001596
Ezio Melottid5a23e32009-07-15 17:07:04 +00001597 def make_test_archive(self, f, compression):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001598 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001599 with zipfile.ZipFile(f, "w", compression) as zipfp:
1600 for fn in self.arcfiles.values():
1601 zipfp.write(fn, fn)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001602
Ezio Melottid5a23e32009-07-15 17:07:04 +00001603 def read_test(self, f, compression):
1604 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001605
1606 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001607 with zipfile.ZipFile(f, "r") as zipfp:
1608 for sep, fn in self.arcfiles.items():
Brian Curtin0d654332011-04-19 21:15:55 -05001609 with zipfp.open(fn, "rU") as fp:
1610 zipdata = fp.read()
Ezio Melotti569e61f2009-12-30 06:14:51 +00001611 self.assertEqual(self.arcdata[sep], zipdata)
Tim Petersea5962f2007-03-12 18:07:52 +00001612
Antoine Pitrou94c33eb2010-01-27 20:59:50 +00001613 def readline_read_test(self, f, compression):
1614 self.make_test_archive(f, compression)
1615
1616 # Read the ZIP archive
1617 zipfp = zipfile.ZipFile(f, "r")
1618 for sep, fn in self.arcfiles.items():
Brian Curtin0d654332011-04-19 21:15:55 -05001619 with zipfp.open(fn, "rU") as zipopen:
1620 data = ''
1621 while True:
1622 read = zipopen.readline()
1623 if not read:
1624 break
1625 data += read
Antoine Pitrou94c33eb2010-01-27 20:59:50 +00001626
Brian Curtin0d654332011-04-19 21:15:55 -05001627 read = zipopen.read(5)
1628 if not read:
1629 break
1630 data += read
Antoine Pitrou94c33eb2010-01-27 20:59:50 +00001631
1632 self.assertEqual(data, self.arcdata['\n'])
1633
1634 zipfp.close()
1635
Ezio Melottid5a23e32009-07-15 17:07:04 +00001636 def readline_test(self, f, compression):
1637 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001638
1639 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001640 with zipfile.ZipFile(f, "r") as zipfp:
1641 for sep, fn in self.arcfiles.items():
Brian Curtin0d654332011-04-19 21:15:55 -05001642 with zipfp.open(fn, "rU") as zipopen:
1643 for line in self.line_gen:
1644 linedata = zipopen.readline()
1645 self.assertEqual(linedata, line + '\n')
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001646
Ezio Melottid5a23e32009-07-15 17:07:04 +00001647 def readlines_test(self, f, compression):
1648 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001649
1650 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001651 with zipfile.ZipFile(f, "r") as zipfp:
1652 for sep, fn in self.arcfiles.items():
Brian Curtin0d654332011-04-19 21:15:55 -05001653 with zipfp.open(fn, "rU") as fp:
1654 ziplines = fp.readlines()
Ezio Melotti569e61f2009-12-30 06:14:51 +00001655 for line, zipline in zip(self.line_gen, ziplines):
1656 self.assertEqual(zipline, line + '\n')
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001657
Ezio Melottid5a23e32009-07-15 17:07:04 +00001658 def iterlines_test(self, f, compression):
1659 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001660
1661 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001662 with zipfile.ZipFile(f, "r") as zipfp:
1663 for sep, fn in self.arcfiles.items():
Benjamin Peterson352eb4f2014-04-03 10:31:25 -04001664 with zipfp.open(fn, "rU") as fid:
1665 for line, zipline in zip(self.line_gen, fid):
1666 self.assertEqual(zipline, line + '\n')
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001667
Ezio Melottid5a23e32009-07-15 17:07:04 +00001668 def test_read_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001669 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001670 self.read_test(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +00001671
Antoine Pitrou94c33eb2010-01-27 20:59:50 +00001672 def test_readline_read_stored(self):
1673 # Issue #7610: calls to readline() interleaved with calls to read().
1674 for f in (TESTFN2, TemporaryFile(), StringIO()):
1675 self.readline_read_test(f, zipfile.ZIP_STORED)
1676
Ezio Melottid5a23e32009-07-15 17:07:04 +00001677 def test_readline_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001678 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001679 self.readline_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001680
Ezio Melottid5a23e32009-07-15 17:07:04 +00001681 def test_readlines_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001682 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001683 self.readlines_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001684
Ezio Melottid5a23e32009-07-15 17:07:04 +00001685 def test_iterlines_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001686 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001687 self.iterlines_test(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +00001688
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001689 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +00001690 def test_read_deflated(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001691 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001692 self.read_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001693
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001694 @skipUnless(zlib, "requires zlib")
Antoine Pitrou94c33eb2010-01-27 20:59:50 +00001695 def test_readline_read_deflated(self):
1696 # Issue #7610: calls to readline() interleaved with calls to read().
1697 for f in (TESTFN2, TemporaryFile(), StringIO()):
1698 self.readline_read_test(f, zipfile.ZIP_DEFLATED)
1699
1700 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +00001701 def test_readline_deflated(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001702 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001703 self.readline_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001704
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001705 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +00001706 def test_readlines_deflated(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001707 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001708 self.readlines_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001709
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001710 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +00001711 def test_iterlines_deflated(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001712 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001713 self.iterlines_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001714
1715 def tearDown(self):
1716 for sep, fn in self.arcfiles.items():
1717 os.remove(fn)
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001718 unlink(TESTFN)
1719 unlink(TESTFN2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001720
1721
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001722def test_main():
Tim Petersea5962f2007-03-12 18:07:52 +00001723 run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
1724 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001725 TestWithDirectory, UniversalNewlineTests,
1726 TestsWithRandomBinaryFiles)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001727
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001728if __name__ == "__main__":
1729 test_main()