blob: 16acabcf057fd82d0e6ed9fec1daf4ab0d3d907e [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
8import sys
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00009import time
Ezio Melottie7a0cc22009-07-04 14:58:27 +000010import shutil
11import 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
Ezio Melotti6cbfc122009-07-10 20:25:56 +000020from test.test_support import TESTFN, run_unittest, findfile, unlink
Guido van Rossum368f04a2000-04-10 13:23:04 +000021
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000022TESTFN2 = TESTFN + "2"
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +000023TESTFNDIR = TESTFN + "d"
Georg Brandl4b3ab6f2007-07-12 09:59:22 +000024FIXEDTEST_SIZE = 1000
Guido van Rossum368f04a2000-04-10 13:23:04 +000025
Georg Brandl62416bc2008-01-07 18:47:44 +000026SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'),
27 ('ziptest2dir/_ziptest2', 'qawsedrftg'),
28 ('/ziptest2dir/ziptest3dir/_ziptest3', 'azsxdcfvgb'),
29 ('ziptest2dir/ziptest3dir/ziptest4dir/_ziptest3', '6y7u8i9o0p')]
30
Ezio Melotti6cbfc122009-07-10 20:25:56 +000031
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000032class TestsWithSourceFile(unittest.TestCase):
33 def setUp(self):
Georg Brandl4b3ab6f2007-07-12 09:59:22 +000034 self.line_gen = ["Zipfile test line %d. random float: %f" % (i, random())
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000035 for i in xrange(FIXEDTEST_SIZE)]
Martin v. Löwis3eb76482007-03-06 10:41:24 +000036 self.data = '\n'.join(self.line_gen) + '\n'
Fred Drake6e7e4852001-02-28 05:34:16 +000037
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000038 # Make a source file with some lines
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000039 with open(TESTFN, "wb") as fp:
40 fp.write(self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000041
Ezio Melottid5a23e32009-07-15 17:07:04 +000042 def make_test_archive(self, f, compression):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000043 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +000044 with zipfile.ZipFile(f, "w", compression) as zipfp:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000045 zipfp.write(TESTFN, "another.name")
Ezio Melotti569e61f2009-12-30 06:14:51 +000046 zipfp.write(TESTFN, TESTFN)
47 zipfp.writestr("strfile", self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000048
Ezio Melottid5a23e32009-07-15 17:07:04 +000049 def zip_test(self, f, compression):
50 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +000051
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000052 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +000053 with zipfile.ZipFile(f, "r", compression) as zipfp:
54 self.assertEqual(zipfp.read(TESTFN), self.data)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000055 self.assertEqual(zipfp.read("another.name"), self.data)
Ezio Melotti569e61f2009-12-30 06:14:51 +000056 self.assertEqual(zipfp.read("strfile"), self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +000057
Ezio Melotti569e61f2009-12-30 06:14:51 +000058 # Print the ZIP directory
59 fp = StringIO()
60 stdout = sys.stdout
61 try:
62 sys.stdout = fp
63 zipfp.printdir()
64 finally:
65 sys.stdout = stdout
Tim Petersa608bb22006-06-15 18:06:29 +000066
Ezio Melotti569e61f2009-12-30 06:14:51 +000067 directory = fp.getvalue()
68 lines = directory.splitlines()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000069 self.assertEqual(len(lines), 4) # Number of files + header
Ronald Oussoren143cefb2006-06-15 08:14:18 +000070
Ezio Melottiaa980582010-01-23 23:04:36 +000071 self.assertIn('File Name', lines[0])
72 self.assertIn('Modified', lines[0])
73 self.assertIn('Size', lines[0])
Ronald Oussoren143cefb2006-06-15 08:14:18 +000074
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000075 fn, date, time_, size = lines[1].split()
76 self.assertEqual(fn, 'another.name')
77 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
78 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
79 self.assertEqual(size, str(len(self.data)))
Ronald Oussoren143cefb2006-06-15 08:14:18 +000080
Ezio Melotti569e61f2009-12-30 06:14:51 +000081 # Check the namelist
82 names = zipfp.namelist()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000083 self.assertEqual(len(names), 3)
Ezio Melottiaa980582010-01-23 23:04:36 +000084 self.assertIn(TESTFN, names)
85 self.assertIn("another.name", names)
86 self.assertIn("strfile", names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +000087
Ezio Melotti569e61f2009-12-30 06:14:51 +000088 # Check infolist
89 infos = zipfp.infolist()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000090 names = [i.filename for i in infos]
91 self.assertEqual(len(names), 3)
Ezio Melottiaa980582010-01-23 23:04:36 +000092 self.assertIn(TESTFN, names)
93 self.assertIn("another.name", names)
94 self.assertIn("strfile", names)
Ezio Melotti569e61f2009-12-30 06:14:51 +000095 for i in infos:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000096 self.assertEqual(i.file_size, len(self.data))
Ronald Oussoren143cefb2006-06-15 08:14:18 +000097
Ezio Melotti569e61f2009-12-30 06:14:51 +000098 # check getinfo
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000099 for nm in (TESTFN, "another.name", "strfile"):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000100 info = zipfp.getinfo(nm)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000101 self.assertEqual(info.filename, nm)
102 self.assertEqual(info.file_size, len(self.data))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000103
Ezio Melotti569e61f2009-12-30 06:14:51 +0000104 # Check that testzip doesn't raise an exception
105 zipfp.testzip()
Tim Peters7d3bad62001-04-04 18:56:49 +0000106
Ezio Melottid5a23e32009-07-15 17:07:04 +0000107 def test_stored(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000108 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000109 self.zip_test(f, zipfile.ZIP_STORED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000110
Ezio Melottid5a23e32009-07-15 17:07:04 +0000111 def zip_open_test(self, f, compression):
112 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000113
114 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000115 with zipfile.ZipFile(f, "r", compression) as zipfp:
116 zipdata1 = []
117 zipopen1 = zipfp.open(TESTFN)
118 while True:
119 read_data = zipopen1.read(256)
120 if not read_data:
121 break
122 zipdata1.append(read_data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000123
Ezio Melotti569e61f2009-12-30 06:14:51 +0000124 zipdata2 = []
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000125 zipopen2 = zipfp.open("another.name")
Ezio Melotti569e61f2009-12-30 06:14:51 +0000126 while True:
127 read_data = zipopen2.read(256)
128 if not read_data:
129 break
130 zipdata2.append(read_data)
Tim Petersea5962f2007-03-12 18:07:52 +0000131
Ezio Melotti569e61f2009-12-30 06:14:51 +0000132 self.assertEqual(''.join(zipdata1), self.data)
133 self.assertEqual(''.join(zipdata2), self.data)
Tim Petersea5962f2007-03-12 18:07:52 +0000134
Ezio Melottid5a23e32009-07-15 17:07:04 +0000135 def test_open_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000136 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000137 self.zip_open_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000138
Ezio Melottid5a23e32009-07-15 17:07:04 +0000139 def test_open_via_zip_info(self):
Georg Brandl112aa502008-05-20 08:25:48 +0000140 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000141 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
142 zipfp.writestr("name", "foo")
143 zipfp.writestr("name", "bar")
Georg Brandl112aa502008-05-20 08:25:48 +0000144
Ezio Melotti569e61f2009-12-30 06:14:51 +0000145 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
146 infos = zipfp.infolist()
147 data = ""
148 for info in infos:
149 data += zipfp.open(info).read()
150 self.assertTrue(data == "foobar" or data == "barfoo")
151 data = ""
152 for info in infos:
153 data += zipfp.read(info)
154 self.assertTrue(data == "foobar" or data == "barfoo")
Georg Brandl112aa502008-05-20 08:25:48 +0000155
Ezio Melottid5a23e32009-07-15 17:07:04 +0000156 def zip_random_open_test(self, f, compression):
157 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000158
159 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000160 with zipfile.ZipFile(f, "r", compression) as zipfp:
161 zipdata1 = []
162 zipopen1 = zipfp.open(TESTFN)
163 while True:
164 read_data = zipopen1.read(randint(1, 1024))
165 if not read_data:
166 break
167 zipdata1.append(read_data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000168
Ezio Melotti569e61f2009-12-30 06:14:51 +0000169 self.assertEqual(''.join(zipdata1), self.data)
Tim Petersea5962f2007-03-12 18:07:52 +0000170
Ezio Melottid5a23e32009-07-15 17:07:04 +0000171 def test_random_open_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000172 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000173 self.zip_random_open_test(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +0000174
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000175 def test_univeral_readaheads(self):
176 f = StringIO()
177
178 data = 'a\r\n' * 16 * 1024
179 zipfp = zipfile.ZipFile(f, 'w', zipfile.ZIP_STORED)
180 zipfp.writestr(TESTFN, data)
181 zipfp.close()
182
183 data2 = ''
184 zipfp = zipfile.ZipFile(f, 'r')
185 zipopen = zipfp.open(TESTFN, 'rU')
186 for line in zipopen:
187 data2 += line
188 zipfp.close()
189
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
196 zipfp = zipfile.ZipFile(f, "r")
197 zipopen = zipfp.open(TESTFN)
198
199 data = ''
200 while True:
201 read = zipopen.readline()
202 if not read:
203 break
204 data += read
205
206 read = zipopen.read(100)
207 if not read:
208 break
209 data += read
210
211 self.assertEqual(data, self.data)
212 zipfp.close()
213
Ezio Melottid5a23e32009-07-15 17:07:04 +0000214 def zip_readline_test(self, f, compression):
215 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000216
217 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000218 with zipfile.ZipFile(f, "r") as zipfp:
219 zipopen = zipfp.open(TESTFN)
220 for line in self.line_gen:
221 linedata = zipopen.readline()
222 self.assertEqual(linedata, line + '\n')
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000223
Ezio Melottid5a23e32009-07-15 17:07:04 +0000224 def zip_readlines_test(self, f, compression):
225 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000226
227 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000228 with zipfile.ZipFile(f, "r") as zipfp:
229 ziplines = zipfp.open(TESTFN).readlines()
230 for line, zipline in zip(self.line_gen, ziplines):
231 self.assertEqual(zipline, line + '\n')
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000232
Ezio Melottid5a23e32009-07-15 17:07:04 +0000233 def zip_iterlines_test(self, f, compression):
234 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000235
236 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000237 with zipfile.ZipFile(f, "r") as zipfp:
238 for line, zipline in zip(self.line_gen, zipfp.open(TESTFN)):
239 self.assertEqual(zipline, line + '\n')
Tim Petersea5962f2007-03-12 18:07:52 +0000240
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000241 def test_readline_read_stored(self):
242 # Issue #7610: calls to readline() interleaved with calls to read().
243 for f in (TESTFN2, TemporaryFile(), StringIO()):
244 self.zip_readline_read_test(f, zipfile.ZIP_STORED)
245
Ezio Melottid5a23e32009-07-15 17:07:04 +0000246 def test_readline_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000247 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000248 self.zip_readline_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000249
Ezio Melottid5a23e32009-07-15 17:07:04 +0000250 def test_readlines_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000251 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000252 self.zip_readlines_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000253
Ezio Melottid5a23e32009-07-15 17:07:04 +0000254 def test_iterlines_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000255 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000256 self.zip_iterlines_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000257
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000258 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000259 def test_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000260 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000261 self.zip_test(f, zipfile.ZIP_DEFLATED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000262
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000263 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000264 def test_open_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000265 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000266 self.zip_open_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000267
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000268 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000269 def test_random_open_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000270 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000271 self.zip_random_open_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000272
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000273 @skipUnless(zlib, "requires zlib")
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000274 def test_readline_read_deflated(self):
275 # Issue #7610: calls to readline() interleaved with calls to read().
276 for f in (TESTFN2, TemporaryFile(), StringIO()):
277 self.zip_readline_read_test(f, zipfile.ZIP_DEFLATED)
278
279 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000280 def test_readline_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000281 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000282 self.zip_readline_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000283
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000284 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000285 def test_readlines_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000286 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000287 self.zip_readlines_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000288
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000289 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000290 def test_iterlines_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000291 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000292 self.zip_iterlines_test(f, zipfile.ZIP_DEFLATED)
Tim Petersea5962f2007-03-12 18:07:52 +0000293
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000294 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000295 def test_low_compression(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000296 """Check for cases where compressed data is larger than original."""
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000297 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000298 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
299 zipfp.writestr("strfile", '12')
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000300
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000301 # Get an open object for strfile
Ezio Melotti569e61f2009-12-30 06:14:51 +0000302 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_DEFLATED) as zipfp:
303 openobj = zipfp.open("strfile")
304 self.assertEqual(openobj.read(1), '1')
305 self.assertEqual(openobj.read(1), '2')
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000306
Ezio Melottid5a23e32009-07-15 17:07:04 +0000307 def test_absolute_arcnames(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000308 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
309 zipfp.write(TESTFN, "/absolute")
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000310
Ezio Melotti569e61f2009-12-30 06:14:51 +0000311 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
312 self.assertEqual(zipfp.namelist(), ["absolute"])
Tim Peters32cbc962006-02-20 21:42:18 +0000313
Ezio Melottid5a23e32009-07-15 17:07:04 +0000314 def test_append_to_zip_file(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000315 """Test appending to an existing zipfile."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000316 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
317 zipfp.write(TESTFN, TESTFN)
318
319 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
320 zipfp.writestr("strfile", self.data)
321 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000322
Ezio Melottid5a23e32009-07-15 17:07:04 +0000323 def test_append_to_non_zip_file(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000324 """Test appending to an existing file that is not a zipfile."""
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000325 # NOTE: this test fails if len(d) < 22 because of the first
326 # line "fpin.seek(-22, 2)" in _EndRecData
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000327 data = 'I am not a ZipFile!'*10
328 with open(TESTFN2, 'wb') as f:
329 f.write(data)
330
Ezio Melotti569e61f2009-12-30 06:14:51 +0000331 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
332 zipfp.write(TESTFN, TESTFN)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000333
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000334 with open(TESTFN2, 'rb') as f:
335 f.seek(len(data))
336 with zipfile.ZipFile(f, "r") as zipfp:
337 self.assertEqual(zipfp.namelist(), [TESTFN])
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000338
Ezio Melottid5a23e32009-07-15 17:07:04 +0000339 def test_write_default_name(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000340 """Check that calling ZipFile.write without arcname specified
341 produces the expected result."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000342 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
343 zipfp.write(TESTFN)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000344 self.assertEqual(zipfp.read(TESTFN), open(TESTFN).read())
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000345
Ezio Melotti1036a7f2009-09-12 14:43:43 +0000346 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000347 def test_per_file_compression(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000348 """Check that files within a Zip archive can have different
349 compression options."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000350 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
351 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
352 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
353 sinfo = zipfp.getinfo('storeme')
354 dinfo = zipfp.getinfo('deflateme')
355 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
356 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000357
Ezio Melottid5a23e32009-07-15 17:07:04 +0000358 def test_write_to_readonly(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000359 """Check that trying to call write() on a readonly ZipFile object
360 raises a RuntimeError."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000361 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
362 zipfp.writestr("somefile.txt", "bogus")
363
364 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
365 self.assertRaises(RuntimeError, zipfp.write, TESTFN)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000366
Ezio Melottid5a23e32009-07-15 17:07:04 +0000367 def test_extract(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000368 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
369 for fpath, fdata in SMALL_TEST_DATA:
370 zipfp.writestr(fpath, fdata)
Georg Brandl62416bc2008-01-07 18:47:44 +0000371
Ezio Melotti569e61f2009-12-30 06:14:51 +0000372 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
373 for fpath, fdata in SMALL_TEST_DATA:
374 writtenfile = zipfp.extract(fpath)
Georg Brandl62416bc2008-01-07 18:47:44 +0000375
Ezio Melotti569e61f2009-12-30 06:14:51 +0000376 # make sure it was written to the right place
377 if os.path.isabs(fpath):
378 correctfile = os.path.join(os.getcwd(), fpath[1:])
379 else:
380 correctfile = os.path.join(os.getcwd(), fpath)
381 correctfile = os.path.normpath(correctfile)
Georg Brandl62416bc2008-01-07 18:47:44 +0000382
Ezio Melotti569e61f2009-12-30 06:14:51 +0000383 self.assertEqual(writtenfile, correctfile)
Georg Brandl62416bc2008-01-07 18:47:44 +0000384
Ezio Melotti569e61f2009-12-30 06:14:51 +0000385 # make sure correct data is in correct file
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000386 self.assertEqual(fdata, open(writtenfile, "rb").read())
Ezio Melotti569e61f2009-12-30 06:14:51 +0000387 os.remove(writtenfile)
Georg Brandl62416bc2008-01-07 18:47:44 +0000388
389 # remove the test file subdirectories
390 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
391
Ezio Melottid5a23e32009-07-15 17:07:04 +0000392 def test_extract_all(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000393 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
394 for fpath, fdata in SMALL_TEST_DATA:
395 zipfp.writestr(fpath, fdata)
Georg Brandl62416bc2008-01-07 18:47:44 +0000396
Ezio Melotti569e61f2009-12-30 06:14:51 +0000397 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
398 zipfp.extractall()
399 for fpath, fdata in SMALL_TEST_DATA:
400 if os.path.isabs(fpath):
401 outfile = os.path.join(os.getcwd(), fpath[1:])
402 else:
403 outfile = os.path.join(os.getcwd(), fpath)
Georg Brandl62416bc2008-01-07 18:47:44 +0000404
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000405 self.assertEqual(fdata, open(outfile, "rb").read())
Ezio Melotti569e61f2009-12-30 06:14:51 +0000406 os.remove(outfile)
Georg Brandl62416bc2008-01-07 18:47:44 +0000407
408 # remove the test file subdirectories
409 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
410
Ronald Oussorendd25e862010-02-07 20:18:02 +0000411 def test_writestr_compression(self):
412 zipfp = zipfile.ZipFile(TESTFN2, "w")
413 zipfp.writestr("a.txt", "hello world", compress_type=zipfile.ZIP_STORED)
414 if zlib:
415 zipfp.writestr("b.txt", "hello world", compress_type=zipfile.ZIP_DEFLATED)
416
417 info = zipfp.getinfo('a.txt')
418 self.assertEqual(info.compress_type, zipfile.ZIP_STORED)
419
420 if zlib:
421 info = zipfp.getinfo('b.txt')
422 self.assertEqual(info.compress_type, zipfile.ZIP_DEFLATED)
423
424
Antoine Pitrou5fdfa3e2008-07-25 19:42:26 +0000425 def zip_test_writestr_permissions(self, f, compression):
426 # Make sure that writestr creates files with mode 0600,
427 # when it is passed a name rather than a ZipInfo instance.
428
Ezio Melottid5a23e32009-07-15 17:07:04 +0000429 self.make_test_archive(f, compression)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000430 with zipfile.ZipFile(f, "r") as zipfp:
431 zinfo = zipfp.getinfo('strfile')
432 self.assertEqual(zinfo.external_attr, 0600 << 16)
Antoine Pitrou5fdfa3e2008-07-25 19:42:26 +0000433
Ezio Melottid5a23e32009-07-15 17:07:04 +0000434 def test_writestr_permissions(self):
Antoine Pitrou5fdfa3e2008-07-25 19:42:26 +0000435 for f in (TESTFN2, TemporaryFile(), StringIO()):
436 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
437
Ezio Melotti569e61f2009-12-30 06:14:51 +0000438 def test_close(self):
439 """Check that the zipfile is closed after the 'with' block."""
440 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
441 for fpath, fdata in SMALL_TEST_DATA:
442 zipfp.writestr(fpath, fdata)
443 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
444 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
445
446 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
447 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
448 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
449
450 def test_close_on_exception(self):
451 """Check that the zipfile is closed if an exception is raised in the
452 'with' block."""
453 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
454 for fpath, fdata in SMALL_TEST_DATA:
455 zipfp.writestr(fpath, fdata)
456
457 try:
458 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
459 raise zipfile.BadZipfile()
460 except zipfile.BadZipfile:
461 self.assertTrue(zipfp2.fp is None, 'zipfp is not closed')
462
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000463 def tearDown(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000464 unlink(TESTFN)
465 unlink(TESTFN2)
466
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000467
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000468class TestZip64InSmallFiles(unittest.TestCase):
469 # These tests test the ZIP64 functionality without using large files,
470 # see test_zipfile64 for proper tests.
471
472 def setUp(self):
473 self._limit = zipfile.ZIP64_LIMIT
474 zipfile.ZIP64_LIMIT = 5
475
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000476 line_gen = ("Test of zipfile line %d." % i
477 for i in range(0, FIXEDTEST_SIZE))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000478 self.data = '\n'.join(line_gen)
479
480 # Make a source file with some lines
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000481 with open(TESTFN, "wb") as fp:
482 fp.write(self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000483
Ezio Melottid5a23e32009-07-15 17:07:04 +0000484 def large_file_exception_test(self, f, compression):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000485 with zipfile.ZipFile(f, "w", compression) as zipfp:
486 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000487 zipfp.write, TESTFN, "another.name")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000488
Ezio Melottid5a23e32009-07-15 17:07:04 +0000489 def large_file_exception_test2(self, f, compression):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000490 with zipfile.ZipFile(f, "w", compression) as zipfp:
491 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000492 zipfp.writestr, "another.name", self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000493
Ezio Melottid5a23e32009-07-15 17:07:04 +0000494 def test_large_file_exception(self):
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000495 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000496 self.large_file_exception_test(f, zipfile.ZIP_STORED)
497 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000498
Ezio Melottid5a23e32009-07-15 17:07:04 +0000499 def zip_test(self, f, compression):
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000500 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000501 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000502 zipfp.write(TESTFN, "another.name")
Ezio Melotti569e61f2009-12-30 06:14:51 +0000503 zipfp.write(TESTFN, TESTFN)
504 zipfp.writestr("strfile", self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000505
506 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000507 with zipfile.ZipFile(f, "r", compression) as zipfp:
508 self.assertEqual(zipfp.read(TESTFN), self.data)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000509 self.assertEqual(zipfp.read("another.name"), self.data)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000510 self.assertEqual(zipfp.read("strfile"), self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000511
Ezio Melotti569e61f2009-12-30 06:14:51 +0000512 # Print the ZIP directory
513 fp = StringIO()
514 stdout = sys.stdout
515 try:
516 sys.stdout = fp
517 zipfp.printdir()
518 finally:
519 sys.stdout = stdout
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000520
Ezio Melotti569e61f2009-12-30 06:14:51 +0000521 directory = fp.getvalue()
522 lines = directory.splitlines()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000523 self.assertEqual(len(lines), 4) # Number of files + header
Tim Petersa608bb22006-06-15 18:06:29 +0000524
Ezio Melottiaa980582010-01-23 23:04:36 +0000525 self.assertIn('File Name', lines[0])
526 self.assertIn('Modified', lines[0])
527 self.assertIn('Size', lines[0])
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000528
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000529 fn, date, time_, size = lines[1].split()
530 self.assertEqual(fn, 'another.name')
531 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
532 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
533 self.assertEqual(size, str(len(self.data)))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000534
Ezio Melotti569e61f2009-12-30 06:14:51 +0000535 # Check the namelist
536 names = zipfp.namelist()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000537 self.assertEqual(len(names), 3)
Ezio Melottiaa980582010-01-23 23:04:36 +0000538 self.assertIn(TESTFN, names)
539 self.assertIn("another.name", names)
540 self.assertIn("strfile", names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000541
Ezio Melotti569e61f2009-12-30 06:14:51 +0000542 # Check infolist
543 infos = zipfp.infolist()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000544 names = [i.filename for i in infos]
545 self.assertEqual(len(names), 3)
Ezio Melottiaa980582010-01-23 23:04:36 +0000546 self.assertIn(TESTFN, names)
547 self.assertIn("another.name", names)
548 self.assertIn("strfile", names)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000549 for i in infos:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000550 self.assertEqual(i.file_size, len(self.data))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000551
Ezio Melotti569e61f2009-12-30 06:14:51 +0000552 # check getinfo
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000553 for nm in (TESTFN, "another.name", "strfile"):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000554 info = zipfp.getinfo(nm)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000555 self.assertEqual(info.filename, nm)
556 self.assertEqual(info.file_size, len(self.data))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000557
Ezio Melotti569e61f2009-12-30 06:14:51 +0000558 # Check that testzip doesn't raise an exception
559 zipfp.testzip()
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000560
Ezio Melottid5a23e32009-07-15 17:07:04 +0000561 def test_stored(self):
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000562 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000563 self.zip_test(f, zipfile.ZIP_STORED)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000564
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000565 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000566 def test_deflated(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000567 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000568 self.zip_test(f, zipfile.ZIP_DEFLATED)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000569
Ezio Melottid5a23e32009-07-15 17:07:04 +0000570 def test_absolute_arcnames(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000571 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
572 allowZip64=True) as zipfp:
573 zipfp.write(TESTFN, "/absolute")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000574
Ezio Melotti569e61f2009-12-30 06:14:51 +0000575 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
576 self.assertEqual(zipfp.namelist(), ["absolute"])
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000577
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000578 def tearDown(self):
579 zipfile.ZIP64_LIMIT = self._limit
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000580 unlink(TESTFN)
581 unlink(TESTFN2)
582
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000583
584class PyZipFileTests(unittest.TestCase):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000585 def test_write_pyfile(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000586 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
587 fn = __file__
588 if fn.endswith('.pyc') or fn.endswith('.pyo'):
589 fn = fn[:-1]
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000590
Ezio Melotti569e61f2009-12-30 06:14:51 +0000591 zipfp.writepy(fn)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000592
Ezio Melotti569e61f2009-12-30 06:14:51 +0000593 bn = os.path.basename(fn)
Ezio Melottiaa980582010-01-23 23:04:36 +0000594 self.assertNotIn(bn, zipfp.namelist())
Ezio Melotti569e61f2009-12-30 06:14:51 +0000595 self.assertTrue(bn + 'o' in zipfp.namelist() or
596 bn + 'c' in zipfp.namelist())
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000597
Ezio Melotti569e61f2009-12-30 06:14:51 +0000598 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
599 fn = __file__
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000600 if fn.endswith(('.pyc', '.pyo')):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000601 fn = fn[:-1]
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000602
Ezio Melotti569e61f2009-12-30 06:14:51 +0000603 zipfp.writepy(fn, "testpackage")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000604
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000605 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
Ezio Melottiaa980582010-01-23 23:04:36 +0000606 self.assertNotIn(bn, zipfp.namelist())
Ezio Melotti569e61f2009-12-30 06:14:51 +0000607 self.assertTrue(bn + 'o' in zipfp.namelist() or
608 bn + 'c' in zipfp.namelist())
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000609
Ezio Melottid5a23e32009-07-15 17:07:04 +0000610 def test_write_python_package(self):
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000611 import email
612 packagedir = os.path.dirname(email.__file__)
613
Ezio Melotti569e61f2009-12-30 06:14:51 +0000614 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
615 zipfp.writepy(packagedir)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000616
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000617 # Check for a couple of modules at different levels of the
618 # hierarchy
Ezio Melotti569e61f2009-12-30 06:14:51 +0000619 names = zipfp.namelist()
620 self.assertTrue('email/__init__.pyo' in names or
621 'email/__init__.pyc' in names)
622 self.assertTrue('email/mime/text.pyo' in names or
623 'email/mime/text.pyc' in names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000624
Ezio Melottid5a23e32009-07-15 17:07:04 +0000625 def test_write_python_directory(self):
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000626 os.mkdir(TESTFN2)
627 try:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000628 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
Ezio Melotti763f1e82009-12-31 13:27:41 +0000629 fp.write("print(42)\n")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000630
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000631 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
Ezio Melotti763f1e82009-12-31 13:27:41 +0000632 fp.write("print(42 * 42)\n")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000633
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000634 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
635 fp.write("bla bla bla\n")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000636
637 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
638 zipfp.writepy(TESTFN2)
639
640 names = zipfp.namelist()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000641 self.assertTrue('mod1.pyc' in names or 'mod1.pyo' in names)
642 self.assertTrue('mod2.pyc' in names or 'mod2.pyo' in names)
Ezio Melottiaa980582010-01-23 23:04:36 +0000643 self.assertNotIn('mod2.txt', names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000644
645 finally:
646 shutil.rmtree(TESTFN2)
647
Ezio Melottid5a23e32009-07-15 17:07:04 +0000648 def test_write_non_pyfile(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000649 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000650 open(TESTFN, 'w').write('most definitely not a python file')
Ezio Melotti569e61f2009-12-30 06:14:51 +0000651 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
652 os.remove(TESTFN)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000653
654
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000655class OtherTests(unittest.TestCase):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000656 def test_unicode_filenames(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000657 with zipfile.ZipFile(TESTFN, "w") as zf:
658 zf.writestr(u"foo.txt", "Test for unicode filename")
659 zf.writestr(u"\xf6.txt", "Test for unicode filename")
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000660 self.assertIsInstance(zf.infolist()[0].filename, unicode)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000661
662 with zipfile.ZipFile(TESTFN, "r") as zf:
663 self.assertEqual(zf.filelist[0].filename, "foo.txt")
664 self.assertEqual(zf.filelist[1].filename, u"\xf6.txt")
Martin v. Löwis471617d2008-05-05 17:16:58 +0000665
Ezio Melottid5a23e32009-07-15 17:07:04 +0000666 def test_create_non_existent_file_for_append(self):
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000667 if os.path.exists(TESTFN):
668 os.unlink(TESTFN)
Tim Petersea5962f2007-03-12 18:07:52 +0000669
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000670 filename = 'testfile.txt'
671 content = 'hello, world. this is some content.'
Tim Petersea5962f2007-03-12 18:07:52 +0000672
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000673 try:
Ezio Melotti569e61f2009-12-30 06:14:51 +0000674 with zipfile.ZipFile(TESTFN, 'a') as zf:
675 zf.writestr(filename, content)
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000676 except IOError:
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000677 self.fail('Could not append data to a non-existent zip file.')
678
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000679 self.assertTrue(os.path.exists(TESTFN))
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000680
Ezio Melotti569e61f2009-12-30 06:14:51 +0000681 with zipfile.ZipFile(TESTFN, 'r') as zf:
682 self.assertEqual(zf.read(filename), content)
Tim Petersea5962f2007-03-12 18:07:52 +0000683
Ezio Melottid5a23e32009-07-15 17:07:04 +0000684 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000685 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000686 # it opens if there's an error in the file. If it doesn't, the
687 # traceback holds a reference to the ZipFile object and, indirectly,
688 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000689 # On Windows, this causes the os.unlink() call to fail because the
690 # underlying file is still open. This is SF bug #412214.
691 #
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000692 with open(TESTFN, "w") as fp:
693 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000694 try:
695 zf = zipfile.ZipFile(TESTFN)
696 except zipfile.BadZipfile:
Collin Winter04a51ec2007-03-29 02:28:16 +0000697 pass
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000698
Ezio Melottid5a23e32009-07-15 17:07:04 +0000699 def test_is_zip_erroneous_file(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000700 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000701 # - passing a filename
702 with open(TESTFN, "w") as fp:
703 fp.write("this is not a legal zip file\n")
Tim Petersea5962f2007-03-12 18:07:52 +0000704 chk = zipfile.is_zipfile(TESTFN)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000705 self.assertFalse(chk)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000706 # - passing a file object
707 with open(TESTFN, "rb") as fp:
708 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000709 self.assertTrue(not chk)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000710 # - passing a file-like object
711 fp = StringIO()
712 fp.write("this is not a legal zip file\n")
713 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000714 self.assertTrue(not chk)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000715 fp.seek(0, 0)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000716 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000717 self.assertTrue(not chk)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000718
Ezio Melottid5a23e32009-07-15 17:07:04 +0000719 def test_is_zip_valid_file(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000720 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000721 # - passing a filename
Ezio Melotti569e61f2009-12-30 06:14:51 +0000722 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
723 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Tim Petersea5962f2007-03-12 18:07:52 +0000724 chk = zipfile.is_zipfile(TESTFN)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000725 self.assertTrue(chk)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000726 # - passing a file object
727 with open(TESTFN, "rb") as fp:
728 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000729 self.assertTrue(chk)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000730 fp.seek(0, 0)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000731 zip_contents = fp.read()
732 # - passing a file-like object
733 fp = StringIO()
734 fp.write(zip_contents)
735 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000736 self.assertTrue(chk)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000737 fp.seek(0, 0)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000738 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000739 self.assertTrue(chk)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000740
Ezio Melottid5a23e32009-07-15 17:07:04 +0000741 def test_non_existent_file_raises_IOError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000742 # make sure we don't raise an AttributeError when a partially-constructed
743 # ZipFile instance is finalized; this tests for regression on SF tracker
744 # bug #403871.
745
746 # The bug we're testing for caused an AttributeError to be raised
747 # when a ZipFile instance was created for a file that did not
748 # exist; the .fp member was not initialized but was needed by the
749 # __del__() method. Since the AttributeError is in the __del__(),
750 # it is ignored, but the user should be sufficiently annoyed by
751 # the message on the output that regression will be noticed
752 # quickly.
753 self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
754
Amaury Forgeot d'Arc3e5b0272009-07-28 22:15:30 +0000755 def test_empty_file_raises_BadZipFile(self):
756 f = open(TESTFN, 'w')
757 f.close()
758 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN)
759
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000760 with open(TESTFN, 'w') as fp:
761 fp.write("short file")
Amaury Forgeot d'Arc3e5b0272009-07-28 22:15:30 +0000762 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN)
763
Ezio Melottid5a23e32009-07-15 17:07:04 +0000764 def test_closed_zip_raises_RuntimeError(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000765 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000766 data = StringIO()
Ezio Melotti569e61f2009-12-30 06:14:51 +0000767 with zipfile.ZipFile(data, mode="w") as zipf:
768 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000769
770 # This is correct; calling .read on a closed ZipFile should throw
771 # a RuntimeError, and so should calling .testzip. An earlier
772 # version of .testzip would swallow this exception (and any other)
773 # and report that the first file in the archive was corrupt.
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000774 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
775 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000776 self.assertRaises(RuntimeError, zipf.testzip)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000777 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000778 open(TESTFN, 'w').write('zipfile test data')
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000779 self.assertRaises(RuntimeError, zipf.write, TESTFN)
780
Ezio Melottid5a23e32009-07-15 17:07:04 +0000781 def test_bad_constructor_mode(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000782 """Check that bad modes passed to ZipFile constructor are caught."""
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000783 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
784
Ezio Melottid5a23e32009-07-15 17:07:04 +0000785 def test_bad_open_mode(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000786 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000787 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
788 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
789
790 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000791 # read the data to make sure the file is there
Ezio Melotti569e61f2009-12-30 06:14:51 +0000792 zipf.read("foo.txt")
793 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000794
Ezio Melottid5a23e32009-07-15 17:07:04 +0000795 def test_read0(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000796 """Check that calling read(0) on a ZipExtFile object returns an empty
797 string and doesn't advance file pointer."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000798 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
799 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
800 # read the data to make sure the file is there
801 f = zipf.open("foo.txt")
802 for i in xrange(FIXEDTEST_SIZE):
803 self.assertEqual(f.read(0), '')
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000804
Ezio Melotti569e61f2009-12-30 06:14:51 +0000805 self.assertEqual(f.read(), "O, for a Muse of Fire!")
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000806
Ezio Melottid5a23e32009-07-15 17:07:04 +0000807 def test_open_non_existent_item(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000808 """Check that attempting to call open() for an item that doesn't
809 exist in the archive raises a RuntimeError."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000810 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
811 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000812
Ezio Melottid5a23e32009-07-15 17:07:04 +0000813 def test_bad_compression_mode(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000814 """Check that bad compression methods passed to ZipFile.open are
815 caught."""
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000816 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
817
Ezio Melottid5a23e32009-07-15 17:07:04 +0000818 def test_null_byte_in_filename(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000819 """Check that a filename containing a null byte is properly
820 terminated."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000821 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
822 zipf.writestr("foo.txt\x00qqq", "O, for a Muse of Fire!")
823 self.assertEqual(zipf.namelist(), ['foo.txt'])
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000824
Ezio Melottid5a23e32009-07-15 17:07:04 +0000825 def test_struct_sizes(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000826 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwis8c436412008-07-03 12:51:14 +0000827 self.assertEqual(zipfile.sizeEndCentDir, 22)
828 self.assertEqual(zipfile.sizeCentralDir, 46)
829 self.assertEqual(zipfile.sizeEndCentDir64, 56)
830 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
831
Ezio Melottid5a23e32009-07-15 17:07:04 +0000832 def test_comments(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000833 """Check that comments on the archive are handled properly."""
Martin v. Löwis8c436412008-07-03 12:51:14 +0000834
835 # check default comment is empty
Ezio Melotti569e61f2009-12-30 06:14:51 +0000836 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
837 self.assertEqual(zipf.comment, '')
838 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
839
840 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
841 self.assertEqual(zipf.comment, '')
Martin v. Löwis8c436412008-07-03 12:51:14 +0000842
843 # check a simple short comment
844 comment = 'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melotti569e61f2009-12-30 06:14:51 +0000845 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
846 zipf.comment = comment
847 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
848 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
849 self.assertEqual(zipf.comment, comment)
Martin v. Löwis8c436412008-07-03 12:51:14 +0000850
851 # check a comment of max length
852 comment2 = ''.join(['%d' % (i**3 % 10) for i in xrange((1 << 16)-1)])
Ezio Melotti569e61f2009-12-30 06:14:51 +0000853 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
854 zipf.comment = comment2
855 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
856
857 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
858 self.assertEqual(zipf.comment, comment2)
Martin v. Löwis8c436412008-07-03 12:51:14 +0000859
860 # check a comment that is too long is truncated
Ezio Melotti569e61f2009-12-30 06:14:51 +0000861 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
862 zipf.comment = comment2 + 'oops'
863 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
864 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
865 self.assertEqual(zipf.comment, comment2)
Martin v. Löwis8c436412008-07-03 12:51:14 +0000866
Collin Winter04a51ec2007-03-29 02:28:16 +0000867 def tearDown(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000868 unlink(TESTFN)
869 unlink(TESTFN2)
870
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000871
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000872class DecryptionTests(unittest.TestCase):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000873 """Check that ZIP decryption works. Since the library does not
874 support encryption at the moment, we use a pre-generated encrypted
875 ZIP file."""
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000876
877 data = (
878 'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
879 '\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
880 '\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
881 'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
882 '\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
883 '\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
884 '\x00\x00L\x00\x00\x00\x00\x00' )
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000885 data2 = (
886 'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
887 '\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
888 '\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
889 'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
890 '\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
891 '\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
892 'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
893 '\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000894
895 plain = 'zipfile.py encryption test'
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000896 plain2 = '\x00'*512
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000897
898 def setUp(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000899 with open(TESTFN, "wb") as fp:
900 fp.write(self.data)
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000901 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000902 with open(TESTFN2, "wb") as fp:
903 fp.write(self.data2)
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000904 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000905
906 def tearDown(self):
907 self.zip.close()
908 os.unlink(TESTFN)
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000909 self.zip2.close()
910 os.unlink(TESTFN2)
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000911
Ezio Melottid5a23e32009-07-15 17:07:04 +0000912 def test_no_password(self):
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000913 # Reading the encrypted file without password
914 # must generate a RunTime exception
915 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000916 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000917
Ezio Melottid5a23e32009-07-15 17:07:04 +0000918 def test_bad_password(self):
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000919 self.zip.setpassword("perl")
920 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000921 self.zip2.setpassword("perl")
922 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Tim Petersea5962f2007-03-12 18:07:52 +0000923
Ezio Melotti1036a7f2009-09-12 14:43:43 +0000924 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000925 def test_good_password(self):
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000926 self.zip.setpassword("python")
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000927 self.assertEqual(self.zip.read("test.txt"), self.plain)
Gregory P. Smith0c63fc22008-01-20 01:21:03 +0000928 self.zip2.setpassword("12345")
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000929 self.assertEqual(self.zip2.read("zero"), self.plain2)
Martin v. Löwisc6d626e2007-02-13 09:49:38 +0000930
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000931
932class TestsWithRandomBinaryFiles(unittest.TestCase):
933 def setUp(self):
934 datacount = randint(16, 64)*1024 + randint(1, 1024)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000935 self.data = ''.join(struct.pack('<f', random()*randint(-1000, 1000))
Ezio Melotti763f1e82009-12-31 13:27:41 +0000936 for i in xrange(datacount))
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000937
938 # Make a source file with some lines
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000939 with open(TESTFN, "wb") as fp:
940 fp.write(self.data)
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000941
Collin Winter04a51ec2007-03-29 02:28:16 +0000942 def tearDown(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000943 unlink(TESTFN)
944 unlink(TESTFN2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000945
Ezio Melottid5a23e32009-07-15 17:07:04 +0000946 def make_test_archive(self, f, compression):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000947 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000948 with zipfile.ZipFile(f, "w", compression) as zipfp:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000949 zipfp.write(TESTFN, "another.name")
Ezio Melotti569e61f2009-12-30 06:14:51 +0000950 zipfp.write(TESTFN, TESTFN)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000951
Ezio Melottid5a23e32009-07-15 17:07:04 +0000952 def zip_test(self, f, compression):
953 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000954
955 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000956 with zipfile.ZipFile(f, "r", compression) as zipfp:
957 testdata = zipfp.read(TESTFN)
958 self.assertEqual(len(testdata), len(self.data))
959 self.assertEqual(testdata, self.data)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000960 self.assertEqual(zipfp.read("another.name"), self.data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000961
Ezio Melottid5a23e32009-07-15 17:07:04 +0000962 def test_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000963 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000964 self.zip_test(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +0000965
Ezio Melottid5a23e32009-07-15 17:07:04 +0000966 def zip_open_test(self, f, compression):
967 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000968
969 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000970 with zipfile.ZipFile(f, "r", compression) as zipfp:
971 zipdata1 = []
972 zipopen1 = zipfp.open(TESTFN)
973 while True:
974 read_data = zipopen1.read(256)
975 if not read_data:
976 break
977 zipdata1.append(read_data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000978
Ezio Melotti569e61f2009-12-30 06:14:51 +0000979 zipdata2 = []
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000980 zipopen2 = zipfp.open("another.name")
Ezio Melotti569e61f2009-12-30 06:14:51 +0000981 while True:
982 read_data = zipopen2.read(256)
983 if not read_data:
984 break
985 zipdata2.append(read_data)
Tim Petersea5962f2007-03-12 18:07:52 +0000986
Ezio Melotti569e61f2009-12-30 06:14:51 +0000987 testdata1 = ''.join(zipdata1)
988 self.assertEqual(len(testdata1), len(self.data))
989 self.assertEqual(testdata1, self.data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000990
Ezio Melotti569e61f2009-12-30 06:14:51 +0000991 testdata2 = ''.join(zipdata2)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000992 self.assertEqual(len(testdata2), len(self.data))
993 self.assertEqual(testdata2, self.data)
Tim Petersea5962f2007-03-12 18:07:52 +0000994
Ezio Melottid5a23e32009-07-15 17:07:04 +0000995 def test_open_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000996 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000997 self.zip_open_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000998
Ezio Melottid5a23e32009-07-15 17:07:04 +0000999 def zip_random_open_test(self, f, compression):
1000 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001001
1002 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001003 with zipfile.ZipFile(f, "r", compression) as zipfp:
1004 zipdata1 = []
1005 zipopen1 = zipfp.open(TESTFN)
1006 while True:
1007 read_data = zipopen1.read(randint(1, 1024))
1008 if not read_data:
1009 break
1010 zipdata1.append(read_data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001011
Ezio Melotti569e61f2009-12-30 06:14:51 +00001012 testdata = ''.join(zipdata1)
1013 self.assertEqual(len(testdata), len(self.data))
1014 self.assertEqual(testdata, self.data)
Tim Petersea5962f2007-03-12 18:07:52 +00001015
Ezio Melottid5a23e32009-07-15 17:07:04 +00001016 def test_random_open_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001017 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001018 self.zip_random_open_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001019
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001020
Ezio Melotti1036a7f2009-09-12 14:43:43 +00001021@skipUnless(zlib, "requires zlib")
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001022class TestsWithMultipleOpens(unittest.TestCase):
1023 def setUp(self):
1024 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001025 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
1026 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
1027 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
Tim Petersea5962f2007-03-12 18:07:52 +00001028
Ezio Melottid5a23e32009-07-15 17:07:04 +00001029 def test_same_file(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001030 # Verify that (when the ZipFile is in control of creating file objects)
1031 # multiple open() calls can be made without interfering with each other.
Ezio Melotti569e61f2009-12-30 06:14:51 +00001032 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
1033 zopen1 = zipf.open('ones')
1034 zopen2 = zipf.open('ones')
1035 data1 = zopen1.read(500)
1036 data2 = zopen2.read(500)
1037 data1 += zopen1.read(500)
1038 data2 += zopen2.read(500)
1039 self.assertEqual(data1, data2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001040
Ezio Melottid5a23e32009-07-15 17:07:04 +00001041 def test_different_file(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001042 # Verify that (when the ZipFile is in control of creating file objects)
1043 # multiple open() calls can be made without interfering with each other.
Ezio Melotti569e61f2009-12-30 06:14:51 +00001044 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
1045 zopen1 = zipf.open('ones')
1046 zopen2 = zipf.open('twos')
1047 data1 = zopen1.read(500)
1048 data2 = zopen2.read(500)
1049 data1 += zopen1.read(500)
1050 data2 += zopen2.read(500)
1051 self.assertEqual(data1, '1'*FIXEDTEST_SIZE)
1052 self.assertEqual(data2, '2'*FIXEDTEST_SIZE)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001053
Ezio Melottid5a23e32009-07-15 17:07:04 +00001054 def test_interleaved(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001055 # Verify that (when the ZipFile is in control of creating file objects)
1056 # multiple open() calls can be made without interfering with each other.
Ezio Melotti569e61f2009-12-30 06:14:51 +00001057 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
1058 zopen1 = zipf.open('ones')
1059 data1 = zopen1.read(500)
1060 zopen2 = zipf.open('twos')
1061 data2 = zopen2.read(500)
1062 data1 += zopen1.read(500)
1063 data2 += zopen2.read(500)
1064 self.assertEqual(data1, '1'*FIXEDTEST_SIZE)
1065 self.assertEqual(data2, '2'*FIXEDTEST_SIZE)
Tim Petersea5962f2007-03-12 18:07:52 +00001066
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001067 def tearDown(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001068 unlink(TESTFN2)
1069
Tim Petersea5962f2007-03-12 18:07:52 +00001070
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001071class TestWithDirectory(unittest.TestCase):
1072 def setUp(self):
1073 os.mkdir(TESTFN2)
1074
Ezio Melottid5a23e32009-07-15 17:07:04 +00001075 def test_extract_dir(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +00001076 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
1077 zipf.extractall(TESTFN2)
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001078 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1079 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1080 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1081
Ezio Melottid5a23e32009-07-15 17:07:04 +00001082 def test_bug_6050(self):
Martin v. Löwis0b09c422009-05-24 19:30:52 +00001083 # Extraction should succeed if directories already exist
1084 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottid5a23e32009-07-15 17:07:04 +00001085 self.test_extract_dir()
Martin v. Löwis0b09c422009-05-24 19:30:52 +00001086
Ezio Melottid5a23e32009-07-15 17:07:04 +00001087 def test_store_dir(self):
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001088 os.mkdir(os.path.join(TESTFN2, "x"))
1089 zipf = zipfile.ZipFile(TESTFN, "w")
1090 zipf.write(os.path.join(TESTFN2, "x"), "x")
1091 self.assertTrue(zipf.filelist[0].filename.endswith("x/"))
1092
1093 def tearDown(self):
1094 shutil.rmtree(TESTFN2)
1095 if os.path.exists(TESTFN):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001096 unlink(TESTFN)
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001097
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001098
1099class UniversalNewlineTests(unittest.TestCase):
1100 def setUp(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001101 self.line_gen = ["Test of zipfile line %d." % i
1102 for i in xrange(FIXEDTEST_SIZE)]
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001103 self.seps = ('\r', '\r\n', '\n')
1104 self.arcdata, self.arcfiles = {}, {}
1105 for n, s in enumerate(self.seps):
1106 self.arcdata[s] = s.join(self.line_gen) + s
1107 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Brett Cannon6cef0762007-05-25 20:17:15 +00001108 open(self.arcfiles[s], "wb").write(self.arcdata[s])
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001109
Ezio Melottid5a23e32009-07-15 17:07:04 +00001110 def make_test_archive(self, f, compression):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001111 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001112 with zipfile.ZipFile(f, "w", compression) as zipfp:
1113 for fn in self.arcfiles.values():
1114 zipfp.write(fn, fn)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001115
Ezio Melottid5a23e32009-07-15 17:07:04 +00001116 def read_test(self, f, compression):
1117 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001118
1119 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001120 with zipfile.ZipFile(f, "r") as zipfp:
1121 for sep, fn in self.arcfiles.items():
1122 zipdata = zipfp.open(fn, "rU").read()
1123 self.assertEqual(self.arcdata[sep], zipdata)
Tim Petersea5962f2007-03-12 18:07:52 +00001124
Antoine Pitrou94c33eb2010-01-27 20:59:50 +00001125 def readline_read_test(self, f, compression):
1126 self.make_test_archive(f, compression)
1127
1128 # Read the ZIP archive
1129 zipfp = zipfile.ZipFile(f, "r")
1130 for sep, fn in self.arcfiles.items():
1131 zipopen = zipfp.open(fn, "rU")
1132 data = ''
1133 while True:
1134 read = zipopen.readline()
1135 if not read:
1136 break
1137 data += read
1138
1139 read = zipopen.read(5)
1140 if not read:
1141 break
1142 data += read
1143
1144 self.assertEqual(data, self.arcdata['\n'])
1145
1146 zipfp.close()
1147
Ezio Melottid5a23e32009-07-15 17:07:04 +00001148 def readline_test(self, f, compression):
1149 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001150
1151 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001152 with zipfile.ZipFile(f, "r") as zipfp:
1153 for sep, fn in self.arcfiles.items():
1154 zipopen = zipfp.open(fn, "rU")
1155 for line in self.line_gen:
1156 linedata = zipopen.readline()
1157 self.assertEqual(linedata, line + '\n')
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001158
Ezio Melottid5a23e32009-07-15 17:07:04 +00001159 def readlines_test(self, f, compression):
1160 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001161
1162 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001163 with zipfile.ZipFile(f, "r") as zipfp:
1164 for sep, fn in self.arcfiles.items():
1165 ziplines = zipfp.open(fn, "rU").readlines()
1166 for line, zipline in zip(self.line_gen, ziplines):
1167 self.assertEqual(zipline, line + '\n')
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001168
Ezio Melottid5a23e32009-07-15 17:07:04 +00001169 def iterlines_test(self, f, compression):
1170 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001171
1172 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001173 with zipfile.ZipFile(f, "r") as zipfp:
1174 for sep, fn in self.arcfiles.items():
1175 for line, zipline in zip(self.line_gen, zipfp.open(fn, "rU")):
1176 self.assertEqual(zipline, line + '\n')
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001177
Ezio Melottid5a23e32009-07-15 17:07:04 +00001178 def test_read_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001179 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001180 self.read_test(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +00001181
Antoine Pitrou94c33eb2010-01-27 20:59:50 +00001182 def test_readline_read_stored(self):
1183 # Issue #7610: calls to readline() interleaved with calls to read().
1184 for f in (TESTFN2, TemporaryFile(), StringIO()):
1185 self.readline_read_test(f, zipfile.ZIP_STORED)
1186
Ezio Melottid5a23e32009-07-15 17:07:04 +00001187 def test_readline_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001188 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001189 self.readline_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001190
Ezio Melottid5a23e32009-07-15 17:07:04 +00001191 def test_readlines_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001192 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001193 self.readlines_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001194
Ezio Melottid5a23e32009-07-15 17:07:04 +00001195 def test_iterlines_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001196 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001197 self.iterlines_test(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +00001198
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001199 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +00001200 def test_read_deflated(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001201 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001202 self.read_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001203
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001204 @skipUnless(zlib, "requires zlib")
Antoine Pitrou94c33eb2010-01-27 20:59:50 +00001205 def test_readline_read_deflated(self):
1206 # Issue #7610: calls to readline() interleaved with calls to read().
1207 for f in (TESTFN2, TemporaryFile(), StringIO()):
1208 self.readline_read_test(f, zipfile.ZIP_DEFLATED)
1209
1210 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +00001211 def test_readline_deflated(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001212 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001213 self.readline_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001214
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001215 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +00001216 def test_readlines_deflated(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001217 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001218 self.readlines_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001219
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001220 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +00001221 def test_iterlines_deflated(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001222 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001223 self.iterlines_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001224
1225 def tearDown(self):
1226 for sep, fn in self.arcfiles.items():
1227 os.remove(fn)
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001228 unlink(TESTFN)
1229 unlink(TESTFN2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001230
1231
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001232def test_main():
Tim Petersea5962f2007-03-12 18:07:52 +00001233 run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
1234 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001235 TestWithDirectory, UniversalNewlineTests,
1236 TestsWithRandomBinaryFiles)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001237
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001238if __name__ == "__main__":
1239 test_main()