VS Code 里调试 pytest,核心是 launch 配置走 module: pytest,而不是直接跑当前文件。这样断点、-s 打印、自定义参数都还在。
settings.json
先打开 pytest 测试面板:
json
{
"python.testing.pytestEnabled": true,
"python.testing.unittestEnabled": false,
"python.testing.pytestArgs": ["."]
}launch.json
调试当前打开的测试文件,并让用户选环境名:
json
{
"version": "0.2.0",
"configurations": [
{
"name": "pytest current",
"type": "debugpy",
"request": "launch",
"module": "pytest",
"python": "${command:python.interpreterPath}",
"args": ["-s", "${file}", "--env=${input:testEnv}"],
"cwd": "${workspaceFolder}",
"console": "integratedTerminal",
"env": {
"PYTHONPATH": "${workspaceFolder}"
},
"justMyCode": false
}
],
"inputs": [
{
"id": "testEnv",
"type": "pickString",
"description": "选择 pytest 运行环境",
"options": ["dev", "test", "staging", "prod"],
"default": "dev"
}
]
}--env 要在你的 conftest 里自己接,例如 parser.addoption("--env")。没有这个选项就删掉对应 args。
justMyCode: false 才能走进第三方库。项目根不在 sys.path 上时,用 PYTHONPATH 补上。
环境名用 dev / test / prod 这种通用取值,不要把内网主机名写进仓库里的 launch.json。