How to get all failed tests _just once_ at the end of the session? #12651
-
I'd like to do something if certain tests have failed, just once, at the end of a test session. Note that this code DOES NOT WORK: @pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_logreport(report: pytest.TestReport) -> Generator[None, None]:
outcome = yield
if report.when == "call" and report.outcome == "failed":
do_the_thing() The problem with ☝🏻 is that it will execute for every single failed test. That's not what I want. I want the code in So I need a higher level hook maybe? But this code ALSO DOES NOT WORK: def pytest_sessionfinish(session: pytest.Session, exitstatus: int) -> None:
if exitstatus != pytest.ExitCode.OK:
do_the_thing() With ☝🏻 the code in
From some googling, I've seen that some people say there should be a So what is the lifetime hook, incantation, and properties that can tell me what tests failed at the end of running a test suite? Is such a thing even possible? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
I figured out a workaround but it seems like I'm doing something wrong here because I needed to import from import pytest
from _pytest.terminal import TerminalReporter
def pytest_terminal_summary(terminalreporter: TerminalReporter, exitstatus: int) -> None:
if exitstatus == pytest.ExitCode.OK:
return
session: pytest.Session | None = terminalreporter._session
if session is None:
return
should_do_the_thing = False
failures: set[str] = {failure.nodeid for failure in terminalreporter.getreports("failed")}
for item in session.items:
if not item.get_closest_marker("failure_triggers_do_the_thing"):
continue
if item.nodeid in failures:
should_do_the_thing = True
break
if should_do_the_thing:
do_the_thing() Also it's unclear if this will only trigger if there's a terminal report. What if the only report style selected is an HTML report? I guess maybe it won't run in that case? No idea. Edit: This still doesn't work if you're using |
Beta Was this translation helpful? Give feedback.
-
Hi, I think the proper way is to implement pytest will not save the intermediate results anywhere by design: it is expected that each plugin interested in test results to implement |
Beta Was this translation helpful? Give feedback.
-
@nicoddemus Actually, my accepted answer is still wrong. When using |
Beta Was this translation helpful? Give feedback.
I figured out a workaround but it seems like I'm doing something wrong here because I needed to import from
_pytest
and access a_session
property to do it 🤷🏻♀️