Kannan Ekanath
Kannan Ekanath

Reputation: 17621

Python unit test how to assert message format

I have my Python unit test code that looks like the following

self.assertRaises(exc.UserError, module.function, args)

This basically asserts that a UserError was raised. I however cannot find how to check if the message in the exception matches my regular expression.

How can I do this? (I would prefer not to write any extra code and just leverage python unittest module features)

Upvotes: 2

Views: 3055

Answers (2)

Kannan Ekanath
Kannan Ekanath

Reputation: 17621

Python seems to have the same method in 2.7.3, the method is named "assertRaisesRegexp" so we do not (and should not) write our own wrappers :)

http://docs.python.org/2/library/unittest.html#unittest.TestCase.assertRaisesRegexp

Upvotes: 2

floqqi
floqqi

Reputation: 1207

class ExtendedTestCase(unittest.TestCase):

    def assertRaisesWithMessage(self, msg, func, *args, **kwargs):
        try:
            func(*args, **kwargs)
            self.assertFail()
        except Exception as inst:
            self.assertEqual(inst.message, msg)

The standard unittest module provides no such method. If you use this more often you can use the code above and inherit from the ExtendedTestCase.

PS: Stolen from How to show the error messages caught by assertRaises() in unittest in Python2.7? :)

Upvotes: 3

Related Questions