VS Code中Pytest测试发现失败:ModuleNotFoundError问题求助
解决VS Code中pytest调试器"error discovering pytests tests"及logdna模块找不到的问题
1. 确保VS Code关联Poetry虚拟环境
- 打开命令面板(Ctrl+Shift+P),执行
Python: Select Interpreter - 选择Poetry创建的虚拟环境,若找不到可先在终端执行
poetry env info --path获取路径,手动选择该路径下的Python解释器
2. 配置VS Code的pytest与环境变量
在项目根目录的.vscode/settings.json中添加以下配置:
{ "python.testing.pytestArgs": ["."], // 替换为你的测试目录,比如"tests/" "python.testing.unittestEnabled": false, "python.testing.pytestEnabled": true, "python.envFile": "${workspaceFolder}/.env" }
3. 修复模块解析错误
- 在
.vscode/settings.json中添加项目根目录到Python分析路径:"python.analysis.extraPaths": ["${workspaceFolder}"] - 若项目根目录没有
__init__.py,新建一个空文件,让VS Code识别为Python包
4. 刷新VS Code环境
- 打开命令面板,执行
Python: Restart Language Server - 关闭并重新打开VS Code,确保配置生效
5. 验证Poetry依赖
- 在终端执行
poetry run pip list,确认logdna在依赖列表中 - 若不在,执行
poetry add logdna(不要用pip3 install,Poetry环境下需通过Poetry管理依赖)
终端能正常运行测试但VS Code不行的核心原因:终端已通过poetry shell或poetry run切换到虚拟环境,但VS Code未正确关联该环境,导致依赖和模块路径识别异常。
内容的提问来源于stack exchange,提问作者brunshte
相关产品推荐
相关产品推荐

