Exception | How Do You Test That A Python Function Throws An Exception?

In this post, we will learn How to test that a Python function throws an Exception where we can use the assert raises method from the in built module called the ‘unit test’ module which we can directly import from the library.


Catching Exception

Here we have given an example where we can see how we had checked for an error that might occur here and for the same we have given a pseudo code to show does it work.

import unit test

def divide( x, y):
    if y == 0:
        raise Zero Division Error(" division by zero")
    return x / y

class Test Divide( unit test. TestCase):

    def test_divide_by_zero( self):
        with self.assertRaises( ZeroDivisionError):
            divide(1, 0)

    def test_divide( self):
        self.assertEqual( divide(4, 2), 2)

In the example given above where we have given a divide function that has raised a ‘Zero Division Error’ depending upon the value of the” variable which is given as zero in this case. And here we have also used the assert raises method in the test to ‘decide by zero’. test case to check that the function raises the expected exception when called with one and zero.

Here the assert raises method takes the expected exception type as its first argument, and the function and arguments to call as the remaining arguments. It checks that the function raises the expected exception and returns nothing which means the console will be empty in this case.

We can also use an alternative method for doing the same and here we are using the pytest method for the same thing to be done so here we have given an example to explain and understand t better.

def divide(x, y):
    if y == 0:
        raise Value Error(" Cannot divide by zero")
    return x / y

def test_divide_by_zero():
    with pytest.raises( ValueError):
        divide(4, 0)

def test_divide():
    assert divide(4, 2) == 2

In this example, we define the divide function as before. We also define two test functions, test divide by zero and test divide which correspond to the two tests in the previous example.

Tere the test which is dividing by zero function uses the pytest raises context manager to test that the divided function raises a value error or we can say it except when the second argument is given as zero which will create the problem.




To learn more about How do you test that a Python function throws an exception visit:  by stack overflow

To learn more about solutions to different problems and tutorials for the concepts we need to know to work on programming along with different ways to solve any generally asked problems: How To Pass-Variables From A Java & all Client To A Linux/Ubuntu Server Which Is Running C?.

Leave a Comment

%d bloggers like this: