Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test exceptions and errors using pytest?

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).

like image 709
orome Avatar asked Nov 25 '15 15:11

orome


People also ask

How can I tell if an error is raised pytest?

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.

How do you write test cases for exceptions in Python?

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.


1 Answers

This way:

with pytest.raises(<YourException>) as exc_info:
    <your code that should raise YourException>

exception_raised = exc_info.value
<do asserts here>
like image 57
Damián Montenegro Avatar answered Sep 30 '22 22:09

Damián Montenegro