blob: de118107a04a43717d671b9ea2991ebb673303e2 [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 Gregorioe1de4162011-02-23 11:30:29 -050025import httplib2
Joe Gregorioccc79542011-02-19 00:05:26 -050026import unittest
27import urlparse
Joe Gregorioe1de4162011-02-23 11:30:29 -050028
Joe Gregorioccc79542011-02-19 00:05:26 -050029try:
30 from urlparse import parse_qs
31except ImportError:
32 from cgi import parse_qs
33
34from apiclient.http import HttpMockSequence
35from oauth2client.client import AccessTokenCredentials
36from oauth2client.client import AccessTokenCredentialsError
37from oauth2client.client import AccessTokenRefreshError
JacobMoshenko8e905102011-06-20 09:53:10 -040038from oauth2client.client import AssertionCredentials
Joe Gregorioccc79542011-02-19 00:05:26 -050039from oauth2client.client import FlowExchangeError
40from oauth2client.client import OAuth2Credentials
41from oauth2client.client import OAuth2WebServerFlow
42
43
44class OAuth2CredentialsTests(unittest.TestCase):
45
46 def setUp(self):
47 access_token = "foo"
48 client_id = "some_client_id"
49 client_secret = "cOuDdkfjxxnv+"
50 refresh_token = "1/0/a.df219fjls0"
51 token_expiry = "ignored"
52 token_uri = "https://www.google.com/accounts/o8/oauth2/token"
53 user_agent = "refresh_checker/1.0"
54 self.credentials = OAuth2Credentials(
55 access_token, client_id, client_secret,
56 refresh_token, token_expiry, token_uri,
57 user_agent)
58
59 def test_token_refresh_success(self):
60 http = HttpMockSequence([
61 ({'status': '401'}, ''),
62 ({'status': '200'}, '{"access_token":"1/3w","expires_in":3600}'),
63 ({'status': '200'}, 'echo_request_headers'),
64 ])
65 http = self.credentials.authorize(http)
66 resp, content = http.request("http://example.com")
67 self.assertEqual(content['authorization'], 'OAuth 1/3w')
68
69 def test_token_refresh_failure(self):
70 http = HttpMockSequence([
71 ({'status': '401'}, ''),
72 ({'status': '400'}, '{"error":"access_denied"}'),
73 ])
74 http = self.credentials.authorize(http)
75 try:
76 http.request("http://example.com")
77 self.fail("should raise AccessTokenRefreshError exception")
78 except AccessTokenRefreshError:
79 pass
80
81 def test_non_401_error_response(self):
82 http = HttpMockSequence([
83 ({'status': '400'}, ''),
84 ])
85 http = self.credentials.authorize(http)
86 resp, content = http.request("http://example.com")
87 self.assertEqual(400, resp.status)
88
89
90class AccessTokenCredentialsTests(unittest.TestCase):
91
92 def setUp(self):
93 access_token = "foo"
94 user_agent = "refresh_checker/1.0"
95 self.credentials = AccessTokenCredentials(access_token, user_agent)
96
97 def test_token_refresh_success(self):
98 http = HttpMockSequence([
99 ({'status': '401'}, ''),
100 ])
101 http = self.credentials.authorize(http)
102 try:
103 resp, content = http.request("http://example.com")
104 self.fail("should throw exception if token expires")
105 except AccessTokenCredentialsError:
106 pass
107 except Exception:
108 self.fail("should only throw AccessTokenCredentialsError")
109
110 def test_non_401_error_response(self):
111 http = HttpMockSequence([
112 ({'status': '400'}, ''),
113 ])
114 http = self.credentials.authorize(http)
Joe Gregorio83cd4392011-06-20 10:11:35 -0400115 resp, content = http.request('http://example.com')
Joe Gregorioccc79542011-02-19 00:05:26 -0500116 self.assertEqual(400, resp.status)
117
Joe Gregorio83cd4392011-06-20 10:11:35 -0400118 def test_auth_header_sent(self):
119 http = HttpMockSequence([
120 ({'status': '200'}, 'echo_request_headers'),
121 ])
122 http = self.credentials.authorize(http)
123 resp, content = http.request('http://example.com')
124 self.assertEqual(content['authorization'], 'OAuth foo')
Joe Gregorioccc79542011-02-19 00:05:26 -0500125
JacobMoshenko8e905102011-06-20 09:53:10 -0400126class TestAssertionCredentials(unittest.TestCase):
127 assertion_text = "This is the assertion"
128 assertion_type = "http://www.google.com/assertionType"
129
130 class AssertionCredentialsTestImpl(AssertionCredentials):
131
132 def _generate_assertion(self):
133 return TestAssertionCredentials.assertion_text
134
135 def setUp(self):
136 user_agent = "fun/2.0"
137 self.credentials = self.AssertionCredentialsTestImpl(self.assertion_type,
138 user_agent)
139
140 def test_assertion_body(self):
141 body = urlparse.parse_qs(self.credentials._generate_refresh_request_body())
142 self.assertEqual(body['assertion'][0], self.assertion_text)
143 self.assertEqual(body['assertion_type'][0], self.assertion_type)
144
145 def test_assertion_refresh(self):
146 http = HttpMockSequence([
147 ({'status': '200'}, '{"access_token":"1/3w"}'),
148 ({'status': '200'}, 'echo_request_headers'),
149 ])
150 http = self.credentials.authorize(http)
151 resp, content = http.request("http://example.com")
152 self.assertEqual(content['authorization'], 'OAuth 1/3w')
153
154
Joe Gregorioccc79542011-02-19 00:05:26 -0500155class OAuth2WebServerFlowTest(unittest.TestCase):
156
157 def setUp(self):
158 self.flow = OAuth2WebServerFlow(
159 client_id='client_id+1',
160 client_secret='secret+1',
161 scope='foo',
162 user_agent='unittest-sample/1.0',
163 )
164
165 def test_construct_authorize_url(self):
166 authorize_url = self.flow.step1_get_authorize_url('oob')
167
168 parsed = urlparse.urlparse(authorize_url)
169 q = parse_qs(parsed[4])
170 self.assertEqual(q['client_id'][0], 'client_id+1')
171 self.assertEqual(q['response_type'][0], 'code')
172 self.assertEqual(q['scope'][0], 'foo')
173 self.assertEqual(q['redirect_uri'][0], 'oob')
174
175 def test_exchange_failure(self):
176 http = HttpMockSequence([
JacobMoshenko8e905102011-06-20 09:53:10 -0400177 ({'status': '400'}, '{"error":"invalid_request"}'),
Joe Gregorioccc79542011-02-19 00:05:26 -0500178 ])
179
180 try:
181 credentials = self.flow.step2_exchange('some random code', http)
182 self.fail("should raise exception if exchange doesn't get 200")
183 except FlowExchangeError:
184 pass
185
186 def test_exchange_success(self):
187 http = HttpMockSequence([
188 ({'status': '200'},
189 """{ "access_token":"SlAV32hkKG",
190 "expires_in":3600,
191 "refresh_token":"8xLOxBtZp8" }"""),
192 ])
193
194 credentials = self.flow.step2_exchange('some random code', http)
195 self.assertEqual(credentials.access_token, 'SlAV32hkKG')
196 self.assertNotEqual(credentials.token_expiry, None)
197 self.assertEqual(credentials.refresh_token, '8xLOxBtZp8')
198
Joe Gregorioccc79542011-02-19 00:05:26 -0500199 def test_exchange_no_expires_in(self):
200 http = HttpMockSequence([
201 ({'status': '200'}, """{ "access_token":"SlAV32hkKG",
202 "refresh_token":"8xLOxBtZp8" }"""),
203 ])
204
205 credentials = self.flow.step2_exchange('some random code', http)
206 self.assertEqual(credentials.token_expiry, None)
207
208
209if __name__ == '__main__':
210 unittest.main()