blob: 606796ef0bd5fa61808289b4221a6823b31d6d58 [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 Gregorio6804c7a2011-11-18 14:30:32 -0500171
172 request = zoo.query(
173 q="foo", i="1", n="1", b="", a=[1,2,3], o={'a':1}, e='bar', rr=['foo',
174 'bar'])
Joe Gregoriobee86832011-02-22 10:00:19 -0500175 self._check_query_types(request)
176
Joe Gregorio13217952011-02-22 15:37:38 -0500177 def test_optional_stack_query_parameters(self):
Joe Gregoriof4153422011-03-18 22:45:18 -0400178 http = HttpMock(datafile('zoo.json'), {'status': '200'})
179 zoo = build('zoo', 'v1', http)
180 request = zoo.query(trace='html', fields='description')
Joe Gregorio13217952011-02-22 15:37:38 -0500181
Joe Gregorioca876e42011-02-22 19:39:42 -0500182 parsed = urlparse.urlparse(request.uri)
183 q = parse_qs(parsed[4])
184 self.assertEqual(q['trace'], ['html'])
Joe Gregoriof4153422011-03-18 22:45:18 -0400185 self.assertEqual(q['fields'], ['description'])
186
187 def test_patch(self):
188 http = HttpMock(datafile('zoo.json'), {'status': '200'})
189 zoo = build('zoo', 'v1', http)
190 request = zoo.animals().patch(name='lion', body='{"description": "foo"}')
191
192 self.assertEqual(request.method, 'PATCH')
193
194 def test_tunnel_patch(self):
195 http = HttpMockSequence([
196 ({'status': '200'}, file(datafile('zoo.json'), 'r').read()),
197 ({'status': '200'}, 'echo_request_headers_as_json'),
198 ])
199 http = tunnel_patch(http)
200 zoo = build('zoo', 'v1', http)
Joe Gregorioa98733f2011-09-16 10:12:28 -0400201 resp = zoo.animals().patch(
202 name='lion', body='{"description": "foo"}').execute()
Joe Gregoriof4153422011-03-18 22:45:18 -0400203
204 self.assertTrue('x-http-method-override' in resp)
Joe Gregorioca876e42011-02-22 19:39:42 -0500205
Joe Gregorio7b70f432011-11-09 10:18:51 -0500206 def test_plus_resources(self):
207 self.http = HttpMock(datafile('plus.json'), {'status': '200'})
208 plus = build('plus', 'v1', self.http)
209 self.assertTrue(getattr(plus, 'activities'))
210 self.assertTrue(getattr(plus, 'people'))
Joe Gregorioc5c5a372010-09-22 11:42:32 -0400211
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400212 def test_full_featured(self):
213 # Zoo should exercise all discovery facets
214 # and should also have no future.json file.
Joe Gregoriocb8103d2011-02-11 23:20:52 -0500215 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400216 zoo = build('zoo', 'v1', self.http)
217 self.assertTrue(getattr(zoo, 'animals'))
Joe Gregoriof863f7a2011-02-24 03:24:44 -0500218
Joe Gregoriof4153422011-03-18 22:45:18 -0400219 request = zoo.animals().list(name='bat', projection="full")
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400220 parsed = urlparse.urlparse(request.uri)
221 q = parse_qs(parsed[4])
222 self.assertEqual(q['name'], ['bat'])
Joe Gregoriof4153422011-03-18 22:45:18 -0400223 self.assertEqual(q['projection'], ['full'])
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400224
Joe Gregorio3fada332011-01-07 17:07:45 -0500225 def test_nested_resources(self):
Joe Gregoriocb8103d2011-02-11 23:20:52 -0500226 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio3fada332011-01-07 17:07:45 -0500227 zoo = build('zoo', 'v1', self.http)
228 self.assertTrue(getattr(zoo, 'animals'))
229 request = zoo.my().favorites().list(max_results="5")
230 parsed = urlparse.urlparse(request.uri)
231 q = parse_qs(parsed[4])
232 self.assertEqual(q['max-results'], ['5'])
233
Joe Gregoriod92897c2011-07-07 11:44:56 -0400234 def test_methods_with_reserved_names(self):
235 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
236 zoo = build('zoo', 'v1', self.http)
237 self.assertTrue(getattr(zoo, 'animals'))
238 request = zoo.global_().print_().assert_(max_results="5")
239 parsed = urlparse.urlparse(request.uri)
240 self.assertEqual(parsed[2], '/zoo/global/print/assert')
241
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500242 def test_top_level_functions(self):
Joe Gregoriocb8103d2011-02-11 23:20:52 -0500243 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500244 zoo = build('zoo', 'v1', self.http)
245 self.assertTrue(getattr(zoo, 'query'))
246 request = zoo.query(q="foo")
247 parsed = urlparse.urlparse(request.uri)
248 q = parse_qs(parsed[4])
249 self.assertEqual(q['q'], ['foo'])
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400250
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400251 def test_simple_media_uploads(self):
252 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
253 zoo = build('zoo', 'v1', self.http)
254 doc = getattr(zoo.animals().insert, '__doc__')
255 self.assertTrue('media_body' in doc)
256
Joe Gregorio84d3c1f2011-07-25 10:39:45 -0400257 def test_simple_media_upload_no_max_size_provided(self):
258 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
259 zoo = build('zoo', 'v1', self.http)
260 request = zoo.animals().crossbreed(media_body=datafile('small.png'))
261 self.assertEquals('image/png', request.headers['content-type'])
262 self.assertEquals('PNG', request.body[1:4])
263
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400264 def test_simple_media_raise_correct_exceptions(self):
265 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
266 zoo = build('zoo', 'v1', self.http)
267
268 try:
269 zoo.animals().insert(media_body=datafile('smiley.png'))
270 self.fail("should throw exception if media is too large.")
271 except MediaUploadSizeError:
272 pass
273
274 try:
275 zoo.animals().insert(media_body=datafile('small.jpg'))
276 self.fail("should throw exception if mimetype is unacceptable.")
277 except UnacceptableMimeTypeError:
278 pass
279
280 def test_simple_media_good_upload(self):
281 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
282 zoo = build('zoo', 'v1', self.http)
283
284 request = zoo.animals().insert(media_body=datafile('small.png'))
285 self.assertEquals('image/png', request.headers['content-type'])
286 self.assertEquals('PNG', request.body[1:4])
287
288 def test_multipart_media_raise_correct_exceptions(self):
289 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
290 zoo = build('zoo', 'v1', self.http)
291
292 try:
293 zoo.animals().insert(media_body=datafile('smiley.png'), body={})
294 self.fail("should throw exception if media is too large.")
295 except MediaUploadSizeError:
296 pass
297
298 try:
299 zoo.animals().insert(media_body=datafile('small.jpg'), body={})
300 self.fail("should throw exception if mimetype is unacceptable.")
301 except UnacceptableMimeTypeError:
302 pass
303
304 def test_multipart_media_good_upload(self):
305 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
306 zoo = build('zoo', 'v1', self.http)
307
308 request = zoo.animals().insert(media_body=datafile('small.png'), body={})
Joe Gregorioa98733f2011-09-16 10:12:28 -0400309 self.assertTrue(request.headers['content-type'].startswith(
310 'multipart/related'))
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400311 self.assertEquals('--==', request.body[0:4])
312
313 def test_media_capable_method_without_media(self):
314 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
315 zoo = build('zoo', 'v1', self.http)
316
317 request = zoo.animals().insert(body={})
318 self.assertTrue(request.headers['content-type'], 'application/json')
Joe Gregorioc5c5a372010-09-22 11:42:32 -0400319
320class Next(unittest.TestCase):
Joe Gregorio00cf1d92010-09-27 09:22:03 -0400321
Joe Gregorio3c676f92011-07-25 10:38:14 -0400322 def test_next_successful_none_on_no_next_page_token(self):
323 self.http = HttpMock(datafile('tasks.json'), {'status': '200'})
324 tasks = build('tasks', 'v1', self.http)
325 request = tasks.tasklists().list()
326 self.assertEqual(None, tasks.tasklists().list_next(request, {}))
327
328 def test_next_successful_with_next_page_token(self):
329 self.http = HttpMock(datafile('tasks.json'), {'status': '200'})
330 tasks = build('tasks', 'v1', self.http)
331 request = tasks.tasklists().list()
Joe Gregorioa98733f2011-09-16 10:12:28 -0400332 next_request = tasks.tasklists().list_next(
333 request, {'nextPageToken': '123abc'})
Joe Gregorio3c676f92011-07-25 10:38:14 -0400334 parsed = list(urlparse.urlparse(next_request.uri))
335 q = parse_qs(parsed[4])
336 self.assertEqual(q['pageToken'][0], '123abc')
337
Joe Gregorio555f33c2011-08-19 14:56:07 -0400338 def test_next_with_method_with_no_properties(self):
339 self.http = HttpMock(datafile('latitude.json'), {'status': '200'})
340 service = build('latitude', 'v1', self.http)
341 request = service.currentLocation().get()
Joe Gregorio00cf1d92010-09-27 09:22:03 -0400342
Joe Gregorioa98733f2011-09-16 10:12:28 -0400343
Joe Gregorioba9ea7f2010-08-19 15:49:04 -0400344if __name__ == '__main__':
345 unittest.main()