python - 如何从pytest中获取通过、失败和跳过的测试总数

标签 python unit-testing pytest

pytest如何获取测试 session 的统计信息?

我试图在 conftest.py 文件中定义 pytest_sessionfinish,但我只看到 testsfailedtestscollected 属性在那里。

我还需要知道通过、跳过的测试次数以及花费的总时间。由于 pytest 在每个 session 结束时打印该信息,我假设有一种编程方式来检索该信息。

最佳答案

使用 pytest_terminal_summary钩。统计数据由 terminalreporter 对象提供。示例:

# conftest.py

def pytest_terminal_summary(terminalreporter, exitstatus, config):
    print('passed amount:', len(terminalreporter.stats['passed']))
    print('failed amount:', len(terminalreporter.stats['failed']))
    print('xfailed amount:', len(terminalreporter.stats['xfailed']))
    print('skipped amount:', len(terminalreporter.stats['skipped']))

    duration = time.time() - terminalreporter._sessionstarttime
    print('duration:', duration, 'seconds')

不幸的是,_pytest.terminal.TerminalReporter 不是 public API 的一部分然而,所以最好检查 its code直接。


如果您需要访问另一个钩子(Hook)中的统计信息,例如 pytest_sessionfinish,请使用插件管理器,例如:

def pytest_sessionfinish(session, exitstatus):
    reporter = session.config.pluginmanager.get_plugin('terminalreporter')
    print('passed amount:', len(reporter.stats['passed']))
    ...

但是,根据您所在的钩子(Hook),您可能无法获得完整的统计数据/正确的持续时间,因此建议您谨慎行事。

关于python - 如何从pytest中获取通过、失败和跳过的测试总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54636051/

相关文章:

python - 在 Python 中模拟远程主机

python - 参数化后如何运行拆卸功能/fixture

python - 如何解决 pytest 中的弃用警告

python - 如何阻止空格键在 PyQt5 中触发聚焦的 QPushButton?

python - 如何在numpy中找到已编译的扩展模块

python - Pandas 重命名索引

python - Windows 中的 Jenkins 在激活 Python VENV 后停止

python - 将 InlineField 添加到 ClusterableModel 不起作用

javascript - Grunt Karma 运行测试但阻止

c# - xUnit 测试引擎的 InlineDataAttribute + 可选方法参数