从覆盖率报告中排除抽象属性

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

我有一个抽象基类:

class MyAbstractClass(object):
    __metaclass__ = ABCMeta

    @abstractproperty
    def myproperty(self): pass

但是当我在我的项目上运行nosetests(覆盖范围)时,它抱怨属性定义线未经测试。它实际上无法被测试(AFAIK),因为抽象类的实例化将导致引发异常.. 是否有任何解决方法,或者我必须接受

当然,我可以删除 < 100% test coverage?

ABCMeta

用法并简单地让基类 raise

NotImpementedError
,但我更喜欢前一种方法。
    

python code-coverage nosetests abc coverage.py
4个回答
66
投票

class MyAbstractClass(object): __metaclass__ = ABCMeta @abstractproperty def myproperty(self): """ this property is too abstract to understand. """



43
投票

@abstractproperty def myproperty(self): raise NotImplementedError

然后您可以指示coverage.py忽略引发NotImplementedError的行。创建一个 .coveragerc 文件,并在其中放入:

[report] exclude_lines = # Have to re-enable the standard pragma pragma: no cover # Don't complain if tests don't hit defensive assertion code: raise NotImplementedError

有关您可能希望始终忽略的行类型的更多想法,请参阅:
http://nedbatchelder.com/code/coverage/config.html


21
投票
.coveragerc

中有自定义跳过逻辑:


[report] exclude_lines = pragma: no cover @abstract

这样所有抽象方法和抽象属性都被标记为已跳过。


0
投票
docs

。将以下部分添加到您的 pyproject.toml

[tool.coverage.report]
exclude_also = [
    "raise AssertionError",
    "raise NotImplementedError",
    "@(abc\\.)?abstractmethod",
    ]

.coveragerc

[report]
exclude_also =
    raise AssertionError
    raise NotImplementedError
    @(abc\.)?abstractmethod

© www.soinside.com 2019 - 2024. All rights reserved.