blob: 3f16041f511f068ac3d85c41e9aee75f4118f625 [file] [log] [blame]
Just van Rossum52e14d62002-12-30 22:08:05 +00001import sys
2import os
3import marshal
Brett Cannon9529fbf2013-06-15 17:11:25 -04004import importlib.util
Just van Rossum52e14d62002-12-30 22:08:05 +00005import 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))
Brett Cannon9529fbf2013-06-15 17:11:25 -040037 pyc = (importlib.util.MAGIC_NUMBER +
38 struct.pack("<ii", int(mtime), size & 0xFFFFFFFF) + data)
Just van Rossum52e14d62002-12-30 22:08:05 +000039 return pyc
40
Tim Peters68f2d002006-01-23 22:19:24 +000041def module_path_to_dotted_name(path):
42 return path.replace(os.sep, '.')
43
Just van Rossum52e14d62002-12-30 22:08:05 +000044NOW = time.time()
Antoine Pitrou5136ac02012-01-13 18:52:16 +010045test_pyc = make_pyc(test_co, NOW, len(test_src))
Just van Rossum52e14d62002-12-30 22:08:05 +000046
47
Just van Rossum52e14d62002-12-30 22:08:05 +000048TESTMOD = "ziptestmodule"
49TESTPACK = "ziptestpackage"
Just van Rossumd35c6db2003-01-02 12:55:48 +000050TESTPACK2 = "ziptestpackage2"
Skip Montanaro7a98be22007-08-16 14:35:24 +000051TEMP_ZIP = os.path.abspath("junk95142.zip")
Just van Rossum52e14d62002-12-30 22:08:05 +000052
Brett Cannon9529fbf2013-06-15 17:11:25 -040053pyc_file = importlib.util.cache_from_source(TESTMOD + '.py')
Barry Warsaw28a691b2010-04-17 00:19:56 +000054pyc_ext = ('.pyc' if __debug__ else '.pyo')
55
Ezio Melotti78ea2022009-09-12 18:41:20 +000056
Brett Cannon638ce072013-06-12 15:57:01 -040057class ImportHooksBaseTestCase(unittest.TestCase):
58
59 def setUp(self):
60 self.path = sys.path[:]
61 self.meta_path = sys.meta_path[:]
62 self.path_hooks = sys.path_hooks[:]
63 sys.path_importer_cache.clear()
64 self.modules_before = support.modules_setup()
65
66 def tearDown(self):
67 sys.path[:] = self.path
68 sys.meta_path[:] = self.meta_path
69 sys.path_hooks[:] = self.path_hooks
70 sys.path_importer_cache.clear()
71 support.modules_cleanup(*self.modules_before)
72
73
Just van Rossum52e14d62002-12-30 22:08:05 +000074class UncompressedZipImportTestCase(ImportHooksBaseTestCase):
75
76 compression = ZIP_STORED
77
78 def setUp(self):
79 # We're reusing the zip archive path, so we must clear the
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000080 # cached directory info and linecache
81 linecache.clearcache()
Just van Rossum52e14d62002-12-30 22:08:05 +000082 zipimport._zip_directory_cache.clear()
83 ImportHooksBaseTestCase.setUp(self)
84
Thomas Heller354e3d92003-07-22 18:10:15 +000085 def doTest(self, expected_ext, files, *modules, **kw):
Just van Rossum52e14d62002-12-30 22:08:05 +000086 z = ZipFile(TEMP_ZIP, "w")
87 try:
88 for name, (mtime, data) in files.items():
89 zinfo = ZipInfo(name, time.localtime(mtime))
90 zinfo.compress_type = self.compression
91 z.writestr(zinfo, data)
92 z.close()
Thomas Heller354e3d92003-07-22 18:10:15 +000093
94 stuff = kw.get("stuff", None)
95 if stuff is not None:
96 # Prepend 'stuff' to the start of the zipfile
Barry Warsaw28a691b2010-04-17 00:19:56 +000097 with open(TEMP_ZIP, "rb") as f:
98 data = f.read()
99 with open(TEMP_ZIP, "wb") as f:
100 f.write(stuff)
101 f.write(data)
Thomas Heller354e3d92003-07-22 18:10:15 +0000102
Just van Rossum52e14d62002-12-30 22:08:05 +0000103 sys.path.insert(0, TEMP_ZIP)
104
105 mod = __import__(".".join(modules), globals(), locals(),
106 ["__dummy__"])
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000107
108 call = kw.get('call')
109 if call is not None:
110 call(mod)
111
Just van Rossum9a3129c2003-01-03 11:18:56 +0000112 if expected_ext:
113 file = mod.get_file()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000114 self.assertEqual(file, os.path.join(TEMP_ZIP,
115 *modules) + expected_ext)
Just van Rossum52e14d62002-12-30 22:08:05 +0000116 finally:
117 z.close()
118 os.remove(TEMP_ZIP)
119
120 def testAFakeZlib(self):
121 #
122 # This could cause a stack overflow before: importing zlib.py
123 # from a compressed archive would cause zlib to be imported
124 # which would find zlib.py in the archive, which would... etc.
125 #
126 # This test *must* be executed first: it must be the first one
127 # to trigger zipimport to import zlib (zipimport caches the
128 # zlib.decompress function object, after which the problem being
129 # tested here wouldn't be a problem anymore...
130 # (Hence the 'A' in the test method name: to make it the first
131 # item in a list sorted by name, like unittest.makeSuite() does.)
132 #
Just van Rossum59498542003-11-18 23:00:55 +0000133 # This test fails on platforms on which the zlib module is
134 # statically linked, but the problem it tests for can't
135 # occur in that case (builtin modules are always found first),
136 # so we'll simply skip it then. Bug #765456.
137 #
138 if "zlib" in sys.builtin_module_names:
139 return
Just van Rossum52e14d62002-12-30 22:08:05 +0000140 if "zlib" in sys.modules:
141 del sys.modules["zlib"]
142 files = {"zlib.py": (NOW, test_src)}
143 try:
144 self.doTest(".py", files, "zlib")
145 except ImportError:
146 if self.compression != ZIP_DEFLATED:
147 self.fail("expected test to not raise ImportError")
148 else:
149 if self.compression != ZIP_STORED:
150 self.fail("expected test to raise ImportError")
151
152 def testPy(self):
153 files = {TESTMOD + ".py": (NOW, test_src)}
154 self.doTest(".py", files, TESTMOD)
155
156 def testPyc(self):
157 files = {TESTMOD + pyc_ext: (NOW, test_pyc)}
158 self.doTest(pyc_ext, files, TESTMOD)
159
160 def testBoth(self):
161 files = {TESTMOD + ".py": (NOW, test_src),
162 TESTMOD + pyc_ext: (NOW, test_pyc)}
163 self.doTest(pyc_ext, files, TESTMOD)
164
Just van Rossum9a3129c2003-01-03 11:18:56 +0000165 def testEmptyPy(self):
166 files = {TESTMOD + ".py": (NOW, "")}
167 self.doTest(None, files, TESTMOD)
168
Just van Rossum52e14d62002-12-30 22:08:05 +0000169 def testBadMagic(self):
170 # make pyc magic word invalid, forcing loading from .py
Guido van Rossum254348e2007-11-21 19:29:53 +0000171 badmagic_pyc = bytearray(test_pyc)
Guido van Rossumad8d3002007-08-03 18:40:49 +0000172 badmagic_pyc[0] ^= 0x04 # flip an arbitrary bit
Just van Rossum52e14d62002-12-30 22:08:05 +0000173 files = {TESTMOD + ".py": (NOW, test_src),
174 TESTMOD + pyc_ext: (NOW, badmagic_pyc)}
175 self.doTest(".py", files, TESTMOD)
176
177 def testBadMagic2(self):
178 # make pyc magic word invalid, causing an ImportError
Guido van Rossum254348e2007-11-21 19:29:53 +0000179 badmagic_pyc = bytearray(test_pyc)
Guido van Rossumad8d3002007-08-03 18:40:49 +0000180 badmagic_pyc[0] ^= 0x04 # flip an arbitrary bit
Just van Rossum52e14d62002-12-30 22:08:05 +0000181 files = {TESTMOD + pyc_ext: (NOW, badmagic_pyc)}
182 try:
183 self.doTest(".py", files, TESTMOD)
184 except ImportError:
185 pass
186 else:
187 self.fail("expected ImportError; import from bad pyc")
188
189 def testBadMTime(self):
Guido van Rossum254348e2007-11-21 19:29:53 +0000190 badtime_pyc = bytearray(test_pyc)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000191 # flip the second bit -- not the first as that one isn't stored in the
192 # .py's mtime in the zip archive.
193 badtime_pyc[7] ^= 0x02
Just van Rossum52e14d62002-12-30 22:08:05 +0000194 files = {TESTMOD + ".py": (NOW, test_src),
195 TESTMOD + pyc_ext: (NOW, badtime_pyc)}
196 self.doTest(".py", files, TESTMOD)
197
198 def testPackage(self):
199 packdir = TESTPACK + os.sep
200 files = {packdir + "__init__" + pyc_ext: (NOW, test_pyc),
201 packdir + TESTMOD + pyc_ext: (NOW, test_pyc)}
202 self.doTest(pyc_ext, files, TESTPACK, TESTMOD)
203
204 def testDeepPackage(self):
205 packdir = TESTPACK + os.sep
Just van Rossumd35c6db2003-01-02 12:55:48 +0000206 packdir2 = packdir + TESTPACK2 + os.sep
Just van Rossum52e14d62002-12-30 22:08:05 +0000207 files = {packdir + "__init__" + pyc_ext: (NOW, test_pyc),
208 packdir2 + "__init__" + pyc_ext: (NOW, test_pyc),
209 packdir2 + TESTMOD + pyc_ext: (NOW, test_pyc)}
Just van Rossumd35c6db2003-01-02 12:55:48 +0000210 self.doTest(pyc_ext, files, TESTPACK, TESTPACK2, TESTMOD)
Just van Rossum52e14d62002-12-30 22:08:05 +0000211
Neal Norwitzb155b622006-01-23 07:52:13 +0000212 def testZipImporterMethods(self):
213 packdir = TESTPACK + os.sep
214 packdir2 = packdir + TESTPACK2 + os.sep
215 files = {packdir + "__init__" + pyc_ext: (NOW, test_pyc),
216 packdir2 + "__init__" + pyc_ext: (NOW, test_pyc),
217 packdir2 + TESTMOD + pyc_ext: (NOW, test_pyc)}
218
219 z = ZipFile(TEMP_ZIP, "w")
220 try:
221 for name, (mtime, data) in files.items():
222 zinfo = ZipInfo(name, time.localtime(mtime))
223 zinfo.compress_type = self.compression
Serhiy Storchaka0e6b7b52013-02-16 17:43:45 +0200224 zinfo.comment = b"spam"
Neal Norwitzb155b622006-01-23 07:52:13 +0000225 z.writestr(zinfo, data)
226 z.close()
227
228 zi = zipimport.zipimporter(TEMP_ZIP)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000229 self.assertEqual(zi.archive, TEMP_ZIP)
230 self.assertEqual(zi.is_package(TESTPACK), True)
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000231 mod = zi.load_module(TESTPACK)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000232 self.assertEqual(zi.get_filename(TESTPACK), mod.__file__)
Tim Petersbc29c1a2006-01-23 21:28:42 +0000233
R David Murraya9719052012-03-12 21:16:33 -0400234 existing_pack_path = __import__(TESTPACK).__path__[0]
235 expected_path_path = os.path.join(TEMP_ZIP, TESTPACK)
236 self.assertEqual(existing_pack_path, expected_path_path)
237
Ezio Melottib3aedd42010-11-20 19:04:17 +0000238 self.assertEqual(zi.is_package(packdir + '__init__'), False)
239 self.assertEqual(zi.is_package(packdir + TESTPACK2), True)
240 self.assertEqual(zi.is_package(packdir2 + TESTMOD), False)
Neal Norwitzb155b622006-01-23 07:52:13 +0000241
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000242 mod_path = packdir2 + TESTMOD
243 mod_name = module_path_to_dotted_name(mod_path)
Georg Brandl89fad142010-03-14 10:23:39 +0000244 __import__(mod_name)
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000245 mod = sys.modules[mod_name]
Ezio Melottib3aedd42010-11-20 19:04:17 +0000246 self.assertEqual(zi.get_source(TESTPACK), None)
247 self.assertEqual(zi.get_source(mod_path), None)
248 self.assertEqual(zi.get_filename(mod_path), mod.__file__)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000249 # To pass in the module name instead of the path, we must use the
250 # right importer
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000251 loader = mod.__loader__
Ezio Melottib3aedd42010-11-20 19:04:17 +0000252 self.assertEqual(loader.get_source(mod_name), None)
253 self.assertEqual(loader.get_filename(mod_name), mod.__file__)
Christian Heimes7f044312008-01-06 17:05:40 +0000254
255 # test prefix and archivepath members
256 zi2 = zipimport.zipimporter(TEMP_ZIP + os.sep + TESTPACK)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000257 self.assertEqual(zi2.archive, TEMP_ZIP)
258 self.assertEqual(zi2.prefix, TESTPACK + os.sep)
Neal Norwitzb155b622006-01-23 07:52:13 +0000259 finally:
260 z.close()
261 os.remove(TEMP_ZIP)
262
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000263 def testZipImporterMethodsInSubDirectory(self):
264 packdir = TESTPACK + os.sep
265 packdir2 = packdir + TESTPACK2 + os.sep
266 files = {packdir2 + "__init__" + pyc_ext: (NOW, test_pyc),
267 packdir2 + TESTMOD + pyc_ext: (NOW, test_pyc)}
268
269 z = ZipFile(TEMP_ZIP, "w")
270 try:
271 for name, (mtime, data) in files.items():
272 zinfo = ZipInfo(name, time.localtime(mtime))
273 zinfo.compress_type = self.compression
Serhiy Storchaka0e6b7b52013-02-16 17:43:45 +0200274 zinfo.comment = b"eggs"
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000275 z.writestr(zinfo, data)
276 z.close()
277
278 zi = zipimport.zipimporter(TEMP_ZIP + os.sep + packdir)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000279 self.assertEqual(zi.archive, TEMP_ZIP)
280 self.assertEqual(zi.prefix, packdir)
281 self.assertEqual(zi.is_package(TESTPACK2), True)
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000282 mod = zi.load_module(TESTPACK2)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000283 self.assertEqual(zi.get_filename(TESTPACK2), mod.__file__)
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000284
Ezio Melottib3aedd42010-11-20 19:04:17 +0000285 self.assertEqual(
Barry Warsaw28a691b2010-04-17 00:19:56 +0000286 zi.is_package(TESTPACK2 + os.sep + '__init__'), False)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000287 self.assertEqual(
Barry Warsaw28a691b2010-04-17 00:19:56 +0000288 zi.is_package(TESTPACK2 + os.sep + TESTMOD), False)
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000289
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000290 mod_path = TESTPACK2 + os.sep + TESTMOD
291 mod_name = module_path_to_dotted_name(mod_path)
Georg Brandl89fad142010-03-14 10:23:39 +0000292 __import__(mod_name)
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000293 mod = sys.modules[mod_name]
Ezio Melottib3aedd42010-11-20 19:04:17 +0000294 self.assertEqual(zi.get_source(TESTPACK2), None)
295 self.assertEqual(zi.get_source(mod_path), None)
296 self.assertEqual(zi.get_filename(mod_path), mod.__file__)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000297 # To pass in the module name instead of the path, we must use the
298 # right importer
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000299 loader = mod.__loader__
Ezio Melottib3aedd42010-11-20 19:04:17 +0000300 self.assertEqual(loader.get_source(mod_name), None)
301 self.assertEqual(loader.get_filename(mod_name), mod.__file__)
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000302 finally:
303 z.close()
304 os.remove(TEMP_ZIP)
305
Just van Rossum52e14d62002-12-30 22:08:05 +0000306 def testGetData(self):
307 z = ZipFile(TEMP_ZIP, "w")
308 z.compression = self.compression
309 try:
310 name = "testdata.dat"
Guido van Rossumad8d3002007-08-03 18:40:49 +0000311 data = bytes(x for x in range(256))
Just van Rossum52e14d62002-12-30 22:08:05 +0000312 z.writestr(name, data)
313 z.close()
314 zi = zipimport.zipimporter(TEMP_ZIP)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000315 self.assertEqual(data, zi.get_data(name))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000316 self.assertIn('zipimporter object', repr(zi))
Just van Rossum52e14d62002-12-30 22:08:05 +0000317 finally:
318 z.close()
319 os.remove(TEMP_ZIP)
320
321 def testImporterAttr(self):
322 src = """if 1: # indent hack
323 def get_file():
324 return __file__
Guido van Rossumad8d3002007-08-03 18:40:49 +0000325 if __loader__.get_data("some.data") != b"some data":
Collin Winter828f04a2007-08-31 00:04:24 +0000326 raise AssertionError("bad data")\n"""
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100327 pyc = make_pyc(compile(src, "<???>", "exec"), NOW, len(src))
Just van Rossum52e14d62002-12-30 22:08:05 +0000328 files = {TESTMOD + pyc_ext: (NOW, pyc),
329 "some.data": (NOW, "some data")}
330 self.doTest(pyc_ext, files, TESTMOD)
331
Thomas Heller354e3d92003-07-22 18:10:15 +0000332 def testImport_WithStuff(self):
333 # try importing from a zipfile which contains additional
334 # stuff at the beginning of the file
335 files = {TESTMOD + ".py": (NOW, test_src)}
336 self.doTest(".py", files, TESTMOD,
Guido van Rossum85825dc2007-08-27 17:03:28 +0000337 stuff=b"Some Stuff"*31)
Just van Rossum52e14d62002-12-30 22:08:05 +0000338
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000339 def assertModuleSource(self, module):
340 self.assertEqual(inspect.getsource(module), test_src)
341
342 def testGetSource(self):
343 files = {TESTMOD + ".py": (NOW, test_src)}
344 self.doTest(".py", files, TESTMOD, call=self.assertModuleSource)
345
346 def testGetCompiledSource(self):
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100347 pyc = make_pyc(compile(test_src, "<???>", "exec"), NOW, len(test_src))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000348 files = {TESTMOD + ".py": (NOW, test_src),
349 TESTMOD + pyc_ext: (NOW, pyc)}
350 self.doTest(pyc_ext, files, TESTMOD, call=self.assertModuleSource)
351
352 def runDoctest(self, callback):
353 files = {TESTMOD + ".py": (NOW, test_src),
354 "xyz.txt": (NOW, ">>> log.append(True)\n")}
355 self.doTest(".py", files, TESTMOD, call=callback)
356
357 def doDoctestFile(self, module):
358 log = []
359 old_master, doctest.master = doctest.master, None
360 try:
361 doctest.testfile(
362 'xyz.txt', package=module, module_relative=True,
363 globs=locals()
364 )
365 finally:
366 doctest.master = old_master
367 self.assertEqual(log,[True])
368
369 def testDoctestFile(self):
370 self.runDoctest(self.doDoctestFile)
371
372 def doDoctestSuite(self, module):
373 log = []
374 doctest.DocFileTest(
375 'xyz.txt', package=module, module_relative=True,
376 globs=locals()
377 ).run()
378 self.assertEqual(log,[True])
379
380 def testDoctestSuite(self):
381 self.runDoctest(self.doDoctestSuite)
382
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000383 def doTraceback(self, module):
384 try:
385 module.do_raise()
386 except:
387 tb = sys.exc_info()[2].tb_next
388
389 f,lno,n,line = extract_tb(tb, 1)[0]
390 self.assertEqual(line, raise_src.strip())
391
392 f,lno,n,line = extract_stack(tb.tb_frame, 1)[0]
393 self.assertEqual(line, raise_src.strip())
394
Guido van Rossum34d19282007-08-09 01:03:29 +0000395 s = io.StringIO()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000396 print_tb(tb, 1, s)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000397 self.assertTrue(s.getvalue().endswith(raise_src))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000398 else:
399 raise AssertionError("This ought to be impossible")
400
401 def testTraceback(self):
402 files = {TESTMOD + ".py": (NOW, raise_src)}
403 self.doTest(None, files, TESTMOD, call=self.doTraceback)
404
Victor Stinner2460a432010-08-16 17:54:28 +0000405 @unittest.skipIf(support.TESTFN_UNENCODABLE is None,
406 "need an unencodable filename")
Victor Stinner36e79112010-08-17 00:44:11 +0000407 def testUnencodable(self):
Victor Stinner2460a432010-08-16 17:54:28 +0000408 filename = support.TESTFN_UNENCODABLE + ".zip"
409 z = ZipFile(filename, "w")
410 zinfo = ZipInfo(TESTMOD + ".py", time.localtime(NOW))
411 zinfo.compress_type = self.compression
412 z.writestr(zinfo, test_src)
413 z.close()
414 try:
415 zipimport.zipimporter(filename)
416 finally:
417 os.remove(filename)
418
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000419
Ezio Melotti975077a2011-05-19 22:03:22 +0300420@support.requires_zlib
Just van Rossum52e14d62002-12-30 22:08:05 +0000421class CompressedZipImportTestCase(UncompressedZipImportTestCase):
422 compression = ZIP_DEFLATED
423
424
Neal Norwitzb155b622006-01-23 07:52:13 +0000425class BadFileZipImportTestCase(unittest.TestCase):
426 def assertZipFailure(self, filename):
427 self.assertRaises(zipimport.ZipImportError,
428 zipimport.zipimporter, filename)
429
430 def testNoFile(self):
431 self.assertZipFailure('AdfjdkFJKDFJjdklfjs')
432
433 def testEmptyFilename(self):
434 self.assertZipFailure('')
435
436 def testBadArgs(self):
437 self.assertRaises(TypeError, zipimport.zipimporter, None)
438 self.assertRaises(TypeError, zipimport.zipimporter, TESTMOD, kwd=None)
439
440 def testFilenameTooLong(self):
441 self.assertZipFailure('A' * 33000)
442
443 def testEmptyFile(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000444 support.unlink(TESTMOD)
Victor Stinnerbf816222011-06-30 23:25:47 +0200445 support.create_empty_file(TESTMOD)
Neal Norwitzb155b622006-01-23 07:52:13 +0000446 self.assertZipFailure(TESTMOD)
447
448 def testFileUnreadable(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000449 support.unlink(TESTMOD)
Neal Norwitzb155b622006-01-23 07:52:13 +0000450 fd = os.open(TESTMOD, os.O_CREAT, 000)
Tim Peters68f2d002006-01-23 22:19:24 +0000451 try:
452 os.close(fd)
453 self.assertZipFailure(TESTMOD)
454 finally:
455 # If we leave "the read-only bit" set on Windows, nothing can
456 # delete TESTMOD, and later tests suffer bogus failures.
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000457 os.chmod(TESTMOD, 0o666)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000458 support.unlink(TESTMOD)
Neal Norwitzb155b622006-01-23 07:52:13 +0000459
460 def testNotZipFile(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000461 support.unlink(TESTMOD)
Neal Norwitzb155b622006-01-23 07:52:13 +0000462 fp = open(TESTMOD, 'w+')
463 fp.write('a' * 22)
464 fp.close()
465 self.assertZipFailure(TESTMOD)
466
Neal Norwitzdbc95f42006-01-23 08:48:03 +0000467 # XXX: disabled until this works on Big-endian machines
468 def _testBogusZipFile(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000469 support.unlink(TESTMOD)
Neal Norwitzb155b622006-01-23 07:52:13 +0000470 fp = open(TESTMOD, 'w+')
471 fp.write(struct.pack('=I', 0x06054B50))
472 fp.write('a' * 18)
473 fp.close()
474 z = zipimport.zipimporter(TESTMOD)
475
476 try:
477 self.assertRaises(TypeError, z.find_module, None)
478 self.assertRaises(TypeError, z.load_module, None)
479 self.assertRaises(TypeError, z.is_package, None)
480 self.assertRaises(TypeError, z.get_code, None)
481 self.assertRaises(TypeError, z.get_data, None)
482 self.assertRaises(TypeError, z.get_source, None)
483
484 error = zipimport.ZipImportError
485 self.assertEqual(z.find_module('abc'), None)
486
487 self.assertRaises(error, z.load_module, 'abc')
488 self.assertRaises(error, z.get_code, 'abc')
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200489 self.assertRaises(OSError, z.get_data, 'abc')
Neal Norwitzb155b622006-01-23 07:52:13 +0000490 self.assertRaises(error, z.get_source, 'abc')
491 self.assertRaises(error, z.is_package, 'abc')
492 finally:
493 zipimport._zip_directory_cache.clear()
494
495
Neal Norwitz5c1ba532003-02-17 18:05:20 +0000496def test_main():
Neal Norwitzb155b622006-01-23 07:52:13 +0000497 try:
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000498 support.run_unittest(
Neal Norwitzb155b622006-01-23 07:52:13 +0000499 UncompressedZipImportTestCase,
500 CompressedZipImportTestCase,
501 BadFileZipImportTestCase,
502 )
503 finally:
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000504 support.unlink(TESTMOD)
Neal Norwitz5c1ba532003-02-17 18:05:20 +0000505
506if __name__ == "__main__":
507 test_main()