Skip to content

Commit fbb69c5

Browse files
committed
Rework ExceptionInfo to not require manual __init__ call
Mypy doesn't like calling __init__() in this way.
1 parent 5efa5d4 commit fbb69c5

File tree

3 files changed

+18
-9
lines changed

3 files changed

+18
-9
lines changed

src/_pytest/_code/code.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -427,11 +427,16 @@ def from_current(
427427
return cls(tup, _striptext)
428428

429429
@classmethod
430-
def for_later(cls) -> "ExceptionInfo[_E]":
430+
def unfilled(cls) -> "ExceptionInfo[_E]":
431431
"""return an unfilled ExceptionInfo
432432
"""
433433
return cls(None)
434434

435+
def fill_unfilled(self, exc_info: Tuple["Type[_E]", _E, TracebackType]) -> None:
436+
"""fill an unfilled ExceptionInfo"""
437+
assert self._excinfo is None, "ExceptionInfo was already filled"
438+
self._excinfo = exc_info
439+
435440
@property
436441
def type(self) -> "Type[_E]":
437442
"""the exception class"""

src/_pytest/python_api.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -731,7 +731,7 @@ def __init__(
731731
self.excinfo = None # type: Optional[_pytest._code.ExceptionInfo[_E]]
732732

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

737737
def __exit__(
@@ -744,9 +744,13 @@ def __exit__(
744744
if exc_type is None:
745745
fail(self.message)
746746
assert self.excinfo is not None
747-
# Type ignored because mypy doesn't like calling __init__ directly like this.
748-
self.excinfo.__init__((exc_type, exc_val, exc_tb)) # type: ignore
749-
suppress_exception = issubclass(self.excinfo.type, self.expected_exception)
750-
if self.match_expr is not None and suppress_exception:
747+
if not issubclass(exc_type, self.expected_exception):
748+
return False
749+
# Cast to narrow the exception type now that it's verified.
750+
exc_info = cast(
751+
Tuple["Type[_E]", _E, TracebackType], (exc_type, exc_val, exc_tb)
752+
)
753+
self.excinfo.fill_unfilled(exc_info)
754+
if self.match_expr is not None:
751755
self.excinfo.match(self.match_expr)
752-
return suppress_exception
756+
return True

testing/code/test_excinfo.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -339,8 +339,8 @@ def test_excinfo_repr_str():
339339
assert str(excinfo) == "<ExceptionInfo ValueError tblen=4>"
340340

341341

342-
def test_excinfo_for_later():
343-
e = ExceptionInfo.for_later()
342+
def test_excinfo_unfilled():
343+
e = ExceptionInfo.unfilled()
344344
assert "for raises" in repr(e)
345345
assert "for raises" in str(e)
346346

0 commit comments

Comments
 (0)