vscode需显式配置pytest框架:设"python.testing.testframework": "pytest"、禁用unittest、启用pytest开关;pytestargs须为正确路径的json数组;文件名须匹配test_.py或_test.py;调试时需指定cwd和解释器路径。

VSCode 默认不识别 pytest,必须手动声明框架类型、指定解释器路径、配置发现参数,三者缺一不可;否则测试侧边栏空白、“运行测试”按钮灰掉、调试断点不生效。
python.testing.testFramework 必须显式设为 pytest
VSCode 的 Python 扩展不会因为 pip install pytest 就自动启用 pytest——它只认配置项。如果没设,它会默认 fallback 到 unittest,导致测试文件被忽略。
- 打开
settings.json(命令面板 → Preferences: Open Workspace Settings (JSON)) - 确保写入:
"python.testing.testFramework": "pytest" - 同时禁用 unittest:
"python.testing.unittestEnabled": false - 别漏掉
"python.testing.pytestEnabled": true(部分旧版扩展仍依赖该开关)
pytestArgs 必须是列表,且路径要对得上 --rootdir
python.testing.pytestArgs 是个严格校验的 JSON 数组,不是字符串;VSCode 用它做测试发现阶段的参数传入,错一个引号或空格就静默失效。
- 错误写法:
"python.testing.pytestArgs": "--rootdir=tests -v"→ 配置加载失败,测试树为空 - 正确写法:
"python.testing.pytestArgs": ["--rootdir=.", "tests/", "-v"] - 如果测试在
src/tests/,则写["--rootdir=src", "tests/"],而非["src/tests/"]—— 否则conftest.py不加载,fixture 失效 - 文件名必须匹配
test_*.py或*_test.py,my_tests.py这类名字不会被发现
调试单个 test_* 函数总报 ModuleNotFoundError?改 cwd 或 sys.path
VSCode 调试测试时,默认工作目录是测试文件所在目录,不是项目根目录。所以 from mypackage import foo 在终端能跑,调试却报错。
- 优先在
settings.json加:"python.testing.cwd": "${workspaceFolder}"(或"${workspaceFolder}/src") - 确保
python.defaultInterpreterPath指向你装了 pytest 的虚拟环境(如./venv/bin/python) - 临时救急:在测试文件顶部加
import sys; sys.path.insert(0, "src"),但别提交到仓库 - 别依赖
pip install -e .—— VSCode 调试器不走setup.py或pyproject.toml的 editable 安装逻辑
点“▶”运行单个测试却跑全文件?检查 pytest 版本和 -k 参数是否生效
VSCode 点单个测试函数旁的播放图标,底层调用的是 pytest -k "test_name"。如果框架不支持 -k 或参数被覆盖,就会退化成整文件运行。
- 确认 pytest ≥ 6:
pytest --version输出应为pytest 6.x或更高 - 不要在
pytestArgs里硬编码-k,它由 VSCode 动态注入;写死会导致单测点击失效 - 如果用了自定义
testpaths或python_files在pyproject.toml中,确保与 VSCode 的--rootdir一致,否则-k匹配范围错乱 - 断点只能打在
def test_*函数体内,不能打在conftest.py的 fixture 定义处(除非加--capture=no并配 pytest-pdb)
最常被跳过的其实是解释器激活和 --rootdir 的协同——VSCode 既要看解释器有没有 pytest,又要靠 --rootdir 定位包结构,二者偏差哪怕一层目录,ModuleNotFoundError 就立刻出现,而且错误信息里完全不提示 rootdir 问题。











