blob: f960b6c7d4f6dae14cb2ae091b47506b9bd7937a [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 shutil
12import struct
13import zipfile
14import unittest
Tim Petersa19a1682001-03-29 04:36:09 +000015
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000016from StringIO import StringIO
17from tempfile import TemporaryFile
Martin v. Löwis3eb76482007-03-06 10:41:24 +000018from random import randint, random
Ezio Melottie7a0cc22009-07-04 14:58:27 +000019from unittest import skipUnless
Tim Petersa19a1682001-03-29 04:36:09 +000020
Serhiy Storchaka6fa83f92013-04-13 12:28:17 +030021from test.test_support import TESTFN, TESTFN_UNICODE, run_unittest, findfile, unlink
Guido van Rossum368f04a2000-04-10 13:23:04 +000022
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000023TESTFN2 = TESTFN + "2"
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +000024TESTFNDIR = TESTFN + "d"
Georg Brandl4b3ab6f2007-07-12 09:59:22 +000025FIXEDTEST_SIZE = 1000
Guido van Rossum368f04a2000-04-10 13:23:04 +000026
Georg Brandl62416bc2008-01-07 18:47:44 +000027SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'),
28 ('ziptest2dir/_ziptest2', 'qawsedrftg'),
Gregory P. Smith608cc452013-02-01 11:40:18 -080029 ('ziptest2dir/ziptest3dir/_ziptest3', 'azsxdcfvgb'),
Georg Brandl62416bc2008-01-07 18:47:44 +000030 ('ziptest2dir/ziptest3dir/ziptest4dir/_ziptest3', '6y7u8i9o0p')]
31
Ezio Melotti6cbfc122009-07-10 20:25:56 +000032
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000033class TestsWithSourceFile(unittest.TestCase):
34 def setUp(self):
Georg Brandl4b3ab6f2007-07-12 09:59:22 +000035 self.line_gen = ["Zipfile test line %d. random float: %f" % (i, random())
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000036 for i in xrange(FIXEDTEST_SIZE)]
Martin v. Löwis3eb76482007-03-06 10:41:24 +000037 self.data = '\n'.join(self.line_gen) + '\n'
Fred Drake6e7e4852001-02-28 05:34:16 +000038
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000039 # Make a source file with some lines
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000040 with open(TESTFN, "wb") as fp:
41 fp.write(self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000042
Ezio Melottid5a23e32009-07-15 17:07:04 +000043 def make_test_archive(self, f, compression):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000044 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +000045 with zipfile.ZipFile(f, "w", compression) as zipfp:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000046 zipfp.write(TESTFN, "another.name")
Ezio Melotti569e61f2009-12-30 06:14:51 +000047 zipfp.write(TESTFN, TESTFN)
48 zipfp.writestr("strfile", self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000049
Ezio Melottid5a23e32009-07-15 17:07:04 +000050 def zip_test(self, f, compression):
51 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +000052
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000053 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +000054 with zipfile.ZipFile(f, "r", compression) as zipfp:
55 self.assertEqual(zipfp.read(TESTFN), self.data)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000056 self.assertEqual(zipfp.read("another.name"), self.data)
Ezio Melotti569e61f2009-12-30 06:14:51 +000057 self.assertEqual(zipfp.read("strfile"), self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +000058
Ezio Melotti569e61f2009-12-30 06:14:51 +000059 # Print the ZIP directory
60 fp = StringIO()
61 stdout = sys.stdout
62 try:
63 sys.stdout = fp
64 zipfp.printdir()
65 finally:
66 sys.stdout = stdout
Tim Petersa608bb22006-06-15 18:06:29 +000067
Ezio Melotti569e61f2009-12-30 06:14:51 +000068 directory = fp.getvalue()
69 lines = directory.splitlines()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000070 self.assertEqual(len(lines), 4) # Number of files + header
Ronald Oussoren143cefb2006-06-15 08:14:18 +000071
Ezio Melottiaa980582010-01-23 23:04:36 +000072 self.assertIn('File Name', lines[0])
73 self.assertIn('Modified', lines[0])
74 self.assertIn('Size', lines[0])
Ronald Oussoren143cefb2006-06-15 08:14:18 +000075
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000076 fn, date, time_, size = lines[1].split()
77 self.assertEqual(fn, 'another.name')
78 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
79 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
80 self.assertEqual(size, str(len(self.data)))
Ronald Oussoren143cefb2006-06-15 08:14:18 +000081
Ezio Melotti569e61f2009-12-30 06:14:51 +000082 # Check the namelist
83 names = zipfp.namelist()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000084 self.assertEqual(len(names), 3)
Ezio Melottiaa980582010-01-23 23:04:36 +000085 self.assertIn(TESTFN, names)
86 self.assertIn("another.name", names)
87 self.assertIn("strfile", names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +000088
Ezio Melotti569e61f2009-12-30 06:14:51 +000089 # Check infolist
90 infos = zipfp.infolist()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000091 names = [i.filename for i in infos]
92 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)
Ezio Melotti569e61f2009-12-30 06:14:51 +000096 for i in infos:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000097 self.assertEqual(i.file_size, len(self.data))
Ronald Oussoren143cefb2006-06-15 08:14:18 +000098
Ezio Melotti569e61f2009-12-30 06:14:51 +000099 # check getinfo
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000100 for nm in (TESTFN, "another.name", "strfile"):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000101 info = zipfp.getinfo(nm)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000102 self.assertEqual(info.filename, nm)
103 self.assertEqual(info.file_size, len(self.data))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000104
Ezio Melotti569e61f2009-12-30 06:14:51 +0000105 # Check that testzip doesn't raise an exception
106 zipfp.testzip()
Tim Peters7d3bad62001-04-04 18:56:49 +0000107
Ezio Melottid5a23e32009-07-15 17:07:04 +0000108 def test_stored(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000109 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000110 self.zip_test(f, zipfile.ZIP_STORED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000111
Ezio Melottid5a23e32009-07-15 17:07:04 +0000112 def zip_open_test(self, f, compression):
113 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000114
115 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000116 with zipfile.ZipFile(f, "r", compression) as zipfp:
117 zipdata1 = []
Brian Curtin0d654332011-04-19 21:15:55 -0500118 with zipfp.open(TESTFN) as zipopen1:
119 while True:
120 read_data = zipopen1.read(256)
121 if not read_data:
122 break
123 zipdata1.append(read_data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000124
Ezio Melotti569e61f2009-12-30 06:14:51 +0000125 zipdata2 = []
Brian Curtin0d654332011-04-19 21:15:55 -0500126 with zipfp.open("another.name") as zipopen2:
127 while True:
128 read_data = zipopen2.read(256)
129 if not read_data:
130 break
131 zipdata2.append(read_data)
Tim Petersea5962f2007-03-12 18:07:52 +0000132
Ezio Melotti569e61f2009-12-30 06:14:51 +0000133 self.assertEqual(''.join(zipdata1), self.data)
134 self.assertEqual(''.join(zipdata2), self.data)
Tim Petersea5962f2007-03-12 18:07:52 +0000135
Ezio Melottid5a23e32009-07-15 17:07:04 +0000136 def test_open_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000137 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000138 self.zip_open_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000139
Ezio Melottid5a23e32009-07-15 17:07:04 +0000140 def test_open_via_zip_info(self):
Georg Brandl112aa502008-05-20 08:25:48 +0000141 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000142 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
143 zipfp.writestr("name", "foo")
144 zipfp.writestr("name", "bar")
Georg Brandl112aa502008-05-20 08:25:48 +0000145
Ezio Melotti569e61f2009-12-30 06:14:51 +0000146 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
147 infos = zipfp.infolist()
148 data = ""
149 for info in infos:
Brian Curtin0d654332011-04-19 21:15:55 -0500150 with zipfp.open(info) as f:
151 data += f.read()
Ezio Melotti569e61f2009-12-30 06:14:51 +0000152 self.assertTrue(data == "foobar" or data == "barfoo")
153 data = ""
154 for info in infos:
155 data += zipfp.read(info)
156 self.assertTrue(data == "foobar" or data == "barfoo")
Georg Brandl112aa502008-05-20 08:25:48 +0000157
Ezio Melottid5a23e32009-07-15 17:07:04 +0000158 def zip_random_open_test(self, f, compression):
159 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000160
161 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000162 with zipfile.ZipFile(f, "r", compression) as zipfp:
163 zipdata1 = []
Brian Curtin0d654332011-04-19 21:15:55 -0500164 with zipfp.open(TESTFN) as zipopen1:
165 while True:
166 read_data = zipopen1.read(randint(1, 1024))
167 if not read_data:
168 break
169 zipdata1.append(read_data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000170
Ezio Melotti569e61f2009-12-30 06:14:51 +0000171 self.assertEqual(''.join(zipdata1), self.data)
Tim Petersea5962f2007-03-12 18:07:52 +0000172
Ezio Melottid5a23e32009-07-15 17:07:04 +0000173 def test_random_open_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000174 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000175 self.zip_random_open_test(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +0000176
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000177 def test_univeral_readaheads(self):
178 f = StringIO()
179
180 data = 'a\r\n' * 16 * 1024
Brian Curtin0d654332011-04-19 21:15:55 -0500181 with zipfile.ZipFile(f, 'w', zipfile.ZIP_STORED) as zipfp:
182 zipfp.writestr(TESTFN, data)
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000183
184 data2 = ''
Brian Curtin0d654332011-04-19 21:15:55 -0500185 with zipfile.ZipFile(f, 'r') as zipfp:
186 with zipfp.open(TESTFN, 'rU') as zipopen:
187 for line in zipopen:
188 data2 += line
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000189
190 self.assertEqual(data, data2.replace('\n', '\r\n'))
191
192 def zip_readline_read_test(self, f, compression):
193 self.make_test_archive(f, compression)
194
195 # Read the ZIP archive
Brian Curtin0d654332011-04-19 21:15:55 -0500196 with zipfile.ZipFile(f, "r") as zipfp:
197 with zipfp.open(TESTFN) as zipopen:
198 data = ''
199 while True:
200 read = zipopen.readline()
201 if not read:
202 break
203 data += read
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000204
Brian Curtin0d654332011-04-19 21:15:55 -0500205 read = zipopen.read(100)
206 if not read:
207 break
208 data += read
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000209
210 self.assertEqual(data, self.data)
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000211
Ezio Melottid5a23e32009-07-15 17:07:04 +0000212 def zip_readline_test(self, f, compression):
213 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000214
215 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000216 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin0d654332011-04-19 21:15:55 -0500217 with zipfp.open(TESTFN) as zipopen:
218 for line in self.line_gen:
219 linedata = zipopen.readline()
220 self.assertEqual(linedata, line + '\n')
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000221
Ezio Melottid5a23e32009-07-15 17:07:04 +0000222 def zip_readlines_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 zo:
228 ziplines = zo.readlines()
229 for line, zipline in zip(self.line_gen, ziplines):
230 self.assertEqual(zipline, line + '\n')
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000231
Ezio Melottid5a23e32009-07-15 17:07:04 +0000232 def zip_iterlines_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:
237 for line, zipline in zip(self.line_gen, zipfp.open(TESTFN)):
238 self.assertEqual(zipline, line + '\n')
Tim Petersea5962f2007-03-12 18:07:52 +0000239
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000240 def test_readline_read_stored(self):
241 # Issue #7610: calls to readline() interleaved with calls to read().
242 for f in (TESTFN2, TemporaryFile(), StringIO()):
243 self.zip_readline_read_test(f, zipfile.ZIP_STORED)
244
Ezio Melottid5a23e32009-07-15 17:07:04 +0000245 def test_readline_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000246 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000247 self.zip_readline_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000248
Ezio Melottid5a23e32009-07-15 17:07:04 +0000249 def test_readlines_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000250 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000251 self.zip_readlines_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000252
Ezio Melottid5a23e32009-07-15 17:07:04 +0000253 def test_iterlines_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_iterlines_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000256
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000257 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000258 def test_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000259 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000260 self.zip_test(f, zipfile.ZIP_DEFLATED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000261
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000262 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000263 def test_open_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000264 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000265 self.zip_open_test(f, zipfile.ZIP_DEFLATED)
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_random_open_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_random_open_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000271
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000272 @skipUnless(zlib, "requires zlib")
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000273 def test_readline_read_deflated(self):
274 # Issue #7610: calls to readline() interleaved with calls to read().
275 for f in (TESTFN2, TemporaryFile(), StringIO()):
276 self.zip_readline_read_test(f, zipfile.ZIP_DEFLATED)
277
278 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000279 def test_readline_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000280 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000281 self.zip_readline_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000282
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000283 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000284 def test_readlines_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000285 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000286 self.zip_readlines_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000287
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000288 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000289 def test_iterlines_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_iterlines_test(f, zipfile.ZIP_DEFLATED)
Tim Petersea5962f2007-03-12 18:07:52 +0000292
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000293 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000294 def test_low_compression(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000295 """Check for cases where compressed data is larger than original."""
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000296 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000297 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
298 zipfp.writestr("strfile", '12')
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000299
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000300 # Get an open object for strfile
Ezio Melotti569e61f2009-12-30 06:14:51 +0000301 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_DEFLATED) as zipfp:
Brian Curtin0d654332011-04-19 21:15:55 -0500302 with zipfp.open("strfile") as openobj:
303 self.assertEqual(openobj.read(1), '1')
304 self.assertEqual(openobj.read(1), '2')
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000305
Ezio Melottid5a23e32009-07-15 17:07:04 +0000306 def test_absolute_arcnames(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000307 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
308 zipfp.write(TESTFN, "/absolute")
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000309
Ezio Melotti569e61f2009-12-30 06:14:51 +0000310 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
311 self.assertEqual(zipfp.namelist(), ["absolute"])
Tim Peters32cbc962006-02-20 21:42:18 +0000312
Ezio Melottid5a23e32009-07-15 17:07:04 +0000313 def test_append_to_zip_file(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000314 """Test appending to an existing zipfile."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000315 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
316 zipfp.write(TESTFN, TESTFN)
317
318 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
319 zipfp.writestr("strfile", self.data)
320 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000321
Ezio Melottid5a23e32009-07-15 17:07:04 +0000322 def test_append_to_non_zip_file(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000323 """Test appending to an existing file that is not a zipfile."""
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000324 # NOTE: this test fails if len(d) < 22 because of the first
325 # line "fpin.seek(-22, 2)" in _EndRecData
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000326 data = 'I am not a ZipFile!'*10
327 with open(TESTFN2, 'wb') as f:
328 f.write(data)
329
Ezio Melotti569e61f2009-12-30 06:14:51 +0000330 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
331 zipfp.write(TESTFN, TESTFN)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000332
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000333 with open(TESTFN2, 'rb') as f:
334 f.seek(len(data))
335 with zipfile.ZipFile(f, "r") as zipfp:
336 self.assertEqual(zipfp.namelist(), [TESTFN])
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000337
R David Murray873c5832011-06-09 16:01:09 -0400338 def test_ignores_newline_at_end(self):
339 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
340 zipfp.write(TESTFN, TESTFN)
341 with open(TESTFN2, 'a') as f:
342 f.write("\r\n\00\00\00")
343 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
344 self.assertIsInstance(zipfp, zipfile.ZipFile)
345
346 def test_ignores_stuff_appended_past_comments(self):
347 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
348 zipfp.comment = b"this is a comment"
349 zipfp.write(TESTFN, TESTFN)
350 with open(TESTFN2, 'a') as f:
351 f.write("abcdef\r\n")
352 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
353 self.assertIsInstance(zipfp, zipfile.ZipFile)
354 self.assertEqual(zipfp.comment, b"this is a comment")
355
Ezio Melottid5a23e32009-07-15 17:07:04 +0000356 def test_write_default_name(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000357 """Check that calling ZipFile.write without arcname specified
358 produces the expected result."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000359 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
360 zipfp.write(TESTFN)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000361 self.assertEqual(zipfp.read(TESTFN), open(TESTFN).read())
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000362
Ezio Melotti1036a7f2009-09-12 14:43:43 +0000363 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000364 def test_per_file_compression(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000365 """Check that files within a Zip archive can have different
366 compression options."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000367 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
368 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
369 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
370 sinfo = zipfp.getinfo('storeme')
371 dinfo = zipfp.getinfo('deflateme')
372 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
373 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000374
Ezio Melottid5a23e32009-07-15 17:07:04 +0000375 def test_write_to_readonly(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000376 """Check that trying to call write() on a readonly ZipFile object
377 raises a RuntimeError."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000378 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
379 zipfp.writestr("somefile.txt", "bogus")
380
381 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
382 self.assertRaises(RuntimeError, zipfp.write, TESTFN)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000383
Ezio Melottid5a23e32009-07-15 17:07:04 +0000384 def test_extract(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000385 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
386 for fpath, fdata in SMALL_TEST_DATA:
387 zipfp.writestr(fpath, fdata)
Georg Brandl62416bc2008-01-07 18:47:44 +0000388
Ezio Melotti569e61f2009-12-30 06:14:51 +0000389 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
390 for fpath, fdata in SMALL_TEST_DATA:
391 writtenfile = zipfp.extract(fpath)
Georg Brandl62416bc2008-01-07 18:47:44 +0000392
Ezio Melotti569e61f2009-12-30 06:14:51 +0000393 # make sure it was written to the right place
Gregory P. Smith608cc452013-02-01 11:40:18 -0800394 correctfile = os.path.join(os.getcwd(), fpath)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000395 correctfile = os.path.normpath(correctfile)
Georg Brandl62416bc2008-01-07 18:47:44 +0000396
Ezio Melotti569e61f2009-12-30 06:14:51 +0000397 self.assertEqual(writtenfile, correctfile)
Georg Brandl62416bc2008-01-07 18:47:44 +0000398
Ezio Melotti569e61f2009-12-30 06:14:51 +0000399 # make sure correct data is in correct file
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000400 self.assertEqual(fdata, open(writtenfile, "rb").read())
Ezio Melotti569e61f2009-12-30 06:14:51 +0000401 os.remove(writtenfile)
Georg Brandl62416bc2008-01-07 18:47:44 +0000402
403 # remove the test file subdirectories
404 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
405
Ezio Melottid5a23e32009-07-15 17:07:04 +0000406 def test_extract_all(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000407 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
408 for fpath, fdata in SMALL_TEST_DATA:
409 zipfp.writestr(fpath, fdata)
Georg Brandl62416bc2008-01-07 18:47:44 +0000410
Ezio Melotti569e61f2009-12-30 06:14:51 +0000411 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
412 zipfp.extractall()
413 for fpath, fdata in SMALL_TEST_DATA:
Gregory P. Smith608cc452013-02-01 11:40:18 -0800414 outfile = os.path.join(os.getcwd(), fpath)
Georg Brandl62416bc2008-01-07 18:47:44 +0000415
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000416 self.assertEqual(fdata, open(outfile, "rb").read())
Ezio Melotti569e61f2009-12-30 06:14:51 +0000417 os.remove(outfile)
Georg Brandl62416bc2008-01-07 18:47:44 +0000418
419 # remove the test file subdirectories
420 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
421
Gregory P. Smith608cc452013-02-01 11:40:18 -0800422 def check_file(self, filename, content):
423 self.assertTrue(os.path.isfile(filename))
424 with open(filename, 'rb') as f:
425 self.assertEqual(f.read(), content)
426
Serhiy Storchaka6fa83f92013-04-13 12:28:17 +0300427 def test_extract_unicode_filenames(self):
428 fnames = [u'foo.txt', os.path.basename(TESTFN_UNICODE)]
429 content = 'Test for unicode filename'
430 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
431 for fname in fnames:
432 zipfp.writestr(fname, content)
433
434 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
435 for fname in fnames:
436 writtenfile = zipfp.extract(fname)
437
438 # make sure it was written to the right place
439 correctfile = os.path.join(os.getcwd(), fname)
440 correctfile = os.path.normpath(correctfile)
441 self.assertEqual(writtenfile, correctfile)
442
443 self.check_file(writtenfile, content)
444 os.remove(writtenfile)
445
Gregory P. Smith608cc452013-02-01 11:40:18 -0800446 def test_extract_hackers_arcnames(self):
447 hacknames = [
448 ('../foo/bar', 'foo/bar'),
449 ('foo/../bar', 'foo/bar'),
450 ('foo/../../bar', 'foo/bar'),
451 ('foo/bar/..', 'foo/bar'),
452 ('./../foo/bar', 'foo/bar'),
453 ('/foo/bar', 'foo/bar'),
454 ('/foo/../bar', 'foo/bar'),
455 ('/foo/../../bar', 'foo/bar'),
Gregory P. Smith608cc452013-02-01 11:40:18 -0800456 ]
457 if os.path.sep == '\\':
458 hacknames.extend([
459 (r'..\foo\bar', 'foo/bar'),
460 (r'..\/foo\/bar', 'foo/bar'),
461 (r'foo/\..\/bar', 'foo/bar'),
462 (r'foo\/../\bar', 'foo/bar'),
463 (r'C:foo/bar', 'foo/bar'),
464 (r'C:/foo/bar', 'foo/bar'),
465 (r'C://foo/bar', 'foo/bar'),
466 (r'C:\foo\bar', 'foo/bar'),
Serhiy Storchaka13e56c72013-02-02 17:46:33 +0200467 (r'//conky/mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
468 (r'\\conky\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
Gregory P. Smith608cc452013-02-01 11:40:18 -0800469 (r'///conky/mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
470 (r'\\\conky\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
471 (r'//conky//mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
472 (r'\\conky\\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
Serhiy Storchaka13e56c72013-02-02 17:46:33 +0200473 (r'//?/C:/foo/bar', '_/C_/foo/bar'),
474 (r'\\?\C:\foo\bar', '_/C_/foo/bar'),
Gregory P. Smith608cc452013-02-01 11:40:18 -0800475 (r'C:/../C:/foo/bar', 'C_/foo/bar'),
476 (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 +0200477 ('../../foo../../ba..r', 'foo/ba..r'),
478 ])
479 else: # Unix
480 hacknames.extend([
481 ('//foo/bar', 'foo/bar'),
482 ('../../foo../../ba..r', 'foo../ba..r'),
Serhiy Storchaka05fd7442013-02-02 18:34:57 +0200483 (r'foo/..\bar', r'foo/..\bar'),
Gregory P. Smith608cc452013-02-01 11:40:18 -0800484 ])
485
486 for arcname, fixedname in hacknames:
487 content = b'foobar' + arcname.encode()
488 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipfp:
Serhiy Storchaka05fd7442013-02-02 18:34:57 +0200489 zinfo = zipfile.ZipInfo()
490 # preserve backslashes
491 zinfo.filename = arcname
492 zinfo.external_attr = 0o600 << 16
493 zipfp.writestr(zinfo, content)
Gregory P. Smith608cc452013-02-01 11:40:18 -0800494
Serhiy Storchaka2a051fa2013-02-02 19:25:57 +0200495 arcname = arcname.replace(os.sep, "/")
Gregory P. Smith608cc452013-02-01 11:40:18 -0800496 targetpath = os.path.join('target', 'subdir', 'subsub')
497 correctfile = os.path.join(targetpath, *fixedname.split('/'))
498
499 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
500 writtenfile = zipfp.extract(arcname, targetpath)
Serhiy Storchaka13e56c72013-02-02 17:46:33 +0200501 self.assertEqual(writtenfile, correctfile,
502 msg="extract %r" % arcname)
Gregory P. Smith608cc452013-02-01 11:40:18 -0800503 self.check_file(correctfile, content)
504 shutil.rmtree('target')
505
506 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
507 zipfp.extractall(targetpath)
508 self.check_file(correctfile, content)
509 shutil.rmtree('target')
510
511 correctfile = os.path.join(os.getcwd(), *fixedname.split('/'))
512
513 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
514 writtenfile = zipfp.extract(arcname)
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)
518 shutil.rmtree(fixedname.split('/')[0])
519
520 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
521 zipfp.extractall()
522 self.check_file(correctfile, content)
523 shutil.rmtree(fixedname.split('/')[0])
524
525 os.remove(TESTFN2)
526
Ronald Oussorendd25e862010-02-07 20:18:02 +0000527 def test_writestr_compression(self):
528 zipfp = zipfile.ZipFile(TESTFN2, "w")
529 zipfp.writestr("a.txt", "hello world", compress_type=zipfile.ZIP_STORED)
530 if zlib:
531 zipfp.writestr("b.txt", "hello world", compress_type=zipfile.ZIP_DEFLATED)
532
533 info = zipfp.getinfo('a.txt')
534 self.assertEqual(info.compress_type, zipfile.ZIP_STORED)
535
536 if zlib:
537 info = zipfp.getinfo('b.txt')
538 self.assertEqual(info.compress_type, zipfile.ZIP_DEFLATED)
539
540
Antoine Pitrou5fdfa3e2008-07-25 19:42:26 +0000541 def zip_test_writestr_permissions(self, f, compression):
542 # Make sure that writestr creates files with mode 0600,
543 # when it is passed a name rather than a ZipInfo instance.
544
Ezio Melottid5a23e32009-07-15 17:07:04 +0000545 self.make_test_archive(f, compression)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000546 with zipfile.ZipFile(f, "r") as zipfp:
547 zinfo = zipfp.getinfo('strfile')
548 self.assertEqual(zinfo.external_attr, 0600 << 16)
Antoine Pitrou5fdfa3e2008-07-25 19:42:26 +0000549
Ezio Melottid5a23e32009-07-15 17:07:04 +0000550 def test_writestr_permissions(self):
Antoine Pitrou5fdfa3e2008-07-25 19:42:26 +0000551 for f in (TESTFN2, TemporaryFile(), StringIO()):
552 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
553
Ezio Melotti569e61f2009-12-30 06:14:51 +0000554 def test_close(self):
555 """Check that the zipfile is closed after the 'with' block."""
556 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
557 for fpath, fdata in SMALL_TEST_DATA:
558 zipfp.writestr(fpath, fdata)
559 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
560 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
561
562 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
563 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
564 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
565
566 def test_close_on_exception(self):
567 """Check that the zipfile is closed if an exception is raised in the
568 'with' block."""
569 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
570 for fpath, fdata in SMALL_TEST_DATA:
571 zipfp.writestr(fpath, fdata)
572
573 try:
574 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
575 raise zipfile.BadZipfile()
576 except zipfile.BadZipfile:
577 self.assertTrue(zipfp2.fp is None, 'zipfp is not closed')
578
Senthil Kumaranddd40312011-10-20 01:38:35 +0800579 def test_add_file_before_1980(self):
580 # Set atime and mtime to 1970-01-01
581 os.utime(TESTFN, (0, 0))
582 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
583 self.assertRaises(ValueError, zipfp.write, TESTFN)
584
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000585 def tearDown(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000586 unlink(TESTFN)
587 unlink(TESTFN2)
588
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000589
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000590class TestZip64InSmallFiles(unittest.TestCase):
591 # These tests test the ZIP64 functionality without using large files,
592 # see test_zipfile64 for proper tests.
593
594 def setUp(self):
595 self._limit = zipfile.ZIP64_LIMIT
596 zipfile.ZIP64_LIMIT = 5
597
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000598 line_gen = ("Test of zipfile line %d." % i
599 for i in range(0, FIXEDTEST_SIZE))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000600 self.data = '\n'.join(line_gen)
601
602 # Make a source file with some lines
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000603 with open(TESTFN, "wb") as fp:
604 fp.write(self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000605
Ezio Melottid5a23e32009-07-15 17:07:04 +0000606 def large_file_exception_test(self, f, compression):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000607 with zipfile.ZipFile(f, "w", compression) as zipfp:
608 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000609 zipfp.write, TESTFN, "another.name")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000610
Ezio Melottid5a23e32009-07-15 17:07:04 +0000611 def large_file_exception_test2(self, f, compression):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000612 with zipfile.ZipFile(f, "w", compression) as zipfp:
613 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000614 zipfp.writestr, "another.name", self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000615
Ezio Melottid5a23e32009-07-15 17:07:04 +0000616 def test_large_file_exception(self):
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000617 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000618 self.large_file_exception_test(f, zipfile.ZIP_STORED)
619 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000620
Ezio Melottid5a23e32009-07-15 17:07:04 +0000621 def zip_test(self, f, compression):
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000622 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000623 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000624 zipfp.write(TESTFN, "another.name")
Ezio Melotti569e61f2009-12-30 06:14:51 +0000625 zipfp.write(TESTFN, TESTFN)
626 zipfp.writestr("strfile", self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000627
628 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000629 with zipfile.ZipFile(f, "r", compression) as zipfp:
630 self.assertEqual(zipfp.read(TESTFN), self.data)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000631 self.assertEqual(zipfp.read("another.name"), self.data)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000632 self.assertEqual(zipfp.read("strfile"), self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000633
Ezio Melotti569e61f2009-12-30 06:14:51 +0000634 # Print the ZIP directory
635 fp = StringIO()
636 stdout = sys.stdout
637 try:
638 sys.stdout = fp
639 zipfp.printdir()
640 finally:
641 sys.stdout = stdout
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000642
Ezio Melotti569e61f2009-12-30 06:14:51 +0000643 directory = fp.getvalue()
644 lines = directory.splitlines()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000645 self.assertEqual(len(lines), 4) # Number of files + header
Tim Petersa608bb22006-06-15 18:06:29 +0000646
Ezio Melottiaa980582010-01-23 23:04:36 +0000647 self.assertIn('File Name', lines[0])
648 self.assertIn('Modified', lines[0])
649 self.assertIn('Size', lines[0])
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000650
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000651 fn, date, time_, size = lines[1].split()
652 self.assertEqual(fn, 'another.name')
653 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
654 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
655 self.assertEqual(size, str(len(self.data)))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000656
Ezio Melotti569e61f2009-12-30 06:14:51 +0000657 # Check the namelist
658 names = zipfp.namelist()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000659 self.assertEqual(len(names), 3)
Ezio Melottiaa980582010-01-23 23:04:36 +0000660 self.assertIn(TESTFN, names)
661 self.assertIn("another.name", names)
662 self.assertIn("strfile", names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000663
Ezio Melotti569e61f2009-12-30 06:14:51 +0000664 # Check infolist
665 infos = zipfp.infolist()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000666 names = [i.filename for i in infos]
667 self.assertEqual(len(names), 3)
Ezio Melottiaa980582010-01-23 23:04:36 +0000668 self.assertIn(TESTFN, names)
669 self.assertIn("another.name", names)
670 self.assertIn("strfile", names)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000671 for i in infos:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000672 self.assertEqual(i.file_size, len(self.data))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000673
Ezio Melotti569e61f2009-12-30 06:14:51 +0000674 # check getinfo
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000675 for nm in (TESTFN, "another.name", "strfile"):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000676 info = zipfp.getinfo(nm)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000677 self.assertEqual(info.filename, nm)
678 self.assertEqual(info.file_size, len(self.data))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000679
Ezio Melotti569e61f2009-12-30 06:14:51 +0000680 # Check that testzip doesn't raise an exception
681 zipfp.testzip()
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000682
Ezio Melottid5a23e32009-07-15 17:07:04 +0000683 def test_stored(self):
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000684 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000685 self.zip_test(f, zipfile.ZIP_STORED)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000686
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000687 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000688 def test_deflated(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000689 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000690 self.zip_test(f, zipfile.ZIP_DEFLATED)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000691
Ezio Melottid5a23e32009-07-15 17:07:04 +0000692 def test_absolute_arcnames(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000693 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
694 allowZip64=True) as zipfp:
695 zipfp.write(TESTFN, "/absolute")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000696
Ezio Melotti569e61f2009-12-30 06:14:51 +0000697 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
698 self.assertEqual(zipfp.namelist(), ["absolute"])
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000699
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000700 def tearDown(self):
701 zipfile.ZIP64_LIMIT = self._limit
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000702 unlink(TESTFN)
703 unlink(TESTFN2)
704
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000705
706class PyZipFileTests(unittest.TestCase):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000707 def test_write_pyfile(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000708 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
709 fn = __file__
710 if fn.endswith('.pyc') or fn.endswith('.pyo'):
711 fn = fn[:-1]
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000712
Ezio Melotti569e61f2009-12-30 06:14:51 +0000713 zipfp.writepy(fn)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000714
Ezio Melotti569e61f2009-12-30 06:14:51 +0000715 bn = os.path.basename(fn)
Ezio Melottiaa980582010-01-23 23:04:36 +0000716 self.assertNotIn(bn, zipfp.namelist())
Ezio Melotti569e61f2009-12-30 06:14:51 +0000717 self.assertTrue(bn + 'o' in zipfp.namelist() or
718 bn + 'c' in zipfp.namelist())
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000719
Ezio Melotti569e61f2009-12-30 06:14:51 +0000720 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
721 fn = __file__
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000722 if fn.endswith(('.pyc', '.pyo')):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000723 fn = fn[:-1]
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000724
Ezio Melotti569e61f2009-12-30 06:14:51 +0000725 zipfp.writepy(fn, "testpackage")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000726
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000727 bn = "%s/%s" % ("testpackage", 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 Melottid5a23e32009-07-15 17:07:04 +0000732 def test_write_python_package(self):
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000733 import email
734 packagedir = os.path.dirname(email.__file__)
735
Ezio Melotti569e61f2009-12-30 06:14:51 +0000736 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
737 zipfp.writepy(packagedir)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000738
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000739 # Check for a couple of modules at different levels of the
740 # hierarchy
Ezio Melotti569e61f2009-12-30 06:14:51 +0000741 names = zipfp.namelist()
742 self.assertTrue('email/__init__.pyo' in names or
743 'email/__init__.pyc' in names)
744 self.assertTrue('email/mime/text.pyo' in names or
745 'email/mime/text.pyc' in names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000746
Ezio Melottid5a23e32009-07-15 17:07:04 +0000747 def test_write_python_directory(self):
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000748 os.mkdir(TESTFN2)
749 try:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000750 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
Ezio Melotti763f1e82009-12-31 13:27:41 +0000751 fp.write("print(42)\n")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000752
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000753 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
Ezio Melotti763f1e82009-12-31 13:27:41 +0000754 fp.write("print(42 * 42)\n")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000755
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000756 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
757 fp.write("bla bla bla\n")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000758
759 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
760 zipfp.writepy(TESTFN2)
761
762 names = zipfp.namelist()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000763 self.assertTrue('mod1.pyc' in names or 'mod1.pyo' in names)
764 self.assertTrue('mod2.pyc' in names or 'mod2.pyo' in names)
Ezio Melottiaa980582010-01-23 23:04:36 +0000765 self.assertNotIn('mod2.txt', names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000766
767 finally:
768 shutil.rmtree(TESTFN2)
769
Ezio Melottid5a23e32009-07-15 17:07:04 +0000770 def test_write_non_pyfile(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000771 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000772 open(TESTFN, 'w').write('most definitely not a python file')
Ezio Melotti569e61f2009-12-30 06:14:51 +0000773 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
774 os.remove(TESTFN)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000775
776
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000777class OtherTests(unittest.TestCase):
Antoine Pitroue1436d12010-08-12 15:25:51 +0000778 zips_with_bad_crc = {
779 zipfile.ZIP_STORED: (
780 b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
781 b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
782 b'ilehello,AworldP'
783 b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
784 b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
785 b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
786 b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
787 b'\0\0/\0\0\0\0\0'),
788 zipfile.ZIP_DEFLATED: (
789 b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
790 b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
791 b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
792 b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
793 b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
794 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
795 b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
796 b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00'),
797 }
798
Ezio Melottid5a23e32009-07-15 17:07:04 +0000799 def test_unicode_filenames(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000800 with zipfile.ZipFile(TESTFN, "w") as zf:
801 zf.writestr(u"foo.txt", "Test for unicode filename")
802 zf.writestr(u"\xf6.txt", "Test for unicode filename")
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000803 self.assertIsInstance(zf.infolist()[0].filename, unicode)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000804
805 with zipfile.ZipFile(TESTFN, "r") as zf:
806 self.assertEqual(zf.filelist[0].filename, "foo.txt")
807 self.assertEqual(zf.filelist[1].filename, u"\xf6.txt")
Martin v. Löwis471617d2008-05-05 17:16:58 +0000808
Ezio Melottid5a23e32009-07-15 17:07:04 +0000809 def test_create_non_existent_file_for_append(self):
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000810 if os.path.exists(TESTFN):
811 os.unlink(TESTFN)
Tim Petersea5962f2007-03-12 18:07:52 +0000812
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000813 filename = 'testfile.txt'
814 content = 'hello, world. this is some content.'
Tim Petersea5962f2007-03-12 18:07:52 +0000815
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000816 try:
Ezio Melotti569e61f2009-12-30 06:14:51 +0000817 with zipfile.ZipFile(TESTFN, 'a') as zf:
818 zf.writestr(filename, content)
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000819 except IOError:
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000820 self.fail('Could not append data to a non-existent zip file.')
821
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000822 self.assertTrue(os.path.exists(TESTFN))
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000823
Ezio Melotti569e61f2009-12-30 06:14:51 +0000824 with zipfile.ZipFile(TESTFN, 'r') as zf:
825 self.assertEqual(zf.read(filename), content)
Tim Petersea5962f2007-03-12 18:07:52 +0000826
Ezio Melottid5a23e32009-07-15 17:07:04 +0000827 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000828 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000829 # it opens if there's an error in the file. If it doesn't, the
830 # traceback holds a reference to the ZipFile object and, indirectly,
831 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000832 # On Windows, this causes the os.unlink() call to fail because the
833 # underlying file is still open. This is SF bug #412214.
834 #
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000835 with open(TESTFN, "w") as fp:
836 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000837 try:
838 zf = zipfile.ZipFile(TESTFN)
839 except zipfile.BadZipfile:
Collin Winter04a51ec2007-03-29 02:28:16 +0000840 pass
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000841
Ezio Melottid5a23e32009-07-15 17:07:04 +0000842 def test_is_zip_erroneous_file(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000843 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000844 # - passing a filename
845 with open(TESTFN, "w") as fp:
846 fp.write("this is not a legal zip file\n")
Tim Petersea5962f2007-03-12 18:07:52 +0000847 chk = zipfile.is_zipfile(TESTFN)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000848 self.assertFalse(chk)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000849 # - passing a file object
850 with open(TESTFN, "rb") as fp:
851 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000852 self.assertTrue(not chk)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000853 # - passing a file-like object
854 fp = StringIO()
855 fp.write("this is not a legal zip file\n")
856 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000857 self.assertTrue(not chk)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000858 fp.seek(0, 0)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000859 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000860 self.assertTrue(not chk)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000861
Serhiy Storchaka0be506a2013-01-31 15:26:55 +0200862 def test_damaged_zipfile(self):
863 """Check that zipfiles with missing bytes at the end raise BadZipFile."""
864 # - Create a valid zip file
865 fp = io.BytesIO()
866 with zipfile.ZipFile(fp, mode="w") as zipf:
867 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
868 zipfiledata = fp.getvalue()
869
870 # - Now create copies of it missing the last N bytes and make sure
871 # a BadZipFile exception is raised when we try to open it
872 for N in range(len(zipfiledata)):
873 fp = io.BytesIO(zipfiledata[:N])
874 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, fp)
875
Ezio Melottid5a23e32009-07-15 17:07:04 +0000876 def test_is_zip_valid_file(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000877 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000878 # - passing a filename
Ezio Melotti569e61f2009-12-30 06:14:51 +0000879 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
880 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Tim Petersea5962f2007-03-12 18:07:52 +0000881 chk = zipfile.is_zipfile(TESTFN)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000882 self.assertTrue(chk)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000883 # - passing a file object
884 with open(TESTFN, "rb") as fp:
885 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000886 self.assertTrue(chk)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000887 fp.seek(0, 0)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000888 zip_contents = fp.read()
889 # - passing a file-like object
890 fp = StringIO()
891 fp.write(zip_contents)
892 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000893 self.assertTrue(chk)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000894 fp.seek(0, 0)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000895 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000896 self.assertTrue(chk)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000897
Ezio Melottid5a23e32009-07-15 17:07:04 +0000898 def test_non_existent_file_raises_IOError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000899 # make sure we don't raise an AttributeError when a partially-constructed
900 # ZipFile instance is finalized; this tests for regression on SF tracker
901 # bug #403871.
902
903 # The bug we're testing for caused an AttributeError to be raised
904 # when a ZipFile instance was created for a file that did not
905 # exist; the .fp member was not initialized but was needed by the
906 # __del__() method. Since the AttributeError is in the __del__(),
907 # it is ignored, but the user should be sufficiently annoyed by
908 # the message on the output that regression will be noticed
909 # quickly.
910 self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
911
Amaury Forgeot d'Arc3e5b0272009-07-28 22:15:30 +0000912 def test_empty_file_raises_BadZipFile(self):
Brian Curtin0d654332011-04-19 21:15:55 -0500913 with open(TESTFN, 'w') as f:
914 pass
Amaury Forgeot d'Arc3e5b0272009-07-28 22:15:30 +0000915 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN)
916
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000917 with open(TESTFN, 'w') as fp:
918 fp.write("short file")
Amaury Forgeot d'Arc3e5b0272009-07-28 22:15:30 +0000919 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN)
920
Ezio Melottid5a23e32009-07-15 17:07:04 +0000921 def test_closed_zip_raises_RuntimeError(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000922 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000923 data = StringIO()
Ezio Melotti569e61f2009-12-30 06:14:51 +0000924 with zipfile.ZipFile(data, mode="w") as zipf:
925 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000926
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200927 # This is correct; calling .read on a closed ZipFile should raise
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000928 # a RuntimeError, and so should calling .testzip. An earlier
929 # version of .testzip would swallow this exception (and any other)
930 # and report that the first file in the archive was corrupt.
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000931 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
932 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000933 self.assertRaises(RuntimeError, zipf.testzip)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000934 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000935 open(TESTFN, 'w').write('zipfile test data')
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000936 self.assertRaises(RuntimeError, zipf.write, TESTFN)
937
Ezio Melottid5a23e32009-07-15 17:07:04 +0000938 def test_bad_constructor_mode(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000939 """Check that bad modes passed to ZipFile constructor are caught."""
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000940 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
941
Ezio Melottid5a23e32009-07-15 17:07:04 +0000942 def test_bad_open_mode(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000943 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000944 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
945 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
946
947 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000948 # read the data to make sure the file is there
Ezio Melotti569e61f2009-12-30 06:14:51 +0000949 zipf.read("foo.txt")
950 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000951
Ezio Melottid5a23e32009-07-15 17:07:04 +0000952 def test_read0(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000953 """Check that calling read(0) on a ZipExtFile object returns an empty
954 string and doesn't advance file pointer."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000955 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
956 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
957 # read the data to make sure the file is there
Brian Curtin0d654332011-04-19 21:15:55 -0500958 with zipf.open("foo.txt") as f:
959 for i in xrange(FIXEDTEST_SIZE):
960 self.assertEqual(f.read(0), '')
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000961
Brian Curtin0d654332011-04-19 21:15:55 -0500962 self.assertEqual(f.read(), "O, for a Muse of Fire!")
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000963
Ezio Melottid5a23e32009-07-15 17:07:04 +0000964 def test_open_non_existent_item(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000965 """Check that attempting to call open() for an item that doesn't
966 exist in the archive raises a RuntimeError."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000967 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
968 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000969
Ezio Melottid5a23e32009-07-15 17:07:04 +0000970 def test_bad_compression_mode(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000971 """Check that bad compression methods passed to ZipFile.open are
972 caught."""
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000973 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
974
Ezio Melotti9e949722012-11-18 13:18:06 +0200975 def test_unsupported_compression(self):
976 # data is declared as shrunk, but actually deflated
977 data = (b'PK\x03\x04.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00'
978 b'\x00\x02\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00x\x03\x00PK\x01'
979 b'\x02.\x03.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00\x00\x02\x00\x00'
980 b'\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
981 b'\x80\x01\x00\x00\x00\x00xPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00'
982 b'/\x00\x00\x00!\x00\x00\x00\x00\x00')
983 with zipfile.ZipFile(io.BytesIO(data), 'r') as zipf:
984 self.assertRaises(NotImplementedError, zipf.open, 'x')
985
Ezio Melottid5a23e32009-07-15 17:07:04 +0000986 def test_null_byte_in_filename(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000987 """Check that a filename containing a null byte is properly
988 terminated."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000989 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
990 zipf.writestr("foo.txt\x00qqq", "O, for a Muse of Fire!")
991 self.assertEqual(zipf.namelist(), ['foo.txt'])
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000992
Ezio Melottid5a23e32009-07-15 17:07:04 +0000993 def test_struct_sizes(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000994 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwis8c436412008-07-03 12:51:14 +0000995 self.assertEqual(zipfile.sizeEndCentDir, 22)
996 self.assertEqual(zipfile.sizeCentralDir, 46)
997 self.assertEqual(zipfile.sizeEndCentDir64, 56)
998 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
999
Ezio Melottid5a23e32009-07-15 17:07:04 +00001000 def test_comments(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001001 """Check that comments on the archive are handled properly."""
Martin v. Löwis8c436412008-07-03 12:51:14 +00001002
1003 # check default comment is empty
Ezio Melotti569e61f2009-12-30 06:14:51 +00001004 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1005 self.assertEqual(zipf.comment, '')
1006 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1007
1008 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
1009 self.assertEqual(zipf.comment, '')
Martin v. Löwis8c436412008-07-03 12:51:14 +00001010
1011 # check a simple short comment
1012 comment = 'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melotti569e61f2009-12-30 06:14:51 +00001013 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1014 zipf.comment = comment
1015 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1016 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
1017 self.assertEqual(zipf.comment, comment)
Martin v. Löwis8c436412008-07-03 12:51:14 +00001018
1019 # check a comment of max length
1020 comment2 = ''.join(['%d' % (i**3 % 10) for i in xrange((1 << 16)-1)])
Ezio Melotti569e61f2009-12-30 06:14:51 +00001021 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1022 zipf.comment = comment2
1023 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1024
1025 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
1026 self.assertEqual(zipf.comment, comment2)
Martin v. Löwis8c436412008-07-03 12:51:14 +00001027
1028 # check a comment that is too long is truncated
Ezio Melotti569e61f2009-12-30 06:14:51 +00001029 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1030 zipf.comment = comment2 + 'oops'
1031 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1032 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
1033 self.assertEqual(zipf.comment, comment2)
Martin v. Löwis8c436412008-07-03 12:51:14 +00001034
R David Murray3f4ccba2012-04-12 18:42:47 -04001035 def test_change_comment_in_empty_archive(self):
1036 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1037 self.assertFalse(zipf.filelist)
1038 zipf.comment = b"this is a comment"
1039 with zipfile.ZipFile(TESTFN, "r") as zipf:
1040 self.assertEqual(zipf.comment, b"this is a comment")
1041
1042 def test_change_comment_in_nonempty_archive(self):
1043 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1044 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1045 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1046 self.assertTrue(zipf.filelist)
1047 zipf.comment = b"this is a comment"
1048 with zipfile.ZipFile(TESTFN, "r") as zipf:
1049 self.assertEqual(zipf.comment, b"this is a comment")
1050
Antoine Pitroue1436d12010-08-12 15:25:51 +00001051 def check_testzip_with_bad_crc(self, compression):
1052 """Tests that files with bad CRCs return their name from testzip."""
1053 zipdata = self.zips_with_bad_crc[compression]
1054
1055 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1056 # testzip returns the name of the first corrupt file, or None
1057 self.assertEqual('afile', zipf.testzip())
1058
1059 def test_testzip_with_bad_crc_stored(self):
1060 self.check_testzip_with_bad_crc(zipfile.ZIP_STORED)
1061
1062 @skipUnless(zlib, "requires zlib")
1063 def test_testzip_with_bad_crc_deflated(self):
1064 self.check_testzip_with_bad_crc(zipfile.ZIP_DEFLATED)
1065
1066 def check_read_with_bad_crc(self, compression):
1067 """Tests that files with bad CRCs raise a BadZipfile exception when read."""
1068 zipdata = self.zips_with_bad_crc[compression]
1069
1070 # Using ZipFile.read()
1071 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1072 self.assertRaises(zipfile.BadZipfile, zipf.read, 'afile')
1073
1074 # Using ZipExtFile.read()
1075 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1076 with zipf.open('afile', 'r') as corrupt_file:
1077 self.assertRaises(zipfile.BadZipfile, corrupt_file.read)
1078
1079 # Same with small reads (in order to exercise the buffering logic)
1080 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1081 with zipf.open('afile', 'r') as corrupt_file:
1082 corrupt_file.MIN_READ_SIZE = 2
1083 with self.assertRaises(zipfile.BadZipfile):
1084 while corrupt_file.read(2):
1085 pass
1086
1087 def test_read_with_bad_crc_stored(self):
1088 self.check_read_with_bad_crc(zipfile.ZIP_STORED)
1089
1090 @skipUnless(zlib, "requires zlib")
1091 def test_read_with_bad_crc_deflated(self):
1092 self.check_read_with_bad_crc(zipfile.ZIP_DEFLATED)
1093
Antoine Pitroue4195e82010-09-12 14:56:27 +00001094 def check_read_return_size(self, compression):
1095 # Issue #9837: ZipExtFile.read() shouldn't return more bytes
1096 # than requested.
1097 for test_size in (1, 4095, 4096, 4097, 16384):
1098 file_size = test_size + 1
1099 junk = b''.join(struct.pack('B', randint(0, 255))
1100 for x in range(file_size))
1101 with zipfile.ZipFile(io.BytesIO(), "w", compression) as zipf:
1102 zipf.writestr('foo', junk)
1103 with zipf.open('foo', 'r') as fp:
1104 buf = fp.read(test_size)
1105 self.assertEqual(len(buf), test_size)
1106
1107 def test_read_return_size_stored(self):
1108 self.check_read_return_size(zipfile.ZIP_STORED)
1109
1110 @skipUnless(zlib, "requires zlib")
1111 def test_read_return_size_deflated(self):
1112 self.check_read_return_size(zipfile.ZIP_DEFLATED)
1113
Georg Brandl86e0c892010-11-26 07:22:28 +00001114 def test_empty_zipfile(self):
1115 # Check that creating a file in 'w' or 'a' mode and closing without
1116 # adding any files to the archives creates a valid empty ZIP file
Brian Curtin0d654332011-04-19 21:15:55 -05001117 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1118 pass
Georg Brandl86e0c892010-11-26 07:22:28 +00001119 try:
1120 zipf = zipfile.ZipFile(TESTFN, mode="r")
Éric Araujo67843b32011-02-02 17:03:38 +00001121 except zipfile.BadZipfile:
Georg Brandl86e0c892010-11-26 07:22:28 +00001122 self.fail("Unable to create empty ZIP file in 'w' mode")
1123
Brian Curtin0d654332011-04-19 21:15:55 -05001124 with zipfile.ZipFile(TESTFN, mode="a") as zipf:
1125 pass
Georg Brandl86e0c892010-11-26 07:22:28 +00001126 try:
1127 zipf = zipfile.ZipFile(TESTFN, mode="r")
1128 except:
1129 self.fail("Unable to create empty ZIP file in 'a' mode")
1130
1131 def test_open_empty_file(self):
1132 # Issue 1710703: Check that opening a file with less than 22 bytes
1133 # raises a BadZipfile exception (rather than the previously unhelpful
1134 # IOError)
Brian Curtin0d654332011-04-19 21:15:55 -05001135 with open(TESTFN, 'w') as f:
1136 pass
Georg Brandl86e0c892010-11-26 07:22:28 +00001137 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN, 'r')
1138
Senthil Kumaranddd40312011-10-20 01:38:35 +08001139 def test_create_zipinfo_before_1980(self):
1140 self.assertRaises(ValueError,
1141 zipfile.ZipInfo, 'seventies', (1979, 1, 1, 0, 0, 0))
1142
Collin Winter04a51ec2007-03-29 02:28:16 +00001143 def tearDown(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001144 unlink(TESTFN)
1145 unlink(TESTFN2)
1146
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001147
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001148class DecryptionTests(unittest.TestCase):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001149 """Check that ZIP decryption works. Since the library does not
1150 support encryption at the moment, we use a pre-generated encrypted
1151 ZIP file."""
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001152
1153 data = (
1154 'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
1155 '\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
1156 '\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
1157 'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
1158 '\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
1159 '\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
1160 '\x00\x00L\x00\x00\x00\x00\x00' )
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001161 data2 = (
1162 'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
1163 '\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
1164 '\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
1165 'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
1166 '\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
1167 '\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
1168 'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
1169 '\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001170
1171 plain = 'zipfile.py encryption test'
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001172 plain2 = '\x00'*512
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001173
1174 def setUp(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001175 with open(TESTFN, "wb") as fp:
1176 fp.write(self.data)
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001177 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001178 with open(TESTFN2, "wb") as fp:
1179 fp.write(self.data2)
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001180 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001181
1182 def tearDown(self):
1183 self.zip.close()
1184 os.unlink(TESTFN)
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001185 self.zip2.close()
1186 os.unlink(TESTFN2)
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001187
Ezio Melottid5a23e32009-07-15 17:07:04 +00001188 def test_no_password(self):
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001189 # Reading the encrypted file without password
1190 # must generate a RunTime exception
1191 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001192 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001193
Ezio Melottid5a23e32009-07-15 17:07:04 +00001194 def test_bad_password(self):
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001195 self.zip.setpassword("perl")
1196 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001197 self.zip2.setpassword("perl")
1198 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Tim Petersea5962f2007-03-12 18:07:52 +00001199
Ezio Melotti1036a7f2009-09-12 14:43:43 +00001200 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +00001201 def test_good_password(self):
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001202 self.zip.setpassword("python")
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001203 self.assertEqual(self.zip.read("test.txt"), self.plain)
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001204 self.zip2.setpassword("12345")
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001205 self.assertEqual(self.zip2.read("zero"), self.plain2)
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001206
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001207
1208class TestsWithRandomBinaryFiles(unittest.TestCase):
1209 def setUp(self):
1210 datacount = randint(16, 64)*1024 + randint(1, 1024)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001211 self.data = ''.join(struct.pack('<f', random()*randint(-1000, 1000))
Ezio Melotti763f1e82009-12-31 13:27:41 +00001212 for i in xrange(datacount))
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001213
1214 # Make a source file with some lines
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001215 with open(TESTFN, "wb") as fp:
1216 fp.write(self.data)
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00001217
Collin Winter04a51ec2007-03-29 02:28:16 +00001218 def tearDown(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001219 unlink(TESTFN)
1220 unlink(TESTFN2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001221
Ezio Melottid5a23e32009-07-15 17:07:04 +00001222 def make_test_archive(self, f, compression):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001223 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001224 with zipfile.ZipFile(f, "w", compression) as zipfp:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001225 zipfp.write(TESTFN, "another.name")
Ezio Melotti569e61f2009-12-30 06:14:51 +00001226 zipfp.write(TESTFN, TESTFN)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001227
Ezio Melottid5a23e32009-07-15 17:07:04 +00001228 def zip_test(self, f, compression):
1229 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001230
1231 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001232 with zipfile.ZipFile(f, "r", compression) as zipfp:
1233 testdata = zipfp.read(TESTFN)
1234 self.assertEqual(len(testdata), len(self.data))
1235 self.assertEqual(testdata, self.data)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001236 self.assertEqual(zipfp.read("another.name"), self.data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001237
Ezio Melottid5a23e32009-07-15 17:07:04 +00001238 def test_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001239 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001240 self.zip_test(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +00001241
Antoine Pitroue1436d12010-08-12 15:25:51 +00001242 @skipUnless(zlib, "requires zlib")
1243 def test_deflated(self):
1244 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1245 self.zip_test(f, zipfile.ZIP_DEFLATED)
1246
Ezio Melottid5a23e32009-07-15 17:07:04 +00001247 def zip_open_test(self, f, compression):
1248 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001249
1250 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001251 with zipfile.ZipFile(f, "r", compression) as zipfp:
1252 zipdata1 = []
Brian Curtin0d654332011-04-19 21:15:55 -05001253 with zipfp.open(TESTFN) as zipopen1:
1254 while True:
1255 read_data = zipopen1.read(256)
1256 if not read_data:
1257 break
1258 zipdata1.append(read_data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001259
Ezio Melotti569e61f2009-12-30 06:14:51 +00001260 zipdata2 = []
Brian Curtin0d654332011-04-19 21:15:55 -05001261 with zipfp.open("another.name") as zipopen2:
1262 while True:
1263 read_data = zipopen2.read(256)
1264 if not read_data:
1265 break
1266 zipdata2.append(read_data)
Tim Petersea5962f2007-03-12 18:07:52 +00001267
Ezio Melotti569e61f2009-12-30 06:14:51 +00001268 testdata1 = ''.join(zipdata1)
1269 self.assertEqual(len(testdata1), len(self.data))
1270 self.assertEqual(testdata1, self.data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001271
Ezio Melotti569e61f2009-12-30 06:14:51 +00001272 testdata2 = ''.join(zipdata2)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001273 self.assertEqual(len(testdata2), len(self.data))
1274 self.assertEqual(testdata2, self.data)
Tim Petersea5962f2007-03-12 18:07:52 +00001275
Ezio Melottid5a23e32009-07-15 17:07:04 +00001276 def test_open_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001277 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001278 self.zip_open_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001279
Antoine Pitroue1436d12010-08-12 15:25:51 +00001280 @skipUnless(zlib, "requires zlib")
1281 def test_open_deflated(self):
1282 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1283 self.zip_open_test(f, zipfile.ZIP_DEFLATED)
1284
Ezio Melottid5a23e32009-07-15 17:07:04 +00001285 def zip_random_open_test(self, f, compression):
1286 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001287
1288 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001289 with zipfile.ZipFile(f, "r", compression) as zipfp:
1290 zipdata1 = []
Brian Curtin0d654332011-04-19 21:15:55 -05001291 with zipfp.open(TESTFN) as zipopen1:
1292 while True:
1293 read_data = zipopen1.read(randint(1, 1024))
1294 if not read_data:
1295 break
1296 zipdata1.append(read_data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001297
Ezio Melotti569e61f2009-12-30 06:14:51 +00001298 testdata = ''.join(zipdata1)
1299 self.assertEqual(len(testdata), len(self.data))
1300 self.assertEqual(testdata, self.data)
Tim Petersea5962f2007-03-12 18:07:52 +00001301
Ezio Melottid5a23e32009-07-15 17:07:04 +00001302 def test_random_open_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001303 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001304 self.zip_random_open_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001305
Antoine Pitroue1436d12010-08-12 15:25:51 +00001306 @skipUnless(zlib, "requires zlib")
1307 def test_random_open_deflated(self):
1308 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1309 self.zip_random_open_test(f, zipfile.ZIP_DEFLATED)
1310
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001311
Ezio Melotti1036a7f2009-09-12 14:43:43 +00001312@skipUnless(zlib, "requires zlib")
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001313class TestsWithMultipleOpens(unittest.TestCase):
1314 def setUp(self):
1315 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001316 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
1317 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
1318 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
Tim Petersea5962f2007-03-12 18:07:52 +00001319
Ezio Melottid5a23e32009-07-15 17:07:04 +00001320 def test_same_file(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001321 # Verify that (when the ZipFile is in control of creating file objects)
1322 # multiple open() calls can be made without interfering with each other.
Ezio Melotti569e61f2009-12-30 06:14:51 +00001323 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
1324 zopen1 = zipf.open('ones')
1325 zopen2 = zipf.open('ones')
1326 data1 = zopen1.read(500)
1327 data2 = zopen2.read(500)
1328 data1 += zopen1.read(500)
1329 data2 += zopen2.read(500)
1330 self.assertEqual(data1, data2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001331
Ezio Melottid5a23e32009-07-15 17:07:04 +00001332 def test_different_file(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001333 # Verify that (when the ZipFile is in control of creating file objects)
1334 # multiple open() calls can be made without interfering with each other.
Ezio Melotti569e61f2009-12-30 06:14:51 +00001335 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin0d654332011-04-19 21:15:55 -05001336 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1337 data1 = zopen1.read(500)
1338 data2 = zopen2.read(500)
1339 data1 += zopen1.read(500)
1340 data2 += zopen2.read(500)
Ezio Melotti569e61f2009-12-30 06:14:51 +00001341 self.assertEqual(data1, '1'*FIXEDTEST_SIZE)
1342 self.assertEqual(data2, '2'*FIXEDTEST_SIZE)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001343
Ezio Melottid5a23e32009-07-15 17:07:04 +00001344 def test_interleaved(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001345 # Verify that (when the ZipFile is in control of creating file objects)
1346 # multiple open() calls can be made without interfering with each other.
Ezio Melotti569e61f2009-12-30 06:14:51 +00001347 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin0d654332011-04-19 21:15:55 -05001348 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1349 data1 = zopen1.read(500)
1350 data2 = zopen2.read(500)
1351 data1 += zopen1.read(500)
1352 data2 += zopen2.read(500)
Ezio Melotti569e61f2009-12-30 06:14:51 +00001353 self.assertEqual(data1, '1'*FIXEDTEST_SIZE)
1354 self.assertEqual(data2, '2'*FIXEDTEST_SIZE)
Tim Petersea5962f2007-03-12 18:07:52 +00001355
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001356 def tearDown(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001357 unlink(TESTFN2)
1358
Tim Petersea5962f2007-03-12 18:07:52 +00001359
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001360class TestWithDirectory(unittest.TestCase):
1361 def setUp(self):
1362 os.mkdir(TESTFN2)
1363
Ezio Melottid5a23e32009-07-15 17:07:04 +00001364 def test_extract_dir(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +00001365 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
1366 zipf.extractall(TESTFN2)
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001367 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1368 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1369 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1370
Ezio Melottid5a23e32009-07-15 17:07:04 +00001371 def test_bug_6050(self):
Martin v. Löwis0b09c422009-05-24 19:30:52 +00001372 # Extraction should succeed if directories already exist
1373 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottid5a23e32009-07-15 17:07:04 +00001374 self.test_extract_dir()
Martin v. Löwis0b09c422009-05-24 19:30:52 +00001375
Ezio Melottid5a23e32009-07-15 17:07:04 +00001376 def test_store_dir(self):
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001377 os.mkdir(os.path.join(TESTFN2, "x"))
1378 zipf = zipfile.ZipFile(TESTFN, "w")
1379 zipf.write(os.path.join(TESTFN2, "x"), "x")
1380 self.assertTrue(zipf.filelist[0].filename.endswith("x/"))
1381
1382 def tearDown(self):
1383 shutil.rmtree(TESTFN2)
1384 if os.path.exists(TESTFN):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001385 unlink(TESTFN)
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001386
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001387
1388class UniversalNewlineTests(unittest.TestCase):
1389 def setUp(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001390 self.line_gen = ["Test of zipfile line %d." % i
1391 for i in xrange(FIXEDTEST_SIZE)]
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001392 self.seps = ('\r', '\r\n', '\n')
1393 self.arcdata, self.arcfiles = {}, {}
1394 for n, s in enumerate(self.seps):
1395 self.arcdata[s] = s.join(self.line_gen) + s
1396 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Brett Cannon6cef0762007-05-25 20:17:15 +00001397 open(self.arcfiles[s], "wb").write(self.arcdata[s])
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001398
Ezio Melottid5a23e32009-07-15 17:07:04 +00001399 def make_test_archive(self, f, compression):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001400 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001401 with zipfile.ZipFile(f, "w", compression) as zipfp:
1402 for fn in self.arcfiles.values():
1403 zipfp.write(fn, fn)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001404
Ezio Melottid5a23e32009-07-15 17:07:04 +00001405 def read_test(self, f, compression):
1406 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001407
1408 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001409 with zipfile.ZipFile(f, "r") as zipfp:
1410 for sep, fn in self.arcfiles.items():
Brian Curtin0d654332011-04-19 21:15:55 -05001411 with zipfp.open(fn, "rU") as fp:
1412 zipdata = fp.read()
Ezio Melotti569e61f2009-12-30 06:14:51 +00001413 self.assertEqual(self.arcdata[sep], zipdata)
Tim Petersea5962f2007-03-12 18:07:52 +00001414
Antoine Pitrou94c33eb2010-01-27 20:59:50 +00001415 def readline_read_test(self, f, compression):
1416 self.make_test_archive(f, compression)
1417
1418 # Read the ZIP archive
1419 zipfp = zipfile.ZipFile(f, "r")
1420 for sep, fn in self.arcfiles.items():
Brian Curtin0d654332011-04-19 21:15:55 -05001421 with zipfp.open(fn, "rU") as zipopen:
1422 data = ''
1423 while True:
1424 read = zipopen.readline()
1425 if not read:
1426 break
1427 data += read
Antoine Pitrou94c33eb2010-01-27 20:59:50 +00001428
Brian Curtin0d654332011-04-19 21:15:55 -05001429 read = zipopen.read(5)
1430 if not read:
1431 break
1432 data += read
Antoine Pitrou94c33eb2010-01-27 20:59:50 +00001433
1434 self.assertEqual(data, self.arcdata['\n'])
1435
1436 zipfp.close()
1437
Ezio Melottid5a23e32009-07-15 17:07:04 +00001438 def readline_test(self, f, compression):
1439 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001440
1441 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001442 with zipfile.ZipFile(f, "r") as zipfp:
1443 for sep, fn in self.arcfiles.items():
Brian Curtin0d654332011-04-19 21:15:55 -05001444 with zipfp.open(fn, "rU") as zipopen:
1445 for line in self.line_gen:
1446 linedata = zipopen.readline()
1447 self.assertEqual(linedata, line + '\n')
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001448
Ezio Melottid5a23e32009-07-15 17:07:04 +00001449 def readlines_test(self, f, compression):
1450 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001451
1452 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001453 with zipfile.ZipFile(f, "r") as zipfp:
1454 for sep, fn in self.arcfiles.items():
Brian Curtin0d654332011-04-19 21:15:55 -05001455 with zipfp.open(fn, "rU") as fp:
1456 ziplines = fp.readlines()
Ezio Melotti569e61f2009-12-30 06:14:51 +00001457 for line, zipline in zip(self.line_gen, ziplines):
1458 self.assertEqual(zipline, line + '\n')
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001459
Ezio Melottid5a23e32009-07-15 17:07:04 +00001460 def iterlines_test(self, f, compression):
1461 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001462
1463 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001464 with zipfile.ZipFile(f, "r") as zipfp:
1465 for sep, fn in self.arcfiles.items():
1466 for line, zipline in zip(self.line_gen, zipfp.open(fn, "rU")):
1467 self.assertEqual(zipline, line + '\n')
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001468
Ezio Melottid5a23e32009-07-15 17:07:04 +00001469 def test_read_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001470 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001471 self.read_test(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +00001472
Antoine Pitrou94c33eb2010-01-27 20:59:50 +00001473 def test_readline_read_stored(self):
1474 # Issue #7610: calls to readline() interleaved with calls to read().
1475 for f in (TESTFN2, TemporaryFile(), StringIO()):
1476 self.readline_read_test(f, zipfile.ZIP_STORED)
1477
Ezio Melottid5a23e32009-07-15 17:07:04 +00001478 def test_readline_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001479 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001480 self.readline_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001481
Ezio Melottid5a23e32009-07-15 17:07:04 +00001482 def test_readlines_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001483 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001484 self.readlines_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001485
Ezio Melottid5a23e32009-07-15 17:07:04 +00001486 def test_iterlines_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001487 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001488 self.iterlines_test(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +00001489
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001490 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +00001491 def test_read_deflated(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001492 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001493 self.read_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001494
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001495 @skipUnless(zlib, "requires zlib")
Antoine Pitrou94c33eb2010-01-27 20:59:50 +00001496 def test_readline_read_deflated(self):
1497 # Issue #7610: calls to readline() interleaved with calls to read().
1498 for f in (TESTFN2, TemporaryFile(), StringIO()):
1499 self.readline_read_test(f, zipfile.ZIP_DEFLATED)
1500
1501 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +00001502 def test_readline_deflated(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001503 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001504 self.readline_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001505
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001506 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +00001507 def test_readlines_deflated(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001508 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001509 self.readlines_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001510
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001511 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +00001512 def test_iterlines_deflated(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001513 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001514 self.iterlines_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001515
1516 def tearDown(self):
1517 for sep, fn in self.arcfiles.items():
1518 os.remove(fn)
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001519 unlink(TESTFN)
1520 unlink(TESTFN2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001521
1522
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001523def test_main():
Tim Petersea5962f2007-03-12 18:07:52 +00001524 run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
1525 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001526 TestWithDirectory, UniversalNewlineTests,
1527 TestsWithRandomBinaryFiles)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001528
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001529if __name__ == "__main__":
1530 test_main()