Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(388)

Side by Side Diff: third_party/google-endpoints/apitools/scripts/oauth2l_test.py

Issue 2666783008: Add google-endpoints to third_party/. (Closed)
Patch Set: Created 3 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 #
2 # Copyright 2015 Google Inc.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 """Tests for oauth2l."""
17
18 import json
19 import os
20 import sys
21
22 import mock
23 import oauth2client.client
24 import six
25 from six.moves import http_client
26 import unittest2
27
28 import apitools.base.py as apitools_base
29
30 _OAUTH2L_MAIN_RUN = False
31
32 if six.PY2:
33 # pylint: disable=wrong-import-position,wrong-import-order
34 import gflags as flags
35 from google.apputils import appcommands
36 from apitools.scripts import oauth2l
37 FLAGS = flags.FLAGS
38
39
40 class _FakeResponse(object):
41
42 def __init__(self, status_code, scopes=None):
43 self.status_code = status_code
44 if self.status_code == http_client.OK:
45 self.content = json.dumps({'scope': ' '.join(scopes or [])})
46 else:
47 self.content = 'Error'
48 self.info = str(http_client.responses[self.status_code])
49 self.request_url = 'some-url'
50
51
52 def _GetCommandOutput(t, command_name, command_argv):
53 global _OAUTH2L_MAIN_RUN # pylint: disable=global-statement
54 if not _OAUTH2L_MAIN_RUN:
55 oauth2l.main(None)
56 _OAUTH2L_MAIN_RUN = True
57 command = appcommands.GetCommandByName(command_name)
58 if command is None:
59 t.fail('Unknown command: %s' % command_name)
60 orig_stdout = sys.stdout
61 new_stdout = six.StringIO()
62 try:
63 sys.stdout = new_stdout
64 command.CommandRun([command_name] + command_argv)
65 finally:
66 sys.stdout = orig_stdout
67 FLAGS.Reset()
68 new_stdout.seek(0)
69 return new_stdout.getvalue().rstrip()
70
71
72 @unittest2.skipIf(six.PY3, 'oauth2l unsupported in python3')
73 class TestTest(unittest2.TestCase):
74
75 def testOutput(self):
76 self.assertRaises(AssertionError,
77 _GetCommandOutput, self, 'foo', [])
78
79
80 @unittest2.skipIf(six.PY3, 'oauth2l unsupported in python3')
81 class Oauth2lFormattingTest(unittest2.TestCase):
82
83 def setUp(self):
84 # Set up an access token to use
85 self.access_token = 'ya29.abdefghijklmnopqrstuvwxyz'
86 self.user_agent = 'oauth2l/1.0'
87 self.credentials = oauth2client.client.AccessTokenCredentials(
88 self.access_token, self.user_agent)
89
90 def _Args(self, credentials_format):
91 return ['--credentials_format=' + credentials_format, 'userinfo.email']
92
93 def testFormatBare(self):
94 with mock.patch.object(oauth2l, 'FetchCredentials',
95 return_value=self.credentials,
96 autospec=True) as mock_credentials:
97 output = _GetCommandOutput(self, 'fetch', self._Args('bare'))
98 self.assertEqual(self.access_token, output)
99 self.assertEqual(1, mock_credentials.call_count)
100
101 def testFormatHeader(self):
102 with mock.patch.object(oauth2l, 'FetchCredentials',
103 return_value=self.credentials,
104 autospec=True) as mock_credentials:
105 output = _GetCommandOutput(self, 'fetch', self._Args('header'))
106 header = 'Authorization: Bearer %s' % self.access_token
107 self.assertEqual(header, output)
108 self.assertEqual(1, mock_credentials.call_count)
109
110 def testHeaderCommand(self):
111 with mock.patch.object(oauth2l, 'FetchCredentials',
112 return_value=self.credentials,
113 autospec=True) as mock_credentials:
114 output = _GetCommandOutput(self, 'header', ['userinfo.email'])
115 header = 'Authorization: Bearer %s' % self.access_token
116 self.assertEqual(header, output)
117 self.assertEqual(1, mock_credentials.call_count)
118
119 def testFormatJson(self):
120 with mock.patch.object(oauth2l, 'FetchCredentials',
121 return_value=self.credentials,
122 autospec=True) as mock_credentials:
123 output = _GetCommandOutput(self, 'fetch', self._Args('json'))
124 output_lines = [l.strip() for l in output.splitlines()]
125 expected_lines = [
126 '"_class": "AccessTokenCredentials",',
127 '"access_token": "%s",' % self.access_token,
128 ]
129 for line in expected_lines:
130 self.assertIn(line, output_lines)
131 self.assertEqual(1, mock_credentials.call_count)
132
133 def testFormatJsonCompact(self):
134 with mock.patch.object(oauth2l, 'FetchCredentials',
135 return_value=self.credentials,
136 autospec=True) as mock_credentials:
137 output = _GetCommandOutput(self, 'fetch',
138 self._Args('json_compact'))
139 expected_clauses = [
140 '"_class":"AccessTokenCredentials",',
141 '"access_token":"%s",' % self.access_token,
142 ]
143 for clause in expected_clauses:
144 self.assertIn(clause, output)
145 self.assertEqual(1, len(output.splitlines()))
146 self.assertEqual(1, mock_credentials.call_count)
147
148 def testFormatPretty(self):
149 with mock.patch.object(oauth2l, 'FetchCredentials',
150 return_value=self.credentials,
151 autospec=True) as mock_credentials:
152 output = _GetCommandOutput(self, 'fetch', self._Args('pretty'))
153 expecteds = ['oauth2client.client.AccessTokenCredentials',
154 self.access_token]
155 for expected in expecteds:
156 self.assertIn(expected, output)
157 self.assertEqual(1, mock_credentials.call_count)
158
159 def testFakeFormat(self):
160 self.assertRaises(ValueError,
161 oauth2l._Format, 'xml', self.credentials)
162
163
164 @unittest2.skipIf(six.PY3, 'oauth2l unsupported in python3')
165 class TestFetch(unittest2.TestCase):
166
167 def setUp(self):
168 # Set up an access token to use
169 self.access_token = 'ya29.abdefghijklmnopqrstuvwxyz'
170 self.user_agent = 'oauth2l/1.0'
171 self.credentials = oauth2client.client.AccessTokenCredentials(
172 self.access_token, self.user_agent)
173
174 def testNoScopes(self):
175 output = _GetCommandOutput(self, 'fetch', [])
176 self.assertEqual(
177 'Exception raised in fetch operation: No scopes provided',
178 output)
179
180 def testScopes(self):
181 expected_scopes = [
182 'https://www.googleapis.com/auth/userinfo.email',
183 'https://www.googleapis.com/auth/cloud-platform',
184 ]
185 with mock.patch.object(apitools_base, 'GetCredentials',
186 return_value=self.credentials,
187 autospec=True) as mock_fetch:
188 with mock.patch.object(oauth2l, '_GetTokenScopes',
189 return_value=expected_scopes,
190 autospec=True) as mock_get_scopes:
191 output = _GetCommandOutput(
192 self, 'fetch', ['userinfo.email', 'cloud-platform'])
193 self.assertIn(self.access_token, output)
194 self.assertEqual(1, mock_fetch.call_count)
195 args, _ = mock_fetch.call_args
196 self.assertEqual(expected_scopes, args[-1])
197 self.assertEqual(1, mock_get_scopes.call_count)
198 self.assertEqual((self.access_token,),
199 mock_get_scopes.call_args[0])
200
201 def testCredentialsRefreshed(self):
202 with mock.patch.object(apitools_base, 'GetCredentials',
203 return_value=self.credentials,
204 autospec=True) as mock_fetch:
205 with mock.patch.object(oauth2l, '_ValidateToken',
206 return_value=False,
207 autospec=True) as mock_validate:
208 with mock.patch.object(self.credentials, 'refresh',
209 return_value=None,
210 autospec=True) as mock_refresh:
211 output = _GetCommandOutput(self, 'fetch',
212 ['userinfo.email'])
213 self.assertIn(self.access_token, output)
214 self.assertEqual(1, mock_fetch.call_count)
215 self.assertEqual(1, mock_validate.call_count)
216 self.assertEqual(1, mock_refresh.call_count)
217
218 def testDefaultClientInfo(self):
219 with mock.patch.object(apitools_base, 'GetCredentials',
220 return_value=self.credentials,
221 autospec=True) as mock_fetch:
222 with mock.patch.object(oauth2l, '_ValidateToken',
223 return_value=True,
224 autospec=True) as mock_validate:
225 output = _GetCommandOutput(self, 'fetch', ['userinfo.email'])
226 self.assertIn(self.access_token, output)
227 self.assertEqual(1, mock_fetch.call_count)
228 _, kwargs = mock_fetch.call_args
229 self.assertEqual(
230 '1042881264118.apps.googleusercontent.com',
231 kwargs['client_id'])
232 self.assertEqual(1, mock_validate.call_count)
233
234 def testMissingClientSecrets(self):
235 try:
236 FLAGS.client_secrets = '/non/existent/file'
237 self.assertRaises(
238 ValueError,
239 oauth2l.GetClientInfoFromFlags)
240 finally:
241 FLAGS.Reset()
242
243 def testWrongClientSecretsFormat(self):
244 client_secrets_path = os.path.join(
245 os.path.dirname(__file__),
246 'testdata/noninstalled_client_secrets.json')
247 try:
248 FLAGS.client_secrets = client_secrets_path
249 self.assertRaises(
250 ValueError,
251 oauth2l.GetClientInfoFromFlags)
252 finally:
253 FLAGS.Reset()
254
255 def testCustomClientInfo(self):
256 client_secrets_path = os.path.join(
257 os.path.dirname(__file__), 'testdata/fake_client_secrets.json')
258 with mock.patch.object(apitools_base, 'GetCredentials',
259 return_value=self.credentials,
260 autospec=True) as mock_fetch:
261 with mock.patch.object(oauth2l, '_ValidateToken',
262 return_value=True,
263 autospec=True) as mock_validate:
264 fetch_args = [
265 '--client_secrets=' + client_secrets_path,
266 'userinfo.email']
267 output = _GetCommandOutput(self, 'fetch', fetch_args)
268 self.assertIn(self.access_token, output)
269 self.assertEqual(1, mock_fetch.call_count)
270 _, kwargs = mock_fetch.call_args
271 self.assertEqual('144169.apps.googleusercontent.com',
272 kwargs['client_id'])
273 self.assertEqual('awesomesecret',
274 kwargs['client_secret'])
275 self.assertEqual(1, mock_validate.call_count)
276
277
278 @unittest2.skipIf(six.PY3, 'oauth2l unsupported in python3')
279 class TestOtherCommands(unittest2.TestCase):
280
281 def setUp(self):
282 # Set up an access token to use
283 self.access_token = 'ya29.abdefghijklmnopqrstuvwxyz'
284 self.user_agent = 'oauth2l/1.0'
285 self.credentials = oauth2client.client.AccessTokenCredentials(
286 self.access_token, self.user_agent)
287
288 def testEmail(self):
289 user_info = {'email': 'foo@example.com'}
290 with mock.patch.object(apitools_base, 'GetUserinfo',
291 return_value=user_info,
292 autospec=True) as mock_get_userinfo:
293 output = _GetCommandOutput(self, 'email', [self.access_token])
294 self.assertEqual(user_info['email'], output)
295 self.assertEqual(1, mock_get_userinfo.call_count)
296 self.assertEqual(self.access_token,
297 mock_get_userinfo.call_args[0][0].access_token)
298
299 def testNoEmail(self):
300 with mock.patch.object(apitools_base, 'GetUserinfo',
301 return_value={},
302 autospec=True) as mock_get_userinfo:
303 output = _GetCommandOutput(self, 'email', [self.access_token])
304 self.assertEqual('', output)
305 self.assertEqual(1, mock_get_userinfo.call_count)
306
307 def testUserinfo(self):
308 user_info = {'email': 'foo@example.com'}
309 with mock.patch.object(apitools_base, 'GetUserinfo',
310 return_value=user_info,
311 autospec=True) as mock_get_userinfo:
312 output = _GetCommandOutput(self, 'userinfo', [self.access_token])
313 self.assertEqual(json.dumps(user_info, indent=4), output)
314 self.assertEqual(1, mock_get_userinfo.call_count)
315 self.assertEqual(self.access_token,
316 mock_get_userinfo.call_args[0][0].access_token)
317
318 def testUserinfoCompact(self):
319 user_info = {'email': 'foo@example.com'}
320 with mock.patch.object(apitools_base, 'GetUserinfo',
321 return_value=user_info,
322 autospec=True) as mock_get_userinfo:
323 output = _GetCommandOutput(
324 self, 'userinfo', ['--format=json_compact', self.access_token])
325 self.assertEqual(json.dumps(user_info, separators=(',', ':')),
326 output)
327 self.assertEqual(1, mock_get_userinfo.call_count)
328 self.assertEqual(self.access_token,
329 mock_get_userinfo.call_args[0][0].access_token)
330
331 def testScopes(self):
332 scopes = [u'https://www.googleapis.com/auth/userinfo.email',
333 u'https://www.googleapis.com/auth/cloud-platform']
334 response = _FakeResponse(http_client.OK, scopes=scopes)
335 with mock.patch.object(apitools_base, 'MakeRequest',
336 return_value=response,
337 autospec=True) as mock_make_request:
338 output = _GetCommandOutput(self, 'scopes', [self.access_token])
339 self.assertEqual(sorted(scopes), output.splitlines())
340 self.assertEqual(1, mock_make_request.call_count)
341
342 def testValidate(self):
343 scopes = [u'https://www.googleapis.com/auth/userinfo.email',
344 u'https://www.googleapis.com/auth/cloud-platform']
345 response = _FakeResponse(http_client.OK, scopes=scopes)
346 with mock.patch.object(apitools_base, 'MakeRequest',
347 return_value=response,
348 autospec=True) as mock_make_request:
349 output = _GetCommandOutput(self, 'validate', [self.access_token])
350 self.assertEqual('', output)
351 self.assertEqual(1, mock_make_request.call_count)
352
353 def testBadResponseCode(self):
354 response = _FakeResponse(http_client.BAD_REQUEST)
355 with mock.patch.object(apitools_base, 'MakeRequest',
356 return_value=response,
357 autospec=True) as mock_make_request:
358 output = _GetCommandOutput(self, 'scopes', [self.access_token])
359 self.assertEqual('', output)
360 self.assertEqual(1, mock_make_request.call_count)
361
362 def testUnexpectedResponseCode(self):
363 response = _FakeResponse(http_client.INTERNAL_SERVER_ERROR)
364 with mock.patch.object(apitools_base, 'MakeRequest',
365 return_value=response,
366 autospec=True) as mock_make_request:
367 output = _GetCommandOutput(self, 'scopes', [self.access_token])
368 self.assertIn(str(http_client.responses[response.status_code]),
369 output)
370 self.assertIn('Exception raised in scopes operation: HttpError',
371 output)
372 self.assertEqual(1, mock_make_request.call_count)
OLDNEW
« no previous file with comments | « third_party/google-endpoints/apitools/scripts/oauth2l.py ('k') | third_party/google-endpoints/appdirs.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698