diff --git a/doc/5934.feature.rst b/doc/5934.feature.rst new file mode 100644 index 000000000..17c0b1737 --- /dev/null +++ b/doc/5934.feature.rst @@ -0,0 +1 @@ +``repr`` of ``ExceptionInfo`` objects has been improved to honor the ``__repr__`` method of the underlying exception. diff --git a/src/_pytest/_code/code.py b/src/_pytest/_code/code.py index 534bfe2a8..1d26d94ab 100644 --- a/src/_pytest/_code/code.py +++ b/src/_pytest/_code/code.py @@ -507,7 +507,9 @@ class ExceptionInfo(Generic[_E]): def __repr__(self) -> str: if self._excinfo is None: return "" - return "" % (self.typename, len(self.traceback)) + return "<{} {} tblen={}>".format( + self.__class__.__name__, saferepr(self._excinfo[1]), len(self.traceback) + ) def exconly(self, tryshort: bool = False) -> str: """ return the exception as a string diff --git a/testing/code/test_excinfo.py b/testing/code/test_excinfo.py index e2f06a0a2..3f205b131 100644 --- a/testing/code/test_excinfo.py +++ b/testing/code/test_excinfo.py @@ -316,8 +316,19 @@ def test_excinfo_exconly(): def test_excinfo_repr_str(): excinfo = pytest.raises(ValueError, h) - assert repr(excinfo) == "" - assert str(excinfo) == "" + assert repr(excinfo) == "" + assert str(excinfo) == "" + + class CustomException(Exception): + def __repr__(self): + return "custom_repr" + + def raises(): + raise CustomException() + + excinfo = pytest.raises(CustomException, raises) + assert repr(excinfo) == "" + assert str(excinfo) == "" def test_excinfo_for_later():