Pytest testing expected exception
Pytest provides a tool that allows us to “expect and exception”.
We’ll usually use it using a with context manager.
Here we can see two different ways to verify the exception.
import pytest
from fibonacci import fib
def test_fib():
assert fib(10) == 55
def test_fib_negative():
with pytest.raises(Exception) as err:
fib(-1)
assert err.type == ValueError
assert str(err.value) == 'Invalid parameter -1'
def test_fib_negative_again():
with pytest.raises(ValueError) as err:
fib(-1)
assert str(err.value) == 'Invalid parameter -1'
Output:
============================= test session starts ==============================
platform linux -- Python 3.8.6, pytest-6.1.2, py-1.9.0, pluggy-0.13.1
rootdir: /home/gabor/work/slides/python/examples/pytest/fib2
plugins: flake8-1.0.6, dash-1.17.0
collected 3 items
test_fibonacci.py ... [100%]
============================== 3 passed in 0.01s ===============================
Now that we are testing the exception let’s see how will this test protect us?
- Someone changing the text of the exception.
- Someone removing the exception.