| 1 |
#!/usr/bin/env python |
| 2 |
# |
| 3 |
# Copyright 2014 Google Inc. All Rights Reserved. |
| 4 |
# |
| 5 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 |
# you may not use this file except in compliance with the License. |
| 7 |
# You may obtain a copy of the License at |
| 8 |
# |
| 9 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 |
# |
| 11 |
# Unless required by applicable law or agreed to in writing, software |
| 12 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 |
# See the License for the specific language governing permissions and |
| 15 |
# limitations under the License. |
| 16 |
|
| 17 |
"""JSON Model tests |
| 18 |
|
| 19 |
Unit tests for the JSON model. |
| 20 |
""" |
| 21 |
from __future__ import absolute_import |
| 22 |
|
| 23 |
__author__ = "[email protected] (Joe Gregorio)" |
| 24 |
|
| 25 |
import io |
| 26 |
import json |
| 27 |
import platform |
| 28 |
import unittest |
| 29 |
import urllib |
| 30 |
|
| 31 |
import httplib2 |
| 32 |
|
| 33 |
from googleapiclient import version as googleapiclient_version |
| 34 |
from googleapiclient.errors import HttpError |
| 35 |
import googleapiclient.model |
| 36 |
from googleapiclient.model import JsonModel |
| 37 |
|
| 38 |
try: |
| 39 |
from google.api_core.version_header import API_VERSION_METADATA_KEY |
| 40 |
|
| 41 |
HAS_API_VERSION = True |
| 42 |
except ImportError: |
| 43 |
HAS_API_VERSION = False |
| 44 |
|
| 45 |
_LIBRARY_VERSION = googleapiclient_version.__version__ |
| 46 |
CSV_TEXT_MOCK = "column1,column2,column3\nstring1,1.2,string2" |
| 47 |
|
| 48 |
|
| 49 |
class Model(unittest.TestCase): |
| 50 |
def test_json_no_body(self): |
| 51 |
model = JsonModel(data_wrapper=False) |
| 52 |
|
| 53 |
headers = {} |
| 54 |
path_params = {} |
| 55 |
query_params = {} |
| 56 |
body = None |
| 57 |
|
| 58 |
headers, unused_params, query, body = model.request( |
| 59 |
headers, path_params, query_params, body |
| 60 |
) |
| 61 |
|
| 62 |
self.assertEqual(headers["accept"], "application/json") |
| 63 |
self.assertTrue("content-type" not in headers) |
| 64 |
self.assertNotEqual(query, "") |
| 65 |
self.assertEqual(body, None) |
| 66 |
|
| 67 |
def test_json_body(self): |
| 68 |
model = JsonModel(data_wrapper=False) |
| 69 |
|
| 70 |
headers = {} |
| 71 |
path_params = {} |
| 72 |
query_params = {} |
| 73 |
body = {} |
| 74 |
|
| 75 |
headers, unused_params, query, body = model.request( |
| 76 |
headers, path_params, query_params, body |
| 77 |
) |
| 78 |
|
| 79 |
self.assertEqual(headers["accept"], "application/json") |
| 80 |
self.assertEqual(headers["content-type"], "application/json") |
| 81 |
self.assertNotEqual(query, "") |
| 82 |
self.assertEqual(body, "{}") |
| 83 |
|
| 84 |
def test_json_body_data_wrapper(self): |
| 85 |
model = JsonModel(data_wrapper=True) |
| 86 |
|
| 87 |
headers = {} |
| 88 |
path_params = {} |
| 89 |
query_params = {} |
| 90 |
body = {} |
| 91 |
|
| 92 |
headers, unused_params, query, body = model.request( |
| 93 |
headers, path_params, query_params, body |
| 94 |
) |
| 95 |
|
| 96 |
self.assertEqual(headers["accept"], "application/json") |
| 97 |
self.assertEqual(headers["content-type"], "application/json") |
| 98 |
self.assertNotEqual(query, "") |
| 99 |
self.assertEqual(body, '{"data": {}}') |
| 100 |
|
| 101 |
def test_json_body_default_data(self): |
| 102 |
"""Test that a 'data' wrapper doesn't get added if one is already present.""" |
| 103 |
model = JsonModel(data_wrapper=True) |
| 104 |
|
| 105 |
headers = {} |
| 106 |
path_params = {} |
| 107 |
query_params = {} |
| 108 |
body = {"data": "foo"} |
| 109 |
|
| 110 |
headers, unused_params, query, body = model.request( |
| 111 |
headers, path_params, query_params, body |
| 112 |
) |
| 113 |
|
| 114 |
self.assertEqual(headers["accept"], "application/json") |
| 115 |
self.assertEqual(headers["content-type"], "application/json") |
| 116 |
self.assertNotEqual(query, "") |
| 117 |
self.assertEqual(body, '{"data": "foo"}') |
| 118 |
|
| 119 |
def test_json_build_query(self): |
| 120 |
model = JsonModel(data_wrapper=False) |
| 121 |
|
| 122 |
headers = {} |
| 123 |
path_params = {} |
| 124 |
query_params = { |
| 125 |
"foo": 1, |
| 126 |
"bar": "\N{COMET}", |
| 127 |
"baz": ["fe", "fi", "fo", "fum"], # Repeated parameters |
| 128 |
"qux": [], |
| 129 |
} |
| 130 |
body = {} |
| 131 |
|
| 132 |
headers, unused_params, query, body = model.request( |
| 133 |
headers, path_params, query_params, body |
| 134 |
) |
| 135 |
|
| 136 |
self.assertEqual(headers["accept"], "application/json") |
| 137 |
self.assertEqual(headers["content-type"], "application/json") |
| 138 |
|
| 139 |
query_dict = urllib.parse.parse_qs(query[1:]) |
| 140 |
self.assertEqual(query_dict["foo"], ["1"]) |
| 141 |
self.assertEqual(query_dict["bar"], ["\N{COMET}"]) |
| 142 |
self.assertEqual(query_dict["baz"], ["fe", "fi", "fo", "fum"]) |
| 143 |
self.assertTrue("qux" not in query_dict) |
| 144 |
self.assertEqual(body, "{}") |
| 145 |
|
| 146 |
def test_user_agent(self): |
| 147 |
model = JsonModel(data_wrapper=False) |
| 148 |
|
| 149 |
headers = {"user-agent": "my-test-app/1.23.4"} |
| 150 |
path_params = {} |
| 151 |
query_params = {} |
| 152 |
body = {} |
| 153 |
|
| 154 |
headers, unused_params, unused_query, body = model.request( |
| 155 |
headers, path_params, query_params, body |
| 156 |
) |
| 157 |
|
| 158 |
self.assertEqual(headers["user-agent"], "my-test-app/1.23.4 (gzip)") |
| 159 |
|
| 160 |
def test_x_goog_api_client(self): |
| 161 |
model = JsonModel(data_wrapper=False) |
| 162 |
|
| 163 |
# test header composition for cloud clients that wrap discovery |
| 164 |
headers = {"x-goog-api-client": "gccl/1.23.4"} |
| 165 |
path_params = {} |
| 166 |
query_params = {} |
| 167 |
body = {} |
| 168 |
|
| 169 |
headers, unused_params, unused_query, body = model.request( |
| 170 |
headers, path_params, query_params, body |
| 171 |
) |
| 172 |
|
| 173 |
self.assertEqual( |
| 174 |
headers["x-goog-api-client"], |
| 175 |
"gccl/1.23.4" |
| 176 |
+ " gdcl/" |
| 177 |
+ _LIBRARY_VERSION |
| 178 |
+ " gl-python/" |
| 179 |
+ platform.python_version(), |
| 180 |
) |
| 181 |
|
| 182 |
@unittest.skipIf( |
| 183 |
not HAS_API_VERSION, |
| 184 |
"Skip this test when an older version of google-api-core is used", |
| 185 |
) |
| 186 |
def test_x_goog_api_version(self): |
| 187 |
model = JsonModel(data_wrapper=False) |
| 188 |
|
| 189 |
# test header composition for clients that wrap discovery |
| 190 |
headers = {} |
| 191 |
path_params = {} |
| 192 |
query_params = {} |
| 193 |
body = {} |
| 194 |
api_version = "20240401" |
| 195 |
|
| 196 |
headers, _, _, body = model.request( |
| 197 |
headers, path_params, query_params, body, api_version |
| 198 |
) |
| 199 |
|
| 200 |
self.assertEqual( |
| 201 |
headers[API_VERSION_METADATA_KEY], |
| 202 |
api_version, |
| 203 |
) |
| 204 |
|
| 205 |
def test_bad_response(self): |
| 206 |
model = JsonModel(data_wrapper=False) |
| 207 |
resp = httplib2.Response({"status": "401"}) |
| 208 |
resp.reason = "Unauthorized" |
| 209 |
content = b'{"error": {"message": "not authorized"}}' |
| 210 |
|
| 211 |
try: |
| 212 |
content = model.response(resp, content) |
| 213 |
self.fail("Should have thrown an exception") |
| 214 |
except HttpError as e: |
| 215 |
self.assertTrue("not authorized" in str(e)) |
| 216 |
|
| 217 |
resp["content-type"] = "application/json" |
| 218 |
|
| 219 |
try: |
| 220 |
content = model.response(resp, content) |
| 221 |
self.fail("Should have thrown an exception") |
| 222 |
except HttpError as e: |
| 223 |
self.assertTrue("not authorized" in str(e)) |
| 224 |
|
| 225 |
def test_good_response(self): |
| 226 |
model = JsonModel(data_wrapper=True) |
| 227 |
resp = httplib2.Response({"status": "200"}) |
| 228 |
resp.reason = "OK" |
| 229 |
content = '{"data": "is good"}' |
| 230 |
|
| 231 |
content = model.response(resp, content) |
| 232 |
self.assertEqual(content, "is good") |
| 233 |
|
| 234 |
def test_good_response_wo_data(self): |
| 235 |
model = JsonModel(data_wrapper=False) |
| 236 |
resp = httplib2.Response({"status": "200"}) |
| 237 |
resp.reason = "OK" |
| 238 |
content = '{"foo": "is good"}' |
| 239 |
|
| 240 |
content = model.response(resp, content) |
| 241 |
self.assertEqual(content, {"foo": "is good"}) |
| 242 |
|
| 243 |
def test_good_response_wo_data_str(self): |
| 244 |
model = JsonModel(data_wrapper=False) |
| 245 |
resp = httplib2.Response({"status": "200"}) |
| 246 |
resp.reason = "OK" |
| 247 |
content = '"data goes here"' |
| 248 |
|
| 249 |
content = model.response(resp, content) |
| 250 |
self.assertEqual(content, "data goes here") |
| 251 |
|
| 252 |
def test_no_content_response(self): |
| 253 |
model = JsonModel(data_wrapper=False) |
| 254 |
resp = httplib2.Response({"status": "204"}) |
| 255 |
resp.reason = "No Content" |
| 256 |
content = "" |
| 257 |
|
| 258 |
content = model.response(resp, content) |
| 259 |
self.assertEqual(content, {}) |
| 260 |
|
| 261 |
def test_logging(self): |
| 262 |
class MockLogging(object): |
| 263 |
def __init__(self): |
| 264 |
self.info_record = [] |
| 265 |
self.debug_record = [] |
| 266 |
|
| 267 |
def info(self, message, *args): |
| 268 |
self.info_record.append(message % args) |
| 269 |
|
| 270 |
def debug(self, message, *args): |
| 271 |
self.debug_record.append(message % args) |
| 272 |
|
| 273 |
class MockResponse(dict): |
| 274 |
def __init__(self, items): |
| 275 |
super(MockResponse, self).__init__() |
| 276 |
self.status = items["status"] |
| 277 |
for key, value in items.items(): |
| 278 |
self[key] = value |
| 279 |
|
| 280 |
old_logging = googleapiclient.model.LOGGER |
| 281 |
googleapiclient.model.LOGGER = MockLogging() |
| 282 |
googleapiclient.model.dump_request_response = True |
| 283 |
model = JsonModel() |
| 284 |
request_body = {"field1": "value1", "field2": "value2"} |
| 285 |
body_string = model.request({}, {}, {}, request_body)[-1] |
| 286 |
json_body = json.loads(body_string) |
| 287 |
self.assertEqual(request_body, json_body) |
| 288 |
|
| 289 |
response = { |
| 290 |
"status": 200, |
| 291 |
"response_field_1": "response_value_1", |
| 292 |
"response_field_2": "response_value_2", |
| 293 |
} |
| 294 |
response_body = model.response(MockResponse(response), body_string) |
| 295 |
self.assertEqual(request_body, response_body) |
| 296 |
self.assertEqual( |
| 297 |
googleapiclient.model.LOGGER.info_record[:2], |
| 298 |
["--request-start--", "-headers-start-"], |
| 299 |
) |
| 300 |
self.assertTrue( |
| 301 |
"response_field_1: response_value_1" |
| 302 |
in googleapiclient.model.LOGGER.info_record |
| 303 |
) |
| 304 |
self.assertTrue( |
| 305 |
"response_field_2: response_value_2" |
| 306 |
in googleapiclient.model.LOGGER.info_record |
| 307 |
) |
| 308 |
self.assertEqual( |
| 309 |
json.loads(googleapiclient.model.LOGGER.info_record[-2]), request_body |
| 310 |
) |
| 311 |
self.assertEqual( |
| 312 |
googleapiclient.model.LOGGER.info_record[-1], "--response-end--" |
| 313 |
) |
| 314 |
googleapiclient.model.LOGGER = old_logging |
| 315 |
|
| 316 |
def test_no_data_wrapper_deserialize(self): |
| 317 |
model = JsonModel(data_wrapper=False) |
| 318 |
resp = httplib2.Response({"status": "200"}) |
| 319 |
resp.reason = "OK" |
| 320 |
content = '{"data": "is good"}' |
| 321 |
content = model.response(resp, content) |
| 322 |
self.assertEqual(content, {"data": "is good"}) |
| 323 |
|
| 324 |
def test_no_data_wrapper_deserialize_text_format(self): |
| 325 |
model = JsonModel(data_wrapper=False) |
| 326 |
resp = httplib2.Response({"status": "200"}) |
| 327 |
resp.reason = "OK" |
| 328 |
content = CSV_TEXT_MOCK |
| 329 |
content = model.response(resp, content) |
| 330 |
self.assertEqual(content, CSV_TEXT_MOCK) |
| 331 |
|
| 332 |
def test_no_data_wrapper_deserialize_raise_type_error(self): |
| 333 |
buffer = io.StringIO() |
| 334 |
buffer.write("String buffer") |
| 335 |
model = JsonModel(data_wrapper=False) |
| 336 |
resp = httplib2.Response({"status": "500"}) |
| 337 |
resp.reason = "The JSON object must be str, bytes or bytearray, not StringIO" |
| 338 |
content = buffer |
| 339 |
with self.assertRaises(TypeError): |
| 340 |
model.response(resp, content) |
| 341 |
|
| 342 |
def test_data_wrapper_deserialize(self): |
| 343 |
model = JsonModel(data_wrapper=True) |
| 344 |
resp = httplib2.Response({"status": "200"}) |
| 345 |
resp.reason = "OK" |
| 346 |
content = '{"data": "is good"}' |
| 347 |
content = model.response(resp, content) |
| 348 |
self.assertEqual(content, "is good") |
| 349 |
|
| 350 |
def test_data_wrapper_deserialize_nodata(self): |
| 351 |
model = JsonModel(data_wrapper=True) |
| 352 |
resp = httplib2.Response({"status": "200"}) |
| 353 |
resp.reason = "OK" |
| 354 |
content = '{"atad": "is good"}' |
| 355 |
content = model.response(resp, content) |
| 356 |
self.assertEqual(content, {"atad": "is good"}) |
| 357 |
|
| 358 |
|
| 359 |
if __name__ == "__main__": |
| 360 |
unittest.main() |