Utility class to assert that an exception was raised when expected Example: .. highlight:: python .. code-block:: python with ExceptionExpected(True, 'Division by zero'): x = 1.0 / 0.0 :param exception_expected: whether an exception is expected to be rais
| 34 | Helper functions & classes for interface test |
| 35 | """ |
| 36 | class ExpectException: |
| 37 | """ |
| 38 | Utility class to assert that an exception was raised when expected |
| 39 | |
| 40 | Example: |
| 41 | |
| 42 | .. highlight:: python |
| 43 | .. code-block:: python |
| 44 | |
| 45 | with ExceptionExpected(True, 'Division by zero'): |
| 46 | x = 1.0 / 0.0 |
| 47 | |
| 48 | :param exception_expected: whether an exception is expected to be raised |
| 49 | :type exception_expected: bool |
| 50 | :param message: message to print if an exception is raised when not expected or vice versa |
| 51 | :type message: str |
| 52 | """ |
| 53 | def __init__(self, exception_expected: bool, message: str = '', verify_msg=False): |
| 54 | self.exception_expected = exception_expected |
| 55 | self.message = message |
| 56 | self.verify_msg = verify_msg |
| 57 | |
| 58 | def __enter__(self): |
| 59 | return self |
| 60 | |
| 61 | def __exit__(self, exc_type, exc_val, traceback): |
| 62 | exception_raised = exc_type is not None |
| 63 | assert self.exception_expected == exception_raised, self.message |
| 64 | if self.verify_msg: |
| 65 | exc_message = f"{exc_type.__name__}: {exc_val}" |
| 66 | assert exc_message == self.message, f"expect error message {self.message}, got {exc_message}" |
| 67 | |
| 68 | # Suppress the exception |
| 69 | return True |
no outgoing calls