| 926 | |
| 927 | @final |
| 928 | class RaisesContext(Generic[E]): |
| 929 | def __init__( |
| 930 | self, |
| 931 | expected_exception: Union[Type[E], Tuple[Type[E], ...]], |
| 932 | message: str, |
| 933 | match_expr: Optional[Union[str, Pattern[str]]] = None, |
| 934 | ) -> None: |
| 935 | self.expected_exception = expected_exception |
| 936 | self.message = message |
| 937 | self.match_expr = match_expr |
| 938 | self.excinfo: Optional[_pytest._code.ExceptionInfo[E]] = None |
| 939 | |
| 940 | def __enter__(self) -> _pytest._code.ExceptionInfo[E]: |
| 941 | self.excinfo = _pytest._code.ExceptionInfo.for_later() |
| 942 | return self.excinfo |
| 943 | |
| 944 | def __exit__( |
| 945 | self, |
| 946 | exc_type: Optional[Type[BaseException]], |
| 947 | exc_val: Optional[BaseException], |
| 948 | exc_tb: Optional[TracebackType], |
| 949 | ) -> bool: |
| 950 | __tracebackhide__ = True |
| 951 | if exc_type is None: |
| 952 | fail(self.message) |
| 953 | assert self.excinfo is not None |
| 954 | if not issubclass(exc_type, self.expected_exception): |
| 955 | return False |
| 956 | # Cast to narrow the exception type now that it's verified. |
| 957 | exc_info = cast(Tuple[Type[E], E, TracebackType], (exc_type, exc_val, exc_tb)) |
| 958 | self.excinfo.fill_unfilled(exc_info) |
| 959 | if self.match_expr is not None: |
| 960 | self.excinfo.match(self.match_expr) |
| 961 | return True |