Rosey
Rosey

Reputation: 821

Using python unittest, how can I assert an error reported gave a certain message?

Let's say I have a method that looks like this:

def my_function(arg1, arg2):
    if arg1:
        raise RuntimeError('error message A')
    else:
        raise RuntimeError('error message B')

Using python's builtin unittets library, is there any way to tell WHICH RuntimeError was raised? I have been doing:

import unittest
from myfile import my_function


class MyTestCase(unittest.TestCase):
    def test_my_function(self):
        self.assertRaises(RuntimeError, my_function, arg1, arg2)

But this only asserts that a RuntimeError was encountered. I want to be able to tell WHICH RuntimeError was encountered. Checking the actual error message is the only way I think this could be accomplished but I can't seem to find any assert method that also tries to assert the error message

Upvotes: 4

Views: 5104

Answers (2)

blhsing
blhsing

Reputation: 106543

You can use assertRaises as a context manager and assert that string value of the exception object is as expected:

def my_function():
    raise RuntimeError('hello')

class MyTestCase(unittest.TestCase):
    def test_my_function(self):
        with self.assertRaises(RuntimeError) as cm:
            my_function()
        self.assertEqual(str(cm.exception), 'hello')

Demo: http://ideone.com/7J0HOR

Upvotes: 3

wim
wim

Reputation: 362657

unittest users:

In this case, it is better to use assertRaisesRegex.

Like assertRaises() but also tests that regex matches on the string representation of the raised exception. regex may be a regular expression object or a string containing a regular expression suitable for use by re.search().

So, you could use:

self.assertRaisesRegex(RuntimeError, "^error message A$", my_function, arg1, arg2)

pytest users:

Install my plugin pytest-raisin. Then you can assert using matching exception instances:

with pytest.raises(RuntimeError("error message A")):
    my_function(arg1, arg2)

Upvotes: 3

Related Questions