blob: a11c5e99194e67051d892d66eaa8e6711f209430 [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 Gregorio08cdcb82012-03-14 00:09:33 -040054from oauth2client.appengine import FlowProperty
Joe Gregorioe84c9442012-03-12 08:45:57 -040055from oauth2client.appengine import CredentialsModel
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 Gregorio08cdcb82012-03-14 00:09:33 -040067DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
68
69
70def datafile(filename):
71 return os.path.join(DATA_DIR, filename)
72
73
Joe Gregorio432f17e2011-05-22 23:18:00 -040074class UserMock(object):
75 """Mock the app engine user service"""
JacobMoshenko8e905102011-06-20 09:53:10 -040076
Joe Gregorio08cdcb82012-03-14 00:09:33 -040077 def __call__(self):
78 return self
79
Joe Gregorio432f17e2011-05-22 23:18:00 -040080 def user_id(self):
81 return 'foo_user'
82
83
Joe Gregorio08cdcb82012-03-14 00:09:33 -040084class UserNotLoggedInMock(object):
85 """Mock the app engine user service"""
86
87 def __call__(self):
88 return None
89
90
Joe Gregorio432f17e2011-05-22 23:18:00 -040091class Http2Mock(object):
92 """Mock httplib2.Http"""
93 status = 200
94 content = {
95 'access_token': 'foo_access_token',
96 'refresh_token': 'foo_refresh_token',
JacobMoshenko8e905102011-06-20 09:53:10 -040097 'expires_in': 3600,
Joe Gregorio432f17e2011-05-22 23:18:00 -040098 }
99
100 def request(self, token_uri, method, body, headers, *args, **kwargs):
101 self.body = body
102 self.headers = headers
103 return (self, simplejson.dumps(self.content))
104
105
JacobMoshenko8e905102011-06-20 09:53:10 -0400106class TestAppAssertionCredentials(unittest.TestCase):
107 account_name = "service_account_name@appspot.com"
108 signature = "signature"
109
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500110
JacobMoshenko8e905102011-06-20 09:53:10 -0400111 class AppIdentityStubImpl(apiproxy_stub.APIProxyStub):
112
113 def __init__(self):
114 super(TestAppAssertionCredentials.AppIdentityStubImpl, self).__init__(
115 'app_identity_service')
116
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500117 def _Dynamic_GetAccessToken(self, request, response):
118 response.set_access_token('a_token_123')
119 response.set_expiration_time(time.time() + 1800)
JacobMoshenko8e905102011-06-20 09:53:10 -0400120
JacobMoshenko8e905102011-06-20 09:53:10 -0400121
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500122 class ErroringAppIdentityStubImpl(apiproxy_stub.APIProxyStub):
123
124 def __init__(self):
125 super(TestAppAssertionCredentials.ErroringAppIdentityStubImpl, self).__init__(
126 'app_identity_service')
127
128 def _Dynamic_GetAccessToken(self, request, response):
129 raise app_identity.BackendDeadlineExceeded()
130
131 def test_raise_correct_type_of_exception(self):
132 app_identity_stub = self.ErroringAppIdentityStubImpl()
133 apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
JacobMoshenko8e905102011-06-20 09:53:10 -0400134 apiproxy_stub_map.apiproxy.RegisterStub("app_identity_service",
135 app_identity_stub)
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500136 apiproxy_stub_map.apiproxy.RegisterStub(
137 'memcache', memcache_stub.MemcacheServiceStub())
JacobMoshenko8e905102011-06-20 09:53:10 -0400138
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500139 scope = "http://www.googleapis.com/scope"
140 try:
141 credentials = AppAssertionCredentials(scope)
142 http = httplib2.Http()
143 credentials.refresh(http)
144 self.fail('Should have raised an AccessTokenRefreshError')
145 except AccessTokenRefreshError:
146 pass
JacobMoshenko8e905102011-06-20 09:53:10 -0400147
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500148 def test_get_access_token_on_refresh(self):
149 app_identity_stub = self.AppIdentityStubImpl()
150 apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
151 apiproxy_stub_map.apiproxy.RegisterStub("app_identity_service",
152 app_identity_stub)
153 apiproxy_stub_map.apiproxy.RegisterStub(
154 'memcache', memcache_stub.MemcacheServiceStub())
JacobMoshenko8e905102011-06-20 09:53:10 -0400155
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400156 scope = ["http://www.googleapis.com/scope"]
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500157 credentials = AppAssertionCredentials(scope)
158 http = httplib2.Http()
159 credentials.refresh(http)
160 self.assertEqual('a_token_123', credentials.access_token)
JacobMoshenko8e905102011-06-20 09:53:10 -0400161
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400162 json = credentials.to_json()
163 credentials = Credentials.new_from_json(json)
164 self.assertEqual(scope[0], credentials.scope)
165
166
167class TestFlowModel(db.Model):
168 flow = FlowProperty()
169
170
171class FlowPropertyTest(unittest.TestCase):
172
173 def setUp(self):
174 self.testbed = testbed.Testbed()
175 self.testbed.activate()
176 self.testbed.init_datastore_v3_stub()
177
178 def tearDown(self):
179 self.testbed.deactivate()
180
181 def test_flow_get_put(self):
182 instance = TestFlowModel(
183 flow=flow_from_clientsecrets(datafile('client_secrets.json'), 'foo'),
184 key_name='foo'
185 )
186 instance.put()
187 retrieved = TestFlowModel.get_by_key_name('foo')
188
189 self.assertEqual('foo_client_id', retrieved.flow.client_id)
190
JacobMoshenko8e905102011-06-20 09:53:10 -0400191
Joe Gregorioe84c9442012-03-12 08:45:57 -0400192def _http_request(*args, **kwargs):
193 resp = httplib2.Response({'status': '200'})
194 content = simplejson.dumps({'access_token': 'bar'})
195
196 return resp, content
197
198
199class StorageByKeyNameTest(unittest.TestCase):
200
201 def setUp(self):
202 self.testbed = testbed.Testbed()
203 self.testbed.activate()
204 self.testbed.init_datastore_v3_stub()
205 self.testbed.init_memcache_stub()
206 self.testbed.init_user_stub()
207
208 access_token = "foo"
209 client_id = "some_client_id"
210 client_secret = "cOuDdkfjxxnv+"
211 refresh_token = "1/0/a.df219fjls0"
212 token_expiry = datetime.datetime.utcnow()
213 token_uri = "https://www.google.com/accounts/o8/oauth2/token"
214 user_agent = "refresh_checker/1.0"
215 self.credentials = OAuth2Credentials(
216 access_token, client_id, client_secret,
217 refresh_token, token_expiry, token_uri,
218 user_agent)
219
220 def tearDown(self):
221 self.testbed.deactivate()
222
223 def test_get_and_put_simple(self):
224 storage = StorageByKeyName(
225 CredentialsModel, 'foo', 'credentials')
226
227 self.assertEqual(None, storage.get())
228 self.credentials.set_store(storage)
229
230 self.credentials._refresh(_http_request)
231 credmodel = CredentialsModel.get_by_key_name('foo')
232 self.assertEqual('bar', credmodel.credentials.access_token)
233
234 def test_get_and_put_cached(self):
235 storage = StorageByKeyName(
236 CredentialsModel, 'foo', 'credentials', cache=memcache)
237
238 self.assertEqual(None, storage.get())
239 self.credentials.set_store(storage)
240
241 self.credentials._refresh(_http_request)
242 credmodel = CredentialsModel.get_by_key_name('foo')
243 self.assertEqual('bar', credmodel.credentials.access_token)
244
245 # Now remove the item from the cache.
246 memcache.delete('foo')
247
248 # Check that getting refreshes the cache.
249 credentials = storage.get()
250 self.assertEqual('bar', credentials.access_token)
251 self.assertNotEqual(None, memcache.get('foo'))
252
253 # Deleting should clear the cache.
254 storage.delete()
255 credentials = storage.get()
256 self.assertEqual(None, credentials)
257 self.assertEqual(None, memcache.get('foo'))
258
259
Joe Gregorio432f17e2011-05-22 23:18:00 -0400260class DecoratorTests(unittest.TestCase):
261
262 def setUp(self):
263 self.testbed = testbed.Testbed()
264 self.testbed.activate()
265 self.testbed.init_datastore_v3_stub()
266 self.testbed.init_memcache_stub()
267 self.testbed.init_user_stub()
268
269 decorator = OAuth2Decorator(client_id='foo_client_id',
270 client_secret='foo_client_secret',
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100271 scope=['foo_scope', 'bar_scope'],
272 user_agent='foo')
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400273
274 self._finish_setup(decorator, user_mock=UserMock)
275
276 def _finish_setup(self, decorator, user_mock):
Joe Gregorio432f17e2011-05-22 23:18:00 -0400277 self.decorator = decorator
278
Joe Gregorio17774972012-03-01 11:11:59 -0500279 class TestRequiredHandler(webapp2.RequestHandler):
JacobMoshenko8e905102011-06-20 09:53:10 -0400280
Joe Gregorio432f17e2011-05-22 23:18:00 -0400281 @decorator.oauth_required
282 def get(self):
283 pass
284
Joe Gregorio17774972012-03-01 11:11:59 -0500285 class TestAwareHandler(webapp2.RequestHandler):
JacobMoshenko8e905102011-06-20 09:53:10 -0400286
Joe Gregorio432f17e2011-05-22 23:18:00 -0400287 @decorator.oauth_aware
Joe Gregorio17774972012-03-01 11:11:59 -0500288 def get(self, *args, **kwargs):
Joe Gregorio432f17e2011-05-22 23:18:00 -0400289 self.response.out.write('Hello World!')
Joe Gregorio17774972012-03-01 11:11:59 -0500290 assert(kwargs['year'] == '2012')
291 assert(kwargs['month'] == '01')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400292
293
Joe Gregorio17774972012-03-01 11:11:59 -0500294 application = webapp2.WSGIApplication([
295 ('/oauth2callback', OAuth2Handler),
296 ('/foo_path', TestRequiredHandler),
297 webapp2.Route(r'/bar_path/<year:\d{4}>/<month:\d{2}>',
298 handler=TestAwareHandler, name='bar')],
299 debug=True)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400300 self.app = TestApp(application)
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400301 users.get_current_user = user_mock()
Joe Gregorio922b78c2011-05-26 21:36:34 -0400302 self.httplib2_orig = httplib2.Http
Joe Gregorio432f17e2011-05-22 23:18:00 -0400303 httplib2.Http = Http2Mock
304
305 def tearDown(self):
306 self.testbed.deactivate()
Joe Gregorio922b78c2011-05-26 21:36:34 -0400307 httplib2.Http = self.httplib2_orig
Joe Gregorio432f17e2011-05-22 23:18:00 -0400308
309 def test_required(self):
310 # An initial request to an oauth_required decorated path should be a
311 # redirect to start the OAuth dance.
312 response = self.app.get('/foo_path')
313 self.assertTrue(response.status.startswith('302'))
314 q = parse_qs(response.headers['Location'].split('?', 1)[1])
315 self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0])
316 self.assertEqual('foo_client_id', q['client_id'][0])
Joe Gregoriof2f8a5a2011-10-14 15:11:29 -0400317 self.assertEqual('foo_scope bar_scope', q['scope'][0])
Joe Gregorio432f17e2011-05-22 23:18:00 -0400318 self.assertEqual('http://localhost/foo_path', q['state'][0])
319 self.assertEqual('code', q['response_type'][0])
320 self.assertEqual(False, self.decorator.has_credentials())
321
Joe Gregorio562b7312011-09-15 09:06:38 -0400322 # Now simulate the callback to /oauth2callback.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400323 response = self.app.get('/oauth2callback', {
324 'code': 'foo_access_code',
JacobMoshenko8e905102011-06-20 09:53:10 -0400325 'state': 'foo_path',
Joe Gregorio432f17e2011-05-22 23:18:00 -0400326 })
327 self.assertEqual('http://localhost/foo_path', response.headers['Location'])
328 self.assertEqual(None, self.decorator.credentials)
329
Joe Gregorio562b7312011-09-15 09:06:38 -0400330 # Now requesting the decorated path should work.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400331 response = self.app.get('/foo_path')
332 self.assertEqual('200 OK', response.status)
333 self.assertEqual(True, self.decorator.has_credentials())
JacobMoshenko8e905102011-06-20 09:53:10 -0400334 self.assertEqual('foo_refresh_token',
335 self.decorator.credentials.refresh_token)
336 self.assertEqual('foo_access_token',
337 self.decorator.credentials.access_token)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400338
Joe Gregorio562b7312011-09-15 09:06:38 -0400339 # Invalidate the stored Credentials.
Joe Gregorio9da2ad82011-09-11 14:04:44 -0400340 self.decorator.credentials.invalid = True
341 self.decorator.credentials.store.put(self.decorator.credentials)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400342
Joe Gregorio562b7312011-09-15 09:06:38 -0400343 # Invalid Credentials should start the OAuth dance again.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400344 response = self.app.get('/foo_path')
345 self.assertTrue(response.status.startswith('302'))
346 q = parse_qs(response.headers['Location'].split('?', 1)[1])
347 self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0])
348
Joe Gregorioec75dc12012-02-06 13:40:42 -0500349 def test_storage_delete(self):
350 # An initial request to an oauth_required decorated path should be a
351 # redirect to start the OAuth dance.
352 response = self.app.get('/foo_path')
353 self.assertTrue(response.status.startswith('302'))
354
355 # Now simulate the callback to /oauth2callback.
356 response = self.app.get('/oauth2callback', {
357 'code': 'foo_access_code',
358 'state': 'foo_path',
359 })
360 self.assertEqual('http://localhost/foo_path', response.headers['Location'])
361 self.assertEqual(None, self.decorator.credentials)
362
363 # Now requesting the decorated path should work.
364 response = self.app.get('/foo_path')
365
366 # Invalidate the stored Credentials.
367 self.decorator.credentials.store.delete()
368
369 # Invalid Credentials should start the OAuth dance again.
370 response = self.app.get('/foo_path')
371 self.assertTrue(response.status.startswith('302'))
372
Joe Gregorio432f17e2011-05-22 23:18:00 -0400373 def test_aware(self):
Joe Gregorio562b7312011-09-15 09:06:38 -0400374 # An initial request to an oauth_aware decorated path should not redirect.
Joe Gregorio17774972012-03-01 11:11:59 -0500375 response = self.app.get('/bar_path/2012/01')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400376 self.assertEqual('Hello World!', response.body)
377 self.assertEqual('200 OK', response.status)
378 self.assertEqual(False, self.decorator.has_credentials())
379 url = self.decorator.authorize_url()
380 q = parse_qs(url.split('?', 1)[1])
381 self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0])
382 self.assertEqual('foo_client_id', q['client_id'][0])
Joe Gregoriof2f8a5a2011-10-14 15:11:29 -0400383 self.assertEqual('foo_scope bar_scope', q['scope'][0])
Joe Gregorio17774972012-03-01 11:11:59 -0500384 self.assertEqual('http://localhost/bar_path/2012/01', q['state'][0])
Joe Gregorio432f17e2011-05-22 23:18:00 -0400385 self.assertEqual('code', q['response_type'][0])
386
Joe Gregorio562b7312011-09-15 09:06:38 -0400387 # Now simulate the callback to /oauth2callback.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400388 url = self.decorator.authorize_url()
389 response = self.app.get('/oauth2callback', {
390 'code': 'foo_access_code',
JacobMoshenko8e905102011-06-20 09:53:10 -0400391 'state': 'bar_path',
Joe Gregorio432f17e2011-05-22 23:18:00 -0400392 })
393 self.assertEqual('http://localhost/bar_path', response.headers['Location'])
394 self.assertEqual(False, self.decorator.has_credentials())
395
Joe Gregorio562b7312011-09-15 09:06:38 -0400396 # Now requesting the decorated path will have credentials.
Joe Gregorio17774972012-03-01 11:11:59 -0500397 response = self.app.get('/bar_path/2012/01')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400398 self.assertEqual('200 OK', response.status)
399 self.assertEqual('Hello World!', response.body)
400 self.assertEqual(True, self.decorator.has_credentials())
JacobMoshenko8e905102011-06-20 09:53:10 -0400401 self.assertEqual('foo_refresh_token',
402 self.decorator.credentials.refresh_token)
403 self.assertEqual('foo_access_token',
404 self.decorator.credentials.access_token)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400405
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500406
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400407 def test_error_in_step2(self):
408 # An initial request to an oauth_aware decorated path should not redirect.
409 response = self.app.get('/bar_path/2012/01')
410 url = self.decorator.authorize_url()
411 response = self.app.get('/oauth2callback', {
412 'error': 'BadStuffHappened'
413 })
414 self.assertEqual('200 OK', response.status)
415 self.assertTrue('BadStuffHappened' in response.body)
416
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500417 def test_kwargs_are_passed_to_underlying_flow(self):
418 decorator = OAuth2Decorator(client_id='foo_client_id',
419 client_secret='foo_client_secret',
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100420 user_agent='foo_user_agent',
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500421 scope=['foo_scope', 'bar_scope'],
422 access_type='offline',
423 approval_prompt='force')
424 self.assertEqual('offline', decorator.flow.params['access_type'])
425 self.assertEqual('force', decorator.flow.params['approval_prompt'])
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100426 self.assertEqual('foo_user_agent', decorator.flow.user_agent)
427 self.assertEqual(None, decorator.flow.params.get('user_agent', None))
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500428
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400429 def test_decorator_from_client_secrets(self):
430 decorator = oauth2decorator_from_clientsecrets(
431 datafile('client_secrets.json'),
432 scope=['foo_scope', 'bar_scope'])
433 self._finish_setup(decorator, user_mock=UserMock)
434
435 self.assertFalse(decorator._in_error)
436 self.decorator = decorator
437 self.test_required()
438 http = self.decorator.http()
439 self.assertEquals('foo_access_token', http.request.credentials.access_token)
440
441 def test_decorator_from_client_secrets_not_logged_in_required(self):
442 decorator = oauth2decorator_from_clientsecrets(
443 datafile('client_secrets.json'),
444 scope=['foo_scope', 'bar_scope'], message='NotLoggedInMessage')
445 self.decorator = decorator
446 self._finish_setup(decorator, user_mock=UserNotLoggedInMock)
447
448 self.assertFalse(decorator._in_error)
449
450 # An initial request to an oauth_required decorated path should be a
451 # redirect to login.
452 response = self.app.get('/foo_path')
453 self.assertTrue(response.status.startswith('302'))
454 self.assertTrue('Login' in str(response))
455
456 def test_decorator_from_client_secrets_not_logged_in_aware(self):
457 decorator = oauth2decorator_from_clientsecrets(
458 datafile('client_secrets.json'),
459 scope=['foo_scope', 'bar_scope'], message='NotLoggedInMessage')
460 self.decorator = decorator
461 self._finish_setup(decorator, user_mock=UserNotLoggedInMock)
462
463 # An initial request to an oauth_aware decorated path should be a
464 # redirect to login.
465 response = self.app.get('/bar_path/2012/03')
466 self.assertTrue(response.status.startswith('302'))
467 self.assertTrue('Login' in str(response))
468
469 def test_decorator_from_unfilled_client_secrets_required(self):
470 MESSAGE = 'File is missing'
471 decorator = oauth2decorator_from_clientsecrets(
472 datafile('unfilled_client_secrets.json'),
473 scope=['foo_scope', 'bar_scope'], message=MESSAGE)
474 self._finish_setup(decorator, user_mock=UserNotLoggedInMock)
475 self.assertTrue(decorator._in_error)
476 self.assertEqual(MESSAGE, decorator._message)
477
478 # An initial request to an oauth_required decorated path should be an
479 # error message.
480 response = self.app.get('/foo_path')
481 self.assertTrue(response.status.startswith('200'))
482 self.assertTrue(MESSAGE in str(response))
483
484 def test_decorator_from_unfilled_client_secrets_aware(self):
485 MESSAGE = 'File is missing'
486 decorator = oauth2decorator_from_clientsecrets(
487 datafile('unfilled_client_secrets.json'),
488 scope=['foo_scope', 'bar_scope'], message=MESSAGE)
489 self._finish_setup(decorator, user_mock=UserNotLoggedInMock)
490 self.assertTrue(decorator._in_error)
491 self.assertEqual(MESSAGE, decorator._message)
492
493 # An initial request to an oauth_aware decorated path should be an
494 # error message.
495 response = self.app.get('/bar_path/2012/03')
496 self.assertTrue(response.status.startswith('200'))
497 self.assertTrue(MESSAGE in str(response))
498
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500499
Joe Gregorio432f17e2011-05-22 23:18:00 -0400500if __name__ == '__main__':
501 unittest.main()