Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Table of Contents

Introduction to testing exceptions

To make tests robust and detailed we also should check all exceptions which can occur during code execution. 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. 

...

Code Block
languagetext
.
└── calculator
    ├── sources
    │   ├──  operations.py
    │   └── __init__.py
    └── tests
        ├── __init__.py
        └── test_operations.py

ZeroDivisionError example

For the record division() function looks like this:

...

Code Block
languagepy
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)

IndexError example

For the IndexError example we need to create another python function:

...

We expect there is no possibility to select the 10th element from the list of three. Our test passed because of the IndexError exception. 

TypeError example

Moreover, there is also a change 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():

Code Block
languagepy
from sources.operations import select_item_from_list


def test_select_item_from_list():
    with pytest.raises(IndexError):
        select_item_from_list([1, 2, 3], 10)

    with pytest.raises(TypeError):
        select_item_from_list('list A', 'index')


ValueError example

For ValueError example there is new function called find_item_possition_in_list:

...

The ValueError raised and test_find_item_position_in_list test passed.


 ValueError - advanced example

Firstly let's write another function called reshape_array.  The function arguments are a list (lst) and output array dimensions  (x and y). The result is an array containing the same data with a new shape. To transform list to array and reshape it there is the NumPy package needed. 

...