24

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

orome
  • 45,163
  • 57
  • 202
  • 418
  • 2
    The line is never executed since raises TypeError exception. You should refactor your code to do assertions on e out of scope (as shown in the answer of this question). – Damián Montenegro Nov 25 '15 at 20:51
  • 2
    Possible duplicate of [How to properly assert that an exception gets raised in pytest?](http://stackoverflow.com/questions/23337471/how-to-properly-assert-that-an-exception-gets-raised-in-pytest) – Peter Wood May 05 '17 at 06:28

1 Answers1

42

This way:

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

exception_raised = exc_info.value
<do asserts here>
orome
  • 45,163
  • 57
  • 202
  • 418
  • @raxacoricofallapatorius it works. You should refactor your code to do assertions on e out of scope. – Damián Montenegro Nov 25 '15 at 20:52
  • 1
    Can you show how I would (a) do several different tests (e.g. several calls do different functions or several calls with bad args) and (b) how to test that for no exception when there should not be one? – orome Nov 25 '15 at 20:53
  • 6
    Pytest evolved since then. I find this more elegant, and more complete: https://stackoverflow.com/a/56569533/145400 – Dr. Jan-Philip Gehrcke Feb 09 '20 at 14:01