VS Code中Unittest测试发现失败,模块导入报错求助
问题:VS Code中Unittest测试发现失败,提示ModuleNotFoundError: No module named 'utils.services'
项目结构
/project /app /app2 /tests /utils /services.py
问题现象
项目已运行多年,此前测试正常,更新Python插件或VS Code后出现以下异常:
app模块可正常调用utils.services- 终端执行
python3 -m unittest tests或python3 -m unittest discover -s tests时,测试能正常运行 - VS Code中无法加载测试列表,Python输出报错如下:
2023-11-20 17:25:33.469 [info] Discover tests for workspace name: order - uri: /Users/ralfeus/Projects/order/tests/__init__.py 2023-11-20 17:25:33.469 [info] Running discovery for unittest using the new test adapter. 2023-11-20 17:25:33.470 [info] Discovering unittest tests with arguments: /Users/ralfeus/.vscode/extensions/ms-python.python-2023.20.0/pythonFiles/unittestadapter/discovery.py,--udiscovery,-v,-s,tests,-p,*test*.py 2023-11-20 17:25:33.470 [info] > ./bin/python ~/.vscode/extensions/ms-python.python-2023.20.0/pythonFiles/unittestadapter/discovery.py --udiscovery -v -s tests -p *test*.py 2023-11-20 17:25:33.471 [info] cwd: . 2023-11-20 17:25:33.738 [info] Test server connected to a client. 2023-11-20 17:25:33.739 [error] Unittest test discovery error Failed to import test module: addresses.test_address_api Traceback (most recent call last): File "/opt/homebrew/Cellar/python@3.11/3.11.4_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/unittest/loader.py", line 407, in _find_test_path module = self._get_module_from_name(name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/homebrew/Cellar/python@3.11/3.11.4_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/unittest/loader.py", line 350, in _get_module_from_name __import__(name) File "/Users/ralfeus/Projects/order/tests/addresses/test_address_api.py", line 3, in <module> from app.users.models.role import Role File "/Users/ralfeus/Projects/order/app/__init__.py", line 18, in <module> from utils.services import get_celery, init_celery ModuleNotFoundError: No module named 'utils.services'; 'utils' is not a package
已尝试的解决方法
- 调整VS Code中的Unittest配置参数
- 修改
sys.path路径,尝试将项目根目录加入Python路径 - 修改
app/__init__.py中的导入语句,将from utils.services import get_celery, init_celery改为from .utils.services import get_celery, init_celery,但出现新错误:
No module named 'app.utils'
猜测
怀疑VS Code执行测试发现时,将/app目录而非项目根目录作为Python的根路径,但无法确认具体原因,寻求可行的解决办法。
内容的提问来源于stack exchange,提问作者Ralfeus
相关产品推荐
相关产品推荐

