Skip to content

Commit db6653c

Browse files
authored
Improve ExceptionInfo.__repr__ (#5934)
Improve ExceptionInfo.__repr__
2 parents 5c92a0f + 2a2fe7d commit db6653c

File tree

3 files changed

+17
-3
lines changed

3 files changed

+17
-3
lines changed

doc/5934.feature.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
``repr`` of ``ExceptionInfo`` objects has been improved to honor the ``__repr__`` method of the underlying exception.

src/_pytest/_code/code.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -507,7 +507,9 @@ def traceback(self, value: Traceback) -> None:
507507
def __repr__(self) -> str:
508508
if self._excinfo is None:
509509
return "<ExceptionInfo for raises contextmanager>"
510-
return "<ExceptionInfo %s tblen=%d>" % (self.typename, len(self.traceback))
510+
return "<{} {} tblen={}>".format(
511+
self.__class__.__name__, saferepr(self._excinfo[1]), len(self.traceback)
512+
)
511513

512514
def exconly(self, tryshort: bool = False) -> str:
513515
""" return the exception as a string

testing/code/test_excinfo.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -316,8 +316,19 @@ def test_excinfo_exconly():
316316

317317
def test_excinfo_repr_str():
318318
excinfo = pytest.raises(ValueError, h)
319-
assert repr(excinfo) == "<ExceptionInfo ValueError tblen=4>"
320-
assert str(excinfo) == "<ExceptionInfo ValueError tblen=4>"
319+
assert repr(excinfo) == "<ExceptionInfo ValueError() tblen=4>"
320+
assert str(excinfo) == "<ExceptionInfo ValueError() tblen=4>"
321+
322+
class CustomException(Exception):
323+
def __repr__(self):
324+
return "custom_repr"
325+
326+
def raises():
327+
raise CustomException()
328+
329+
excinfo = pytest.raises(CustomException, raises)
330+
assert repr(excinfo) == "<ExceptionInfo custom_repr tblen=2>"
331+
assert str(excinfo) == "<ExceptionInfo custom_repr tblen=2>"
321332

322333

323334
def test_excinfo_for_later():

0 commit comments

Comments
 (0)