0
0
PyTesttesting~5 mins

Checking exception attributes in PyTest

Choose your learning style9 modes available
Introduction

We check exception attributes to make sure errors happen as expected and carry the right information.

When you want to confirm a function raises an error with a specific message.
When testing that an error has a certain code or property.
When verifying that your program handles wrong inputs correctly by raising exceptions.
When you want to catch and inspect details of an error during automated tests.
Syntax
PyTest
with pytest.raises(ExpectedException) as exc_info:
    # code that raises the exception

# access exception attributes
assert exc_info.value.attribute == expected_value

Use exc_info.value to get the actual exception object.

You can check any attribute of the exception like message, code, or custom properties.

Examples
This checks that converting 'abc' to int raises a ValueError with a message containing 'invalid literal'.
PyTest
with pytest.raises(ValueError) as exc_info:
    int('abc')

assert 'invalid literal' in str(exc_info.value)
This tests a custom exception and checks its code attribute.
PyTest
class MyError(Exception):
    def __init__(self, code):
        self.code = code

with pytest.raises(MyError) as exc_info:
    raise MyError(404)

assert exc_info.value.code == 404
Sample Program

This test checks that func() raises CustomError with message 'Not found' and code 404.

PyTest
import pytest

class CustomError(Exception):
    def __init__(self, message, code):
        super().__init__(message)
        self.code = code

def func():
    raise CustomError('Not found', 404)

def test_func_raises():
    with pytest.raises(CustomError) as exc_info:
        func()
    assert str(exc_info.value) == 'Not found'
    assert exc_info.value.code == 404

if __name__ == '__main__':
    pytest.main([__file__])
OutputSuccess
Important Notes

Always check the exact attribute you want to verify on the exception object.

Using exc_info helps you avoid catching exceptions outside the test scope.

Summary

Use pytest.raises with as exc_info to capture exceptions.

Check exception attributes via exc_info.value.

This helps confirm your code raises correct errors with expected details.