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.
raises()
methodThe 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.
with pytest.raises(exception, match)
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.import pytestdef test_zero_division():with pytest.raises(ZeroDivisionError):1 / 0test_zero_division()
Note: To avoid the
ZeroDivisionError
, change the divisor from0
to any integer.
pytest
.1
by 0
. This causes the ZeroDivisionError
to be thrown. We wrap the 1/0
code with the pytest.raises()
method. Here, the ZeroDivisionError
is the expected exception.Let’s look at another example to demonstrate the use of the raise()
function.
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.
pytest
.func
that takes a parameter called x
. The function throws an exception called ValueError
with a message, "x must be a value other than 5"
if the input argument is 5
.func()
with x
as 5
throws ValueError
with the expected message. To do this, we use the pytest.raises()
method. We use the match
parameter to specify the expected message or the string representation of the exception.