Skip to content

Commit

Permalink
fix: manage JSONDecodeError exception (#1574)
Browse files Browse the repository at this point in the history
Closes #1570.
  • Loading branch information
gparonitti committed Oct 21, 2021
1 parent 0b400f9 commit 7d63027
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
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)

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

0 comments on commit 7d63027

Please sign in to comment.