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 example, we are going to write a test to check if the divide() function returns an exception during a dividing number by zero or not.  In this example, all tests are written in the test_exceptions.py file. For the tutorial purpose, there is also created new file list_func.py which contains the extra function to test.  

Our project folder should look like this:

Code Block
languagetext
.
├── code_examples
│   ├── division_func.py
│   ├── __init__.py
│   └── list_func.py
└── tests
    ├── __init__.py
    ├── test_division_func.py
    └── test_exceptions.py

ZeroDivisionError example

For the record division() function looks like this:

Code Block
languagepy
def division(a, b):
    return a/b


To check is dividing by zero returns exception we are going to import pytest and write a test which looks like this:

Code Block
languagepy
import pytest
from code_examples.division_func import division


def test_division_by_zero():
    with pytest.raises(ZeroDivisionError):
        division(1, 0)


This test uses a special context manager facility in pytest, in which you run a block of code that you expect to raise an exception, and let pytest handle it. Your test will fail if the exception is not raised. 

Let's run a pytest and see the output. To run the only tests from the test_exceptions.py file pytest run should look like this:

Code Block
languagetext
pytest test_exceptions.py -v


Image Added

Test passed. As expected, the division method returns a ZeroDivisionError exception.  


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, which is a wrapper around the actual exception raised. The main attributes of interest are .type, .value and .traceback.

Code Block
languagepy
import pytest
from code_examples.division_func import division


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:

Code Block
languagepy
def select_item_from_list(lst, idx):
    return lst[idx]


This dummy function doesn't have protection against providing a list index that is out of range (is greater than list length). To prevent that there should be a test that checks if provided index is improper range. 

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


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

Image Added

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
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')


Image Added

ValueError example

For ValueError example there is created new function called find_item_possition_in_list:

Code Block
languagepy
def find_item_position_in_list(lst, item):
    return lst.index(item)


This function also doesn't have protection against fails that can occur during code execution. What if somebody provides an item and list which doesn't contain this element. There is no opportunity to find the position of the element which doesn't occur in the list. Let's prove it by test using the ValueError exception. 

Code Block
languagepy
def test_find_item_position_in_list():
    with pytest.raises(ValueError):
        find_item_position_in_list([], 1)


As expected there is no change to find a position of element '1' in an empty list. Let's run the test and check the output. 

Image Added

The ValueError raised and test_find_item_position_in_list test passed.




The official documentation with listed available python built-in exceptions: https://docs.python.org/3/library/exceptions.html