You'd want this if you want to fail if and only if a ValueError is thrown (and pass on all other exceptions, and also pass if there is NO exception at all):
def test_exception():
try:
call_some_function()
except ValueError:
assert False
except:
pass
If you want to make sure an exception is thrown, but NOT a ValueError, then you'd want this:
def test_exception():
try:
call_some_function()
assert False
except ValueError:
assert False
except:
pass
As a warning, this is backwards from what most people want to test. Not saying what you're doing is wrong, but usually you want to test that a certain exception IS being thrown: not that a certain exception is NOT being thrown. If that's what you want, you'd want this:
def test_exception():
try:
call_some_function()
assert False
except ValueError:
pass
except:
assert False
Or you could get rid of that last except
block and let it bubble up. The difference is just between an "error" and a "failure". Either way, your test suite won't pass.
In terms of style, there's nothing wrong with assert False
or assert 0
when you want to explicitly fail. I (and other professional python devs I work with) do it all the time.
EDIT: Better to use pytest.fail
with a particular message instead of assert False
, especially in cases where there is more than one assert False
floating around. That way, you'll know which assert
failed and why if you add a helpful error message.