Verifying Exception Handling and Error States
In this lesson, you will learn how to use pytest context managers to formally verify that your functions correctly raise specific exceptions when they encounter invalid inputs or error states.
Why Test for Exceptions?
In robust software, "success" isn't the only outcome we care about. Sometimes, the correct behavior of a function is to fail—for example, if you provide a negative value to a function designed only for positive numbers. If your code doesn't raise an error in those cases, it might continue running with corrupted data, leading to harder-to-find bugs later on. To verify your error logic, we use the pytest.raises context manager.
Using pytest.raises
When you want to assert that a block of code throws an exception, you wrap that code inside a with pytest.raises(...) block. If the code inside raises the specified exception, the test passes. If the code finishes without an error, or raises a different type of error, the test fails.
Consider a simple function that calculates the square root:
import pytest
def calculate_square_root(number):
if number < 0:
raise ValueError("Cannot calculate square root of a negative number")
return number ** 0.5
def test_calculate_square_root_raises_error():
# We expect a ValueError because -1 is invalid
with pytest.raises(ValueError):
calculate_square_root(-1)
Checking Exception Details
Often, you want to ensure the exception raised contains the specific error message you intended. You can capture the exception object and inspect it:
def test_calculate_square_root_message():
with pytest.raises(ValueError) as excinfo:
calculate_square_root(-1)
# Assert the error message matches
assert "Cannot calculate square root" in str(excinfo.value)
By using pytest.raises, you ensure that your code doesn't just "fail" accidentally, but explicitly handles edge cases according to your design specifications. This transforms your error handling from a passive feature into a testable contract of your application's reliability.
Key Takeaway: Use the pytest.raises context manager to confirm your code enforces its own boundaries by explicitly raising exceptions when provided with invalid data or encountered with fatal system states.