We test custom exceptions to make sure our program handles errors the way we expect. This helps catch problems early and keeps the program stable.
0
0
Testing custom exceptions in PyTest
Introduction
When you want to check if your code raises a specific error for bad input.
When you create your own error types to explain problems clearly.
When you want to confirm that error messages are correct and helpful.
When you want to prevent your program from crashing unexpectedly.
When you want to document how your code behaves in error situations.
Syntax
PyTest
import pytest with pytest.raises(ExpectedException): function_that_raises()
Use pytest.raises() as a context manager to check for exceptions.
Replace ExpectedException with your custom exception class.
Examples
This example tests that
bad_func() raises the custom MyError.PyTest
import pytest class MyError(Exception): pass def bad_func(): raise MyError("Oops") with pytest.raises(MyError): bad_func()
This example also checks the error message text.
PyTest
import pytest class CustomError(Exception): pass def check_value(x): if x < 0: raise CustomError("Negative value") with pytest.raises(CustomError) as exc_info: check_value(-1) assert str(exc_info.value) == "Negative value"
Sample Program
This test checks that set_age raises InvalidAgeError for invalid ages and returns the age for valid input.
PyTest
import pytest class InvalidAgeError(Exception): pass def set_age(age): if age < 0 or age > 120: raise InvalidAgeError("Age must be between 0 and 120") return age def test_set_age(): with pytest.raises(InvalidAgeError) as e: set_age(-5) assert str(e.value) == "Age must be between 0 and 120" with pytest.raises(InvalidAgeError): set_age(150) assert set_age(30) == 30
OutputSuccess
Important Notes
Always test both that the exception is raised and that the message is correct.
Use clear and descriptive names for your custom exceptions.
pytest shows a clear report when tests pass or fail, making debugging easier.
Summary
Testing custom exceptions ensures your code handles errors properly.
Use pytest.raises() to check for exceptions in tests.
Check both the type of exception and its message for full coverage.