blob: e833b1613e5760b4a5757ec1ad3b1eec346a4927 [file] [log] [blame]
Nick Coghlanbe7e49f2012-07-20 23:40:09 +10001# We import importlib *ASAP* in order to test #15386
2import importlib
Collin Winter6498cff2010-03-17 03:14:31 +00003import builtins
Christian Heimes13a7a212008-01-07 17:13:09 +00004import imp
Brett Cannon1f274792010-07-23 14:03:16 +00005from importlib.test.import_ import util as importlib_util
Antoine Pitroud35cbf62009-01-06 19:02:24 +00006import marshal
Collin Winter88e333d2010-03-17 03:09:21 +00007import os
Charles-François Natalia13b1fa2011-10-04 19:17:26 +02008import platform
Collin Winter88e333d2010-03-17 03:09:21 +00009import py_compile
10import random
Collin Winter88e333d2010-03-17 03:09:21 +000011import stat
12import sys
13import unittest
R. David Murrayce4b1702010-12-14 23:06:25 +000014import textwrap
Antoine Pitroudd21f682012-01-25 03:00:57 +010015import errno
Jason R. Coombs71fde312012-06-17 03:53:47 -040016import shutil
Barry Warsaw28a691b2010-04-17 00:19:56 +000017
Jason R. Coombs71fde312012-06-17 03:53:47 -040018import test.support
Barry Warsaw28a691b2010-04-17 00:19:56 +000019from test.support import (
20 EnvironmentVarGuard, TESTFN, check_warnings, forget, is_jython,
21 make_legacy_pyc, rmtree, run_unittest, swap_attr, swap_item, temp_umask,
Antoine Pitrou48114b92012-06-17 22:33:38 +020022 unlink, unload, create_empty_file, cpython_only)
R. David Murrayce4b1702010-12-14 23:06:25 +000023from test import script_helper
Guido van Rossumbd6f4fb2000-10-24 17:16:32 +000024
Tim Peters72f98e92001-05-08 15:19:57 +000025
Tim Peters08138fd2004-08-02 03:58:27 +000026def remove_files(name):
Skip Montanaro7a98be22007-08-16 14:35:24 +000027 for f in (name + ".py",
28 name + ".pyc",
29 name + ".pyo",
30 name + ".pyw",
Tim Peters08138fd2004-08-02 03:58:27 +000031 name + "$py.class"):
Florent Xicluna8fbddf12010-03-17 20:29:51 +000032 unlink(f)
Florent Xicluna27354cc2010-08-16 18:41:19 +000033 rmtree('__pycache__')
Tim Peters08138fd2004-08-02 03:58:27 +000034
Tim Petersc1731372001-08-04 08:12:36 +000035
Collin Winter88e333d2010-03-17 03:09:21 +000036class ImportTests(unittest.TestCase):
Tim Petersc1731372001-08-04 08:12:36 +000037
Antoine Pitrou46719af2011-03-21 19:05:02 +010038 def setUp(self):
39 remove_files(TESTFN)
Antoine Pitrouc541f8e2012-02-20 01:48:16 +010040 importlib.invalidate_caches()
Antoine Pitrou46719af2011-03-21 19:05:02 +010041
Florent Xicluna8fbddf12010-03-17 20:29:51 +000042 def tearDown(self):
43 unload(TESTFN)
Barry Warsaw28a691b2010-04-17 00:19:56 +000044
Florent Xicluna8fbddf12010-03-17 20:29:51 +000045 setUp = tearDown
46
Collin Winter88e333d2010-03-17 03:09:21 +000047 def test_case_sensitivity(self):
48 # Brief digression to test that import is case-sensitive: if we got
49 # this far, we know for sure that "random" exists.
Benjamin Peterson1c87e292010-10-30 23:04:49 +000050 with self.assertRaises(ImportError):
Thomas Wouters89f507f2006-12-13 04:49:30 +000051 import RAnDoM
Tim Peters08138fd2004-08-02 03:58:27 +000052
Collin Winter88e333d2010-03-17 03:09:21 +000053 def test_double_const(self):
54 # Another brief digression to test the accuracy of manifest float
55 # constants.
Thomas Wouters89f507f2006-12-13 04:49:30 +000056 from test import double_const # don't blink -- that *was* the test
Tim Peters08138fd2004-08-02 03:58:27 +000057
Collin Winter88e333d2010-03-17 03:09:21 +000058 def test_import(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +000059 def test_with_extension(ext):
Collin Winter88e333d2010-03-17 03:09:21 +000060 # The extension is normally ".py", perhaps ".pyw".
Thomas Wouters89f507f2006-12-13 04:49:30 +000061 source = TESTFN + ext
Skip Montanaro7a98be22007-08-16 14:35:24 +000062 pyo = TESTFN + ".pyo"
Florent Xicluna8fbddf12010-03-17 20:29:51 +000063 if is_jython:
Thomas Wouters89f507f2006-12-13 04:49:30 +000064 pyc = TESTFN + "$py.class"
65 else:
Skip Montanaro7a98be22007-08-16 14:35:24 +000066 pyc = TESTFN + ".pyc"
Tim Peters08138fd2004-08-02 03:58:27 +000067
Benjamin Peterson16a1f632009-06-13 13:01:19 +000068 with open(source, "w") as f:
Barry Warsaw28a691b2010-04-17 00:19:56 +000069 print("# This tests Python's ability to import a",
70 ext, "file.", file=f)
Benjamin Peterson16a1f632009-06-13 13:01:19 +000071 a = random.randrange(1000)
72 b = random.randrange(1000)
73 print("a =", a, file=f)
74 print("b =", b, file=f)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000075
Amaury Forgeot d'Arcdd9e3b82007-11-16 00:56:23 +000076 if TESTFN in sys.modules:
77 del sys.modules[TESTFN]
Brett Cannonfd074152012-04-14 14:10:13 -040078 importlib.invalidate_caches()
Thomas Wouters89f507f2006-12-13 04:49:30 +000079 try:
80 try:
81 mod = __import__(TESTFN)
Guido van Rossumb940e112007-01-10 16:19:56 +000082 except ImportError as err:
Thomas Wouters89f507f2006-12-13 04:49:30 +000083 self.fail("import from %s failed: %s" % (ext, err))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000084
Florent Xicluna8fbddf12010-03-17 20:29:51 +000085 self.assertEqual(mod.a, a,
Thomas Wouters89f507f2006-12-13 04:49:30 +000086 "module loaded (%s) but contents invalid" % mod)
Florent Xicluna8fbddf12010-03-17 20:29:51 +000087 self.assertEqual(mod.b, b,
Thomas Wouters89f507f2006-12-13 04:49:30 +000088 "module loaded (%s) but contents invalid" % mod)
89 finally:
Barry Warsaw28a691b2010-04-17 00:19:56 +000090 forget(TESTFN)
Guido van Rossume7ba4952007-06-06 23:52:48 +000091 unlink(source)
92 unlink(pyc)
93 unlink(pyo)
Thomas Wouters477c8d52006-05-27 19:21:47 +000094
Thomas Wouters89f507f2006-12-13 04:49:30 +000095 sys.path.insert(0, os.curdir)
96 try:
Skip Montanaro7a98be22007-08-16 14:35:24 +000097 test_with_extension(".py")
Thomas Wouters89f507f2006-12-13 04:49:30 +000098 if sys.platform.startswith("win"):
Collin Winter88e333d2010-03-17 03:09:21 +000099 for ext in [".PY", ".Py", ".pY", ".pyw", ".PYW", ".pYw"]:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000100 test_with_extension(ext)
101 finally:
102 del sys.path[0]
Thomas Wouters477c8d52006-05-27 19:21:47 +0000103
Barry Warsaw28a691b2010-04-17 00:19:56 +0000104 @unittest.skipUnless(os.name == 'posix',
105 "test meaningful only on posix systems")
Charles-François Natali0c929d92011-11-10 19:12:29 +0100106 def test_creation_mode(self):
107 mask = 0o022
108 with temp_umask(mask):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000109 sys.path.insert(0, os.curdir)
110 try:
111 fname = TESTFN + os.extsep + "py"
Victor Stinnerbf816222011-06-30 23:25:47 +0200112 create_empty_file(fname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000113 fn = imp.cache_from_source(fname)
Antoine Pitrou28f8bee2011-12-21 15:50:42 +0100114 unlink(fn)
Antoine Pitrouc541f8e2012-02-20 01:48:16 +0100115 importlib.invalidate_caches()
Antoine Pitrou28f8bee2011-12-21 15:50:42 +0100116 __import__(TESTFN)
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000117 if not os.path.exists(fn):
118 self.fail("__import__ did not result in creation of "
119 "either a .pyc or .pyo file")
Charles-François Natali0c929d92011-11-10 19:12:29 +0100120 s = os.stat(fn)
121 # Check that the umask is respected, and the executable bits
122 # aren't set.
123 self.assertEqual(stat.S_IMODE(s.st_mode), 0o666 & ~mask)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000124 finally:
125 del sys.path[0]
126 remove_files(TESTFN)
127 unload(TESTFN)
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +0000128
Collin Winter88e333d2010-03-17 03:09:21 +0000129 def test_imp_module(self):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000130 # Verify that the imp module can correctly load and find .py files
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000131 # XXX (ncoghlan): It would be nice to use support.CleanImport
Nick Coghlan6ead5522009-10-18 13:19:33 +0000132 # here, but that breaks because the os module registers some
133 # handlers in copy_reg on import. Since CleanImport doesn't
134 # revert that registration, the module is left in a broken
135 # state after reversion. Reinitialising the module contents
136 # and just reverting os.environ to its previous state is an OK
137 # workaround
138 orig_path = os.path
139 orig_getenv = os.getenv
140 with EnvironmentVarGuard():
141 x = imp.find_module("os")
Benjamin Petersone0487972010-10-30 23:06:57 +0000142 self.addCleanup(x[0].close)
Nick Coghlan6ead5522009-10-18 13:19:33 +0000143 new_os = imp.load_module("os", *x)
144 self.assertIs(os, new_os)
145 self.assertIs(orig_path, new_os.path)
146 self.assertIsNot(orig_getenv, new_os.getenv)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000147
Victor Stinner53ffdc52011-09-23 18:54:40 +0200148 def test_bug7732(self):
149 source = TESTFN + '.py'
150 os.mkdir(source)
151 try:
152 self.assertRaisesRegex(ImportError, '^No module',
153 imp.find_module, TESTFN, ["."])
154 finally:
155 os.rmdir(source)
156
Thomas Wouters89f507f2006-12-13 04:49:30 +0000157 def test_module_with_large_stack(self, module='longlist'):
Collin Winter88e333d2010-03-17 03:09:21 +0000158 # Regression test for http://bugs.python.org/issue561858.
Skip Montanaro7a98be22007-08-16 14:35:24 +0000159 filename = module + '.py'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000160
Collin Winter88e333d2010-03-17 03:09:21 +0000161 # Create a file with a list of 65000 elements.
Brett Cannon2cab50b2010-07-03 01:32:48 +0000162 with open(filename, 'w') as f:
Collin Winter88e333d2010-03-17 03:09:21 +0000163 f.write('d = [\n')
164 for i in range(65000):
165 f.write('"",\n')
166 f.write(']')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000167
Brett Cannon2cab50b2010-07-03 01:32:48 +0000168 try:
169 # Compile & remove .py file; we only need .pyc (or .pyo).
170 # Bytecode must be relocated from the PEP 3147 bytecode-only location.
171 py_compile.compile(filename)
172 finally:
173 unlink(filename)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000174
Collin Winter88e333d2010-03-17 03:09:21 +0000175 # Need to be able to load from current dir.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000176 sys.path.append('')
Brett Cannon73def612012-04-14 14:38:19 -0400177 importlib.invalidate_caches()
Thomas Wouters89f507f2006-12-13 04:49:30 +0000178
Brett Cannon93220d02010-05-15 22:20:16 +0000179 try:
Brett Cannon2cab50b2010-07-03 01:32:48 +0000180 make_legacy_pyc(filename)
Brett Cannon93220d02010-05-15 22:20:16 +0000181 # This used to crash.
182 exec('import ' + module)
183 finally:
184 # Cleanup.
185 del sys.path[-1]
186 unlink(filename + 'c')
187 unlink(filename + 'o')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000188
189 def test_failing_import_sticks(self):
Skip Montanaro7a98be22007-08-16 14:35:24 +0000190 source = TESTFN + ".py"
Collin Winter88e333d2010-03-17 03:09:21 +0000191 with open(source, "w") as f:
192 print("a = 1/0", file=f)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000193
194 # New in 2.4, we shouldn't be able to import that no matter how often
195 # we try.
196 sys.path.insert(0, os.curdir)
Antoine Pitrou021548c2012-07-12 19:21:43 +0200197 importlib.invalidate_caches()
Guido van Rossume7ba4952007-06-06 23:52:48 +0000198 if TESTFN in sys.modules:
199 del sys.modules[TESTFN]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000200 try:
Collin Winter88e333d2010-03-17 03:09:21 +0000201 for i in [1, 2, 3]:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000202 self.assertRaises(ZeroDivisionError, __import__, TESTFN)
203 self.assertNotIn(TESTFN, sys.modules,
204 "damaged module in sys.modules on %i try" % i)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000205 finally:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000206 del sys.path[0]
Thomas Wouters89f507f2006-12-13 04:49:30 +0000207 remove_files(TESTFN)
208
Thomas Wouters89f507f2006-12-13 04:49:30 +0000209 def test_import_name_binding(self):
210 # import x.y.z binds x in the current namespace
211 import test as x
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000212 import test.support
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000213 self.assertTrue(x is test, x.__name__)
214 self.assertTrue(hasattr(test.support, "__file__"))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000215
216 # import x.y.z as w binds z as w
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000217 import test.support as y
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000218 self.assertTrue(y is test.support, y.__name__)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000219
Christian Heimes13a7a212008-01-07 17:13:09 +0000220 def test_failing_reload(self):
221 # A failing reload should leave the module object in sys.modules.
Collin Winter88e333d2010-03-17 03:09:21 +0000222 source = TESTFN + os.extsep + "py"
Christian Heimes13a7a212008-01-07 17:13:09 +0000223 with open(source, "w") as f:
224 f.write("a = 1\nb=2\n")
225
226 sys.path.insert(0, os.curdir)
227 try:
228 mod = __import__(TESTFN)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000229 self.assertIn(TESTFN, sys.modules)
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000230 self.assertEqual(mod.a, 1, "module has wrong attribute values")
231 self.assertEqual(mod.b, 2, "module has wrong attribute values")
Christian Heimes13a7a212008-01-07 17:13:09 +0000232
233 # On WinXP, just replacing the .py file wasn't enough to
234 # convince reload() to reparse it. Maybe the timestamp didn't
235 # move enough. We force it to get reparsed by removing the
236 # compiled file too.
237 remove_files(TESTFN)
238
239 # Now damage the module.
240 with open(source, "w") as f:
241 f.write("a = 10\nb=20//0\n")
242
243 self.assertRaises(ZeroDivisionError, imp.reload, mod)
244 # But we still expect the module to be in sys.modules.
245 mod = sys.modules.get(TESTFN)
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000246 self.assertIsNot(mod, None, "expected module to be in sys.modules")
Christian Heimes13a7a212008-01-07 17:13:09 +0000247
248 # We should have replaced a w/ 10, but the old b value should
249 # stick.
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000250 self.assertEqual(mod.a, 10, "module has wrong attribute values")
251 self.assertEqual(mod.b, 2, "module has wrong attribute values")
Christian Heimes13a7a212008-01-07 17:13:09 +0000252
253 finally:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000254 del sys.path[0]
Christian Heimes13a7a212008-01-07 17:13:09 +0000255 remove_files(TESTFN)
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000256 unload(TESTFN)
Christian Heimes13a7a212008-01-07 17:13:09 +0000257
Christian Heimes3b06e532008-01-07 20:12:44 +0000258 def test_file_to_source(self):
259 # check if __file__ points to the source file where available
260 source = TESTFN + ".py"
261 with open(source, "w") as f:
262 f.write("test = None\n")
263
264 sys.path.insert(0, os.curdir)
265 try:
266 mod = __import__(TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000267 self.assertTrue(mod.__file__.endswith('.py'))
Christian Heimes3b06e532008-01-07 20:12:44 +0000268 os.remove(source)
269 del sys.modules[TESTFN]
Barry Warsaw28a691b2010-04-17 00:19:56 +0000270 make_legacy_pyc(source)
Antoine Pitrouc541f8e2012-02-20 01:48:16 +0100271 importlib.invalidate_caches()
Christian Heimes3b06e532008-01-07 20:12:44 +0000272 mod = __import__(TESTFN)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000273 base, ext = os.path.splitext(mod.__file__)
Benjamin Peterson577473f2010-01-19 00:09:57 +0000274 self.assertIn(ext, ('.pyc', '.pyo'))
Christian Heimes3b06e532008-01-07 20:12:44 +0000275 finally:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000276 del sys.path[0]
Christian Heimes3b06e532008-01-07 20:12:44 +0000277 remove_files(TESTFN)
278 if TESTFN in sys.modules:
279 del sys.modules[TESTFN]
280
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000281 def test_import_name_binding(self):
282 # import x.y.z binds x in the current namespace.
283 import test as x
284 import test.support
285 self.assertIs(x, test, x.__name__)
286 self.assertTrue(hasattr(test.support, "__file__"))
287
288 # import x.y.z as w binds z as w.
289 import test.support as y
290 self.assertIs(y, test.support, y.__name__)
291
Collin Winter88e333d2010-03-17 03:09:21 +0000292 def test_import_by_filename(self):
Christian Heimes454f37b2008-01-10 00:10:02 +0000293 path = os.path.abspath(TESTFN)
Victor Stinner6c6f8512010-08-07 10:09:35 +0000294 encoding = sys.getfilesystemencoding()
295 try:
296 path.encode(encoding)
297 except UnicodeEncodeError:
298 self.skipTest('path is not encodable to {}'.format(encoding))
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000299 with self.assertRaises(ImportError) as c:
Christian Heimes454f37b2008-01-10 00:10:02 +0000300 __import__(path)
Christian Heimes454f37b2008-01-10 00:10:02 +0000301
R. David Murrayce4b1702010-12-14 23:06:25 +0000302 def test_import_in_del_does_not_crash(self):
303 # Issue 4236
304 testfn = script_helper.make_script('', TESTFN, textwrap.dedent("""\
305 import sys
306 class C:
307 def __del__(self):
308 import imp
309 sys.argv.insert(0, C())
310 """))
311 script_helper.assert_python_ok(testfn)
312
Antoine Pitrou2be60af2012-01-24 17:44:06 +0100313 def test_timestamp_overflow(self):
314 # A modification timestamp larger than 2**32 should not be a problem
315 # when importing a module (issue #11235).
Antoine Pitrou05f29b72012-01-25 01:35:26 +0100316 sys.path.insert(0, os.curdir)
317 try:
318 source = TESTFN + ".py"
319 compiled = imp.cache_from_source(source)
320 with open(source, 'w') as f:
321 pass
322 try:
Antoine Pitrou33d15f72012-01-25 18:01:45 +0100323 os.utime(source, (2 ** 33 - 5, 2 ** 33 - 5))
Antoine Pitrou05f29b72012-01-25 01:35:26 +0100324 except OverflowError:
325 self.skipTest("cannot set modification time to large integer")
Antoine Pitroudd21f682012-01-25 03:00:57 +0100326 except OSError as e:
327 if e.errno != getattr(errno, 'EOVERFLOW', None):
328 raise
329 self.skipTest("cannot set modification time to large integer ({})".format(e))
Antoine Pitrou05f29b72012-01-25 01:35:26 +0100330 __import__(TESTFN)
331 # The pyc file was created.
332 os.stat(compiled)
333 finally:
334 del sys.path[0]
335 remove_files(TESTFN)
Antoine Pitrou2be60af2012-01-24 17:44:06 +0100336
Alexandre Vassalotti9d58e3e2009-07-17 10:55:50 +0000337
Collin Winter88e333d2010-03-17 03:09:21 +0000338class PycRewritingTests(unittest.TestCase):
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000339 # Test that the `co_filename` attribute on code objects always points
340 # to the right file, even when various things happen (e.g. both the .py
341 # and the .pyc file are renamed).
342
343 module_name = "unlikely_module_name"
344 module_source = """
345import sys
346code_filename = sys._getframe().f_code.co_filename
347module_filename = __file__
348constant = 1
349def func():
350 pass
351func_filename = func.__code__.co_filename
352"""
353 dir_name = os.path.abspath(TESTFN)
354 file_name = os.path.join(dir_name, module_name) + os.extsep + "py"
Barry Warsaw28a691b2010-04-17 00:19:56 +0000355 compiled_name = imp.cache_from_source(file_name)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000356
357 def setUp(self):
358 self.sys_path = sys.path[:]
359 self.orig_module = sys.modules.pop(self.module_name, None)
360 os.mkdir(self.dir_name)
361 with open(self.file_name, "w") as f:
362 f.write(self.module_source)
363 sys.path.insert(0, self.dir_name)
Antoine Pitrouc541f8e2012-02-20 01:48:16 +0100364 importlib.invalidate_caches()
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000365
366 def tearDown(self):
367 sys.path[:] = self.sys_path
368 if self.orig_module is not None:
369 sys.modules[self.module_name] = self.orig_module
370 else:
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000371 unload(self.module_name)
372 unlink(self.file_name)
373 unlink(self.compiled_name)
Florent Xicluna27354cc2010-08-16 18:41:19 +0000374 rmtree(self.dir_name)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000375
376 def import_module(self):
377 ns = globals()
378 __import__(self.module_name, ns, ns)
379 return sys.modules[self.module_name]
380
381 def test_basics(self):
382 mod = self.import_module()
383 self.assertEqual(mod.module_filename, self.file_name)
384 self.assertEqual(mod.code_filename, self.file_name)
385 self.assertEqual(mod.func_filename, self.file_name)
386 del sys.modules[self.module_name]
387 mod = self.import_module()
388 self.assertEqual(mod.module_filename, self.file_name)
389 self.assertEqual(mod.code_filename, self.file_name)
390 self.assertEqual(mod.func_filename, self.file_name)
391
392 def test_incorrect_code_name(self):
393 py_compile.compile(self.file_name, dfile="another_module.py")
394 mod = self.import_module()
395 self.assertEqual(mod.module_filename, self.file_name)
396 self.assertEqual(mod.code_filename, self.file_name)
397 self.assertEqual(mod.func_filename, self.file_name)
398
399 def test_module_without_source(self):
400 target = "another_module.py"
401 py_compile.compile(self.file_name, dfile=target)
402 os.remove(self.file_name)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000403 pyc_file = make_legacy_pyc(self.file_name)
Brett Cannonfd074152012-04-14 14:10:13 -0400404 importlib.invalidate_caches()
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000405 mod = self.import_module()
Barry Warsaw28a691b2010-04-17 00:19:56 +0000406 self.assertEqual(mod.module_filename, pyc_file)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000407 self.assertEqual(mod.code_filename, target)
408 self.assertEqual(mod.func_filename, target)
409
410 def test_foreign_code(self):
411 py_compile.compile(self.file_name)
412 with open(self.compiled_name, "rb") as f:
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100413 header = f.read(12)
Antoine Pitroud35cbf62009-01-06 19:02:24 +0000414 code = marshal.load(f)
415 constants = list(code.co_consts)
416 foreign_code = test_main.__code__
417 pos = constants.index(1)
418 constants[pos] = foreign_code
419 code = type(code)(code.co_argcount, code.co_kwonlyargcount,
420 code.co_nlocals, code.co_stacksize,
421 code.co_flags, code.co_code, tuple(constants),
422 code.co_names, code.co_varnames, code.co_filename,
423 code.co_name, code.co_firstlineno, code.co_lnotab,
424 code.co_freevars, code.co_cellvars)
425 with open(self.compiled_name, "wb") as f:
426 f.write(header)
427 marshal.dump(code, f)
428 mod = self.import_module()
429 self.assertEqual(mod.constant.co_filename, foreign_code.co_filename)
430
Collin Winter88e333d2010-03-17 03:09:21 +0000431
Christian Heimes204093a2007-11-01 22:37:07 +0000432class PathsTests(unittest.TestCase):
433 SAMPLES = ('test', 'test\u00e4\u00f6\u00fc\u00df', 'test\u00e9\u00e8',
434 'test\u00b0\u00b3\u00b2')
Christian Heimes90333392007-11-01 19:08:42 +0000435 path = TESTFN
436
437 def setUp(self):
438 os.mkdir(self.path)
439 self.syspath = sys.path[:]
440
441 def tearDown(self):
Florent Xicluna27354cc2010-08-16 18:41:19 +0000442 rmtree(self.path)
Nick Coghlan6ead5522009-10-18 13:19:33 +0000443 sys.path[:] = self.syspath
Christian Heimes90333392007-11-01 19:08:42 +0000444
Collin Winter88e333d2010-03-17 03:09:21 +0000445 # Regression test for http://bugs.python.org/issue1293.
Christian Heimes1d1a4002007-11-01 19:41:07 +0000446 def test_trailing_slash(self):
Collin Winter88e333d2010-03-17 03:09:21 +0000447 with open(os.path.join(self.path, 'test_trailing_slash.py'), 'w') as f:
448 f.write("testdata = 'test_trailing_slash'")
Christian Heimes1d1a4002007-11-01 19:41:07 +0000449 sys.path.append(self.path+'/')
450 mod = __import__("test_trailing_slash")
451 self.assertEqual(mod.testdata, 'test_trailing_slash')
452 unload("test_trailing_slash")
453
Collin Winter88e333d2010-03-17 03:09:21 +0000454 # Regression test for http://bugs.python.org/issue3677.
Brett Cannonbbdc9cd2012-04-20 16:29:39 -0400455 @unittest.skipUnless(sys.platform == 'win32', 'Windows-specific')
Brett Cannon9e924ed2012-04-20 17:34:59 -0400456 def test_UNC_path(self):
Antoine Pitrouf189e802012-07-12 19:48:49 +0200457 with open(os.path.join(self.path, 'test_unc_path.py'), 'w') as f:
458 f.write("testdata = 'test_unc_path'")
Brett Cannonb8c02062012-04-21 19:11:58 -0400459 importlib.invalidate_caches()
Collin Winter88e333d2010-03-17 03:09:21 +0000460 # Create the UNC path, like \\myhost\c$\foo\bar.
Kristján Valur Jónssond9aab512009-01-24 10:50:45 +0000461 path = os.path.abspath(self.path)
462 import socket
463 hn = socket.gethostname()
464 drive = path[0]
465 unc = "\\\\%s\\%s$"%(hn, drive)
466 unc += path[2:]
Brett Cannonb8c02062012-04-21 19:11:58 -0400467 try:
Antoine Pitrou5df02042012-07-12 19:50:03 +0200468 os.listdir(unc)
Antoine Pitrou68f42472012-07-13 20:54:42 +0200469 except OSError as e:
470 if e.errno in (errno.EPERM, errno.EACCES):
471 # See issue #15338
472 self.skipTest("cannot access administrative share %r" % (unc,))
473 raise
Antoine Pitrouc27ace62012-07-13 20:59:19 +0200474 sys.path.insert(0, unc)
475 try:
476 mod = __import__("test_unc_path")
477 except ImportError as e:
478 self.fail("could not import 'test_unc_path' from %r: %r"
479 % (unc, e))
480 self.assertEqual(mod.testdata, 'test_unc_path')
481 self.assertTrue(mod.__file__.startswith(unc), mod.__file__)
482 unload("test_unc_path")
Kristján Valur Jónssond9aab512009-01-24 10:50:45 +0000483
Kristján Valur Jónssond9aab512009-01-24 10:50:45 +0000484
Collin Winter88e333d2010-03-17 03:09:21 +0000485class RelativeImportTests(unittest.TestCase):
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000486
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000487 def tearDown(self):
Florent Xicluna8fbddf12010-03-17 20:29:51 +0000488 unload("test.relimport")
489 setUp = tearDown
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000490
491 def test_relimport_star(self):
492 # This will import * from .test_import.
493 from . import relimport
Collin Winter88e333d2010-03-17 03:09:21 +0000494 self.assertTrue(hasattr(relimport, "RelativeImportTests"))
Christian Heimesd5e2b6f2008-03-19 21:50:51 +0000495
Georg Brandl2ee470f2008-07-16 12:55:28 +0000496 def test_issue3221(self):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000497 # Note for mergers: the 'absolute' tests from the 2.x branch
498 # are missing in Py3k because implicit relative imports are
499 # a thing of the past
Collin Winter88e333d2010-03-17 03:09:21 +0000500 #
501 # Regression test for http://bugs.python.org/issue3221.
Georg Brandl2ee470f2008-07-16 12:55:28 +0000502 def check_relative():
503 exec("from . import relimport", ns)
Collin Winter88e333d2010-03-17 03:09:21 +0000504
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000505 # Check relative import OK with __package__ and __name__ correct
Georg Brandl2ee470f2008-07-16 12:55:28 +0000506 ns = dict(__package__='test', __name__='test.notarealmodule')
507 check_relative()
Collin Winter88e333d2010-03-17 03:09:21 +0000508
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000509 # Check relative import OK with only __name__ wrong
Georg Brandl2ee470f2008-07-16 12:55:28 +0000510 ns = dict(__package__='test', __name__='notarealpkg.notarealmodule')
511 check_relative()
Collin Winter88e333d2010-03-17 03:09:21 +0000512
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000513 # Check relative import fails with only __package__ wrong
Georg Brandl2ee470f2008-07-16 12:55:28 +0000514 ns = dict(__package__='foo', __name__='test.notarealmodule')
515 self.assertRaises(SystemError, check_relative)
Collin Winter88e333d2010-03-17 03:09:21 +0000516
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000517 # Check relative import fails with __package__ and __name__ wrong
Georg Brandl2ee470f2008-07-16 12:55:28 +0000518 ns = dict(__package__='foo', __name__='notarealpkg.notarealmodule')
519 self.assertRaises(SystemError, check_relative)
Collin Winter88e333d2010-03-17 03:09:21 +0000520
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000521 # Check relative import fails with package set to a non-string
Georg Brandl2ee470f2008-07-16 12:55:28 +0000522 ns = dict(__package__=object())
Brett Cannonfd074152012-04-14 14:10:13 -0400523 self.assertRaises(TypeError, check_relative)
Georg Brandl2ee470f2008-07-16 12:55:28 +0000524
Benjamin Peterson556d8002010-06-27 22:37:28 +0000525 def test_absolute_import_without_future(self):
Florent Xicluna27354cc2010-08-16 18:41:19 +0000526 # If explicit relative import syntax is used, then do not try
Florent Xiclunac9c29e22010-08-16 19:03:05 +0000527 # to perform an absolute import in the face of failure.
Benjamin Peterson556d8002010-06-27 22:37:28 +0000528 # Issue #7902.
Florent Xicluna27354cc2010-08-16 18:41:19 +0000529 with self.assertRaises(ImportError):
Benjamin Peterson556d8002010-06-27 22:37:28 +0000530 from .os import sep
Benjamin Peterson556d8002010-06-27 22:37:28 +0000531 self.fail("explicit relative import triggered an "
Florent Xicluna27354cc2010-08-16 18:41:19 +0000532 "implicit absolute import")
Collin Winter88e333d2010-03-17 03:09:21 +0000533
Florent Xiclunac9c29e22010-08-16 19:03:05 +0000534
Collin Winter6498cff2010-03-17 03:14:31 +0000535class OverridingImportBuiltinTests(unittest.TestCase):
536 def test_override_builtin(self):
537 # Test that overriding builtins.__import__ can bypass sys.modules.
538 import os
539
540 def foo():
541 import os
542 return os
543 self.assertEqual(foo(), os) # Quick sanity check.
544
545 with swap_attr(builtins, "__import__", lambda *x: 5):
546 self.assertEqual(foo(), 5)
547
548 # Test what happens when we shadow __import__ in globals(); this
549 # currently does not impact the import process, but if this changes,
550 # other code will need to change, so keep this test as a tripwire.
551 with swap_item(globals(), "__import__", lambda *x: 5):
552 self.assertEqual(foo(), os)
553
554
Barry Warsaw28a691b2010-04-17 00:19:56 +0000555class PycacheTests(unittest.TestCase):
556 # Test the various PEP 3147 related behaviors.
557
558 tag = imp.get_tag()
559
560 def _clean(self):
561 forget(TESTFN)
562 rmtree('__pycache__')
563 unlink(self.source)
564
565 def setUp(self):
566 self.source = TESTFN + '.py'
567 self._clean()
568 with open(self.source, 'w') as fp:
569 print('# This is a test file written by test_import.py', file=fp)
570 sys.path.insert(0, os.curdir)
Antoine Pitrouc541f8e2012-02-20 01:48:16 +0100571 importlib.invalidate_caches()
Barry Warsaw28a691b2010-04-17 00:19:56 +0000572
573 def tearDown(self):
574 assert sys.path[0] == os.curdir, 'Unexpected sys.path[0]'
575 del sys.path[0]
576 self._clean()
577
578 def test_import_pyc_path(self):
579 self.assertFalse(os.path.exists('__pycache__'))
580 __import__(TESTFN)
581 self.assertTrue(os.path.exists('__pycache__'))
582 self.assertTrue(os.path.exists(os.path.join(
Georg Brandlfb3c84a2010-10-14 07:24:28 +0000583 '__pycache__', '{}.{}.py{}'.format(
Georg Brandl1c2a7b72010-10-14 07:34:56 +0000584 TESTFN, self.tag, __debug__ and 'c' or 'o'))))
Barry Warsaw28a691b2010-04-17 00:19:56 +0000585
586 @unittest.skipUnless(os.name == 'posix',
587 "test meaningful only on posix systems")
Charles-François Natali035018d2011-10-04 23:35:47 +0200588 @unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
Charles-François Natali79164c82011-10-04 20:40:58 +0200589 "due to varying filesystem permission semantics (issue #11956)")
Barry Warsaw28a691b2010-04-17 00:19:56 +0000590 def test_unwritable_directory(self):
591 # When the umask causes the new __pycache__ directory to be
592 # unwritable, the import still succeeds but no .pyc file is written.
593 with temp_umask(0o222):
594 __import__(TESTFN)
595 self.assertTrue(os.path.exists('__pycache__'))
596 self.assertFalse(os.path.exists(os.path.join(
597 '__pycache__', '{}.{}.pyc'.format(TESTFN, self.tag))))
598
599 def test_missing_source(self):
600 # With PEP 3147 cache layout, removing the source but leaving the pyc
601 # file does not satisfy the import.
602 __import__(TESTFN)
603 pyc_file = imp.cache_from_source(self.source)
604 self.assertTrue(os.path.exists(pyc_file))
605 os.remove(self.source)
606 forget(TESTFN)
607 self.assertRaises(ImportError, __import__, TESTFN)
608
609 def test_missing_source_legacy(self):
610 # Like test_missing_source() except that for backward compatibility,
611 # when the pyc file lives where the py file would have been (and named
612 # without the tag), it is importable. The __file__ of the imported
613 # module is the pyc location.
614 __import__(TESTFN)
615 # pyc_file gets removed in _clean() via tearDown().
616 pyc_file = make_legacy_pyc(self.source)
617 os.remove(self.source)
618 unload(TESTFN)
Antoine Pitrouc541f8e2012-02-20 01:48:16 +0100619 importlib.invalidate_caches()
Barry Warsaw28a691b2010-04-17 00:19:56 +0000620 m = __import__(TESTFN)
621 self.assertEqual(m.__file__,
622 os.path.join(os.curdir, os.path.relpath(pyc_file)))
623
624 def test___cached__(self):
625 # Modules now also have an __cached__ that points to the pyc file.
626 m = __import__(TESTFN)
627 pyc_file = imp.cache_from_source(TESTFN + '.py')
628 self.assertEqual(m.__cached__, os.path.join(os.curdir, pyc_file))
629
630 def test___cached___legacy_pyc(self):
631 # Like test___cached__() except that for backward compatibility,
632 # when the pyc file lives where the py file would have been (and named
633 # without the tag), it is importable. The __cached__ of the imported
634 # module is the pyc location.
635 __import__(TESTFN)
636 # pyc_file gets removed in _clean() via tearDown().
637 pyc_file = make_legacy_pyc(self.source)
638 os.remove(self.source)
639 unload(TESTFN)
Antoine Pitrouc541f8e2012-02-20 01:48:16 +0100640 importlib.invalidate_caches()
Barry Warsaw28a691b2010-04-17 00:19:56 +0000641 m = __import__(TESTFN)
642 self.assertEqual(m.__cached__,
643 os.path.join(os.curdir, os.path.relpath(pyc_file)))
644
645 def test_package___cached__(self):
646 # Like test___cached__ but for packages.
647 def cleanup():
Florent Xicluna27354cc2010-08-16 18:41:19 +0000648 rmtree('pep3147')
Antoine Pitroud4daa872012-06-23 18:09:55 +0200649 unload('pep3147.foo')
650 unload('pep3147')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000651 os.mkdir('pep3147')
652 self.addCleanup(cleanup)
653 # Touch the __init__.py
654 with open(os.path.join('pep3147', '__init__.py'), 'w'):
655 pass
656 with open(os.path.join('pep3147', 'foo.py'), 'w'):
657 pass
Brett Cannonfd074152012-04-14 14:10:13 -0400658 importlib.invalidate_caches()
Barry Warsaw28a691b2010-04-17 00:19:56 +0000659 m = __import__('pep3147.foo')
660 init_pyc = imp.cache_from_source(
661 os.path.join('pep3147', '__init__.py'))
662 self.assertEqual(m.__cached__, os.path.join(os.curdir, init_pyc))
663 foo_pyc = imp.cache_from_source(os.path.join('pep3147', 'foo.py'))
664 self.assertEqual(sys.modules['pep3147.foo'].__cached__,
665 os.path.join(os.curdir, foo_pyc))
666
667 def test_package___cached___from_pyc(self):
668 # Like test___cached__ but ensuring __cached__ when imported from a
669 # PEP 3147 pyc file.
670 def cleanup():
Florent Xicluna27354cc2010-08-16 18:41:19 +0000671 rmtree('pep3147')
Antoine Pitroud4daa872012-06-23 18:09:55 +0200672 unload('pep3147.foo')
673 unload('pep3147')
Barry Warsaw28a691b2010-04-17 00:19:56 +0000674 os.mkdir('pep3147')
675 self.addCleanup(cleanup)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000676 # Touch the __init__.py
677 with open(os.path.join('pep3147', '__init__.py'), 'w'):
678 pass
679 with open(os.path.join('pep3147', 'foo.py'), 'w'):
680 pass
Brett Cannonfd074152012-04-14 14:10:13 -0400681 importlib.invalidate_caches()
Barry Warsaw28a691b2010-04-17 00:19:56 +0000682 m = __import__('pep3147.foo')
683 unload('pep3147.foo')
684 unload('pep3147')
Brett Cannonfd074152012-04-14 14:10:13 -0400685 importlib.invalidate_caches()
Barry Warsaw28a691b2010-04-17 00:19:56 +0000686 m = __import__('pep3147.foo')
687 init_pyc = imp.cache_from_source(
688 os.path.join('pep3147', '__init__.py'))
689 self.assertEqual(m.__cached__, os.path.join(os.curdir, init_pyc))
690 foo_pyc = imp.cache_from_source(os.path.join('pep3147', 'foo.py'))
691 self.assertEqual(sys.modules['pep3147.foo'].__cached__,
692 os.path.join(os.curdir, foo_pyc))
693
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100694 def test_recompute_pyc_same_second(self):
695 # Even when the source file doesn't change timestamp, a change in
696 # source size is enough to trigger recomputation of the pyc file.
697 __import__(TESTFN)
698 unload(TESTFN)
699 with open(self.source, 'a') as fp:
700 print("x = 5", file=fp)
701 m = __import__(TESTFN)
702 self.assertEqual(m.x, 5)
703
Barry Warsaw28a691b2010-04-17 00:19:56 +0000704
Jason R. Coombs71fde312012-06-17 03:53:47 -0400705class TestSymbolicallyLinkedPackage(unittest.TestCase):
706 package_name = 'sample'
Brett Cannon6ee96952012-07-20 14:22:04 -0400707 tagged = package_name + '-tagged'
Jason R. Coombs71fde312012-06-17 03:53:47 -0400708
709 def setUp(self):
Brett Cannon6ee96952012-07-20 14:22:04 -0400710 test.support.rmtree(self.tagged)
711 test.support.rmtree(self.package_name)
Jason R. Coombs71fde312012-06-17 03:53:47 -0400712 self.orig_sys_path = sys.path[:]
713
714 # create a sample package; imagine you have a package with a tag and
715 # you want to symbolically link it from its untagged name.
716 os.mkdir(self.tagged)
Brett Cannon6ee96952012-07-20 14:22:04 -0400717 self.addCleanup(test.support.rmtree, self.tagged)
Jason R. Coombs71fde312012-06-17 03:53:47 -0400718 init_file = os.path.join(self.tagged, '__init__.py')
Brett Cannon6ee96952012-07-20 14:22:04 -0400719 test.support.create_empty_file(init_file)
720 assert os.path.exists(init_file)
Jason R. Coombs71fde312012-06-17 03:53:47 -0400721
722 # now create a symlink to the tagged package
723 # sample -> sample-tagged
724 os.symlink(self.tagged, self.package_name)
Brett Cannon6ee96952012-07-20 14:22:04 -0400725 self.addCleanup(test.support.unlink, self.package_name)
726 importlib.invalidate_caches()
Jason R. Coombs71fde312012-06-17 03:53:47 -0400727
Jason R. Coombs42c9b042012-06-20 10:24:24 -0400728 # disabled because os.isdir currently fails (see issue 15093)
729 # self.assertEqual(os.path.isdir(self.package_name), True)
730
Brett Cannon6ee96952012-07-20 14:22:04 -0400731 assert os.path.isfile(os.path.join(self.package_name, '__init__.py'))
Jason R. Coombs71fde312012-06-17 03:53:47 -0400732
Brett Cannon6ee96952012-07-20 14:22:04 -0400733 def tearDown(self):
734 sys.path[:] = self.orig_sys_path
Jason R. Coombs71fde312012-06-17 03:53:47 -0400735
736 # regression test for issue6727
737 @unittest.skipUnless(
738 not hasattr(sys, 'getwindowsversion')
739 or sys.getwindowsversion() >= (6, 0),
740 "Windows Vista or later required")
741 @test.support.skip_unless_symlink
742 def test_symlinked_dir_importable(self):
743 # make sure sample can only be imported from the current directory.
744 sys.path[:] = ['.']
Brett Cannon6ee96952012-07-20 14:22:04 -0400745 assert os.path.exists(self.package_name)
746 assert os.path.exists(os.path.join(self.package_name, '__init__.py'))
Jason R. Coombs71fde312012-06-17 03:53:47 -0400747
Brett Cannon6ee96952012-07-20 14:22:04 -0400748 # Try to import the package
749 importlib.import_module(self.package_name)
Jason R. Coombs71fde312012-06-17 03:53:47 -0400750
751
Antoine Pitrou48114b92012-06-17 22:33:38 +0200752@cpython_only
753class ImportlibBootstrapTests(unittest.TestCase):
754 # These tests check that importlib is bootstrapped.
755
756 def test_frozen_importlib(self):
757 mod = sys.modules['_frozen_importlib']
758 self.assertTrue(mod)
759
760 def test_frozen_importlib_is_bootstrap(self):
761 from importlib import _bootstrap
762 mod = sys.modules['_frozen_importlib']
763 self.assertIs(mod, _bootstrap)
764 self.assertEqual(mod.__name__, 'importlib._bootstrap')
765 self.assertEqual(mod.__package__, 'importlib')
766 self.assertTrue(mod.__file__.endswith('_bootstrap.py'), mod.__file__)
767
Nick Coghlanbe7e49f2012-07-20 23:40:09 +1000768 def test_there_can_be_only_one(self):
769 # Issue #15386 revealed a tricky loophole in the bootstrapping
770 # This test is technically redundant, since the bug caused importing
771 # this test module to crash completely, but it helps prove the point
772 from importlib import machinery
773 mod = sys.modules['_frozen_importlib']
774 self.assertIs(machinery.FileFinder, mod.FileFinder)
775 self.assertIs(imp.new_module, mod.new_module)
776
Antoine Pitrou48114b92012-06-17 22:33:38 +0200777
Antoine Pitroubc07a5c2012-07-08 12:01:27 +0200778class ImportTracebackTests(unittest.TestCase):
779
780 def setUp(self):
781 os.mkdir(TESTFN)
782 self.old_path = sys.path[:]
783 sys.path.insert(0, TESTFN)
784
785 def tearDown(self):
786 sys.path[:] = self.old_path
787 rmtree(TESTFN)
788
789 def create_module(self, mod, contents):
790 with open(os.path.join(TESTFN, mod + ".py"), "w") as f:
791 f.write(contents)
792 self.addCleanup(unload, mod)
793 importlib.invalidate_caches()
794
795 def assert_traceback(self, tb, files):
796 deduped_files = []
797 while tb:
798 code = tb.tb_frame.f_code
799 fn = code.co_filename
800 if not deduped_files or fn != deduped_files[-1]:
801 deduped_files.append(fn)
802 tb = tb.tb_next
803 self.assertEqual(len(deduped_files), len(files), deduped_files)
804 for fn, pat in zip(deduped_files, files):
Antoine Pitrou68038552012-07-08 13:16:15 +0200805 self.assertIn(pat, fn)
Antoine Pitroubc07a5c2012-07-08 12:01:27 +0200806
807 def test_nonexistent_module(self):
808 try:
809 # assertRaises() clears __traceback__
810 import nonexistent_xyzzy
811 except ImportError as e:
812 tb = e.__traceback__
813 else:
814 self.fail("ImportError should have been raised")
815 self.assert_traceback(tb, [__file__])
816
817 def test_nonexistent_module_nested(self):
818 self.create_module("foo", "import nonexistent_xyzzy")
819 try:
820 import foo
821 except ImportError as e:
822 tb = e.__traceback__
823 else:
824 self.fail("ImportError should have been raised")
825 self.assert_traceback(tb, [__file__, 'foo.py'])
826
827 def test_exec_failure(self):
828 self.create_module("foo", "1/0")
829 try:
830 import foo
831 except ZeroDivisionError as e:
832 tb = e.__traceback__
833 else:
834 self.fail("ZeroDivisionError should have been raised")
835 self.assert_traceback(tb, [__file__, 'foo.py'])
836
837 def test_exec_failure_nested(self):
838 self.create_module("foo", "import bar")
839 self.create_module("bar", "1/0")
840 try:
841 import foo
842 except ZeroDivisionError as e:
843 tb = e.__traceback__
844 else:
845 self.fail("ZeroDivisionError should have been raised")
846 self.assert_traceback(tb, [__file__, 'foo.py', 'bar.py'])
847
848 @cpython_only
849 def test_import_bug(self):
850 # We simulate a bug in importlib and check that it's not stripped
851 # away from the traceback.
852 self.create_module("foo", "")
853 importlib = sys.modules['_frozen_importlib']
854 old_load_module = importlib.SourceLoader.load_module
855 try:
856 def load_module(*args):
857 1/0
858 importlib.SourceLoader.load_module = load_module
859 try:
860 import foo
861 except ZeroDivisionError as e:
862 tb = e.__traceback__
863 else:
864 self.fail("ZeroDivisionError should have been raised")
865 self.assert_traceback(tb, [__file__, '<frozen importlib', __file__])
866 finally:
867 importlib.SourceLoader.load_module = old_load_module
868
869
Thomas Wouters89f507f2006-12-13 04:49:30 +0000870def test_main(verbose=None):
Brett Cannonba525862012-07-20 14:01:34 -0400871 run_unittest(ImportTests, PycacheTests,
872 PycRewritingTests, PathsTests, RelativeImportTests,
873 OverridingImportBuiltinTests,
874 ImportlibBootstrapTests,
875 TestSymbolicallyLinkedPackage,
876 ImportTracebackTests)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000877
Barry Warsaw28a691b2010-04-17 00:19:56 +0000878
Thomas Wouters89f507f2006-12-13 04:49:30 +0000879if __name__ == '__main__':
Collin Winter88e333d2010-03-17 03:09:21 +0000880 # Test needs to be a package, so we can do relative imports.
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000881 from test.test_import import test_main
Thomas Wouters89f507f2006-12-13 04:49:30 +0000882 test_main()