What is assertRaises?
assertraises is a function that fails unless an exception is raised by an object of a class. It is mostly used in testing scenarios to prevent our code from malfunctioning.
Let’s work with a detailed example to see the working of assertRaises.
Code
Imagine that you are asked to write a function that calculates the volume of a sphere where the radius is given.
You may remember that the volume of a sphere is .
Let’s write a code for this problem:
def sphere_volume(radius):pi = 3.141592653589793return 4/3 * pi * (radius**3)r = [1, 2.5, 3.4, 5.6, 7, 9.0]for x in r:print("Volume of sphere with radius = ",x ,"is", sphere_volume(x))
What if a string, a boolean value, or a negative number is passed as a radius? Let’s see what will happen:
def sphere_volume(radius):pi = 3.141592653589793return 4/3 *pi*(radius**3)r = [1,2.5,3.4,5.6,7,9.0, -2, -5, True, False, "string"]for x in r:print("Volume of sphere with radius = ", x, "is", sphere_volume(x))
The function can also outputs on the following values instead of throwing an error:
-2– The radius cannot be a negative value-5– The radius cannot be a negative valueTrue– The radius cannot be a boolean valueFalse– The radius cannot be a boolean value
The program gives an error when a string is passed as a radius. We want functions to cover all cases of errors, which is why we need to use assertRaises to validate the radius passed. Let’s write the code for the test file:
def sphere_volume(radius):pi = 3.141592653589793return 4/3 * pi * (radius**3)r = [1, 2.5, 3.4, 5.6, 7, 9.0]for x in r:print("Volume of sphere with radius = ",x ,"is", sphere_volume(x))
When we run the code above, it gives an error for boolean and negative values. This error tells us that our test has failed, which means we are on the right track. So, we will remove the invalid values. Now, our test gives the correct output.
Let’s understand the code above:
In our function, we mainly encountered two major problems:
-
sphere_volume(radius)gave output on negative values. In such a situation, we call theassertRaisesmethod, which returns aValueErrorif the radius is negative. For testing purposes, we have given the radius as-2and-5. Involume.py, we define anifcondition to only calculate the volume if the radius is positive. If the radius is not positive, a value error will be raised. Now, our code is aligned with our first test case. -
sphere_volume(radius)gave output on boolean values. In such a situation, we call theassertRaisesmethod, which returnsTypeErrorif the radius is boolean or string (for testing purposes, supplied boolean and string values). Now we know that for boolean and string inputs, thesphere_volume(radius)function will raise an error. So, involume.py, we define anifcondition to only calculate the volume if the radius data type isfloatorint. If not, a type error will be raised. Our code is now also aligned with our second test case.
Free Resources