vscode调试pytest断点不生效,首要检查launch.json中"request"必须为"launch"且配置"module": "pytest";其次确认python解释器与命令行一致,并安装pytest;推荐使用python test explorer扩展实现右键调试。

vscode 调试 pytest 时断点不生效?先检查 launch.json 的 request 类型
断点灰色、点击无响应,大概率是 launch.json 里写成了 "request": "launch" 却没配 module 或 program,或者错用了 "request": "attach"。pytest 必须用 "request": "launch",且必须指定运行入口。
推荐配置方式(以当前工作区根目录下有 tests/ 目录为例):
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: pytest",
"type": "python",
"request": "launch",
"module": "pytest",
"args": ["tests/", "-s", "-v"],
"console": "integratedTerminal",
"justMyCode": true
}
]
}
-
module字段不能省略,填"pytest"才能走 pytest 入口而非直接执行 Python 文件 -
args中的-s保留 print 输出,-v显示详细测试名,调试时很关键 - 如果测试文件在子目录(如
tests/unit/test_api.py),可把args改成["tests/unit/test_api.py::test_login", "-s"]精确到函数级 - 不要用
program指向pytest可执行文件路径——不同虚拟环境位置不同,易失效
Python 解释器选错导致 No module named pytest
VSCode 左下角显示的 Python 解释器,必须和你命令行中能跑通 pytest --version 的那个一致。常见错误是:终端激活了 venv,但 VSCode 仍用系统 Python 或另一个 venv。
- 快捷键
Ctrl+Shift+P(Win/Linux)或Cmd+Shift+P(Mac),输入Python: Select Interpreter,手动选中项目虚拟环境下的python(路径通常含venv/bin/python或venv\Scripts\python.exe) - 确认后,在集成终端中执行
which pytest(macOS/Linux)或where pytest(Windows),看是否指向同一 venv 的Scripts/或bin/目录 - 如果没装 pytest,别在全局 pip 装,就在当前解释器环境下运行:
pip install pytest pytest-cov
调试时跳过第三方库代码?靠 justMyCode 和 pathMappings
默认调试会进入 pytest 源码甚至 requests、pytest-cov 等依赖内部,干扰定位。VSCode 的 justMyCode 是第一道防线,但对某些包(比如通过 pip install -e . 安装的本地包)可能失效。
- 确保
"justMyCode": true(默认值,但显式写出更稳妥) - 若仍跳进自己写的包(比如
src/mylib/),在launch.json的 configuration 里加"pathMappings": [ { "localRoot": "${workspaceFolder}/src", "remoteRoot": "${workspaceFolder}/src" } ] -
remoteRoot在本地调试场景下和localRoot一致即可,不用模拟远程路径 - 注意:修改
launch.json后必须重启调试会话,热重载不生效
想直接右键测试函数调试?需要安装并启用 Python Test Explorer
VSCode 内置调试只支持配置式启动,没法直接右键单测函数。要实现“右键 → Debug Test”,得靠扩展。
- 安装官方扩展 Python Test Explorer(作者:Microsoft)
- 确保
settings.json中启用了 pytest 支持:"python.testing.pytestEnabled": true - 首次使用需让插件发现测试:点击侧边栏测试图标 → “Discover Tests” → 选
pytest→ 指定tests/目录 - 发现成功后,测试树里每个
test_*.py文件和函数旁会出现 ▶️ 图标,点击即调试,等价于自动构造带--no-header -s -v的 launch 配置
这个功能看似方便,但背后仍依赖正确的解释器、pytest 可执行路径和 sys.path 设置;一旦右键调试失败,优先回退到手动配置 launch.json 排查——很多“点不动”的问题,其实卡在解释器或路径上,而不是操作本身。











