blob: be94fa12db9dede870e4177bd49d028d77cd733a [file] [log] [blame]
Joe Gregorioccc79542011-02-19 00:05:26 -05001#!/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
Joe Gregorio0bc70912011-05-24 15:30:49 -040018"""Oauth2client tests
Joe Gregorioccc79542011-02-19 00:05:26 -050019
Joe Gregorio0bc70912011-05-24 15:30:49 -040020Unit tests for oauth2client.
Joe Gregorioccc79542011-02-19 00:05:26 -050021"""
22
23__author__ = 'jcgregorio@google.com (Joe Gregorio)'
24
Joe Gregorio8b4c1732011-12-06 11:28:29 -050025import base64
Joe Gregorio562b7312011-09-15 09:06:38 -040026import datetime
Joe Gregorioe1de4162011-02-23 11:30:29 -050027import httplib2
Joe Gregorio32d852d2012-06-14 09:08:18 -040028import os
Joe Gregorioccc79542011-02-19 00:05:26 -050029import unittest
30import urlparse
Joe Gregorioe1de4162011-02-23 11:30:29 -050031
Joe Gregorioccc79542011-02-19 00:05:26 -050032try:
33 from urlparse import parse_qs
34except ImportError:
35 from cgi import parse_qs
36
37from apiclient.http import HttpMockSequence
Joe Gregorio549230c2012-01-11 10:38:05 -050038from oauth2client.anyjson import simplejson
Joe Gregorioc29aaa92012-07-16 16:16:31 -040039from oauth2client.clientsecrets import _loadfile
Joe Gregorioccc79542011-02-19 00:05:26 -050040from oauth2client.client import AccessTokenCredentials
41from oauth2client.client import AccessTokenCredentialsError
42from oauth2client.client import AccessTokenRefreshError
JacobMoshenko8e905102011-06-20 09:53:10 -040043from oauth2client.client import AssertionCredentials
Joe Gregorio08cdcb82012-03-14 00:09:33 -040044from oauth2client.client import Credentials
Joe Gregorioccc79542011-02-19 00:05:26 -050045from oauth2client.client import FlowExchangeError
Joe Gregorio08cdcb82012-03-14 00:09:33 -040046from oauth2client.client import MemoryCache
Joe Gregorioccc79542011-02-19 00:05:26 -050047from oauth2client.client import OAuth2Credentials
48from oauth2client.client import OAuth2WebServerFlow
Joe Gregoriof2326c02012-02-09 12:18:44 -050049from oauth2client.client import OOB_CALLBACK_URN
Joe Gregorio8b4c1732011-12-06 11:28:29 -050050from oauth2client.client import VerifyJwtTokenError
51from oauth2client.client import _extract_id_token
Joe Gregorio32d852d2012-06-14 09:08:18 -040052from oauth2client.client import credentials_from_code
53from oauth2client.client import credentials_from_clientsecrets_and_code
Joe Gregorioc29aaa92012-07-16 16:16:31 -040054from oauth2client.client import flow_from_clientsecrets
Joe Gregorio32d852d2012-06-14 09:08:18 -040055
56DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
57
Joe Gregorio68a8cfe2012-08-03 16:17:40 -040058
Joe Gregorio32d852d2012-06-14 09:08:18 -040059def datafile(filename):
60 return os.path.join(DATA_DIR, filename)
Joe Gregorioccc79542011-02-19 00:05:26 -050061
Joe Gregorio68a8cfe2012-08-03 16:17:40 -040062
Joe Gregorioc29aaa92012-07-16 16:16:31 -040063def load_and_cache(existing_file, fakename, cache_mock):
64 client_type, client_info = _loadfile(datafile(existing_file))
65 cache_mock.cache[fakename] = {client_type: client_info}
66
Joe Gregorio68a8cfe2012-08-03 16:17:40 -040067
Joe Gregorioc29aaa92012-07-16 16:16:31 -040068class CacheMock(object):
69 def __init__(self):
70 self.cache = {}
71
72 def get(self, key, namespace=''):
73 # ignoring namespace for easier testing
74 return self.cache.get(key, None)
75
76 def set(self, key, value, namespace=''):
77 # ignoring namespace for easier testing
78 self.cache[key] = value
79
Joe Gregorioccc79542011-02-19 00:05:26 -050080
Joe Gregorio08cdcb82012-03-14 00:09:33 -040081class CredentialsTests(unittest.TestCase):
82
83 def test_to_from_json(self):
84 credentials = Credentials()
85 json = credentials.to_json()
86 restored = Credentials.new_from_json(json)
87
88
Joe Gregorioccc79542011-02-19 00:05:26 -050089class OAuth2CredentialsTests(unittest.TestCase):
90
91 def setUp(self):
92 access_token = "foo"
93 client_id = "some_client_id"
94 client_secret = "cOuDdkfjxxnv+"
95 refresh_token = "1/0/a.df219fjls0"
Joe Gregorio562b7312011-09-15 09:06:38 -040096 token_expiry = datetime.datetime.utcnow()
Joe Gregorioccc79542011-02-19 00:05:26 -050097 token_uri = "https://www.google.com/accounts/o8/oauth2/token"
98 user_agent = "refresh_checker/1.0"
99 self.credentials = OAuth2Credentials(
100 access_token, client_id, client_secret,
101 refresh_token, token_expiry, token_uri,
102 user_agent)
103
104 def test_token_refresh_success(self):
Joe Gregorio7c7c6b12012-07-16 16:31:01 -0400105 # Older API (GData) respond with 403
106 for status_code in ['401', '403']:
107 http = HttpMockSequence([
108 ({'status': status_code}, ''),
109 ({'status': '200'}, '{"access_token":"1/3w","expires_in":3600}'),
110 ({'status': '200'}, 'echo_request_headers'),
111 ])
112 http = self.credentials.authorize(http)
113 resp, content = http.request("http://example.com")
114 self.assertEqual('Bearer 1/3w', content['Authorization'])
115 self.assertFalse(self.credentials.access_token_expired)
Joe Gregorioccc79542011-02-19 00:05:26 -0500116
117 def test_token_refresh_failure(self):
Joe Gregorio7c7c6b12012-07-16 16:31:01 -0400118 # Older API (GData) respond with 403
119 for status_code in ['401', '403']:
120 http = HttpMockSequence([
121 ({'status': status_code}, ''),
122 ({'status': '400'}, '{"error":"access_denied"}'),
123 ])
124 http = self.credentials.authorize(http)
125 try:
126 http.request("http://example.com")
127 self.fail("should raise AccessTokenRefreshError exception")
128 except AccessTokenRefreshError:
129 pass
130 self.assertTrue(self.credentials.access_token_expired)
Joe Gregorioccc79542011-02-19 00:05:26 -0500131
132 def test_non_401_error_response(self):
133 http = HttpMockSequence([
134 ({'status': '400'}, ''),
135 ])
136 http = self.credentials.authorize(http)
137 resp, content = http.request("http://example.com")
138 self.assertEqual(400, resp.status)
139
Joe Gregorio562b7312011-09-15 09:06:38 -0400140 def test_to_from_json(self):
141 json = self.credentials.to_json()
142 instance = OAuth2Credentials.from_json(json)
Joe Gregorio654f4a22012-02-09 14:15:44 -0500143 self.assertEqual(OAuth2Credentials, type(instance))
Joe Gregorio1daa71b2011-09-15 18:12:14 -0400144 instance.token_expiry = None
145 self.credentials.token_expiry = None
146
Joe Gregorio654f4a22012-02-09 14:15:44 -0500147 self.assertEqual(instance.__dict__, self.credentials.__dict__)
Joe Gregorio562b7312011-09-15 09:06:38 -0400148
Joe Gregorioccc79542011-02-19 00:05:26 -0500149
150class AccessTokenCredentialsTests(unittest.TestCase):
151
152 def setUp(self):
153 access_token = "foo"
154 user_agent = "refresh_checker/1.0"
155 self.credentials = AccessTokenCredentials(access_token, user_agent)
156
157 def test_token_refresh_success(self):
Joe Gregorio7c7c6b12012-07-16 16:31:01 -0400158 # Older API (GData) respond with 403
159 for status_code in ['401', '403']:
160 http = HttpMockSequence([
161 ({'status': status_code}, ''),
162 ])
163 http = self.credentials.authorize(http)
164 try:
165 resp, content = http.request("http://example.com")
166 self.fail("should throw exception if token expires")
167 except AccessTokenCredentialsError:
168 pass
169 except Exception:
170 self.fail("should only throw AccessTokenCredentialsError")
Joe Gregorioccc79542011-02-19 00:05:26 -0500171
172 def test_non_401_error_response(self):
173 http = HttpMockSequence([
174 ({'status': '400'}, ''),
175 ])
176 http = self.credentials.authorize(http)
Joe Gregorio83cd4392011-06-20 10:11:35 -0400177 resp, content = http.request('http://example.com')
Joe Gregorioccc79542011-02-19 00:05:26 -0500178 self.assertEqual(400, resp.status)
179
Joe Gregorio83cd4392011-06-20 10:11:35 -0400180 def test_auth_header_sent(self):
181 http = HttpMockSequence([
182 ({'status': '200'}, 'echo_request_headers'),
183 ])
184 http = self.credentials.authorize(http)
185 resp, content = http.request('http://example.com')
Joe Gregorio654f4a22012-02-09 14:15:44 -0500186 self.assertEqual('Bearer foo', content['Authorization'])
Joe Gregorioccc79542011-02-19 00:05:26 -0500187
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500188
JacobMoshenko8e905102011-06-20 09:53:10 -0400189class TestAssertionCredentials(unittest.TestCase):
190 assertion_text = "This is the assertion"
191 assertion_type = "http://www.google.com/assertionType"
192
193 class AssertionCredentialsTestImpl(AssertionCredentials):
194
195 def _generate_assertion(self):
196 return TestAssertionCredentials.assertion_text
197
198 def setUp(self):
199 user_agent = "fun/2.0"
200 self.credentials = self.AssertionCredentialsTestImpl(self.assertion_type,
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400201 user_agent=user_agent)
JacobMoshenko8e905102011-06-20 09:53:10 -0400202
203 def test_assertion_body(self):
204 body = urlparse.parse_qs(self.credentials._generate_refresh_request_body())
Joe Gregorio654f4a22012-02-09 14:15:44 -0500205 self.assertEqual(self.assertion_text, body['assertion'][0])
206 self.assertEqual(self.assertion_type, body['assertion_type'][0])
JacobMoshenko8e905102011-06-20 09:53:10 -0400207
208 def test_assertion_refresh(self):
209 http = HttpMockSequence([
210 ({'status': '200'}, '{"access_token":"1/3w"}'),
211 ({'status': '200'}, 'echo_request_headers'),
212 ])
213 http = self.credentials.authorize(http)
214 resp, content = http.request("http://example.com")
Joe Gregorio654f4a22012-02-09 14:15:44 -0500215 self.assertEqual('Bearer 1/3w', content['Authorization'])
JacobMoshenko8e905102011-06-20 09:53:10 -0400216
217
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500218class ExtractIdTokenText(unittest.TestCase):
219 """Tests _extract_id_token()."""
220
221 def test_extract_success(self):
222 body = {'foo': 'bar'}
223 payload = base64.urlsafe_b64encode(simplejson.dumps(body)).strip('=')
224 jwt = 'stuff.' + payload + '.signature'
225
226 extracted = _extract_id_token(jwt)
Joe Gregorio654f4a22012-02-09 14:15:44 -0500227 self.assertEqual(extracted, body)
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500228
229 def test_extract_failure(self):
230 body = {'foo': 'bar'}
231 payload = base64.urlsafe_b64encode(simplejson.dumps(body)).strip('=')
232 jwt = 'stuff.' + payload
233
234 self.assertRaises(VerifyJwtTokenError, _extract_id_token, jwt)
235
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400236
Joe Gregorioccc79542011-02-19 00:05:26 -0500237class OAuth2WebServerFlowTest(unittest.TestCase):
238
239 def setUp(self):
240 self.flow = OAuth2WebServerFlow(
241 client_id='client_id+1',
242 client_secret='secret+1',
243 scope='foo',
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400244 redirect_uri=OOB_CALLBACK_URN,
Joe Gregorioccc79542011-02-19 00:05:26 -0500245 user_agent='unittest-sample/1.0',
246 )
247
248 def test_construct_authorize_url(self):
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400249 authorize_url = self.flow.step1_get_authorize_url()
Joe Gregorioccc79542011-02-19 00:05:26 -0500250
251 parsed = urlparse.urlparse(authorize_url)
252 q = parse_qs(parsed[4])
Joe Gregorio654f4a22012-02-09 14:15:44 -0500253 self.assertEqual('client_id+1', q['client_id'][0])
254 self.assertEqual('code', q['response_type'][0])
255 self.assertEqual('foo', q['scope'][0])
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400256 self.assertEqual(OOB_CALLBACK_URN, q['redirect_uri'][0])
Joe Gregorio654f4a22012-02-09 14:15:44 -0500257 self.assertEqual('offline', q['access_type'][0])
Joe Gregorio69a0aca2011-11-03 10:47:32 -0400258
259 def test_override_flow_access_type(self):
260 """Passing access_type overrides the default."""
261 flow = OAuth2WebServerFlow(
262 client_id='client_id+1',
263 client_secret='secret+1',
264 scope='foo',
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400265 redirect_uri=OOB_CALLBACK_URN,
Joe Gregorio69a0aca2011-11-03 10:47:32 -0400266 user_agent='unittest-sample/1.0',
267 access_type='online'
268 )
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400269 authorize_url = flow.step1_get_authorize_url()
Joe Gregorio69a0aca2011-11-03 10:47:32 -0400270
271 parsed = urlparse.urlparse(authorize_url)
272 q = parse_qs(parsed[4])
Joe Gregorio654f4a22012-02-09 14:15:44 -0500273 self.assertEqual('client_id+1', q['client_id'][0])
274 self.assertEqual('code', q['response_type'][0])
275 self.assertEqual('foo', q['scope'][0])
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400276 self.assertEqual(OOB_CALLBACK_URN, q['redirect_uri'][0])
Joe Gregorio654f4a22012-02-09 14:15:44 -0500277 self.assertEqual('online', q['access_type'][0])
Joe Gregorioccc79542011-02-19 00:05:26 -0500278
279 def test_exchange_failure(self):
280 http = HttpMockSequence([
JacobMoshenko8e905102011-06-20 09:53:10 -0400281 ({'status': '400'}, '{"error":"invalid_request"}'),
Joe Gregorioccc79542011-02-19 00:05:26 -0500282 ])
283
284 try:
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400285 credentials = self.flow.step2_exchange('some random code', http=http)
Joe Gregorioccc79542011-02-19 00:05:26 -0500286 self.fail("should raise exception if exchange doesn't get 200")
287 except FlowExchangeError:
288 pass
289
Joe Gregorioddb969a2012-07-11 11:04:12 -0400290 def test_urlencoded_exchange_failure(self):
291 http = HttpMockSequence([
292 ({'status': '400'}, "error=invalid_request"),
293 ])
294
295 try:
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400296 credentials = self.flow.step2_exchange('some random code', http=http)
Joe Gregorioddb969a2012-07-11 11:04:12 -0400297 self.fail("should raise exception if exchange doesn't get 200")
298 except FlowExchangeError, e:
299 self.assertEquals('invalid_request', str(e))
300
301 def test_exchange_failure_with_json_error(self):
302 # Some providers have "error" attribute as a JSON object
303 # in place of regular string.
304 # This test makes sure no strange object-to-string coversion
305 # exceptions are being raised instead of FlowExchangeError.
306 http = HttpMockSequence([
307 ({'status': '400'},
308 """ {"error": {
309 "type": "OAuthException",
310 "message": "Error validating verification code."} }"""),
311 ])
312
313 try:
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400314 credentials = self.flow.step2_exchange('some random code', http=http)
Joe Gregorioddb969a2012-07-11 11:04:12 -0400315 self.fail("should raise exception if exchange doesn't get 200")
316 except FlowExchangeError, e:
317 pass
318
Joe Gregorioccc79542011-02-19 00:05:26 -0500319 def test_exchange_success(self):
320 http = HttpMockSequence([
321 ({'status': '200'},
322 """{ "access_token":"SlAV32hkKG",
323 "expires_in":3600,
324 "refresh_token":"8xLOxBtZp8" }"""),
325 ])
326
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400327 credentials = self.flow.step2_exchange('some random code', http=http)
Joe Gregorio654f4a22012-02-09 14:15:44 -0500328 self.assertEqual('SlAV32hkKG', credentials.access_token)
329 self.assertNotEqual(None, credentials.token_expiry)
330 self.assertEqual('8xLOxBtZp8', credentials.refresh_token)
Joe Gregorioccc79542011-02-19 00:05:26 -0500331
Joe Gregorioddb969a2012-07-11 11:04:12 -0400332 def test_urlencoded_exchange_success(self):
333 http = HttpMockSequence([
334 ({'status': '200'}, "access_token=SlAV32hkKG&expires_in=3600"),
335 ])
336
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400337 credentials = self.flow.step2_exchange('some random code', http=http)
Joe Gregorioddb969a2012-07-11 11:04:12 -0400338 self.assertEqual('SlAV32hkKG', credentials.access_token)
339 self.assertNotEqual(None, credentials.token_expiry)
340
341 def test_urlencoded_expires_param(self):
342 http = HttpMockSequence([
343 # Note the "expires=3600" where you'd normally
344 # have if named "expires_in"
345 ({'status': '200'}, "access_token=SlAV32hkKG&expires=3600"),
346 ])
347
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400348 credentials = self.flow.step2_exchange('some random code', http=http)
Joe Gregorioddb969a2012-07-11 11:04:12 -0400349 self.assertNotEqual(None, credentials.token_expiry)
350
Joe Gregorioccc79542011-02-19 00:05:26 -0500351 def test_exchange_no_expires_in(self):
352 http = HttpMockSequence([
353 ({'status': '200'}, """{ "access_token":"SlAV32hkKG",
354 "refresh_token":"8xLOxBtZp8" }"""),
355 ])
356
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400357 credentials = self.flow.step2_exchange('some random code', http=http)
Joe Gregorio654f4a22012-02-09 14:15:44 -0500358 self.assertEqual(None, credentials.token_expiry)
Joe Gregorioccc79542011-02-19 00:05:26 -0500359
Joe Gregorioddb969a2012-07-11 11:04:12 -0400360 def test_urlencoded_exchange_no_expires_in(self):
361 http = HttpMockSequence([
362 # This might be redundant but just to make sure
363 # urlencoded access_token gets parsed correctly
364 ({'status': '200'}, "access_token=SlAV32hkKG"),
365 ])
366
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400367 credentials = self.flow.step2_exchange('some random code', http=http)
Joe Gregorioddb969a2012-07-11 11:04:12 -0400368 self.assertEqual(None, credentials.token_expiry)
369
Joe Gregorio4b4002f2012-06-14 15:41:01 -0400370 def test_exchange_fails_if_no_code(self):
371 http = HttpMockSequence([
372 ({'status': '200'}, """{ "access_token":"SlAV32hkKG",
373 "refresh_token":"8xLOxBtZp8" }"""),
374 ])
375
376 code = {'error': 'thou shall not pass'}
377 try:
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400378 credentials = self.flow.step2_exchange(code, http=http)
Joe Gregorio4b4002f2012-06-14 15:41:01 -0400379 self.fail('should raise exception if no code in dictionary.')
380 except FlowExchangeError, e:
381 self.assertTrue('shall not pass' in str(e))
382
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500383 def test_exchange_id_token_fail(self):
384 http = HttpMockSequence([
385 ({'status': '200'}, """{ "access_token":"SlAV32hkKG",
386 "refresh_token":"8xLOxBtZp8",
387 "id_token": "stuff.payload"}"""),
388 ])
389
390 self.assertRaises(VerifyJwtTokenError, self.flow.step2_exchange,
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400391 'some random code', http=http)
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500392
393 def test_exchange_id_token_fail(self):
394 body = {'foo': 'bar'}
395 payload = base64.urlsafe_b64encode(simplejson.dumps(body)).strip('=')
Joe Gregoriobd512b52011-12-06 15:39:26 -0500396 jwt = (base64.urlsafe_b64encode('stuff')+ '.' + payload + '.' +
397 base64.urlsafe_b64encode('signature'))
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500398
399 http = HttpMockSequence([
400 ({'status': '200'}, """{ "access_token":"SlAV32hkKG",
401 "refresh_token":"8xLOxBtZp8",
402 "id_token": "%s"}""" % jwt),
403 ])
404
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400405 credentials = self.flow.step2_exchange('some random code', http=http)
Joe Gregorio654f4a22012-02-09 14:15:44 -0500406 self.assertEqual(credentials.id_token, body)
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500407
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400408
409class FlowFromCachedClientsecrets(unittest.TestCase):
Joe Gregorioc29aaa92012-07-16 16:16:31 -0400410
411 def test_flow_from_clientsecrets_cached(self):
412 cache_mock = CacheMock()
413 load_and_cache('client_secrets.json', 'some_secrets', cache_mock)
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400414
415 flow = flow_from_clientsecrets(
416 'some_secrets', '', redirect_uri='oob', cache=cache_mock)
Joe Gregorioc29aaa92012-07-16 16:16:31 -0400417 self.assertEquals('foo_client_secret', flow.client_secret)
418
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400419
Joe Gregorio32d852d2012-06-14 09:08:18 -0400420class CredentialsFromCodeTests(unittest.TestCase):
421 def setUp(self):
422 self.client_id = 'client_id_abc'
423 self.client_secret = 'secret_use_code'
424 self.scope = 'foo'
425 self.code = '12345abcde'
426 self.redirect_uri = 'postmessage'
427
428 def test_exchange_code_for_token(self):
429 http = HttpMockSequence([
430 ({'status': '200'},
431 """{ "access_token":"asdfghjkl",
432 "expires_in":3600 }"""),
433 ])
434 credentials = credentials_from_code(self.client_id, self.client_secret,
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400435 self.scope, self.code, redirect_uri=self.redirect_uri,
436 http=http)
Joe Gregorio32d852d2012-06-14 09:08:18 -0400437 self.assertEquals(credentials.access_token, 'asdfghjkl')
438 self.assertNotEqual(None, credentials.token_expiry)
439
440 def test_exchange_code_for_token_fail(self):
441 http = HttpMockSequence([
442 ({'status': '400'}, '{"error":"invalid_request"}'),
443 ])
444
445 try:
446 credentials = credentials_from_code(self.client_id, self.client_secret,
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400447 self.scope, self.code, redirect_uri=self.redirect_uri,
448 http=http)
Joe Gregorio32d852d2012-06-14 09:08:18 -0400449 self.fail("should raise exception if exchange doesn't get 200")
450 except FlowExchangeError:
451 pass
452
Joe Gregorio32d852d2012-06-14 09:08:18 -0400453 def test_exchange_code_and_file_for_token(self):
454 http = HttpMockSequence([
455 ({'status': '200'},
456 """{ "access_token":"asdfghjkl",
457 "expires_in":3600 }"""),
458 ])
459 credentials = credentials_from_clientsecrets_and_code(
460 datafile('client_secrets.json'), self.scope,
461 self.code, http=http)
462 self.assertEquals(credentials.access_token, 'asdfghjkl')
463 self.assertNotEqual(None, credentials.token_expiry)
464
Joe Gregorioc29aaa92012-07-16 16:16:31 -0400465 def test_exchange_code_and_cached_file_for_token(self):
466 http = HttpMockSequence([
467 ({'status': '200'}, '{ "access_token":"asdfghjkl"}'),
468 ])
469 cache_mock = CacheMock()
470 load_and_cache('client_secrets.json', 'some_secrets', cache_mock)
471
472 credentials = credentials_from_clientsecrets_and_code(
473 'some_secrets', self.scope,
474 self.code, http=http, cache=cache_mock)
475 self.assertEquals(credentials.access_token, 'asdfghjkl')
476
Joe Gregorio32d852d2012-06-14 09:08:18 -0400477 def test_exchange_code_and_file_for_token_fail(self):
478 http = HttpMockSequence([
479 ({'status': '400'}, '{"error":"invalid_request"}'),
480 ])
481
482 try:
483 credentials = credentials_from_clientsecrets_and_code(
484 datafile('client_secrets.json'), self.scope,
485 self.code, http=http)
486 self.fail("should raise exception if exchange doesn't get 200")
487 except FlowExchangeError:
488 pass
489
490
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400491class MemoryCacheTests(unittest.TestCase):
492
493 def test_get_set_delete(self):
494 m = MemoryCache()
495 self.assertEqual(None, m.get('foo'))
496 self.assertEqual(None, m.delete('foo'))
497 m.set('foo', 'bar')
498 self.assertEqual('bar', m.get('foo'))
499 m.delete('foo')
500 self.assertEqual(None, m.get('foo'))
501
502
Joe Gregorioccc79542011-02-19 00:05:26 -0500503if __name__ == '__main__':
504 unittest.main()