blob: 6bf5c2f3189b7b63a67463d5363f5921af024d14 [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
Martin v. Löwis3eb76482007-03-06 10:41:24 +000017from random import randint, random
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
Ezio Melotti6cbfc122009-07-10 20:25:56 +000038
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000039class TestsWithSourceFile(unittest.TestCase):
40 def setUp(self):
Georg Brandl4b3ab6f2007-07-12 09:59:22 +000041 self.line_gen = ["Zipfile test line %d. random float: %f" % (i, random())
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000042 for i in xrange(FIXEDTEST_SIZE)]
Martin v. Löwis3eb76482007-03-06 10:41:24 +000043 self.data = '\n'.join(self.line_gen) + '\n'
Fred Drake6e7e4852001-02-28 05:34:16 +000044
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000045 # Make a source file with some lines
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000046 with open(TESTFN, "wb") as fp:
47 fp.write(self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000048
Ezio Melottid5a23e32009-07-15 17:07:04 +000049 def make_test_archive(self, f, compression):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000050 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +000051 with zipfile.ZipFile(f, "w", compression) as zipfp:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000052 zipfp.write(TESTFN, "another.name")
Ezio Melotti569e61f2009-12-30 06:14:51 +000053 zipfp.write(TESTFN, TESTFN)
54 zipfp.writestr("strfile", self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000055
Ezio Melottid5a23e32009-07-15 17:07:04 +000056 def zip_test(self, f, compression):
57 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +000058
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000059 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +000060 with zipfile.ZipFile(f, "r", compression) as zipfp:
61 self.assertEqual(zipfp.read(TESTFN), self.data)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000062 self.assertEqual(zipfp.read("another.name"), self.data)
Ezio Melotti569e61f2009-12-30 06:14:51 +000063 self.assertEqual(zipfp.read("strfile"), self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +000064
Ezio Melotti569e61f2009-12-30 06:14:51 +000065 # Print the ZIP directory
66 fp = StringIO()
67 stdout = sys.stdout
68 try:
69 sys.stdout = fp
70 zipfp.printdir()
71 finally:
72 sys.stdout = stdout
Tim Petersa608bb22006-06-15 18:06:29 +000073
Ezio Melotti569e61f2009-12-30 06:14:51 +000074 directory = fp.getvalue()
75 lines = directory.splitlines()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000076 self.assertEqual(len(lines), 4) # Number of files + header
Ronald Oussoren143cefb2006-06-15 08:14:18 +000077
Ezio Melottiaa980582010-01-23 23:04:36 +000078 self.assertIn('File Name', lines[0])
79 self.assertIn('Modified', lines[0])
80 self.assertIn('Size', lines[0])
Ronald Oussoren143cefb2006-06-15 08:14:18 +000081
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000082 fn, date, time_, size = lines[1].split()
83 self.assertEqual(fn, 'another.name')
84 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
85 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
86 self.assertEqual(size, str(len(self.data)))
Ronald Oussoren143cefb2006-06-15 08:14:18 +000087
Ezio Melotti569e61f2009-12-30 06:14:51 +000088 # Check the namelist
89 names = zipfp.namelist()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000090 self.assertEqual(len(names), 3)
Ezio Melottiaa980582010-01-23 23:04:36 +000091 self.assertIn(TESTFN, names)
92 self.assertIn("another.name", names)
93 self.assertIn("strfile", names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +000094
Ezio Melotti569e61f2009-12-30 06:14:51 +000095 # Check infolist
96 infos = zipfp.infolist()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000097 names = [i.filename for i in infos]
98 self.assertEqual(len(names), 3)
Ezio Melottiaa980582010-01-23 23:04:36 +000099 self.assertIn(TESTFN, names)
100 self.assertIn("another.name", names)
101 self.assertIn("strfile", names)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000102 for i in infos:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000103 self.assertEqual(i.file_size, len(self.data))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000104
Ezio Melotti569e61f2009-12-30 06:14:51 +0000105 # check getinfo
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000106 for nm in (TESTFN, "another.name", "strfile"):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000107 info = zipfp.getinfo(nm)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000108 self.assertEqual(info.filename, nm)
109 self.assertEqual(info.file_size, len(self.data))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000110
Ezio Melotti569e61f2009-12-30 06:14:51 +0000111 # Check that testzip doesn't raise an exception
112 zipfp.testzip()
Tim Peters7d3bad62001-04-04 18:56:49 +0000113
Ezio Melottid5a23e32009-07-15 17:07:04 +0000114 def test_stored(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000115 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000116 self.zip_test(f, zipfile.ZIP_STORED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000117
Ezio Melottid5a23e32009-07-15 17:07:04 +0000118 def zip_open_test(self, f, compression):
119 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000120
121 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000122 with zipfile.ZipFile(f, "r", compression) as zipfp:
123 zipdata1 = []
Brian Curtin0d654332011-04-19 21:15:55 -0500124 with zipfp.open(TESTFN) as zipopen1:
125 while True:
126 read_data = zipopen1.read(256)
127 if not read_data:
128 break
129 zipdata1.append(read_data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000130
Ezio Melotti569e61f2009-12-30 06:14:51 +0000131 zipdata2 = []
Brian Curtin0d654332011-04-19 21:15:55 -0500132 with zipfp.open("another.name") as zipopen2:
133 while True:
134 read_data = zipopen2.read(256)
135 if not read_data:
136 break
137 zipdata2.append(read_data)
Tim Petersea5962f2007-03-12 18:07:52 +0000138
Ezio Melotti569e61f2009-12-30 06:14:51 +0000139 self.assertEqual(''.join(zipdata1), self.data)
140 self.assertEqual(''.join(zipdata2), self.data)
Tim Petersea5962f2007-03-12 18:07:52 +0000141
Ezio Melottid5a23e32009-07-15 17:07:04 +0000142 def test_open_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000143 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000144 self.zip_open_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000145
Ezio Melottid5a23e32009-07-15 17:07:04 +0000146 def test_open_via_zip_info(self):
Georg Brandl112aa502008-05-20 08:25:48 +0000147 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000148 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
149 zipfp.writestr("name", "foo")
Serhiy Storchaka49259352014-01-20 21:57:09 +0200150 with check_warnings(('', UserWarning)):
151 zipfp.writestr("name", "bar")
152 self.assertEqual(zipfp.namelist(), ["name"] * 2)
Georg Brandl112aa502008-05-20 08:25:48 +0000153
Ezio Melotti569e61f2009-12-30 06:14:51 +0000154 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
155 infos = zipfp.infolist()
156 data = ""
157 for info in infos:
Brian Curtin0d654332011-04-19 21:15:55 -0500158 with zipfp.open(info) as f:
159 data += f.read()
Ezio Melotti569e61f2009-12-30 06:14:51 +0000160 self.assertTrue(data == "foobar" or data == "barfoo")
161 data = ""
162 for info in infos:
163 data += zipfp.read(info)
164 self.assertTrue(data == "foobar" or data == "barfoo")
Georg Brandl112aa502008-05-20 08:25:48 +0000165
Ezio Melottid5a23e32009-07-15 17:07:04 +0000166 def zip_random_open_test(self, f, compression):
167 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000168
169 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000170 with zipfile.ZipFile(f, "r", compression) as zipfp:
171 zipdata1 = []
Brian Curtin0d654332011-04-19 21:15:55 -0500172 with zipfp.open(TESTFN) as zipopen1:
173 while True:
174 read_data = zipopen1.read(randint(1, 1024))
175 if not read_data:
176 break
177 zipdata1.append(read_data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000178
Ezio Melotti569e61f2009-12-30 06:14:51 +0000179 self.assertEqual(''.join(zipdata1), self.data)
Tim Petersea5962f2007-03-12 18:07:52 +0000180
Ezio Melottid5a23e32009-07-15 17:07:04 +0000181 def test_random_open_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000182 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000183 self.zip_random_open_test(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +0000184
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000185 def test_univeral_readaheads(self):
186 f = StringIO()
187
188 data = 'a\r\n' * 16 * 1024
Brian Curtin0d654332011-04-19 21:15:55 -0500189 with zipfile.ZipFile(f, 'w', zipfile.ZIP_STORED) as zipfp:
190 zipfp.writestr(TESTFN, data)
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000191
192 data2 = ''
Brian Curtin0d654332011-04-19 21:15:55 -0500193 with zipfile.ZipFile(f, 'r') as zipfp:
194 with zipfp.open(TESTFN, 'rU') as zipopen:
195 for line in zipopen:
196 data2 += line
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000197
198 self.assertEqual(data, data2.replace('\n', '\r\n'))
199
200 def zip_readline_read_test(self, f, compression):
201 self.make_test_archive(f, compression)
202
203 # Read the ZIP archive
Brian Curtin0d654332011-04-19 21:15:55 -0500204 with zipfile.ZipFile(f, "r") as zipfp:
205 with zipfp.open(TESTFN) as zipopen:
206 data = ''
207 while True:
208 read = zipopen.readline()
209 if not read:
210 break
211 data += read
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000212
Brian Curtin0d654332011-04-19 21:15:55 -0500213 read = zipopen.read(100)
214 if not read:
215 break
216 data += read
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000217
218 self.assertEqual(data, self.data)
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000219
Ezio Melottid5a23e32009-07-15 17:07:04 +0000220 def zip_readline_test(self, f, compression):
221 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000222
223 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000224 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin0d654332011-04-19 21:15:55 -0500225 with zipfp.open(TESTFN) as zipopen:
226 for line in self.line_gen:
227 linedata = zipopen.readline()
228 self.assertEqual(linedata, line + '\n')
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000229
Ezio Melottid5a23e32009-07-15 17:07:04 +0000230 def zip_readlines_test(self, f, compression):
231 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000232
233 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000234 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin0d654332011-04-19 21:15:55 -0500235 with zipfp.open(TESTFN) as zo:
236 ziplines = zo.readlines()
237 for line, zipline in zip(self.line_gen, ziplines):
238 self.assertEqual(zipline, line + '\n')
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000239
Ezio Melottid5a23e32009-07-15 17:07:04 +0000240 def zip_iterlines_test(self, f, compression):
241 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000242
243 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000244 with zipfile.ZipFile(f, "r") as zipfp:
245 for line, zipline in zip(self.line_gen, zipfp.open(TESTFN)):
246 self.assertEqual(zipline, line + '\n')
Tim Petersea5962f2007-03-12 18:07:52 +0000247
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000248 def test_readline_read_stored(self):
249 # Issue #7610: calls to readline() interleaved with calls to read().
250 for f in (TESTFN2, TemporaryFile(), StringIO()):
251 self.zip_readline_read_test(f, zipfile.ZIP_STORED)
252
Ezio Melottid5a23e32009-07-15 17:07:04 +0000253 def test_readline_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000254 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000255 self.zip_readline_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000256
Ezio Melottid5a23e32009-07-15 17:07:04 +0000257 def test_readlines_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000258 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000259 self.zip_readlines_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000260
Ezio Melottid5a23e32009-07-15 17:07:04 +0000261 def test_iterlines_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000262 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000263 self.zip_iterlines_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000264
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000265 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000266 def test_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000267 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000268 self.zip_test(f, zipfile.ZIP_DEFLATED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000269
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000270 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000271 def test_open_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000272 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000273 self.zip_open_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000274
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000275 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000276 def test_random_open_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000277 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000278 self.zip_random_open_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000279
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000280 @skipUnless(zlib, "requires zlib")
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000281 def test_readline_read_deflated(self):
282 # Issue #7610: calls to readline() interleaved with calls to read().
283 for f in (TESTFN2, TemporaryFile(), StringIO()):
284 self.zip_readline_read_test(f, zipfile.ZIP_DEFLATED)
285
286 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000287 def test_readline_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000288 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000289 self.zip_readline_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000290
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000291 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000292 def test_readlines_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000293 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000294 self.zip_readlines_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000295
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000296 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000297 def test_iterlines_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000298 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000299 self.zip_iterlines_test(f, zipfile.ZIP_DEFLATED)
Tim Petersea5962f2007-03-12 18:07:52 +0000300
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000301 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000302 def test_low_compression(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000303 """Check for cases where compressed data is larger than original."""
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000304 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000305 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
306 zipfp.writestr("strfile", '12')
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000307
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000308 # Get an open object for strfile
Ezio Melotti569e61f2009-12-30 06:14:51 +0000309 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_DEFLATED) as zipfp:
Brian Curtin0d654332011-04-19 21:15:55 -0500310 with zipfp.open("strfile") as openobj:
311 self.assertEqual(openobj.read(1), '1')
312 self.assertEqual(openobj.read(1), '2')
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000313
Ezio Melottid5a23e32009-07-15 17:07:04 +0000314 def test_absolute_arcnames(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000315 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
316 zipfp.write(TESTFN, "/absolute")
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000317
Ezio Melotti569e61f2009-12-30 06:14:51 +0000318 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
319 self.assertEqual(zipfp.namelist(), ["absolute"])
Tim Peters32cbc962006-02-20 21:42:18 +0000320
Ezio Melottid5a23e32009-07-15 17:07:04 +0000321 def test_append_to_zip_file(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000322 """Test appending to an existing zipfile."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000323 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
324 zipfp.write(TESTFN, TESTFN)
325
326 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
327 zipfp.writestr("strfile", self.data)
328 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000329
Ezio Melottid5a23e32009-07-15 17:07:04 +0000330 def test_append_to_non_zip_file(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000331 """Test appending to an existing file that is not a zipfile."""
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000332 # NOTE: this test fails if len(d) < 22 because of the first
333 # line "fpin.seek(-22, 2)" in _EndRecData
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000334 data = 'I am not a ZipFile!'*10
335 with open(TESTFN2, 'wb') as f:
336 f.write(data)
337
Ezio Melotti569e61f2009-12-30 06:14:51 +0000338 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
339 zipfp.write(TESTFN, TESTFN)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000340
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000341 with open(TESTFN2, 'rb') as f:
342 f.seek(len(data))
343 with zipfile.ZipFile(f, "r") as zipfp:
344 self.assertEqual(zipfp.namelist(), [TESTFN])
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000345
R David Murray873c5832011-06-09 16:01:09 -0400346 def test_ignores_newline_at_end(self):
347 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
348 zipfp.write(TESTFN, TESTFN)
349 with open(TESTFN2, 'a') as f:
350 f.write("\r\n\00\00\00")
351 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
352 self.assertIsInstance(zipfp, zipfile.ZipFile)
353
354 def test_ignores_stuff_appended_past_comments(self):
355 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
356 zipfp.comment = b"this is a comment"
357 zipfp.write(TESTFN, TESTFN)
358 with open(TESTFN2, 'a') as f:
359 f.write("abcdef\r\n")
360 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
361 self.assertIsInstance(zipfp, zipfile.ZipFile)
362 self.assertEqual(zipfp.comment, b"this is a comment")
363
Ezio Melottid5a23e32009-07-15 17:07:04 +0000364 def test_write_default_name(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000365 """Check that calling ZipFile.write without arcname specified
366 produces the expected result."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000367 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
368 zipfp.write(TESTFN)
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400369 with open(TESTFN,'r') as fid:
370 self.assertEqual(zipfp.read(TESTFN), fid.read())
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000371
Ezio Melotti1036a7f2009-09-12 14:43:43 +0000372 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000373 def test_per_file_compression(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000374 """Check that files within a Zip archive can have different
375 compression options."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000376 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
377 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
378 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
379 sinfo = zipfp.getinfo('storeme')
380 dinfo = zipfp.getinfo('deflateme')
381 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
382 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000383
Ezio Melottid5a23e32009-07-15 17:07:04 +0000384 def test_write_to_readonly(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000385 """Check that trying to call write() on a readonly ZipFile object
386 raises a RuntimeError."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000387 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
388 zipfp.writestr("somefile.txt", "bogus")
389
390 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
391 self.assertRaises(RuntimeError, zipfp.write, TESTFN)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000392
Ezio Melottid5a23e32009-07-15 17:07:04 +0000393 def test_extract(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000394 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
395 for fpath, fdata in SMALL_TEST_DATA:
396 zipfp.writestr(fpath, fdata)
Georg Brandl62416bc2008-01-07 18:47:44 +0000397
Ezio Melotti569e61f2009-12-30 06:14:51 +0000398 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
399 for fpath, fdata in SMALL_TEST_DATA:
400 writtenfile = zipfp.extract(fpath)
Georg Brandl62416bc2008-01-07 18:47:44 +0000401
Ezio Melotti569e61f2009-12-30 06:14:51 +0000402 # make sure it was written to the right place
Gregory P. Smith608cc452013-02-01 11:40:18 -0800403 correctfile = os.path.join(os.getcwd(), fpath)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000404 correctfile = os.path.normpath(correctfile)
Georg Brandl62416bc2008-01-07 18:47:44 +0000405
Ezio Melotti569e61f2009-12-30 06:14:51 +0000406 self.assertEqual(writtenfile, correctfile)
Georg Brandl62416bc2008-01-07 18:47:44 +0000407
Ezio Melotti569e61f2009-12-30 06:14:51 +0000408 # make sure correct data is in correct file
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400409 with open(writtenfile, "rb") as fid:
410 self.assertEqual(fdata, fid.read())
Ezio Melotti569e61f2009-12-30 06:14:51 +0000411 os.remove(writtenfile)
Georg Brandl62416bc2008-01-07 18:47:44 +0000412
413 # remove the test file subdirectories
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400414 rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
Georg Brandl62416bc2008-01-07 18:47:44 +0000415
Ezio Melottid5a23e32009-07-15 17:07:04 +0000416 def test_extract_all(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000417 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
418 for fpath, fdata in SMALL_TEST_DATA:
419 zipfp.writestr(fpath, fdata)
Georg Brandl62416bc2008-01-07 18:47:44 +0000420
Ezio Melotti569e61f2009-12-30 06:14:51 +0000421 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
422 zipfp.extractall()
423 for fpath, fdata in SMALL_TEST_DATA:
Gregory P. Smith608cc452013-02-01 11:40:18 -0800424 outfile = os.path.join(os.getcwd(), fpath)
Georg Brandl62416bc2008-01-07 18:47:44 +0000425
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400426 with open(outfile, "rb") as fid:
427 self.assertEqual(fdata, fid.read())
Ezio Melotti569e61f2009-12-30 06:14:51 +0000428 os.remove(outfile)
Georg Brandl62416bc2008-01-07 18:47:44 +0000429
430 # remove the test file subdirectories
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400431 rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
Georg Brandl62416bc2008-01-07 18:47:44 +0000432
Gregory P. Smith608cc452013-02-01 11:40:18 -0800433 def check_file(self, filename, content):
434 self.assertTrue(os.path.isfile(filename))
435 with open(filename, 'rb') as f:
436 self.assertEqual(f.read(), content)
437
Serhiy Storchakadb03e6b2013-05-08 21:52:31 +0300438 @skipUnless(TESTFN_UNICODE, "No Unicode filesystem semantics on this platform.")
Serhiy Storchaka6fa83f92013-04-13 12:28:17 +0300439 def test_extract_unicode_filenames(self):
440 fnames = [u'foo.txt', os.path.basename(TESTFN_UNICODE)]
441 content = 'Test for unicode filename'
442 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
443 for fname in fnames:
444 zipfp.writestr(fname, content)
445
446 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
447 for fname in fnames:
448 writtenfile = zipfp.extract(fname)
449
450 # make sure it was written to the right place
451 correctfile = os.path.join(os.getcwd(), fname)
452 correctfile = os.path.normpath(correctfile)
453 self.assertEqual(writtenfile, correctfile)
454
455 self.check_file(writtenfile, content)
456 os.remove(writtenfile)
457
Gregory P. Smith608cc452013-02-01 11:40:18 -0800458 def test_extract_hackers_arcnames(self):
459 hacknames = [
460 ('../foo/bar', 'foo/bar'),
461 ('foo/../bar', 'foo/bar'),
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'),
Gregory P. Smith608cc452013-02-01 11:40:18 -0800468 ]
469 if os.path.sep == '\\':
470 hacknames.extend([
471 (r'..\foo\bar', 'foo/bar'),
472 (r'..\/foo\/bar', 'foo/bar'),
473 (r'foo/\..\/bar', 'foo/bar'),
474 (r'foo\/../\bar', 'foo/bar'),
475 (r'C:foo/bar', 'foo/bar'),
476 (r'C:/foo/bar', 'foo/bar'),
477 (r'C://foo/bar', 'foo/bar'),
478 (r'C:\foo\bar', 'foo/bar'),
Serhiy Storchaka13e56c72013-02-02 17:46:33 +0200479 (r'//conky/mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
480 (r'\\conky\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
Gregory P. Smith608cc452013-02-01 11:40:18 -0800481 (r'///conky/mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
482 (r'\\\conky\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
483 (r'//conky//mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
484 (r'\\conky\\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
Serhiy Storchaka13e56c72013-02-02 17:46:33 +0200485 (r'//?/C:/foo/bar', '_/C_/foo/bar'),
486 (r'\\?\C:\foo\bar', '_/C_/foo/bar'),
Gregory P. Smith608cc452013-02-01 11:40:18 -0800487 (r'C:/../C:/foo/bar', 'C_/foo/bar'),
488 (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 +0200489 ('../../foo../../ba..r', 'foo/ba..r'),
490 ])
491 else: # Unix
492 hacknames.extend([
493 ('//foo/bar', 'foo/bar'),
494 ('../../foo../../ba..r', 'foo../ba..r'),
Serhiy Storchaka05fd7442013-02-02 18:34:57 +0200495 (r'foo/..\bar', r'foo/..\bar'),
Gregory P. Smith608cc452013-02-01 11:40:18 -0800496 ])
497
498 for arcname, fixedname in hacknames:
499 content = b'foobar' + arcname.encode()
500 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipfp:
Serhiy Storchaka05fd7442013-02-02 18:34:57 +0200501 zinfo = zipfile.ZipInfo()
502 # preserve backslashes
503 zinfo.filename = arcname
504 zinfo.external_attr = 0o600 << 16
505 zipfp.writestr(zinfo, content)
Gregory P. Smith608cc452013-02-01 11:40:18 -0800506
Serhiy Storchaka2a051fa2013-02-02 19:25:57 +0200507 arcname = arcname.replace(os.sep, "/")
Gregory P. Smith608cc452013-02-01 11:40:18 -0800508 targetpath = os.path.join('target', 'subdir', 'subsub')
509 correctfile = os.path.join(targetpath, *fixedname.split('/'))
510
511 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
512 writtenfile = zipfp.extract(arcname, targetpath)
Serhiy Storchaka13e56c72013-02-02 17:46:33 +0200513 self.assertEqual(writtenfile, correctfile,
514 msg="extract %r" % arcname)
Gregory P. Smith608cc452013-02-01 11:40:18 -0800515 self.check_file(correctfile, content)
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400516 rmtree('target')
Gregory P. Smith608cc452013-02-01 11:40:18 -0800517
518 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
519 zipfp.extractall(targetpath)
520 self.check_file(correctfile, content)
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400521 rmtree('target')
Gregory P. Smith608cc452013-02-01 11:40:18 -0800522
523 correctfile = os.path.join(os.getcwd(), *fixedname.split('/'))
524
525 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
526 writtenfile = zipfp.extract(arcname)
Serhiy Storchaka13e56c72013-02-02 17:46:33 +0200527 self.assertEqual(writtenfile, correctfile,
528 msg="extract %r" % arcname)
Gregory P. Smith608cc452013-02-01 11:40:18 -0800529 self.check_file(correctfile, content)
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400530 rmtree(fixedname.split('/')[0])
Gregory P. Smith608cc452013-02-01 11:40:18 -0800531
532 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
533 zipfp.extractall()
534 self.check_file(correctfile, content)
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400535 rmtree(fixedname.split('/')[0])
Gregory P. Smith608cc452013-02-01 11:40:18 -0800536
537 os.remove(TESTFN2)
538
Ronald Oussorendd25e862010-02-07 20:18:02 +0000539 def test_writestr_compression(self):
540 zipfp = zipfile.ZipFile(TESTFN2, "w")
541 zipfp.writestr("a.txt", "hello world", compress_type=zipfile.ZIP_STORED)
542 if zlib:
543 zipfp.writestr("b.txt", "hello world", compress_type=zipfile.ZIP_DEFLATED)
544
545 info = zipfp.getinfo('a.txt')
546 self.assertEqual(info.compress_type, zipfile.ZIP_STORED)
547
548 if zlib:
549 info = zipfp.getinfo('b.txt')
550 self.assertEqual(info.compress_type, zipfile.ZIP_DEFLATED)
551
552
Antoine Pitrou5fdfa3e2008-07-25 19:42:26 +0000553 def zip_test_writestr_permissions(self, f, compression):
554 # Make sure that writestr creates files with mode 0600,
555 # when it is passed a name rather than a ZipInfo instance.
556
Ezio Melottid5a23e32009-07-15 17:07:04 +0000557 self.make_test_archive(f, compression)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000558 with zipfile.ZipFile(f, "r") as zipfp:
559 zinfo = zipfp.getinfo('strfile')
560 self.assertEqual(zinfo.external_attr, 0600 << 16)
Antoine Pitrou5fdfa3e2008-07-25 19:42:26 +0000561
Ezio Melottid5a23e32009-07-15 17:07:04 +0000562 def test_writestr_permissions(self):
Antoine Pitrou5fdfa3e2008-07-25 19:42:26 +0000563 for f in (TESTFN2, TemporaryFile(), StringIO()):
564 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
565
Ezio Melotti569e61f2009-12-30 06:14:51 +0000566 def test_close(self):
567 """Check that the zipfile is closed after the 'with' block."""
568 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
569 for fpath, fdata in SMALL_TEST_DATA:
570 zipfp.writestr(fpath, fdata)
571 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
572 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
573
574 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
575 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
576 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
577
578 def test_close_on_exception(self):
579 """Check that the zipfile is closed if an exception is raised in the
580 'with' block."""
581 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
582 for fpath, fdata in SMALL_TEST_DATA:
583 zipfp.writestr(fpath, fdata)
584
585 try:
586 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
587 raise zipfile.BadZipfile()
588 except zipfile.BadZipfile:
589 self.assertTrue(zipfp2.fp is None, 'zipfp is not closed')
590
Senthil Kumaranddd40312011-10-20 01:38:35 +0800591 def test_add_file_before_1980(self):
592 # Set atime and mtime to 1970-01-01
593 os.utime(TESTFN, (0, 0))
594 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
595 self.assertRaises(ValueError, zipfp.write, TESTFN)
596
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000597 def tearDown(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000598 unlink(TESTFN)
599 unlink(TESTFN2)
600
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000601
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000602class TestZip64InSmallFiles(unittest.TestCase):
603 # These tests test the ZIP64 functionality without using large files,
604 # see test_zipfile64 for proper tests.
605
606 def setUp(self):
607 self._limit = zipfile.ZIP64_LIMIT
608 zipfile.ZIP64_LIMIT = 5
609
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000610 line_gen = ("Test of zipfile line %d." % i
611 for i in range(0, FIXEDTEST_SIZE))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000612 self.data = '\n'.join(line_gen)
613
614 # Make a source file with some lines
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000615 with open(TESTFN, "wb") as fp:
616 fp.write(self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000617
Ezio Melottid5a23e32009-07-15 17:07:04 +0000618 def large_file_exception_test(self, f, compression):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000619 with zipfile.ZipFile(f, "w", compression) as zipfp:
620 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000621 zipfp.write, TESTFN, "another.name")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000622
Ezio Melottid5a23e32009-07-15 17:07:04 +0000623 def large_file_exception_test2(self, f, compression):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000624 with zipfile.ZipFile(f, "w", compression) as zipfp:
625 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000626 zipfp.writestr, "another.name", self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000627
Ezio Melottid5a23e32009-07-15 17:07:04 +0000628 def test_large_file_exception(self):
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000629 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000630 self.large_file_exception_test(f, zipfile.ZIP_STORED)
631 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000632
Ezio Melottid5a23e32009-07-15 17:07:04 +0000633 def zip_test(self, f, compression):
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000634 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000635 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000636 zipfp.write(TESTFN, "another.name")
Ezio Melotti569e61f2009-12-30 06:14:51 +0000637 zipfp.write(TESTFN, TESTFN)
638 zipfp.writestr("strfile", self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000639
640 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000641 with zipfile.ZipFile(f, "r", compression) as zipfp:
642 self.assertEqual(zipfp.read(TESTFN), self.data)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000643 self.assertEqual(zipfp.read("another.name"), self.data)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000644 self.assertEqual(zipfp.read("strfile"), self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000645
Ezio Melotti569e61f2009-12-30 06:14:51 +0000646 # Print the ZIP directory
647 fp = StringIO()
648 stdout = sys.stdout
649 try:
650 sys.stdout = fp
651 zipfp.printdir()
652 finally:
653 sys.stdout = stdout
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000654
Ezio Melotti569e61f2009-12-30 06:14:51 +0000655 directory = fp.getvalue()
656 lines = directory.splitlines()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000657 self.assertEqual(len(lines), 4) # Number of files + header
Tim Petersa608bb22006-06-15 18:06:29 +0000658
Ezio Melottiaa980582010-01-23 23:04:36 +0000659 self.assertIn('File Name', lines[0])
660 self.assertIn('Modified', lines[0])
661 self.assertIn('Size', lines[0])
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000662
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000663 fn, date, time_, size = lines[1].split()
664 self.assertEqual(fn, 'another.name')
665 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
666 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
667 self.assertEqual(size, str(len(self.data)))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000668
Ezio Melotti569e61f2009-12-30 06:14:51 +0000669 # Check the namelist
670 names = zipfp.namelist()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000671 self.assertEqual(len(names), 3)
Ezio Melottiaa980582010-01-23 23:04:36 +0000672 self.assertIn(TESTFN, names)
673 self.assertIn("another.name", names)
674 self.assertIn("strfile", names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000675
Ezio Melotti569e61f2009-12-30 06:14:51 +0000676 # Check infolist
677 infos = zipfp.infolist()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000678 names = [i.filename for i in infos]
679 self.assertEqual(len(names), 3)
Ezio Melottiaa980582010-01-23 23:04:36 +0000680 self.assertIn(TESTFN, names)
681 self.assertIn("another.name", names)
682 self.assertIn("strfile", names)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000683 for i in infos:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000684 self.assertEqual(i.file_size, len(self.data))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000685
Ezio Melotti569e61f2009-12-30 06:14:51 +0000686 # check getinfo
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000687 for nm in (TESTFN, "another.name", "strfile"):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000688 info = zipfp.getinfo(nm)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000689 self.assertEqual(info.filename, nm)
690 self.assertEqual(info.file_size, len(self.data))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000691
Ezio Melotti569e61f2009-12-30 06:14:51 +0000692 # Check that testzip doesn't raise an exception
693 zipfp.testzip()
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000694
Ezio Melottid5a23e32009-07-15 17:07:04 +0000695 def test_stored(self):
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000696 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000697 self.zip_test(f, zipfile.ZIP_STORED)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000698
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000699 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000700 def test_deflated(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000701 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000702 self.zip_test(f, zipfile.ZIP_DEFLATED)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000703
Ezio Melottid5a23e32009-07-15 17:07:04 +0000704 def test_absolute_arcnames(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000705 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
706 allowZip64=True) as zipfp:
707 zipfp.write(TESTFN, "/absolute")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000708
Ezio Melotti569e61f2009-12-30 06:14:51 +0000709 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
710 self.assertEqual(zipfp.namelist(), ["absolute"])
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000711
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000712 def tearDown(self):
713 zipfile.ZIP64_LIMIT = self._limit
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000714 unlink(TESTFN)
715 unlink(TESTFN2)
716
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000717
718class PyZipFileTests(unittest.TestCase):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000719 def test_write_pyfile(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000720 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
721 fn = __file__
722 if fn.endswith('.pyc') or fn.endswith('.pyo'):
723 fn = fn[:-1]
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000724
Ezio Melotti569e61f2009-12-30 06:14:51 +0000725 zipfp.writepy(fn)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000726
Ezio Melotti569e61f2009-12-30 06:14:51 +0000727 bn = os.path.basename(fn)
Ezio Melottiaa980582010-01-23 23:04:36 +0000728 self.assertNotIn(bn, zipfp.namelist())
Ezio Melotti569e61f2009-12-30 06:14:51 +0000729 self.assertTrue(bn + 'o' in zipfp.namelist() or
730 bn + 'c' in zipfp.namelist())
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000731
Ezio Melotti569e61f2009-12-30 06:14:51 +0000732 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
733 fn = __file__
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000734 if fn.endswith(('.pyc', '.pyo')):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000735 fn = fn[:-1]
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000736
Ezio Melotti569e61f2009-12-30 06:14:51 +0000737 zipfp.writepy(fn, "testpackage")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000738
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000739 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
Ezio Melottiaa980582010-01-23 23:04:36 +0000740 self.assertNotIn(bn, zipfp.namelist())
Ezio Melotti569e61f2009-12-30 06:14:51 +0000741 self.assertTrue(bn + 'o' in zipfp.namelist() or
742 bn + 'c' in zipfp.namelist())
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000743
Ezio Melottid5a23e32009-07-15 17:07:04 +0000744 def test_write_python_package(self):
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000745 import email
746 packagedir = os.path.dirname(email.__file__)
747
Ezio Melotti569e61f2009-12-30 06:14:51 +0000748 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
749 zipfp.writepy(packagedir)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000750
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000751 # Check for a couple of modules at different levels of the
752 # hierarchy
Ezio Melotti569e61f2009-12-30 06:14:51 +0000753 names = zipfp.namelist()
754 self.assertTrue('email/__init__.pyo' in names or
755 'email/__init__.pyc' in names)
756 self.assertTrue('email/mime/text.pyo' in names or
757 'email/mime/text.pyc' in names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000758
Ezio Melottid5a23e32009-07-15 17:07:04 +0000759 def test_write_python_directory(self):
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000760 os.mkdir(TESTFN2)
761 try:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000762 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
Ezio Melotti763f1e82009-12-31 13:27:41 +0000763 fp.write("print(42)\n")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000764
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000765 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
Ezio Melotti763f1e82009-12-31 13:27:41 +0000766 fp.write("print(42 * 42)\n")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000767
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000768 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
769 fp.write("bla bla bla\n")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000770
771 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
772 zipfp.writepy(TESTFN2)
773
774 names = zipfp.namelist()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000775 self.assertTrue('mod1.pyc' in names or 'mod1.pyo' in names)
776 self.assertTrue('mod2.pyc' in names or 'mod2.pyo' in names)
Ezio Melottiaa980582010-01-23 23:04:36 +0000777 self.assertNotIn('mod2.txt', names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000778
779 finally:
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400780 rmtree(TESTFN2)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000781
Ezio Melottid5a23e32009-07-15 17:07:04 +0000782 def test_write_non_pyfile(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000783 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400784 with open(TESTFN, 'w') as fid:
785 fid.write('most definitely not a python file')
Ezio Melotti569e61f2009-12-30 06:14:51 +0000786 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
787 os.remove(TESTFN)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000788
789
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000790class OtherTests(unittest.TestCase):
Antoine Pitroue1436d12010-08-12 15:25:51 +0000791 zips_with_bad_crc = {
792 zipfile.ZIP_STORED: (
793 b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
794 b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
795 b'ilehello,AworldP'
796 b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
797 b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
798 b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
799 b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
800 b'\0\0/\0\0\0\0\0'),
801 zipfile.ZIP_DEFLATED: (
802 b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
803 b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
804 b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
805 b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
806 b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
807 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
808 b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
809 b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00'),
810 }
811
Ezio Melottid5a23e32009-07-15 17:07:04 +0000812 def test_unicode_filenames(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000813 with zipfile.ZipFile(TESTFN, "w") as zf:
814 zf.writestr(u"foo.txt", "Test for unicode filename")
815 zf.writestr(u"\xf6.txt", "Test for unicode filename")
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000816 self.assertIsInstance(zf.infolist()[0].filename, unicode)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000817
818 with zipfile.ZipFile(TESTFN, "r") as zf:
819 self.assertEqual(zf.filelist[0].filename, "foo.txt")
820 self.assertEqual(zf.filelist[1].filename, u"\xf6.txt")
Martin v. Löwis471617d2008-05-05 17:16:58 +0000821
Ezio Melottid5a23e32009-07-15 17:07:04 +0000822 def test_create_non_existent_file_for_append(self):
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000823 if os.path.exists(TESTFN):
824 os.unlink(TESTFN)
Tim Petersea5962f2007-03-12 18:07:52 +0000825
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000826 filename = 'testfile.txt'
827 content = 'hello, world. this is some content.'
Tim Petersea5962f2007-03-12 18:07:52 +0000828
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000829 try:
Ezio Melotti569e61f2009-12-30 06:14:51 +0000830 with zipfile.ZipFile(TESTFN, 'a') as zf:
831 zf.writestr(filename, content)
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000832 except IOError:
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000833 self.fail('Could not append data to a non-existent zip file.')
834
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000835 self.assertTrue(os.path.exists(TESTFN))
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000836
Ezio Melotti569e61f2009-12-30 06:14:51 +0000837 with zipfile.ZipFile(TESTFN, 'r') as zf:
838 self.assertEqual(zf.read(filename), content)
Tim Petersea5962f2007-03-12 18:07:52 +0000839
Ezio Melottid5a23e32009-07-15 17:07:04 +0000840 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000841 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000842 # it opens if there's an error in the file. If it doesn't, the
843 # traceback holds a reference to the ZipFile object and, indirectly,
844 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000845 # On Windows, this causes the os.unlink() call to fail because the
846 # underlying file is still open. This is SF bug #412214.
847 #
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000848 with open(TESTFN, "w") as fp:
849 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000850 try:
851 zf = zipfile.ZipFile(TESTFN)
852 except zipfile.BadZipfile:
Collin Winter04a51ec2007-03-29 02:28:16 +0000853 pass
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000854
Ezio Melottid5a23e32009-07-15 17:07:04 +0000855 def test_is_zip_erroneous_file(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000856 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000857 # - passing a filename
858 with open(TESTFN, "w") as fp:
859 fp.write("this is not a legal zip file\n")
Tim Petersea5962f2007-03-12 18:07:52 +0000860 chk = zipfile.is_zipfile(TESTFN)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000861 self.assertFalse(chk)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000862 # - passing a file object
863 with open(TESTFN, "rb") as fp:
864 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000865 self.assertTrue(not chk)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000866 # - passing a file-like object
867 fp = StringIO()
868 fp.write("this is not a legal zip file\n")
869 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000870 self.assertTrue(not chk)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000871 fp.seek(0, 0)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000872 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000873 self.assertTrue(not chk)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000874
Serhiy Storchaka0be506a2013-01-31 15:26:55 +0200875 def test_damaged_zipfile(self):
876 """Check that zipfiles with missing bytes at the end raise BadZipFile."""
877 # - Create a valid zip file
878 fp = io.BytesIO()
879 with zipfile.ZipFile(fp, mode="w") as zipf:
880 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
881 zipfiledata = fp.getvalue()
882
883 # - Now create copies of it missing the last N bytes and make sure
884 # a BadZipFile exception is raised when we try to open it
885 for N in range(len(zipfiledata)):
886 fp = io.BytesIO(zipfiledata[:N])
887 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, fp)
888
Ezio Melottid5a23e32009-07-15 17:07:04 +0000889 def test_is_zip_valid_file(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000890 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000891 # - passing a filename
Ezio Melotti569e61f2009-12-30 06:14:51 +0000892 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
893 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Tim Petersea5962f2007-03-12 18:07:52 +0000894 chk = zipfile.is_zipfile(TESTFN)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000895 self.assertTrue(chk)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000896 # - passing a file object
897 with open(TESTFN, "rb") as fp:
898 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000899 self.assertTrue(chk)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000900 fp.seek(0, 0)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000901 zip_contents = fp.read()
902 # - passing a file-like object
903 fp = StringIO()
904 fp.write(zip_contents)
905 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000906 self.assertTrue(chk)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000907 fp.seek(0, 0)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000908 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000909 self.assertTrue(chk)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000910
Ezio Melottid5a23e32009-07-15 17:07:04 +0000911 def test_non_existent_file_raises_IOError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000912 # make sure we don't raise an AttributeError when a partially-constructed
913 # ZipFile instance is finalized; this tests for regression on SF tracker
914 # bug #403871.
915
916 # The bug we're testing for caused an AttributeError to be raised
917 # when a ZipFile instance was created for a file that did not
918 # exist; the .fp member was not initialized but was needed by the
919 # __del__() method. Since the AttributeError is in the __del__(),
920 # it is ignored, but the user should be sufficiently annoyed by
921 # the message on the output that regression will be noticed
922 # quickly.
923 self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
924
Amaury Forgeot d'Arc3e5b0272009-07-28 22:15:30 +0000925 def test_empty_file_raises_BadZipFile(self):
Brian Curtin0d654332011-04-19 21:15:55 -0500926 with open(TESTFN, 'w') as f:
927 pass
Amaury Forgeot d'Arc3e5b0272009-07-28 22:15:30 +0000928 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN)
929
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000930 with open(TESTFN, 'w') as fp:
931 fp.write("short file")
Amaury Forgeot d'Arc3e5b0272009-07-28 22:15:30 +0000932 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN)
933
Ezio Melottid5a23e32009-07-15 17:07:04 +0000934 def test_closed_zip_raises_RuntimeError(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000935 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000936 data = StringIO()
Ezio Melotti569e61f2009-12-30 06:14:51 +0000937 with zipfile.ZipFile(data, mode="w") as zipf:
938 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000939
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200940 # This is correct; calling .read on a closed ZipFile should raise
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000941 # a RuntimeError, and so should calling .testzip. An earlier
942 # version of .testzip would swallow this exception (and any other)
943 # and report that the first file in the archive was corrupt.
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000944 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
945 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000946 self.assertRaises(RuntimeError, zipf.testzip)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000947 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Benjamin Peterson352eb4f2014-04-03 10:31:25 -0400948 with open(TESTFN, 'w') as fid:
949 fid.write('zipfile test data')
950 self.assertRaises(RuntimeError, zipf.write, TESTFN)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000951
Ezio Melottid5a23e32009-07-15 17:07:04 +0000952 def test_bad_constructor_mode(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000953 """Check that bad modes passed to ZipFile constructor are caught."""
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000954 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
955
Ezio Melottid5a23e32009-07-15 17:07:04 +0000956 def test_bad_open_mode(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000957 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000958 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
959 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
960
961 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000962 # read the data to make sure the file is there
Ezio Melotti569e61f2009-12-30 06:14:51 +0000963 zipf.read("foo.txt")
964 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000965
Ezio Melottid5a23e32009-07-15 17:07:04 +0000966 def test_read0(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000967 """Check that calling read(0) on a ZipExtFile object returns an empty
968 string and doesn't advance file pointer."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000969 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
970 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
971 # read the data to make sure the file is there
Brian Curtin0d654332011-04-19 21:15:55 -0500972 with zipf.open("foo.txt") as f:
973 for i in xrange(FIXEDTEST_SIZE):
974 self.assertEqual(f.read(0), '')
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000975
Brian Curtin0d654332011-04-19 21:15:55 -0500976 self.assertEqual(f.read(), "O, for a Muse of Fire!")
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000977
Ezio Melottid5a23e32009-07-15 17:07:04 +0000978 def test_open_non_existent_item(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000979 """Check that attempting to call open() for an item that doesn't
980 exist in the archive raises a RuntimeError."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000981 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
982 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000983
Ezio Melottid5a23e32009-07-15 17:07:04 +0000984 def test_bad_compression_mode(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000985 """Check that bad compression methods passed to ZipFile.open are
986 caught."""
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000987 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
988
Ezio Melotti9e949722012-11-18 13:18:06 +0200989 def test_unsupported_compression(self):
990 # data is declared as shrunk, but actually deflated
991 data = (b'PK\x03\x04.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00'
992 b'\x00\x02\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00x\x03\x00PK\x01'
993 b'\x02.\x03.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00\x00\x02\x00\x00'
994 b'\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
995 b'\x80\x01\x00\x00\x00\x00xPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00'
996 b'/\x00\x00\x00!\x00\x00\x00\x00\x00')
997 with zipfile.ZipFile(io.BytesIO(data), 'r') as zipf:
998 self.assertRaises(NotImplementedError, zipf.open, 'x')
999
Ezio Melottid5a23e32009-07-15 17:07:04 +00001000 def test_null_byte_in_filename(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001001 """Check that a filename containing a null byte is properly
1002 terminated."""
Ezio Melotti569e61f2009-12-30 06:14:51 +00001003 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1004 zipf.writestr("foo.txt\x00qqq", "O, for a Muse of Fire!")
1005 self.assertEqual(zipf.namelist(), ['foo.txt'])
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00001006
Ezio Melottid5a23e32009-07-15 17:07:04 +00001007 def test_struct_sizes(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001008 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwis8c436412008-07-03 12:51:14 +00001009 self.assertEqual(zipfile.sizeEndCentDir, 22)
1010 self.assertEqual(zipfile.sizeCentralDir, 46)
1011 self.assertEqual(zipfile.sizeEndCentDir64, 56)
1012 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
1013
Ezio Melottid5a23e32009-07-15 17:07:04 +00001014 def test_comments(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001015 """Check that comments on the archive are handled properly."""
Martin v. Löwis8c436412008-07-03 12:51:14 +00001016
1017 # check default comment is empty
Ezio Melotti569e61f2009-12-30 06:14:51 +00001018 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1019 self.assertEqual(zipf.comment, '')
1020 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1021
1022 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
1023 self.assertEqual(zipf.comment, '')
Martin v. Löwis8c436412008-07-03 12:51:14 +00001024
1025 # check a simple short comment
1026 comment = 'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melotti569e61f2009-12-30 06:14:51 +00001027 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1028 zipf.comment = comment
1029 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1030 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
1031 self.assertEqual(zipf.comment, comment)
Martin v. Löwis8c436412008-07-03 12:51:14 +00001032
1033 # check a comment of max length
1034 comment2 = ''.join(['%d' % (i**3 % 10) for i in xrange((1 << 16)-1)])
Ezio Melotti569e61f2009-12-30 06:14:51 +00001035 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1036 zipf.comment = comment2
1037 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1038
1039 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
1040 self.assertEqual(zipf.comment, comment2)
Martin v. Löwis8c436412008-07-03 12:51:14 +00001041
1042 # check a comment that is too long is truncated
Ezio Melotti569e61f2009-12-30 06:14:51 +00001043 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
Serhiy Storchaka49259352014-01-20 21:57:09 +02001044 with check_warnings(('', UserWarning)):
1045 zipf.comment = comment2 + 'oops'
Ezio Melotti569e61f2009-12-30 06:14:51 +00001046 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1047 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
1048 self.assertEqual(zipf.comment, comment2)
Martin v. Löwis8c436412008-07-03 12:51:14 +00001049
R David Murray3f4ccba2012-04-12 18:42:47 -04001050 def test_change_comment_in_empty_archive(self):
1051 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1052 self.assertFalse(zipf.filelist)
1053 zipf.comment = b"this is a comment"
1054 with zipfile.ZipFile(TESTFN, "r") as zipf:
1055 self.assertEqual(zipf.comment, b"this is a comment")
1056
1057 def test_change_comment_in_nonempty_archive(self):
1058 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1059 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1060 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1061 self.assertTrue(zipf.filelist)
1062 zipf.comment = b"this is a comment"
1063 with zipfile.ZipFile(TESTFN, "r") as zipf:
1064 self.assertEqual(zipf.comment, b"this is a comment")
1065
Antoine Pitroue1436d12010-08-12 15:25:51 +00001066 def check_testzip_with_bad_crc(self, compression):
1067 """Tests that files with bad CRCs return their name from testzip."""
1068 zipdata = self.zips_with_bad_crc[compression]
1069
1070 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1071 # testzip returns the name of the first corrupt file, or None
1072 self.assertEqual('afile', zipf.testzip())
1073
1074 def test_testzip_with_bad_crc_stored(self):
1075 self.check_testzip_with_bad_crc(zipfile.ZIP_STORED)
1076
1077 @skipUnless(zlib, "requires zlib")
1078 def test_testzip_with_bad_crc_deflated(self):
1079 self.check_testzip_with_bad_crc(zipfile.ZIP_DEFLATED)
1080
1081 def check_read_with_bad_crc(self, compression):
1082 """Tests that files with bad CRCs raise a BadZipfile exception when read."""
1083 zipdata = self.zips_with_bad_crc[compression]
1084
1085 # Using ZipFile.read()
1086 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1087 self.assertRaises(zipfile.BadZipfile, zipf.read, 'afile')
1088
1089 # Using ZipExtFile.read()
1090 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1091 with zipf.open('afile', 'r') as corrupt_file:
1092 self.assertRaises(zipfile.BadZipfile, corrupt_file.read)
1093
1094 # Same with small reads (in order to exercise the buffering logic)
1095 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1096 with zipf.open('afile', 'r') as corrupt_file:
1097 corrupt_file.MIN_READ_SIZE = 2
1098 with self.assertRaises(zipfile.BadZipfile):
1099 while corrupt_file.read(2):
1100 pass
1101
1102 def test_read_with_bad_crc_stored(self):
1103 self.check_read_with_bad_crc(zipfile.ZIP_STORED)
1104
1105 @skipUnless(zlib, "requires zlib")
1106 def test_read_with_bad_crc_deflated(self):
1107 self.check_read_with_bad_crc(zipfile.ZIP_DEFLATED)
1108
Antoine Pitroue4195e82010-09-12 14:56:27 +00001109 def check_read_return_size(self, compression):
1110 # Issue #9837: ZipExtFile.read() shouldn't return more bytes
1111 # than requested.
1112 for test_size in (1, 4095, 4096, 4097, 16384):
1113 file_size = test_size + 1
1114 junk = b''.join(struct.pack('B', randint(0, 255))
1115 for x in range(file_size))
1116 with zipfile.ZipFile(io.BytesIO(), "w", compression) as zipf:
1117 zipf.writestr('foo', junk)
1118 with zipf.open('foo', 'r') as fp:
1119 buf = fp.read(test_size)
1120 self.assertEqual(len(buf), test_size)
1121
1122 def test_read_return_size_stored(self):
1123 self.check_read_return_size(zipfile.ZIP_STORED)
1124
1125 @skipUnless(zlib, "requires zlib")
1126 def test_read_return_size_deflated(self):
1127 self.check_read_return_size(zipfile.ZIP_DEFLATED)
1128
Georg Brandl86e0c892010-11-26 07:22:28 +00001129 def test_empty_zipfile(self):
1130 # Check that creating a file in 'w' or 'a' mode and closing without
1131 # adding any files to the archives creates a valid empty ZIP file
Brian Curtin0d654332011-04-19 21:15:55 -05001132 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1133 pass
Georg Brandl86e0c892010-11-26 07:22:28 +00001134 try:
1135 zipf = zipfile.ZipFile(TESTFN, mode="r")
Benjamin Peterson352eb4f2014-04-03 10:31:25 -04001136 zipf.close()
Éric Araujo67843b32011-02-02 17:03:38 +00001137 except zipfile.BadZipfile:
Georg Brandl86e0c892010-11-26 07:22:28 +00001138 self.fail("Unable to create empty ZIP file in 'w' mode")
1139
Brian Curtin0d654332011-04-19 21:15:55 -05001140 with zipfile.ZipFile(TESTFN, mode="a") as zipf:
1141 pass
Georg Brandl86e0c892010-11-26 07:22:28 +00001142 try:
1143 zipf = zipfile.ZipFile(TESTFN, mode="r")
Benjamin Peterson352eb4f2014-04-03 10:31:25 -04001144 zipf.close()
Georg Brandl86e0c892010-11-26 07:22:28 +00001145 except:
1146 self.fail("Unable to create empty ZIP file in 'a' mode")
1147
1148 def test_open_empty_file(self):
1149 # Issue 1710703: Check that opening a file with less than 22 bytes
1150 # raises a BadZipfile exception (rather than the previously unhelpful
1151 # IOError)
Brian Curtin0d654332011-04-19 21:15:55 -05001152 with open(TESTFN, 'w') as f:
1153 pass
Georg Brandl86e0c892010-11-26 07:22:28 +00001154 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN, 'r')
1155
Senthil Kumaranddd40312011-10-20 01:38:35 +08001156 def test_create_zipinfo_before_1980(self):
1157 self.assertRaises(ValueError,
1158 zipfile.ZipInfo, 'seventies', (1979, 1, 1, 0, 0, 0))
1159
Collin Winter04a51ec2007-03-29 02:28:16 +00001160 def tearDown(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001161 unlink(TESTFN)
1162 unlink(TESTFN2)
1163
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001164
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001165class DecryptionTests(unittest.TestCase):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001166 """Check that ZIP decryption works. Since the library does not
1167 support encryption at the moment, we use a pre-generated encrypted
1168 ZIP file."""
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001169
1170 data = (
1171 'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
1172 '\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
1173 '\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
1174 'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
1175 '\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
1176 '\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
1177 '\x00\x00L\x00\x00\x00\x00\x00' )
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001178 data2 = (
1179 'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
1180 '\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
1181 '\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
1182 'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
1183 '\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
1184 '\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
1185 'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
1186 '\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001187
1188 plain = 'zipfile.py encryption test'
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001189 plain2 = '\x00'*512
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001190
1191 def setUp(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001192 with open(TESTFN, "wb") as fp:
1193 fp.write(self.data)
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001194 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001195 with open(TESTFN2, "wb") as fp:
1196 fp.write(self.data2)
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001197 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001198
1199 def tearDown(self):
1200 self.zip.close()
1201 os.unlink(TESTFN)
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001202 self.zip2.close()
1203 os.unlink(TESTFN2)
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001204
Ezio Melottid5a23e32009-07-15 17:07:04 +00001205 def test_no_password(self):
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001206 # Reading the encrypted file without password
1207 # must generate a RunTime exception
1208 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001209 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001210
Ezio Melottid5a23e32009-07-15 17:07:04 +00001211 def test_bad_password(self):
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001212 self.zip.setpassword("perl")
1213 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001214 self.zip2.setpassword("perl")
1215 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Tim Petersea5962f2007-03-12 18:07:52 +00001216
Ezio Melotti1036a7f2009-09-12 14:43:43 +00001217 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +00001218 def test_good_password(self):
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001219 self.zip.setpassword("python")
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001220 self.assertEqual(self.zip.read("test.txt"), self.plain)
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001221 self.zip2.setpassword("12345")
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001222 self.assertEqual(self.zip2.read("zero"), self.plain2)
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001223
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001224
1225class TestsWithRandomBinaryFiles(unittest.TestCase):
1226 def setUp(self):
1227 datacount = randint(16, 64)*1024 + randint(1, 1024)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001228 self.data = ''.join(struct.pack('<f', random()*randint(-1000, 1000))
Ezio Melotti763f1e82009-12-31 13:27:41 +00001229 for i in xrange(datacount))
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001230
1231 # Make a source file with some lines
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001232 with open(TESTFN, "wb") as fp:
1233 fp.write(self.data)
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00001234
Collin Winter04a51ec2007-03-29 02:28:16 +00001235 def tearDown(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001236 unlink(TESTFN)
1237 unlink(TESTFN2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001238
Ezio Melottid5a23e32009-07-15 17:07:04 +00001239 def make_test_archive(self, f, compression):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001240 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001241 with zipfile.ZipFile(f, "w", compression) as zipfp:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001242 zipfp.write(TESTFN, "another.name")
Ezio Melotti569e61f2009-12-30 06:14:51 +00001243 zipfp.write(TESTFN, TESTFN)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001244
Ezio Melottid5a23e32009-07-15 17:07:04 +00001245 def zip_test(self, f, compression):
1246 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001247
1248 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001249 with zipfile.ZipFile(f, "r", compression) as zipfp:
1250 testdata = zipfp.read(TESTFN)
1251 self.assertEqual(len(testdata), len(self.data))
1252 self.assertEqual(testdata, self.data)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001253 self.assertEqual(zipfp.read("another.name"), self.data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001254
Ezio Melottid5a23e32009-07-15 17:07:04 +00001255 def test_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001256 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001257 self.zip_test(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +00001258
Antoine Pitroue1436d12010-08-12 15:25:51 +00001259 @skipUnless(zlib, "requires zlib")
1260 def test_deflated(self):
1261 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1262 self.zip_test(f, zipfile.ZIP_DEFLATED)
1263
Ezio Melottid5a23e32009-07-15 17:07:04 +00001264 def zip_open_test(self, f, compression):
1265 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001266
1267 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001268 with zipfile.ZipFile(f, "r", compression) as zipfp:
1269 zipdata1 = []
Brian Curtin0d654332011-04-19 21:15:55 -05001270 with zipfp.open(TESTFN) as zipopen1:
1271 while True:
1272 read_data = zipopen1.read(256)
1273 if not read_data:
1274 break
1275 zipdata1.append(read_data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001276
Ezio Melotti569e61f2009-12-30 06:14:51 +00001277 zipdata2 = []
Brian Curtin0d654332011-04-19 21:15:55 -05001278 with zipfp.open("another.name") as zipopen2:
1279 while True:
1280 read_data = zipopen2.read(256)
1281 if not read_data:
1282 break
1283 zipdata2.append(read_data)
Tim Petersea5962f2007-03-12 18:07:52 +00001284
Ezio Melotti569e61f2009-12-30 06:14:51 +00001285 testdata1 = ''.join(zipdata1)
1286 self.assertEqual(len(testdata1), len(self.data))
1287 self.assertEqual(testdata1, self.data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001288
Ezio Melotti569e61f2009-12-30 06:14:51 +00001289 testdata2 = ''.join(zipdata2)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001290 self.assertEqual(len(testdata2), len(self.data))
1291 self.assertEqual(testdata2, self.data)
Tim Petersea5962f2007-03-12 18:07:52 +00001292
Ezio Melottid5a23e32009-07-15 17:07:04 +00001293 def test_open_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001294 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001295 self.zip_open_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001296
Antoine Pitroue1436d12010-08-12 15:25:51 +00001297 @skipUnless(zlib, "requires zlib")
1298 def test_open_deflated(self):
1299 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1300 self.zip_open_test(f, zipfile.ZIP_DEFLATED)
1301
Ezio Melottid5a23e32009-07-15 17:07:04 +00001302 def zip_random_open_test(self, f, compression):
1303 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001304
1305 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001306 with zipfile.ZipFile(f, "r", compression) as zipfp:
1307 zipdata1 = []
Brian Curtin0d654332011-04-19 21:15:55 -05001308 with zipfp.open(TESTFN) as zipopen1:
1309 while True:
1310 read_data = zipopen1.read(randint(1, 1024))
1311 if not read_data:
1312 break
1313 zipdata1.append(read_data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001314
Ezio Melotti569e61f2009-12-30 06:14:51 +00001315 testdata = ''.join(zipdata1)
1316 self.assertEqual(len(testdata), len(self.data))
1317 self.assertEqual(testdata, self.data)
Tim Petersea5962f2007-03-12 18:07:52 +00001318
Ezio Melottid5a23e32009-07-15 17:07:04 +00001319 def test_random_open_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001320 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001321 self.zip_random_open_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001322
Antoine Pitroue1436d12010-08-12 15:25:51 +00001323 @skipUnless(zlib, "requires zlib")
1324 def test_random_open_deflated(self):
1325 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1326 self.zip_random_open_test(f, zipfile.ZIP_DEFLATED)
1327
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001328
Ezio Melotti1036a7f2009-09-12 14:43:43 +00001329@skipUnless(zlib, "requires zlib")
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001330class TestsWithMultipleOpens(unittest.TestCase):
1331 def setUp(self):
1332 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001333 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
1334 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
1335 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
Tim Petersea5962f2007-03-12 18:07:52 +00001336
Ezio Melottid5a23e32009-07-15 17:07:04 +00001337 def test_same_file(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001338 # Verify that (when the ZipFile is in control of creating file objects)
1339 # multiple open() calls can be made without interfering with each other.
Ezio Melotti569e61f2009-12-30 06:14:51 +00001340 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Benjamin Peterson352eb4f2014-04-03 10:31:25 -04001341 with zipf.open('ones') as zopen1, zipf.open('ones') as zopen2:
1342 data1 = zopen1.read(500)
1343 data2 = zopen2.read(500)
1344 data1 += zopen1.read(500)
1345 data2 += zopen2.read(500)
Ezio Melotti569e61f2009-12-30 06:14:51 +00001346 self.assertEqual(data1, data2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001347
Ezio Melottid5a23e32009-07-15 17:07:04 +00001348 def test_different_file(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001349 # Verify that (when the ZipFile is in control of creating file objects)
1350 # multiple open() calls can be made without interfering with each other.
Ezio Melotti569e61f2009-12-30 06:14:51 +00001351 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin0d654332011-04-19 21:15:55 -05001352 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1353 data1 = zopen1.read(500)
1354 data2 = zopen2.read(500)
1355 data1 += zopen1.read(500)
1356 data2 += zopen2.read(500)
Ezio Melotti569e61f2009-12-30 06:14:51 +00001357 self.assertEqual(data1, '1'*FIXEDTEST_SIZE)
1358 self.assertEqual(data2, '2'*FIXEDTEST_SIZE)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001359
Ezio Melottid5a23e32009-07-15 17:07:04 +00001360 def test_interleaved(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001361 # Verify that (when the ZipFile is in control of creating file objects)
1362 # multiple open() calls can be made without interfering with each other.
Ezio Melotti569e61f2009-12-30 06:14:51 +00001363 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin0d654332011-04-19 21:15:55 -05001364 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1365 data1 = zopen1.read(500)
1366 data2 = zopen2.read(500)
1367 data1 += zopen1.read(500)
1368 data2 += zopen2.read(500)
Ezio Melotti569e61f2009-12-30 06:14:51 +00001369 self.assertEqual(data1, '1'*FIXEDTEST_SIZE)
1370 self.assertEqual(data2, '2'*FIXEDTEST_SIZE)
Tim Petersea5962f2007-03-12 18:07:52 +00001371
Benjamin Peterson352eb4f2014-04-03 10:31:25 -04001372 def test_many_opens(self):
1373 # Verify that read() and open() promptly close the file descriptor,
1374 # and don't rely on the garbage collector to free resources.
1375 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
1376 for x in range(100):
1377 zipf.read('ones')
1378 with zipf.open('ones') as zopen1:
1379 pass
1380 with open(os.devnull) as f:
1381 self.assertLess(f.fileno(), 100)
1382
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001383 def tearDown(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001384 unlink(TESTFN2)
1385
Tim Petersea5962f2007-03-12 18:07:52 +00001386
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001387class TestWithDirectory(unittest.TestCase):
1388 def setUp(self):
1389 os.mkdir(TESTFN2)
1390
Ezio Melottid5a23e32009-07-15 17:07:04 +00001391 def test_extract_dir(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +00001392 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
1393 zipf.extractall(TESTFN2)
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001394 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1395 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1396 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1397
Ezio Melottid5a23e32009-07-15 17:07:04 +00001398 def test_bug_6050(self):
Martin v. Löwis0b09c422009-05-24 19:30:52 +00001399 # Extraction should succeed if directories already exist
1400 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottid5a23e32009-07-15 17:07:04 +00001401 self.test_extract_dir()
Martin v. Löwis0b09c422009-05-24 19:30:52 +00001402
Ezio Melottid5a23e32009-07-15 17:07:04 +00001403 def test_store_dir(self):
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001404 os.mkdir(os.path.join(TESTFN2, "x"))
Benjamin Peterson352eb4f2014-04-03 10:31:25 -04001405 with zipfile.ZipFile(TESTFN, "w") as zipf:
1406 zipf.write(os.path.join(TESTFN2, "x"), "x")
1407 self.assertTrue(zipf.filelist[0].filename.endswith("x/"))
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001408
1409 def tearDown(self):
Benjamin Peterson352eb4f2014-04-03 10:31:25 -04001410 rmtree(TESTFN2)
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001411 if os.path.exists(TESTFN):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001412 unlink(TESTFN)
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001413
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001414
1415class UniversalNewlineTests(unittest.TestCase):
1416 def setUp(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001417 self.line_gen = ["Test of zipfile line %d." % i
1418 for i in xrange(FIXEDTEST_SIZE)]
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001419 self.seps = ('\r', '\r\n', '\n')
1420 self.arcdata, self.arcfiles = {}, {}
1421 for n, s in enumerate(self.seps):
1422 self.arcdata[s] = s.join(self.line_gen) + s
1423 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Benjamin Peterson352eb4f2014-04-03 10:31:25 -04001424 with open(self.arcfiles[s], "wb") as fid:
1425 fid.write(self.arcdata[s])
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001426
Ezio Melottid5a23e32009-07-15 17:07:04 +00001427 def make_test_archive(self, f, compression):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001428 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001429 with zipfile.ZipFile(f, "w", compression) as zipfp:
1430 for fn in self.arcfiles.values():
1431 zipfp.write(fn, fn)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001432
Ezio Melottid5a23e32009-07-15 17:07:04 +00001433 def read_test(self, f, compression):
1434 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001435
1436 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001437 with zipfile.ZipFile(f, "r") as zipfp:
1438 for sep, fn in self.arcfiles.items():
Brian Curtin0d654332011-04-19 21:15:55 -05001439 with zipfp.open(fn, "rU") as fp:
1440 zipdata = fp.read()
Ezio Melotti569e61f2009-12-30 06:14:51 +00001441 self.assertEqual(self.arcdata[sep], zipdata)
Tim Petersea5962f2007-03-12 18:07:52 +00001442
Antoine Pitrou94c33eb2010-01-27 20:59:50 +00001443 def readline_read_test(self, f, compression):
1444 self.make_test_archive(f, compression)
1445
1446 # Read the ZIP archive
1447 zipfp = zipfile.ZipFile(f, "r")
1448 for sep, fn in self.arcfiles.items():
Brian Curtin0d654332011-04-19 21:15:55 -05001449 with zipfp.open(fn, "rU") as zipopen:
1450 data = ''
1451 while True:
1452 read = zipopen.readline()
1453 if not read:
1454 break
1455 data += read
Antoine Pitrou94c33eb2010-01-27 20:59:50 +00001456
Brian Curtin0d654332011-04-19 21:15:55 -05001457 read = zipopen.read(5)
1458 if not read:
1459 break
1460 data += read
Antoine Pitrou94c33eb2010-01-27 20:59:50 +00001461
1462 self.assertEqual(data, self.arcdata['\n'])
1463
1464 zipfp.close()
1465
Ezio Melottid5a23e32009-07-15 17:07:04 +00001466 def readline_test(self, f, compression):
1467 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001468
1469 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001470 with zipfile.ZipFile(f, "r") as zipfp:
1471 for sep, fn in self.arcfiles.items():
Brian Curtin0d654332011-04-19 21:15:55 -05001472 with zipfp.open(fn, "rU") as zipopen:
1473 for line in self.line_gen:
1474 linedata = zipopen.readline()
1475 self.assertEqual(linedata, line + '\n')
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001476
Ezio Melottid5a23e32009-07-15 17:07:04 +00001477 def readlines_test(self, f, compression):
1478 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001479
1480 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001481 with zipfile.ZipFile(f, "r") as zipfp:
1482 for sep, fn in self.arcfiles.items():
Brian Curtin0d654332011-04-19 21:15:55 -05001483 with zipfp.open(fn, "rU") as fp:
1484 ziplines = fp.readlines()
Ezio Melotti569e61f2009-12-30 06:14:51 +00001485 for line, zipline in zip(self.line_gen, ziplines):
1486 self.assertEqual(zipline, line + '\n')
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001487
Ezio Melottid5a23e32009-07-15 17:07:04 +00001488 def iterlines_test(self, f, compression):
1489 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001490
1491 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001492 with zipfile.ZipFile(f, "r") as zipfp:
1493 for sep, fn in self.arcfiles.items():
Benjamin Peterson352eb4f2014-04-03 10:31:25 -04001494 with zipfp.open(fn, "rU") as fid:
1495 for line, zipline in zip(self.line_gen, fid):
1496 self.assertEqual(zipline, line + '\n')
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001497
Ezio Melottid5a23e32009-07-15 17:07:04 +00001498 def test_read_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001499 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001500 self.read_test(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +00001501
Antoine Pitrou94c33eb2010-01-27 20:59:50 +00001502 def test_readline_read_stored(self):
1503 # Issue #7610: calls to readline() interleaved with calls to read().
1504 for f in (TESTFN2, TemporaryFile(), StringIO()):
1505 self.readline_read_test(f, zipfile.ZIP_STORED)
1506
Ezio Melottid5a23e32009-07-15 17:07:04 +00001507 def test_readline_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001508 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001509 self.readline_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001510
Ezio Melottid5a23e32009-07-15 17:07:04 +00001511 def test_readlines_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001512 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001513 self.readlines_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001514
Ezio Melottid5a23e32009-07-15 17:07:04 +00001515 def test_iterlines_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001516 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001517 self.iterlines_test(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +00001518
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001519 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +00001520 def test_read_deflated(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001521 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001522 self.read_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001523
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001524 @skipUnless(zlib, "requires zlib")
Antoine Pitrou94c33eb2010-01-27 20:59:50 +00001525 def test_readline_read_deflated(self):
1526 # Issue #7610: calls to readline() interleaved with calls to read().
1527 for f in (TESTFN2, TemporaryFile(), StringIO()):
1528 self.readline_read_test(f, zipfile.ZIP_DEFLATED)
1529
1530 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +00001531 def test_readline_deflated(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001532 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001533 self.readline_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001534
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001535 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +00001536 def test_readlines_deflated(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001537 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001538 self.readlines_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001539
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001540 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +00001541 def test_iterlines_deflated(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001542 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001543 self.iterlines_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001544
1545 def tearDown(self):
1546 for sep, fn in self.arcfiles.items():
1547 os.remove(fn)
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001548 unlink(TESTFN)
1549 unlink(TESTFN2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001550
1551
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001552def test_main():
Tim Petersea5962f2007-03-12 18:07:52 +00001553 run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
1554 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001555 TestWithDirectory, UniversalNewlineTests,
1556 TestsWithRandomBinaryFiles)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001557
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001558if __name__ == "__main__":
1559 test_main()