How to properly assert that an exception gets raised in pytest?
pytest.raises
is the go-to tool for asserting exceptions in pytests. Encapsulate the relevant code block to assert the specific exception.
Example:
This test clears only if ZeroDivisionError
is thrown when dividing by zero.
Examining the exception details
Extracting the exception details is critical for in-depth assertions or analysis. Utilize the as
keyword in the context manager to achieve this:
Example:
Here, exc_info
is holding that golden information about the exception. You can access the actual exception via exc_info.value
. Useful for checking the error message or other exception attributes.
Testing exception absence
At times, you may want to ensure a block of code does NOT trigger any exception. By default, pytest does this implicitly if your test passes. However, if you want to make it explicit:
Example:
While it's not a good practice compared to simply letting the test pass without exceptions, it clearly documents the Test-Innocence.
Focusing on specific exception messages
In some cases, exception messages need to be as specific as an Oxford English professor. For these scenarios, pytest.raises
combines with the match
parameter for asserting message correctness:
Example:
The test will clear only if the error message carries '42'. Highly precise way to assert the exact exception type and its content.
Tackling foreign exceptions
When your code interacts with foreign systems or libraries, ensure to handle exceptions pointing to issues beyond your control.
Asserting an exception raised by an external library informs about a potential alien bug, rather than a flaw in your own awesome code.
Example:
Clean and effective way to separate errors within your control from those beyond!
Was this article helpful?