Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: manage JSONDecodeError exception #1574

Merged
merged 8 commits into from Oct 21, 2021
10 changes: 7 additions & 3 deletions googleapiclient/model.py
Expand Up @@ -277,9 +277,13 @@ def deserialize(self, content):
content = content.decode("utf-8")
except AttributeError:
pass
body = json.loads(content)
if self._data_wrapper and isinstance(body, dict) and "data" in body:
body = body["data"]
try:
body = json.loads(content)
except json.decoder.JSONDecodeError:
body = content
else:
if self._data_wrapper and "data" in body:
body = body["data"]
return body

@property
Expand Down
21 changes: 20 additions & 1 deletion tests/test_json_model.py
Expand Up @@ -22,6 +22,7 @@

__author__ = "jcgregorio@google.com (Joe Gregorio)"

import io
import httplib2
import json
import pkg_resources
Expand All @@ -31,11 +32,11 @@

import googleapiclient.model


from googleapiclient.errors import HttpError
from googleapiclient.model import JsonModel

_LIBRARY_VERSION = pkg_resources.get_distribution("google-api-python-client").version
CSV_TEXT_MOCK = 'column1,column2,column3\nstring1,1.2,string2'


class Model(unittest.TestCase):
Expand Down Expand Up @@ -290,6 +291,24 @@ def test_no_data_wrapper_deserialize(self):
content = model.response(resp, content)
self.assertEqual(content, {"data": "is good"})

def test_no_data_wrapper_deserialize_text_format(self):
model = JsonModel(data_wrapper=False)
resp = httplib2.Response({"status": "200"})
resp.reason = "OK"
content = CSV_TEXT_MOCK
content = model.response(resp, content)
self.assertEqual(content, CSV_TEXT_MOCK)

gparonitti marked this conversation as resolved.
Show resolved Hide resolved
def test_no_data_wrapper_deserialize_raise_type_error(self):
buffer = io.StringIO()
buffer.write('String buffer')
model = JsonModel(data_wrapper=False)
resp = httplib2.Response({"status": "500"})
resp.reason = "The JSON object must be str, bytes or bytearray, not StringIO"
content = buffer
with self.assertRaises(TypeError):
model.response(resp, content)

def test_data_wrapper_deserialize(self):
model = JsonModel(data_wrapper=True)
resp = httplib2.Response({"status": "200"})
Expand Down