Raw pep8ify changes.

Simply ran

  pep8ify -w oauth2client/
  pep8ify -w tests/
This commit is contained in:
Danny Hermes
2015-08-19 22:03:50 -07:00
parent 043e066e54
commit 34c1ff543d
40 changed files with 4635 additions and 4654 deletions

View File

@@ -55,7 +55,6 @@ try:
except ImportError: except ImportError:
ndb = None ndb = None
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
OAUTH2CLIENT_NAMESPACE = 'oauth2client#ns' OAUTH2CLIENT_NAMESPACE = 'oauth2client#ns'
@@ -313,6 +312,8 @@ class CredentialsProperty(db.Property):
if ndb is not None: if ndb is not None:
# TODO(dhermes): Turn this into a JsonProperty and overhaul the Credentials # TODO(dhermes): Turn this into a JsonProperty and overhaul the Credentials
# and subclass mechanics to use new_from_dict, to_dict, # and subclass mechanics to use new_from_dict, to_dict,
# from_dict, etc. # from_dict, etc.
@@ -326,6 +327,7 @@ if ndb is not None:
Utility property that allows easy storage and retrieval of Credentials and Utility property that allows easy storage and retrieval of Credentials and
subclasses. subclasses.
""" """
def _validate(self, value): def _validate(self, value):
"""Validates a value as a proper credentials object. """Validates a value as a proper credentials object.
@@ -617,7 +619,6 @@ class OAuth2Decorator(object):
flow = property(get_flow, set_flow) flow = property(get_flow, set_flow)
@util.positional(4) @util.positional(4)
def __init__(self, client_id, client_secret, scope, def __init__(self, client_id, client_secret, scope,
auth_uri=GOOGLE_AUTH_URI, auth_uri=GOOGLE_AUTH_URI,
@@ -797,7 +798,6 @@ class OAuth2Decorator(object):
return resp return resp
return setup_oauth return setup_oauth
def has_credentials(self): def has_credentials(self):
"""True if for the logged in user there are valid access Credentials. """True if for the logged in user there are valid access Credentials.
@@ -841,7 +841,6 @@ class OAuth2Decorator(object):
""" """
return self._callback_path return self._callback_path
def callback_handler(self): def callback_handler(self):
"""RequestHandler for the OAuth 2.0 redirect callback. """RequestHandler for the OAuth 2.0 redirect callback.

View File

@@ -107,6 +107,7 @@ DEFAULT_ENV_NAME = 'UNKNOWN'
# If set to True _get_environment avoid GCE check (_detect_gce_environment) # If set to True _get_environment avoid GCE check (_detect_gce_environment)
NO_GCE_CHECK = os.environ.setdefault('NO_GCE_CHECK', 'False') NO_GCE_CHECK = os.environ.setdefault('NO_GCE_CHECK', 'False')
class SETTINGS(object): class SETTINGS(object):
"""Settings namespace for globally defined values.""" """Settings namespace for globally defined values."""
env_name = None env_name = None
@@ -188,7 +189,6 @@ class Credentials(object):
NON_SERIALIZED_MEMBERS = ['store'] NON_SERIALIZED_MEMBERS = ['store']
def authorize(self, http): def authorize(self, http):
"""Take an httplib2.Http instance (or equivalent) and authorizes it. """Take an httplib2.Http instance (or equivalent) and authorizes it.
@@ -202,7 +202,6 @@ class Credentials(object):
""" """
_abstract() _abstract()
def refresh(self, http): def refresh(self, http):
"""Forces a refresh of the access_token. """Forces a refresh of the access_token.
@@ -212,7 +211,6 @@ class Credentials(object):
""" """
_abstract() _abstract()
def revoke(self, http): def revoke(self, http):
"""Revokes a refresh_token and makes the credentials void. """Revokes a refresh_token and makes the credentials void.
@@ -222,7 +220,6 @@ class Credentials(object):
""" """
_abstract() _abstract()
def apply(self, headers): def apply(self, headers):
"""Add the authorization to the headers. """Add the authorization to the headers.
@@ -1007,7 +1004,6 @@ class AccessTokenCredentials(OAuth2Credentials):
user_agent, user_agent,
revoke_uri=revoke_uri) revoke_uri=revoke_uri)
@classmethod @classmethod
def from_json(cls, s): def from_json(cls, s):
data = json.loads(_from_bytes(s)) data = json.loads(_from_bytes(s))
@@ -1637,6 +1633,7 @@ class SignedJwtAssertionCredentials(AssertionCredentials):
# for the certs. # for the certs.
_cached_http = httplib2.Http(MemoryCache()) _cached_http = httplib2.Http(MemoryCache())
@util.positional(2) @util.positional(2)
def verify_id_token(id_token, audience, http=None, def verify_id_token(id_token, audience, http=None,
cert_uri=ID_TOKEN_VERIFICATION_CERTS): cert_uri=ID_TOKEN_VERIFICATION_CERTS):
@@ -1851,6 +1848,7 @@ class DeviceFlowInfo(collections.namedtuple('DeviceFlowInfo', (
return cls(**kwargs) return cls(**kwargs)
class OAuth2WebServerFlow(Flow): class OAuth2WebServerFlow(Flow):
"""Does the Web Server Flow for OAuth 2.0. """Does the Web Server Flow for OAuth 2.0.

View File

@@ -23,7 +23,6 @@ __author__ = 'jcgregorio@google.com (Joe Gregorio)'
import json import json
import six import six
# Properties that make a client_secrets.json file valid. # Properties that make a client_secrets.json file valid.
TYPE_WEB = 'web' TYPE_WEB = 'web'
TYPE_INSTALLED = 'installed' TYPE_INSTALLED = 'installed'

View File

@@ -25,12 +25,10 @@ from oauth2client._helpers import _to_bytes
from oauth2client._helpers import _urlsafe_b64decode from oauth2client._helpers import _urlsafe_b64decode
from oauth2client._helpers import _urlsafe_b64encode from oauth2client._helpers import _urlsafe_b64encode
CLOCK_SKEW_SECS = 300 # 5 minutes in seconds CLOCK_SKEW_SECS = 300 # 5 minutes in seconds
AUTH_TOKEN_LIFETIME_SECS = 300 # 5 minutes in seconds AUTH_TOKEN_LIFETIME_SECS = 300 # 5 minutes in seconds
MAX_TOKEN_LIFETIME_SECS = 86400 # 1 day in seconds MAX_TOKEN_LIFETIME_SECS = 86400 # 1 day in seconds
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -45,6 +43,8 @@ try:
except ImportError: except ImportError:
OpenSSLVerifier = None OpenSSLVerifier = None
OpenSSLSigner = None OpenSSLSigner = None
def pkcs12_key_as_pem(*args, **kwargs): def pkcs12_key_as_pem(*args, **kwargs):
raise NotImplementedError('pkcs12_key_as_pem requires OpenSSL.') raise NotImplementedError('pkcs12_key_as_pem requires OpenSSL.')

View File

@@ -20,7 +20,6 @@ import os
from oauth2client._helpers import _to_bytes from oauth2client._helpers import _to_bytes
from oauth2client import client from oauth2client import client
DEVSHELL_ENV = 'DEVSHELL_CLIENT_PORT' DEVSHELL_ENV = 'DEVSHELL_CLIENT_PORT'
@@ -36,7 +35,6 @@ class CommunicationError(Error):
class NoDevshellServer(Error): class NoDevshellServer(Error):
"""Error when no Developer Shell server can be contacted.""" """Error when no Developer Shell server can be contacted."""
# The request for credential information to the Developer Shell client socket is # The request for credential information to the Developer Shell client socket is
# always an empty PBLite-formatted JSON object, so just define it as a constant. # always an empty PBLite-formatted JSON object, so just define it as a constant.
CREDENTIAL_INFO_REQUEST_JSON = '[]' CREDENTIAL_INFO_REQUEST_JSON = '[]'

View File

@@ -27,6 +27,7 @@ import pickle
from django.db import models from django.db import models
from oauth2client.client import Storage as BaseStorage from oauth2client.client import Storage as BaseStorage
class CredentialsField(models.Field): class CredentialsField(models.Field):
__metaclass__ = models.SubfieldBase __metaclass__ = models.SubfieldBase

View File

@@ -189,7 +189,6 @@ from oauth2client.client import Storage
from oauth2client import clientsecrets from oauth2client import clientsecrets
from oauth2client import util from oauth2client import util
DEFAULT_SCOPES = ('email', ) DEFAULT_SCOPES = ('email', )
@@ -461,6 +460,7 @@ class UserOAuth2(object):
be redirected to the authorization flow. Once complete, the user will be redirected to the authorization flow. Once complete, the user will
be redirected back to the original page. be redirected back to the original page.
""" """
def curry_wrapper(wrapped_function): def curry_wrapper(wrapped_function):
@wraps(wrapped_function) @wraps(wrapped_function)
def required_wrapper(*args, **kwargs): def required_wrapper(*args, **kwargs):
@@ -519,6 +519,7 @@ class FlaskSessionStorage(Storage):
credentials. We strongly recommend using a server-side session credentials. We strongly recommend using a server-side session
implementation. implementation.
""" """
def locked_get(self): def locked_get(self):
serialized = session.get('google_oauth2_credentials') serialized = session.get('google_oauth2_credentials')

View File

@@ -58,6 +58,7 @@ def validate_file(filename):
raise CredentialsFileSymbolicLinkError( raise CredentialsFileSymbolicLinkError(
'File: %s is a symbolic link.' % filename) 'File: %s is a symbolic link.' % filename)
class _Opener(object): class _Opener(object):
"""Base class for different locking primitives.""" """Base class for different locking primitives."""
@@ -174,6 +175,7 @@ class _PosixOpener(_Opener):
try: try:
import fcntl import fcntl
class _FcntlOpener(_Opener): class _FcntlOpener(_Opener):
"""Open, lock, and unlock a file using fcntl.lockf.""" """Open, lock, and unlock a file using fcntl.lockf."""
@@ -241,6 +243,7 @@ try:
import win32con import win32con
import win32file import win32file
class _Win32Opener(_Opener): class _Win32Opener(_Opener):
"""Open, lock, and unlock a file using windows primitives.""" """Open, lock, and unlock a file using windows primitives."""

View File

@@ -30,7 +30,6 @@ from oauth2client import util
from oauth2client.tools import ClientRedirectHandler from oauth2client.tools import ClientRedirectHandler
from oauth2client.tools import ClientRedirectServer from oauth2client.tools import ClientRedirectServer
FLAGS = gflags.FLAGS FLAGS = gflags.FLAGS
gflags.DEFINE_boolean('auth_local_webserver', True, gflags.DEFINE_boolean('auth_local_webserver', True,

View File

@@ -35,7 +35,6 @@ from six.moves import input
from oauth2client import client from oauth2client import client
from oauth2client import util from oauth2client import util
_CLIENT_SECRETS_MESSAGE = """WARNING: Please configure OAuth 2.0 _CLIENT_SECRETS_MESSAGE = """WARNING: Please configure OAuth 2.0
To make this sample run you will need to populate the client_secrets.json file To make this sample run you will need to populate the client_secrets.json file
@@ -47,6 +46,7 @@ with information from the APIs Console <https://code.google.com/apis/console>.
""" """
def _CreateArgumentParser(): def _CreateArgumentParser():
try: try:
import argparse import argparse

View File

@@ -38,7 +38,6 @@ import types
import six import six
from six.moves import urllib from six.moves import urllib
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
POSITIONAL_WARNING = 'WARNING' POSITIONAL_WARNING = 'WARNING'
@@ -49,6 +48,7 @@ POSITIONAL_SET = frozenset([POSITIONAL_WARNING, POSITIONAL_EXCEPTION,
positional_parameters_enforcement = POSITIONAL_WARNING positional_parameters_enforcement = POSITIONAL_WARNING
def positional(max_positional_args): def positional(max_positional_args):
"""A decorator to declare that only the first N arguments my be positional. """A decorator to declare that only the first N arguments my be positional.
@@ -119,6 +119,7 @@ def positional(max_positional_args):
POSITIONAL_EXCEPTION. POSITIONAL_EXCEPTION.
""" """
def positional_decorator(wrapped): def positional_decorator(wrapped):
@functools.wraps(wrapped) @functools.wraps(wrapped)
def positional_wrapper(*args, **kwargs): def positional_wrapper(*args, **kwargs):

View File

@@ -20,7 +20,6 @@ __authors__ = [
'"Joe Gregorio" <jcgregorio@google.com>', '"Joe Gregorio" <jcgregorio@google.com>',
] ]
import base64 import base64
import hmac import hmac
import time import time
@@ -28,11 +27,9 @@ import time
import six import six
from oauth2client import util from oauth2client import util
# Delimiter character # Delimiter character
DELIMITER = b':' DELIMITER = b':'
# 1 hour in seconds # 1 hour in seconds
DEFAULT_TIMEOUT_SECS = 1 * 60 * 60 DEFAULT_TIMEOUT_SECS = 1 * 60 * 60

View File

@@ -16,6 +16,7 @@ __author__ = 'afshar@google.com (Ali Afshar)'
import oauth2client.util import oauth2client.util
def setup_package(): def setup_package():
"""Run on testing package.""" """Run on testing package."""
oauth2client.util.positional_parameters_enforcement = 'EXCEPTION' oauth2client.util.positional_parameters_enforcement = 'EXCEPTION'

View File

@@ -20,7 +20,6 @@ import httplib2
# TODO(craigcitro): Find a cleaner way to share this code with googleapiclient. # TODO(craigcitro): Find a cleaner way to share this code with googleapiclient.
class HttpMock(object): class HttpMock(object):
"""Mock of httplib2.Http""" """Mock of httplib2.Http"""
@@ -45,7 +44,6 @@ class HttpMock(object):
self.body = None self.body = None
self.headers = None self.headers = None
def request(self, uri, def request(self, uri,
method='GET', method='GET',
body=None, body=None,

View File

@@ -14,7 +14,6 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
"""Discovery document tests """Discovery document tests
Unit tests for objects created from discovery documents. Unit tests for objects created from discovery documents.
@@ -68,7 +67,6 @@ from oauth2client.client import flow_from_clientsecrets
from oauth2client.client import save_to_well_known_file from oauth2client.client import save_to_well_known_file
from webtest import TestApp from webtest import TestApp
DATA_DIR = os.path.join(os.path.dirname(__file__), 'data') DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
@@ -131,7 +129,6 @@ class TestAppAssertionCredentials(unittest.TestCase):
account_name = "service_account_name@appspot.com" account_name = "service_account_name@appspot.com"
signature = "signature" signature = "signature"
class AppIdentityStubImpl(apiproxy_stub.APIProxyStub): class AppIdentityStubImpl(apiproxy_stub.APIProxyStub):
def __init__(self): def __init__(self):
@@ -142,7 +139,6 @@ class TestAppAssertionCredentials(unittest.TestCase):
response.set_access_token('a_token_123') response.set_access_token('a_token_123')
response.set_expiration_time(time.time() + 1800) response.set_expiration_time(time.time() + 1800)
class ErroringAppIdentityStubImpl(apiproxy_stub.APIProxyStub): class ErroringAppIdentityStubImpl(apiproxy_stub.APIProxyStub):
def __init__(self): def __init__(self):
@@ -527,7 +523,6 @@ class DecoratorTests(unittest.TestCase):
if parent.should_raise: if parent.should_raise:
raise Exception('') raise Exception('')
application = webapp2.WSGIApplication([ application = webapp2.WSGIApplication([
('/oauth2callback', self.decorator.callback_handler()), ('/oauth2callback', self.decorator.callback_handler()),
('/foo_path', TestRequiredHandler), ('/foo_path', TestRequiredHandler),
@@ -696,7 +691,6 @@ class DecoratorTests(unittest.TestCase):
self.should_raise = False self.should_raise = False
self.assertEqual(None, self.decorator.credentials) self.assertEqual(None, self.decorator.credentials)
def test_error_in_step2(self): def test_error_in_step2(self):
# An initial request to an oauth_aware decorated path should not redirect. # An initial request to an oauth_aware decorated path should not redirect.
response = self.app.get('/bar_path/2012/01') response = self.app.get('/bar_path/2012/01')
@@ -756,7 +750,6 @@ class DecoratorTests(unittest.TestCase):
approval_prompt='force') approval_prompt='force')
self.assertTrue('approval_prompt' in decorator._kwargs) self.assertTrue('approval_prompt' in decorator._kwargs)
def test_decorator_from_cached_client_secrets(self): def test_decorator_from_cached_client_secrets(self):
cache_mock = CacheMock() cache_mock = CacheMock()
load_and_cache('client_secrets.json', 'secret', cache_mock) load_and_cache('client_secrets.json', 'secret', cache_mock)

View File

@@ -16,7 +16,6 @@
__author__ = 'jcgregorio@google.com (Joe Gregorio)' __author__ = 'jcgregorio@google.com (Joe Gregorio)'
import os import os
import unittest import unittest
from io import StringIO from io import StringIO
@@ -25,12 +24,12 @@ import httplib2
from oauth2client import clientsecrets from oauth2client import clientsecrets
DATA_DIR = os.path.join(os.path.dirname(__file__), 'data') DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
VALID_FILE = os.path.join(DATA_DIR, 'client_secrets.json') VALID_FILE = os.path.join(DATA_DIR, 'client_secrets.json')
INVALID_FILE = os.path.join(DATA_DIR, 'unfilled_client_secrets.json') INVALID_FILE = os.path.join(DATA_DIR, 'unfilled_client_secrets.json')
NONEXISTENT_FILE = os.path.join(__file__, '..', 'afilethatisntthere.json') NONEXISTENT_FILE = os.path.join(__file__, '..', 'afilethatisntthere.json')
class OAuth2CredentialsTests(unittest.TestCase): class OAuth2CredentialsTests(unittest.TestCase):
def setUp(self): def setUp(self):

View File

@@ -12,7 +12,6 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
"""Tests for oauth2client.devshell.""" """Tests for oauth2client.devshell."""
import os import os

View File

@@ -14,7 +14,6 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
"""Discovery document tests """Discovery document tests
Unit tests for objects created from discovery documents. Unit tests for objects created from discovery documents.

View File

@@ -14,7 +14,6 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
"""Oauth2client.file tests """Oauth2client.file tests
Unit tests for oauth2client.file Unit tests for oauth2client.file
@@ -47,7 +46,6 @@ try:
except: except:
pass pass
FILENAME = tempfile.mktemp('oauth2client_test.data') FILENAME = tempfile.mktemp('oauth2client_test.data')

View File

@@ -12,7 +12,6 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
"""Unit tests for the Flask utilities""" """Unit tests for the Flask utilities"""
__author__ = 'jonwayne@google.com (Jon Wayne Parrott)' __author__ = 'jonwayne@google.com (Jon Wayne Parrott)'
@@ -35,6 +34,7 @@ from oauth2client.client import OAuth2Credentials
class Http2Mock(object): class Http2Mock(object):
"""Mock httplib2.Http for code exchange / refresh""" """Mock httplib2.Http for code exchange / refresh"""
def __init__(self, status=httplib.OK, **kwargs): def __init__(self, status=httplib.OK, **kwargs):
self.status = status self.status = status
self.content = { self.content = {

View File

@@ -12,7 +12,6 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
"""Tests for oauth2client.gce. """Tests for oauth2client.gce.
Unit tests for oauth2client.gce. Unit tests for oauth2client.gce.

View File

@@ -14,7 +14,6 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
"""Oauth2client tests """Oauth2client tests
Unit tests for oauth2client. Unit tests for oauth2client.

View File

@@ -12,7 +12,6 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
"""Tests for oauth2client.keyring_storage tests. """Tests for oauth2client.keyring_storage tests.
Unit tests for oauth2client.keyring_storage. Unit tests for oauth2client.keyring_storage.

View File

@@ -14,7 +14,6 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
"""Oauth2client tests """Oauth2client tests
Unit tests for oauth2client. Unit tests for oauth2client.
@@ -618,6 +617,7 @@ def _token_revoke_test_helper(testcase, status, revoke_raise,
actual_do_revoke = testcase.credentials._do_revoke actual_do_revoke = testcase.credentials._do_revoke
testcase.token_from_revoke = None testcase.token_from_revoke = None
def do_revoke_stub(http_request, token): def do_revoke_stub(http_request, token):
testcase.token_from_revoke = token testcase.token_from_revoke = token
return actual_do_revoke(http_request, token) return actual_do_revoke(http_request, token)
@@ -884,6 +884,7 @@ class BasicCredentialsTests(unittest.TestCase):
self.credentials.retrieve_scopes, self.credentials.retrieve_scopes,
http) http)
class AccessTokenCredentialsTests(unittest.TestCase): class AccessTokenCredentialsTests(unittest.TestCase):
def setUp(self): def setUp(self):

View File

@@ -14,7 +14,6 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
"""Oauth2client tests. """Oauth2client tests.
Unit tests for service account credentials implemented using RSA. Unit tests for service account credentials implemented using RSA.

View File

@@ -5,6 +5,7 @@ from oauth2client import tools
from six.moves.urllib import request from six.moves.urllib import request
import threading import threading
class TestClientRedirectServer(unittest.TestCase): class TestClientRedirectServer(unittest.TestCase):
"""Test the ClientRedirectServer and ClientRedirectHandler classes.""" """Test the ClientRedirectServer and ClientRedirectHandler classes."""
@@ -27,4 +28,3 @@ class TestClientRedirectServer(unittest.TestCase):
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()

View File

@@ -40,6 +40,7 @@ class StringToScopeTests(unittest.TestCase):
for case, expected in cases: for case, expected in cases:
self.assertEqual(expected, util.string_to_scopes(case)) self.assertEqual(expected, util.string_to_scopes(case))
class KeyConversionTests(unittest.TestCase): class KeyConversionTests(unittest.TestCase):
def test_key_conversions(self): def test_key_conversions(self):