0
0
PytestHow-ToBeginner ยท 3 min read

How to Assert Exception in pytest: Simple Guide with Examples

In pytest, you can assert that an exception is raised using the pytest.raises() context manager. Wrap the code that should raise the exception inside this context, and pytest will check if the expected exception occurs.
๐Ÿ“

Syntax

The basic syntax to assert an exception in pytest uses the pytest.raises() context manager. You pass the expected exception type to it, then run the code inside the with block.

  • pytest.raises(ExceptionType): Specifies the exception you expect.
  • with block: Contains the code that should raise the exception.
python
import pytest

def test_example():
    with pytest.raises(ValueError):
        int('invalid')
๐Ÿ’ป

Example

This example shows how to test that converting a non-numeric string to an integer raises a ValueError. The test passes if the exception is raised, otherwise it fails.

python
import pytest

def test_value_error():
    with pytest.raises(ValueError):
        int('abc')

# Run this test with: pytest -q --tb=short
Output
============================= test session starts ============================== collected 1 item test_value_error.py . [100%] ============================== 1 passed in 0.03s ===============================
โš ๏ธ

Common Pitfalls

Common mistakes when asserting exceptions in pytest include:

  • Not using with block, which means the exception won't be caught by pytest.
  • Expecting the wrong exception type, causing the test to fail unexpectedly.
  • Placing code outside the with pytest.raises() block that raises the exception.

Always ensure the code that should raise the exception is inside the with block.

python
import pytest

def test_wrong_usage():
    # Wrong: exception raised outside the context manager
    int('abc')  # This will cause the test to error, not fail gracefully

    with pytest.raises(ValueError):
        pass  # No exception raised here

# Correct usage:

def test_correct_usage():
    with pytest.raises(ValueError):
        int('abc')
๐Ÿ“Š

Quick Reference

Use this quick reference to remember how to assert exceptions in pytest:

ActionCode Example
Assert exception raisedwith pytest.raises(ValueError):\n code_that_raises()
Check exception messagewith pytest.raises(ValueError) as exc_info:\n code_that_raises()\nassert 'invalid' in str(exc_info.value)
Fail if no exceptionpytest.raises() fails test if exception not raised
โœ…

Key Takeaways

Use pytest.raises() as a context manager to assert exceptions.
Place the code that should raise the exception inside the with block.
Specify the exact exception type you expect to catch.
You can capture the exception info to check the message if needed.
Avoid raising exceptions outside the pytest.raises() block.