From f31e1e014fa9632fd5d71ccd03d19a14320c95d0 Mon Sep 17 00:00:00 2001 From: Pat Ferate Date: Thu, 21 Jul 2016 14:42:27 -0700 Subject: [PATCH] Update imports to only Packages or Modules Also cleaned up some nested attribute access. --- oauth2client/_openssl_crypt.py | 19 +- oauth2client/_pure_python_crypt.py | 11 +- oauth2client/_pycrypto_crypt.py | 14 +- oauth2client/client.py | 76 ++- oauth2client/contrib/_fcntl_opener.py | 15 +- oauth2client/contrib/_metadata.py | 8 +- oauth2client/contrib/_win32_opener.py | 15 +- oauth2client/contrib/appengine.py | 39 +- oauth2client/contrib/devshell.py | 10 +- oauth2client/contrib/dictionary_storage.py | 7 +- oauth2client/contrib/django_util/storage.py | 4 +- oauth2client/contrib/flask_util.py | 12 +- oauth2client/contrib/gce.py | 7 +- oauth2client/contrib/keyring_storage.py | 11 +- .../contrib/multiprocess_file_storage.py | 7 +- oauth2client/contrib/multistore_file.py | 11 +- oauth2client/contrib/sqlalchemy.py | 12 +- oauth2client/contrib/xsrfutil.py | 10 +- oauth2client/crypt.py | 38 +- oauth2client/file.py | 7 +- oauth2client/service_account.py | 63 +- tests/contrib/django_util/test_decorators.py | 6 +- tests/contrib/test__appengine_ndb.py | 28 +- tests/contrib/test_appengine.py | 205 +++--- tests/contrib/test_devshell.py | 79 ++- tests/contrib/test_dictionary_storage.py | 23 +- tests/contrib/test_flask_util.py | 42 +- tests/contrib/test_gce.py | 36 +- tests/contrib/test_keyring_storage.py | 30 +- tests/contrib/test_metadata.py | 2 +- .../contrib/test_multiprocess_file_storage.py | 4 +- tests/contrib/test_multistore_file.py | 4 +- tests/contrib/test_xsrfutil.py | 27 +- tests/test__helpers.py | 37 +- tests/test__pure_python_crypt.py | 75 +-- tests/test__pycrypto_crypt.py | 25 +- tests/test_client.py | 606 +++++++++--------- tests/test_clientsecrets.py | 14 +- tests/test_crypt.py | 14 +- tests/test_file.py | 9 +- tests/test_jwt.py | 35 +- tests/test_service_account.py | 100 ++- tests/test_tools.py | 11 +- 43 files changed, 858 insertions(+), 950 deletions(-) diff --git a/oauth2client/_openssl_crypt.py b/oauth2client/_openssl_crypt.py index 49b763b..77fac74 100644 --- a/oauth2client/_openssl_crypt.py +++ b/oauth2client/_openssl_crypt.py @@ -15,8 +15,7 @@ from OpenSSL import crypto -from oauth2client._helpers import _parse_pem_key -from oauth2client._helpers import _to_bytes +from oauth2client import _helpers class OpenSSLVerifier(object): @@ -43,8 +42,8 @@ class OpenSSLVerifier(object): True if message was signed by the private key associated with the public key that this object was constructed with. """ - message = _to_bytes(message, encoding='utf-8') - signature = _to_bytes(signature, encoding='utf-8') + message = _helpers._to_bytes(message, encoding='utf-8') + signature = _helpers._to_bytes(signature, encoding='utf-8') try: crypto.verify(self._pubkey, signature, message, 'sha256') return True @@ -66,7 +65,7 @@ class OpenSSLVerifier(object): Raises: 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: pubkey = crypto.load_certificate(crypto.FILETYPE_PEM, key_pem) else: @@ -94,7 +93,7 @@ class OpenSSLSigner(object): Returns: 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') @staticmethod @@ -111,12 +110,12 @@ class OpenSSLSigner(object): Raises: OpenSSL.crypto.Error if the key can't be parsed. """ - key = _to_bytes(key) - parsed_pem_key = _parse_pem_key(key) + key = _helpers._to_bytes(key) + parsed_pem_key = _helpers._parse_pem_key(key) if parsed_pem_key: pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, parsed_pem_key) else: - password = _to_bytes(password, encoding='utf-8') + password = _helpers._to_bytes(password, encoding='utf-8') pkey = crypto.load_pkcs12(key, password).get_privatekey() return OpenSSLSigner(pkey) @@ -131,7 +130,7 @@ def pkcs12_key_as_pem(private_key_bytes, private_key_password): Returns: 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) return crypto.dump_privatekey(crypto.FILETYPE_PEM, pkcs12.get_privatekey()) diff --git a/oauth2client/_pure_python_crypt.py b/oauth2client/_pure_python_crypt.py index af98477..2c5d43a 100644 --- a/oauth2client/_pure_python_crypt.py +++ b/oauth2client/_pure_python_crypt.py @@ -26,8 +26,7 @@ from pyasn1_modules.rfc5208 import PrivateKeyInfo import rsa import six -from oauth2client._helpers import _from_bytes -from oauth2client._helpers import _to_bytes +from oauth2client import _helpers _PKCS12_ERROR = r"""\ @@ -86,7 +85,7 @@ class RsaVerifier(object): True if message was signed by the private key associated with the public key that this object was constructed with. """ - message = _to_bytes(message, encoding='utf-8') + message = _helpers._to_bytes(message, encoding='utf-8') try: return rsa.pkcs1.verify(message, signature, self._pubkey) except (ValueError, rsa.pkcs1.VerificationError): @@ -111,7 +110,7 @@ class RsaVerifier(object): "-----BEGIN CERTIFICATE-----" error, otherwise fails to find "-----BEGIN RSA PUBLIC KEY-----". """ - key_pem = _to_bytes(key_pem) + key_pem = _helpers._to_bytes(key_pem) if is_x509_cert: der = rsa.pem.load_pem(key_pem, 'CERTIFICATE') asn1_cert, remaining = decoder.decode(der, asn1Spec=Certificate()) @@ -145,7 +144,7 @@ class RsaSigner(object): Returns: 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') @classmethod @@ -164,7 +163,7 @@ class RsaSigner(object): ValueError if the key cannot be parsed as PKCS#1 or PKCS#8 in 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( six.StringIO(key), _PKCS1_MARKER, _PKCS8_MARKER) diff --git a/oauth2client/_pycrypto_crypt.py b/oauth2client/_pycrypto_crypt.py index 0b31ba3..fd2ce0c 100644 --- a/oauth2client/_pycrypto_crypt.py +++ b/oauth2client/_pycrypto_crypt.py @@ -18,9 +18,7 @@ from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 from Crypto.Util.asn1 import DerSequence -from oauth2client._helpers import _parse_pem_key -from oauth2client._helpers import _to_bytes -from oauth2client._helpers import _urlsafe_b64decode +from oauth2client import _helpers class PyCryptoVerifier(object): @@ -47,7 +45,7 @@ class PyCryptoVerifier(object): True if message was signed by the private key associated with the 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( SHA256.new(message), signature) @@ -64,9 +62,9 @@ class PyCryptoVerifier(object): Verifier instance. """ if is_x509_cert: - key_pem = _to_bytes(key_pem) + key_pem = _helpers._to_bytes(key_pem) 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.decode(certDer) tbsSeq = DerSequence() @@ -97,7 +95,7 @@ class PyCryptoSigner(object): Returns: 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)) @staticmethod @@ -115,7 +113,7 @@ class PyCryptoSigner(object): Raises: 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: pkey = RSA.importKey(parsed_pem_key) else: diff --git a/oauth2client/client.py b/oauth2client/client.py index 1ae0e88..4efd492 100644 --- a/oauth2client/client.py +++ b/oauth2client/client.py @@ -32,16 +32,11 @@ import six from six.moves import http_client from six.moves import urllib +import oauth2client +from oauth2client import _helpers 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 util -from oauth2client._helpers import _from_bytes -from oauth2client._helpers import _urlsafe_b64decode __author__ = 'jcgregorio@google.com (Joe Gregorio)' @@ -294,7 +289,7 @@ class Credentials(object): An instance of the subclass of Credentials that was serialized with 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) # Find and call the right classmethod from_json() to restore # the object. @@ -619,7 +614,7 @@ class OAuth2Credentials(Credentials): Returns: 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 not isinstance(data['token_expiry'], datetime.datetime)): try: @@ -792,7 +787,7 @@ class OAuth2Credentials(Credentials): logger.info('Refreshing access_token') resp, content = http_request( self.token_uri, method='POST', body=body, headers=headers) - content = _from_bytes(content) + content = _helpers._from_bytes(content) if resp.status == http_client.OK: d = json.loads(content) self.token_response = d @@ -863,7 +858,7 @@ class OAuth2Credentials(Credentials): else: error_msg = 'Invalid response {0}.'.format(resp.status) try: - d = json.loads(_from_bytes(content)) + d = json.loads(_helpers._from_bytes(content)) if 'error' in d: error_msg = d['error'] except (TypeError, ValueError): @@ -902,7 +897,7 @@ class OAuth2Credentials(Credentials): token_info_uri = _update_query_params(self.token_info_uri, query_params) resp, content = http_request(token_info_uri) - content = _from_bytes(content) + content = _helpers._from_bytes(content) if resp.status == http_client.OK: d = json.loads(content) self.scopes = set(util.string_to_scopes(d.get('scope', ''))) @@ -968,7 +963,7 @@ class AccessTokenCredentials(OAuth2Credentials): @classmethod def from_json(cls, json_data): - data = json.loads(_from_bytes(json_data)) + data = json.loads(_helpers._from_bytes(json_data)) retval = AccessTokenCredentials( data['access_token'], data['user_agent']) @@ -1091,7 +1086,7 @@ class GoogleCredentials(OAuth2Credentials): def __init__(self, access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, - revoke_uri=GOOGLE_REVOKE_URI): + revoke_uri=oauth2client.GOOGLE_REVOKE_URI): """Create an instance of GoogleCredentials. 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 application. revoke_uri: string, URI for revoke endpoint. Defaults to - GOOGLE_REVOKE_URI; a token can't be revoked if this - is None. + oauth2client.GOOGLE_REVOKE_URI; a token can't be + revoked if this is None. """ super(GoogleCredentials, self).__init__( access_token, client_id, client_secret, refresh_token, @@ -1135,18 +1130,17 @@ class GoogleCredentials(OAuth2Credentials): def from_json(cls, json_data): # TODO(issue 388): eliminate the circularity that is the reason for # this non-top-level import. - from oauth2client.service_account import ServiceAccountCredentials - from oauth2client.service_account import _JWTAccessCredentials - data = json.loads(_from_bytes(json_data)) + from oauth2client import service_account + data = json.loads(_helpers._from_bytes(json_data)) # We handle service_account.ServiceAccountCredentials since it is a # possible return type of GoogleCredentials.get_application_default() if (data['_module'] == 'oauth2client.service_account' and data['_class'] == 'ServiceAccountCredentials'): - return ServiceAccountCredentials.from_json(data) + return service_account.ServiceAccountCredentials.from_json(data) elif (data['_module'] == 'oauth2client.service_account' and data['_class'] == '_JWTAccessCredentials'): - return _JWTAccessCredentials.from_json(data) + return service_account._JWTAccessCredentials.from_json(data) token_expiry = _parse_expiry(data.get('token_expiry')) google_credentials = cls( @@ -1423,11 +1417,11 @@ def _get_application_default_credential_from_file(filename): client_secret=client_credentials['client_secret'], refresh_token=client_credentials['refresh_token'], token_expiry=None, - token_uri=GOOGLE_TOKEN_URI, + token_uri=oauth2client.GOOGLE_TOKEN_URI, user_agent='Python client library') else: # client_credentials['type'] == SERVICE_ACCOUNT - from oauth2client.service_account import _JWTAccessCredentials - return _JWTAccessCredentials.from_json_keyfile_dict( + from oauth2client import service_account + return service_account._JWTAccessCredentials.from_json_keyfile_dict( client_credentials) @@ -1469,8 +1463,8 @@ class AssertionCredentials(GoogleCredentials): @util.positional(2) def __init__(self, assertion_type, user_agent=None, - token_uri=GOOGLE_TOKEN_URI, - revoke_uri=GOOGLE_REVOKE_URI, + token_uri=oauth2client.GOOGLE_TOKEN_URI, + revoke_uri=oauth2client.GOOGLE_REVOKE_URI, **unused_kwargs): """Constructor for AssertionFlowCredentials. @@ -1572,7 +1566,7 @@ def verify_id_token(id_token, audience, http=None, resp, content = http.request(cert_uri) 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) else: raise VerifyJwtTokenError('Status code: {0}'.format(resp.status)) @@ -1598,7 +1592,8 @@ def _extract_id_token(id_token): raise VerifyJwtTokenError( '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): @@ -1615,7 +1610,7 @@ def _parse_exchange_token_response(content): i.e. {}. That basically indicates a failure. """ resp = {} - content = _from_bytes(content) + content = _helpers._from_bytes(content) try: resp = json.loads(content) except Exception: @@ -1633,11 +1628,12 @@ def _parse_exchange_token_response(content): @util.positional(4) def credentials_from_code(client_id, client_secret, scope, code, redirect_uri='postmessage', http=None, - user_agent=None, token_uri=GOOGLE_TOKEN_URI, - auth_uri=GOOGLE_AUTH_URI, - revoke_uri=GOOGLE_REVOKE_URI, - device_uri=GOOGLE_DEVICE_URI, - token_info_uri=GOOGLE_TOKEN_INFO_URI): + user_agent=None, + token_uri=oauth2client.GOOGLE_TOKEN_URI, + auth_uri=oauth2client.GOOGLE_AUTH_URI, + revoke_uri=oauth2client.GOOGLE_REVOKE_URI, + device_uri=oauth2client.GOOGLE_DEVICE_URI, + token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI): """Exchanges an authorization code for an OAuth2Credentials object. Args: @@ -1778,12 +1774,12 @@ class OAuth2WebServerFlow(Flow): scope=None, redirect_uri=None, user_agent=None, - auth_uri=GOOGLE_AUTH_URI, - token_uri=GOOGLE_TOKEN_URI, - revoke_uri=GOOGLE_REVOKE_URI, + auth_uri=oauth2client.GOOGLE_AUTH_URI, + token_uri=oauth2client.GOOGLE_TOKEN_URI, + revoke_uri=oauth2client.GOOGLE_REVOKE_URI, login_hint=None, - device_uri=GOOGLE_DEVICE_URI, - token_info_uri=GOOGLE_TOKEN_INFO_URI, + device_uri=oauth2client.GOOGLE_DEVICE_URI, + token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI, authorization_header=None, **kwargs): """Constructor for OAuth2WebServerFlow. @@ -1915,7 +1911,7 @@ class OAuth2WebServerFlow(Flow): resp, content = http.request(self.device_uri, method='POST', body=body, headers=headers) - content = _from_bytes(content) + content = _helpers._from_bytes(content) if resp.status == http_client.OK: try: flow_info = json.loads(content) diff --git a/oauth2client/contrib/_fcntl_opener.py b/oauth2client/contrib/_fcntl_opener.py index 754196d..ae6c85b 100644 --- a/oauth2client/contrib/_fcntl_opener.py +++ b/oauth2client/contrib/_fcntl_opener.py @@ -16,13 +16,10 @@ import errno import fcntl import time -from oauth2client.contrib.locked_file import _Opener -from oauth2client.contrib.locked_file import AlreadyLockedException -from oauth2client.contrib.locked_file import logger -from oauth2client.contrib.locked_file import validate_file +from oauth2client.contrib import locked_file -class _FcntlOpener(_Opener): +class _FcntlOpener(locked_file._Opener): """Open, lock, and unlock a file using fcntl.lockf.""" def open_and_lock(self, timeout, delay): @@ -39,11 +36,11 @@ class _FcntlOpener(_Opener): link. """ if self._locked: - raise AlreadyLockedException( + raise locked_file.AlreadyLockedException( 'File {0} is already locked'.format(self._filename)) start_time = time.time() - validate_file(self._filename) + locked_file.validate_file(self._filename) try: self._fh = open(self._filename, self._mode) except IOError as e: @@ -67,8 +64,8 @@ class _FcntlOpener(_Opener): raise # We could not acquire the lock. Try again. if (time.time() - start_time) >= timeout: - logger.warn('Could not lock %s in %s seconds', - self._filename, timeout) + locked_file.logger.warn('Could not lock %s in %s seconds', + self._filename, timeout) if self._fh: self._fh.close() self._fh = open(self._filename, self._fallback_mode) diff --git a/oauth2client/contrib/_metadata.py b/oauth2client/contrib/_metadata.py index 07ca619..10e6a69 100644 --- a/oauth2client/contrib/_metadata.py +++ b/oauth2client/contrib/_metadata.py @@ -24,9 +24,9 @@ import httplib2 from six.moves import http_client from six.moves.urllib import parse as urlparse +from oauth2client import _helpers +from oauth2client import client from oauth2client import util -from oauth2client._helpers import _from_bytes -from oauth2client.client import _UTCNOW 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: - decoded = _from_bytes(content) + decoded = _helpers._from_bytes(content) if response['content-type'] == 'application/json': return json.loads(decoded) else: @@ -118,6 +118,6 @@ def get_token(http_request, service_account='default'): token_json = get( http_request, 'instance/service-accounts/{0}/token'.format(service_account)) - token_expiry = _UTCNOW() + datetime.timedelta( + token_expiry = client._UTCNOW() + datetime.timedelta( seconds=token_json['expires_in']) return token_json['access_token'], token_expiry diff --git a/oauth2client/contrib/_win32_opener.py b/oauth2client/contrib/_win32_opener.py index aa14401..34b4f48 100644 --- a/oauth2client/contrib/_win32_opener.py +++ b/oauth2client/contrib/_win32_opener.py @@ -19,13 +19,10 @@ import pywintypes import win32con import win32file -from oauth2client.contrib.locked_file import _Opener -from oauth2client.contrib.locked_file import AlreadyLockedException -from oauth2client.contrib.locked_file import logger -from oauth2client.contrib.locked_file import validate_file +from oauth2client.contrib import locked_file -class _Win32Opener(_Opener): +class _Win32Opener(locked_file._Opener): """Open, lock, and unlock a file using windows primitives.""" # Error #33: @@ -50,11 +47,11 @@ class _Win32Opener(_Opener): link. """ if self._locked: - raise AlreadyLockedException( + raise locked_file.AlreadyLockedException( 'File {0} is already locked'.format(self._filename)) start_time = time.time() - validate_file(self._filename) + locked_file.validate_file(self._filename) try: self._fh = open(self._filename, self._mode) except IOError as e: @@ -86,8 +83,8 @@ class _Win32Opener(_Opener): # We could not acquire the lock. Try again. if (time.time() - start_time) >= timeout: - logger.warn('Could not lock %s in %s seconds', - self._filename, timeout) + locked_file.logger.warn('Could not lock %s in %s seconds', + self._filename, timeout) if self._fh: self._fh.close() self._fh = open(self._filename, self._fallback_mode) diff --git a/oauth2client/contrib/appengine.py b/oauth2client/contrib/appengine.py index 513825a..661105e 100644 --- a/oauth2client/contrib/appengine.py +++ b/oauth2client/contrib/appengine.py @@ -32,17 +32,10 @@ from google.appengine.ext.webapp.util import login_required import httplib2 import webapp2 as webapp +import oauth2client +from oauth2client import client 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.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 # This is a temporary fix for a Google internal issue. @@ -125,7 +118,7 @@ def xsrf_secret_key(): return str(secret) -class AppAssertionCredentials(AssertionCredentials): +class AppAssertionCredentials(client.AssertionCredentials): """Credentials object for App Engine Assertion Grants 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( scopes, service_account_id=self.service_account_id) except app_identity.Error as e: - raise AccessTokenRefreshError(str(e)) + raise client.AccessTokenRefreshError(str(e)) self.access_token = token @property @@ -235,7 +228,7 @@ class FlowProperty(db.Property): """ # Tell what the user type is. - data_type = Flow + data_type = client.Flow # For writing to datastore. def get_value_for_datastore(self, model_instance): @@ -250,7 +243,7 @@ class FlowProperty(db.Property): return pickle.loads(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( 'Property {0} must be convertible ' 'to a FlowThreeLegged instance ({1})'.format(self.name, value)) @@ -268,7 +261,7 @@ class CredentialsProperty(db.Property): """ # Tell what the user type is. - data_type = Credentials + data_type = client.Credentials # For writing to datastore. def get_value_for_datastore(self, model_instance): @@ -289,7 +282,7 @@ class CredentialsProperty(db.Property): if len(value) == 0: return None try: - credentials = Credentials.new_from_json(value) + credentials = client.Credentials.new_from_json(value) except ValueError: credentials = None return credentials @@ -297,14 +290,14 @@ class CredentialsProperty(db.Property): def validate(self, value): value = super(CredentialsProperty, self).validate(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( 'Property {0} must be convertible ' 'to a Credentials instance ({1})'.format(self.name, value)) return value -class StorageByKeyName(Storage): +class StorageByKeyName(client.Storage): """Store and retrieve a credential to and from the App Engine datastore. This Storage helper presumes the Credentials have been stored as a @@ -396,7 +389,7 @@ class StorageByKeyName(Storage): if self._cache: json = self._cache.get(self._key_name) if json: - credentials = Credentials.new_from_json(json) + credentials = client.Credentials.new_from_json(json) if credentials is None: entity = self._get_entity() if entity is not None: @@ -532,9 +525,9 @@ class OAuth2Decorator(object): @util.positional(4) def __init__(self, client_id, client_secret, scope, - auth_uri=GOOGLE_AUTH_URI, - token_uri=GOOGLE_TOKEN_URI, - revoke_uri=GOOGLE_REVOKE_URI, + auth_uri=oauth2client.GOOGLE_AUTH_URI, + token_uri=oauth2client.GOOGLE_TOKEN_URI, + revoke_uri=oauth2client.GOOGLE_REVOKE_URI, user_agent=None, message=None, callback_path='/oauth2callback', @@ -653,7 +646,7 @@ class OAuth2Decorator(object): return request_handler.redirect(self.authorize_url()) try: resp = method(request_handler, *args, **kwargs) - except AccessTokenRefreshError: + except client.AccessTokenRefreshError: return request_handler.redirect(self.authorize_url()) finally: self.credentials = None @@ -674,7 +667,7 @@ class OAuth2Decorator(object): if self.flow is None: redirect_uri = request_handler.request.relative_url( self._callback_path) # Usually /oauth2callback - self.flow = OAuth2WebServerFlow( + self.flow = client.OAuth2WebServerFlow( self._client_id, self._client_secret, self._scope, redirect_uri=redirect_uri, user_agent=self._user_agent, auth_uri=self._auth_uri, token_uri=self._token_uri, diff --git a/oauth2client/contrib/devshell.py b/oauth2client/contrib/devshell.py index 83a0578..b8bb978 100644 --- a/oauth2client/contrib/devshell.py +++ b/oauth2client/contrib/devshell.py @@ -19,12 +19,8 @@ import json import os import socket +from oauth2client import _helpers 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' @@ -84,7 +80,7 @@ def _SendRecv(): data = CREDENTIAL_INFO_REQUEST_JSON 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() if '\n' not in header: @@ -127,7 +123,7 @@ class DevshellCredentials(client.GoogleCredentials): expires_in = self.devshell_response.expires_in if expires_in is not None: delta = datetime.timedelta(seconds=expires_in) - self.token_expiry = _UTCNOW() + delta + self.token_expiry = client._UTCNOW() + delta else: self.token_expiry = None diff --git a/oauth2client/contrib/dictionary_storage.py b/oauth2client/contrib/dictionary_storage.py index 8d8e6cf..6ee333f 100644 --- a/oauth2client/contrib/dictionary_storage.py +++ b/oauth2client/contrib/dictionary_storage.py @@ -14,11 +14,10 @@ """Dictionary storage for OAuth2 Credentials.""" -from oauth2client.client import OAuth2Credentials -from oauth2client.client import Storage +from oauth2client import client -class DictionaryStorage(Storage): +class DictionaryStorage(client.Storage): """Store and retrieve credentials to and from a dictionary-like object. Args: @@ -46,7 +45,7 @@ class DictionaryStorage(Storage): if serialized is None: return None - credentials = OAuth2Credentials.from_json(serialized) + credentials = client.OAuth2Credentials.from_json(serialized) credentials.set_store(self) return credentials diff --git a/oauth2client/contrib/django_util/storage.py b/oauth2client/contrib/django_util/storage.py index 5b4dc16..5682919 100644 --- a/oauth2client/contrib/django_util/storage.py +++ b/oauth2client/contrib/django_util/storage.py @@ -14,10 +14,10 @@ """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. This Storage helper presumes the Credentials diff --git a/oauth2client/contrib/flask_util.py b/oauth2client/contrib/flask_util.py index 91bf7b8..47c3df1 100644 --- a/oauth2client/contrib/flask_util.py +++ b/oauth2client/contrib/flask_util.py @@ -182,10 +182,9 @@ except ImportError: # pragma: NO COVER import httplib2 import six.moves.http_client as httplib +from oauth2client import client from oauth2client import clientsecrets -from oauth2client.client import FlowExchangeError -from oauth2client.client import OAuth2WebServerFlow -from oauth2client.contrib.dictionary_storage import DictionaryStorage +from oauth2client.contrib import dictionary_storage __author__ = 'jonwayne@google.com (Jon Wayne Parrott)' @@ -263,7 +262,8 @@ class UserOAuth2(object): self.flow_kwargs = kwargs if storage is None: - storage = DictionaryStorage(session, key=_CREDENTIALS_KEY) + storage = dictionary_storage.DictionaryStorage( + session, key=_CREDENTIALS_KEY) self.storage = storage if scopes is None: @@ -341,7 +341,7 @@ class UserOAuth2(object): extra_scopes = kw.pop('scopes', []) scopes = set(self.scopes).union(set(extra_scopes)) - flow = OAuth2WebServerFlow( + flow = client.OAuth2WebServerFlow( client_id=self.client_id, client_secret=self.client_secret, scope=scopes, @@ -418,7 +418,7 @@ class UserOAuth2(object): # Exchange the auth code for credentials. try: credentials = flow.step2_exchange(code) - except FlowExchangeError as exchange_error: + except client.FlowExchangeError as exchange_error: current_app.logger.exception(exchange_error) content = 'An error occurred: {0}'.format(exchange_error) return content, httplib.BAD_REQUEST diff --git a/oauth2client/contrib/gce.py b/oauth2client/contrib/gce.py index cccf495..f3a6ca1 100644 --- a/oauth2client/contrib/gce.py +++ b/oauth2client/contrib/gce.py @@ -22,8 +22,7 @@ import warnings import httplib2 -from oauth2client.client import AssertionCredentials -from oauth2client.client import HttpAccessTokenRefreshError +from oauth2client import client 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 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( http_request, service_account=self.service_account_email) except httplib2.HttpLib2Error as e: - raise HttpAccessTokenRefreshError(str(e)) + raise client.HttpAccessTokenRefreshError(str(e)) @property def serialization_data(self): diff --git a/oauth2client/contrib/keyring_storage.py b/oauth2client/contrib/keyring_storage.py index 431b67b..f4f2e30 100644 --- a/oauth2client/contrib/keyring_storage.py +++ b/oauth2client/contrib/keyring_storage.py @@ -21,14 +21,13 @@ import threading import keyring -from oauth2client.client import Credentials -from oauth2client.client import Storage as BaseStorage +from oauth2client import client __author__ = 'jcgregorio@google.com (Joe Gregorio)' -class Storage(BaseStorage): +class Storage(client.Storage): """Store and retrieve a single credential to and from the keyring. To use this module you must have the keyring module installed. See @@ -44,9 +43,9 @@ class Storage(BaseStorage): 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() """ @@ -74,7 +73,7 @@ class Storage(BaseStorage): if content is not None: try: - credentials = Credentials.new_from_json(content) + credentials = client.Credentials.new_from_json(content) credentials.set_store(self) except ValueError: pass diff --git a/oauth2client/contrib/multiprocess_file_storage.py b/oauth2client/contrib/multiprocess_file_storage.py index 14e5fc3..e9e8c8c 100644 --- a/oauth2client/contrib/multiprocess_file_storage.py +++ b/oauth2client/contrib/multiprocess_file_storage.py @@ -85,8 +85,7 @@ import fasteners from six import iteritems from oauth2client import _helpers -from oauth2client.client import Credentials -from oauth2client.client import Storage as BaseStorage +from oauth2client import client #: 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', {})): try: credential_json = base64.b64decode(encoded_credential) - credential = Credentials.new_from_json(credential_json) + credential = client.Credentials.new_from_json(credential_json) credentials[key] = credential except: logger.warning( @@ -310,7 +309,7 @@ def _get_backend(filename): return _backends[filename] -class MultiprocessFileStorage(BaseStorage): +class MultiprocessFileStorage(client.Storage): """Multiprocess file credential storage. Args: diff --git a/oauth2client/contrib/multistore_file.py b/oauth2client/contrib/multistore_file.py index 9ad7a6f..dd4c8f4 100644 --- a/oauth2client/contrib/multistore_file.py +++ b/oauth2client/contrib/multistore_file.py @@ -50,10 +50,9 @@ import logging import os import threading +from oauth2client import client from oauth2client import util -from oauth2client.client import Credentials -from oauth2client.client import Storage as BaseStorage -from oauth2client.contrib.locked_file import LockedFile +from oauth2client.contrib import locked_file __author__ = 'jbeda@google.com (Joe Beda)' @@ -208,7 +207,7 @@ class _MultiStore(object): 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._read_only = False 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. self._data = None - class _Storage(BaseStorage): + class _Storage(client.Storage): """A Storage object that can read/write a single credential.""" def __init__(self, multistore, key): @@ -421,7 +420,7 @@ class _MultiStore(object): raw_key = cred_entry['key'] key = _dict_to_tuple_key(raw_key) credential = None - credential = Credentials.new_from_json( + credential = client.Credentials.new_from_json( json.dumps(cred_entry['credential'])) return (key, credential) diff --git a/oauth2client/contrib/sqlalchemy.py b/oauth2client/contrib/sqlalchemy.py index a05a9fe..7d9fd4b 100644 --- a/oauth2client/contrib/sqlalchemy.py +++ b/oauth2client/contrib/sqlalchemy.py @@ -20,7 +20,7 @@ Configuration ============= 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 table or put the column in a table with a belongs-to relationship to a user info table. @@ -30,11 +30,12 @@ column that's related to a user table by the `user_id` key. .. code-block:: python - from oauth2client.contrib.sql_alchemy import CredentialsType from sqlalchemy import Column, ForeignKey, Integer from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship + from oauth2client.contrib.sqlalchemy import CredentialsType + Base = declarative_base() @@ -60,9 +61,10 @@ We will reuse tables defined above. .. code-block:: python + from sqlalchemy.orm import Session + from oauth2client.client import OAuth2Credentials from oauth2client.contrib.sql_alchemy import Storage - from sqlalchemy.orm import Session session = Session() user = session.query(User).first() @@ -92,7 +94,7 @@ from __future__ import absolute_import import sqlalchemy.types -import oauth2client.client +from oauth2client import client 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. This helper presumes the Credentials have been stored as a Credentials column diff --git a/oauth2client/contrib/xsrfutil.py b/oauth2client/contrib/xsrfutil.py index 91545e7..c03e679 100644 --- a/oauth2client/contrib/xsrfutil.py +++ b/oauth2client/contrib/xsrfutil.py @@ -19,8 +19,8 @@ import binascii import hmac import time +from oauth2client import _helpers from oauth2client import util -from oauth2client._helpers import _to_bytes __authors__ = [ '"Doug Coker" ', @@ -49,12 +49,12 @@ def generate_token(key, user_id, action_id='', when=None): Returns: A string XSRF protection token. """ - digester = hmac.new(_to_bytes(key, encoding='utf-8')) - digester.update(_to_bytes(str(user_id), encoding='utf-8')) + digester = hmac.new(_helpers._to_bytes(key, encoding='utf-8')) + digester.update(_helpers._to_bytes(str(user_id), encoding='utf-8')) 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) - 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) digest = digester.digest() diff --git a/oauth2client/crypt.py b/oauth2client/crypt.py index 14eb4ef..1326098 100644 --- a/oauth2client/crypt.py +++ b/oauth2client/crypt.py @@ -19,15 +19,13 @@ import json import logging import time -from oauth2client._helpers import _from_bytes -from oauth2client._helpers import _json_encode -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 +from oauth2client import _helpers +from oauth2client import _pure_python_crypt +RsaSigner = _pure_python_crypt.RsaSigner +RsaVerifier = _pure_python_crypt.RsaVerifier + CLOCK_SKEW_SECS = 300 # 5 minutes in seconds AUTH_TOKEN_LIFETIME_SECS = 300 # 5 minutes in seconds MAX_TOKEN_LIFETIME_SECS = 86400 # 1 day in seconds @@ -44,17 +42,19 @@ def _bad_pkcs12_key_as_pem(*args, **kwargs): try: - from oauth2client._openssl_crypt import OpenSSLVerifier - from oauth2client._openssl_crypt import OpenSSLSigner - from oauth2client._openssl_crypt import pkcs12_key_as_pem + from oauth2client import _openssl_crypt + OpenSSLSigner = _openssl_crypt.OpenSSLSigner + OpenSSLVerifier = _openssl_crypt.OpenSSLVerifier + pkcs12_key_as_pem = _openssl_crypt.pkcs12_key_as_pem except ImportError: # pragma: NO COVER OpenSSLVerifier = None OpenSSLSigner = None pkcs12_key_as_pem = _bad_pkcs12_key_as_pem try: - from oauth2client._pycrypto_crypt import PyCryptoVerifier - from oauth2client._pycrypto_crypt import PyCryptoSigner + from oauth2client import _pycrypto_crypt + PyCryptoSigner = _pycrypto_crypt.PyCryptoSigner + PyCryptoVerifier = _pycrypto_crypt.PyCryptoVerifier except ImportError: # pragma: NO COVER PyCryptoVerifier = None PyCryptoSigner = None @@ -89,13 +89,13 @@ def make_signed_jwt(signer, payload, key_id=None): header['kid'] = key_id segments = [ - _urlsafe_b64encode(_json_encode(header)), - _urlsafe_b64encode(_json_encode(payload)), + _helpers._urlsafe_b64encode(_helpers._json_encode(header)), + _helpers._urlsafe_b64encode(_helpers._json_encode(payload)), ] signing_input = b'.'.join(segments) signature = signer.sign(signing_input) - segments.append(_urlsafe_b64encode(signature)) + segments.append(_helpers._urlsafe_b64encode(signature)) logger.debug(str(segments)) @@ -221,7 +221,7 @@ def verify_signed_jwt_with_certs(jwt, certs, audience=None): Raises: AppIdentityError: if any checks are failed. """ - jwt = _to_bytes(jwt) + jwt = _helpers._to_bytes(jwt) if jwt.count(b'.') != 2: raise AppIdentityError( @@ -229,12 +229,12 @@ def verify_signed_jwt_with_certs(jwt, certs, audience=None): header, payload, signature = jwt.split(b'.') message_to_sign = header + b'.' + payload - signature = _urlsafe_b64decode(signature) + signature = _helpers._urlsafe_b64decode(signature) # Parse token. - payload_bytes = _urlsafe_b64decode(payload) + payload_bytes = _helpers._urlsafe_b64decode(payload) try: - payload_dict = json.loads(_from_bytes(payload_bytes)) + payload_dict = json.loads(_helpers._from_bytes(payload_bytes)) except: raise AppIdentityError('Can\'t parse token: {0}'.format(payload_bytes)) diff --git a/oauth2client/file.py b/oauth2client/file.py index 5047937..feede11 100644 --- a/oauth2client/file.py +++ b/oauth2client/file.py @@ -21,8 +21,7 @@ credentials. import os import threading -from oauth2client.client import Credentials -from oauth2client.client import Storage as BaseStorage +from oauth2client import client __author__ = 'jcgregorio@google.com (Joe Gregorio)' @@ -32,7 +31,7 @@ class CredentialsFileSymbolicLinkError(Exception): """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.""" def __init__(self, filename): @@ -63,7 +62,7 @@ class Storage(BaseStorage): return credentials try: - credentials = Credentials.new_from_json(content) + credentials = client.Credentials.new_from_json(content) credentials.set_store(self) except ValueError: pass diff --git a/oauth2client/service_account.py b/oauth2client/service_account.py index 57cfc09..bdcfd69 100644 --- a/oauth2client/service_account.py +++ b/oauth2client/service_account.py @@ -20,17 +20,12 @@ import datetime import json import time +import oauth2client +from oauth2client import _helpers +from oauth2client import client from oauth2client import crypt -from oauth2client import GOOGLE_REVOKE_URI -from oauth2client import GOOGLE_TOKEN_URI from oauth2client import transport 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' @@ -45,7 +40,7 @@ to .pem format: """ -class ServiceAccountCredentials(AssertionCredentials): +class ServiceAccountCredentials(client.AssertionCredentials): """Service Account credential for OAuth 2.0 signed JWT grants. Supports @@ -89,7 +84,7 @@ class ServiceAccountCredentials(AssertionCredentials): NON_SERIALIZED_MEMBERS = ( frozenset(['_signer']) | - AssertionCredentials.NON_SERIALIZED_MEMBERS) + client.AssertionCredentials.NON_SERIALIZED_MEMBERS) """Members that aren't serialized when object is converted to JSON.""" # Can be over-ridden by factory constructors. Used for @@ -105,8 +100,8 @@ class ServiceAccountCredentials(AssertionCredentials): private_key_id=None, client_id=None, user_agent=None, - token_uri=GOOGLE_TOKEN_URI, - revoke_uri=GOOGLE_REVOKE_URI, + token_uri=oauth2client.GOOGLE_TOKEN_URI, + revoke_uri=oauth2client.GOOGLE_REVOKE_URI, **kwargs): super(ServiceAccountCredentials, self).__init__( @@ -173,18 +168,20 @@ class ServiceAccountCredentials(AssertionCredentials): the keyfile. """ creds_type = keyfile_dict.get('type') - if creds_type != SERVICE_ACCOUNT: + if creds_type != client.SERVICE_ACCOUNT: raise ValueError('Unexpected credentials type', creds_type, - 'Expected', SERVICE_ACCOUNT) + 'Expected', client.SERVICE_ACCOUNT) service_account_email = keyfile_dict['client_email'] private_key_pkcs8_pem = keyfile_dict['private_key'] private_key_id = keyfile_dict['private_key_id'] client_id = keyfile_dict['client_id'] 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: - 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) credentials = cls(service_account_email, signer, scopes=scopes, @@ -260,8 +257,8 @@ class ServiceAccountCredentials(AssertionCredentials): def _from_p12_keyfile_contents(cls, service_account_email, private_key_pkcs12, private_key_password=None, scopes='', - token_uri=GOOGLE_TOKEN_URI, - revoke_uri=GOOGLE_REVOKE_URI): + token_uri=oauth2client.GOOGLE_TOKEN_URI, + revoke_uri=oauth2client.GOOGLE_REVOKE_URI): """Factory constructor from JSON keyfile. Args: @@ -302,8 +299,8 @@ class ServiceAccountCredentials(AssertionCredentials): @classmethod def from_p12_keyfile(cls, service_account_email, filename, private_key_password=None, scopes='', - token_uri=GOOGLE_TOKEN_URI, - revoke_uri=GOOGLE_REVOKE_URI): + token_uri=oauth2client.GOOGLE_TOKEN_URI, + revoke_uri=oauth2client.GOOGLE_REVOKE_URI): """Factory constructor from JSON keyfile. @@ -340,8 +337,8 @@ class ServiceAccountCredentials(AssertionCredentials): @classmethod def from_p12_keyfile_buffer(cls, service_account_email, file_buffer, private_key_password=None, scopes='', - token_uri=GOOGLE_TOKEN_URI, - revoke_uri=GOOGLE_REVOKE_URI): + token_uri=oauth2client.GOOGLE_TOKEN_URI, + revoke_uri=oauth2client.GOOGLE_REVOKE_URI): """Factory constructor from JSON keyfile. Args: @@ -437,7 +434,7 @@ class ServiceAccountCredentials(AssertionCredentials): ServiceAccountCredentials from the serialized data. """ 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 pkcs12_val = json_data.get(_PKCS12_KEY) @@ -475,7 +472,7 @@ class ServiceAccountCredentials(AssertionCredentials): token_expiry = json_data.get('token_expiry', None) if token_expiry is not None: credentials.token_expiry = datetime.datetime.strptime( - token_expiry, EXPIRY_FORMAT) + token_expiry, client.EXPIRY_FORMAT) return credentials def create_scoped_required(self): @@ -570,8 +567,8 @@ class _JWTAccessCredentials(ServiceAccountCredentials): private_key_id=None, client_id=None, user_agent=None, - token_uri=GOOGLE_TOKEN_URI, - revoke_uri=GOOGLE_REVOKE_URI, + token_uri=oauth2client.GOOGLE_TOKEN_URI, + revoke_uri=oauth2client.GOOGLE_REVOKE_URI, additional_claims=None): if additional_claims is None: additional_claims = {} @@ -616,13 +613,13 @@ class _JWTAccessCredentials(ServiceAccountCredentials): if additional_claims is None: if self.access_token is None or self.access_token_expired: self.refresh(None) - return AccessTokenInfo(access_token=self.access_token, - expires_in=self._expires_in()) + return client.AccessTokenInfo( + access_token=self.access_token, expires_in=self._expires_in()) else: # Create a 1 time token token, unused_expiry = self._create_token(additional_claims) - return AccessTokenInfo(access_token=token, - expires_in=self._MAX_TOKEN_LIFETIME_SECS) + return client.AccessTokenInfo( + access_token=token, expires_in=self._MAX_TOKEN_LIFETIME_SECS) def revoke(self, http): """Cannot revoke JWTAccessCredentials tokens.""" @@ -632,8 +629,8 @@ class _JWTAccessCredentials(ServiceAccountCredentials): # JWTAccessCredentials are unscoped by definition return True - def create_scoped(self, scopes, token_uri=GOOGLE_TOKEN_URI, - revoke_uri=GOOGLE_REVOKE_URI): + def create_scoped(self, scopes, token_uri=oauth2client.GOOGLE_TOKEN_URI, + revoke_uri=oauth2client.GOOGLE_REVOKE_URI): # Returns an OAuth2 credentials with the given scope result = ServiceAccountCredentials(self._service_account_email, self._signer, @@ -659,7 +656,7 @@ class _JWTAccessCredentials(ServiceAccountCredentials): self.access_token, self.token_expiry = self._create_token() def _create_token(self, additional_claims=None): - now = _UTCNOW() + now = client._UTCNOW() lifetime = datetime.timedelta(seconds=self._MAX_TOKEN_LIFETIME_SECS) expiry = now + lifetime payload = { diff --git a/tests/contrib/django_util/test_decorators.py b/tests/contrib/django_util/test_decorators.py index 8902d0d..846c6dd 100644 --- a/tests/contrib/django_util/test_decorators.py +++ b/tests/contrib/django_util/test_decorators.py @@ -60,7 +60,7 @@ class OAuth2EnabledDecoratorTest(TestWithDjangoEnvironment): self.assertFalse(request.oauth.has_credentials()) 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): request = self.factory.get('/test') request.session = mock.MagicMock() @@ -156,7 +156,7 @@ class OAuth2RequiredDecoratorTest(TestWithDjangoEnvironment): self.assertEqual(response.status_code, http_client.OK) 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( self, OAuth2Credentials): request = self.factory.get('/test') @@ -176,7 +176,7 @@ class OAuth2RequiredDecoratorTest(TestWithDjangoEnvironment): self.assertEqual( 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): request = self.factory.get('/test') request.session = mock.MagicMock() diff --git a/tests/contrib/test__appengine_ndb.py b/tests/contrib/test__appengine_ndb.py index 6bb1cde..41e3805 100644 --- a/tests/contrib/test__appengine_ndb.py +++ b/tests/contrib/test__appengine_ndb.py @@ -20,10 +20,8 @@ from google.appengine.ext import testbed import mock import unittest2 -from oauth2client.client import Credentials -from oauth2client.client import flow_from_clientsecrets -from oauth2client.contrib.appengine import CredentialsNDBProperty -from oauth2client.contrib.appengine import FlowNDBProperty +from oauth2client import client +from oauth2client.contrib import appengine DATA_DIR = os.path.join(os.path.dirname(__file__), '..', 'data') @@ -34,8 +32,8 @@ def datafile(filename): class TestNDBModel(ndb.Model): - flow = FlowNDBProperty() - creds = CredentialsNDBProperty() + flow = appengine.FlowNDBProperty() + creds = appengine.CredentialsNDBProperty() class TestFlowNDBProperty(unittest2.TestCase): @@ -51,8 +49,8 @@ class TestFlowNDBProperty(unittest2.TestCase): def test_flow_get_put(self): instance = TestNDBModel( - flow=flow_from_clientsecrets(datafile('client_secrets.json'), - 'foo', redirect_uri='oob'), + flow=client.flow_from_clientsecrets( + datafile('client_secrets.json'), 'foo', redirect_uri='oob'), id='foo' ) instance.put() @@ -63,8 +61,8 @@ class TestFlowNDBProperty(unittest2.TestCase): @mock.patch('oauth2client.contrib._appengine_ndb._LOGGER') def test_validate_success(self, mock_logger): flow_prop = TestNDBModel.flow - flow_val = flow_from_clientsecrets(datafile('client_secrets.json'), - 'foo', redirect_uri='oob') + flow_val = client.flow_from_clientsecrets( + datafile('client_secrets.json'), 'foo', redirect_uri='oob') flow_prop._validate(flow_val) mock_logger.info.assert_called_once_with('validate: Got type %s', type(flow_val)) @@ -99,16 +97,16 @@ class TestCredentialsNDBProperty(unittest2.TestCase): self.testbed.deactivate() def test_valid_creds_get_put(self): - creds = Credentials() + creds = client.Credentials() instance = TestNDBModel(creds=creds, id='bar') instance.put() retrieved = TestNDBModel.get_by_id('bar') - self.assertIsInstance(retrieved.creds, Credentials) + self.assertIsInstance(retrieved.creds, client.Credentials) @mock.patch('oauth2client.contrib._appengine_ndb._LOGGER') def test_validate_success(self, mock_logger): creds_prop = TestNDBModel.creds - creds_val = Credentials() + creds_val = client.Credentials() creds_prop._validate(creds_val) mock_logger.info.assert_called_once_with('validate: Got type %s', type(creds_val)) @@ -132,7 +130,7 @@ class TestCredentialsNDBProperty(unittest2.TestCase): def test__to_base_type_valid_creds(self): creds_prop = TestNDBModel.creds - creds = Credentials() + creds = client.Credentials() creds_json = json.loads(creds_prop._to_base_type(creds)) self.assertDictEqual(creds_json, { '_class': 'Credentials', @@ -152,7 +150,7 @@ class TestCredentialsNDBProperty(unittest2.TestCase): 'token_expiry': None, }) 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): creds_prop = TestNDBModel.creds diff --git a/tests/contrib/test_appengine.py b/tests/contrib/test_appengine.py index 5f1770c..af544e3 100644 --- a/tests/contrib/test_appengine.py +++ b/tests/contrib/test_appengine.py @@ -38,27 +38,10 @@ import unittest2 import webapp2 from webtest import TestApp -from oauth2client import GOOGLE_REVOKE_URI -from oauth2client import GOOGLE_TOKEN_URI -from oauth2client.client import _CLOUDSDK_CONFIG_ENV_VAR -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 +import oauth2client +from oauth2client import client +from oauth2client import clientsecrets 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 __author__ = 'jcgregorio@google.com (Joe Gregorio)' @@ -71,7 +54,7 @@ def datafile(filename): 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} @@ -155,9 +138,9 @@ class TestAppAssertionCredentials(unittest2.TestCase): 'memcache', memcache_stub.MemcacheServiceStub()) scope = 'http://www.googleapis.com/scope' - credentials = AppAssertionCredentials(scope) + credentials = appengine.AppAssertionCredentials(scope) http = httplib2.Http() - with self.assertRaises(AccessTokenRefreshError): + with self.assertRaises(client.AccessTokenRefreshError): credentials.refresh(http) def test_get_access_token_on_refresh(self): @@ -171,20 +154,20 @@ class TestAppAssertionCredentials(unittest2.TestCase): scope = [ "http://www.googleapis.com/scope", "http://www.googleapis.com/scope2"] - credentials = AppAssertionCredentials(scope) + credentials = appengine.AppAssertionCredentials(scope) http = httplib2.Http() credentials.refresh(http) self.assertEqual('a_token_123', credentials.access_token) json = credentials.to_json() - credentials = Credentials.new_from_json(json) + credentials = client.Credentials.new_from_json(json) self.assertEqual( 'http://www.googleapis.com/scope http://www.googleapis.com/scope2', credentials.scope) scope = ('http://www.googleapis.com/scope ' 'http://www.googleapis.com/scope2') - credentials = AppAssertionCredentials(scope) + credentials = appengine.AppAssertionCredentials(scope) http = httplib2.Http() credentials.refresh(http) 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', return_value=('a_token_456', None), autospec=True) as get_access_token: - credentials = AppAssertionCredentials( + credentials = appengine.AppAssertionCredentials( scope, service_account_id=account_id) http = httplib2.Http() credentials.refresh(http) @@ -210,18 +193,19 @@ class TestAppAssertionCredentials(unittest2.TestCase): [scope], service_account_id=account_id) def test_create_scoped_required_without_scopes(self): - credentials = AppAssertionCredentials([]) + credentials = appengine.AppAssertionCredentials([]) self.assertTrue(credentials.create_scoped_required()) def test_create_scoped_required_with_scopes(self): - credentials = AppAssertionCredentials(['dummy_scope']) + credentials = appengine.AppAssertionCredentials(['dummy_scope']) self.assertFalse(credentials.create_scoped_required()) def test_create_scoped(self): - credentials = AppAssertionCredentials([]) + credentials = appengine.AppAssertionCredentials([]) new_credentials = credentials.create_scoped(['dummy_scope']) self.assertNotEqual(credentials, new_credentials) - self.assertIsInstance(new_credentials, AppAssertionCredentials) + self.assertIsInstance( + new_credentials, appengine.AppAssertionCredentials) self.assertEqual('dummy_scope', new_credentials.scope) 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.RegisterStub('app_identity_service', app_identity_stub) - credentials = AppAssertionCredentials([]) + credentials = appengine.AppAssertionCredentials([]) to_sign = b'blob' self.assertEqual(app_identity_stub._sign_calls, []) result = credentials.sign_blob(to_sign) @@ -246,7 +230,7 @@ class TestAppAssertionCredentials(unittest2.TestCase): apiproxy_stub_map.apiproxy.RegisterStub('app_identity_service', app_identity_stub) - credentials = AppAssertionCredentials([]) + credentials = appengine.AppAssertionCredentials([]) self.assertIsNone(credentials._service_account_email) self.assertEqual(app_identity_stub._get_acct_name_calls, 0) self.assertEqual(credentials.service_account_email, acct_name) @@ -255,7 +239,7 @@ class TestAppAssertionCredentials(unittest2.TestCase): def test_service_account_email_already_set(self): acct_name = 'existing@appspot.gserviceaccount.com' - credentials = AppAssertionCredentials([]) + credentials = appengine.AppAssertionCredentials([]) credentials._service_account_email = acct_name app_identity_stub = self.AppIdentityStubImpl(svc_acct=acct_name) @@ -275,21 +259,21 @@ class TestAppAssertionCredentials(unittest2.TestCase): apiproxy_stub_map.apiproxy.RegisterStub( 'memcache', memcache_stub.MemcacheServiceStub()) - credentials = AppAssertionCredentials(['dummy_scope']) + credentials = appengine.AppAssertionCredentials(['dummy_scope']) token = credentials.get_access_token() self.assertEqual('a_token_123', token.access_token) self.assertEqual(None, token.expires_in) def test_save_to_well_known_file(self): - os.environ[_CLOUDSDK_CONFIG_ENV_VAR] = tempfile.mkdtemp() - credentials = AppAssertionCredentials([]) + os.environ[client._CLOUDSDK_CONFIG_ENV_VAR] = tempfile.mkdtemp() + credentials = appengine.AppAssertionCredentials([]) with self.assertRaises(NotImplementedError): - save_to_well_known_file(credentials) - del os.environ[_CLOUDSDK_CONFIG_ENV_VAR] + client.save_to_well_known_file(credentials) + del os.environ[client._CLOUDSDK_CONFIG_ENV_VAR] class TestFlowModel(db.Model): - flow = FlowProperty() + flow = appengine.FlowProperty() class FlowPropertyTest(unittest2.TestCase): @@ -299,7 +283,7 @@ class FlowPropertyTest(unittest2.TestCase): self.testbed.activate() self.testbed.init_datastore_v3_stub() - self.flow = flow_from_clientsecrets( + self.flow = client.flow_from_clientsecrets( datafile('client_secrets.json'), 'foo', redirect_uri='oob') @@ -318,16 +302,17 @@ class FlowPropertyTest(unittest2.TestCase): self.assertEqual('foo_client_id', retrieved.flow.client_id) 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): - FlowProperty().validate(None) + appengine.FlowProperty().validate(None) with self.assertRaises(db.BadValueError): - FlowProperty().validate(42) + appengine.FlowProperty().validate(42) class TestCredentialsModel(db.Model): - credentials = CredentialsProperty() + credentials = appengine.CredentialsProperty() class CredentialsPropertyTest(unittest2.TestCase): @@ -343,9 +328,9 @@ class CredentialsPropertyTest(unittest2.TestCase): refresh_token = '1/0/a.df219fjls0' token_expiry = datetime.datetime.utcnow() user_agent = 'refresh_checker/1.0' - self.credentials = OAuth2Credentials( + self.credentials = client.OAuth2Credentials( access_token, client_id, client_secret, - refresh_token, token_expiry, GOOGLE_TOKEN_URI, + refresh_token, token_expiry, oauth2client.GOOGLE_TOKEN_URI, user_agent) def tearDown(self): @@ -365,23 +350,23 @@ class CredentialsPropertyTest(unittest2.TestCase): def test_make_value_from_datastore(self): self.assertIsNone( - CredentialsProperty().make_value_from_datastore(None)) + appengine.CredentialsProperty().make_value_from_datastore(None)) self.assertIsNone( - CredentialsProperty().make_value_from_datastore('')) + appengine.CredentialsProperty().make_value_from_datastore('')) 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.assertEqual( self.credentials.to_json(), decoded.to_json()) def test_validate(self): - CredentialsProperty().validate(self.credentials) - CredentialsProperty().validate(None) + appengine.CredentialsProperty().validate(self.credentials) + appengine.CredentialsProperty().validate(None) with self.assertRaises(db.BadValueError): - CredentialsProperty().validate(42) + appengine.CredentialsProperty().validate(42) def _http_request(*args, **kwargs): @@ -406,9 +391,9 @@ class StorageByKeyNameTest(unittest2.TestCase): refresh_token = '1/0/a.df219fjls0' token_expiry = datetime.datetime.utcnow() user_agent = 'refresh_checker/1.0' - self.credentials = OAuth2Credentials( + self.credentials = client.OAuth2Credentials( access_token, client_id, client_secret, - refresh_token, token_expiry, GOOGLE_TOKEN_URI, + refresh_token, token_expiry, oauth2client.GOOGLE_TOKEN_URI, user_agent) def tearDown(self): @@ -416,10 +401,10 @@ class StorageByKeyNameTest(unittest2.TestCase): def test_bad_ctor(self): with self.assertRaises(ValueError): - StorageByKeyName(CredentialsModel, None, None) + appengine.StorageByKeyName(appengine.CredentialsModel, None, None) def test__is_ndb(self): - storage = StorageByKeyName( + storage = appengine.StorageByKeyName( object(), 'foo', 'credentials') with self.assertRaises(TypeError): @@ -429,32 +414,32 @@ class StorageByKeyNameTest(unittest2.TestCase): with self.assertRaises(TypeError): storage._is_ndb() - storage._model = CredentialsModel + storage._model = appengine.CredentialsModel self.assertFalse(storage._is_ndb()) - storage._model = CredentialsNDBModel + storage._model = appengine.CredentialsNDBModel self.assertTrue(storage._is_ndb()) def test_get_and_put_simple(self): - storage = StorageByKeyName( - CredentialsModel, 'foo', 'credentials') + storage = appengine.StorageByKeyName( + appengine.CredentialsModel, 'foo', 'credentials') self.assertEqual(None, storage.get()) self.credentials.set_store(storage) 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) def test_get_and_put_cached(self): - storage = StorageByKeyName( - CredentialsModel, 'foo', 'credentials', cache=memcache) + storage = appengine.StorageByKeyName( + appengine.CredentialsModel, 'foo', 'credentials', cache=memcache) self.assertEqual(None, storage.get()) self.credentials.set_store(storage) 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) # Now remove the item from the cache. @@ -472,8 +457,8 @@ class StorageByKeyNameTest(unittest2.TestCase): self.assertEqual(None, memcache.get('foo')) def test_get_and_put_set_store_on_cache_retrieval(self): - storage = StorageByKeyName( - CredentialsModel, 'foo', 'credentials', cache=memcache) + storage = appengine.StorageByKeyName( + appengine.CredentialsModel, 'foo', 'credentials', cache=memcache) self.assertEqual(None, storage.get()) self.credentials.set_store(storage) @@ -489,28 +474,28 @@ class StorageByKeyNameTest(unittest2.TestCase): def test_get_and_put_ndb(self): # Start empty - storage = StorageByKeyName( - CredentialsNDBModel, 'foo', 'credentials') + storage = appengine.StorageByKeyName( + appengine.CredentialsNDBModel, 'foo', 'credentials') self.assertEqual(None, storage.get()) # Refresh storage and retrieve without using storage self.credentials.set_store(storage) 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(credmodel.credentials.to_json(), self.credentials.to_json()) def test_delete_ndb(self): # Start empty - storage = StorageByKeyName( - CredentialsNDBModel, 'foo', 'credentials') + storage = appengine.StorageByKeyName( + appengine.CredentialsNDBModel, 'foo', 'credentials') self.assertEqual(None, storage.get()) # Add credentials to model with storage, and check equivalent # w/o storage storage.put(self.credentials) - credmodel = CredentialsNDBModel.get_by_id('foo') + credmodel = appengine.CredentialsNDBModel.get_by_id('foo') self.assertEqual(credmodel.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): # Start empty - storage = StorageByKeyName( - CredentialsNDBModel, 'foo', 'credentials') + storage = appengine.StorageByKeyName( + appengine.CredentialsNDBModel, 'foo', 'credentials') self.assertEqual(None, storage.get()) # Set NDB store and refresh to add to storage @@ -529,15 +514,15 @@ class StorageByKeyNameTest(unittest2.TestCase): self.credentials._refresh(_http_request) # 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(self.credentials.to_json(), credmodel.credentials.to_json()) def test_get_and_put_mixed_db_storage_ndb_get(self): # Start empty - storage = StorageByKeyName( - CredentialsModel, 'foo', 'credentials') + storage = appengine.StorageByKeyName( + appengine.CredentialsModel, 'foo', 'credentials') self.assertEqual(None, storage.get()) # Set DB store and refresh to add to storage @@ -545,17 +530,17 @@ class StorageByKeyNameTest(unittest2.TestCase): self.credentials._refresh(_http_request) # 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(self.credentials.to_json(), credmodel.credentials.to_json()) def test_delete_db_ndb_mixed(self): # Start empty - storage_ndb = StorageByKeyName( - CredentialsNDBModel, 'foo', 'credentials') - storage = StorageByKeyName( - CredentialsModel, 'foo', 'credentials') + storage_ndb = appengine.StorageByKeyName( + appengine.CredentialsNDBModel, 'foo', 'credentials') + storage = appengine.StorageByKeyName( + appengine.CredentialsModel, 'foo', 'credentials') # First DB, then NDB self.assertEqual(None, storage.get()) @@ -597,10 +582,9 @@ class DecoratorTests(unittest2.TestCase): self.testbed.init_memcache_stub() self.testbed.init_user_stub() - decorator = OAuth2Decorator(client_id='foo_client_id', - client_secret='foo_client_secret', - scope=['foo_scope', 'bar_scope'], - user_agent='foo') + decorator = appengine.OAuth2Decorator( + client_id='foo_client_id', client_secret='foo_client_secret', + scope=['foo_scope', 'bar_scope'], user_agent='foo') self._finish_setup(decorator, user_mock=UserMock) @@ -731,7 +715,7 @@ class DecoratorTests(unittest2.TestCase): self.assertEqual(None, self.decorator.credentials) # Access token refresh error should start the dance again - self.should_raise = AccessTokenRefreshError() + self.should_raise = client.AccessTokenRefreshError() response = self.app.get('/foo_path') self.should_raise = False self.assertTrue(response.status.startswith('302')) @@ -853,13 +837,11 @@ class DecoratorTests(unittest2.TestCase): self.assertTrue('Bad<Stuff>Happened'' in response.body) def test_kwargs_are_passed_to_underlying_flow(self): - decorator = OAuth2Decorator(client_id='foo_client_id', - client_secret='foo_client_secret', - user_agent='foo_user_agent', - scope=['foo_scope', 'bar_scope'], - access_type='offline', - approval_prompt='force', - revoke_uri='dummy_revoke_uri') + decorator = appengine.OAuth2Decorator( + client_id='foo_client_id', client_secret='foo_client_secret', + user_agent='foo_user_agent', scope=['foo_scope', 'bar_scope'], + access_type='offline', approval_prompt='force', + revoke_uri='dummy_revoke_uri') request_handler = MockRequestHandler() decorator._create_flow(request_handler) @@ -877,7 +859,7 @@ class DecoratorTests(unittest2.TestCase): self.test_required() def test_decorator_from_client_secrets(self): - decorator = OAuth2DecoratorFromClientSecrets( + decorator = appengine.OAuth2DecoratorFromClientSecrets( datafile('client_secrets.json'), scope=['foo_scope', 'bar_scope']) self._finish_setup(decorator, user_mock=UserMock) @@ -901,7 +883,8 @@ class DecoratorTests(unittest2.TestCase): with decorator_patch as decorator_mock: 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( filename, 'foo_scope', @@ -919,13 +902,13 @@ class DecoratorTests(unittest2.TestCase): 'oauth2client.contrib.appengine.clientsecrets.loadfile') with loadfile_patch as loadfile_mock: loadfile_mock.return_value = ('badtype', None) - with self.assertRaises(InvalidClientSecretsError): - OAuth2DecoratorFromClientSecrets( + with self.assertRaises(clientsecrets.InvalidClientSecretsError): + appengine.OAuth2DecoratorFromClientSecrets( 'doesntmatter.json', scope=['foo_scope', 'bar_scope']) def test_decorator_from_client_secrets_kwargs(self): - decorator = OAuth2DecoratorFromClientSecrets( + decorator = appengine.OAuth2DecoratorFromClientSecrets( datafile('client_secrets.json'), scope=['foo_scope', 'bar_scope'], approval_prompt='force') @@ -934,13 +917,13 @@ class DecoratorTests(unittest2.TestCase): def test_decorator_from_cached_client_secrets(self): cache_mock = CacheMock() load_and_cache('client_secrets.json', 'secret', cache_mock) - decorator = OAuth2DecoratorFromClientSecrets( + decorator = appengine.OAuth2DecoratorFromClientSecrets( # filename, scope, message=None, cache=None 'secret', '', cache=cache_mock) self.assertFalse(decorator._in_error) def test_decorator_from_client_secrets_not_logged_in_required(self): - decorator = OAuth2DecoratorFromClientSecrets( + decorator = appengine.OAuth2DecoratorFromClientSecrets( datafile('client_secrets.json'), scope=['foo_scope', 'bar_scope'], message='NotLoggedInMessage') self.decorator = decorator @@ -955,7 +938,7 @@ class DecoratorTests(unittest2.TestCase): self.assertTrue('Login' in str(response)) def test_decorator_from_client_secrets_not_logged_in_aware(self): - decorator = OAuth2DecoratorFromClientSecrets( + decorator = appengine.OAuth2DecoratorFromClientSecrets( datafile('client_secrets.json'), scope=['foo_scope', 'bar_scope'], message='NotLoggedInMessage') self.decorator = decorator @@ -970,19 +953,19 @@ class DecoratorTests(unittest2.TestCase): def test_decorator_from_unfilled_client_secrets_required(self): MESSAGE = 'File is missing' try: - OAuth2DecoratorFromClientSecrets( + appengine.OAuth2DecoratorFromClientSecrets( datafile('unfilled_client_secrets.json'), scope=['foo_scope', 'bar_scope'], message=MESSAGE) - except InvalidClientSecretsError: + except clientsecrets.InvalidClientSecretsError: pass def test_decorator_from_unfilled_client_secrets_aware(self): MESSAGE = 'File is missing' try: - OAuth2DecoratorFromClientSecrets( + appengine.OAuth2DecoratorFromClientSecrets( datafile('unfilled_client_secrets.json'), scope=['foo_scope', 'bar_scope'], message=MESSAGE) - except InvalidClientSecretsError: + except clientsecrets.InvalidClientSecretsError: pass def test_decorator_from_client_secrets_with_optional_settings(self): @@ -991,7 +974,7 @@ class DecoratorTests(unittest2.TestCase): loadfile_patch = mock.patch( 'oauth2client.contrib.appengine.clientsecrets.loadfile') 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_secret": "foo_client_secret", "redirect_uris": [], @@ -1000,11 +983,11 @@ class DecoratorTests(unittest2.TestCase): # No revoke URI }) - decorator = OAuth2DecoratorFromClientSecrets( + decorator = appengine.OAuth2DecoratorFromClientSecrets( 'doesntmatter.json', 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. self.assertFalse(decorator._in_error) diff --git a/tests/contrib/test_devshell.py b/tests/contrib/test_devshell.py index e685134..659a53b 100644 --- a/tests/contrib/test_devshell.py +++ b/tests/contrib/test_devshell.py @@ -23,17 +23,9 @@ import threading import mock import unittest2 -from oauth2client._helpers import _from_bytes -from oauth2client._helpers import _to_bytes -from oauth2client.client import save_to_well_known_file +from oauth2client import _helpers +from oauth2client import client 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 # in CredentialInfoResponse. @@ -51,15 +43,15 @@ class TestCredentialInfoResponse(unittest2.TestCase): def test_constructor_with_non_list(self): json_non_list = '{}' with self.assertRaises(ValueError): - CredentialInfoResponse(json_non_list) + devshell.CredentialInfoResponse(json_non_list) def test_constructor_with_bad_json(self): json_non_list = '{BADJSON' with self.assertRaises(ValueError): - CredentialInfoResponse(json_non_list) + devshell.CredentialInfoResponse(json_non_list) def test_constructor_empty_list(self): - info_response = CredentialInfoResponse('[]') + info_response = devshell.CredentialInfoResponse('[]') self.assertEqual(info_response.user_email, None) self.assertEqual(info_response.project_id, None) self.assertEqual(info_response.access_token, None) @@ -72,7 +64,7 @@ class TestCredentialInfoResponse(unittest2.TestCase): expires_in = 1 json_string = json.dumps( [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.project_id, project_id) self.assertEqual(info_response.access_token, access_token) @@ -84,9 +76,9 @@ class Test_SendRecv(unittest2.TestCase): def test_port_zero(self): with mock.patch('oauth2client.contrib.devshell.os') as os_mod: os_mod.getenv = mock.MagicMock(name='getenv', return_value=0) - with self.assertRaises(NoDevshellServer): - _SendRecv() - os_mod.getenv.assert_called_once_with(DEVSHELL_ENV, 0) + with self.assertRaises(devshell.NoDevshellServer): + devshell._SendRecv() + os_mod.getenv.assert_called_once_with(devshell.DEVSHELL_ENV, 0) def test_no_newline_in_received_header(self): non_zero_port = 1 @@ -102,15 +94,15 @@ class Test_SendRecv(unittest2.TestCase): with mock.patch('oauth2client.contrib.devshell.socket') as socket: socket.socket = mock.MagicMock(name='socket', return_value=sock) - with self.assertRaises(CommunicationError): - _SendRecv() - os_mod.getenv.assert_called_once_with(DEVSHELL_ENV, 0) + with self.assertRaises(devshell.CommunicationError): + devshell._SendRecv() + os_mod.getenv.assert_called_once_with(devshell.DEVSHELL_ENV, 0) socket.socket.assert_called_once_with() sock.recv(6).decode.assert_called_once_with() - data = CREDENTIAL_INFO_REQUEST_JSON - msg = _to_bytes('{0}\n{1}'.format(len(data), data), - encoding='utf-8') + data = devshell.CREDENTIAL_INFO_REQUEST_JSON + msg = _helpers._to_bytes( + '{0}\n{1}'.format(len(data), data), encoding='utf-8') expected_sock_calls = [ mock.call.recv(6), # From the set-up above 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.bind(('localhost', 0)) port = self._socket.getsockname()[1] - os.environ[DEVSHELL_ENV] = str(port) + os.environ[devshell.DEVSHELL_ENV] = str(port) self._socket.listen(0) self.daemon = True self.start() @@ -145,7 +137,7 @@ class _AuthReferenceServer(threading.Thread): self.stop_server() def stop_server(self): - del os.environ[DEVSHELL_ENV] + del os.environ[devshell.DEVSHELL_ENV] self._socket.close() def run(self): @@ -164,8 +156,9 @@ class _AuthReferenceServer(threading.Thread): n = int(nstr) to_read = n - len(extra) if to_read > 0: - resp_buffer += _from_bytes(s.recv(to_read, socket.MSG_WAITALL)) - if resp_buffer != CREDENTIAL_INFO_REQUEST_JSON: + resp_buffer += _helpers._from_bytes( + s.recv(to_read, socket.MSG_WAITALL)) + if resp_buffer != devshell.CREDENTIAL_INFO_REQUEST_JSON: self.bad_request = True l = len(self.response) s.sendall('{0}\n{1}'.format(l, self.response).encode()) @@ -178,18 +171,18 @@ class _AuthReferenceServer(threading.Thread): class DevshellCredentialsTests(unittest2.TestCase): def test_signals_no_server(self): - with self.assertRaises(NoDevshellServer): - DevshellCredentials() + with self.assertRaises(devshell.NoDevshellServer): + devshell.DevshellCredentials() def test_bad_message_to_mock_server(self): - request_content = CREDENTIAL_INFO_REQUEST_JSON + 'extrastuff' - request_message = _to_bytes( + request_content = devshell.CREDENTIAL_INFO_REQUEST_JSON + 'extrastuff' + request_message = _helpers._to_bytes( '{0}\n{1}'.format(len(request_content), request_content)) response_message = 'foobar' with _AuthReferenceServer(response_message) as auth_server: self.assertFalse(auth_server.bad_request) sock = socket.socket() - port = int(os.getenv(DEVSHELL_ENV, 0)) + port = int(os.getenv(devshell.DEVSHELL_ENV, 0)) sock.connect(('localhost', port)) sock.sendall(request_message) @@ -204,22 +197,22 @@ class DevshellCredentialsTests(unittest2.TestCase): def test_request_response(self): with _AuthReferenceServer(): - response = _SendRecv() + response = devshell._SendRecv() self.assertEqual(response.user_email, 'joe@example.com') self.assertEqual(response.project_id, 'fooproj') self.assertEqual(response.access_token, 'sometoken') def test_no_refresh_token(self): with _AuthReferenceServer(): - creds = DevshellCredentials() + creds = devshell.DevshellCredentials() self.assertEquals(None, creds.refresh_token) - @mock.patch.object(devshell, '_UTCNOW') + @mock.patch('oauth2client.client._UTCNOW') def test_reads_credentials(self, utcnow): NOW = datetime.datetime(1992, 12, 31) utcnow.return_value = NOW with _AuthReferenceServer(): - creds = DevshellCredentials() + creds = devshell.DevshellCredentials() self.assertEqual('joe@example.com', creds.user_email) self.assertEqual('fooproj', creds.project_id) self.assertEqual('sometoken', creds.access_token) @@ -230,7 +223,7 @@ class DevshellCredentialsTests(unittest2.TestCase): def test_handles_skipped_fields(self): with _AuthReferenceServer('["joe@example.com"]'): - creds = DevshellCredentials() + creds = devshell.DevshellCredentials() self.assertEqual('joe@example.com', creds.user_email) self.assertEqual(None, creds.project_id) self.assertEqual(None, creds.access_token) @@ -238,7 +231,7 @@ class DevshellCredentialsTests(unittest2.TestCase): def test_handles_tiny_response(self): with _AuthReferenceServer('[]'): - creds = DevshellCredentials() + creds = devshell.DevshellCredentials() self.assertEqual(None, creds.user_email) self.assertEqual(None, creds.project_id) self.assertEqual(None, creds.access_token) @@ -246,7 +239,7 @@ class DevshellCredentialsTests(unittest2.TestCase): def test_handles_ignores_extra_fields(self): with _AuthReferenceServer( '["joe@example.com", "fooproj", "sometoken", 1, "extra"]'): - creds = DevshellCredentials() + creds = devshell.DevshellCredentials() self.assertEqual('joe@example.com', creds.user_email) self.assertEqual('fooproj', creds.project_id) self.assertEqual('sometoken', creds.access_token) @@ -256,18 +249,18 @@ class DevshellCredentialsTests(unittest2.TestCase): try: os.path.isdir = lambda path: True with _AuthReferenceServer(): - creds = DevshellCredentials() + creds = devshell.DevshellCredentials() with self.assertRaises(NotImplementedError): - save_to_well_known_file(creds) + client.save_to_well_known_file(creds) finally: os.path.isdir = ORIGINAL_ISDIR def test_from_json(self): with self.assertRaises(NotImplementedError): - DevshellCredentials.from_json(None) + devshell.DevshellCredentials.from_json(None) def test_serialization_data(self): with _AuthReferenceServer('[]'): - credentials = DevshellCredentials() + credentials = devshell.DevshellCredentials() with self.assertRaises(NotImplementedError): getattr(credentials, 'serialization_data') diff --git a/tests/contrib/test_dictionary_storage.py b/tests/contrib/test_dictionary_storage.py index b1cdb6d..888c938 100644 --- a/tests/contrib/test_dictionary_storage.py +++ b/tests/contrib/test_dictionary_storage.py @@ -16,19 +16,19 @@ import unittest2 -from oauth2client import GOOGLE_TOKEN_URI -from oauth2client.client import OAuth2Credentials -from oauth2client.contrib.dictionary_storage import DictionaryStorage +import oauth2client +from oauth2client import client +from oauth2client.contrib import dictionary_storage def _generate_credentials(scopes=None): - return OAuth2Credentials( + return client.OAuth2Credentials( 'access_tokenz', 'client_idz', 'client_secretz', 'refresh_tokenz', '3600', - GOOGLE_TOKEN_URI, + oauth2client.GOOGLE_TOKEN_URI, 'Test', id_token={ 'sub': '123', @@ -42,7 +42,7 @@ class DictionaryStorageTests(unittest2.TestCase): def test_constructor_defaults(self): dictionary = {} key = 'test-key' - storage = DictionaryStorage(dictionary, key) + storage = dictionary_storage.DictionaryStorage(dictionary, key) self.assertEqual(dictionary, storage._dictionary) self.assertEqual(key, storage._key) @@ -51,17 +51,18 @@ class DictionaryStorageTests(unittest2.TestCase): def test_constructor_explicit(self): dictionary = {} key = 'test-key' - storage = DictionaryStorage(dictionary, key) + storage = dictionary_storage.DictionaryStorage(dictionary, key) lock = object() - storage = DictionaryStorage(dictionary, key, lock=lock) + storage = dictionary_storage.DictionaryStorage( + dictionary, key, lock=lock) self.assertEqual(storage._lock, lock) def test_get(self): credentials = _generate_credentials() dictionary = {} key = 'credentials' - storage = DictionaryStorage(dictionary, key) + storage = dictionary_storage.DictionaryStorage(dictionary, key) self.assertIsNone(storage.get()) @@ -78,7 +79,7 @@ class DictionaryStorageTests(unittest2.TestCase): credentials = _generate_credentials() dictionary = {} key = 'credentials' - storage = DictionaryStorage(dictionary, key) + storage = dictionary_storage.DictionaryStorage(dictionary, key) storage.put(credentials) returned = storage.get() @@ -94,7 +95,7 @@ class DictionaryStorageTests(unittest2.TestCase): credentials = _generate_credentials() dictionary = {} key = 'credentials' - storage = DictionaryStorage(dictionary, key) + storage = dictionary_storage.DictionaryStorage(dictionary, key) storage.put(credentials) diff --git a/tests/contrib/test_flask_util.py b/tests/contrib/test_flask_util.py index b8e2f6a..74cb218 100644 --- a/tests/contrib/test_flask_util.py +++ b/tests/contrib/test_flask_util.py @@ -25,12 +25,10 @@ import six.moves.http_client as httplib import six.moves.urllib.parse as urlparse import unittest2 +import oauth2client +from oauth2client import client from oauth2client import clientsecrets -from oauth2client import GOOGLE_AUTH_URI -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 +from oauth2client.contrib import flask_util __author__ = 'jonwayne@google.com (Jon Wayne Parrott)' @@ -73,19 +71,19 @@ class FlaskOAuth2Tests(unittest2.TestCase): self.app.testing = True self.app.config['SECRET_KEY'] = 'notasecert' self.app.logger.setLevel(logging.CRITICAL) - self.oauth2 = FlaskOAuth2( + self.oauth2 = flask_util.UserOAuth2( self.app, client_id='client_idz', client_secret='client_secretz') def _generate_credentials(self, scopes=None): - return OAuth2Credentials( + return client.OAuth2Credentials( 'access_tokenz', 'client_idz', 'client_secretz', 'refresh_tokenz', datetime.datetime.utcnow() + datetime.timedelta(seconds=3600), - GOOGLE_TOKEN_URI, + oauth2client.GOOGLE_TOKEN_URI, 'Test', id_token={ 'sub': '123', @@ -94,7 +92,7 @@ class FlaskOAuth2Tests(unittest2.TestCase): scopes=scopes) def test_explicit_configuration(self): - oauth2 = FlaskOAuth2( + oauth2 = flask_util.UserOAuth2( flask.Flask(__name__), client_id='id', client_secret='secret') self.assertEqual(oauth2.client_id, 'id') @@ -107,7 +105,7 @@ class FlaskOAuth2Tests(unittest2.TestCase): with mock.patch('oauth2client.clientsecrets.loadfile', return_value=return_val): - oauth2 = FlaskOAuth2( + oauth2 = flask_util.UserOAuth2( flask.Flask(__name__), client_secrets_file='file.json') self.assertEqual(oauth2.client_id, 'id') @@ -115,19 +113,19 @@ class FlaskOAuth2Tests(unittest2.TestCase): def test_delayed_configuration(self): app = flask.Flask(__name__) - oauth2 = FlaskOAuth2() + oauth2 = flask_util.UserOAuth2() oauth2.init_app(app, client_id='id', client_secret='secret') self.assertEqual(oauth2.app, app) def test_explicit_storage(self): storage_mock = mock.Mock() - oauth2 = FlaskOAuth2( + oauth2 = flask_util.UserOAuth2( flask.Flask(__name__), storage=storage_mock, client_id='id', client_secret='secret') self.assertEqual(oauth2.storage, storage_mock) def test_explicit_scopes(self): - oauth2 = FlaskOAuth2( + oauth2 = flask_util.UserOAuth2( flask.Flask(__name__), scopes=['1', '2'], client_id='id', client_secret='secret') self.assertEqual(oauth2.scopes, ['1', '2']) @@ -140,15 +138,15 @@ class FlaskOAuth2Tests(unittest2.TestCase): with mock.patch('oauth2client.clientsecrets.loadfile', return_value=return_val): with self.assertRaises(ValueError): - FlaskOAuth2(flask.Flask(__name__), - client_secrets_file='file.json') + flask_util.UserOAuth2(flask.Flask(__name__), + client_secrets_file='file.json') def test_app_configuration(self): app = flask.Flask(__name__) app.config['GOOGLE_OAUTH2_CLIENT_ID'] = 'id' 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_secret, 'secret') @@ -162,14 +160,14 @@ class FlaskOAuth2Tests(unittest2.TestCase): app = flask.Flask(__name__) 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_secret, 'secret2') def test_no_configuration(self): with self.assertRaises(ValueError): - FlaskOAuth2(flask.Flask(__name__)) + flask_util.UserOAuth2(flask.Flask(__name__)) def test_create_flow(self): with self.app.test_request_context(): @@ -193,7 +191,7 @@ class FlaskOAuth2Tests(unittest2.TestCase): # Test extra args specified in the constructor. app = flask.Flask(__name__) app.config['SECRET_KEY'] = 'notasecert' - oauth2 = FlaskOAuth2( + oauth2 = flask_util.UserOAuth2( app, client_id='client_id', client_secret='secret', extra_arg='test') @@ -208,7 +206,7 @@ class FlaskOAuth2Tests(unittest2.TestCase): q = urlparse.parse_qs(location.split('?', 1)[1]) 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.assertIn(self.oauth2.client_id, q['client_id']) self.assertEqual( @@ -240,7 +238,7 @@ class FlaskOAuth2Tests(unittest2.TestCase): with client.session_transaction() as session: session.update(flask.session) 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'] return state @@ -434,7 +432,7 @@ class FlaskOAuth2Tests(unittest2.TestCase): self.app = flask.Flask(__name__) self.app.testing = True self.app.config['SECRET_KEY'] = 'notasecert' - self.oauth2 = FlaskOAuth2( + self.oauth2 = flask_util.UserOAuth2( self.app, client_id='client_idz', client_secret='client_secretz', diff --git a/tests/contrib/test_gce.py b/tests/contrib/test_gce.py index 36ea83f..e71bd44 100644 --- a/tests/contrib/test_gce.py +++ b/tests/contrib/test_gce.py @@ -23,10 +23,8 @@ from six.moves import http_client from tests.contrib.test_metadata import request_mock import unittest2 -from oauth2client.client import HttpAccessTokenRefreshError -from oauth2client.client import save_to_well_known_file -from oauth2client.contrib.gce import _SCOPES_WARNING -from oauth2client.contrib.gce import AppAssertionCredentials +from oauth2client import client +from oauth2client.contrib import gce __author__ = 'jcgregorio@google.com (Joe Gregorio)' @@ -40,7 +38,7 @@ SERVICE_ACCOUNT_INFO = { class AppAssertionCredentialsTests(unittest2.TestCase): def test_constructor(self): - credentials = AppAssertionCredentials() + credentials = gce.AppAssertionCredentials() self.assertIsNone(credentials.assertion_type, None) self.assertIsNone(credentials.service_account_email) self.assertIsNone(credentials.scopes) @@ -50,19 +48,19 @@ class AppAssertionCredentialsTests(unittest2.TestCase): def test_constructor_with_scopes(self, warn_mock): scope = 'http://example.com/a http://example.com/b' scopes = scope.split() - credentials = AppAssertionCredentials(scopes=scopes) + credentials = gce.AppAssertionCredentials(scopes=scopes) self.assertEqual(credentials.scopes, 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): - credentials = AppAssertionCredentials() + credentials = gce.AppAssertionCredentials() with self.assertRaises(NotImplementedError): credentials.to_json() def test_from_json(self): with self.assertRaises(NotImplementedError): - AppAssertionCredentials.from_json({}) + gce.AppAssertionCredentials.from_json({}) @mock.patch('oauth2client.contrib._metadata.get_token', side_effect=[('A', datetime.datetime.min), @@ -72,7 +70,7 @@ class AppAssertionCredentialsTests(unittest2.TestCase): def test_refresh_token(self, get_info, get_token): http_request = mock.MagicMock() http_mock = mock.MagicMock(request=http_request) - credentials = AppAssertionCredentials() + credentials = gce.AppAssertionCredentials() credentials.invalid = False credentials.service_account_email = 'a@example.com' self.assertIsNone(credentials.access_token) @@ -94,23 +92,23 @@ class AppAssertionCredentialsTests(unittest2.TestCase): 'application/json', json.dumps({'access_token': 'a', 'expires_in': 100}) ) - credentials = AppAssertionCredentials() + credentials = gce.AppAssertionCredentials() credentials.invalid = False credentials.service_account_email = 'a@example.com' - with self.assertRaises(HttpAccessTokenRefreshError): + with self.assertRaises(client.HttpAccessTokenRefreshError): credentials._refresh(http_request) def test_serialization_data(self): - credentials = AppAssertionCredentials() + credentials = gce.AppAssertionCredentials() with self.assertRaises(NotImplementedError): getattr(credentials, 'serialization_data') def test_create_scoped_required(self): - credentials = AppAssertionCredentials() + credentials = gce.AppAssertionCredentials() self.assertFalse(credentials.create_scoped_required()) def test_sign_blob_not_implemented(self): - credentials = AppAssertionCredentials([]) + credentials = gce.AppAssertionCredentials([]) with self.assertRaises(NotImplementedError): credentials.sign_blob(b'blob') @@ -119,7 +117,7 @@ class AppAssertionCredentialsTests(unittest2.TestCase): def test_retrieve_scopes(self, metadata): http_request = mock.MagicMock() http_mock = mock.MagicMock(request=http_request) - credentials = AppAssertionCredentials() + credentials = gce.AppAssertionCredentials() self.assertTrue(credentials.invalid) self.assertIsNone(credentials.scopes) scopes = credentials.retrieve_scopes(http_mock) @@ -135,7 +133,7 @@ class AppAssertionCredentialsTests(unittest2.TestCase): def test_retrieve_scopes_bad_email(self, metadata): http_request = mock.MagicMock() 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): credentials.retrieve_scopes(http_mock) @@ -147,8 +145,8 @@ class AppAssertionCredentialsTests(unittest2.TestCase): ORIGINAL_ISDIR = os.path.isdir try: os.path.isdir = lambda path: True - credentials = AppAssertionCredentials() + credentials = gce.AppAssertionCredentials() with self.assertRaises(NotImplementedError): - save_to_well_known_file(credentials) + client.save_to_well_known_file(credentials) finally: os.path.isdir = ORIGINAL_ISDIR diff --git a/tests/contrib/test_keyring_storage.py b/tests/contrib/test_keyring_storage.py index 30866b6..5d274c0 100644 --- a/tests/contrib/test_keyring_storage.py +++ b/tests/contrib/test_keyring_storage.py @@ -21,9 +21,9 @@ import keyring import mock import unittest2 -from oauth2client import GOOGLE_TOKEN_URI -from oauth2client.client import OAuth2Credentials -from oauth2client.contrib.keyring_storage import Storage +import oauth2client +from oauth2client import client +from oauth2client.contrib import keyring_storage __author__ = 'jcgregorio@google.com (Joe Gregorio)' @@ -34,21 +34,21 @@ class KeyringStorageTests(unittest2.TestCase): def test_constructor(self): service_name = 'my_unit_test' 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._user_name, user_name) lock_type = type(threading.Lock()) self.assertIsInstance(store._lock, lock_type) def test_acquire_lock(self): - store = Storage('my_unit_test', 'me') + store = keyring_storage.Storage('my_unit_test', 'me') store._lock = lock = _FakeLock() self.assertEqual(lock._acquire_count, 0) store.acquire_lock() self.assertEqual(lock._acquire_count, 1) def test_release_lock(self): - store = Storage('my_unit_test', 'me') + store = keyring_storage.Storage('my_unit_test', 'me') store._lock = lock = _FakeLock() self.assertEqual(lock._release_count, 0) store.release_lock() @@ -64,11 +64,11 @@ class KeyringStorageTests(unittest2.TestCase): with mock.patch.object(keyring, 'get_password', return_value=mock_content, autospec=True) as get_password: - class_name = 'oauth2client.contrib.keyring_storage.Credentials' + class_name = 'oauth2client.client.Credentials' with mock.patch(class_name) as MockCreds: MockCreds.new_from_json = new_from_json = mock.MagicMock( 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() new_from_json.assert_called_once_with(mock_content) get_password.assert_called_once_with(service_name, user_name) @@ -78,7 +78,7 @@ class KeyringStorageTests(unittest2.TestCase): def test_locked_put(self): service_name = 'my_unit_test' user_name = 'me' - store = Storage(service_name, user_name) + store = keyring_storage.Storage(service_name, user_name) with mock.patch.object(keyring, 'set_password', return_value=None, autospec=True) as set_password: @@ -94,7 +94,7 @@ class KeyringStorageTests(unittest2.TestCase): def test_locked_delete(self): service_name = 'my_unit_test' user_name = 'me' - store = Storage(service_name, user_name) + store = keyring_storage.Storage(service_name, user_name) with mock.patch.object(keyring, 'set_password', return_value=None, autospec=True) as set_password: @@ -105,7 +105,7 @@ class KeyringStorageTests(unittest2.TestCase): with mock.patch.object(keyring, 'get_password', return_value=None, autospec=True) as get_password: - store = Storage('my_unit_test', 'me') + store = keyring_storage.Storage('my_unit_test', 'me') credentials = store.get() self.assertEquals(None, credentials) 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', return_value='{', autospec=True) as get_password: - store = Storage('my_unit_test', 'me') + store = keyring_storage.Storage('my_unit_test', 'me') credentials = store.get() self.assertEquals(None, credentials) get_password.assert_called_once_with('my_unit_test', 'me') @@ -127,9 +127,9 @@ class KeyringStorageTests(unittest2.TestCase): token_expiry = datetime.datetime.utcnow() user_agent = 'refresh_checker/1.0' - credentials = OAuth2Credentials( + credentials = client.OAuth2Credentials( access_token, client_id, client_secret, - refresh_token, token_expiry, GOOGLE_TOKEN_URI, + refresh_token, token_expiry, oauth2client.GOOGLE_TOKEN_URI, user_agent) # 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', return_value=None, autospec=True) as set_password: - store = Storage('my_unit_test', 'me') + store = keyring_storage.Storage('my_unit_test', 'me') self.assertEquals(None, store.get()) store.put(credentials) diff --git a/tests/contrib/test_metadata.py b/tests/contrib/test_metadata.py index 3fe3338..7f11d04 100644 --- a/tests/contrib/test_metadata.py +++ b/tests/contrib/test_metadata.py @@ -68,7 +68,7 @@ class TestMetadata(unittest2.TestCase): http_request.assert_called_once_with(EXPECTED_URL, **EXPECTED_KWARGS) @mock.patch( - 'oauth2client.contrib._metadata._UTCNOW', + 'oauth2client.client._UTCNOW', return_value=datetime.datetime.min) def test_get_token_success(self, now): http_request = request_mock( diff --git a/tests/contrib/test_multiprocess_file_storage.py b/tests/contrib/test_multiprocess_file_storage.py index a59d7f6..bf30c14 100644 --- a/tests/contrib/test_multiprocess_file_storage.py +++ b/tests/contrib/test_multiprocess_file_storage.py @@ -26,7 +26,7 @@ import mock from six import StringIO import unittest2 -from oauth2client.client import OAuth2Credentials +from oauth2client import client from oauth2client.contrib import multiprocess_file_storage 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' user_agent = 'refresh_checker/1.0' - credentials = OAuth2Credentials( + credentials = client.OAuth2Credentials( access_token, 'test-client-id', client_secret, refresh_token, token_expiry, token_uri, user_agent) diff --git a/tests/contrib/test_multistore_file.py b/tests/contrib/test_multistore_file.py index 469743b..b5cb598 100644 --- a/tests/contrib/test_multistore_file.py +++ b/tests/contrib/test_multistore_file.py @@ -23,8 +23,8 @@ import tempfile import mock import unittest2 +from oauth2client import client from oauth2client import util -from oauth2client.client import OAuth2Credentials from oauth2client.contrib import locked_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' user_agent = 'refresh_checker/1.0' - credentials = OAuth2Credentials( + credentials = client.OAuth2Credentials( access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent) diff --git a/tests/contrib/test_xsrfutil.py b/tests/contrib/test_xsrfutil.py index d6eddd6..64b842f 100644 --- a/tests/contrib/test_xsrfutil.py +++ b/tests/contrib/test_xsrfutil.py @@ -19,7 +19,7 @@ import base64 import mock import unittest2 -from oauth2client._helpers import _to_bytes +from oauth2client import _helpers from oauth2client.contrib import xsrfutil # Jan 17 2008, 5:40PM @@ -61,16 +61,16 @@ class Test_generate_token(unittest2.TestCase): digester.digest.assert_called_once_with() 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(TEST_ACTION_ID_1), 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) 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_as_bytes) self.assertEqual(token, expected_token) @@ -95,16 +95,17 @@ class Test_generate_token(unittest2.TestCase): digester.digest.assert_called_once_with() 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(TEST_ACTION_ID_1), 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) - expected_token_as_bytes = (digest + xsrfutil.DELIMITER + - _to_bytes(str(int(curr_time)))) + expected_token_as_bytes = ( + digest + xsrfutil.DELIMITER + + _helpers._to_bytes(str(int(curr_time)))) expected_token = base64.urlsafe_b64encode( expected_token_as_bytes) self.assertEqual(token, expected_token) @@ -139,7 +140,7 @@ class Test_validate_token(unittest2.TestCase): curr_time = token_time + xsrfutil.DEFAULT_TIMEOUT_SECS + 1 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: time.time = mock.MagicMock(name='time', return_value=curr_time) 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 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, current_time=curr_time)) @@ -162,7 +163,7 @@ class Test_validate_token(unittest2.TestCase): key = object() user_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' # Make sure the token length comparison will fail. self.assertNotEqual(len(token), len(generated_token)) @@ -183,7 +184,7 @@ class Test_validate_token(unittest2.TestCase): key = object() user_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. generated_token = b'M' * 12 # Make sure the token length comparison will succeed, but the token @@ -207,7 +208,7 @@ class Test_validate_token(unittest2.TestCase): key = object() user_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', return_value=token) as gen_tok: self.assertTrue(xsrfutil.validate_token(key, token, user_id, diff --git a/tests/test__helpers.py b/tests/test__helpers.py index 21a4af8..cd54186 100644 --- a/tests/test__helpers.py +++ b/tests/test__helpers.py @@ -15,24 +15,19 @@ import unittest2 -from oauth2client._helpers import _from_bytes -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 +from oauth2client import _helpers class Test__parse_pem_key(unittest2.TestCase): def test_valid_input(self): 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:]) def test_bad_input(self): test_string = b'DOES NOT HAVE DASHES' - result = _parse_pem_key(test_string) + result = _helpers._parse_pem_key(test_string) self.assertEqual(result, None) @@ -42,12 +37,12 @@ class Test__json_encode(unittest2.TestCase): # Use only a single key since dictionary hash order # is non-deterministic. data = {u'foo': 10} - result = _json_encode(data) + result = _helpers._json_encode(data) self.assertEqual(result, '{"foo":10}') def test_list_input(self): data = [42, 1337] - result = _json_encode(data) + result = _helpers._json_encode(data) self.assertEqual(result, '[42,1337]') @@ -55,34 +50,34 @@ class Test__to_bytes(unittest2.TestCase): def test_with_bytes(self): value = b'bytes-val' - self.assertEqual(_to_bytes(value), value) + self.assertEqual(_helpers._to_bytes(value), value) def test_with_unicode(self): value = u'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): value = object() with self.assertRaises(ValueError): - _to_bytes(value) + _helpers._to_bytes(value) class Test__from_bytes(unittest2.TestCase): def test_with_unicode(self): value = u'bytes-val' - self.assertEqual(_from_bytes(value), value) + self.assertEqual(_helpers._from_bytes(value), value) def test_with_bytes(self): value = b'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): value = object() with self.assertRaises(ValueError): - _from_bytes(value) + _helpers._from_bytes(value) class Test__urlsafe_b64encode(unittest2.TestCase): @@ -91,12 +86,12 @@ class Test__urlsafe_b64encode(unittest2.TestCase): def test_valid_input_bytes(self): test_string = b'deadbeef' - result = _urlsafe_b64encode(test_string) + result = _helpers._urlsafe_b64encode(test_string) self.assertEqual(result, self.DEADBEEF_ENCODED) def test_valid_input_unicode(self): test_string = u'deadbeef' - result = _urlsafe_b64encode(test_string) + result = _helpers._urlsafe_b64encode(test_string) self.assertEqual(result, self.DEADBEEF_ENCODED) @@ -104,16 +99,16 @@ class Test__urlsafe_b64decode(unittest2.TestCase): def test_valid_input_bytes(self): test_string = b'ZGVhZGJlZWY' - result = _urlsafe_b64decode(test_string) + result = _helpers._urlsafe_b64decode(test_string) self.assertEqual(result, b'deadbeef') def test_valid_input_unicode(self): test_string = b'ZGVhZGJlZWY' - result = _urlsafe_b64decode(test_string) + result = _helpers._urlsafe_b64decode(test_string) self.assertEqual(result, b'deadbeef') def test_bad_input(self): import binascii bad_string = b'+' with self.assertRaises((TypeError, binascii.Error)): - _urlsafe_b64decode(bad_string) + _helpers._urlsafe_b64decode(bad_string) diff --git a/tests/test__pure_python_crypt.py b/tests/test__pure_python_crypt.py index bae2bcd..3c2962a 100644 --- a/tests/test__pure_python_crypt.py +++ b/tests/test__pure_python_crypt.py @@ -22,10 +22,9 @@ import rsa import six import unittest2 +from oauth2client import _helpers from oauth2client import _pure_python_crypt -from oauth2client._helpers import _from_bytes -from oauth2client.crypt import RsaSigner -from oauth2client.crypt import RsaVerifier +from oauth2client import crypt class TestRsaVerifier(unittest2.TestCase): @@ -51,25 +50,25 @@ class TestRsaVerifier(unittest2.TestCase): def test_verify_success(self): 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) - verifier = RsaVerifier.from_string(self._load_public_key_bytes(), - is_x509_cert=False) + verifier = crypt.RsaVerifier.from_string( + self._load_public_key_bytes(), is_x509_cert=False) self.assertTrue(verifier.verify(to_sign, actual_signature)) def test_verify_unicode_success(self): 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) - verifier = RsaVerifier.from_string(self._load_public_key_bytes(), - is_x509_cert=False) + verifier = crypt.RsaVerifier.from_string( + self._load_public_key_bytes(), is_x509_cert=False) self.assertTrue(verifier.verify(to_sign, actual_signature)) def test_verify_failure(self): - verifier = RsaVerifier.from_string(self._load_public_key_bytes(), - is_x509_cert=False) + verifier = crypt.RsaVerifier.from_string( + self._load_public_key_bytes(), is_x509_cert=False) bad_signature1 = b'' self.assertFalse(verifier.verify(b'foo', bad_signature1)) bad_signature2 = b'a' @@ -77,26 +76,30 @@ class TestRsaVerifier(unittest2.TestCase): def test_from_string_pub_key(self): public_key = self._load_public_key_bytes() - verifier = RsaVerifier.from_string(public_key, is_x509_cert=False) - self.assertIsInstance(verifier, RsaVerifier) + verifier = crypt.RsaVerifier.from_string( + public_key, is_x509_cert=False) + self.assertIsInstance(verifier, crypt.RsaVerifier) self.assertIsInstance(verifier._pubkey, rsa.key.PublicKey) def test_from_string_pub_key_unicode(self): - public_key = _from_bytes(self._load_public_key_bytes()) - verifier = RsaVerifier.from_string(public_key, is_x509_cert=False) - self.assertIsInstance(verifier, RsaVerifier) + public_key = _helpers._from_bytes(self._load_public_key_bytes()) + verifier = crypt.RsaVerifier.from_string( + public_key, is_x509_cert=False) + self.assertIsInstance(verifier, crypt.RsaVerifier) self.assertIsInstance(verifier._pubkey, rsa.key.PublicKey) def test_from_string_pub_cert(self): public_cert = self._load_public_cert_bytes() - verifier = RsaVerifier.from_string(public_cert, is_x509_cert=True) - self.assertIsInstance(verifier, RsaVerifier) + verifier = crypt.RsaVerifier.from_string( + public_cert, is_x509_cert=True) + self.assertIsInstance(verifier, crypt.RsaVerifier) self.assertIsInstance(verifier._pubkey, rsa.key.PublicKey) def test_from_string_pub_cert_unicode(self): - public_cert = _from_bytes(self._load_public_cert_bytes()) - verifier = RsaVerifier.from_string(public_cert, is_x509_cert=True) - self.assertIsInstance(verifier, RsaVerifier) + public_cert = _helpers._from_bytes(self._load_public_cert_bytes()) + verifier = crypt.RsaVerifier.from_string( + public_cert, is_x509_cert=True) + self.assertIsInstance(verifier, crypt.RsaVerifier) self.assertIsInstance(verifier._pubkey, rsa.key.PublicKey) def test_from_string_pub_cert_failure(self): @@ -105,7 +108,7 @@ class TestRsaVerifier(unittest2.TestCase): with mock.patch('rsa.pem.load_pem', return_value=true_der + b'extra') as load_pem: 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') @@ -132,49 +135,49 @@ class TestRsaSigner(unittest2.TestCase): def test_from_string_pkcs1(self): key_bytes = self._load_pkcs1_key_bytes() - signer = RsaSigner.from_string(key_bytes) - self.assertIsInstance(signer, RsaSigner) + signer = crypt.RsaSigner.from_string(key_bytes) + self.assertIsInstance(signer, crypt.RsaSigner) self.assertIsInstance(signer._key, rsa.key.PrivateKey) def test_from_string_pkcs1_unicode(self): - key_bytes = _from_bytes(self._load_pkcs1_key_bytes()) - signer = RsaSigner.from_string(key_bytes) - self.assertIsInstance(signer, RsaSigner) + key_bytes = _helpers._from_bytes(self._load_pkcs1_key_bytes()) + signer = crypt.RsaSigner.from_string(key_bytes) + self.assertIsInstance(signer, crypt.RsaSigner) self.assertIsInstance(signer._key, rsa.key.PrivateKey) def test_from_string_pkcs8(self): key_bytes = self._load_pkcs8_key_bytes() - signer = RsaSigner.from_string(key_bytes) - self.assertIsInstance(signer, RsaSigner) + signer = crypt.RsaSigner.from_string(key_bytes) + self.assertIsInstance(signer, crypt.RsaSigner) self.assertIsInstance(signer._key, rsa.key.PrivateKey) def test_from_string_pkcs8_extra_bytes(self): key_bytes = self._load_pkcs8_key_bytes() _, pem_bytes = pem.readPemBlocksFromFile( - six.StringIO(_from_bytes(key_bytes)), + six.StringIO(_helpers._from_bytes(key_bytes)), _pure_python_crypt._PKCS8_MARKER) with mock.patch('pyasn1.codec.der.decoder.decode') as mock_decode: key_info, remaining = None, 'extra' mock_decode.return_value = (key_info, remaining) with self.assertRaises(ValueError): - RsaSigner.from_string(key_bytes) + crypt.RsaSigner.from_string(key_bytes) # Verify mock was called. mock_decode.assert_called_once_with( pem_bytes, asn1Spec=_pure_python_crypt._PKCS8_SPEC) def test_from_string_pkcs8_unicode(self): - key_bytes = _from_bytes(self._load_pkcs8_key_bytes()) - signer = RsaSigner.from_string(key_bytes) - self.assertIsInstance(signer, RsaSigner) + key_bytes = _helpers._from_bytes(self._load_pkcs8_key_bytes()) + signer = crypt.RsaSigner.from_string(key_bytes) + self.assertIsInstance(signer, crypt.RsaSigner) self.assertIsInstance(signer._key, rsa.key.PrivateKey) def test_from_string_pkcs12(self): key_bytes = self._load_pkcs12_key_bytes() with self.assertRaises(ValueError): - RsaSigner.from_string(key_bytes) + crypt.RsaSigner.from_string(key_bytes) def test_from_string_bogus_key(self): key_bytes = 'bogus-key' with self.assertRaises(ValueError): - RsaSigner.from_string(key_bytes) + crypt.RsaSigner.from_string(key_bytes) diff --git a/tests/test__pycrypto_crypt.py b/tests/test__pycrypto_crypt.py index 26521cf..2f45291 100644 --- a/tests/test__pycrypto_crypt.py +++ b/tests/test__pycrypto_crypt.py @@ -17,8 +17,7 @@ import os import unittest2 -from oauth2client.crypt import PyCryptoSigner -from oauth2client.crypt import PyCryptoVerifier +from oauth2client import crypt class TestPyCryptoVerifier(unittest2.TestCase): @@ -38,30 +37,32 @@ class TestPyCryptoVerifier(unittest2.TestCase): def test_verify_success(self): 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) - verifier = PyCryptoVerifier.from_string(self._load_public_cert_bytes(), - is_x509_cert=True) + verifier = crypt.PyCryptoVerifier.from_string( + self._load_public_cert_bytes(), is_x509_cert=True) self.assertTrue(verifier.verify(to_sign, actual_signature)) def test_verify_failure(self): - verifier = PyCryptoVerifier.from_string(self._load_public_cert_bytes(), - is_x509_cert=True) + verifier = crypt.PyCryptoVerifier.from_string( + self._load_public_cert_bytes(), is_x509_cert=True) bad_signature = b'' self.assertFalse(verifier.verify(b'foo', bad_signature)) def test_verify_bad_key(self): - verifier = PyCryptoVerifier.from_string(self._load_public_cert_bytes(), - is_x509_cert=True) + verifier = crypt.PyCryptoVerifier.from_string( + self._load_public_cert_bytes(), is_x509_cert=True) bad_signature = b'' self.assertFalse(verifier.verify(b'foo', bad_signature)) def test_from_string_unicode_key(self): public_key = self._load_public_cert_bytes() public_key = public_key.decode('utf-8') - verifier = PyCryptoVerifier.from_string(public_key, is_x509_cert=True) - self.assertIsInstance(verifier, PyCryptoVerifier) + verifier = crypt.PyCryptoVerifier.from_string( + public_key, is_x509_cert=True) + self.assertIsInstance(verifier, crypt.PyCryptoVerifier) class TestPyCryptoSigner(unittest2.TestCase): @@ -69,4 +70,4 @@ class TestPyCryptoSigner(unittest2.TestCase): def test_from_string_bad_key(self): key_bytes = 'definitely-not-pem-format' with self.assertRaises(NotImplementedError): - PyCryptoSigner.from_string(key_bytes) + crypt.PyCryptoSigner.from_string(key_bytes) diff --git a/tests/test_client.py b/tests/test_client.py index ad047d7..5af0422 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -34,53 +34,12 @@ from six.moves import http_client from six.moves import urllib import unittest2 +import oauth2client +from oauth2client import _helpers from oauth2client import client -from oauth2client import GOOGLE_REVOKE_URI -from oauth2client import GOOGLE_TOKEN_INFO_URI -from oauth2client import GOOGLE_TOKEN_URI -from oauth2client import util as oauth2client_util -from oauth2client._helpers import _to_bytes -from oauth2client.client import _extract_id_token -from oauth2client.client import _get_application_default_credential_from_file -from oauth2client.client import _get_environment_variable_file -from oauth2client.client import _get_well_known_file -from oauth2client.client import _in_gae_environment -from oauth2client.client import _in_gce_environment -from oauth2client.client import _raise_exception_for_missing_fields -from oauth2client.client import _raise_exception_for_reading_json -from oauth2client.client import _update_query_params -from oauth2client.client import _WELL_KNOWN_CREDENTIALS_FILE -from oauth2client.client import AccessTokenCredentials -from oauth2client.client import AccessTokenCredentialsError -from oauth2client.client import ADC_HELP_MSG -from oauth2client.client import ApplicationDefaultCredentialsError -from oauth2client.client import AssertionCredentials -from oauth2client.client import AUTHORIZED_USER -from oauth2client.client import Credentials -from oauth2client.client import credentials_from_clientsecrets_and_code -from oauth2client.client import credentials_from_code -from oauth2client.client import DEFAULT_ENV_NAME -from oauth2client.client import DeviceFlowInfo -from oauth2client.client import Error -from oauth2client.client import flow_from_clientsecrets -from oauth2client.client import FlowExchangeError -from oauth2client.client import GOOGLE_APPLICATION_CREDENTIALS -from oauth2client.client import GoogleCredentials -from oauth2client.client import HttpAccessTokenRefreshError -from oauth2client.client import NonAsciiHeaderError -from oauth2client.client import OAuth2Credentials -from oauth2client.client import OAuth2WebServerFlow -from oauth2client.client import OOB_CALLBACK_URN -from oauth2client.client import REFRESH_STATUS_CODES -from oauth2client.client import save_to_well_known_file -from oauth2client.client import SERVICE_ACCOUNT -from oauth2client.client import Storage -from oauth2client.client import TokenRevokeError -from oauth2client.client import VerifyJwtTokenError -from oauth2client.clientsecrets import _loadfile -from oauth2client.clientsecrets import InvalidClientSecretsError -from oauth2client.clientsecrets import TYPE_WEB -from oauth2client.service_account import ServiceAccountCredentials +from oauth2client import clientsecrets +from oauth2client import service_account +from oauth2client import util from .http_mock import CacheMock from .http_mock import HttpMock from .http_mock import HttpMockSequence @@ -114,56 +73,56 @@ def datafile(filename): 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} class CredentialsTests(unittest2.TestCase): def test_to_from_json(self): - credentials = Credentials() + credentials = client.Credentials() json = credentials.to_json() - Credentials.new_from_json(json) + client.Credentials.new_from_json(json) def test_authorize_abstract(self): - credentials = Credentials() + credentials = client.Credentials() http = object() with self.assertRaises(NotImplementedError): credentials.authorize(http) def test_refresh_abstract(self): - credentials = Credentials() + credentials = client.Credentials() http = object() with self.assertRaises(NotImplementedError): credentials.refresh(http) def test_revoke_abstract(self): - credentials = Credentials() + credentials = client.Credentials() http = object() with self.assertRaises(NotImplementedError): credentials.revoke(http) def test_apply_abstract(self): - credentials = Credentials() + credentials = client.Credentials() headers = {} with self.assertRaises(NotImplementedError): credentials.apply(headers) def test__to_json_basic(self): - credentials = Credentials() + credentials = client.Credentials() json_payload = credentials._to_json([]) # str(bytes) in Python2 and str(unicode) in Python3 self.assertIsInstance(json_payload, str) payload = json.loads(json_payload) expected_payload = { - '_class': Credentials.__name__, - '_module': Credentials.__module__, + '_class': client.Credentials.__name__, + '_module': client.Credentials.__module__, 'token_expiry': None, } self.assertEqual(payload, expected_payload) def test__to_json_with_strip(self): - credentials = Credentials() + credentials = client.Credentials() credentials.foo = 'bar' credentials.baz = 'quux' to_strip = ['foo'] @@ -172,15 +131,15 @@ class CredentialsTests(unittest2.TestCase): self.assertIsInstance(json_payload, str) payload = json.loads(json_payload) expected_payload = { - '_class': Credentials.__name__, - '_module': Credentials.__module__, + '_class': client.Credentials.__name__, + '_module': client.Credentials.__module__, 'token_expiry': None, 'baz': credentials.baz, } self.assertEqual(payload, expected_payload) def test__to_json_to_serialize(self): - credentials = Credentials() + credentials = client.Credentials() to_serialize = { 'foo': b'bar', 'baz': u'quux', @@ -192,8 +151,8 @@ class CredentialsTests(unittest2.TestCase): self.assertIsInstance(json_payload, str) payload = json.loads(json_payload) expected_payload = { - '_class': Credentials.__name__, - '_module': Credentials.__module__, + '_class': client.Credentials.__name__, + '_module': client.Credentials.__module__, 'token_expiry': None, } expected_payload.update(to_serialize) @@ -205,18 +164,19 @@ class CredentialsTests(unittest2.TestCase): # Make sure the method call didn't modify our dictionary. self.assertEqual(to_serialize, orig_vals) - @mock.patch.object(Credentials, '_to_json', + @mock.patch.object(client.Credentials, '_to_json', return_value=object()) def test_to_json(self, to_json): - credentials = Credentials() + credentials = client.Credentials() self.assertEqual(credentials.to_json(), to_json.return_value) - to_json.assert_called_once_with(Credentials.NON_SERIALIZED_MEMBERS) + to_json.assert_called_once_with( + client.Credentials.NON_SERIALIZED_MEMBERS) def test_new_from_json_no_data(self): creds_data = {} json_data = json.dumps(creds_data) with self.assertRaises(KeyError): - Credentials.new_from_json(json_data) + client.Credentials.new_from_json(json_data) def test_new_from_json_basic_data(self): creds_data = { @@ -224,8 +184,8 @@ class CredentialsTests(unittest2.TestCase): '_class': 'Credentials', } json_data = json.dumps(creds_data) - credentials = Credentials.new_from_json(json_data) - self.assertIsInstance(credentials, Credentials) + credentials = client.Credentials.new_from_json(json_data) + self.assertIsInstance(credentials, client.Credentials) def test_new_from_json_old_name(self): creds_data = { @@ -233,8 +193,8 @@ class CredentialsTests(unittest2.TestCase): '_class': 'Credentials', } json_data = json.dumps(creds_data) - credentials = Credentials.new_from_json(json_data) - self.assertIsInstance(credentials, Credentials) + credentials = client.Credentials.new_from_json(json_data) + self.assertIsInstance(credentials, client.Credentials) def test_new_from_json_bad_module(self): creds_data = { @@ -243,7 +203,7 @@ class CredentialsTests(unittest2.TestCase): } json_data = json.dumps(creds_data) with self.assertRaises(ImportError): - Credentials.new_from_json(json_data) + client.Credentials.new_from_json(json_data) def test_new_from_json_bad_class(self): creds_data = { @@ -252,30 +212,30 @@ class CredentialsTests(unittest2.TestCase): } json_data = json.dumps(creds_data) with self.assertRaises(AttributeError): - Credentials.new_from_json(json_data) + client.Credentials.new_from_json(json_data) def test_from_json(self): unused_data = {} - credentials = Credentials.from_json(unused_data) - self.assertIsInstance(credentials, Credentials) + credentials = client.Credentials.from_json(unused_data) + self.assertIsInstance(credentials, client.Credentials) self.assertEqual(credentials.__dict__, {}) class TestStorage(unittest2.TestCase): def test_locked_get_abstract(self): - storage = Storage() + storage = client.Storage() with self.assertRaises(NotImplementedError): storage.locked_get() def test_locked_put_abstract(self): - storage = Storage() + storage = client.Storage() credentials = object() with self.assertRaises(NotImplementedError): storage.locked_put(credentials) def test_locked_delete_abstract(self): - storage = Storage() + storage = client.Storage() with self.assertRaises(NotImplementedError): storage.locked_delete() @@ -304,7 +264,7 @@ class GoogleCredentialsTests(unittest2.TestCase): def tearDown(self): self.reset_env('SERVER_SOFTWARE') - self.reset_env(GOOGLE_APPLICATION_CREDENTIALS) + self.reset_env(client.GOOGLE_APPLICATION_CREDENTIALS) self.reset_env('APPDATA') os.name = self.os_name @@ -313,7 +273,8 @@ class GoogleCredentialsTests(unittest2.TestCase): os.environ.pop(env, None) def validate_service_account_credentials(self, credentials): - self.assertIsInstance(credentials, ServiceAccountCredentials) + self.assertIsInstance( + credentials, service_account.ServiceAccountCredentials) self.assertEqual('123', credentials.client_id) self.assertEqual('dummy@google.com', credentials._service_account_email) @@ -321,18 +282,18 @@ class GoogleCredentialsTests(unittest2.TestCase): self.assertEqual('', credentials._scopes) def validate_google_credentials(self, credentials): - self.assertIsInstance(credentials, GoogleCredentials) + self.assertIsInstance(credentials, client.GoogleCredentials) self.assertEqual(None, credentials.access_token) self.assertEqual('123', credentials.client_id) self.assertEqual('secret', credentials.client_secret) self.assertEqual('alabalaportocala', credentials.refresh_token) self.assertEqual(None, credentials.token_expiry) - self.assertEqual(GOOGLE_TOKEN_URI, credentials.token_uri) + self.assertEqual(oauth2client.GOOGLE_TOKEN_URI, credentials.token_uri) self.assertEqual('Python client library', credentials.user_agent) def get_a_google_credentials_object(self): - return GoogleCredentials(None, None, None, None, - None, None, None, None) + return client.GoogleCredentials(None, None, None, None, + None, None, None, None) def test_create_scoped_required(self): self.assertFalse( @@ -344,9 +305,9 @@ class GoogleCredentialsTests(unittest2.TestCase): self.assertEqual(credentials, credentials.create_scoped(['dummy_scope'])) - @mock.patch.object(GoogleCredentials, + @mock.patch.object(client.GoogleCredentials, '_implicit_credentials_from_files') - @mock.patch.object(GoogleCredentials, + @mock.patch.object(client.GoogleCredentials, '_implicit_credentials_from_gce') @mock.patch.object(client, '_in_gae_environment', return_value=True) @@ -354,16 +315,16 @@ class GoogleCredentialsTests(unittest2.TestCase): return_value=object()) def test_get_application_default_in_gae(self, gae_adc, in_gae, from_gce, from_files): - credentials = GoogleCredentials.get_application_default() + credentials = client.GoogleCredentials.get_application_default() self.assertEqual(credentials, gae_adc.return_value) in_gae.assert_called_once_with() from_files.assert_not_called() from_gce.assert_not_called() - @mock.patch.object(GoogleCredentials, + @mock.patch.object(client.GoogleCredentials, '_implicit_credentials_from_gae', return_value=None) - @mock.patch.object(GoogleCredentials, + @mock.patch.object(client.GoogleCredentials, '_implicit_credentials_from_files', return_value=None) @mock.patch.object(client, '_in_gce_environment', @@ -372,7 +333,7 @@ class GoogleCredentialsTests(unittest2.TestCase): return_value=object()) def test_get_application_default_in_gce(self, gce_adc, in_gce, from_files, from_gae): - credentials = GoogleCredentials.get_application_default() + credentials = client.GoogleCredentials.get_application_default() self.assertEqual(credentials, gce_adc.return_value) in_gce.assert_called_once_with() from_gae.assert_called_once_with() @@ -396,11 +357,11 @@ class GoogleCredentialsTests(unittest2.TestCase): def test_environment_caching(self): os.environ['SERVER_SOFTWARE'] = 'Development/XYZ' with mock_module_import('google.appengine'): - self.assertTrue(_in_gae_environment()) + self.assertTrue(client._in_gae_environment()) os.environ['SERVER_SOFTWARE'] = '' # Even though we no longer pass the environment check, it # is cached. - self.assertTrue(_in_gae_environment()) + self.assertTrue(client._in_gae_environment()) def _environment_check_gce_helper(self, status_ok=True, socket_error=False, server_software=''): @@ -427,14 +388,14 @@ class GoogleCredentialsTests(unittest2.TestCase): name='HTTPConnection', return_value=connection) if server_software == '': - self.assertFalse(_in_gae_environment()) + self.assertFalse(client._in_gae_environment()) else: - self.assertTrue(_in_gae_environment()) + self.assertTrue(client._in_gae_environment()) if status_ok and not socket_error and server_software == '': - self.assertTrue(_in_gce_environment()) + self.assertTrue(client._in_gce_environment()) else: - self.assertFalse(_in_gce_environment()) + self.assertFalse(client._in_gce_environment()) if server_software == '': http_client_module.HTTPConnection.assert_called_once_with( @@ -482,32 +443,34 @@ class GoogleCredentialsTests(unittest2.TestCase): def test_get_environment_variable_file(self): environment_variable_file = datafile( - os.path.join('gcloud', _WELL_KNOWN_CREDENTIALS_FILE)) - os.environ[GOOGLE_APPLICATION_CREDENTIALS] = environment_variable_file + os.path.join('gcloud', client._WELL_KNOWN_CREDENTIALS_FILE)) + os.environ[client.GOOGLE_APPLICATION_CREDENTIALS] = ( + environment_variable_file) self.assertEqual(environment_variable_file, - _get_environment_variable_file()) + client._get_environment_variable_file()) def test_get_environment_variable_file_error(self): nonexistent_file = datafile('nonexistent') - os.environ[GOOGLE_APPLICATION_CREDENTIALS] = nonexistent_file - expected_err_msg = ('File ' + nonexistent_file + - ' \(pointed by ' + GOOGLE_APPLICATION_CREDENTIALS + - ' environment variable\) does not exist!') - with self.assertRaisesRegexp(ApplicationDefaultCredentialsError, + os.environ[client.GOOGLE_APPLICATION_CREDENTIALS] = nonexistent_file + expected_err_msg = ( + 'File {0} \(pointed by {1} environment variable\) does not ' + 'exist!'.format( + nonexistent_file, client.GOOGLE_APPLICATION_CREDENTIALS)) + with self.assertRaisesRegexp(client.ApplicationDefaultCredentialsError, expected_err_msg): - _get_environment_variable_file() + client._get_environment_variable_file() @mock.patch.dict(os.environ, {}, clear=True) def test_get_environment_variable_file_without_env_var(self): - self.assertIsNone(_get_environment_variable_file()) + self.assertIsNone(client._get_environment_variable_file()) @mock.patch('os.name', new='nt') @mock.patch.dict(os.environ, {'APPDATA': DATA_DIR}, clear=True) def test_get_well_known_file_on_windows(self): well_known_file = datafile( os.path.join(client._CLOUDSDK_CONFIG_DIRECTORY, - _WELL_KNOWN_CREDENTIALS_FILE)) - self.assertEqual(well_known_file, _get_well_known_file()) + client._WELL_KNOWN_CREDENTIALS_FILE)) + self.assertEqual(well_known_file, client._get_well_known_file()) @mock.patch('os.name', new='nt') @mock.patch.dict(os.environ, {'SystemDrive': 'G:'}, clear=True) @@ -515,7 +478,7 @@ class GoogleCredentialsTests(unittest2.TestCase): well_known_file = os.path.join('G:', '\\', client._CLOUDSDK_CONFIG_DIRECTORY, client._WELL_KNOWN_CREDENTIALS_FILE) - self.assertEqual(well_known_file, _get_well_known_file()) + self.assertEqual(well_known_file, client._get_well_known_file()) @mock.patch.dict(os.environ, {client._CLOUDSDK_CONFIG_ENV_VAR: 'CUSTOM_DIR'}, @@ -523,26 +486,26 @@ class GoogleCredentialsTests(unittest2.TestCase): def test_get_well_known_file_with_custom_config_dir(self): CUSTOM_DIR = os.environ[client._CLOUDSDK_CONFIG_ENV_VAR] EXPECTED_FILE = os.path.join(CUSTOM_DIR, - _WELL_KNOWN_CREDENTIALS_FILE) - well_known_file = _get_well_known_file() + client._WELL_KNOWN_CREDENTIALS_FILE) + well_known_file = client._get_well_known_file() self.assertEqual(well_known_file, EXPECTED_FILE) def test_get_adc_from_file_service_account(self): credentials_file = datafile( - os.path.join('gcloud', _WELL_KNOWN_CREDENTIALS_FILE)) - credentials = _get_application_default_credential_from_file( + os.path.join('gcloud', client._WELL_KNOWN_CREDENTIALS_FILE)) + credentials = client._get_application_default_credential_from_file( credentials_file) self.validate_service_account_credentials(credentials) def test_save_to_well_known_file_service_account(self): credential_file = datafile( - os.path.join('gcloud', _WELL_KNOWN_CREDENTIALS_FILE)) - credentials = _get_application_default_credential_from_file( + os.path.join('gcloud', client._WELL_KNOWN_CREDENTIALS_FILE)) + credentials = client._get_application_default_credential_from_file( credential_file) temp_credential_file = datafile( os.path.join('gcloud', 'temp_well_known_file_service_account.json')) - save_to_well_known_file(credentials, temp_credential_file) + client.save_to_well_known_file(credentials, temp_credential_file) with open(temp_credential_file) as f: d = json.load(f) self.assertEqual('service_account', d['type']) @@ -555,11 +518,11 @@ class GoogleCredentialsTests(unittest2.TestCase): def test_save_well_known_file_with_non_existent_config_dir(self, isdir_mock): credential_file = datafile( - os.path.join('gcloud', _WELL_KNOWN_CREDENTIALS_FILE)) - credentials = _get_application_default_credential_from_file( + os.path.join('gcloud', client._WELL_KNOWN_CREDENTIALS_FILE)) + credentials = client._get_application_default_credential_from_file( credential_file) with self.assertRaises(OSError): - save_to_well_known_file(credentials) + client.save_to_well_known_file(credentials) config_dir = os.path.join(os.path.expanduser('~'), '.config', 'gcloud') isdir_mock.assert_called_once_with(config_dir) @@ -567,7 +530,7 @@ class GoogleCredentialsTests(unittest2.TestCase): credentials_file = datafile(os.path.join( 'gcloud', 'application_default_credentials_authorized_user.json')) - credentials = _get_application_default_credential_from_file( + credentials = client._get_application_default_credential_from_file( credentials_file) self.validate_google_credentials(credentials) @@ -575,12 +538,12 @@ class GoogleCredentialsTests(unittest2.TestCase): credentials_file = datafile(os.path.join( 'gcloud', 'application_default_credentials_authorized_user.json')) - credentials = _get_application_default_credential_from_file( + credentials = client._get_application_default_credential_from_file( credentials_file) temp_credential_file = datafile( os.path.join('gcloud', 'temp_well_known_file_authorized_user.json')) - save_to_well_known_file(credentials, temp_credential_file) + client.save_to_well_known_file(credentials, temp_credential_file) with open(temp_credential_file) as f: d = json.load(f) self.assertEqual('authorized_user', d['type']) @@ -593,12 +556,15 @@ class GoogleCredentialsTests(unittest2.TestCase): credentials_file = datafile( os.path.join('gcloud', 'application_default_credentials_malformed_1.json')) - expected_err_msg = ("'type' field should be defined " - "\(and have one of the '" + AUTHORIZED_USER + - "' or '" + SERVICE_ACCOUNT + "' values\)") - with self.assertRaisesRegexp(ApplicationDefaultCredentialsError, + expected_err_msg = ( + "'type' field should be defined \(and have one of the '{0}' or " + "'{1}' values\)".format(client.AUTHORIZED_USER, + client.SERVICE_ACCOUNT)) + + with self.assertRaisesRegexp(client.ApplicationDefaultCredentialsError, expected_err_msg): - _get_application_default_credential_from_file(credentials_file) + client._get_application_default_credential_from_file( + credentials_file) def test_get_application_default_credential_from_malformed_file_2(self): credentials_file = datafile( @@ -606,36 +572,38 @@ class GoogleCredentialsTests(unittest2.TestCase): 'application_default_credentials_malformed_2.json')) expected_err_msg = ( 'The following field\(s\) must be defined: private_key_id') - with self.assertRaisesRegexp(ApplicationDefaultCredentialsError, + with self.assertRaisesRegexp(client.ApplicationDefaultCredentialsError, expected_err_msg): - _get_application_default_credential_from_file(credentials_file) + client._get_application_default_credential_from_file( + credentials_file) def test_get_application_default_credential_from_malformed_file_3(self): credentials_file = datafile( os.path.join('gcloud', 'application_default_credentials_malformed_3.json')) with self.assertRaises(ValueError): - _get_application_default_credential_from_file(credentials_file) + client._get_application_default_credential_from_file( + credentials_file) def test_raise_exception_for_missing_fields(self): missing_fields = ['first', 'second', 'third'] expected_err_msg = ('The following field\(s\) must be defined: ' + ', '.join(missing_fields)) - with self.assertRaisesRegexp(ApplicationDefaultCredentialsError, + with self.assertRaisesRegexp(client.ApplicationDefaultCredentialsError, expected_err_msg): - _raise_exception_for_missing_fields(missing_fields) + client._raise_exception_for_missing_fields(missing_fields) def test_raise_exception_for_reading_json(self): credential_file = 'any_file' extra_help = ' be good' - error = ApplicationDefaultCredentialsError('stuff happens') + error = client.ApplicationDefaultCredentialsError('stuff happens') expected_err_msg = ('An error was encountered while reading ' 'json file: ' + credential_file + extra_help + ': ' + str(error)) - with self.assertRaisesRegexp(ApplicationDefaultCredentialsError, + with self.assertRaisesRegexp(client.ApplicationDefaultCredentialsError, expected_err_msg): - _raise_exception_for_reading_json(credential_file, - extra_help, error) + client._raise_exception_for_reading_json( + credential_file, extra_help, error) @mock.patch('oauth2client.client._in_gce_environment') @mock.patch('oauth2client.client._in_gae_environment', return_value=False) @@ -645,9 +613,9 @@ class GoogleCredentialsTests(unittest2.TestCase): # Set up stubs. get_well_known, get_env_file, in_gae, in_gce = stubs get_env_file.return_value = datafile( - os.path.join('gcloud', _WELL_KNOWN_CREDENTIALS_FILE)) + os.path.join('gcloud', client._WELL_KNOWN_CREDENTIALS_FILE)) - credentials = GoogleCredentials.get_application_default() + credentials = client.GoogleCredentials.get_application_default() self.validate_service_account_credentials(credentials) get_well_known.assert_not_called() @@ -658,7 +626,7 @@ class GoogleCredentialsTests(unittest2.TestCase): def test_env_name(self): self.assertEqual(None, client.SETTINGS.env_name) self.test_get_adc_from_env_var_service_account() - self.assertEqual(DEFAULT_ENV_NAME, client.SETTINGS.env_name) + self.assertEqual(client.DEFAULT_ENV_NAME, client.SETTINGS.env_name) @mock.patch('oauth2client.client._in_gce_environment') @mock.patch('oauth2client.client._in_gae_environment', return_value=False) @@ -671,7 +639,7 @@ class GoogleCredentialsTests(unittest2.TestCase): 'gcloud', 'application_default_credentials_authorized_user.json')) - credentials = GoogleCredentials.get_application_default() + credentials = client.GoogleCredentials.get_application_default() self.validate_google_credentials(credentials) get_well_known.assert_not_called() @@ -690,14 +658,14 @@ class GoogleCredentialsTests(unittest2.TestCase): os.path.join('gcloud', 'application_default_credentials_malformed_3.json')) - expected_err = ApplicationDefaultCredentialsError + expected_err = client.ApplicationDefaultCredentialsError with self.assertRaises(expected_err) as exc_manager: - GoogleCredentials.get_application_default() + client.GoogleCredentials.get_application_default() self.assertTrue(str(exc_manager.exception).startswith( 'An error was encountered while reading json file: ' + get_env_file.return_value + ' (pointed to by ' + - GOOGLE_APPLICATION_CREDENTIALS + ' environment variable):')) + client.GOOGLE_APPLICATION_CREDENTIALS + ' environment variable):')) get_well_known.assert_not_called() in_gce.assert_not_called() @@ -716,11 +684,11 @@ class GoogleCredentialsTests(unittest2.TestCase): # Make sure the well-known file actually doesn't exist. self.assertFalse(os.path.exists(get_well_known.return_value)) - expected_err = ApplicationDefaultCredentialsError + expected_err = client.ApplicationDefaultCredentialsError with self.assertRaises(expected_err) as exc_manager: - GoogleCredentials.get_application_default() + client.GoogleCredentials.get_application_default() - self.assertEqual(ADC_HELP_MSG, str(exc_manager.exception)) + self.assertEqual(client.ADC_HELP_MSG, str(exc_manager.exception)) get_well_known.assert_called_once_with() get_env_file.assert_called_once_with() in_gae.assert_called_once_with() @@ -739,12 +707,12 @@ class GoogleCredentialsTests(unittest2.TestCase): # Make sure the well-known file actually doesn't exist. self.assertTrue(os.path.exists(get_well_known.return_value)) - method_name = ('oauth2client.client.' - '_get_application_default_credential_from_file') + method_name = \ + 'oauth2client.client._get_application_default_credential_from_file' result_creds = object() with mock.patch(method_name, return_value=result_creds) as get_from_file: - result = GoogleCredentials.get_application_default() + result = client.GoogleCredentials.get_application_default() self.assertEqual(result, result_creds) get_from_file.assert_called_once_with(__file__) @@ -755,7 +723,7 @@ class GoogleCredentialsTests(unittest2.TestCase): def test_from_stream_service_account(self): credentials_file = datafile( - os.path.join('gcloud', _WELL_KNOWN_CREDENTIALS_FILE)) + os.path.join('gcloud', client._WELL_KNOWN_CREDENTIALS_FILE)) credentials = self.get_a_google_credentials_object().from_stream( credentials_file) self.validate_service_account_credentials(credentials) @@ -772,7 +740,7 @@ class GoogleCredentialsTests(unittest2.TestCase): credentials_filename = None expected_err_msg = (r'The parameter passed to the from_stream\(\) ' r'method should point to a file.') - with self.assertRaisesRegexp(ApplicationDefaultCredentialsError, + with self.assertRaisesRegexp(client.ApplicationDefaultCredentialsError, expected_err_msg): self.get_a_google_credentials_object().from_stream( credentials_filename) @@ -786,9 +754,9 @@ class GoogleCredentialsTests(unittest2.TestCase): credentials_file + ' \(provided as parameter to the from_stream\(\) method\): ' + "'type' field should be defined \(and have one of the '" + - AUTHORIZED_USER + "' or '" + SERVICE_ACCOUNT + + client.AUTHORIZED_USER + "' or '" + client.SERVICE_ACCOUNT + "' values\)") - with self.assertRaisesRegexp(ApplicationDefaultCredentialsError, + with self.assertRaisesRegexp(client.ApplicationDefaultCredentialsError, expected_err_msg): self.get_a_google_credentials_object().from_stream( credentials_file) @@ -803,7 +771,7 @@ class GoogleCredentialsTests(unittest2.TestCase): ' \(provided as parameter to the from_stream\(\) method\): ' 'The following field\(s\) must be defined: ' 'private_key_id') - with self.assertRaisesRegexp(ApplicationDefaultCredentialsError, + with self.assertRaisesRegexp(client.ApplicationDefaultCredentialsError, expected_err_msg): self.get_a_google_credentials_object().from_stream( credentials_file) @@ -812,25 +780,25 @@ class GoogleCredentialsTests(unittest2.TestCase): credentials_file = datafile( os.path.join('gcloud', 'application_default_credentials_malformed_3.json')) - with self.assertRaises(ApplicationDefaultCredentialsError): + with self.assertRaises(client.ApplicationDefaultCredentialsError): self.get_a_google_credentials_object().from_stream( credentials_file) def test_to_from_json_authorized_user(self): filename = 'application_default_credentials_authorized_user.json' credentials_file = datafile(os.path.join('gcloud', filename)) - creds = GoogleCredentials.from_stream(credentials_file) + creds = client.GoogleCredentials.from_stream(credentials_file) json = creds.to_json() - creds2 = GoogleCredentials.from_json(json) + creds2 = client.GoogleCredentials.from_json(json) self.assertEqual(creds.__dict__, creds2.__dict__) def test_to_from_json_service_account(self): credentials_file = datafile( - os.path.join('gcloud', _WELL_KNOWN_CREDENTIALS_FILE)) - creds1 = GoogleCredentials.from_stream(credentials_file) + os.path.join('gcloud', client._WELL_KNOWN_CREDENTIALS_FILE)) + creds1 = client.GoogleCredentials.from_stream(credentials_file) # Convert to and then back from json. - creds2 = GoogleCredentials.from_json(creds1.to_json()) + creds2 = client.GoogleCredentials.from_json(creds1.to_json()) creds1_vals = creds1.__dict__ creds1_vals.pop('_signer') @@ -840,11 +808,11 @@ class GoogleCredentialsTests(unittest2.TestCase): def test_to_from_json_service_account_scoped(self): credentials_file = datafile( - os.path.join('gcloud', _WELL_KNOWN_CREDENTIALS_FILE)) - creds1 = GoogleCredentials.from_stream(credentials_file) + os.path.join('gcloud', client._WELL_KNOWN_CREDENTIALS_FILE)) + creds1 = client.GoogleCredentials.from_stream(credentials_file) creds1 = creds1.create_scoped(['dummy_scope']) # Convert to and then back from json. - creds2 = GoogleCredentials.from_json(creds1.to_json()) + creds2 = client.GoogleCredentials.from_json(creds1.to_json()) creds1_vals = creds1.__dict__ creds1_vals.pop('_signer') @@ -863,7 +831,7 @@ class GoogleCredentialsTests(unittest2.TestCase): self.assertEqual(None, parsed_expiry) -class DummyDeleteStorage(Storage): +class DummyDeleteStorage(client.Storage): delete_called = False def locked_delete(self): @@ -887,7 +855,7 @@ def _token_revoke_test_helper(testcase, status, revoke_raise, http = HttpMock(headers={'status': status}) if revoke_raise: - testcase.assertRaises(TokenRevokeError, + testcase.assertRaises(client.TokenRevokeError, testcase.credentials.revoke, http) else: testcase.credentials.revoke(http) @@ -909,24 +877,24 @@ class BasicCredentialsTests(unittest2.TestCase): refresh_token = '1/0/a.df219fjls0' token_expiry = datetime.datetime.utcnow() user_agent = 'refresh_checker/1.0' - self.credentials = OAuth2Credentials( + self.credentials = client.OAuth2Credentials( access_token, client_id, client_secret, - refresh_token, token_expiry, GOOGLE_TOKEN_URI, - user_agent, revoke_uri=GOOGLE_REVOKE_URI, scopes='foo', - token_info_uri=GOOGLE_TOKEN_INFO_URI) + refresh_token, token_expiry, oauth2client.GOOGLE_TOKEN_URI, + user_agent, revoke_uri=oauth2client.GOOGLE_REVOKE_URI, + scopes='foo', token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI) # Provoke a failure if @util.positional is not respected. self.old_positional_enforcement = ( - oauth2client_util.positional_parameters_enforcement) - oauth2client_util.positional_parameters_enforcement = ( - oauth2client_util.POSITIONAL_EXCEPTION) + util.positional_parameters_enforcement) + util.positional_parameters_enforcement = ( + util.POSITIONAL_EXCEPTION) def tearDown(self): - oauth2client_util.positional_parameters_enforcement = ( + util.positional_parameters_enforcement = ( self.old_positional_enforcement) def test_token_refresh_success(self): - for status_code in REFRESH_STATUS_CODES: + for status_code in client.REFRESH_STATUS_CODES: token_response = {'access_token': '1/3w', 'expires_in': 3600} http = HttpMockSequence([ ({'status': status_code}, b''), @@ -961,14 +929,15 @@ class BasicCredentialsTests(unittest2.TestCase): http.request('http://example.com') def test_token_refresh_failure(self): - for status_code in REFRESH_STATUS_CODES: + for status_code in client.REFRESH_STATUS_CODES: http = HttpMockSequence([ ({'status': status_code}, b''), ({'status': http_client.BAD_REQUEST}, b'{"error":"access_denied"}'), ]) http = self.credentials.authorize(http) - with self.assertRaises(HttpAccessTokenRefreshError) as exc_manager: + with self.assertRaises( + client.HttpAccessTokenRefreshError) as exc_manager: http.request('http://example.com') self.assertEqual(http_client.BAD_REQUEST, exc_manager.exception.status) @@ -1004,8 +973,8 @@ class BasicCredentialsTests(unittest2.TestCase): def test_to_from_json(self): json = self.credentials.to_json() - instance = OAuth2Credentials.from_json(json) - self.assertEqual(OAuth2Credentials, type(instance)) + instance = client.OAuth2Credentials.from_json(json) + self.assertEqual(client.OAuth2Credentials, type(instance)) instance.token_expiry = None self.credentials.token_expiry = None @@ -1014,14 +983,14 @@ class BasicCredentialsTests(unittest2.TestCase): def test_from_json_token_expiry(self): data = json.loads(self.credentials.to_json()) data['token_expiry'] = None - instance = OAuth2Credentials.from_json(json.dumps(data)) - self.assertIsInstance(instance, OAuth2Credentials) + instance = client.OAuth2Credentials.from_json(json.dumps(data)) + self.assertIsInstance(instance, client.OAuth2Credentials) def test_from_json_bad_token_expiry(self): data = json.loads(self.credentials.to_json()) data['token_expiry'] = 'foobar' - instance = OAuth2Credentials.from_json(json.dumps(data)) - self.assertIsInstance(instance, OAuth2Credentials) + instance = client.OAuth2Credentials.from_json(json.dumps(data)) + self.assertIsInstance(instance, client.OAuth2Credentials) def test_unicode_header_checks(self): access_token = u'foo' @@ -1029,12 +998,12 @@ class BasicCredentialsTests(unittest2.TestCase): client_secret = u'cOuDdkfjxxnv+' refresh_token = u'1/0/a.df219fjls0' token_expiry = str(datetime.datetime.utcnow()) - token_uri = str(GOOGLE_TOKEN_URI) - revoke_uri = str(GOOGLE_REVOKE_URI) + token_uri = str(oauth2client.GOOGLE_TOKEN_URI) + revoke_uri = str(oauth2client.GOOGLE_REVOKE_URI) user_agent = u'refresh_checker/1.0' - credentials = OAuth2Credentials(access_token, client_id, client_secret, - refresh_token, token_expiry, token_uri, - user_agent, revoke_uri=revoke_uri) + credentials = client.OAuth2Credentials( + access_token, client_id, client_secret, refresh_token, + token_expiry, token_uri, user_agent, revoke_uri=revoke_uri) # First, test that we correctly encode basic objects, making sure # to include a bytes object. Note that oauth2client will normalize @@ -1049,7 +1018,7 @@ class BasicCredentialsTests(unittest2.TestCase): # Next, test that we do fail on unicode. unicode_str = six.unichr(40960) + 'abcd' - with self.assertRaises(NonAsciiHeaderError): + with self.assertRaises(client.NonAsciiHeaderError): http.request(u'http://example.com', method=u'GET', headers={u'foo': unicode_str}) @@ -1059,12 +1028,12 @@ class BasicCredentialsTests(unittest2.TestCase): client_secret = u'cOuDdkfjxxnv+' refresh_token = u'1/0/a.df219fjls0' token_expiry = str(datetime.datetime.utcnow()) - token_uri = str(GOOGLE_TOKEN_URI) - revoke_uri = str(GOOGLE_REVOKE_URI) + token_uri = str(oauth2client.GOOGLE_TOKEN_URI) + revoke_uri = str(oauth2client.GOOGLE_REVOKE_URI) user_agent = u'refresh_checker/1.0' - credentials = OAuth2Credentials(access_token, client_id, client_secret, - refresh_token, token_expiry, token_uri, - user_agent, revoke_uri=revoke_uri) + credentials = client.OAuth2Credentials( + access_token, client_id, client_secret, refresh_token, + token_expiry, token_uri, user_agent, revoke_uri=revoke_uri) http = HttpMock() http = credentials.authorize(http) @@ -1076,25 +1045,26 @@ class BasicCredentialsTests(unittest2.TestCase): # Test again with unicode strings that can't simply be converted # to ASCII. - with self.assertRaises(NonAsciiHeaderError): + with self.assertRaises(client.NonAsciiHeaderError): http.request( u'http://example.com', method=u'GET', headers={u'foo': u'\N{COMET}'}) self.credentials.token_response = 'foobar' - instance = OAuth2Credentials.from_json(self.credentials.to_json()) + instance = client.OAuth2Credentials.from_json( + self.credentials.to_json()) self.assertEqual('foobar', instance.token_response) def test__expires_in_no_expiry(self): - credentials = OAuth2Credentials(None, None, None, None, - None, None, None) + credentials = client.OAuth2Credentials(None, None, None, None, + None, None, None) self.assertIsNone(credentials.token_expiry) self.assertIsNone(credentials._expires_in()) @mock.patch('oauth2client.client._UTCNOW') def test__expires_in_expired(self, utcnow): - credentials = OAuth2Credentials(None, None, None, None, - None, None, None) + credentials = client.OAuth2Credentials(None, None, None, None, + None, None, None) credentials.token_expiry = datetime.datetime.utcnow() now = credentials.token_expiry + datetime.timedelta(seconds=1) self.assertLess(credentials.token_expiry, now) @@ -1104,8 +1074,8 @@ class BasicCredentialsTests(unittest2.TestCase): @mock.patch('oauth2client.client._UTCNOW') def test__expires_in_not_expired(self, utcnow): - credentials = OAuth2Credentials(None, None, None, None, - None, None, None) + credentials = client.OAuth2Credentials(None, None, None, None, + None, None, None) credentials.token_expiry = datetime.datetime.utcnow() seconds = 1234 now = credentials.token_expiry - datetime.timedelta(seconds=seconds) @@ -1198,12 +1168,12 @@ class BasicCredentialsTests(unittest2.TestCase): expected_utcnow_calls = [mock.call()] * (2 + 3 + 5) self.assertEqual(expected_utcnow_calls, utcnow.mock_calls) - @mock.patch.object(OAuth2Credentials, 'refresh') - @mock.patch.object(OAuth2Credentials, '_expires_in', + @mock.patch.object(client.OAuth2Credentials, 'refresh') + @mock.patch.object(client.OAuth2Credentials, '_expires_in', return_value=1835) def test_get_access_token_without_http(self, expires_in, refresh_mock): - credentials = OAuth2Credentials(None, None, None, None, - None, None, None) + credentials = client.OAuth2Credentials(None, None, None, None, + None, None, None) # Make sure access_token_expired returns True credentials.invalid = True # Specify a token so we can use it in the response. @@ -1221,12 +1191,12 @@ class BasicCredentialsTests(unittest2.TestCase): self.assertEqual(token_info.expires_in, expires_in.return_value) - @mock.patch.object(OAuth2Credentials, 'refresh') - @mock.patch.object(OAuth2Credentials, '_expires_in', + @mock.patch.object(client.OAuth2Credentials, 'refresh') + @mock.patch.object(client.OAuth2Credentials, '_expires_in', return_value=1835) def test_get_access_token_with_http(self, expires_in, refresh_mock): - credentials = OAuth2Credentials(None, None, None, None, - None, None, None) + credentials = client.OAuth2Credentials(None, None, None, None, + None, None, None) # Make sure access_token_expired returns True credentials.invalid = True # Specify a token so we can use it in the response. @@ -1243,21 +1213,24 @@ class BasicCredentialsTests(unittest2.TestCase): expires_in.assert_called_once_with() refresh_mock.assert_called_once_with(http_obj) - @mock.patch.object(OAuth2Credentials, '_generate_refresh_request_headers', + @mock.patch.object(client.OAuth2Credentials, + '_generate_refresh_request_headers', return_value=object()) - @mock.patch.object(OAuth2Credentials, '_generate_refresh_request_body', + @mock.patch.object(client.OAuth2Credentials, + '_generate_refresh_request_body', return_value=object()) @mock.patch('oauth2client.client.logger') def _do_refresh_request_test_helper(self, response, content, error_msg, logger, gen_body, gen_headers, store=None): - credentials = OAuth2Credentials(None, None, None, None, - None, None, None) + credentials = client.OAuth2Credentials(None, None, None, None, + None, None, None) credentials.store = store http_request = mock.Mock() http_request.return_value = response, content - with self.assertRaises(HttpAccessTokenRefreshError) as exc_manager: + with self.assertRaises( + client.HttpAccessTokenRefreshError) as exc_manager: credentials._do_refresh_request(http_request) self.assertEqual(exc_manager.exception.args, (error_msg,)) @@ -1323,9 +1296,9 @@ class BasicCredentialsTests(unittest2.TestCase): @mock.patch('oauth2client.client.logger') def _do_revoke_test_helper(self, response, content, error_msg, logger, store=None): - credentials = OAuth2Credentials(None, None, None, None, - None, None, None, - revoke_uri=GOOGLE_REVOKE_URI) + credentials = client.OAuth2Credentials( + None, None, None, None, None, None, None, + revoke_uri=oauth2client.GOOGLE_REVOKE_URI) credentials.store = store http_request = mock.Mock() http_request.return_value = response, content @@ -1339,7 +1312,7 @@ class BasicCredentialsTests(unittest2.TestCase): store.delete.assert_called_once_with() else: self.assertFalse(credentials.invalid) - with self.assertRaises(TokenRevokeError) as exc_manager: + with self.assertRaises(client.TokenRevokeError) as exc_manager: credentials._do_revoke(http_request, token) # Make sure invalid was not flipped on. self.assertFalse(credentials.invalid) @@ -1347,7 +1320,7 @@ class BasicCredentialsTests(unittest2.TestCase): if store is not None: store.delete.assert_not_called() - revoke_uri = GOOGLE_REVOKE_URI + '?token=' + token + revoke_uri = oauth2client.GOOGLE_REVOKE_URI + '?token=' + token http_request.assert_called_once_with(revoke_uri) logger.info.assert_called_once_with('Revoking token') @@ -1402,9 +1375,9 @@ class BasicCredentialsTests(unittest2.TestCase): @mock.patch('oauth2client.client.logger') def _do_retrieve_scopes_test_helper(self, response, content, error_msg, logger, scopes=None): - credentials = OAuth2Credentials(None, None, None, None, - None, None, None, - token_info_uri=GOOGLE_TOKEN_INFO_URI) + credentials = client.OAuth2Credentials( + None, None, None, None, None, None, None, + token_info_uri=oauth2client.GOOGLE_TOKEN_INFO_URI) http_request = mock.Mock() http_request.return_value = response, content token = u's3kr3tz' @@ -1422,8 +1395,8 @@ class BasicCredentialsTests(unittest2.TestCase): self.assertEqual(credentials.scopes, set()) self.assertEqual(exc_manager.exception.args, (error_msg,)) - token_uri = _update_query_params( - GOOGLE_TOKEN_INFO_URI, + token_uri = client._update_query_params( + oauth2client.GOOGLE_TOKEN_INFO_URI, {'fields': 'scope', 'access_token': token}) self.assertEqual(len(http_request.mock_calls), 1) scopes_call = http_request.mock_calls[0] @@ -1503,14 +1476,14 @@ class BasicCredentialsTests(unittest2.TestCase): self.credentials.retrieve_scopes(http) self.assertEqual(set(['foo', 'bar']), self.credentials.scopes) - with self.assertRaises(Error): + with self.assertRaises(client.Error): self.credentials.retrieve_scopes(http) - with self.assertRaises(Error): + with self.assertRaises(client.Error): self.credentials.retrieve_scopes(http) def test_refresh_updates_id_token(self): - for status_code in REFRESH_STATUS_CODES: + for status_code in client.REFRESH_STATUS_CODES: body = {'foo': 'bar'} body_json = json.dumps(body).encode('ascii') payload = base64.urlsafe_b64encode(body_json).strip(b'=') @@ -1536,16 +1509,17 @@ class AccessTokenCredentialsTests(unittest2.TestCase): def setUp(self): access_token = 'foo' user_agent = 'refresh_checker/1.0' - self.credentials = AccessTokenCredentials(access_token, user_agent, - revoke_uri=GOOGLE_REVOKE_URI) + self.credentials = client.AccessTokenCredentials( + access_token, user_agent, + revoke_uri=oauth2client.GOOGLE_REVOKE_URI) def test_token_refresh_success(self): - for status_code in REFRESH_STATUS_CODES: + for status_code in client.REFRESH_STATUS_CODES: http = HttpMockSequence([ ({'status': status_code}, b''), ]) http = self.credentials.authorize(http) - with self.assertRaises(AccessTokenCredentialsError): + with self.assertRaises(client.AccessTokenCredentialsError): resp, content = http.request('http://example.com') def test_token_revoke_success(self): @@ -1579,7 +1553,7 @@ class TestAssertionCredentials(unittest2.TestCase): assertion_text = 'This is the assertion' assertion_type = 'http://www.google.com/assertionType' - class AssertionCredentialsTestImpl(AssertionCredentials): + class AssertionCredentialsTestImpl(client.AssertionCredentials): def _generate_assertion(self): return TestAssertionCredentials.assertion_text @@ -1590,7 +1564,7 @@ class TestAssertionCredentials(unittest2.TestCase): self.assertion_type, user_agent=user_agent) def test__generate_assertion_abstract(self): - credentials = AssertionCredentials(None) + credentials = client.AssertionCredentials(None) with self.assertRaises(NotImplementedError): credentials._generate_assertion() @@ -1621,7 +1595,7 @@ class TestAssertionCredentials(unittest2.TestCase): valid_bool_value=False, token_attr='access_token') def test_sign_blob_abstract(self): - credentials = AssertionCredentials(None) + credentials = client.AssertionCredentials(None) with self.assertRaises(NotImplementedError): credentials.sign_blob(b'blob') @@ -1629,18 +1603,18 @@ class TestAssertionCredentials(unittest2.TestCase): class UpdateQueryParamsTest(unittest2.TestCase): def test_update_query_params_no_params(self): uri = 'http://www.google.com' - updated = _update_query_params(uri, {'a': 'b'}) + updated = client._update_query_params(uri, {'a': 'b'}) self.assertEqual(updated, uri + '?a=b') def test_update_query_params_existing_params(self): uri = 'http://www.google.com?x=y' - updated = _update_query_params(uri, {'a': 'b', 'c': 'd&'}) + updated = client._update_query_params(uri, {'a': 'b', 'c': 'd&'}) hardcoded_update = uri + '&a=b&c=d%26' assertUrisEqual(self, updated, hardcoded_update) class ExtractIdTokenTest(unittest2.TestCase): - """Tests _extract_id_token().""" + """Tests client._extract_id_token().""" def test_extract_success(self): body = {'foo': 'bar'} @@ -1648,7 +1622,7 @@ class ExtractIdTokenTest(unittest2.TestCase): payload = base64.urlsafe_b64encode(body_json).strip(b'=') jwt = b'stuff.' + payload + b'.signature' - extracted = _extract_id_token(jwt) + extracted = client._extract_id_token(jwt) self.assertEqual(extracted, body) def test_extract_failure(self): @@ -1656,18 +1630,18 @@ class ExtractIdTokenTest(unittest2.TestCase): body_json = json.dumps(body).encode('ascii') payload = base64.urlsafe_b64encode(body_json).strip(b'=') jwt = b'stuff.' + payload - with self.assertRaises(VerifyJwtTokenError): - _extract_id_token(jwt) + with self.assertRaises(client.VerifyJwtTokenError): + client._extract_id_token(jwt) class OAuth2WebServerFlowTest(unittest2.TestCase): def setUp(self): - self.flow = OAuth2WebServerFlow( + self.flow = client.OAuth2WebServerFlow( client_id='client_id+1', client_secret='secret+1', scope='foo', - redirect_uri=OOB_CALLBACK_URN, + redirect_uri=client.OOB_CALLBACK_URN, user_agent='unittest-sample/1.0', revoke_uri='dummy_revoke_uri', ) @@ -1680,17 +1654,17 @@ class OAuth2WebServerFlowTest(unittest2.TestCase): self.assertEqual('client_id+1', q['client_id'][0]) self.assertEqual('code', q['response_type'][0]) self.assertEqual('foo', q['scope'][0]) - self.assertEqual(OOB_CALLBACK_URN, q['redirect_uri'][0]) + self.assertEqual(client.OOB_CALLBACK_URN, q['redirect_uri'][0]) self.assertEqual('offline', q['access_type'][0]) self.assertEqual('state+1', q['state'][0]) def test_override_flow_via_kwargs(self): """Passing kwargs to override defaults.""" - flow = OAuth2WebServerFlow( + flow = client.OAuth2WebServerFlow( client_id='client_id+1', client_secret='secret+1', scope='foo', - redirect_uri=OOB_CALLBACK_URN, + redirect_uri=client.OOB_CALLBACK_URN, user_agent='unittest-sample/1.0', access_type='online', response_type='token' @@ -1702,15 +1676,15 @@ class OAuth2WebServerFlowTest(unittest2.TestCase): self.assertEqual('client_id+1', q['client_id'][0]) self.assertEqual('token', q['response_type'][0]) self.assertEqual('foo', q['scope'][0]) - self.assertEqual(OOB_CALLBACK_URN, q['redirect_uri'][0]) + self.assertEqual(client.OOB_CALLBACK_URN, q['redirect_uri'][0]) self.assertEqual('online', q['access_type'][0]) @mock.patch('oauth2client.client.logger') def test_step1_get_authorize_url_redirect_override(self, logger): - flow = OAuth2WebServerFlow('client_id+1', scope='foo', - redirect_uri=OOB_CALLBACK_URN) + flow = client.OAuth2WebServerFlow('client_id+1', scope='foo', + redirect_uri=client.OOB_CALLBACK_URN) alt_redirect = 'foo:bar' - self.assertEqual(flow.redirect_uri, OOB_CALLBACK_URN) + self.assertEqual(flow.redirect_uri, client.OOB_CALLBACK_URN) result = flow.step1_get_authorize_url(redirect_uri=alt_redirect) # Make sure the redirect value was updated. self.assertEqual(flow.redirect_uri, alt_redirect) @@ -1721,44 +1695,44 @@ class OAuth2WebServerFlowTest(unittest2.TestCase): 'access_type': 'offline', 'response_type': 'code', } - expected = _update_query_params(flow.auth_uri, query_params) + expected = client._update_query_params(flow.auth_uri, query_params) assertUrisEqual(self, expected, result) # Check stubs. self.assertEqual(logger.warning.call_count, 1) def test_step1_get_authorize_url_without_redirect(self): - flow = OAuth2WebServerFlow('client_id+1', scope='foo', - redirect_uri=None) + flow = client.OAuth2WebServerFlow('client_id+1', scope='foo', + redirect_uri=None) with self.assertRaises(ValueError): flow.step1_get_authorize_url(redirect_uri=None) def test_step1_get_authorize_url_without_login_hint(self): login_hint = 'There are wascally wabbits nearby' - flow = OAuth2WebServerFlow('client_id+1', scope='foo', - redirect_uri=OOB_CALLBACK_URN, - login_hint=login_hint) + flow = client.OAuth2WebServerFlow('client_id+1', scope='foo', + redirect_uri=client.OOB_CALLBACK_URN, + login_hint=login_hint) result = flow.step1_get_authorize_url() query_params = { 'client_id': flow.client_id, 'login_hint': login_hint, - 'redirect_uri': OOB_CALLBACK_URN, + 'redirect_uri': client.OOB_CALLBACK_URN, 'scope': flow.scope, 'access_type': 'offline', 'response_type': 'code', } - expected = _update_query_params(flow.auth_uri, query_params) + expected = client._update_query_params(flow.auth_uri, query_params) assertUrisEqual(self, expected, result) def test_step1_get_device_and_user_codes_wo_device_uri(self): - flow = OAuth2WebServerFlow('CID', scope='foo', device_uri=None) + flow = client.OAuth2WebServerFlow('CID', scope='foo', device_uri=None) with self.assertRaises(ValueError): flow.step1_get_device_and_user_codes() def _step1_get_device_and_user_codes_helper( self, extra_headers=None, user_agent=None, default_http=False, content=None): - flow = OAuth2WebServerFlow('CID', scope='foo', - user_agent=user_agent) + flow = client.OAuth2WebServerFlow('CID', scope='foo', + user_agent=user_agent) device_code = 'bfc06756-062e-430f-9f0f-460ca44724e5' user_code = '5faf2780-fc83-11e5-9bc2-00c2c63e5792' ver_url = 'http://foo.bar' @@ -1777,11 +1751,12 @@ class OAuth2WebServerFlowTest(unittest2.TestCase): else: result = flow.step1_get_device_and_user_codes(http=http) - expected = DeviceFlowInfo(device_code, user_code, - None, ver_url, None) + expected = client.DeviceFlowInfo( + device_code, user_code, None, ver_url, None) self.assertEqual(result, expected) self.assertEqual(len(http.requests), 1) - self.assertEqual(http.requests[0]['uri'], client.GOOGLE_DEVICE_URI) + self.assertEqual( + http.requests[0]['uri'], oauth2client.GOOGLE_DEVICE_URI) body = http.requests[0]['body'] self.assertEqual(urllib.parse.parse_qs(body), {'client_id': [flow.client_id], @@ -1811,7 +1786,7 @@ class OAuth2WebServerFlowTest(unittest2.TestCase): def _step1_get_device_and_user_codes_fail_helper(self, status, content, error_msg): - flow = OAuth2WebServerFlow('CID', scope='foo') + flow = client.OAuth2WebServerFlow('CID', scope='foo') http = HttpMockSequence([ ({'status': status}, content), ]) @@ -1844,25 +1819,25 @@ class OAuth2WebServerFlowTest(unittest2.TestCase): error_msg) def test_step2_exchange_no_input(self): - flow = OAuth2WebServerFlow('client_id+1', scope='foo') + flow = client.OAuth2WebServerFlow('client_id+1', scope='foo') with self.assertRaises(ValueError): flow.step2_exchange() def test_step2_exchange_code_and_device_flow(self): - flow = OAuth2WebServerFlow('client_id+1', scope='foo') + flow = client.OAuth2WebServerFlow('client_id+1', scope='foo') with self.assertRaises(ValueError): flow.step2_exchange(code='code', device_flow_info='dfi') def test_scope_is_required(self): with self.assertRaises(TypeError): - OAuth2WebServerFlow('client_id+1') + client.OAuth2WebServerFlow('client_id+1') def test_exchange_failure(self): http = HttpMockSequence([ ({'status': '400'}, b'{"error":"invalid_request"}'), ]) - with self.assertRaises(FlowExchangeError): + with self.assertRaises(client.FlowExchangeError): self.flow.step2_exchange(code='some random code', http=http) def test_urlencoded_exchange_failure(self): @@ -1870,7 +1845,7 @@ class OAuth2WebServerFlowTest(unittest2.TestCase): ({'status': '400'}, b'error=invalid_request'), ]) - with self.assertRaisesRegexp(FlowExchangeError, + with self.assertRaisesRegexp(client.FlowExchangeError, 'invalid_request'): self.flow.step2_exchange(code='some random code', http=http) @@ -1887,7 +1862,7 @@ class OAuth2WebServerFlowTest(unittest2.TestCase): b'}') http = HttpMockSequence([({'status': '400'}, payload)]) - with self.assertRaises(FlowExchangeError): + with self.assertRaises(client.FlowExchangeError): self.flow.step2_exchange(code='some random code', http=http) def _exchange_success_test_helper(self, code=None, device_flow_info=None): @@ -1909,8 +1884,8 @@ class OAuth2WebServerFlowTest(unittest2.TestCase): self._exchange_success_test_helper(code='some random code') def test_exchange_success_with_device_flow_info(self): - device_flow_info = DeviceFlowInfo('some random code', None, - None, None, None) + device_flow_info = client.DeviceFlowInfo( + 'some random code', None, None, None, None) self._exchange_success_test_helper(device_flow_info=device_flow_info) def test_exchange_success_binary_code(self): @@ -1925,7 +1900,8 @@ class OAuth2WebServerFlowTest(unittest2.TestCase): ' "expires_in":' + expires_in + ',' ' "refresh_token":"' + refresh_token + '"' '}') - http = HttpMockSequence([({'status': '200'}, _to_bytes(payload))]) + http = HttpMockSequence( + [({'status': '200'}, _helpers._to_bytes(payload))]) credentials = self.flow.step2_exchange(code=binary_code, http=http) self.assertEqual(access_token, credentials.access_token) self.assertIsNotNone(credentials.token_expiry) @@ -1964,12 +1940,12 @@ class OAuth2WebServerFlowTest(unittest2.TestCase): self.assertEqual(code, request_code) def test_exchange_using_authorization_header(self): - auth_header = 'Basic Y2xpZW50X2lkKzE6c2VjcmV0KzE=', - flow = OAuth2WebServerFlow( + auth_header = 'Basic Y2xpZW50X2lkKzE6c2Vjexc_managerV0KzE=', + flow = client.OAuth2WebServerFlow( client_id='client_id+1', authorization_header=auth_header, scope='foo', - redirect_uri=OOB_CALLBACK_URN, + redirect_uri=client.OOB_CALLBACK_URN, user_agent='unittest-sample/1.0', revoke_uri='dummy_revoke_uri', ) @@ -2037,7 +2013,8 @@ class OAuth2WebServerFlowTest(unittest2.TestCase): http = HttpMockSequence([({'status': '200'}, payload)]) code = {'error': 'thou shall not pass'} - with self.assertRaisesRegexp(FlowExchangeError, 'shall not pass'): + with self.assertRaisesRegexp( + client.FlowExchangeError, 'shall not pass'): self.flow.step2_exchange(code=code, http=http) def test_exchange_id_token_fail(self): @@ -2048,7 +2025,7 @@ class OAuth2WebServerFlowTest(unittest2.TestCase): b'}') http = HttpMockSequence([({'status': '200'}, payload)]) - with self.assertRaises(VerifyJwtTokenError): + with self.assertRaises(client.VerifyJwtTokenError): self.flow.step2_exchange(code='some random code', http=http) def test_exchange_id_token(self): @@ -2075,7 +2052,7 @@ class FlowFromCachedClientsecrets(unittest2.TestCase): cache_mock = CacheMock() load_and_cache('client_secrets.json', 'some_secrets', cache_mock) - flow = flow_from_clientsecrets( + flow = client.flow_from_clientsecrets( 'some_secrets', '', redirect_uri='oob', cache=cache_mock) self.assertEqual('foo_client_secret', flow.client_secret) @@ -2083,7 +2060,7 @@ class FlowFromCachedClientsecrets(unittest2.TestCase): def _flow_from_clientsecrets_success_helper(self, loadfile_mock, device_uri=None, revoke_uri=None): - client_type = TYPE_WEB + client_type = clientsecrets.TYPE_WEB client_info = { 'auth_uri': 'auth_uri', 'token_uri': 'token_uri', @@ -2098,13 +2075,14 @@ class FlowFromCachedClientsecrets(unittest2.TestCase): cache = object() if device_uri is not None: - result = flow_from_clientsecrets(filename, scope, cache=cache, - device_uri=device_uri) + result = client.flow_from_clientsecrets( + filename, scope, cache=cache, device_uri=device_uri) self.assertEqual(result.device_uri, device_uri) else: - result = flow_from_clientsecrets(filename, scope, cache=cache) + result = client.flow_from_clientsecrets( + filename, scope, cache=cache) - self.assertIsInstance(result, OAuth2WebServerFlow) + self.assertIsInstance(result, client.OAuth2WebServerFlow) loadfile_mock.assert_called_once_with(filename, cache=cache) def test_flow_from_clientsecrets_success(self): @@ -2119,17 +2097,17 @@ class FlowFromCachedClientsecrets(unittest2.TestCase): self._flow_from_clientsecrets_success_helper(revoke_uri=revoke_uri) @mock.patch('oauth2client.clientsecrets.loadfile', - side_effect=InvalidClientSecretsError) + side_effect=clientsecrets.InvalidClientSecretsError) def test_flow_from_clientsecrets_invalid(self, loadfile_mock): filename = object() cache = object() - with self.assertRaises(InvalidClientSecretsError): - flow_from_clientsecrets(filename, None, cache=cache, - message=None) + with self.assertRaises(clientsecrets.InvalidClientSecretsError): + client.flow_from_clientsecrets( + filename, None, cache=cache, message=None) loadfile_mock.assert_called_once_with(filename, cache=cache) @mock.patch('oauth2client.clientsecrets.loadfile', - side_effect=InvalidClientSecretsError) + side_effect=clientsecrets.InvalidClientSecretsError) @mock.patch('sys.exit') def test_flow_from_clientsecrets_invalid_w_msg(self, sys_exit, loadfile_mock): @@ -2137,12 +2115,13 @@ class FlowFromCachedClientsecrets(unittest2.TestCase): cache = object() message = 'hi mom' - flow_from_clientsecrets(filename, None, cache=cache, message=message) + client.flow_from_clientsecrets( + filename, None, cache=cache, message=message) sys_exit.assert_called_once_with(message) loadfile_mock.assert_called_once_with(filename, cache=cache) @mock.patch('oauth2client.clientsecrets.loadfile', - side_effect=InvalidClientSecretsError('foobar')) + side_effect=clientsecrets.InvalidClientSecretsError('foobar')) @mock.patch('sys.exit') def test_flow_from_clientsecrets_invalid_w_msg_and_text(self, sys_exit, loadfile_mock): @@ -2152,7 +2131,8 @@ class FlowFromCachedClientsecrets(unittest2.TestCase): expected = ('The client secrets were invalid: ' '\n{0}\n{1}'.format('foobar', 'hi mom')) - flow_from_clientsecrets(filename, None, cache=cache, message=message) + client.flow_from_clientsecrets( + filename, None, cache=cache, message=message) sys_exit.assert_called_once_with(expected) loadfile_mock.assert_called_once_with(filename, cache=cache) @@ -2167,7 +2147,7 @@ class FlowFromCachedClientsecrets(unittest2.TestCase): '{0!r}'.format(client_type)) with self.assertRaisesRegexp(client.UnknownClientSecretsFlowError, err_msg): - flow_from_clientsecrets(filename, None, cache=cache) + client.flow_from_clientsecrets(filename, None, cache=cache) loadfile_mock.assert_called_once_with(filename, cache=cache) @@ -2187,9 +2167,9 @@ class CredentialsFromCodeTests(unittest2.TestCase): http = HttpMockSequence([ ({'status': '200'}, payload.encode('utf-8')), ]) - credentials = credentials_from_code(self.client_id, self.client_secret, - self.scope, self.code, http=http, - redirect_uri=self.redirect_uri) + credentials = client.credentials_from_code( + self.client_id, self.client_secret, self.scope, + self.code, http=http, redirect_uri=self.redirect_uri) self.assertEqual(credentials.access_token, token) self.assertNotEqual(None, credentials.token_expiry) self.assertEqual(set(['foo']), credentials.scopes) @@ -2199,10 +2179,10 @@ class CredentialsFromCodeTests(unittest2.TestCase): ({'status': '400'}, b'{"error":"invalid_request"}'), ]) - with self.assertRaises(FlowExchangeError): - credentials_from_code(self.client_id, self.client_secret, - self.scope, self.code, http=http, - redirect_uri=self.redirect_uri) + with self.assertRaises(client.FlowExchangeError): + client.credentials_from_code( + self.client_id, self.client_secret, self.scope, + self.code, http=http, redirect_uri=self.redirect_uri) def test_exchange_code_and_file_for_token(self): payload = (b'{' @@ -2210,7 +2190,7 @@ class CredentialsFromCodeTests(unittest2.TestCase): b' "expires_in":3600' b'}') http = HttpMockSequence([({'status': '200'}, payload)]) - credentials = credentials_from_clientsecrets_and_code( + credentials = client.credentials_from_clientsecrets_and_code( datafile('client_secrets.json'), self.scope, self.code, http=http) self.assertEqual(credentials.access_token, 'asdfghjkl') @@ -2224,7 +2204,7 @@ class CredentialsFromCodeTests(unittest2.TestCase): cache_mock = CacheMock() load_and_cache('client_secrets.json', 'some_secrets', cache_mock) - credentials = credentials_from_clientsecrets_and_code( + credentials = client.credentials_from_clientsecrets_and_code( 'some_secrets', self.scope, self.code, http=http, cache=cache_mock) self.assertEqual(credentials.access_token, 'asdfghjkl') @@ -2235,8 +2215,8 @@ class CredentialsFromCodeTests(unittest2.TestCase): ({'status': '400'}, b'{"error":"invalid_request"}'), ]) - with self.assertRaises(FlowExchangeError): - credentials_from_clientsecrets_and_code( + with self.assertRaises(client.FlowExchangeError): + client.credentials_from_clientsecrets_and_code( datafile('client_secrets.json'), self.scope, self.code, http=http) @@ -2319,9 +2299,9 @@ class TestDeviceFlowInfo(unittest2.TestCase): 'user_code': self.USER_CODE, 'verification_url': self.VER_URL, } - result = DeviceFlowInfo.FromResponse(response) - expected_result = DeviceFlowInfo(self.DEVICE_CODE, self.USER_CODE, - None, self.VER_URL, None) + result = client.DeviceFlowInfo.FromResponse(response) + expected_result = client.DeviceFlowInfo( + self.DEVICE_CODE, self.USER_CODE, None, self.VER_URL, None) self.assertEqual(result, expected_result) def test_FromResponse_fallback_to_uri(self): @@ -2330,9 +2310,9 @@ class TestDeviceFlowInfo(unittest2.TestCase): 'user_code': self.USER_CODE, 'verification_uri': self.VER_URL, } - result = DeviceFlowInfo.FromResponse(response) - expected_result = DeviceFlowInfo(self.DEVICE_CODE, self.USER_CODE, - None, self.VER_URL, None) + result = client.DeviceFlowInfo.FromResponse(response) + expected_result = client.DeviceFlowInfo( + self.DEVICE_CODE, self.USER_CODE, None, self.VER_URL, None) self.assertEqual(result, expected_result) def test_FromResponse_missing_url(self): @@ -2341,7 +2321,7 @@ class TestDeviceFlowInfo(unittest2.TestCase): 'user_code': self.USER_CODE, } with self.assertRaises(client.OAuth2DeviceCodeError): - DeviceFlowInfo.FromResponse(response) + client.DeviceFlowInfo.FromResponse(response) @mock.patch('oauth2client.client._UTCNOW') def test_FromResponse_with_expires_in(self, utcnow): @@ -2356,7 +2336,7 @@ class TestDeviceFlowInfo(unittest2.TestCase): expire = datetime.datetime(1999, 1, 1, 12, 30, 27 + expires_in) utcnow.return_value = now - result = DeviceFlowInfo.FromResponse(response) - expected_result = DeviceFlowInfo(self.DEVICE_CODE, self.USER_CODE, - None, self.VER_URL, expire) + result = client.DeviceFlowInfo.FromResponse(response) + expected_result = client.DeviceFlowInfo( + self.DEVICE_CODE, self.USER_CODE, None, self.VER_URL, expire) self.assertEqual(result, expected_result) diff --git a/tests/test_clientsecrets.py b/tests/test_clientsecrets.py index 95be076..42eb8c7 100644 --- a/tests/test_clientsecrets.py +++ b/tests/test_clientsecrets.py @@ -21,11 +21,9 @@ import tempfile import unittest2 +import oauth2client +from oauth2client import _helpers 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)' @@ -157,9 +155,9 @@ class Test__loadfile(unittest2.TestCase): 'client_id': 'foo_client_id', 'client_secret': 'foo_client_secret', 'redirect_uris': [], - 'auth_uri': GOOGLE_AUTH_URI, - 'token_uri': GOOGLE_TOKEN_URI, - 'revoke_uri': GOOGLE_REVOKE_URI, + 'auth_uri': oauth2client.GOOGLE_AUTH_URI, + 'token_uri': oauth2client.GOOGLE_TOKEN_URI, + 'revoke_uri': oauth2client.GOOGLE_REVOKE_URI, } self.assertEqual(client_type, clientsecrets.TYPE_WEB) self.assertEqual(client_info, expected_client_info) @@ -200,7 +198,7 @@ class OAuth2CredentialsTests(unittest2.TestCase): ] for src, match in ERRORS: # Ensure that it is unicode - src = _from_bytes(src) + src = _helpers._from_bytes(src) # Test load(s) with self.assertRaises( clientsecrets.InvalidClientSecretsError) as exc_manager: diff --git a/tests/test_crypt.py b/tests/test_crypt.py index d7312ef..b7534bd 100644 --- a/tests/test_crypt.py +++ b/tests/test_crypt.py @@ -19,9 +19,9 @@ import mock import unittest2 from oauth2client import _helpers +from oauth2client import client from oauth2client import crypt -from oauth2client.client import HAS_OPENSSL -from oauth2client.service_account import ServiceAccountCredentials +from oauth2client import service_account 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'): filename = data_filename(private_key_file) - credentials = ServiceAccountCredentials.from_p12_keyfile( - 'some_account@example.com', - filename, - scopes='read+write') + credentials = ( + service_account.ServiceAccountCredentials.from_p12_keyfile( + 'some_account@example.com', filename, + scopes='read+write')) credentials._kwargs['sub'] = 'joe@example.org' return credentials def _succeeds_helper(self, password=None): - self.assertEqual(True, HAS_OPENSSL) + self.assertEqual(True, client.HAS_OPENSSL) credentials = self._make_svc_account_creds() if password is None: diff --git a/tests/test_file.py b/tests/test_file.py index 6962dee..924acb4 100644 --- a/tests/test_file.py +++ b/tests/test_file.py @@ -29,9 +29,8 @@ import six from six.moves import http_client import unittest2 +from oauth2client import client from oauth2client import file -from oauth2client.client import AccessTokenCredentials -from oauth2client.client import OAuth2Credentials from .http_mock import HttpMockSequence try: @@ -69,7 +68,7 @@ class OAuth2ClientFileTests(unittest2.TestCase): token_uri = 'https://www.google.com/accounts/o8/oauth2/token' user_agent = 'refresh_checker/1.0' - credentials = OAuth2Credentials( + credentials = client.OAuth2Credentials( access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent) @@ -112,7 +111,7 @@ class OAuth2ClientFileTests(unittest2.TestCase): self.assertEquals(data['access_token'], 'foo') 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): expiration = (datetime.datetime.utcnow() - @@ -228,7 +227,7 @@ class OAuth2ClientFileTests(unittest2.TestCase): access_token = 'foo' user_agent = 'refresh_checker/1.0' - credentials = AccessTokenCredentials(access_token, user_agent) + credentials = client.AccessTokenCredentials(access_token, user_agent) s = file.Storage(FILENAME) credentials = s.put(credentials) diff --git a/tests/test_jwt.py b/tests/test_jwt.py index 762f12f..ecc58e8 100644 --- a/tests/test_jwt.py +++ b/tests/test_jwt.py @@ -21,15 +21,11 @@ import time import mock import unittest2 +from oauth2client import _helpers +from oauth2client import client from oauth2client import crypt -from oauth2client.client import Credentials -from oauth2client.client import HAS_CRYPTO -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 oauth2client import file +from oauth2client import service_account from .http_mock import HttpMockSequence @@ -125,7 +121,7 @@ class CryptTests(unittest2.TestCase): ({'status': '200'}, datafile('certs.json')), ]) - contents = verify_id_token( + contents = client.verify_id_token( jwt, 'some_audience_address@testing.gserviceaccount.com', http=http) self.assertEqual('billy bob', contents['user']) @@ -139,7 +135,7 @@ class CryptTests(unittest2.TestCase): ]) 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') self.assertEqual('billy bob', contents['user']) @@ -153,8 +149,8 @@ class CryptTests(unittest2.TestCase): ({'status': '404'}, datafile('certs.json')), ]) - with self.assertRaises(VerifyJwtTokenError): - verify_id_token(jwt, test_email, http=http) + with self.assertRaises(client.VerifyJwtTokenError): + client.verify_id_token(jwt, test_email, http=http) def test_verify_id_token_bad_tokens(self): private_key = datafile('privatekey.' + self.format_) @@ -167,7 +163,7 @@ class CryptTests(unittest2.TestCase): # Bad signature jwt = b'.'.join([b'foo', - crypt._urlsafe_b64encode('{"a":"b"}'), + _helpers._urlsafe_b64encode('{"a":"b"}'), b'baz']) self._check_jwt_failure(jwt, 'Invalid token signature') @@ -245,7 +241,7 @@ class SignedJwtAssertionCredentialsTests(unittest2.TestCase): def _make_credentials(self): private_key = datafile('privatekey.' + self.format_) signer = crypt.Signer.from_string(private_key) - credentials = ServiceAccountCredentials( + credentials = service_account.ServiceAccountCredentials( 'some_account@example.com', signer, scopes='read+write', sub='joe@example.org') @@ -253,7 +249,8 @@ class SignedJwtAssertionCredentialsTests(unittest2.TestCase): credentials._private_key_pkcs8_pem = private_key elif self.format_ == 'p12': credentials._private_key_pkcs12 = private_key - credentials._private_key_password = _PASSWORD_DEFAULT + credentials._private_key_password = ( + service_account._PASSWORD_DEFAULT) else: # pragma: NO COVER raise ValueError('Unexpected format.') return credentials @@ -271,7 +268,7 @@ class SignedJwtAssertionCredentialsTests(unittest2.TestCase): def test_credentials_to_from_json(self): credentials = self._make_credentials() json = credentials.to_json() - restored = Credentials.new_from_json(json) + restored = client.Credentials.new_from_json(json) self.assertEqual(credentials._private_key_pkcs12, restored._private_key_pkcs12) self.assertEqual(credentials._private_key_password, @@ -299,7 +296,7 @@ class SignedJwtAssertionCredentialsTests(unittest2.TestCase): filehandle, filename = tempfile.mkstemp() os.close(filehandle) - store = Storage(filename) + store = file.Storage(filename) store.put(credentials) credentials.set_store(store) @@ -328,5 +325,5 @@ class PEMSignedJwtAssertionCredentialsPyCryptoTests( class TestHasOpenSSLFlag(unittest2.TestCase): def test_true(self): - self.assertEqual(True, HAS_OPENSSL) - self.assertEqual(True, HAS_CRYPTO) + self.assertEqual(True, client.HAS_OPENSSL) + self.assertEqual(True, client.HAS_CRYPTO) diff --git a/tests/test_service_account.py b/tests/test_service_account.py index 3bdfc0d..699e699 100644 --- a/tests/test_service_account.py +++ b/tests/test_service_account.py @@ -28,10 +28,9 @@ import rsa from six import BytesIO import unittest2 +from oauth2client import client from oauth2client import crypt -from oauth2client.service_account import _JWTAccessCredentials -from oauth2client.service_account import SERVICE_ACCOUNT -from oauth2client.service_account import ServiceAccountCredentials +from oauth2client import service_account from .http_mock import HttpMockSequence @@ -53,7 +52,7 @@ class ServiceAccountCredentialsTests(unittest2.TestCase): self.private_key = datafile('pem_from_pkcs12.pem') self.scopes = ['dummy_scope'] self.signer = crypt.Signer.from_string(self.private_key) - self.credentials = ServiceAccountCredentials( + self.credentials = service_account.ServiceAccountCredentials( self.service_account_email, self.signer, private_key_id=self.private_key_id, @@ -62,8 +61,8 @@ class ServiceAccountCredentialsTests(unittest2.TestCase): def test__to_json_override(self): signer = object() - creds = ServiceAccountCredentials('name@email.com', - signer) + creds = service_account.ServiceAccountCredentials( + 'name@email.com', signer) self.assertEqual(creds._signer, signer) # Serialize over-ridden data (unrelated to ``creds``). to_serialize = {'unrelated': 'data'} @@ -103,9 +102,11 @@ class ServiceAccountCredentialsTests(unittest2.TestCase): try: with open(filename, 'w') as file_obj: json.dump(payload, file_obj) - return ServiceAccountCredentials.from_json_keyfile_name( - filename, scopes=scopes, token_uri=token_uri, - revoke_uri=revoke_uri) + return ( + service_account.ServiceAccountCredentials + .from_json_keyfile_name( + filename, scopes=scopes, token_uri=token_uri, + revoke_uri=revoke_uri)) finally: os.remove(filename) @@ -117,7 +118,7 @@ class ServiceAccountCredentialsTests(unittest2.TestCase): private_key_id = 'pkid456' private_key = 's3kr3tz' payload = { - 'type': SERVICE_ACCOUNT, + 'type': client.SERVICE_ACCOUNT, 'client_id': client_id, 'client_email': client_email, '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( payload, scopes=scopes) 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._service_account_email, client_email) 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): type_ = 'bad-type' - self.assertNotEqual(type_, SERVICE_ACCOUNT) + self.assertNotEqual(type_, client.SERVICE_ACCOUNT) payload = {'type': type_} with self.assertRaises(ValueError): self._from_json_keyfile_name_helper(payload) def test_from_json_keyfile_name_factory_missing_field(self): payload = { - 'type': SERVICE_ACCOUNT, + 'type': client.SERVICE_ACCOUNT, 'client_id': 'my-client', } with self.assertRaises(KeyError): @@ -166,17 +168,19 @@ class ServiceAccountCredentialsTests(unittest2.TestCase): filename = data_filename('privatekey.p12') with open(filename, 'rb') as file_obj: key_contents = file_obj.read() - creds_from_filename = ServiceAccountCredentials.from_p12_keyfile( - service_account_email, filename, - private_key_password=private_key_password, - scopes=scopes, token_uri=token_uri, revoke_uri=revoke_uri) + creds_from_filename = ( + service_account.ServiceAccountCredentials.from_p12_keyfile( + service_account_email, filename, + private_key_password=private_key_password, + scopes=scopes, token_uri=token_uri, revoke_uri=revoke_uri)) creds_from_file_contents = ( - ServiceAccountCredentials.from_p12_keyfile_buffer( + service_account.ServiceAccountCredentials.from_p12_keyfile_buffer( service_account_email, BytesIO(key_contents), private_key_password=private_key_password, scopes=scopes, token_uri=token_uri, revoke_uri=revoke_uri)) 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.assertEqual(creds._service_account_email, service_account_email) @@ -194,7 +198,7 @@ class ServiceAccountCredentialsTests(unittest2.TestCase): service_account_email = 'name@email.com' filename = data_filename('privatekey.p12') with self.assertRaises(NotImplementedError): - ServiceAccountCredentials.from_p12_keyfile( + service_account.ServiceAccountCredentials.from_p12_keyfile( service_account_email, filename) @mock.patch('oauth2client.crypt.Signer', new=crypt.PyCryptoSigner) @@ -219,7 +223,7 @@ class ServiceAccountCredentialsTests(unittest2.TestCase): def test_create_scoped_required_with_scopes(self): signer = object() - self.credentials = ServiceAccountCredentials( + self.credentials = service_account.ServiceAccountCredentials( self.service_account_email, signer, scopes=self.scopes, @@ -232,13 +236,14 @@ class ServiceAccountCredentialsTests(unittest2.TestCase): new_credentials = self.credentials.create_scoped(self.scopes) self.assertNotEqual(self.credentials, new_credentials) self.assertIsInstance(new_credentials, - ServiceAccountCredentials) + service_account.ServiceAccountCredentials) self.assertEqual('dummy_scope', new_credentials._scopes) def test_create_delegated(self): signer = object() sub = 'foo@email.com' - creds = ServiceAccountCredentials('name@email.com', signer) + creds = service_account.ServiceAccountCredentials( + 'name@email.com', signer) self.assertNotIn('sub', creds._kwargs) delegated_creds = creds.create_delegated(sub) self.assertEqual(delegated_creds._kwargs['sub'], sub) @@ -249,7 +254,8 @@ class ServiceAccountCredentialsTests(unittest2.TestCase): signer = object() sub1 = 'existing@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) delegated_creds = creds.create_delegated(sub2) self.assertEqual(delegated_creds._kwargs['sub'], sub2) @@ -268,7 +274,7 @@ class ServiceAccountCredentialsTests(unittest2.TestCase): signed_value = b'signed-content' signer.sign = mock.MagicMock(name='sign', return_value=signed_value) - credentials = ServiceAccountCredentials( + credentials = service_account.ServiceAccountCredentials( self.service_account_email, signer, private_key_id=self.private_key_id, @@ -356,7 +362,7 @@ class ServiceAccountCredentialsTests(unittest2.TestCase): 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_DATE = datetime.datetime(1970, 1, 1, second=T1) T1_EXPIRY = T1 + TOKEN_LIFE @@ -382,18 +388,15 @@ class JWTAccessCredentialsTests(unittest2.TestCase): self.private_key = datafile('pem_from_pkcs12.pem') self.signer = crypt.Signer.from_string(self.private_key) self.url = 'https://test.url.com' - self.jwt = _JWTAccessCredentials(self.service_account_email, - self.signer, - private_key_id=self.private_key_id, - client_id=self.client_id, - additional_claims={'aud': self.url}) + self.jwt = service_account._JWTAccessCredentials( + self.service_account_email, self.signer, + private_key_id=self.private_key_id, client_id=self.client_id, + additional_claims={'aud': self.url}) - @mock.patch('oauth2client.service_account._UTCNOW') @mock.patch('oauth2client.client._UTCNOW') @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 - client_utcnow.return_value = T1_DATE time.return_value = T1 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 utcnow.return_value = T2_DATE - client_utcnow.return_value = T2_DATE token_info = self.jwt.get_access_token() payload = crypt.verify_signed_jwt_with_certs( token_info.access_token, @@ -419,7 +421,6 @@ class JWTAccessCredentialsTests(unittest2.TestCase): # Verify that we vend a new token after _MAX_TOKEN_LIFETIME_SECS utcnow.return_value = T3_DATE - client_utcnow.return_value = T3_DATE time.return_value = T3 token_info = self.jwt.get_access_token() payload = crypt.verify_signed_jwt_with_certs( @@ -430,7 +431,7 @@ class JWTAccessCredentialsTests(unittest2.TestCase): self.assertEqual(payload['exp'], T3_EXPIRY) self.assertEqual(expires_in, T3_EXPIRY - T3) - @mock.patch('oauth2client.service_account._UTCNOW') + @mock.patch('oauth2client.client._UTCNOW') @mock.patch('time.time') def test_get_access_token_additional_claims(self, time, utcnow): utcnow.return_value = T1_DATE @@ -463,15 +464,14 @@ class JWTAccessCredentialsTests(unittest2.TestCase): new_credentials = self.jwt.create_scoped('dummy_scope') 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) - @mock.patch('oauth2client.service_account._UTCNOW') @mock.patch('oauth2client.client._UTCNOW') @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 - client_utcnow.return_value = T1_DATE time.return_value = T1 def mock_request(uri, method='GET', body=None, headers=None, @@ -497,21 +497,17 @@ class JWTAccessCredentialsTests(unittest2.TestCase): # Ensure we use the cached token utcnow.return_value = T2_DATE - client_utcnow.return_value = T2_DATE h.request(self.url) - @mock.patch('oauth2client.service_account._UTCNOW') @mock.patch('oauth2client.client._UTCNOW') @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 - client_utcnow.return_value = T1_DATE time.return_value = T1 - jwt = _JWTAccessCredentials(self.service_account_email, - self.signer, - private_key_id=self.private_key_id, - client_id=self.client_id) + jwt = service_account._JWTAccessCredentials( + self.service_account_email, self.signer, + private_key_id=self.private_key_id, client_id=self.client_id) def mock_request(uri, method='GET', body=None, headers=None, redirections=0, connection_type=None): @@ -537,7 +533,7 @@ class JWTAccessCredentialsTests(unittest2.TestCase): # Ensure we do not cache the token self.assertIsNone(jwt.access_token) - @mock.patch('oauth2client.service_account._UTCNOW') + @mock.patch('oauth2client.client._UTCNOW') def test_authorize_stale_token(self, utcnow): utcnow.return_value = T1_DATE # Create an initial token @@ -554,7 +550,7 @@ class JWTAccessCredentialsTests(unittest2.TestCase): self.assertEquals(self.jwt.token_expiry, T3_EXPIRY_DATE) self.assertNotEqual(token_1, token_2) - @mock.patch('oauth2client.service_account._UTCNOW') + @mock.patch('oauth2client.client._UTCNOW') def test_authorize_401(self, utcnow): utcnow.return_value = T1_DATE @@ -572,7 +568,7 @@ class JWTAccessCredentialsTests(unittest2.TestCase): # Check the 401 forced a new token self.assertNotEqual(token_1, token_2) - @mock.patch('oauth2client.service_account._UTCNOW') + @mock.patch('oauth2client.client._UTCNOW') def test_refresh(self, utcnow): utcnow.return_value = T1_DATE token_1 = self.jwt.access_token diff --git a/tests/test_tools.py b/tests/test_tools.py index 8a86324..369f567 100644 --- a/tests/test_tools.py +++ b/tests/test_tools.py @@ -20,9 +20,8 @@ import mock from six.moves.urllib import request import unittest2 +from oauth2client import client from oauth2client import tools -from oauth2client.client import FlowExchangeError -from oauth2client.client import OOB_CALLBACK_URN try: import argparse @@ -82,7 +81,7 @@ class TestRunFlow(unittest2.TestCase): returned_credentials = tools.run_flow(self.flow, self.storage) 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( 'auth_code', http=None) 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.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( 'auth_code', http=None) @@ -108,7 +107,7 @@ class TestRunFlow(unittest2.TestCase): def test_run_flow_no_webserver_exchange_error( self, input_mock, logging_mock): input_mock.return_value = 'auth_code' - self.flow.step2_exchange.side_effect = FlowExchangeError() + self.flow.step2_exchange.side_effect = client.FlowExchangeError() # Error while exchanging. with self.assertRaises(SystemExit): @@ -181,7 +180,7 @@ class TestRunFlow(unittest2.TestCase): self.flow, self.storage, flags=self.server_flags) 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( 'auth_code', http=None) self.assertTrue(server_ctor_mock.called)