Pytest Examples: Handling Exceptions
Last updated:Table of Contents
Python 3x+, Pytest 7x+ used unless otherwise stated.
Assert exception is raised
Use with pytest.raises(ValueError):
as a context manager:
# inside my_test.py
def test_raises_index_error():
# test will success if an IndexError is raised
with pytest.raises(IndexError):
arr = [1,2,3]
arr[1]
Assert exception with specific text
Use pytest.raises(<class>, match=<regular_expression>
). <regular_expression>
supports whatever you can use in re.search.
# inside my_test.py
def test_raises_specific_exception():
# test will success if a ValueError is raised,
# but only if the text contains a number starting with "5"
# (e.g. 500 or 503 HTTP errors)
with pytest.raises(RuntimeError, match=r"5\d+"):
some_code_that_raises_the_exception()