blob: 0d1f283f8f0b7d5651b8d9fc122b361a4fbeaf75 [file] [log] [blame]
Craig Citro15744b12015-03-02 13:34:32 -08001#!/usr/bin/env python
Joe Gregorioba9ea7f2010-08-19 15:49:04 -04002#
Craig Citro751b7fb2014-09-23 11:20:38 -07003# Copyright 2014 Google Inc. All Rights Reserved.
Joe Gregorio6d5e94f2010-08-25 23:49:30 -04004#
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.
Joe Gregorioba9ea7f2010-08-19 15:49:04 -040016
Joe Gregorio6d5e94f2010-08-25 23:49:30 -040017"""JSON Model tests
Joe Gregorioba9ea7f2010-08-19 15:49:04 -040018
Joe Gregorio6d5e94f2010-08-25 23:49:30 -040019Unit tests for the JSON model.
Joe Gregorioba9ea7f2010-08-19 15:49:04 -040020"""
INADA Naokid898a372015-03-04 03:52:46 +090021from __future__ import absolute_import
22import six
Joe Gregorioba9ea7f2010-08-19 15:49:04 -040023
24__author__ = 'jcgregorio@google.com (Joe Gregorio)'
25
Joe Gregorio34044bc2011-03-07 16:58:33 -050026import copy
Craig Citro6ae34d72014-08-18 23:10:09 -070027import json
Joe Gregorioba9ea7f2010-08-19 15:49:04 -040028import os
Pat Ferate497a90f2015-03-09 09:52:54 -070029import unittest2 as unittest
Joe Gregorioc5c5a372010-09-22 11:42:32 -040030import httplib2
John Asmuth864311d2014-04-24 15:46:08 -040031import googleapiclient.model
ade@google.comd69e5e42010-08-31 15:28:20 +010032
John Asmuth864311d2014-04-24 15:46:08 -040033from googleapiclient import __version__
34from googleapiclient.errors import HttpError
35from googleapiclient.model import JsonModel
Joe Gregorio34044bc2011-03-07 16:58:33 -050036
Pat Ferated5b61bd2015-03-03 16:04:11 -080037from six.moves.urllib.parse import parse_qs
ade@google.comd69e5e42010-08-31 15:28:20 +010038
Joe Gregorioba9ea7f2010-08-19 15:49:04 -040039
Joe Gregorioba9ea7f2010-08-19 15:49:04 -040040class Model(unittest.TestCase):
41 def test_json_no_body(self):
Joe Gregoriod433b2a2011-02-22 10:51:51 -050042 model = JsonModel(data_wrapper=False)
Joe Gregorioba9ea7f2010-08-19 15:49:04 -040043
44 headers = {}
ade@google.com850cf552010-08-20 23:24:56 +010045 path_params = {}
46 query_params = {}
47 body = None
Joe Gregorioba9ea7f2010-08-19 15:49:04 -040048
Joe Gregorio5a4c3282013-07-29 13:48:06 -040049 headers, unused_params, query, body = model.request(
Joe Gregorioa314b1f2013-04-05 16:25:11 -040050 headers, path_params, query_params, body)
Joe Gregorioba9ea7f2010-08-19 15:49:04 -040051
52 self.assertEqual(headers['accept'], 'application/json')
53 self.assertTrue('content-type' not in headers)
54 self.assertNotEqual(query, '')
55 self.assertEqual(body, None)
56
57 def test_json_body(self):
Joe Gregoriod433b2a2011-02-22 10:51:51 -050058 model = JsonModel(data_wrapper=False)
Joe Gregorioba9ea7f2010-08-19 15:49:04 -040059
60 headers = {}
ade@google.com850cf552010-08-20 23:24:56 +010061 path_params = {}
62 query_params = {}
63 body = {}
Joe Gregorioba9ea7f2010-08-19 15:49:04 -040064
Joe Gregorio5a4c3282013-07-29 13:48:06 -040065 headers, unused_params, query, body = model.request(
Joe Gregorioa314b1f2013-04-05 16:25:11 -040066 headers, path_params, query_params, body)
Joe Gregorioba9ea7f2010-08-19 15:49:04 -040067
68 self.assertEqual(headers['accept'], 'application/json')
69 self.assertEqual(headers['content-type'], 'application/json')
70 self.assertNotEqual(query, '')
Joe Gregorio913e70d2010-11-05 15:38:23 -040071 self.assertEqual(body, '{}')
Joe Gregorioba9ea7f2010-08-19 15:49:04 -040072
Joe Gregoriod433b2a2011-02-22 10:51:51 -050073 def test_json_body_data_wrapper(self):
74 model = JsonModel(data_wrapper=True)
75
76 headers = {}
77 path_params = {}
78 query_params = {}
79 body = {}
80
Joe Gregorio5a4c3282013-07-29 13:48:06 -040081 headers, unused_params, query, body = model.request(
Joe Gregorioa314b1f2013-04-05 16:25:11 -040082 headers, path_params, query_params, body)
Joe Gregoriod433b2a2011-02-22 10:51:51 -050083
84 self.assertEqual(headers['accept'], 'application/json')
85 self.assertEqual(headers['content-type'], 'application/json')
86 self.assertNotEqual(query, '')
87 self.assertEqual(body, '{"data": {}}')
88
Joe Gregorio8963ff92010-10-11 13:14:43 -040089 def test_json_body_default_data(self):
90 """Test that a 'data' wrapper doesn't get added if one is already present."""
Joe Gregoriod433b2a2011-02-22 10:51:51 -050091 model = JsonModel(data_wrapper=True)
Joe Gregorio8963ff92010-10-11 13:14:43 -040092
93 headers = {}
94 path_params = {}
95 query_params = {}
96 body = {'data': 'foo'}
97
Joe Gregorio5a4c3282013-07-29 13:48:06 -040098 headers, unused_params, query, body = model.request(
Joe Gregorioa314b1f2013-04-05 16:25:11 -040099 headers, path_params, query_params, body)
Joe Gregorio8963ff92010-10-11 13:14:43 -0400100
101 self.assertEqual(headers['accept'], 'application/json')
102 self.assertEqual(headers['content-type'], 'application/json')
103 self.assertNotEqual(query, '')
104 self.assertEqual(body, '{"data": "foo"}')
105
Joe Gregoriofe695fb2010-08-30 12:04:04 -0400106 def test_json_build_query(self):
Joe Gregoriod433b2a2011-02-22 10:51:51 -0500107 model = JsonModel(data_wrapper=False)
Joe Gregoriofe695fb2010-08-30 12:04:04 -0400108
109 headers = {}
110 path_params = {}
Joe Gregorio61d7e962011-02-22 22:52:07 -0500111 query_params = {'foo': 1, 'bar': u'\N{COMET}',
112 'baz': ['fe', 'fi', 'fo', 'fum'], # Repeated parameters
113 'qux': []}
Joe Gregoriofe695fb2010-08-30 12:04:04 -0400114 body = {}
115
Joe Gregorio5a4c3282013-07-29 13:48:06 -0400116 headers, unused_params, query, body = model.request(
Joe Gregorioa314b1f2013-04-05 16:25:11 -0400117 headers, path_params, query_params, body)
Joe Gregoriofe695fb2010-08-30 12:04:04 -0400118
119 self.assertEqual(headers['accept'], 'application/json')
120 self.assertEqual(headers['content-type'], 'application/json')
121
Joe Gregorio61d7e962011-02-22 22:52:07 -0500122 query_dict = parse_qs(query[1:])
Joe Gregoriofe695fb2010-08-30 12:04:04 -0400123 self.assertEqual(query_dict['foo'], ['1'])
Pat Ferateca397a72015-03-03 18:06:15 -0800124 if six.PY3:
125 # Python 3, no need to encode
126 self.assertEqual(query_dict['bar'], [u'\N{COMET}'])
127 else:
128 # Python 2, encode string
129 self.assertEqual(query_dict['bar'], [u'\N{COMET}'.encode('utf-8')])
Joe Gregorio61d7e962011-02-22 22:52:07 -0500130 self.assertEqual(query_dict['baz'], ['fe', 'fi', 'fo', 'fum'])
131 self.assertTrue('qux' not in query_dict)
Joe Gregorio913e70d2010-11-05 15:38:23 -0400132 self.assertEqual(body, '{}')
Joe Gregoriofe695fb2010-08-30 12:04:04 -0400133
Joe Gregorioc5c5a372010-09-22 11:42:32 -0400134 def test_user_agent(self):
Joe Gregoriod433b2a2011-02-22 10:51:51 -0500135 model = JsonModel(data_wrapper=False)
Joe Gregorioc5c5a372010-09-22 11:42:32 -0400136
137 headers = {'user-agent': 'my-test-app/1.23.4'}
138 path_params = {}
139 query_params = {}
140 body = {}
141
Joe Gregorio5a4c3282013-07-29 13:48:06 -0400142 headers, unused_params, unused_query, body = model.request(
Joe Gregorioa314b1f2013-04-05 16:25:11 -0400143 headers, path_params, query_params, body)
Joe Gregorioc5c5a372010-09-22 11:42:32 -0400144
Joe Gregorioa314b1f2013-04-05 16:25:11 -0400145 self.assertEqual(headers['user-agent'],
Joe Gregorioc02f5632013-05-13 11:28:56 -0400146 'my-test-app/1.23.4 google-api-python-client/' + __version__ +
147 ' (gzip)')
Joe Gregorioc5c5a372010-09-22 11:42:32 -0400148
149 def test_bad_response(self):
Joe Gregoriod433b2a2011-02-22 10:51:51 -0500150 model = JsonModel(data_wrapper=False)
Joe Gregorioc5c5a372010-09-22 11:42:32 -0400151 resp = httplib2.Response({'status': '401'})
152 resp.reason = 'Unauthorized'
INADA Naoki09157612015-03-25 01:51:03 +0900153 content = b'{"error": {"message": "not authorized"}}'
Joe Gregorioc5c5a372010-09-22 11:42:32 -0400154
155 try:
156 content = model.response(resp, content)
157 self.fail('Should have thrown an exception')
INADA Naokic1505df2014-08-20 15:19:53 +0900158 except HttpError as e:
Joe Gregorio20b54fb2012-07-26 09:59:35 -0400159 self.assertTrue('not authorized' in str(e))
Joe Gregorioc5c5a372010-09-22 11:42:32 -0400160
161 resp['content-type'] = 'application/json'
162
163 try:
164 content = model.response(resp, content)
165 self.fail('Should have thrown an exception')
INADA Naokic1505df2014-08-20 15:19:53 +0900166 except HttpError as e:
Joe Gregorioc5c5a372010-09-22 11:42:32 -0400167 self.assertTrue('not authorized' in str(e))
168
Joe Gregorioc5c5a372010-09-22 11:42:32 -0400169 def test_good_response(self):
Joe Gregoriod433b2a2011-02-22 10:51:51 -0500170 model = JsonModel(data_wrapper=True)
Joe Gregorioc5c5a372010-09-22 11:42:32 -0400171 resp = httplib2.Response({'status': '200'})
172 resp.reason = 'OK'
173 content = '{"data": "is good"}'
174
175 content = model.response(resp, content)
176 self.assertEqual(content, 'is good')
Joe Gregoriofe695fb2010-08-30 12:04:04 -0400177
Joe Gregorio78a508d2010-10-26 16:36:36 -0400178 def test_good_response_wo_data(self):
Joe Gregoriod433b2a2011-02-22 10:51:51 -0500179 model = JsonModel(data_wrapper=False)
Joe Gregorio78a508d2010-10-26 16:36:36 -0400180 resp = httplib2.Response({'status': '200'})
181 resp.reason = 'OK'
182 content = '{"foo": "is good"}'
183
184 content = model.response(resp, content)
185 self.assertEqual(content, {'foo': 'is good'})
186
187 def test_good_response_wo_data_str(self):
Joe Gregoriod433b2a2011-02-22 10:51:51 -0500188 model = JsonModel(data_wrapper=False)
Joe Gregorio78a508d2010-10-26 16:36:36 -0400189 resp = httplib2.Response({'status': '200'})
190 resp.reason = 'OK'
191 content = '"data goes here"'
192
193 content = model.response(resp, content)
194 self.assertEqual(content, 'data goes here')
195
Matt McDonald2a5f4132011-04-29 16:32:27 -0400196 def test_no_content_response(self):
197 model = JsonModel(data_wrapper=False)
198 resp = httplib2.Response({'status': '204'})
199 resp.reason = 'No Content'
200 content = ''
Joe Gregorio34044bc2011-03-07 16:58:33 -0500201
Matt McDonald2a5f4132011-04-29 16:32:27 -0400202 content = model.response(resp, content)
203 self.assertEqual(content, {})
Joe Gregorio34044bc2011-03-07 16:58:33 -0500204
Matt McDonald2a5f4132011-04-29 16:32:27 -0400205 def test_logging(self):
Joe Gregorio34044bc2011-03-07 16:58:33 -0500206 class MockLogging(object):
207 def __init__(self):
208 self.info_record = []
209 self.debug_record = []
210 def info(self, message, *args):
211 self.info_record.append(message % args)
212
213 def debug(self, message, *args):
214 self.debug_record.append(message % args)
215
216 class MockResponse(dict):
217 def __init__(self, items):
218 super(MockResponse, self).__init__()
219 self.status = items['status']
INADA Naokid898a372015-03-04 03:52:46 +0900220 for key, value in six.iteritems(items):
Joe Gregorio34044bc2011-03-07 16:58:33 -0500221 self[key] = value
Emmett Butler09699152016-02-08 14:26:00 -0800222 old_logging = googleapiclient.model.LOGGER
223 googleapiclient.model.LOGGER = MockLogging()
John Asmuth864311d2014-04-24 15:46:08 -0400224 googleapiclient.model.dump_request_response = True
Matt McDonald2a5f4132011-04-29 16:32:27 -0400225 model = JsonModel()
Joe Gregorio34044bc2011-03-07 16:58:33 -0500226 request_body = {
227 'field1': 'value1',
228 'field2': 'value2'
229 }
230 body_string = model.request({}, {}, {}, request_body)[-1]
Craig Citro6ae34d72014-08-18 23:10:09 -0700231 json_body = json.loads(body_string)
Joe Gregorio34044bc2011-03-07 16:58:33 -0500232 self.assertEqual(request_body, json_body)
233
234 response = {'status': 200,
235 'response_field_1': 'response_value_1',
236 'response_field_2': 'response_value_2'}
237 response_body = model.response(MockResponse(response), body_string)
238 self.assertEqual(request_body, response_body)
Emmett Butler09699152016-02-08 14:26:00 -0800239 self.assertEqual(googleapiclient.model.LOGGER.info_record[:2],
Joe Gregorioafdf50b2011-03-08 09:41:52 -0500240 ['--request-start--',
241 '-headers-start-'])
242 self.assertTrue('response_field_1: response_value_1' in
Emmett Butler09699152016-02-08 14:26:00 -0800243 googleapiclient.model.LOGGER.info_record)
Joe Gregorioafdf50b2011-03-08 09:41:52 -0500244 self.assertTrue('response_field_2: response_value_2' in
Emmett Butler09699152016-02-08 14:26:00 -0800245 googleapiclient.model.LOGGER.info_record)
246 self.assertEqual(json.loads(googleapiclient.model.LOGGER.info_record[-2]),
Joe Gregorio34044bc2011-03-07 16:58:33 -0500247 request_body)
Emmett Butler09699152016-02-08 14:26:00 -0800248 self.assertEqual(googleapiclient.model.LOGGER.info_record[-1],
Joe Gregorio34044bc2011-03-07 16:58:33 -0500249 '--response-end--')
Emmett Butler09699152016-02-08 14:26:00 -0800250 googleapiclient.model.LOGGER = old_logging
Joe Gregorio34044bc2011-03-07 16:58:33 -0500251
Ali Afshar81fde8e2012-10-23 11:14:28 -0700252 def test_no_data_wrapper_deserialize(self):
253 model = JsonModel(data_wrapper=False)
254 resp = httplib2.Response({'status': '200'})
255 resp.reason = 'OK'
256 content = '{"data": "is good"}'
257 content = model.response(resp, content)
258 self.assertEqual(content, {'data': 'is good'})
259
260 def test_data_wrapper_deserialize(self):
261 model = JsonModel(data_wrapper=True)
262 resp = httplib2.Response({'status': '200'})
263 resp.reason = 'OK'
264 content = '{"data": "is good"}'
265 content = model.response(resp, content)
266 self.assertEqual(content, 'is good')
267
268 def test_data_wrapper_deserialize_nodata(self):
269 model = JsonModel(data_wrapper=True)
270 resp = httplib2.Response({'status': '200'})
271 resp.reason = 'OK'
272 content = '{"atad": "is good"}'
273 content = model.response(resp, content)
274 self.assertEqual(content, {'atad': 'is good'})
275
276
Joe Gregorio34044bc2011-03-07 16:58:33 -0500277
Joe Gregorioba9ea7f2010-08-19 15:49:04 -0400278if __name__ == '__main__':
279 unittest.main()