【问题标题】:Make pytest require code coverage only on full test suite run使 pytest 仅在完整的测试套件运行时才需要代码覆盖
【发布时间】:2026-01-03 02:55:01
【问题描述】:

我正在使用类似的东西

# .coveragerc
fail_under = 100

# pytest.ini
[pytest]
addopts = --cov=modname/ --cov-report=term-missing

让我的测试套件运行覆盖率并在不是 100% 时失败。

这可行,但问题是如果我只运行一部分测试,比如

pytest some/specific/test.py

然后它抱怨覆盖率不是 100%,因为当然单个测试文件不会覆盖整个代码库。是否有更好的方法来使 pytest 运行覆盖率,但仅在运行完整的测试套件时?

【问题讨论】:

    标签: python pytest code-coverage coverage.py test-coverage


    【解决方案1】:

    您可以通过在命令中添加以下标志来临时覆盖您的 .coveragerc

    --cov-fail-under=x
    

    其中 x 是失败的百分比(如果将其设置为 0,则根据代码覆盖率它永远不会失败)

    因此,在您的情况下,您将运行:

    pytest some/specific/test.py --cov-fail-under=x
    

    【讨论】:

      最近更新 更多