Raise a helpful exception when trying to refresh credentials without a refresh token (#262)
diff --git a/google/oauth2/credentials.py b/google/oauth2/credentials.py
index 24b3a3e..8e2a7f8 100644
--- a/google/oauth2/credentials.py
+++ b/google/oauth2/credentials.py
@@ -38,6 +38,7 @@
from google.auth import _helpers
from google.auth import credentials
+from google.auth import exceptions
from google.oauth2 import _client
@@ -120,6 +121,15 @@
@_helpers.copy_docstring(credentials.Credentials)
def refresh(self, request):
+ if (self._refresh_token is None or
+ self._token_uri is None or
+ self._client_id is None or
+ self._client_secret is None):
+ raise exceptions.RefreshError(
+ 'The credentials do not contain the necessary fields need to '
+ 'refresh the access token. You must specify refresh_token, '
+ 'token_uri, client_id, and client_secret.')
+
access_token, refresh_token, expiry, grant_response = (
_client.refresh_grant(
request, self._token_uri, self._refresh_token, self._client_id,
diff --git a/tests/oauth2/test_credentials.py b/tests/oauth2/test_credentials.py
index 9064363..922c3bb 100644
--- a/tests/oauth2/test_credentials.py
+++ b/tests/oauth2/test_credentials.py
@@ -17,8 +17,10 @@
import os
import mock
+import pytest
from google.auth import _helpers
+from google.auth import exceptions
from google.auth import transport
from google.oauth2 import credentials
@@ -95,6 +97,16 @@
# expired)
assert credentials.valid
+ def test_refresh_no_refresh_token(self):
+ request = mock.create_autospec(transport.Request)
+ credentials_ = credentials.Credentials(
+ token=None, refresh_token=None)
+
+ with pytest.raises(exceptions.RefreshError, match='necessary fields'):
+ credentials_.refresh(request)
+
+ request.assert_not_called()
+
def test_from_authorized_user_info(self):
info = AUTH_USER_INFO.copy()