Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 什么是代码覆盖率的部分命中?_Python_Code Coverage_Coverage.py - Fatal编程技术网

Python 什么是代码覆盖率的部分命中?

Python 什么是代码覆盖率的部分命中?,python,code-coverage,coverage.py,Python,Code Coverage,Coverage.py,最近,当我的项目从工作服转向Codecov时,覆盖率下降了几个百分点。这似乎是由于部分命中,这在工作服中被视为命中,但在Codecov中被视为未命中 下面是一个代码示例: class Struct(object): # hit def __init__(self, content=None): # hit if content is not None: # partial hit

最近,当我的项目从工作服转向Codecov时,覆盖率下降了几个百分点。这似乎是由于部分命中,这在工作服中被视为命中,但在Codecov中被视为未命中

下面是一个代码示例:

class Struct(object):                  # hit
    def __init__(self, content=None):  # hit            
        if content is not None:        # partial hit
            self.content = content     # missed

s = Struct()                           # hit

据我所知,if语句是由解释器完全评估的。那为什么不算作命中呢?

这意味着在那一行有一个分支语句,但其中一个分支从未执行过

从下一行可以明显看出,内容从未提供给该构造函数,因此您从未使用
Struct(content=something)
测试过代码

还请注意,如果不提供参数,则不会设置
self.content
,因此,如果尝试访问,将引发
AttributeError


在本例中,如果真值与之相反,则可以从
中的语句推断出它,但您看不出该条件从来都不是false。再次考虑你的例子,略微修改

class Struct(object):                  # hit
    def __init__(self, content=None):  # hit            
        if content is not None:        # partial hit
            self.content = content     # hit

    def print_content(self):           # hit
        print(self.content)            # hit

s = Struct('42')                       # hit
s.print_content()                      # hit
看起来一切都很好?如果您未使用分支覆盖率,
If
也会显示“hit”,并且您不会注意到在
内容不是None
False
的情况下从未测试过代码,这将导致未设置
self.content
属性的错误:以下程序:

s = Struct()
s.print_content()
运行时,引发:

Traceback (most recent call last):
  File "foo.py", line 10, in <module>
    s.print_content()
  File "foo.py", line 7, in print_content
    print(self.content)
AttributeError: 'Struct' object has no attribute 'content'
回溯(最近一次呼叫最后一次):
文件“foo.py”,第10行,在
s、 打印内容()
打印内容中第7行的文件“foo.py”
打印(self.content)
AttributeError:“Struct”对象没有属性“content”

大概是因为您没有尝试过这两种情况,
if
覆盖,这也是块中的行完全丢失的原因。请注意,文档中已经介绍了这一点:@jornsharpe谢谢,我没有意识到这与分支覆盖有关。这很有意义。如果我理解正确,部分命中会通知可能遗漏的测试用例。在这种特殊情况下,这样的测试可能会发现不设置
self.content
的错误。是吗?@kazemakase希望我现在解释得更好你从一开始就解释得很好,但是你编辑了一些有价值的信息。