How to get the total number of tests passed, failed and skipped from pytest

不羁的心 提交于 2019-12-22 09:47:04

问题


How can I get to the statistics information of a test session in pytest?

I've tried to define pytest_sessionfinish in the conftest.py file, but I only see testsfailed and testscollected attributes on there.

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.


回答1:


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')

Unfortunately, _pytest.terminal.TerminalReporter isn't part of the public API yet, so it's best to inspect its code directly.


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.



来源:https://stackoverflow.com/questions/54636051/how-to-get-the-total-number-of-tests-passed-failed-and-skipped-from-pytest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!