Skip to content

Commit 99d162e

Browse files
committed
Handle Exit exception in pytest_sessionfinish
Similar to a7268aa (#6258).
1 parent 8bd612b commit 99d162e

File tree

3 files changed

+34
-3
lines changed

3 files changed

+34
-3
lines changed

changelog/6660.bugfix.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
:func:`pytest.exit() <_pytest.outcomes.exit>` is handled when emitted from the :func:`pytest_sessionfinish <_pytest.hookspec.pytest_sessionfinish>` hook. This includes quitting from a debugger.

src/_pytest/main.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -244,9 +244,14 @@ def wrap_session(
244244
excinfo = None # type: ignore
245245
session.startdir.chdir()
246246
if initstate >= 2:
247-
config.hook.pytest_sessionfinish(
248-
session=session, exitstatus=session.exitstatus
249-
)
247+
try:
248+
config.hook.pytest_sessionfinish(
249+
session=session, exitstatus=session.exitstatus
250+
)
251+
except Exit as exc:
252+
if exc.returncode is not None:
253+
session.exitstatus = exc.returncode
254+
sys.stderr.write("{}: {}\n".format(type(exc).__name__, exc))
250255
config._ensure_unconfigure()
251256
return session.exitstatus
252257

testing/test_main.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
1+
from typing import Optional
2+
13
import pytest
24
from _pytest.main import ExitCode
5+
from _pytest.pytester import Testdir
36

47

58
@pytest.mark.parametrize(
@@ -50,3 +53,25 @@ def pytest_internalerror(excrepr, excinfo):
5053
assert result.stderr.lines == ["mainloop: caught unexpected SystemExit!"]
5154
else:
5255
assert result.stderr.lines == ["Exit: exiting after {}...".format(exc.__name__)]
56+
57+
58+
@pytest.mark.parametrize("returncode", (None, 42))
59+
def test_wrap_session_exit_sessionfinish(
60+
returncode: Optional[int], testdir: Testdir
61+
) -> None:
62+
testdir.makeconftest(
63+
"""
64+
import pytest
65+
def pytest_sessionfinish():
66+
pytest.exit(msg="exit_pytest_sessionfinish", returncode={returncode})
67+
""".format(
68+
returncode=returncode
69+
)
70+
)
71+
result = testdir.runpytest()
72+
if returncode:
73+
assert result.ret == returncode
74+
else:
75+
assert result.ret == ExitCode.NO_TESTS_COLLECTED
76+
assert result.stdout.lines[-1] == "collected 0 items"
77+
assert result.stderr.lines == ["Exit: exit_pytest_sessionfinish"]

0 commit comments

Comments
 (0)