]> review.fuel-infra Code Review - openstack-build/cinder-build.git/commitdiff
Fix exception message formatting
authorEduardo Costa <eduardo.costa@tvglobo.com.br>
Sun, 2 Nov 2014 15:06:12 +0000 (16:06 +0100)
committerEduardo Costa <eduardo.costa@tvglobo.com.br>
Mon, 24 Nov 2014 14:39:00 +0000 (12:39 -0200)
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

cinder/exception.py
cinder/tests/test_exception.py

index 919f0e2f201e82cab50863d1637a9ed3da68cd23..9044193a1936da1fefd5081653b6bf598af966ff 100644 (file)
@@ -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)
 
index 88d442ec48bf3f68f065e4923a89c50c5581b25d..d5712459fec35f21fbb42b54fea262002c5c18a2 100644 (file)
@@ -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')