blob: d6cf0c0bdc5e83e4f651ae5b8f71692be695d3a5 [file] [log] [blame]
Joe Gregorioba9ea7f2010-08-19 15:49:04 -04001#!/usr/bin/python2.4
2#
Joe Gregorio6d5e94f2010-08-25 23:49:30 -04003# Copyright 2010 Google Inc.
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.
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"""
21
22__author__ = 'jcgregorio@google.com (Joe Gregorio)'
23
Joe Gregorio34044bc2011-03-07 16:58:33 -050024import copy
25import gflags
Joe Gregorioba9ea7f2010-08-19 15:49:04 -040026import os
27import unittest
Joe Gregorioc5c5a372010-09-22 11:42:32 -040028import httplib2
Joe Gregorio34044bc2011-03-07 16:58:33 -050029import apiclient.model
ade@google.comd69e5e42010-08-31 15:28:20 +010030
Joe Gregorioe1de4162011-02-23 11:30:29 -050031from apiclient.errors import HttpError
Joe Gregorio34044bc2011-03-07 16:58:33 -050032from apiclient.model import JsonModel
Joe Gregorio549230c2012-01-11 10:38:05 -050033from oauth2client.anyjson import simplejson
Joe Gregorio34044bc2011-03-07 16:58:33 -050034
35FLAGS = gflags.FLAGS
Joe Gregorioe1de4162011-02-23 11:30:29 -050036
ade@google.comd69e5e42010-08-31 15:28:20 +010037# Python 2.5 requires different modules
38try:
39 from urlparse import parse_qs
40except ImportError:
41 from cgi import parse_qs
42
Joe Gregorioba9ea7f2010-08-19 15:49:04 -040043
Joe Gregorioba9ea7f2010-08-19 15:49:04 -040044class Model(unittest.TestCase):
45 def test_json_no_body(self):
Joe Gregoriod433b2a2011-02-22 10:51:51 -050046 model = JsonModel(data_wrapper=False)
Joe Gregorioba9ea7f2010-08-19 15:49:04 -040047
48 headers = {}
ade@google.com850cf552010-08-20 23:24:56 +010049 path_params = {}
50 query_params = {}
51 body = None
Joe Gregorioba9ea7f2010-08-19 15:49:04 -040052
ade@google.com850cf552010-08-20 23:24:56 +010053 headers, params, query, body = model.request(headers, path_params, query_params, body)
Joe Gregorioba9ea7f2010-08-19 15:49:04 -040054
55 self.assertEqual(headers['accept'], 'application/json')
56 self.assertTrue('content-type' not in headers)
57 self.assertNotEqual(query, '')
58 self.assertEqual(body, None)
59
60 def test_json_body(self):
Joe Gregoriod433b2a2011-02-22 10:51:51 -050061 model = JsonModel(data_wrapper=False)
Joe Gregorioba9ea7f2010-08-19 15:49:04 -040062
63 headers = {}
ade@google.com850cf552010-08-20 23:24:56 +010064 path_params = {}
65 query_params = {}
66 body = {}
Joe Gregorioba9ea7f2010-08-19 15:49:04 -040067
ade@google.com850cf552010-08-20 23:24:56 +010068 headers, params, query, body = model.request(headers, path_params, query_params, body)
Joe Gregorioba9ea7f2010-08-19 15:49:04 -040069
70 self.assertEqual(headers['accept'], 'application/json')
71 self.assertEqual(headers['content-type'], 'application/json')
72 self.assertNotEqual(query, '')
Joe Gregorio913e70d2010-11-05 15:38:23 -040073 self.assertEqual(body, '{}')
Joe Gregorioba9ea7f2010-08-19 15:49:04 -040074
Joe Gregoriod433b2a2011-02-22 10:51:51 -050075 def test_json_body_data_wrapper(self):
76 model = JsonModel(data_wrapper=True)
77
78 headers = {}
79 path_params = {}
80 query_params = {}
81 body = {}
82
83 headers, params, query, body = model.request(headers, path_params, query_params, body)
84
85 self.assertEqual(headers['accept'], 'application/json')
86 self.assertEqual(headers['content-type'], 'application/json')
87 self.assertNotEqual(query, '')
88 self.assertEqual(body, '{"data": {}}')
89
Joe Gregorio8963ff92010-10-11 13:14:43 -040090 def test_json_body_default_data(self):
91 """Test that a 'data' wrapper doesn't get added if one is already present."""
Joe Gregoriod433b2a2011-02-22 10:51:51 -050092 model = JsonModel(data_wrapper=True)
Joe Gregorio8963ff92010-10-11 13:14:43 -040093
94 headers = {}
95 path_params = {}
96 query_params = {}
97 body = {'data': 'foo'}
98
99 headers, params, query, body = model.request(headers, path_params, query_params, body)
100
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
116 headers, params, query, body = model.request(headers, path_params, query_params, body)
117
118 self.assertEqual(headers['accept'], 'application/json')
119 self.assertEqual(headers['content-type'], 'application/json')
120
Joe Gregorio61d7e962011-02-22 22:52:07 -0500121 query_dict = parse_qs(query[1:])
Joe Gregoriofe695fb2010-08-30 12:04:04 -0400122 self.assertEqual(query_dict['foo'], ['1'])
123 self.assertEqual(query_dict['bar'], [u'\N{COMET}'.encode('utf-8')])
Joe Gregorio61d7e962011-02-22 22:52:07 -0500124 self.assertEqual(query_dict['baz'], ['fe', 'fi', 'fo', 'fum'])
125 self.assertTrue('qux' not in query_dict)
Joe Gregorio913e70d2010-11-05 15:38:23 -0400126 self.assertEqual(body, '{}')
Joe Gregoriofe695fb2010-08-30 12:04:04 -0400127
Joe Gregorioc5c5a372010-09-22 11:42:32 -0400128 def test_user_agent(self):
Joe Gregoriod433b2a2011-02-22 10:51:51 -0500129 model = JsonModel(data_wrapper=False)
Joe Gregorioc5c5a372010-09-22 11:42:32 -0400130
131 headers = {'user-agent': 'my-test-app/1.23.4'}
132 path_params = {}
133 query_params = {}
134 body = {}
135
136 headers, params, query, body = model.request(headers, path_params, query_params, body)
137
138 self.assertEqual(headers['user-agent'], 'my-test-app/1.23.4 google-api-python-client/1.0')
139
140 def test_bad_response(self):
Joe Gregoriod433b2a2011-02-22 10:51:51 -0500141 model = JsonModel(data_wrapper=False)
Joe Gregorioc5c5a372010-09-22 11:42:32 -0400142 resp = httplib2.Response({'status': '401'})
143 resp.reason = 'Unauthorized'
Joe Gregoriod4e14562011-01-04 09:51:45 -0500144 content = '{"error": {"message": "not authorized"}}'
Joe Gregorioc5c5a372010-09-22 11:42:32 -0400145
146 try:
147 content = model.response(resp, content)
148 self.fail('Should have thrown an exception')
149 except HttpError, e:
Joe Gregorio20b54fb2012-07-26 09:59:35 -0400150 self.assertTrue('not authorized' in str(e))
Joe Gregorioc5c5a372010-09-22 11:42:32 -0400151
152 resp['content-type'] = 'application/json'
153
154 try:
155 content = model.response(resp, content)
156 self.fail('Should have thrown an exception')
157 except HttpError, e:
158 self.assertTrue('not authorized' in str(e))
159
Joe Gregorioc5c5a372010-09-22 11:42:32 -0400160 def test_good_response(self):
Joe Gregoriod433b2a2011-02-22 10:51:51 -0500161 model = JsonModel(data_wrapper=True)
Joe Gregorioc5c5a372010-09-22 11:42:32 -0400162 resp = httplib2.Response({'status': '200'})
163 resp.reason = 'OK'
164 content = '{"data": "is good"}'
165
166 content = model.response(resp, content)
167 self.assertEqual(content, 'is good')
Joe Gregoriofe695fb2010-08-30 12:04:04 -0400168
Joe Gregorio78a508d2010-10-26 16:36:36 -0400169 def test_good_response_wo_data(self):
Joe Gregoriod433b2a2011-02-22 10:51:51 -0500170 model = JsonModel(data_wrapper=False)
Joe Gregorio78a508d2010-10-26 16:36:36 -0400171 resp = httplib2.Response({'status': '200'})
172 resp.reason = 'OK'
173 content = '{"foo": "is good"}'
174
175 content = model.response(resp, content)
176 self.assertEqual(content, {'foo': 'is good'})
177
178 def test_good_response_wo_data_str(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 = '"data goes here"'
183
184 content = model.response(resp, content)
185 self.assertEqual(content, 'data goes here')
186
Matt McDonald2a5f4132011-04-29 16:32:27 -0400187 def test_no_content_response(self):
188 model = JsonModel(data_wrapper=False)
189 resp = httplib2.Response({'status': '204'})
190 resp.reason = 'No Content'
191 content = ''
Joe Gregorio34044bc2011-03-07 16:58:33 -0500192
Matt McDonald2a5f4132011-04-29 16:32:27 -0400193 content = model.response(resp, content)
194 self.assertEqual(content, {})
Joe Gregorio34044bc2011-03-07 16:58:33 -0500195
Matt McDonald2a5f4132011-04-29 16:32:27 -0400196 def test_logging(self):
Joe Gregorio34044bc2011-03-07 16:58:33 -0500197 class MockLogging(object):
198 def __init__(self):
199 self.info_record = []
200 self.debug_record = []
201 def info(self, message, *args):
202 self.info_record.append(message % args)
203
204 def debug(self, message, *args):
205 self.debug_record.append(message % args)
206
207 class MockResponse(dict):
208 def __init__(self, items):
209 super(MockResponse, self).__init__()
210 self.status = items['status']
211 for key, value in items.iteritems():
212 self[key] = value
Matt McDonald2a5f4132011-04-29 16:32:27 -0400213 old_logging = apiclient.model.logging
Joe Gregorio34044bc2011-03-07 16:58:33 -0500214 apiclient.model.logging = MockLogging()
215 apiclient.model.FLAGS = copy.deepcopy(FLAGS)
Joe Gregorioafdf50b2011-03-08 09:41:52 -0500216 apiclient.model.FLAGS.dump_request_response = True
Matt McDonald2a5f4132011-04-29 16:32:27 -0400217 model = JsonModel()
Joe Gregorio34044bc2011-03-07 16:58:33 -0500218 request_body = {
219 'field1': 'value1',
220 'field2': 'value2'
221 }
222 body_string = model.request({}, {}, {}, request_body)[-1]
223 json_body = simplejson.loads(body_string)
224 self.assertEqual(request_body, json_body)
225
226 response = {'status': 200,
227 'response_field_1': 'response_value_1',
228 'response_field_2': 'response_value_2'}
229 response_body = model.response(MockResponse(response), body_string)
230 self.assertEqual(request_body, response_body)
Joe Gregorioafdf50b2011-03-08 09:41:52 -0500231 self.assertEqual(apiclient.model.logging.info_record[:2],
232 ['--request-start--',
233 '-headers-start-'])
234 self.assertTrue('response_field_1: response_value_1' in
235 apiclient.model.logging.info_record)
236 self.assertTrue('response_field_2: response_value_2' in
237 apiclient.model.logging.info_record)
Joe Gregorio34044bc2011-03-07 16:58:33 -0500238 self.assertEqual(simplejson.loads(apiclient.model.logging.info_record[-2]),
239 request_body)
240 self.assertEqual(apiclient.model.logging.info_record[-1],
241 '--response-end--')
Matt McDonald2a5f4132011-04-29 16:32:27 -0400242 apiclient.model.logging = old_logging
Joe Gregorio34044bc2011-03-07 16:58:33 -0500243
Ali Afshar81fde8e2012-10-23 11:14:28 -0700244 def test_no_data_wrapper_deserialize(self):
245 model = JsonModel(data_wrapper=False)
246 resp = httplib2.Response({'status': '200'})
247 resp.reason = 'OK'
248 content = '{"data": "is good"}'
249 content = model.response(resp, content)
250 self.assertEqual(content, {'data': 'is good'})
251
252 def test_data_wrapper_deserialize(self):
253 model = JsonModel(data_wrapper=True)
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, 'is good')
259
260 def test_data_wrapper_deserialize_nodata(self):
261 model = JsonModel(data_wrapper=True)
262 resp = httplib2.Response({'status': '200'})
263 resp.reason = 'OK'
264 content = '{"atad": "is good"}'
265 content = model.response(resp, content)
266 self.assertEqual(content, {'atad': 'is good'})
267
268
Joe Gregorio34044bc2011-03-07 16:58:33 -0500269
Joe Gregorioba9ea7f2010-08-19 15:49:04 -0400270if __name__ == '__main__':
271 unittest.main()