Update imports to only Packages or Modules

Also cleaned up some nested attribute access.
This commit is contained in:
Pat Ferate
2016-07-21 14:42:27 -07:00
parent 25165adbc1
commit f31e1e014f
43 changed files with 858 additions and 950 deletions

View File

@@ -15,8 +15,7 @@
from OpenSSL import crypto from OpenSSL import crypto
from oauth2client._helpers import _parse_pem_key from oauth2client import _helpers
from oauth2client._helpers import _to_bytes
class OpenSSLVerifier(object): class OpenSSLVerifier(object):
@@ -43,8 +42,8 @@ class OpenSSLVerifier(object):
True if message was signed by the private key associated with the True if message was signed by the private key associated with the
public key that this object was constructed with. public key that this object was constructed with.
""" """
message = _to_bytes(message, encoding='utf-8') message = _helpers._to_bytes(message, encoding='utf-8')
signature = _to_bytes(signature, encoding='utf-8') signature = _helpers._to_bytes(signature, encoding='utf-8')
try: try:
crypto.verify(self._pubkey, signature, message, 'sha256') crypto.verify(self._pubkey, signature, message, 'sha256')
return True return True
@@ -66,7 +65,7 @@ class OpenSSLVerifier(object):
Raises: Raises:
OpenSSL.crypto.Error: if the key_pem can't be parsed. OpenSSL.crypto.Error: if the key_pem can't be parsed.
""" """
key_pem = _to_bytes(key_pem) key_pem = _helpers._to_bytes(key_pem)
if is_x509_cert: if is_x509_cert:
pubkey = crypto.load_certificate(crypto.FILETYPE_PEM, key_pem) pubkey = crypto.load_certificate(crypto.FILETYPE_PEM, key_pem)
else: else:
@@ -94,7 +93,7 @@ class OpenSSLSigner(object):
Returns: Returns:
string, The signature of the message for the given key. string, The signature of the message for the given key.
""" """
message = _to_bytes(message, encoding='utf-8') message = _helpers._to_bytes(message, encoding='utf-8')
return crypto.sign(self._key, message, 'sha256') return crypto.sign(self._key, message, 'sha256')
@staticmethod @staticmethod
@@ -111,12 +110,12 @@ class OpenSSLSigner(object):
Raises: Raises:
OpenSSL.crypto.Error if the key can't be parsed. OpenSSL.crypto.Error if the key can't be parsed.
""" """
key = _to_bytes(key) key = _helpers._to_bytes(key)
parsed_pem_key = _parse_pem_key(key) parsed_pem_key = _helpers._parse_pem_key(key)
if parsed_pem_key: if parsed_pem_key:
pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, parsed_pem_key) pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, parsed_pem_key)
else: else:
password = _to_bytes(password, encoding='utf-8') password = _helpers._to_bytes(password, encoding='utf-8')
pkey = crypto.load_pkcs12(key, password).get_privatekey() pkey = crypto.load_pkcs12(key, password).get_privatekey()
return OpenSSLSigner(pkey) return OpenSSLSigner(pkey)
@@ -131,7 +130,7 @@ def pkcs12_key_as_pem(private_key_bytes, private_key_password):
Returns: Returns:
String. PEM contents of ``private_key_bytes``. String. PEM contents of ``private_key_bytes``.
""" """
private_key_password = _to_bytes(private_key_password) private_key_password = _helpers._to_bytes(private_key_password)
pkcs12 = crypto.load_pkcs12(private_key_bytes, private_key_password) pkcs12 = crypto.load_pkcs12(private_key_bytes, private_key_password)
return crypto.dump_privatekey(crypto.FILETYPE_PEM, return crypto.dump_privatekey(crypto.FILETYPE_PEM,
pkcs12.get_privatekey()) pkcs12.get_privatekey())

View File

@@ -26,8 +26,7 @@ from pyasn1_modules.rfc5208 import PrivateKeyInfo
import rsa import rsa
import six import six
from oauth2client._helpers import _from_bytes from oauth2client import _helpers
from oauth2client._helpers import _to_bytes
_PKCS12_ERROR = r"""\ _PKCS12_ERROR = r"""\
@@ -86,7 +85,7 @@ class RsaVerifier(object):
True if message was signed by the private key associated with the True if message was signed by the private key associated with the
public key that this object was constructed with. public key that this object was constructed with.
""" """
message = _to_bytes(message, encoding='utf-8') message = _helpers._to_bytes(message, encoding='utf-8')
try: try:
return rsa.pkcs1.verify(message, signature, self._pubkey) return rsa.pkcs1.verify(message, signature, self._pubkey)
except (ValueError, rsa.pkcs1.VerificationError): except (ValueError, rsa.pkcs1.VerificationError):
@@ -111,7 +110,7 @@ class RsaVerifier(object):
"-----BEGIN CERTIFICATE-----" error, otherwise fails "-----BEGIN CERTIFICATE-----" error, otherwise fails
to find "-----BEGIN RSA PUBLIC KEY-----". to find "-----BEGIN RSA PUBLIC KEY-----".
""" """
key_pem = _to_bytes(key_pem) key_pem = _helpers._to_bytes(key_pem)
if is_x509_cert: if is_x509_cert:
der = rsa.pem.load_pem(key_pem, 'CERTIFICATE') der = rsa.pem.load_pem(key_pem, 'CERTIFICATE')
asn1_cert, remaining = decoder.decode(der, asn1Spec=Certificate()) asn1_cert, remaining = decoder.decode(der, asn1Spec=Certificate())
@@ -145,7 +144,7 @@ class RsaSigner(object):
Returns: Returns:
string, The signature of the message for the given key. string, The signature of the message for the given key.
""" """
message = _to_bytes(message, encoding='utf-8') message = _helpers._to_bytes(message, encoding='utf-8')
return rsa.pkcs1.sign(message, self._key, 'SHA-256') return rsa.pkcs1.sign(message, self._key, 'SHA-256')
@classmethod @classmethod
@@ -164,7 +163,7 @@ class RsaSigner(object):
ValueError if the key cannot be parsed as PKCS#1 or PKCS#8 in ValueError if the key cannot be parsed as PKCS#1 or PKCS#8 in
PEM format. PEM format.
""" """
key = _from_bytes(key) # pem expects str in Py3 key = _helpers._from_bytes(key) # pem expects str in Py3
marker_id, key_bytes = pem.readPemBlocksFromFile( marker_id, key_bytes = pem.readPemBlocksFromFile(
six.StringIO(key), _PKCS1_MARKER, _PKCS8_MARKER) six.StringIO(key), _PKCS1_MARKER, _PKCS8_MARKER)

View File

@@ -18,9 +18,7 @@ from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5 from Crypto.Signature import PKCS1_v1_5
from Crypto.Util.asn1 import DerSequence from Crypto.Util.asn1 import DerSequence
from oauth2client._helpers import _parse_pem_key from oauth2client import _helpers
from oauth2client._helpers import _to_bytes
from oauth2client._helpers import _urlsafe_b64decode
class PyCryptoVerifier(object): class PyCryptoVerifier(object):
@@ -47,7 +45,7 @@ class PyCryptoVerifier(object):
True if message was signed by the private key associated with the True if message was signed by the private key associated with the
public key that this object was constructed with. public key that this object was constructed with.
""" """
message = _to_bytes(message, encoding='utf-8') message = _helpers._to_bytes(message, encoding='utf-8')
return PKCS1_v1_5.new(self._pubkey).verify( return PKCS1_v1_5.new(self._pubkey).verify(
SHA256.new(message), signature) SHA256.new(message), signature)
@@ -64,9 +62,9 @@ class PyCryptoVerifier(object):
Verifier instance. Verifier instance.
""" """
if is_x509_cert: if is_x509_cert:
key_pem = _to_bytes(key_pem) key_pem = _helpers._to_bytes(key_pem)
pemLines = key_pem.replace(b' ', b'').split() pemLines = key_pem.replace(b' ', b'').split()
certDer = _urlsafe_b64decode(b''.join(pemLines[1:-1])) certDer = _helpers._urlsafe_b64decode(b''.join(pemLines[1:-1]))
certSeq = DerSequence() certSeq = DerSequence()
certSeq.decode(certDer) certSeq.decode(certDer)
tbsSeq = DerSequence() tbsSeq = DerSequence()
@@ -97,7 +95,7 @@ class PyCryptoSigner(object):
Returns: Returns:
string, The signature of the message for the given key. string, The signature of the message for the given key.
""" """
message = _to_bytes(message, encoding='utf-8') message = _helpers._to_bytes(message, encoding='utf-8')
return PKCS1_v1_5.new(self._key).sign(SHA256.new(message)) return PKCS1_v1_5.new(self._key).sign(SHA256.new(message))
@staticmethod @staticmethod
@@ -115,7 +113,7 @@ class PyCryptoSigner(object):
Raises: Raises:
NotImplementedError if the key isn't in PEM format. NotImplementedError if the key isn't in PEM format.
""" """
parsed_pem_key = _parse_pem_key(_to_bytes(key)) parsed_pem_key = _helpers._parse_pem_key(_helpers._to_bytes(key))
if parsed_pem_key: if parsed_pem_key:
pkey = RSA.importKey(parsed_pem_key) pkey = RSA.importKey(parsed_pem_key)
else: else:

View File

@@ -32,16 +32,11 @@ import six
from six.moves import http_client from six.moves import http_client
from six.moves import urllib from six.moves import urllib
import oauth2client
from oauth2client import _helpers
from oauth2client import clientsecrets from oauth2client import clientsecrets
from oauth2client import GOOGLE_AUTH_URI
from oauth2client import GOOGLE_DEVICE_URI
from oauth2client import GOOGLE_REVOKE_URI
from oauth2client import GOOGLE_TOKEN_INFO_URI
from oauth2client import GOOGLE_TOKEN_URI
from oauth2client import transport from oauth2client import transport
from oauth2client import util from oauth2client import util
from oauth2client._helpers import _from_bytes
from oauth2client._helpers import _urlsafe_b64decode
__author__ = 'jcgregorio@google.com (Joe Gregorio)' __author__ = 'jcgregorio@google.com (Joe Gregorio)'
@@ -294,7 +289,7 @@ class Credentials(object):
An instance of the subclass of Credentials that was serialized with An instance of the subclass of Credentials that was serialized with
to_json(). to_json().
""" """
json_data_as_unicode = _from_bytes(json_data) json_data_as_unicode = _helpers._from_bytes(json_data)
data = json.loads(json_data_as_unicode) data = json.loads(json_data_as_unicode)
# Find and call the right classmethod from_json() to restore # Find and call the right classmethod from_json() to restore
# the object. # the object.
@@ -619,7 +614,7 @@ class OAuth2Credentials(Credentials):
Returns: Returns:
An instance of a Credentials subclass. An instance of a Credentials subclass.
""" """
data = json.loads(_from_bytes(json_data)) data = json.loads(_helpers._from_bytes(json_data))
if (data.get('token_expiry') and if (data.get('token_expiry') and
not isinstance(data['token_expiry'], datetime.datetime)): not isinstance(data['token_expiry'], datetime.datetime)):
try: try:
@@ -792,7 +787,7 @@ class OAuth2Credentials(Credentials):
logger.info('Refreshing access_token') logger.info('Refreshing access_token')
resp, content = http_request( resp, content = http_request(
self.token_uri, method='POST', body=body, headers=headers) self.token_uri, method='POST', body=body, headers=headers)
content = _from_bytes(content) content = _helpers._from_bytes(content)
if resp.status == http_client.OK: if resp.status == http_client.OK:
d = json.loads(content) d = json.loads(content)
self.token_response = d self.token_response = d
@@ -863,7 +858,7 @@ class OAuth2Credentials(Credentials):
else: else:
error_msg = 'Invalid response {0}.'.format(resp.status) error_msg = 'Invalid response {0}.'.format(resp.status)
try: try:
d = json.loads(_from_bytes(content)) d = json.loads(_helpers._from_bytes(content))
if 'error' in d: if 'error' in d:
error_msg = d['error'] error_msg = d['error']
except (TypeError, ValueError): except (TypeError, ValueError):
@@ -902,7 +897,7 @@ class OAuth2Credentials(Credentials):
token_info_uri = _update_query_params(self.token_info_uri, token_info_uri = _update_query_params(self.token_info_uri,
query_params) query_params)
resp, content = http_request(token_info_uri) resp, content = http_request(token_info_uri)
content = _from_bytes(content) content = _helpers._from_bytes(content)
if resp.status == http_client.OK: if resp.status == http_client.OK:
d = json.loads(content) d = json.loads(content)
self.scopes = set(util.string_to_scopes(d.get('scope', ''))) self.scopes = set(util.string_to_scopes(d.get('scope', '')))
@@ -968,7 +963,7 @@ class AccessTokenCredentials(OAuth2Credentials):
@classmethod @classmethod
def from_json(cls, json_data): def from_json(cls, json_data):
data = json.loads(_from_bytes(json_data)) data = json.loads(_helpers._from_bytes(json_data))
retval = AccessTokenCredentials( retval = AccessTokenCredentials(
data['access_token'], data['access_token'],
data['user_agent']) data['user_agent'])
@@ -1091,7 +1086,7 @@ class GoogleCredentials(OAuth2Credentials):
def __init__(self, access_token, client_id, client_secret, refresh_token, def __init__(self, access_token, client_id, client_secret, refresh_token,
token_expiry, token_uri, user_agent, token_expiry, token_uri, user_agent,
revoke_uri=GOOGLE_REVOKE_URI): revoke_uri=oauth2client.GOOGLE_REVOKE_URI):
"""Create an instance of GoogleCredentials. """Create an instance of GoogleCredentials.
This constructor is not usually called by the user, instead This constructor is not usually called by the user, instead
@@ -1109,8 +1104,8 @@ class GoogleCredentials(OAuth2Credentials):
user_agent: string, The HTTP User-Agent to provide for this user_agent: string, The HTTP User-Agent to provide for this
application. application.
revoke_uri: string, URI for revoke endpoint. Defaults to revoke_uri: string, URI for revoke endpoint. Defaults to
GOOGLE_REVOKE_URI; a token can't be revoked if this oauth2client.GOOGLE_REVOKE_URI; a token can't be
is None. revoked if this is None.
""" """
super(GoogleCredentials, self).__init__( super(GoogleCredentials, self).__init__(
access_token, client_id, client_secret, refresh_token, access_token, client_id, client_secret, refresh_token,
@@ -1135,18 +1130,17 @@ class GoogleCredentials(OAuth2Credentials):
def from_json(cls, json_data): def from_json(cls, json_data):
# TODO(issue 388): eliminate the circularity that is the reason for # TODO(issue 388): eliminate the circularity that is the reason for
# this non-top-level import. # this non-top-level import.
from oauth2client.service_account import ServiceAccountCredentials from oauth2client import service_account
from oauth2client.service_account import _JWTAccessCredentials data = json.loads(_helpers._from_bytes(json_data))
data = json.loads(_from_bytes(json_data))
# We handle service_account.ServiceAccountCredentials since it is a # We handle service_account.ServiceAccountCredentials since it is a
# possible return type of GoogleCredentials.get_application_default() # possible return type of GoogleCredentials.get_application_default()
if (data['_module'] == 'oauth2client.service_account' and if (data['_module'] == 'oauth2client.service_account' and
data['_class'] == 'ServiceAccountCredentials'): data['_class'] == 'ServiceAccountCredentials'):
return ServiceAccountCredentials.from_json(data) return service_account.ServiceAccountCredentials.from_json(data)
elif (data['_module'] == 'oauth2client.service_account' and elif (data['_module'] == 'oauth2client.service_account' and
data['_class'] == '_JWTAccessCredentials'): data['_class'] == '_JWTAccessCredentials'):
return _JWTAccessCredentials.from_json(data) return service_account._JWTAccessCredentials.from_json(data)
token_expiry = _parse_expiry(data.get('token_expiry')) token_expiry = _parse_expiry(data.get('token_expiry'))
google_credentials = cls( google_credentials = cls(
@@ -1423,11 +1417,11 @@ def _get_application_default_credential_from_file(filename):
client_secret=client_credentials['client_secret'], client_secret=client_credentials['client_secret'],
refresh_token=client_credentials['refresh_token'], refresh_token=client_credentials['refresh_token'],
token_expiry=None, token_expiry=None,
token_uri=GOOGLE_TOKEN_URI, token_uri=oauth2client.GOOGLE_TOKEN_URI,
user_agent='Python client library') user_agent='Python client library')
else: # client_credentials['type'] == SERVICE_ACCOUNT else: # client_credentials['type'] == SERVICE_ACCOUNT
from oauth2client.service_account import _JWTAccessCredentials from oauth2client import service_account
return _JWTAccessCredentials.from_json_keyfile_dict( return service_account._JWTAccessCredentials.from_json_keyfile_dict(
client_credentials) client_credentials)
@@ -1469,8 +1463,8 @@ class AssertionCredentials(GoogleCredentials):
@util.positional(2) @util.positional(2)
def __init__(self, assertion_type, user_agent=None, def __init__(self, assertion_type, user_agent=None,
token_uri=GOOGLE_TOKEN_URI, token_uri=oauth2client.GOOGLE_TOKEN_URI,
revoke_uri=GOOGLE_REVOKE_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI,
**unused_kwargs): **unused_kwargs):
"""Constructor for AssertionFlowCredentials. """Constructor for AssertionFlowCredentials.
@@ -1572,7 +1566,7 @@ def verify_id_token(id_token, audience, http=None,
resp, content = http.request(cert_uri) resp, content = http.request(cert_uri)
if resp.status == http_client.OK: if resp.status == http_client.OK:
certs = json.loads(_from_bytes(content)) certs = json.loads(_helpers._from_bytes(content))
return crypt.verify_signed_jwt_with_certs(id_token, certs, audience) return crypt.verify_signed_jwt_with_certs(id_token, certs, audience)
else: else:
raise VerifyJwtTokenError('Status code: {0}'.format(resp.status)) raise VerifyJwtTokenError('Status code: {0}'.format(resp.status))
@@ -1598,7 +1592,8 @@ def _extract_id_token(id_token):
raise VerifyJwtTokenError( raise VerifyJwtTokenError(
'Wrong number of segments in token: {0}'.format(id_token)) 'Wrong number of segments in token: {0}'.format(id_token))
return json.loads(_from_bytes(_urlsafe_b64decode(segments[1]))) return json.loads(
_helpers._from_bytes(_helpers._urlsafe_b64decode(segments[1])))
def _parse_exchange_token_response(content): def _parse_exchange_token_response(content):
@@ -1615,7 +1610,7 @@ def _parse_exchange_token_response(content):
i.e. {}. That basically indicates a failure. i.e. {}. That basically indicates a failure.
""" """
resp = {} resp = {}
content = _from_bytes(content) content = _helpers._from_bytes(content)
try: try:
resp = json.loads(content) resp = json.loads(content)
except Exception: except Exception:
@@ -1633,11 +1628,12 @@ def _parse_exchange_token_response(content):
@util.positional(4) @util.positional(4)
def credentials_from_code(client_id, client_secret, scope, code, def credentials_from_code(client_id, client_secret, scope, code,
redirect_uri='postmessage', http=None, redirect_uri='postmessage', http=None,
user_agent=None, token_uri=GOOGLE_TOKEN_URI, user_agent=None,
auth_uri=GOOGLE_AUTH_URI, token_uri=oauth2client.GOOGLE_TOKEN_URI,
revoke_uri=GOOGLE_REVOKE_URI, auth_uri=oauth2client.GOOGLE_AUTH_URI,
device_uri=GOOGLE_DEVICE_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI,
token_info_uri=GOOGLE_TOKEN_INFO_URI): device_uri=oauth2client.GOOGLE_DEVICE_URI,
token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI):
"""Exchanges an authorization code for an OAuth2Credentials object. """Exchanges an authorization code for an OAuth2Credentials object.
Args: Args:
@@ -1778,12 +1774,12 @@ class OAuth2WebServerFlow(Flow):
scope=None, scope=None,
redirect_uri=None, redirect_uri=None,
user_agent=None, user_agent=None,
auth_uri=GOOGLE_AUTH_URI, auth_uri=oauth2client.GOOGLE_AUTH_URI,
token_uri=GOOGLE_TOKEN_URI, token_uri=oauth2client.GOOGLE_TOKEN_URI,
revoke_uri=GOOGLE_REVOKE_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI,
login_hint=None, login_hint=None,
device_uri=GOOGLE_DEVICE_URI, device_uri=oauth2client.GOOGLE_DEVICE_URI,
token_info_uri=GOOGLE_TOKEN_INFO_URI, token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI,
authorization_header=None, authorization_header=None,
**kwargs): **kwargs):
"""Constructor for OAuth2WebServerFlow. """Constructor for OAuth2WebServerFlow.
@@ -1915,7 +1911,7 @@ class OAuth2WebServerFlow(Flow):
resp, content = http.request(self.device_uri, method='POST', body=body, resp, content = http.request(self.device_uri, method='POST', body=body,
headers=headers) headers=headers)
content = _from_bytes(content) content = _helpers._from_bytes(content)
if resp.status == http_client.OK: if resp.status == http_client.OK:
try: try:
flow_info = json.loads(content) flow_info = json.loads(content)

View File

@@ -16,13 +16,10 @@ import errno
import fcntl import fcntl
import time import time
from oauth2client.contrib.locked_file import _Opener from oauth2client.contrib import locked_file
from oauth2client.contrib.locked_file import AlreadyLockedException
from oauth2client.contrib.locked_file import logger
from oauth2client.contrib.locked_file import validate_file
class _FcntlOpener(_Opener): class _FcntlOpener(locked_file._Opener):
"""Open, lock, and unlock a file using fcntl.lockf.""" """Open, lock, and unlock a file using fcntl.lockf."""
def open_and_lock(self, timeout, delay): def open_and_lock(self, timeout, delay):
@@ -39,11 +36,11 @@ class _FcntlOpener(_Opener):
link. link.
""" """
if self._locked: if self._locked:
raise AlreadyLockedException( raise locked_file.AlreadyLockedException(
'File {0} is already locked'.format(self._filename)) 'File {0} is already locked'.format(self._filename))
start_time = time.time() start_time = time.time()
validate_file(self._filename) locked_file.validate_file(self._filename)
try: try:
self._fh = open(self._filename, self._mode) self._fh = open(self._filename, self._mode)
except IOError as e: except IOError as e:
@@ -67,8 +64,8 @@ class _FcntlOpener(_Opener):
raise raise
# We could not acquire the lock. Try again. # We could not acquire the lock. Try again.
if (time.time() - start_time) >= timeout: if (time.time() - start_time) >= timeout:
logger.warn('Could not lock %s in %s seconds', locked_file.logger.warn('Could not lock %s in %s seconds',
self._filename, timeout) self._filename, timeout)
if self._fh: if self._fh:
self._fh.close() self._fh.close()
self._fh = open(self._filename, self._fallback_mode) self._fh = open(self._filename, self._fallback_mode)

View File

@@ -24,9 +24,9 @@ import httplib2
from six.moves import http_client from six.moves import http_client
from six.moves.urllib import parse as urlparse from six.moves.urllib import parse as urlparse
from oauth2client import _helpers
from oauth2client import client
from oauth2client import util from oauth2client import util
from oauth2client._helpers import _from_bytes
from oauth2client.client import _UTCNOW
METADATA_ROOT = 'http://metadata.google.internal/computeMetadata/v1/' METADATA_ROOT = 'http://metadata.google.internal/computeMetadata/v1/'
@@ -62,7 +62,7 @@ def get(http_request, path, root=METADATA_ROOT, recursive=None):
) )
if response.status == http_client.OK: if response.status == http_client.OK:
decoded = _from_bytes(content) decoded = _helpers._from_bytes(content)
if response['content-type'] == 'application/json': if response['content-type'] == 'application/json':
return json.loads(decoded) return json.loads(decoded)
else: else:
@@ -118,6 +118,6 @@ def get_token(http_request, service_account='default'):
token_json = get( token_json = get(
http_request, http_request,
'instance/service-accounts/{0}/token'.format(service_account)) 'instance/service-accounts/{0}/token'.format(service_account))
token_expiry = _UTCNOW() + datetime.timedelta( token_expiry = client._UTCNOW() + datetime.timedelta(
seconds=token_json['expires_in']) seconds=token_json['expires_in'])
return token_json['access_token'], token_expiry return token_json['access_token'], token_expiry

View File

@@ -19,13 +19,10 @@ import pywintypes
import win32con import win32con
import win32file import win32file
from oauth2client.contrib.locked_file import _Opener from oauth2client.contrib import locked_file
from oauth2client.contrib.locked_file import AlreadyLockedException
from oauth2client.contrib.locked_file import logger
from oauth2client.contrib.locked_file import validate_file
class _Win32Opener(_Opener): class _Win32Opener(locked_file._Opener):
"""Open, lock, and unlock a file using windows primitives.""" """Open, lock, and unlock a file using windows primitives."""
# Error #33: # Error #33:
@@ -50,11 +47,11 @@ class _Win32Opener(_Opener):
link. link.
""" """
if self._locked: if self._locked:
raise AlreadyLockedException( raise locked_file.AlreadyLockedException(
'File {0} is already locked'.format(self._filename)) 'File {0} is already locked'.format(self._filename))
start_time = time.time() start_time = time.time()
validate_file(self._filename) locked_file.validate_file(self._filename)
try: try:
self._fh = open(self._filename, self._mode) self._fh = open(self._filename, self._mode)
except IOError as e: except IOError as e:
@@ -86,8 +83,8 @@ class _Win32Opener(_Opener):
# We could not acquire the lock. Try again. # We could not acquire the lock. Try again.
if (time.time() - start_time) >= timeout: if (time.time() - start_time) >= timeout:
logger.warn('Could not lock %s in %s seconds', locked_file.logger.warn('Could not lock %s in %s seconds',
self._filename, timeout) self._filename, timeout)
if self._fh: if self._fh:
self._fh.close() self._fh.close()
self._fh = open(self._filename, self._fallback_mode) self._fh = open(self._filename, self._fallback_mode)

View File

@@ -32,17 +32,10 @@ from google.appengine.ext.webapp.util import login_required
import httplib2 import httplib2
import webapp2 as webapp import webapp2 as webapp
import oauth2client
from oauth2client import client
from oauth2client import clientsecrets from oauth2client import clientsecrets
from oauth2client import GOOGLE_AUTH_URI
from oauth2client import GOOGLE_REVOKE_URI
from oauth2client import GOOGLE_TOKEN_URI
from oauth2client import util from oauth2client import util
from oauth2client.client import AccessTokenRefreshError
from oauth2client.client import AssertionCredentials
from oauth2client.client import Credentials
from oauth2client.client import Flow
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.client import Storage
from oauth2client.contrib import xsrfutil from oauth2client.contrib import xsrfutil
# This is a temporary fix for a Google internal issue. # This is a temporary fix for a Google internal issue.
@@ -125,7 +118,7 @@ def xsrf_secret_key():
return str(secret) return str(secret)
class AppAssertionCredentials(AssertionCredentials): class AppAssertionCredentials(client.AssertionCredentials):
"""Credentials object for App Engine Assertion Grants """Credentials object for App Engine Assertion Grants
This object will allow an App Engine application to identify itself to This object will allow an App Engine application to identify itself to
@@ -184,7 +177,7 @@ class AppAssertionCredentials(AssertionCredentials):
(token, _) = app_identity.get_access_token( (token, _) = app_identity.get_access_token(
scopes, service_account_id=self.service_account_id) scopes, service_account_id=self.service_account_id)
except app_identity.Error as e: except app_identity.Error as e:
raise AccessTokenRefreshError(str(e)) raise client.AccessTokenRefreshError(str(e))
self.access_token = token self.access_token = token
@property @property
@@ -235,7 +228,7 @@ class FlowProperty(db.Property):
""" """
# Tell what the user type is. # Tell what the user type is.
data_type = Flow data_type = client.Flow
# For writing to datastore. # For writing to datastore.
def get_value_for_datastore(self, model_instance): def get_value_for_datastore(self, model_instance):
@@ -250,7 +243,7 @@ class FlowProperty(db.Property):
return pickle.loads(value) return pickle.loads(value)
def validate(self, value): def validate(self, value):
if value is not None and not isinstance(value, Flow): if value is not None and not isinstance(value, client.Flow):
raise db.BadValueError( raise db.BadValueError(
'Property {0} must be convertible ' 'Property {0} must be convertible '
'to a FlowThreeLegged instance ({1})'.format(self.name, value)) 'to a FlowThreeLegged instance ({1})'.format(self.name, value))
@@ -268,7 +261,7 @@ class CredentialsProperty(db.Property):
""" """
# Tell what the user type is. # Tell what the user type is.
data_type = Credentials data_type = client.Credentials
# For writing to datastore. # For writing to datastore.
def get_value_for_datastore(self, model_instance): def get_value_for_datastore(self, model_instance):
@@ -289,7 +282,7 @@ class CredentialsProperty(db.Property):
if len(value) == 0: if len(value) == 0:
return None return None
try: try:
credentials = Credentials.new_from_json(value) credentials = client.Credentials.new_from_json(value)
except ValueError: except ValueError:
credentials = None credentials = None
return credentials return credentials
@@ -297,14 +290,14 @@ class CredentialsProperty(db.Property):
def validate(self, value): def validate(self, value):
value = super(CredentialsProperty, self).validate(value) value = super(CredentialsProperty, self).validate(value)
logger.info("validate: Got type " + str(type(value))) logger.info("validate: Got type " + str(type(value)))
if value is not None and not isinstance(value, Credentials): if value is not None and not isinstance(value, client.Credentials):
raise db.BadValueError( raise db.BadValueError(
'Property {0} must be convertible ' 'Property {0} must be convertible '
'to a Credentials instance ({1})'.format(self.name, value)) 'to a Credentials instance ({1})'.format(self.name, value))
return value return value
class StorageByKeyName(Storage): class StorageByKeyName(client.Storage):
"""Store and retrieve a credential to and from the App Engine datastore. """Store and retrieve a credential to and from the App Engine datastore.
This Storage helper presumes the Credentials have been stored as a This Storage helper presumes the Credentials have been stored as a
@@ -396,7 +389,7 @@ class StorageByKeyName(Storage):
if self._cache: if self._cache:
json = self._cache.get(self._key_name) json = self._cache.get(self._key_name)
if json: if json:
credentials = Credentials.new_from_json(json) credentials = client.Credentials.new_from_json(json)
if credentials is None: if credentials is None:
entity = self._get_entity() entity = self._get_entity()
if entity is not None: if entity is not None:
@@ -532,9 +525,9 @@ class OAuth2Decorator(object):
@util.positional(4) @util.positional(4)
def __init__(self, client_id, client_secret, scope, def __init__(self, client_id, client_secret, scope,
auth_uri=GOOGLE_AUTH_URI, auth_uri=oauth2client.GOOGLE_AUTH_URI,
token_uri=GOOGLE_TOKEN_URI, token_uri=oauth2client.GOOGLE_TOKEN_URI,
revoke_uri=GOOGLE_REVOKE_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI,
user_agent=None, user_agent=None,
message=None, message=None,
callback_path='/oauth2callback', callback_path='/oauth2callback',
@@ -653,7 +646,7 @@ class OAuth2Decorator(object):
return request_handler.redirect(self.authorize_url()) return request_handler.redirect(self.authorize_url())
try: try:
resp = method(request_handler, *args, **kwargs) resp = method(request_handler, *args, **kwargs)
except AccessTokenRefreshError: except client.AccessTokenRefreshError:
return request_handler.redirect(self.authorize_url()) return request_handler.redirect(self.authorize_url())
finally: finally:
self.credentials = None self.credentials = None
@@ -674,7 +667,7 @@ class OAuth2Decorator(object):
if self.flow is None: if self.flow is None:
redirect_uri = request_handler.request.relative_url( redirect_uri = request_handler.request.relative_url(
self._callback_path) # Usually /oauth2callback self._callback_path) # Usually /oauth2callback
self.flow = OAuth2WebServerFlow( self.flow = client.OAuth2WebServerFlow(
self._client_id, self._client_secret, self._scope, self._client_id, self._client_secret, self._scope,
redirect_uri=redirect_uri, user_agent=self._user_agent, redirect_uri=redirect_uri, user_agent=self._user_agent,
auth_uri=self._auth_uri, token_uri=self._token_uri, auth_uri=self._auth_uri, token_uri=self._token_uri,

View File

@@ -19,12 +19,8 @@ import json
import os import os
import socket import socket
from oauth2client import _helpers
from oauth2client import client from oauth2client import client
from oauth2client._helpers import _to_bytes
# Expose utcnow() at module level to allow for
# easier testing (by replacing with a stub).
_UTCNOW = datetime.datetime.utcnow
DEVSHELL_ENV = 'DEVSHELL_CLIENT_PORT' DEVSHELL_ENV = 'DEVSHELL_CLIENT_PORT'
@@ -84,7 +80,7 @@ def _SendRecv():
data = CREDENTIAL_INFO_REQUEST_JSON data = CREDENTIAL_INFO_REQUEST_JSON
msg = '{0}\n{1}'.format(len(data), data) msg = '{0}\n{1}'.format(len(data), data)
sock.sendall(_to_bytes(msg, encoding='utf-8')) sock.sendall(_helpers._to_bytes(msg, encoding='utf-8'))
header = sock.recv(6).decode() header = sock.recv(6).decode()
if '\n' not in header: if '\n' not in header:
@@ -127,7 +123,7 @@ class DevshellCredentials(client.GoogleCredentials):
expires_in = self.devshell_response.expires_in expires_in = self.devshell_response.expires_in
if expires_in is not None: if expires_in is not None:
delta = datetime.timedelta(seconds=expires_in) delta = datetime.timedelta(seconds=expires_in)
self.token_expiry = _UTCNOW() + delta self.token_expiry = client._UTCNOW() + delta
else: else:
self.token_expiry = None self.token_expiry = None

View File

@@ -14,11 +14,10 @@
"""Dictionary storage for OAuth2 Credentials.""" """Dictionary storage for OAuth2 Credentials."""
from oauth2client.client import OAuth2Credentials from oauth2client import client
from oauth2client.client import Storage
class DictionaryStorage(Storage): class DictionaryStorage(client.Storage):
"""Store and retrieve credentials to and from a dictionary-like object. """Store and retrieve credentials to and from a dictionary-like object.
Args: Args:
@@ -46,7 +45,7 @@ class DictionaryStorage(Storage):
if serialized is None: if serialized is None:
return None return None
credentials = OAuth2Credentials.from_json(serialized) credentials = client.OAuth2Credentials.from_json(serialized)
credentials.set_store(self) credentials.set_store(self)
return credentials return credentials

View File

@@ -14,10 +14,10 @@
"""Contains a storage module that stores credentials using the Django ORM.""" """Contains a storage module that stores credentials using the Django ORM."""
from oauth2client.client import Storage from oauth2client import client
class DjangoORMStorage(Storage): class DjangoORMStorage(client.Storage):
"""Store and retrieve a single credential to and from the Django datastore. """Store and retrieve a single credential to and from the Django datastore.
This Storage helper presumes the Credentials This Storage helper presumes the Credentials

View File

@@ -182,10 +182,9 @@ except ImportError: # pragma: NO COVER
import httplib2 import httplib2
import six.moves.http_client as httplib import six.moves.http_client as httplib
from oauth2client import client
from oauth2client import clientsecrets from oauth2client import clientsecrets
from oauth2client.client import FlowExchangeError from oauth2client.contrib import dictionary_storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.contrib.dictionary_storage import DictionaryStorage
__author__ = 'jonwayne@google.com (Jon Wayne Parrott)' __author__ = 'jonwayne@google.com (Jon Wayne Parrott)'
@@ -263,7 +262,8 @@ class UserOAuth2(object):
self.flow_kwargs = kwargs self.flow_kwargs = kwargs
if storage is None: if storage is None:
storage = DictionaryStorage(session, key=_CREDENTIALS_KEY) storage = dictionary_storage.DictionaryStorage(
session, key=_CREDENTIALS_KEY)
self.storage = storage self.storage = storage
if scopes is None: if scopes is None:
@@ -341,7 +341,7 @@ class UserOAuth2(object):
extra_scopes = kw.pop('scopes', []) extra_scopes = kw.pop('scopes', [])
scopes = set(self.scopes).union(set(extra_scopes)) scopes = set(self.scopes).union(set(extra_scopes))
flow = OAuth2WebServerFlow( flow = client.OAuth2WebServerFlow(
client_id=self.client_id, client_id=self.client_id,
client_secret=self.client_secret, client_secret=self.client_secret,
scope=scopes, scope=scopes,
@@ -418,7 +418,7 @@ class UserOAuth2(object):
# Exchange the auth code for credentials. # Exchange the auth code for credentials.
try: try:
credentials = flow.step2_exchange(code) credentials = flow.step2_exchange(code)
except FlowExchangeError as exchange_error: except client.FlowExchangeError as exchange_error:
current_app.logger.exception(exchange_error) current_app.logger.exception(exchange_error)
content = 'An error occurred: {0}'.format(exchange_error) content = 'An error occurred: {0}'.format(exchange_error)
return content, httplib.BAD_REQUEST return content, httplib.BAD_REQUEST

View File

@@ -22,8 +22,7 @@ import warnings
import httplib2 import httplib2
from oauth2client.client import AssertionCredentials from oauth2client import client
from oauth2client.client import HttpAccessTokenRefreshError
from oauth2client.contrib import _metadata from oauth2client.contrib import _metadata
@@ -39,7 +38,7 @@ can't be overridden in the request.
""" """
class AppAssertionCredentials(AssertionCredentials): class AppAssertionCredentials(client.AssertionCredentials):
"""Credentials object for Compute Engine Assertion Grants """Credentials object for Compute Engine Assertion Grants
This object will allow a Compute Engine instance to identify itself to This object will allow a Compute Engine instance to identify itself to
@@ -136,7 +135,7 @@ class AppAssertionCredentials(AssertionCredentials):
self.access_token, self.token_expiry = _metadata.get_token( self.access_token, self.token_expiry = _metadata.get_token(
http_request, service_account=self.service_account_email) http_request, service_account=self.service_account_email)
except httplib2.HttpLib2Error as e: except httplib2.HttpLib2Error as e:
raise HttpAccessTokenRefreshError(str(e)) raise client.HttpAccessTokenRefreshError(str(e))
@property @property
def serialization_data(self): def serialization_data(self):

View File

@@ -21,14 +21,13 @@ import threading
import keyring import keyring
from oauth2client.client import Credentials from oauth2client import client
from oauth2client.client import Storage as BaseStorage
__author__ = 'jcgregorio@google.com (Joe Gregorio)' __author__ = 'jcgregorio@google.com (Joe Gregorio)'
class Storage(BaseStorage): class Storage(client.Storage):
"""Store and retrieve a single credential to and from the keyring. """Store and retrieve a single credential to and from the keyring.
To use this module you must have the keyring module installed. See To use this module you must have the keyring module installed. See
@@ -44,9 +43,9 @@ class Storage(BaseStorage):
Usage:: Usage::
from oauth2client.keyring_storage import Storage from oauth2client import keyring_storage
s = Storage('name_of_application', 'user1') s = keyring_storage.Storage('name_of_application', 'user1')
credentials = s.get() credentials = s.get()
""" """
@@ -74,7 +73,7 @@ class Storage(BaseStorage):
if content is not None: if content is not None:
try: try:
credentials = Credentials.new_from_json(content) credentials = client.Credentials.new_from_json(content)
credentials.set_store(self) credentials.set_store(self)
except ValueError: except ValueError:
pass pass

View File

@@ -85,8 +85,7 @@ import fasteners
from six import iteritems from six import iteritems
from oauth2client import _helpers from oauth2client import _helpers
from oauth2client.client import Credentials from oauth2client import client
from oauth2client.client import Storage as BaseStorage
#: The maximum amount of time, in seconds, to wait when acquire the #: The maximum amount of time, in seconds, to wait when acquire the
@@ -155,7 +154,7 @@ def _load_credentials_file(credentials_file):
for key, encoded_credential in iteritems(data.get('credentials', {})): for key, encoded_credential in iteritems(data.get('credentials', {})):
try: try:
credential_json = base64.b64decode(encoded_credential) credential_json = base64.b64decode(encoded_credential)
credential = Credentials.new_from_json(credential_json) credential = client.Credentials.new_from_json(credential_json)
credentials[key] = credential credentials[key] = credential
except: except:
logger.warning( logger.warning(
@@ -310,7 +309,7 @@ def _get_backend(filename):
return _backends[filename] return _backends[filename]
class MultiprocessFileStorage(BaseStorage): class MultiprocessFileStorage(client.Storage):
"""Multiprocess file credential storage. """Multiprocess file credential storage.
Args: Args:

View File

@@ -50,10 +50,9 @@ import logging
import os import os
import threading import threading
from oauth2client import client
from oauth2client import util from oauth2client import util
from oauth2client.client import Credentials from oauth2client.contrib import locked_file
from oauth2client.client import Storage as BaseStorage
from oauth2client.contrib.locked_file import LockedFile
__author__ = 'jbeda@google.com (Joe Beda)' __author__ = 'jbeda@google.com (Joe Beda)'
@@ -208,7 +207,7 @@ class _MultiStore(object):
This will create the file if necessary. This will create the file if necessary.
""" """
self._file = LockedFile(filename, 'r+', 'r') self._file = locked_file.LockedFile(filename, 'r+', 'r')
self._thread_lock = threading.Lock() self._thread_lock = threading.Lock()
self._read_only = False self._read_only = False
self._warn_on_readonly = warn_on_readonly self._warn_on_readonly = warn_on_readonly
@@ -224,7 +223,7 @@ class _MultiStore(object):
# If this is None, then the store hasn't been read yet. # If this is None, then the store hasn't been read yet.
self._data = None self._data = None
class _Storage(BaseStorage): class _Storage(client.Storage):
"""A Storage object that can read/write a single credential.""" """A Storage object that can read/write a single credential."""
def __init__(self, multistore, key): def __init__(self, multistore, key):
@@ -421,7 +420,7 @@ class _MultiStore(object):
raw_key = cred_entry['key'] raw_key = cred_entry['key']
key = _dict_to_tuple_key(raw_key) key = _dict_to_tuple_key(raw_key)
credential = None credential = None
credential = Credentials.new_from_json( credential = client.Credentials.new_from_json(
json.dumps(cred_entry['credential'])) json.dumps(cred_entry['credential']))
return (key, credential) return (key, credential)

View File

@@ -20,7 +20,7 @@ Configuration
============= =============
In order to use this storage, you'll need to create table In order to use this storage, you'll need to create table
with :class:`oauth2client.contrib.sql_alchemy.CredentialsType` column. with :class:`oauth2client.contrib.sqlalchemy.CredentialsType` column.
It's recommended to either put this column on some sort of user info It's recommended to either put this column on some sort of user info
table or put the column in a table with a belongs-to relationship to table or put the column in a table with a belongs-to relationship to
a user info table. a user info table.
@@ -30,11 +30,12 @@ column that's related to a user table by the `user_id` key.
.. code-block:: python .. code-block:: python
from oauth2client.contrib.sql_alchemy import CredentialsType
from sqlalchemy import Column, ForeignKey, Integer from sqlalchemy import Column, ForeignKey, Integer
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship from sqlalchemy.orm import relationship
from oauth2client.contrib.sqlalchemy import CredentialsType
Base = declarative_base() Base = declarative_base()
@@ -60,9 +61,10 @@ We will reuse tables defined above.
.. code-block:: python .. code-block:: python
from sqlalchemy.orm import Session
from oauth2client.client import OAuth2Credentials from oauth2client.client import OAuth2Credentials
from oauth2client.contrib.sql_alchemy import Storage from oauth2client.contrib.sql_alchemy import Storage
from sqlalchemy.orm import Session
session = Session() session = Session()
user = session.query(User).first() user = session.query(User).first()
@@ -92,7 +94,7 @@ from __future__ import absolute_import
import sqlalchemy.types import sqlalchemy.types
import oauth2client.client from oauth2client import client
class CredentialsType(sqlalchemy.types.PickleType): class CredentialsType(sqlalchemy.types.PickleType):
@@ -102,7 +104,7 @@ class CredentialsType(sqlalchemy.types.PickleType):
""" """
class Storage(oauth2client.client.Storage): class Storage(client.Storage):
"""Store and retrieve a single credential to and from SQLAlchemy. """Store and retrieve a single credential to and from SQLAlchemy.
This helper presumes the Credentials This helper presumes the Credentials
have been stored as a Credentials column have been stored as a Credentials column

View File

@@ -19,8 +19,8 @@ import binascii
import hmac import hmac
import time import time
from oauth2client import _helpers
from oauth2client import util from oauth2client import util
from oauth2client._helpers import _to_bytes
__authors__ = [ __authors__ = [
'"Doug Coker" <dcoker@google.com>', '"Doug Coker" <dcoker@google.com>',
@@ -49,12 +49,12 @@ def generate_token(key, user_id, action_id='', when=None):
Returns: Returns:
A string XSRF protection token. A string XSRF protection token.
""" """
digester = hmac.new(_to_bytes(key, encoding='utf-8')) digester = hmac.new(_helpers._to_bytes(key, encoding='utf-8'))
digester.update(_to_bytes(str(user_id), encoding='utf-8')) digester.update(_helpers._to_bytes(str(user_id), encoding='utf-8'))
digester.update(DELIMITER) digester.update(DELIMITER)
digester.update(_to_bytes(action_id, encoding='utf-8')) digester.update(_helpers._to_bytes(action_id, encoding='utf-8'))
digester.update(DELIMITER) digester.update(DELIMITER)
when = _to_bytes(str(when or int(time.time())), encoding='utf-8') when = _helpers._to_bytes(str(when or int(time.time())), encoding='utf-8')
digester.update(when) digester.update(when)
digest = digester.digest() digest = digester.digest()

View File

@@ -19,15 +19,13 @@ import json
import logging import logging
import time import time
from oauth2client._helpers import _from_bytes from oauth2client import _helpers
from oauth2client._helpers import _json_encode from oauth2client import _pure_python_crypt
from oauth2client._helpers import _to_bytes
from oauth2client._helpers import _urlsafe_b64decode
from oauth2client._helpers import _urlsafe_b64encode
from oauth2client._pure_python_crypt import RsaSigner
from oauth2client._pure_python_crypt import RsaVerifier
RsaSigner = _pure_python_crypt.RsaSigner
RsaVerifier = _pure_python_crypt.RsaVerifier
CLOCK_SKEW_SECS = 300 # 5 minutes in seconds CLOCK_SKEW_SECS = 300 # 5 minutes in seconds
AUTH_TOKEN_LIFETIME_SECS = 300 # 5 minutes in seconds AUTH_TOKEN_LIFETIME_SECS = 300 # 5 minutes in seconds
MAX_TOKEN_LIFETIME_SECS = 86400 # 1 day in seconds MAX_TOKEN_LIFETIME_SECS = 86400 # 1 day in seconds
@@ -44,17 +42,19 @@ def _bad_pkcs12_key_as_pem(*args, **kwargs):
try: try:
from oauth2client._openssl_crypt import OpenSSLVerifier from oauth2client import _openssl_crypt
from oauth2client._openssl_crypt import OpenSSLSigner OpenSSLSigner = _openssl_crypt.OpenSSLSigner
from oauth2client._openssl_crypt import pkcs12_key_as_pem OpenSSLVerifier = _openssl_crypt.OpenSSLVerifier
pkcs12_key_as_pem = _openssl_crypt.pkcs12_key_as_pem
except ImportError: # pragma: NO COVER except ImportError: # pragma: NO COVER
OpenSSLVerifier = None OpenSSLVerifier = None
OpenSSLSigner = None OpenSSLSigner = None
pkcs12_key_as_pem = _bad_pkcs12_key_as_pem pkcs12_key_as_pem = _bad_pkcs12_key_as_pem
try: try:
from oauth2client._pycrypto_crypt import PyCryptoVerifier from oauth2client import _pycrypto_crypt
from oauth2client._pycrypto_crypt import PyCryptoSigner PyCryptoSigner = _pycrypto_crypt.PyCryptoSigner
PyCryptoVerifier = _pycrypto_crypt.PyCryptoVerifier
except ImportError: # pragma: NO COVER except ImportError: # pragma: NO COVER
PyCryptoVerifier = None PyCryptoVerifier = None
PyCryptoSigner = None PyCryptoSigner = None
@@ -89,13 +89,13 @@ def make_signed_jwt(signer, payload, key_id=None):
header['kid'] = key_id header['kid'] = key_id
segments = [ segments = [
_urlsafe_b64encode(_json_encode(header)), _helpers._urlsafe_b64encode(_helpers._json_encode(header)),
_urlsafe_b64encode(_json_encode(payload)), _helpers._urlsafe_b64encode(_helpers._json_encode(payload)),
] ]
signing_input = b'.'.join(segments) signing_input = b'.'.join(segments)
signature = signer.sign(signing_input) signature = signer.sign(signing_input)
segments.append(_urlsafe_b64encode(signature)) segments.append(_helpers._urlsafe_b64encode(signature))
logger.debug(str(segments)) logger.debug(str(segments))
@@ -221,7 +221,7 @@ def verify_signed_jwt_with_certs(jwt, certs, audience=None):
Raises: Raises:
AppIdentityError: if any checks are failed. AppIdentityError: if any checks are failed.
""" """
jwt = _to_bytes(jwt) jwt = _helpers._to_bytes(jwt)
if jwt.count(b'.') != 2: if jwt.count(b'.') != 2:
raise AppIdentityError( raise AppIdentityError(
@@ -229,12 +229,12 @@ def verify_signed_jwt_with_certs(jwt, certs, audience=None):
header, payload, signature = jwt.split(b'.') header, payload, signature = jwt.split(b'.')
message_to_sign = header + b'.' + payload message_to_sign = header + b'.' + payload
signature = _urlsafe_b64decode(signature) signature = _helpers._urlsafe_b64decode(signature)
# Parse token. # Parse token.
payload_bytes = _urlsafe_b64decode(payload) payload_bytes = _helpers._urlsafe_b64decode(payload)
try: try:
payload_dict = json.loads(_from_bytes(payload_bytes)) payload_dict = json.loads(_helpers._from_bytes(payload_bytes))
except: except:
raise AppIdentityError('Can\'t parse token: {0}'.format(payload_bytes)) raise AppIdentityError('Can\'t parse token: {0}'.format(payload_bytes))

View File

@@ -21,8 +21,7 @@ credentials.
import os import os
import threading import threading
from oauth2client.client import Credentials from oauth2client import client
from oauth2client.client import Storage as BaseStorage
__author__ = 'jcgregorio@google.com (Joe Gregorio)' __author__ = 'jcgregorio@google.com (Joe Gregorio)'
@@ -32,7 +31,7 @@ class CredentialsFileSymbolicLinkError(Exception):
"""Credentials files must not be symbolic links.""" """Credentials files must not be symbolic links."""
class Storage(BaseStorage): class Storage(client.Storage):
"""Store and retrieve a single credential to and from a file.""" """Store and retrieve a single credential to and from a file."""
def __init__(self, filename): def __init__(self, filename):
@@ -63,7 +62,7 @@ class Storage(BaseStorage):
return credentials return credentials
try: try:
credentials = Credentials.new_from_json(content) credentials = client.Credentials.new_from_json(content)
credentials.set_store(self) credentials.set_store(self)
except ValueError: except ValueError:
pass pass

View File

@@ -20,17 +20,12 @@ import datetime
import json import json
import time import time
import oauth2client
from oauth2client import _helpers
from oauth2client import client
from oauth2client import crypt from oauth2client import crypt
from oauth2client import GOOGLE_REVOKE_URI
from oauth2client import GOOGLE_TOKEN_URI
from oauth2client import transport from oauth2client import transport
from oauth2client import util from oauth2client import util
from oauth2client._helpers import _from_bytes
from oauth2client.client import _UTCNOW
from oauth2client.client import AccessTokenInfo
from oauth2client.client import AssertionCredentials
from oauth2client.client import EXPIRY_FORMAT
from oauth2client.client import SERVICE_ACCOUNT
_PASSWORD_DEFAULT = 'notasecret' _PASSWORD_DEFAULT = 'notasecret'
@@ -45,7 +40,7 @@ to .pem format:
""" """
class ServiceAccountCredentials(AssertionCredentials): class ServiceAccountCredentials(client.AssertionCredentials):
"""Service Account credential for OAuth 2.0 signed JWT grants. """Service Account credential for OAuth 2.0 signed JWT grants.
Supports Supports
@@ -89,7 +84,7 @@ class ServiceAccountCredentials(AssertionCredentials):
NON_SERIALIZED_MEMBERS = ( NON_SERIALIZED_MEMBERS = (
frozenset(['_signer']) | frozenset(['_signer']) |
AssertionCredentials.NON_SERIALIZED_MEMBERS) client.AssertionCredentials.NON_SERIALIZED_MEMBERS)
"""Members that aren't serialized when object is converted to JSON.""" """Members that aren't serialized when object is converted to JSON."""
# Can be over-ridden by factory constructors. Used for # Can be over-ridden by factory constructors. Used for
@@ -105,8 +100,8 @@ class ServiceAccountCredentials(AssertionCredentials):
private_key_id=None, private_key_id=None,
client_id=None, client_id=None,
user_agent=None, user_agent=None,
token_uri=GOOGLE_TOKEN_URI, token_uri=oauth2client.GOOGLE_TOKEN_URI,
revoke_uri=GOOGLE_REVOKE_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI,
**kwargs): **kwargs):
super(ServiceAccountCredentials, self).__init__( super(ServiceAccountCredentials, self).__init__(
@@ -173,18 +168,20 @@ class ServiceAccountCredentials(AssertionCredentials):
the keyfile. the keyfile.
""" """
creds_type = keyfile_dict.get('type') creds_type = keyfile_dict.get('type')
if creds_type != SERVICE_ACCOUNT: if creds_type != client.SERVICE_ACCOUNT:
raise ValueError('Unexpected credentials type', creds_type, raise ValueError('Unexpected credentials type', creds_type,
'Expected', SERVICE_ACCOUNT) 'Expected', client.SERVICE_ACCOUNT)
service_account_email = keyfile_dict['client_email'] service_account_email = keyfile_dict['client_email']
private_key_pkcs8_pem = keyfile_dict['private_key'] private_key_pkcs8_pem = keyfile_dict['private_key']
private_key_id = keyfile_dict['private_key_id'] private_key_id = keyfile_dict['private_key_id']
client_id = keyfile_dict['client_id'] client_id = keyfile_dict['client_id']
if not token_uri: if not token_uri:
token_uri = keyfile_dict.get('token_uri', GOOGLE_TOKEN_URI) token_uri = keyfile_dict.get('token_uri',
oauth2client.GOOGLE_TOKEN_URI)
if not revoke_uri: if not revoke_uri:
revoke_uri = keyfile_dict.get('revoke_uri', GOOGLE_REVOKE_URI) revoke_uri = keyfile_dict.get('revoke_uri',
oauth2client.GOOGLE_REVOKE_URI)
signer = crypt.Signer.from_string(private_key_pkcs8_pem) signer = crypt.Signer.from_string(private_key_pkcs8_pem)
credentials = cls(service_account_email, signer, scopes=scopes, credentials = cls(service_account_email, signer, scopes=scopes,
@@ -260,8 +257,8 @@ class ServiceAccountCredentials(AssertionCredentials):
def _from_p12_keyfile_contents(cls, service_account_email, def _from_p12_keyfile_contents(cls, service_account_email,
private_key_pkcs12, private_key_pkcs12,
private_key_password=None, scopes='', private_key_password=None, scopes='',
token_uri=GOOGLE_TOKEN_URI, token_uri=oauth2client.GOOGLE_TOKEN_URI,
revoke_uri=GOOGLE_REVOKE_URI): revoke_uri=oauth2client.GOOGLE_REVOKE_URI):
"""Factory constructor from JSON keyfile. """Factory constructor from JSON keyfile.
Args: Args:
@@ -302,8 +299,8 @@ class ServiceAccountCredentials(AssertionCredentials):
@classmethod @classmethod
def from_p12_keyfile(cls, service_account_email, filename, def from_p12_keyfile(cls, service_account_email, filename,
private_key_password=None, scopes='', private_key_password=None, scopes='',
token_uri=GOOGLE_TOKEN_URI, token_uri=oauth2client.GOOGLE_TOKEN_URI,
revoke_uri=GOOGLE_REVOKE_URI): revoke_uri=oauth2client.GOOGLE_REVOKE_URI):
"""Factory constructor from JSON keyfile. """Factory constructor from JSON keyfile.
@@ -340,8 +337,8 @@ class ServiceAccountCredentials(AssertionCredentials):
@classmethod @classmethod
def from_p12_keyfile_buffer(cls, service_account_email, file_buffer, def from_p12_keyfile_buffer(cls, service_account_email, file_buffer,
private_key_password=None, scopes='', private_key_password=None, scopes='',
token_uri=GOOGLE_TOKEN_URI, token_uri=oauth2client.GOOGLE_TOKEN_URI,
revoke_uri=GOOGLE_REVOKE_URI): revoke_uri=oauth2client.GOOGLE_REVOKE_URI):
"""Factory constructor from JSON keyfile. """Factory constructor from JSON keyfile.
Args: Args:
@@ -437,7 +434,7 @@ class ServiceAccountCredentials(AssertionCredentials):
ServiceAccountCredentials from the serialized data. ServiceAccountCredentials from the serialized data.
""" """
if not isinstance(json_data, dict): if not isinstance(json_data, dict):
json_data = json.loads(_from_bytes(json_data)) json_data = json.loads(_helpers._from_bytes(json_data))
private_key_pkcs8_pem = None private_key_pkcs8_pem = None
pkcs12_val = json_data.get(_PKCS12_KEY) pkcs12_val = json_data.get(_PKCS12_KEY)
@@ -475,7 +472,7 @@ class ServiceAccountCredentials(AssertionCredentials):
token_expiry = json_data.get('token_expiry', None) token_expiry = json_data.get('token_expiry', None)
if token_expiry is not None: if token_expiry is not None:
credentials.token_expiry = datetime.datetime.strptime( credentials.token_expiry = datetime.datetime.strptime(
token_expiry, EXPIRY_FORMAT) token_expiry, client.EXPIRY_FORMAT)
return credentials return credentials
def create_scoped_required(self): def create_scoped_required(self):
@@ -570,8 +567,8 @@ class _JWTAccessCredentials(ServiceAccountCredentials):
private_key_id=None, private_key_id=None,
client_id=None, client_id=None,
user_agent=None, user_agent=None,
token_uri=GOOGLE_TOKEN_URI, token_uri=oauth2client.GOOGLE_TOKEN_URI,
revoke_uri=GOOGLE_REVOKE_URI, revoke_uri=oauth2client.GOOGLE_REVOKE_URI,
additional_claims=None): additional_claims=None):
if additional_claims is None: if additional_claims is None:
additional_claims = {} additional_claims = {}
@@ -616,13 +613,13 @@ class _JWTAccessCredentials(ServiceAccountCredentials):
if additional_claims is None: if additional_claims is None:
if self.access_token is None or self.access_token_expired: if self.access_token is None or self.access_token_expired:
self.refresh(None) self.refresh(None)
return AccessTokenInfo(access_token=self.access_token, return client.AccessTokenInfo(
expires_in=self._expires_in()) access_token=self.access_token, expires_in=self._expires_in())
else: else:
# Create a 1 time token # Create a 1 time token
token, unused_expiry = self._create_token(additional_claims) token, unused_expiry = self._create_token(additional_claims)
return AccessTokenInfo(access_token=token, return client.AccessTokenInfo(
expires_in=self._MAX_TOKEN_LIFETIME_SECS) access_token=token, expires_in=self._MAX_TOKEN_LIFETIME_SECS)
def revoke(self, http): def revoke(self, http):
"""Cannot revoke JWTAccessCredentials tokens.""" """Cannot revoke JWTAccessCredentials tokens."""
@@ -632,8 +629,8 @@ class _JWTAccessCredentials(ServiceAccountCredentials):
# JWTAccessCredentials are unscoped by definition # JWTAccessCredentials are unscoped by definition
return True return True
def create_scoped(self, scopes, token_uri=GOOGLE_TOKEN_URI, def create_scoped(self, scopes, token_uri=oauth2client.GOOGLE_TOKEN_URI,
revoke_uri=GOOGLE_REVOKE_URI): revoke_uri=oauth2client.GOOGLE_REVOKE_URI):
# Returns an OAuth2 credentials with the given scope # Returns an OAuth2 credentials with the given scope
result = ServiceAccountCredentials(self._service_account_email, result = ServiceAccountCredentials(self._service_account_email,
self._signer, self._signer,
@@ -659,7 +656,7 @@ class _JWTAccessCredentials(ServiceAccountCredentials):
self.access_token, self.token_expiry = self._create_token() self.access_token, self.token_expiry = self._create_token()
def _create_token(self, additional_claims=None): def _create_token(self, additional_claims=None):
now = _UTCNOW() now = client._UTCNOW()
lifetime = datetime.timedelta(seconds=self._MAX_TOKEN_LIFETIME_SECS) lifetime = datetime.timedelta(seconds=self._MAX_TOKEN_LIFETIME_SECS)
expiry = now + lifetime expiry = now + lifetime
payload = { payload = {

View File

@@ -60,7 +60,7 @@ class OAuth2EnabledDecoratorTest(TestWithDjangoEnvironment):
self.assertFalse(request.oauth.has_credentials()) self.assertFalse(request.oauth.has_credentials())
self.assertIsNone(request.oauth.http) self.assertIsNone(request.oauth.http)
@mock.patch('oauth2client.contrib.dictionary_storage.OAuth2Credentials') @mock.patch('oauth2client.client.OAuth2Credentials')
def test_has_credentials_in_storage(self, OAuth2Credentials): def test_has_credentials_in_storage(self, OAuth2Credentials):
request = self.factory.get('/test') request = self.factory.get('/test')
request.session = mock.MagicMock() request.session = mock.MagicMock()
@@ -156,7 +156,7 @@ class OAuth2RequiredDecoratorTest(TestWithDjangoEnvironment):
self.assertEqual(response.status_code, http_client.OK) self.assertEqual(response.status_code, http_client.OK)
self.assertEqual(response.content, b"test") self.assertEqual(response.content, b"test")
@mock.patch('oauth2client.contrib.dictionary_storage.OAuth2Credentials') @mock.patch('oauth2client.client.OAuth2Credentials')
def test_has_credentials_in_storage_no_scopes( def test_has_credentials_in_storage_no_scopes(
self, OAuth2Credentials): self, OAuth2Credentials):
request = self.factory.get('/test') request = self.factory.get('/test')
@@ -176,7 +176,7 @@ class OAuth2RequiredDecoratorTest(TestWithDjangoEnvironment):
self.assertEqual( self.assertEqual(
response.status_code, django.http.HttpResponseRedirect.status_code) response.status_code, django.http.HttpResponseRedirect.status_code)
@mock.patch('oauth2client.contrib.dictionary_storage.OAuth2Credentials') @mock.patch('oauth2client.client.OAuth2Credentials')
def test_specified_scopes(self, OAuth2Credentials): def test_specified_scopes(self, OAuth2Credentials):
request = self.factory.get('/test') request = self.factory.get('/test')
request.session = mock.MagicMock() request.session = mock.MagicMock()

View File

@@ -20,10 +20,8 @@ from google.appengine.ext import testbed
import mock import mock
import unittest2 import unittest2
from oauth2client.client import Credentials from oauth2client import client
from oauth2client.client import flow_from_clientsecrets from oauth2client.contrib import appengine
from oauth2client.contrib.appengine import CredentialsNDBProperty
from oauth2client.contrib.appengine import FlowNDBProperty
DATA_DIR = os.path.join(os.path.dirname(__file__), '..', 'data') DATA_DIR = os.path.join(os.path.dirname(__file__), '..', 'data')
@@ -34,8 +32,8 @@ def datafile(filename):
class TestNDBModel(ndb.Model): class TestNDBModel(ndb.Model):
flow = FlowNDBProperty() flow = appengine.FlowNDBProperty()
creds = CredentialsNDBProperty() creds = appengine.CredentialsNDBProperty()
class TestFlowNDBProperty(unittest2.TestCase): class TestFlowNDBProperty(unittest2.TestCase):
@@ -51,8 +49,8 @@ class TestFlowNDBProperty(unittest2.TestCase):
def test_flow_get_put(self): def test_flow_get_put(self):
instance = TestNDBModel( instance = TestNDBModel(
flow=flow_from_clientsecrets(datafile('client_secrets.json'), flow=client.flow_from_clientsecrets(
'foo', redirect_uri='oob'), datafile('client_secrets.json'), 'foo', redirect_uri='oob'),
id='foo' id='foo'
) )
instance.put() instance.put()
@@ -63,8 +61,8 @@ class TestFlowNDBProperty(unittest2.TestCase):
@mock.patch('oauth2client.contrib._appengine_ndb._LOGGER') @mock.patch('oauth2client.contrib._appengine_ndb._LOGGER')
def test_validate_success(self, mock_logger): def test_validate_success(self, mock_logger):
flow_prop = TestNDBModel.flow flow_prop = TestNDBModel.flow
flow_val = flow_from_clientsecrets(datafile('client_secrets.json'), flow_val = client.flow_from_clientsecrets(
'foo', redirect_uri='oob') datafile('client_secrets.json'), 'foo', redirect_uri='oob')
flow_prop._validate(flow_val) flow_prop._validate(flow_val)
mock_logger.info.assert_called_once_with('validate: Got type %s', mock_logger.info.assert_called_once_with('validate: Got type %s',
type(flow_val)) type(flow_val))
@@ -99,16 +97,16 @@ class TestCredentialsNDBProperty(unittest2.TestCase):
self.testbed.deactivate() self.testbed.deactivate()
def test_valid_creds_get_put(self): def test_valid_creds_get_put(self):
creds = Credentials() creds = client.Credentials()
instance = TestNDBModel(creds=creds, id='bar') instance = TestNDBModel(creds=creds, id='bar')
instance.put() instance.put()
retrieved = TestNDBModel.get_by_id('bar') retrieved = TestNDBModel.get_by_id('bar')
self.assertIsInstance(retrieved.creds, Credentials) self.assertIsInstance(retrieved.creds, client.Credentials)
@mock.patch('oauth2client.contrib._appengine_ndb._LOGGER') @mock.patch('oauth2client.contrib._appengine_ndb._LOGGER')
def test_validate_success(self, mock_logger): def test_validate_success(self, mock_logger):
creds_prop = TestNDBModel.creds creds_prop = TestNDBModel.creds
creds_val = Credentials() creds_val = client.Credentials()
creds_prop._validate(creds_val) creds_prop._validate(creds_val)
mock_logger.info.assert_called_once_with('validate: Got type %s', mock_logger.info.assert_called_once_with('validate: Got type %s',
type(creds_val)) type(creds_val))
@@ -132,7 +130,7 @@ class TestCredentialsNDBProperty(unittest2.TestCase):
def test__to_base_type_valid_creds(self): def test__to_base_type_valid_creds(self):
creds_prop = TestNDBModel.creds creds_prop = TestNDBModel.creds
creds = Credentials() creds = client.Credentials()
creds_json = json.loads(creds_prop._to_base_type(creds)) creds_json = json.loads(creds_prop._to_base_type(creds))
self.assertDictEqual(creds_json, { self.assertDictEqual(creds_json, {
'_class': 'Credentials', '_class': 'Credentials',
@@ -152,7 +150,7 @@ class TestCredentialsNDBProperty(unittest2.TestCase):
'token_expiry': None, 'token_expiry': None,
}) })
creds = creds_prop._from_base_type(creds_json) creds = creds_prop._from_base_type(creds_json)
self.assertIsInstance(creds, Credentials) self.assertIsInstance(creds, client.Credentials)
def test__from_base_type_false_value(self): def test__from_base_type_false_value(self):
creds_prop = TestNDBModel.creds creds_prop = TestNDBModel.creds

View File

@@ -38,27 +38,10 @@ import unittest2
import webapp2 import webapp2
from webtest import TestApp from webtest import TestApp
from oauth2client import GOOGLE_REVOKE_URI import oauth2client
from oauth2client import GOOGLE_TOKEN_URI from oauth2client import client
from oauth2client.client import _CLOUDSDK_CONFIG_ENV_VAR from oauth2client import clientsecrets
from oauth2client.client import AccessTokenRefreshError
from oauth2client.client import Credentials
from oauth2client.client import flow_from_clientsecrets
from oauth2client.client import OAuth2Credentials
from oauth2client.client import save_to_well_known_file
from oauth2client.clientsecrets import _loadfile
from oauth2client.clientsecrets import InvalidClientSecretsError
from oauth2client.clientsecrets import TYPE_WEB
from oauth2client.contrib import appengine from oauth2client.contrib import appengine
from oauth2client.contrib.appengine import AppAssertionCredentials
from oauth2client.contrib.appengine import CredentialsModel
from oauth2client.contrib.appengine import CredentialsNDBModel
from oauth2client.contrib.appengine import CredentialsProperty
from oauth2client.contrib.appengine import FlowProperty
from oauth2client.contrib.appengine import OAuth2Decorator
from oauth2client.contrib.appengine import oauth2decorator_from_clientsecrets
from oauth2client.contrib.appengine import OAuth2DecoratorFromClientSecrets
from oauth2client.contrib.appengine import StorageByKeyName
from ..http_mock import CacheMock from ..http_mock import CacheMock
__author__ = 'jcgregorio@google.com (Joe Gregorio)' __author__ = 'jcgregorio@google.com (Joe Gregorio)'
@@ -71,7 +54,7 @@ def datafile(filename):
def load_and_cache(existing_file, fakename, cache_mock): def load_and_cache(existing_file, fakename, cache_mock):
client_type, client_info = _loadfile(datafile(existing_file)) client_type, client_info = clientsecrets._loadfile(datafile(existing_file))
cache_mock.cache[fakename] = {client_type: client_info} cache_mock.cache[fakename] = {client_type: client_info}
@@ -155,9 +138,9 @@ class TestAppAssertionCredentials(unittest2.TestCase):
'memcache', memcache_stub.MemcacheServiceStub()) 'memcache', memcache_stub.MemcacheServiceStub())
scope = 'http://www.googleapis.com/scope' scope = 'http://www.googleapis.com/scope'
credentials = AppAssertionCredentials(scope) credentials = appengine.AppAssertionCredentials(scope)
http = httplib2.Http() http = httplib2.Http()
with self.assertRaises(AccessTokenRefreshError): with self.assertRaises(client.AccessTokenRefreshError):
credentials.refresh(http) credentials.refresh(http)
def test_get_access_token_on_refresh(self): def test_get_access_token_on_refresh(self):
@@ -171,20 +154,20 @@ class TestAppAssertionCredentials(unittest2.TestCase):
scope = [ scope = [
"http://www.googleapis.com/scope", "http://www.googleapis.com/scope",
"http://www.googleapis.com/scope2"] "http://www.googleapis.com/scope2"]
credentials = AppAssertionCredentials(scope) credentials = appengine.AppAssertionCredentials(scope)
http = httplib2.Http() http = httplib2.Http()
credentials.refresh(http) credentials.refresh(http)
self.assertEqual('a_token_123', credentials.access_token) self.assertEqual('a_token_123', credentials.access_token)
json = credentials.to_json() json = credentials.to_json()
credentials = Credentials.new_from_json(json) credentials = client.Credentials.new_from_json(json)
self.assertEqual( self.assertEqual(
'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 ' scope = ('http://www.googleapis.com/scope '
'http://www.googleapis.com/scope2') 'http://www.googleapis.com/scope2')
credentials = AppAssertionCredentials(scope) credentials = appengine.AppAssertionCredentials(scope)
http = httplib2.Http() http = httplib2.Http()
credentials.refresh(http) credentials.refresh(http)
self.assertEqual('a_token_123', credentials.access_token) self.assertEqual('a_token_123', credentials.access_token)
@@ -199,7 +182,7 @@ class TestAppAssertionCredentials(unittest2.TestCase):
with mock.patch.object(app_identity, 'get_access_token', with mock.patch.object(app_identity, 'get_access_token',
return_value=('a_token_456', None), return_value=('a_token_456', None),
autospec=True) as get_access_token: autospec=True) as get_access_token:
credentials = AppAssertionCredentials( credentials = appengine.AppAssertionCredentials(
scope, service_account_id=account_id) scope, service_account_id=account_id)
http = httplib2.Http() http = httplib2.Http()
credentials.refresh(http) credentials.refresh(http)
@@ -210,18 +193,19 @@ class TestAppAssertionCredentials(unittest2.TestCase):
[scope], service_account_id=account_id) [scope], service_account_id=account_id)
def test_create_scoped_required_without_scopes(self): def test_create_scoped_required_without_scopes(self):
credentials = AppAssertionCredentials([]) credentials = appengine.AppAssertionCredentials([])
self.assertTrue(credentials.create_scoped_required()) self.assertTrue(credentials.create_scoped_required())
def test_create_scoped_required_with_scopes(self): def test_create_scoped_required_with_scopes(self):
credentials = AppAssertionCredentials(['dummy_scope']) credentials = appengine.AppAssertionCredentials(['dummy_scope'])
self.assertFalse(credentials.create_scoped_required()) self.assertFalse(credentials.create_scoped_required())
def test_create_scoped(self): def test_create_scoped(self):
credentials = AppAssertionCredentials([]) credentials = appengine.AppAssertionCredentials([])
new_credentials = credentials.create_scoped(['dummy_scope']) new_credentials = credentials.create_scoped(['dummy_scope'])
self.assertNotEqual(credentials, new_credentials) self.assertNotEqual(credentials, new_credentials)
self.assertIsInstance(new_credentials, AppAssertionCredentials) self.assertIsInstance(
new_credentials, appengine.AppAssertionCredentials)
self.assertEqual('dummy_scope', new_credentials.scope) self.assertEqual('dummy_scope', new_credentials.scope)
def test_sign_blob(self): def test_sign_blob(self):
@@ -232,7 +216,7 @@ class TestAppAssertionCredentials(unittest2.TestCase):
apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap() apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
apiproxy_stub_map.apiproxy.RegisterStub('app_identity_service', apiproxy_stub_map.apiproxy.RegisterStub('app_identity_service',
app_identity_stub) app_identity_stub)
credentials = AppAssertionCredentials([]) credentials = appengine.AppAssertionCredentials([])
to_sign = b'blob' to_sign = b'blob'
self.assertEqual(app_identity_stub._sign_calls, []) self.assertEqual(app_identity_stub._sign_calls, [])
result = credentials.sign_blob(to_sign) result = credentials.sign_blob(to_sign)
@@ -246,7 +230,7 @@ class TestAppAssertionCredentials(unittest2.TestCase):
apiproxy_stub_map.apiproxy.RegisterStub('app_identity_service', apiproxy_stub_map.apiproxy.RegisterStub('app_identity_service',
app_identity_stub) app_identity_stub)
credentials = AppAssertionCredentials([]) credentials = appengine.AppAssertionCredentials([])
self.assertIsNone(credentials._service_account_email) self.assertIsNone(credentials._service_account_email)
self.assertEqual(app_identity_stub._get_acct_name_calls, 0) self.assertEqual(app_identity_stub._get_acct_name_calls, 0)
self.assertEqual(credentials.service_account_email, acct_name) self.assertEqual(credentials.service_account_email, acct_name)
@@ -255,7 +239,7 @@ class TestAppAssertionCredentials(unittest2.TestCase):
def test_service_account_email_already_set(self): def test_service_account_email_already_set(self):
acct_name = 'existing@appspot.gserviceaccount.com' acct_name = 'existing@appspot.gserviceaccount.com'
credentials = AppAssertionCredentials([]) credentials = appengine.AppAssertionCredentials([])
credentials._service_account_email = acct_name credentials._service_account_email = acct_name
app_identity_stub = self.AppIdentityStubImpl(svc_acct=acct_name) app_identity_stub = self.AppIdentityStubImpl(svc_acct=acct_name)
@@ -275,21 +259,21 @@ class TestAppAssertionCredentials(unittest2.TestCase):
apiproxy_stub_map.apiproxy.RegisterStub( apiproxy_stub_map.apiproxy.RegisterStub(
'memcache', memcache_stub.MemcacheServiceStub()) 'memcache', memcache_stub.MemcacheServiceStub())
credentials = AppAssertionCredentials(['dummy_scope']) credentials = appengine.AppAssertionCredentials(['dummy_scope'])
token = credentials.get_access_token() token = credentials.get_access_token()
self.assertEqual('a_token_123', token.access_token) self.assertEqual('a_token_123', token.access_token)
self.assertEqual(None, token.expires_in) self.assertEqual(None, token.expires_in)
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[client._CLOUDSDK_CONFIG_ENV_VAR] = tempfile.mkdtemp()
credentials = AppAssertionCredentials([]) credentials = appengine.AppAssertionCredentials([])
with self.assertRaises(NotImplementedError): with self.assertRaises(NotImplementedError):
save_to_well_known_file(credentials) client.save_to_well_known_file(credentials)
del os.environ[_CLOUDSDK_CONFIG_ENV_VAR] del os.environ[client._CLOUDSDK_CONFIG_ENV_VAR]
class TestFlowModel(db.Model): class TestFlowModel(db.Model):
flow = FlowProperty() flow = appengine.FlowProperty()
class FlowPropertyTest(unittest2.TestCase): class FlowPropertyTest(unittest2.TestCase):
@@ -299,7 +283,7 @@ class FlowPropertyTest(unittest2.TestCase):
self.testbed.activate() self.testbed.activate()
self.testbed.init_datastore_v3_stub() self.testbed.init_datastore_v3_stub()
self.flow = flow_from_clientsecrets( self.flow = client.flow_from_clientsecrets(
datafile('client_secrets.json'), datafile('client_secrets.json'),
'foo', 'foo',
redirect_uri='oob') redirect_uri='oob')
@@ -318,16 +302,17 @@ class FlowPropertyTest(unittest2.TestCase):
self.assertEqual('foo_client_id', retrieved.flow.client_id) self.assertEqual('foo_client_id', retrieved.flow.client_id)
def test_make_value_from_datastore_none(self): def test_make_value_from_datastore_none(self):
self.assertIsNone(FlowProperty().make_value_from_datastore(None)) self.assertIsNone(
appengine.FlowProperty().make_value_from_datastore(None))
def test_validate(self): def test_validate(self):
FlowProperty().validate(None) appengine.FlowProperty().validate(None)
with self.assertRaises(db.BadValueError): with self.assertRaises(db.BadValueError):
FlowProperty().validate(42) appengine.FlowProperty().validate(42)
class TestCredentialsModel(db.Model): class TestCredentialsModel(db.Model):
credentials = CredentialsProperty() credentials = appengine.CredentialsProperty()
class CredentialsPropertyTest(unittest2.TestCase): class CredentialsPropertyTest(unittest2.TestCase):
@@ -343,9 +328,9 @@ class CredentialsPropertyTest(unittest2.TestCase):
refresh_token = '1/0/a.df219fjls0' refresh_token = '1/0/a.df219fjls0'
token_expiry = datetime.datetime.utcnow() token_expiry = datetime.datetime.utcnow()
user_agent = 'refresh_checker/1.0' user_agent = 'refresh_checker/1.0'
self.credentials = OAuth2Credentials( self.credentials = client.OAuth2Credentials(
access_token, client_id, client_secret, access_token, client_id, client_secret,
refresh_token, token_expiry, GOOGLE_TOKEN_URI, refresh_token, token_expiry, oauth2client.GOOGLE_TOKEN_URI,
user_agent) user_agent)
def tearDown(self): def tearDown(self):
@@ -365,23 +350,23 @@ class CredentialsPropertyTest(unittest2.TestCase):
def test_make_value_from_datastore(self): def test_make_value_from_datastore(self):
self.assertIsNone( self.assertIsNone(
CredentialsProperty().make_value_from_datastore(None)) appengine.CredentialsProperty().make_value_from_datastore(None))
self.assertIsNone( self.assertIsNone(
CredentialsProperty().make_value_from_datastore('')) appengine.CredentialsProperty().make_value_from_datastore(''))
self.assertIsNone( self.assertIsNone(
CredentialsProperty().make_value_from_datastore('{')) appengine.CredentialsProperty().make_value_from_datastore('{'))
decoded = CredentialsProperty().make_value_from_datastore( decoded = appengine.CredentialsProperty().make_value_from_datastore(
self.credentials.to_json()) self.credentials.to_json())
self.assertEqual( self.assertEqual(
self.credentials.to_json(), self.credentials.to_json(),
decoded.to_json()) decoded.to_json())
def test_validate(self): def test_validate(self):
CredentialsProperty().validate(self.credentials) appengine.CredentialsProperty().validate(self.credentials)
CredentialsProperty().validate(None) appengine.CredentialsProperty().validate(None)
with self.assertRaises(db.BadValueError): with self.assertRaises(db.BadValueError):
CredentialsProperty().validate(42) appengine.CredentialsProperty().validate(42)
def _http_request(*args, **kwargs): def _http_request(*args, **kwargs):
@@ -406,9 +391,9 @@ class StorageByKeyNameTest(unittest2.TestCase):
refresh_token = '1/0/a.df219fjls0' refresh_token = '1/0/a.df219fjls0'
token_expiry = datetime.datetime.utcnow() token_expiry = datetime.datetime.utcnow()
user_agent = 'refresh_checker/1.0' user_agent = 'refresh_checker/1.0'
self.credentials = OAuth2Credentials( self.credentials = client.OAuth2Credentials(
access_token, client_id, client_secret, access_token, client_id, client_secret,
refresh_token, token_expiry, GOOGLE_TOKEN_URI, refresh_token, token_expiry, oauth2client.GOOGLE_TOKEN_URI,
user_agent) user_agent)
def tearDown(self): def tearDown(self):
@@ -416,10 +401,10 @@ class StorageByKeyNameTest(unittest2.TestCase):
def test_bad_ctor(self): def test_bad_ctor(self):
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
StorageByKeyName(CredentialsModel, None, None) appengine.StorageByKeyName(appengine.CredentialsModel, None, None)
def test__is_ndb(self): def test__is_ndb(self):
storage = StorageByKeyName( storage = appengine.StorageByKeyName(
object(), 'foo', 'credentials') object(), 'foo', 'credentials')
with self.assertRaises(TypeError): with self.assertRaises(TypeError):
@@ -429,32 +414,32 @@ class StorageByKeyNameTest(unittest2.TestCase):
with self.assertRaises(TypeError): with self.assertRaises(TypeError):
storage._is_ndb() storage._is_ndb()
storage._model = CredentialsModel storage._model = appengine.CredentialsModel
self.assertFalse(storage._is_ndb()) self.assertFalse(storage._is_ndb())
storage._model = CredentialsNDBModel storage._model = appengine.CredentialsNDBModel
self.assertTrue(storage._is_ndb()) self.assertTrue(storage._is_ndb())
def test_get_and_put_simple(self): def test_get_and_put_simple(self):
storage = StorageByKeyName( storage = appengine.StorageByKeyName(
CredentialsModel, 'foo', 'credentials') appengine.CredentialsModel, 'foo', 'credentials')
self.assertEqual(None, storage.get()) self.assertEqual(None, storage.get())
self.credentials.set_store(storage) self.credentials.set_store(storage)
self.credentials._refresh(_http_request) self.credentials._refresh(_http_request)
credmodel = CredentialsModel.get_by_key_name('foo') credmodel = appengine.CredentialsModel.get_by_key_name('foo')
self.assertEqual('bar', credmodel.credentials.access_token) self.assertEqual('bar', credmodel.credentials.access_token)
def test_get_and_put_cached(self): def test_get_and_put_cached(self):
storage = StorageByKeyName( storage = appengine.StorageByKeyName(
CredentialsModel, 'foo', 'credentials', cache=memcache) appengine.CredentialsModel, 'foo', 'credentials', cache=memcache)
self.assertEqual(None, storage.get()) self.assertEqual(None, storage.get())
self.credentials.set_store(storage) self.credentials.set_store(storage)
self.credentials._refresh(_http_request) self.credentials._refresh(_http_request)
credmodel = CredentialsModel.get_by_key_name('foo') credmodel = appengine.CredentialsModel.get_by_key_name('foo')
self.assertEqual('bar', credmodel.credentials.access_token) self.assertEqual('bar', credmodel.credentials.access_token)
# Now remove the item from the cache. # Now remove the item from the cache.
@@ -472,8 +457,8 @@ class StorageByKeyNameTest(unittest2.TestCase):
self.assertEqual(None, memcache.get('foo')) self.assertEqual(None, memcache.get('foo'))
def test_get_and_put_set_store_on_cache_retrieval(self): def test_get_and_put_set_store_on_cache_retrieval(self):
storage = StorageByKeyName( storage = appengine.StorageByKeyName(
CredentialsModel, 'foo', 'credentials', cache=memcache) appengine.CredentialsModel, 'foo', 'credentials', cache=memcache)
self.assertEqual(None, storage.get()) self.assertEqual(None, storage.get())
self.credentials.set_store(storage) self.credentials.set_store(storage)
@@ -489,28 +474,28 @@ class StorageByKeyNameTest(unittest2.TestCase):
def test_get_and_put_ndb(self): def test_get_and_put_ndb(self):
# Start empty # Start empty
storage = StorageByKeyName( storage = appengine.StorageByKeyName(
CredentialsNDBModel, 'foo', 'credentials') appengine.CredentialsNDBModel, 'foo', 'credentials')
self.assertEqual(None, storage.get()) self.assertEqual(None, storage.get())
# Refresh storage and retrieve without using storage # Refresh storage and retrieve without using storage
self.credentials.set_store(storage) self.credentials.set_store(storage)
self.credentials._refresh(_http_request) self.credentials._refresh(_http_request)
credmodel = CredentialsNDBModel.get_by_id('foo') credmodel = appengine.CredentialsNDBModel.get_by_id('foo')
self.assertEqual('bar', credmodel.credentials.access_token) self.assertEqual('bar', credmodel.credentials.access_token)
self.assertEqual(credmodel.credentials.to_json(), self.assertEqual(credmodel.credentials.to_json(),
self.credentials.to_json()) self.credentials.to_json())
def test_delete_ndb(self): def test_delete_ndb(self):
# Start empty # Start empty
storage = StorageByKeyName( storage = appengine.StorageByKeyName(
CredentialsNDBModel, 'foo', 'credentials') appengine.CredentialsNDBModel, 'foo', 'credentials')
self.assertEqual(None, storage.get()) self.assertEqual(None, storage.get())
# Add credentials to model with storage, and check equivalent # Add credentials to model with storage, and check equivalent
# w/o storage # w/o storage
storage.put(self.credentials) storage.put(self.credentials)
credmodel = CredentialsNDBModel.get_by_id('foo') credmodel = appengine.CredentialsNDBModel.get_by_id('foo')
self.assertEqual(credmodel.credentials.to_json(), self.assertEqual(credmodel.credentials.to_json(),
self.credentials.to_json()) self.credentials.to_json())
@@ -520,8 +505,8 @@ class StorageByKeyNameTest(unittest2.TestCase):
def test_get_and_put_mixed_ndb_storage_db_get(self): def test_get_and_put_mixed_ndb_storage_db_get(self):
# Start empty # Start empty
storage = StorageByKeyName( storage = appengine.StorageByKeyName(
CredentialsNDBModel, 'foo', 'credentials') appengine.CredentialsNDBModel, 'foo', 'credentials')
self.assertEqual(None, storage.get()) self.assertEqual(None, storage.get())
# Set NDB store and refresh to add to storage # Set NDB store and refresh to add to storage
@@ -529,15 +514,15 @@ class StorageByKeyNameTest(unittest2.TestCase):
self.credentials._refresh(_http_request) self.credentials._refresh(_http_request)
# Retrieve same key from DB model to confirm mixing works # Retrieve same key from DB model to confirm mixing works
credmodel = CredentialsModel.get_by_key_name('foo') credmodel = appengine.CredentialsModel.get_by_key_name('foo')
self.assertEqual('bar', credmodel.credentials.access_token) self.assertEqual('bar', credmodel.credentials.access_token)
self.assertEqual(self.credentials.to_json(), self.assertEqual(self.credentials.to_json(),
credmodel.credentials.to_json()) credmodel.credentials.to_json())
def test_get_and_put_mixed_db_storage_ndb_get(self): def test_get_and_put_mixed_db_storage_ndb_get(self):
# Start empty # Start empty
storage = StorageByKeyName( storage = appengine.StorageByKeyName(
CredentialsModel, 'foo', 'credentials') appengine.CredentialsModel, 'foo', 'credentials')
self.assertEqual(None, storage.get()) self.assertEqual(None, storage.get())
# Set DB store and refresh to add to storage # Set DB store and refresh to add to storage
@@ -545,17 +530,17 @@ class StorageByKeyNameTest(unittest2.TestCase):
self.credentials._refresh(_http_request) self.credentials._refresh(_http_request)
# Retrieve same key from NDB model to confirm mixing works # Retrieve same key from NDB model to confirm mixing works
credmodel = CredentialsNDBModel.get_by_id('foo') credmodel = appengine.CredentialsNDBModel.get_by_id('foo')
self.assertEqual('bar', credmodel.credentials.access_token) self.assertEqual('bar', credmodel.credentials.access_token)
self.assertEqual(self.credentials.to_json(), self.assertEqual(self.credentials.to_json(),
credmodel.credentials.to_json()) credmodel.credentials.to_json())
def test_delete_db_ndb_mixed(self): def test_delete_db_ndb_mixed(self):
# Start empty # Start empty
storage_ndb = StorageByKeyName( storage_ndb = appengine.StorageByKeyName(
CredentialsNDBModel, 'foo', 'credentials') appengine.CredentialsNDBModel, 'foo', 'credentials')
storage = StorageByKeyName( storage = appengine.StorageByKeyName(
CredentialsModel, 'foo', 'credentials') appengine.CredentialsModel, 'foo', 'credentials')
# First DB, then NDB # First DB, then NDB
self.assertEqual(None, storage.get()) self.assertEqual(None, storage.get())
@@ -597,10 +582,9 @@ class DecoratorTests(unittest2.TestCase):
self.testbed.init_memcache_stub() self.testbed.init_memcache_stub()
self.testbed.init_user_stub() self.testbed.init_user_stub()
decorator = OAuth2Decorator(client_id='foo_client_id', decorator = appengine.OAuth2Decorator(
client_secret='foo_client_secret', client_id='foo_client_id', client_secret='foo_client_secret',
scope=['foo_scope', 'bar_scope'], scope=['foo_scope', 'bar_scope'], user_agent='foo')
user_agent='foo')
self._finish_setup(decorator, user_mock=UserMock) self._finish_setup(decorator, user_mock=UserMock)
@@ -731,7 +715,7 @@ class DecoratorTests(unittest2.TestCase):
self.assertEqual(None, self.decorator.credentials) self.assertEqual(None, self.decorator.credentials)
# Access token refresh error should start the dance again # Access token refresh error should start the dance again
self.should_raise = AccessTokenRefreshError() self.should_raise = client.AccessTokenRefreshError()
response = self.app.get('/foo_path') response = self.app.get('/foo_path')
self.should_raise = False self.should_raise = False
self.assertTrue(response.status.startswith('302')) self.assertTrue(response.status.startswith('302'))
@@ -853,13 +837,11 @@ class DecoratorTests(unittest2.TestCase):
self.assertTrue('Bad&lt;Stuff&gt;Happened&#39;' in response.body) self.assertTrue('Bad&lt;Stuff&gt;Happened&#39;' in response.body)
def test_kwargs_are_passed_to_underlying_flow(self): def test_kwargs_are_passed_to_underlying_flow(self):
decorator = OAuth2Decorator(client_id='foo_client_id', decorator = appengine.OAuth2Decorator(
client_secret='foo_client_secret', client_id='foo_client_id', client_secret='foo_client_secret',
user_agent='foo_user_agent', user_agent='foo_user_agent', scope=['foo_scope', 'bar_scope'],
scope=['foo_scope', 'bar_scope'], access_type='offline', approval_prompt='force',
access_type='offline', revoke_uri='dummy_revoke_uri')
approval_prompt='force',
revoke_uri='dummy_revoke_uri')
request_handler = MockRequestHandler() request_handler = MockRequestHandler()
decorator._create_flow(request_handler) decorator._create_flow(request_handler)
@@ -877,7 +859,7 @@ class DecoratorTests(unittest2.TestCase):
self.test_required() self.test_required()
def test_decorator_from_client_secrets(self): def test_decorator_from_client_secrets(self):
decorator = OAuth2DecoratorFromClientSecrets( decorator = appengine.OAuth2DecoratorFromClientSecrets(
datafile('client_secrets.json'), datafile('client_secrets.json'),
scope=['foo_scope', 'bar_scope']) scope=['foo_scope', 'bar_scope'])
self._finish_setup(decorator, user_mock=UserMock) self._finish_setup(decorator, user_mock=UserMock)
@@ -901,7 +883,8 @@ class DecoratorTests(unittest2.TestCase):
with decorator_patch as decorator_mock: with decorator_patch as decorator_mock:
filename = datafile('client_secrets.json') filename = datafile('client_secrets.json')
oauth2decorator_from_clientsecrets(filename, scope='foo_scope') appengine.oauth2decorator_from_clientsecrets(
filename, scope='foo_scope')
decorator_mock.assert_called_once_with( decorator_mock.assert_called_once_with(
filename, filename,
'foo_scope', 'foo_scope',
@@ -919,13 +902,13 @@ class DecoratorTests(unittest2.TestCase):
'oauth2client.contrib.appengine.clientsecrets.loadfile') 'oauth2client.contrib.appengine.clientsecrets.loadfile')
with loadfile_patch as loadfile_mock: with loadfile_patch as loadfile_mock:
loadfile_mock.return_value = ('badtype', None) loadfile_mock.return_value = ('badtype', None)
with self.assertRaises(InvalidClientSecretsError): with self.assertRaises(clientsecrets.InvalidClientSecretsError):
OAuth2DecoratorFromClientSecrets( appengine.OAuth2DecoratorFromClientSecrets(
'doesntmatter.json', 'doesntmatter.json',
scope=['foo_scope', 'bar_scope']) scope=['foo_scope', 'bar_scope'])
def test_decorator_from_client_secrets_kwargs(self): def test_decorator_from_client_secrets_kwargs(self):
decorator = OAuth2DecoratorFromClientSecrets( decorator = appengine.OAuth2DecoratorFromClientSecrets(
datafile('client_secrets.json'), datafile('client_secrets.json'),
scope=['foo_scope', 'bar_scope'], scope=['foo_scope', 'bar_scope'],
approval_prompt='force') approval_prompt='force')
@@ -934,13 +917,13 @@ class DecoratorTests(unittest2.TestCase):
def test_decorator_from_cached_client_secrets(self): def test_decorator_from_cached_client_secrets(self):
cache_mock = CacheMock() cache_mock = CacheMock()
load_and_cache('client_secrets.json', 'secret', cache_mock) load_and_cache('client_secrets.json', 'secret', cache_mock)
decorator = OAuth2DecoratorFromClientSecrets( decorator = appengine.OAuth2DecoratorFromClientSecrets(
# filename, scope, message=None, cache=None # filename, scope, message=None, cache=None
'secret', '', cache=cache_mock) 'secret', '', cache=cache_mock)
self.assertFalse(decorator._in_error) self.assertFalse(decorator._in_error)
def test_decorator_from_client_secrets_not_logged_in_required(self): def test_decorator_from_client_secrets_not_logged_in_required(self):
decorator = OAuth2DecoratorFromClientSecrets( decorator = appengine.OAuth2DecoratorFromClientSecrets(
datafile('client_secrets.json'), datafile('client_secrets.json'),
scope=['foo_scope', 'bar_scope'], message='NotLoggedInMessage') scope=['foo_scope', 'bar_scope'], message='NotLoggedInMessage')
self.decorator = decorator self.decorator = decorator
@@ -955,7 +938,7 @@ class DecoratorTests(unittest2.TestCase):
self.assertTrue('Login' in str(response)) self.assertTrue('Login' in str(response))
def test_decorator_from_client_secrets_not_logged_in_aware(self): def test_decorator_from_client_secrets_not_logged_in_aware(self):
decorator = OAuth2DecoratorFromClientSecrets( decorator = appengine.OAuth2DecoratorFromClientSecrets(
datafile('client_secrets.json'), datafile('client_secrets.json'),
scope=['foo_scope', 'bar_scope'], message='NotLoggedInMessage') scope=['foo_scope', 'bar_scope'], message='NotLoggedInMessage')
self.decorator = decorator self.decorator = decorator
@@ -970,19 +953,19 @@ class DecoratorTests(unittest2.TestCase):
def test_decorator_from_unfilled_client_secrets_required(self): def test_decorator_from_unfilled_client_secrets_required(self):
MESSAGE = 'File is missing' MESSAGE = 'File is missing'
try: try:
OAuth2DecoratorFromClientSecrets( appengine.OAuth2DecoratorFromClientSecrets(
datafile('unfilled_client_secrets.json'), datafile('unfilled_client_secrets.json'),
scope=['foo_scope', 'bar_scope'], message=MESSAGE) scope=['foo_scope', 'bar_scope'], message=MESSAGE)
except InvalidClientSecretsError: except clientsecrets.InvalidClientSecretsError:
pass pass
def test_decorator_from_unfilled_client_secrets_aware(self): def test_decorator_from_unfilled_client_secrets_aware(self):
MESSAGE = 'File is missing' MESSAGE = 'File is missing'
try: try:
OAuth2DecoratorFromClientSecrets( appengine.OAuth2DecoratorFromClientSecrets(
datafile('unfilled_client_secrets.json'), datafile('unfilled_client_secrets.json'),
scope=['foo_scope', 'bar_scope'], message=MESSAGE) scope=['foo_scope', 'bar_scope'], message=MESSAGE)
except InvalidClientSecretsError: except clientsecrets.InvalidClientSecretsError:
pass pass
def test_decorator_from_client_secrets_with_optional_settings(self): def test_decorator_from_client_secrets_with_optional_settings(self):
@@ -991,7 +974,7 @@ class DecoratorTests(unittest2.TestCase):
loadfile_patch = mock.patch( loadfile_patch = mock.patch(
'oauth2client.contrib.appengine.clientsecrets.loadfile') 'oauth2client.contrib.appengine.clientsecrets.loadfile')
with loadfile_patch as loadfile_mock: with loadfile_patch as loadfile_mock:
loadfile_mock.return_value = (TYPE_WEB, { loadfile_mock.return_value = (clientsecrets.TYPE_WEB, {
"client_id": "foo_client_id", "client_id": "foo_client_id",
"client_secret": "foo_client_secret", "client_secret": "foo_client_secret",
"redirect_uris": [], "redirect_uris": [],
@@ -1000,11 +983,11 @@ class DecoratorTests(unittest2.TestCase):
# No revoke URI # No revoke URI
}) })
decorator = OAuth2DecoratorFromClientSecrets( decorator = appengine.OAuth2DecoratorFromClientSecrets(
'doesntmatter.json', 'doesntmatter.json',
scope=['foo_scope', 'bar_scope']) scope=['foo_scope', 'bar_scope'])
self.assertEqual(decorator._revoke_uri, GOOGLE_REVOKE_URI) self.assertEqual(decorator._revoke_uri, oauth2client.GOOGLE_REVOKE_URI)
# This is never set, but it's consistent with other tests. # This is never set, but it's consistent with other tests.
self.assertFalse(decorator._in_error) self.assertFalse(decorator._in_error)

View File

@@ -23,17 +23,9 @@ import threading
import mock import mock
import unittest2 import unittest2
from oauth2client._helpers import _from_bytes from oauth2client import _helpers
from oauth2client._helpers import _to_bytes from oauth2client import client
from oauth2client.client import save_to_well_known_file
from oauth2client.contrib import devshell from oauth2client.contrib import devshell
from oauth2client.contrib.devshell import _SendRecv
from oauth2client.contrib.devshell import CommunicationError
from oauth2client.contrib.devshell import CREDENTIAL_INFO_REQUEST_JSON
from oauth2client.contrib.devshell import CredentialInfoResponse
from oauth2client.contrib.devshell import DEVSHELL_ENV
from oauth2client.contrib.devshell import DevshellCredentials
from oauth2client.contrib.devshell import NoDevshellServer
# A dummy value to use for the expires_in field # A dummy value to use for the expires_in field
# in CredentialInfoResponse. # in CredentialInfoResponse.
@@ -51,15 +43,15 @@ class TestCredentialInfoResponse(unittest2.TestCase):
def test_constructor_with_non_list(self): def test_constructor_with_non_list(self):
json_non_list = '{}' json_non_list = '{}'
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
CredentialInfoResponse(json_non_list) devshell.CredentialInfoResponse(json_non_list)
def test_constructor_with_bad_json(self): def test_constructor_with_bad_json(self):
json_non_list = '{BADJSON' json_non_list = '{BADJSON'
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
CredentialInfoResponse(json_non_list) devshell.CredentialInfoResponse(json_non_list)
def test_constructor_empty_list(self): def test_constructor_empty_list(self):
info_response = CredentialInfoResponse('[]') info_response = devshell.CredentialInfoResponse('[]')
self.assertEqual(info_response.user_email, None) self.assertEqual(info_response.user_email, None)
self.assertEqual(info_response.project_id, None) self.assertEqual(info_response.project_id, None)
self.assertEqual(info_response.access_token, None) self.assertEqual(info_response.access_token, None)
@@ -72,7 +64,7 @@ class TestCredentialInfoResponse(unittest2.TestCase):
expires_in = 1 expires_in = 1
json_string = json.dumps( json_string = json.dumps(
[user_email, project_id, access_token, expires_in]) [user_email, project_id, access_token, expires_in])
info_response = CredentialInfoResponse(json_string) info_response = devshell.CredentialInfoResponse(json_string)
self.assertEqual(info_response.user_email, user_email) self.assertEqual(info_response.user_email, user_email)
self.assertEqual(info_response.project_id, project_id) self.assertEqual(info_response.project_id, project_id)
self.assertEqual(info_response.access_token, access_token) self.assertEqual(info_response.access_token, access_token)
@@ -84,9 +76,9 @@ class Test_SendRecv(unittest2.TestCase):
def test_port_zero(self): def test_port_zero(self):
with mock.patch('oauth2client.contrib.devshell.os') as os_mod: with mock.patch('oauth2client.contrib.devshell.os') as os_mod:
os_mod.getenv = mock.MagicMock(name='getenv', return_value=0) os_mod.getenv = mock.MagicMock(name='getenv', return_value=0)
with self.assertRaises(NoDevshellServer): with self.assertRaises(devshell.NoDevshellServer):
_SendRecv() devshell._SendRecv()
os_mod.getenv.assert_called_once_with(DEVSHELL_ENV, 0) os_mod.getenv.assert_called_once_with(devshell.DEVSHELL_ENV, 0)
def test_no_newline_in_received_header(self): def test_no_newline_in_received_header(self):
non_zero_port = 1 non_zero_port = 1
@@ -102,15 +94,15 @@ class Test_SendRecv(unittest2.TestCase):
with mock.patch('oauth2client.contrib.devshell.socket') as socket: with mock.patch('oauth2client.contrib.devshell.socket') as socket:
socket.socket = mock.MagicMock(name='socket', socket.socket = mock.MagicMock(name='socket',
return_value=sock) return_value=sock)
with self.assertRaises(CommunicationError): with self.assertRaises(devshell.CommunicationError):
_SendRecv() devshell._SendRecv()
os_mod.getenv.assert_called_once_with(DEVSHELL_ENV, 0) os_mod.getenv.assert_called_once_with(devshell.DEVSHELL_ENV, 0)
socket.socket.assert_called_once_with() socket.socket.assert_called_once_with()
sock.recv(6).decode.assert_called_once_with() sock.recv(6).decode.assert_called_once_with()
data = CREDENTIAL_INFO_REQUEST_JSON data = devshell.CREDENTIAL_INFO_REQUEST_JSON
msg = _to_bytes('{0}\n{1}'.format(len(data), data), msg = _helpers._to_bytes(
encoding='utf-8') '{0}\n{1}'.format(len(data), data), encoding='utf-8')
expected_sock_calls = [ expected_sock_calls = [
mock.call.recv(6), # From the set-up above mock.call.recv(6), # From the set-up above
mock.call.connect(('localhost', non_zero_port)), mock.call.connect(('localhost', non_zero_port)),
@@ -135,7 +127,7 @@ class _AuthReferenceServer(threading.Thread):
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._socket.bind(('localhost', 0)) self._socket.bind(('localhost', 0))
port = self._socket.getsockname()[1] port = self._socket.getsockname()[1]
os.environ[DEVSHELL_ENV] = str(port) os.environ[devshell.DEVSHELL_ENV] = str(port)
self._socket.listen(0) self._socket.listen(0)
self.daemon = True self.daemon = True
self.start() self.start()
@@ -145,7 +137,7 @@ class _AuthReferenceServer(threading.Thread):
self.stop_server() self.stop_server()
def stop_server(self): def stop_server(self):
del os.environ[DEVSHELL_ENV] del os.environ[devshell.DEVSHELL_ENV]
self._socket.close() self._socket.close()
def run(self): def run(self):
@@ -164,8 +156,9 @@ class _AuthReferenceServer(threading.Thread):
n = int(nstr) n = int(nstr)
to_read = n - len(extra) to_read = n - len(extra)
if to_read > 0: if to_read > 0:
resp_buffer += _from_bytes(s.recv(to_read, socket.MSG_WAITALL)) resp_buffer += _helpers._from_bytes(
if resp_buffer != CREDENTIAL_INFO_REQUEST_JSON: s.recv(to_read, socket.MSG_WAITALL))
if resp_buffer != devshell.CREDENTIAL_INFO_REQUEST_JSON:
self.bad_request = True self.bad_request = True
l = len(self.response) l = len(self.response)
s.sendall('{0}\n{1}'.format(l, self.response).encode()) s.sendall('{0}\n{1}'.format(l, self.response).encode())
@@ -178,18 +171,18 @@ class _AuthReferenceServer(threading.Thread):
class DevshellCredentialsTests(unittest2.TestCase): class DevshellCredentialsTests(unittest2.TestCase):
def test_signals_no_server(self): def test_signals_no_server(self):
with self.assertRaises(NoDevshellServer): with self.assertRaises(devshell.NoDevshellServer):
DevshellCredentials() devshell.DevshellCredentials()
def test_bad_message_to_mock_server(self): def test_bad_message_to_mock_server(self):
request_content = CREDENTIAL_INFO_REQUEST_JSON + 'extrastuff' request_content = devshell.CREDENTIAL_INFO_REQUEST_JSON + 'extrastuff'
request_message = _to_bytes( request_message = _helpers._to_bytes(
'{0}\n{1}'.format(len(request_content), request_content)) '{0}\n{1}'.format(len(request_content), request_content))
response_message = 'foobar' response_message = 'foobar'
with _AuthReferenceServer(response_message) as auth_server: with _AuthReferenceServer(response_message) as auth_server:
self.assertFalse(auth_server.bad_request) self.assertFalse(auth_server.bad_request)
sock = socket.socket() sock = socket.socket()
port = int(os.getenv(DEVSHELL_ENV, 0)) port = int(os.getenv(devshell.DEVSHELL_ENV, 0))
sock.connect(('localhost', port)) sock.connect(('localhost', port))
sock.sendall(request_message) sock.sendall(request_message)
@@ -204,22 +197,22 @@ class DevshellCredentialsTests(unittest2.TestCase):
def test_request_response(self): def test_request_response(self):
with _AuthReferenceServer(): with _AuthReferenceServer():
response = _SendRecv() response = devshell._SendRecv()
self.assertEqual(response.user_email, 'joe@example.com') self.assertEqual(response.user_email, 'joe@example.com')
self.assertEqual(response.project_id, 'fooproj') self.assertEqual(response.project_id, 'fooproj')
self.assertEqual(response.access_token, 'sometoken') self.assertEqual(response.access_token, 'sometoken')
def test_no_refresh_token(self): def test_no_refresh_token(self):
with _AuthReferenceServer(): with _AuthReferenceServer():
creds = DevshellCredentials() creds = devshell.DevshellCredentials()
self.assertEquals(None, creds.refresh_token) self.assertEquals(None, creds.refresh_token)
@mock.patch.object(devshell, '_UTCNOW') @mock.patch('oauth2client.client._UTCNOW')
def test_reads_credentials(self, utcnow): def test_reads_credentials(self, utcnow):
NOW = datetime.datetime(1992, 12, 31) NOW = datetime.datetime(1992, 12, 31)
utcnow.return_value = NOW utcnow.return_value = NOW
with _AuthReferenceServer(): with _AuthReferenceServer():
creds = DevshellCredentials() creds = devshell.DevshellCredentials()
self.assertEqual('joe@example.com', creds.user_email) self.assertEqual('joe@example.com', creds.user_email)
self.assertEqual('fooproj', creds.project_id) self.assertEqual('fooproj', creds.project_id)
self.assertEqual('sometoken', creds.access_token) self.assertEqual('sometoken', creds.access_token)
@@ -230,7 +223,7 @@ class DevshellCredentialsTests(unittest2.TestCase):
def test_handles_skipped_fields(self): def test_handles_skipped_fields(self):
with _AuthReferenceServer('["joe@example.com"]'): with _AuthReferenceServer('["joe@example.com"]'):
creds = DevshellCredentials() creds = devshell.DevshellCredentials()
self.assertEqual('joe@example.com', creds.user_email) self.assertEqual('joe@example.com', creds.user_email)
self.assertEqual(None, creds.project_id) self.assertEqual(None, creds.project_id)
self.assertEqual(None, creds.access_token) self.assertEqual(None, creds.access_token)
@@ -238,7 +231,7 @@ class DevshellCredentialsTests(unittest2.TestCase):
def test_handles_tiny_response(self): def test_handles_tiny_response(self):
with _AuthReferenceServer('[]'): with _AuthReferenceServer('[]'):
creds = DevshellCredentials() creds = devshell.DevshellCredentials()
self.assertEqual(None, creds.user_email) self.assertEqual(None, creds.user_email)
self.assertEqual(None, creds.project_id) self.assertEqual(None, creds.project_id)
self.assertEqual(None, creds.access_token) self.assertEqual(None, creds.access_token)
@@ -246,7 +239,7 @@ class DevshellCredentialsTests(unittest2.TestCase):
def test_handles_ignores_extra_fields(self): def test_handles_ignores_extra_fields(self):
with _AuthReferenceServer( with _AuthReferenceServer(
'["joe@example.com", "fooproj", "sometoken", 1, "extra"]'): '["joe@example.com", "fooproj", "sometoken", 1, "extra"]'):
creds = DevshellCredentials() creds = devshell.DevshellCredentials()
self.assertEqual('joe@example.com', creds.user_email) self.assertEqual('joe@example.com', creds.user_email)
self.assertEqual('fooproj', creds.project_id) self.assertEqual('fooproj', creds.project_id)
self.assertEqual('sometoken', creds.access_token) self.assertEqual('sometoken', creds.access_token)
@@ -256,18 +249,18 @@ class DevshellCredentialsTests(unittest2.TestCase):
try: try:
os.path.isdir = lambda path: True os.path.isdir = lambda path: True
with _AuthReferenceServer(): with _AuthReferenceServer():
creds = DevshellCredentials() creds = devshell.DevshellCredentials()
with self.assertRaises(NotImplementedError): with self.assertRaises(NotImplementedError):
save_to_well_known_file(creds) client.save_to_well_known_file(creds)
finally: finally:
os.path.isdir = ORIGINAL_ISDIR os.path.isdir = ORIGINAL_ISDIR
def test_from_json(self): def test_from_json(self):
with self.assertRaises(NotImplementedError): with self.assertRaises(NotImplementedError):
DevshellCredentials.from_json(None) devshell.DevshellCredentials.from_json(None)
def test_serialization_data(self): def test_serialization_data(self):
with _AuthReferenceServer('[]'): with _AuthReferenceServer('[]'):
credentials = DevshellCredentials() credentials = devshell.DevshellCredentials()
with self.assertRaises(NotImplementedError): with self.assertRaises(NotImplementedError):
getattr(credentials, 'serialization_data') getattr(credentials, 'serialization_data')

View File

@@ -16,19 +16,19 @@
import unittest2 import unittest2
from oauth2client import GOOGLE_TOKEN_URI import oauth2client
from oauth2client.client import OAuth2Credentials from oauth2client import client
from oauth2client.contrib.dictionary_storage import DictionaryStorage from oauth2client.contrib import dictionary_storage
def _generate_credentials(scopes=None): def _generate_credentials(scopes=None):
return OAuth2Credentials( return client.OAuth2Credentials(
'access_tokenz', 'access_tokenz',
'client_idz', 'client_idz',
'client_secretz', 'client_secretz',
'refresh_tokenz', 'refresh_tokenz',
'3600', '3600',
GOOGLE_TOKEN_URI, oauth2client.GOOGLE_TOKEN_URI,
'Test', 'Test',
id_token={ id_token={
'sub': '123', 'sub': '123',
@@ -42,7 +42,7 @@ class DictionaryStorageTests(unittest2.TestCase):
def test_constructor_defaults(self): def test_constructor_defaults(self):
dictionary = {} dictionary = {}
key = 'test-key' key = 'test-key'
storage = DictionaryStorage(dictionary, key) storage = dictionary_storage.DictionaryStorage(dictionary, key)
self.assertEqual(dictionary, storage._dictionary) self.assertEqual(dictionary, storage._dictionary)
self.assertEqual(key, storage._key) self.assertEqual(key, storage._key)
@@ -51,17 +51,18 @@ class DictionaryStorageTests(unittest2.TestCase):
def test_constructor_explicit(self): def test_constructor_explicit(self):
dictionary = {} dictionary = {}
key = 'test-key' key = 'test-key'
storage = DictionaryStorage(dictionary, key) storage = dictionary_storage.DictionaryStorage(dictionary, key)
lock = object() lock = object()
storage = DictionaryStorage(dictionary, key, lock=lock) storage = dictionary_storage.DictionaryStorage(
dictionary, key, lock=lock)
self.assertEqual(storage._lock, lock) self.assertEqual(storage._lock, lock)
def test_get(self): def test_get(self):
credentials = _generate_credentials() credentials = _generate_credentials()
dictionary = {} dictionary = {}
key = 'credentials' key = 'credentials'
storage = DictionaryStorage(dictionary, key) storage = dictionary_storage.DictionaryStorage(dictionary, key)
self.assertIsNone(storage.get()) self.assertIsNone(storage.get())
@@ -78,7 +79,7 @@ class DictionaryStorageTests(unittest2.TestCase):
credentials = _generate_credentials() credentials = _generate_credentials()
dictionary = {} dictionary = {}
key = 'credentials' key = 'credentials'
storage = DictionaryStorage(dictionary, key) storage = dictionary_storage.DictionaryStorage(dictionary, key)
storage.put(credentials) storage.put(credentials)
returned = storage.get() returned = storage.get()
@@ -94,7 +95,7 @@ class DictionaryStorageTests(unittest2.TestCase):
credentials = _generate_credentials() credentials = _generate_credentials()
dictionary = {} dictionary = {}
key = 'credentials' key = 'credentials'
storage = DictionaryStorage(dictionary, key) storage = dictionary_storage.DictionaryStorage(dictionary, key)
storage.put(credentials) storage.put(credentials)

View File

@@ -25,12 +25,10 @@ import six.moves.http_client as httplib
import six.moves.urllib.parse as urlparse import six.moves.urllib.parse as urlparse
import unittest2 import unittest2
import oauth2client
from oauth2client import client
from oauth2client import clientsecrets from oauth2client import clientsecrets
from oauth2client import GOOGLE_AUTH_URI from oauth2client.contrib import flask_util
from oauth2client import GOOGLE_TOKEN_URI
from oauth2client.client import OAuth2Credentials
from oauth2client.contrib.flask_util import _get_flow_for_token
from oauth2client.contrib.flask_util import UserOAuth2 as FlaskOAuth2
__author__ = 'jonwayne@google.com (Jon Wayne Parrott)' __author__ = 'jonwayne@google.com (Jon Wayne Parrott)'
@@ -73,19 +71,19 @@ class FlaskOAuth2Tests(unittest2.TestCase):
self.app.testing = True self.app.testing = True
self.app.config['SECRET_KEY'] = 'notasecert' self.app.config['SECRET_KEY'] = 'notasecert'
self.app.logger.setLevel(logging.CRITICAL) self.app.logger.setLevel(logging.CRITICAL)
self.oauth2 = FlaskOAuth2( self.oauth2 = flask_util.UserOAuth2(
self.app, self.app,
client_id='client_idz', client_id='client_idz',
client_secret='client_secretz') client_secret='client_secretz')
def _generate_credentials(self, scopes=None): def _generate_credentials(self, scopes=None):
return OAuth2Credentials( return client.OAuth2Credentials(
'access_tokenz', 'access_tokenz',
'client_idz', 'client_idz',
'client_secretz', 'client_secretz',
'refresh_tokenz', 'refresh_tokenz',
datetime.datetime.utcnow() + datetime.timedelta(seconds=3600), datetime.datetime.utcnow() + datetime.timedelta(seconds=3600),
GOOGLE_TOKEN_URI, oauth2client.GOOGLE_TOKEN_URI,
'Test', 'Test',
id_token={ id_token={
'sub': '123', 'sub': '123',
@@ -94,7 +92,7 @@ class FlaskOAuth2Tests(unittest2.TestCase):
scopes=scopes) scopes=scopes)
def test_explicit_configuration(self): def test_explicit_configuration(self):
oauth2 = FlaskOAuth2( oauth2 = flask_util.UserOAuth2(
flask.Flask(__name__), client_id='id', client_secret='secret') flask.Flask(__name__), client_id='id', client_secret='secret')
self.assertEqual(oauth2.client_id, 'id') self.assertEqual(oauth2.client_id, 'id')
@@ -107,7 +105,7 @@ class FlaskOAuth2Tests(unittest2.TestCase):
with mock.patch('oauth2client.clientsecrets.loadfile', with mock.patch('oauth2client.clientsecrets.loadfile',
return_value=return_val): return_value=return_val):
oauth2 = FlaskOAuth2( oauth2 = flask_util.UserOAuth2(
flask.Flask(__name__), client_secrets_file='file.json') flask.Flask(__name__), client_secrets_file='file.json')
self.assertEqual(oauth2.client_id, 'id') self.assertEqual(oauth2.client_id, 'id')
@@ -115,19 +113,19 @@ class FlaskOAuth2Tests(unittest2.TestCase):
def test_delayed_configuration(self): def test_delayed_configuration(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
oauth2 = FlaskOAuth2() oauth2 = flask_util.UserOAuth2()
oauth2.init_app(app, client_id='id', client_secret='secret') oauth2.init_app(app, client_id='id', client_secret='secret')
self.assertEqual(oauth2.app, app) self.assertEqual(oauth2.app, app)
def test_explicit_storage(self): def test_explicit_storage(self):
storage_mock = mock.Mock() storage_mock = mock.Mock()
oauth2 = FlaskOAuth2( oauth2 = flask_util.UserOAuth2(
flask.Flask(__name__), storage=storage_mock, client_id='id', flask.Flask(__name__), storage=storage_mock, client_id='id',
client_secret='secret') client_secret='secret')
self.assertEqual(oauth2.storage, storage_mock) self.assertEqual(oauth2.storage, storage_mock)
def test_explicit_scopes(self): def test_explicit_scopes(self):
oauth2 = FlaskOAuth2( oauth2 = flask_util.UserOAuth2(
flask.Flask(__name__), scopes=['1', '2'], client_id='id', flask.Flask(__name__), scopes=['1', '2'], client_id='id',
client_secret='secret') client_secret='secret')
self.assertEqual(oauth2.scopes, ['1', '2']) self.assertEqual(oauth2.scopes, ['1', '2'])
@@ -140,15 +138,15 @@ class FlaskOAuth2Tests(unittest2.TestCase):
with mock.patch('oauth2client.clientsecrets.loadfile', with mock.patch('oauth2client.clientsecrets.loadfile',
return_value=return_val): return_value=return_val):
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
FlaskOAuth2(flask.Flask(__name__), flask_util.UserOAuth2(flask.Flask(__name__),
client_secrets_file='file.json') client_secrets_file='file.json')
def test_app_configuration(self): def test_app_configuration(self):
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.config['GOOGLE_OAUTH2_CLIENT_ID'] = 'id' app.config['GOOGLE_OAUTH2_CLIENT_ID'] = 'id'
app.config['GOOGLE_OAUTH2_CLIENT_SECRET'] = 'secret' app.config['GOOGLE_OAUTH2_CLIENT_SECRET'] = 'secret'
oauth2 = FlaskOAuth2(app) oauth2 = flask_util.UserOAuth2(app)
self.assertEqual(oauth2.client_id, 'id') self.assertEqual(oauth2.client_id, 'id')
self.assertEqual(oauth2.client_secret, 'secret') self.assertEqual(oauth2.client_secret, 'secret')
@@ -162,14 +160,14 @@ class FlaskOAuth2Tests(unittest2.TestCase):
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.config['GOOGLE_OAUTH2_CLIENT_SECRETS_FILE'] = 'file.json' app.config['GOOGLE_OAUTH2_CLIENT_SECRETS_FILE'] = 'file.json'
oauth2 = FlaskOAuth2(app) oauth2 = flask_util.UserOAuth2(app)
self.assertEqual(oauth2.client_id, 'id2') self.assertEqual(oauth2.client_id, 'id2')
self.assertEqual(oauth2.client_secret, 'secret2') self.assertEqual(oauth2.client_secret, 'secret2')
def test_no_configuration(self): def test_no_configuration(self):
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
FlaskOAuth2(flask.Flask(__name__)) flask_util.UserOAuth2(flask.Flask(__name__))
def test_create_flow(self): def test_create_flow(self):
with self.app.test_request_context(): with self.app.test_request_context():
@@ -193,7 +191,7 @@ class FlaskOAuth2Tests(unittest2.TestCase):
# Test extra args specified in the constructor. # Test extra args specified in the constructor.
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.config['SECRET_KEY'] = 'notasecert' app.config['SECRET_KEY'] = 'notasecert'
oauth2 = FlaskOAuth2( oauth2 = flask_util.UserOAuth2(
app, client_id='client_id', client_secret='secret', app, client_id='client_id', client_secret='secret',
extra_arg='test') extra_arg='test')
@@ -208,7 +206,7 @@ class FlaskOAuth2Tests(unittest2.TestCase):
q = urlparse.parse_qs(location.split('?', 1)[1]) q = urlparse.parse_qs(location.split('?', 1)[1])
state = json.loads(q['state'][0]) state = json.loads(q['state'][0])
self.assertIn(GOOGLE_AUTH_URI, location) self.assertIn(oauth2client.GOOGLE_AUTH_URI, location)
self.assertNotIn(self.oauth2.client_secret, location) self.assertNotIn(self.oauth2.client_secret, location)
self.assertIn(self.oauth2.client_id, q['client_id']) self.assertIn(self.oauth2.client_id, q['client_id'])
self.assertEqual( self.assertEqual(
@@ -240,7 +238,7 @@ class FlaskOAuth2Tests(unittest2.TestCase):
with client.session_transaction() as session: with client.session_transaction() as session:
session.update(flask.session) session.update(flask.session)
csrf_token = session['google_oauth2_csrf_token'] csrf_token = session['google_oauth2_csrf_token']
flow = _get_flow_for_token(csrf_token) flow = flask_util._get_flow_for_token(csrf_token)
state = flow.params['state'] state = flow.params['state']
return state return state
@@ -434,7 +432,7 @@ class FlaskOAuth2Tests(unittest2.TestCase):
self.app = flask.Flask(__name__) self.app = flask.Flask(__name__)
self.app.testing = True self.app.testing = True
self.app.config['SECRET_KEY'] = 'notasecert' self.app.config['SECRET_KEY'] = 'notasecert'
self.oauth2 = FlaskOAuth2( self.oauth2 = flask_util.UserOAuth2(
self.app, self.app,
client_id='client_idz', client_id='client_idz',
client_secret='client_secretz', client_secret='client_secretz',

View File

@@ -23,10 +23,8 @@ from six.moves import http_client
from tests.contrib.test_metadata import request_mock from tests.contrib.test_metadata import request_mock
import unittest2 import unittest2
from oauth2client.client import HttpAccessTokenRefreshError from oauth2client import client
from oauth2client.client import save_to_well_known_file from oauth2client.contrib import gce
from oauth2client.contrib.gce import _SCOPES_WARNING
from oauth2client.contrib.gce import AppAssertionCredentials
__author__ = 'jcgregorio@google.com (Joe Gregorio)' __author__ = 'jcgregorio@google.com (Joe Gregorio)'
@@ -40,7 +38,7 @@ SERVICE_ACCOUNT_INFO = {
class AppAssertionCredentialsTests(unittest2.TestCase): class AppAssertionCredentialsTests(unittest2.TestCase):
def test_constructor(self): def test_constructor(self):
credentials = AppAssertionCredentials() credentials = gce.AppAssertionCredentials()
self.assertIsNone(credentials.assertion_type, None) self.assertIsNone(credentials.assertion_type, None)
self.assertIsNone(credentials.service_account_email) self.assertIsNone(credentials.service_account_email)
self.assertIsNone(credentials.scopes) self.assertIsNone(credentials.scopes)
@@ -50,19 +48,19 @@ class AppAssertionCredentialsTests(unittest2.TestCase):
def test_constructor_with_scopes(self, warn_mock): def test_constructor_with_scopes(self, warn_mock):
scope = 'http://example.com/a http://example.com/b' scope = 'http://example.com/a http://example.com/b'
scopes = scope.split() scopes = scope.split()
credentials = AppAssertionCredentials(scopes=scopes) credentials = gce.AppAssertionCredentials(scopes=scopes)
self.assertEqual(credentials.scopes, None) self.assertEqual(credentials.scopes, None)
self.assertEqual(credentials.assertion_type, None) self.assertEqual(credentials.assertion_type, None)
warn_mock.assert_called_once_with(_SCOPES_WARNING) warn_mock.assert_called_once_with(gce._SCOPES_WARNING)
def test_to_json(self): def test_to_json(self):
credentials = AppAssertionCredentials() credentials = gce.AppAssertionCredentials()
with self.assertRaises(NotImplementedError): with self.assertRaises(NotImplementedError):
credentials.to_json() credentials.to_json()
def test_from_json(self): def test_from_json(self):
with self.assertRaises(NotImplementedError): with self.assertRaises(NotImplementedError):
AppAssertionCredentials.from_json({}) gce.AppAssertionCredentials.from_json({})
@mock.patch('oauth2client.contrib._metadata.get_token', @mock.patch('oauth2client.contrib._metadata.get_token',
side_effect=[('A', datetime.datetime.min), side_effect=[('A', datetime.datetime.min),
@@ -72,7 +70,7 @@ class AppAssertionCredentialsTests(unittest2.TestCase):
def test_refresh_token(self, get_info, get_token): def test_refresh_token(self, get_info, get_token):
http_request = mock.MagicMock() http_request = mock.MagicMock()
http_mock = mock.MagicMock(request=http_request) http_mock = mock.MagicMock(request=http_request)
credentials = AppAssertionCredentials() credentials = gce.AppAssertionCredentials()
credentials.invalid = False credentials.invalid = False
credentials.service_account_email = 'a@example.com' credentials.service_account_email = 'a@example.com'
self.assertIsNone(credentials.access_token) self.assertIsNone(credentials.access_token)
@@ -94,23 +92,23 @@ class AppAssertionCredentialsTests(unittest2.TestCase):
'application/json', 'application/json',
json.dumps({'access_token': 'a', 'expires_in': 100}) json.dumps({'access_token': 'a', 'expires_in': 100})
) )
credentials = AppAssertionCredentials() credentials = gce.AppAssertionCredentials()
credentials.invalid = False credentials.invalid = False
credentials.service_account_email = 'a@example.com' credentials.service_account_email = 'a@example.com'
with self.assertRaises(HttpAccessTokenRefreshError): with self.assertRaises(client.HttpAccessTokenRefreshError):
credentials._refresh(http_request) credentials._refresh(http_request)
def test_serialization_data(self): def test_serialization_data(self):
credentials = AppAssertionCredentials() credentials = gce.AppAssertionCredentials()
with self.assertRaises(NotImplementedError): with self.assertRaises(NotImplementedError):
getattr(credentials, 'serialization_data') getattr(credentials, 'serialization_data')
def test_create_scoped_required(self): def test_create_scoped_required(self):
credentials = AppAssertionCredentials() credentials = gce.AppAssertionCredentials()
self.assertFalse(credentials.create_scoped_required()) self.assertFalse(credentials.create_scoped_required())
def test_sign_blob_not_implemented(self): def test_sign_blob_not_implemented(self):
credentials = AppAssertionCredentials([]) credentials = gce.AppAssertionCredentials([])
with self.assertRaises(NotImplementedError): with self.assertRaises(NotImplementedError):
credentials.sign_blob(b'blob') credentials.sign_blob(b'blob')
@@ -119,7 +117,7 @@ class AppAssertionCredentialsTests(unittest2.TestCase):
def test_retrieve_scopes(self, metadata): def test_retrieve_scopes(self, metadata):
http_request = mock.MagicMock() http_request = mock.MagicMock()
http_mock = mock.MagicMock(request=http_request) http_mock = mock.MagicMock(request=http_request)
credentials = AppAssertionCredentials() credentials = gce.AppAssertionCredentials()
self.assertTrue(credentials.invalid) self.assertTrue(credentials.invalid)
self.assertIsNone(credentials.scopes) self.assertIsNone(credentials.scopes)
scopes = credentials.retrieve_scopes(http_mock) scopes = credentials.retrieve_scopes(http_mock)
@@ -135,7 +133,7 @@ class AppAssertionCredentialsTests(unittest2.TestCase):
def test_retrieve_scopes_bad_email(self, metadata): def test_retrieve_scopes_bad_email(self, metadata):
http_request = mock.MagicMock() http_request = mock.MagicMock()
http_mock = mock.MagicMock(request=http_request) http_mock = mock.MagicMock(request=http_request)
credentials = AppAssertionCredentials(email='b@example.com') credentials = gce.AppAssertionCredentials(email='b@example.com')
with self.assertRaises(httplib2.HttpLib2Error): with self.assertRaises(httplib2.HttpLib2Error):
credentials.retrieve_scopes(http_mock) credentials.retrieve_scopes(http_mock)
@@ -147,8 +145,8 @@ class AppAssertionCredentialsTests(unittest2.TestCase):
ORIGINAL_ISDIR = os.path.isdir ORIGINAL_ISDIR = os.path.isdir
try: try:
os.path.isdir = lambda path: True os.path.isdir = lambda path: True
credentials = AppAssertionCredentials() credentials = gce.AppAssertionCredentials()
with self.assertRaises(NotImplementedError): with self.assertRaises(NotImplementedError):
save_to_well_known_file(credentials) client.save_to_well_known_file(credentials)
finally: finally:
os.path.isdir = ORIGINAL_ISDIR os.path.isdir = ORIGINAL_ISDIR

View File

@@ -21,9 +21,9 @@ import keyring
import mock import mock
import unittest2 import unittest2
from oauth2client import GOOGLE_TOKEN_URI import oauth2client
from oauth2client.client import OAuth2Credentials from oauth2client import client
from oauth2client.contrib.keyring_storage import Storage from oauth2client.contrib import keyring_storage
__author__ = 'jcgregorio@google.com (Joe Gregorio)' __author__ = 'jcgregorio@google.com (Joe Gregorio)'
@@ -34,21 +34,21 @@ class KeyringStorageTests(unittest2.TestCase):
def test_constructor(self): def test_constructor(self):
service_name = 'my_unit_test' service_name = 'my_unit_test'
user_name = 'me' user_name = 'me'
store = Storage(service_name, user_name) store = keyring_storage.Storage(service_name, user_name)
self.assertEqual(store._service_name, service_name) self.assertEqual(store._service_name, service_name)
self.assertEqual(store._user_name, user_name) self.assertEqual(store._user_name, user_name)
lock_type = type(threading.Lock()) lock_type = type(threading.Lock())
self.assertIsInstance(store._lock, lock_type) self.assertIsInstance(store._lock, lock_type)
def test_acquire_lock(self): def test_acquire_lock(self):
store = Storage('my_unit_test', 'me') store = keyring_storage.Storage('my_unit_test', 'me')
store._lock = lock = _FakeLock() store._lock = lock = _FakeLock()
self.assertEqual(lock._acquire_count, 0) self.assertEqual(lock._acquire_count, 0)
store.acquire_lock() store.acquire_lock()
self.assertEqual(lock._acquire_count, 1) self.assertEqual(lock._acquire_count, 1)
def test_release_lock(self): def test_release_lock(self):
store = Storage('my_unit_test', 'me') store = keyring_storage.Storage('my_unit_test', 'me')
store._lock = lock = _FakeLock() store._lock = lock = _FakeLock()
self.assertEqual(lock._release_count, 0) self.assertEqual(lock._release_count, 0)
store.release_lock() store.release_lock()
@@ -64,11 +64,11 @@ class KeyringStorageTests(unittest2.TestCase):
with mock.patch.object(keyring, 'get_password', with mock.patch.object(keyring, 'get_password',
return_value=mock_content, return_value=mock_content,
autospec=True) as get_password: autospec=True) as get_password:
class_name = 'oauth2client.contrib.keyring_storage.Credentials' class_name = 'oauth2client.client.Credentials'
with mock.patch(class_name) as MockCreds: with mock.patch(class_name) as MockCreds:
MockCreds.new_from_json = new_from_json = mock.MagicMock( MockCreds.new_from_json = new_from_json = mock.MagicMock(
name='new_from_json', return_value=mock_return_creds) name='new_from_json', return_value=mock_return_creds)
store = Storage(service_name, user_name) store = keyring_storage.Storage(service_name, user_name)
credentials = store.locked_get() credentials = store.locked_get()
new_from_json.assert_called_once_with(mock_content) new_from_json.assert_called_once_with(mock_content)
get_password.assert_called_once_with(service_name, user_name) get_password.assert_called_once_with(service_name, user_name)
@@ -78,7 +78,7 @@ class KeyringStorageTests(unittest2.TestCase):
def test_locked_put(self): def test_locked_put(self):
service_name = 'my_unit_test' service_name = 'my_unit_test'
user_name = 'me' user_name = 'me'
store = Storage(service_name, user_name) store = keyring_storage.Storage(service_name, user_name)
with mock.patch.object(keyring, 'set_password', with mock.patch.object(keyring, 'set_password',
return_value=None, return_value=None,
autospec=True) as set_password: autospec=True) as set_password:
@@ -94,7 +94,7 @@ class KeyringStorageTests(unittest2.TestCase):
def test_locked_delete(self): def test_locked_delete(self):
service_name = 'my_unit_test' service_name = 'my_unit_test'
user_name = 'me' user_name = 'me'
store = Storage(service_name, user_name) store = keyring_storage.Storage(service_name, user_name)
with mock.patch.object(keyring, 'set_password', with mock.patch.object(keyring, 'set_password',
return_value=None, return_value=None,
autospec=True) as set_password: autospec=True) as set_password:
@@ -105,7 +105,7 @@ class KeyringStorageTests(unittest2.TestCase):
with mock.patch.object(keyring, 'get_password', with mock.patch.object(keyring, 'get_password',
return_value=None, return_value=None,
autospec=True) as get_password: autospec=True) as get_password:
store = Storage('my_unit_test', 'me') store = keyring_storage.Storage('my_unit_test', 'me')
credentials = store.get() credentials = store.get()
self.assertEquals(None, credentials) self.assertEquals(None, credentials)
get_password.assert_called_once_with('my_unit_test', 'me') get_password.assert_called_once_with('my_unit_test', 'me')
@@ -114,7 +114,7 @@ class KeyringStorageTests(unittest2.TestCase):
with mock.patch.object(keyring, 'get_password', with mock.patch.object(keyring, 'get_password',
return_value='{', return_value='{',
autospec=True) as get_password: autospec=True) as get_password:
store = Storage('my_unit_test', 'me') store = keyring_storage.Storage('my_unit_test', 'me')
credentials = store.get() credentials = store.get()
self.assertEquals(None, credentials) self.assertEquals(None, credentials)
get_password.assert_called_once_with('my_unit_test', 'me') get_password.assert_called_once_with('my_unit_test', 'me')
@@ -127,9 +127,9 @@ class KeyringStorageTests(unittest2.TestCase):
token_expiry = datetime.datetime.utcnow() token_expiry = datetime.datetime.utcnow()
user_agent = 'refresh_checker/1.0' user_agent = 'refresh_checker/1.0'
credentials = OAuth2Credentials( credentials = client.OAuth2Credentials(
access_token, client_id, client_secret, access_token, client_id, client_secret,
refresh_token, token_expiry, GOOGLE_TOKEN_URI, refresh_token, token_expiry, oauth2client.GOOGLE_TOKEN_URI,
user_agent) user_agent)
# Setting autospec on a mock with an iterable side_effect is # Setting autospec on a mock with an iterable side_effect is
@@ -141,7 +141,7 @@ class KeyringStorageTests(unittest2.TestCase):
with mock.patch.object(keyring, 'set_password', with mock.patch.object(keyring, 'set_password',
return_value=None, return_value=None,
autospec=True) as set_password: autospec=True) as set_password:
store = Storage('my_unit_test', 'me') store = keyring_storage.Storage('my_unit_test', 'me')
self.assertEquals(None, store.get()) self.assertEquals(None, store.get())
store.put(credentials) store.put(credentials)

View File

@@ -68,7 +68,7 @@ class TestMetadata(unittest2.TestCase):
http_request.assert_called_once_with(EXPECTED_URL, **EXPECTED_KWARGS) http_request.assert_called_once_with(EXPECTED_URL, **EXPECTED_KWARGS)
@mock.patch( @mock.patch(
'oauth2client.contrib._metadata._UTCNOW', 'oauth2client.client._UTCNOW',
return_value=datetime.datetime.min) return_value=datetime.datetime.min)
def test_get_token_success(self, now): def test_get_token_success(self, now):
http_request = request_mock( http_request = request_mock(

View File

@@ -26,7 +26,7 @@ import mock
from six import StringIO from six import StringIO
import unittest2 import unittest2
from oauth2client.client import OAuth2Credentials from oauth2client import client
from oauth2client.contrib import multiprocess_file_storage from oauth2client.contrib import multiprocess_file_storage
from ..http_mock import HttpMockSequence from ..http_mock import HttpMockSequence
@@ -56,7 +56,7 @@ def _create_test_credentials(expiration=None):
token_uri = 'https://www.google.com/accounts/o8/oauth2/token' token_uri = 'https://www.google.com/accounts/o8/oauth2/token'
user_agent = 'refresh_checker/1.0' user_agent = 'refresh_checker/1.0'
credentials = OAuth2Credentials( credentials = client.OAuth2Credentials(
access_token, 'test-client-id', client_secret, access_token, 'test-client-id', client_secret,
refresh_token, token_expiry, token_uri, refresh_token, token_expiry, token_uri,
user_agent) user_agent)

View File

@@ -23,8 +23,8 @@ import tempfile
import mock import mock
import unittest2 import unittest2
from oauth2client import client
from oauth2client import util from oauth2client import util
from oauth2client.client import OAuth2Credentials
from oauth2client.contrib import locked_file from oauth2client.contrib import locked_file
from oauth2client.contrib import multistore_file from oauth2client.contrib import multistore_file
@@ -98,7 +98,7 @@ class MultistoreFileTests(unittest2.TestCase):
token_uri = 'https://www.google.com/accounts/o8/oauth2/token' token_uri = 'https://www.google.com/accounts/o8/oauth2/token'
user_agent = 'refresh_checker/1.0' user_agent = 'refresh_checker/1.0'
credentials = OAuth2Credentials( credentials = client.OAuth2Credentials(
access_token, client_id, client_secret, access_token, client_id, client_secret,
refresh_token, token_expiry, token_uri, refresh_token, token_expiry, token_uri,
user_agent) user_agent)

View File

@@ -19,7 +19,7 @@ import base64
import mock import mock
import unittest2 import unittest2
from oauth2client._helpers import _to_bytes from oauth2client import _helpers
from oauth2client.contrib import xsrfutil from oauth2client.contrib import xsrfutil
# Jan 17 2008, 5:40PM # Jan 17 2008, 5:40PM
@@ -61,16 +61,16 @@ class Test_generate_token(unittest2.TestCase):
digester.digest.assert_called_once_with() digester.digest.assert_called_once_with()
expected_digest_calls = [ expected_digest_calls = [
mock.call.update(_to_bytes(str(TEST_USER_ID_1))), mock.call.update(_helpers._to_bytes(str(TEST_USER_ID_1))),
mock.call.update(xsrfutil.DELIMITER), mock.call.update(xsrfutil.DELIMITER),
mock.call.update(TEST_ACTION_ID_1), mock.call.update(TEST_ACTION_ID_1),
mock.call.update(xsrfutil.DELIMITER), mock.call.update(xsrfutil.DELIMITER),
mock.call.update(_to_bytes(str(TEST_TIME))), mock.call.update(_helpers._to_bytes(str(TEST_TIME))),
] ]
self.assertEqual(digester.method_calls, expected_digest_calls) self.assertEqual(digester.method_calls, expected_digest_calls)
expected_token_as_bytes = (digest + xsrfutil.DELIMITER + expected_token_as_bytes = (digest + xsrfutil.DELIMITER +
_to_bytes(str(TEST_TIME))) _helpers._to_bytes(str(TEST_TIME)))
expected_token = base64.urlsafe_b64encode( expected_token = base64.urlsafe_b64encode(
expected_token_as_bytes) expected_token_as_bytes)
self.assertEqual(token, expected_token) self.assertEqual(token, expected_token)
@@ -95,16 +95,17 @@ class Test_generate_token(unittest2.TestCase):
digester.digest.assert_called_once_with() digester.digest.assert_called_once_with()
expected_digest_calls = [ expected_digest_calls = [
mock.call.update(_to_bytes(str(TEST_USER_ID_1))), mock.call.update(_helpers._to_bytes(str(TEST_USER_ID_1))),
mock.call.update(xsrfutil.DELIMITER), mock.call.update(xsrfutil.DELIMITER),
mock.call.update(TEST_ACTION_ID_1), mock.call.update(TEST_ACTION_ID_1),
mock.call.update(xsrfutil.DELIMITER), mock.call.update(xsrfutil.DELIMITER),
mock.call.update(_to_bytes(str(int(curr_time)))), mock.call.update(_helpers._to_bytes(str(int(curr_time)))),
] ]
self.assertEqual(digester.method_calls, expected_digest_calls) self.assertEqual(digester.method_calls, expected_digest_calls)
expected_token_as_bytes = (digest + xsrfutil.DELIMITER + expected_token_as_bytes = (
_to_bytes(str(int(curr_time)))) digest + xsrfutil.DELIMITER +
_helpers._to_bytes(str(int(curr_time))))
expected_token = base64.urlsafe_b64encode( expected_token = base64.urlsafe_b64encode(
expected_token_as_bytes) expected_token_as_bytes)
self.assertEqual(token, expected_token) self.assertEqual(token, expected_token)
@@ -139,7 +140,7 @@ class Test_validate_token(unittest2.TestCase):
curr_time = token_time + xsrfutil.DEFAULT_TIMEOUT_SECS + 1 curr_time = token_time + xsrfutil.DEFAULT_TIMEOUT_SECS + 1
key = user_id = None key = user_id = None
token = base64.b64encode(_to_bytes(str(token_time))) token = base64.b64encode(_helpers._to_bytes(str(token_time)))
with mock.patch('oauth2client.contrib.xsrfutil.time') as time: with mock.patch('oauth2client.contrib.xsrfutil.time') as time:
time.time = mock.MagicMock(name='time', return_value=curr_time) time.time = mock.MagicMock(name='time', return_value=curr_time)
self.assertFalse(xsrfutil.validate_token(key, token, user_id)) self.assertFalse(xsrfutil.validate_token(key, token, user_id))
@@ -150,7 +151,7 @@ class Test_validate_token(unittest2.TestCase):
curr_time = token_time + xsrfutil.DEFAULT_TIMEOUT_SECS + 1 curr_time = token_time + xsrfutil.DEFAULT_TIMEOUT_SECS + 1
key = user_id = None key = user_id = None
token = base64.b64encode(_to_bytes(str(token_time))) token = base64.b64encode(_helpers._to_bytes(str(token_time)))
self.assertFalse(xsrfutil.validate_token(key, token, user_id, self.assertFalse(xsrfutil.validate_token(key, token, user_id,
current_time=curr_time)) current_time=curr_time))
@@ -162,7 +163,7 @@ class Test_validate_token(unittest2.TestCase):
key = object() key = object()
user_id = object() user_id = object()
action_id = object() action_id = object()
token = base64.b64encode(_to_bytes(str(token_time))) token = base64.b64encode(_helpers._to_bytes(str(token_time)))
generated_token = b'a' generated_token = b'a'
# Make sure the token length comparison will fail. # Make sure the token length comparison will fail.
self.assertNotEqual(len(token), len(generated_token)) self.assertNotEqual(len(token), len(generated_token))
@@ -183,7 +184,7 @@ class Test_validate_token(unittest2.TestCase):
key = object() key = object()
user_id = object() user_id = object()
action_id = object() action_id = object()
token = base64.b64encode(_to_bytes(str(token_time))) token = base64.b64encode(_helpers._to_bytes(str(token_time)))
# It is encoded as b'MTIzNDU2Nzg5', which has length 12. # It is encoded as b'MTIzNDU2Nzg5', which has length 12.
generated_token = b'M' * 12 generated_token = b'M' * 12
# Make sure the token length comparison will succeed, but the token # Make sure the token length comparison will succeed, but the token
@@ -207,7 +208,7 @@ class Test_validate_token(unittest2.TestCase):
key = object() key = object()
user_id = object() user_id = object()
action_id = object() action_id = object()
token = base64.b64encode(_to_bytes(str(token_time))) token = base64.b64encode(_helpers._to_bytes(str(token_time)))
with mock.patch('oauth2client.contrib.xsrfutil.generate_token', with mock.patch('oauth2client.contrib.xsrfutil.generate_token',
return_value=token) as gen_tok: return_value=token) as gen_tok:
self.assertTrue(xsrfutil.validate_token(key, token, user_id, self.assertTrue(xsrfutil.validate_token(key, token, user_id,

View File

@@ -15,24 +15,19 @@
import unittest2 import unittest2
from oauth2client._helpers import _from_bytes from oauth2client import _helpers
from oauth2client._helpers import _json_encode
from oauth2client._helpers import _parse_pem_key
from oauth2client._helpers import _to_bytes
from oauth2client._helpers import _urlsafe_b64decode
from oauth2client._helpers import _urlsafe_b64encode
class Test__parse_pem_key(unittest2.TestCase): class Test__parse_pem_key(unittest2.TestCase):
def test_valid_input(self): def test_valid_input(self):
test_string = b'1234-----BEGIN FOO BAR BAZ' test_string = b'1234-----BEGIN FOO BAR BAZ'
result = _parse_pem_key(test_string) result = _helpers._parse_pem_key(test_string)
self.assertEqual(result, test_string[4:]) self.assertEqual(result, test_string[4:])
def test_bad_input(self): def test_bad_input(self):
test_string = b'DOES NOT HAVE DASHES' test_string = b'DOES NOT HAVE DASHES'
result = _parse_pem_key(test_string) result = _helpers._parse_pem_key(test_string)
self.assertEqual(result, None) self.assertEqual(result, None)
@@ -42,12 +37,12 @@ class Test__json_encode(unittest2.TestCase):
# Use only a single key since dictionary hash order # Use only a single key since dictionary hash order
# is non-deterministic. # is non-deterministic.
data = {u'foo': 10} data = {u'foo': 10}
result = _json_encode(data) result = _helpers._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 = _helpers._json_encode(data)
self.assertEqual(result, '[42,1337]') self.assertEqual(result, '[42,1337]')
@@ -55,34 +50,34 @@ class Test__to_bytes(unittest2.TestCase):
def test_with_bytes(self): def test_with_bytes(self):
value = b'bytes-val' value = b'bytes-val'
self.assertEqual(_to_bytes(value), value) self.assertEqual(_helpers._to_bytes(value), value)
def test_with_unicode(self): def test_with_unicode(self):
value = u'string-val' value = u'string-val'
encoded_value = b'string-val' encoded_value = b'string-val'
self.assertEqual(_to_bytes(value), encoded_value) self.assertEqual(_helpers._to_bytes(value), encoded_value)
def test_with_nonstring_type(self): def test_with_nonstring_type(self):
value = object() value = object()
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
_to_bytes(value) _helpers._to_bytes(value)
class Test__from_bytes(unittest2.TestCase): class Test__from_bytes(unittest2.TestCase):
def test_with_unicode(self): def test_with_unicode(self):
value = u'bytes-val' value = u'bytes-val'
self.assertEqual(_from_bytes(value), value) self.assertEqual(_helpers._from_bytes(value), value)
def test_with_bytes(self): def test_with_bytes(self):
value = b'string-val' value = b'string-val'
decoded_value = u'string-val' decoded_value = u'string-val'
self.assertEqual(_from_bytes(value), decoded_value) self.assertEqual(_helpers._from_bytes(value), decoded_value)
def test_with_nonstring_type(self): def test_with_nonstring_type(self):
value = object() value = object()
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
_from_bytes(value) _helpers._from_bytes(value)
class Test__urlsafe_b64encode(unittest2.TestCase): class Test__urlsafe_b64encode(unittest2.TestCase):
@@ -91,12 +86,12 @@ class Test__urlsafe_b64encode(unittest2.TestCase):
def test_valid_input_bytes(self): def test_valid_input_bytes(self):
test_string = b'deadbeef' test_string = b'deadbeef'
result = _urlsafe_b64encode(test_string) result = _helpers._urlsafe_b64encode(test_string)
self.assertEqual(result, self.DEADBEEF_ENCODED) self.assertEqual(result, self.DEADBEEF_ENCODED)
def test_valid_input_unicode(self): def test_valid_input_unicode(self):
test_string = u'deadbeef' test_string = u'deadbeef'
result = _urlsafe_b64encode(test_string) result = _helpers._urlsafe_b64encode(test_string)
self.assertEqual(result, self.DEADBEEF_ENCODED) self.assertEqual(result, self.DEADBEEF_ENCODED)
@@ -104,16 +99,16 @@ class Test__urlsafe_b64decode(unittest2.TestCase):
def test_valid_input_bytes(self): def test_valid_input_bytes(self):
test_string = b'ZGVhZGJlZWY' test_string = b'ZGVhZGJlZWY'
result = _urlsafe_b64decode(test_string) result = _helpers._urlsafe_b64decode(test_string)
self.assertEqual(result, b'deadbeef') self.assertEqual(result, b'deadbeef')
def test_valid_input_unicode(self): def test_valid_input_unicode(self):
test_string = b'ZGVhZGJlZWY' test_string = b'ZGVhZGJlZWY'
result = _urlsafe_b64decode(test_string) result = _helpers._urlsafe_b64decode(test_string)
self.assertEqual(result, b'deadbeef') self.assertEqual(result, b'deadbeef')
def test_bad_input(self): def test_bad_input(self):
import binascii import binascii
bad_string = b'+' bad_string = b'+'
with self.assertRaises((TypeError, binascii.Error)): with self.assertRaises((TypeError, binascii.Error)):
_urlsafe_b64decode(bad_string) _helpers._urlsafe_b64decode(bad_string)

View File

@@ -22,10 +22,9 @@ import rsa
import six import six
import unittest2 import unittest2
from oauth2client import _helpers
from oauth2client import _pure_python_crypt from oauth2client import _pure_python_crypt
from oauth2client._helpers import _from_bytes from oauth2client import crypt
from oauth2client.crypt import RsaSigner
from oauth2client.crypt import RsaVerifier
class TestRsaVerifier(unittest2.TestCase): class TestRsaVerifier(unittest2.TestCase):
@@ -51,25 +50,25 @@ class TestRsaVerifier(unittest2.TestCase):
def test_verify_success(self): def test_verify_success(self):
to_sign = b'foo' to_sign = b'foo'
signer = RsaSigner.from_string(self._load_private_key_bytes()) signer = crypt.RsaSigner.from_string(self._load_private_key_bytes())
actual_signature = signer.sign(to_sign) actual_signature = signer.sign(to_sign)
verifier = RsaVerifier.from_string(self._load_public_key_bytes(), verifier = crypt.RsaVerifier.from_string(
is_x509_cert=False) self._load_public_key_bytes(), is_x509_cert=False)
self.assertTrue(verifier.verify(to_sign, actual_signature)) self.assertTrue(verifier.verify(to_sign, actual_signature))
def test_verify_unicode_success(self): def test_verify_unicode_success(self):
to_sign = u'foo' to_sign = u'foo'
signer = RsaSigner.from_string(self._load_private_key_bytes()) signer = crypt.RsaSigner.from_string(self._load_private_key_bytes())
actual_signature = signer.sign(to_sign) actual_signature = signer.sign(to_sign)
verifier = RsaVerifier.from_string(self._load_public_key_bytes(), verifier = crypt.RsaVerifier.from_string(
is_x509_cert=False) self._load_public_key_bytes(), is_x509_cert=False)
self.assertTrue(verifier.verify(to_sign, actual_signature)) self.assertTrue(verifier.verify(to_sign, actual_signature))
def test_verify_failure(self): def test_verify_failure(self):
verifier = RsaVerifier.from_string(self._load_public_key_bytes(), verifier = crypt.RsaVerifier.from_string(
is_x509_cert=False) self._load_public_key_bytes(), is_x509_cert=False)
bad_signature1 = b'' bad_signature1 = b''
self.assertFalse(verifier.verify(b'foo', bad_signature1)) self.assertFalse(verifier.verify(b'foo', bad_signature1))
bad_signature2 = b'a' bad_signature2 = b'a'
@@ -77,26 +76,30 @@ class TestRsaVerifier(unittest2.TestCase):
def test_from_string_pub_key(self): def test_from_string_pub_key(self):
public_key = self._load_public_key_bytes() public_key = self._load_public_key_bytes()
verifier = RsaVerifier.from_string(public_key, is_x509_cert=False) verifier = crypt.RsaVerifier.from_string(
self.assertIsInstance(verifier, RsaVerifier) public_key, is_x509_cert=False)
self.assertIsInstance(verifier, crypt.RsaVerifier)
self.assertIsInstance(verifier._pubkey, rsa.key.PublicKey) self.assertIsInstance(verifier._pubkey, rsa.key.PublicKey)
def test_from_string_pub_key_unicode(self): def test_from_string_pub_key_unicode(self):
public_key = _from_bytes(self._load_public_key_bytes()) public_key = _helpers._from_bytes(self._load_public_key_bytes())
verifier = RsaVerifier.from_string(public_key, is_x509_cert=False) verifier = crypt.RsaVerifier.from_string(
self.assertIsInstance(verifier, RsaVerifier) public_key, is_x509_cert=False)
self.assertIsInstance(verifier, crypt.RsaVerifier)
self.assertIsInstance(verifier._pubkey, rsa.key.PublicKey) self.assertIsInstance(verifier._pubkey, rsa.key.PublicKey)
def test_from_string_pub_cert(self): def test_from_string_pub_cert(self):
public_cert = self._load_public_cert_bytes() public_cert = self._load_public_cert_bytes()
verifier = RsaVerifier.from_string(public_cert, is_x509_cert=True) verifier = crypt.RsaVerifier.from_string(
self.assertIsInstance(verifier, RsaVerifier) public_cert, is_x509_cert=True)
self.assertIsInstance(verifier, crypt.RsaVerifier)
self.assertIsInstance(verifier._pubkey, rsa.key.PublicKey) self.assertIsInstance(verifier._pubkey, rsa.key.PublicKey)
def test_from_string_pub_cert_unicode(self): def test_from_string_pub_cert_unicode(self):
public_cert = _from_bytes(self._load_public_cert_bytes()) public_cert = _helpers._from_bytes(self._load_public_cert_bytes())
verifier = RsaVerifier.from_string(public_cert, is_x509_cert=True) verifier = crypt.RsaVerifier.from_string(
self.assertIsInstance(verifier, RsaVerifier) public_cert, is_x509_cert=True)
self.assertIsInstance(verifier, crypt.RsaVerifier)
self.assertIsInstance(verifier._pubkey, rsa.key.PublicKey) self.assertIsInstance(verifier._pubkey, rsa.key.PublicKey)
def test_from_string_pub_cert_failure(self): def test_from_string_pub_cert_failure(self):
@@ -105,7 +108,7 @@ class TestRsaVerifier(unittest2.TestCase):
with mock.patch('rsa.pem.load_pem', with mock.patch('rsa.pem.load_pem',
return_value=true_der + b'extra') as load_pem: return_value=true_der + b'extra') as load_pem:
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
RsaVerifier.from_string(cert_bytes, is_x509_cert=True) crypt.RsaVerifier.from_string(cert_bytes, is_x509_cert=True)
load_pem.assert_called_once_with(cert_bytes, 'CERTIFICATE') load_pem.assert_called_once_with(cert_bytes, 'CERTIFICATE')
@@ -132,49 +135,49 @@ class TestRsaSigner(unittest2.TestCase):
def test_from_string_pkcs1(self): def test_from_string_pkcs1(self):
key_bytes = self._load_pkcs1_key_bytes() key_bytes = self._load_pkcs1_key_bytes()
signer = RsaSigner.from_string(key_bytes) signer = crypt.RsaSigner.from_string(key_bytes)
self.assertIsInstance(signer, RsaSigner) self.assertIsInstance(signer, crypt.RsaSigner)
self.assertIsInstance(signer._key, rsa.key.PrivateKey) self.assertIsInstance(signer._key, rsa.key.PrivateKey)
def test_from_string_pkcs1_unicode(self): def test_from_string_pkcs1_unicode(self):
key_bytes = _from_bytes(self._load_pkcs1_key_bytes()) key_bytes = _helpers._from_bytes(self._load_pkcs1_key_bytes())
signer = RsaSigner.from_string(key_bytes) signer = crypt.RsaSigner.from_string(key_bytes)
self.assertIsInstance(signer, RsaSigner) self.assertIsInstance(signer, crypt.RsaSigner)
self.assertIsInstance(signer._key, rsa.key.PrivateKey) self.assertIsInstance(signer._key, rsa.key.PrivateKey)
def test_from_string_pkcs8(self): def test_from_string_pkcs8(self):
key_bytes = self._load_pkcs8_key_bytes() key_bytes = self._load_pkcs8_key_bytes()
signer = RsaSigner.from_string(key_bytes) signer = crypt.RsaSigner.from_string(key_bytes)
self.assertIsInstance(signer, RsaSigner) self.assertIsInstance(signer, crypt.RsaSigner)
self.assertIsInstance(signer._key, rsa.key.PrivateKey) self.assertIsInstance(signer._key, rsa.key.PrivateKey)
def test_from_string_pkcs8_extra_bytes(self): def test_from_string_pkcs8_extra_bytes(self):
key_bytes = self._load_pkcs8_key_bytes() key_bytes = self._load_pkcs8_key_bytes()
_, pem_bytes = pem.readPemBlocksFromFile( _, pem_bytes = pem.readPemBlocksFromFile(
six.StringIO(_from_bytes(key_bytes)), six.StringIO(_helpers._from_bytes(key_bytes)),
_pure_python_crypt._PKCS8_MARKER) _pure_python_crypt._PKCS8_MARKER)
with mock.patch('pyasn1.codec.der.decoder.decode') as mock_decode: with mock.patch('pyasn1.codec.der.decoder.decode') as mock_decode:
key_info, remaining = None, 'extra' key_info, remaining = None, 'extra'
mock_decode.return_value = (key_info, remaining) mock_decode.return_value = (key_info, remaining)
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
RsaSigner.from_string(key_bytes) crypt.RsaSigner.from_string(key_bytes)
# Verify mock was called. # Verify mock was called.
mock_decode.assert_called_once_with( mock_decode.assert_called_once_with(
pem_bytes, asn1Spec=_pure_python_crypt._PKCS8_SPEC) pem_bytes, asn1Spec=_pure_python_crypt._PKCS8_SPEC)
def test_from_string_pkcs8_unicode(self): def test_from_string_pkcs8_unicode(self):
key_bytes = _from_bytes(self._load_pkcs8_key_bytes()) key_bytes = _helpers._from_bytes(self._load_pkcs8_key_bytes())
signer = RsaSigner.from_string(key_bytes) signer = crypt.RsaSigner.from_string(key_bytes)
self.assertIsInstance(signer, RsaSigner) self.assertIsInstance(signer, crypt.RsaSigner)
self.assertIsInstance(signer._key, rsa.key.PrivateKey) self.assertIsInstance(signer._key, rsa.key.PrivateKey)
def test_from_string_pkcs12(self): def test_from_string_pkcs12(self):
key_bytes = self._load_pkcs12_key_bytes() key_bytes = self._load_pkcs12_key_bytes()
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
RsaSigner.from_string(key_bytes) crypt.RsaSigner.from_string(key_bytes)
def test_from_string_bogus_key(self): def test_from_string_bogus_key(self):
key_bytes = 'bogus-key' key_bytes = 'bogus-key'
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
RsaSigner.from_string(key_bytes) crypt.RsaSigner.from_string(key_bytes)

View File

@@ -17,8 +17,7 @@ import os
import unittest2 import unittest2
from oauth2client.crypt import PyCryptoSigner from oauth2client import crypt
from oauth2client.crypt import PyCryptoVerifier
class TestPyCryptoVerifier(unittest2.TestCase): class TestPyCryptoVerifier(unittest2.TestCase):
@@ -38,30 +37,32 @@ class TestPyCryptoVerifier(unittest2.TestCase):
def test_verify_success(self): def test_verify_success(self):
to_sign = b'foo' to_sign = b'foo'
signer = PyCryptoSigner.from_string(self._load_private_key_bytes()) signer = crypt.PyCryptoSigner.from_string(
self._load_private_key_bytes())
actual_signature = signer.sign(to_sign) actual_signature = signer.sign(to_sign)
verifier = PyCryptoVerifier.from_string(self._load_public_cert_bytes(), verifier = crypt.PyCryptoVerifier.from_string(
is_x509_cert=True) self._load_public_cert_bytes(), is_x509_cert=True)
self.assertTrue(verifier.verify(to_sign, actual_signature)) self.assertTrue(verifier.verify(to_sign, actual_signature))
def test_verify_failure(self): def test_verify_failure(self):
verifier = PyCryptoVerifier.from_string(self._load_public_cert_bytes(), verifier = crypt.PyCryptoVerifier.from_string(
is_x509_cert=True) self._load_public_cert_bytes(), is_x509_cert=True)
bad_signature = b'' bad_signature = b''
self.assertFalse(verifier.verify(b'foo', bad_signature)) self.assertFalse(verifier.verify(b'foo', bad_signature))
def test_verify_bad_key(self): def test_verify_bad_key(self):
verifier = PyCryptoVerifier.from_string(self._load_public_cert_bytes(), verifier = crypt.PyCryptoVerifier.from_string(
is_x509_cert=True) self._load_public_cert_bytes(), is_x509_cert=True)
bad_signature = b'' bad_signature = b''
self.assertFalse(verifier.verify(b'foo', bad_signature)) self.assertFalse(verifier.verify(b'foo', bad_signature))
def test_from_string_unicode_key(self): def test_from_string_unicode_key(self):
public_key = self._load_public_cert_bytes() public_key = self._load_public_cert_bytes()
public_key = public_key.decode('utf-8') public_key = public_key.decode('utf-8')
verifier = PyCryptoVerifier.from_string(public_key, is_x509_cert=True) verifier = crypt.PyCryptoVerifier.from_string(
self.assertIsInstance(verifier, PyCryptoVerifier) public_key, is_x509_cert=True)
self.assertIsInstance(verifier, crypt.PyCryptoVerifier)
class TestPyCryptoSigner(unittest2.TestCase): class TestPyCryptoSigner(unittest2.TestCase):
@@ -69,4 +70,4 @@ class TestPyCryptoSigner(unittest2.TestCase):
def test_from_string_bad_key(self): def test_from_string_bad_key(self):
key_bytes = 'definitely-not-pem-format' key_bytes = 'definitely-not-pem-format'
with self.assertRaises(NotImplementedError): with self.assertRaises(NotImplementedError):
PyCryptoSigner.from_string(key_bytes) crypt.PyCryptoSigner.from_string(key_bytes)

File diff suppressed because it is too large Load Diff

View File

@@ -21,11 +21,9 @@ import tempfile
import unittest2 import unittest2
import oauth2client
from oauth2client import _helpers
from oauth2client import clientsecrets from oauth2client import clientsecrets
from oauth2client import GOOGLE_AUTH_URI
from oauth2client import GOOGLE_REVOKE_URI
from oauth2client import GOOGLE_TOKEN_URI
from oauth2client._helpers import _from_bytes
__author__ = 'jcgregorio@google.com (Joe Gregorio)' __author__ = 'jcgregorio@google.com (Joe Gregorio)'
@@ -157,9 +155,9 @@ class Test__loadfile(unittest2.TestCase):
'client_id': 'foo_client_id', 'client_id': 'foo_client_id',
'client_secret': 'foo_client_secret', 'client_secret': 'foo_client_secret',
'redirect_uris': [], 'redirect_uris': [],
'auth_uri': GOOGLE_AUTH_URI, 'auth_uri': oauth2client.GOOGLE_AUTH_URI,
'token_uri': GOOGLE_TOKEN_URI, 'token_uri': oauth2client.GOOGLE_TOKEN_URI,
'revoke_uri': GOOGLE_REVOKE_URI, 'revoke_uri': oauth2client.GOOGLE_REVOKE_URI,
} }
self.assertEqual(client_type, clientsecrets.TYPE_WEB) self.assertEqual(client_type, clientsecrets.TYPE_WEB)
self.assertEqual(client_info, expected_client_info) self.assertEqual(client_info, expected_client_info)
@@ -200,7 +198,7 @@ class OAuth2CredentialsTests(unittest2.TestCase):
] ]
for src, match in ERRORS: for src, match in ERRORS:
# Ensure that it is unicode # Ensure that it is unicode
src = _from_bytes(src) src = _helpers._from_bytes(src)
# Test load(s) # Test load(s)
with self.assertRaises( with self.assertRaises(
clientsecrets.InvalidClientSecretsError) as exc_manager: clientsecrets.InvalidClientSecretsError) as exc_manager:

View File

@@ -19,9 +19,9 @@ import mock
import unittest2 import unittest2
from oauth2client import _helpers from oauth2client import _helpers
from oauth2client import client
from oauth2client import crypt from oauth2client import crypt
from oauth2client.client import HAS_OPENSSL from oauth2client import service_account
from oauth2client.service_account import ServiceAccountCredentials
def data_filename(filename): def data_filename(filename):
@@ -44,15 +44,15 @@ class Test_pkcs12_key_as_pem(unittest2.TestCase):
def _make_svc_account_creds(self, private_key_file='privatekey.p12'): def _make_svc_account_creds(self, private_key_file='privatekey.p12'):
filename = data_filename(private_key_file) filename = data_filename(private_key_file)
credentials = ServiceAccountCredentials.from_p12_keyfile( credentials = (
'some_account@example.com', service_account.ServiceAccountCredentials.from_p12_keyfile(
filename, 'some_account@example.com', filename,
scopes='read+write') scopes='read+write'))
credentials._kwargs['sub'] = 'joe@example.org' credentials._kwargs['sub'] = 'joe@example.org'
return credentials return credentials
def _succeeds_helper(self, password=None): def _succeeds_helper(self, password=None):
self.assertEqual(True, HAS_OPENSSL) self.assertEqual(True, client.HAS_OPENSSL)
credentials = self._make_svc_account_creds() credentials = self._make_svc_account_creds()
if password is None: if password is None:

View File

@@ -29,9 +29,8 @@ import six
from six.moves import http_client from six.moves import http_client
import unittest2 import unittest2
from oauth2client import client
from oauth2client import file from oauth2client import file
from oauth2client.client import AccessTokenCredentials
from oauth2client.client import OAuth2Credentials
from .http_mock import HttpMockSequence from .http_mock import HttpMockSequence
try: try:
@@ -69,7 +68,7 @@ class OAuth2ClientFileTests(unittest2.TestCase):
token_uri = 'https://www.google.com/accounts/o8/oauth2/token' token_uri = 'https://www.google.com/accounts/o8/oauth2/token'
user_agent = 'refresh_checker/1.0' user_agent = 'refresh_checker/1.0'
credentials = OAuth2Credentials( credentials = client.OAuth2Credentials(
access_token, client_id, client_secret, access_token, client_id, client_secret,
refresh_token, token_expiry, token_uri, refresh_token, token_expiry, token_uri,
user_agent) user_agent)
@@ -112,7 +111,7 @@ class OAuth2ClientFileTests(unittest2.TestCase):
self.assertEquals(data['access_token'], 'foo') self.assertEquals(data['access_token'], 'foo')
self.assertEquals(data['_class'], 'OAuth2Credentials') self.assertEquals(data['_class'], 'OAuth2Credentials')
self.assertEquals(data['_module'], OAuth2Credentials.__module__) self.assertEquals(data['_module'], client.OAuth2Credentials.__module__)
def test_token_refresh_store_expired(self): def test_token_refresh_store_expired(self):
expiration = (datetime.datetime.utcnow() - expiration = (datetime.datetime.utcnow() -
@@ -228,7 +227,7 @@ class OAuth2ClientFileTests(unittest2.TestCase):
access_token = 'foo' access_token = 'foo'
user_agent = 'refresh_checker/1.0' user_agent = 'refresh_checker/1.0'
credentials = AccessTokenCredentials(access_token, user_agent) credentials = client.AccessTokenCredentials(access_token, user_agent)
s = file.Storage(FILENAME) s = file.Storage(FILENAME)
credentials = s.put(credentials) credentials = s.put(credentials)

View File

@@ -21,15 +21,11 @@ import time
import mock import mock
import unittest2 import unittest2
from oauth2client import _helpers
from oauth2client import client
from oauth2client import crypt from oauth2client import crypt
from oauth2client.client import Credentials from oauth2client import file
from oauth2client.client import HAS_CRYPTO from oauth2client import service_account
from oauth2client.client import HAS_OPENSSL
from oauth2client.client import verify_id_token
from oauth2client.client import VerifyJwtTokenError
from oauth2client.file import Storage
from oauth2client.service_account import _PASSWORD_DEFAULT
from oauth2client.service_account import ServiceAccountCredentials
from .http_mock import HttpMockSequence from .http_mock import HttpMockSequence
@@ -125,7 +121,7 @@ class CryptTests(unittest2.TestCase):
({'status': '200'}, datafile('certs.json')), ({'status': '200'}, datafile('certs.json')),
]) ])
contents = verify_id_token( contents = client.verify_id_token(
jwt, 'some_audience_address@testing.gserviceaccount.com', jwt, 'some_audience_address@testing.gserviceaccount.com',
http=http) http=http)
self.assertEqual('billy bob', contents['user']) self.assertEqual('billy bob', contents['user'])
@@ -139,7 +135,7 @@ class CryptTests(unittest2.TestCase):
]) ])
with mock.patch('oauth2client.transport._CACHED_HTTP', new=http): with mock.patch('oauth2client.transport._CACHED_HTTP', new=http):
contents = verify_id_token( contents = client.verify_id_token(
jwt, 'some_audience_address@testing.gserviceaccount.com') jwt, 'some_audience_address@testing.gserviceaccount.com')
self.assertEqual('billy bob', contents['user']) self.assertEqual('billy bob', contents['user'])
@@ -153,8 +149,8 @@ class CryptTests(unittest2.TestCase):
({'status': '404'}, datafile('certs.json')), ({'status': '404'}, datafile('certs.json')),
]) ])
with self.assertRaises(VerifyJwtTokenError): with self.assertRaises(client.VerifyJwtTokenError):
verify_id_token(jwt, test_email, http=http) client.verify_id_token(jwt, test_email, http=http)
def test_verify_id_token_bad_tokens(self): def test_verify_id_token_bad_tokens(self):
private_key = datafile('privatekey.' + self.format_) private_key = datafile('privatekey.' + self.format_)
@@ -167,7 +163,7 @@ class CryptTests(unittest2.TestCase):
# Bad signature # Bad signature
jwt = b'.'.join([b'foo', jwt = b'.'.join([b'foo',
crypt._urlsafe_b64encode('{"a":"b"}'), _helpers._urlsafe_b64encode('{"a":"b"}'),
b'baz']) b'baz'])
self._check_jwt_failure(jwt, 'Invalid token signature') self._check_jwt_failure(jwt, 'Invalid token signature')
@@ -245,7 +241,7 @@ class SignedJwtAssertionCredentialsTests(unittest2.TestCase):
def _make_credentials(self): def _make_credentials(self):
private_key = datafile('privatekey.' + self.format_) private_key = datafile('privatekey.' + self.format_)
signer = crypt.Signer.from_string(private_key) signer = crypt.Signer.from_string(private_key)
credentials = ServiceAccountCredentials( credentials = service_account.ServiceAccountCredentials(
'some_account@example.com', signer, 'some_account@example.com', signer,
scopes='read+write', scopes='read+write',
sub='joe@example.org') sub='joe@example.org')
@@ -253,7 +249,8 @@ class SignedJwtAssertionCredentialsTests(unittest2.TestCase):
credentials._private_key_pkcs8_pem = private_key credentials._private_key_pkcs8_pem = private_key
elif self.format_ == 'p12': elif self.format_ == 'p12':
credentials._private_key_pkcs12 = private_key credentials._private_key_pkcs12 = private_key
credentials._private_key_password = _PASSWORD_DEFAULT credentials._private_key_password = (
service_account._PASSWORD_DEFAULT)
else: # pragma: NO COVER else: # pragma: NO COVER
raise ValueError('Unexpected format.') raise ValueError('Unexpected format.')
return credentials return credentials
@@ -271,7 +268,7 @@ class SignedJwtAssertionCredentialsTests(unittest2.TestCase):
def test_credentials_to_from_json(self): def test_credentials_to_from_json(self):
credentials = self._make_credentials() credentials = self._make_credentials()
json = credentials.to_json() json = credentials.to_json()
restored = Credentials.new_from_json(json) restored = client.Credentials.new_from_json(json)
self.assertEqual(credentials._private_key_pkcs12, self.assertEqual(credentials._private_key_pkcs12,
restored._private_key_pkcs12) restored._private_key_pkcs12)
self.assertEqual(credentials._private_key_password, self.assertEqual(credentials._private_key_password,
@@ -299,7 +296,7 @@ class SignedJwtAssertionCredentialsTests(unittest2.TestCase):
filehandle, filename = tempfile.mkstemp() filehandle, filename = tempfile.mkstemp()
os.close(filehandle) os.close(filehandle)
store = Storage(filename) store = file.Storage(filename)
store.put(credentials) store.put(credentials)
credentials.set_store(store) credentials.set_store(store)
@@ -328,5 +325,5 @@ class PEMSignedJwtAssertionCredentialsPyCryptoTests(
class TestHasOpenSSLFlag(unittest2.TestCase): class TestHasOpenSSLFlag(unittest2.TestCase):
def test_true(self): def test_true(self):
self.assertEqual(True, HAS_OPENSSL) self.assertEqual(True, client.HAS_OPENSSL)
self.assertEqual(True, HAS_CRYPTO) self.assertEqual(True, client.HAS_CRYPTO)

View File

@@ -28,10 +28,9 @@ import rsa
from six import BytesIO from six import BytesIO
import unittest2 import unittest2
from oauth2client import client
from oauth2client import crypt from oauth2client import crypt
from oauth2client.service_account import _JWTAccessCredentials from oauth2client import service_account
from oauth2client.service_account import SERVICE_ACCOUNT
from oauth2client.service_account import ServiceAccountCredentials
from .http_mock import HttpMockSequence from .http_mock import HttpMockSequence
@@ -53,7 +52,7 @@ class ServiceAccountCredentialsTests(unittest2.TestCase):
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.signer = crypt.Signer.from_string(self.private_key) self.signer = crypt.Signer.from_string(self.private_key)
self.credentials = ServiceAccountCredentials( self.credentials = service_account.ServiceAccountCredentials(
self.service_account_email, self.service_account_email,
self.signer, self.signer,
private_key_id=self.private_key_id, private_key_id=self.private_key_id,
@@ -62,8 +61,8 @@ class ServiceAccountCredentialsTests(unittest2.TestCase):
def test__to_json_override(self): def test__to_json_override(self):
signer = object() signer = object()
creds = ServiceAccountCredentials('name@email.com', creds = service_account.ServiceAccountCredentials(
signer) 'name@email.com', signer)
self.assertEqual(creds._signer, signer) self.assertEqual(creds._signer, signer)
# Serialize over-ridden data (unrelated to ``creds``). # Serialize over-ridden data (unrelated to ``creds``).
to_serialize = {'unrelated': 'data'} to_serialize = {'unrelated': 'data'}
@@ -103,9 +102,11 @@ class ServiceAccountCredentialsTests(unittest2.TestCase):
try: try:
with open(filename, 'w') as file_obj: with open(filename, 'w') as file_obj:
json.dump(payload, file_obj) json.dump(payload, file_obj)
return ServiceAccountCredentials.from_json_keyfile_name( return (
filename, scopes=scopes, token_uri=token_uri, service_account.ServiceAccountCredentials
revoke_uri=revoke_uri) .from_json_keyfile_name(
filename, scopes=scopes, token_uri=token_uri,
revoke_uri=revoke_uri))
finally: finally:
os.remove(filename) os.remove(filename)
@@ -117,7 +118,7 @@ class ServiceAccountCredentialsTests(unittest2.TestCase):
private_key_id = 'pkid456' private_key_id = 'pkid456'
private_key = 's3kr3tz' private_key = 's3kr3tz'
payload = { payload = {
'type': SERVICE_ACCOUNT, 'type': client.SERVICE_ACCOUNT,
'client_id': client_id, 'client_id': client_id,
'client_email': client_email, 'client_email': client_email,
'private_key_id': private_key_id, 'private_key_id': private_key_id,
@@ -136,7 +137,8 @@ class ServiceAccountCredentialsTests(unittest2.TestCase):
creds_with_uris_from_file = self._from_json_keyfile_name_helper( creds_with_uris_from_file = self._from_json_keyfile_name_helper(
payload, scopes=scopes) payload, scopes=scopes)
for creds in (base_creds, creds_with_uris_from_file): for creds in (base_creds, creds_with_uris_from_file):
self.assertIsInstance(creds, ServiceAccountCredentials) self.assertIsInstance(
creds, service_account.ServiceAccountCredentials)
self.assertEqual(creds.client_id, client_id) self.assertEqual(creds.client_id, client_id)
self.assertEqual(creds._service_account_email, client_email) self.assertEqual(creds._service_account_email, client_email)
self.assertEqual(creds._private_key_id, private_key_id) self.assertEqual(creds._private_key_id, private_key_id)
@@ -147,14 +149,14 @@ class ServiceAccountCredentialsTests(unittest2.TestCase):
def test_from_json_keyfile_name_factory_bad_type(self): def test_from_json_keyfile_name_factory_bad_type(self):
type_ = 'bad-type' type_ = 'bad-type'
self.assertNotEqual(type_, SERVICE_ACCOUNT) self.assertNotEqual(type_, client.SERVICE_ACCOUNT)
payload = {'type': type_} payload = {'type': type_}
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
self._from_json_keyfile_name_helper(payload) self._from_json_keyfile_name_helper(payload)
def test_from_json_keyfile_name_factory_missing_field(self): def test_from_json_keyfile_name_factory_missing_field(self):
payload = { payload = {
'type': SERVICE_ACCOUNT, 'type': client.SERVICE_ACCOUNT,
'client_id': 'my-client', 'client_id': 'my-client',
} }
with self.assertRaises(KeyError): with self.assertRaises(KeyError):
@@ -166,17 +168,19 @@ class ServiceAccountCredentialsTests(unittest2.TestCase):
filename = data_filename('privatekey.p12') filename = data_filename('privatekey.p12')
with open(filename, 'rb') as file_obj: with open(filename, 'rb') as file_obj:
key_contents = file_obj.read() key_contents = file_obj.read()
creds_from_filename = ServiceAccountCredentials.from_p12_keyfile( creds_from_filename = (
service_account_email, filename, service_account.ServiceAccountCredentials.from_p12_keyfile(
private_key_password=private_key_password, service_account_email, filename,
scopes=scopes, token_uri=token_uri, revoke_uri=revoke_uri) private_key_password=private_key_password,
scopes=scopes, token_uri=token_uri, revoke_uri=revoke_uri))
creds_from_file_contents = ( creds_from_file_contents = (
ServiceAccountCredentials.from_p12_keyfile_buffer( service_account.ServiceAccountCredentials.from_p12_keyfile_buffer(
service_account_email, BytesIO(key_contents), service_account_email, BytesIO(key_contents),
private_key_password=private_key_password, private_key_password=private_key_password,
scopes=scopes, token_uri=token_uri, revoke_uri=revoke_uri)) scopes=scopes, token_uri=token_uri, revoke_uri=revoke_uri))
for creds in (creds_from_filename, creds_from_file_contents): for creds in (creds_from_filename, creds_from_file_contents):
self.assertIsInstance(creds, ServiceAccountCredentials) self.assertIsInstance(
creds, service_account.ServiceAccountCredentials)
self.assertIsNone(creds.client_id) self.assertIsNone(creds.client_id)
self.assertEqual(creds._service_account_email, self.assertEqual(creds._service_account_email,
service_account_email) service_account_email)
@@ -194,7 +198,7 @@ class ServiceAccountCredentialsTests(unittest2.TestCase):
service_account_email = 'name@email.com' service_account_email = 'name@email.com'
filename = data_filename('privatekey.p12') filename = data_filename('privatekey.p12')
with self.assertRaises(NotImplementedError): with self.assertRaises(NotImplementedError):
ServiceAccountCredentials.from_p12_keyfile( service_account.ServiceAccountCredentials.from_p12_keyfile(
service_account_email, filename) service_account_email, filename)
@mock.patch('oauth2client.crypt.Signer', new=crypt.PyCryptoSigner) @mock.patch('oauth2client.crypt.Signer', new=crypt.PyCryptoSigner)
@@ -219,7 +223,7 @@ class ServiceAccountCredentialsTests(unittest2.TestCase):
def test_create_scoped_required_with_scopes(self): def test_create_scoped_required_with_scopes(self):
signer = object() signer = object()
self.credentials = ServiceAccountCredentials( self.credentials = service_account.ServiceAccountCredentials(
self.service_account_email, self.service_account_email,
signer, signer,
scopes=self.scopes, scopes=self.scopes,
@@ -232,13 +236,14 @@ class ServiceAccountCredentialsTests(unittest2.TestCase):
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.assertIsInstance(new_credentials, self.assertIsInstance(new_credentials,
ServiceAccountCredentials) service_account.ServiceAccountCredentials)
self.assertEqual('dummy_scope', new_credentials._scopes) self.assertEqual('dummy_scope', new_credentials._scopes)
def test_create_delegated(self): def test_create_delegated(self):
signer = object() signer = object()
sub = 'foo@email.com' sub = 'foo@email.com'
creds = ServiceAccountCredentials('name@email.com', signer) creds = service_account.ServiceAccountCredentials(
'name@email.com', signer)
self.assertNotIn('sub', creds._kwargs) self.assertNotIn('sub', creds._kwargs)
delegated_creds = creds.create_delegated(sub) delegated_creds = creds.create_delegated(sub)
self.assertEqual(delegated_creds._kwargs['sub'], sub) self.assertEqual(delegated_creds._kwargs['sub'], sub)
@@ -249,7 +254,8 @@ class ServiceAccountCredentialsTests(unittest2.TestCase):
signer = object() signer = object()
sub1 = 'existing@email.com' sub1 = 'existing@email.com'
sub2 = 'new@email.com' sub2 = 'new@email.com'
creds = ServiceAccountCredentials('name@email.com', signer, sub=sub1) creds = service_account.ServiceAccountCredentials(
'name@email.com', signer, sub=sub1)
self.assertEqual(creds._kwargs['sub'], sub1) self.assertEqual(creds._kwargs['sub'], sub1)
delegated_creds = creds.create_delegated(sub2) delegated_creds = creds.create_delegated(sub2)
self.assertEqual(delegated_creds._kwargs['sub'], sub2) self.assertEqual(delegated_creds._kwargs['sub'], sub2)
@@ -268,7 +274,7 @@ class ServiceAccountCredentialsTests(unittest2.TestCase):
signed_value = b'signed-content' signed_value = b'signed-content'
signer.sign = mock.MagicMock(name='sign', signer.sign = mock.MagicMock(name='sign',
return_value=signed_value) return_value=signed_value)
credentials = ServiceAccountCredentials( credentials = service_account.ServiceAccountCredentials(
self.service_account_email, self.service_account_email,
signer, signer,
private_key_id=self.private_key_id, private_key_id=self.private_key_id,
@@ -356,7 +362,7 @@ class ServiceAccountCredentialsTests(unittest2.TestCase):
self.assertEqual(credentials.access_token, token2) self.assertEqual(credentials.access_token, token2)
TOKEN_LIFE = _JWTAccessCredentials._MAX_TOKEN_LIFETIME_SECS TOKEN_LIFE = service_account._JWTAccessCredentials._MAX_TOKEN_LIFETIME_SECS
T1 = 42 T1 = 42
T1_DATE = datetime.datetime(1970, 1, 1, second=T1) T1_DATE = datetime.datetime(1970, 1, 1, second=T1)
T1_EXPIRY = T1 + TOKEN_LIFE T1_EXPIRY = T1 + TOKEN_LIFE
@@ -382,18 +388,15 @@ class JWTAccessCredentialsTests(unittest2.TestCase):
self.private_key = datafile('pem_from_pkcs12.pem') self.private_key = datafile('pem_from_pkcs12.pem')
self.signer = crypt.Signer.from_string(self.private_key) self.signer = crypt.Signer.from_string(self.private_key)
self.url = 'https://test.url.com' self.url = 'https://test.url.com'
self.jwt = _JWTAccessCredentials(self.service_account_email, self.jwt = service_account._JWTAccessCredentials(
self.signer, self.service_account_email, self.signer,
private_key_id=self.private_key_id, private_key_id=self.private_key_id, client_id=self.client_id,
client_id=self.client_id, additional_claims={'aud': self.url})
additional_claims={'aud': self.url})
@mock.patch('oauth2client.service_account._UTCNOW')
@mock.patch('oauth2client.client._UTCNOW') @mock.patch('oauth2client.client._UTCNOW')
@mock.patch('time.time') @mock.patch('time.time')
def test_get_access_token_no_claims(self, time, client_utcnow, utcnow): def test_get_access_token_no_claims(self, time, utcnow):
utcnow.return_value = T1_DATE utcnow.return_value = T1_DATE
client_utcnow.return_value = T1_DATE
time.return_value = T1 time.return_value = T1
token_info = self.jwt.get_access_token() token_info = self.jwt.get_access_token()
@@ -408,7 +411,6 @@ class JWTAccessCredentialsTests(unittest2.TestCase):
# Verify that we vend the same token after 100 seconds # Verify that we vend the same token after 100 seconds
utcnow.return_value = T2_DATE utcnow.return_value = T2_DATE
client_utcnow.return_value = T2_DATE
token_info = self.jwt.get_access_token() token_info = self.jwt.get_access_token()
payload = crypt.verify_signed_jwt_with_certs( payload = crypt.verify_signed_jwt_with_certs(
token_info.access_token, token_info.access_token,
@@ -419,7 +421,6 @@ class JWTAccessCredentialsTests(unittest2.TestCase):
# Verify that we vend a new token after _MAX_TOKEN_LIFETIME_SECS # Verify that we vend a new token after _MAX_TOKEN_LIFETIME_SECS
utcnow.return_value = T3_DATE utcnow.return_value = T3_DATE
client_utcnow.return_value = T3_DATE
time.return_value = T3 time.return_value = T3
token_info = self.jwt.get_access_token() token_info = self.jwt.get_access_token()
payload = crypt.verify_signed_jwt_with_certs( payload = crypt.verify_signed_jwt_with_certs(
@@ -430,7 +431,7 @@ class JWTAccessCredentialsTests(unittest2.TestCase):
self.assertEqual(payload['exp'], T3_EXPIRY) self.assertEqual(payload['exp'], T3_EXPIRY)
self.assertEqual(expires_in, T3_EXPIRY - T3) self.assertEqual(expires_in, T3_EXPIRY - T3)
@mock.patch('oauth2client.service_account._UTCNOW') @mock.patch('oauth2client.client._UTCNOW')
@mock.patch('time.time') @mock.patch('time.time')
def test_get_access_token_additional_claims(self, time, utcnow): def test_get_access_token_additional_claims(self, time, utcnow):
utcnow.return_value = T1_DATE utcnow.return_value = T1_DATE
@@ -463,15 +464,14 @@ class JWTAccessCredentialsTests(unittest2.TestCase):
new_credentials = self.jwt.create_scoped('dummy_scope') new_credentials = self.jwt.create_scoped('dummy_scope')
self.assertNotEqual(self.jwt, new_credentials) self.assertNotEqual(self.jwt, new_credentials)
self.assertIsInstance(new_credentials, ServiceAccountCredentials) self.assertIsInstance(
new_credentials, service_account.ServiceAccountCredentials)
self.assertEqual('dummy_scope', new_credentials._scopes) self.assertEqual('dummy_scope', new_credentials._scopes)
@mock.patch('oauth2client.service_account._UTCNOW')
@mock.patch('oauth2client.client._UTCNOW') @mock.patch('oauth2client.client._UTCNOW')
@mock.patch('time.time') @mock.patch('time.time')
def test_authorize_success(self, time, client_utcnow, utcnow): def test_authorize_success(self, time, utcnow):
utcnow.return_value = T1_DATE utcnow.return_value = T1_DATE
client_utcnow.return_value = T1_DATE
time.return_value = T1 time.return_value = T1
def mock_request(uri, method='GET', body=None, headers=None, def mock_request(uri, method='GET', body=None, headers=None,
@@ -497,21 +497,17 @@ class JWTAccessCredentialsTests(unittest2.TestCase):
# Ensure we use the cached token # Ensure we use the cached token
utcnow.return_value = T2_DATE utcnow.return_value = T2_DATE
client_utcnow.return_value = T2_DATE
h.request(self.url) h.request(self.url)
@mock.patch('oauth2client.service_account._UTCNOW')
@mock.patch('oauth2client.client._UTCNOW') @mock.patch('oauth2client.client._UTCNOW')
@mock.patch('time.time') @mock.patch('time.time')
def test_authorize_no_aud(self, time, client_utcnow, utcnow): def test_authorize_no_aud(self, time, utcnow):
utcnow.return_value = T1_DATE utcnow.return_value = T1_DATE
client_utcnow.return_value = T1_DATE
time.return_value = T1 time.return_value = T1
jwt = _JWTAccessCredentials(self.service_account_email, jwt = service_account._JWTAccessCredentials(
self.signer, self.service_account_email, self.signer,
private_key_id=self.private_key_id, private_key_id=self.private_key_id, client_id=self.client_id)
client_id=self.client_id)
def mock_request(uri, method='GET', body=None, headers=None, def mock_request(uri, method='GET', body=None, headers=None,
redirections=0, connection_type=None): redirections=0, connection_type=None):
@@ -537,7 +533,7 @@ class JWTAccessCredentialsTests(unittest2.TestCase):
# Ensure we do not cache the token # Ensure we do not cache the token
self.assertIsNone(jwt.access_token) self.assertIsNone(jwt.access_token)
@mock.patch('oauth2client.service_account._UTCNOW') @mock.patch('oauth2client.client._UTCNOW')
def test_authorize_stale_token(self, utcnow): def test_authorize_stale_token(self, utcnow):
utcnow.return_value = T1_DATE utcnow.return_value = T1_DATE
# Create an initial token # Create an initial token
@@ -554,7 +550,7 @@ class JWTAccessCredentialsTests(unittest2.TestCase):
self.assertEquals(self.jwt.token_expiry, T3_EXPIRY_DATE) self.assertEquals(self.jwt.token_expiry, T3_EXPIRY_DATE)
self.assertNotEqual(token_1, token_2) self.assertNotEqual(token_1, token_2)
@mock.patch('oauth2client.service_account._UTCNOW') @mock.patch('oauth2client.client._UTCNOW')
def test_authorize_401(self, utcnow): def test_authorize_401(self, utcnow):
utcnow.return_value = T1_DATE utcnow.return_value = T1_DATE
@@ -572,7 +568,7 @@ class JWTAccessCredentialsTests(unittest2.TestCase):
# Check the 401 forced a new token # Check the 401 forced a new token
self.assertNotEqual(token_1, token_2) self.assertNotEqual(token_1, token_2)
@mock.patch('oauth2client.service_account._UTCNOW') @mock.patch('oauth2client.client._UTCNOW')
def test_refresh(self, utcnow): def test_refresh(self, utcnow):
utcnow.return_value = T1_DATE utcnow.return_value = T1_DATE
token_1 = self.jwt.access_token token_1 = self.jwt.access_token

View File

@@ -20,9 +20,8 @@ import mock
from six.moves.urllib import request from six.moves.urllib import request
import unittest2 import unittest2
from oauth2client import client
from oauth2client import tools from oauth2client import tools
from oauth2client.client import FlowExchangeError
from oauth2client.client import OOB_CALLBACK_URN
try: try:
import argparse import argparse
@@ -82,7 +81,7 @@ class TestRunFlow(unittest2.TestCase):
returned_credentials = tools.run_flow(self.flow, self.storage) returned_credentials = tools.run_flow(self.flow, self.storage)
self.assertEqual(self.credentials, returned_credentials) self.assertEqual(self.credentials, returned_credentials)
self.assertEqual(self.flow.redirect_uri, OOB_CALLBACK_URN) self.assertEqual(self.flow.redirect_uri, client.OOB_CALLBACK_URN)
self.flow.step2_exchange.assert_called_once_with( self.flow.step2_exchange.assert_called_once_with(
'auth_code', http=None) 'auth_code', http=None)
self.storage.put.assert_called_once_with(self.credentials) self.storage.put.assert_called_once_with(self.credentials)
@@ -99,7 +98,7 @@ class TestRunFlow(unittest2.TestCase):
self.flow, self.storage, flags=self.flags) self.flow, self.storage, flags=self.flags)
self.assertEqual(self.credentials, returned_credentials) self.assertEqual(self.credentials, returned_credentials)
self.assertEqual(self.flow.redirect_uri, OOB_CALLBACK_URN) self.assertEqual(self.flow.redirect_uri, client.OOB_CALLBACK_URN)
self.flow.step2_exchange.assert_called_once_with( self.flow.step2_exchange.assert_called_once_with(
'auth_code', http=None) 'auth_code', http=None)
@@ -108,7 +107,7 @@ class TestRunFlow(unittest2.TestCase):
def test_run_flow_no_webserver_exchange_error( def test_run_flow_no_webserver_exchange_error(
self, input_mock, logging_mock): self, input_mock, logging_mock):
input_mock.return_value = 'auth_code' input_mock.return_value = 'auth_code'
self.flow.step2_exchange.side_effect = FlowExchangeError() self.flow.step2_exchange.side_effect = client.FlowExchangeError()
# Error while exchanging. # Error while exchanging.
with self.assertRaises(SystemExit): with self.assertRaises(SystemExit):
@@ -181,7 +180,7 @@ class TestRunFlow(unittest2.TestCase):
self.flow, self.storage, flags=self.server_flags) self.flow, self.storage, flags=self.server_flags)
self.assertEqual(self.credentials, returned_credentials) self.assertEqual(self.credentials, returned_credentials)
self.assertEqual(self.flow.redirect_uri, OOB_CALLBACK_URN) self.assertEqual(self.flow.redirect_uri, client.OOB_CALLBACK_URN)
self.flow.step2_exchange.assert_called_once_with( self.flow.step2_exchange.assert_called_once_with(
'auth_code', http=None) 'auth_code', http=None)
self.assertTrue(server_ctor_mock.called) self.assertTrue(server_ctor_mock.called)