blob: 3b544b04f5e6eaac3a559722ae7a8569c3204673 [file] [log] [blame]
Joe Gregorioba9ea7f2010-08-19 15:49:04 -04001#!/usr/bin/python2.4
Joe Gregoriof863f7a2011-02-24 03:24:44 -05002# -*- coding: utf-8 -*-
Joe Gregorioba9ea7f2010-08-19 15:49:04 -04003#
Joe Gregorio6d5e94f2010-08-25 23:49:30 -04004# Copyright 2010 Google Inc.
5#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17
Joe Gregorioba9ea7f2010-08-19 15:49:04 -040018
19"""Discovery document tests
20
21Unit tests for objects created from discovery documents.
22"""
23
24__author__ = 'jcgregorio@google.com (Joe Gregorio)'
25
Joe Gregorioba9ea7f2010-08-19 15:49:04 -040026import httplib2
27import os
28import unittest
Joe Gregorio00cf1d92010-09-27 09:22:03 -040029import urlparse
Joe Gregorioa98733f2011-09-16 10:12:28 -040030
ade@google.comc5eb46f2010-09-27 23:35:39 +010031try:
32 from urlparse import parse_qs
33except ImportError:
34 from cgi import parse_qs
Joe Gregorio00cf1d92010-09-27 09:22:03 -040035
ade@google.com6a8c1cb2011-09-06 17:40:00 +010036from apiclient.discovery import build, build_from_document, key2param
Joe Gregoriocb8103d2011-02-11 23:20:52 -050037from apiclient.http import HttpMock
Joe Gregoriof4153422011-03-18 22:45:18 -040038from apiclient.http import tunnel_patch
39from apiclient.http import HttpMockSequence
Joe Gregorioc0e0fe92011-03-04 16:16:55 -050040from apiclient.errors import HttpError
Joe Gregorio49396552011-03-08 10:39:00 -050041from apiclient.errors import InvalidJsonError
Joe Gregoriofdf7c802011-06-30 12:33:38 -040042from apiclient.errors import MediaUploadSizeError
43from apiclient.errors import UnacceptableMimeTypeError
Joe Gregoriocb8103d2011-02-11 23:20:52 -050044
45
46DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
47
Joe Gregorioa98733f2011-09-16 10:12:28 -040048
Joe Gregoriocb8103d2011-02-11 23:20:52 -050049def datafile(filename):
50 return os.path.join(DATA_DIR, filename)
Joe Gregorioba9ea7f2010-08-19 15:49:04 -040051
52
Joe Gregorioc5c5a372010-09-22 11:42:32 -040053class Utilities(unittest.TestCase):
54 def test_key2param(self):
55 self.assertEqual('max_results', key2param('max-results'))
56 self.assertEqual('x007_bond', key2param('007-bond'))
57
58
Joe Gregorioc0e0fe92011-03-04 16:16:55 -050059class DiscoveryErrors(unittest.TestCase):
60
61 def test_failed_to_parse_discovery_json(self):
62 self.http = HttpMock(datafile('malformed.json'), {'status': '200'})
63 try:
Joe Gregorio7b70f432011-11-09 10:18:51 -050064 plus = build('plus', 'v1', self.http)
Joe Gregorioc0e0fe92011-03-04 16:16:55 -050065 self.fail("should have raised an exception over malformed JSON.")
Joe Gregorio49396552011-03-08 10:39:00 -050066 except InvalidJsonError:
67 pass
Joe Gregorioc0e0fe92011-03-04 16:16:55 -050068
69
ade@google.com6a8c1cb2011-09-06 17:40:00 +010070class DiscoveryFromDocument(unittest.TestCase):
Joe Gregorioa98733f2011-09-16 10:12:28 -040071
ade@google.com6a8c1cb2011-09-06 17:40:00 +010072 def test_can_build_from_local_document(self):
Joe Gregorio7b70f432011-11-09 10:18:51 -050073 discovery = file(datafile('plus.json')).read()
74 plus = build_from_document(discovery, base="https://www.googleapis.com/")
75 self.assertTrue(plus is not None)
Joe Gregorioa98733f2011-09-16 10:12:28 -040076
ade@google.com6a8c1cb2011-09-06 17:40:00 +010077 def test_building_with_base_remembers_base(self):
Joe Gregorio7b70f432011-11-09 10:18:51 -050078 discovery = file(datafile('plus.json')).read()
Joe Gregorioa98733f2011-09-16 10:12:28 -040079
ade@google.com6a8c1cb2011-09-06 17:40:00 +010080 base = "https://www.example.com/"
Joe Gregorio7b70f432011-11-09 10:18:51 -050081 plus = build_from_document(discovery, base=base)
82 self.assertEquals(base + "plus/v1/", plus._baseUrl)
ade@google.com6a8c1cb2011-09-06 17:40:00 +010083
84
Joe Gregorioa98733f2011-09-16 10:12:28 -040085class DiscoveryFromHttp(unittest.TestCase):
Joe Gregorio583d9e42011-09-16 15:54:15 -040086 def setUp(self):
Joe Bedafb463cb2011-09-19 17:39:49 -070087 self.old_environ = os.environ.copy()
Joe Gregorioa98733f2011-09-16 10:12:28 -040088
Joe Gregorio583d9e42011-09-16 15:54:15 -040089 def tearDown(self):
90 os.environ = self.old_environ
91
92 def test_userip_is_added_to_discovery_uri(self):
Joe Gregorioa98733f2011-09-16 10:12:28 -040093 # build() will raise an HttpError on a 400, use this to pick the request uri
94 # out of the raised exception.
Joe Gregorio583d9e42011-09-16 15:54:15 -040095 os.environ['REMOTE_ADDR'] = '10.0.0.1'
Joe Gregorioa98733f2011-09-16 10:12:28 -040096 try:
97 http = HttpMockSequence([
98 ({'status': '400'}, file(datafile('zoo.json'), 'r').read()),
99 ])
100 zoo = build('zoo', 'v1', http, developerKey='foo',
101 discoveryServiceUrl='http://example.com')
102 self.fail('Should have raised an exception.')
103 except HttpError, e:
Joe Gregorio583d9e42011-09-16 15:54:15 -0400104 self.assertEqual(e.uri, 'http://example.com?userIp=10.0.0.1')
Joe Gregorioa98733f2011-09-16 10:12:28 -0400105
Joe Gregorio583d9e42011-09-16 15:54:15 -0400106 def test_userip_missing_is_not_added_to_discovery_uri(self):
Joe Gregorioa98733f2011-09-16 10:12:28 -0400107 # build() will raise an HttpError on a 400, use this to pick the request uri
108 # out of the raised exception.
109 try:
110 http = HttpMockSequence([
111 ({'status': '400'}, file(datafile('zoo.json'), 'r').read()),
112 ])
113 zoo = build('zoo', 'v1', http, developerKey=None,
114 discoveryServiceUrl='http://example.com')
115 self.fail('Should have raised an exception.')
116 except HttpError, e:
117 self.assertEqual(e.uri, 'http://example.com')
118
119
Joe Gregorioba9ea7f2010-08-19 15:49:04 -0400120class Discovery(unittest.TestCase):
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400121
Joe Gregorioba9ea7f2010-08-19 15:49:04 -0400122 def test_method_error_checking(self):
Joe Gregorio7b70f432011-11-09 10:18:51 -0500123 self.http = HttpMock(datafile('plus.json'), {'status': '200'})
124 plus = build('plus', 'v1', self.http)
Joe Gregorioba9ea7f2010-08-19 15:49:04 -0400125
126 # Missing required parameters
127 try:
Joe Gregorio7b70f432011-11-09 10:18:51 -0500128 plus.activities().list()
Joe Gregorioba9ea7f2010-08-19 15:49:04 -0400129 self.fail()
130 except TypeError, e:
131 self.assertTrue('Missing' in str(e))
132
133 # Parameter doesn't match regex
134 try:
Joe Gregorio7b70f432011-11-09 10:18:51 -0500135 plus.activities().list(collection='not_a_collection_name', userId='me')
Joe Gregorioba9ea7f2010-08-19 15:49:04 -0400136 self.fail()
137 except TypeError, e:
Joe Gregorioca876e42011-02-22 19:39:42 -0500138 self.assertTrue('not an allowed value' in str(e))
Joe Gregorioba9ea7f2010-08-19 15:49:04 -0400139
140 # Unexpected parameter
141 try:
Joe Gregorio7b70f432011-11-09 10:18:51 -0500142 plus.activities().list(flubber=12)
Joe Gregorioba9ea7f2010-08-19 15:49:04 -0400143 self.fail()
144 except TypeError, e:
145 self.assertTrue('unexpected' in str(e))
146
Joe Gregoriobee86832011-02-22 10:00:19 -0500147 def _check_query_types(self, request):
148 parsed = urlparse.urlparse(request.uri)
149 q = parse_qs(parsed[4])
150 self.assertEqual(q['q'], ['foo'])
151 self.assertEqual(q['i'], ['1'])
152 self.assertEqual(q['n'], ['1.0'])
153 self.assertEqual(q['b'], ['false'])
154 self.assertEqual(q['a'], ['[1, 2, 3]'])
155 self.assertEqual(q['o'], ['{\'a\': 1}'])
156 self.assertEqual(q['e'], ['bar'])
157
158 def test_type_coercion(self):
Joe Gregoriof4153422011-03-18 22:45:18 -0400159 http = HttpMock(datafile('zoo.json'), {'status': '200'})
160 zoo = build('zoo', 'v1', http)
Joe Gregoriobee86832011-02-22 10:00:19 -0500161
Joe Gregorioa98733f2011-09-16 10:12:28 -0400162 request = zoo.query(
163 q="foo", i=1.0, n=1.0, b=0, a=[1,2,3], o={'a':1}, e='bar')
Joe Gregoriobee86832011-02-22 10:00:19 -0500164 self._check_query_types(request)
Joe Gregorioa98733f2011-09-16 10:12:28 -0400165 request = zoo.query(
166 q="foo", i=1, n=1, b=False, a=[1,2,3], o={'a':1}, e='bar')
Joe Gregoriobee86832011-02-22 10:00:19 -0500167 self._check_query_types(request)
Joe Gregoriof863f7a2011-02-24 03:24:44 -0500168
Joe Gregorioa98733f2011-09-16 10:12:28 -0400169 request = zoo.query(
170 q="foo", i="1", n="1", b="", a=[1,2,3], o={'a':1}, e='bar')
Joe Gregoriobee86832011-02-22 10:00:19 -0500171 self._check_query_types(request)
172
Joe Gregorio13217952011-02-22 15:37:38 -0500173 def test_optional_stack_query_parameters(self):
Joe Gregoriof4153422011-03-18 22:45:18 -0400174 http = HttpMock(datafile('zoo.json'), {'status': '200'})
175 zoo = build('zoo', 'v1', http)
176 request = zoo.query(trace='html', fields='description')
Joe Gregorio13217952011-02-22 15:37:38 -0500177
Joe Gregorioca876e42011-02-22 19:39:42 -0500178 parsed = urlparse.urlparse(request.uri)
179 q = parse_qs(parsed[4])
180 self.assertEqual(q['trace'], ['html'])
Joe Gregoriof4153422011-03-18 22:45:18 -0400181 self.assertEqual(q['fields'], ['description'])
182
183 def test_patch(self):
184 http = HttpMock(datafile('zoo.json'), {'status': '200'})
185 zoo = build('zoo', 'v1', http)
186 request = zoo.animals().patch(name='lion', body='{"description": "foo"}')
187
188 self.assertEqual(request.method, 'PATCH')
189
190 def test_tunnel_patch(self):
191 http = HttpMockSequence([
192 ({'status': '200'}, file(datafile('zoo.json'), 'r').read()),
193 ({'status': '200'}, 'echo_request_headers_as_json'),
194 ])
195 http = tunnel_patch(http)
196 zoo = build('zoo', 'v1', http)
Joe Gregorioa98733f2011-09-16 10:12:28 -0400197 resp = zoo.animals().patch(
198 name='lion', body='{"description": "foo"}').execute()
Joe Gregoriof4153422011-03-18 22:45:18 -0400199
200 self.assertTrue('x-http-method-override' in resp)
Joe Gregorioca876e42011-02-22 19:39:42 -0500201
Joe Gregorio7b70f432011-11-09 10:18:51 -0500202 def test_plus_resources(self):
203 self.http = HttpMock(datafile('plus.json'), {'status': '200'})
204 plus = build('plus', 'v1', self.http)
205 self.assertTrue(getattr(plus, 'activities'))
206 self.assertTrue(getattr(plus, 'people'))
Joe Gregorioc5c5a372010-09-22 11:42:32 -0400207
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400208 def test_full_featured(self):
209 # Zoo should exercise all discovery facets
210 # and should also have no future.json file.
Joe Gregoriocb8103d2011-02-11 23:20:52 -0500211 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400212 zoo = build('zoo', 'v1', self.http)
213 self.assertTrue(getattr(zoo, 'animals'))
Joe Gregoriof863f7a2011-02-24 03:24:44 -0500214
Joe Gregoriof4153422011-03-18 22:45:18 -0400215 request = zoo.animals().list(name='bat', projection="full")
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400216 parsed = urlparse.urlparse(request.uri)
217 q = parse_qs(parsed[4])
218 self.assertEqual(q['name'], ['bat'])
Joe Gregoriof4153422011-03-18 22:45:18 -0400219 self.assertEqual(q['projection'], ['full'])
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400220
Joe Gregorio3fada332011-01-07 17:07:45 -0500221 def test_nested_resources(self):
Joe Gregoriocb8103d2011-02-11 23:20:52 -0500222 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio3fada332011-01-07 17:07:45 -0500223 zoo = build('zoo', 'v1', self.http)
224 self.assertTrue(getattr(zoo, 'animals'))
225 request = zoo.my().favorites().list(max_results="5")
226 parsed = urlparse.urlparse(request.uri)
227 q = parse_qs(parsed[4])
228 self.assertEqual(q['max-results'], ['5'])
229
Joe Gregoriod92897c2011-07-07 11:44:56 -0400230 def test_methods_with_reserved_names(self):
231 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
232 zoo = build('zoo', 'v1', self.http)
233 self.assertTrue(getattr(zoo, 'animals'))
234 request = zoo.global_().print_().assert_(max_results="5")
235 parsed = urlparse.urlparse(request.uri)
236 self.assertEqual(parsed[2], '/zoo/global/print/assert')
237
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500238 def test_top_level_functions(self):
Joe Gregoriocb8103d2011-02-11 23:20:52 -0500239 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500240 zoo = build('zoo', 'v1', self.http)
241 self.assertTrue(getattr(zoo, 'query'))
242 request = zoo.query(q="foo")
243 parsed = urlparse.urlparse(request.uri)
244 q = parse_qs(parsed[4])
245 self.assertEqual(q['q'], ['foo'])
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400246
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400247 def test_simple_media_uploads(self):
248 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
249 zoo = build('zoo', 'v1', self.http)
250 doc = getattr(zoo.animals().insert, '__doc__')
251 self.assertTrue('media_body' in doc)
252
Joe Gregorio84d3c1f2011-07-25 10:39:45 -0400253 def test_simple_media_upload_no_max_size_provided(self):
254 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
255 zoo = build('zoo', 'v1', self.http)
256 request = zoo.animals().crossbreed(media_body=datafile('small.png'))
257 self.assertEquals('image/png', request.headers['content-type'])
258 self.assertEquals('PNG', request.body[1:4])
259
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400260 def test_simple_media_raise_correct_exceptions(self):
261 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
262 zoo = build('zoo', 'v1', self.http)
263
264 try:
265 zoo.animals().insert(media_body=datafile('smiley.png'))
266 self.fail("should throw exception if media is too large.")
267 except MediaUploadSizeError:
268 pass
269
270 try:
271 zoo.animals().insert(media_body=datafile('small.jpg'))
272 self.fail("should throw exception if mimetype is unacceptable.")
273 except UnacceptableMimeTypeError:
274 pass
275
276 def test_simple_media_good_upload(self):
277 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
278 zoo = build('zoo', 'v1', self.http)
279
280 request = zoo.animals().insert(media_body=datafile('small.png'))
281 self.assertEquals('image/png', request.headers['content-type'])
282 self.assertEquals('PNG', request.body[1:4])
283
284 def test_multipart_media_raise_correct_exceptions(self):
285 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
286 zoo = build('zoo', 'v1', self.http)
287
288 try:
289 zoo.animals().insert(media_body=datafile('smiley.png'), body={})
290 self.fail("should throw exception if media is too large.")
291 except MediaUploadSizeError:
292 pass
293
294 try:
295 zoo.animals().insert(media_body=datafile('small.jpg'), body={})
296 self.fail("should throw exception if mimetype is unacceptable.")
297 except UnacceptableMimeTypeError:
298 pass
299
300 def test_multipart_media_good_upload(self):
301 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
302 zoo = build('zoo', 'v1', self.http)
303
304 request = zoo.animals().insert(media_body=datafile('small.png'), body={})
Joe Gregorioa98733f2011-09-16 10:12:28 -0400305 self.assertTrue(request.headers['content-type'].startswith(
306 'multipart/related'))
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400307 self.assertEquals('--==', request.body[0:4])
308
309 def test_media_capable_method_without_media(self):
310 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
311 zoo = build('zoo', 'v1', self.http)
312
313 request = zoo.animals().insert(body={})
314 self.assertTrue(request.headers['content-type'], 'application/json')
Joe Gregorioc5c5a372010-09-22 11:42:32 -0400315
316class Next(unittest.TestCase):
Joe Gregorio00cf1d92010-09-27 09:22:03 -0400317
Joe Gregorio3c676f92011-07-25 10:38:14 -0400318 def test_next_successful_none_on_no_next_page_token(self):
319 self.http = HttpMock(datafile('tasks.json'), {'status': '200'})
320 tasks = build('tasks', 'v1', self.http)
321 request = tasks.tasklists().list()
322 self.assertEqual(None, tasks.tasklists().list_next(request, {}))
323
324 def test_next_successful_with_next_page_token(self):
325 self.http = HttpMock(datafile('tasks.json'), {'status': '200'})
326 tasks = build('tasks', 'v1', self.http)
327 request = tasks.tasklists().list()
Joe Gregorioa98733f2011-09-16 10:12:28 -0400328 next_request = tasks.tasklists().list_next(
329 request, {'nextPageToken': '123abc'})
Joe Gregorio3c676f92011-07-25 10:38:14 -0400330 parsed = list(urlparse.urlparse(next_request.uri))
331 q = parse_qs(parsed[4])
332 self.assertEqual(q['pageToken'][0], '123abc')
333
Joe Gregorio555f33c2011-08-19 14:56:07 -0400334 def test_next_with_method_with_no_properties(self):
335 self.http = HttpMock(datafile('latitude.json'), {'status': '200'})
336 service = build('latitude', 'v1', self.http)
337 request = service.currentLocation().get()
Joe Gregorio00cf1d92010-09-27 09:22:03 -0400338
Joe Gregorioa98733f2011-09-16 10:12:28 -0400339
Joe Gregorioba9ea7f2010-08-19 15:49:04 -0400340if __name__ == '__main__':
341 unittest.main()