Skip to content

fix #4386 - handle uninitialized exceptioninfo in repr/str #4444

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 23, 2018
Merged
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
1 change: 1 addition & 0 deletions changelog/4386.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Handle uninitialized exceptioninfo in repr/str.
15 changes: 11 additions & 4 deletions src/_pytest/_code/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -425,7 +425,10 @@ def __init__(self, tup=None, exprinfo=None):
self.traceback = _pytest._code.Traceback(self.tb, excinfo=ref(self))

def __repr__(self):
return "<ExceptionInfo %s tblen=%d>" % (self.typename, len(self.traceback))
try:
return "<ExceptionInfo %s tblen=%d>" % (self.typename, len(self.traceback))
except AttributeError:
return "<ExceptionInfo uninitialized>"

def exconly(self, tryshort=False):
""" return the exception as a string
Expand Down Expand Up @@ -513,9 +516,13 @@ def getrepr(
return fmt.repr_excinfo(self)

def __str__(self):
entry = self.traceback[-1]
loc = ReprFileLocation(entry.path, entry.lineno + 1, self.exconly())
return str(loc)
try:
entry = self.traceback[-1]
except AttributeError:
return repr(self)
else:
loc = ReprFileLocation(entry.path, entry.lineno + 1, self.exconly())
return str(loc)

def __unicode__(self):
entry = self.traceback[-1]
Expand Down
17 changes: 17 additions & 0 deletions testing/python/raises.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,23 @@ def __call__(self):
except pytest.raises.Exception:
pass

def test_raises_repr_inflight(self):
"""Ensure repr() on an exception info inside a pytest.raises with block works (#4386)"""

class E(Exception):
pass

with pytest.raises(E) as excinfo:
# this test prints the inflight uninitialized object
# using repr and str as well as pprint to demonstrate
# it works
print(str(excinfo))
print(repr(excinfo))
import pprint

pprint.pprint(excinfo)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please add a comment explaining the strategy here

raise E()

def test_raises_as_contextmanager(self, testdir):
testdir.makepyfile(
"""
Expand Down