Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 1 | #!/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 | |
| 20 | Unit tests for objects created from discovery documents. |
| 21 | """ |
| 22 | |
| 23 | __author__ = 'jcgregorio@google.com (Joe Gregorio)' |
| 24 | |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 25 | import base64 |
Joe Gregorio | e84c944 | 2012-03-12 08:45:57 -0400 | [diff] [blame] | 26 | import datetime |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 27 | import httplib2 |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 28 | import os |
Joe Gregorio | d84d6b8 | 2012-02-28 14:53:00 -0500 | [diff] [blame] | 29 | import time |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 30 | import unittest |
| 31 | import urlparse |
| 32 | |
| 33 | try: |
| 34 | from urlparse import parse_qs |
| 35 | except ImportError: |
| 36 | from cgi import parse_qs |
| 37 | |
Joe Gregorio | 8b4c173 | 2011-12-06 11:28:29 -0500 | [diff] [blame] | 38 | import dev_appserver |
| 39 | dev_appserver.fix_sys_path() |
Joe Gregorio | 1777497 | 2012-03-01 11:11:59 -0500 | [diff] [blame] | 40 | import webapp2 |
Joe Gregorio | 8b4c173 | 2011-12-06 11:28:29 -0500 | [diff] [blame] | 41 | |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 42 | from apiclient.http import HttpMockSequence |
| 43 | from google.appengine.api import apiproxy_stub |
| 44 | from google.appengine.api import apiproxy_stub_map |
Joe Gregorio | d84d6b8 | 2012-02-28 14:53:00 -0500 | [diff] [blame] | 45 | from google.appengine.api import app_identity |
Joe Gregorio | e84c944 | 2012-03-12 08:45:57 -0400 | [diff] [blame] | 46 | from google.appengine.api import memcache |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 47 | from google.appengine.api import users |
Joe Gregorio | d84d6b8 | 2012-02-28 14:53:00 -0500 | [diff] [blame] | 48 | from google.appengine.api.memcache import memcache_stub |
Joe Gregorio | e84c944 | 2012-03-12 08:45:57 -0400 | [diff] [blame] | 49 | from google.appengine.ext import db |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 50 | from google.appengine.ext import testbed |
Joe Gregorio | d84d6b8 | 2012-02-28 14:53:00 -0500 | [diff] [blame] | 51 | from google.appengine.runtime import apiproxy_errors |
Joe Gregorio | 549230c | 2012-01-11 10:38:05 -0500 | [diff] [blame] | 52 | from oauth2client.anyjson import simplejson |
Joe Gregorio | c29aaa9 | 2012-07-16 16:16:31 -0400 | [diff] [blame] | 53 | from oauth2client.clientsecrets import _loadfile |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 54 | from oauth2client.appengine import AppAssertionCredentials |
Joe Gregorio | e84c944 | 2012-03-12 08:45:57 -0400 | [diff] [blame] | 55 | from oauth2client.appengine import CredentialsModel |
Joe Gregorio | 4fbde1c | 2012-07-11 14:47:39 -0400 | [diff] [blame] | 56 | from oauth2client.appengine import FlowProperty |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 57 | from oauth2client.appengine import OAuth2Decorator |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 58 | from oauth2client.appengine import OAuth2Handler |
Joe Gregorio | e84c944 | 2012-03-12 08:45:57 -0400 | [diff] [blame] | 59 | from oauth2client.appengine import StorageByKeyName |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 60 | from oauth2client.appengine import oauth2decorator_from_clientsecrets |
Joe Gregorio | 549230c | 2012-01-11 10:38:05 -0500 | [diff] [blame] | 61 | from oauth2client.client import AccessTokenRefreshError |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 62 | from oauth2client.client import Credentials |
Joe Gregorio | 549230c | 2012-01-11 10:38:05 -0500 | [diff] [blame] | 63 | from oauth2client.client import FlowExchangeError |
Joe Gregorio | e84c944 | 2012-03-12 08:45:57 -0400 | [diff] [blame] | 64 | from oauth2client.client import OAuth2Credentials |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 65 | from oauth2client.client import flow_from_clientsecrets |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 66 | from webtest import TestApp |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 67 | |
Joe Gregorio | 4fbde1c | 2012-07-11 14:47:39 -0400 | [diff] [blame] | 68 | |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 69 | DATA_DIR = os.path.join(os.path.dirname(__file__), 'data') |
| 70 | |
| 71 | |
| 72 | def datafile(filename): |
| 73 | return os.path.join(DATA_DIR, filename) |
| 74 | |
| 75 | |
Joe Gregorio | c29aaa9 | 2012-07-16 16:16:31 -0400 | [diff] [blame] | 76 | def 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 | |
| 81 | class 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 Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 94 | class UserMock(object): |
| 95 | """Mock the app engine user service""" |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 96 | |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 97 | def __call__(self): |
| 98 | return self |
| 99 | |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 100 | def user_id(self): |
| 101 | return 'foo_user' |
| 102 | |
| 103 | |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 104 | class UserNotLoggedInMock(object): |
| 105 | """Mock the app engine user service""" |
| 106 | |
| 107 | def __call__(self): |
| 108 | return None |
| 109 | |
| 110 | |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 111 | class Http2Mock(object): |
| 112 | """Mock httplib2.Http""" |
| 113 | status = 200 |
| 114 | content = { |
| 115 | 'access_token': 'foo_access_token', |
| 116 | 'refresh_token': 'foo_refresh_token', |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 117 | 'expires_in': 3600, |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 118 | } |
| 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 | |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 126 | class TestAppAssertionCredentials(unittest.TestCase): |
| 127 | account_name = "service_account_name@appspot.com" |
| 128 | signature = "signature" |
| 129 | |
Joe Gregorio | d84d6b8 | 2012-02-28 14:53:00 -0500 | [diff] [blame] | 130 | |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 131 | class AppIdentityStubImpl(apiproxy_stub.APIProxyStub): |
| 132 | |
| 133 | def __init__(self): |
| 134 | super(TestAppAssertionCredentials.AppIdentityStubImpl, self).__init__( |
| 135 | 'app_identity_service') |
| 136 | |
Joe Gregorio | d84d6b8 | 2012-02-28 14:53:00 -0500 | [diff] [blame] | 137 | def _Dynamic_GetAccessToken(self, request, response): |
| 138 | response.set_access_token('a_token_123') |
| 139 | response.set_expiration_time(time.time() + 1800) |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 140 | |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 141 | |
Joe Gregorio | d84d6b8 | 2012-02-28 14:53:00 -0500 | [diff] [blame] | 142 | 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() |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 154 | apiproxy_stub_map.apiproxy.RegisterStub("app_identity_service", |
| 155 | app_identity_stub) |
Joe Gregorio | d84d6b8 | 2012-02-28 14:53:00 -0500 | [diff] [blame] | 156 | apiproxy_stub_map.apiproxy.RegisterStub( |
| 157 | 'memcache', memcache_stub.MemcacheServiceStub()) |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 158 | |
Joe Gregorio | d84d6b8 | 2012-02-28 14:53:00 -0500 | [diff] [blame] | 159 | 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 |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 167 | |
Joe Gregorio | d84d6b8 | 2012-02-28 14:53:00 -0500 | [diff] [blame] | 168 | 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()) |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 175 | |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 176 | scope = ["http://www.googleapis.com/scope"] |
Joe Gregorio | d84d6b8 | 2012-02-28 14:53:00 -0500 | [diff] [blame] | 177 | credentials = AppAssertionCredentials(scope) |
| 178 | http = httplib2.Http() |
| 179 | credentials.refresh(http) |
| 180 | self.assertEqual('a_token_123', credentials.access_token) |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 181 | |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 182 | json = credentials.to_json() |
| 183 | credentials = Credentials.new_from_json(json) |
| 184 | self.assertEqual(scope[0], credentials.scope) |
| 185 | |
| 186 | |
| 187 | class TestFlowModel(db.Model): |
| 188 | flow = FlowProperty() |
| 189 | |
| 190 | |
| 191 | class 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 | |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 211 | |
Joe Gregorio | e84c944 | 2012-03-12 08:45:57 -0400 | [diff] [blame] | 212 | def _http_request(*args, **kwargs): |
| 213 | resp = httplib2.Response({'status': '200'}) |
| 214 | content = simplejson.dumps({'access_token': 'bar'}) |
| 215 | |
| 216 | return resp, content |
| 217 | |
| 218 | |
| 219 | class 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 Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 280 | class 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 Euphrosine | acf517f | 2012-02-13 21:08:33 +0100 | [diff] [blame] | 291 | scope=['foo_scope', 'bar_scope'], |
| 292 | user_agent='foo') |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 293 | |
| 294 | self._finish_setup(decorator, user_mock=UserMock) |
| 295 | |
| 296 | def _finish_setup(self, decorator, user_mock): |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 297 | self.decorator = decorator |
| 298 | |
Joe Gregorio | 1777497 | 2012-03-01 11:11:59 -0500 | [diff] [blame] | 299 | class TestRequiredHandler(webapp2.RequestHandler): |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 300 | |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 301 | @decorator.oauth_required |
| 302 | def get(self): |
| 303 | pass |
| 304 | |
Joe Gregorio | 1777497 | 2012-03-01 11:11:59 -0500 | [diff] [blame] | 305 | class TestAwareHandler(webapp2.RequestHandler): |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 306 | |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 307 | @decorator.oauth_aware |
Joe Gregorio | 1777497 | 2012-03-01 11:11:59 -0500 | [diff] [blame] | 308 | def get(self, *args, **kwargs): |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 309 | self.response.out.write('Hello World!') |
Joe Gregorio | 1777497 | 2012-03-01 11:11:59 -0500 | [diff] [blame] | 310 | assert(kwargs['year'] == '2012') |
| 311 | assert(kwargs['month'] == '01') |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 312 | |
| 313 | |
Joe Gregorio | 1777497 | 2012-03-01 11:11:59 -0500 | [diff] [blame] | 314 | 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 Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 320 | self.app = TestApp(application) |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 321 | users.get_current_user = user_mock() |
Joe Gregorio | 922b78c | 2011-05-26 21:36:34 -0400 | [diff] [blame] | 322 | self.httplib2_orig = httplib2.Http |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 323 | httplib2.Http = Http2Mock |
| 324 | |
| 325 | def tearDown(self): |
| 326 | self.testbed.deactivate() |
Joe Gregorio | 922b78c | 2011-05-26 21:36:34 -0400 | [diff] [blame] | 327 | httplib2.Http = self.httplib2_orig |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 328 | |
| 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 Gregorio | f2f8a5a | 2011-10-14 15:11:29 -0400 | [diff] [blame] | 337 | self.assertEqual('foo_scope bar_scope', q['scope'][0]) |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 338 | 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 Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 342 | # Now simulate the callback to /oauth2callback. |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 343 | response = self.app.get('/oauth2callback', { |
| 344 | 'code': 'foo_access_code', |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 345 | 'state': 'foo_path', |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 346 | }) |
| 347 | self.assertEqual('http://localhost/foo_path', response.headers['Location']) |
| 348 | self.assertEqual(None, self.decorator.credentials) |
| 349 | |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 350 | # Now requesting the decorated path should work. |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 351 | response = self.app.get('/foo_path') |
| 352 | self.assertEqual('200 OK', response.status) |
| 353 | self.assertEqual(True, self.decorator.has_credentials()) |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 354 | self.assertEqual('foo_refresh_token', |
| 355 | self.decorator.credentials.refresh_token) |
| 356 | self.assertEqual('foo_access_token', |
| 357 | self.decorator.credentials.access_token) |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 358 | |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 359 | # Invalidate the stored Credentials. |
Joe Gregorio | 9da2ad8 | 2011-09-11 14:04:44 -0400 | [diff] [blame] | 360 | self.decorator.credentials.invalid = True |
| 361 | self.decorator.credentials.store.put(self.decorator.credentials) |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 362 | |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 363 | # Invalid Credentials should start the OAuth dance again. |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 364 | 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 Gregorio | ec75dc1 | 2012-02-06 13:40:42 -0500 | [diff] [blame] | 369 | 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 Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 393 | def test_aware(self): |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 394 | # An initial request to an oauth_aware decorated path should not redirect. |
Joe Gregorio | 1777497 | 2012-03-01 11:11:59 -0500 | [diff] [blame] | 395 | response = self.app.get('/bar_path/2012/01') |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 396 | 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 Gregorio | f2f8a5a | 2011-10-14 15:11:29 -0400 | [diff] [blame] | 403 | self.assertEqual('foo_scope bar_scope', q['scope'][0]) |
Joe Gregorio | 1777497 | 2012-03-01 11:11:59 -0500 | [diff] [blame] | 404 | self.assertEqual('http://localhost/bar_path/2012/01', q['state'][0]) |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 405 | self.assertEqual('code', q['response_type'][0]) |
| 406 | |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 407 | # Now simulate the callback to /oauth2callback. |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 408 | url = self.decorator.authorize_url() |
| 409 | response = self.app.get('/oauth2callback', { |
| 410 | 'code': 'foo_access_code', |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 411 | 'state': 'bar_path', |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 412 | }) |
| 413 | self.assertEqual('http://localhost/bar_path', response.headers['Location']) |
| 414 | self.assertEqual(False, self.decorator.has_credentials()) |
| 415 | |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 416 | # Now requesting the decorated path will have credentials. |
Joe Gregorio | 1777497 | 2012-03-01 11:11:59 -0500 | [diff] [blame] | 417 | response = self.app.get('/bar_path/2012/01') |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 418 | self.assertEqual('200 OK', response.status) |
| 419 | self.assertEqual('Hello World!', response.body) |
| 420 | self.assertEqual(True, self.decorator.has_credentials()) |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 421 | self.assertEqual('foo_refresh_token', |
| 422 | self.decorator.credentials.refresh_token) |
| 423 | self.assertEqual('foo_access_token', |
| 424 | self.decorator.credentials.access_token) |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 425 | |
Joe Gregorio | 1adde1a | 2012-01-06 12:30:35 -0500 | [diff] [blame] | 426 | |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 427 | 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 Gregorio | 1adde1a | 2012-01-06 12:30:35 -0500 | [diff] [blame] | 437 | def test_kwargs_are_passed_to_underlying_flow(self): |
| 438 | decorator = OAuth2Decorator(client_id='foo_client_id', |
| 439 | client_secret='foo_client_secret', |
Johan Euphrosine | acf517f | 2012-02-13 21:08:33 +0100 | [diff] [blame] | 440 | user_agent='foo_user_agent', |
Joe Gregorio | 1adde1a | 2012-01-06 12:30:35 -0500 | [diff] [blame] | 441 | 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 Euphrosine | acf517f | 2012-02-13 21:08:33 +0100 | [diff] [blame] | 446 | self.assertEqual('foo_user_agent', decorator.flow.user_agent) |
| 447 | self.assertEqual(None, decorator.flow.params.get('user_agent', None)) |
Joe Gregorio | 1adde1a | 2012-01-06 12:30:35 -0500 | [diff] [blame] | 448 | |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 449 | 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 Gregorio | c29aaa9 | 2012-07-16 16:16:31 -0400 | [diff] [blame] | 461 | 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 Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 469 | 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 Gregorio | 1adde1a | 2012-01-06 12:30:35 -0500 | [diff] [blame] | 527 | |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 528 | if __name__ == '__main__': |
| 529 | unittest.main() |