显示python单元测试中的断言数

Dud*_*ock 7 python unit-testing assertions

phpUnit显示运行的测试次数和断言次数.我目前执行python的单元测试的方式,只显示运行的测试次数.有没有办法计算断言的数量?

Don*_*kby 4

如果您愿意使用 pytest 运行测试,它可以为您计算断言。

您可以在文件中实现一个钩子conftest.py,每个传递的断言都会调用该钩子。您可以计算被调用的次数,然后在摘要中打印出来。这不会计算对unittest.TestCase.assert...()函数的调用,只assert计算语句。

要启用该挂钩,请编写conftest.py如下文件:

assertion_count = 0


def pytest_assertion_pass(item, lineno, orig, expl):
    global assertion_count
    assertion_count += 1


def pytest_terminal_summary(terminalreporter, exitstatus, config):
    print(f'{assertion_count} assertions tested.')
Run Code Online (Sandbox Code Playgroud)

然后在您的文件中启用挂钩pytest.ini

[pytest]
enable_assertion_pass_hook=true
Run Code Online (Sandbox Code Playgroud)

您可能还会发现断言比较挂钩很有用。

毕竟,我不确定断言的数量是否是测试质量的可靠衡量标准。您可能想研究使用MutPymutmut进行突变测试。