Skip to content

Commit 7d63027

Browse files
authored
fix: manage JSONDecodeError exception (#1574)
Closes #1570.
1 parent 0b400f9 commit 7d63027

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

googleapiclient/model.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -277,9 +277,13 @@ def deserialize(self, content):
277277
content = content.decode("utf-8")
278278
except AttributeError:
279279
pass
280-
body = json.loads(content)
281-
if self._data_wrapper and isinstance(body, dict) and "data" in body:
282-
body = body["data"]
280+
try:
281+
body = json.loads(content)
282+
except json.decoder.JSONDecodeError:
283+
body = content
284+
else:
285+
if self._data_wrapper and "data" in body:
286+
body = body["data"]
283287
return body
284288

285289
@property

tests/test_json_model.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222

2323
__author__ = "[email protected] (Joe Gregorio)"
2424

25+
import io
2526
import httplib2
2627
import json
2728
import pkg_resources
@@ -31,11 +32,11 @@
3132

3233
import googleapiclient.model
3334

34-
3535
from googleapiclient.errors import HttpError
3636
from googleapiclient.model import JsonModel
3737

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

4041

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

294+
def test_no_data_wrapper_deserialize_text_format(self):
295+
model = JsonModel(data_wrapper=False)
296+
resp = httplib2.Response({"status": "200"})
297+
resp.reason = "OK"
298+
content = CSV_TEXT_MOCK
299+
content = model.response(resp, content)
300+
self.assertEqual(content, CSV_TEXT_MOCK)
301+
302+
def test_no_data_wrapper_deserialize_raise_type_error(self):
303+
buffer = io.StringIO()
304+
buffer.write('String buffer')
305+
model = JsonModel(data_wrapper=False)
306+
resp = httplib2.Response({"status": "500"})
307+
resp.reason = "The JSON object must be str, bytes or bytearray, not StringIO"
308+
content = buffer
309+
with self.assertRaises(TypeError):
310+
model.response(resp, content)
311+
293312
def test_data_wrapper_deserialize(self):
294313
model = JsonModel(data_wrapper=True)
295314
resp = httplib2.Response({"status": "200"})

0 commit comments

Comments
 (0)