0
0
PyTesttesting~5 mins

Matching exception messages in PyTest

Choose your learning style9 modes available
Introduction

We check exception messages to make sure the error is exactly what we expect. This helps catch the right problems.

When testing if a function raises an error with a specific message.
When you want to confirm that your code handles bad input correctly.
When debugging to ensure the error message is clear and helpful.
When writing tests that must verify error details for user feedback.
Syntax
PyTest
with pytest.raises(ExpectedException) as exc_info:
    function_call()

assert "expected message" in str(exc_info.value)

Use pytest.raises() to catch exceptions in tests.

Check the exception message by converting exc_info.value to string.

Examples
This test checks that dividing by zero raises the correct error message.
PyTest
import pytest

def test_zero_division():
    with pytest.raises(ZeroDivisionError) as exc_info:
        1 / 0
    assert "division by zero" in str(exc_info.value)
This test confirms that converting a bad string to int raises a ValueError with the expected message.
PyTest
import pytest

def test_value_error():
    with pytest.raises(ValueError) as exc_info:
        int('abc')
    assert "invalid literal" in str(exc_info.value)
Sample Program

This test checks that the divide function raises a ValueError with the message "Cannot divide by zero" when dividing by zero.

PyTest
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) as exc_info:
        divide(10, 0)
    assert "Cannot divide by zero" in str(exc_info.value)

# Run the test
if __name__ == "__main__":
    pytest.main([__file__])
OutputSuccess
Important Notes

Always check the exact message to avoid false positives in tests.

You can use in to check if the message contains a part of the text.

Use clear and simple messages in your code to make testing easier.

Summary

Use pytest.raises() to catch exceptions in tests.

Check exception messages by asserting text in str(exc_info.value).

This ensures your code raises the right errors with clear messages.