I have functions in my Python code that raise exceptions in response to certain conditions, and would like to confirm that they behave as expected in my pytest scripts.
Currently I have
def test_something():
try:
my_func(good_args)
assert True
except MyError as e:
assert False
try:
my_func(bad_args)
assert False
except MyError as e:
assert e.message == "My expected message for bad args"
but this seems cumbersome (and needs to be repeated for each case).
Is there way to test exceptions and errors using Python, or a preferred pattern for doing so?
def test_something():
with pytest.raises(TypeError) as e:
my_func(bad_args)
assert e.message == "My expected message for bad args"
does not work (i.e. it passes even if I replace the assertion with assert False
).