...
To make tests robust and detailed we also should check all exceptions which can occur during code execution. To In order to write assertions about raised exceptions, you can use pytest.raises() as a context manager. For this example, we are going to write a test to check whether the divide() function returns an exception during a dividing number by zero or not. Like in the previous section all tests will be collected in the test_operations.py file and all new functions will be added to the operations.py file.
...
If there is a need to have access to the actual exception info the Pytest context manager optionally lets you add as 'your_text' like in the example below. "'exception_info" is an ExceptionInfo instance' is an ExceptionInfo
instance, which is a wrapper around the actual exception raised. The main attributes of interest are .type
, .
value and value
and .traceback
.
Code Block | ||
---|---|---|
| ||
import pytest from sources.operations import divide def test_division_by_zero_with_exception_info(): with pytest.raises(ZeroDivisionError) as exception_info: division(1, 0) assert "division by zero" in str(exception_info.value) |
...
Moreover, there is also a change chance that arguments provided to the test_select_item_from_list function have an improper type. To verify that we are going to check if the TypeError exception was raised. Let's add another test to test_selected_item_from_list():
...