首页 > 解决方案 > 如果从未在测试中直接调用函数,是否可以制作 pytest 报告?

问题描述

例子

def main(p):
    if foo_a(p):
        return False
    return p**2

def foo_a(p):
    return p % 11 == 0

现在您可以通过以下方式获得 100% 的测试覆盖率

import unittest
from script import main

class Foobar(unittest.TestCase):
    def test_main(self):
        self.assertEquals(main(3), 9)

但也许有人想foo_a成为p % 2 == 0

问题

分支覆盖会对此有所了解,但我也想知道一个函数是否从未被测试“直接”调用(例如main示例中的 is),而只是间接调用(例如foo_a示例中)。

pytest可以做到这一点吗?

标签: pythonpytesttest-coveragepytest-cov

解决方案


首先,一般的思路也是进行单元foo_a测试

import unittest
from script import main, foo_a

class Foobar(unittest.TestCase):
    def test_main(self):
        self.assertEquals(main(3), 9)

    def test_foo_a(self):
        self.assertEquals(foo_a(11), True)

您可能正在寻找可以与 pytest https://pypi.org/project/pytest-cov/一起使用的https://coverage.readthedocs.io/en/coverage-4.5.1/,这个工具可以准确地向您展示测试期间调用了哪些代码行

但是我认为还有另一种方法可以检查您的问题,它称为突变测试,这里有一些可以帮助您解决问题的库

https://github.com/sixty-north/cosmic-ray

https://github.com/mutpy/mutpy

并查看基于属性的测试库,例如https://github.com/HypothesisWorks/hypothesis/tree/master/hypothesis-python


推荐阅读