Created
March 31, 2020 11:58
-
-
Save Tadaboody/030d504d978ef7bdd95bffa418cb376c to your computer and use it in GitHub Desktop.
Check if a function raises an expected exception with given arguments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ExceptionMatch = typing.Union[ | |
typing.Type[Exception], typing.Tuple[typing.Type[Exception], ...] | |
] | |
def raises( | |
expected_exception: ExceptionMatch, | |
function: typing.Callable, | |
*args, | |
**kwargs, | |
) -> bool: | |
""" | |
Checks if calling the given function raises an exception of the given type. | |
>>> def will_raise(cond=True): | |
... if cond: | |
... raise ValueError | |
>>> raises(ValueError,will_raise) | |
True | |
>>> raises(IndexError, will_raise) | |
False | |
>>> raises(ValueError, will_raise, False) | |
False | |
>>> raises(ValueError, will_raise, cond=False) | |
False | |
>>> raises(IndexError, lambda: True) | |
False | |
""" | |
try: | |
function(*args, **kwargs) | |
except expected_exception: | |
return True | |
except: # Unexpected exception | |
pass | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment