如何从pytest中获取通过、失败和跳过的测试总数 [英] How to get the total number of tests passed, failed and skipped from pytest
问题描述
如何在pytest中获取一个test session的统计信息?
How can I get to the statistics information of a test session in pytest?
我尝试在 conftest.py
文件中定义 pytest_sessionfinish
,但我只看到 testsfailed
和 testscollected代码>属性在那里.
I've tried to define pytest_sessionfinish
in the conftest.py
file, but I only see testsfailed
and testscollected
attributes on there.
我还需要知道通过、跳过的测试数量以及花费的总时间.由于 pytest 在每个会话结束时打印该信息,我认为有一种编程方式可以检索该信息.
I also need to know the number of tests passed, skipped and the total time it took. Since pytest prints that info at the end of each session, I assume there's a programmatic way to retrieve that.
推荐答案
使用 pytest_terminal_summary
钩子.统计信息由 terminalreporter
对象提供.示例:
Use the pytest_terminal_summary
hook. The stats are provided by the terminalreporter
object. Example:
# 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
不是 公共 API,所以最好检查 它的代码直接.
Unfortunately, _pytest.terminal.TerminalReporter
isn't part of the public API yet, so it's best to inspect its code directly.
如果您需要访问另一个钩子(如 pytest_sessionfinish
)中的统计信息,请使用插件管理器,例如:
If you need to access the stats in another hook like pytest_sessionfinish
, use the plugin manager, e.g.:
def pytest_sessionfinish(session, exitstatus):
reporter = session.config.pluginmanager.get_plugin('terminalreporter')
print('passed amount:', len(reporter.stats['passed']))
...
但是,根据您所处的钩子,您可能无法获得完整的统计数据/正确的持续时间,因此建议谨慎.
However, depending on what hook you are in, you may not get the complete stats/correct duration, so caution advised.
这篇关于如何从pytest中获取通过、失败和跳过的测试总数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!