2

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)

Kannan Ekanath
  • 16,759
  • 22
  • 75
  • 101
  • 1
    May this help? http://stackoverflow.com/questions/8215653/using-a-context-manager-with-python-assertraises Should there be an assertRaisesRegex? – User Feb 19 '13 at 12:44

2 Answers2

3
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? :)

Community
  • 1
  • 1
floqqi
  • 1,137
  • 2
  • 10
  • 19
  • "The standard unittest module provides no such method." False, see the answer of Calm Storm. However this solution works in python<2.7. – Bakuriu Nov 11 '13 at 12:55
2

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

Kannan Ekanath
  • 16,759
  • 22
  • 75
  • 101