|
10 | 10 | from test.support import threading_helper |
11 | 11 | from test.test_importlib import util as test_util |
12 | 12 |
|
| 13 | +# Make sure sys.modules[util] is in sync with the import. |
| 14 | +# That is needed as other tests may reload util. |
| 15 | +sys.modules['importlib.util'] = util |
13 | 16 |
|
14 | 17 | class CollectInit: |
15 | 18 |
|
@@ -192,7 +195,7 @@ def test_lazy_self_referential_modules(self): |
192 | 195 | sys.modules['json'] = module |
193 | 196 | loader.exec_module(module) |
194 | 197 |
|
195 | | - # Trigger load with attribute lookup, ensure expected behavior |
| 198 | + # Trigger load with attribute lookup, ensure expected behavior. |
196 | 199 | test_load = module.loads('{}') |
197 | 200 | self.assertEqual(test_load, {}) |
198 | 201 |
|
@@ -224,6 +227,26 @@ def __delattr__(self, name): |
224 | 227 | with self.assertRaises(AttributeError): |
225 | 228 | del module.CONSTANT |
226 | 229 |
|
| 230 | + def test_reload(self): |
| 231 | + # Reloading a lazy module that hasn't been materialized is a no-op. |
| 232 | + module = self.new_module() |
| 233 | + sys.modules[TestingImporter.module_name] = module |
| 234 | + |
| 235 | + # Change the source code to add a new attribute. |
| 236 | + TestingImporter.source_code = 'attr = 42\nnew_attr = 123\n__name__ = {!r}'.format(TestingImporter.mutated_name) |
| 237 | + self.assertIsInstance(module, util._LazyModule) |
| 238 | + |
| 239 | + # Reload the module (should be a no-op since not materialized). |
| 240 | + reloaded = importlib.reload(module) |
| 241 | + self.assertIs(reloaded, module) |
| 242 | + self.assertIsInstance(module, util._LazyModule) |
| 243 | + |
| 244 | + # Access the new attribute (should trigger materialization, and new_attr should exist). |
| 245 | + self.assertEqual(module.attr, 42) |
| 246 | + self.assertNotIsInstance(module, util._LazyModule) |
| 247 | + self.assertTrue(hasattr(module, 'new_attr')) |
| 248 | + self.assertEqual(module.new_attr, 123) |
| 249 | + |
227 | 250 |
|
228 | 251 | if __name__ == '__main__': |
229 | 252 | unittest.main() |
0 commit comments