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
).
The raises() method The pytest framework's raises() method asserts that a block of code or a function call raises the specified exception. If it does not, the method raises a failure exception, indicating that the intended exception was not raised.
There are two ways you can use assertRaises: using keyword arguments. Just pass the exception, the callable function and the parameters of the callable function as keyword arguments that will elicit the exception. Make a function call that should raise the exception with a context.
This way:
with pytest.raises(<YourException>) as exc_info:
<your code that should raise YourException>
exception_raised = exc_info.value
<do asserts here>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With