blob: 7ab2f985454d79382fe9f60ba20f0db4cffad939 [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 Gregorio34044bc2011-03-07 16:58:33 -050031from apiclient.anyjson import simplejson
Joe Gregorioe1de4162011-02-23 11:30:29 -050032from apiclient.errors import HttpError
Joe Gregorio34044bc2011-03-07 16:58:33 -050033from apiclient.model import JsonModel
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:
150 self.assertTrue('Unauthorized' in str(e))
151
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
160
161 def test_good_response(self):
Joe Gregoriod433b2a2011-02-22 10:51:51 -0500162 model = JsonModel(data_wrapper=True)
Joe Gregorioc5c5a372010-09-22 11:42:32 -0400163 resp = httplib2.Response({'status': '200'})
164 resp.reason = 'OK'
165 content = '{"data": "is good"}'
166
167 content = model.response(resp, content)
168 self.assertEqual(content, 'is good')
Joe Gregoriofe695fb2010-08-30 12:04:04 -0400169
Joe Gregorio78a508d2010-10-26 16:36:36 -0400170 def test_good_response_wo_data(self):
Joe Gregoriod433b2a2011-02-22 10:51:51 -0500171 model = JsonModel(data_wrapper=False)
Joe Gregorio78a508d2010-10-26 16:36:36 -0400172 resp = httplib2.Response({'status': '200'})
173 resp.reason = 'OK'
174 content = '{"foo": "is good"}'
175
176 content = model.response(resp, content)
177 self.assertEqual(content, {'foo': 'is good'})
178
179 def test_good_response_wo_data_str(self):
Joe Gregoriod433b2a2011-02-22 10:51:51 -0500180 model = JsonModel(data_wrapper=False)
Joe Gregorio78a508d2010-10-26 16:36:36 -0400181 resp = httplib2.Response({'status': '200'})
182 resp.reason = 'OK'
183 content = '"data goes here"'
184
185 content = model.response(resp, content)
186 self.assertEqual(content, 'data goes here')
187
Matt McDonald2a5f4132011-04-29 16:32:27 -0400188 def test_no_content_response(self):
189 model = JsonModel(data_wrapper=False)
190 resp = httplib2.Response({'status': '204'})
191 resp.reason = 'No Content'
192 content = ''
Joe Gregorio34044bc2011-03-07 16:58:33 -0500193
Matt McDonald2a5f4132011-04-29 16:32:27 -0400194 content = model.response(resp, content)
195 self.assertEqual(content, {})
Joe Gregorio34044bc2011-03-07 16:58:33 -0500196
Matt McDonald2a5f4132011-04-29 16:32:27 -0400197 def test_logging(self):
Joe Gregorio34044bc2011-03-07 16:58:33 -0500198 class MockLogging(object):
199 def __init__(self):
200 self.info_record = []
201 self.debug_record = []
202 def info(self, message, *args):
203 self.info_record.append(message % args)
204
205 def debug(self, message, *args):
206 self.debug_record.append(message % args)
207
208 class MockResponse(dict):
209 def __init__(self, items):
210 super(MockResponse, self).__init__()
211 self.status = items['status']
212 for key, value in items.iteritems():
213 self[key] = value
Matt McDonald2a5f4132011-04-29 16:32:27 -0400214 old_logging = apiclient.model.logging
Joe Gregorio34044bc2011-03-07 16:58:33 -0500215 apiclient.model.logging = MockLogging()
216 apiclient.model.FLAGS = copy.deepcopy(FLAGS)
Joe Gregorioafdf50b2011-03-08 09:41:52 -0500217 apiclient.model.FLAGS.dump_request_response = True
Matt McDonald2a5f4132011-04-29 16:32:27 -0400218 model = JsonModel()
Joe Gregorio34044bc2011-03-07 16:58:33 -0500219 request_body = {
220 'field1': 'value1',
221 'field2': 'value2'
222 }
223 body_string = model.request({}, {}, {}, request_body)[-1]
224 json_body = simplejson.loads(body_string)
225 self.assertEqual(request_body, json_body)
226
227 response = {'status': 200,
228 'response_field_1': 'response_value_1',
229 'response_field_2': 'response_value_2'}
230 response_body = model.response(MockResponse(response), body_string)
231 self.assertEqual(request_body, response_body)
Joe Gregorioafdf50b2011-03-08 09:41:52 -0500232 self.assertEqual(apiclient.model.logging.info_record[:2],
233 ['--request-start--',
234 '-headers-start-'])
235 self.assertTrue('response_field_1: response_value_1' in
236 apiclient.model.logging.info_record)
237 self.assertTrue('response_field_2: response_value_2' in
238 apiclient.model.logging.info_record)
Joe Gregorio34044bc2011-03-07 16:58:33 -0500239 self.assertEqual(simplejson.loads(apiclient.model.logging.info_record[-2]),
240 request_body)
241 self.assertEqual(apiclient.model.logging.info_record[-1],
242 '--response-end--')
Matt McDonald2a5f4132011-04-29 16:32:27 -0400243 apiclient.model.logging = old_logging
Joe Gregorio34044bc2011-03-07 16:58:33 -0500244
245
Joe Gregorioba9ea7f2010-08-19 15:49:04 -0400246if __name__ == '__main__':
247 unittest.main()