Pytest can be used to test whether a function raises an exception. For instance, consider a division function that raises a ZeroDivisionError if there is an attempt to divide by zero:
Attempting to execute this function with zero as the divisor results in a ZeroDivisionError:
To verify that this exception is raised as expected, use the pytest.raises in a test case:
When this test is run, it confirms that the divide() function behaves as expected by successfully raising a ZeroDivisionError when dividing by zero, indicated by a passing test result:
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.