Debian Codegraph @

Lib/test/test_importlib/test_lazy.py

raw
1 import importlib
2 from importlib import abc
3 from importlib import util
4 import sys
5 import time
6 import threading
7 import types
8 import unittest
9
10 from test.support import threading_helper
11 from test.test_importlib import util as test_util
12 from test.support.testcase import ExtraAssertions
13
14
15 class CollectInit:
16
17 def __init__(self, *args, **kwargs):
18 self.args = args
19 self.kwargs = kwargs
20
21 def exec_module(self, module):
22 return self
23
24
25 class LazyLoaderFactoryTests(unittest.TestCase):
26
27 def test_init(self):
28 factory = util.LazyLoader.factory(CollectInit)
29 # E.g. what importlib.machinery.FileFinder instantiates loaders with
30 # plus keyword arguments.
31 lazy_loader = factory('module name', 'module path', kw='kw')
32 loader = lazy_loader.loader
33 self.assertEqual(('module name', 'module path'), loader.args)
34 self.assertEqual({'kw': 'kw'}, loader.kwargs)
35
36 def test_validation(self):
37 # No exec_module(), no lazy loading.
38 with self.assertRaises(TypeError):
39 util.LazyLoader.factory(object)
40
41
42 class TestingImporter(abc.MetaPathFinder, abc.Loader):
43
44 module_name = 'lazy_loader_test'
45 mutated_name = 'changed'
46 loaded = None
47 load_count = 0
48 source_code = 'attr = 42; __name__ = {!r}'.format(mutated_name)
49
50 def find_spec(self, name, path, target=None):
51 if name != self.module_name:
52 return None
53 return util.spec_from_loader(name, util.LazyLoader(self))
54
55 def exec_module(self, module):
56 time.sleep(0.01) # Simulate a slow load.
57 exec(self.source_code, module.__dict__)
58 self.loaded = module
59 self.load_count += 1
60
61
62 class LazyLoaderTests(unittest.TestCase, ExtraAssertions):
63
64 def test_init(self):
65 with self.assertRaises(TypeError):
66 # Classes that don't define exec_module() trigger TypeError.
67 util.LazyLoader(object)
68
69 def new_module(self, source_code=None, loader=None):
70 if loader is None:
71 loader = TestingImporter()
72 if source_code is not None:
73 loader.source_code = source_code
74 spec = util.spec_from_loader(TestingImporter.module_name,
75 util.LazyLoader(loader))
76 module = spec.loader.create_module(spec)
77 if module is None:
78 module = types.ModuleType(TestingImporter.module_name)
79 module.__spec__ = spec
80 module.__loader__ = spec.loader
81 spec.loader.exec_module(module)
82 # Module is now lazy.
83 self.assertIsNone(loader.loaded)
84 return module
85
86 def test_e2e(self):
87 # End-to-end test to verify the load is in fact lazy.
88 importer = TestingImporter()
89 assert importer.loaded is None
90 with test_util.uncache(importer.module_name):
91 with test_util.import_state(meta_path=[importer]):
92 module = importlib.import_module(importer.module_name)
93 self.assertIsNone(importer.loaded)
94 # Trigger load.
95 self.assertEqual(module.__loader__, importer)
96 self.assertIsNotNone(importer.loaded)
97 self.assertEqual(module, importer.loaded)
98
99 def test_attr_unchanged(self):
100 # An attribute only mutated as a side-effect of import should not be
101 # changed needlessly.
102 module = self.new_module()
103 self.assertEqual(TestingImporter.mutated_name, module.__name__)
104
105 def test_new_attr(self):
106 # A new attribute should persist.
107 module = self.new_module()
108 module.new_attr = 42
109 self.assertEqual(42, module.new_attr)
110
111 def test_mutated_preexisting_attr(self):
112 # Changing an attribute that already existed on the module --
113 # e.g. __name__ -- should persist.
114 module = self.new_module()
115 module.__name__ = 'bogus'
116 self.assertEqual('bogus', module.__name__)
117
118 def test_mutated_attr(self):
119 # Changing an attribute that comes into existence after an import
120 # should persist.
121 module = self.new_module()
122 module.attr = 6
123 self.assertEqual(6, module.attr)
124
125 def test_delete_eventual_attr(self):
126 # Deleting an attribute should stay deleted.
127 module = self.new_module()
128 del module.attr
129 self.assertNotHasAttr(module, 'attr')
130
131 def test_delete_preexisting_attr(self):
132 module = self.new_module()
133 del module.__name__
134 self.assertNotHasAttr(module, '__name__')
135
136 def test_module_substitution_error(self):
137 with test_util.uncache(TestingImporter.module_name):
138 fresh_module = types.ModuleType(TestingImporter.module_name)
139 sys.modules[TestingImporter.module_name] = fresh_module
140 module = self.new_module()
141 with self.assertRaisesRegex(ValueError, "substituted"):
142 module.__name__
143
144 def test_module_already_in_sys(self):
145 with test_util.uncache(TestingImporter.module_name):
146 module = self.new_module()
147 sys.modules[TestingImporter.module_name] = module
148 # Force the load; just care that no exception is raised.
149 module.__name__
150
151 @threading_helper.requires_working_threading()
152 def test_module_load_race(self):
153 with test_util.uncache(TestingImporter.module_name):
154 loader = TestingImporter()
155 module = self.new_module(loader=loader)
156 self.assertEqual(loader.load_count, 0)
157
158 class RaisingThread(threading.Thread):
159 exc = None
160 def run(self):
161 try:
162 super().run()
163 except Exception as exc:
164 self.exc = exc
165
166 def access_module():
167 return module.attr
168
169 threads = []
170 for _ in range(2):
171 threads.append(thread := RaisingThread(target=access_module))
172 thread.start()
173
174 # Races could cause errors
175 for thread in threads:
176 thread.join()
177 self.assertIsNone(thread.exc)
178
179 # Or multiple load attempts
180 self.assertEqual(loader.load_count, 1)
181
182 def test_lazy_self_referential_modules(self):
183 # Directory modules with submodules that reference the parent can attempt to access
184 # the parent module during a load. Verify that this common pattern works with lazy loading.
185 # json is a good example in the stdlib.
186 json_modules = [name for name in sys.modules if name.startswith('json')]
187 with test_util.uncache(*json_modules):
188 # Standard lazy loading, unwrapped
189 spec = util.find_spec('json')
190 loader = util.LazyLoader(spec.loader)
191 spec.loader = loader
192 module = util.module_from_spec(spec)
193 sys.modules['json'] = module
194 loader.exec_module(module)
195
196 # Trigger load with attribute lookup, ensure expected behavior
197 test_load = module.loads('{}')
198 self.assertEqual(test_load, {})
199
200 def test_lazy_module_type_override(self):
201 # Verify that lazy loading works with a module that modifies
202 # its __class__ to be a custom type.
203
204 # Example module from PEP 726
205 module = self.new_module(source_code="""\
206 import sys
207 from types import ModuleType
208
209 CONSTANT = 3.14
210
211 class ImmutableModule(ModuleType):
212 def __setattr__(self, name, value):
213 raise AttributeError('Read-only attribute!')
214
215 def __delattr__(self, name):
216 raise AttributeError('Read-only attribute!')
217
218 sys.modules[__name__].__class__ = ImmutableModule
219 """)
220 sys.modules[TestingImporter.module_name] = module
221 self.assertIsInstance(module, util._LazyModule)
222 self.assertEqual(module.CONSTANT, 3.14)
223 with self.assertRaises(AttributeError):
224 module.CONSTANT = 2.71
225 with self.assertRaises(AttributeError):
226 del module.CONSTANT
227
228
229 if __name__ == '__main__':
230 unittest.main()