How to check if an exception gets raised in pytest

Share

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 pytest
def test_zero_division():
with pytest.raises(ZeroDivisionError):
1 / 0
test_zero_division()

Note: To avoid the ZeroDivisionError, change the divisor from 0 to any integer.

Explanation

  • Line 1: We import pytest.
  • Lines 4-5: We divide 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.

Example 2

import pytest
def func(x):
if x == 5:
raise ValueError("x must be a value other than 5")
return x
def test_func():
with pytest.raises(ValueError, match="x must be a value other than 5"):
func(5)
# func(5) # Raises an exemption
test_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 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.
  • Lines 9–10: We check if invoking 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.