Given the following code:
def fun(param):
if param == 'a':
assert False
else:
return None
# fun('a') THIS THROWS AN AssertionError
# PSEUDOCODE FOR WHAT I WANT TO DO:
# assert (fun('a') throws an AssertionError)
assert fun('b') == None
How do I assert that the first function call (fun('a')) will give me an AssertionError? Will I need a try-catch for this or is there a more elegant way?
You can use
pytest
for this:This will raise an error if
fun('a')
does not raise an AssertionError.Or, if you are using
unittest
, and you are within aTestCase
, you can useassert Raises
:Also, as other answers have mentioned, you would be better off
raise
ing an error than assertingFalse
. And if you do raise an error, you could raise one that tells the user more about what went wrong, or raise your own custom exception: