blob: 3c3ba89d7596eed60eba1188a5777a22e86d1b1e [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 Cannon53089c62012-07-04 14:03:40 -04004from importlib import machinery
Brett Cannon2c318a12009-02-07 01:15:27 +00005import sys
Brett Cannon53089c62012-07-04 14:03:40 -04006from test import support
Brett Cannone7387b42013-02-01 14:43:59 -05007import types
Brett Cannon2c318a12009-02-07 01:15:27 +00008import unittest
Brett Cannon23cbd8a2009-01-18 00:24:28 +00009
10
11class ImportModuleTests(unittest.TestCase):
12
13 """Test importlib.import_module."""
14
15 def test_module_import(self):
16 # Test importing a top-level module.
Brett Cannonbcb26c52009-02-01 04:00:05 +000017 with util.mock_modules('top_level') as mock:
18 with util.import_state(meta_path=[mock]):
Brett Cannon23cbd8a2009-01-18 00:24:28 +000019 module = importlib.import_module('top_level')
20 self.assertEqual(module.__name__, 'top_level')
21
22 def test_absolute_package_import(self):
23 # Test importing a module from a package with an absolute name.
24 pkg_name = 'pkg'
25 pkg_long_name = '{0}.__init__'.format(pkg_name)
26 name = '{0}.mod'.format(pkg_name)
Brett Cannonbcb26c52009-02-01 04:00:05 +000027 with util.mock_modules(pkg_long_name, name) as mock:
28 with util.import_state(meta_path=[mock]):
Brett Cannon23cbd8a2009-01-18 00:24:28 +000029 module = importlib.import_module(name)
30 self.assertEqual(module.__name__, name)
31
Brett Cannonb5f03c62009-03-04 01:02:54 +000032 def test_shallow_relative_package_import(self):
Brett Cannon2cf15852010-07-03 22:03:16 +000033 # Test importing a module from a package through a relative import.
Brett Cannon23cbd8a2009-01-18 00:24:28 +000034 pkg_name = 'pkg'
35 pkg_long_name = '{0}.__init__'.format(pkg_name)
36 module_name = 'mod'
37 absolute_name = '{0}.{1}'.format(pkg_name, module_name)
38 relative_name = '.{0}'.format(module_name)
Brett Cannonbcb26c52009-02-01 04:00:05 +000039 with util.mock_modules(pkg_long_name, absolute_name) as mock:
40 with util.import_state(meta_path=[mock]):
Brett Cannon2c318a12009-02-07 01:15:27 +000041 importlib.import_module(pkg_name)
Brett Cannon23cbd8a2009-01-18 00:24:28 +000042 module = importlib.import_module(relative_name, pkg_name)
43 self.assertEqual(module.__name__, absolute_name)
44
Brett Cannonb5f03c62009-03-04 01:02:54 +000045 def test_deep_relative_package_import(self):
46 modules = ['a.__init__', 'a.b.__init__', 'a.c']
47 with util.mock_modules(*modules) as mock:
48 with util.import_state(meta_path=[mock]):
49 importlib.import_module('a')
50 importlib.import_module('a.b')
51 module = importlib.import_module('..c', 'a.b')
52 self.assertEqual(module.__name__, 'a.c')
53
Brett Cannon23cbd8a2009-01-18 00:24:28 +000054 def test_absolute_import_with_package(self):
55 # Test importing a module from a package with an absolute name with
56 # the 'package' argument given.
57 pkg_name = 'pkg'
58 pkg_long_name = '{0}.__init__'.format(pkg_name)
59 name = '{0}.mod'.format(pkg_name)
Brett Cannonbcb26c52009-02-01 04:00:05 +000060 with util.mock_modules(pkg_long_name, name) as mock:
61 with util.import_state(meta_path=[mock]):
Brett Cannon2c318a12009-02-07 01:15:27 +000062 importlib.import_module(pkg_name)
Brett Cannon23cbd8a2009-01-18 00:24:28 +000063 module = importlib.import_module(name, pkg_name)
64 self.assertEqual(module.__name__, name)
65
66 def test_relative_import_wo_package(self):
67 # Relative imports cannot happen without the 'package' argument being
68 # set.
Brett Cannon2153dc02009-08-27 23:49:21 +000069 with self.assertRaises(TypeError):
70 importlib.import_module('.support')
Brett Cannon23cbd8a2009-01-18 00:24:28 +000071
72
Meador Inge416f12d2011-12-14 22:23:46 -060073 def test_loaded_once(self):
74 # Issue #13591: Modules should only be loaded once when
75 # initializing the parent package attempts to import the
76 # module currently being imported.
77 b_load_count = 0
78 def load_a():
79 importlib.import_module('a.b')
80 def load_b():
81 nonlocal b_load_count
82 b_load_count += 1
83 code = {'a': load_a, 'a.b': load_b}
84 modules = ['a.__init__', 'a.b']
85 with util.mock_modules(*modules, module_code=code) as mock:
86 with util.import_state(meta_path=[mock]):
87 importlib.import_module('a.b')
88 self.assertEqual(b_load_count, 1)
89
Brett Cannonb46a1792012-02-27 18:15:42 -050090
Brett Cannonee78a2b2012-05-12 17:43:17 -040091class FindLoaderTests(unittest.TestCase):
92
93 class FakeMetaFinder:
94 @staticmethod
95 def find_module(name, path=None): return name, path
96
97 def test_sys_modules(self):
98 # If a module with __loader__ is in sys.modules, then return it.
99 name = 'some_mod'
100 with util.uncache(name):
101 module = imp.new_module(name)
102 loader = 'a loader!'
103 module.__loader__ = loader
104 sys.modules[name] = module
105 found = importlib.find_loader(name)
106 self.assertEqual(loader, found)
107
108 def test_sys_modules_loader_is_None(self):
109 # If sys.modules[name].__loader__ is None, raise ValueError.
110 name = 'some_mod'
111 with util.uncache(name):
112 module = imp.new_module(name)
113 module.__loader__ = None
114 sys.modules[name] = module
115 with self.assertRaises(ValueError):
116 importlib.find_loader(name)
117
118 def test_success(self):
119 # Return the loader found on sys.meta_path.
120 name = 'some_mod'
121 with util.uncache(name):
122 with util.import_state(meta_path=[self.FakeMetaFinder]):
123 self.assertEqual((name, None), importlib.find_loader(name))
124
125 def test_success_path(self):
126 # Searching on a path should work.
127 name = 'some_mod'
128 path = 'path to some place'
129 with util.uncache(name):
130 with util.import_state(meta_path=[self.FakeMetaFinder]):
131 self.assertEqual((name, path),
132 importlib.find_loader(name, path))
133
134 def test_nothing(self):
135 # None is returned upon failure to find a loader.
136 self.assertIsNone(importlib.find_loader('nevergoingtofindthismodule'))
137
138
Brett Cannonb46a1792012-02-27 18:15:42 -0500139class InvalidateCacheTests(unittest.TestCase):
140
141 def test_method_called(self):
142 # If defined the method should be called.
143 class InvalidatingNullFinder:
144 def __init__(self, *ignored):
145 self.called = False
146 def find_module(self, *args):
147 return None
148 def invalidate_caches(self):
149 self.called = True
150
151 key = 'gobledeegook'
Brett Cannonf4dc9202012-08-10 12:21:12 -0400152 meta_ins = InvalidatingNullFinder()
153 path_ins = InvalidatingNullFinder()
154 sys.meta_path.insert(0, meta_ins)
Brett Cannonb46a1792012-02-27 18:15:42 -0500155 self.addCleanup(lambda: sys.path_importer_cache.__delitem__(key))
Brett Cannonf4dc9202012-08-10 12:21:12 -0400156 sys.path_importer_cache[key] = path_ins
157 self.addCleanup(lambda: sys.meta_path.remove(meta_ins))
Brett Cannonb46a1792012-02-27 18:15:42 -0500158 importlib.invalidate_caches()
Brett Cannonf4dc9202012-08-10 12:21:12 -0400159 self.assertTrue(meta_ins.called)
160 self.assertTrue(path_ins.called)
Brett Cannonb46a1792012-02-27 18:15:42 -0500161
162 def test_method_lacking(self):
163 # There should be no issues if the method is not defined.
164 key = 'gobbledeegook'
165 sys.path_importer_cache[key] = imp.NullImporter('abc')
166 self.addCleanup(lambda: sys.path_importer_cache.__delitem__(key))
167 importlib.invalidate_caches() # Shouldn't trigger an exception.
168
169
Brett Cannon8e2f5562012-07-02 14:53:10 -0400170class FrozenImportlibTests(unittest.TestCase):
171
172 def test_no_frozen_importlib(self):
173 # Should be able to import w/o _frozen_importlib being defined.
Brett Cannon53089c62012-07-04 14:03:40 -0400174 module = support.import_fresh_module('importlib', blocked=['_frozen_importlib'])
175 self.assertFalse(isinstance(module.__loader__,
176 machinery.FrozenImporter))
Brett Cannon8e2f5562012-07-02 14:53:10 -0400177
178
Brett Cannone7387b42013-02-01 14:43:59 -0500179class StartupTests(unittest.TestCase):
180
181 def test_everyone_has___loader__(self):
182 # Issue #17098: all modules should have __loader__ defined.
183 for name, module in sys.modules.items():
184 if isinstance(module, types.ModuleType):
185 self.assertTrue(hasattr(module, '__loader__'),
186 '{!r} lacks a __loader__ attribute'.format(name))
187
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000188def test_main():
189 from test.support import run_unittest
Brett Cannon8e2f5562012-07-02 14:53:10 -0400190 run_unittest(ImportModuleTests,
191 FindLoaderTests,
192 InvalidateCacheTests,
Brett Cannone7387b42013-02-01 14:43:59 -0500193 FrozenImportlibTests,
194 StartupTests)
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000195
196
197if __name__ == '__main__':
198 test_main()