Versions Compared

Key

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

...

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 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
pytest pytest -k zero -v


Image Modified

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 add as '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.

...

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 Modified

TypeError example

...

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


Image Modified

ValueError example

...

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. 

...

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 Modified

The ValueError raised and test_find_item_position_in_list test passed.

...

It's impossible to reshape an array into any shape.  We can reshape an 4 elements 1D array into 2 elements in 2 rows 2D array but we cannot reshape it into a 2 elements 3 rows 2D array as that would require 2x3 = 6 elements. We can check that using Pytest.

...

We used np. ndarray. all() to check if two NumPy arrays are equivalent. 


Image Modified

The first test passed and raised a ValueError exception because there is no possibility to reshape the 4 elements list into 2x3 array. The second test also passed - a list of 4 elements can be reshaped into 2x2 array. 

...