How to check if an exception gets raised in pytest
What is pytest?
In Python, pytest is a testing framework that makes generating short and comprehensible test cases simple. It can also handle complicated functional testing for programs and modules.
The raises() method
The pytest framework’s raises() method asserts that a block of code or a function call raises the specified exception. If it does not, the method raises a failure exception, indicating that the intended exception was not raised.
Syntax
with pytest.raises(exception, match)
Parameters
exception: This is the exception to be thrown.match: This parameter can be a literal string or a regular expression that matches the string representation of the exception.
Example 1
import pytestdef test_zero_division():with pytest.raises(ZeroDivisionError):1 / 0test_zero_division()
Note: To avoid the
ZeroDivisionError, change the divisor from0to any integer.
Explanation
- Line 1: We import
pytest. - Lines 4-5: We divide
1by0. This causes theZeroDivisionErrorto be thrown. We wrap the1/0code with thepytest.raises()method. Here, theZeroDivisionErroris the expected exception.
Let’s look at another example to demonstrate the use of the raise() function.
Example 2
import pytestdef func(x):if x == 5:raise ValueError("x must be a value other than 5")return xdef test_func():with pytest.raises(ValueError, match="x must be a value other than 5"):func(5)# func(5) # Raises an exemptiontest_func()
Note: To encounter the error at an exemption, we uncomment line 12 and comment line 14.
Explanation
- Line 1: We import
pytest. - Lines 3–6: We define a function called
functhat takes a parameter calledx. The function throws an exception calledValueErrorwith a message,"x must be a value other than 5"if the input argument is5. - Lines 9–10: We check if invoking
func()withxas5throwsValueErrorwith the expected message. To do this, we use thepytest.raises()method. We use thematchparameter to specify the expected message or the string representation of the exception.