How do I test exceptions and errors using pytest?
15,354
This way:
with pytest.raises(<YourException>) as exc_info:
<your code that should raise YourException>
exception_raised = exc_info.value
<do asserts here>
Author by
orome
"I mingle the probable with the necessary and draw a plausible conclusion from the mixture."
Updated on June 24, 2022Comments
-
orome almost 2 years
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
). -
Damián Montenegro over 8 years@raxacoricofallapatorius it works. You should refactor your code to do assertions on e out of <with .... as e: > scope.
-
orome over 8 yearsCan 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?
-
Dr. Jan-Philip Gehrcke over 4 yearsPytest evolved since then. I find this more elegant, and more complete: stackoverflow.com/a/56569533/145400