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
This commit is contained in:
parent
6704d5f8ba
commit
ede68f08d3
|
@ -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'):
|
||||
|
|
|
@ -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=='))
|
||||
|
|
Loading…
Reference in New Issue