vscode debug test 无响应或断点失效,根本原因是调试路径与模块加载上下文未对齐:需显式配置 python.testing.cwd、python.defaultinterpreterpath,禁用冲突测试框架,删除 launch.json 中的 program 字段,改用 module: "pytest" 启动。

VSCode 里点“Debug Test”没反应、断点跳过、报 ModuleNotFoundError,不是插件没装对,而是调试启动路径和模块加载上下文根本没对齐——python.testing.cwd 和 python.defaultInterpreterPath 必须显式配,且 launch.json 不能有 program 字段。
为什么 Debug Test 按钮点了没反应
按钮灰掉或点击无响应,本质是 VSCode 测试适配器没拿到可执行的 pytest 进程入口。常见原因:
-
python.testing.pytestEnabled为false,或python.testing.unittestEnabled为true(二者冲突) -
python.testing.pytestArgs路径写错,比如写成["src/tests/"]却没加--rootdir=src,导致conftest.py不加载、fixture 失效 - 没手动刷新测试资源管理器:改完
settings.json后必须点测试侧边栏右上角 ↻ 按钮,VSCode 不自动重扫
Debug Test 断点不命中或 ModuleNotFoundError
这是最常被忽略的根源:VSCode 调试器默认以测试文件所在目录为工作目录(cwd),不是项目根目录,sys.path 也不含你的源码路径。
- 在
.vscode/settings.json中加:"python.testing.cwd": "${workspaceFolder}/src"(源码在src/下)或"${workspaceFolder}"(源码在根目录) - 同时配
"python.envFile": "${workspaceFolder}/.env",并在.env里写PYTHONPATH=${workspaceFolder}/src,双重保险 - 断点别打在
def test_xxx():那行,要打在函数体第一句有效代码上,否则 pytest 加载阶段就跳过了
launch.json 调试单个测试必须删掉 program 字段
想用 F5 直接调试一个测试函数?launch.json 必须走 pytest 模块方式启动,不能当普通脚本跑。
- 删掉
"program"字段——它和"module"冲突,留着必报错 - 必须写
"module": "pytest",等价于终端执行python -m pytest -
"args"是数组,例如:["tests/test_api.py::test_login", "-s"](双冒号分隔文件和函数名) - 如果
pytestArgs用了--rootdir,确保args中路径与之匹配,否则 pytest 可能找不到测试函数
真正卡住人的地方是 cwd 和 sys.path 的隐式耦合
VSCode 调试器不继承终端的环境变量,也不执行 pip install -e . 的 editable 安装逻辑,所有路径都得靠配置项或 .env 显式声明。哪怕只差一层目录,from mypackage import x 就会直接失败——这不是代码问题,是调试上下文没搭对。











