blob: 2e2297b3d594d197a79e7f6dbfcffdad338bc974 [file] [log] [blame]
Just van Rossum52e14d62002-12-30 22:08:05 +00001import sys
2import os
3import marshal
4import imp
5import struct
6import time
Neal Norwitzb155b622006-01-23 07:52:13 +00007import unittest
Just van Rossum52e14d62002-12-30 22:08:05 +00008
Benjamin Petersonee8712c2008-05-20 21:35:26 +00009from test import support
Just van Rossum52e14d62002-12-30 22:08:05 +000010
Ezio Melotti78ea2022009-09-12 18:41:20 +000011from zipfile import ZipFile, ZipInfo, ZIP_STORED, ZIP_DEFLATED
12
Just van Rossum52e14d62002-12-30 22:08:05 +000013import zipimport
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014import linecache
15import doctest
16import inspect
Guido van Rossum34d19282007-08-09 01:03:29 +000017import io
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000018from traceback import extract_tb, extract_stack, print_tb
Brett Cannon638ce072013-06-12 15:57:01 -040019
20test_src = """\
21def get_name():
22 return __name__
23def get_file():
24 return __file__
25"""
26test_co = compile(test_src, "<???>", "exec")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000027raise_src = 'def do_raise(): raise TypeError\n'
Just van Rossum52e14d62002-12-30 22:08:05 +000028
Antoine Pitrou5136ac02012-01-13 18:52:16 +010029def make_pyc(co, mtime, size):
Just van Rossum52e14d62002-12-30 22:08:05 +000030 data = marshal.dumps(co)
Jack Jansen472e7db2003-01-08 16:37:03 +000031 if type(mtime) is type(0.0):
Tim Petersf2715e02003-02-19 02:35:07 +000032 # Mac mtimes need a bit of special casing
33 if mtime < 0x7fffffff:
34 mtime = int(mtime)
35 else:
Guido van Rossume2a383d2007-01-15 16:59:06 +000036 mtime = int(-0x100000000 + int(mtime))
Antoine Pitrou5136ac02012-01-13 18:52:16 +010037 pyc = imp.get_magic() + struct.pack("<ii", int(mtime), size & 0xFFFFFFFF) + data
Just van Rossum52e14d62002-12-30 22:08:05 +000038 return pyc
39
Tim Peters68f2d002006-01-23 22:19:24 +000040def module_path_to_dotted_name(path):
41 return path.replace(os.sep, '.')
42
Just van Rossum52e14d62002-12-30 22:08:05 +000043NOW = time.time()
Antoine Pitrou5136ac02012-01-13 18:52:16 +010044test_pyc = make_pyc(test_co, NOW, len(test_src))
Just van Rossum52e14d62002-12-30 22:08:05 +000045
46
Just van Rossum52e14d62002-12-30 22:08:05 +000047TESTMOD = "ziptestmodule"
48TESTPACK = "ziptestpackage"
Just van Rossumd35c6db2003-01-02 12:55:48 +000049TESTPACK2 = "ziptestpackage2"
Skip Montanaro7a98be22007-08-16 14:35:24 +000050TEMP_ZIP = os.path.abspath("junk95142.zip")
Just van Rossum52e14d62002-12-30 22:08:05 +000051
Barry Warsaw28a691b2010-04-17 00:19:56 +000052pyc_file = imp.cache_from_source(TESTMOD + '.py')
53pyc_ext = ('.pyc' if __debug__ else '.pyo')
54
Ezio Melotti78ea2022009-09-12 18:41:20 +000055
Brett Cannon638ce072013-06-12 15:57:01 -040056class ImportHooksBaseTestCase(unittest.TestCase):
57
58 def setUp(self):
59 self.path = sys.path[:]
60 self.meta_path = sys.meta_path[:]
61 self.path_hooks = sys.path_hooks[:]
62 sys.path_importer_cache.clear()
63 self.modules_before = support.modules_setup()
64
65 def tearDown(self):
66 sys.path[:] = self.path
67 sys.meta_path[:] = self.meta_path
68 sys.path_hooks[:] = self.path_hooks
69 sys.path_importer_cache.clear()
70 support.modules_cleanup(*self.modules_before)
71
72
Just van Rossum52e14d62002-12-30 22:08:05 +000073class UncompressedZipImportTestCase(ImportHooksBaseTestCase):
74
75 compression = ZIP_STORED
76
77 def setUp(self):
78 # We're reusing the zip archive path, so we must clear the
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000079 # cached directory info and linecache
80 linecache.clearcache()
Just van Rossum52e14d62002-12-30 22:08:05 +000081 zipimport._zip_directory_cache.clear()
82 ImportHooksBaseTestCase.setUp(self)
83
Thomas Heller354e3d92003-07-22 18:10:15 +000084 def doTest(self, expected_ext, files, *modules, **kw):
Just van Rossum52e14d62002-12-30 22:08:05 +000085 z = ZipFile(TEMP_ZIP, "w")
86 try:
87 for name, (mtime, data) in files.items():
88 zinfo = ZipInfo(name, time.localtime(mtime))
89 zinfo.compress_type = self.compression
90 z.writestr(zinfo, data)
91 z.close()
Thomas Heller354e3d92003-07-22 18:10:15 +000092
93 stuff = kw.get("stuff", None)
94 if stuff is not None:
95 # Prepend 'stuff' to the start of the zipfile
Barry Warsaw28a691b2010-04-17 00:19:56 +000096 with open(TEMP_ZIP, "rb") as f:
97 data = f.read()
98 with open(TEMP_ZIP, "wb") as f:
99 f.write(stuff)
100 f.write(data)
Thomas Heller354e3d92003-07-22 18:10:15 +0000101
Just van Rossum52e14d62002-12-30 22:08:05 +0000102 sys.path.insert(0, TEMP_ZIP)
103
104 mod = __import__(".".join(modules), globals(), locals(),
105 ["__dummy__"])
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000106
107 call = kw.get('call')
108 if call is not None:
109 call(mod)
110
Just van Rossum9a3129c2003-01-03 11:18:56 +0000111 if expected_ext:
112 file = mod.get_file()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000113 self.assertEqual(file, os.path.join(TEMP_ZIP,
114 *modules) + expected_ext)
Just van Rossum52e14d62002-12-30 22:08:05 +0000115 finally:
116 z.close()
117 os.remove(TEMP_ZIP)
118
119 def testAFakeZlib(self):
120 #
121 # This could cause a stack overflow before: importing zlib.py
122 # from a compressed archive would cause zlib to be imported
123 # which would find zlib.py in the archive, which would... etc.
124 #
125 # This test *must* be executed first: it must be the first one
126 # to trigger zipimport to import zlib (zipimport caches the
127 # zlib.decompress function object, after which the problem being
128 # tested here wouldn't be a problem anymore...
129 # (Hence the 'A' in the test method name: to make it the first
130 # item in a list sorted by name, like unittest.makeSuite() does.)
131 #
Just van Rossum59498542003-11-18 23:00:55 +0000132 # This test fails on platforms on which the zlib module is
133 # statically linked, but the problem it tests for can't
134 # occur in that case (builtin modules are always found first),
135 # so we'll simply skip it then. Bug #765456.
136 #
137 if "zlib" in sys.builtin_module_names:
138 return
Just van Rossum52e14d62002-12-30 22:08:05 +0000139 if "zlib" in sys.modules:
140 del sys.modules["zlib"]
141 files = {"zlib.py": (NOW, test_src)}
142 try:
143 self.doTest(".py", files, "zlib")
144 except ImportError:
145 if self.compression != ZIP_DEFLATED:
146 self.fail("expected test to not raise ImportError")
147 else:
148 if self.compression != ZIP_STORED:
149 self.fail("expected test to raise ImportError")
150
151 def testPy(self):
152 files = {TESTMOD + ".py": (NOW, test_src)}
153 self.doTest(".py", files, TESTMOD)
154
155 def testPyc(self):
156 files = {TESTMOD + pyc_ext: (NOW, test_pyc)}
157 self.doTest(pyc_ext, files, TESTMOD)
158
159 def testBoth(self):
160 files = {TESTMOD + ".py": (NOW, test_src),
161 TESTMOD + pyc_ext: (NOW, test_pyc)}
162 self.doTest(pyc_ext, files, TESTMOD)
163
Just van Rossum9a3129c2003-01-03 11:18:56 +0000164 def testEmptyPy(self):
165 files = {TESTMOD + ".py": (NOW, "")}
166 self.doTest(None, files, TESTMOD)
167
Just van Rossum52e14d62002-12-30 22:08:05 +0000168 def testBadMagic(self):
169 # make pyc magic word invalid, forcing loading from .py
Guido van Rossum254348e2007-11-21 19:29:53 +0000170 badmagic_pyc = bytearray(test_pyc)
Guido van Rossumad8d3002007-08-03 18:40:49 +0000171 badmagic_pyc[0] ^= 0x04 # flip an arbitrary bit
Just van Rossum52e14d62002-12-30 22:08:05 +0000172 files = {TESTMOD + ".py": (NOW, test_src),
173 TESTMOD + pyc_ext: (NOW, badmagic_pyc)}
174 self.doTest(".py", files, TESTMOD)
175
176 def testBadMagic2(self):
177 # make pyc magic word invalid, causing an ImportError
Guido van Rossum254348e2007-11-21 19:29:53 +0000178 badmagic_pyc = bytearray(test_pyc)
Guido van Rossumad8d3002007-08-03 18:40:49 +0000179 badmagic_pyc[0] ^= 0x04 # flip an arbitrary bit
Just van Rossum52e14d62002-12-30 22:08:05 +0000180 files = {TESTMOD + pyc_ext: (NOW, badmagic_pyc)}
181 try:
182 self.doTest(".py", files, TESTMOD)
183 except ImportError:
184 pass
185 else:
186 self.fail("expected ImportError; import from bad pyc")
187
188 def testBadMTime(self):
Guido van Rossum254348e2007-11-21 19:29:53 +0000189 badtime_pyc = bytearray(test_pyc)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000190 # flip the second bit -- not the first as that one isn't stored in the
191 # .py's mtime in the zip archive.
192 badtime_pyc[7] ^= 0x02
Just van Rossum52e14d62002-12-30 22:08:05 +0000193 files = {TESTMOD + ".py": (NOW, test_src),
194 TESTMOD + pyc_ext: (NOW, badtime_pyc)}
195 self.doTest(".py", files, TESTMOD)
196
197 def testPackage(self):
198 packdir = TESTPACK + os.sep
199 files = {packdir + "__init__" + pyc_ext: (NOW, test_pyc),
200 packdir + TESTMOD + pyc_ext: (NOW, test_pyc)}
201 self.doTest(pyc_ext, files, TESTPACK, TESTMOD)
202
203 def testDeepPackage(self):
204 packdir = TESTPACK + os.sep
Just van Rossumd35c6db2003-01-02 12:55:48 +0000205 packdir2 = packdir + TESTPACK2 + os.sep
Just van Rossum52e14d62002-12-30 22:08:05 +0000206 files = {packdir + "__init__" + pyc_ext: (NOW, test_pyc),
207 packdir2 + "__init__" + pyc_ext: (NOW, test_pyc),
208 packdir2 + TESTMOD + pyc_ext: (NOW, test_pyc)}
Just van Rossumd35c6db2003-01-02 12:55:48 +0000209 self.doTest(pyc_ext, files, TESTPACK, TESTPACK2, TESTMOD)
Just van Rossum52e14d62002-12-30 22:08:05 +0000210
Neal Norwitzb155b622006-01-23 07:52:13 +0000211 def testZipImporterMethods(self):
212 packdir = TESTPACK + os.sep
213 packdir2 = packdir + TESTPACK2 + os.sep
214 files = {packdir + "__init__" + pyc_ext: (NOW, test_pyc),
215 packdir2 + "__init__" + pyc_ext: (NOW, test_pyc),
216 packdir2 + TESTMOD + pyc_ext: (NOW, test_pyc)}
217
218 z = ZipFile(TEMP_ZIP, "w")
219 try:
220 for name, (mtime, data) in files.items():
221 zinfo = ZipInfo(name, time.localtime(mtime))
222 zinfo.compress_type = self.compression
Serhiy Storchaka0e6b7b52013-02-16 17:43:45 +0200223 zinfo.comment = b"spam"
Neal Norwitzb155b622006-01-23 07:52:13 +0000224 z.writestr(zinfo, data)
225 z.close()
226
227 zi = zipimport.zipimporter(TEMP_ZIP)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000228 self.assertEqual(zi.archive, TEMP_ZIP)
229 self.assertEqual(zi.is_package(TESTPACK), True)
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000230 mod = zi.load_module(TESTPACK)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000231 self.assertEqual(zi.get_filename(TESTPACK), mod.__file__)
Tim Petersbc29c1a2006-01-23 21:28:42 +0000232
R David Murraya9719052012-03-12 21:16:33 -0400233 existing_pack_path = __import__(TESTPACK).__path__[0]
234 expected_path_path = os.path.join(TEMP_ZIP, TESTPACK)
235 self.assertEqual(existing_pack_path, expected_path_path)
236
Ezio Melottib3aedd42010-11-20 19:04:17 +0000237 self.assertEqual(zi.is_package(packdir + '__init__'), False)
238 self.assertEqual(zi.is_package(packdir + TESTPACK2), True)
239 self.assertEqual(zi.is_package(packdir2 + TESTMOD), False)
Neal Norwitzb155b622006-01-23 07:52:13 +0000240
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000241 mod_path = packdir2 + TESTMOD
242 mod_name = module_path_to_dotted_name(mod_path)
Georg Brandl89fad142010-03-14 10:23:39 +0000243 __import__(mod_name)
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000244 mod = sys.modules[mod_name]
Ezio Melottib3aedd42010-11-20 19:04:17 +0000245 self.assertEqual(zi.get_source(TESTPACK), None)
246 self.assertEqual(zi.get_source(mod_path), None)
247 self.assertEqual(zi.get_filename(mod_path), mod.__file__)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000248 # To pass in the module name instead of the path, we must use the
249 # right importer
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000250 loader = mod.__loader__
Ezio Melottib3aedd42010-11-20 19:04:17 +0000251 self.assertEqual(loader.get_source(mod_name), None)
252 self.assertEqual(loader.get_filename(mod_name), mod.__file__)
Christian Heimes7f044312008-01-06 17:05:40 +0000253
254 # test prefix and archivepath members
255 zi2 = zipimport.zipimporter(TEMP_ZIP + os.sep + TESTPACK)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000256 self.assertEqual(zi2.archive, TEMP_ZIP)
257 self.assertEqual(zi2.prefix, TESTPACK + os.sep)
Neal Norwitzb155b622006-01-23 07:52:13 +0000258 finally:
259 z.close()
260 os.remove(TEMP_ZIP)
261
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000262 def testZipImporterMethodsInSubDirectory(self):
263 packdir = TESTPACK + os.sep
264 packdir2 = packdir + TESTPACK2 + os.sep
265 files = {packdir2 + "__init__" + pyc_ext: (NOW, test_pyc),
266 packdir2 + TESTMOD + pyc_ext: (NOW, test_pyc)}
267
268 z = ZipFile(TEMP_ZIP, "w")
269 try:
270 for name, (mtime, data) in files.items():
271 zinfo = ZipInfo(name, time.localtime(mtime))
272 zinfo.compress_type = self.compression
Serhiy Storchaka0e6b7b52013-02-16 17:43:45 +0200273 zinfo.comment = b"eggs"
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000274 z.writestr(zinfo, data)
275 z.close()
276
277 zi = zipimport.zipimporter(TEMP_ZIP + os.sep + packdir)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000278 self.assertEqual(zi.archive, TEMP_ZIP)
279 self.assertEqual(zi.prefix, packdir)
280 self.assertEqual(zi.is_package(TESTPACK2), True)
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000281 mod = zi.load_module(TESTPACK2)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000282 self.assertEqual(zi.get_filename(TESTPACK2), mod.__file__)
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000283
Ezio Melottib3aedd42010-11-20 19:04:17 +0000284 self.assertEqual(
Barry Warsaw28a691b2010-04-17 00:19:56 +0000285 zi.is_package(TESTPACK2 + os.sep + '__init__'), False)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000286 self.assertEqual(
Barry Warsaw28a691b2010-04-17 00:19:56 +0000287 zi.is_package(TESTPACK2 + os.sep + TESTMOD), False)
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000288
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000289 mod_path = TESTPACK2 + os.sep + TESTMOD
290 mod_name = module_path_to_dotted_name(mod_path)
Georg Brandl89fad142010-03-14 10:23:39 +0000291 __import__(mod_name)
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000292 mod = sys.modules[mod_name]
Ezio Melottib3aedd42010-11-20 19:04:17 +0000293 self.assertEqual(zi.get_source(TESTPACK2), None)
294 self.assertEqual(zi.get_source(mod_path), None)
295 self.assertEqual(zi.get_filename(mod_path), mod.__file__)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000296 # To pass in the module name instead of the path, we must use the
297 # right importer
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000298 loader = mod.__loader__
Ezio Melottib3aedd42010-11-20 19:04:17 +0000299 self.assertEqual(loader.get_source(mod_name), None)
300 self.assertEqual(loader.get_filename(mod_name), mod.__file__)
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000301 finally:
302 z.close()
303 os.remove(TEMP_ZIP)
304
Just van Rossum52e14d62002-12-30 22:08:05 +0000305 def testGetData(self):
306 z = ZipFile(TEMP_ZIP, "w")
307 z.compression = self.compression
308 try:
309 name = "testdata.dat"
Guido van Rossumad8d3002007-08-03 18:40:49 +0000310 data = bytes(x for x in range(256))
Just van Rossum52e14d62002-12-30 22:08:05 +0000311 z.writestr(name, data)
312 z.close()
313 zi = zipimport.zipimporter(TEMP_ZIP)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000314 self.assertEqual(data, zi.get_data(name))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000315 self.assertIn('zipimporter object', repr(zi))
Just van Rossum52e14d62002-12-30 22:08:05 +0000316 finally:
317 z.close()
318 os.remove(TEMP_ZIP)
319
320 def testImporterAttr(self):
321 src = """if 1: # indent hack
322 def get_file():
323 return __file__
Guido van Rossumad8d3002007-08-03 18:40:49 +0000324 if __loader__.get_data("some.data") != b"some data":
Collin Winter828f04a2007-08-31 00:04:24 +0000325 raise AssertionError("bad data")\n"""
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100326 pyc = make_pyc(compile(src, "<???>", "exec"), NOW, len(src))
Just van Rossum52e14d62002-12-30 22:08:05 +0000327 files = {TESTMOD + pyc_ext: (NOW, pyc),
328 "some.data": (NOW, "some data")}
329 self.doTest(pyc_ext, files, TESTMOD)
330
Thomas Heller354e3d92003-07-22 18:10:15 +0000331 def testImport_WithStuff(self):
332 # try importing from a zipfile which contains additional
333 # stuff at the beginning of the file
334 files = {TESTMOD + ".py": (NOW, test_src)}
335 self.doTest(".py", files, TESTMOD,
Guido van Rossum85825dc2007-08-27 17:03:28 +0000336 stuff=b"Some Stuff"*31)
Just van Rossum52e14d62002-12-30 22:08:05 +0000337
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000338 def assertModuleSource(self, module):
339 self.assertEqual(inspect.getsource(module), test_src)
340
341 def testGetSource(self):
342 files = {TESTMOD + ".py": (NOW, test_src)}
343 self.doTest(".py", files, TESTMOD, call=self.assertModuleSource)
344
345 def testGetCompiledSource(self):
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100346 pyc = make_pyc(compile(test_src, "<???>", "exec"), NOW, len(test_src))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000347 files = {TESTMOD + ".py": (NOW, test_src),
348 TESTMOD + pyc_ext: (NOW, pyc)}
349 self.doTest(pyc_ext, files, TESTMOD, call=self.assertModuleSource)
350
351 def runDoctest(self, callback):
352 files = {TESTMOD + ".py": (NOW, test_src),
353 "xyz.txt": (NOW, ">>> log.append(True)\n")}
354 self.doTest(".py", files, TESTMOD, call=callback)
355
356 def doDoctestFile(self, module):
357 log = []
358 old_master, doctest.master = doctest.master, None
359 try:
360 doctest.testfile(
361 'xyz.txt', package=module, module_relative=True,
362 globs=locals()
363 )
364 finally:
365 doctest.master = old_master
366 self.assertEqual(log,[True])
367
368 def testDoctestFile(self):
369 self.runDoctest(self.doDoctestFile)
370
371 def doDoctestSuite(self, module):
372 log = []
373 doctest.DocFileTest(
374 'xyz.txt', package=module, module_relative=True,
375 globs=locals()
376 ).run()
377 self.assertEqual(log,[True])
378
379 def testDoctestSuite(self):
380 self.runDoctest(self.doDoctestSuite)
381
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000382 def doTraceback(self, module):
383 try:
384 module.do_raise()
385 except:
386 tb = sys.exc_info()[2].tb_next
387
388 f,lno,n,line = extract_tb(tb, 1)[0]
389 self.assertEqual(line, raise_src.strip())
390
391 f,lno,n,line = extract_stack(tb.tb_frame, 1)[0]
392 self.assertEqual(line, raise_src.strip())
393
Guido van Rossum34d19282007-08-09 01:03:29 +0000394 s = io.StringIO()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000395 print_tb(tb, 1, s)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000396 self.assertTrue(s.getvalue().endswith(raise_src))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000397 else:
398 raise AssertionError("This ought to be impossible")
399
400 def testTraceback(self):
401 files = {TESTMOD + ".py": (NOW, raise_src)}
402 self.doTest(None, files, TESTMOD, call=self.doTraceback)
403
Victor Stinner2460a432010-08-16 17:54:28 +0000404 @unittest.skipIf(support.TESTFN_UNENCODABLE is None,
405 "need an unencodable filename")
Victor Stinner36e79112010-08-17 00:44:11 +0000406 def testUnencodable(self):
Victor Stinner2460a432010-08-16 17:54:28 +0000407 filename = support.TESTFN_UNENCODABLE + ".zip"
408 z = ZipFile(filename, "w")
409 zinfo = ZipInfo(TESTMOD + ".py", time.localtime(NOW))
410 zinfo.compress_type = self.compression
411 z.writestr(zinfo, test_src)
412 z.close()
413 try:
414 zipimport.zipimporter(filename)
415 finally:
416 os.remove(filename)
417
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000418
Ezio Melotti975077a2011-05-19 22:03:22 +0300419@support.requires_zlib
Just van Rossum52e14d62002-12-30 22:08:05 +0000420class CompressedZipImportTestCase(UncompressedZipImportTestCase):
421 compression = ZIP_DEFLATED
422
423
Neal Norwitzb155b622006-01-23 07:52:13 +0000424class BadFileZipImportTestCase(unittest.TestCase):
425 def assertZipFailure(self, filename):
426 self.assertRaises(zipimport.ZipImportError,
427 zipimport.zipimporter, filename)
428
429 def testNoFile(self):
430 self.assertZipFailure('AdfjdkFJKDFJjdklfjs')
431
432 def testEmptyFilename(self):
433 self.assertZipFailure('')
434
435 def testBadArgs(self):
436 self.assertRaises(TypeError, zipimport.zipimporter, None)
437 self.assertRaises(TypeError, zipimport.zipimporter, TESTMOD, kwd=None)
438
439 def testFilenameTooLong(self):
440 self.assertZipFailure('A' * 33000)
441
442 def testEmptyFile(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000443 support.unlink(TESTMOD)
Victor Stinnerbf816222011-06-30 23:25:47 +0200444 support.create_empty_file(TESTMOD)
Neal Norwitzb155b622006-01-23 07:52:13 +0000445 self.assertZipFailure(TESTMOD)
446
447 def testFileUnreadable(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000448 support.unlink(TESTMOD)
Neal Norwitzb155b622006-01-23 07:52:13 +0000449 fd = os.open(TESTMOD, os.O_CREAT, 000)
Tim Peters68f2d002006-01-23 22:19:24 +0000450 try:
451 os.close(fd)
452 self.assertZipFailure(TESTMOD)
453 finally:
454 # If we leave "the read-only bit" set on Windows, nothing can
455 # delete TESTMOD, and later tests suffer bogus failures.
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000456 os.chmod(TESTMOD, 0o666)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000457 support.unlink(TESTMOD)
Neal Norwitzb155b622006-01-23 07:52:13 +0000458
459 def testNotZipFile(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000460 support.unlink(TESTMOD)
Neal Norwitzb155b622006-01-23 07:52:13 +0000461 fp = open(TESTMOD, 'w+')
462 fp.write('a' * 22)
463 fp.close()
464 self.assertZipFailure(TESTMOD)
465
Neal Norwitzdbc95f42006-01-23 08:48:03 +0000466 # XXX: disabled until this works on Big-endian machines
467 def _testBogusZipFile(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000468 support.unlink(TESTMOD)
Neal Norwitzb155b622006-01-23 07:52:13 +0000469 fp = open(TESTMOD, 'w+')
470 fp.write(struct.pack('=I', 0x06054B50))
471 fp.write('a' * 18)
472 fp.close()
473 z = zipimport.zipimporter(TESTMOD)
474
475 try:
476 self.assertRaises(TypeError, z.find_module, None)
477 self.assertRaises(TypeError, z.load_module, None)
478 self.assertRaises(TypeError, z.is_package, None)
479 self.assertRaises(TypeError, z.get_code, None)
480 self.assertRaises(TypeError, z.get_data, None)
481 self.assertRaises(TypeError, z.get_source, None)
482
483 error = zipimport.ZipImportError
484 self.assertEqual(z.find_module('abc'), None)
485
486 self.assertRaises(error, z.load_module, 'abc')
487 self.assertRaises(error, z.get_code, 'abc')
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200488 self.assertRaises(OSError, z.get_data, 'abc')
Neal Norwitzb155b622006-01-23 07:52:13 +0000489 self.assertRaises(error, z.get_source, 'abc')
490 self.assertRaises(error, z.is_package, 'abc')
491 finally:
492 zipimport._zip_directory_cache.clear()
493
494
Neal Norwitz5c1ba532003-02-17 18:05:20 +0000495def test_main():
Neal Norwitzb155b622006-01-23 07:52:13 +0000496 try:
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000497 support.run_unittest(
Neal Norwitzb155b622006-01-23 07:52:13 +0000498 UncompressedZipImportTestCase,
499 CompressedZipImportTestCase,
500 BadFileZipImportTestCase,
501 )
502 finally:
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000503 support.unlink(TESTMOD)
Neal Norwitz5c1ba532003-02-17 18:05:20 +0000504
505if __name__ == "__main__":
506 test_main()