Skip to content

Instantly share code, notes, and snippets.

@Tadaboody
Created March 31, 2020 11:58
Show Gist options
  • Save Tadaboody/030d504d978ef7bdd95bffa418cb376c to your computer and use it in GitHub Desktop.
Save Tadaboody/030d504d978ef7bdd95bffa418cb376c to your computer and use it in GitHub Desktop.
Check if a function raises an expected exception with given arguments
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