8
class ImportModuleTests(unittest.TestCase):
10
"""Test importlib.import_module."""
12
def test_module_import(self):
13
# Test importing a top-level module.
14
with util.mock_modules('top_level') as mock:
15
with util.import_state(meta_path=[mock]):
16
module = importlib.import_module('top_level')
17
self.assertEqual(module.__name__, 'top_level')
19
def test_absolute_package_import(self):
20
# Test importing a module from a package with an absolute name.
22
pkg_long_name = '{0}.__init__'.format(pkg_name)
23
name = '{0}.mod'.format(pkg_name)
24
with util.mock_modules(pkg_long_name, name) as mock:
25
with util.import_state(meta_path=[mock]):
26
module = importlib.import_module(name)
27
self.assertEqual(module.__name__, name)
29
def test_shallow_relative_package_import(self):
30
# Test importing a module from a package through a relatve import.
32
pkg_long_name = '{0}.__init__'.format(pkg_name)
34
absolute_name = '{0}.{1}'.format(pkg_name, module_name)
35
relative_name = '.{0}'.format(module_name)
36
with util.mock_modules(pkg_long_name, absolute_name) as mock:
37
with util.import_state(meta_path=[mock]):
38
importlib.import_module(pkg_name)
39
module = importlib.import_module(relative_name, pkg_name)
40
self.assertEqual(module.__name__, absolute_name)
42
def test_deep_relative_package_import(self):
43
modules = ['a.__init__', 'a.b.__init__', 'a.c']
44
with util.mock_modules(*modules) as mock:
45
with util.import_state(meta_path=[mock]):
46
importlib.import_module('a')
47
importlib.import_module('a.b')
48
module = importlib.import_module('..c', 'a.b')
49
self.assertEqual(module.__name__, 'a.c')
51
def test_absolute_import_with_package(self):
52
# Test importing a module from a package with an absolute name with
53
# the 'package' argument given.
55
pkg_long_name = '{0}.__init__'.format(pkg_name)
56
name = '{0}.mod'.format(pkg_name)
57
with util.mock_modules(pkg_long_name, name) as mock:
58
with util.import_state(meta_path=[mock]):
59
importlib.import_module(pkg_name)
60
module = importlib.import_module(name, pkg_name)
61
self.assertEqual(module.__name__, name)
63
def test_relative_import_wo_package(self):
64
# Relative imports cannot happen without the 'package' argument being
66
self.assertRaises(TypeError, importlib.import_module, '.support')
70
from test.support import run_unittest
71
run_unittest(ImportModuleTests)
74
if __name__ == '__main__':