Refactor insert_missing_modules function (#12210)
Makes the logic more straightforward IMO.
This commit is contained in:
parent
ff806b239e
commit
6fb474a3eb
|
@ -737,34 +737,31 @@ def insert_missing_modules(modules: Dict[str, ModuleType], module_name: str) ->
|
||||||
otherwise "src.tests.test_foo" is not importable by ``__import__``.
|
otherwise "src.tests.test_foo" is not importable by ``__import__``.
|
||||||
"""
|
"""
|
||||||
module_parts = module_name.split(".")
|
module_parts = module_name.split(".")
|
||||||
child_module: Union[ModuleType, None] = None
|
|
||||||
module: Union[ModuleType, None] = None
|
|
||||||
child_name: str = ""
|
|
||||||
while module_name:
|
while module_name:
|
||||||
if module_name not in modules:
|
parent_module_name, _, child_name = module_name.rpartition(".")
|
||||||
try:
|
if parent_module_name:
|
||||||
# If sys.meta_path is empty, calling import_module will issue
|
parent_module = modules.get(parent_module_name)
|
||||||
# a warning and raise ModuleNotFoundError. To avoid the
|
if parent_module is None:
|
||||||
# warning, we check sys.meta_path explicitly and raise the error
|
try:
|
||||||
# ourselves to fall back to creating a dummy module.
|
# If sys.meta_path is empty, calling import_module will issue
|
||||||
if not sys.meta_path:
|
# a warning and raise ModuleNotFoundError. To avoid the
|
||||||
raise ModuleNotFoundError
|
# warning, we check sys.meta_path explicitly and raise the error
|
||||||
module = importlib.import_module(module_name)
|
# ourselves to fall back to creating a dummy module.
|
||||||
except ModuleNotFoundError:
|
if not sys.meta_path:
|
||||||
module = ModuleType(
|
raise ModuleNotFoundError
|
||||||
module_name,
|
parent_module = importlib.import_module(parent_module_name)
|
||||||
doc="Empty module created by pytest's importmode=importlib.",
|
except ModuleNotFoundError:
|
||||||
)
|
parent_module = ModuleType(
|
||||||
else:
|
module_name,
|
||||||
module = modules[module_name]
|
doc="Empty module created by pytest's importmode=importlib.",
|
||||||
if child_module:
|
)
|
||||||
|
modules[parent_module_name] = parent_module
|
||||||
|
|
||||||
# Add child attribute to the parent that can reference the child
|
# Add child attribute to the parent that can reference the child
|
||||||
# modules.
|
# modules.
|
||||||
if not hasattr(module, child_name):
|
if not hasattr(parent_module, child_name):
|
||||||
setattr(module, child_name, child_module)
|
setattr(parent_module, child_name, modules[module_name])
|
||||||
modules[module_name] = module
|
|
||||||
# Keep track of the child module while moving up the tree.
|
|
||||||
child_module, child_name = module, module_name.rpartition(".")[-1]
|
|
||||||
module_parts.pop(-1)
|
module_parts.pop(-1)
|
||||||
module_name = ".".join(module_parts)
|
module_name = ".".join(module_parts)
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue