blob: 58f3e552107a4718ee5eab2f796b1d5d67b53ae9 [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 Gregorio432f17e2011-05-22 23:18:00 -040058from oauth2client.appengine import OAuth2Handler
Joe Gregorioe84c9442012-03-12 08:45:57 -040059from oauth2client.appengine import StorageByKeyName
Joe Gregorio08cdcb82012-03-14 00:09:33 -040060from oauth2client.appengine import oauth2decorator_from_clientsecrets
Joe Gregorio549230c2012-01-11 10:38:05 -050061from oauth2client.client import AccessTokenRefreshError
Joe Gregorio08cdcb82012-03-14 00:09:33 -040062from oauth2client.client import Credentials
Joe Gregorio549230c2012-01-11 10:38:05 -050063from oauth2client.client import FlowExchangeError
Joe Gregorioe84c9442012-03-12 08:45:57 -040064from oauth2client.client import OAuth2Credentials
Joe Gregorio08cdcb82012-03-14 00:09:33 -040065from oauth2client.client import flow_from_clientsecrets
JacobMoshenko8e905102011-06-20 09:53:10 -040066from webtest import TestApp
Joe Gregorio432f17e2011-05-22 23:18:00 -040067
Joe Gregorio4fbde1c2012-07-11 14:47:39 -040068
Joe Gregorio08cdcb82012-03-14 00:09:33 -040069DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
70
71
72def datafile(filename):
73 return os.path.join(DATA_DIR, filename)
74
75
Joe Gregorioc29aaa92012-07-16 16:16:31 -040076def load_and_cache(existing_file, fakename, cache_mock):
77 client_type, client_info = _loadfile(datafile(existing_file))
78 cache_mock.cache[fakename] = {client_type: client_info}
79
80
81class CacheMock(object):
82 def __init__(self):
83 self.cache = {}
84
85 def get(self, key, namespace=''):
86 # ignoring namespace for easier testing
87 return self.cache.get(key, None)
88
89 def set(self, key, value, namespace=''):
90 # ignoring namespace for easier testing
91 self.cache[key] = value
92
93
Joe Gregorio432f17e2011-05-22 23:18:00 -040094class UserMock(object):
95 """Mock the app engine user service"""
JacobMoshenko8e905102011-06-20 09:53:10 -040096
Joe Gregorio08cdcb82012-03-14 00:09:33 -040097 def __call__(self):
98 return self
99
Joe Gregorio432f17e2011-05-22 23:18:00 -0400100 def user_id(self):
101 return 'foo_user'
102
103
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400104class UserNotLoggedInMock(object):
105 """Mock the app engine user service"""
106
107 def __call__(self):
108 return None
109
110
Joe Gregorio432f17e2011-05-22 23:18:00 -0400111class Http2Mock(object):
112 """Mock httplib2.Http"""
113 status = 200
114 content = {
115 'access_token': 'foo_access_token',
116 'refresh_token': 'foo_refresh_token',
JacobMoshenko8e905102011-06-20 09:53:10 -0400117 'expires_in': 3600,
Joe Gregorio432f17e2011-05-22 23:18:00 -0400118 }
119
120 def request(self, token_uri, method, body, headers, *args, **kwargs):
121 self.body = body
122 self.headers = headers
123 return (self, simplejson.dumps(self.content))
124
125
JacobMoshenko8e905102011-06-20 09:53:10 -0400126class TestAppAssertionCredentials(unittest.TestCase):
127 account_name = "service_account_name@appspot.com"
128 signature = "signature"
129
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500130
JacobMoshenko8e905102011-06-20 09:53:10 -0400131 class AppIdentityStubImpl(apiproxy_stub.APIProxyStub):
132
133 def __init__(self):
134 super(TestAppAssertionCredentials.AppIdentityStubImpl, self).__init__(
135 'app_identity_service')
136
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500137 def _Dynamic_GetAccessToken(self, request, response):
138 response.set_access_token('a_token_123')
139 response.set_expiration_time(time.time() + 1800)
JacobMoshenko8e905102011-06-20 09:53:10 -0400140
JacobMoshenko8e905102011-06-20 09:53:10 -0400141
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500142 class ErroringAppIdentityStubImpl(apiproxy_stub.APIProxyStub):
143
144 def __init__(self):
145 super(TestAppAssertionCredentials.ErroringAppIdentityStubImpl, self).__init__(
146 'app_identity_service')
147
148 def _Dynamic_GetAccessToken(self, request, response):
149 raise app_identity.BackendDeadlineExceeded()
150
151 def test_raise_correct_type_of_exception(self):
152 app_identity_stub = self.ErroringAppIdentityStubImpl()
153 apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
JacobMoshenko8e905102011-06-20 09:53:10 -0400154 apiproxy_stub_map.apiproxy.RegisterStub("app_identity_service",
155 app_identity_stub)
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500156 apiproxy_stub_map.apiproxy.RegisterStub(
157 'memcache', memcache_stub.MemcacheServiceStub())
JacobMoshenko8e905102011-06-20 09:53:10 -0400158
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500159 scope = "http://www.googleapis.com/scope"
160 try:
161 credentials = AppAssertionCredentials(scope)
162 http = httplib2.Http()
163 credentials.refresh(http)
164 self.fail('Should have raised an AccessTokenRefreshError')
165 except AccessTokenRefreshError:
166 pass
JacobMoshenko8e905102011-06-20 09:53:10 -0400167
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500168 def test_get_access_token_on_refresh(self):
169 app_identity_stub = self.AppIdentityStubImpl()
170 apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
171 apiproxy_stub_map.apiproxy.RegisterStub("app_identity_service",
172 app_identity_stub)
173 apiproxy_stub_map.apiproxy.RegisterStub(
174 'memcache', memcache_stub.MemcacheServiceStub())
JacobMoshenko8e905102011-06-20 09:53:10 -0400175
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400176 scope = ["http://www.googleapis.com/scope"]
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500177 credentials = AppAssertionCredentials(scope)
178 http = httplib2.Http()
179 credentials.refresh(http)
180 self.assertEqual('a_token_123', credentials.access_token)
JacobMoshenko8e905102011-06-20 09:53:10 -0400181
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400182 json = credentials.to_json()
183 credentials = Credentials.new_from_json(json)
184 self.assertEqual(scope[0], credentials.scope)
185
186
187class TestFlowModel(db.Model):
188 flow = FlowProperty()
189
190
191class FlowPropertyTest(unittest.TestCase):
192
193 def setUp(self):
194 self.testbed = testbed.Testbed()
195 self.testbed.activate()
196 self.testbed.init_datastore_v3_stub()
197
198 def tearDown(self):
199 self.testbed.deactivate()
200
201 def test_flow_get_put(self):
202 instance = TestFlowModel(
203 flow=flow_from_clientsecrets(datafile('client_secrets.json'), 'foo'),
204 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
279
Joe Gregorio432f17e2011-05-22 23:18:00 -0400280class DecoratorTests(unittest.TestCase):
281
282 def setUp(self):
283 self.testbed = testbed.Testbed()
284 self.testbed.activate()
285 self.testbed.init_datastore_v3_stub()
286 self.testbed.init_memcache_stub()
287 self.testbed.init_user_stub()
288
289 decorator = OAuth2Decorator(client_id='foo_client_id',
290 client_secret='foo_client_secret',
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100291 scope=['foo_scope', 'bar_scope'],
292 user_agent='foo')
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400293
294 self._finish_setup(decorator, user_mock=UserMock)
295
296 def _finish_setup(self, decorator, user_mock):
Joe Gregorio432f17e2011-05-22 23:18:00 -0400297 self.decorator = decorator
298
Joe Gregorio17774972012-03-01 11:11:59 -0500299 class TestRequiredHandler(webapp2.RequestHandler):
JacobMoshenko8e905102011-06-20 09:53:10 -0400300
Joe Gregorio432f17e2011-05-22 23:18:00 -0400301 @decorator.oauth_required
302 def get(self):
303 pass
304
Joe Gregorio17774972012-03-01 11:11:59 -0500305 class TestAwareHandler(webapp2.RequestHandler):
JacobMoshenko8e905102011-06-20 09:53:10 -0400306
Joe Gregorio432f17e2011-05-22 23:18:00 -0400307 @decorator.oauth_aware
Joe Gregorio17774972012-03-01 11:11:59 -0500308 def get(self, *args, **kwargs):
Joe Gregorio432f17e2011-05-22 23:18:00 -0400309 self.response.out.write('Hello World!')
Joe Gregorio17774972012-03-01 11:11:59 -0500310 assert(kwargs['year'] == '2012')
311 assert(kwargs['month'] == '01')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400312
313
Joe Gregorio17774972012-03-01 11:11:59 -0500314 application = webapp2.WSGIApplication([
315 ('/oauth2callback', OAuth2Handler),
316 ('/foo_path', TestRequiredHandler),
317 webapp2.Route(r'/bar_path/<year:\d{4}>/<month:\d{2}>',
318 handler=TestAwareHandler, name='bar')],
319 debug=True)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400320 self.app = TestApp(application)
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400321 users.get_current_user = user_mock()
Joe Gregorio922b78c2011-05-26 21:36:34 -0400322 self.httplib2_orig = httplib2.Http
Joe Gregorio432f17e2011-05-22 23:18:00 -0400323 httplib2.Http = Http2Mock
324
325 def tearDown(self):
326 self.testbed.deactivate()
Joe Gregorio922b78c2011-05-26 21:36:34 -0400327 httplib2.Http = self.httplib2_orig
Joe Gregorio432f17e2011-05-22 23:18:00 -0400328
329 def test_required(self):
330 # An initial request to an oauth_required decorated path should be a
331 # redirect to start the OAuth dance.
332 response = self.app.get('/foo_path')
333 self.assertTrue(response.status.startswith('302'))
334 q = parse_qs(response.headers['Location'].split('?', 1)[1])
335 self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0])
336 self.assertEqual('foo_client_id', q['client_id'][0])
Joe Gregoriof2f8a5a2011-10-14 15:11:29 -0400337 self.assertEqual('foo_scope bar_scope', q['scope'][0])
Joe Gregorio432f17e2011-05-22 23:18:00 -0400338 self.assertEqual('http://localhost/foo_path', q['state'][0])
339 self.assertEqual('code', q['response_type'][0])
340 self.assertEqual(False, self.decorator.has_credentials())
341
Joe Gregorio562b7312011-09-15 09:06:38 -0400342 # Now simulate the callback to /oauth2callback.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400343 response = self.app.get('/oauth2callback', {
344 'code': 'foo_access_code',
JacobMoshenko8e905102011-06-20 09:53:10 -0400345 'state': 'foo_path',
Joe Gregorio432f17e2011-05-22 23:18:00 -0400346 })
347 self.assertEqual('http://localhost/foo_path', response.headers['Location'])
348 self.assertEqual(None, self.decorator.credentials)
349
Joe Gregorio562b7312011-09-15 09:06:38 -0400350 # Now requesting the decorated path should work.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400351 response = self.app.get('/foo_path')
352 self.assertEqual('200 OK', response.status)
353 self.assertEqual(True, self.decorator.has_credentials())
JacobMoshenko8e905102011-06-20 09:53:10 -0400354 self.assertEqual('foo_refresh_token',
355 self.decorator.credentials.refresh_token)
356 self.assertEqual('foo_access_token',
357 self.decorator.credentials.access_token)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400358
Joe Gregorio562b7312011-09-15 09:06:38 -0400359 # Invalidate the stored Credentials.
Joe Gregorio9da2ad82011-09-11 14:04:44 -0400360 self.decorator.credentials.invalid = True
361 self.decorator.credentials.store.put(self.decorator.credentials)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400362
Joe Gregorio562b7312011-09-15 09:06:38 -0400363 # Invalid Credentials should start the OAuth dance again.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400364 response = self.app.get('/foo_path')
365 self.assertTrue(response.status.startswith('302'))
366 q = parse_qs(response.headers['Location'].split('?', 1)[1])
367 self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0])
368
Joe Gregorioec75dc12012-02-06 13:40:42 -0500369 def test_storage_delete(self):
370 # An initial request to an oauth_required decorated path should be a
371 # redirect to start the OAuth dance.
372 response = self.app.get('/foo_path')
373 self.assertTrue(response.status.startswith('302'))
374
375 # Now simulate the callback to /oauth2callback.
376 response = self.app.get('/oauth2callback', {
377 'code': 'foo_access_code',
378 'state': 'foo_path',
379 })
380 self.assertEqual('http://localhost/foo_path', response.headers['Location'])
381 self.assertEqual(None, self.decorator.credentials)
382
383 # Now requesting the decorated path should work.
384 response = self.app.get('/foo_path')
385
386 # Invalidate the stored Credentials.
387 self.decorator.credentials.store.delete()
388
389 # Invalid Credentials should start the OAuth dance again.
390 response = self.app.get('/foo_path')
391 self.assertTrue(response.status.startswith('302'))
392
Joe Gregorio432f17e2011-05-22 23:18:00 -0400393 def test_aware(self):
Joe Gregorio562b7312011-09-15 09:06:38 -0400394 # An initial request to an oauth_aware decorated path should not redirect.
Joe Gregorio17774972012-03-01 11:11:59 -0500395 response = self.app.get('/bar_path/2012/01')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400396 self.assertEqual('Hello World!', response.body)
397 self.assertEqual('200 OK', response.status)
398 self.assertEqual(False, self.decorator.has_credentials())
399 url = self.decorator.authorize_url()
400 q = parse_qs(url.split('?', 1)[1])
401 self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0])
402 self.assertEqual('foo_client_id', q['client_id'][0])
Joe Gregoriof2f8a5a2011-10-14 15:11:29 -0400403 self.assertEqual('foo_scope bar_scope', q['scope'][0])
Joe Gregorio17774972012-03-01 11:11:59 -0500404 self.assertEqual('http://localhost/bar_path/2012/01', q['state'][0])
Joe Gregorio432f17e2011-05-22 23:18:00 -0400405 self.assertEqual('code', q['response_type'][0])
406
Joe Gregorio562b7312011-09-15 09:06:38 -0400407 # Now simulate the callback to /oauth2callback.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400408 url = self.decorator.authorize_url()
409 response = self.app.get('/oauth2callback', {
410 'code': 'foo_access_code',
JacobMoshenko8e905102011-06-20 09:53:10 -0400411 'state': 'bar_path',
Joe Gregorio432f17e2011-05-22 23:18:00 -0400412 })
413 self.assertEqual('http://localhost/bar_path', response.headers['Location'])
414 self.assertEqual(False, self.decorator.has_credentials())
415
Joe Gregorio562b7312011-09-15 09:06:38 -0400416 # Now requesting the decorated path will have credentials.
Joe Gregorio17774972012-03-01 11:11:59 -0500417 response = self.app.get('/bar_path/2012/01')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400418 self.assertEqual('200 OK', response.status)
419 self.assertEqual('Hello World!', response.body)
420 self.assertEqual(True, self.decorator.has_credentials())
JacobMoshenko8e905102011-06-20 09:53:10 -0400421 self.assertEqual('foo_refresh_token',
422 self.decorator.credentials.refresh_token)
423 self.assertEqual('foo_access_token',
424 self.decorator.credentials.access_token)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400425
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500426
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400427 def test_error_in_step2(self):
428 # An initial request to an oauth_aware decorated path should not redirect.
429 response = self.app.get('/bar_path/2012/01')
430 url = self.decorator.authorize_url()
431 response = self.app.get('/oauth2callback', {
432 'error': 'BadStuffHappened'
433 })
434 self.assertEqual('200 OK', response.status)
435 self.assertTrue('BadStuffHappened' in response.body)
436
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500437 def test_kwargs_are_passed_to_underlying_flow(self):
438 decorator = OAuth2Decorator(client_id='foo_client_id',
439 client_secret='foo_client_secret',
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100440 user_agent='foo_user_agent',
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500441 scope=['foo_scope', 'bar_scope'],
442 access_type='offline',
443 approval_prompt='force')
444 self.assertEqual('offline', decorator.flow.params['access_type'])
445 self.assertEqual('force', decorator.flow.params['approval_prompt'])
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100446 self.assertEqual('foo_user_agent', decorator.flow.user_agent)
447 self.assertEqual(None, decorator.flow.params.get('user_agent', None))
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500448
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400449 def test_decorator_from_client_secrets(self):
450 decorator = oauth2decorator_from_clientsecrets(
451 datafile('client_secrets.json'),
452 scope=['foo_scope', 'bar_scope'])
453 self._finish_setup(decorator, user_mock=UserMock)
454
455 self.assertFalse(decorator._in_error)
456 self.decorator = decorator
457 self.test_required()
458 http = self.decorator.http()
459 self.assertEquals('foo_access_token', http.request.credentials.access_token)
460
Joe Gregorioc29aaa92012-07-16 16:16:31 -0400461 def test_decorator_from_cached_client_secrets(self):
462 cache_mock = CacheMock()
463 load_and_cache('client_secrets.json', 'secret', cache_mock)
464 decorator = oauth2decorator_from_clientsecrets(
465 # filename, scope, message=None, cache=None
466 'secret', '', cache=cache_mock)
467 self.assertFalse(decorator._in_error)
468
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400469 def test_decorator_from_client_secrets_not_logged_in_required(self):
470 decorator = oauth2decorator_from_clientsecrets(
471 datafile('client_secrets.json'),
472 scope=['foo_scope', 'bar_scope'], message='NotLoggedInMessage')
473 self.decorator = decorator
474 self._finish_setup(decorator, user_mock=UserNotLoggedInMock)
475
476 self.assertFalse(decorator._in_error)
477
478 # An initial request to an oauth_required decorated path should be a
479 # redirect to login.
480 response = self.app.get('/foo_path')
481 self.assertTrue(response.status.startswith('302'))
482 self.assertTrue('Login' in str(response))
483
484 def test_decorator_from_client_secrets_not_logged_in_aware(self):
485 decorator = oauth2decorator_from_clientsecrets(
486 datafile('client_secrets.json'),
487 scope=['foo_scope', 'bar_scope'], message='NotLoggedInMessage')
488 self.decorator = decorator
489 self._finish_setup(decorator, user_mock=UserNotLoggedInMock)
490
491 # An initial request to an oauth_aware decorated path should be a
492 # redirect to login.
493 response = self.app.get('/bar_path/2012/03')
494 self.assertTrue(response.status.startswith('302'))
495 self.assertTrue('Login' in str(response))
496
497 def test_decorator_from_unfilled_client_secrets_required(self):
498 MESSAGE = 'File is missing'
499 decorator = oauth2decorator_from_clientsecrets(
500 datafile('unfilled_client_secrets.json'),
501 scope=['foo_scope', 'bar_scope'], message=MESSAGE)
502 self._finish_setup(decorator, user_mock=UserNotLoggedInMock)
503 self.assertTrue(decorator._in_error)
504 self.assertEqual(MESSAGE, decorator._message)
505
506 # An initial request to an oauth_required decorated path should be an
507 # error message.
508 response = self.app.get('/foo_path')
509 self.assertTrue(response.status.startswith('200'))
510 self.assertTrue(MESSAGE in str(response))
511
512 def test_decorator_from_unfilled_client_secrets_aware(self):
513 MESSAGE = 'File is missing'
514 decorator = oauth2decorator_from_clientsecrets(
515 datafile('unfilled_client_secrets.json'),
516 scope=['foo_scope', 'bar_scope'], message=MESSAGE)
517 self._finish_setup(decorator, user_mock=UserNotLoggedInMock)
518 self.assertTrue(decorator._in_error)
519 self.assertEqual(MESSAGE, decorator._message)
520
521 # An initial request to an oauth_aware decorated path should be an
522 # error message.
523 response = self.app.get('/bar_path/2012/03')
524 self.assertTrue(response.status.startswith('200'))
525 self.assertTrue(MESSAGE in str(response))
526
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500527
Joe Gregorio432f17e2011-05-22 23:18:00 -0400528if __name__ == '__main__':
529 unittest.main()