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

前端 未结 5 1345
长情又很酷
长情又很酷 2020-12-07 18:27

In order to make sure that the error messages from my module are informative, I would like to see all the error messages caught by assertRaises(). Today I do it for each ass

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-07 19:00

    mkelley33 gives nice answer, but this approach can be detected as issue by some code analysis tools like Codacy. The problem is that it doesn't know that assertRaises can be used as context manager and it reports that not all arguments are passed to assertRaises method.

    So, I'd like to improve Robert's Rossney answer:

    class TestCaseMixin(object):
    
        def assertRaisesWithMessage(self, exception_type, message, func, *args, **kwargs):
            try:
                func(*args, **kwargs)
            except exception_type as e:
                self.assertEqual(e.args[0], message)
            else:
                self.fail('"{0}" was expected to throw "{1}" exception'
                          .format(func.__name__, exception_type.__name__))
    

    Key differences are:

    1. We test type of exception.
    2. We can run this code both on Python 2 and Python 3 (we call e.args[0] because errors in Py3 don't have message attribute).

提交回复
热议问题