blob: 297d6cbef66e1d5eb1ddda9643d6ab5a5571381f [file] [log] [blame]
Brett Cannonbcb26c52009-02-01 04:00:05 +00001from . import util
Brett Cannon2c318a12009-02-07 01:15:27 +00002import imp
3import importlib
Brett Cannon85ae3562013-02-01 16:36:29 -05004from importlib import _bootstrap
Brett Cannon53089c62012-07-04 14:03:40 -04005from importlib import machinery
Brett Cannon2c318a12009-02-07 01:15:27 +00006import sys
Brett Cannon53089c62012-07-04 14:03:40 -04007from test import support
Brett Cannone7387b42013-02-01 14:43:59 -05008import types
Brett Cannon2c318a12009-02-07 01:15:27 +00009import unittest
Brett Cannon23cbd8a2009-01-18 00:24:28 +000010
11
12class ImportModuleTests(unittest.TestCase):
13
14 """Test importlib.import_module."""
15
16 def test_module_import(self):
17 # Test importing a top-level module.
Brett Cannonbcb26c52009-02-01 04:00:05 +000018 with util.mock_modules('top_level') as mock:
19 with util.import_state(meta_path=[mock]):
Brett Cannon23cbd8a2009-01-18 00:24:28 +000020 module = importlib.import_module('top_level')
21 self.assertEqual(module.__name__, 'top_level')
22
23 def test_absolute_package_import(self):
24 # Test importing a module from a package with an absolute name.
25 pkg_name = 'pkg'
26 pkg_long_name = '{0}.__init__'.format(pkg_name)
27 name = '{0}.mod'.format(pkg_name)
Brett Cannonbcb26c52009-02-01 04:00:05 +000028 with util.mock_modules(pkg_long_name, name) as mock:
29 with util.import_state(meta_path=[mock]):
Brett Cannon23cbd8a2009-01-18 00:24:28 +000030 module = importlib.import_module(name)
31 self.assertEqual(module.__name__, name)
32
Brett Cannonb5f03c62009-03-04 01:02:54 +000033 def test_shallow_relative_package_import(self):
Brett Cannon2cf15852010-07-03 22:03:16 +000034 # Test importing a module from a package through a relative import.
Brett Cannon23cbd8a2009-01-18 00:24:28 +000035 pkg_name = 'pkg'
36 pkg_long_name = '{0}.__init__'.format(pkg_name)
37 module_name = 'mod'
38 absolute_name = '{0}.{1}'.format(pkg_name, module_name)
39 relative_name = '.{0}'.format(module_name)
Brett Cannonbcb26c52009-02-01 04:00:05 +000040 with util.mock_modules(pkg_long_name, absolute_name) as mock:
41 with util.import_state(meta_path=[mock]):
Brett Cannon2c318a12009-02-07 01:15:27 +000042 importlib.import_module(pkg_name)
Brett Cannon23cbd8a2009-01-18 00:24:28 +000043 module = importlib.import_module(relative_name, pkg_name)
44 self.assertEqual(module.__name__, absolute_name)
45
Brett Cannonb5f03c62009-03-04 01:02:54 +000046 def test_deep_relative_package_import(self):
47 modules = ['a.__init__', 'a.b.__init__', 'a.c']
48 with util.mock_modules(*modules) as mock:
49 with util.import_state(meta_path=[mock]):
50 importlib.import_module('a')
51 importlib.import_module('a.b')
52 module = importlib.import_module('..c', 'a.b')
53 self.assertEqual(module.__name__, 'a.c')
54
Brett Cannon23cbd8a2009-01-18 00:24:28 +000055 def test_absolute_import_with_package(self):
56 # Test importing a module from a package with an absolute name with
57 # the 'package' argument given.
58 pkg_name = 'pkg'
59 pkg_long_name = '{0}.__init__'.format(pkg_name)
60 name = '{0}.mod'.format(pkg_name)
Brett Cannonbcb26c52009-02-01 04:00:05 +000061 with util.mock_modules(pkg_long_name, name) as mock:
62 with util.import_state(meta_path=[mock]):
Brett Cannon2c318a12009-02-07 01:15:27 +000063 importlib.import_module(pkg_name)
Brett Cannon23cbd8a2009-01-18 00:24:28 +000064 module = importlib.import_module(name, pkg_name)
65 self.assertEqual(module.__name__, name)
66
67 def test_relative_import_wo_package(self):
68 # Relative imports cannot happen without the 'package' argument being
69 # set.
Brett Cannon2153dc02009-08-27 23:49:21 +000070 with self.assertRaises(TypeError):
71 importlib.import_module('.support')
Brett Cannon23cbd8a2009-01-18 00:24:28 +000072
73
Meador Inge416f12d2011-12-14 22:23:46 -060074 def test_loaded_once(self):
75 # Issue #13591: Modules should only be loaded once when
76 # initializing the parent package attempts to import the
77 # module currently being imported.
78 b_load_count = 0
79 def load_a():
80 importlib.import_module('a.b')
81 def load_b():
82 nonlocal b_load_count
83 b_load_count += 1
84 code = {'a': load_a, 'a.b': load_b}
85 modules = ['a.__init__', 'a.b']
86 with util.mock_modules(*modules, module_code=code) as mock:
87 with util.import_state(meta_path=[mock]):
88 importlib.import_module('a.b')
89 self.assertEqual(b_load_count, 1)
90
Brett Cannonb46a1792012-02-27 18:15:42 -050091
Brett Cannonee78a2b2012-05-12 17:43:17 -040092class FindLoaderTests(unittest.TestCase):
93
94 class FakeMetaFinder:
95 @staticmethod
96 def find_module(name, path=None): return name, path
97
98 def test_sys_modules(self):
99 # If a module with __loader__ is in sys.modules, then return it.
100 name = 'some_mod'
101 with util.uncache(name):
102 module = imp.new_module(name)
103 loader = 'a loader!'
104 module.__loader__ = loader
105 sys.modules[name] = module
106 found = importlib.find_loader(name)
107 self.assertEqual(loader, found)
108
109 def test_sys_modules_loader_is_None(self):
110 # If sys.modules[name].__loader__ is None, raise ValueError.
111 name = 'some_mod'
112 with util.uncache(name):
113 module = imp.new_module(name)
114 module.__loader__ = None
115 sys.modules[name] = module
116 with self.assertRaises(ValueError):
117 importlib.find_loader(name)
118
Brett Cannon32799232013-03-13 11:09:08 -0700119 def test_sys_modules_loader_is_not_set(self):
120 # Should raise ValueError
121 # Issue #17099
122 name = 'some_mod'
123 with util.uncache(name):
124 module = imp.new_module(name)
125 try:
126 del module.__loader__
127 except AttributeError:
128 pass
129 sys.modules[name] = module
130 with self.assertRaises(ValueError):
131 importlib.find_loader(name)
132
Brett Cannonee78a2b2012-05-12 17:43:17 -0400133 def test_success(self):
134 # Return the loader found on sys.meta_path.
135 name = 'some_mod'
136 with util.uncache(name):
137 with util.import_state(meta_path=[self.FakeMetaFinder]):
138 self.assertEqual((name, None), importlib.find_loader(name))
139
140 def test_success_path(self):
141 # Searching on a path should work.
142 name = 'some_mod'
143 path = 'path to some place'
144 with util.uncache(name):
145 with util.import_state(meta_path=[self.FakeMetaFinder]):
146 self.assertEqual((name, path),
147 importlib.find_loader(name, path))
148
149 def test_nothing(self):
150 # None is returned upon failure to find a loader.
151 self.assertIsNone(importlib.find_loader('nevergoingtofindthismodule'))
152
153
Brett Cannonb46a1792012-02-27 18:15:42 -0500154class InvalidateCacheTests(unittest.TestCase):
155
156 def test_method_called(self):
157 # If defined the method should be called.
158 class InvalidatingNullFinder:
159 def __init__(self, *ignored):
160 self.called = False
161 def find_module(self, *args):
162 return None
163 def invalidate_caches(self):
164 self.called = True
165
166 key = 'gobledeegook'
Brett Cannonf4dc9202012-08-10 12:21:12 -0400167 meta_ins = InvalidatingNullFinder()
168 path_ins = InvalidatingNullFinder()
169 sys.meta_path.insert(0, meta_ins)
Brett Cannonb46a1792012-02-27 18:15:42 -0500170 self.addCleanup(lambda: sys.path_importer_cache.__delitem__(key))
Brett Cannonf4dc9202012-08-10 12:21:12 -0400171 sys.path_importer_cache[key] = path_ins
172 self.addCleanup(lambda: sys.meta_path.remove(meta_ins))
Brett Cannonb46a1792012-02-27 18:15:42 -0500173 importlib.invalidate_caches()
Brett Cannonf4dc9202012-08-10 12:21:12 -0400174 self.assertTrue(meta_ins.called)
175 self.assertTrue(path_ins.called)
Brett Cannonb46a1792012-02-27 18:15:42 -0500176
177 def test_method_lacking(self):
178 # There should be no issues if the method is not defined.
179 key = 'gobbledeegook'
180 sys.path_importer_cache[key] = imp.NullImporter('abc')
181 self.addCleanup(lambda: sys.path_importer_cache.__delitem__(key))
182 importlib.invalidate_caches() # Shouldn't trigger an exception.
183
184
Brett Cannon8e2f5562012-07-02 14:53:10 -0400185class FrozenImportlibTests(unittest.TestCase):
186
187 def test_no_frozen_importlib(self):
188 # Should be able to import w/o _frozen_importlib being defined.
Brett Cannon53089c62012-07-04 14:03:40 -0400189 module = support.import_fresh_module('importlib', blocked=['_frozen_importlib'])
190 self.assertFalse(isinstance(module.__loader__,
191 machinery.FrozenImporter))
Brett Cannon8e2f5562012-07-02 14:53:10 -0400192
193
Brett Cannone7387b42013-02-01 14:43:59 -0500194class StartupTests(unittest.TestCase):
195
196 def test_everyone_has___loader__(self):
197 # Issue #17098: all modules should have __loader__ defined.
198 for name, module in sys.modules.items():
199 if isinstance(module, types.ModuleType):
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400200 self.assertTrue(hasattr(module, '__loader__'),
201 '{!r} lacks a __loader__ attribute'.format(name))
202 if importlib.machinery.BuiltinImporter.find_module(name):
203 self.assertIsNot(module.__loader__, None)
204 elif importlib.machinery.FrozenImporter.find_module(name):
205 self.assertIsNot(module.__loader__, None)
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000206
207
208if __name__ == '__main__':
Brett Cannonf41fa4f32013-02-01 14:51:43 -0500209 unittest.main()