You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 4 Next »

1.1. 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 if the divide() function returns an exception during a dividing number by zero or not.  In this case, 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_examples
│   ├── __init__.py
│   ├── calculator.py
│   └── list_func.py
└── tests
    ├── __init__.py
    ├── test_division.py
    └── test_exceptions.py

1.2. ZeroDivisionError example

For the record division() function looks like this:

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 that looks like this:

import pytest
from code_examples.calculator 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:

pytest test_exceptions.py -v


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.

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)

1.3. IndexError example

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

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. 

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. 

1.4. 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():

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


1.5. ValueError example

For ValueError example there is created new function called find_item_possition_in_list:

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. 

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. 

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
























  • No labels