Skip to content

Commit

Permalink
Merge pull request #212 from dhermes/six-raise-from
Browse files Browse the repository at this point in the history
Using `six.raise_from` wherever possible.
  • Loading branch information
dhermes authored Nov 9, 2017
2 parents b7b48f1 + 0a93e87 commit 01efcd4
Show file tree
Hide file tree
Showing 10 changed files with 86 additions and 46 deletions.
28 changes: 17 additions & 11 deletions google/auth/_default.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
import logging
import os

import six

from google.auth import environment_vars
from google.auth import exceptions
import google.auth.transport._http_client
Expand Down Expand Up @@ -67,9 +69,11 @@ def _load_credentials_from_file(filename):
with io.open(filename, 'r') as file_obj:
try:
info = json.load(file_obj)
except ValueError as exc:
raise exceptions.DefaultCredentialsError(
'File {} is not a valid json file.'.format(filename), exc)
except ValueError as caught_exc:
new_exc = exceptions.DefaultCredentialsError(
'File {} is not a valid json file.'.format(filename),
caught_exc)
six.raise_from(new_exc, caught_exc)

# The type key should indicate that the file is either a service account
# credentials file or an authorized user credentials file.
Expand All @@ -80,10 +84,11 @@ def _load_credentials_from_file(filename):

try:
credentials = _cloud_sdk.load_authorized_user_credentials(info)
except ValueError as exc:
raise exceptions.DefaultCredentialsError(
'Failed to load authorized user credentials from {}'.format(
filename), exc)
except ValueError as caught_exc:
msg = 'Failed to load authorized user credentials from {}'.format(
filename)
new_exc = exceptions.DefaultCredentialsError(msg, caught_exc)
six.raise_from(new_exc, caught_exc)
# Authorized user credentials do not contain the project ID.
return credentials, None

Expand All @@ -93,10 +98,11 @@ def _load_credentials_from_file(filename):
try:
credentials = (
service_account.Credentials.from_service_account_info(info))
except ValueError as exc:
raise exceptions.DefaultCredentialsError(
'Failed to load service account credentials from {}'.format(
filename), exc)
except ValueError as caught_exc:
msg = 'Failed to load service account credentials from {}'.format(
filename)
new_exc = exceptions.DefaultCredentialsError(msg, caught_exc)
six.raise_from(new_exc, caught_exc)
return credentials, info.get('project_id')

else:
Expand Down
12 changes: 8 additions & 4 deletions google/auth/_oauth2client.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@

from __future__ import absolute_import

import six

from google.auth import _helpers
import google.auth.app_engine
import google.oauth2.credentials
Expand All @@ -30,8 +32,9 @@
import oauth2client.client
import oauth2client.contrib.gce
import oauth2client.service_account
except ImportError:
raise ImportError('oauth2client is not installed.')
except ImportError as caught_exc:
six.raise_from(
ImportError('oauth2client is not installed.'), caught_exc)

try:
import oauth2client.contrib.appengine
Expand Down Expand Up @@ -162,5 +165,6 @@ def convert(credentials):

try:
return _CLASS_CONVERSION_MAP[credentials_class](credentials)
except KeyError:
raise ValueError(_CONVERT_ERROR_TMPL.format(credentials_class))
except KeyError as caught_exc:
new_exc = ValueError(_CONVERT_ERROR_TMPL.format(credentials_class))
six.raise_from(new_exc, caught_exc)
6 changes: 4 additions & 2 deletions google/auth/compute_engine/_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import logging
import os

import six
from six.moves import http_client
from six.moves.urllib import parse as urlparse

Expand Down Expand Up @@ -118,10 +119,11 @@ def get(request, path, root=_METADATA_ROOT, recursive=False):
if response.headers['content-type'] == 'application/json':
try:
return json.loads(content)
except ValueError:
raise exceptions.TransportError(
except ValueError as caught_exc:
new_exc = exceptions.TransportError(
'Received invalid JSON from the Google Compute Engine'
'metadata service: {:.20}'.format(content))
six.raise_from(new_exc, caught_exc)
else:
return content
else:
Expand Down
7 changes: 5 additions & 2 deletions google/auth/compute_engine/credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
"""

import six

from google.auth import credentials
from google.auth import exceptions
from google.auth.compute_engine import _metadata
Expand Down Expand Up @@ -89,8 +91,9 @@ def refresh(self, request):
self.token, self.expiry = _metadata.get_service_account_token(
request,
service_account=self._service_account_email)
except exceptions.TransportError as exc:
raise exceptions.RefreshError(exc)
except exceptions.TransportError as caught_exc:
new_exc = exceptions.RefreshError(caught_exc)
six.raise_from(new_exc, caught_exc)

@property
def service_account_email(self):
Expand Down
6 changes: 4 additions & 2 deletions google/auth/jwt.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
import json

import cachetools
import six
from six.moves import urllib

from google.auth import _helpers
Expand Down Expand Up @@ -101,8 +102,9 @@ def _decode_jwt_segment(encoded_section):
section_bytes = _helpers.padded_urlsafe_b64decode(encoded_section)
try:
return json.loads(section_bytes.decode('utf-8'))
except ValueError:
raise ValueError('Can\'t parse segment: {0}'.format(section_bytes))
except ValueError as caught_exc:
new_exc = ValueError('Can\'t parse segment: {0}'.format(section_bytes))
six.raise_from(new_exc, caught_exc)


def _unverified_decode(token):
Expand Down
6 changes: 4 additions & 2 deletions google/auth/transport/_http_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import logging
import socket

import six
from six.moves import http_client
from six.moves import urllib

Expand Down Expand Up @@ -104,8 +105,9 @@ def __call__(self, url, method='GET', body=None, headers=None,
response = connection.getresponse()
return Response(response)

except (http_client.HTTPException, socket.error) as exc:
raise exceptions.TransportError(exc)
except (http_client.HTTPException, socket.error) as caught_exc:
new_exc = exceptions.TransportError(caught_exc)
six.raise_from(new_exc, caught_exc)

finally:
connection.close()
14 changes: 9 additions & 5 deletions google/auth/transport/grpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,17 @@

from __future__ import absolute_import

import six
try:
import grpc
except ImportError: # pragma: NO COVER
raise ImportError(
'gRPC is not installed, please install the grpcio package to use the '
'gRPC transport.')
import six
except ImportError as caught_exc: # pragma: NO COVER
six.raise_from(
ImportError(
'gRPC is not installed, please install the grpcio package '
'to use the gRPC transport.'
),
caught_exc,
)


class AuthMetadataPlugin(grpc.AuthMetadataPlugin):
Expand Down
21 changes: 14 additions & 7 deletions google/auth/transport/requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,17 @@

try:
import requests
except ImportError: # pragma: NO COVER
raise ImportError(
'The requests library is not installed, please install the requests '
'package to use the requests transport.')
import requests.exceptions
except ImportError as caught_exc: # pragma: NO COVER
import six
six.raise_from(
ImportError(
'The requests library is not installed, please install the '
'requests package to use the requests transport.'
),
caught_exc,
)
import requests.exceptions # pylint: disable=ungrouped-imports
import six # pylint: disable=ungrouped-imports

from google.auth import exceptions
from google.auth import transport
Expand Down Expand Up @@ -111,8 +117,9 @@ def __call__(self, url, method='GET', body=None, headers=None,
method, url, data=body, headers=headers, timeout=timeout,
**kwargs)
return _Response(response)
except requests.exceptions.RequestException as exc:
raise exceptions.TransportError(exc)
except requests.exceptions.RequestException as caught_exc:
new_exc = exceptions.TransportError(caught_exc)
six.raise_from(new_exc, caught_exc)


class AuthorizedSession(requests.Session):
Expand Down
21 changes: 14 additions & 7 deletions google/auth/transport/urllib3.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,17 @@

try:
import urllib3
except ImportError: # pragma: NO COVER
raise ImportError(
'The urllib3 library is not installed, please install the urllib3 '
'package to use the urllib3 transport.')
import urllib3.exceptions
except ImportError as caught_exc: # pragma: NO COVER
import six
six.raise_from(
ImportError(
'The urllib3 library is not installed, please install the '
'urllib3 package to use the urllib3 transport.'
),
caught_exc,
)
import six
import urllib3.exceptions # pylint: disable=ungrouped-imports

from google.auth import exceptions
from google.auth import transport
Expand Down Expand Up @@ -126,8 +132,9 @@ def __call__(self, url, method='GET', body=None, headers=None,
response = self.http.request(
method, url, body=body, headers=headers, **kwargs)
return _Response(response)
except urllib3.exceptions.HTTPError as exc:
raise exceptions.TransportError(exc)
except urllib3.exceptions.HTTPError as caught_exc:
new_exc = exceptions.TransportError(caught_exc)
six.raise_from(new_exc, caught_exc)


def _make_default_http():
Expand Down
11 changes: 7 additions & 4 deletions google/oauth2/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import datetime
import json

import six
from six.moves import http_client
from six.moves import urllib

Expand Down Expand Up @@ -144,9 +145,10 @@ def jwt_grant(request, token_uri, assertion):

try:
access_token = response_data['access_token']
except KeyError:
raise exceptions.RefreshError(
except KeyError as caught_exc:
new_exc = exceptions.RefreshError(
'No access token in response.', response_data)
six.raise_from(new_exc, caught_exc)

expiry = _parse_expiry(response_data)

Expand Down Expand Up @@ -190,9 +192,10 @@ def refresh_grant(request, token_uri, refresh_token, client_id, client_secret):

try:
access_token = response_data['access_token']
except KeyError:
raise exceptions.RefreshError(
except KeyError as caught_exc:
new_exc = exceptions.RefreshError(
'No access token in response.', response_data)
six.raise_from(new_exc, caught_exc)

refresh_token = response_data.get('refresh_token', refresh_token)
expiry = _parse_expiry(response_data)
Expand Down

0 comments on commit 01efcd4

Please sign in to comment.