[英]How to get the total number of tests passed, failed and skipped from pytest
How can I get to the statistics information of a test session in pytest?如何在pytest中获取测试会话的统计信息?
I've tried to define pytest_sessionfinish
in the conftest.py
file, but I only see testsfailed
and testscollected
attributes on there.我试图在
conftest.py
文件中定义pytest_sessionfinish
,但我只在那里看到testsfailed
和testscollected
属性。
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 在每个会话结束时打印该信息,我假设有一种编程方式来检索该信息。
Use the pytest_terminal_summary
hook.使用
pytest_terminal_summary
钩子。 The stats are provided by the terminalreporter
object.统计信息由
terminalreporter
对象提供。 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')
Unfortunately, _pytest.terminal.TerminalReporter
isn't part of the public API yet, so it's best to inspect its code directly.不幸的是,
_pytest.terminal.TerminalReporter
是公共 API 的一部分,因此最好直接检查其代码。
If you need to access the stats in another hook like pytest_sessionfinish
, use the plugin manager, eg:如果您需要访问另一个钩子(如
pytest_sessionfinish
的统计信息,请使用插件管理器,例如:
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.但是,根据您所处的钩子,您可能无法获得完整的统计数据/正确的持续时间,因此建议谨慎。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.