【问题标题】:Python code coverage missing when files have the same name文件同名时缺少 Python 代码覆盖率
【发布时间】:2021-01-11 09:45:14
【问题描述】:

我正在使用 pytest 和 pytest-cov 进行代码覆盖。

我的项目如下所示。有两个模块servicesworkers

python_tmp
├── tests
│   └── some_test.py
├── services
│   └── utils.py
└── workers
    └── utils.py

他们俩都在里面有utils.py。但内容不同。

services/utils.py

def function_1():
    return 1

和workers/utils.py

def function_2():
    return 2

tests/some_test.py你可以找到测试用例。

import pytest
import services.utils as t1
import workers.utils as t2

def test_function_1():
    res = t1.function_1()
    assert res == 1

def test_function_2():
    res = t2.function_2()
    assert res == 2

如果我运行测试python -m pytest -v tests --cov=services --cov=workers --cov-report=xml:coverage.xml,它将生成以下报告。但是你可以看到utils.py只被举报了一个,而且有歧义你不知道它属于哪个模块。

...
    <sources>
        <source>/Users/xxxxxxx/workspace/tmp/python_tmp/services</source>
        <source>/Users/xxxxxxx/workspace/tmp/python_tmp/workers</source>
    </sources>
    <packages>
        <package branch-rate="0" complexity="0" line-rate="1" name=".">
            <classes>
                <class branch-rate="0" complexity="0" filename="utils.py" line-rate="1" name="utils.py">
                    <methods/>
                    <lines>
                        <line hits="1" number="1"/>
                        <line hits="1" number="2"/>
                    </lines>
                </class>
            </classes>
        </package>
    </packages>
</coverage>

如何解决?感谢您的宝贵时间!

【问题讨论】:

    标签: python pytest code-coverage


    【解决方案1】:

    这个问题提到here

    所以要解决这个问题,你可以运行python -m pytest -v tests --cov --cov-report=xml:coverage.xml

    希望这会有所帮助。

    【讨论】:

    • 可能是--cov=.,AFAIR 它需要一个值。
    • 我已经在我的系统上运行它进行测试。它工作正常。 (不要添加“=”符号)
    • 我也在我的系统上运行过它。 --cov 不带参数确实有效(我记得它之前没有用过),但报告中还包括 pytest 和插件源,这是不可取的。
    • 您有什么建议忽略文件夹,因为--cov 将包括当前目录中的所有文件夹。创建一个.coveragerc 文件并省略那里?谢谢!
    • 从我的回答中提到的链接中,它说这个错误没有在 2.2.0 版本中重现,但回滚到这样的旧版本会引发其他错误。我想最好的办法是修改 .coveragerc 文件。
    猜你喜欢
    • 2012-02-02
    • 2016-08-11
    • 2016-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多