From ac5787d0e42ba6aa1c26d2e040c9f0a1ca8cb575 Mon Sep 17 00:00:00 2001 From: Joshua Harlow Date: Mon, 9 Jan 2017 11:23:40 -0800 Subject: [PATCH] Prefer raising the python2.x type error for b64 decode errors The current change made in de68f08d37 breaks cinder and other projects that were expecting a TypeError, so for now and to keep those projects operating translate the py3.x exception from binascii into a type error to prefer consistency with existing code. Change-Id: I4575ea3dad51be9bb2278eb0bfa31cef54c300d5 --- oslo_serialization/base64.py | 10 +++++++--- oslo_serialization/tests/test_base64.py | 4 +--- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/oslo_serialization/base64.py b/oslo_serialization/base64.py index 7ff6e57..401e036 100644 --- a/oslo_serialization/base64.py +++ b/oslo_serialization/base64.py @@ -22,6 +22,7 @@ Utilities to encode and decode Base64. from __future__ import absolute_import import base64 +import binascii import six @@ -64,13 +65,16 @@ def decode_as_bytes(encoded): :returns: decoded bytes string (bytes) Use decode_as_text() to get the decoded string as text. + + A TypeError is raised if the input is invalid (or incorrectly padded). """ if isinstance(encoded, bytes): encoded = encoded.decode('ascii') - if six.PY2: - return base64.decodestring(encoded) - else: + try: return base64.b64decode(encoded) + except binascii.Error as e: + # Transform this exception for consistency. + raise TypeError(str(e)) def decode_as_text(encoded, encoding='utf-8'): diff --git a/oslo_serialization/tests/test_base64.py b/oslo_serialization/tests/test_base64.py index 8b29d70..645f2ee 100644 --- a/oslo_serialization/tests/test_base64.py +++ b/oslo_serialization/tests/test_base64.py @@ -13,8 +13,6 @@ # License for the specific language governing permissions and limitations # under the License. -import binascii - from oslo_serialization import base64 from oslotest import base as test_base @@ -48,7 +46,7 @@ class Base64Tests(test_base.BaseTestCase): base64.decode_as_bytes(u'dGV4dA==')) def test_decode_as_bytes__error(self): - self.assertRaises(binascii.Error, + self.assertRaises(TypeError, base64.decode_as_bytes, 'hello world')