komodovaran_
komodovaran_

Reputation: 2012

How do I obtain test durations with pytest session_finish?

Instead of capturing the printed output of --durations=..., how can I capture them via e.g. the pytest_sessionfinish function?

I've tried to capture them via a dict self.durations = {} in a plugin class:

def pytest_runtest_logreport(self, report):
    self.durations[report.head_line] = report.duration

But the numbers seem way too low from what pytest itself reports.

Upvotes: 0

Views: 361

Answers (1)

anthony sottile
anthony sottile

Reputation: 70223

you're probably capturing the durations from teardown (or I guess more specifically, you're capturing all of them but the (often trivial) teardown is clobbering the others) -- you need to specifically filter for .when == 'call'

class CollectResults:
    def __init__(self) -> None:
        self.times: dict[str, bool] = {}

    def pytest_runtest_logreport(self, report: pytest.TestReport) -> None:
        if report.when == 'call':
            self.results[report.head_line] = report.duration

___

disclaimer: I'm one of the pytest core devs

Upvotes: 1

Related Questions