我有一个抽象基类:
class MyAbstractClass(object):
__metaclass__ = ABCMeta
@abstractproperty
def myproperty(self): pass
但是当我在我的项目上运行nosetests(覆盖范围)时,它抱怨属性定义线未经测试。它实际上无法被测试(AFAIK),因为抽象类的实例化将导致引发异常.. 是否有任何解决方法,或者我必须接受
当然,我可以删除 < 100% test coverage?
ABCMeta
用法并简单地让基类 raise
NotImpementedError
,但我更喜欢前一种方法。class MyAbstractClass(object):
__metaclass__ = ABCMeta
@abstractproperty
def myproperty(self):
""" this property is too abstract to understand. """
@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
.coveragerc
中有自定义跳过逻辑:
[report]
exclude_lines =
pragma: no cover
@abstract
这样所有抽象方法和抽象属性都被标记为已跳过。
。将以下部分添加到您的 pyproject.toml
:
[tool.coverage.report]
exclude_also = [
"raise AssertionError",
"raise NotImplementedError",
"@(abc\\.)?abstractmethod",
]
或
.coveragerc
[report]
exclude_also =
raise AssertionError
raise NotImplementedError
@(abc\.)?abstractmethod