aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGianluca Paronitti <gparonitti@users.noreply.github.com>2021-10-21 22:37:37 +0200
committerGitHub <noreply@github.com>2021-10-21 16:37:37 -0400
commit7d630270758459225f7169a03e9a6973b9e5ad82 (patch)
tree1b7f48f4e792b2a3b989402affdd486b2c287a9c
parent0b400f97be45808ade211ca8291b2e1d9476bde1 (diff)
downloadgoogle-api-python-client-7d630270758459225f7169a03e9a6973b9e5ad82.tar.gz
fix: manage JSONDecodeError exception (#1574)
Closes #1570.
-rw-r--r--googleapiclient/model.py10
-rw-r--r--tests/test_json_model.py21
2 files changed, 27 insertions, 4 deletions
diff --git a/googleapiclient/model.py b/googleapiclient/model.py
index b853a4f68..b023db4dd 100644
--- a/googleapiclient/model.py
+++ b/googleapiclient/model.py
@@ -277,9 +277,13 @@ class JsonModel(BaseModel):
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
diff --git a/tests/test_json_model.py b/tests/test_json_model.py
index 1ddc1c73b..322a7b484 100644
--- a/tests/test_json_model.py
+++ b/tests/test_json_model.py
@@ -22,6 +22,7 @@ from __future__ import absolute_import
__author__ = "jcgregorio@google.com (Joe Gregorio)"
+import io
import httplib2
import json
import pkg_resources
@@ -31,11 +32,11 @@ import urllib
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):
@@ -290,6 +291,24 @@ class Model(unittest.TestCase):
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"})