[Enhance] Enhance error message during custom import (#1102)

This commit is contained in:
Mashiro 2023-04-26 11:08:58 +08:00 committed by GitHub
parent 1c01594c5c
commit 9868131c98
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 1 deletions

View File

@ -5,6 +5,7 @@ import os
import os.path as osp
import platform
import shutil
import sys
import tempfile
import types
import uuid
@ -180,7 +181,15 @@ class Config:
try:
import_modules_from_strings(**cfg_dict['custom_imports'])
except ImportError as e:
raise ImportError('Failed to custom import!') from e
err_msg = (
'Failed to import custom modules from '
f"{cfg_dict['custom_imports']}, the current sys.path is: ")
for p in sys.path:
err_msg += f'\n {p}'
err_msg += (
'\nYou should set `PYTHONPATH` to make `sys.path` include '
'the directory which contains your custom module')
raise ImportError(err_msg) from e
return Config(
cfg_dict,
cfg_text=cfg_text,

View File

@ -65,8 +65,14 @@ class TestConfig:
# If import successfully, os.environ[''TEST_VALUE''] will be
# set to 'test'
assert os.environ.pop('TEST_VALUE') == 'test'
sys.path.pop()
Config.fromfile(cfg_file, import_custom_modules=False)
assert 'TEST_VALUE' not in os.environ
sys.modules.pop('test_custom_import_module')
with pytest.raises(
ImportError, match='Failed to import custom modules from'):
Config.fromfile(cfg_file, import_custom_modules=True)
@pytest.mark.parametrize('file_format', ['py', 'json', 'yaml'])
def test_fromstring(self, file_format):