From c8640c0d72945c5224af673fa3f24bb8068fc59d Mon Sep 17 00:00:00 2001 From: Pat Ferate Date: Thu, 7 Jul 2016 13:55:38 -0700 Subject: [PATCH 1/8] Remove unused imports --- oauth2client/_openssl_crypt.py | 2 -- oauth2client/client.py | 2 -- oauth2client/contrib/django_orm.py | 1 - oauth2client/service_account.py | 4 ---- tests/contrib/test_django_orm.py | 5 +---- 5 files changed, 1 insertion(+), 13 deletions(-) diff --git a/oauth2client/_openssl_crypt.py b/oauth2client/_openssl_crypt.py index 7a76fb7..49b763b 100644 --- a/oauth2client/_openssl_crypt.py +++ b/oauth2client/_openssl_crypt.py @@ -13,8 +13,6 @@ # limitations under the License. """OpenSSL Crypto-related routines for oauth2client.""" -import base64 - from OpenSSL import crypto from oauth2client._helpers import _parse_pem_key diff --git a/oauth2client/client.py b/oauth2client/client.py index 432146e..8bef6e6 100644 --- a/oauth2client/client.py +++ b/oauth2client/client.py @@ -17,7 +17,6 @@ Tools for interacting with OAuth 2.0 protected resources. """ -import base64 import collections import copy import datetime @@ -27,7 +26,6 @@ import os import socket import sys import tempfile -import time import shutil import six from six.moves import http_client diff --git a/oauth2client/contrib/django_orm.py b/oauth2client/contrib/django_orm.py index 18e24f2..f080bd5 100644 --- a/oauth2client/contrib/django_orm.py +++ b/oauth2client/contrib/django_orm.py @@ -24,7 +24,6 @@ Only Django versions 1.8+ are supported. import oauth2client import base64 import pickle -import six from django.db import models from django.utils.encoding import smart_bytes, smart_text diff --git a/oauth2client/service_account.py b/oauth2client/service_account.py index ce7f78e..ed7c904 100644 --- a/oauth2client/service_account.py +++ b/oauth2client/service_account.py @@ -23,9 +23,7 @@ import time from oauth2client import GOOGLE_REVOKE_URI from oauth2client import GOOGLE_TOKEN_URI -from oauth2client._helpers import _json_encode from oauth2client._helpers import _from_bytes -from oauth2client._helpers import _urlsafe_b64encode from oauth2client import util from oauth2client.client import _apply_user_agent from oauth2client.client import _initialize_headers @@ -33,9 +31,7 @@ from oauth2client.client import AccessTokenInfo from oauth2client.client import AssertionCredentials from oauth2client.client import clean_headers from oauth2client.client import EXPIRY_FORMAT -from oauth2client.client import GoogleCredentials from oauth2client.client import SERVICE_ACCOUNT -from oauth2client.client import TokenRevokeError from oauth2client.client import _UTCNOW from oauth2client import crypt diff --git a/tests/contrib/test_django_orm.py b/tests/contrib/test_django_orm.py index 2924bea..a28b7e8 100644 --- a/tests/contrib/test_django_orm.py +++ b/tests/contrib/test_django_orm.py @@ -19,14 +19,11 @@ Unit tests for objects created from discovery documents. import base64 import datetime -import imp import os import pickle -import sys import unittest2 -# Mock a Django environment -from django.conf import global_settings +# Mock a Django environment os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.contrib.test_django_settings' from django.conf import settings From 514c1707460038494598f88f6569cec388724cf1 Mon Sep 17 00:00:00 2001 From: Pat Ferate Date: Thu, 7 Jul 2016 14:11:02 -0700 Subject: [PATCH 2/8] Remove unused local variable assignment Fixed flake8 F841 errors: local variable is assigned to but never used. --- oauth2client/contrib/django_orm.py | 2 +- tests/contrib/test_appengine.py | 10 ++++------ tests/contrib/test_xsrfutil.py | 1 - tests/test_client.py | 31 ++++++++++++------------------ tests/test_tools.py | 6 ++---- 5 files changed, 19 insertions(+), 31 deletions(-) diff --git a/oauth2client/contrib/django_orm.py b/oauth2client/contrib/django_orm.py index f080bd5..dd83b8f 100644 --- a/oauth2client/contrib/django_orm.py +++ b/oauth2client/contrib/django_orm.py @@ -178,4 +178,4 @@ class Storage(BaseStorage): """Delete Credentials from the datastore.""" query = {self.key_name: self.key_value} - entities = self.model_class.objects.filter(**query).delete() + self.model_class.objects.filter(**query).delete() diff --git a/tests/contrib/test_appengine.py b/tests/contrib/test_appengine.py index de7821c..31b8b0c 100644 --- a/tests/contrib/test_appengine.py +++ b/tests/contrib/test_appengine.py @@ -847,7 +847,7 @@ class DecoratorTests(unittest2.TestCase): # An initial request to an oauth_aware decorated path should # not redirect. response = self.app.get('/bar_path/2012/01') - url = self.decorator.authorize_url() + self.decorator.authorize_url() response = self.app.get('/oauth2callback', { 'error': 'BadHappened\'' }) @@ -903,9 +903,7 @@ class DecoratorTests(unittest2.TestCase): with decorator_patch as decorator_mock: filename = datafile('client_secrets.json') - decorator = oauth2decorator_from_clientsecrets( - filename, - scope='foo_scope') + oauth2decorator_from_clientsecrets(filename, scope='foo_scope') decorator_mock.assert_called_once_with( filename, 'foo_scope', @@ -974,7 +972,7 @@ class DecoratorTests(unittest2.TestCase): def test_decorator_from_unfilled_client_secrets_required(self): MESSAGE = 'File is missing' try: - decorator = OAuth2DecoratorFromClientSecrets( + OAuth2DecoratorFromClientSecrets( datafile('unfilled_client_secrets.json'), scope=['foo_scope', 'bar_scope'], message=MESSAGE) except InvalidClientSecretsError: @@ -983,7 +981,7 @@ class DecoratorTests(unittest2.TestCase): def test_decorator_from_unfilled_client_secrets_aware(self): MESSAGE = 'File is missing' try: - decorator = OAuth2DecoratorFromClientSecrets( + OAuth2DecoratorFromClientSecrets( datafile('unfilled_client_secrets.json'), scope=['foo_scope', 'bar_scope'], message=MESSAGE) except InvalidClientSecretsError: diff --git a/tests/contrib/test_xsrfutil.py b/tests/contrib/test_xsrfutil.py index 363a189..f397e1f 100644 --- a/tests/contrib/test_xsrfutil.py +++ b/tests/contrib/test_xsrfutil.py @@ -49,7 +49,6 @@ class Test_generate_token(unittest2.TestCase): def test_it(self): digest = b'foobar' - curr_time = 1440449755.74 digester = mock.MagicMock() digester.digest = mock.MagicMock(name='digest', return_value=digest) with mock.patch('oauth2client.contrib.xsrfutil.hmac') as hmac: diff --git a/tests/test_client.py b/tests/test_client.py index 8099538..59a80e8 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -124,7 +124,7 @@ class CredentialsTests(unittest2.TestCase): def test_to_from_json(self): credentials = Credentials() json = credentials.to_json() - restored = Credentials.new_from_json(json) + Credentials.new_from_json(json) def test_authorize_abstract(self): credentials = Credentials() @@ -1863,8 +1863,7 @@ class OAuth2WebServerFlowTest(unittest2.TestCase): ]) with self.assertRaises(FlowExchangeError): - credentials = self.flow.step2_exchange(code='some random code', - http=http) + self.flow.step2_exchange(code='some random code', http=http) def test_urlencoded_exchange_failure(self): http = HttpMockSequence([ @@ -1873,8 +1872,7 @@ class OAuth2WebServerFlowTest(unittest2.TestCase): with self.assertRaisesRegexp(FlowExchangeError, 'invalid_request'): - credentials = self.flow.step2_exchange(code='some random code', - http=http) + self.flow.step2_exchange(code='some random code', http=http) def test_exchange_failure_with_json_error(self): # Some providers have 'error' attribute as a JSON object @@ -1890,8 +1888,7 @@ class OAuth2WebServerFlowTest(unittest2.TestCase): http = HttpMockSequence([({'status': '400'}, payload)]) with self.assertRaises(FlowExchangeError): - credentials = self.flow.step2_exchange(code='some random code', - http=http) + self.flow.step2_exchange(code='some random code', http=http) def _exchange_success_test_helper(self, code=None, device_flow_info=None): payload = (b'{' @@ -2040,9 +2037,8 @@ class OAuth2WebServerFlowTest(unittest2.TestCase): http = HttpMockSequence([({'status': '200'}, payload)]) code = {'error': 'thou shall not pass'} - with self.assertRaisesRegexp(FlowExchangeError, - 'shall not pass'): - credentials = self.flow.step2_exchange(code=code, http=http) + with self.assertRaisesRegexp(FlowExchangeError, 'shall not pass'): + self.flow.step2_exchange(code=code, http=http) def test_exchange_id_token_fail(self): payload = (b'{' @@ -2190,9 +2186,8 @@ class CredentialsFromCodeTests(unittest2.TestCase): ({'status': '200'}, payload.encode('utf-8')), ]) credentials = credentials_from_code(self.client_id, self.client_secret, - self.scope, self.code, - redirect_uri=self.redirect_uri, - http=http) + 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) @@ -2203,11 +2198,9 @@ class CredentialsFromCodeTests(unittest2.TestCase): ]) with self.assertRaises(FlowExchangeError): - credentials = credentials_from_code(self.client_id, - self.client_secret, - self.scope, self.code, - redirect_uri=self.redirect_uri, - http=http) + 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'{' @@ -2241,7 +2234,7 @@ class CredentialsFromCodeTests(unittest2.TestCase): ]) with self.assertRaises(FlowExchangeError): - credentials = credentials_from_clientsecrets_and_code( + credentials_from_clientsecrets_and_code( datafile('client_secrets.json'), self.scope, self.code, http=http) diff --git a/tests/test_tools.py b/tests/test_tools.py index 8efe9e1..bd19227 100644 --- a/tests/test_tools.py +++ b/tests/test_tools.py @@ -149,8 +149,7 @@ class TestRunFlow(unittest2.TestCase): # Exchange returned an error code. with self.assertRaises(SystemExit): - returned_credentials = tools.run_flow( - self.flow, self.storage, flags=self.server_flags) + tools.run_flow(self.flow, self.storage, flags=self.server_flags) self.assertTrue(self.server.handle_request.called) @@ -164,8 +163,7 @@ class TestRunFlow(unittest2.TestCase): # No code found in response with self.assertRaises(SystemExit): - returned_credentials = tools.run_flow( - self.flow, self.storage, flags=self.server_flags) + tools.run_flow(self.flow, self.storage, flags=self.server_flags) self.assertTrue(self.server.handle_request.called) From 1934bfb1796f27076be6c3b7ba20d3a30fc7cf99 Mon Sep 17 00:00:00 2001 From: Pat Ferate Date: Fri, 8 Jul 2016 10:24:21 -0700 Subject: [PATCH 3/8] Clean up whitespace --- oauth2client/client.py | 14 ++++++------- oauth2client/contrib/django_util/__init__.py | 4 ++-- oauth2client/contrib/flask_util.py | 4 ++-- oauth2client/service_account.py | 14 ++++++------- tests/contrib/test_django_util.py | 5 ++--- tests/contrib/test_gce.py | 1 + tests/contrib/test_metadata.py | 4 ++-- tests/test__pure_python_crypt.py | 2 +- tests/test_client.py | 2 +- tests/test_clientsecrets.py | 20 +++++++++--------- tests/test_crypt.py | 3 ++- tests/test_service_account.py | 22 ++++++++++---------- tests/test_tools.py | 5 ++--- tests/test_util.py | 4 ---- 14 files changed, 49 insertions(+), 55 deletions(-) diff --git a/oauth2client/client.py b/oauth2client/client.py index 8bef6e6..a0e4473 100644 --- a/oauth2client/client.py +++ b/oauth2client/client.py @@ -1193,7 +1193,7 @@ class GoogleCredentials(OAuth2Credentials): print(response) """ - NON_SERIALIZED_MEMBERS = ( + NON_SERIALIZED_MEMBERS = ( frozenset(['_private_key']) | OAuth2Credentials.NON_SERIALIZED_MEMBERS) """Members that aren't serialized when object is converted to JSON.""" @@ -1251,12 +1251,11 @@ class GoogleCredentials(OAuth2Credentials): # 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'): + data['_class'] == 'ServiceAccountCredentials'): return ServiceAccountCredentials.from_json(data) elif (data['_module'] == 'oauth2client.service_account' and - data['_class'] == '_JWTAccessCredentials'): + data['_class'] == '_JWTAccessCredentials'): return _JWTAccessCredentials.from_json(data) - token_expiry = _parse_expiry(data.get('token_expiry')) google_credentials = cls( @@ -1466,8 +1465,7 @@ def save_to_well_known_file(credentials, well_known_file=None): def _get_environment_variable_file(): application_default_credential_filename = ( - os.environ.get(GOOGLE_APPLICATION_CREDENTIALS, - None)) + os.environ.get(GOOGLE_APPLICATION_CREDENTIALS, None)) if application_default_credential_filename: if os.path.isfile(application_default_credential_filename): @@ -1550,8 +1548,8 @@ def _raise_exception_for_reading_json(credential_file, extra_help, error): raise ApplicationDefaultCredentialsError( - 'An error was encountered while reading json file: ' + - credential_file + extra_help + ': ' + str(error)) + 'An error was encountered while reading json file: ' + + credential_file + extra_help + ': ' + str(error)) def _get_application_default_credential_GAE(): diff --git a/oauth2client/contrib/django_util/__init__.py b/oauth2client/contrib/django_util/__init__.py index 5aa12ac..19ac8b4 100644 --- a/oauth2client/contrib/django_util/__init__.py +++ b/oauth2client/contrib/django_util/__init__.py @@ -290,8 +290,8 @@ class UserOAuth2(object): def has_credentials(self): """Returns True if there are valid credentials for the current user and required scopes.""" - return (self.credentials and not self.credentials.invalid - and self.credentials.has_scopes(self.scopes)) + return (self.credentials and not self.credentials.invalid and + self.credentials.has_scopes(self.scopes)) @property def credentials(self): diff --git a/oauth2client/contrib/flask_util.py b/oauth2client/contrib/flask_util.py index fc6dd3d..ad61963 100644 --- a/oauth2client/contrib/flask_util.py +++ b/oauth2client/contrib/flask_util.py @@ -446,8 +446,8 @@ class UserOAuth2(object): if not self.credentials: return False # Is the access token expired? If so, do we have an refresh token? - elif (self.credentials.access_token_expired - and not self.credentials.refresh_token): + elif (self.credentials.access_token_expired and + not self.credentials.refresh_token): return False else: return True diff --git a/oauth2client/service_account.py b/oauth2client/service_account.py index ed7c904..33fff4e 100644 --- a/oauth2client/service_account.py +++ b/oauth2client/service_account.py @@ -90,7 +90,7 @@ class ServiceAccountCredentials(AssertionCredentials): MAX_TOKEN_LIFETIME_SECS = 3600 """Max lifetime of the token (one hour, in seconds).""" - NON_SERIALIZED_MEMBERS = ( + NON_SERIALIZED_MEMBERS = ( frozenset(['_signer']) | AssertionCredentials.NON_SERIALIZED_MEMBERS) """Members that aren't serialized when object is converted to JSON.""" @@ -498,7 +498,7 @@ class ServiceAccountCredentials(AssertionCredentials): result._private_key_pkcs12 = self._private_key_pkcs12 result._private_key_password = self._private_key_password return result - + def create_with_claims(self, claims): """Create credentials that specify additional claims. @@ -548,11 +548,11 @@ class ServiceAccountCredentials(AssertionCredentials): def _datetime_to_secs(utc_time): - # TODO(issue 298): use time_delta.total_seconds() - # time_delta.total_seconds() not supported in Python 2.6 - epoch = datetime.datetime(1970, 1, 1) - time_delta = utc_time - epoch - return time_delta.days * 86400 + time_delta.seconds + # TODO(issue 298): use time_delta.total_seconds() + # time_delta.total_seconds() not supported in Python 2.6 + epoch = datetime.datetime(1970, 1, 1) + time_delta = utc_time - epoch + return time_delta.days * 86400 + time_delta.seconds class _JWTAccessCredentials(ServiceAccountCredentials): diff --git a/tests/contrib/test_django_util.py b/tests/contrib/test_django_util.py index 18eab30..3b01427 100644 --- a/tests/contrib/test_django_util.py +++ b/tests/contrib/test_django_util.py @@ -242,9 +242,8 @@ class Oauth2AuthorizeTest(TestWithSession): self.assertTrue(isinstance(response, http.HttpResponseRedirect)) def test_authorize_works_explicit_return_url(self): - request = self.factory.get('oauth2/oauth2authorize', data={ - 'return_url': '/return_endpoint' - }) + request = self.factory.get('oauth2/oauth2authorize', + data={'return_url': '/return_endpoint'}) request.session = self.session response = views.oauth2_authorize(request) self.assertTrue(isinstance(response, http.HttpResponseRedirect)) diff --git a/tests/contrib/test_gce.py b/tests/contrib/test_gce.py index 1974020..49d7599 100644 --- a/tests/contrib/test_gce.py +++ b/tests/contrib/test_gce.py @@ -36,6 +36,7 @@ SERVICE_ACCOUNT_INFO = { 'aliases': ['default'] } + class AppAssertionCredentialsTests(unittest2.TestCase): def test_constructor(self): diff --git a/tests/contrib/test_metadata.py b/tests/contrib/test_metadata.py index 8c6b973..9bf96c9 100644 --- a/tests/contrib/test_metadata.py +++ b/tests/contrib/test_metadata.py @@ -81,7 +81,7 @@ class TestMetadata(unittest2.TestCase): self.assertEqual( expiry, datetime.datetime.min + datetime.timedelta(seconds=100)) http_request.assert_called_once_with( - EXPECTED_URL+'/token', + EXPECTED_URL + '/token', **EXPECTED_KWARGS ) now.assert_called_once_with() @@ -92,6 +92,6 @@ class TestMetadata(unittest2.TestCase): info = _metadata.get_service_account_info(http_request) self.assertEqual(info, DATA) http_request.assert_called_once_with( - EXPECTED_URL+'/?recursive=True', + EXPECTED_URL + '/?recursive=True', **EXPECTED_KWARGS ) diff --git a/tests/test__pure_python_crypt.py b/tests/test__pure_python_crypt.py index 754b29d..cbfe728 100644 --- a/tests/test__pure_python_crypt.py +++ b/tests/test__pure_python_crypt.py @@ -33,7 +33,7 @@ class TestRsaVerifier(unittest2.TestCase): PUBLIC_KEY_FILENAME = os.path.join(os.path.dirname(__file__), 'data', 'privatekey.pub') PUBLIC_CERT_FILENAME = os.path.join(os.path.dirname(__file__), - 'data', 'public_cert.pem') + 'data', 'public_cert.pem') PRIVATE_KEY_FILENAME = os.path.join(os.path.dirname(__file__), 'data', 'privatekey.pem') diff --git a/tests/test_client.py b/tests/test_client.py index 59a80e8..3a2a20a 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -457,7 +457,7 @@ class GoogleCredentialsTests(unittest2.TestCase): client._METADATA_FLAVOR_HEADER) else: self.assertEqual( - http_client_module.HTTPConnection.mock_calls, []) + http_client_module.HTTPConnection.mock_calls, []) self.assertEqual(connection.getresponse.mock_calls, []) # Remaining calls are not "getresponse" self.assertEqual(connection.method_calls, []) diff --git a/tests/test_clientsecrets.py b/tests/test_clientsecrets.py index 5065e31..081a2b1 100644 --- a/tests/test_clientsecrets.py +++ b/tests/test_clientsecrets.py @@ -121,11 +121,11 @@ class Test__validate_clientsecrets(unittest2.TestCase): def test_success_type_web(self): client_info = { - 'client_id': 'eye-dee', - 'client_secret': 'seekrit', - 'redirect_uris': None, - 'auth_uri': None, - 'token_uri': None, + 'client_id': 'eye-dee', + 'client_secret': 'seekrit', + 'redirect_uris': None, + 'auth_uri': None, + 'token_uri': None, } clientsecrets_dict = { clientsecrets.TYPE_WEB: client_info, @@ -135,11 +135,11 @@ class Test__validate_clientsecrets(unittest2.TestCase): def test_success_type_installed(self): client_info = { - 'client_id': 'eye-dee', - 'client_secret': 'seekrit', - 'redirect_uris': None, - 'auth_uri': None, - 'token_uri': None, + 'client_id': 'eye-dee', + 'client_secret': 'seekrit', + 'redirect_uris': None, + 'auth_uri': None, + 'token_uri': None, } clientsecrets_dict = { clientsecrets.TYPE_INSTALLED: client_info, diff --git a/tests/test_crypt.py b/tests/test_crypt.py index 55e60d9..278c5e6 100644 --- a/tests/test_crypt.py +++ b/tests/test_crypt.py @@ -48,7 +48,7 @@ class Test_pkcs12_key_as_pem(unittest2.TestCase): 'some_account@example.com', filename, scopes='read+write') - credentials._kwargs['sub'] ='joe@example.org' + credentials._kwargs['sub'] = 'joe@example.org' return credentials def _succeeds_helper(self, password=None): @@ -171,6 +171,7 @@ class Test__check_audience(unittest2.TestCase): with self.assertRaises(crypt.AppIdentityError): crypt._check_audience(payload_dict, audience2) + class Test__verify_time_range(unittest2.TestCase): def _exception_helper(self, payload_dict): diff --git a/tests/test_service_account.py b/tests/test_service_account.py index 9c7f444..d9e08f9 100644 --- a/tests/test_service_account.py +++ b/tests/test_service_account.py @@ -114,7 +114,7 @@ class ServiceAccountCredentialsTests(unittest2.TestCase): return_value=object()) def test_from_json_keyfile_name_factory(self, signer_factory): client_id = 'id123' - client_email= 'foo@bar.com' + client_email = 'foo@bar.com' private_key_id = 'pkid456' private_key = 's3kr3tz' payload = { @@ -435,13 +435,13 @@ class JWTAccessCredentialsTests(unittest2.TestCase): utcnow.return_value = T1_DATE time.return_value = T1 - token_info = self.jwt.get_access_token(additional_claims= - {'aud': 'https://test2.url.com', - 'sub': 'dummy2@google.com' - }) + token_info = self.jwt.get_access_token( + additional_claims={'aud': 'https://test2.url.com', + 'sub': 'dummy2@google.com' + }) payload = crypt.verify_signed_jwt_with_certs( token_info.access_token, - {'key' : datafile('public_cert.pem')}, + {'key': datafile('public_cert.pem')}, audience='https://test2.url.com') expires_in = token_info.expires_in self.assertEqual(payload['iss'], self.service_account_email) @@ -449,13 +449,13 @@ class JWTAccessCredentialsTests(unittest2.TestCase): self.assertEqual(payload['iat'], T1) self.assertEqual(payload['exp'], T1_EXPIRY) self.assertEqual(expires_in, T1_EXPIRY - T1) - + def test_revoke(self): self.jwt.revoke(None) - + def test_create_scoped_required(self): self.assertTrue(self.jwt.create_scoped_required()) - + def test_create_scoped(self): self.jwt._private_key_pkcs12 = '' self.jwt._private_key_password = '' @@ -464,7 +464,7 @@ class JWTAccessCredentialsTests(unittest2.TestCase): self.assertNotEqual(self.jwt, new_credentials) self.assertIsInstance(new_credentials, ServiceAccountCredentials) self.assertEqual('dummy_scope', new_credentials._scopes) - + @mock.patch('oauth2client.service_account._UTCNOW') @mock.patch('oauth2client.client._UTCNOW') @mock.patch('time.time') @@ -479,7 +479,7 @@ class JWTAccessCredentialsTests(unittest2.TestCase): bearer, token = headers[b'Authorization'].split() payload = crypt.verify_signed_jwt_with_certs( token, - {'key': datafile('public_cert.pem')}, + {'key': datafile('public_cert.pem')}, audience=self.url) self.assertEqual(payload['iss'], self.service_account_email) self.assertEqual(payload['sub'], self.service_account_email) diff --git a/tests/test_tools.py b/tests/test_tools.py index bd19227..ac0fc70 100644 --- a/tests/test_tools.py +++ b/tests/test_tools.py @@ -68,11 +68,10 @@ class TestRunFlow(unittest2.TestCase): self.server_flags = argparse.Namespace( noauth_local_webserver=False, logging_level='INFO', - auth_host_port=[8080,], + auth_host_port=[8080, ], auth_host_name='localhost') - @mock.patch.object(sys, 'argv', - ['ignored', '--noauth_local_webserver']) + @mock.patch.object(sys, 'argv', ['ignored', '--noauth_local_webserver']) @mock.patch('oauth2client.tools.logging') @mock.patch('oauth2client.tools.input') def test_run_flow_no_webserver(self, input_mock, logging_mock): diff --git a/tests/test_util.py b/tests/test_util.py index 9f1d7ed..533460f 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -9,7 +9,6 @@ from oauth2client import util __author__ = 'jcgregorio@google.com (Joe Gregorio)' - class PositionalTests(unittest2.TestCase): def test_usage(self): @@ -45,7 +44,6 @@ class PositionalTests(unittest2.TestCase): with self.assertRaises(TypeError): fn3(1, 2) - @mock.patch('oauth2client.util.logger') def test_enforcement_warning(self, mock_logger): util.positional_parameters_enforcement = util.POSITIONAL_WARNING @@ -57,7 +55,6 @@ class PositionalTests(unittest2.TestCase): self.assertTrue(fn(1, 2)) self.assertTrue(mock_logger.warning.called) - @mock.patch('oauth2client.util.logger') def test_enforcement_ignore(self, mock_logger): util.positional_parameters_enforcement = util.POSITIONAL_IGNORE @@ -104,7 +101,6 @@ class StringToScopeTests(unittest2.TestCase): self.assertEqual(expected, util.string_to_scopes(case)) - class AddQueryParameterTests(unittest2.TestCase): def test__add_query_parameter(self): From 9f9dbc22f1a7dac3cf7dcf8469525a55134363d8 Mon Sep 17 00:00:00 2001 From: Pat Ferate Date: Fri, 8 Jul 2016 08:49:04 -0700 Subject: [PATCH 4/8] Clean up command line messages Move messages split up by multiple print calls to multi-line strings. --- oauth2client/tools.py | 51 ++++++++++++++++++++++++------------------- 1 file changed, 29 insertions(+), 22 deletions(-) diff --git a/oauth2client/tools.py b/oauth2client/tools.py index 9e3e85d..f24b23f 100644 --- a/oauth2client/tools.py +++ b/oauth2client/tools.py @@ -48,6 +48,32 @@ with information from the APIs Console . """ +_FAILED_START_MESSAGE = """ +Failed to start a local webserver listening on either port 8080 +or port 8090. Please check your firewall settings and locally +running programs that may be blocking or using those ports. + +Falling back to --noauth_local_webserver and continuing with +authorization. +""" + +_BROWSER_OPENED_MESSAGE = """ +Your browser has been opened to visit: + + %s + +If your browser is on a different machine then exit and re-run this +application with the command-line parameter + + --noauth_local_webserver +""" + +_GO_TO_LINK_MESSAGE = """ +Go to the following link in your browser: + + %s +""" + def _CreateArgumentParser(): try: @@ -182,14 +208,7 @@ def run_flow(flow, storage, flags=None, http=None): break flags.noauth_local_webserver = not success if not success: - print('Failed to start a local webserver listening ' - 'on either port 8080') - print('or port 8090. Please check your firewall settings and locally') - print('running programs that may be blocking or using those ports.') - print() - print('Falling back to --noauth_local_webserver and continuing with') - print('authorization.') - print() + print(_FAILED_START_MESSAGE) if not flags.noauth_local_webserver: oauth_callback = 'http://%s:%s/' % (flags.auth_host_name, port_number) @@ -201,21 +220,9 @@ def run_flow(flow, storage, flags=None, http=None): if not flags.noauth_local_webserver: import webbrowser webbrowser.open(authorize_url, new=1, autoraise=True) - print('Your browser has been opened to visit:') - print() - print(' ' + authorize_url) - print() - print('If your browser is on a different machine then ' - 'exit and re-run this') - print('application with the command-line parameter ') - print() - print(' --noauth_local_webserver') - print() + print(_BROWSER_OPENED_MESSAGE % authorize_url) else: - print('Go to the following link in your browser:') - print() - print(' ' + authorize_url) - print() + print(_GO_TO_LINK_MESSAGE % authorize_url) code = None if not flags.noauth_local_webserver: From 5ef8bb0950b62ba18b9c05344cdf32aca5671e2f Mon Sep 17 00:00:00 2001 From: Pat Ferate Date: Fri, 8 Jul 2016 09:10:16 -0700 Subject: [PATCH 5/8] Resolve lines over 80 characters --- oauth2client/client.py | 10 ++++++---- oauth2client/contrib/django_util/__init__.py | 18 +++++++++--------- oauth2client/contrib/django_util/views.py | 3 ++- oauth2client/contrib/gce.py | 3 ++- oauth2client/service_account.py | 13 ++++++++----- tests/contrib/test_gce.py | 12 ++++++++---- tests/test_client.py | 3 ++- tests/test_service_account.py | 6 ++++-- 8 files changed, 41 insertions(+), 27 deletions(-) diff --git a/oauth2client/client.py b/oauth2client/client.py index a0e4473..97ac3e6 100644 --- a/oauth2client/client.py +++ b/oauth2client/client.py @@ -257,8 +257,8 @@ class Credentials(object): strip: array, An array of names of members to exclude from the JSON. to_serialize: dict, (Optional) The properties for this object - that will be serialized. This allows callers to modify - before serializing. + that will be serialized. This allows callers to + modify before serializing. Returns: string, a JSON representation of this instance, suitable to pass to @@ -357,7 +357,8 @@ class Storage(object): Args: lock: An optional threading.Lock-like object. Must implement at - least acquire() and release(). Does not need to be re-entrant. + least acquire() and release(). Does not need to be + re-entrant. """ self._lock = lock @@ -2209,7 +2210,8 @@ def flow_from_clientsecrets(filename, scope, redirect_uri=None, except clientsecrets.InvalidClientSecretsError as e: if message is not None: if e.args: - message = 'The client secrets were invalid: \n{0}\n{1}'.format(e, message) + message = ('The client secrets were invalid: ' + '\n{0}\n{1}'.format(e, message)) sys.exit(message) else: raise diff --git a/oauth2client/contrib/django_util/__init__.py b/oauth2client/contrib/django_util/__init__.py index 19ac8b4..4ede05b 100644 --- a/oauth2client/contrib/django_util/__init__.py +++ b/oauth2client/contrib/django_util/__init__.py @@ -15,10 +15,10 @@ """Utilities for the Django web framework Provides Django views and helpers the make using the OAuth2 web server -flow easier. It includes an ``oauth_required`` decorator to automatically ensure -that user credentials are available, and an ``oauth_enabled`` decorator to check -if the user has authorized, and helper shortcuts to create the authorization -URL otherwise. +flow easier. It includes an ``oauth_required`` decorator to automatically +ensure that user credentials are available, and an ``oauth_enabled`` decorator +to check if the user has authorized, and helper shortcuts to create the +authorization URL otherwise. Only Django versions 1.8+ are supported. @@ -89,8 +89,8 @@ Add the oauth2 routes to your application's urls.py urlpatterns. urlpatterns += [url(r'^oauth2/', include(oauth2_urls))] To require OAuth2 credentials for a view, use the `oauth2_required` decorator. -This creates a credentials object with an id_token, and allows you to create an -`http` object to build service clients with. These are all attached to the +This creates a credentials object with an id_token, and allows you to create +an `http` object to build service clients with. These are all attached to the request.oauth .. code-block:: python @@ -202,9 +202,9 @@ def _get_oauth2_client_id_and_secret(settings_instance): return client_id, client_secret else: raise exceptions.ImproperlyConfigured( - "Must specify either GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, or " - " both GOOGLE_OAUTH2_CLIENT_ID and GOOGLE_OAUTH2_CLIENT_SECRET " - "in settings.py") + "Must specify either GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, or " + "both GOOGLE_OAUTH2_CLIENT_ID and " + "GOOGLE_OAUTH2_CLIENT_SECRET in settings.py") class OAuth2Settings(object): diff --git a/oauth2client/contrib/django_util/views.py b/oauth2client/contrib/django_util/views.py index 0d5561c..523e479 100644 --- a/oauth2client/contrib/django_util/views.py +++ b/oauth2client/contrib/django_util/views.py @@ -87,7 +87,8 @@ def oauth2_callback(request): try: server_csrf = request.session[_CSRF_KEY] except KeyError: - return http.HttpResponseBadRequest("No existing session for this flow.") + return http.HttpResponseBadRequest( + "No existing session for this flow.") try: state = json.loads(encoded_state) diff --git a/oauth2client/contrib/gce.py b/oauth2client/contrib/gce.py index b495e44..cccf495 100644 --- a/oauth2client/contrib/gce.py +++ b/oauth2client/contrib/gce.py @@ -112,7 +112,8 @@ class AppAssertionCredentials(AssertionCredentials): """ if self.invalid: info = _metadata.get_service_account_info( - http_request, service_account=self.service_account_email or 'default') + http_request, + service_account=self.service_account_email or 'default') self.invalid = False self.service_account_email = info['email'] self.scopes = info['scopes'] diff --git a/oauth2client/service_account.py b/oauth2client/service_account.py index 33fff4e..8cc3505 100644 --- a/oauth2client/service_account.py +++ b/oauth2client/service_account.py @@ -134,8 +134,8 @@ class ServiceAccountCredentials(AssertionCredentials): strip: array, An array of names of members to exclude from the JSON. to_serialize: dict, (Optional) The properties for this object - that will be serialized. This allows callers to modify - before serializing. + that will be serialized. This allows callers to + modify before serializing. Returns: string, a JSON representation of this instance, suitable to pass to @@ -507,7 +507,8 @@ class ServiceAccountCredentials(AssertionCredentials): Returns: ServiceAccountCredentials, a copy of the current service account - credentials with updated claims to use when obtaining access tokens. + credentials with updated claims to use when obtaining access + tokens. """ new_kwargs = dict(self._kwargs) new_kwargs.update(claims) @@ -603,7 +604,8 @@ class _JWTAccessCredentials(ServiceAccountCredentials): h = credentials.authorize(h) """ request_orig = http.request - request_auth = super(_JWTAccessCredentials, self).authorize(http).request + request_auth = super(_JWTAccessCredentials, + self).authorize(http).request # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, @@ -691,7 +693,8 @@ class _JWTAccessCredentials(ServiceAccountCredentials): def _create_token(self, additional_claims=None): now = _UTCNOW() - expiry = now + datetime.timedelta(seconds=self._MAX_TOKEN_LIFETIME_SECS) + lifetime = datetime.timedelta(seconds=self._MAX_TOKEN_LIFETIME_SECS) + expiry = now + lifetime payload = { 'iat': _datetime_to_secs(now), 'exp': _datetime_to_secs(expiry), diff --git a/tests/contrib/test_gce.py b/tests/contrib/test_gce.py index 49d7599..bacecca 100644 --- a/tests/contrib/test_gce.py +++ b/tests/contrib/test_gce.py @@ -79,11 +79,13 @@ class AppAssertionCredentialsTests(unittest2.TestCase): credentials.get_access_token(http=http_mock) self.assertEqual(credentials.access_token, 'A') self.assertTrue(credentials.access_token_expired) - get_token.assert_called_with(http_request, service_account='a@example.com') + get_token.assert_called_with(http_request, + service_account='a@example.com') credentials.get_access_token(http=http_mock) self.assertEqual(credentials.access_token, 'B') self.assertFalse(credentials.access_token_expired) - get_token.assert_called_with(http_request, service_account='a@example.com') + get_token.assert_called_with(http_request, + service_account='a@example.com') get_info.assert_not_called() def test_refresh_token_failed_fetch(self): @@ -125,7 +127,8 @@ class AppAssertionCredentialsTests(unittest2.TestCase): self.assertFalse(credentials.invalid) credentials.retrieve_scopes(http_mock) # Assert scopes weren't refetched - metadata.assert_called_once_with(http_request, service_account='default') + metadata.assert_called_once_with(http_request, + service_account='default') @mock.patch('oauth2client.contrib._metadata.get_service_account_info', side_effect=httplib2.HttpLib2Error('No Such Email')) @@ -136,7 +139,8 @@ class AppAssertionCredentialsTests(unittest2.TestCase): with self.assertRaises(httplib2.HttpLib2Error): credentials.retrieve_scopes(http_mock) - metadata.assert_called_once_with(http_request, service_account='b@example.com') + metadata.assert_called_once_with(http_request, + service_account='b@example.com') def test_save_to_well_known_file(self): import os diff --git a/tests/test_client.py b/tests/test_client.py index 3a2a20a..a8feb19 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -2149,7 +2149,8 @@ class FlowFromCachedClientsecrets(unittest2.TestCase): filename = object() cache = object() message = 'hi mom' - expected = 'The client secrets were invalid: \n{0}\n{1}'.format('foobar', 'hi mom') + expected = ('The client secrets were invalid: ' + '\n{0}\n{1}'.format('foobar', 'hi mom')) flow_from_clientsecrets(filename, None, cache=cache, message=message) sys_exit.assert_called_once_with(expected) diff --git a/tests/test_service_account.py b/tests/test_service_account.py index d9e08f9..1548632 100644 --- a/tests/test_service_account.py +++ b/tests/test_service_account.py @@ -179,12 +179,14 @@ class ServiceAccountCredentialsTests(unittest2.TestCase): for creds in (creds_from_filename, creds_from_file_contents): self.assertIsInstance(creds, ServiceAccountCredentials) self.assertIsNone(creds.client_id) - self.assertEqual(creds._service_account_email, service_account_email) + self.assertEqual(creds._service_account_email, + service_account_email) self.assertIsNone(creds._private_key_id) self.assertIsNone(creds._private_key_pkcs8_pem) self.assertEqual(creds._private_key_pkcs12, key_contents) if private_key_password is not None: - self.assertEqual(creds._private_key_password, private_key_password) + self.assertEqual(creds._private_key_password, + private_key_password) self.assertEqual(creds._scopes, ' '.join(scopes)) self.assertEqual(creds.token_uri, token_uri) self.assertEqual(creds.revoke_uri, revoke_uri) From 8eb3aa2f955dd4ad31aeb3cb1e43c783aaebb85a Mon Sep 17 00:00:00 2001 From: Pat Ferate Date: Fri, 8 Jul 2016 13:30:17 -0700 Subject: [PATCH 6/8] Add new tox env: flake8 --- .travis.yml | 1 + tox.ini | 17 +++++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/.travis.yml b/.travis.yml index c66632c..4f1272f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -18,6 +18,7 @@ env: - TOX_ENV=system-tests - TOX_ENV=system-tests3 - TOX_ENV=gae + - TOX_ENV=flake8 global: - GAE_PYTHONPATH=${HOME}/.cache/google_appengine cache: diff --git a/tox.ini b/tox.ini index eba723c..ea58432 100644 --- a/tox.ini +++ b/tox.ini @@ -154,3 +154,20 @@ commands = deps = pycrypto>=2.6 passenv = {[testenv:system-tests]passenv} + +[testenv:flake8] +commands = flake8 {posargs} +deps = flake8-putty + +[flake8] +exclude = .tox,.git,./*.egg,build, +putty-ignore = + # E402 module level import not at top of file + # These files have needed configurations defined before import + docs/conf.py : E402 + tests/contrib/test_appengine.py : E402 + tests/contrib/test_django_orm.py : E402 + # E501 line too long + # Ignore lines over 80 chars that include "http:" or "https:" + /http:/ : E501 + /https:/ : E501 From 6b6c56d3ee60c749f74f746300934e3ae18c56c1 Mon Sep 17 00:00:00 2001 From: Pat Ferate Date: Fri, 8 Jul 2016 13:31:15 -0700 Subject: [PATCH 7/8] More general PEP8 cleanup --- docs/conf.py | 23 +++++++++---------- oauth2client/contrib/django_util/__init__.py | 10 ++++---- .../contrib/django_util/decorators.py | 2 +- oauth2client/service_account.py | 4 ++-- .../call_compute_service_from_gae.py | 2 +- scripts/run_system_tests.py | 4 ++-- setup.py | 7 +++--- tests/contrib/test_flask_util.py | 3 ++- tests/test_jwt.py | 5 ++-- 9 files changed, 30 insertions(+), 30 deletions(-) diff --git a/docs/conf.py b/docs/conf.py index f84911c..4afcfe0 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -10,9 +10,17 @@ import sys import mock -# See -# (https://read-the-docs.readthedocs.io/en/latest/faq.html#\ -# i-get-import-errors-on-libraries-that-depend-on-c-modules) +# In order to load django before 1.7, we need to create a faux +# settings module and load it. This assumes django has been installed +# (but it must be for the docs to build), so if it has not already +# been installed run `pip install -r docs/requirements.txt`. +os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.contrib.test_django_settings' +import django +if django.VERSION[1] < 7: + sys.path.insert(0, '.') + +# See https://read-the-docs.readthedocs.io/en/latest/faq.html#i-get-import-errors-on-libraries-that-depend-on-c-modules + class Mock(mock.Mock): @@ -61,15 +69,6 @@ release = distro.version exclude_patterns = ['_build'] -# In order to load django before 1.7, we need to create a faux -# settings module and load it. This assumes django has been installed -# (but it must be for the docs to build), so if it has not already -# been installed run `pip install -r docs/requirements.txt`. -os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.contrib.test_django_settings' -import django -if django.VERSION[1] < 7: - sys.path.insert(0, '.') - # -- Options for HTML output ---------------------------------------------- # We fake our more expensive imports when building the docs. diff --git a/oauth2client/contrib/django_util/__init__.py b/oauth2client/contrib/django_util/__init__.py index 4ede05b..a9dfb39 100644 --- a/oauth2client/contrib/django_util/__init__.py +++ b/oauth2client/contrib/django_util/__init__.py @@ -124,8 +124,9 @@ To make OAuth2 optional and provide an authorization link in your own views. return HttpResponse("User email: %s" % request.oauth.credentials.id_token['email']) else: - return HttpResponse('Here is an OAuth Authorize link: - Authorize' % request.oauth.get_authorize_redirect()) + return HttpResponse( + 'Here is an OAuth Authorize link: Authorize' + % request.oauth.get_authorize_redirect()) If a view needs a scope not included in the default scopes specified in the settings, you can use [incremental auth](https://developers.google.com/identity/sign-in/web/incremental-auth) @@ -144,8 +145,9 @@ and specify additional scopes in the decorator arguments. events = service.files().list().execute()['items'] return HttpResponse(str(events)) else: - return HttpResponse('Here is an OAuth Authorize link: - Authorize' % request.oauth.get_authorize_redirect()) + return HttpResponse( + 'Here is an OAuth Authorize link: Authorize' + % request.oauth.get_authorize_redirect()) To provide a callback on authorization being completed, use the diff --git a/oauth2client/contrib/django_util/decorators.py b/oauth2client/contrib/django_util/decorators.py index 0e0a4b2..214f867 100644 --- a/oauth2client/contrib/django_util/decorators.py +++ b/oauth2client/contrib/django_util/decorators.py @@ -36,7 +36,7 @@ def oauth_required(decorated_function=None, scopes=None, **decorator_kwargs): developerKey=API_KEY) events = service.events().list( calendarId='primary').execute()['items'] - return HttpResponse("email: %s , calendar: %s" % (email, str(events))) + return HttpResponse("email: %s, calendar: %s" % (email, str(events))) :param decorated_function: View function to decorate, must have the Django request object as the first argument diff --git a/oauth2client/service_account.py b/oauth2client/service_account.py index 8cc3505..57b4856 100644 --- a/oauth2client/service_account.py +++ b/oauth2client/service_account.py @@ -604,8 +604,8 @@ class _JWTAccessCredentials(ServiceAccountCredentials): h = credentials.authorize(h) """ request_orig = http.request - request_auth = super(_JWTAccessCredentials, - self).authorize(http).request + request_auth = super( + _JWTAccessCredentials, self).authorize(http).request # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, diff --git a/samples/googleappengine/call_compute_service_from_gae.py b/samples/googleappengine/call_compute_service_from_gae.py index b1b1000..5c7fa33 100644 --- a/samples/googleappengine/call_compute_service_from_gae.py +++ b/samples/googleappengine/call_compute_service_from_gae.py @@ -23,4 +23,4 @@ class MainPage(webapp2.RequestHandler): self.response.write(get_instances()) -app = webapp2.WSGIApplication([('/', MainPage),], debug=True) +app = webapp2.WSGIApplication([('/', MainPage), ], debug=True) diff --git a/scripts/run_system_tests.py b/scripts/run_system_tests.py index f955e3b..74d27d9 100644 --- a/scripts/run_system_tests.py +++ b/scripts/run_system_tests.py @@ -36,8 +36,8 @@ USER_INFO = 'https://www.googleapis.com/oauth2/v2/userinfo' def _require_environ(): if (JSON_KEY_PATH is None or P12_KEY_PATH is None or - P12_KEY_EMAIL is None or USER_KEY_PATH is None or - USER_KEY_EMAIL is None): + P12_KEY_EMAIL is None or USER_KEY_PATH is None or + USER_KEY_EMAIL is None): raise EnvironmentError('Expected environment variables to be set:', 'OAUTH2CLIENT_TEST_JSON_KEY_PATH', 'OAUTH2CLIENT_TEST_P12_KEY_PATH', diff --git a/setup.py b/setup.py index ef6e2e1..36894a8 100644 --- a/setup.py +++ b/setup.py @@ -20,6 +20,9 @@ are not already installed. from __future__ import print_function import sys +from setuptools import find_packages +from setuptools import setup +import oauth2client if sys.version_info < (2, 6): print('oauth2client requires python2 version >= 2.6.', file=sys.stderr) @@ -28,9 +31,6 @@ if (3, 1) <= sys.version_info < (3, 3): print('oauth2client requires python3 version >= 3.3.', file=sys.stderr) sys.exit(1) -from setuptools import find_packages -from setuptools import setup - install_requires = [ 'httplib2>=0.9.1', 'pyasn1>=0.1.7', @@ -41,7 +41,6 @@ install_requires = [ long_desc = """The oauth2client is a client library for OAuth 2.0.""" -import oauth2client version = oauth2client.__version__ setup( diff --git a/tests/contrib/test_flask_util.py b/tests/contrib/test_flask_util.py index f4fe0e9..f08d229 100644 --- a/tests/contrib/test_flask_util.py +++ b/tests/contrib/test_flask_util.py @@ -474,7 +474,8 @@ class FlaskOAuth2Tests(unittest2.TestCase): # Starting the authorization flow should include the # include_granted_scopes parameter as well as the scopes. response = client.get(response.headers['Location'][17:]) - q = urlparse.parse_qs(response.headers['Location'].split('?', 1)[1]) + q = urlparse.parse_qs( + response.headers['Location'].split('?', 1)[1]) self.assertIn('include_granted_scopes', q) self.assertEqual( set(q['scope'][0].split(' ')), diff --git a/tests/test_jwt.py b/tests/test_jwt.py index f567f5d..00c8ef7 100644 --- a/tests/test_jwt.py +++ b/tests/test_jwt.py @@ -147,15 +147,14 @@ class CryptTests(unittest2.TestCase): def test_verify_id_token_with_certs_uri_fails(self): jwt = self._create_signed_jwt() + test_email = 'some_audience_address@testing.gserviceaccount.com' http = HttpMockSequence([ ({'status': '404'}, datafile('certs.json')), ]) with self.assertRaises(VerifyJwtTokenError): - verify_id_token(jwt, - 'some_audience_address@testing.gserviceaccount.com', - http=http) + verify_id_token(jwt, test_email, http=http) def test_verify_id_token_bad_tokens(self): private_key = datafile('privatekey.' + self.format_) From 09e9420ab7b0d6e0f21c25f2377ecee7d027fc02 Mon Sep 17 00:00:00 2001 From: Pat Ferate Date: Sun, 10 Jul 2016 17:24:18 -0700 Subject: [PATCH 8/8] Check for Google import order style in flake8 --- docs/conf.py | 4 +- oauth2client/_helpers.py | 1 + oauth2client/_pycrypto_crypt.py | 2 +- oauth2client/client.py | 11 ++-- oauth2client/clientsecrets.py | 2 +- oauth2client/contrib/_fcntl_opener.py | 3 +- oauth2client/contrib/_metadata.py | 4 +- oauth2client/contrib/appengine.py | 7 +-- oauth2client/contrib/devshell.py | 2 +- oauth2client/contrib/django_orm.py | 3 +- oauth2client/contrib/django_util/__init__.py | 3 +- .../contrib/django_util/decorators.py | 3 +- oauth2client/contrib/django_util/site.py | 1 + oauth2client/contrib/django_util/views.py | 4 +- oauth2client/contrib/flask_util.py | 10 +-- oauth2client/contrib/multistore_file.py | 3 +- oauth2client/contrib/sqlalchemy.py | 3 +- oauth2client/contrib/xsrfutil.py | 2 +- oauth2client/service_account.py | 9 +-- oauth2client/tools.py | 2 +- samples/call_compute_service.py | 1 + .../call_compute_service_from_gae.py | 3 +- samples/oauth2_for_devices.py | 3 +- scripts/run_gce_system_tests.py | 2 +- scripts/run_system_tests.py | 1 + setup.py | 2 + tests/contrib/test_appengine.py | 40 ++++++------ tests/contrib/test_devshell.py | 6 +- tests/contrib/test_django_orm.py | 8 +-- tests/contrib/test_django_util.py | 15 ++--- tests/contrib/test_flask_util.py | 10 +-- tests/contrib/test_gce.py | 6 +- tests/contrib/test_keyring_storage.py | 4 +- tests/contrib/test_metadata.py | 6 +- tests/contrib/test_multistore_file.py | 2 +- tests/contrib/test_sqlalchemy.py | 7 ++- tests/contrib/test_xsrfutil.py | 2 +- tests/test__pure_python_crypt.py | 2 +- tests/test__pycrypto_crypt.py | 1 + tests/test_client.py | 62 +++++++++---------- tests/test_clientsecrets.py | 5 +- tests/test_crypt.py | 4 +- tests/test_file.py | 7 ++- tests/test_jwt.py | 12 ++-- tests/test_service_account.py | 9 ++- tests/test_tools.py | 2 +- tox.ini | 10 ++- 47 files changed, 166 insertions(+), 145 deletions(-) diff --git a/docs/conf.py b/docs/conf.py index 4afcfe0..fcbf2fb 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -5,10 +5,8 @@ # import os -from pkg_resources import get_distribution import sys -import mock # In order to load django before 1.7, we need to create a faux # settings module and load it. This assumes django has been installed @@ -16,6 +14,8 @@ import mock # been installed run `pip install -r docs/requirements.txt`. os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.contrib.test_django_settings' import django +import mock +from pkg_resources import get_distribution if django.VERSION[1] < 7: sys.path.insert(0, '.') diff --git a/oauth2client/_helpers.py b/oauth2client/_helpers.py index 39bfeb6..2b86d01 100644 --- a/oauth2client/_helpers.py +++ b/oauth2client/_helpers.py @@ -15,6 +15,7 @@ import base64 import json + import six diff --git a/oauth2client/_pycrypto_crypt.py b/oauth2client/_pycrypto_crypt.py index 5ee7046..0b31ba3 100644 --- a/oauth2client/_pycrypto_crypt.py +++ b/oauth2client/_pycrypto_crypt.py @@ -13,8 +13,8 @@ # limitations under the License. """pyCrypto Crypto-related routines for oauth2client.""" -from Crypto.PublicKey import RSA from Crypto.Hash import SHA256 +from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 from Crypto.Util.asn1 import DerSequence diff --git a/oauth2client/client.py b/oauth2client/client.py index 97ac3e6..fafa8c0 100644 --- a/oauth2client/client.py +++ b/oauth2client/client.py @@ -23,25 +23,26 @@ import datetime import json import logging import os +import shutil import socket import sys import tempfile -import shutil + +import httplib2 import six from six.moves import http_client from six.moves import urllib -import httplib2 +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_URI from oauth2client import GOOGLE_TOKEN_INFO_URI +from oauth2client import GOOGLE_TOKEN_URI +from oauth2client import util from oauth2client._helpers import _from_bytes from oauth2client._helpers import _to_bytes from oauth2client._helpers import _urlsafe_b64decode -from oauth2client import clientsecrets -from oauth2client import util __author__ = 'jcgregorio@google.com (Joe Gregorio)' diff --git a/oauth2client/clientsecrets.py b/oauth2client/clientsecrets.py index 4a47d0d..2c69d7e 100644 --- a/oauth2client/clientsecrets.py +++ b/oauth2client/clientsecrets.py @@ -19,8 +19,8 @@ an OAuth 2.0 protected service. """ import json -import six +import six __author__ = 'jcgregorio@google.com (Joe Gregorio)' diff --git a/oauth2client/contrib/_fcntl_opener.py b/oauth2client/contrib/_fcntl_opener.py index 4e758b9..9edfec2 100644 --- a/oauth2client/contrib/_fcntl_opener.py +++ b/oauth2client/contrib/_fcntl_opener.py @@ -13,9 +13,8 @@ # limitations under the License. import errno -import time - import fcntl +import time from oauth2client.contrib.locked_file import _Opener from oauth2client.contrib.locked_file import AlreadyLockedException diff --git a/oauth2client/contrib/_metadata.py b/oauth2client/contrib/_metadata.py index 2995f65..07ca619 100644 --- a/oauth2client/contrib/_metadata.py +++ b/oauth2client/contrib/_metadata.py @@ -18,15 +18,15 @@ See https://cloud.google.com/compute/docs/metadata """ import datetime -import httplib2 import json +import httplib2 from six.moves import http_client from six.moves.urllib import parse as urlparse +from oauth2client import util from oauth2client._helpers import _from_bytes from oauth2client.client import _UTCNOW -from oauth2client import util METADATA_ROOT = 'http://metadata.google.internal/computeMetadata/v1/' diff --git a/oauth2client/contrib/appengine.py b/oauth2client/contrib/appengine.py index 84c3a39..746312a 100644 --- a/oauth2client/contrib/appengine.py +++ b/oauth2client/contrib/appengine.py @@ -24,19 +24,18 @@ import os import pickle import threading -import httplib2 -import webapp2 as webapp - from google.appengine.api import app_identity from google.appengine.api import memcache from google.appengine.api import users from google.appengine.ext import db from google.appengine.ext.webapp.util import login_required +import httplib2 +import webapp2 as webapp +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 clientsecrets from oauth2client import util from oauth2client.client import AccessTokenRefreshError from oauth2client.client import AssertionCredentials diff --git a/oauth2client/contrib/devshell.py b/oauth2client/contrib/devshell.py index 662cb70..b489c10 100644 --- a/oauth2client/contrib/devshell.py +++ b/oauth2client/contrib/devshell.py @@ -19,8 +19,8 @@ import json import os import socket -from oauth2client._helpers import _to_bytes 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). diff --git a/oauth2client/contrib/django_orm.py b/oauth2client/contrib/django_orm.py index dd83b8f..205daac 100644 --- a/oauth2client/contrib/django_orm.py +++ b/oauth2client/contrib/django_orm.py @@ -21,12 +21,13 @@ the Django datastore. Only Django versions 1.8+ are supported. """ -import oauth2client import base64 import pickle from django.db import models from django.utils.encoding import smart_bytes, smart_text + +import oauth2client from oauth2client.client import Storage as BaseStorage diff --git a/oauth2client/contrib/django_util/__init__.py b/oauth2client/contrib/django_util/__init__.py index a9dfb39..4718da2 100644 --- a/oauth2client/contrib/django_util/__init__.py +++ b/oauth2client/contrib/django_util/__init__.py @@ -170,9 +170,10 @@ import django.conf from django.core import exceptions from django.core import urlresolvers import httplib2 +from six.moves.urllib import parse + from oauth2client import clientsecrets from oauth2client.contrib.django_util import storage -from six.moves.urllib import parse GOOGLE_OAUTH2_DEFAULT_SCOPES = ('email',) GOOGLE_OAUTH2_REQUEST_ATTRIBUTE = 'oauth' diff --git a/oauth2client/contrib/django_util/decorators.py b/oauth2client/contrib/django_util/decorators.py index 214f867..26c3216 100644 --- a/oauth2client/contrib/django_util/decorators.py +++ b/oauth2client/contrib/django_util/decorators.py @@ -13,9 +13,10 @@ # limitations under the License. from django import shortcuts -from oauth2client.contrib import django_util from six import wraps +from oauth2client.contrib import django_util + def oauth_required(decorated_function=None, scopes=None, **decorator_kwargs): """ Decorator to require OAuth2 credentials for a view diff --git a/oauth2client/contrib/django_util/site.py b/oauth2client/contrib/django_util/site.py index c13ed6b..7943920 100644 --- a/oauth2client/contrib/django_util/site.py +++ b/oauth2client/contrib/django_util/site.py @@ -13,6 +13,7 @@ # limitations under the License. from django.conf import urls + from oauth2client.contrib.django_util import views urlpatterns = [ diff --git a/oauth2client/contrib/django_util/views.py b/oauth2client/contrib/django_util/views.py index 523e479..de8df07 100644 --- a/oauth2client/contrib/django_util/views.py +++ b/oauth2client/contrib/django_util/views.py @@ -16,9 +16,11 @@ import hashlib import json import os import pickle + from django import http -from django.core import urlresolvers from django import shortcuts +from django.core import urlresolvers + from oauth2client import client from oauth2client.contrib import django_util from oauth2client.contrib.django_util import signals diff --git a/oauth2client/contrib/flask_util.py b/oauth2client/contrib/flask_util.py index ad61963..91bf7b8 100644 --- a/oauth2client/contrib/flask_util.py +++ b/oauth2client/contrib/flask_util.py @@ -162,14 +162,11 @@ available outside of a request context, you will need to implement your own :class:`oauth2client.Storage`. """ +from functools import wraps import hashlib import json import os import pickle -from functools import wraps - -import six.moves.http_client as httplib -import httplib2 try: from flask import Blueprint @@ -182,10 +179,13 @@ try: except ImportError: # pragma: NO COVER raise ImportError('The flask utilities require flask 0.9 or newer.') +import httplib2 +import six.moves.http_client as httplib + +from oauth2client import clientsecrets from oauth2client.client import FlowExchangeError from oauth2client.client import OAuth2WebServerFlow from oauth2client.contrib.dictionary_storage import DictionaryStorage -from oauth2client import clientsecrets __author__ = 'jonwayne@google.com (Jon Wayne Parrott)' diff --git a/oauth2client/contrib/multistore_file.py b/oauth2client/contrib/multistore_file.py index 879f3b6..3c96eb1 100644 --- a/oauth2client/contrib/multistore_file.py +++ b/oauth2client/contrib/multistore_file.py @@ -50,12 +50,11 @@ import logging import os import threading +from oauth2client import util from oauth2client.client import Credentials from oauth2client.client import Storage as BaseStorage -from oauth2client import util from oauth2client.contrib.locked_file import LockedFile - __author__ = 'jbeda@google.com (Joe Beda)' logger = logging.getLogger(__name__) diff --git a/oauth2client/contrib/sqlalchemy.py b/oauth2client/contrib/sqlalchemy.py index 4c62a06..a05a9fe 100644 --- a/oauth2client/contrib/sqlalchemy.py +++ b/oauth2client/contrib/sqlalchemy.py @@ -90,9 +90,10 @@ We will reuse tables defined above. from __future__ import absolute_import -import oauth2client.client import sqlalchemy.types +import oauth2client.client + class CredentialsType(sqlalchemy.types.PickleType): """Type representing credentials. diff --git a/oauth2client/contrib/xsrfutil.py b/oauth2client/contrib/xsrfutil.py index 20e728e..91545e7 100644 --- a/oauth2client/contrib/xsrfutil.py +++ b/oauth2client/contrib/xsrfutil.py @@ -19,8 +19,8 @@ import binascii import hmac import time -from oauth2client._helpers import _to_bytes from oauth2client import util +from oauth2client._helpers import _to_bytes __authors__ = [ '"Doug Coker" ', diff --git a/oauth2client/service_account.py b/oauth2client/service_account.py index 57b4856..d2b2b0b 100644 --- a/oauth2client/service_account.py +++ b/oauth2client/service_account.py @@ -17,23 +17,24 @@ import base64 import copy import datetime -import httplib2 import json import time +import httplib2 + +from oauth2client import crypt from oauth2client import GOOGLE_REVOKE_URI from oauth2client import GOOGLE_TOKEN_URI -from oauth2client._helpers import _from_bytes from oauth2client import util +from oauth2client._helpers import _from_bytes from oauth2client.client import _apply_user_agent from oauth2client.client import _initialize_headers +from oauth2client.client import _UTCNOW from oauth2client.client import AccessTokenInfo from oauth2client.client import AssertionCredentials from oauth2client.client import clean_headers from oauth2client.client import EXPIRY_FORMAT from oauth2client.client import SERVICE_ACCOUNT -from oauth2client.client import _UTCNOW -from oauth2client import crypt _PASSWORD_DEFAULT = 'notasecret' diff --git a/oauth2client/tools.py b/oauth2client/tools.py index f24b23f..499861e 100644 --- a/oauth2client/tools.py +++ b/oauth2client/tools.py @@ -27,8 +27,8 @@ import sys from six.moves import BaseHTTPServer from six.moves import http_client -from six.moves import urllib from six.moves import input +from six.moves import urllib from oauth2client import client from oauth2client import util diff --git a/samples/call_compute_service.py b/samples/call_compute_service.py index c5f372e..72beef0 100644 --- a/samples/call_compute_service.py +++ b/samples/call_compute_service.py @@ -5,6 +5,7 @@ # See: https://developers.google.com/compute/docs/authentication from googleapiclient.discovery import build + from oauth2client.client import GoogleCredentials diff --git a/samples/googleappengine/call_compute_service_from_gae.py b/samples/googleappengine/call_compute_service_from_gae.py index 5c7fa33..3557f58 100644 --- a/samples/googleappengine/call_compute_service_from_gae.py +++ b/samples/googleappengine/call_compute_service_from_gae.py @@ -1,8 +1,9 @@ # To be used to test GoogleCredentials.get_application_default() # from devel GAE (ie, dev_appserver.py). -import webapp2 from googleapiclient.discovery import build +import webapp2 + from oauth2client.client import GoogleCredentials diff --git a/samples/oauth2_for_devices.py b/samples/oauth2_for_devices.py index 6b3b72e..6e70ff1 100644 --- a/samples/oauth2_for_devices.py +++ b/samples/oauth2_for_devices.py @@ -2,10 +2,11 @@ # See: https://developers.google.com/accounts/docs/OAuth2ForDevices +from googleapiclient.discovery import build import httplib2 from six.moves import input + from oauth2client.client import OAuth2WebServerFlow -from googleapiclient.discovery import build CLIENT_ID = "some+client+id" CLIENT_SECRET = "some+client+secret" diff --git a/scripts/run_gce_system_tests.py b/scripts/run_gce_system_tests.py index 40c105e..d446f9c 100644 --- a/scripts/run_gce_system_tests.py +++ b/scripts/run_gce_system_tests.py @@ -13,11 +13,11 @@ # limitations under the License. import json -import unittest2 import httplib2 from six.moves import http_client from six.moves import urllib +import unittest2 from oauth2client import GOOGLE_TOKEN_INFO_URI from oauth2client.client import GoogleCredentials diff --git a/scripts/run_system_tests.py b/scripts/run_system_tests.py index 74d27d9..535a1ba 100644 --- a/scripts/run_system_tests.py +++ b/scripts/run_system_tests.py @@ -17,6 +17,7 @@ import os import httplib2 from six.moves import http_client + from oauth2client import client from oauth2client.service_account import ServiceAccountCredentials diff --git a/setup.py b/setup.py index 36894a8..686d1db 100644 --- a/setup.py +++ b/setup.py @@ -20,8 +20,10 @@ are not already installed. from __future__ import print_function import sys + from setuptools import find_packages from setuptools import setup + import oauth2client if sys.version_info < (2, 6): diff --git a/tests/contrib/test_appengine.py b/tests/contrib/test_appengine.py index 31b8b0c..2290663 100644 --- a/tests/contrib/test_appengine.py +++ b/tests/contrib/test_appengine.py @@ -13,21 +13,15 @@ # limitations under the License. import datetime -import httplib2 import json import os import tempfile import time -import unittest2 - -from six.moves import urllib import dev_appserver -dev_appserver.fix_sys_path() -import mock -import webapp2 -from ..http_mock import CacheMock +dev_appserver.fix_sys_path() + from google.appengine.api import apiproxy_stub from google.appengine.api import apiproxy_stub_map from google.appengine.api import app_identity @@ -37,12 +31,25 @@ from google.appengine.api.memcache import memcache_stub from google.appengine.ext import db from google.appengine.ext import ndb from google.appengine.ext import testbed -from oauth2client.contrib import appengine -from oauth2client import GOOGLE_TOKEN_URI +import httplib2 +import mock +from six.moves import urllib +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 TYPE_WEB from oauth2client.clientsecrets import InvalidClientSecretsError +from oauth2client.clientsecrets import TYPE_WEB +from oauth2client.contrib import appengine from oauth2client.contrib.appengine import AppAssertionCredentials from oauth2client.contrib.appengine import CredentialsModel from oauth2client.contrib.appengine import CredentialsNDBModel @@ -51,17 +58,10 @@ from oauth2client.contrib.appengine import FlowProperty from oauth2client.contrib.appengine import ( InvalidClientSecretsError as AppEngineInvalidClientSecretsError) from oauth2client.contrib.appengine import OAuth2Decorator -from oauth2client.contrib.appengine import OAuth2DecoratorFromClientSecrets from oauth2client.contrib.appengine import oauth2decorator_from_clientsecrets +from oauth2client.contrib.appengine import OAuth2DecoratorFromClientSecrets from oauth2client.contrib.appengine import StorageByKeyName -from oauth2client.client import _CLOUDSDK_CONFIG_ENV_VAR -from oauth2client.client import AccessTokenRefreshError -from oauth2client.client import Credentials -from oauth2client.client import OAuth2Credentials -from oauth2client.client import flow_from_clientsecrets -from oauth2client.client import save_to_well_known_file -from webtest import TestApp - +from ..http_mock import CacheMock __author__ = 'jcgregorio@google.com (Joe Gregorio)' diff --git a/tests/contrib/test_devshell.py b/tests/contrib/test_devshell.py index 9fcafd4..4e5ff72 100644 --- a/tests/contrib/test_devshell.py +++ b/tests/contrib/test_devshell.py @@ -19,17 +19,17 @@ import json import os import socket import threading -import unittest2 import mock +import unittest2 -from oauth2client.contrib import devshell from oauth2client._helpers import _from_bytes from oauth2client._helpers import _to_bytes from oauth2client.client import save_to_well_known_file +from oauth2client.contrib import devshell from oauth2client.contrib.devshell import _SendRecv -from oauth2client.contrib.devshell import CREDENTIAL_INFO_REQUEST_JSON 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 diff --git a/tests/contrib/test_django_orm.py b/tests/contrib/test_django_orm.py index a28b7e8..7462e25 100644 --- a/tests/contrib/test_django_orm.py +++ b/tests/contrib/test_django_orm.py @@ -21,7 +21,6 @@ import base64 import datetime import os import pickle -import unittest2 # Mock a Django environment os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.contrib.test_django_settings' @@ -35,8 +34,6 @@ import django django.setup() from django.apps import AppConfig -import mock - class DjangoOrmTestApp(AppConfig): """App Config for Django Helper.""" @@ -45,6 +42,10 @@ class DjangoOrmTestApp(AppConfig): from django.db import models +import mock +import unittest2 + +from oauth2client import GOOGLE_TOKEN_URI from oauth2client._helpers import _from_bytes from oauth2client.client import Credentials from oauth2client.client import Flow @@ -52,7 +53,6 @@ from oauth2client.client import OAuth2Credentials from oauth2client.contrib.django_orm import CredentialsField from oauth2client.contrib.django_orm import FlowField from oauth2client.contrib.django_orm import Storage -from oauth2client import GOOGLE_TOKEN_URI __author__ = 'conleyo@google.com (Conley Owens)' diff --git a/tests/contrib/test_django_util.py b/tests/contrib/test_django_util.py index 3b01427..11f2dc3 100644 --- a/tests/contrib/test_django_util.py +++ b/tests/contrib/test_django_util.py @@ -13,22 +13,23 @@ # limitations under the License. import json -import unittest2 -from django.conf.urls import include, url -from django.core import exceptions from django import http from django import test -import mock -from oauth2client.client import FlowExchangeError, OAuth2WebServerFlow import django.conf +from django.conf.urls import include, url +from django.core import exceptions +import mock +from six.moves import http_client +from six.moves.urllib import parse +import unittest2 + +from oauth2client.client import FlowExchangeError, OAuth2WebServerFlow from oauth2client.contrib import django_util from oauth2client.contrib.django_util import decorators from oauth2client.contrib.django_util import site from oauth2client.contrib.django_util import storage from oauth2client.contrib.django_util import views -from six.moves import http_client -from six.moves.urllib import parse urlpatterns = [ url(r'^oauth2/', include(site.urls)) diff --git a/tests/contrib/test_flask_util.py b/tests/contrib/test_flask_util.py index f08d229..dbf3cac 100644 --- a/tests/contrib/test_flask_util.py +++ b/tests/contrib/test_flask_util.py @@ -15,21 +15,21 @@ """Unit tests for the Flask utilities""" import datetime -import httplib2 import json -import unittest2 import flask -import six.moves.http_client as httplib +import httplib2 import mock +import six.moves.http_client as httplib import six.moves.urllib.parse as urlparse +import unittest2 +from oauth2client import clientsecrets from oauth2client import GOOGLE_AUTH_URI from oauth2client import GOOGLE_TOKEN_URI -from oauth2client import clientsecrets +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.client import OAuth2Credentials __author__ = 'jonwayne@google.com (Jon Wayne Parrott)' diff --git a/tests/contrib/test_gce.py b/tests/contrib/test_gce.py index bacecca..36ea83f 100644 --- a/tests/contrib/test_gce.py +++ b/tests/contrib/test_gce.py @@ -15,18 +15,18 @@ """Unit tests for oauth2client.contrib.gce.""" import datetime -import httplib2 import json +import httplib2 import mock from six.moves import http_client +from tests.contrib.test_metadata import request_mock import unittest2 -from oauth2client.client import save_to_well_known_file 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 tests.contrib.test_metadata import request_mock __author__ = 'jcgregorio@google.com (Joe Gregorio)' diff --git a/tests/contrib/test_keyring_storage.py b/tests/contrib/test_keyring_storage.py index 3ebf48b..d3a032a 100644 --- a/tests/contrib/test_keyring_storage.py +++ b/tests/contrib/test_keyring_storage.py @@ -15,11 +15,11 @@ """Tests for oauth2client.contrib.keyring_storage.""" import datetime -import keyring import threading -import unittest2 +import keyring import mock +import unittest2 from oauth2client import GOOGLE_TOKEN_URI from oauth2client.client import OAuth2Credentials diff --git a/tests/contrib/test_metadata.py b/tests/contrib/test_metadata.py index 9bf96c9..3fe3338 100644 --- a/tests/contrib/test_metadata.py +++ b/tests/contrib/test_metadata.py @@ -13,12 +13,12 @@ # limitations under the License. import datetime -import httplib2 import json -import mock -import unittest2 +import httplib2 +import mock from six.moves import http_client +import unittest2 from oauth2client.contrib import _metadata diff --git a/tests/contrib/test_multistore_file.py b/tests/contrib/test_multistore_file.py index de54cb0..469743b 100644 --- a/tests/contrib/test_multistore_file.py +++ b/tests/contrib/test_multistore_file.py @@ -19,9 +19,9 @@ import errno import os import stat import tempfile -import unittest2 import mock +import unittest2 from oauth2client import util from oauth2client.client import OAuth2Credentials diff --git a/tests/contrib/test_sqlalchemy.py b/tests/contrib/test_sqlalchemy.py index 8f671a3..14067e0 100644 --- a/tests/contrib/test_sqlalchemy.py +++ b/tests/contrib/test_sqlalchemy.py @@ -14,14 +14,15 @@ import datetime -import oauth2client -import oauth2client.client -import oauth2client.contrib.sqlalchemy import sqlalchemy import sqlalchemy.ext.declarative import sqlalchemy.orm import unittest2 +import oauth2client +import oauth2client.client +import oauth2client.contrib.sqlalchemy + Base = sqlalchemy.ext.declarative.declarative_base() diff --git a/tests/contrib/test_xsrfutil.py b/tests/contrib/test_xsrfutil.py index f397e1f..d6eddd6 100644 --- a/tests/contrib/test_xsrfutil.py +++ b/tests/contrib/test_xsrfutil.py @@ -15,9 +15,9 @@ """Tests for oauth2client.contrib.xsrfutil.""" import base64 -import unittest2 import mock +import unittest2 from oauth2client._helpers import _to_bytes from oauth2client.contrib import xsrfutil diff --git a/tests/test__pure_python_crypt.py b/tests/test__pure_python_crypt.py index cbfe728..bae2bcd 100644 --- a/tests/test__pure_python_crypt.py +++ b/tests/test__pure_python_crypt.py @@ -22,8 +22,8 @@ import rsa import six import unittest2 -from oauth2client._helpers import _from_bytes from oauth2client import _pure_python_crypt +from oauth2client._helpers import _from_bytes from oauth2client.crypt import RsaSigner from oauth2client.crypt import RsaVerifier diff --git a/tests/test__pycrypto_crypt.py b/tests/test__pycrypto_crypt.py index 99e968a..53c7f07 100644 --- a/tests/test__pycrypto_crypt.py +++ b/tests/test__pycrypto_crypt.py @@ -14,6 +14,7 @@ """Unit tests for oauth2client._pycrypto_crypt.""" import os + import unittest2 from oauth2client.crypt import PyCryptoSigner diff --git a/tests/test_client.py b/tests/test_client.py index a8feb19..d57dacf 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -34,38 +34,12 @@ from six.moves import http_client from six.moves import urllib import unittest2 -from .http_mock import CacheMock -from .http_mock import HttpMock -from .http_mock import HttpMockSequence -from oauth2client import GOOGLE_REVOKE_URI -from oauth2client import GOOGLE_TOKEN_URI -from oauth2client import GOOGLE_TOKEN_INFO_URI 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.client import AccessTokenCredentials -from oauth2client.client import AccessTokenCredentialsError -from oauth2client.client import HttpAccessTokenRefreshError -from oauth2client.client import ADC_HELP_MSG -from oauth2client.client import AssertionCredentials -from oauth2client.client import AUTHORIZED_USER -from oauth2client.client import Credentials -from oauth2client.client import DEFAULT_ENV_NAME -from oauth2client.client import DeviceFlowInfo -from oauth2client.client import Error -from oauth2client.client import ApplicationDefaultCredentialsError -from oauth2client.client import FlowExchangeError -from oauth2client.client import GoogleCredentials -from oauth2client.client import GOOGLE_APPLICATION_CREDENTIALS -from oauth2client.client import MemoryCache -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 SERVICE_ACCOUNT -from oauth2client.client import Storage -from oauth2client.client import TokenRevokeError -from oauth2client.client import VerifyJwtTokenError +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 @@ -76,15 +50,41 @@ 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 MemoryCache +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._helpers import _to_bytes +from .http_mock import CacheMock +from .http_mock import HttpMock +from .http_mock import HttpMockSequence __author__ = 'jcgregorio@google.com (Joe Gregorio)' diff --git a/tests/test_clientsecrets.py b/tests/test_clientsecrets.py index 081a2b1..95be076 100644 --- a/tests/test_clientsecrets.py +++ b/tests/test_clientsecrets.py @@ -18,13 +18,14 @@ import errno from io import StringIO import os import tempfile + import unittest2 -from oauth2client._helpers import _from_bytes +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 clientsecrets +from oauth2client._helpers import _from_bytes __author__ = 'jcgregorio@google.com (Joe Gregorio)' diff --git a/tests/test_crypt.py b/tests/test_crypt.py index 278c5e6..d7312ef 100644 --- a/tests/test_crypt.py +++ b/tests/test_crypt.py @@ -14,13 +14,13 @@ import base64 import os -import unittest2 import mock +import unittest2 from oauth2client import _helpers -from oauth2client.client import HAS_OPENSSL from oauth2client import crypt +from oauth2client.client import HAS_OPENSSL from oauth2client.service_account import ServiceAccountCredentials diff --git a/tests/test_file.py b/tests/test_file.py index 27f3cab..6962dee 100644 --- a/tests/test_file.py +++ b/tests/test_file.py @@ -24,15 +24,16 @@ import os import pickle import stat import tempfile -import unittest2 -from .http_mock import HttpMockSequence import six +from six.moves import http_client +import unittest2 from oauth2client import file from oauth2client.client import AccessTokenCredentials from oauth2client.client import OAuth2Credentials -from six.moves import http_client +from .http_mock import HttpMockSequence + try: # Python2 from future_builtins import oct diff --git a/tests/test_jwt.py b/tests/test_jwt.py index 00c8ef7..bbcdd3c 100644 --- a/tests/test_jwt.py +++ b/tests/test_jwt.py @@ -21,16 +21,16 @@ import time import mock import unittest2 -from .http_mock import HttpMockSequence -from oauth2client.client import Credentials -from oauth2client.client import VerifyJwtTokenError -from oauth2client.client import verify_id_token -from oauth2client.client import HAS_OPENSSL -from oauth2client.client import HAS_CRYPTO 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 .http_mock import HttpMockSequence __author__ = 'jcgregorio@google.com (Joe Gregorio)' diff --git a/tests/test_service_account.py b/tests/test_service_account.py index 1548632..7bca56b 100644 --- a/tests/test_service_account.py +++ b/tests/test_service_account.py @@ -20,20 +20,19 @@ Unit tests for service account credentials implemented using RSA. import datetime import json import os -import rsa import tempfile import httplib2 import mock +import rsa +from six import BytesIO import unittest2 -from .http_mock import HttpMockSequence from oauth2client import crypt from oauth2client.service_account import _JWTAccessCredentials -from oauth2client.service_account import ServiceAccountCredentials from oauth2client.service_account import SERVICE_ACCOUNT - -from six import BytesIO +from oauth2client.service_account import ServiceAccountCredentials +from .http_mock import HttpMockSequence def data_filename(filename): diff --git a/tests/test_tools.py b/tests/test_tools.py index ac0fc70..69c28ca 100644 --- a/tests/test_tools.py +++ b/tests/test_tools.py @@ -20,9 +20,9 @@ import mock from six.moves.urllib import request import unittest2 +from oauth2client import tools from oauth2client.client import FlowExchangeError from oauth2client.client import OOB_CALLBACK_URN -from oauth2client import tools try: import argparse diff --git a/tox.ini b/tox.ini index ea58432..1c9d92b 100644 --- a/tox.ini +++ b/tox.ini @@ -156,17 +156,21 @@ deps = passenv = {[testenv:system-tests]passenv} [testenv:flake8] -commands = flake8 {posargs} -deps = flake8-putty +commands = flake8 --import-order-style google {posargs} +deps = + flake8-putty + flake8-import-order [flake8] exclude = .tox,.git,./*.egg,build, +application-import-names = oauth2client putty-ignore = # E402 module level import not at top of file # These files have needed configurations defined before import docs/conf.py : E402 tests/contrib/test_appengine.py : E402 - tests/contrib/test_django_orm.py : E402 + # Additionally, ignore E100 (imports in wrong order) for Django configuration + tests/contrib/test_django_orm.py : E402,I100 # E501 line too long # Ignore lines over 80 chars that include "http:" or "https:" /http:/ : E501