Assert Exception Message in pytest

pytest(https://pytest.orig) makes it easy to assert that an exception is raised and that it's the one you expect.

Prerequisites

Once we setup pytest, we get a nice assertion utility to verify that exceptions are raised.

For instance, in module my_module.py with code:

def my_fn():
    raise Exception('Kaboom')

We can write a test that expects the exception to be raised.

import pytest

import my_module

def test_exception_raise():
    with pytest.raises(Exception) as exc_info:
        my_module.my_fn()

    assert str(exc_info.value) == 'Kaboom'

A with block is used. Note the as binding to exc_info. This is of type _pytest._code.code.ExceptionInfo. It has a member called value, which is the actual Exception. If we were raising a different type of Exception, we would define that in the raises parameter (eg, pytest.raises(HttpException)). We cast the exception to a string to extract its message. We make the assertion on that message.