VSCode需手动配置pytest框架:设置"python.testing.testFramework": "pytest"、启用pytestEnabled并禁用unittestEnabled;pytestArgs必须为JSON数组;调试时需指定cwd和PYTHONPATH以解决导入问题。

VSCode根本不识别pytest,必须手动声明框架类型
VSCode不会因为pip install pytest就自动启用它——它只认配置项python.testing.testFramework。不设这个值,它默认 fallback 到 unittest,所有test_*.py文件都会被忽略,测试侧边栏空白,“Run Test”按钮灰掉。
打开.vscode/settings.json,确保写入:
"python.testing.testFramework": "pytest", "python.testing.unittestEnabled": false, "python.testing.pytestEnabled": true
别漏掉python.testing.pytestEnabled,部分旧版扩展仍依赖该开关;同时禁用unittestEnabled,避免冲突。
pytestArgs必须是JSON数组,路径写错就静默失效
python.testing.pytestArgs不是字符串,是严格校验的 JSON 数组。写成字符串(比如"tests/ -v")会导致配置加载失败,测试树为空,且无任何报错提示。
立即学习“Python免费学习笔记(深入)”;
- 正确写法:
["tests/", "-s", "-v"]或["--rootdir=src", "tests/", "-s"] - 如果测试在
src/tests/,且conftest.py也在src/下,用--rootdir=src才能加载fixture - 路径是相对
${workspaceFolder}的,不要写绝对路径或./tests/ - 改完必须点测试侧边栏右上角
↻刷新,VSCode 不会自动重扫
调试时ModuleNotFoundError?根本原因是cwd不是源码根目录
VSCode调试测试时,默认工作目录(cwd)是测试文件所在目录,不是项目根目录。所以from mypackage import x在终端能跑,调试却报错——这是最常被忽略的根源。
在.vscode/settings.json中加:
"python.testing.cwd": "${workspaceFolder}/src"
如果源码在src/下(即src/mymodule/和src/tests/并列),这一行必不可少。配合"python.envFile": "${workspaceFolder}/.env"并在.env里写PYTHONPATH=${workspaceFolder}/src,双重保险。
别在测试文件里写sys.path.insert(0, "src")来救急——这容易提交到仓库,且不解决根本问题。
launch.json调试单个测试:module不能丢,args必须是数组
想F5调试一个函数?launch.json里不能有program字段,否则VSCode会忽略module并报“Cannot launch program”。
必须这样配:
{
"name": "Debug pytest",
"type": "python",
"request": "launch",
"module": "pytest",
"args": ["tests/test_api.py::test_login", "-s"],
"cwd": "${workspaceFolder}"
}
args是数组,双冒号::分隔文件与函数名;cwd要和settings.json里的python.testing.cwd一致;断点别打在def test_xxx():那行,要打在函数体第一句代码上。
复杂点在于:测试发现、运行、调试三套路径逻辑各自独立,pytestArgs管发现,cwd管导入,launch.json管执行——改一处,其他地方可能跟着崩。


















