Navigation Menu

Skip to content

Commit

Permalink
Merge pull request #4444 from RonnyPfannschmidt/fix-4386-2
Browse files Browse the repository at this point in the history
fix #4386 - handle uninitialized exceptioninfo in repr/str
  • Loading branch information
nicoddemus committed Nov 23, 2018
2 parents e4ae33d + 9ae8429 commit 0b73d6d
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 4 deletions.
1 change: 1 addition & 0 deletions changelog/4386.bugfix.rst
@@ -0,0 +1 @@
Handle uninitialized exceptioninfo in repr/str.
15 changes: 11 additions & 4 deletions src/_pytest/_code/code.py
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
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)
raise E()

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

0 comments on commit 0b73d6d

Please sign in to comment.