From: Eduardo Costa Date: Sun, 2 Nov 2014 15:06:12 +0000 (+0100) Subject: Fix exception message formatting X-Git-Url: https://review.fuel-infra.org/gitweb?a=commitdiff_plain;h=9cd907a8377a4c112ce46755ab68b384ceac75c7;p=openstack-build%2Fcinder-build.git Fix exception message formatting If the exception class made a reference to the "message" field in its format string, it would be overriden with the value of the "message" argument itself. It is now possible to use the "message" field and preserve the desired message formatting. Test cases provided. Change-Id: I5705203466535fa242d13e43571012e5bf72712a Closes-Bug: #1288066 --- diff --git a/cinder/exception.py b/cinder/exception.py index 919f0e2f2..9044193a1 100644 --- a/cinder/exception.py +++ b/cinder/exception.py @@ -71,6 +71,7 @@ class CinderException(Exception): def __init__(self, message=None, **kwargs): self.kwargs = kwargs + self.kwargs['message'] = message if 'code' not in self.kwargs: try: @@ -82,7 +83,7 @@ class CinderException(Exception): if isinstance(v, Exception): self.kwargs[k] = six.text_type(v) - if not message: + if self._should_format(): try: message = self.message % kwargs @@ -106,6 +107,9 @@ class CinderException(Exception): self.msg = message super(CinderException, self).__init__(message) + def _should_format(self): + return self.kwargs['message'] is None or '%(message)' in self.message + def __unicode__(self): return unicode(self.msg) diff --git a/cinder/tests/test_exception.py b/cinder/tests/test_exception.py index 88d442ec4..d5712459f 100644 --- a/cinder/tests/test_exception.py +++ b/cinder/tests/test_exception.py @@ -101,3 +101,26 @@ class CinderExceptionTestCase(test.TestCase): exc1 = Exception(msg) exc2 = exception.CinderException(kwarg1=exc1) self.assertEqual(msg, exc2.kwargs['kwarg1']) + + def test_message_in_format_string(self): + class FakeCinderException(exception.CinderException): + message = 'FakeCinderException: %(message)s' + + exc = FakeCinderException(message='message') + self.assertEqual(unicode(exc), 'FakeCinderException: message') + + def test_message_and_kwarg_in_format_string(self): + class FakeCinderException(exception.CinderException): + message = 'Error %(code)d: %(message)s' + + exc = FakeCinderException(message='message', code=404) + self.assertEqual(unicode(exc), 'Error 404: message') + + def test_message_is_exception_in_format_string(self): + class FakeCinderException(exception.CinderException): + message = 'Exception: %(message)s' + + msg = 'test message' + exc1 = Exception(msg) + exc2 = FakeCinderException(message=exc1) + self.assertEqual(unicode(exc2), 'Exception: test message')