从coverage报告中排除abstractproperties

时间:2012-02-08 22:48:08

标签: python code-coverage nosetests abc coverage.py

我有一个抽象的基类:

class MyAbstractClass(object):
    __metaclass__ = ABCMeta

    @abstractproperty
    def myproperty(self): pass

但是当我在我的项目中运行nosetests(覆盖率)时,它会抱怨属性def line未经测试。它不能实际进行测试(AFAIK),因为抽象类的实例化将导致异常被引发..

是否有任何解决方法,或者我只需要接受< 100%的测试覆盖率?

当然,我可以删除ABCMeta用法,只是让基类引用NotImpementedError,但我更喜欢前一种方法。

3 个答案:

答案 0 :(得分:28)

没有办法像你拥有的那样精确地排除抽象属性,但如果你做了一些改变,你就可以。让您的抽象属性引发错误:

@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

答案 1 :(得分:27)

对我来说,最好的解决方案是@Wesley在对已接受答案的评论中提到的内容,特别是用抽象属性的文档字符串替换'pass',例如:

class MyAbstractClass(object):
    __metaclass__ = ABCMeta

    @abstractproperty
    def myproperty(self):
       """ this property is too abstract to understand. """

答案 2 :(得分:8)

我的.coveragerc中有自定义跳过逻辑:

[report]
exclude_lines =
    pragma: no cover
    @abstract

这样所有abstractmethods和abstractproperties都被标记为跳过。

相关问题