Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions changelog/8986.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Warn when a plugin raises :class:`SystemExit` from the
:hook:`pytest_cmdline_main` hook.
10 changes: 9 additions & 1 deletion src/_pytest/config/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,15 @@ def _main(
return ExitCode.USAGE_ERROR

try:
ret: ExitCode | int = config.hook.pytest_cmdline_main(config=config)
try:
ret: ExitCode | int = config.hook.pytest_cmdline_main(config=config)
except SystemExit:
warnings.warn(
PytestConfigWarning(
"A plugin raised SystemExit from the pytest_cmdline_main hook"
)
)
raise
try:
return ExitCode(ret)
except ValueError:
Expand Down
18 changes: 18 additions & 0 deletions testing/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
from _pytest.monkeypatch import MonkeyPatch
from _pytest.pathlib import absolutepath
from _pytest.pytester import Pytester
from _pytest.warning_types import PytestConfigWarning
from _pytest.warning_types import PytestDeprecationWarning
import pytest

Expand Down Expand Up @@ -852,6 +853,23 @@ def test_absolute_win32_path(self, pytester: Pytester) -> None:


class TestConfigAPI:
@pytest.mark.parametrize("code", [0, 42])
def test_cmdline_main_system_exit(self, code: int) -> None:
class Plugin:
def pytest_cmdline_main(self, config: Config) -> None:
raise SystemExit(code)

with (
pytest.warns(
PytestConfigWarning,
match="plugin raised SystemExit from the pytest_cmdline_main hook",
),
pytest.raises(SystemExit) as exc_info,
):
pytest.main([], plugins=[Plugin()])

assert exc_info.value.code == code

def test_config_trace(self, pytester: Pytester) -> None:
config = pytester.parseconfig()
values: list[str] = []
Expand Down