blob: 6774abd538e5958a1dda8c72f1d3d8565428f768 [file] [log] [blame]
Joe Gregorio432f17e2011-05-22 23:18:00 -04001#!/usr/bin/python2.4
2#
3# 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.
16
17
18"""Discovery document tests
19
20Unit tests for objects created from discovery documents.
21"""
22
23__author__ = 'jcgregorio@google.com (Joe Gregorio)'
24
JacobMoshenko8e905102011-06-20 09:53:10 -040025import base64
Joe Gregorioe84c9442012-03-12 08:45:57 -040026import datetime
Joe Gregorio432f17e2011-05-22 23:18:00 -040027import httplib2
Joe Gregorio08cdcb82012-03-14 00:09:33 -040028import os
Joe Gregoriod84d6b82012-02-28 14:53:00 -050029import time
Joe Gregorio432f17e2011-05-22 23:18:00 -040030import unittest
31import urlparse
32
33try:
34 from urlparse import parse_qs
35except ImportError:
36 from cgi import parse_qs
37
Joe Gregorio8b4c1732011-12-06 11:28:29 -050038import dev_appserver
39dev_appserver.fix_sys_path()
Joe Gregorio17774972012-03-01 11:11:59 -050040import webapp2
Joe Gregorio8b4c1732011-12-06 11:28:29 -050041
JacobMoshenko8e905102011-06-20 09:53:10 -040042from apiclient.http import HttpMockSequence
43from google.appengine.api import apiproxy_stub
44from google.appengine.api import apiproxy_stub_map
Joe Gregoriod84d6b82012-02-28 14:53:00 -050045from google.appengine.api import app_identity
Joe Gregorioe84c9442012-03-12 08:45:57 -040046from google.appengine.api import memcache
Joe Gregorio08cdcb82012-03-14 00:09:33 -040047from google.appengine.api import users
Joe Gregoriod84d6b82012-02-28 14:53:00 -050048from google.appengine.api.memcache import memcache_stub
Joe Gregorioe84c9442012-03-12 08:45:57 -040049from google.appengine.ext import db
JacobMoshenko8e905102011-06-20 09:53:10 -040050from google.appengine.ext import testbed
Joe Gregoriod84d6b82012-02-28 14:53:00 -050051from google.appengine.runtime import apiproxy_errors
Joe Gregorio549230c2012-01-11 10:38:05 -050052from oauth2client.anyjson import simplejson
Joe Gregorioc29aaa92012-07-16 16:16:31 -040053from oauth2client.clientsecrets import _loadfile
JacobMoshenko8e905102011-06-20 09:53:10 -040054from oauth2client.appengine import AppAssertionCredentials
Joe Gregorioe84c9442012-03-12 08:45:57 -040055from oauth2client.appengine import CredentialsModel
Joe Gregorio4fbde1c2012-07-11 14:47:39 -040056from oauth2client.appengine import FlowProperty
Joe Gregorio432f17e2011-05-22 23:18:00 -040057from oauth2client.appengine import OAuth2Decorator
Joe Gregorioe84c9442012-03-12 08:45:57 -040058from oauth2client.appengine import StorageByKeyName
Joe Gregorio08cdcb82012-03-14 00:09:33 -040059from oauth2client.appengine import oauth2decorator_from_clientsecrets
Joe Gregorio549230c2012-01-11 10:38:05 -050060from oauth2client.client import AccessTokenRefreshError
Joe Gregorio08cdcb82012-03-14 00:09:33 -040061from oauth2client.client import Credentials
Joe Gregorio549230c2012-01-11 10:38:05 -050062from oauth2client.client import FlowExchangeError
Joe Gregorioe84c9442012-03-12 08:45:57 -040063from oauth2client.client import OAuth2Credentials
Joe Gregorio08cdcb82012-03-14 00:09:33 -040064from oauth2client.client import flow_from_clientsecrets
JacobMoshenko8e905102011-06-20 09:53:10 -040065from webtest import TestApp
Joe Gregorio432f17e2011-05-22 23:18:00 -040066
Joe Gregorio4fbde1c2012-07-11 14:47:39 -040067
Joe Gregorio08cdcb82012-03-14 00:09:33 -040068DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
69
70
71def datafile(filename):
72 return os.path.join(DATA_DIR, filename)
73
74
Joe Gregorioc29aaa92012-07-16 16:16:31 -040075def load_and_cache(existing_file, fakename, cache_mock):
76 client_type, client_info = _loadfile(datafile(existing_file))
77 cache_mock.cache[fakename] = {client_type: client_info}
78
79
80class CacheMock(object):
81 def __init__(self):
82 self.cache = {}
83
84 def get(self, key, namespace=''):
85 # ignoring namespace for easier testing
86 return self.cache.get(key, None)
87
88 def set(self, key, value, namespace=''):
89 # ignoring namespace for easier testing
90 self.cache[key] = value
91
92
Joe Gregorio432f17e2011-05-22 23:18:00 -040093class UserMock(object):
94 """Mock the app engine user service"""
JacobMoshenko8e905102011-06-20 09:53:10 -040095
Joe Gregorio08cdcb82012-03-14 00:09:33 -040096 def __call__(self):
97 return self
98
Joe Gregorio432f17e2011-05-22 23:18:00 -040099 def user_id(self):
100 return 'foo_user'
101
102
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400103class UserNotLoggedInMock(object):
104 """Mock the app engine user service"""
105
106 def __call__(self):
107 return None
108
109
Joe Gregorio432f17e2011-05-22 23:18:00 -0400110class Http2Mock(object):
111 """Mock httplib2.Http"""
112 status = 200
113 content = {
114 'access_token': 'foo_access_token',
115 'refresh_token': 'foo_refresh_token',
JacobMoshenko8e905102011-06-20 09:53:10 -0400116 'expires_in': 3600,
Joe Gregorio432f17e2011-05-22 23:18:00 -0400117 }
118
119 def request(self, token_uri, method, body, headers, *args, **kwargs):
120 self.body = body
121 self.headers = headers
122 return (self, simplejson.dumps(self.content))
123
124
JacobMoshenko8e905102011-06-20 09:53:10 -0400125class TestAppAssertionCredentials(unittest.TestCase):
126 account_name = "service_account_name@appspot.com"
127 signature = "signature"
128
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500129
JacobMoshenko8e905102011-06-20 09:53:10 -0400130 class AppIdentityStubImpl(apiproxy_stub.APIProxyStub):
131
132 def __init__(self):
133 super(TestAppAssertionCredentials.AppIdentityStubImpl, self).__init__(
134 'app_identity_service')
135
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500136 def _Dynamic_GetAccessToken(self, request, response):
137 response.set_access_token('a_token_123')
138 response.set_expiration_time(time.time() + 1800)
JacobMoshenko8e905102011-06-20 09:53:10 -0400139
JacobMoshenko8e905102011-06-20 09:53:10 -0400140
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500141 class ErroringAppIdentityStubImpl(apiproxy_stub.APIProxyStub):
142
143 def __init__(self):
144 super(TestAppAssertionCredentials.ErroringAppIdentityStubImpl, self).__init__(
145 'app_identity_service')
146
147 def _Dynamic_GetAccessToken(self, request, response):
148 raise app_identity.BackendDeadlineExceeded()
149
150 def test_raise_correct_type_of_exception(self):
151 app_identity_stub = self.ErroringAppIdentityStubImpl()
152 apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
JacobMoshenko8e905102011-06-20 09:53:10 -0400153 apiproxy_stub_map.apiproxy.RegisterStub("app_identity_service",
154 app_identity_stub)
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500155 apiproxy_stub_map.apiproxy.RegisterStub(
156 'memcache', memcache_stub.MemcacheServiceStub())
JacobMoshenko8e905102011-06-20 09:53:10 -0400157
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500158 scope = "http://www.googleapis.com/scope"
159 try:
160 credentials = AppAssertionCredentials(scope)
161 http = httplib2.Http()
162 credentials.refresh(http)
163 self.fail('Should have raised an AccessTokenRefreshError')
164 except AccessTokenRefreshError:
165 pass
JacobMoshenko8e905102011-06-20 09:53:10 -0400166
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500167 def test_get_access_token_on_refresh(self):
168 app_identity_stub = self.AppIdentityStubImpl()
169 apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
170 apiproxy_stub_map.apiproxy.RegisterStub("app_identity_service",
171 app_identity_stub)
172 apiproxy_stub_map.apiproxy.RegisterStub(
173 'memcache', memcache_stub.MemcacheServiceStub())
JacobMoshenko8e905102011-06-20 09:53:10 -0400174
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400175 scope = ["http://www.googleapis.com/scope"]
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500176 credentials = AppAssertionCredentials(scope)
177 http = httplib2.Http()
178 credentials.refresh(http)
179 self.assertEqual('a_token_123', credentials.access_token)
JacobMoshenko8e905102011-06-20 09:53:10 -0400180
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400181 json = credentials.to_json()
182 credentials = Credentials.new_from_json(json)
183 self.assertEqual(scope[0], credentials.scope)
184
185
186class TestFlowModel(db.Model):
187 flow = FlowProperty()
188
189
190class FlowPropertyTest(unittest.TestCase):
191
192 def setUp(self):
193 self.testbed = testbed.Testbed()
194 self.testbed.activate()
195 self.testbed.init_datastore_v3_stub()
196
197 def tearDown(self):
198 self.testbed.deactivate()
199
200 def test_flow_get_put(self):
201 instance = TestFlowModel(
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400202 flow=flow_from_clientsecrets(datafile('client_secrets.json'), 'foo',
203 redirect_uri='oob'),
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400204 key_name='foo'
205 )
206 instance.put()
207 retrieved = TestFlowModel.get_by_key_name('foo')
208
209 self.assertEqual('foo_client_id', retrieved.flow.client_id)
210
JacobMoshenko8e905102011-06-20 09:53:10 -0400211
Joe Gregorioe84c9442012-03-12 08:45:57 -0400212def _http_request(*args, **kwargs):
213 resp = httplib2.Response({'status': '200'})
214 content = simplejson.dumps({'access_token': 'bar'})
215
216 return resp, content
217
218
219class StorageByKeyNameTest(unittest.TestCase):
220
221 def setUp(self):
222 self.testbed = testbed.Testbed()
223 self.testbed.activate()
224 self.testbed.init_datastore_v3_stub()
225 self.testbed.init_memcache_stub()
226 self.testbed.init_user_stub()
227
228 access_token = "foo"
229 client_id = "some_client_id"
230 client_secret = "cOuDdkfjxxnv+"
231 refresh_token = "1/0/a.df219fjls0"
232 token_expiry = datetime.datetime.utcnow()
233 token_uri = "https://www.google.com/accounts/o8/oauth2/token"
234 user_agent = "refresh_checker/1.0"
235 self.credentials = OAuth2Credentials(
236 access_token, client_id, client_secret,
237 refresh_token, token_expiry, token_uri,
238 user_agent)
239
240 def tearDown(self):
241 self.testbed.deactivate()
242
243 def test_get_and_put_simple(self):
244 storage = StorageByKeyName(
245 CredentialsModel, 'foo', 'credentials')
246
247 self.assertEqual(None, storage.get())
248 self.credentials.set_store(storage)
249
250 self.credentials._refresh(_http_request)
251 credmodel = CredentialsModel.get_by_key_name('foo')
252 self.assertEqual('bar', credmodel.credentials.access_token)
253
254 def test_get_and_put_cached(self):
255 storage = StorageByKeyName(
256 CredentialsModel, 'foo', 'credentials', cache=memcache)
257
258 self.assertEqual(None, storage.get())
259 self.credentials.set_store(storage)
260
261 self.credentials._refresh(_http_request)
262 credmodel = CredentialsModel.get_by_key_name('foo')
263 self.assertEqual('bar', credmodel.credentials.access_token)
264
265 # Now remove the item from the cache.
266 memcache.delete('foo')
267
268 # Check that getting refreshes the cache.
269 credentials = storage.get()
270 self.assertEqual('bar', credentials.access_token)
271 self.assertNotEqual(None, memcache.get('foo'))
272
273 # Deleting should clear the cache.
274 storage.delete()
275 credentials = storage.get()
276 self.assertEqual(None, credentials)
277 self.assertEqual(None, memcache.get('foo'))
278
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400279class MockRequest(object):
280 url = 'https://example.org'
281
282 def relative_url(self, rel):
283 return self.url + rel
284
285class MockRequestHandler(object):
286 request = MockRequest()
Joe Gregorioe84c9442012-03-12 08:45:57 -0400287
Joe Gregorio432f17e2011-05-22 23:18:00 -0400288class DecoratorTests(unittest.TestCase):
289
290 def setUp(self):
291 self.testbed = testbed.Testbed()
292 self.testbed.activate()
293 self.testbed.init_datastore_v3_stub()
294 self.testbed.init_memcache_stub()
295 self.testbed.init_user_stub()
296
297 decorator = OAuth2Decorator(client_id='foo_client_id',
298 client_secret='foo_client_secret',
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100299 scope=['foo_scope', 'bar_scope'],
300 user_agent='foo')
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400301
302 self._finish_setup(decorator, user_mock=UserMock)
303
304 def _finish_setup(self, decorator, user_mock):
Joe Gregorio432f17e2011-05-22 23:18:00 -0400305 self.decorator = decorator
306
Joe Gregorio17774972012-03-01 11:11:59 -0500307 class TestRequiredHandler(webapp2.RequestHandler):
JacobMoshenko8e905102011-06-20 09:53:10 -0400308
Joe Gregorio432f17e2011-05-22 23:18:00 -0400309 @decorator.oauth_required
310 def get(self):
311 pass
312
Joe Gregorio17774972012-03-01 11:11:59 -0500313 class TestAwareHandler(webapp2.RequestHandler):
JacobMoshenko8e905102011-06-20 09:53:10 -0400314
Joe Gregorio432f17e2011-05-22 23:18:00 -0400315 @decorator.oauth_aware
Joe Gregorio17774972012-03-01 11:11:59 -0500316 def get(self, *args, **kwargs):
Joe Gregorio432f17e2011-05-22 23:18:00 -0400317 self.response.out.write('Hello World!')
Joe Gregorio17774972012-03-01 11:11:59 -0500318 assert(kwargs['year'] == '2012')
319 assert(kwargs['month'] == '01')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400320
321
Joe Gregorio17774972012-03-01 11:11:59 -0500322 application = webapp2.WSGIApplication([
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400323 ('/oauth2callback', self.decorator.callback_handler()),
Joe Gregorio17774972012-03-01 11:11:59 -0500324 ('/foo_path', TestRequiredHandler),
325 webapp2.Route(r'/bar_path/<year:\d{4}>/<month:\d{2}>',
326 handler=TestAwareHandler, name='bar')],
327 debug=True)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400328 self.app = TestApp(application)
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400329 users.get_current_user = user_mock()
Joe Gregorio922b78c2011-05-26 21:36:34 -0400330 self.httplib2_orig = httplib2.Http
Joe Gregorio432f17e2011-05-22 23:18:00 -0400331 httplib2.Http = Http2Mock
332
333 def tearDown(self):
334 self.testbed.deactivate()
Joe Gregorio922b78c2011-05-26 21:36:34 -0400335 httplib2.Http = self.httplib2_orig
Joe Gregorio432f17e2011-05-22 23:18:00 -0400336
337 def test_required(self):
338 # An initial request to an oauth_required decorated path should be a
339 # redirect to start the OAuth dance.
340 response = self.app.get('/foo_path')
341 self.assertTrue(response.status.startswith('302'))
342 q = parse_qs(response.headers['Location'].split('?', 1)[1])
343 self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0])
344 self.assertEqual('foo_client_id', q['client_id'][0])
Joe Gregoriof2f8a5a2011-10-14 15:11:29 -0400345 self.assertEqual('foo_scope bar_scope', q['scope'][0])
Joe Gregorio432f17e2011-05-22 23:18:00 -0400346 self.assertEqual('http://localhost/foo_path', q['state'][0])
347 self.assertEqual('code', q['response_type'][0])
348 self.assertEqual(False, self.decorator.has_credentials())
349
Joe Gregorio562b7312011-09-15 09:06:38 -0400350 # Now simulate the callback to /oauth2callback.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400351 response = self.app.get('/oauth2callback', {
352 'code': 'foo_access_code',
JacobMoshenko8e905102011-06-20 09:53:10 -0400353 'state': 'foo_path',
Joe Gregorio432f17e2011-05-22 23:18:00 -0400354 })
355 self.assertEqual('http://localhost/foo_path', response.headers['Location'])
356 self.assertEqual(None, self.decorator.credentials)
357
Joe Gregorio562b7312011-09-15 09:06:38 -0400358 # Now requesting the decorated path should work.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400359 response = self.app.get('/foo_path')
360 self.assertEqual('200 OK', response.status)
361 self.assertEqual(True, self.decorator.has_credentials())
JacobMoshenko8e905102011-06-20 09:53:10 -0400362 self.assertEqual('foo_refresh_token',
363 self.decorator.credentials.refresh_token)
364 self.assertEqual('foo_access_token',
365 self.decorator.credentials.access_token)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400366
Joe Gregorio562b7312011-09-15 09:06:38 -0400367 # Invalidate the stored Credentials.
Joe Gregorio9da2ad82011-09-11 14:04:44 -0400368 self.decorator.credentials.invalid = True
369 self.decorator.credentials.store.put(self.decorator.credentials)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400370
Joe Gregorio562b7312011-09-15 09:06:38 -0400371 # Invalid Credentials should start the OAuth dance again.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400372 response = self.app.get('/foo_path')
373 self.assertTrue(response.status.startswith('302'))
374 q = parse_qs(response.headers['Location'].split('?', 1)[1])
375 self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0])
376
Joe Gregorioec75dc12012-02-06 13:40:42 -0500377 def test_storage_delete(self):
378 # An initial request to an oauth_required decorated path should be a
379 # redirect to start the OAuth dance.
380 response = self.app.get('/foo_path')
381 self.assertTrue(response.status.startswith('302'))
382
383 # Now simulate the callback to /oauth2callback.
384 response = self.app.get('/oauth2callback', {
385 'code': 'foo_access_code',
386 'state': 'foo_path',
387 })
388 self.assertEqual('http://localhost/foo_path', response.headers['Location'])
389 self.assertEqual(None, self.decorator.credentials)
390
391 # Now requesting the decorated path should work.
392 response = self.app.get('/foo_path')
393
394 # Invalidate the stored Credentials.
395 self.decorator.credentials.store.delete()
396
397 # Invalid Credentials should start the OAuth dance again.
398 response = self.app.get('/foo_path')
399 self.assertTrue(response.status.startswith('302'))
400
Joe Gregorio432f17e2011-05-22 23:18:00 -0400401 def test_aware(self):
Joe Gregorio562b7312011-09-15 09:06:38 -0400402 # An initial request to an oauth_aware decorated path should not redirect.
Joe Gregorio17774972012-03-01 11:11:59 -0500403 response = self.app.get('/bar_path/2012/01')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400404 self.assertEqual('Hello World!', response.body)
405 self.assertEqual('200 OK', response.status)
406 self.assertEqual(False, self.decorator.has_credentials())
407 url = self.decorator.authorize_url()
408 q = parse_qs(url.split('?', 1)[1])
409 self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0])
410 self.assertEqual('foo_client_id', q['client_id'][0])
Joe Gregoriof2f8a5a2011-10-14 15:11:29 -0400411 self.assertEqual('foo_scope bar_scope', q['scope'][0])
Joe Gregorio17774972012-03-01 11:11:59 -0500412 self.assertEqual('http://localhost/bar_path/2012/01', q['state'][0])
Joe Gregorio432f17e2011-05-22 23:18:00 -0400413 self.assertEqual('code', q['response_type'][0])
414
Joe Gregorio562b7312011-09-15 09:06:38 -0400415 # Now simulate the callback to /oauth2callback.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400416 url = self.decorator.authorize_url()
417 response = self.app.get('/oauth2callback', {
418 'code': 'foo_access_code',
JacobMoshenko8e905102011-06-20 09:53:10 -0400419 'state': 'bar_path',
Joe Gregorio432f17e2011-05-22 23:18:00 -0400420 })
421 self.assertEqual('http://localhost/bar_path', response.headers['Location'])
422 self.assertEqual(False, self.decorator.has_credentials())
423
Joe Gregorio562b7312011-09-15 09:06:38 -0400424 # Now requesting the decorated path will have credentials.
Joe Gregorio17774972012-03-01 11:11:59 -0500425 response = self.app.get('/bar_path/2012/01')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400426 self.assertEqual('200 OK', response.status)
427 self.assertEqual('Hello World!', response.body)
428 self.assertEqual(True, self.decorator.has_credentials())
JacobMoshenko8e905102011-06-20 09:53:10 -0400429 self.assertEqual('foo_refresh_token',
430 self.decorator.credentials.refresh_token)
431 self.assertEqual('foo_access_token',
432 self.decorator.credentials.access_token)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400433
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500434
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400435 def test_error_in_step2(self):
436 # An initial request to an oauth_aware decorated path should not redirect.
437 response = self.app.get('/bar_path/2012/01')
438 url = self.decorator.authorize_url()
439 response = self.app.get('/oauth2callback', {
440 'error': 'BadStuffHappened'
441 })
442 self.assertEqual('200 OK', response.status)
443 self.assertTrue('BadStuffHappened' in response.body)
444
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500445 def test_kwargs_are_passed_to_underlying_flow(self):
446 decorator = OAuth2Decorator(client_id='foo_client_id',
447 client_secret='foo_client_secret',
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100448 user_agent='foo_user_agent',
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500449 scope=['foo_scope', 'bar_scope'],
450 access_type='offline',
451 approval_prompt='force')
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400452 request_handler = MockRequestHandler()
453 decorator._create_flow(request_handler)
454
455 self.assertEqual('https://example.org/oauth2callback',
456 decorator.flow.redirect_uri)
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500457 self.assertEqual('offline', decorator.flow.params['access_type'])
458 self.assertEqual('force', decorator.flow.params['approval_prompt'])
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100459 self.assertEqual('foo_user_agent', decorator.flow.user_agent)
460 self.assertEqual(None, decorator.flow.params.get('user_agent', None))
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500461
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400462 def test_decorator_from_client_secrets(self):
463 decorator = oauth2decorator_from_clientsecrets(
464 datafile('client_secrets.json'),
465 scope=['foo_scope', 'bar_scope'])
466 self._finish_setup(decorator, user_mock=UserMock)
467
468 self.assertFalse(decorator._in_error)
469 self.decorator = decorator
470 self.test_required()
471 http = self.decorator.http()
472 self.assertEquals('foo_access_token', http.request.credentials.access_token)
473
Joe Gregorioc29aaa92012-07-16 16:16:31 -0400474 def test_decorator_from_cached_client_secrets(self):
475 cache_mock = CacheMock()
476 load_and_cache('client_secrets.json', 'secret', cache_mock)
477 decorator = oauth2decorator_from_clientsecrets(
478 # filename, scope, message=None, cache=None
479 'secret', '', cache=cache_mock)
480 self.assertFalse(decorator._in_error)
481
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400482 def test_decorator_from_client_secrets_not_logged_in_required(self):
483 decorator = oauth2decorator_from_clientsecrets(
484 datafile('client_secrets.json'),
485 scope=['foo_scope', 'bar_scope'], message='NotLoggedInMessage')
486 self.decorator = decorator
487 self._finish_setup(decorator, user_mock=UserNotLoggedInMock)
488
489 self.assertFalse(decorator._in_error)
490
491 # An initial request to an oauth_required decorated path should be a
492 # redirect to login.
493 response = self.app.get('/foo_path')
494 self.assertTrue(response.status.startswith('302'))
495 self.assertTrue('Login' in str(response))
496
497 def test_decorator_from_client_secrets_not_logged_in_aware(self):
498 decorator = oauth2decorator_from_clientsecrets(
499 datafile('client_secrets.json'),
500 scope=['foo_scope', 'bar_scope'], message='NotLoggedInMessage')
501 self.decorator = decorator
502 self._finish_setup(decorator, user_mock=UserNotLoggedInMock)
503
504 # An initial request to an oauth_aware decorated path should be a
505 # redirect to login.
506 response = self.app.get('/bar_path/2012/03')
507 self.assertTrue(response.status.startswith('302'))
508 self.assertTrue('Login' in str(response))
509
510 def test_decorator_from_unfilled_client_secrets_required(self):
511 MESSAGE = 'File is missing'
512 decorator = oauth2decorator_from_clientsecrets(
513 datafile('unfilled_client_secrets.json'),
514 scope=['foo_scope', 'bar_scope'], message=MESSAGE)
515 self._finish_setup(decorator, user_mock=UserNotLoggedInMock)
516 self.assertTrue(decorator._in_error)
517 self.assertEqual(MESSAGE, decorator._message)
518
519 # An initial request to an oauth_required decorated path should be an
520 # error message.
521 response = self.app.get('/foo_path')
522 self.assertTrue(response.status.startswith('200'))
523 self.assertTrue(MESSAGE in str(response))
524
525 def test_decorator_from_unfilled_client_secrets_aware(self):
526 MESSAGE = 'File is missing'
527 decorator = oauth2decorator_from_clientsecrets(
528 datafile('unfilled_client_secrets.json'),
529 scope=['foo_scope', 'bar_scope'], message=MESSAGE)
530 self._finish_setup(decorator, user_mock=UserNotLoggedInMock)
531 self.assertTrue(decorator._in_error)
532 self.assertEqual(MESSAGE, decorator._message)
533
534 # An initial request to an oauth_aware decorated path should be an
535 # error message.
536 response = self.app.get('/bar_path/2012/03')
537 self.assertTrue(response.status.startswith('200'))
538 self.assertTrue(MESSAGE in str(response))
539
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500540
Joe Gregorio432f17e2011-05-22 23:18:00 -0400541if __name__ == '__main__':
542 unittest.main()