From ede68f08d375a35d438a12b62b5bbbf7229cf15e Mon Sep 17 00:00:00 2001 From: Stephen Finucane Date: Wed, 14 Dec 2016 14:51:51 +0000 Subject: [PATCH] Don't raise TypeError for invalid b64 In Python 2, the 'b64decode' function calls the 'binascii.a2b_base64' function but catches any 'binascii.Error' exceptions raised and raises a TypeError instead [1]. In Python 3, a 'binascii.Error' error is raised instead [2]. Rather than forcing users to handle two types of exception, we can allow them to catch only the 'bisascii.Error'. Python 2 provides a function that does just this - 'decodestring' - which we can use. Make it so. [1] https://github.com/python/cpython/blob/2.7/Lib/base64.py#L78 [2] https://github.com/python/cpython/blob/3.5/Lib/base64.py#L87 [3] https://github.com/python/cpython/blob/2.7/Lib/base64.py#L326 Change-Id: I72c6de71b174181292427128d20e03756f85fb97 --- oslo_serialization/base64.py | 5 ++++- oslo_serialization/tests/test_base64.py | 7 +++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/oslo_serialization/base64.py b/oslo_serialization/base64.py index 34c8e4e..7ff6e57 100644 --- a/oslo_serialization/base64.py +++ b/oslo_serialization/base64.py @@ -67,7 +67,10 @@ def decode_as_bytes(encoded): """ if isinstance(encoded, bytes): encoded = encoded.decode('ascii') - return base64.b64decode(encoded) + if six.PY2: + return base64.decodestring(encoded) + else: + return base64.b64decode(encoded) 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 292c214..8b29d70 100644 --- a/oslo_serialization/tests/test_base64.py +++ b/oslo_serialization/tests/test_base64.py @@ -13,6 +13,8 @@ # 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 @@ -45,6 +47,11 @@ class Base64Tests(test_base.BaseTestCase): self.assertEqual(b'text', base64.decode_as_bytes(u'dGV4dA==')) + def test_decode_as_bytes__error(self): + self.assertRaises(binascii.Error, + base64.decode_as_bytes, + 'hello world') + def test_decode_as_text(self): self.assertEqual(u'text', base64.decode_as_text(b'dGV4dA=='))