1
"""Test that sys.modules is used properly by import."""
3
from . import util as import_util
5
from types import MethodType
11
"""When it comes to sys.modules, import prefers it over anything else.
13
Once a name has been resolved, sys.modules is checked to see if it contains
14
the module desired. If so, then it is returned [use cache]. If it is not
15
found, then the proper steps are taken to perform the import, but
16
sys.modules is still used to return the imported module (e.g., not what a
17
loader returns) [from cache on return]. This also applies to imports of
18
things contained within a package and thus get assigned as an attribute
19
[from cache to attribute] or pulled in thanks to a fromlist import
20
[from cache for fromlist]. But if sys.modules contains None then
21
ImportError is raised [None in cache].
25
def test_using_cache(self):
27
module_to_use = "some module found!"
28
with util.uncache('some_module'):
29
sys.modules['some_module'] = module_to_use
30
module = self.__import__('some_module')
31
self.assertEqual(id(module_to_use), id(module))
33
def test_None_in_cache(self):
36
with util.uncache(name):
37
sys.modules[name] = None
38
with self.assertRaises(ImportError) as cm:
40
self.assertEqual(cm.exception.name, name)
42
def create_mock(self, *names, return_=None):
43
mock = util.mock_modules(*names)
44
original_load = mock.load_module
45
def load_module(self, fullname):
46
original_load(fullname)
48
mock.load_module = MethodType(load_module, mock)
51
Frozen_UseCache, Source_UseCache = util.test_both(
52
UseCache, __import__=import_util.__import__)
55
class ImportlibUseCache(UseCache, unittest.TestCase):
57
__import__ = import_util.__import__[1]
59
# __import__ inconsistent between loaders and built-in import when it comes
60
# to when to use the module in sys.modules and when not to.
61
def test_using_cache_after_loader(self):
62
# [from cache on return]
63
with self.create_mock('module') as mock:
64
with util.import_state(meta_path=[mock]):
65
module = self.__import__('module')
66
self.assertEqual(id(module), id(sys.modules['module']))
68
# See test_using_cache_after_loader() for reasoning.
69
def test_using_cache_for_assigning_to_attribute(self):
70
# [from cache to attribute]
71
with self.create_mock('pkg.__init__', 'pkg.module') as importer:
72
with util.import_state(meta_path=[importer]):
73
module = self.__import__('pkg.module')
74
self.assertTrue(hasattr(module, 'module'))
75
self.assertEqual(id(module.module),
76
id(sys.modules['pkg.module']))
78
# See test_using_cache_after_loader() for reasoning.
79
def test_using_cache_for_fromlist(self):
80
# [from cache for fromlist]
81
with self.create_mock('pkg.__init__', 'pkg.module') as importer:
82
with util.import_state(meta_path=[importer]):
83
module = self.__import__('pkg', fromlist=['module'])
84
self.assertTrue(hasattr(module, 'module'))
85
self.assertEqual(id(module.module),
86
id(sys.modules['pkg.module']))
89
if __name__ == '__main__':