Testing Python Exceptions
Python’s py.test provides a helper to test code raises the right exceptions.
import pytest
def test_divide():
with pytest.raises(ZeroDivisionError) as excinfo:
1 / 0
The pytest.raises
helper will fail a test if the error is not raised.
The excinfo
value contains info about the error for more asserts. It has the
following properties:
value
- An instance of the error caught by py.test.
type
- The class of the error instance.
traceback
- The traceback of the error instance.
import pytest
def test_divide():
with pytest.raises(ZeroDivisionError) as excinfo:
1 / 0
assert 'division by zero' in str(excinfo.value)