diff --git a/src/_pytest/_code/code.py b/src/_pytest/_code/code.py index 0d635db132..85ed3145e6 100644 --- a/src/_pytest/_code/code.py +++ b/src/_pytest/_code/code.py @@ -593,26 +593,18 @@ def exconly(self, tryshort: bool = False) -> str: def _get_single_subexc( eg: BaseExceptionGroup[BaseException], ) -> BaseException | None: - res: BaseException | None = None - for subexc in eg.exceptions: - if res is not None: - return None - - if isinstance(subexc, BaseExceptionGroup): - res = _get_single_subexc(subexc) - if res is None: - # there were multiple exceptions in the subgroup - return None - else: - res = subexc - return res + if len(eg.exceptions) != 1: + return None + if isinstance(e := eg.exceptions[0], BaseExceptionGroup): + return _get_single_subexc(e) + return e if ( tryshort and isinstance(self.value, BaseExceptionGroup) and (subexc := _get_single_subexc(self.value)) is not None ): - return f"[in {type(self.value).__name__}] {subexc!r}" + return f"{subexc!r} [single exception in {type(self.value).__name__}]" lines = format_exception_only(self.type, self.value) text = "".join(lines) diff --git a/testing/code/test_excinfo.py b/testing/code/test_excinfo.py index d23382c898..b049e0cf18 100644 --- a/testing/code/test_excinfo.py +++ b/testing/code/test_excinfo.py @@ -1757,15 +1757,15 @@ def test_nested_multiple() -> None: "*= short test summary info =*", ( "FAILED test_exceptiongroup_short_summary_info.py::test_base - " - "[in BaseExceptionGroup] SystemExit('aaaaaaaaaa')" + "SystemExit('aaaaaaaaaa') [single exception in BaseExceptionGroup]" ), ( "FAILED test_exceptiongroup_short_summary_info.py::test_nonbase - " - "[in ExceptionGroup] ValueError('aaaaaaaaaa')" + "ValueError('aaaaaaaaaa') [single exception in ExceptionGroup]" ), ( "FAILED test_exceptiongroup_short_summary_info.py::test_nested - " - "[in ExceptionGroup] ValueError('aaaaaaaaaa')" + "ValueError('aaaaaaaaaa') [single exception in ExceptionGroup]" ), ( "FAILED test_exceptiongroup_short_summary_info.py::test_multiple - "