Search code examples
pythonpython-3.xunit-testingpython-unittestassert

Getting Python assertRaises to check for message


I want to use assertRaises and check for the error message too. According to the docs I have to use it as a context manager.

with self.assertRaises(ValueError, msg='Invalid id format.'):
    api.get_by_id('a')

This results in the following error:

TypeError: assertRaises() missing 1 required positional argument: 'callableObj'

I get the exact same error if I use it without msg.

Using it like assertRaises(exception, callable, *args, **kwds) works fine, but that obviously can't process the error message.

I don't understand why Python can't recognise the use case I'm going for.

Python 3.7.10, MacOS Monterey 12.2


Solution

  • Two things - first of all, it's hard to tell what actually happens but there must be some other error in your code because with self.assertRaises(ValueError, msg='Invalid id format.'): should work perfectly fine (tested on Python 3.10)

    2nd thing - msg argument does not do what you want it to do - self.assertRaises as a context manager with msg argument not working as expected

    Link provided also explains how to check for error message with assertRaisesRegex