Making tests/ files pass PEP8.
This is all errors except E402: module level import not at top of file. This is because in most (all?) files the __author__ global comes before imports begin. Ref: http://stackoverflow.com/a/24859703/1068170
This commit is contained in:
@@ -20,6 +20,7 @@ import httplib2
|
|||||||
|
|
||||||
# TODO(craigcitro): Find a cleaner way to share this code with googleapiclient.
|
# TODO(craigcitro): Find a cleaner way to share this code with googleapiclient.
|
||||||
|
|
||||||
|
|
||||||
class HttpMock(object):
|
class HttpMock(object):
|
||||||
"""Mock of httplib2.Http"""
|
"""Mock of httplib2.Http"""
|
||||||
|
|
||||||
@@ -102,15 +103,17 @@ class HttpMockSequence(object):
|
|||||||
resp, content = self._iterable.pop(0)
|
resp, content = self._iterable.pop(0)
|
||||||
self.requests.append({'uri': uri, 'body': body, 'headers': headers})
|
self.requests.append({'uri': uri, 'body': body, 'headers': headers})
|
||||||
# Read any underlying stream before sending the request.
|
# Read any underlying stream before sending the request.
|
||||||
body_stream_content = body.read() if getattr(body, 'read', None) else None
|
body_stream_content = (body.read()
|
||||||
|
if getattr(body, 'read', None) else None)
|
||||||
if content == 'echo_request_headers':
|
if content == 'echo_request_headers':
|
||||||
content = headers
|
content = headers
|
||||||
elif content == 'echo_request_headers_as_json':
|
elif content == 'echo_request_headers_as_json':
|
||||||
content = json.dumps(headers)
|
content = json.dumps(headers)
|
||||||
elif content == 'echo_request_body':
|
elif content == 'echo_request_body':
|
||||||
content = body if body_stream_content is None else body_stream_content
|
content = (body
|
||||||
|
if body_stream_content is None else body_stream_content)
|
||||||
elif content == 'echo_request_uri':
|
elif content == 'echo_request_uri':
|
||||||
content = uri
|
content = uri
|
||||||
elif not isinstance(content, bytes):
|
elif not isinstance(content, bytes):
|
||||||
raise TypeError('http content should be bytes: %r' % (content, ))
|
raise TypeError('http content should be bytes: %r' % (content,))
|
||||||
return httplib2.Response(resp), content
|
return httplib2.Response(resp), content
|
||||||
|
|||||||
@@ -43,12 +43,12 @@ class Test__json_encode(unittest.TestCase):
|
|||||||
# is non-deterministic.
|
# is non-deterministic.
|
||||||
data = {u'foo': 10}
|
data = {u'foo': 10}
|
||||||
result = _json_encode(data)
|
result = _json_encode(data)
|
||||||
self.assertEqual(result, """{"foo":10}""")
|
self.assertEqual(result, '{"foo":10}')
|
||||||
|
|
||||||
def test_list_input(self):
|
def test_list_input(self):
|
||||||
data = [42, 1337]
|
data = [42, 1337]
|
||||||
result = _json_encode(data)
|
result = _json_encode(data)
|
||||||
self.assertEqual(result, """[42,1337]""")
|
self.assertEqual(result, '[42,1337]')
|
||||||
|
|
||||||
|
|
||||||
class Test__to_bytes(unittest.TestCase):
|
class Test__to_bytes(unittest.TestCase):
|
||||||
|
|||||||
@@ -122,7 +122,7 @@ class Http2Mock(object):
|
|||||||
def request(self, token_uri, method, body, headers, *args, **kwargs):
|
def request(self, token_uri, method, body, headers, *args, **kwargs):
|
||||||
self.body = body
|
self.body = body
|
||||||
self.headers = headers
|
self.headers = headers
|
||||||
return (self, json.dumps(self.content))
|
return self, json.dumps(self.content)
|
||||||
|
|
||||||
|
|
||||||
class TestAppAssertionCredentials(unittest.TestCase):
|
class TestAppAssertionCredentials(unittest.TestCase):
|
||||||
@@ -132,8 +132,8 @@ class TestAppAssertionCredentials(unittest.TestCase):
|
|||||||
class AppIdentityStubImpl(apiproxy_stub.APIProxyStub):
|
class AppIdentityStubImpl(apiproxy_stub.APIProxyStub):
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
super(TestAppAssertionCredentials.AppIdentityStubImpl, self).__init__(
|
super(TestAppAssertionCredentials.AppIdentityStubImpl,
|
||||||
'app_identity_service')
|
self).__init__('app_identity_service')
|
||||||
|
|
||||||
def _Dynamic_GetAccessToken(self, request, response):
|
def _Dynamic_GetAccessToken(self, request, response):
|
||||||
response.set_access_token('a_token_123')
|
response.set_access_token('a_token_123')
|
||||||
@@ -142,8 +142,8 @@ class TestAppAssertionCredentials(unittest.TestCase):
|
|||||||
class ErroringAppIdentityStubImpl(apiproxy_stub.APIProxyStub):
|
class ErroringAppIdentityStubImpl(apiproxy_stub.APIProxyStub):
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
super(TestAppAssertionCredentials.ErroringAppIdentityStubImpl, self).__init__(
|
super(TestAppAssertionCredentials.ErroringAppIdentityStubImpl,
|
||||||
'app_identity_service')
|
self).__init__('app_identity_service')
|
||||||
|
|
||||||
def _Dynamic_GetAccessToken(self, request, response):
|
def _Dynamic_GetAccessToken(self, request, response):
|
||||||
raise app_identity.BackendDeadlineExceeded()
|
raise app_identity.BackendDeadlineExceeded()
|
||||||
@@ -183,7 +183,8 @@ class TestAppAssertionCredentials(unittest.TestCase):
|
|||||||
'http://www.googleapis.com/scope http://www.googleapis.com/scope2',
|
'http://www.googleapis.com/scope http://www.googleapis.com/scope2',
|
||||||
credentials.scope)
|
credentials.scope)
|
||||||
|
|
||||||
scope = "http://www.googleapis.com/scope http://www.googleapis.com/scope2"
|
scope = ('http://www.googleapis.com/scope '
|
||||||
|
'http://www.googleapis.com/scope2')
|
||||||
credentials = AppAssertionCredentials(scope)
|
credentials = AppAssertionCredentials(scope)
|
||||||
http = httplib2.Http()
|
http = httplib2.Http()
|
||||||
credentials.refresh(http)
|
credentials.refresh(http)
|
||||||
@@ -240,7 +241,8 @@ class TestAppAssertionCredentials(unittest.TestCase):
|
|||||||
def test_save_to_well_known_file(self):
|
def test_save_to_well_known_file(self):
|
||||||
os.environ[_CLOUDSDK_CONFIG_ENV_VAR] = tempfile.mkdtemp()
|
os.environ[_CLOUDSDK_CONFIG_ENV_VAR] = tempfile.mkdtemp()
|
||||||
credentials = AppAssertionCredentials([])
|
credentials = AppAssertionCredentials([])
|
||||||
self.assertRaises(NotImplementedError, save_to_well_known_file, credentials)
|
self.assertRaises(NotImplementedError,
|
||||||
|
save_to_well_known_file, credentials)
|
||||||
del os.environ[_CLOUDSDK_CONFIG_ENV_VAR]
|
del os.environ[_CLOUDSDK_CONFIG_ENV_VAR]
|
||||||
|
|
||||||
|
|
||||||
@@ -260,8 +262,8 @@ class FlowPropertyTest(unittest.TestCase):
|
|||||||
|
|
||||||
def test_flow_get_put(self):
|
def test_flow_get_put(self):
|
||||||
instance = TestFlowModel(
|
instance = TestFlowModel(
|
||||||
flow=flow_from_clientsecrets(datafile('client_secrets.json'), 'foo',
|
flow=flow_from_clientsecrets(datafile('client_secrets.json'),
|
||||||
redirect_uri='oob'),
|
'foo', redirect_uri='oob'),
|
||||||
key_name='foo'
|
key_name='foo'
|
||||||
)
|
)
|
||||||
instance.put()
|
instance.put()
|
||||||
@@ -287,8 +289,8 @@ class FlowNDBPropertyTest(unittest.TestCase):
|
|||||||
|
|
||||||
def test_flow_get_put(self):
|
def test_flow_get_put(self):
|
||||||
instance = TestFlowNDBModel(
|
instance = TestFlowNDBModel(
|
||||||
flow=flow_from_clientsecrets(datafile('client_secrets.json'), 'foo',
|
flow=flow_from_clientsecrets(datafile('client_secrets.json'),
|
||||||
redirect_uri='oob'),
|
'foo', redirect_uri='oob'),
|
||||||
id='foo'
|
id='foo'
|
||||||
)
|
)
|
||||||
instance.put()
|
instance.put()
|
||||||
@@ -370,8 +372,8 @@ class StorageByKeyNameTest(unittest.TestCase):
|
|||||||
self.assertEqual(None, storage.get())
|
self.assertEqual(None, storage.get())
|
||||||
self.credentials.set_store(storage)
|
self.credentials.set_store(storage)
|
||||||
storage.put(self.credentials)
|
storage.put(self.credentials)
|
||||||
# Pre-bug 292 old_creds wouldn't have storage, and the _refresh wouldn't
|
# Pre-bug 292 old_creds wouldn't have storage, and the _refresh
|
||||||
# be able to store the updated cred back into the storage.
|
# wouldn't be able to store the updated cred back into the storage.
|
||||||
old_creds = storage.get()
|
old_creds = storage.get()
|
||||||
self.assertEqual(old_creds.access_token, 'foo')
|
self.assertEqual(old_creds.access_token, 'foo')
|
||||||
old_creds.invalid = True
|
old_creds.invalid = True
|
||||||
@@ -399,7 +401,8 @@ class StorageByKeyNameTest(unittest.TestCase):
|
|||||||
CredentialsNDBModel, 'foo', 'credentials')
|
CredentialsNDBModel, 'foo', 'credentials')
|
||||||
self.assertEqual(None, storage.get())
|
self.assertEqual(None, storage.get())
|
||||||
|
|
||||||
# Add credentials to model with storage, and check equivalent w/o storage
|
# Add credentials to model with storage, and check equivalent
|
||||||
|
# w/o storage
|
||||||
storage.put(self.credentials)
|
storage.put(self.credentials)
|
||||||
credmodel = CredentialsNDBModel.get_by_id('foo')
|
credmodel = CredentialsNDBModel.get_by_id('foo')
|
||||||
self.assertEqual(credmodel.credentials.to_json(),
|
self.assertEqual(credmodel.credentials.to_json(),
|
||||||
@@ -523,12 +526,14 @@ class DecoratorTests(unittest.TestCase):
|
|||||||
if parent.should_raise:
|
if parent.should_raise:
|
||||||
raise Exception('')
|
raise Exception('')
|
||||||
|
|
||||||
application = webapp2.WSGIApplication([
|
routes = [
|
||||||
('/oauth2callback', self.decorator.callback_handler()),
|
('/oauth2callback', self.decorator.callback_handler()),
|
||||||
('/foo_path', TestRequiredHandler),
|
('/foo_path', TestRequiredHandler),
|
||||||
webapp2.Route(r'/bar_path/<year:\d{4}>/<month:\d{2}>',
|
webapp2.Route(r'/bar_path/<year:\d{4}>/<month:\d{2}>',
|
||||||
handler=TestAwareHandler, name='bar')],
|
handler=TestAwareHandler, name='bar'),
|
||||||
debug=True)
|
]
|
||||||
|
application = webapp2.WSGIApplication(routes, debug=True)
|
||||||
|
|
||||||
self.app = TestApp(application, extra_environ={
|
self.app = TestApp(application, extra_environ={
|
||||||
'wsgi.url_scheme': 'http',
|
'wsgi.url_scheme': 'http',
|
||||||
'HTTP_HOST': 'localhost',
|
'HTTP_HOST': 'localhost',
|
||||||
@@ -549,8 +554,10 @@ class DecoratorTests(unittest.TestCase):
|
|||||||
self.assertEqual(self.decorator.credentials, None)
|
self.assertEqual(self.decorator.credentials, None)
|
||||||
response = self.app.get('http://localhost/foo_path')
|
response = self.app.get('http://localhost/foo_path')
|
||||||
self.assertTrue(response.status.startswith('302'))
|
self.assertTrue(response.status.startswith('302'))
|
||||||
q = urllib.parse.parse_qs(response.headers['Location'].split('?', 1)[1])
|
q = urllib.parse.parse_qs(
|
||||||
self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0])
|
response.headers['Location'].split('?', 1)[1])
|
||||||
|
self.assertEqual('http://localhost/oauth2callback',
|
||||||
|
q['redirect_uri'][0])
|
||||||
self.assertEqual('foo_client_id', q['client_id'][0])
|
self.assertEqual('foo_client_id', q['client_id'][0])
|
||||||
self.assertEqual('foo_scope bar_scope', q['scope'][0])
|
self.assertEqual('foo_scope bar_scope', q['scope'][0])
|
||||||
self.assertEqual('http://localhost/foo_path',
|
self.assertEqual('http://localhost/foo_path',
|
||||||
@@ -571,7 +578,8 @@ class DecoratorTests(unittest.TestCase):
|
|||||||
self.assertEqual(None, self.decorator.credentials)
|
self.assertEqual(None, self.decorator.credentials)
|
||||||
if self.decorator._token_response_param:
|
if self.decorator._token_response_param:
|
||||||
response_query = urllib.parse.parse_qs(parts[1])
|
response_query = urllib.parse.parse_qs(parts[1])
|
||||||
response = response_query[self.decorator._token_response_param][0]
|
response = response_query[
|
||||||
|
self.decorator._token_response_param][0]
|
||||||
self.assertEqual(Http2Mock.content,
|
self.assertEqual(Http2Mock.content,
|
||||||
json.loads(urllib.parse.unquote(response)))
|
json.loads(urllib.parse.unquote(response)))
|
||||||
self.assertEqual(self.decorator.flow, self.decorator._tls.flow)
|
self.assertEqual(self.decorator.flow, self.decorator._tls.flow)
|
||||||
@@ -604,8 +612,10 @@ class DecoratorTests(unittest.TestCase):
|
|||||||
# Invalid Credentials should start the OAuth dance again.
|
# Invalid Credentials should start the OAuth dance again.
|
||||||
response = self.app.get('/foo_path')
|
response = self.app.get('/foo_path')
|
||||||
self.assertTrue(response.status.startswith('302'))
|
self.assertTrue(response.status.startswith('302'))
|
||||||
q = urllib.parse.parse_qs(response.headers['Location'].split('?', 1)[1])
|
q = urllib.parse.parse_qs(
|
||||||
self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0])
|
response.headers['Location'].split('?', 1)[1])
|
||||||
|
self.assertEqual('http://localhost/oauth2callback',
|
||||||
|
q['redirect_uri'][0])
|
||||||
|
|
||||||
def test_storage_delete(self):
|
def test_storage_delete(self):
|
||||||
# An initial request to an oauth_required decorated path should be a
|
# An initial request to an oauth_required decorated path should be a
|
||||||
@@ -621,7 +631,8 @@ class DecoratorTests(unittest.TestCase):
|
|||||||
'code': 'foo_access_code',
|
'code': 'foo_access_code',
|
||||||
'state': 'foo_path:xsrfkey123',
|
'state': 'foo_path:xsrfkey123',
|
||||||
})
|
})
|
||||||
self.assertEqual('http://localhost/foo_path', response.headers['Location'])
|
self.assertEqual('http://localhost/foo_path',
|
||||||
|
response.headers['Location'])
|
||||||
self.assertEqual(None, self.decorator.credentials)
|
self.assertEqual(None, self.decorator.credentials)
|
||||||
|
|
||||||
# Now requesting the decorated path should work.
|
# Now requesting the decorated path should work.
|
||||||
@@ -643,14 +654,16 @@ class DecoratorTests(unittest.TestCase):
|
|||||||
'foo_path:xsrfkey123', self.current_user)
|
'foo_path:xsrfkey123', self.current_user)
|
||||||
|
|
||||||
def test_aware(self):
|
def test_aware(self):
|
||||||
# An initial request to an oauth_aware decorated path should not redirect.
|
# An initial request to an oauth_aware decorated path should
|
||||||
|
# not redirect.
|
||||||
response = self.app.get('http://localhost/bar_path/2012/01')
|
response = self.app.get('http://localhost/bar_path/2012/01')
|
||||||
self.assertEqual('Hello World!', response.body)
|
self.assertEqual('Hello World!', response.body)
|
||||||
self.assertEqual('200 OK', response.status)
|
self.assertEqual('200 OK', response.status)
|
||||||
self.assertEqual(False, self.decorator.has_credentials())
|
self.assertEqual(False, self.decorator.has_credentials())
|
||||||
url = self.decorator.authorize_url()
|
url = self.decorator.authorize_url()
|
||||||
q = urllib.parse.parse_qs(url.split('?', 1)[1])
|
q = urllib.parse.parse_qs(url.split('?', 1)[1])
|
||||||
self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0])
|
self.assertEqual('http://localhost/oauth2callback',
|
||||||
|
q['redirect_uri'][0])
|
||||||
self.assertEqual('foo_client_id', q['client_id'][0])
|
self.assertEqual('foo_client_id', q['client_id'][0])
|
||||||
self.assertEqual('foo_scope bar_scope', q['scope'][0])
|
self.assertEqual('foo_scope bar_scope', q['scope'][0])
|
||||||
self.assertEqual('http://localhost/bar_path/2012/01',
|
self.assertEqual('http://localhost/bar_path/2012/01',
|
||||||
@@ -667,7 +680,8 @@ class DecoratorTests(unittest.TestCase):
|
|||||||
'state': 'bar_path:xsrfkey456',
|
'state': 'bar_path:xsrfkey456',
|
||||||
})
|
})
|
||||||
|
|
||||||
self.assertEqual('http://localhost/bar_path', response.headers['Location'])
|
self.assertEqual('http://localhost/bar_path',
|
||||||
|
response.headers['Location'])
|
||||||
self.assertEqual(False, self.decorator.has_credentials())
|
self.assertEqual(False, self.decorator.has_credentials())
|
||||||
parse_state_value.assert_called_once_with(
|
parse_state_value.assert_called_once_with(
|
||||||
'bar_path:xsrfkey456', self.current_user)
|
'bar_path:xsrfkey456', self.current_user)
|
||||||
@@ -692,7 +706,8 @@ class DecoratorTests(unittest.TestCase):
|
|||||||
self.assertEqual(None, self.decorator.credentials)
|
self.assertEqual(None, self.decorator.credentials)
|
||||||
|
|
||||||
def test_error_in_step2(self):
|
def test_error_in_step2(self):
|
||||||
# An initial request to an oauth_aware decorated path should not redirect.
|
# An initial request to an oauth_aware decorated path should
|
||||||
|
# not redirect.
|
||||||
response = self.app.get('/bar_path/2012/01')
|
response = self.app.get('/bar_path/2012/01')
|
||||||
url = self.decorator.authorize_url()
|
url = self.decorator.authorize_url()
|
||||||
response = self.app.get('/oauth2callback', {
|
response = self.app.get('/oauth2callback', {
|
||||||
@@ -735,7 +750,8 @@ class DecoratorTests(unittest.TestCase):
|
|||||||
self.decorator = decorator
|
self.decorator = decorator
|
||||||
self.test_required()
|
self.test_required()
|
||||||
http = self.decorator.http()
|
http = self.decorator.http()
|
||||||
self.assertEquals('foo_access_token', http.request.credentials.access_token)
|
self.assertEquals('foo_access_token',
|
||||||
|
http.request.credentials.access_token)
|
||||||
|
|
||||||
# revoke_uri is not required
|
# revoke_uri is not required
|
||||||
self.assertEqual(self.decorator._revoke_uri,
|
self.assertEqual(self.decorator._revoke_uri,
|
||||||
|
|||||||
@@ -14,8 +14,6 @@
|
|||||||
|
|
||||||
"""Unit tests for oauth2client.clientsecrets."""
|
"""Unit tests for oauth2client.clientsecrets."""
|
||||||
|
|
||||||
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
|
|
||||||
|
|
||||||
import os
|
import os
|
||||||
import unittest
|
import unittest
|
||||||
from io import StringIO
|
from io import StringIO
|
||||||
@@ -24,6 +22,10 @@ import httplib2
|
|||||||
|
|
||||||
from oauth2client import clientsecrets
|
from oauth2client import clientsecrets
|
||||||
|
|
||||||
|
|
||||||
|
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
|
||||||
|
|
||||||
|
|
||||||
DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
|
DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
|
||||||
VALID_FILE = os.path.join(DATA_DIR, 'client_secrets.json')
|
VALID_FILE = os.path.join(DATA_DIR, 'client_secrets.json')
|
||||||
INVALID_FILE = os.path.join(DATA_DIR, 'unfilled_client_secrets.json')
|
INVALID_FILE = os.path.join(DATA_DIR, 'unfilled_client_secrets.json')
|
||||||
@@ -32,28 +34,23 @@ NONEXISTENT_FILE = os.path.join(__file__, '..', 'afilethatisntthere.json')
|
|||||||
|
|
||||||
class OAuth2CredentialsTests(unittest.TestCase):
|
class OAuth2CredentialsTests(unittest.TestCase):
|
||||||
|
|
||||||
def setUp(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
def tearDown(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
def test_validate_error(self):
|
def test_validate_error(self):
|
||||||
|
payload = (
|
||||||
|
b'{'
|
||||||
|
b' "web": {'
|
||||||
|
b' "client_id": "[[CLIENT ID REQUIRED]]",'
|
||||||
|
b' "client_secret": "[[CLIENT SECRET REQUIRED]]",'
|
||||||
|
b' "redirect_uris": ["http://localhost:8080/oauth2callback"],'
|
||||||
|
b' "auth_uri": "",'
|
||||||
|
b' "token_uri": ""'
|
||||||
|
b' }'
|
||||||
|
b'}')
|
||||||
ERRORS = [
|
ERRORS = [
|
||||||
('{}', 'Invalid'),
|
('{}', 'Invalid'),
|
||||||
('{"foo": {}}', 'Unknown'),
|
('{"foo": {}}', 'Unknown'),
|
||||||
('{"web": {}}', 'Missing'),
|
('{"web": {}}', 'Missing'),
|
||||||
('{"web": {"client_id": "dkkd"}}', 'Missing'),
|
('{"web": {"client_id": "dkkd"}}', 'Missing'),
|
||||||
("""{
|
(payload, 'Property'),
|
||||||
"web": {
|
|
||||||
"client_id": "[[CLIENT ID REQUIRED]]",
|
|
||||||
"client_secret": "[[CLIENT SECRET REQUIRED]]",
|
|
||||||
"redirect_uris": ["http://localhost:8080/oauth2callback"],
|
|
||||||
"auth_uri": "",
|
|
||||||
"token_uri": ""
|
|
||||||
}
|
|
||||||
}
|
|
||||||
""", 'Property'),
|
|
||||||
]
|
]
|
||||||
for src, match in ERRORS:
|
for src, match in ERRORS:
|
||||||
# Ensure that it is unicode
|
# Ensure that it is unicode
|
||||||
|
|||||||
@@ -53,7 +53,8 @@ class Test_pkcs12_key_as_pem(unittest.TestCase):
|
|||||||
credentials = self._make_signed_jwt_creds()
|
credentials = self._make_signed_jwt_creds()
|
||||||
if password is None:
|
if password is None:
|
||||||
password = credentials.private_key_password
|
password = credentials.private_key_password
|
||||||
pem_contents = crypt.pkcs12_key_as_pem(credentials.private_key, password)
|
pem_contents = crypt.pkcs12_key_as_pem(credentials.private_key,
|
||||||
|
password)
|
||||||
pkcs12_key_as_pem = datafile('pem_from_pkcs12.pem')
|
pkcs12_key_as_pem = datafile('pem_from_pkcs12.pem')
|
||||||
pkcs12_key_as_pem = _helpers._parse_pem_key(pkcs12_key_as_pem)
|
pkcs12_key_as_pem = _helpers._parse_pem_key(pkcs12_key_as_pem)
|
||||||
alternate_pem = datafile('pem_from_pkcs12_alternate.pem')
|
alternate_pem = datafile('pem_from_pkcs12_alternate.pem')
|
||||||
@@ -70,4 +71,5 @@ class Test_pkcs12_key_as_pem(unittest.TestCase):
|
|||||||
from OpenSSL import crypto
|
from OpenSSL import crypto
|
||||||
credentials = self._make_signed_jwt_creds(private_key=b'NOT_A_KEY')
|
credentials = self._make_signed_jwt_creds(private_key=b'NOT_A_KEY')
|
||||||
self.assertRaises(crypto.Error, crypt.pkcs12_key_as_pem,
|
self.assertRaises(crypto.Error, crypt.pkcs12_key_as_pem,
|
||||||
credentials.private_key, credentials.private_key_password)
|
credentials.private_key,
|
||||||
|
credentials.private_key_password)
|
||||||
|
|||||||
@@ -57,8 +57,9 @@ class _AuthReferenceServer(threading.Thread):
|
|||||||
def run(self):
|
def run(self):
|
||||||
s = None
|
s = None
|
||||||
try:
|
try:
|
||||||
# Do not set the timeout on the socket, leave it in the blocking mode as
|
# Do not set the timeout on the socket, leave it in the blocking
|
||||||
# setting the timeout seems to cause spurious EAGAIN errors on OSX.
|
# mode as setting the timeout seems to cause spurious EAGAIN
|
||||||
|
# errors on OSX.
|
||||||
self._socket.settimeout(None)
|
self._socket.settimeout(None)
|
||||||
|
|
||||||
s, unused_addr = self._socket.accept()
|
s, unused_addr = self._socket.accept()
|
||||||
@@ -133,6 +134,7 @@ class DevshellCredentialsTests(unittest.TestCase):
|
|||||||
os.path.isdir = lambda path: True
|
os.path.isdir = lambda path: True
|
||||||
with _AuthReferenceServer():
|
with _AuthReferenceServer():
|
||||||
creds = DevshellCredentials()
|
creds = DevshellCredentials()
|
||||||
self.assertRaises(NotImplementedError, save_to_well_known_file, creds)
|
self.assertRaises(NotImplementedError,
|
||||||
|
save_to_well_known_file, creds)
|
||||||
finally:
|
finally:
|
||||||
os.path.isdir = ORIGINAL_ISDIR
|
os.path.isdir = ORIGINAL_ISDIR
|
||||||
|
|||||||
@@ -42,7 +42,8 @@ from oauth2client.client import Flow
|
|||||||
from django.conf import global_settings
|
from django.conf import global_settings
|
||||||
global_settings.SECRET_KEY = 'NotASecret'
|
global_settings.SECRET_KEY = 'NotASecret'
|
||||||
os.environ['DJANGO_SETTINGS_MODULE'] = 'django_settings'
|
os.environ['DJANGO_SETTINGS_MODULE'] = 'django_settings'
|
||||||
sys.modules['django_settings'] = django_settings = imp.new_module('django_settings')
|
sys.modules['django_settings'] = django_settings = imp.new_module(
|
||||||
|
'django_settings')
|
||||||
django_settings.SECRET_KEY = 'xyzzy'
|
django_settings.SECRET_KEY = 'xyzzy'
|
||||||
|
|
||||||
from oauth2client.django_orm import CredentialsField
|
from oauth2client.django_orm import CredentialsField
|
||||||
@@ -50,6 +51,7 @@ from oauth2client.django_orm import FlowField
|
|||||||
|
|
||||||
|
|
||||||
class TestCredentialsField(unittest.TestCase):
|
class TestCredentialsField(unittest.TestCase):
|
||||||
|
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
self.field = CredentialsField()
|
self.field = CredentialsField()
|
||||||
self.credentials = Credentials()
|
self.credentials = Credentials()
|
||||||
@@ -59,7 +61,8 @@ class TestCredentialsField(unittest.TestCase):
|
|||||||
self.assertEquals(self.field.get_internal_type(), 'TextField')
|
self.assertEquals(self.field.get_internal_type(), 'TextField')
|
||||||
|
|
||||||
def test_field_unpickled(self):
|
def test_field_unpickled(self):
|
||||||
self.assertTrue(isinstance(self.field.to_python(self.pickle), Credentials))
|
self.assertTrue(isinstance(self.field.to_python(self.pickle),
|
||||||
|
Credentials))
|
||||||
|
|
||||||
def test_field_pickled(self):
|
def test_field_pickled(self):
|
||||||
prep_value = self.field.get_db_prep_value(self.credentials,
|
prep_value = self.field.get_db_prep_value(self.credentials,
|
||||||
|
|||||||
@@ -104,8 +104,8 @@ class OAuth2ClientFileTests(unittest.TestCase):
|
|||||||
pickle.dump(credentials, f)
|
pickle.dump(credentials, f)
|
||||||
f.close()
|
f.close()
|
||||||
|
|
||||||
# Storage should be not be able to read that object, as the capability to
|
# Storage should be not be able to read that object, as the capability
|
||||||
# read and write credentials as pickled objects has been removed.
|
# to read and write credentials as pickled objects has been removed.
|
||||||
s = file.Storage(FILENAME)
|
s = file.Storage(FILENAME)
|
||||||
read_credentials = s.get()
|
read_credentials = s.get()
|
||||||
self.assertEquals(None, read_credentials)
|
self.assertEquals(None, read_credentials)
|
||||||
@@ -120,7 +120,8 @@ class OAuth2ClientFileTests(unittest.TestCase):
|
|||||||
self.assertEquals(data['_module'], OAuth2Credentials.__module__)
|
self.assertEquals(data['_module'], OAuth2Credentials.__module__)
|
||||||
|
|
||||||
def test_token_refresh_store_expired(self):
|
def test_token_refresh_store_expired(self):
|
||||||
expiration = datetime.datetime.utcnow() - datetime.timedelta(minutes=15)
|
expiration = (datetime.datetime.utcnow() -
|
||||||
|
datetime.timedelta(minutes=15))
|
||||||
credentials = self.create_test_credentials(expiration=expiration)
|
credentials = self.create_test_credentials(expiration=expiration)
|
||||||
|
|
||||||
s = file.Storage(FILENAME)
|
s = file.Storage(FILENAME)
|
||||||
@@ -140,9 +141,10 @@ class OAuth2ClientFileTests(unittest.TestCase):
|
|||||||
self.assertEquals(credentials.access_token, access_token)
|
self.assertEquals(credentials.access_token, access_token)
|
||||||
|
|
||||||
def test_token_refresh_store_expires_soon(self):
|
def test_token_refresh_store_expires_soon(self):
|
||||||
# Tests the case where an access token that is valid when it is read from
|
# Tests the case where an access token that is valid when it is read
|
||||||
# the store expires before the original request succeeds.
|
# from the store expires before the original request succeeds.
|
||||||
expiration = datetime.datetime.utcnow() + datetime.timedelta(minutes=15)
|
expiration = (datetime.datetime.utcnow() +
|
||||||
|
datetime.timedelta(minutes=15))
|
||||||
credentials = self.create_test_credentials(expiration=expiration)
|
credentials = self.create_test_credentials(expiration=expiration)
|
||||||
|
|
||||||
s = file.Storage(FILENAME)
|
s = file.Storage(FILENAME)
|
||||||
@@ -155,8 +157,10 @@ class OAuth2ClientFileTests(unittest.TestCase):
|
|||||||
access_token = '1/3w'
|
access_token = '1/3w'
|
||||||
token_response = {'access_token': access_token, 'expires_in': 3600}
|
token_response = {'access_token': access_token, 'expires_in': 3600}
|
||||||
http = HttpMockSequence([
|
http = HttpMockSequence([
|
||||||
({'status': str(http_client.UNAUTHORIZED)}, b'Initial token expired'),
|
({'status': str(http_client.UNAUTHORIZED)},
|
||||||
({'status': str(http_client.UNAUTHORIZED)}, b'Store token expired'),
|
b'Initial token expired'),
|
||||||
|
({'status': str(http_client.UNAUTHORIZED)},
|
||||||
|
b'Store token expired'),
|
||||||
({'status': str(http_client.OK)},
|
({'status': str(http_client.OK)},
|
||||||
json.dumps(token_response).encode('utf-8')),
|
json.dumps(token_response).encode('utf-8')),
|
||||||
({'status': str(http_client.OK)},
|
({'status': str(http_client.OK)},
|
||||||
@@ -168,7 +172,8 @@ class OAuth2ClientFileTests(unittest.TestCase):
|
|||||||
self.assertEqual(credentials.access_token, access_token)
|
self.assertEqual(credentials.access_token, access_token)
|
||||||
|
|
||||||
def test_token_refresh_good_store(self):
|
def test_token_refresh_good_store(self):
|
||||||
expiration = datetime.datetime.utcnow() + datetime.timedelta(minutes=15)
|
expiration = (datetime.datetime.utcnow() +
|
||||||
|
datetime.timedelta(minutes=15))
|
||||||
credentials = self.create_test_credentials(expiration=expiration)
|
credentials = self.create_test_credentials(expiration=expiration)
|
||||||
|
|
||||||
s = file.Storage(FILENAME)
|
s = file.Storage(FILENAME)
|
||||||
@@ -182,7 +187,8 @@ class OAuth2ClientFileTests(unittest.TestCase):
|
|||||||
self.assertEquals(credentials.access_token, 'bar')
|
self.assertEquals(credentials.access_token, 'bar')
|
||||||
|
|
||||||
def test_token_refresh_stream_body(self):
|
def test_token_refresh_stream_body(self):
|
||||||
expiration = datetime.datetime.utcnow() + datetime.timedelta(minutes=15)
|
expiration = (datetime.datetime.utcnow() +
|
||||||
|
datetime.timedelta(minutes=15))
|
||||||
credentials = self.create_test_credentials(expiration=expiration)
|
credentials = self.create_test_credentials(expiration=expiration)
|
||||||
|
|
||||||
s = file.Storage(FILENAME)
|
s = file.Storage(FILENAME)
|
||||||
@@ -193,10 +199,13 @@ class OAuth2ClientFileTests(unittest.TestCase):
|
|||||||
s.put(new_cred)
|
s.put(new_cred)
|
||||||
|
|
||||||
valid_access_token = '1/3w'
|
valid_access_token = '1/3w'
|
||||||
token_response = {'access_token': valid_access_token, 'expires_in': 3600}
|
token_response = {'access_token': valid_access_token,
|
||||||
|
'expires_in': 3600}
|
||||||
http = HttpMockSequence([
|
http = HttpMockSequence([
|
||||||
({'status': str(http_client.UNAUTHORIZED)}, b'Initial token expired'),
|
({'status': str(http_client.UNAUTHORIZED)},
|
||||||
({'status': str(http_client.UNAUTHORIZED)}, b'Store token expired'),
|
b'Initial token expired'),
|
||||||
|
({'status': str(http_client.UNAUTHORIZED)},
|
||||||
|
b'Store token expired'),
|
||||||
({'status': str(http_client.OK)},
|
({'status': str(http_client.OK)},
|
||||||
json.dumps(token_response).encode('utf-8')),
|
json.dumps(token_response).encode('utf-8')),
|
||||||
({'status': str(http_client.OK)}, 'echo_request_body')
|
({'status': str(http_client.OK)}, 'echo_request_body')
|
||||||
@@ -235,7 +244,8 @@ class OAuth2ClientFileTests(unittest.TestCase):
|
|||||||
mode = os.stat(FILENAME).st_mode
|
mode = os.stat(FILENAME).st_mode
|
||||||
|
|
||||||
if os.name == 'posix':
|
if os.name == 'posix':
|
||||||
self.assertEquals('0o600', oct(stat.S_IMODE(os.stat(FILENAME).st_mode)))
|
self.assertEquals('0o600',
|
||||||
|
oct(stat.S_IMODE(os.stat(FILENAME).st_mode)))
|
||||||
|
|
||||||
def test_read_only_file_fail_lock(self):
|
def test_read_only_file_fail_lock(self):
|
||||||
credentials = self.create_test_credentials()
|
credentials = self.create_test_credentials()
|
||||||
@@ -302,7 +312,8 @@ class OAuth2ClientFileTests(unittest.TestCase):
|
|||||||
self.assertEquals(None, credentials)
|
self.assertEquals(None, credentials)
|
||||||
|
|
||||||
if os.name == 'posix':
|
if os.name == 'posix':
|
||||||
self.assertEquals('0o600', oct(stat.S_IMODE(os.stat(FILENAME).st_mode)))
|
self.assertEquals('0o600',
|
||||||
|
oct(stat.S_IMODE(os.stat(FILENAME).st_mode)))
|
||||||
|
|
||||||
def test_multistore_file_custom_key(self):
|
def test_multistore_file_custom_key(self):
|
||||||
credentials = self.create_test_credentials()
|
credentials = self.create_test_credentials()
|
||||||
@@ -315,7 +326,8 @@ class OAuth2ClientFileTests(unittest.TestCase):
|
|||||||
stored_credentials = store.get()
|
stored_credentials = store.get()
|
||||||
|
|
||||||
self.assertNotEquals(None, stored_credentials)
|
self.assertNotEquals(None, stored_credentials)
|
||||||
self.assertEqual(credentials.access_token, stored_credentials.access_token)
|
self.assertEqual(credentials.access_token,
|
||||||
|
stored_credentials.access_token)
|
||||||
|
|
||||||
store.delete()
|
store.delete()
|
||||||
stored_credentials = store.get()
|
stored_credentials = store.get()
|
||||||
@@ -333,14 +345,16 @@ class OAuth2ClientFileTests(unittest.TestCase):
|
|||||||
stored_credentials = store.get()
|
stored_credentials = store.get()
|
||||||
|
|
||||||
self.assertNotEquals(None, stored_credentials)
|
self.assertNotEquals(None, stored_credentials)
|
||||||
self.assertEqual(credentials.access_token, stored_credentials.access_token)
|
self.assertEqual(credentials.access_token,
|
||||||
|
stored_credentials.access_token)
|
||||||
|
|
||||||
# try retrieving with a dictionary
|
# try retrieving with a dictionary
|
||||||
store_dict = multistore_file.get_credential_storage_custom_string_key(
|
store_dict = multistore_file.get_credential_storage_custom_string_key(
|
||||||
FILENAME, {'key': 'mykey'})
|
FILENAME, {'key': 'mykey'})
|
||||||
stored_credentials = store.get()
|
stored_credentials = store.get()
|
||||||
self.assertNotEquals(None, stored_credentials)
|
self.assertNotEquals(None, stored_credentials)
|
||||||
self.assertEqual(credentials.access_token, stored_credentials.access_token)
|
self.assertEqual(credentials.access_token,
|
||||||
|
stored_credentials.access_token)
|
||||||
|
|
||||||
store.delete()
|
store.delete()
|
||||||
stored_credentials = store.get()
|
stored_credentials = store.get()
|
||||||
@@ -356,13 +370,16 @@ class OAuth2ClientFileTests(unittest.TestCase):
|
|||||||
FILENAME, 'client_id', 'user_agent', scopes)
|
FILENAME, 'client_id', 'user_agent', scopes)
|
||||||
store.put(credentials)
|
store.put(credentials)
|
||||||
|
|
||||||
# retrieve the credentials using a custom key that matches the legacy key
|
# retrieve the credentials using a custom key that matches the
|
||||||
|
# legacy key
|
||||||
key = {'clientId': 'client_id', 'userAgent': 'user_agent',
|
key = {'clientId': 'client_id', 'userAgent': 'user_agent',
|
||||||
'scope': util.scopes_to_string(scopes)}
|
'scope': util.scopes_to_string(scopes)}
|
||||||
store = multistore_file.get_credential_storage_custom_key(FILENAME, key)
|
store = multistore_file.get_credential_storage_custom_key(
|
||||||
|
FILENAME, key)
|
||||||
stored_credentials = store.get()
|
stored_credentials = store.get()
|
||||||
|
|
||||||
self.assertEqual(credentials.access_token, stored_credentials.access_token)
|
self.assertEqual(credentials.access_token,
|
||||||
|
stored_credentials.access_token)
|
||||||
|
|
||||||
def test_multistore_file_get_all_keys(self):
|
def test_multistore_file_get_all_keys(self):
|
||||||
# start with no keys
|
# start with no keys
|
||||||
|
|||||||
@@ -64,7 +64,8 @@ class AssertionCredentialsTests(unittest.TestCase):
|
|||||||
|
|
||||||
def test_fail_refresh(self):
|
def test_fail_refresh(self):
|
||||||
http = mock.MagicMock()
|
http = mock.MagicMock()
|
||||||
http.request = mock.MagicMock(return_value=(mock.Mock(status=400), '{}'))
|
http.request = mock.MagicMock(
|
||||||
|
return_value=(mock.Mock(status=400), '{}'))
|
||||||
|
|
||||||
c = AppAssertionCredentials(scope=['http://example.com/a',
|
c = AppAssertionCredentials(scope=['http://example.com/a',
|
||||||
'http://example.com/b'])
|
'http://example.com/b'])
|
||||||
|
|||||||
@@ -58,7 +58,8 @@ class CryptTests(unittest.TestCase):
|
|||||||
self._check_sign_and_verify('privatekey.%s' % self.format)
|
self._check_sign_and_verify('privatekey.%s' % self.format)
|
||||||
|
|
||||||
def test_sign_and_verify_from_converted_pkcs12(self):
|
def test_sign_and_verify_from_converted_pkcs12(self):
|
||||||
# Tests that following instructions to convert from PKCS12 to PEM works.
|
# Tests that following instructions to convert from PKCS12 to
|
||||||
|
# PEM works.
|
||||||
if self.format == 'pem':
|
if self.format == 'pem':
|
||||||
self._check_sign_and_verify('pem_from_pkcs12.pem')
|
self._check_sign_and_verify('pem_from_pkcs12.pem')
|
||||||
|
|
||||||
@@ -121,7 +122,8 @@ class CryptTests(unittest.TestCase):
|
|||||||
])
|
])
|
||||||
|
|
||||||
contents = verify_id_token(
|
contents = verify_id_token(
|
||||||
jwt, 'some_audience_address@testing.gserviceaccount.com', http=http)
|
jwt, 'some_audience_address@testing.gserviceaccount.com',
|
||||||
|
http=http)
|
||||||
self.assertEqual('billy bob', contents['user'])
|
self.assertEqual('billy bob', contents['user'])
|
||||||
self.assertEqual('data', contents['metadata']['meta'])
|
self.assertEqual('data', contents['metadata']['meta'])
|
||||||
|
|
||||||
@@ -146,7 +148,9 @@ class CryptTests(unittest.TestCase):
|
|||||||
self._check_jwt_failure('foo.bar.baz', 'Can\'t parse token')
|
self._check_jwt_failure('foo.bar.baz', 'Can\'t parse token')
|
||||||
|
|
||||||
# Bad signature
|
# Bad signature
|
||||||
jwt = b'.'.join([b'foo', crypt._urlsafe_b64encode('{"a":"b"}'), b'baz'])
|
jwt = b'.'.join([b'foo',
|
||||||
|
crypt._urlsafe_b64encode('{"a":"b"}'),
|
||||||
|
b'baz'])
|
||||||
self._check_jwt_failure(jwt, 'Invalid token signature')
|
self._check_jwt_failure(jwt, 'Invalid token signature')
|
||||||
|
|
||||||
# No expiration
|
# No expiration
|
||||||
@@ -280,7 +284,7 @@ class SignedJwtAssertionCredentialsTests(unittest.TestCase):
|
|||||||
scope='read+write',
|
scope='read+write',
|
||||||
sub='joe@example.org')
|
sub='joe@example.org')
|
||||||
|
|
||||||
(filehandle, filename) = tempfile.mkstemp()
|
filehandle, filename = tempfile.mkstemp()
|
||||||
os.close(filehandle)
|
os.close(filehandle)
|
||||||
store = Storage(filename)
|
store = Storage(filename)
|
||||||
store.put(credentials)
|
store.put(credentials)
|
||||||
@@ -326,6 +330,7 @@ class PKCSSignedJwtAssertionCredentialsPyCryptoTests(unittest.TestCase):
|
|||||||
|
|
||||||
|
|
||||||
class TestHasOpenSSLFlag(unittest.TestCase):
|
class TestHasOpenSSLFlag(unittest.TestCase):
|
||||||
|
|
||||||
def test_true(self):
|
def test_true(self):
|
||||||
self.assertEqual(True, HAS_OPENSSL)
|
self.assertEqual(True, HAS_OPENSSL)
|
||||||
self.assertEqual(True, HAS_CRYPTO)
|
self.assertEqual(True, HAS_CRYPTO)
|
||||||
|
|||||||
@@ -194,7 +194,8 @@ class GoogleCredentialsTests(unittest.TestCase):
|
|||||||
def validate_service_account_credentials(self, credentials):
|
def validate_service_account_credentials(self, credentials):
|
||||||
self.assertTrue(isinstance(credentials, _ServiceAccountCredentials))
|
self.assertTrue(isinstance(credentials, _ServiceAccountCredentials))
|
||||||
self.assertEqual('123', credentials._service_account_id)
|
self.assertEqual('123', credentials._service_account_id)
|
||||||
self.assertEqual('dummy@google.com', credentials._service_account_email)
|
self.assertEqual('dummy@google.com',
|
||||||
|
credentials._service_account_email)
|
||||||
self.assertEqual('ABCDEF', credentials._private_key_id)
|
self.assertEqual('ABCDEF', credentials._private_key_id)
|
||||||
self.assertEqual('', credentials._scopes)
|
self.assertEqual('', credentials._scopes)
|
||||||
|
|
||||||
@@ -209,7 +210,8 @@ class GoogleCredentialsTests(unittest.TestCase):
|
|||||||
self.assertEqual('Python client library', credentials.user_agent)
|
self.assertEqual('Python client library', credentials.user_agent)
|
||||||
|
|
||||||
def get_a_google_credentials_object(self):
|
def get_a_google_credentials_object(self):
|
||||||
return GoogleCredentials(None, None, None, None, None, None, None, None)
|
return GoogleCredentials(None, None, None, None,
|
||||||
|
None, None, None, None)
|
||||||
|
|
||||||
def test_create_scoped_required(self):
|
def test_create_scoped_required(self):
|
||||||
self.assertFalse(
|
self.assertFalse(
|
||||||
@@ -241,7 +243,8 @@ class GoogleCredentialsTests(unittest.TestCase):
|
|||||||
autospec=True) as urlopen:
|
autospec=True) as urlopen:
|
||||||
self.assertTrue(_in_gae_environment())
|
self.assertTrue(_in_gae_environment())
|
||||||
self.assertFalse(_in_gce_environment())
|
self.assertFalse(_in_gce_environment())
|
||||||
# We already know are in GAE, so we shouldn't actually do the urlopen.
|
# We already know are in GAE, so we shouldn't actually do
|
||||||
|
# the urlopen.
|
||||||
self.assertFalse(urlopen.called)
|
self.assertFalse(urlopen.called)
|
||||||
|
|
||||||
def test_environment_caching(self):
|
def test_environment_caching(self):
|
||||||
@@ -249,7 +252,8 @@ class GoogleCredentialsTests(unittest.TestCase):
|
|||||||
with mock_module_import('google.appengine'):
|
with mock_module_import('google.appengine'):
|
||||||
self.assertTrue(_in_gae_environment())
|
self.assertTrue(_in_gae_environment())
|
||||||
os.environ['SERVER_SOFTWARE'] = ''
|
os.environ['SERVER_SOFTWARE'] = ''
|
||||||
# Even though we no longer pass the environment check, it is cached.
|
# Even though we no longer pass the environment check, it
|
||||||
|
# is cached.
|
||||||
self.assertTrue(_in_gae_environment())
|
self.assertTrue(_in_gae_environment())
|
||||||
|
|
||||||
def test_environment_check_gae_module_on_gce(self):
|
def test_environment_check_gae_module_on_gce(self):
|
||||||
@@ -325,7 +329,8 @@ class GoogleCredentialsTests(unittest.TestCase):
|
|||||||
def test_get_environment_variable_file_error(self):
|
def test_get_environment_variable_file_error(self):
|
||||||
nonexistent_file = datafile('nonexistent')
|
nonexistent_file = datafile('nonexistent')
|
||||||
os.environ[GOOGLE_APPLICATION_CREDENTIALS] = nonexistent_file
|
os.environ[GOOGLE_APPLICATION_CREDENTIALS] = nonexistent_file
|
||||||
# we can't use self.assertRaisesRegexp() because it is only in Python 2.7+
|
# we can't use self.assertRaisesRegexp() because it is only in
|
||||||
|
# Python 2.7+
|
||||||
try:
|
try:
|
||||||
_get_environment_variable_file()
|
_get_environment_variable_file()
|
||||||
self.fail(nonexistent_file + ' should not exist.')
|
self.fail(nonexistent_file + ' should not exist.')
|
||||||
@@ -363,7 +368,7 @@ class GoogleCredentialsTests(unittest.TestCase):
|
|||||||
os.environ = ORIGINAL_ENVIRON
|
os.environ = ORIGINAL_ENVIRON
|
||||||
os.path.isdir = ORIGINAL_ISDIR
|
os.path.isdir = ORIGINAL_ISDIR
|
||||||
|
|
||||||
def test_get_application_default_credential_from_file_service_account(self):
|
def test_get_adc_from_file_service_account(self):
|
||||||
credentials_file = datafile(
|
credentials_file = datafile(
|
||||||
os.path.join('gcloud', 'application_default_credentials.json'))
|
os.path.join('gcloud', 'application_default_credentials.json'))
|
||||||
credentials = _get_application_default_credential_from_file(
|
credentials = _get_application_default_credential_from_file(
|
||||||
@@ -376,7 +381,8 @@ class GoogleCredentialsTests(unittest.TestCase):
|
|||||||
credentials = _get_application_default_credential_from_file(
|
credentials = _get_application_default_credential_from_file(
|
||||||
credential_file)
|
credential_file)
|
||||||
temp_credential_file = datafile(
|
temp_credential_file = datafile(
|
||||||
os.path.join('gcloud', 'temp_well_known_file_service_account.json'))
|
os.path.join('gcloud',
|
||||||
|
'temp_well_known_file_service_account.json'))
|
||||||
save_to_well_known_file(credentials, temp_credential_file)
|
save_to_well_known_file(credentials, temp_credential_file)
|
||||||
with open(temp_credential_file) as f:
|
with open(temp_credential_file) as f:
|
||||||
d = json.load(f)
|
d = json.load(f)
|
||||||
@@ -398,22 +404,23 @@ class GoogleCredentialsTests(unittest.TestCase):
|
|||||||
finally:
|
finally:
|
||||||
os.path.isdir = ORIGINAL_ISDIR
|
os.path.isdir = ORIGINAL_ISDIR
|
||||||
|
|
||||||
def test_get_application_default_credential_from_file_authorized_user(self):
|
def test_get_adc_from_file_authorized_user(self):
|
||||||
credentials_file = datafile(
|
credentials_file = datafile(os.path.join(
|
||||||
os.path.join('gcloud',
|
'gcloud',
|
||||||
'application_default_credentials_authorized_user.json'))
|
'application_default_credentials_authorized_user.json'))
|
||||||
credentials = _get_application_default_credential_from_file(
|
credentials = _get_application_default_credential_from_file(
|
||||||
credentials_file)
|
credentials_file)
|
||||||
self.validate_google_credentials(credentials)
|
self.validate_google_credentials(credentials)
|
||||||
|
|
||||||
def test_save_to_well_known_file_authorized_user(self):
|
def test_save_to_well_known_file_authorized_user(self):
|
||||||
credentials_file = datafile(
|
credentials_file = datafile(os.path.join(
|
||||||
os.path.join('gcloud',
|
'gcloud',
|
||||||
'application_default_credentials_authorized_user.json'))
|
'application_default_credentials_authorized_user.json'))
|
||||||
credentials = _get_application_default_credential_from_file(
|
credentials = _get_application_default_credential_from_file(
|
||||||
credentials_file)
|
credentials_file)
|
||||||
temp_credential_file = datafile(
|
temp_credential_file = datafile(
|
||||||
os.path.join('gcloud', 'temp_well_known_file_authorized_user.json'))
|
os.path.join('gcloud',
|
||||||
|
'temp_well_known_file_authorized_user.json'))
|
||||||
save_to_well_known_file(credentials, temp_credential_file)
|
save_to_well_known_file(credentials, temp_credential_file)
|
||||||
with open(temp_credential_file) as f:
|
with open(temp_credential_file) as f:
|
||||||
d = json.load(f)
|
d = json.load(f)
|
||||||
@@ -427,7 +434,8 @@ class GoogleCredentialsTests(unittest.TestCase):
|
|||||||
credentials_file = datafile(
|
credentials_file = datafile(
|
||||||
os.path.join('gcloud',
|
os.path.join('gcloud',
|
||||||
'application_default_credentials_malformed_1.json'))
|
'application_default_credentials_malformed_1.json'))
|
||||||
# we can't use self.assertRaisesRegexp() because it is only in Python 2.7+
|
# we can't use self.assertRaisesRegexp() because it is only in
|
||||||
|
# Python 2.7+
|
||||||
try:
|
try:
|
||||||
_get_application_default_credential_from_file(credentials_file)
|
_get_application_default_credential_from_file(credentials_file)
|
||||||
self.fail('An exception was expected!')
|
self.fail('An exception was expected!')
|
||||||
@@ -441,24 +449,28 @@ class GoogleCredentialsTests(unittest.TestCase):
|
|||||||
credentials_file = datafile(
|
credentials_file = datafile(
|
||||||
os.path.join('gcloud',
|
os.path.join('gcloud',
|
||||||
'application_default_credentials_malformed_2.json'))
|
'application_default_credentials_malformed_2.json'))
|
||||||
# we can't use self.assertRaisesRegexp() because it is only in Python 2.7+
|
# we can't use self.assertRaisesRegexp() because it is only in
|
||||||
|
# Python 2.7+
|
||||||
try:
|
try:
|
||||||
_get_application_default_credential_from_file(credentials_file)
|
_get_application_default_credential_from_file(credentials_file)
|
||||||
self.fail('An exception was expected!')
|
self.fail('An exception was expected!')
|
||||||
except ApplicationDefaultCredentialsError as error:
|
except ApplicationDefaultCredentialsError as error:
|
||||||
self.assertEqual('The following field(s) must be defined: private_key_id',
|
self.assertEqual(
|
||||||
|
'The following field(s) must be defined: private_key_id',
|
||||||
str(error))
|
str(error))
|
||||||
|
|
||||||
def test_get_application_default_credential_from_malformed_file_3(self):
|
def test_get_application_default_credential_from_malformed_file_3(self):
|
||||||
credentials_file = datafile(
|
credentials_file = datafile(
|
||||||
os.path.join('gcloud',
|
os.path.join('gcloud',
|
||||||
'application_default_credentials_malformed_3.json'))
|
'application_default_credentials_malformed_3.json'))
|
||||||
self.assertRaises(ValueError, _get_application_default_credential_from_file,
|
self.assertRaises(ValueError,
|
||||||
|
_get_application_default_credential_from_file,
|
||||||
credentials_file)
|
credentials_file)
|
||||||
|
|
||||||
def test_raise_exception_for_missing_fields(self):
|
def test_raise_exception_for_missing_fields(self):
|
||||||
missing_fields = ['first', 'second', 'third']
|
missing_fields = ['first', 'second', 'third']
|
||||||
# we can't use self.assertRaisesRegexp() because it is only in Python 2.7+
|
# we can't use self.assertRaisesRegexp() because it is only in
|
||||||
|
# Python 2.7+
|
||||||
try:
|
try:
|
||||||
_raise_exception_for_missing_fields(missing_fields)
|
_raise_exception_for_missing_fields(missing_fields)
|
||||||
self.fail('An exception was expected!')
|
self.fail('An exception was expected!')
|
||||||
@@ -471,9 +483,11 @@ class GoogleCredentialsTests(unittest.TestCase):
|
|||||||
credential_file = 'any_file'
|
credential_file = 'any_file'
|
||||||
extra_help = ' be good'
|
extra_help = ' be good'
|
||||||
error = ApplicationDefaultCredentialsError('stuff happens')
|
error = ApplicationDefaultCredentialsError('stuff happens')
|
||||||
# we can't use self.assertRaisesRegexp() because it is only in Python 2.7+
|
# we can't use self.assertRaisesRegexp() because it is only in
|
||||||
|
# Python 2.7+
|
||||||
try:
|
try:
|
||||||
_raise_exception_for_reading_json(credential_file, extra_help, error)
|
_raise_exception_for_reading_json(credential_file,
|
||||||
|
extra_help, error)
|
||||||
self.fail('An exception was expected!')
|
self.fail('An exception was expected!')
|
||||||
except ApplicationDefaultCredentialsError as ex:
|
except ApplicationDefaultCredentialsError as ex:
|
||||||
self.assertEqual('An error was encountered while reading '
|
self.assertEqual('An error was encountered while reading '
|
||||||
@@ -481,8 +495,7 @@ class GoogleCredentialsTests(unittest.TestCase):
|
|||||||
extra_help + ': ' + str(error),
|
extra_help + ': ' + str(error),
|
||||||
str(ex))
|
str(ex))
|
||||||
|
|
||||||
def test_get_application_default_from_environment_variable_service_account(
|
def test_get_adc_from_environment_variable_service_account(self):
|
||||||
self):
|
|
||||||
os.environ['SERVER_SOFTWARE'] = ''
|
os.environ['SERVER_SOFTWARE'] = ''
|
||||||
environment_variable_file = datafile(
|
environment_variable_file = datafile(
|
||||||
os.path.join('gcloud', 'application_default_credentials.json'))
|
os.path.join('gcloud', 'application_default_credentials.json'))
|
||||||
@@ -493,27 +506,26 @@ class GoogleCredentialsTests(unittest.TestCase):
|
|||||||
def test_env_name(self):
|
def test_env_name(self):
|
||||||
from oauth2client import client
|
from oauth2client import client
|
||||||
self.assertEqual(None, client.SETTINGS.env_name)
|
self.assertEqual(None, client.SETTINGS.env_name)
|
||||||
self.test_get_application_default_from_environment_variable_service_account()
|
self.test_get_adc_from_environment_variable_service_account()
|
||||||
self.assertEqual(DEFAULT_ENV_NAME, client.SETTINGS.env_name)
|
self.assertEqual(DEFAULT_ENV_NAME, client.SETTINGS.env_name)
|
||||||
|
|
||||||
def test_get_application_default_from_environment_variable_authorized_user(
|
def test_get_adc_from_environment_variable_authorized_user(self):
|
||||||
self):
|
|
||||||
os.environ['SERVER_SOFTWARE'] = ''
|
os.environ['SERVER_SOFTWARE'] = ''
|
||||||
environment_variable_file = datafile(
|
environment_variable_file = datafile(os.path.join(
|
||||||
os.path.join('gcloud',
|
'gcloud',
|
||||||
'application_default_credentials_authorized_user.json'))
|
'application_default_credentials_authorized_user.json'))
|
||||||
os.environ[GOOGLE_APPLICATION_CREDENTIALS] = environment_variable_file
|
os.environ[GOOGLE_APPLICATION_CREDENTIALS] = environment_variable_file
|
||||||
self.validate_google_credentials(
|
self.validate_google_credentials(
|
||||||
GoogleCredentials.get_application_default())
|
GoogleCredentials.get_application_default())
|
||||||
|
|
||||||
def test_get_application_default_from_environment_variable_malformed_file(
|
def test_get_adc_from_environment_variable_malformed_file(self):
|
||||||
self):
|
|
||||||
os.environ['SERVER_SOFTWARE'] = ''
|
os.environ['SERVER_SOFTWARE'] = ''
|
||||||
environment_variable_file = datafile(
|
environment_variable_file = datafile(
|
||||||
os.path.join('gcloud',
|
os.path.join('gcloud',
|
||||||
'application_default_credentials_malformed_3.json'))
|
'application_default_credentials_malformed_3.json'))
|
||||||
os.environ[GOOGLE_APPLICATION_CREDENTIALS] = environment_variable_file
|
os.environ[GOOGLE_APPLICATION_CREDENTIALS] = environment_variable_file
|
||||||
# we can't use self.assertRaisesRegexp() because it is only in Python 2.7+
|
# we can't use self.assertRaisesRegexp() because it is only in
|
||||||
|
# Python 2.7+
|
||||||
try:
|
try:
|
||||||
GoogleCredentials.get_application_default()
|
GoogleCredentials.get_application_default()
|
||||||
self.fail('An exception was expected!')
|
self.fail('An exception was expected!')
|
||||||
@@ -530,7 +542,8 @@ class GoogleCredentialsTests(unittest.TestCase):
|
|||||||
os.environ['SERVER_SOFTWARE'] = ''
|
os.environ['SERVER_SOFTWARE'] = ''
|
||||||
os.environ[GOOGLE_APPLICATION_CREDENTIALS] = ''
|
os.environ[GOOGLE_APPLICATION_CREDENTIALS] = ''
|
||||||
os.environ['APPDATA'] = ''
|
os.environ['APPDATA'] = ''
|
||||||
# we can't use self.assertRaisesRegexp() because it is only in Python 2.7+
|
# we can't use self.assertRaisesRegexp() because it is only in
|
||||||
|
# Python 2.7+
|
||||||
VALID_CONFIG_DIR = client._CLOUDSDK_CONFIG_DIRECTORY
|
VALID_CONFIG_DIR = client._CLOUDSDK_CONFIG_DIRECTORY
|
||||||
ORIGINAL_ISDIR = os.path.isdir
|
ORIGINAL_ISDIR = os.path.isdir
|
||||||
try:
|
try:
|
||||||
@@ -547,28 +560,31 @@ class GoogleCredentialsTests(unittest.TestCase):
|
|||||||
def test_from_stream_service_account(self):
|
def test_from_stream_service_account(self):
|
||||||
credentials_file = datafile(
|
credentials_file = datafile(
|
||||||
os.path.join('gcloud', 'application_default_credentials.json'))
|
os.path.join('gcloud', 'application_default_credentials.json'))
|
||||||
credentials = (
|
credentials = self.get_a_google_credentials_object().from_stream(
|
||||||
self.get_a_google_credentials_object().from_stream(credentials_file))
|
credentials_file)
|
||||||
self.validate_service_account_credentials(credentials)
|
self.validate_service_account_credentials(credentials)
|
||||||
|
|
||||||
def test_from_stream_authorized_user(self):
|
def test_from_stream_authorized_user(self):
|
||||||
credentials_file = datafile(
|
credentials_file = datafile(os.path.join(
|
||||||
os.path.join('gcloud',
|
'gcloud',
|
||||||
'application_default_credentials_authorized_user.json'))
|
'application_default_credentials_authorized_user.json'))
|
||||||
credentials = (
|
credentials = self.get_a_google_credentials_object().from_stream(
|
||||||
self.get_a_google_credentials_object().from_stream(credentials_file))
|
credentials_file)
|
||||||
self.validate_google_credentials(credentials)
|
self.validate_google_credentials(credentials)
|
||||||
|
|
||||||
def test_from_stream_malformed_file_1(self):
|
def test_from_stream_malformed_file_1(self):
|
||||||
credentials_file = datafile(
|
credentials_file = datafile(
|
||||||
os.path.join('gcloud',
|
os.path.join('gcloud',
|
||||||
'application_default_credentials_malformed_1.json'))
|
'application_default_credentials_malformed_1.json'))
|
||||||
# we can't use self.assertRaisesRegexp() because it is only in Python 2.7+
|
# we can't use self.assertRaisesRegexp() because it is only in
|
||||||
|
# Python 2.7+
|
||||||
try:
|
try:
|
||||||
self.get_a_google_credentials_object().from_stream(credentials_file)
|
self.get_a_google_credentials_object().from_stream(
|
||||||
|
credentials_file)
|
||||||
self.fail('An exception was expected!')
|
self.fail('An exception was expected!')
|
||||||
except ApplicationDefaultCredentialsError as error:
|
except ApplicationDefaultCredentialsError as error:
|
||||||
self.assertEqual("An error was encountered while reading json file: " +
|
self.assertEqual(
|
||||||
|
"An error was encountered while reading json file: " +
|
||||||
credentials_file +
|
credentials_file +
|
||||||
" (provided as parameter to the from_stream() method): "
|
" (provided as parameter to the from_stream() method): "
|
||||||
"'type' field should be defined (and have one of the '" +
|
"'type' field should be defined (and have one of the '" +
|
||||||
@@ -580,12 +596,15 @@ class GoogleCredentialsTests(unittest.TestCase):
|
|||||||
credentials_file = datafile(
|
credentials_file = datafile(
|
||||||
os.path.join('gcloud',
|
os.path.join('gcloud',
|
||||||
'application_default_credentials_malformed_2.json'))
|
'application_default_credentials_malformed_2.json'))
|
||||||
# we can't use self.assertRaisesRegexp() because it is only in Python 2.7+
|
# we can't use self.assertRaisesRegexp() because it is only in
|
||||||
|
# Python 2.7+
|
||||||
try:
|
try:
|
||||||
self.get_a_google_credentials_object().from_stream(credentials_file)
|
self.get_a_google_credentials_object().from_stream(
|
||||||
|
credentials_file)
|
||||||
self.fail('An exception was expected!')
|
self.fail('An exception was expected!')
|
||||||
except ApplicationDefaultCredentialsError as error:
|
except ApplicationDefaultCredentialsError as error:
|
||||||
self.assertEqual('An error was encountered while reading json file: ' +
|
self.assertEqual(
|
||||||
|
'An error was encountered while reading json file: ' +
|
||||||
credentials_file +
|
credentials_file +
|
||||||
' (provided as parameter to the from_stream() method): '
|
' (provided as parameter to the from_stream() method): '
|
||||||
'The following field(s) must be defined: '
|
'The following field(s) must be defined: '
|
||||||
@@ -598,7 +617,8 @@ class GoogleCredentialsTests(unittest.TestCase):
|
|||||||
'application_default_credentials_malformed_3.json'))
|
'application_default_credentials_malformed_3.json'))
|
||||||
self.assertRaises(
|
self.assertRaises(
|
||||||
ApplicationDefaultCredentialsError,
|
ApplicationDefaultCredentialsError,
|
||||||
self.get_a_google_credentials_object().from_stream, credentials_file)
|
self.get_a_google_credentials_object().from_stream,
|
||||||
|
credentials_file)
|
||||||
|
|
||||||
|
|
||||||
class DummyDeleteStorage(Storage):
|
class DummyDeleteStorage(Storage):
|
||||||
@@ -625,7 +645,8 @@ def _token_revoke_test_helper(testcase, status, revoke_raise,
|
|||||||
|
|
||||||
http = HttpMock(headers={'status': status})
|
http = HttpMock(headers={'status': status})
|
||||||
if revoke_raise:
|
if revoke_raise:
|
||||||
testcase.assertRaises(TokenRevokeError, testcase.credentials.revoke, http)
|
testcase.assertRaises(TokenRevokeError,
|
||||||
|
testcase.credentials.revoke, http)
|
||||||
else:
|
else:
|
||||||
testcase.credentials.revoke(http)
|
testcase.credentials.revoke(http)
|
||||||
|
|
||||||
@@ -667,7 +688,8 @@ class BasicCredentialsTests(unittest.TestCase):
|
|||||||
token_response = {'access_token': '1/3w', 'expires_in': 3600}
|
token_response = {'access_token': '1/3w', 'expires_in': 3600}
|
||||||
http = HttpMockSequence([
|
http = HttpMockSequence([
|
||||||
({'status': status_code}, b''),
|
({'status': status_code}, b''),
|
||||||
({'status': '200'}, json.dumps(token_response).encode('utf-8')),
|
({'status': '200'}, json.dumps(token_response).encode(
|
||||||
|
'utf-8')),
|
||||||
({'status': '200'}, 'echo_request_headers'),
|
({'status': '200'}, 'echo_request_headers'),
|
||||||
])
|
])
|
||||||
http = self.credentials.authorize(http)
|
http = self.credentials.authorize(http)
|
||||||
@@ -782,7 +804,8 @@ class BasicCredentialsTests(unittest.TestCase):
|
|||||||
self.assertRaises(
|
self.assertRaises(
|
||||||
NonAsciiHeaderError,
|
NonAsciiHeaderError,
|
||||||
http.request,
|
http.request,
|
||||||
u'http://example.com', method=u'GET', headers={u'foo': unicode_str})
|
u'http://example.com', method=u'GET',
|
||||||
|
headers={u'foo': unicode_str})
|
||||||
|
|
||||||
def test_no_unicode_in_request_params(self):
|
def test_no_unicode_in_request_params(self):
|
||||||
access_token = u'foo'
|
access_token = u'foo'
|
||||||
@@ -799,15 +822,18 @@ class BasicCredentialsTests(unittest.TestCase):
|
|||||||
|
|
||||||
http = HttpMock(headers={'status': '200'})
|
http = HttpMock(headers={'status': '200'})
|
||||||
http = credentials.authorize(http)
|
http = credentials.authorize(http)
|
||||||
http.request(u'http://example.com', method=u'GET', headers={u'foo': u'bar'})
|
http.request(u'http://example.com', method=u'GET',
|
||||||
|
headers={u'foo': u'bar'})
|
||||||
for k, v in six.iteritems(http.headers):
|
for k, v in six.iteritems(http.headers):
|
||||||
self.assertTrue(isinstance(k, six.binary_type))
|
self.assertTrue(isinstance(k, six.binary_type))
|
||||||
self.assertTrue(isinstance(v, six.binary_type))
|
self.assertTrue(isinstance(v, six.binary_type))
|
||||||
|
|
||||||
# Test again with unicode strings that can't simply be converted to ASCII.
|
# Test again with unicode strings that can't simply be converted
|
||||||
|
# to ASCII.
|
||||||
try:
|
try:
|
||||||
http.request(
|
http.request(
|
||||||
u'http://example.com', method=u'GET', headers={u'foo': u'\N{COMET}'})
|
u'http://example.com', method=u'GET',
|
||||||
|
headers={u'foo': u'\N{COMET}'})
|
||||||
self.fail('Expected exception to be raised.')
|
self.fail('Expected exception to be raised.')
|
||||||
except NonAsciiHeaderError:
|
except NonAsciiHeaderError:
|
||||||
pass
|
pass
|
||||||
@@ -819,10 +845,13 @@ class BasicCredentialsTests(unittest.TestCase):
|
|||||||
def test_get_access_token(self):
|
def test_get_access_token(self):
|
||||||
S = 2 # number of seconds in which the token expires
|
S = 2 # number of seconds in which the token expires
|
||||||
token_response_first = {'access_token': 'first_token', 'expires_in': S}
|
token_response_first = {'access_token': 'first_token', 'expires_in': S}
|
||||||
token_response_second = {'access_token': 'second_token', 'expires_in': S}
|
token_response_second = {'access_token': 'second_token',
|
||||||
|
'expires_in': S}
|
||||||
http = HttpMockSequence([
|
http = HttpMockSequence([
|
||||||
({'status': '200'}, json.dumps(token_response_first).encode('utf-8')),
|
({'status': '200'}, json.dumps(token_response_first).encode(
|
||||||
({'status': '200'}, json.dumps(token_response_second).encode('utf-8')),
|
'utf-8')),
|
||||||
|
({'status': '200'}, json.dumps(token_response_second).encode(
|
||||||
|
'utf-8')),
|
||||||
])
|
])
|
||||||
|
|
||||||
token = self.credentials.get_access_token(http=http)
|
token = self.credentials.get_access_token(http=http)
|
||||||
@@ -844,7 +873,8 @@ class BasicCredentialsTests(unittest.TestCase):
|
|||||||
self.assertEqual('second_token', token.access_token)
|
self.assertEqual('second_token', token.access_token)
|
||||||
self.assertEqual(S - 1, token.expires_in)
|
self.assertEqual(S - 1, token.expires_in)
|
||||||
self.assertFalse(self.credentials.access_token_expired)
|
self.assertFalse(self.credentials.access_token_expired)
|
||||||
self.assertEqual(token_response_second, self.credentials.token_response)
|
self.assertEqual(token_response_second,
|
||||||
|
self.credentials.token_response)
|
||||||
|
|
||||||
def test_has_scopes(self):
|
def test_has_scopes(self):
|
||||||
self.assertTrue(self.credentials.has_scopes('foo'))
|
self.assertTrue(self.credentials.has_scopes('foo'))
|
||||||
@@ -866,8 +896,10 @@ class BasicCredentialsTests(unittest.TestCase):
|
|||||||
info_response_first = {'scope': 'foo bar'}
|
info_response_first = {'scope': 'foo bar'}
|
||||||
info_response_second = {'error_description': 'abcdef'}
|
info_response_second = {'error_description': 'abcdef'}
|
||||||
http = HttpMockSequence([
|
http = HttpMockSequence([
|
||||||
({'status': '200'}, json.dumps(info_response_first).encode('utf-8')),
|
({'status': '200'}, json.dumps(info_response_first).encode(
|
||||||
({'status': '400'}, json.dumps(info_response_second).encode('utf-8')),
|
'utf-8')),
|
||||||
|
({'status': '400'}, json.dumps(info_response_second).encode(
|
||||||
|
'utf-8')),
|
||||||
({'status': '500'}, b''),
|
({'status': '500'}, b''),
|
||||||
])
|
])
|
||||||
|
|
||||||
@@ -945,8 +977,8 @@ class TestAssertionCredentials(unittest.TestCase):
|
|||||||
|
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
user_agent = 'fun/2.0'
|
user_agent = 'fun/2.0'
|
||||||
self.credentials = self.AssertionCredentialsTestImpl(self.assertion_type,
|
self.credentials = self.AssertionCredentialsTestImpl(
|
||||||
user_agent=user_agent)
|
self.assertion_type, user_agent=user_agent)
|
||||||
|
|
||||||
def test_assertion_body(self):
|
def test_assertion_body(self):
|
||||||
body = urllib.parse.parse_qs(
|
body = urllib.parse.parse_qs(
|
||||||
@@ -1005,7 +1037,6 @@ class ExtractIdTokenTest(unittest.TestCase):
|
|||||||
body_json = json.dumps(body).encode('ascii')
|
body_json = json.dumps(body).encode('ascii')
|
||||||
payload = base64.urlsafe_b64encode(body_json).strip(b'=')
|
payload = base64.urlsafe_b64encode(body_json).strip(b'=')
|
||||||
jwt = b'stuff.' + payload
|
jwt = b'stuff.' + payload
|
||||||
|
|
||||||
self.assertRaises(VerifyJwtTokenError, _extract_id_token, jwt)
|
self.assertRaises(VerifyJwtTokenError, _extract_id_token, jwt)
|
||||||
|
|
||||||
|
|
||||||
@@ -1063,7 +1094,8 @@ class OAuth2WebServerFlowTest(unittest.TestCase):
|
|||||||
])
|
])
|
||||||
|
|
||||||
try:
|
try:
|
||||||
credentials = self.flow.step2_exchange('some random code', http=http)
|
credentials = self.flow.step2_exchange('some random code',
|
||||||
|
http=http)
|
||||||
self.fail('should raise exception if exchange doesn\'t get 200')
|
self.fail('should raise exception if exchange doesn\'t get 200')
|
||||||
except FlowExchangeError:
|
except FlowExchangeError:
|
||||||
pass
|
pass
|
||||||
@@ -1074,7 +1106,8 @@ class OAuth2WebServerFlowTest(unittest.TestCase):
|
|||||||
])
|
])
|
||||||
|
|
||||||
try:
|
try:
|
||||||
credentials = self.flow.step2_exchange('some random code', http=http)
|
credentials = self.flow.step2_exchange('some random code',
|
||||||
|
http=http)
|
||||||
self.fail('should raise exception if exchange doesn\'t get 200')
|
self.fail('should raise exception if exchange doesn\'t get 200')
|
||||||
except FlowExchangeError as e:
|
except FlowExchangeError as e:
|
||||||
self.assertEqual('invalid_request', str(e))
|
self.assertEqual('invalid_request', str(e))
|
||||||
@@ -1084,27 +1117,28 @@ class OAuth2WebServerFlowTest(unittest.TestCase):
|
|||||||
# in place of regular string.
|
# in place of regular string.
|
||||||
# This test makes sure no strange object-to-string coversion
|
# This test makes sure no strange object-to-string coversion
|
||||||
# exceptions are being raised instead of FlowExchangeError.
|
# exceptions are being raised instead of FlowExchangeError.
|
||||||
http = HttpMockSequence([
|
payload = (b'{'
|
||||||
({'status': '400'},
|
b' "error": {'
|
||||||
b""" {"error": {
|
b' "message": "Error validating verification code.",'
|
||||||
"type": "OAuthException",
|
b' "type": "OAuthException"'
|
||||||
"message": "Error validating verification code."} }"""),
|
b' }'
|
||||||
])
|
b'}')
|
||||||
|
http = HttpMockSequence([({'status': '400'}, payload)])
|
||||||
|
|
||||||
try:
|
try:
|
||||||
credentials = self.flow.step2_exchange('some random code', http=http)
|
credentials = self.flow.step2_exchange('some random code',
|
||||||
|
http=http)
|
||||||
self.fail('should raise exception if exchange doesn\'t get 200')
|
self.fail('should raise exception if exchange doesn\'t get 200')
|
||||||
except FlowExchangeError as e:
|
except FlowExchangeError as e:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def test_exchange_success(self):
|
def test_exchange_success(self):
|
||||||
http = HttpMockSequence([
|
payload = (b'{'
|
||||||
({'status': '200'},
|
b' "access_token":"SlAV32hkKG",'
|
||||||
b"""{ "access_token":"SlAV32hkKG",
|
b' "expires_in":3600,'
|
||||||
"expires_in":3600,
|
b' "refresh_token":"8xLOxBtZp8"'
|
||||||
"refresh_token":"8xLOxBtZp8" }"""),
|
b'}')
|
||||||
])
|
http = HttpMockSequence([({'status': '200'}, payload)])
|
||||||
|
|
||||||
credentials = self.flow.step2_exchange('some random code', http=http)
|
credentials = self.flow.step2_exchange('some random code', http=http)
|
||||||
self.assertEqual('SlAV32hkKG', credentials.access_token)
|
self.assertEqual('SlAV32hkKG', credentials.access_token)
|
||||||
self.assertNotEqual(None, credentials.token_expiry)
|
self.assertNotEqual(None, credentials.token_expiry)
|
||||||
@@ -1130,7 +1164,7 @@ class OAuth2WebServerFlowTest(unittest.TestCase):
|
|||||||
b' "expires_in":3600,'
|
b' "expires_in":3600,'
|
||||||
b' "refresh_token":"8xLOxBtZp8"'
|
b' "refresh_token":"8xLOxBtZp8"'
|
||||||
b'}')
|
b'}')
|
||||||
http = HttpMockSequence([({'status': '200'}, payload), ])
|
http = HttpMockSequence([({'status': '200'}, payload)])
|
||||||
|
|
||||||
credentials = self.flow.step2_exchange(not_a_dict, http=http)
|
credentials = self.flow.step2_exchange(not_a_dict, http=http)
|
||||||
self.assertEqual('SlAV32hkKG', credentials.access_token)
|
self.assertEqual('SlAV32hkKG', credentials.access_token)
|
||||||
@@ -1138,7 +1172,8 @@ class OAuth2WebServerFlowTest(unittest.TestCase):
|
|||||||
self.assertEqual('8xLOxBtZp8', credentials.refresh_token)
|
self.assertEqual('8xLOxBtZp8', credentials.refresh_token)
|
||||||
self.assertEqual('dummy_revoke_uri', credentials.revoke_uri)
|
self.assertEqual('dummy_revoke_uri', credentials.revoke_uri)
|
||||||
self.assertEqual(set(['foo']), credentials.scopes)
|
self.assertEqual(set(['foo']), credentials.scopes)
|
||||||
request_code = urllib.parse.parse_qs(http.requests[0]['body'])['code'][0]
|
request_code = urllib.parse.parse_qs(
|
||||||
|
http.requests[0]['body'])['code'][0]
|
||||||
self.assertEqual(code, request_code)
|
self.assertEqual(code, request_code)
|
||||||
|
|
||||||
def test_exchange_using_authorization_header(self):
|
def test_exchange_using_authorization_header(self):
|
||||||
@@ -1184,10 +1219,11 @@ class OAuth2WebServerFlowTest(unittest.TestCase):
|
|||||||
self.assertNotEqual(None, credentials.token_expiry)
|
self.assertNotEqual(None, credentials.token_expiry)
|
||||||
|
|
||||||
def test_exchange_no_expires_in(self):
|
def test_exchange_no_expires_in(self):
|
||||||
http = HttpMockSequence([
|
payload = (b'{'
|
||||||
({'status': '200'}, b"""{ "access_token":"SlAV32hkKG",
|
b' "access_token":"SlAV32hkKG",'
|
||||||
"refresh_token":"8xLOxBtZp8" }"""),
|
b' "refresh_token":"8xLOxBtZp8"'
|
||||||
])
|
b'}')
|
||||||
|
http = HttpMockSequence([({'status': '200'}, payload)])
|
||||||
|
|
||||||
credentials = self.flow.step2_exchange('some random code', http=http)
|
credentials = self.flow.step2_exchange('some random code', http=http)
|
||||||
self.assertEqual(None, credentials.token_expiry)
|
self.assertEqual(None, credentials.token_expiry)
|
||||||
@@ -1203,10 +1239,11 @@ class OAuth2WebServerFlowTest(unittest.TestCase):
|
|||||||
self.assertEqual(None, credentials.token_expiry)
|
self.assertEqual(None, credentials.token_expiry)
|
||||||
|
|
||||||
def test_exchange_fails_if_no_code(self):
|
def test_exchange_fails_if_no_code(self):
|
||||||
http = HttpMockSequence([
|
payload = (b'{'
|
||||||
({'status': '200'}, b"""{ "access_token":"SlAV32hkKG",
|
b' "access_token":"SlAV32hkKG",'
|
||||||
"refresh_token":"8xLOxBtZp8" }"""),
|
b' "refresh_token":"8xLOxBtZp8"'
|
||||||
])
|
b'}')
|
||||||
|
http = HttpMockSequence([({'status': '200'}, payload)])
|
||||||
|
|
||||||
code = {'error': 'thou shall not pass'}
|
code = {'error': 'thou shall not pass'}
|
||||||
try:
|
try:
|
||||||
@@ -1216,11 +1253,12 @@ class OAuth2WebServerFlowTest(unittest.TestCase):
|
|||||||
self.assertTrue('shall not pass' in str(e))
|
self.assertTrue('shall not pass' in str(e))
|
||||||
|
|
||||||
def test_exchange_id_token_fail(self):
|
def test_exchange_id_token_fail(self):
|
||||||
http = HttpMockSequence([
|
payload = (b'{'
|
||||||
({'status': '200'}, b"""{ "access_token":"SlAV32hkKG",
|
b' "access_token":"SlAV32hkKG",'
|
||||||
"refresh_token":"8xLOxBtZp8",
|
b' "refresh_token":"8xLOxBtZp8",'
|
||||||
"id_token": "stuff.payload"}"""),
|
b' "id_token": "stuff.payload"'
|
||||||
])
|
b'}')
|
||||||
|
http = HttpMockSequence([({'status': '200'}, payload)])
|
||||||
|
|
||||||
self.assertRaises(VerifyJwtTokenError, self.flow.step2_exchange,
|
self.assertRaises(VerifyJwtTokenError, self.flow.step2_exchange,
|
||||||
'some random code', http=http)
|
'some random code', http=http)
|
||||||
@@ -1232,12 +1270,12 @@ class OAuth2WebServerFlowTest(unittest.TestCase):
|
|||||||
jwt = (base64.urlsafe_b64encode(b'stuff') + b'.' + payload + b'.' +
|
jwt = (base64.urlsafe_b64encode(b'stuff') + b'.' + payload + b'.' +
|
||||||
base64.urlsafe_b64encode(b'signature'))
|
base64.urlsafe_b64encode(b'signature'))
|
||||||
|
|
||||||
http = HttpMockSequence([
|
payload = (b'{'
|
||||||
({'status': '200'}, ("""{ "access_token":"SlAV32hkKG",
|
b' "access_token":"SlAV32hkKG",'
|
||||||
"refresh_token":"8xLOxBtZp8",
|
b' "refresh_token":"8xLOxBtZp8",'
|
||||||
"id_token": "%s"}""" % jwt).encode('utf-8')),
|
b' "id_token": "' + jwt + '"'
|
||||||
])
|
b'}')
|
||||||
|
http = HttpMockSequence([({'status': '200'}, payload)])
|
||||||
credentials = self.flow.step2_exchange('some random code', http=http)
|
credentials = self.flow.step2_exchange('some random code', http=http)
|
||||||
self.assertEqual(credentials.id_token, body)
|
self.assertEqual(credentials.id_token, body)
|
||||||
|
|
||||||
@@ -1254,6 +1292,7 @@ class FlowFromCachedClientsecrets(unittest.TestCase):
|
|||||||
|
|
||||||
|
|
||||||
class CredentialsFromCodeTests(unittest.TestCase):
|
class CredentialsFromCodeTests(unittest.TestCase):
|
||||||
|
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
self.client_id = 'client_id_abc'
|
self.client_id = 'client_id_abc'
|
||||||
self.client_secret = 'secret_use_code'
|
self.client_secret = 'secret_use_code'
|
||||||
@@ -1268,7 +1307,8 @@ class CredentialsFromCodeTests(unittest.TestCase):
|
|||||||
({'status': '200'}, payload.encode('utf-8')),
|
({'status': '200'}, payload.encode('utf-8')),
|
||||||
])
|
])
|
||||||
credentials = credentials_from_code(self.client_id, self.client_secret,
|
credentials = credentials_from_code(self.client_id, self.client_secret,
|
||||||
self.scope, self.code, redirect_uri=self.redirect_uri,
|
self.scope, self.code,
|
||||||
|
redirect_uri=self.redirect_uri,
|
||||||
http=http)
|
http=http)
|
||||||
self.assertEqual(credentials.access_token, token)
|
self.assertEqual(credentials.access_token, token)
|
||||||
self.assertNotEqual(None, credentials.token_expiry)
|
self.assertNotEqual(None, credentials.token_expiry)
|
||||||
@@ -1280,19 +1320,21 @@ class CredentialsFromCodeTests(unittest.TestCase):
|
|||||||
])
|
])
|
||||||
|
|
||||||
try:
|
try:
|
||||||
credentials = credentials_from_code(self.client_id, self.client_secret,
|
credentials = credentials_from_code(self.client_id,
|
||||||
self.scope, self.code, redirect_uri=self.redirect_uri,
|
self.client_secret,
|
||||||
|
self.scope, self.code,
|
||||||
|
redirect_uri=self.redirect_uri,
|
||||||
http=http)
|
http=http)
|
||||||
self.fail('should raise exception if exchange doesn\'t get 200')
|
self.fail('should raise exception if exchange doesn\'t get 200')
|
||||||
except FlowExchangeError:
|
except FlowExchangeError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def test_exchange_code_and_file_for_token(self):
|
def test_exchange_code_and_file_for_token(self):
|
||||||
http = HttpMockSequence([
|
payload = (b'{'
|
||||||
({'status': '200'},
|
b' "access_token":"asdfghjkl",'
|
||||||
b"""{ "access_token":"asdfghjkl",
|
b' "expires_in":3600'
|
||||||
"expires_in":3600 }"""),
|
b'}')
|
||||||
])
|
http = HttpMockSequence([({'status': '200'}, payload)])
|
||||||
credentials = credentials_from_clientsecrets_and_code(
|
credentials = credentials_from_clientsecrets_and_code(
|
||||||
datafile('client_secrets.json'), self.scope,
|
datafile('client_secrets.json'), self.scope,
|
||||||
self.code, http=http)
|
self.code, http=http)
|
||||||
|
|||||||
@@ -38,13 +38,15 @@ def datafile(filename):
|
|||||||
|
|
||||||
|
|
||||||
class ServiceAccountCredentialsTests(unittest.TestCase):
|
class ServiceAccountCredentialsTests(unittest.TestCase):
|
||||||
|
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
self.service_account_id = '123'
|
self.service_account_id = '123'
|
||||||
self.service_account_email = 'dummy@google.com'
|
self.service_account_email = 'dummy@google.com'
|
||||||
self.private_key_id = 'ABCDEF'
|
self.private_key_id = 'ABCDEF'
|
||||||
self.private_key = datafile('pem_from_pkcs12.pem')
|
self.private_key = datafile('pem_from_pkcs12.pem')
|
||||||
self.scopes = ['dummy_scope']
|
self.scopes = ['dummy_scope']
|
||||||
self.credentials = _ServiceAccountCredentials(self.service_account_id,
|
self.credentials = _ServiceAccountCredentials(
|
||||||
|
self.service_account_id,
|
||||||
self.service_account_email,
|
self.service_account_email,
|
||||||
self.private_key_id,
|
self.private_key_id,
|
||||||
self.private_key,
|
self.private_key,
|
||||||
@@ -79,7 +81,8 @@ class ServiceAccountCredentialsTests(unittest.TestCase):
|
|||||||
self.assertTrue(self.credentials.create_scoped_required())
|
self.assertTrue(self.credentials.create_scoped_required())
|
||||||
|
|
||||||
def test_create_scoped_required_with_scopes(self):
|
def test_create_scoped_required_with_scopes(self):
|
||||||
self.credentials = _ServiceAccountCredentials(self.service_account_id,
|
self.credentials = _ServiceAccountCredentials(
|
||||||
|
self.service_account_id,
|
||||||
self.service_account_email,
|
self.service_account_email,
|
||||||
self.private_key_id,
|
self.private_key_id,
|
||||||
self.private_key,
|
self.private_key,
|
||||||
@@ -89,16 +92,20 @@ class ServiceAccountCredentialsTests(unittest.TestCase):
|
|||||||
def test_create_scoped(self):
|
def test_create_scoped(self):
|
||||||
new_credentials = self.credentials.create_scoped(self.scopes)
|
new_credentials = self.credentials.create_scoped(self.scopes)
|
||||||
self.assertNotEqual(self.credentials, new_credentials)
|
self.assertNotEqual(self.credentials, new_credentials)
|
||||||
self.assertTrue(isinstance(new_credentials, _ServiceAccountCredentials))
|
self.assertTrue(isinstance(new_credentials,
|
||||||
|
_ServiceAccountCredentials))
|
||||||
self.assertEqual('dummy_scope', new_credentials._scopes)
|
self.assertEqual('dummy_scope', new_credentials._scopes)
|
||||||
|
|
||||||
def test_access_token(self):
|
def test_access_token(self):
|
||||||
S = 2 # number of seconds in which the token expires
|
S = 2 # number of seconds in which the token expires
|
||||||
token_response_first = {'access_token': 'first_token', 'expires_in': S}
|
token_response_first = {'access_token': 'first_token', 'expires_in': S}
|
||||||
token_response_second = {'access_token': 'second_token', 'expires_in': S}
|
token_response_second = {'access_token': 'second_token',
|
||||||
|
'expires_in': S}
|
||||||
http = HttpMockSequence([
|
http = HttpMockSequence([
|
||||||
({'status': '200'}, json.dumps(token_response_first).encode('utf-8')),
|
({'status': '200'},
|
||||||
({'status': '200'}, json.dumps(token_response_second).encode('utf-8')),
|
json.dumps(token_response_first).encode('utf-8')),
|
||||||
|
({'status': '200'},
|
||||||
|
json.dumps(token_response_second).encode('utf-8')),
|
||||||
])
|
])
|
||||||
|
|
||||||
token = self.credentials.get_access_token(http=http)
|
token = self.credentials.get_access_token(http=http)
|
||||||
@@ -120,4 +127,5 @@ class ServiceAccountCredentialsTests(unittest.TestCase):
|
|||||||
self.assertEqual('second_token', token.access_token)
|
self.assertEqual('second_token', token.access_token)
|
||||||
self.assertEqual(S - 1, token.expires_in)
|
self.assertEqual(S - 1, token.expires_in)
|
||||||
self.assertFalse(self.credentials.access_token_expired)
|
self.assertFalse(self.credentials.access_token_expired)
|
||||||
self.assertEqual(token_response_second, self.credentials.token_response)
|
self.assertEqual(token_response_second,
|
||||||
|
self.credentials.token_response)
|
||||||
|
|||||||
@@ -13,7 +13,8 @@ class TestClientRedirectServer(unittest.TestCase):
|
|||||||
# create a ClientRedirectServer and run it in a thread to listen
|
# create a ClientRedirectServer and run it in a thread to listen
|
||||||
# for a mock GET request with the access token
|
# for a mock GET request with the access token
|
||||||
# the server should return a 200 message and store the token
|
# the server should return a 200 message and store the token
|
||||||
httpd = tools.ClientRedirectServer(('localhost', 0), tools.ClientRedirectHandler)
|
httpd = tools.ClientRedirectServer(('localhost', 0),
|
||||||
|
tools.ClientRedirectHandler)
|
||||||
code = 'foo'
|
code = 'foo'
|
||||||
url = 'http://localhost:%i?code=%s' % (httpd.server_address[1], code)
|
url = 'http://localhost:%i?code=%s' % (httpd.server_address[1], code)
|
||||||
t = threading.Thread(target=httpd.handle_request)
|
t = threading.Thread(target=httpd.handle_request)
|
||||||
|
|||||||
@@ -14,9 +14,9 @@ class ScopeToStringTests(unittest.TestCase):
|
|||||||
('', ''),
|
('', ''),
|
||||||
('', ()),
|
('', ()),
|
||||||
('', []),
|
('', []),
|
||||||
('', ('', )),
|
('', ('',)),
|
||||||
('', ['', ]),
|
('', ['', ]),
|
||||||
('a', ('a', )),
|
('a', ('a',)),
|
||||||
('b', ['b', ]),
|
('b', ['b', ]),
|
||||||
('a b', ['a', 'b']),
|
('a b', ['a', 'b']),
|
||||||
('a b', ('a', 'b')),
|
('a b', ('a', 'b')),
|
||||||
@@ -44,7 +44,8 @@ class StringToScopeTests(unittest.TestCase):
|
|||||||
class KeyConversionTests(unittest.TestCase):
|
class KeyConversionTests(unittest.TestCase):
|
||||||
|
|
||||||
def test_key_conversions(self):
|
def test_key_conversions(self):
|
||||||
d = {'somekey': 'some value', 'another': 'something else', 'onemore': 'foo'}
|
d = {'somekey': 'some value', 'another': 'something else',
|
||||||
|
'onemore': 'foo'}
|
||||||
tuple_key = util.dict_to_tuple_key(d)
|
tuple_key = util.dict_to_tuple_key(d)
|
||||||
|
|
||||||
# the resulting key should be naturally sorted
|
# the resulting key should be naturally sorted
|
||||||
|
|||||||
@@ -107,5 +107,6 @@ class XsrfUtilTests(unittest.TestCase):
|
|||||||
TEST_USER_ID_1,
|
TEST_USER_ID_1,
|
||||||
action_id=TEST_ACTION_ID_1))
|
action_id=TEST_ACTION_ID_1))
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
Reference in New Issue
Block a user