如何在 VS Code 中使用 pytest 运行 pytest-cov?

问题描述 投票:0回答:2

我正在尝试这样做,以便当我在测试资源管理器中运行测试时,它会同时在项目文件夹中自动生成一个 cov.xml 文件。我尝试将参数添加到 VS Code 上的 pytest 参数字段,但它似乎没有对测试资源管理器运行测试/pytest 的方式进行任何更改。我可能错过了一些东西,或者这可能是不可能的。

python-3.x visual-studio-code pytest pytest-cov
2个回答
18
投票

首先,

pytest
pytest-cov
都必须通过pip安装:

$ pip install pytest
$ pip install pytest-cov

在本地存储库设置中,将以下配置添加到

.vscode/settings.json
文件中:

{
    "python.testing.unittestEnabled": false,
    "python.testing.pytestEnabled": true,
    "python.testing.pytestArgs": [
        "-v",
        "--cov=myproj/",
        "--cov-report=xml",
        "--pdb",
        "tests/"
    ]
}

现在您可以使用内置测试资源管理器运行测试:测试 > 运行测试。 将生成 xml 文件并位于您的工作目录中。另请参阅有关报告的 pytest-cov 文档 和有关 pytest 配置的 vscode 文档。正如 vscode 文档中所述,我建议还将下面的启动配置添加到

.vscode/launch.json
,以免使用 pytest-cov 中断调试:

{
    "configurations": [
        {
            "name": "Python: Debug Tests",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "purpose": ["debug-test"],
            "console": "integratedTerminal",
            "env": {
                "PYTEST_ADDOPTS": "--no-cov"
            },
            "justMyCode": false
        }
    ]
}

1
投票

我对@ncw的答案进行了轻微修改,以解决两个问题:

  1. 调试器挂起
  2. 错误:
    "Could not load unit test config from launch.json as it is missing a field"
    。现场是
    version

launch.json:


    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Debug Tests",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "purpose": [
                "debug-test"
            ],
            "console": "integratedTerminal",
            "env": {
                "PYTEST_ADDOPTS": "--no-cov"
            },
            "justMyCode": false
        }
    ]
}

设置.json

{
    "python.testing.unittestEnabled": false,
    "python.testing.pytestEnabled": true,
    "python.testing.pytestArgs": [
        "-v",
        "--cov",
        "--cov-report=xml",
        "python/tests/"
    ]
}
© www.soinside.com 2019 - 2024. All rights reserved.