You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VSCode测试资源管理器无法检测pytest测试用例(WSL2+Poetry场景)

VSCode WSL环境下pytest用例不显示在测试资源管理器问题解决

问题描述

单元测试无法展示在VSCode的测试资源管理器中,测试发现过程在输出中没有报错,但也没有展示任何测试用例。已确认Python解释器配置正确,在项目根目录手动执行pytest或poetry run pytest都可以完美运行测试,tests目录下也放置了空的__init__.py文件,运行环境为WSL2上的Ubuntu系统。
环境截图

环境配置流程

  • 在Windows上安装WSL2
  • 在Windows上安装VSCode
  • 安装VSCode的「Remote - WSL」扩展
  • 在VSCode中打开新的WSL窗口
  • 参考公开教程在Ubuntu中安装Anaconda
  • 安装VSCode Python扩展
  • 将VSCode Python解释器设置为Anaconda安装路径,打开新终端
  • 执行pip install poetry
  • 进入项目根文件夹
  • 执行poetry install
  • 将VSCode Python解释器设置为poetry创建的虚拟环境,打开新终端
  • 配置完成,可通过命令行正常运行pytest

现有配置

工作区setting.json

{
    "restructuredtext.confPath": "${workspaceFolder}/docs/source",
    "python.testing.pytestEnabled": true
}

测试发现命令输出

刷新测试时输出面板内容如下:

~/.cache/pypoetry/virtualenvs/monaco-bfS1OgpY-py3.9/bin/python ~/.vscode-server/extensions/ms-python.python-2021.11.1422169775/pythonFiles/testing_tools/run_adapter.py discover pytest -- --rootdir ~/coding/monaco -s --cache-clear
cwd: ~/coding/monaco

手动执行上述命令,会输出包含所有测试用例的字典,确认测试发现脚本本身可以正常识别到所有测试用例,内容片段如下:

[
    {
        "rootid": ".", 
        "root": "/mnt/c/Users/Scott/Documents/Documents/Coding/monaco", 
        "parents": [
            {"id": "./tests", "kind": "folder", "name": "tests", "parentid": ".", "relpath": "./tests"}, 
            {"id": "./tests/test_MCCase.py", "kind": "file", "name": "test_MCCase.py", "parentid": "./tests", "relpath": "./tests/test_MCCase.py"}
            // 其余测试文件结构一致
        ]
    }
]

根因定位与解决方案

问题核心是WSL环境下路径表示不一致导致的匹配失败:VSCode调用测试发现脚本时传入的rootdir为~/coding/monaco,但脚本返回的测试根路径为挂载路径/mnt/c/Users/Scott/Documents/Documents/Coding/monaco,两者实际指向同一目录但字符串不匹配,VSCode无法将识别到的用例映射到工作区。
在工作区setting.json中明确指定pytest根路径为当前工作区即可解决:

{
    "restructuredtext.confPath": "${workspaceFolder}/docs/source",
    "python.testing.pytestEnabled": true,
    "python.testing.pytestArgs": [
        "--rootdir",
        "${workspaceFolder}"
    ]
}

修改后重新加载VSCode窗口,刷新测试资源管理器即可正常展示所有测试用例。

内容的提问来源于stack exchange,提问作者Scott

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 02:36:04