0
0
PytestHow-ToBeginner ยท 3 min read

How to Use pytest.raises for Exception Testing

Use pytest.raises as a context manager to check if a block of code raises a specific exception. It helps verify that your code correctly handles error cases by expecting exceptions during tests.
๐Ÿ“

Syntax

The basic syntax of pytest.raises is using it as a context manager with the with statement. You pass the expected exception type to pytest.raises(), then write the code that should raise that exception inside the with block.

Optionally, you can capture the exception info using as exc_info to inspect the exception details.

python
with pytest.raises(ExpectedException) as exc_info:
    # code that should raise ExpectedException
    function_that_raises()
๐Ÿ’ป

Example

This example shows how to test that dividing by zero raises a ZeroDivisionError. The test passes if the exception is raised, otherwise it fails.

python
import pytest

def divide(a, b):
    return a / b

def test_divide_by_zero():
    with pytest.raises(ZeroDivisionError) as exc_info:
        divide(10, 0)
    assert "division by zero" in str(exc_info.value)
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, which will not catch exceptions properly.
  • Placing code that should raise the exception outside the with block.
  • Expecting the wrong exception type, causing tests to fail unexpectedly.
  • Not asserting on the exception message when needed to verify the error details.
python
import pytest

def test_wrong_usage():
    # Wrong: exception raised outside the with block
    with pytest.raises(ValueError):
        pass
    int('not a number')  # This raises ValueError but is outside the block

def test_correct_usage():
    with pytest.raises(ValueError):
        int('not a number')
Output
============================= test session starts ============================== collected 2 items test_example.py F. [100%] =================================== FAILURES =================================== ____________________________ test_wrong_usage ________________________________ def test_wrong_usage(): # Wrong: exception raised outside the with block with pytest.raises(ValueError): pass > int('not a number') # This raises ValueError but is outside the block E ValueError: invalid literal for int() with base 10: 'not a number'
๐Ÿ“Š

Quick Reference

Remember these tips when using pytest.raises:

  • Use it as a with context manager.
  • Pass the exact exception type you expect.
  • Put only the code that should raise the exception inside the with block.
  • Optionally capture the exception info to check the message.
โœ…

Key Takeaways

Use pytest.raises as a context manager to test for expected exceptions.
Place the code that should raise the exception inside the with block.
Pass the correct exception type to pytest.raises to avoid false test failures.
Capture exception info with as exc_info to assert on exception messages.
Avoid placing exception-raising code outside the pytest.raises context.