Assert that a callable raises an expected exception type. Args: expected_exception: Exception type or tuple of types to expect func: Callable to invoke *args: Positional arguments to pass to func match: Optional regex pattern to match in exception message
(
expected_exception: Union[Type[BaseException], tuple],
func,
*args,
match: Optional[str] = None,
**kwargs
)
| 5 | |
| 6 | |
| 7 | def assert_raises( |
| 8 | expected_exception: Union[Type[BaseException], tuple], |
| 9 | func, |
| 10 | *args, |
| 11 | match: Optional[str] = None, |
| 12 | **kwargs |
| 13 | ) -> None: |
| 14 | """Assert that a callable raises an expected exception type. |
| 15 | |
| 16 | Args: |
| 17 | expected_exception: Exception type or tuple of types to expect |
| 18 | func: Callable to invoke |
| 19 | *args: Positional arguments to pass to func |
| 20 | match: Optional regex pattern to match in exception message |
| 21 | **kwargs: Keyword arguments to pass to func |
| 22 | |
| 23 | Raises: |
| 24 | AssertionError: If expected exception is not raised |
| 25 | """ |
| 26 | try: |
| 27 | func(*args, **kwargs) |
| 28 | except expected_exception as exc: |
| 29 | if match is not None: |
| 30 | if not re.search(match, str(exc)): |
| 31 | raise AssertionError(f"Pattern '{match}' not found in '{exc}'") |
| 32 | return |
| 33 | except Exception as exc: |
| 34 | raise AssertionError( |
| 35 | f"Expected {expected_exception}, got {type(exc).__name__}: {exc}" |
| 36 | ) |
| 37 | |
| 38 | raise AssertionError(f"Expected {expected_exception} to be raised") |
no test coverage detected