Skip to content

Commit

Permalink
Rework ExceptionInfo to not require manual __init__ call
Browse files Browse the repository at this point in the history
Mypy doesn't like calling __init__() in this way.
  • Loading branch information
bluetech committed Jul 11, 2019
1 parent 5efa5d4 commit fbb69c5
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 9 deletions.
7 changes: 6 additions & 1 deletion src/_pytest/_code/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -427,11 +427,16 @@ def from_current(
return cls(tup, _striptext)

@classmethod
def for_later(cls) -> "ExceptionInfo[_E]":
def unfilled(cls) -> "ExceptionInfo[_E]":
"""return an unfilled ExceptionInfo
"""
return cls(None)

def fill_unfilled(self, exc_info: Tuple["Type[_E]", _E, TracebackType]) -> None:
"""fill an unfilled ExceptionInfo"""
assert self._excinfo is None, "ExceptionInfo was already filled"
self._excinfo = exc_info

@property
def type(self) -> "Type[_E]":
"""the exception class"""
Expand Down
16 changes: 10 additions & 6 deletions src/_pytest/python_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -731,7 +731,7 @@ def __init__(
self.excinfo = None # type: Optional[_pytest._code.ExceptionInfo[_E]]

def __enter__(self) -> _pytest._code.ExceptionInfo[_E]:
self.excinfo = _pytest._code.ExceptionInfo.for_later()
self.excinfo = _pytest._code.ExceptionInfo.unfilled()
return self.excinfo

def __exit__(
Expand All @@ -744,9 +744,13 @@ def __exit__(
if exc_type is None:
fail(self.message)
assert self.excinfo is not None
# Type ignored because mypy doesn't like calling __init__ directly like this.
self.excinfo.__init__((exc_type, exc_val, exc_tb)) # type: ignore
suppress_exception = issubclass(self.excinfo.type, self.expected_exception)
if self.match_expr is not None and suppress_exception:
if not issubclass(exc_type, self.expected_exception):
return False
# Cast to narrow the exception type now that it's verified.
exc_info = cast(
Tuple["Type[_E]", _E, TracebackType], (exc_type, exc_val, exc_tb)
)
self.excinfo.fill_unfilled(exc_info)
if self.match_expr is not None:
self.excinfo.match(self.match_expr)
return suppress_exception
return True
4 changes: 2 additions & 2 deletions testing/code/test_excinfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -339,8 +339,8 @@ def test_excinfo_repr_str():
assert str(excinfo) == "<ExceptionInfo ValueError tblen=4>"


def test_excinfo_for_later():
e = ExceptionInfo.for_later()
def test_excinfo_unfilled():
e = ExceptionInfo.unfilled()
assert "for raises" in repr(e)
assert "for raises" in str(e)

Expand Down

0 comments on commit fbb69c5

Please sign in to comment.