You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 03:54:28