diff --git a/src/mog_commons/__init__.py b/src/mog_commons/__init__.py index c3bb296..1c98a23 100644 --- a/src/mog_commons/__init__.py +++ b/src/mog_commons/__init__.py @@ -1 +1 @@ -__version__ = '0.1.8' +__version__ = '0.1.9' diff --git a/src/mog_commons/unittest.py b/src/mog_commons/unittest.py index 3cd0ac8..019228e 100644 --- a/src/mog_commons/unittest.py +++ b/src/mog_commons/unittest.py @@ -59,6 +59,26 @@ def assertRaisesRegexp(self, expected_exception, expected_regexp, callable_obj=N else: self.assertRegex(to_str(cm.exception, encoding), expected_regexp) + def assertRaisesMessage(self, expected_exception, expected_message, callable_obj=None, *args, **kwargs): + """ + Assert the expected exception is raised and its message is equal to expected. + + :param expected_exception: class: + :param expected_message: string: + :param callable_obj: function: + :param args: args + :param kwargs: kwargs + """ + encoding = 'utf-8' + with self.assertRaises(expected_exception) as cm: + callable_obj(*args, **kwargs) + try: + msg = to_str(cm.exception, encoding) + except UnicodeEncodeError: + # avoid to use cm.exception.message + msg = cm.exception.args[0] + self.assertEqual(msg, expected_message) + @contextmanager def withOutput(self): """ diff --git a/tests/mog_commons/test_unittest.py b/tests/mog_commons/test_unittest.py index d1ba439..9f6d180 100644 --- a/tests/mog_commons/test_unittest.py +++ b/tests/mog_commons/test_unittest.py @@ -3,6 +3,7 @@ import sys import os +import six from mog_commons import unittest @@ -46,6 +47,25 @@ def g(text): g('かきくけこ\n') self.assertRaisesRegexp(AssertionError, 'かきくけこ', g, 'あいうえお\n') + def test_assert_raises_message(self): + class MyException(Exception): + pass + + def f(msg): + raise MyException(msg) + + self.assertRaisesMessage(MyException, 'あいうえお', f, 'あいうえお') + self.assertRaisesMessage(AssertionError, 'MyException not raised', + self.assertRaisesMessage, MyException, 'あいうえお', lambda: None) + + if six.PY2: + expected = ("u'\\u3042\\u3044\\u3046\\u3048' != u'\\u3042\\u3044\\u3046\\u3048\\u304a'\n" + + "- \u3042\u3044\u3046\u3048\n+ \u3042\u3044\u3046\u3048\u304a\n? +\n") + else: + expected = "'あいうえ' != 'あいうえお'\n- あいうえ\n+ あいうえお\n? +\n" + self.assertRaisesMessage(AssertionError, expected, + self.assertRaisesMessage, MyException, 'あいうえお', f, 'あいうえ') + def test_assert_system_exit_fail(self): self.assertRaisesRegexp(AssertionError, 'SystemExit not raised', self.assertSystemExit, 0, lambda: 0) self.assertRaisesRegexp(AssertionError, '1 != 0', self.assertSystemExit, 0, lambda: sys.exit(1))