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.
Use the pytest_terminal_summary
hook. The stats are provided by the terminalreporter
object. Example:
# conftest.pydef 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._sessionstarttimeprint('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.