How to Assert Raises in pytest: Syntax and Examples
In
pytest, use the pytest.raises() context manager to assert that a specific exception is raised during a block of code. Wrap the code that should raise the exception inside the with pytest.raises(ExceptionType): block to verify the error occurs.Syntax
The pytest.raises() function is used as a context manager to check if a block of code raises a specific exception.
ExceptionType: The type of exception you expect (e.g.,ValueError).- The code inside the
withblock is the code expected to raise the exception. - If the exception is raised, the test passes; if not, the test fails.
python
import pytest def function_that_raises(): raise ExceptionType("Error message") with pytest.raises(ExceptionType): # code that should raise ExceptionType function_that_raises()
Example
This example shows how to test that a function raises a ValueError when given invalid input.
python
import pytest def divide(a, b): if b == 0: raise ValueError("Cannot divide by zero") return a / b def test_divide_by_zero(): with pytest.raises(ValueError): divide(10, 0)
Output
============================= test session starts ==============================
collected 1 item
test_example.py . [100%]
============================== 1 passed in 0.03s ===============================
Common Pitfalls
Common mistakes when using pytest.raises() include:
- Not using it as a context manager with
with, which will not catch the exception properly. - Expecting the wrong exception type, causing tests to fail unexpectedly.
- Placing code that does not raise inside the
withblock, leading to false positives.
python
import pytest def divide(a, b): if b == 0: raise ValueError("Cannot divide by zero") return a / b def test_wrong_usage(): # Wrong: not using 'with' - this will not catch the exception try: divide(10, 0) except ValueError: pass # This is manual and not recommended def test_correct_usage(): with pytest.raises(ValueError): divide(10, 0)
Quick Reference
Remember these tips when asserting exceptions in pytest:
- Always use
with pytest.raises(ExceptionType):as a context manager. - Check for the exact exception type you expect.
- You can access the exception info with
as exc_infoif needed.
python
import pytest def divide(a, b): if b == 0: raise ValueError("Cannot divide by zero") return a / b def test_exception_message(): with pytest.raises(ValueError) as exc_info: divide(10, 0) assert str(exc_info.value) == "Cannot divide by zero"
Output
============================= test session starts ==============================
collected 1 item
test_example.py . [100%]
============================== 1 passed in 0.03s ===============================
Key Takeaways
Use pytest.raises() as a context manager to assert exceptions.
Wrap only the code that should raise the exception inside the with block.
Specify the exact exception type to catch for accurate tests.
Access exception details with 'as exc_info' for further assertions.
Avoid manual try-except blocks; pytest.raises() is cleaner and more reliable.