blob: 9e3a28b4383e7ffbab50eb0f1b781429f8d0d41f [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 Storchakadb03e6b2013-05-08 21:52:31 +030021from test.test_support import TESTFN, TESTFN_UNICODE, TESTFN_ENCODING, \
22 run_unittest, findfile, unlink
23try:
24 TESTFN_UNICODE.encode(TESTFN_ENCODING)
25except (UnicodeError, TypeError):
26 # Either the file system encoding is None, or the file name
27 # cannot be encoded in the file system encoding.
28 TESTFN_UNICODE = None
Guido van Rossum368f04a2000-04-10 13:23:04 +000029
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000030TESTFN2 = TESTFN + "2"
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +000031TESTFNDIR = TESTFN + "d"
Georg Brandl4b3ab6f2007-07-12 09:59:22 +000032FIXEDTEST_SIZE = 1000
Guido van Rossum368f04a2000-04-10 13:23:04 +000033
Georg Brandl62416bc2008-01-07 18:47:44 +000034SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'),
35 ('ziptest2dir/_ziptest2', 'qawsedrftg'),
Gregory P. Smith608cc452013-02-01 11:40:18 -080036 ('ziptest2dir/ziptest3dir/_ziptest3', 'azsxdcfvgb'),
Georg Brandl62416bc2008-01-07 18:47:44 +000037 ('ziptest2dir/ziptest3dir/ziptest4dir/_ziptest3', '6y7u8i9o0p')]
38
Ezio Melotti6cbfc122009-07-10 20:25:56 +000039
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000040class TestsWithSourceFile(unittest.TestCase):
41 def setUp(self):
Georg Brandl4b3ab6f2007-07-12 09:59:22 +000042 self.line_gen = ["Zipfile test line %d. random float: %f" % (i, random())
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000043 for i in xrange(FIXEDTEST_SIZE)]
Martin v. Löwis3eb76482007-03-06 10:41:24 +000044 self.data = '\n'.join(self.line_gen) + '\n'
Fred Drake6e7e4852001-02-28 05:34:16 +000045
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000046 # Make a source file with some lines
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000047 with open(TESTFN, "wb") as fp:
48 fp.write(self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000049
Ezio Melottid5a23e32009-07-15 17:07:04 +000050 def make_test_archive(self, f, compression):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000051 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +000052 with zipfile.ZipFile(f, "w", compression) as zipfp:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000053 zipfp.write(TESTFN, "another.name")
Ezio Melotti569e61f2009-12-30 06:14:51 +000054 zipfp.write(TESTFN, TESTFN)
55 zipfp.writestr("strfile", self.data)
Tim Peters7d3bad62001-04-04 18:56:49 +000056
Ezio Melottid5a23e32009-07-15 17:07:04 +000057 def zip_test(self, f, compression):
58 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +000059
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +000060 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +000061 with zipfile.ZipFile(f, "r", compression) as zipfp:
62 self.assertEqual(zipfp.read(TESTFN), self.data)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000063 self.assertEqual(zipfp.read("another.name"), self.data)
Ezio Melotti569e61f2009-12-30 06:14:51 +000064 self.assertEqual(zipfp.read("strfile"), self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +000065
Ezio Melotti569e61f2009-12-30 06:14:51 +000066 # Print the ZIP directory
67 fp = StringIO()
68 stdout = sys.stdout
69 try:
70 sys.stdout = fp
71 zipfp.printdir()
72 finally:
73 sys.stdout = stdout
Tim Petersa608bb22006-06-15 18:06:29 +000074
Ezio Melotti569e61f2009-12-30 06:14:51 +000075 directory = fp.getvalue()
76 lines = directory.splitlines()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000077 self.assertEqual(len(lines), 4) # Number of files + header
Ronald Oussoren143cefb2006-06-15 08:14:18 +000078
Ezio Melottiaa980582010-01-23 23:04:36 +000079 self.assertIn('File Name', lines[0])
80 self.assertIn('Modified', lines[0])
81 self.assertIn('Size', lines[0])
Ronald Oussoren143cefb2006-06-15 08:14:18 +000082
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000083 fn, date, time_, size = lines[1].split()
84 self.assertEqual(fn, 'another.name')
85 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
86 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
87 self.assertEqual(size, str(len(self.data)))
Ronald Oussoren143cefb2006-06-15 08:14:18 +000088
Ezio Melotti569e61f2009-12-30 06:14:51 +000089 # Check the namelist
90 names = zipfp.namelist()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000091 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)
Ronald Oussoren143cefb2006-06-15 08:14:18 +000095
Ezio Melotti569e61f2009-12-30 06:14:51 +000096 # Check infolist
97 infos = zipfp.infolist()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +000098 names = [i.filename for i in infos]
99 self.assertEqual(len(names), 3)
Ezio Melottiaa980582010-01-23 23:04:36 +0000100 self.assertIn(TESTFN, names)
101 self.assertIn("another.name", names)
102 self.assertIn("strfile", names)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000103 for i in infos:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000104 self.assertEqual(i.file_size, len(self.data))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000105
Ezio Melotti569e61f2009-12-30 06:14:51 +0000106 # check getinfo
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000107 for nm in (TESTFN, "another.name", "strfile"):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000108 info = zipfp.getinfo(nm)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000109 self.assertEqual(info.filename, nm)
110 self.assertEqual(info.file_size, len(self.data))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000111
Ezio Melotti569e61f2009-12-30 06:14:51 +0000112 # Check that testzip doesn't raise an exception
113 zipfp.testzip()
Tim Peters7d3bad62001-04-04 18:56:49 +0000114
Ezio Melottid5a23e32009-07-15 17:07:04 +0000115 def test_stored(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000116 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000117 self.zip_test(f, zipfile.ZIP_STORED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000118
Ezio Melottid5a23e32009-07-15 17:07:04 +0000119 def zip_open_test(self, f, compression):
120 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000121
122 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000123 with zipfile.ZipFile(f, "r", compression) as zipfp:
124 zipdata1 = []
Brian Curtin0d654332011-04-19 21:15:55 -0500125 with zipfp.open(TESTFN) as zipopen1:
126 while True:
127 read_data = zipopen1.read(256)
128 if not read_data:
129 break
130 zipdata1.append(read_data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000131
Ezio Melotti569e61f2009-12-30 06:14:51 +0000132 zipdata2 = []
Brian Curtin0d654332011-04-19 21:15:55 -0500133 with zipfp.open("another.name") as zipopen2:
134 while True:
135 read_data = zipopen2.read(256)
136 if not read_data:
137 break
138 zipdata2.append(read_data)
Tim Petersea5962f2007-03-12 18:07:52 +0000139
Ezio Melotti569e61f2009-12-30 06:14:51 +0000140 self.assertEqual(''.join(zipdata1), self.data)
141 self.assertEqual(''.join(zipdata2), self.data)
Tim Petersea5962f2007-03-12 18:07:52 +0000142
Ezio Melottid5a23e32009-07-15 17:07:04 +0000143 def test_open_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000144 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000145 self.zip_open_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000146
Ezio Melottid5a23e32009-07-15 17:07:04 +0000147 def test_open_via_zip_info(self):
Georg Brandl112aa502008-05-20 08:25:48 +0000148 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000149 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
150 zipfp.writestr("name", "foo")
151 zipfp.writestr("name", "bar")
Georg Brandl112aa502008-05-20 08:25:48 +0000152
Ezio Melotti569e61f2009-12-30 06:14:51 +0000153 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
154 infos = zipfp.infolist()
155 data = ""
156 for info in infos:
Brian Curtin0d654332011-04-19 21:15:55 -0500157 with zipfp.open(info) as f:
158 data += f.read()
Ezio Melotti569e61f2009-12-30 06:14:51 +0000159 self.assertTrue(data == "foobar" or data == "barfoo")
160 data = ""
161 for info in infos:
162 data += zipfp.read(info)
163 self.assertTrue(data == "foobar" or data == "barfoo")
Georg Brandl112aa502008-05-20 08:25:48 +0000164
Ezio Melottid5a23e32009-07-15 17:07:04 +0000165 def zip_random_open_test(self, f, compression):
166 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000167
168 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000169 with zipfile.ZipFile(f, "r", compression) as zipfp:
170 zipdata1 = []
Brian Curtin0d654332011-04-19 21:15:55 -0500171 with zipfp.open(TESTFN) as zipopen1:
172 while True:
173 read_data = zipopen1.read(randint(1, 1024))
174 if not read_data:
175 break
176 zipdata1.append(read_data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000177
Ezio Melotti569e61f2009-12-30 06:14:51 +0000178 self.assertEqual(''.join(zipdata1), self.data)
Tim Petersea5962f2007-03-12 18:07:52 +0000179
Ezio Melottid5a23e32009-07-15 17:07:04 +0000180 def test_random_open_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000181 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000182 self.zip_random_open_test(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +0000183
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000184 def test_univeral_readaheads(self):
185 f = StringIO()
186
187 data = 'a\r\n' * 16 * 1024
Brian Curtin0d654332011-04-19 21:15:55 -0500188 with zipfile.ZipFile(f, 'w', zipfile.ZIP_STORED) as zipfp:
189 zipfp.writestr(TESTFN, data)
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000190
191 data2 = ''
Brian Curtin0d654332011-04-19 21:15:55 -0500192 with zipfile.ZipFile(f, 'r') as zipfp:
193 with zipfp.open(TESTFN, 'rU') as zipopen:
194 for line in zipopen:
195 data2 += line
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000196
197 self.assertEqual(data, data2.replace('\n', '\r\n'))
198
199 def zip_readline_read_test(self, f, compression):
200 self.make_test_archive(f, compression)
201
202 # Read the ZIP archive
Brian Curtin0d654332011-04-19 21:15:55 -0500203 with zipfile.ZipFile(f, "r") as zipfp:
204 with zipfp.open(TESTFN) as zipopen:
205 data = ''
206 while True:
207 read = zipopen.readline()
208 if not read:
209 break
210 data += read
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000211
Brian Curtin0d654332011-04-19 21:15:55 -0500212 read = zipopen.read(100)
213 if not read:
214 break
215 data += read
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000216
217 self.assertEqual(data, self.data)
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000218
Ezio Melottid5a23e32009-07-15 17:07:04 +0000219 def zip_readline_test(self, f, compression):
220 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000221
222 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000223 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin0d654332011-04-19 21:15:55 -0500224 with zipfp.open(TESTFN) as zipopen:
225 for line in self.line_gen:
226 linedata = zipopen.readline()
227 self.assertEqual(linedata, line + '\n')
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000228
Ezio Melottid5a23e32009-07-15 17:07:04 +0000229 def zip_readlines_test(self, f, compression):
230 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000231
232 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000233 with zipfile.ZipFile(f, "r") as zipfp:
Brian Curtin0d654332011-04-19 21:15:55 -0500234 with zipfp.open(TESTFN) as zo:
235 ziplines = zo.readlines()
236 for line, zipline in zip(self.line_gen, ziplines):
237 self.assertEqual(zipline, line + '\n')
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000238
Ezio Melottid5a23e32009-07-15 17:07:04 +0000239 def zip_iterlines_test(self, f, compression):
240 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000241
242 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000243 with zipfile.ZipFile(f, "r") as zipfp:
244 for line, zipline in zip(self.line_gen, zipfp.open(TESTFN)):
245 self.assertEqual(zipline, line + '\n')
Tim Petersea5962f2007-03-12 18:07:52 +0000246
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000247 def test_readline_read_stored(self):
248 # Issue #7610: calls to readline() interleaved with calls to read().
249 for f in (TESTFN2, TemporaryFile(), StringIO()):
250 self.zip_readline_read_test(f, zipfile.ZIP_STORED)
251
Ezio Melottid5a23e32009-07-15 17:07:04 +0000252 def test_readline_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000253 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000254 self.zip_readline_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000255
Ezio Melottid5a23e32009-07-15 17:07:04 +0000256 def test_readlines_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000257 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000258 self.zip_readlines_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000259
Ezio Melottid5a23e32009-07-15 17:07:04 +0000260 def test_iterlines_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000261 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000262 self.zip_iterlines_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000263
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000264 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000265 def test_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000266 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000267 self.zip_test(f, zipfile.ZIP_DEFLATED)
Raymond Hettingerc0fac962003-06-27 22:25:03 +0000268
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000269 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000270 def test_open_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000271 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000272 self.zip_open_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000273
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000274 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000275 def test_random_open_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000276 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000277 self.zip_random_open_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000278
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000279 @skipUnless(zlib, "requires zlib")
Antoine Pitrou94c33eb2010-01-27 20:59:50 +0000280 def test_readline_read_deflated(self):
281 # Issue #7610: calls to readline() interleaved with calls to read().
282 for f in (TESTFN2, TemporaryFile(), StringIO()):
283 self.zip_readline_read_test(f, zipfile.ZIP_DEFLATED)
284
285 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000286 def test_readline_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000287 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000288 self.zip_readline_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000289
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000290 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000291 def test_readlines_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000292 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000293 self.zip_readlines_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000294
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000295 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000296 def test_iterlines_deflated(self):
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000297 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000298 self.zip_iterlines_test(f, zipfile.ZIP_DEFLATED)
Tim Petersea5962f2007-03-12 18:07:52 +0000299
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000300 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000301 def test_low_compression(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000302 """Check for cases where compressed data is larger than original."""
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000303 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000304 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
305 zipfp.writestr("strfile", '12')
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000306
Ezio Melottie7a0cc22009-07-04 14:58:27 +0000307 # Get an open object for strfile
Ezio Melotti569e61f2009-12-30 06:14:51 +0000308 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_DEFLATED) as zipfp:
Brian Curtin0d654332011-04-19 21:15:55 -0500309 with zipfp.open("strfile") as openobj:
310 self.assertEqual(openobj.read(1), '1')
311 self.assertEqual(openobj.read(1), '2')
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000312
Ezio Melottid5a23e32009-07-15 17:07:04 +0000313 def test_absolute_arcnames(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000314 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
315 zipfp.write(TESTFN, "/absolute")
Georg Brandl8f7c54e2006-02-20 08:40:38 +0000316
Ezio Melotti569e61f2009-12-30 06:14:51 +0000317 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
318 self.assertEqual(zipfp.namelist(), ["absolute"])
Tim Peters32cbc962006-02-20 21:42:18 +0000319
Ezio Melottid5a23e32009-07-15 17:07:04 +0000320 def test_append_to_zip_file(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000321 """Test appending to an existing zipfile."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000322 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
323 zipfp.write(TESTFN, TESTFN)
324
325 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
326 zipfp.writestr("strfile", self.data)
327 self.assertEqual(zipfp.namelist(), [TESTFN, "strfile"])
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000328
Ezio Melottid5a23e32009-07-15 17:07:04 +0000329 def test_append_to_non_zip_file(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000330 """Test appending to an existing file that is not a zipfile."""
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000331 # NOTE: this test fails if len(d) < 22 because of the first
332 # line "fpin.seek(-22, 2)" in _EndRecData
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000333 data = 'I am not a ZipFile!'*10
334 with open(TESTFN2, 'wb') as f:
335 f.write(data)
336
Ezio Melotti569e61f2009-12-30 06:14:51 +0000337 with zipfile.ZipFile(TESTFN2, "a", zipfile.ZIP_STORED) as zipfp:
338 zipfp.write(TESTFN, TESTFN)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000339
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000340 with open(TESTFN2, 'rb') as f:
341 f.seek(len(data))
342 with zipfile.ZipFile(f, "r") as zipfp:
343 self.assertEqual(zipfp.namelist(), [TESTFN])
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000344
R David Murray873c5832011-06-09 16:01:09 -0400345 def test_ignores_newline_at_end(self):
346 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
347 zipfp.write(TESTFN, TESTFN)
348 with open(TESTFN2, 'a') as f:
349 f.write("\r\n\00\00\00")
350 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
351 self.assertIsInstance(zipfp, zipfile.ZipFile)
352
353 def test_ignores_stuff_appended_past_comments(self):
354 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
355 zipfp.comment = b"this is a comment"
356 zipfp.write(TESTFN, TESTFN)
357 with open(TESTFN2, 'a') as f:
358 f.write("abcdef\r\n")
359 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
360 self.assertIsInstance(zipfp, zipfile.ZipFile)
361 self.assertEqual(zipfp.comment, b"this is a comment")
362
Ezio Melottid5a23e32009-07-15 17:07:04 +0000363 def test_write_default_name(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000364 """Check that calling ZipFile.write without arcname specified
365 produces the expected result."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000366 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
367 zipfp.write(TESTFN)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000368 self.assertEqual(zipfp.read(TESTFN), open(TESTFN).read())
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000369
Ezio Melotti1036a7f2009-09-12 14:43:43 +0000370 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000371 def test_per_file_compression(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000372 """Check that files within a Zip archive can have different
373 compression options."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000374 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
375 zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
376 zipfp.write(TESTFN, 'deflateme', zipfile.ZIP_DEFLATED)
377 sinfo = zipfp.getinfo('storeme')
378 dinfo = zipfp.getinfo('deflateme')
379 self.assertEqual(sinfo.compress_type, zipfile.ZIP_STORED)
380 self.assertEqual(dinfo.compress_type, zipfile.ZIP_DEFLATED)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000381
Ezio Melottid5a23e32009-07-15 17:07:04 +0000382 def test_write_to_readonly(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000383 """Check that trying to call write() on a readonly ZipFile object
384 raises a RuntimeError."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000385 with zipfile.ZipFile(TESTFN2, mode="w") as zipfp:
386 zipfp.writestr("somefile.txt", "bogus")
387
388 with zipfile.ZipFile(TESTFN2, mode="r") as zipfp:
389 self.assertRaises(RuntimeError, zipfp.write, TESTFN)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000390
Ezio Melottid5a23e32009-07-15 17:07:04 +0000391 def test_extract(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000392 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
393 for fpath, fdata in SMALL_TEST_DATA:
394 zipfp.writestr(fpath, fdata)
Georg Brandl62416bc2008-01-07 18:47:44 +0000395
Ezio Melotti569e61f2009-12-30 06:14:51 +0000396 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
397 for fpath, fdata in SMALL_TEST_DATA:
398 writtenfile = zipfp.extract(fpath)
Georg Brandl62416bc2008-01-07 18:47:44 +0000399
Ezio Melotti569e61f2009-12-30 06:14:51 +0000400 # make sure it was written to the right place
Gregory P. Smith608cc452013-02-01 11:40:18 -0800401 correctfile = os.path.join(os.getcwd(), fpath)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000402 correctfile = os.path.normpath(correctfile)
Georg Brandl62416bc2008-01-07 18:47:44 +0000403
Ezio Melotti569e61f2009-12-30 06:14:51 +0000404 self.assertEqual(writtenfile, correctfile)
Georg Brandl62416bc2008-01-07 18:47:44 +0000405
Ezio Melotti569e61f2009-12-30 06:14:51 +0000406 # make sure correct data is in correct file
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000407 self.assertEqual(fdata, open(writtenfile, "rb").read())
Ezio Melotti569e61f2009-12-30 06:14:51 +0000408 os.remove(writtenfile)
Georg Brandl62416bc2008-01-07 18:47:44 +0000409
410 # remove the test file subdirectories
411 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
412
Ezio Melottid5a23e32009-07-15 17:07:04 +0000413 def test_extract_all(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000414 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
415 for fpath, fdata in SMALL_TEST_DATA:
416 zipfp.writestr(fpath, fdata)
Georg Brandl62416bc2008-01-07 18:47:44 +0000417
Ezio Melotti569e61f2009-12-30 06:14:51 +0000418 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
419 zipfp.extractall()
420 for fpath, fdata in SMALL_TEST_DATA:
Gregory P. Smith608cc452013-02-01 11:40:18 -0800421 outfile = os.path.join(os.getcwd(), fpath)
Georg Brandl62416bc2008-01-07 18:47:44 +0000422
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000423 self.assertEqual(fdata, open(outfile, "rb").read())
Ezio Melotti569e61f2009-12-30 06:14:51 +0000424 os.remove(outfile)
Georg Brandl62416bc2008-01-07 18:47:44 +0000425
426 # remove the test file subdirectories
427 shutil.rmtree(os.path.join(os.getcwd(), 'ziptest2dir'))
428
Gregory P. Smith608cc452013-02-01 11:40:18 -0800429 def check_file(self, filename, content):
430 self.assertTrue(os.path.isfile(filename))
431 with open(filename, 'rb') as f:
432 self.assertEqual(f.read(), content)
433
Serhiy Storchakadb03e6b2013-05-08 21:52:31 +0300434 @skipUnless(TESTFN_UNICODE, "No Unicode filesystem semantics on this platform.")
Serhiy Storchaka6fa83f92013-04-13 12:28:17 +0300435 def test_extract_unicode_filenames(self):
436 fnames = [u'foo.txt', os.path.basename(TESTFN_UNICODE)]
437 content = 'Test for unicode filename'
438 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
439 for fname in fnames:
440 zipfp.writestr(fname, content)
441
442 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
443 for fname in fnames:
444 writtenfile = zipfp.extract(fname)
445
446 # make sure it was written to the right place
447 correctfile = os.path.join(os.getcwd(), fname)
448 correctfile = os.path.normpath(correctfile)
449 self.assertEqual(writtenfile, correctfile)
450
451 self.check_file(writtenfile, content)
452 os.remove(writtenfile)
453
Gregory P. Smith608cc452013-02-01 11:40:18 -0800454 def test_extract_hackers_arcnames(self):
455 hacknames = [
456 ('../foo/bar', 'foo/bar'),
457 ('foo/../bar', 'foo/bar'),
458 ('foo/../../bar', 'foo/bar'),
459 ('foo/bar/..', 'foo/bar'),
460 ('./../foo/bar', 'foo/bar'),
461 ('/foo/bar', 'foo/bar'),
462 ('/foo/../bar', 'foo/bar'),
463 ('/foo/../../bar', 'foo/bar'),
Gregory P. Smith608cc452013-02-01 11:40:18 -0800464 ]
465 if os.path.sep == '\\':
466 hacknames.extend([
467 (r'..\foo\bar', 'foo/bar'),
468 (r'..\/foo\/bar', 'foo/bar'),
469 (r'foo/\..\/bar', 'foo/bar'),
470 (r'foo\/../\bar', 'foo/bar'),
471 (r'C:foo/bar', 'foo/bar'),
472 (r'C:/foo/bar', 'foo/bar'),
473 (r'C://foo/bar', 'foo/bar'),
474 (r'C:\foo\bar', 'foo/bar'),
Serhiy Storchaka13e56c72013-02-02 17:46:33 +0200475 (r'//conky/mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
476 (r'\\conky\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
Gregory P. Smith608cc452013-02-01 11:40:18 -0800477 (r'///conky/mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
478 (r'\\\conky\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
479 (r'//conky//mountpoint/foo/bar', 'conky/mountpoint/foo/bar'),
480 (r'\\conky\\mountpoint\foo\bar', 'conky/mountpoint/foo/bar'),
Serhiy Storchaka13e56c72013-02-02 17:46:33 +0200481 (r'//?/C:/foo/bar', '_/C_/foo/bar'),
482 (r'\\?\C:\foo\bar', '_/C_/foo/bar'),
Gregory P. Smith608cc452013-02-01 11:40:18 -0800483 (r'C:/../C:/foo/bar', 'C_/foo/bar'),
484 (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 +0200485 ('../../foo../../ba..r', 'foo/ba..r'),
486 ])
487 else: # Unix
488 hacknames.extend([
489 ('//foo/bar', 'foo/bar'),
490 ('../../foo../../ba..r', 'foo../ba..r'),
Serhiy Storchaka05fd7442013-02-02 18:34:57 +0200491 (r'foo/..\bar', r'foo/..\bar'),
Gregory P. Smith608cc452013-02-01 11:40:18 -0800492 ])
493
494 for arcname, fixedname in hacknames:
495 content = b'foobar' + arcname.encode()
496 with zipfile.ZipFile(TESTFN2, 'w', zipfile.ZIP_STORED) as zipfp:
Serhiy Storchaka05fd7442013-02-02 18:34:57 +0200497 zinfo = zipfile.ZipInfo()
498 # preserve backslashes
499 zinfo.filename = arcname
500 zinfo.external_attr = 0o600 << 16
501 zipfp.writestr(zinfo, content)
Gregory P. Smith608cc452013-02-01 11:40:18 -0800502
Serhiy Storchaka2a051fa2013-02-02 19:25:57 +0200503 arcname = arcname.replace(os.sep, "/")
Gregory P. Smith608cc452013-02-01 11:40:18 -0800504 targetpath = os.path.join('target', 'subdir', 'subsub')
505 correctfile = os.path.join(targetpath, *fixedname.split('/'))
506
507 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
508 writtenfile = zipfp.extract(arcname, targetpath)
Serhiy Storchaka13e56c72013-02-02 17:46:33 +0200509 self.assertEqual(writtenfile, correctfile,
510 msg="extract %r" % arcname)
Gregory P. Smith608cc452013-02-01 11:40:18 -0800511 self.check_file(correctfile, content)
512 shutil.rmtree('target')
513
514 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
515 zipfp.extractall(targetpath)
516 self.check_file(correctfile, content)
517 shutil.rmtree('target')
518
519 correctfile = os.path.join(os.getcwd(), *fixedname.split('/'))
520
521 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
522 writtenfile = zipfp.extract(arcname)
Serhiy Storchaka13e56c72013-02-02 17:46:33 +0200523 self.assertEqual(writtenfile, correctfile,
524 msg="extract %r" % arcname)
Gregory P. Smith608cc452013-02-01 11:40:18 -0800525 self.check_file(correctfile, content)
526 shutil.rmtree(fixedname.split('/')[0])
527
528 with zipfile.ZipFile(TESTFN2, 'r') as zipfp:
529 zipfp.extractall()
530 self.check_file(correctfile, content)
531 shutil.rmtree(fixedname.split('/')[0])
532
533 os.remove(TESTFN2)
534
Ronald Oussorendd25e862010-02-07 20:18:02 +0000535 def test_writestr_compression(self):
536 zipfp = zipfile.ZipFile(TESTFN2, "w")
537 zipfp.writestr("a.txt", "hello world", compress_type=zipfile.ZIP_STORED)
538 if zlib:
539 zipfp.writestr("b.txt", "hello world", compress_type=zipfile.ZIP_DEFLATED)
540
541 info = zipfp.getinfo('a.txt')
542 self.assertEqual(info.compress_type, zipfile.ZIP_STORED)
543
544 if zlib:
545 info = zipfp.getinfo('b.txt')
546 self.assertEqual(info.compress_type, zipfile.ZIP_DEFLATED)
547
548
Antoine Pitrou5fdfa3e2008-07-25 19:42:26 +0000549 def zip_test_writestr_permissions(self, f, compression):
550 # Make sure that writestr creates files with mode 0600,
551 # when it is passed a name rather than a ZipInfo instance.
552
Ezio Melottid5a23e32009-07-15 17:07:04 +0000553 self.make_test_archive(f, compression)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000554 with zipfile.ZipFile(f, "r") as zipfp:
555 zinfo = zipfp.getinfo('strfile')
556 self.assertEqual(zinfo.external_attr, 0600 << 16)
Antoine Pitrou5fdfa3e2008-07-25 19:42:26 +0000557
Ezio Melottid5a23e32009-07-15 17:07:04 +0000558 def test_writestr_permissions(self):
Antoine Pitrou5fdfa3e2008-07-25 19:42:26 +0000559 for f in (TESTFN2, TemporaryFile(), StringIO()):
560 self.zip_test_writestr_permissions(f, zipfile.ZIP_STORED)
561
Ezio Melotti569e61f2009-12-30 06:14:51 +0000562 def test_close(self):
563 """Check that the zipfile is closed after the 'with' block."""
564 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
565 for fpath, fdata in SMALL_TEST_DATA:
566 zipfp.writestr(fpath, fdata)
567 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
568 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
569
570 with zipfile.ZipFile(TESTFN2, "r") as zipfp:
571 self.assertTrue(zipfp.fp is not None, 'zipfp is not open')
572 self.assertTrue(zipfp.fp is None, 'zipfp is not closed')
573
574 def test_close_on_exception(self):
575 """Check that the zipfile is closed if an exception is raised in the
576 'with' block."""
577 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
578 for fpath, fdata in SMALL_TEST_DATA:
579 zipfp.writestr(fpath, fdata)
580
581 try:
582 with zipfile.ZipFile(TESTFN2, "r") as zipfp2:
583 raise zipfile.BadZipfile()
584 except zipfile.BadZipfile:
585 self.assertTrue(zipfp2.fp is None, 'zipfp is not closed')
586
Senthil Kumaranddd40312011-10-20 01:38:35 +0800587 def test_add_file_before_1980(self):
588 # Set atime and mtime to 1970-01-01
589 os.utime(TESTFN, (0, 0))
590 with zipfile.ZipFile(TESTFN2, "w") as zipfp:
591 self.assertRaises(ValueError, zipfp.write, TESTFN)
592
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000593 def tearDown(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000594 unlink(TESTFN)
595 unlink(TESTFN2)
596
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000597
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000598class TestZip64InSmallFiles(unittest.TestCase):
599 # These tests test the ZIP64 functionality without using large files,
600 # see test_zipfile64 for proper tests.
601
602 def setUp(self):
603 self._limit = zipfile.ZIP64_LIMIT
604 zipfile.ZIP64_LIMIT = 5
605
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000606 line_gen = ("Test of zipfile line %d." % i
607 for i in range(0, FIXEDTEST_SIZE))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000608 self.data = '\n'.join(line_gen)
609
610 # Make a source file with some lines
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000611 with open(TESTFN, "wb") as fp:
612 fp.write(self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000613
Ezio Melottid5a23e32009-07-15 17:07:04 +0000614 def large_file_exception_test(self, f, compression):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000615 with zipfile.ZipFile(f, "w", compression) as zipfp:
616 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000617 zipfp.write, TESTFN, "another.name")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000618
Ezio Melottid5a23e32009-07-15 17:07:04 +0000619 def large_file_exception_test2(self, f, compression):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000620 with zipfile.ZipFile(f, "w", compression) as zipfp:
621 self.assertRaises(zipfile.LargeZipFile,
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000622 zipfp.writestr, "another.name", self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000623
Ezio Melottid5a23e32009-07-15 17:07:04 +0000624 def test_large_file_exception(self):
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000625 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000626 self.large_file_exception_test(f, zipfile.ZIP_STORED)
627 self.large_file_exception_test2(f, zipfile.ZIP_STORED)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000628
Ezio Melottid5a23e32009-07-15 17:07:04 +0000629 def zip_test(self, f, compression):
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000630 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000631 with zipfile.ZipFile(f, "w", compression, allowZip64=True) as zipfp:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000632 zipfp.write(TESTFN, "another.name")
Ezio Melotti569e61f2009-12-30 06:14:51 +0000633 zipfp.write(TESTFN, TESTFN)
634 zipfp.writestr("strfile", self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000635
636 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +0000637 with zipfile.ZipFile(f, "r", compression) as zipfp:
638 self.assertEqual(zipfp.read(TESTFN), self.data)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000639 self.assertEqual(zipfp.read("another.name"), self.data)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000640 self.assertEqual(zipfp.read("strfile"), self.data)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000641
Ezio Melotti569e61f2009-12-30 06:14:51 +0000642 # Print the ZIP directory
643 fp = StringIO()
644 stdout = sys.stdout
645 try:
646 sys.stdout = fp
647 zipfp.printdir()
648 finally:
649 sys.stdout = stdout
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000650
Ezio Melotti569e61f2009-12-30 06:14:51 +0000651 directory = fp.getvalue()
652 lines = directory.splitlines()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000653 self.assertEqual(len(lines), 4) # Number of files + header
Tim Petersa608bb22006-06-15 18:06:29 +0000654
Ezio Melottiaa980582010-01-23 23:04:36 +0000655 self.assertIn('File Name', lines[0])
656 self.assertIn('Modified', lines[0])
657 self.assertIn('Size', lines[0])
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000658
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000659 fn, date, time_, size = lines[1].split()
660 self.assertEqual(fn, 'another.name')
661 self.assertTrue(time.strptime(date, '%Y-%m-%d'))
662 self.assertTrue(time.strptime(time_, '%H:%M:%S'))
663 self.assertEqual(size, str(len(self.data)))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000664
Ezio Melotti569e61f2009-12-30 06:14:51 +0000665 # Check the namelist
666 names = zipfp.namelist()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000667 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)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000671
Ezio Melotti569e61f2009-12-30 06:14:51 +0000672 # Check infolist
673 infos = zipfp.infolist()
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000674 names = [i.filename for i in infos]
675 self.assertEqual(len(names), 3)
Ezio Melottiaa980582010-01-23 23:04:36 +0000676 self.assertIn(TESTFN, names)
677 self.assertIn("another.name", names)
678 self.assertIn("strfile", names)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000679 for i in infos:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000680 self.assertEqual(i.file_size, len(self.data))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000681
Ezio Melotti569e61f2009-12-30 06:14:51 +0000682 # check getinfo
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000683 for nm in (TESTFN, "another.name", "strfile"):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000684 info = zipfp.getinfo(nm)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000685 self.assertEqual(info.filename, nm)
686 self.assertEqual(info.file_size, len(self.data))
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000687
Ezio Melotti569e61f2009-12-30 06:14:51 +0000688 # Check that testzip doesn't raise an exception
689 zipfp.testzip()
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000690
Ezio Melottid5a23e32009-07-15 17:07:04 +0000691 def test_stored(self):
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000692 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000693 self.zip_test(f, zipfile.ZIP_STORED)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000694
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000695 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +0000696 def test_deflated(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000697 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000698 self.zip_test(f, zipfile.ZIP_DEFLATED)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000699
Ezio Melottid5a23e32009-07-15 17:07:04 +0000700 def test_absolute_arcnames(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000701 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED,
702 allowZip64=True) as zipfp:
703 zipfp.write(TESTFN, "/absolute")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000704
Ezio Melotti569e61f2009-12-30 06:14:51 +0000705 with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_STORED) as zipfp:
706 self.assertEqual(zipfp.namelist(), ["absolute"])
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000707
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000708 def tearDown(self):
709 zipfile.ZIP64_LIMIT = self._limit
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000710 unlink(TESTFN)
711 unlink(TESTFN2)
712
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000713
714class PyZipFileTests(unittest.TestCase):
Ezio Melottid5a23e32009-07-15 17:07:04 +0000715 def test_write_pyfile(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000716 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
717 fn = __file__
718 if fn.endswith('.pyc') or fn.endswith('.pyo'):
719 fn = fn[:-1]
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000720
Ezio Melotti569e61f2009-12-30 06:14:51 +0000721 zipfp.writepy(fn)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000722
Ezio Melotti569e61f2009-12-30 06:14:51 +0000723 bn = os.path.basename(fn)
Ezio Melottiaa980582010-01-23 23:04:36 +0000724 self.assertNotIn(bn, zipfp.namelist())
Ezio Melotti569e61f2009-12-30 06:14:51 +0000725 self.assertTrue(bn + 'o' in zipfp.namelist() or
726 bn + 'c' in zipfp.namelist())
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000727
Ezio Melotti569e61f2009-12-30 06:14:51 +0000728 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
729 fn = __file__
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000730 if fn.endswith(('.pyc', '.pyo')):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000731 fn = fn[:-1]
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000732
Ezio Melotti569e61f2009-12-30 06:14:51 +0000733 zipfp.writepy(fn, "testpackage")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000734
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000735 bn = "%s/%s" % ("testpackage", os.path.basename(fn))
Ezio Melottiaa980582010-01-23 23:04:36 +0000736 self.assertNotIn(bn, zipfp.namelist())
Ezio Melotti569e61f2009-12-30 06:14:51 +0000737 self.assertTrue(bn + 'o' in zipfp.namelist() or
738 bn + 'c' in zipfp.namelist())
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000739
Ezio Melottid5a23e32009-07-15 17:07:04 +0000740 def test_write_python_package(self):
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000741 import email
742 packagedir = os.path.dirname(email.__file__)
743
Ezio Melotti569e61f2009-12-30 06:14:51 +0000744 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
745 zipfp.writepy(packagedir)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000746
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000747 # Check for a couple of modules at different levels of the
748 # hierarchy
Ezio Melotti569e61f2009-12-30 06:14:51 +0000749 names = zipfp.namelist()
750 self.assertTrue('email/__init__.pyo' in names or
751 'email/__init__.pyc' in names)
752 self.assertTrue('email/mime/text.pyo' in names or
753 'email/mime/text.pyc' in names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000754
Ezio Melottid5a23e32009-07-15 17:07:04 +0000755 def test_write_python_directory(self):
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000756 os.mkdir(TESTFN2)
757 try:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000758 with open(os.path.join(TESTFN2, "mod1.py"), "w") as fp:
Ezio Melotti763f1e82009-12-31 13:27:41 +0000759 fp.write("print(42)\n")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000760
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000761 with open(os.path.join(TESTFN2, "mod2.py"), "w") as fp:
Ezio Melotti763f1e82009-12-31 13:27:41 +0000762 fp.write("print(42 * 42)\n")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000763
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000764 with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
765 fp.write("bla bla bla\n")
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000766
767 zipfp = zipfile.PyZipFile(TemporaryFile(), "w")
768 zipfp.writepy(TESTFN2)
769
770 names = zipfp.namelist()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000771 self.assertTrue('mod1.pyc' in names or 'mod1.pyo' in names)
772 self.assertTrue('mod2.pyc' in names or 'mod2.pyo' in names)
Ezio Melottiaa980582010-01-23 23:04:36 +0000773 self.assertNotIn('mod2.txt', names)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000774
775 finally:
776 shutil.rmtree(TESTFN2)
777
Ezio Melottid5a23e32009-07-15 17:07:04 +0000778 def test_write_non_pyfile(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000779 with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000780 open(TESTFN, 'w').write('most definitely not a python file')
Ezio Melotti569e61f2009-12-30 06:14:51 +0000781 self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
782 os.remove(TESTFN)
Ronald Oussoren143cefb2006-06-15 08:14:18 +0000783
784
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000785class OtherTests(unittest.TestCase):
Antoine Pitroue1436d12010-08-12 15:25:51 +0000786 zips_with_bad_crc = {
787 zipfile.ZIP_STORED: (
788 b'PK\003\004\024\0\0\0\0\0 \213\212;:r'
789 b'\253\377\f\0\0\0\f\0\0\0\005\0\0\000af'
790 b'ilehello,AworldP'
791 b'K\001\002\024\003\024\0\0\0\0\0 \213\212;:'
792 b'r\253\377\f\0\0\0\f\0\0\0\005\0\0\0\0'
793 b'\0\0\0\0\0\0\0\200\001\0\0\0\000afi'
794 b'lePK\005\006\0\0\0\0\001\0\001\0003\000'
795 b'\0\0/\0\0\0\0\0'),
796 zipfile.ZIP_DEFLATED: (
797 b'PK\x03\x04\x14\x00\x00\x00\x08\x00n}\x0c=FA'
798 b'KE\x10\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
799 b'ile\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\xc9\xa0'
800 b'=\x13\x00PK\x01\x02\x14\x03\x14\x00\x00\x00\x08\x00n'
801 b'}\x0c=FAKE\x10\x00\x00\x00n\x00\x00\x00\x05'
802 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
803 b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
804 b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00'),
805 }
806
Ezio Melottid5a23e32009-07-15 17:07:04 +0000807 def test_unicode_filenames(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +0000808 with zipfile.ZipFile(TESTFN, "w") as zf:
809 zf.writestr(u"foo.txt", "Test for unicode filename")
810 zf.writestr(u"\xf6.txt", "Test for unicode filename")
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000811 self.assertIsInstance(zf.infolist()[0].filename, unicode)
Ezio Melotti569e61f2009-12-30 06:14:51 +0000812
813 with zipfile.ZipFile(TESTFN, "r") as zf:
814 self.assertEqual(zf.filelist[0].filename, "foo.txt")
815 self.assertEqual(zf.filelist[1].filename, u"\xf6.txt")
Martin v. Löwis471617d2008-05-05 17:16:58 +0000816
Ezio Melottid5a23e32009-07-15 17:07:04 +0000817 def test_create_non_existent_file_for_append(self):
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000818 if os.path.exists(TESTFN):
819 os.unlink(TESTFN)
Tim Petersea5962f2007-03-12 18:07:52 +0000820
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000821 filename = 'testfile.txt'
822 content = 'hello, world. this is some content.'
Tim Petersea5962f2007-03-12 18:07:52 +0000823
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000824 try:
Ezio Melotti569e61f2009-12-30 06:14:51 +0000825 with zipfile.ZipFile(TESTFN, 'a') as zf:
826 zf.writestr(filename, content)
Ezio Melotti6cbfc122009-07-10 20:25:56 +0000827 except IOError:
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000828 self.fail('Could not append data to a non-existent zip file.')
829
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000830 self.assertTrue(os.path.exists(TESTFN))
Martin v. Löwis84f6de92007-02-13 10:10:39 +0000831
Ezio Melotti569e61f2009-12-30 06:14:51 +0000832 with zipfile.ZipFile(TESTFN, 'r') as zf:
833 self.assertEqual(zf.read(filename), content)
Tim Petersea5962f2007-03-12 18:07:52 +0000834
Ezio Melottid5a23e32009-07-15 17:07:04 +0000835 def test_close_erroneous_file(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000836 # This test checks that the ZipFile constructor closes the file object
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000837 # it opens if there's an error in the file. If it doesn't, the
838 # traceback holds a reference to the ZipFile object and, indirectly,
839 # the file object.
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000840 # On Windows, this causes the os.unlink() call to fail because the
841 # underlying file is still open. This is SF bug #412214.
842 #
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000843 with open(TESTFN, "w") as fp:
844 fp.write("this is not a legal zip file\n")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000845 try:
846 zf = zipfile.ZipFile(TESTFN)
847 except zipfile.BadZipfile:
Collin Winter04a51ec2007-03-29 02:28:16 +0000848 pass
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000849
Ezio Melottid5a23e32009-07-15 17:07:04 +0000850 def test_is_zip_erroneous_file(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000851 """Check that is_zipfile() correctly identifies non-zip files."""
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000852 # - passing a filename
853 with open(TESTFN, "w") as fp:
854 fp.write("this is not a legal zip file\n")
Tim Petersea5962f2007-03-12 18:07:52 +0000855 chk = zipfile.is_zipfile(TESTFN)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000856 self.assertFalse(chk)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000857 # - passing a file object
858 with open(TESTFN, "rb") as fp:
859 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000860 self.assertTrue(not chk)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000861 # - passing a file-like object
862 fp = StringIO()
863 fp.write("this is not a legal zip file\n")
864 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000865 self.assertTrue(not chk)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000866 fp.seek(0, 0)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000867 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000868 self.assertTrue(not chk)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000869
Serhiy Storchaka0be506a2013-01-31 15:26:55 +0200870 def test_damaged_zipfile(self):
871 """Check that zipfiles with missing bytes at the end raise BadZipFile."""
872 # - Create a valid zip file
873 fp = io.BytesIO()
874 with zipfile.ZipFile(fp, mode="w") as zipf:
875 zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
876 zipfiledata = fp.getvalue()
877
878 # - Now create copies of it missing the last N bytes and make sure
879 # a BadZipFile exception is raised when we try to open it
880 for N in range(len(zipfiledata)):
881 fp = io.BytesIO(zipfiledata[:N])
882 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, fp)
883
Ezio Melottid5a23e32009-07-15 17:07:04 +0000884 def test_is_zip_valid_file(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000885 """Check that is_zipfile() correctly identifies zip files."""
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000886 # - passing a filename
Ezio Melotti569e61f2009-12-30 06:14:51 +0000887 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
888 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Tim Petersea5962f2007-03-12 18:07:52 +0000889 chk = zipfile.is_zipfile(TESTFN)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000890 self.assertTrue(chk)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000891 # - passing a file object
892 with open(TESTFN, "rb") as fp:
893 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000894 self.assertTrue(chk)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000895 fp.seek(0, 0)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000896 zip_contents = fp.read()
897 # - passing a file-like object
898 fp = StringIO()
899 fp.write(zip_contents)
900 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000901 self.assertTrue(chk)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000902 fp.seek(0, 0)
Antoine Pitrou6f193e02008-12-27 15:43:12 +0000903 chk = zipfile.is_zipfile(fp)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000904 self.assertTrue(chk)
Martin v. Löwis3eb76482007-03-06 10:41:24 +0000905
Ezio Melottid5a23e32009-07-15 17:07:04 +0000906 def test_non_existent_file_raises_IOError(self):
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000907 # make sure we don't raise an AttributeError when a partially-constructed
908 # ZipFile instance is finalized; this tests for regression on SF tracker
909 # bug #403871.
910
911 # The bug we're testing for caused an AttributeError to be raised
912 # when a ZipFile instance was created for a file that did not
913 # exist; the .fp member was not initialized but was needed by the
914 # __del__() method. Since the AttributeError is in the __del__(),
915 # it is ignored, but the user should be sufficiently annoyed by
916 # the message on the output that regression will be noticed
917 # quickly.
918 self.assertRaises(IOError, zipfile.ZipFile, TESTFN)
919
Amaury Forgeot d'Arc3e5b0272009-07-28 22:15:30 +0000920 def test_empty_file_raises_BadZipFile(self):
Brian Curtin0d654332011-04-19 21:15:55 -0500921 with open(TESTFN, 'w') as f:
922 pass
Amaury Forgeot d'Arc3e5b0272009-07-28 22:15:30 +0000923 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN)
924
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000925 with open(TESTFN, 'w') as fp:
926 fp.write("short file")
Amaury Forgeot d'Arc3e5b0272009-07-28 22:15:30 +0000927 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN)
928
Ezio Melottid5a23e32009-07-15 17:07:04 +0000929 def test_closed_zip_raises_RuntimeError(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000930 """Verify that testzip() doesn't swallow inappropriate exceptions."""
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000931 data = StringIO()
Ezio Melotti569e61f2009-12-30 06:14:51 +0000932 with zipfile.ZipFile(data, mode="w") as zipf:
933 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000934
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200935 # This is correct; calling .read on a closed ZipFile should raise
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000936 # a RuntimeError, and so should calling .testzip. An earlier
937 # version of .testzip would swallow this exception (and any other)
938 # and report that the first file in the archive was corrupt.
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000939 self.assertRaises(RuntimeError, zipf.read, "foo.txt")
940 self.assertRaises(RuntimeError, zipf.open, "foo.txt")
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +0000941 self.assertRaises(RuntimeError, zipf.testzip)
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000942 self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000943 open(TESTFN, 'w').write('zipfile test data')
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000944 self.assertRaises(RuntimeError, zipf.write, TESTFN)
945
Ezio Melottid5a23e32009-07-15 17:07:04 +0000946 def test_bad_constructor_mode(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000947 """Check that bad modes passed to ZipFile constructor are caught."""
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000948 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "q")
949
Ezio Melottid5a23e32009-07-15 17:07:04 +0000950 def test_bad_open_mode(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000951 """Check that bad modes passed to ZipFile.open are caught."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000952 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
953 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
954
955 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000956 # read the data to make sure the file is there
Ezio Melotti569e61f2009-12-30 06:14:51 +0000957 zipf.read("foo.txt")
958 self.assertRaises(RuntimeError, zipf.open, "foo.txt", "q")
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000959
Ezio Melottid5a23e32009-07-15 17:07:04 +0000960 def test_read0(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000961 """Check that calling read(0) on a ZipExtFile object returns an empty
962 string and doesn't advance file pointer."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000963 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
964 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
965 # read the data to make sure the file is there
Brian Curtin0d654332011-04-19 21:15:55 -0500966 with zipf.open("foo.txt") as f:
967 for i in xrange(FIXEDTEST_SIZE):
968 self.assertEqual(f.read(0), '')
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000969
Brian Curtin0d654332011-04-19 21:15:55 -0500970 self.assertEqual(f.read(), "O, for a Muse of Fire!")
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000971
Ezio Melottid5a23e32009-07-15 17:07:04 +0000972 def test_open_non_existent_item(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000973 """Check that attempting to call open() for an item that doesn't
974 exist in the archive raises a RuntimeError."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000975 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
976 self.assertRaises(KeyError, zipf.open, "foo.txt", "r")
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000977
Ezio Melottid5a23e32009-07-15 17:07:04 +0000978 def test_bad_compression_mode(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000979 """Check that bad compression methods passed to ZipFile.open are
980 caught."""
Georg Brandl4b3ab6f2007-07-12 09:59:22 +0000981 self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, "w", -1)
982
Ezio Melotti9e949722012-11-18 13:18:06 +0200983 def test_unsupported_compression(self):
984 # data is declared as shrunk, but actually deflated
985 data = (b'PK\x03\x04.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00'
986 b'\x00\x02\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00x\x03\x00PK\x01'
987 b'\x02.\x03.\x00\x00\x00\x01\x00\xe4C\xa1@\x00\x00\x00\x00\x02\x00\x00'
988 b'\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
989 b'\x80\x01\x00\x00\x00\x00xPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00'
990 b'/\x00\x00\x00!\x00\x00\x00\x00\x00')
991 with zipfile.ZipFile(io.BytesIO(data), 'r') as zipf:
992 self.assertRaises(NotImplementedError, zipf.open, 'x')
993
Ezio Melottid5a23e32009-07-15 17:07:04 +0000994 def test_null_byte_in_filename(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +0000995 """Check that a filename containing a null byte is properly
996 terminated."""
Ezio Melotti569e61f2009-12-30 06:14:51 +0000997 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
998 zipf.writestr("foo.txt\x00qqq", "O, for a Muse of Fire!")
999 self.assertEqual(zipf.namelist(), ['foo.txt'])
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00001000
Ezio Melottid5a23e32009-07-15 17:07:04 +00001001 def test_struct_sizes(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001002 """Check that ZIP internal structure sizes are calculated correctly."""
Martin v. Löwis8c436412008-07-03 12:51:14 +00001003 self.assertEqual(zipfile.sizeEndCentDir, 22)
1004 self.assertEqual(zipfile.sizeCentralDir, 46)
1005 self.assertEqual(zipfile.sizeEndCentDir64, 56)
1006 self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
1007
Ezio Melottid5a23e32009-07-15 17:07:04 +00001008 def test_comments(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001009 """Check that comments on the archive are handled properly."""
Martin v. Löwis8c436412008-07-03 12:51:14 +00001010
1011 # check default comment is empty
Ezio Melotti569e61f2009-12-30 06:14:51 +00001012 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1013 self.assertEqual(zipf.comment, '')
1014 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1015
1016 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
1017 self.assertEqual(zipf.comment, '')
Martin v. Löwis8c436412008-07-03 12:51:14 +00001018
1019 # check a simple short comment
1020 comment = 'Bravely taking to his feet, he beat a very brave retreat.'
Ezio Melotti569e61f2009-12-30 06:14:51 +00001021 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1022 zipf.comment = comment
1023 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1024 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
1025 self.assertEqual(zipf.comment, comment)
Martin v. Löwis8c436412008-07-03 12:51:14 +00001026
1027 # check a comment of max length
1028 comment2 = ''.join(['%d' % (i**3 % 10) for i in xrange((1 << 16)-1)])
Ezio Melotti569e61f2009-12-30 06:14:51 +00001029 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1030 zipf.comment = comment2
1031 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1032
1033 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
1034 self.assertEqual(zipf.comment, comment2)
Martin v. Löwis8c436412008-07-03 12:51:14 +00001035
1036 # check a comment that is too long is truncated
Ezio Melotti569e61f2009-12-30 06:14:51 +00001037 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1038 zipf.comment = comment2 + 'oops'
1039 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1040 with zipfile.ZipFile(TESTFN, mode="r") as zipf:
1041 self.assertEqual(zipf.comment, comment2)
Martin v. Löwis8c436412008-07-03 12:51:14 +00001042
R David Murray3f4ccba2012-04-12 18:42:47 -04001043 def test_change_comment_in_empty_archive(self):
1044 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1045 self.assertFalse(zipf.filelist)
1046 zipf.comment = b"this is a comment"
1047 with zipfile.ZipFile(TESTFN, "r") as zipf:
1048 self.assertEqual(zipf.comment, b"this is a comment")
1049
1050 def test_change_comment_in_nonempty_archive(self):
1051 with zipfile.ZipFile(TESTFN, "w", zipfile.ZIP_STORED) as zipf:
1052 zipf.writestr("foo.txt", "O, for a Muse of Fire!")
1053 with zipfile.ZipFile(TESTFN, "a", zipfile.ZIP_STORED) as zipf:
1054 self.assertTrue(zipf.filelist)
1055 zipf.comment = b"this is a comment"
1056 with zipfile.ZipFile(TESTFN, "r") as zipf:
1057 self.assertEqual(zipf.comment, b"this is a comment")
1058
Antoine Pitroue1436d12010-08-12 15:25:51 +00001059 def check_testzip_with_bad_crc(self, compression):
1060 """Tests that files with bad CRCs return their name from testzip."""
1061 zipdata = self.zips_with_bad_crc[compression]
1062
1063 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1064 # testzip returns the name of the first corrupt file, or None
1065 self.assertEqual('afile', zipf.testzip())
1066
1067 def test_testzip_with_bad_crc_stored(self):
1068 self.check_testzip_with_bad_crc(zipfile.ZIP_STORED)
1069
1070 @skipUnless(zlib, "requires zlib")
1071 def test_testzip_with_bad_crc_deflated(self):
1072 self.check_testzip_with_bad_crc(zipfile.ZIP_DEFLATED)
1073
1074 def check_read_with_bad_crc(self, compression):
1075 """Tests that files with bad CRCs raise a BadZipfile exception when read."""
1076 zipdata = self.zips_with_bad_crc[compression]
1077
1078 # Using ZipFile.read()
1079 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1080 self.assertRaises(zipfile.BadZipfile, zipf.read, 'afile')
1081
1082 # Using ZipExtFile.read()
1083 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1084 with zipf.open('afile', 'r') as corrupt_file:
1085 self.assertRaises(zipfile.BadZipfile, corrupt_file.read)
1086
1087 # Same with small reads (in order to exercise the buffering logic)
1088 with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
1089 with zipf.open('afile', 'r') as corrupt_file:
1090 corrupt_file.MIN_READ_SIZE = 2
1091 with self.assertRaises(zipfile.BadZipfile):
1092 while corrupt_file.read(2):
1093 pass
1094
1095 def test_read_with_bad_crc_stored(self):
1096 self.check_read_with_bad_crc(zipfile.ZIP_STORED)
1097
1098 @skipUnless(zlib, "requires zlib")
1099 def test_read_with_bad_crc_deflated(self):
1100 self.check_read_with_bad_crc(zipfile.ZIP_DEFLATED)
1101
Antoine Pitroue4195e82010-09-12 14:56:27 +00001102 def check_read_return_size(self, compression):
1103 # Issue #9837: ZipExtFile.read() shouldn't return more bytes
1104 # than requested.
1105 for test_size in (1, 4095, 4096, 4097, 16384):
1106 file_size = test_size + 1
1107 junk = b''.join(struct.pack('B', randint(0, 255))
1108 for x in range(file_size))
1109 with zipfile.ZipFile(io.BytesIO(), "w", compression) as zipf:
1110 zipf.writestr('foo', junk)
1111 with zipf.open('foo', 'r') as fp:
1112 buf = fp.read(test_size)
1113 self.assertEqual(len(buf), test_size)
1114
1115 def test_read_return_size_stored(self):
1116 self.check_read_return_size(zipfile.ZIP_STORED)
1117
1118 @skipUnless(zlib, "requires zlib")
1119 def test_read_return_size_deflated(self):
1120 self.check_read_return_size(zipfile.ZIP_DEFLATED)
1121
Georg Brandl86e0c892010-11-26 07:22:28 +00001122 def test_empty_zipfile(self):
1123 # Check that creating a file in 'w' or 'a' mode and closing without
1124 # adding any files to the archives creates a valid empty ZIP file
Brian Curtin0d654332011-04-19 21:15:55 -05001125 with zipfile.ZipFile(TESTFN, mode="w") as zipf:
1126 pass
Georg Brandl86e0c892010-11-26 07:22:28 +00001127 try:
1128 zipf = zipfile.ZipFile(TESTFN, mode="r")
Éric Araujo67843b32011-02-02 17:03:38 +00001129 except zipfile.BadZipfile:
Georg Brandl86e0c892010-11-26 07:22:28 +00001130 self.fail("Unable to create empty ZIP file in 'w' mode")
1131
Brian Curtin0d654332011-04-19 21:15:55 -05001132 with zipfile.ZipFile(TESTFN, mode="a") as zipf:
1133 pass
Georg Brandl86e0c892010-11-26 07:22:28 +00001134 try:
1135 zipf = zipfile.ZipFile(TESTFN, mode="r")
1136 except:
1137 self.fail("Unable to create empty ZIP file in 'a' mode")
1138
1139 def test_open_empty_file(self):
1140 # Issue 1710703: Check that opening a file with less than 22 bytes
1141 # raises a BadZipfile exception (rather than the previously unhelpful
1142 # IOError)
Brian Curtin0d654332011-04-19 21:15:55 -05001143 with open(TESTFN, 'w') as f:
1144 pass
Georg Brandl86e0c892010-11-26 07:22:28 +00001145 self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN, 'r')
1146
Senthil Kumaranddd40312011-10-20 01:38:35 +08001147 def test_create_zipinfo_before_1980(self):
1148 self.assertRaises(ValueError,
1149 zipfile.ZipInfo, 'seventies', (1979, 1, 1, 0, 0, 0))
1150
Collin Winter04a51ec2007-03-29 02:28:16 +00001151 def tearDown(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001152 unlink(TESTFN)
1153 unlink(TESTFN2)
1154
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001155
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001156class DecryptionTests(unittest.TestCase):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001157 """Check that ZIP decryption works. Since the library does not
1158 support encryption at the moment, we use a pre-generated encrypted
1159 ZIP file."""
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001160
1161 data = (
1162 'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
1163 '\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
1164 '\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
1165 'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
1166 '\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
1167 '\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
1168 '\x00\x00L\x00\x00\x00\x00\x00' )
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001169 data2 = (
1170 'PK\x03\x04\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02'
1171 '\x00\x00\x04\x00\x15\x00zeroUT\t\x00\x03\xd6\x8b\x92G\xda\x8b\x92GUx\x04'
1172 '\x00\xe8\x03\xe8\x03\xc7<M\xb5a\xceX\xa3Y&\x8b{oE\xd7\x9d\x8c\x98\x02\xc0'
1173 'PK\x07\x08xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00PK\x01\x02\x17\x03'
1174 '\x14\x00\t\x00\x08\x00\xcf}38xu\xaa\xb2\x14\x00\x00\x00\x00\x02\x00\x00'
1175 '\x04\x00\r\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00ze'
1176 'roUT\x05\x00\x03\xd6\x8b\x92GUx\x00\x00PK\x05\x06\x00\x00\x00\x00\x01'
1177 '\x00\x01\x00?\x00\x00\x00[\x00\x00\x00\x00\x00' )
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001178
1179 plain = 'zipfile.py encryption test'
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001180 plain2 = '\x00'*512
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001181
1182 def setUp(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001183 with open(TESTFN, "wb") as fp:
1184 fp.write(self.data)
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001185 self.zip = zipfile.ZipFile(TESTFN, "r")
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001186 with open(TESTFN2, "wb") as fp:
1187 fp.write(self.data2)
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001188 self.zip2 = zipfile.ZipFile(TESTFN2, "r")
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001189
1190 def tearDown(self):
1191 self.zip.close()
1192 os.unlink(TESTFN)
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001193 self.zip2.close()
1194 os.unlink(TESTFN2)
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001195
Ezio Melottid5a23e32009-07-15 17:07:04 +00001196 def test_no_password(self):
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001197 # Reading the encrypted file without password
1198 # must generate a RunTime exception
1199 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001200 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001201
Ezio Melottid5a23e32009-07-15 17:07:04 +00001202 def test_bad_password(self):
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001203 self.zip.setpassword("perl")
1204 self.assertRaises(RuntimeError, self.zip.read, "test.txt")
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001205 self.zip2.setpassword("perl")
1206 self.assertRaises(RuntimeError, self.zip2.read, "zero")
Tim Petersea5962f2007-03-12 18:07:52 +00001207
Ezio Melotti1036a7f2009-09-12 14:43:43 +00001208 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +00001209 def test_good_password(self):
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001210 self.zip.setpassword("python")
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001211 self.assertEqual(self.zip.read("test.txt"), self.plain)
Gregory P. Smith0c63fc22008-01-20 01:21:03 +00001212 self.zip2.setpassword("12345")
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001213 self.assertEqual(self.zip2.read("zero"), self.plain2)
Martin v. Löwisc6d626e2007-02-13 09:49:38 +00001214
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001215
1216class TestsWithRandomBinaryFiles(unittest.TestCase):
1217 def setUp(self):
1218 datacount = randint(16, 64)*1024 + randint(1, 1024)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001219 self.data = ''.join(struct.pack('<f', random()*randint(-1000, 1000))
Ezio Melotti763f1e82009-12-31 13:27:41 +00001220 for i in xrange(datacount))
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001221
1222 # Make a source file with some lines
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001223 with open(TESTFN, "wb") as fp:
1224 fp.write(self.data)
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00001225
Collin Winter04a51ec2007-03-29 02:28:16 +00001226 def tearDown(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001227 unlink(TESTFN)
1228 unlink(TESTFN2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001229
Ezio Melottid5a23e32009-07-15 17:07:04 +00001230 def make_test_archive(self, f, compression):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001231 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001232 with zipfile.ZipFile(f, "w", compression) as zipfp:
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001233 zipfp.write(TESTFN, "another.name")
Ezio Melotti569e61f2009-12-30 06:14:51 +00001234 zipfp.write(TESTFN, TESTFN)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001235
Ezio Melottid5a23e32009-07-15 17:07:04 +00001236 def zip_test(self, f, compression):
1237 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001238
1239 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001240 with zipfile.ZipFile(f, "r", compression) as zipfp:
1241 testdata = zipfp.read(TESTFN)
1242 self.assertEqual(len(testdata), len(self.data))
1243 self.assertEqual(testdata, self.data)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001244 self.assertEqual(zipfp.read("another.name"), self.data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001245
Ezio Melottid5a23e32009-07-15 17:07:04 +00001246 def test_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001247 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001248 self.zip_test(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +00001249
Antoine Pitroue1436d12010-08-12 15:25:51 +00001250 @skipUnless(zlib, "requires zlib")
1251 def test_deflated(self):
1252 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1253 self.zip_test(f, zipfile.ZIP_DEFLATED)
1254
Ezio Melottid5a23e32009-07-15 17:07:04 +00001255 def zip_open_test(self, f, compression):
1256 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001257
1258 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001259 with zipfile.ZipFile(f, "r", compression) as zipfp:
1260 zipdata1 = []
Brian Curtin0d654332011-04-19 21:15:55 -05001261 with zipfp.open(TESTFN) as zipopen1:
1262 while True:
1263 read_data = zipopen1.read(256)
1264 if not read_data:
1265 break
1266 zipdata1.append(read_data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001267
Ezio Melotti569e61f2009-12-30 06:14:51 +00001268 zipdata2 = []
Brian Curtin0d654332011-04-19 21:15:55 -05001269 with zipfp.open("another.name") as zipopen2:
1270 while True:
1271 read_data = zipopen2.read(256)
1272 if not read_data:
1273 break
1274 zipdata2.append(read_data)
Tim Petersea5962f2007-03-12 18:07:52 +00001275
Ezio Melotti569e61f2009-12-30 06:14:51 +00001276 testdata1 = ''.join(zipdata1)
1277 self.assertEqual(len(testdata1), len(self.data))
1278 self.assertEqual(testdata1, self.data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001279
Ezio Melotti569e61f2009-12-30 06:14:51 +00001280 testdata2 = ''.join(zipdata2)
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001281 self.assertEqual(len(testdata2), len(self.data))
1282 self.assertEqual(testdata2, self.data)
Tim Petersea5962f2007-03-12 18:07:52 +00001283
Ezio Melottid5a23e32009-07-15 17:07:04 +00001284 def test_open_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001285 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001286 self.zip_open_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001287
Antoine Pitroue1436d12010-08-12 15:25:51 +00001288 @skipUnless(zlib, "requires zlib")
1289 def test_open_deflated(self):
1290 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1291 self.zip_open_test(f, zipfile.ZIP_DEFLATED)
1292
Ezio Melottid5a23e32009-07-15 17:07:04 +00001293 def zip_random_open_test(self, f, compression):
1294 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001295
1296 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001297 with zipfile.ZipFile(f, "r", compression) as zipfp:
1298 zipdata1 = []
Brian Curtin0d654332011-04-19 21:15:55 -05001299 with zipfp.open(TESTFN) as zipopen1:
1300 while True:
1301 read_data = zipopen1.read(randint(1, 1024))
1302 if not read_data:
1303 break
1304 zipdata1.append(read_data)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001305
Ezio Melotti569e61f2009-12-30 06:14:51 +00001306 testdata = ''.join(zipdata1)
1307 self.assertEqual(len(testdata), len(self.data))
1308 self.assertEqual(testdata, self.data)
Tim Petersea5962f2007-03-12 18:07:52 +00001309
Ezio Melottid5a23e32009-07-15 17:07:04 +00001310 def test_random_open_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001311 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001312 self.zip_random_open_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001313
Antoine Pitroue1436d12010-08-12 15:25:51 +00001314 @skipUnless(zlib, "requires zlib")
1315 def test_random_open_deflated(self):
1316 for f in (TESTFN2, TemporaryFile(), io.BytesIO()):
1317 self.zip_random_open_test(f, zipfile.ZIP_DEFLATED)
1318
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001319
Ezio Melotti1036a7f2009-09-12 14:43:43 +00001320@skipUnless(zlib, "requires zlib")
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001321class TestsWithMultipleOpens(unittest.TestCase):
1322 def setUp(self):
1323 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001324 with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_DEFLATED) as zipfp:
1325 zipfp.writestr('ones', '1'*FIXEDTEST_SIZE)
1326 zipfp.writestr('twos', '2'*FIXEDTEST_SIZE)
Tim Petersea5962f2007-03-12 18:07:52 +00001327
Ezio Melottid5a23e32009-07-15 17:07:04 +00001328 def test_same_file(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001329 # Verify that (when the ZipFile is in control of creating file objects)
1330 # multiple open() calls can be made without interfering with each other.
Ezio Melotti569e61f2009-12-30 06:14:51 +00001331 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
1332 zopen1 = zipf.open('ones')
1333 zopen2 = zipf.open('ones')
1334 data1 = zopen1.read(500)
1335 data2 = zopen2.read(500)
1336 data1 += zopen1.read(500)
1337 data2 += zopen2.read(500)
1338 self.assertEqual(data1, data2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001339
Ezio Melottid5a23e32009-07-15 17:07:04 +00001340 def test_different_file(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001341 # Verify that (when the ZipFile is in control of creating file objects)
1342 # multiple open() calls can be made without interfering with each other.
Ezio Melotti569e61f2009-12-30 06:14:51 +00001343 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin0d654332011-04-19 21:15:55 -05001344 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1345 data1 = zopen1.read(500)
1346 data2 = zopen2.read(500)
1347 data1 += zopen1.read(500)
1348 data2 += zopen2.read(500)
Ezio Melotti569e61f2009-12-30 06:14:51 +00001349 self.assertEqual(data1, '1'*FIXEDTEST_SIZE)
1350 self.assertEqual(data2, '2'*FIXEDTEST_SIZE)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001351
Ezio Melottid5a23e32009-07-15 17:07:04 +00001352 def test_interleaved(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001353 # Verify that (when the ZipFile is in control of creating file objects)
1354 # multiple open() calls can be made without interfering with each other.
Ezio Melotti569e61f2009-12-30 06:14:51 +00001355 with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
Brian Curtin0d654332011-04-19 21:15:55 -05001356 with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
1357 data1 = zopen1.read(500)
1358 data2 = zopen2.read(500)
1359 data1 += zopen1.read(500)
1360 data2 += zopen2.read(500)
Ezio Melotti569e61f2009-12-30 06:14:51 +00001361 self.assertEqual(data1, '1'*FIXEDTEST_SIZE)
1362 self.assertEqual(data2, '2'*FIXEDTEST_SIZE)
Tim Petersea5962f2007-03-12 18:07:52 +00001363
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001364 def tearDown(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001365 unlink(TESTFN2)
1366
Tim Petersea5962f2007-03-12 18:07:52 +00001367
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001368class TestWithDirectory(unittest.TestCase):
1369 def setUp(self):
1370 os.mkdir(TESTFN2)
1371
Ezio Melottid5a23e32009-07-15 17:07:04 +00001372 def test_extract_dir(self):
Ezio Melotti569e61f2009-12-30 06:14:51 +00001373 with zipfile.ZipFile(findfile("zipdir.zip")) as zipf:
1374 zipf.extractall(TESTFN2)
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001375 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a")))
1376 self.assertTrue(os.path.isdir(os.path.join(TESTFN2, "a", "b")))
1377 self.assertTrue(os.path.exists(os.path.join(TESTFN2, "a", "b", "c")))
1378
Ezio Melottid5a23e32009-07-15 17:07:04 +00001379 def test_bug_6050(self):
Martin v. Löwis0b09c422009-05-24 19:30:52 +00001380 # Extraction should succeed if directories already exist
1381 os.mkdir(os.path.join(TESTFN2, "a"))
Ezio Melottid5a23e32009-07-15 17:07:04 +00001382 self.test_extract_dir()
Martin v. Löwis0b09c422009-05-24 19:30:52 +00001383
Ezio Melottid5a23e32009-07-15 17:07:04 +00001384 def test_store_dir(self):
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001385 os.mkdir(os.path.join(TESTFN2, "x"))
1386 zipf = zipfile.ZipFile(TESTFN, "w")
1387 zipf.write(os.path.join(TESTFN2, "x"), "x")
1388 self.assertTrue(zipf.filelist[0].filename.endswith("x/"))
1389
1390 def tearDown(self):
1391 shutil.rmtree(TESTFN2)
1392 if os.path.exists(TESTFN):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001393 unlink(TESTFN)
Martin v. Löwis0dfcfc82009-01-24 14:00:33 +00001394
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001395
1396class UniversalNewlineTests(unittest.TestCase):
1397 def setUp(self):
Ezio Melotti6d6b53c2009-12-31 13:00:43 +00001398 self.line_gen = ["Test of zipfile line %d." % i
1399 for i in xrange(FIXEDTEST_SIZE)]
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001400 self.seps = ('\r', '\r\n', '\n')
1401 self.arcdata, self.arcfiles = {}, {}
1402 for n, s in enumerate(self.seps):
1403 self.arcdata[s] = s.join(self.line_gen) + s
1404 self.arcfiles[s] = '%s-%d' % (TESTFN, n)
Brett Cannon6cef0762007-05-25 20:17:15 +00001405 open(self.arcfiles[s], "wb").write(self.arcdata[s])
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001406
Ezio Melottid5a23e32009-07-15 17:07:04 +00001407 def make_test_archive(self, f, compression):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001408 # Create the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001409 with zipfile.ZipFile(f, "w", compression) as zipfp:
1410 for fn in self.arcfiles.values():
1411 zipfp.write(fn, fn)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001412
Ezio Melottid5a23e32009-07-15 17:07:04 +00001413 def read_test(self, f, compression):
1414 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001415
1416 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001417 with zipfile.ZipFile(f, "r") as zipfp:
1418 for sep, fn in self.arcfiles.items():
Brian Curtin0d654332011-04-19 21:15:55 -05001419 with zipfp.open(fn, "rU") as fp:
1420 zipdata = fp.read()
Ezio Melotti569e61f2009-12-30 06:14:51 +00001421 self.assertEqual(self.arcdata[sep], zipdata)
Tim Petersea5962f2007-03-12 18:07:52 +00001422
Antoine Pitrou94c33eb2010-01-27 20:59:50 +00001423 def readline_read_test(self, f, compression):
1424 self.make_test_archive(f, compression)
1425
1426 # Read the ZIP archive
1427 zipfp = zipfile.ZipFile(f, "r")
1428 for sep, fn in self.arcfiles.items():
Brian Curtin0d654332011-04-19 21:15:55 -05001429 with zipfp.open(fn, "rU") as zipopen:
1430 data = ''
1431 while True:
1432 read = zipopen.readline()
1433 if not read:
1434 break
1435 data += read
Antoine Pitrou94c33eb2010-01-27 20:59:50 +00001436
Brian Curtin0d654332011-04-19 21:15:55 -05001437 read = zipopen.read(5)
1438 if not read:
1439 break
1440 data += read
Antoine Pitrou94c33eb2010-01-27 20:59:50 +00001441
1442 self.assertEqual(data, self.arcdata['\n'])
1443
1444 zipfp.close()
1445
Ezio Melottid5a23e32009-07-15 17:07:04 +00001446 def readline_test(self, f, compression):
1447 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001448
1449 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001450 with zipfile.ZipFile(f, "r") as zipfp:
1451 for sep, fn in self.arcfiles.items():
Brian Curtin0d654332011-04-19 21:15:55 -05001452 with zipfp.open(fn, "rU") as zipopen:
1453 for line in self.line_gen:
1454 linedata = zipopen.readline()
1455 self.assertEqual(linedata, line + '\n')
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001456
Ezio Melottid5a23e32009-07-15 17:07:04 +00001457 def readlines_test(self, f, compression):
1458 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001459
1460 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001461 with zipfile.ZipFile(f, "r") as zipfp:
1462 for sep, fn in self.arcfiles.items():
Brian Curtin0d654332011-04-19 21:15:55 -05001463 with zipfp.open(fn, "rU") as fp:
1464 ziplines = fp.readlines()
Ezio Melotti569e61f2009-12-30 06:14:51 +00001465 for line, zipline in zip(self.line_gen, ziplines):
1466 self.assertEqual(zipline, line + '\n')
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001467
Ezio Melottid5a23e32009-07-15 17:07:04 +00001468 def iterlines_test(self, f, compression):
1469 self.make_test_archive(f, compression)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001470
1471 # Read the ZIP archive
Ezio Melotti569e61f2009-12-30 06:14:51 +00001472 with zipfile.ZipFile(f, "r") as zipfp:
1473 for sep, fn in self.arcfiles.items():
1474 for line, zipline in zip(self.line_gen, zipfp.open(fn, "rU")):
1475 self.assertEqual(zipline, line + '\n')
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001476
Ezio Melottid5a23e32009-07-15 17:07:04 +00001477 def test_read_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001478 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001479 self.read_test(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +00001480
Antoine Pitrou94c33eb2010-01-27 20:59:50 +00001481 def test_readline_read_stored(self):
1482 # Issue #7610: calls to readline() interleaved with calls to read().
1483 for f in (TESTFN2, TemporaryFile(), StringIO()):
1484 self.readline_read_test(f, zipfile.ZIP_STORED)
1485
Ezio Melottid5a23e32009-07-15 17:07:04 +00001486 def test_readline_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.readline_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001489
Ezio Melottid5a23e32009-07-15 17:07:04 +00001490 def test_readlines_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001491 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001492 self.readlines_test(f, zipfile.ZIP_STORED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001493
Ezio Melottid5a23e32009-07-15 17:07:04 +00001494 def test_iterlines_stored(self):
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001495 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001496 self.iterlines_test(f, zipfile.ZIP_STORED)
Tim Petersea5962f2007-03-12 18:07:52 +00001497
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001498 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +00001499 def test_read_deflated(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001500 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001501 self.read_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001502
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001503 @skipUnless(zlib, "requires zlib")
Antoine Pitrou94c33eb2010-01-27 20:59:50 +00001504 def test_readline_read_deflated(self):
1505 # Issue #7610: calls to readline() interleaved with calls to read().
1506 for f in (TESTFN2, TemporaryFile(), StringIO()):
1507 self.readline_read_test(f, zipfile.ZIP_DEFLATED)
1508
1509 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +00001510 def test_readline_deflated(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001511 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001512 self.readline_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001513
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001514 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +00001515 def test_readlines_deflated(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001516 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001517 self.readlines_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001518
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001519 @skipUnless(zlib, "requires zlib")
Ezio Melottid5a23e32009-07-15 17:07:04 +00001520 def test_iterlines_deflated(self):
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001521 for f in (TESTFN2, TemporaryFile(), StringIO()):
Ezio Melottid5a23e32009-07-15 17:07:04 +00001522 self.iterlines_test(f, zipfile.ZIP_DEFLATED)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001523
1524 def tearDown(self):
1525 for sep, fn in self.arcfiles.items():
1526 os.remove(fn)
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001527 unlink(TESTFN)
1528 unlink(TESTFN2)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001529
1530
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001531def test_main():
Tim Petersea5962f2007-03-12 18:07:52 +00001532 run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
1533 PyZipFileTests, DecryptionTests, TestsWithMultipleOpens,
Ezio Melotti6cbfc122009-07-10 20:25:56 +00001534 TestWithDirectory, UniversalNewlineTests,
1535 TestsWithRandomBinaryFiles)
Martin v. Löwis3eb76482007-03-06 10:41:24 +00001536
Johannes Gijsbers3caf9c12004-08-19 15:11:50 +00001537if __name__ == "__main__":
1538 test_main()