blob: b2f69c505e5eb74cbf7d4b22ee52d0515a3a35f9 [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 Gregorio910b9b12012-06-12 09:36:30 -040030import StringIO
31
Joe Gregorioa98733f2011-09-16 10:12:28 -040032
ade@google.comc5eb46f2010-09-27 23:35:39 +010033try:
34 from urlparse import parse_qs
35except ImportError:
36 from cgi import parse_qs
Joe Gregorio00cf1d92010-09-27 09:22:03 -040037
ade@google.com6a8c1cb2011-09-06 17:40:00 +010038from apiclient.discovery import build, build_from_document, key2param
Joe Gregorioc0e0fe92011-03-04 16:16:55 -050039from apiclient.errors import HttpError
Joe Gregorio49396552011-03-08 10:39:00 -050040from apiclient.errors import InvalidJsonError
Joe Gregoriofdf7c802011-06-30 12:33:38 -040041from apiclient.errors import MediaUploadSizeError
Joe Gregoriod0bd3882011-11-22 09:49:47 -050042from apiclient.errors import ResumableUploadError
Joe Gregoriofdf7c802011-06-30 12:33:38 -040043from apiclient.errors import UnacceptableMimeTypeError
Joe Gregoriod0bd3882011-11-22 09:49:47 -050044from apiclient.http import HttpMock
45from apiclient.http import HttpMockSequence
46from apiclient.http import MediaFileUpload
Joe Gregorio910b9b12012-06-12 09:36:30 -040047from apiclient.http import MediaIoBaseUpload
Joe Gregoriod0bd3882011-11-22 09:49:47 -050048from apiclient.http import MediaUploadProgress
49from apiclient.http import tunnel_patch
Joe Gregorio910b9b12012-06-12 09:36:30 -040050from oauth2client.anyjson import simplejson
Joe Gregoriocb8103d2011-02-11 23:20:52 -050051
52DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
53
Joe Gregorioa98733f2011-09-16 10:12:28 -040054
Joe Gregoriocb8103d2011-02-11 23:20:52 -050055def datafile(filename):
56 return os.path.join(DATA_DIR, filename)
Joe Gregorioba9ea7f2010-08-19 15:49:04 -040057
58
Joe Gregorioc5c5a372010-09-22 11:42:32 -040059class Utilities(unittest.TestCase):
60 def test_key2param(self):
61 self.assertEqual('max_results', key2param('max-results'))
62 self.assertEqual('x007_bond', key2param('007-bond'))
63
64
Joe Gregorioc0e0fe92011-03-04 16:16:55 -050065class DiscoveryErrors(unittest.TestCase):
66
Joe Gregorio68a8cfe2012-08-03 16:17:40 -040067 def test_tests_should_be_run_with_strict_positional_enforcement(self):
68 try:
69 plus = build('plus', 'v1', None)
70 self.fail("should have raised a TypeError exception over missing http=.")
71 except TypeError:
72 pass
73
Joe Gregorioc0e0fe92011-03-04 16:16:55 -050074 def test_failed_to_parse_discovery_json(self):
75 self.http = HttpMock(datafile('malformed.json'), {'status': '200'})
76 try:
Joe Gregorio68a8cfe2012-08-03 16:17:40 -040077 plus = build('plus', 'v1', http=self.http)
Joe Gregorioc0e0fe92011-03-04 16:16:55 -050078 self.fail("should have raised an exception over malformed JSON.")
Joe Gregorio49396552011-03-08 10:39:00 -050079 except InvalidJsonError:
80 pass
Joe Gregorioc0e0fe92011-03-04 16:16:55 -050081
82
ade@google.com6a8c1cb2011-09-06 17:40:00 +010083class DiscoveryFromDocument(unittest.TestCase):
Joe Gregorioa98733f2011-09-16 10:12:28 -040084
ade@google.com6a8c1cb2011-09-06 17:40:00 +010085 def test_can_build_from_local_document(self):
Joe Gregorio7b70f432011-11-09 10:18:51 -050086 discovery = file(datafile('plus.json')).read()
87 plus = build_from_document(discovery, base="https://www.googleapis.com/")
88 self.assertTrue(plus is not None)
Joe Gregorioa98733f2011-09-16 10:12:28 -040089
ade@google.com6a8c1cb2011-09-06 17:40:00 +010090 def test_building_with_base_remembers_base(self):
Joe Gregorio7b70f432011-11-09 10:18:51 -050091 discovery = file(datafile('plus.json')).read()
Joe Gregorioa98733f2011-09-16 10:12:28 -040092
ade@google.com6a8c1cb2011-09-06 17:40:00 +010093 base = "https://www.example.com/"
Joe Gregorio7b70f432011-11-09 10:18:51 -050094 plus = build_from_document(discovery, base=base)
Joe Gregorioa2838152012-07-16 11:52:17 -040095 self.assertEquals("https://www.googleapis.com/plus/v1/", plus._baseUrl)
ade@google.com6a8c1cb2011-09-06 17:40:00 +010096
97
Joe Gregorioa98733f2011-09-16 10:12:28 -040098class DiscoveryFromHttp(unittest.TestCase):
Joe Gregorio583d9e42011-09-16 15:54:15 -040099 def setUp(self):
Joe Bedafb463cb2011-09-19 17:39:49 -0700100 self.old_environ = os.environ.copy()
Joe Gregorioa98733f2011-09-16 10:12:28 -0400101
Joe Gregorio583d9e42011-09-16 15:54:15 -0400102 def tearDown(self):
103 os.environ = self.old_environ
104
105 def test_userip_is_added_to_discovery_uri(self):
Joe Gregorioa98733f2011-09-16 10:12:28 -0400106 # build() will raise an HttpError on a 400, use this to pick the request uri
107 # out of the raised exception.
Joe Gregorio583d9e42011-09-16 15:54:15 -0400108 os.environ['REMOTE_ADDR'] = '10.0.0.1'
Joe Gregorioa98733f2011-09-16 10:12:28 -0400109 try:
110 http = HttpMockSequence([
111 ({'status': '400'}, file(datafile('zoo.json'), 'r').read()),
112 ])
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400113 zoo = build('zoo', 'v1', http=http, developerKey='foo',
Joe Gregorioa98733f2011-09-16 10:12:28 -0400114 discoveryServiceUrl='http://example.com')
115 self.fail('Should have raised an exception.')
116 except HttpError, e:
Joe Gregorio583d9e42011-09-16 15:54:15 -0400117 self.assertEqual(e.uri, 'http://example.com?userIp=10.0.0.1')
Joe Gregorioa98733f2011-09-16 10:12:28 -0400118
Joe Gregorio583d9e42011-09-16 15:54:15 -0400119 def test_userip_missing_is_not_added_to_discovery_uri(self):
Joe Gregorioa98733f2011-09-16 10:12:28 -0400120 # build() will raise an HttpError on a 400, use this to pick the request uri
121 # out of the raised exception.
122 try:
123 http = HttpMockSequence([
124 ({'status': '400'}, file(datafile('zoo.json'), 'r').read()),
125 ])
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400126 zoo = build('zoo', 'v1', http=http, developerKey=None,
Joe Gregorioa98733f2011-09-16 10:12:28 -0400127 discoveryServiceUrl='http://example.com')
128 self.fail('Should have raised an exception.')
129 except HttpError, e:
130 self.assertEqual(e.uri, 'http://example.com')
131
132
Joe Gregorioba9ea7f2010-08-19 15:49:04 -0400133class Discovery(unittest.TestCase):
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400134
Joe Gregorioba9ea7f2010-08-19 15:49:04 -0400135 def test_method_error_checking(self):
Joe Gregorio7b70f432011-11-09 10:18:51 -0500136 self.http = HttpMock(datafile('plus.json'), {'status': '200'})
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400137 plus = build('plus', 'v1', http=self.http)
Joe Gregorioba9ea7f2010-08-19 15:49:04 -0400138
139 # Missing required parameters
140 try:
Joe Gregorio7b70f432011-11-09 10:18:51 -0500141 plus.activities().list()
Joe Gregorioba9ea7f2010-08-19 15:49:04 -0400142 self.fail()
143 except TypeError, e:
144 self.assertTrue('Missing' in str(e))
145
Joe Gregorio2467afa2012-06-20 12:21:25 -0400146 # Missing required parameters even if supplied as None.
147 try:
148 plus.activities().list(collection=None, userId=None)
149 self.fail()
150 except TypeError, e:
151 self.assertTrue('Missing' in str(e))
152
Joe Gregorioba9ea7f2010-08-19 15:49:04 -0400153 # Parameter doesn't match regex
154 try:
Joe Gregorio7b70f432011-11-09 10:18:51 -0500155 plus.activities().list(collection='not_a_collection_name', userId='me')
Joe Gregorioba9ea7f2010-08-19 15:49:04 -0400156 self.fail()
157 except TypeError, e:
Joe Gregorioca876e42011-02-22 19:39:42 -0500158 self.assertTrue('not an allowed value' in str(e))
Joe Gregorioba9ea7f2010-08-19 15:49:04 -0400159
160 # Unexpected parameter
161 try:
Joe Gregorio7b70f432011-11-09 10:18:51 -0500162 plus.activities().list(flubber=12)
Joe Gregorioba9ea7f2010-08-19 15:49:04 -0400163 self.fail()
164 except TypeError, e:
165 self.assertTrue('unexpected' in str(e))
166
Joe Gregoriobee86832011-02-22 10:00:19 -0500167 def _check_query_types(self, request):
168 parsed = urlparse.urlparse(request.uri)
169 q = parse_qs(parsed[4])
170 self.assertEqual(q['q'], ['foo'])
171 self.assertEqual(q['i'], ['1'])
172 self.assertEqual(q['n'], ['1.0'])
173 self.assertEqual(q['b'], ['false'])
174 self.assertEqual(q['a'], ['[1, 2, 3]'])
175 self.assertEqual(q['o'], ['{\'a\': 1}'])
176 self.assertEqual(q['e'], ['bar'])
177
178 def test_type_coercion(self):
Joe Gregoriof4153422011-03-18 22:45:18 -0400179 http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400180 zoo = build('zoo', 'v1', http=http)
Joe Gregoriobee86832011-02-22 10:00:19 -0500181
Joe Gregorioa98733f2011-09-16 10:12:28 -0400182 request = zoo.query(
183 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 -0500184 self._check_query_types(request)
Joe Gregorioa98733f2011-09-16 10:12:28 -0400185 request = zoo.query(
186 q="foo", i=1, n=1, b=False, a=[1,2,3], o={'a':1}, e='bar')
Joe Gregoriobee86832011-02-22 10:00:19 -0500187 self._check_query_types(request)
Joe Gregoriof863f7a2011-02-24 03:24:44 -0500188
Joe Gregorioa98733f2011-09-16 10:12:28 -0400189 request = zoo.query(
Craig Citro1e742822012-03-01 12:59:22 -0800190 q="foo", i="1", n="1", b="", a=[1,2,3], o={'a':1}, e='bar', er='two')
Joe Gregorio6804c7a2011-11-18 14:30:32 -0500191
192 request = zoo.query(
Craig Citro1e742822012-03-01 12:59:22 -0800193 q="foo", i="1", n="1", b="", a=[1,2,3], o={'a':1}, e='bar',
194 er=['one', 'three'], rr=['foo', 'bar'])
Joe Gregoriobee86832011-02-22 10:00:19 -0500195 self._check_query_types(request)
196
Craig Citro1e742822012-03-01 12:59:22 -0800197 # Five is right out.
Joe Gregorio20c26e52012-03-02 15:58:31 -0500198 self.assertRaises(TypeError, zoo.query, er=['one', 'five'])
Craig Citro1e742822012-03-01 12:59:22 -0800199
Joe Gregorio13217952011-02-22 15:37:38 -0500200 def test_optional_stack_query_parameters(self):
Joe Gregoriof4153422011-03-18 22:45:18 -0400201 http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400202 zoo = build('zoo', 'v1', http=http)
Joe Gregoriof4153422011-03-18 22:45:18 -0400203 request = zoo.query(trace='html', fields='description')
Joe Gregorio13217952011-02-22 15:37:38 -0500204
Joe Gregorioca876e42011-02-22 19:39:42 -0500205 parsed = urlparse.urlparse(request.uri)
206 q = parse_qs(parsed[4])
207 self.assertEqual(q['trace'], ['html'])
Joe Gregoriof4153422011-03-18 22:45:18 -0400208 self.assertEqual(q['fields'], ['description'])
209
Joe Gregorio2467afa2012-06-20 12:21:25 -0400210 def test_string_params_value_of_none_get_dropped(self):
Joe Gregorio4b4002f2012-06-14 15:41:01 -0400211 http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400212 zoo = build('zoo', 'v1', http=http)
Joe Gregorio2467afa2012-06-20 12:21:25 -0400213 request = zoo.query(trace=None, fields='description')
214
215 parsed = urlparse.urlparse(request.uri)
216 q = parse_qs(parsed[4])
217 self.assertFalse('trace' in q)
Joe Gregorio4b4002f2012-06-14 15:41:01 -0400218
Joe Gregorioe08a1662011-12-07 09:48:22 -0500219 def test_model_added_query_parameters(self):
220 http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400221 zoo = build('zoo', 'v1', http=http)
Joe Gregorioe08a1662011-12-07 09:48:22 -0500222 request = zoo.animals().get(name='Lion')
223
224 parsed = urlparse.urlparse(request.uri)
225 q = parse_qs(parsed[4])
226 self.assertEqual(q['alt'], ['json'])
227 self.assertEqual(request.headers['accept'], 'application/json')
228
229 def test_fallback_to_raw_model(self):
230 http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400231 zoo = build('zoo', 'v1', http=http)
Joe Gregorioe08a1662011-12-07 09:48:22 -0500232 request = zoo.animals().getmedia(name='Lion')
233
234 parsed = urlparse.urlparse(request.uri)
235 q = parse_qs(parsed[4])
236 self.assertTrue('alt' not in q)
237 self.assertEqual(request.headers['accept'], '*/*')
238
Joe Gregoriof4153422011-03-18 22:45:18 -0400239 def test_patch(self):
240 http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400241 zoo = build('zoo', 'v1', http=http)
Joe Gregoriof4153422011-03-18 22:45:18 -0400242 request = zoo.animals().patch(name='lion', body='{"description": "foo"}')
243
244 self.assertEqual(request.method, 'PATCH')
245
246 def test_tunnel_patch(self):
247 http = HttpMockSequence([
248 ({'status': '200'}, file(datafile('zoo.json'), 'r').read()),
249 ({'status': '200'}, 'echo_request_headers_as_json'),
250 ])
251 http = tunnel_patch(http)
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400252 zoo = build('zoo', 'v1', http=http)
Joe Gregorioa98733f2011-09-16 10:12:28 -0400253 resp = zoo.animals().patch(
254 name='lion', body='{"description": "foo"}').execute()
Joe Gregoriof4153422011-03-18 22:45:18 -0400255
256 self.assertTrue('x-http-method-override' in resp)
Joe Gregorioca876e42011-02-22 19:39:42 -0500257
Joe Gregorio7b70f432011-11-09 10:18:51 -0500258 def test_plus_resources(self):
259 self.http = HttpMock(datafile('plus.json'), {'status': '200'})
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400260 plus = build('plus', 'v1', http=self.http)
Joe Gregorio7b70f432011-11-09 10:18:51 -0500261 self.assertTrue(getattr(plus, 'activities'))
262 self.assertTrue(getattr(plus, 'people'))
Joe Gregorioc5c5a372010-09-22 11:42:32 -0400263
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400264 def test_full_featured(self):
265 # Zoo should exercise all discovery facets
266 # and should also have no future.json file.
Joe Gregoriocb8103d2011-02-11 23:20:52 -0500267 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400268 zoo = build('zoo', 'v1', http=self.http)
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400269 self.assertTrue(getattr(zoo, 'animals'))
Joe Gregoriof863f7a2011-02-24 03:24:44 -0500270
Joe Gregoriof4153422011-03-18 22:45:18 -0400271 request = zoo.animals().list(name='bat', projection="full")
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400272 parsed = urlparse.urlparse(request.uri)
273 q = parse_qs(parsed[4])
274 self.assertEqual(q['name'], ['bat'])
Joe Gregoriof4153422011-03-18 22:45:18 -0400275 self.assertEqual(q['projection'], ['full'])
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400276
Joe Gregorio3fada332011-01-07 17:07:45 -0500277 def test_nested_resources(self):
Joe Gregoriocb8103d2011-02-11 23:20:52 -0500278 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400279 zoo = build('zoo', 'v1', http=self.http)
Joe Gregorio3fada332011-01-07 17:07:45 -0500280 self.assertTrue(getattr(zoo, 'animals'))
281 request = zoo.my().favorites().list(max_results="5")
282 parsed = urlparse.urlparse(request.uri)
283 q = parse_qs(parsed[4])
284 self.assertEqual(q['max-results'], ['5'])
285
Joe Gregoriod92897c2011-07-07 11:44:56 -0400286 def test_methods_with_reserved_names(self):
287 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400288 zoo = build('zoo', 'v1', http=self.http)
Joe Gregoriod92897c2011-07-07 11:44:56 -0400289 self.assertTrue(getattr(zoo, 'animals'))
290 request = zoo.global_().print_().assert_(max_results="5")
291 parsed = urlparse.urlparse(request.uri)
Joe Gregorioa2838152012-07-16 11:52:17 -0400292 self.assertEqual(parsed[2], '/zoo/v1/global/print/assert')
Joe Gregoriod92897c2011-07-07 11:44:56 -0400293
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500294 def test_top_level_functions(self):
Joe Gregoriocb8103d2011-02-11 23:20:52 -0500295 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400296 zoo = build('zoo', 'v1', http=self.http)
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500297 self.assertTrue(getattr(zoo, 'query'))
298 request = zoo.query(q="foo")
299 parsed = urlparse.urlparse(request.uri)
300 q = parse_qs(parsed[4])
301 self.assertEqual(q['q'], ['foo'])
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400302
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400303 def test_simple_media_uploads(self):
304 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400305 zoo = build('zoo', 'v1', http=self.http)
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400306 doc = getattr(zoo.animals().insert, '__doc__')
307 self.assertTrue('media_body' in doc)
308
Joe Gregorio84d3c1f2011-07-25 10:39:45 -0400309 def test_simple_media_upload_no_max_size_provided(self):
310 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400311 zoo = build('zoo', 'v1', http=self.http)
Joe Gregorio84d3c1f2011-07-25 10:39:45 -0400312 request = zoo.animals().crossbreed(media_body=datafile('small.png'))
313 self.assertEquals('image/png', request.headers['content-type'])
314 self.assertEquals('PNG', request.body[1:4])
315
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400316 def test_simple_media_raise_correct_exceptions(self):
317 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400318 zoo = build('zoo', 'v1', http=self.http)
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400319
320 try:
321 zoo.animals().insert(media_body=datafile('smiley.png'))
322 self.fail("should throw exception if media is too large.")
323 except MediaUploadSizeError:
324 pass
325
326 try:
327 zoo.animals().insert(media_body=datafile('small.jpg'))
328 self.fail("should throw exception if mimetype is unacceptable.")
329 except UnacceptableMimeTypeError:
330 pass
331
332 def test_simple_media_good_upload(self):
333 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400334 zoo = build('zoo', 'v1', http=self.http)
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400335
336 request = zoo.animals().insert(media_body=datafile('small.png'))
337 self.assertEquals('image/png', request.headers['content-type'])
338 self.assertEquals('PNG', request.body[1:4])
Joe Gregoriode860442012-03-02 15:55:52 -0500339 self.assertEqual(
Joe Gregorioa2838152012-07-16 11:52:17 -0400340 'https://www.googleapis.com/upload/zoo/v1/animals?uploadType=media&alt=json',
Joe Gregoriode860442012-03-02 15:55:52 -0500341 request.uri)
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400342
343 def test_multipart_media_raise_correct_exceptions(self):
344 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400345 zoo = build('zoo', 'v1', http=self.http)
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400346
347 try:
348 zoo.animals().insert(media_body=datafile('smiley.png'), body={})
349 self.fail("should throw exception if media is too large.")
350 except MediaUploadSizeError:
351 pass
352
353 try:
354 zoo.animals().insert(media_body=datafile('small.jpg'), body={})
355 self.fail("should throw exception if mimetype is unacceptable.")
356 except UnacceptableMimeTypeError:
357 pass
358
359 def test_multipart_media_good_upload(self):
360 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400361 zoo = build('zoo', 'v1', http=self.http)
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400362
363 request = zoo.animals().insert(media_body=datafile('small.png'), body={})
Joe Gregorioa98733f2011-09-16 10:12:28 -0400364 self.assertTrue(request.headers['content-type'].startswith(
365 'multipart/related'))
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400366 self.assertEquals('--==', request.body[0:4])
Joe Gregoriode860442012-03-02 15:55:52 -0500367 self.assertEqual(
Joe Gregorioa2838152012-07-16 11:52:17 -0400368 'https://www.googleapis.com/upload/zoo/v1/animals?uploadType=multipart&alt=json',
Joe Gregoriode860442012-03-02 15:55:52 -0500369 request.uri)
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400370
371 def test_media_capable_method_without_media(self):
372 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400373 zoo = build('zoo', 'v1', http=self.http)
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400374
375 request = zoo.animals().insert(body={})
376 self.assertTrue(request.headers['content-type'], 'application/json')
Joe Gregorioc5c5a372010-09-22 11:42:32 -0400377
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500378 def test_resumable_multipart_media_good_upload(self):
379 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400380 zoo = build('zoo', 'v1', http=self.http)
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500381
382 media_upload = MediaFileUpload(datafile('small.png'), resumable=True)
383 request = zoo.animals().insert(media_body=media_upload, body={})
384 self.assertTrue(request.headers['content-type'].startswith(
Joe Gregorio945be3e2012-01-27 17:01:06 -0500385 'application/json'))
386 self.assertEquals('{"data": {}}', request.body)
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500387 self.assertEquals(media_upload, request.resumable)
388
389 self.assertEquals('image/png', request.resumable.mimetype())
390
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500391 self.assertNotEquals(request.body, None)
392 self.assertEquals(request.resumable_uri, None)
393
394 http = HttpMockSequence([
395 ({'status': '200',
396 'location': 'http://upload.example.com'}, ''),
397 ({'status': '308',
398 'location': 'http://upload.example.com/2',
399 'range': '0-12'}, ''),
400 ({'status': '308',
401 'location': 'http://upload.example.com/3',
Joe Gregorio945be3e2012-01-27 17:01:06 -0500402 'range': '0-%d' % (media_upload.size() - 2)}, ''),
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500403 ({'status': '200'}, '{"foo": "bar"}'),
404 ])
405
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400406 status, body = request.next_chunk(http=http)
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500407 self.assertEquals(None, body)
408 self.assertTrue(isinstance(status, MediaUploadProgress))
409 self.assertEquals(13, status.resumable_progress)
410
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500411 # Two requests should have been made and the resumable_uri should have been
412 # updated for each one.
413 self.assertEquals(request.resumable_uri, 'http://upload.example.com/2')
414
415 self.assertEquals(media_upload, request.resumable)
416 self.assertEquals(13, request.resumable_progress)
417
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400418 status, body = request.next_chunk(http=http)
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500419 self.assertEquals(request.resumable_uri, 'http://upload.example.com/3')
Joe Gregorio945be3e2012-01-27 17:01:06 -0500420 self.assertEquals(media_upload.size()-1, request.resumable_progress)
421 self.assertEquals('{"data": {}}', request.body)
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500422
423 # Final call to next_chunk should complete the upload.
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400424 status, body = request.next_chunk(http=http)
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500425 self.assertEquals(body, {"foo": "bar"})
426 self.assertEquals(status, None)
427
428
429 def test_resumable_media_good_upload(self):
430 """Not a multipart upload."""
431 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400432 zoo = build('zoo', 'v1', http=self.http)
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500433
434 media_upload = MediaFileUpload(datafile('small.png'), resumable=True)
435 request = zoo.animals().insert(media_body=media_upload, body=None)
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500436 self.assertEquals(media_upload, request.resumable)
437
438 self.assertEquals('image/png', request.resumable.mimetype())
439
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500440 self.assertEquals(request.body, None)
441 self.assertEquals(request.resumable_uri, None)
442
443 http = HttpMockSequence([
444 ({'status': '200',
445 'location': 'http://upload.example.com'}, ''),
446 ({'status': '308',
447 'location': 'http://upload.example.com/2',
448 'range': '0-12'}, ''),
449 ({'status': '308',
450 'location': 'http://upload.example.com/3',
Joe Gregorio945be3e2012-01-27 17:01:06 -0500451 'range': '0-%d' % (media_upload.size() - 2)}, ''),
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500452 ({'status': '200'}, '{"foo": "bar"}'),
453 ])
454
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400455 status, body = request.next_chunk(http=http)
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500456 self.assertEquals(None, body)
457 self.assertTrue(isinstance(status, MediaUploadProgress))
458 self.assertEquals(13, status.resumable_progress)
459
460 # Two requests should have been made and the resumable_uri should have been
461 # updated for each one.
462 self.assertEquals(request.resumable_uri, 'http://upload.example.com/2')
463
464 self.assertEquals(media_upload, request.resumable)
465 self.assertEquals(13, request.resumable_progress)
466
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400467 status, body = request.next_chunk(http=http)
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500468 self.assertEquals(request.resumable_uri, 'http://upload.example.com/3')
Joe Gregorio945be3e2012-01-27 17:01:06 -0500469 self.assertEquals(media_upload.size()-1, request.resumable_progress)
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500470 self.assertEquals(request.body, None)
471
472 # Final call to next_chunk should complete the upload.
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400473 status, body = request.next_chunk(http=http)
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500474 self.assertEquals(body, {"foo": "bar"})
475 self.assertEquals(status, None)
476
477
478 def test_resumable_media_good_upload_from_execute(self):
479 """Not a multipart upload."""
480 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400481 zoo = build('zoo', 'v1', http=self.http)
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500482
483 media_upload = MediaFileUpload(datafile('small.png'), resumable=True)
484 request = zoo.animals().insert(media_body=media_upload, body=None)
Joe Gregoriode860442012-03-02 15:55:52 -0500485 self.assertEqual(
Joe Gregorioa2838152012-07-16 11:52:17 -0400486 'https://www.googleapis.com/upload/zoo/v1/animals?uploadType=resumable&alt=json',
Joe Gregoriode860442012-03-02 15:55:52 -0500487 request.uri)
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500488
489 http = HttpMockSequence([
490 ({'status': '200',
491 'location': 'http://upload.example.com'}, ''),
492 ({'status': '308',
493 'location': 'http://upload.example.com/2',
494 'range': '0-12'}, ''),
495 ({'status': '308',
496 'location': 'http://upload.example.com/3',
Joe Gregorio945be3e2012-01-27 17:01:06 -0500497 'range': '0-%d' % media_upload.size()}, ''),
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500498 ({'status': '200'}, '{"foo": "bar"}'),
499 ])
500
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400501 body = request.execute(http=http)
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500502 self.assertEquals(body, {"foo": "bar"})
503
504 def test_resumable_media_fail_unknown_response_code_first_request(self):
505 """Not a multipart upload."""
506 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400507 zoo = build('zoo', 'v1', http=self.http)
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500508
509 media_upload = MediaFileUpload(datafile('small.png'), resumable=True)
510 request = zoo.animals().insert(media_body=media_upload, body=None)
511
512 http = HttpMockSequence([
513 ({'status': '400',
514 'location': 'http://upload.example.com'}, ''),
515 ])
516
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400517 self.assertRaises(ResumableUploadError, request.execute, http=http)
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500518
519 def test_resumable_media_fail_unknown_response_code_subsequent_request(self):
520 """Not a multipart upload."""
521 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400522 zoo = build('zoo', 'v1', http=self.http)
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500523
524 media_upload = MediaFileUpload(datafile('small.png'), resumable=True)
525 request = zoo.animals().insert(media_body=media_upload, body=None)
526
527 http = HttpMockSequence([
528 ({'status': '200',
529 'location': 'http://upload.example.com'}, ''),
530 ({'status': '400'}, ''),
531 ])
532
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400533 self.assertRaises(HttpError, request.execute, http=http)
Joe Gregorio910b9b12012-06-12 09:36:30 -0400534 self.assertTrue(request._in_error_state)
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500535
Joe Gregorio910b9b12012-06-12 09:36:30 -0400536 http = HttpMockSequence([
537 ({'status': '308',
538 'range': '0-5'}, ''),
539 ({'status': '308',
540 'range': '0-6'}, ''),
541 ])
542
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400543 status, body = request.next_chunk(http=http)
Joe Gregorio910b9b12012-06-12 09:36:30 -0400544 self.assertEquals(status.resumable_progress, 7,
545 'Should have first checked length and then tried to PUT more.')
546 self.assertFalse(request._in_error_state)
547
548 # Put it back in an error state.
549 http = HttpMockSequence([
550 ({'status': '400'}, ''),
551 ])
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400552 self.assertRaises(HttpError, request.execute, http=http)
Joe Gregorio910b9b12012-06-12 09:36:30 -0400553 self.assertTrue(request._in_error_state)
554
555 # Pretend the last request that 400'd actually succeeded.
556 http = HttpMockSequence([
557 ({'status': '200'}, '{"foo": "bar"}'),
558 ])
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400559 status, body = request.next_chunk(http=http)
Joe Gregorio910b9b12012-06-12 09:36:30 -0400560 self.assertEqual(body, {'foo': 'bar'})
561
562 def test_resumable_media_handle_uploads_of_unknown_size(self):
563 http = HttpMockSequence([
564 ({'status': '200',
565 'location': 'http://upload.example.com'}, ''),
566 ({'status': '200'}, 'echo_request_headers_as_json'),
567 ])
568
569 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400570 zoo = build('zoo', 'v1', http=self.http)
Joe Gregorio910b9b12012-06-12 09:36:30 -0400571
Joe Gregorio4a2c29f2012-07-12 12:52:47 -0400572 fd = StringIO.StringIO('data goes here')
Joe Gregorio910b9b12012-06-12 09:36:30 -0400573
574 # Create an upload that doesn't know the full size of the media.
575 upload = MediaIoBaseUpload(
Joe Gregorio4a2c29f2012-07-12 12:52:47 -0400576 fd=fd, mimetype='image/png', chunksize=10, resumable=True)
Joe Gregorio910b9b12012-06-12 09:36:30 -0400577
578 request = zoo.animals().insert(media_body=upload, body=None)
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400579 status, body = request.next_chunk(http=http)
Joe Gregorio44454e42012-06-15 08:38:53 -0400580 self.assertEqual(body, {'Content-Range': 'bytes 0-9/*'},
581 'Should be 10 out of * bytes.')
582
583 def test_resumable_media_handle_uploads_of_unknown_size_eof(self):
584 http = HttpMockSequence([
585 ({'status': '200',
586 'location': 'http://upload.example.com'}, ''),
587 ({'status': '200'}, 'echo_request_headers_as_json'),
588 ])
589
590 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400591 zoo = build('zoo', 'v1', http=self.http)
Joe Gregorio44454e42012-06-15 08:38:53 -0400592
Joe Gregorio4a2c29f2012-07-12 12:52:47 -0400593 fd = StringIO.StringIO('data goes here')
Joe Gregorio44454e42012-06-15 08:38:53 -0400594
595 # Create an upload that doesn't know the full size of the media.
596 upload = MediaIoBaseUpload(
Joe Gregorio4a2c29f2012-07-12 12:52:47 -0400597 fd=fd, mimetype='image/png', chunksize=15, resumable=True)
Joe Gregorio44454e42012-06-15 08:38:53 -0400598
599 request = zoo.animals().insert(media_body=upload, body=None)
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400600 status, body = request.next_chunk(http=http)
Joe Gregorio44454e42012-06-15 08:38:53 -0400601 self.assertEqual(body, {'Content-Range': 'bytes 0-13/14'})
Joe Gregorio910b9b12012-06-12 09:36:30 -0400602
603 def test_resumable_media_handle_resume_of_upload_of_unknown_size(self):
604 http = HttpMockSequence([
605 ({'status': '200',
606 'location': 'http://upload.example.com'}, ''),
607 ({'status': '400'}, ''),
608 ])
609
610 self.http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400611 zoo = build('zoo', 'v1', http=self.http)
Joe Gregorio910b9b12012-06-12 09:36:30 -0400612
613 # Create an upload that doesn't know the full size of the media.
Joe Gregorio4a2c29f2012-07-12 12:52:47 -0400614 fd = StringIO.StringIO('data goes here')
Joe Gregorio910b9b12012-06-12 09:36:30 -0400615
616 upload = MediaIoBaseUpload(
Joe Gregorio4a2c29f2012-07-12 12:52:47 -0400617 fd=fd, mimetype='image/png', chunksize=500, resumable=True)
Joe Gregorio910b9b12012-06-12 09:36:30 -0400618
619 request = zoo.animals().insert(media_body=upload, body=None)
620
621 # Put it in an error state.
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400622 self.assertRaises(HttpError, request.next_chunk, http=http)
Joe Gregorio910b9b12012-06-12 09:36:30 -0400623
624 http = HttpMockSequence([
625 ({'status': '400',
626 'range': '0-5'}, 'echo_request_headers_as_json'),
627 ])
628 try:
629 # Should resume the upload by first querying the status of the upload.
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400630 request.next_chunk(http=http)
Joe Gregorio910b9b12012-06-12 09:36:30 -0400631 except HttpError, e:
632 expected = {
633 'Content-Range': 'bytes */*',
634 'content-length': '0'
635 }
636 self.assertEqual(expected, simplejson.loads(e.content),
637 'Should send an empty body when requesting the current upload status.')
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500638
Joe Gregorio708388c2012-06-15 13:43:04 -0400639
Joe Gregorioc5c5a372010-09-22 11:42:32 -0400640class Next(unittest.TestCase):
Joe Gregorio00cf1d92010-09-27 09:22:03 -0400641
Joe Gregorio3c676f92011-07-25 10:38:14 -0400642 def test_next_successful_none_on_no_next_page_token(self):
643 self.http = HttpMock(datafile('tasks.json'), {'status': '200'})
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400644 tasks = build('tasks', 'v1', http=self.http)
Joe Gregorio3c676f92011-07-25 10:38:14 -0400645 request = tasks.tasklists().list()
646 self.assertEqual(None, tasks.tasklists().list_next(request, {}))
647
648 def test_next_successful_with_next_page_token(self):
649 self.http = HttpMock(datafile('tasks.json'), {'status': '200'})
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400650 tasks = build('tasks', 'v1', http=self.http)
Joe Gregorio3c676f92011-07-25 10:38:14 -0400651 request = tasks.tasklists().list()
Joe Gregorioa98733f2011-09-16 10:12:28 -0400652 next_request = tasks.tasklists().list_next(
653 request, {'nextPageToken': '123abc'})
Joe Gregorio3c676f92011-07-25 10:38:14 -0400654 parsed = list(urlparse.urlparse(next_request.uri))
655 q = parse_qs(parsed[4])
656 self.assertEqual(q['pageToken'][0], '123abc')
657
Joe Gregorio555f33c2011-08-19 14:56:07 -0400658 def test_next_with_method_with_no_properties(self):
659 self.http = HttpMock(datafile('latitude.json'), {'status': '200'})
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400660 service = build('latitude', 'v1', http=self.http)
Joe Gregorio555f33c2011-08-19 14:56:07 -0400661 request = service.currentLocation().get()
Joe Gregorio00cf1d92010-09-27 09:22:03 -0400662
Joe Gregorioa98733f2011-09-16 10:12:28 -0400663
Joe Gregorio708388c2012-06-15 13:43:04 -0400664class MediaGet(unittest.TestCase):
665
666 def test_get_media(self):
667 http = HttpMock(datafile('zoo.json'), {'status': '200'})
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400668 zoo = build('zoo', 'v1', http=http)
Joe Gregorio708388c2012-06-15 13:43:04 -0400669 request = zoo.animals().get_media(name='Lion')
670
671 parsed = urlparse.urlparse(request.uri)
672 q = parse_qs(parsed[4])
673 self.assertEqual(q['alt'], ['media'])
674 self.assertEqual(request.headers['accept'], '*/*')
675
676 http = HttpMockSequence([
677 ({'status': '200'}, 'standing in for media'),
678 ])
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400679 response = request.execute(http=http)
Joe Gregorio708388c2012-06-15 13:43:04 -0400680 self.assertEqual('standing in for media', response)
681
682
Joe Gregorioba9ea7f2010-08-19 15:49:04 -0400683if __name__ == '__main__':
684 unittest.main()