diff --git a/changelog/8986.bugfix.rst b/changelog/8986.bugfix.rst new file mode 100644 index 00000000000..c0e5ba37270 --- /dev/null +++ b/changelog/8986.bugfix.rst @@ -0,0 +1 @@ +Emit a :class:`~pytest.PytestConfigWarning` when a plugin raises ``SystemExit`` in :hook:`pytest_cmdline_main`. diff --git a/src/_pytest/config/__init__.py b/src/_pytest/config/__init__.py index 76d4fc99fa1..d99ae33ee9b 100644 --- a/src/_pytest/config/__init__.py +++ b/src/_pytest/config/__init__.py @@ -259,7 +259,17 @@ def _main( return ExitCode.INTERNAL_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 in pytest_cmdline_main; " + "pytest_cmdline_main implementations should return an ExitCode or int instead." + ), + stacklevel=2, + ) + raise try: return ExitCode(ret) except ValueError: diff --git a/testing/test_main.py b/testing/test_main.py index 41d7055df26..b6f1a099144 100644 --- a/testing/test_main.py +++ b/testing/test_main.py @@ -370,3 +370,21 @@ def test_foo(specified_feeds): ) result = pytester.runpytest("--long-list", ",".join(["helloworld"] * 100_000)) result.stdout.fnmatch_lines("* 1 passed *") + + +def test_cmdline_main_systemexit_warning() -> None: + """Warn when a plugin raises SystemExit in pytest_cmdline_main (#8986).""" + + class Plugin: + def pytest_cmdline_main(self) -> int: + raise SystemExit(2) + + with ( + pytest.warns( + pytest.PytestConfigWarning, + match="A plugin raised SystemExit in pytest_cmdline_main", + ), + pytest.raises(SystemExit) as excinfo, + ): + pytest.main([], plugins=[Plugin()]) + assert excinfo.value.code == 2