Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using six.raise_from wherever possible. #212

Merged
merged 3 commits into from
Nov 9, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 14 additions & 9 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,10 @@ 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))
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 +83,11 @@ def _load_credentials_from_file(filename):

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

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

else:
Expand Down
11 changes: 7 additions & 4 deletions google/auth/_oauth2client.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,14 @@
import google.oauth2.credentials
import google.oauth2.service_account

import six
try:
import oauth2client.client
import oauth2client.contrib.gce
import oauth2client.service_account
except ImportError:
raise ImportError('oauth2client is not installed.')
except ImportError as caught_exc:
new_exc = ImportError('oauth2client is not installed.')
six.raise_from(new_exc, caught_exc)

try:
import oauth2client.contrib.appengine
Expand Down Expand Up @@ -162,5 +164,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()
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()
six.raise_from(new_exc, caught_exc)

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

from __future__ import absolute_import

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


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

import logging

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

from google.auth import exceptions
Expand Down Expand Up @@ -111,8 +113,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()
six.raise_from(new_exc, caught_exc)


class AuthorizedSession(requests.Session):
Expand Down
11 changes: 7 additions & 4 deletions google/auth/transport/urllib3.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,14 @@
except ImportError: # pragma: NO COVER
certifi = None

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

from google.auth import exceptions
Expand Down Expand Up @@ -126,8 +128,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()
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
2 changes: 0 additions & 2 deletions tests/compute_engine/test_credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,6 @@ def test_refresh_error(self, get):
with pytest.raises(exceptions.RefreshError) as excinfo:
self.credentials.refresh(None)

assert excinfo.match(r'http error')

@mock.patch('google.auth.compute_engine._metadata.get', autospec=True)
def test_before_request_refreshes(self, get):
get.side_effect = [{
Expand Down
2 changes: 0 additions & 2 deletions tests/test__default.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,6 @@ def test__load_credentials_from_file_authorized_user_bad_format(tmpdir):
_default._load_credentials_from_file(str(filename))

assert excinfo.match(r'Failed to load authorized user')
assert excinfo.match(r'missing fields')

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.



def test__load_credentials_from_file_service_account():
Expand All @@ -103,7 +102,6 @@ def test__load_credentials_from_file_service_account_bad_format(tmpdir):
_default._load_credentials_from_file(str(filename))

assert excinfo.match(r'Failed to load service account')
assert excinfo.match(r'missing fields')


@mock.patch.dict(os.environ, {}, clear=True)
Expand Down