blob: edc5996eaabd4cc023a6eaf174fd6772e64b75ed [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
JacobMoshenko8e905102011-06-20 09:53:10 -040053from oauth2client.appengine import AppAssertionCredentials
Joe Gregorioe84c9442012-03-12 08:45:57 -040054from oauth2client.appengine import CredentialsModel
Joe Gregorio4fbde1c2012-07-11 14:47:39 -040055from oauth2client.appengine import FlowProperty
Joe Gregorio432f17e2011-05-22 23:18:00 -040056from oauth2client.appengine import OAuth2Decorator
Joe Gregorio432f17e2011-05-22 23:18:00 -040057from oauth2client.appengine import OAuth2Handler
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 Gregorio432f17e2011-05-22 23:18:00 -040075class UserMock(object):
76 """Mock the app engine user service"""
JacobMoshenko8e905102011-06-20 09:53:10 -040077
Joe Gregorio08cdcb82012-03-14 00:09:33 -040078 def __call__(self):
79 return self
80
Joe Gregorio432f17e2011-05-22 23:18:00 -040081 def user_id(self):
82 return 'foo_user'
83
84
Joe Gregorio08cdcb82012-03-14 00:09:33 -040085class UserNotLoggedInMock(object):
86 """Mock the app engine user service"""
87
88 def __call__(self):
89 return None
90
91
Joe Gregorio432f17e2011-05-22 23:18:00 -040092class Http2Mock(object):
93 """Mock httplib2.Http"""
94 status = 200
95 content = {
96 'access_token': 'foo_access_token',
97 'refresh_token': 'foo_refresh_token',
JacobMoshenko8e905102011-06-20 09:53:10 -040098 'expires_in': 3600,
Joe Gregorio432f17e2011-05-22 23:18:00 -040099 }
100
101 def request(self, token_uri, method, body, headers, *args, **kwargs):
102 self.body = body
103 self.headers = headers
104 return (self, simplejson.dumps(self.content))
105
106
JacobMoshenko8e905102011-06-20 09:53:10 -0400107class TestAppAssertionCredentials(unittest.TestCase):
108 account_name = "service_account_name@appspot.com"
109 signature = "signature"
110
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500111
JacobMoshenko8e905102011-06-20 09:53:10 -0400112 class AppIdentityStubImpl(apiproxy_stub.APIProxyStub):
113
114 def __init__(self):
115 super(TestAppAssertionCredentials.AppIdentityStubImpl, self).__init__(
116 'app_identity_service')
117
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500118 def _Dynamic_GetAccessToken(self, request, response):
119 response.set_access_token('a_token_123')
120 response.set_expiration_time(time.time() + 1800)
JacobMoshenko8e905102011-06-20 09:53:10 -0400121
JacobMoshenko8e905102011-06-20 09:53:10 -0400122
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500123 class ErroringAppIdentityStubImpl(apiproxy_stub.APIProxyStub):
124
125 def __init__(self):
126 super(TestAppAssertionCredentials.ErroringAppIdentityStubImpl, self).__init__(
127 'app_identity_service')
128
129 def _Dynamic_GetAccessToken(self, request, response):
130 raise app_identity.BackendDeadlineExceeded()
131
132 def test_raise_correct_type_of_exception(self):
133 app_identity_stub = self.ErroringAppIdentityStubImpl()
134 apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
JacobMoshenko8e905102011-06-20 09:53:10 -0400135 apiproxy_stub_map.apiproxy.RegisterStub("app_identity_service",
136 app_identity_stub)
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500137 apiproxy_stub_map.apiproxy.RegisterStub(
138 'memcache', memcache_stub.MemcacheServiceStub())
JacobMoshenko8e905102011-06-20 09:53:10 -0400139
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500140 scope = "http://www.googleapis.com/scope"
141 try:
142 credentials = AppAssertionCredentials(scope)
143 http = httplib2.Http()
144 credentials.refresh(http)
145 self.fail('Should have raised an AccessTokenRefreshError')
146 except AccessTokenRefreshError:
147 pass
JacobMoshenko8e905102011-06-20 09:53:10 -0400148
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500149 def test_get_access_token_on_refresh(self):
150 app_identity_stub = self.AppIdentityStubImpl()
151 apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
152 apiproxy_stub_map.apiproxy.RegisterStub("app_identity_service",
153 app_identity_stub)
154 apiproxy_stub_map.apiproxy.RegisterStub(
155 'memcache', memcache_stub.MemcacheServiceStub())
JacobMoshenko8e905102011-06-20 09:53:10 -0400156
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400157 scope = ["http://www.googleapis.com/scope"]
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500158 credentials = AppAssertionCredentials(scope)
159 http = httplib2.Http()
160 credentials.refresh(http)
161 self.assertEqual('a_token_123', credentials.access_token)
JacobMoshenko8e905102011-06-20 09:53:10 -0400162
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400163 json = credentials.to_json()
164 credentials = Credentials.new_from_json(json)
165 self.assertEqual(scope[0], credentials.scope)
166
167
168class TestFlowModel(db.Model):
169 flow = FlowProperty()
170
171
172class FlowPropertyTest(unittest.TestCase):
173
174 def setUp(self):
175 self.testbed = testbed.Testbed()
176 self.testbed.activate()
177 self.testbed.init_datastore_v3_stub()
178
179 def tearDown(self):
180 self.testbed.deactivate()
181
182 def test_flow_get_put(self):
183 instance = TestFlowModel(
184 flow=flow_from_clientsecrets(datafile('client_secrets.json'), 'foo'),
185 key_name='foo'
186 )
187 instance.put()
188 retrieved = TestFlowModel.get_by_key_name('foo')
189
190 self.assertEqual('foo_client_id', retrieved.flow.client_id)
191
JacobMoshenko8e905102011-06-20 09:53:10 -0400192
Joe Gregorioe84c9442012-03-12 08:45:57 -0400193def _http_request(*args, **kwargs):
194 resp = httplib2.Response({'status': '200'})
195 content = simplejson.dumps({'access_token': 'bar'})
196
197 return resp, content
198
199
200class StorageByKeyNameTest(unittest.TestCase):
201
202 def setUp(self):
203 self.testbed = testbed.Testbed()
204 self.testbed.activate()
205 self.testbed.init_datastore_v3_stub()
206 self.testbed.init_memcache_stub()
207 self.testbed.init_user_stub()
208
209 access_token = "foo"
210 client_id = "some_client_id"
211 client_secret = "cOuDdkfjxxnv+"
212 refresh_token = "1/0/a.df219fjls0"
213 token_expiry = datetime.datetime.utcnow()
214 token_uri = "https://www.google.com/accounts/o8/oauth2/token"
215 user_agent = "refresh_checker/1.0"
216 self.credentials = OAuth2Credentials(
217 access_token, client_id, client_secret,
218 refresh_token, token_expiry, token_uri,
219 user_agent)
220
221 def tearDown(self):
222 self.testbed.deactivate()
223
224 def test_get_and_put_simple(self):
225 storage = StorageByKeyName(
226 CredentialsModel, 'foo', 'credentials')
227
228 self.assertEqual(None, storage.get())
229 self.credentials.set_store(storage)
230
231 self.credentials._refresh(_http_request)
232 credmodel = CredentialsModel.get_by_key_name('foo')
233 self.assertEqual('bar', credmodel.credentials.access_token)
234
235 def test_get_and_put_cached(self):
236 storage = StorageByKeyName(
237 CredentialsModel, 'foo', 'credentials', cache=memcache)
238
239 self.assertEqual(None, storage.get())
240 self.credentials.set_store(storage)
241
242 self.credentials._refresh(_http_request)
243 credmodel = CredentialsModel.get_by_key_name('foo')
244 self.assertEqual('bar', credmodel.credentials.access_token)
245
246 # Now remove the item from the cache.
247 memcache.delete('foo')
248
249 # Check that getting refreshes the cache.
250 credentials = storage.get()
251 self.assertEqual('bar', credentials.access_token)
252 self.assertNotEqual(None, memcache.get('foo'))
253
254 # Deleting should clear the cache.
255 storage.delete()
256 credentials = storage.get()
257 self.assertEqual(None, credentials)
258 self.assertEqual(None, memcache.get('foo'))
259
260
Joe Gregorio432f17e2011-05-22 23:18:00 -0400261class DecoratorTests(unittest.TestCase):
262
263 def setUp(self):
264 self.testbed = testbed.Testbed()
265 self.testbed.activate()
266 self.testbed.init_datastore_v3_stub()
267 self.testbed.init_memcache_stub()
268 self.testbed.init_user_stub()
269
270 decorator = OAuth2Decorator(client_id='foo_client_id',
271 client_secret='foo_client_secret',
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100272 scope=['foo_scope', 'bar_scope'],
273 user_agent='foo')
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400274
275 self._finish_setup(decorator, user_mock=UserMock)
276
277 def _finish_setup(self, decorator, user_mock):
Joe Gregorio432f17e2011-05-22 23:18:00 -0400278 self.decorator = decorator
279
Joe Gregorio17774972012-03-01 11:11:59 -0500280 class TestRequiredHandler(webapp2.RequestHandler):
JacobMoshenko8e905102011-06-20 09:53:10 -0400281
Joe Gregorio432f17e2011-05-22 23:18:00 -0400282 @decorator.oauth_required
283 def get(self):
284 pass
285
Joe Gregorio17774972012-03-01 11:11:59 -0500286 class TestAwareHandler(webapp2.RequestHandler):
JacobMoshenko8e905102011-06-20 09:53:10 -0400287
Joe Gregorio432f17e2011-05-22 23:18:00 -0400288 @decorator.oauth_aware
Joe Gregorio17774972012-03-01 11:11:59 -0500289 def get(self, *args, **kwargs):
Joe Gregorio432f17e2011-05-22 23:18:00 -0400290 self.response.out.write('Hello World!')
Joe Gregorio17774972012-03-01 11:11:59 -0500291 assert(kwargs['year'] == '2012')
292 assert(kwargs['month'] == '01')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400293
294
Joe Gregorio17774972012-03-01 11:11:59 -0500295 application = webapp2.WSGIApplication([
296 ('/oauth2callback', OAuth2Handler),
297 ('/foo_path', TestRequiredHandler),
298 webapp2.Route(r'/bar_path/<year:\d{4}>/<month:\d{2}>',
299 handler=TestAwareHandler, name='bar')],
300 debug=True)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400301 self.app = TestApp(application)
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400302 users.get_current_user = user_mock()
Joe Gregorio922b78c2011-05-26 21:36:34 -0400303 self.httplib2_orig = httplib2.Http
Joe Gregorio432f17e2011-05-22 23:18:00 -0400304 httplib2.Http = Http2Mock
305
306 def tearDown(self):
307 self.testbed.deactivate()
Joe Gregorio922b78c2011-05-26 21:36:34 -0400308 httplib2.Http = self.httplib2_orig
Joe Gregorio432f17e2011-05-22 23:18:00 -0400309
310 def test_required(self):
311 # An initial request to an oauth_required decorated path should be a
312 # redirect to start the OAuth dance.
313 response = self.app.get('/foo_path')
314 self.assertTrue(response.status.startswith('302'))
315 q = parse_qs(response.headers['Location'].split('?', 1)[1])
316 self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0])
317 self.assertEqual('foo_client_id', q['client_id'][0])
Joe Gregoriof2f8a5a2011-10-14 15:11:29 -0400318 self.assertEqual('foo_scope bar_scope', q['scope'][0])
Joe Gregorio432f17e2011-05-22 23:18:00 -0400319 self.assertEqual('http://localhost/foo_path', q['state'][0])
320 self.assertEqual('code', q['response_type'][0])
321 self.assertEqual(False, self.decorator.has_credentials())
322
Joe Gregorio562b7312011-09-15 09:06:38 -0400323 # Now simulate the callback to /oauth2callback.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400324 response = self.app.get('/oauth2callback', {
325 'code': 'foo_access_code',
JacobMoshenko8e905102011-06-20 09:53:10 -0400326 'state': 'foo_path',
Joe Gregorio432f17e2011-05-22 23:18:00 -0400327 })
328 self.assertEqual('http://localhost/foo_path', response.headers['Location'])
329 self.assertEqual(None, self.decorator.credentials)
330
Joe Gregorio562b7312011-09-15 09:06:38 -0400331 # Now requesting the decorated path should work.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400332 response = self.app.get('/foo_path')
333 self.assertEqual('200 OK', response.status)
334 self.assertEqual(True, self.decorator.has_credentials())
JacobMoshenko8e905102011-06-20 09:53:10 -0400335 self.assertEqual('foo_refresh_token',
336 self.decorator.credentials.refresh_token)
337 self.assertEqual('foo_access_token',
338 self.decorator.credentials.access_token)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400339
Joe Gregorio562b7312011-09-15 09:06:38 -0400340 # Invalidate the stored Credentials.
Joe Gregorio9da2ad82011-09-11 14:04:44 -0400341 self.decorator.credentials.invalid = True
342 self.decorator.credentials.store.put(self.decorator.credentials)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400343
Joe Gregorio562b7312011-09-15 09:06:38 -0400344 # Invalid Credentials should start the OAuth dance again.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400345 response = self.app.get('/foo_path')
346 self.assertTrue(response.status.startswith('302'))
347 q = parse_qs(response.headers['Location'].split('?', 1)[1])
348 self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0])
349
Joe Gregorioec75dc12012-02-06 13:40:42 -0500350 def test_storage_delete(self):
351 # An initial request to an oauth_required decorated path should be a
352 # redirect to start the OAuth dance.
353 response = self.app.get('/foo_path')
354 self.assertTrue(response.status.startswith('302'))
355
356 # Now simulate the callback to /oauth2callback.
357 response = self.app.get('/oauth2callback', {
358 'code': 'foo_access_code',
359 'state': 'foo_path',
360 })
361 self.assertEqual('http://localhost/foo_path', response.headers['Location'])
362 self.assertEqual(None, self.decorator.credentials)
363
364 # Now requesting the decorated path should work.
365 response = self.app.get('/foo_path')
366
367 # Invalidate the stored Credentials.
368 self.decorator.credentials.store.delete()
369
370 # Invalid Credentials should start the OAuth dance again.
371 response = self.app.get('/foo_path')
372 self.assertTrue(response.status.startswith('302'))
373
Joe Gregorio432f17e2011-05-22 23:18:00 -0400374 def test_aware(self):
Joe Gregorio562b7312011-09-15 09:06:38 -0400375 # An initial request to an oauth_aware decorated path should not redirect.
Joe Gregorio17774972012-03-01 11:11:59 -0500376 response = self.app.get('/bar_path/2012/01')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400377 self.assertEqual('Hello World!', response.body)
378 self.assertEqual('200 OK', response.status)
379 self.assertEqual(False, self.decorator.has_credentials())
380 url = self.decorator.authorize_url()
381 q = parse_qs(url.split('?', 1)[1])
382 self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0])
383 self.assertEqual('foo_client_id', q['client_id'][0])
Joe Gregoriof2f8a5a2011-10-14 15:11:29 -0400384 self.assertEqual('foo_scope bar_scope', q['scope'][0])
Joe Gregorio17774972012-03-01 11:11:59 -0500385 self.assertEqual('http://localhost/bar_path/2012/01', q['state'][0])
Joe Gregorio432f17e2011-05-22 23:18:00 -0400386 self.assertEqual('code', q['response_type'][0])
387
Joe Gregorio562b7312011-09-15 09:06:38 -0400388 # Now simulate the callback to /oauth2callback.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400389 url = self.decorator.authorize_url()
390 response = self.app.get('/oauth2callback', {
391 'code': 'foo_access_code',
JacobMoshenko8e905102011-06-20 09:53:10 -0400392 'state': 'bar_path',
Joe Gregorio432f17e2011-05-22 23:18:00 -0400393 })
394 self.assertEqual('http://localhost/bar_path', response.headers['Location'])
395 self.assertEqual(False, self.decorator.has_credentials())
396
Joe Gregorio562b7312011-09-15 09:06:38 -0400397 # Now requesting the decorated path will have credentials.
Joe Gregorio17774972012-03-01 11:11:59 -0500398 response = self.app.get('/bar_path/2012/01')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400399 self.assertEqual('200 OK', response.status)
400 self.assertEqual('Hello World!', response.body)
401 self.assertEqual(True, self.decorator.has_credentials())
JacobMoshenko8e905102011-06-20 09:53:10 -0400402 self.assertEqual('foo_refresh_token',
403 self.decorator.credentials.refresh_token)
404 self.assertEqual('foo_access_token',
405 self.decorator.credentials.access_token)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400406
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500407
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400408 def test_error_in_step2(self):
409 # An initial request to an oauth_aware decorated path should not redirect.
410 response = self.app.get('/bar_path/2012/01')
411 url = self.decorator.authorize_url()
412 response = self.app.get('/oauth2callback', {
413 'error': 'BadStuffHappened'
414 })
415 self.assertEqual('200 OK', response.status)
416 self.assertTrue('BadStuffHappened' in response.body)
417
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500418 def test_kwargs_are_passed_to_underlying_flow(self):
419 decorator = OAuth2Decorator(client_id='foo_client_id',
420 client_secret='foo_client_secret',
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100421 user_agent='foo_user_agent',
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500422 scope=['foo_scope', 'bar_scope'],
423 access_type='offline',
424 approval_prompt='force')
425 self.assertEqual('offline', decorator.flow.params['access_type'])
426 self.assertEqual('force', decorator.flow.params['approval_prompt'])
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100427 self.assertEqual('foo_user_agent', decorator.flow.user_agent)
428 self.assertEqual(None, decorator.flow.params.get('user_agent', None))
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500429
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400430 def test_decorator_from_client_secrets(self):
431 decorator = oauth2decorator_from_clientsecrets(
432 datafile('client_secrets.json'),
433 scope=['foo_scope', 'bar_scope'])
434 self._finish_setup(decorator, user_mock=UserMock)
435
436 self.assertFalse(decorator._in_error)
437 self.decorator = decorator
438 self.test_required()
439 http = self.decorator.http()
440 self.assertEquals('foo_access_token', http.request.credentials.access_token)
441
442 def test_decorator_from_client_secrets_not_logged_in_required(self):
443 decorator = oauth2decorator_from_clientsecrets(
444 datafile('client_secrets.json'),
445 scope=['foo_scope', 'bar_scope'], message='NotLoggedInMessage')
446 self.decorator = decorator
447 self._finish_setup(decorator, user_mock=UserNotLoggedInMock)
448
449 self.assertFalse(decorator._in_error)
450
451 # An initial request to an oauth_required decorated path should be a
452 # redirect to login.
453 response = self.app.get('/foo_path')
454 self.assertTrue(response.status.startswith('302'))
455 self.assertTrue('Login' in str(response))
456
457 def test_decorator_from_client_secrets_not_logged_in_aware(self):
458 decorator = oauth2decorator_from_clientsecrets(
459 datafile('client_secrets.json'),
460 scope=['foo_scope', 'bar_scope'], message='NotLoggedInMessage')
461 self.decorator = decorator
462 self._finish_setup(decorator, user_mock=UserNotLoggedInMock)
463
464 # An initial request to an oauth_aware decorated path should be a
465 # redirect to login.
466 response = self.app.get('/bar_path/2012/03')
467 self.assertTrue(response.status.startswith('302'))
468 self.assertTrue('Login' in str(response))
469
470 def test_decorator_from_unfilled_client_secrets_required(self):
471 MESSAGE = 'File is missing'
472 decorator = oauth2decorator_from_clientsecrets(
473 datafile('unfilled_client_secrets.json'),
474 scope=['foo_scope', 'bar_scope'], message=MESSAGE)
475 self._finish_setup(decorator, user_mock=UserNotLoggedInMock)
476 self.assertTrue(decorator._in_error)
477 self.assertEqual(MESSAGE, decorator._message)
478
479 # An initial request to an oauth_required decorated path should be an
480 # error message.
481 response = self.app.get('/foo_path')
482 self.assertTrue(response.status.startswith('200'))
483 self.assertTrue(MESSAGE in str(response))
484
485 def test_decorator_from_unfilled_client_secrets_aware(self):
486 MESSAGE = 'File is missing'
487 decorator = oauth2decorator_from_clientsecrets(
488 datafile('unfilled_client_secrets.json'),
489 scope=['foo_scope', 'bar_scope'], message=MESSAGE)
490 self._finish_setup(decorator, user_mock=UserNotLoggedInMock)
491 self.assertTrue(decorator._in_error)
492 self.assertEqual(MESSAGE, decorator._message)
493
494 # An initial request to an oauth_aware decorated path should be an
495 # error message.
496 response = self.app.get('/bar_path/2012/03')
497 self.assertTrue(response.status.startswith('200'))
498 self.assertTrue(MESSAGE in str(response))
499
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500500
Joe Gregorio432f17e2011-05-22 23:18:00 -0400501if __name__ == '__main__':
502 unittest.main()