Update string formatters to new style

Changing `%` style string formatters to `.format()`.
Leaving `logging` strings in old style for Python 2 compatibility.

Resolves: Issue #541
This commit is contained in:
Pat Ferate
2016-07-18 12:14:11 -07:00
parent 00afef9eb0
commit a7cddf20a6
20 changed files with 117 additions and 103 deletions

View File

@@ -68,7 +68,7 @@ def _to_bytes(value, encoding='ascii'):
if isinstance(result, six.binary_type):
return result
else:
raise ValueError('%r could not be converted to bytes' % (value,))
raise ValueError('{0!r} could not be converted to bytes'.format(value))
def _from_bytes(value):
@@ -89,7 +89,8 @@ def _from_bytes(value):
if isinstance(result, six.text_type):
return result
else:
raise ValueError('%r could not be converted to unicode' % (value,))
raise ValueError(
'{0!r} could not be converted to unicode'.format(value))
def _urlsafe_b64encode(raw_bytes):

View File

@@ -927,7 +927,7 @@ class OAuth2Credentials(Credentials):
# An {'error':...} response body means the token is expired or
# revoked, so we flag the credentials as such.
logger.info('Failed to retrieve access token: %s', content)
error_msg = 'Invalid response %s.' % (resp['status'],)
error_msg = 'Invalid response {0}.'.format(resp['status'])
try:
d = json.loads(content)
if 'error' in d:
@@ -972,7 +972,7 @@ class OAuth2Credentials(Credentials):
if resp.status == http_client.OK:
self.invalid = True
else:
error_msg = 'Invalid response %s.' % resp.status
error_msg = 'Invalid response {0}.'.format(resp.status)
try:
d = json.loads(_from_bytes(content))
if 'error' in d:
@@ -1018,7 +1018,7 @@ class OAuth2Credentials(Credentials):
d = json.loads(content)
self.scopes = set(util.string_to_scopes(d.get('scope', '')))
else:
error_msg = 'Invalid response %s.' % (resp.status,)
error_msg = 'Invalid response {0}.'.format(resp.status)
try:
d = json.loads(content)
if 'error_description' in d:
@@ -1459,7 +1459,8 @@ def save_to_well_known_file(credentials, well_known_file=None):
config_dir = os.path.dirname(well_known_file)
if not os.path.isdir(config_dir):
raise OSError('Config directory does not exist: %s' % config_dir)
raise OSError(
'Config directory does not exist: {0}'.format(config_dir))
credentials_data = credentials.serialization_data
_save_private_file(well_known_file, credentials_data)
@@ -1690,7 +1691,7 @@ def verify_id_token(id_token, audience, http=None,
certs = json.loads(_from_bytes(content))
return crypt.verify_signed_jwt_with_certs(id_token, certs, audience)
else:
raise VerifyJwtTokenError('Status code: %d' % resp.status)
raise VerifyJwtTokenError('Status code: {0}'.format(resp.status))
def _extract_id_token(id_token):
@@ -1711,7 +1712,7 @@ def _extract_id_token(id_token):
if len(segments) != 3:
raise VerifyJwtTokenError(
'Wrong number of segments in token: %s' % id_token)
'Wrong number of segments in token: {0}'.format(id_token))
return json.loads(_from_bytes(_urlsafe_b64decode(segments[1])))
@@ -2036,15 +2037,15 @@ class OAuth2WebServerFlow(Flow):
flow_info = json.loads(content)
except ValueError as exc:
raise OAuth2DeviceCodeError(
'Could not parse server response as JSON: "%s", '
'error: "%s"' % (content, exc))
'Could not parse server response as JSON: "{0}", '
'error: "{1}"'.format(content, exc))
return DeviceFlowInfo.FromResponse(flow_info)
else:
error_msg = 'Invalid response %s.' % (resp.status,)
error_msg = 'Invalid response {0}.'.format(resp.status)
try:
error_dict = json.loads(content)
if 'error' in error_dict:
error_msg += ' Error: %s' % (error_dict['error'],)
error_msg += ' Error: {0}'.format(error_dict['error'])
except ValueError:
# Couldn't decode a JSON response, stick with the
# default message.
@@ -2144,7 +2145,7 @@ class OAuth2WebServerFlow(Flow):
error_msg = (str(d['error']) +
str(d.get('error_description', '')))
else:
error_msg = 'Invalid response: %s.' % str(resp.status)
error_msg = 'Invalid response: {0}.'.format(str(resp.status))
raise FlowExchangeError(error_msg)
@@ -2218,4 +2219,4 @@ def flow_from_clientsecrets(filename, scope, redirect_uri=None,
raise
else:
raise UnknownClientSecretsFlowError(
'This OAuth 2.0 flow is unsupported: %r' % (client_type,))
'This OAuth 2.0 flow is unsupported: {0!r}'.format(client_type))

View File

@@ -93,17 +93,17 @@ def _validate_clientsecrets(clientsecrets_dict):
if client_type not in VALID_CLIENT:
raise InvalidClientSecretsError(
'Unknown client type: %s.' % (client_type,))
'Unknown client type: {0}.'.format(client_type))
for prop_name in VALID_CLIENT[client_type]['required']:
if prop_name not in client_info:
raise InvalidClientSecretsError(
'Missing property "%s" in a client type of "%s".' %
(prop_name, client_type))
'Missing property "{0}" in a client type of "{1}".'.format(
prop_name, client_type))
for prop_name in VALID_CLIENT[client_type]['string']:
if client_info[prop_name].startswith('[['):
raise InvalidClientSecretsError(
'Property "%s" is not configured.' % prop_name)
'Property "{0}" is not configured.'.format(prop_name))
return client_type, client_info

View File

@@ -76,9 +76,9 @@ class FlowNDBProperty(ndb.PickleProperty):
"""
_LOGGER.info('validate: Got type %s', type(value))
if value is not None and not isinstance(value, client.Flow):
raise TypeError('Property %s must be convertible to a flow '
'instance; received: %s.' % (self._name,
value))
raise TypeError(
'Property {0} must be convertible to a flow '
'instance; received: {1}.'.format(self._name, value))
class CredentialsNDBProperty(ndb.BlobProperty):
@@ -104,9 +104,9 @@ class CredentialsNDBProperty(ndb.BlobProperty):
"""
_LOGGER.info('validate: Got type %s', type(value))
if value is not None and not isinstance(value, client.Credentials):
raise TypeError('Property %s must be convertible to a '
'credentials instance; received: %s.' %
(self._name, value))
raise TypeError(
'Property {0} must be convertible to a credentials '
'instance; received: {1}.'.format(self._name, value))
def _to_base_type(self, value):
"""Converts our validated value to a JSON serialized string.

View File

@@ -39,8 +39,8 @@ class _FcntlOpener(_Opener):
link.
"""
if self._locked:
raise AlreadyLockedException('File %s is already locked' %
self._filename)
raise AlreadyLockedException(
'File {0} is already locked'.format(self._filename))
start_time = time.time()
validate_file(self._filename)

View File

@@ -50,8 +50,8 @@ class _Win32Opener(_Opener):
link.
"""
if self._locked:
raise AlreadyLockedException('File %s is already locked' %
self._filename)
raise AlreadyLockedException(
'File {0} is already locked'.format(self._filename))
start_time = time.time()
validate_file(self._filename)
@@ -86,8 +86,8 @@ class _Win32Opener(_Opener):
# We could not acquire the lock. Try again.
if (time.time() - start_time) >= timeout:
logger.warn('Could not lock %s in %s seconds' % (
self._filename, timeout))
logger.warn('Could not lock %s in %s seconds',
self._filename, timeout)
if self._fh:
self._fh.close()
self._fh = open(self._filename, self._fallback_mode)

View File

@@ -251,9 +251,9 @@ class FlowProperty(db.Property):
def validate(self, value):
if value is not None and not isinstance(value, Flow):
raise db.BadValueError('Property %s must be convertible '
'to a FlowThreeLegged instance (%s)' %
(self.name, value))
raise db.BadValueError(
'Property {0} must be convertible '
'to a FlowThreeLegged instance ({1})'.format(self.name, value))
return super(FlowProperty, self).validate(value)
def empty(self, value):
@@ -298,9 +298,9 @@ class CredentialsProperty(db.Property):
value = super(CredentialsProperty, self).validate(value)
logger.info("validate: Got type " + str(type(value)))
if value is not None and not isinstance(value, Credentials):
raise db.BadValueError('Property %s must be convertible '
'to a Credentials instance (%s)' %
(self.name, value))
raise db.BadValueError(
'Property {0} must be convertible '
'to a Credentials instance ({1})'.format(self.name, value))
return value
@@ -356,8 +356,8 @@ class StorageByKeyName(Storage):
elif issubclass(self._model, db.Model):
return False
raise TypeError('Model class not an NDB or DB model: %s.' %
(self._model,))
raise TypeError(
'Model class not an NDB or DB model: {0}.'.format(self._model))
def _get_entity(self):
"""Retrieve entity from datastore.
@@ -790,8 +790,8 @@ class OAuth2Decorator(object):
if error:
errormsg = self.request.get('error_description', error)
self.response.out.write(
'The authorization request failed: %s' %
_safe_html(errormsg))
'The authorization request failed: {0}'.format(
_safe_html(errormsg)))
else:
user = users.get_current_user()
decorator._create_flow(self)

View File

@@ -83,7 +83,7 @@ def _SendRecv():
sock.connect(('localhost', port))
data = CREDENTIAL_INFO_REQUEST_JSON
msg = '%s\n%s' % (len(data), data)
msg = '{0}\n{1}'.format(len(data), data)
sock.sendall(_to_bytes(msg, encoding='utf-8'))
header = sock.recv(6).decode()

View File

@@ -106,7 +106,8 @@ request.oauth
http=request.oauth.http,
developerKey=API_KEY)
events = service.events().list(calendarId='primary').execute()['items']
return HttpResponse("email: %s , calendar: %s" % (email, str(events)))
return HttpResponse(
"email: {0} , calendar: {1}".format(email, str(events)))
To make OAuth2 optional and provide an authorization link in your own views.
@@ -121,12 +122,12 @@ To make OAuth2 optional and provide an authorization link in your own views.
if request.oauth.has_credentials():
# this could be passed into a view
# request.oauth.http is also initialized
return HttpResponse("User email: %s"
% request.oauth.credentials.id_token['email'])
return HttpResponse("User email: {0}".format(
request.oauth.credentials.id_token['email']))
else:
return HttpResponse(
'Here is an OAuth Authorize link: <a href="%s">Authorize</a>'
% request.oauth.get_authorize_redirect())
'Here is an OAuth Authorize link: <a href="{0}">Authorize'
'</a>'.format(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)
@@ -146,8 +147,8 @@ and specify additional scopes in the decorator arguments.
return HttpResponse(str(events))
else:
return HttpResponse(
'Here is an OAuth Authorize link: <a href="%s">Authorize</a>'
% request.oauth.get_authorize_redirect())
'Here is an OAuth Authorize link: <a href="{0}">Authorize'
'</a>'.format(request.oauth.get_authorize_redirect()))
To provide a callback on authorization being completed, use the
@@ -160,7 +161,8 @@ oauth2_authorized signal:
from oauth2client.contrib.django_util.signals import oauth2_authorized
def test_callback(sender, request, credentials, **kwargs):
print "Authorization Signal Received %s" % credentials.id_token['email']
print("Authorization Signal Received {0}".format(
credentials.id_token['email']))
oauth2_authorized.connect(test_callback)

View File

@@ -37,7 +37,8 @@ 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: {0}, calendar: {1}".format(email, str(events)))
:param decorated_function: View function to decorate, must have the Django
request object as the first argument
@@ -85,12 +86,12 @@ def oauth_enabled(decorated_function=None, scopes=None, **decorator_kwargs):
if request.oauth.has_credentials():
# this could be passed into a view
# request.oauth.http is also initialized
return HttpResponse("User email: %s" %
request.oauth.credentials.id_token['email'])
return HttpResponse("User email: {0}".format(
request.oauth.credentials.id_token['email']))
else:
return HttpResponse('Here is an OAuth Authorize link:
<a href="%s">Authorize</a>' %
request.oauth.get_authorize_redirect())
<a href="{0}">Authorize</a>'.format(
request.oauth.get_authorize_redirect()))
:param decorated_function: View function to decorate

View File

@@ -77,7 +77,7 @@ def oauth2_callback(request):
reason = request.GET.get(
'error_description', request.GET.get('error', ''))
return http.HttpResponseBadRequest(
'Authorization failed %s' % reason)
'Authorization failed {0}'.format(reason))
try:
encoded_state = request.GET['state']

View File

@@ -57,7 +57,7 @@ class AlreadyLockedException(Exception):
def validate_file(filename):
if os.path.islink(filename):
raise CredentialsFileSymbolicLinkError(
'File: %s is a symbolic link.' % filename)
'File: {0} is a symbolic link.'.format(filename))
class _Opener(object):
@@ -122,8 +122,8 @@ class _PosixOpener(_Opener):
CredentialsFileSymbolicLinkError if the file is a symbolic link.
"""
if self._locked:
raise AlreadyLockedException('File %s is already locked' %
self._filename)
raise AlreadyLockedException(
'File {0} is already locked'.format(self._filename))
self._locked = False
validate_file(self._filename)
@@ -170,7 +170,7 @@ class _PosixOpener(_Opener):
def _posix_lockfile(self, filename):
"""The name of the lock file to use for posix locking."""
return '%s.lock' % filename
return '{0}.lock'.format(filename)
class LockedFile(object):

View File

@@ -390,8 +390,8 @@ class _MultiStore(object):
'corrupt or an old version. Overwriting.')
if version > 1:
raise NewerCredentialStoreError(
'Credential file has file_version of %d. '
'Only file_version of 1 is supported.' % version)
'Credential file has file_version of {0}. '
'Only file_version of 1 is supported.'.format(version))
credentials = []
try:

View File

@@ -144,11 +144,11 @@ def _check_audience(payload_dict, audience):
audience_in_payload = payload_dict.get('aud')
if audience_in_payload is None:
raise AppIdentityError('No aud field in token: %s' %
(payload_dict,))
raise AppIdentityError(
'No aud field in token: {0}'.format(payload_dict))
if audience_in_payload != audience:
raise AppIdentityError('Wrong recipient, %s != %s: %s' %
(audience_in_payload, audience, payload_dict))
raise AppIdentityError('Wrong recipient, {0} != {1}: {2}'.format(
audience_in_payload, audience, payload_dict))
def _verify_time_range(payload_dict):
@@ -180,26 +180,28 @@ def _verify_time_range(payload_dict):
# Make sure issued at and expiration are in the payload.
issued_at = payload_dict.get('iat')
if issued_at is None:
raise AppIdentityError('No iat field in token: %s' % (payload_dict,))
raise AppIdentityError(
'No iat field in token: {0}'.format(payload_dict))
expiration = payload_dict.get('exp')
if expiration is None:
raise AppIdentityError('No exp field in token: %s' % (payload_dict,))
raise AppIdentityError(
'No exp field in token: {0}'.format(payload_dict))
# Make sure the expiration gives an acceptable token lifetime.
if expiration >= now + MAX_TOKEN_LIFETIME_SECS:
raise AppIdentityError('exp field too far in future: %s' %
(payload_dict,))
raise AppIdentityError(
'exp field too far in future: {0}'.format(payload_dict))
# Make sure (up to clock skew) that the token wasn't issued in the future.
earliest = issued_at - CLOCK_SKEW_SECS
if now < earliest:
raise AppIdentityError('Token used too early, %d < %d: %s' %
(now, earliest, payload_dict))
raise AppIdentityError('Token used too early, {0} < {1}: {2}'.format(
now, earliest, payload_dict))
# Make sure (up to clock skew) that the token isn't already expired.
latest = expiration + CLOCK_SKEW_SECS
if now > latest:
raise AppIdentityError('Token used too late, %d > %d: %s' %
(now, latest, payload_dict))
raise AppIdentityError('Token used too late, {0} > {1}: {2}'.format(
now, latest, payload_dict))
def verify_signed_jwt_with_certs(jwt, certs, audience=None):
@@ -223,7 +225,7 @@ def verify_signed_jwt_with_certs(jwt, certs, audience=None):
if jwt.count(b'.') != 2:
raise AppIdentityError(
'Wrong number of segments in token: %s' % (jwt,))
'Wrong number of segments in token: {0}'.format(jwt))
header, payload, signature = jwt.split(b'.')
message_to_sign = header + b'.' + payload
@@ -234,7 +236,7 @@ def verify_signed_jwt_with_certs(jwt, certs, audience=None):
try:
payload_dict = json.loads(_from_bytes(payload_bytes))
except:
raise AppIdentityError('Can\'t parse token: %s' % (payload_bytes,))
raise AppIdentityError('Can\'t parse token: {0}'.format(payload_bytes))
# Verify that the signature matches the message.
_verify_signature(message_to_sign, signature, certs.values())

View File

@@ -42,7 +42,7 @@ class Storage(BaseStorage):
def _validate_file(self):
if os.path.islink(self._filename):
raise CredentialsFileSymbolicLinkError(
'File: %s is a symbolic link.' % self._filename)
'File: {0} is a symbolic link.'.format(self._filename))
def locked_get(self):
"""Retrieve Credential from file.

View File

@@ -42,7 +42,7 @@ _CLIENT_SECRETS_MESSAGE = """WARNING: Please configure OAuth 2.0
To make this sample run you will need to populate the client_secrets.json file
found at:
%s
{file_path}
with information from the APIs Console <https://code.google.com/apis/console>.
@@ -60,7 +60,7 @@ authorization.
_BROWSER_OPENED_MESSAGE = """
Your browser has been opened to visit:
%s
{address}
If your browser is on a different machine then exit and re-run this
application with the command-line parameter
@@ -71,7 +71,7 @@ application with the command-line parameter
_GO_TO_LINK_MESSAGE = """
Go to the following link in your browser:
%s
{address}
"""
@@ -211,7 +211,8 @@ def run_flow(flow, storage, flags=None, http=None):
print(_FAILED_START_MESSAGE)
if not flags.noauth_local_webserver:
oauth_callback = 'http://%s:%s/' % (flags.auth_host_name, port_number)
oauth_callback = 'http://{host}:{port}/'.format(
host=flags.auth_host_name, port=port_number)
else:
oauth_callback = client.OOB_CALLBACK_URN
flow.redirect_uri = oauth_callback
@@ -220,9 +221,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(_BROWSER_OPENED_MESSAGE % authorize_url)
print(_BROWSER_OPENED_MESSAGE.format(address=authorize_url))
else:
print(_GO_TO_LINK_MESSAGE % authorize_url)
print(_GO_TO_LINK_MESSAGE.format(address=authorize_url))
code = None
if not flags.noauth_local_webserver:
@@ -241,7 +242,7 @@ def run_flow(flow, storage, flags=None, http=None):
try:
credential = flow.step2_exchange(code, http=http)
except client.FlowExchangeError as e:
sys.exit('Authentication has failed: %s' % e)
sys.exit('Authentication has failed: {0}'.format(e))
storage.put(credential)
credential.set_store(storage)
@@ -252,4 +253,4 @@ def run_flow(flow, storage, flags=None, http=None):
def message_if_missing(filename):
"""Helpful message to display if the CLIENT_SECRETS file is missing."""
return _CLIENT_SECRETS_MESSAGE % filename
return _CLIENT_SECRETS_MESSAGE.format(file_path=filename)

View File

@@ -124,10 +124,12 @@ def positional(max_positional_args):
plural_s = ''
if max_positional_args != 1:
plural_s = 's'
message = ('%s() takes at most %d positional '
'argument%s (%d given)' % (
wrapped.__name__, max_positional_args,
plural_s, len(args)))
message = ('{function}() takes at most {args_max} positional '
'argument{plural} ({args_given} given)'.format(
function=wrapped.__name__,
args_max=max_positional_args,
args_given=len(args),
plural=plural_s))
if positional_parameters_enforcement == POSITIONAL_EXCEPTION:
raise TypeError(message)
elif positional_parameters_enforcement == POSITIONAL_WARNING:

View File

@@ -109,7 +109,8 @@ class Test_SendRecv(unittest2.TestCase):
sock.recv(6).decode.assert_called_once_with()
data = CREDENTIAL_INFO_REQUEST_JSON
msg = _to_bytes('%s\n%s' % (len(data), data), encoding='utf-8')
msg = _to_bytes('{0}\n{1}'.format(len(data), data),
encoding='utf-8')
expected_sock_calls = [
mock.call.recv(6), # From the set-up above
mock.call.connect(('localhost', non_zero_port)),
@@ -167,7 +168,7 @@ class _AuthReferenceServer(threading.Thread):
if resp_buffer != CREDENTIAL_INFO_REQUEST_JSON:
self.bad_request = True
l = len(self.response)
s.sendall(('%d\n%s' % (l, self.response)).encode())
s.sendall('{0}\n{1}'.format(l, self.response).encode())
finally:
# Will fail if s is None, but these tests never encounter
# that scenario.
@@ -183,7 +184,7 @@ class DevshellCredentialsTests(unittest2.TestCase):
def test_bad_message_to_mock_server(self):
request_content = CREDENTIAL_INFO_REQUEST_JSON + 'extrastuff'
request_message = _to_bytes(
'%d\n%s' % (len(request_content), request_content))
'{0}\n{1}'.format(len(request_content), request_content))
response_message = 'foobar'
with _AuthReferenceServer(response_message) as auth_server:
self.assertFalse(auth_server.bad_request)

View File

@@ -1279,7 +1279,7 @@ class BasicCredentialsTests(unittest2.TestCase):
'status': int(http_client.BAD_REQUEST),
})
content = u'Bad request'
error_msg = 'Invalid response %s.' % (int(response.status),)
error_msg = 'Invalid response {0}.'.format(int(response.status))
self._do_refresh_request_test_helper(response, content, error_msg)
def test__do_refresh_request_basic_failure(self):
@@ -1287,7 +1287,7 @@ class BasicCredentialsTests(unittest2.TestCase):
'status': int(http_client.INTERNAL_SERVER_ERROR),
})
content = u'{}'
error_msg = 'Invalid response %s.' % (int(response.status),)
error_msg = 'Invalid response {0}.'.format(int(response.status))
self._do_refresh_request_test_helper(response, content, error_msg)
def test__do_refresh_request_failure_w_json_error(self):
@@ -1318,7 +1318,7 @@ class BasicCredentialsTests(unittest2.TestCase):
'error': base_error,
'error_description': error_desc,
})
error_msg = '%s: %s' % (base_error, error_desc)
error_msg = '{0}: {1}'.format(base_error, error_desc)
self._do_refresh_request_test_helper(response, content, error_msg)
@mock.patch('oauth2client.client.logger')
@@ -1371,7 +1371,7 @@ class BasicCredentialsTests(unittest2.TestCase):
'status': http_client.BAD_REQUEST,
})
content = u'Bad request'
error_msg = 'Invalid response %s.' % (response.status,)
error_msg = 'Invalid response {0}.'.format(response.status)
self._do_revoke_test_helper(response, content, error_msg)
def test__do_revoke_basic_failure(self):
@@ -1379,7 +1379,7 @@ class BasicCredentialsTests(unittest2.TestCase):
'status': http_client.INTERNAL_SERVER_ERROR,
})
content = u'{}'
error_msg = 'Invalid response %s.' % (response.status,)
error_msg = 'Invalid response {0}.'.format(response.status)
self._do_revoke_test_helper(response, content, error_msg)
def test__do_revoke_failure_w_json_error(self):
@@ -1455,7 +1455,7 @@ class BasicCredentialsTests(unittest2.TestCase):
'status': http_client.BAD_REQUEST,
})
content = u'Bad request'
error_msg = 'Invalid response %s.' % (response.status,)
error_msg = 'Invalid response {0}.'.format(response.status)
self._do_retrieve_scopes_test_helper(response, content, error_msg)
def test__do_retrieve_scopes_basic_failure(self):
@@ -1463,7 +1463,7 @@ class BasicCredentialsTests(unittest2.TestCase):
'status': http_client.INTERNAL_SERVER_ERROR,
})
content = u'{}'
error_msg = 'Invalid response %s.' % (response.status,)
error_msg = 'Invalid response {0}.'.format(response.status)
self._do_retrieve_scopes_test_helper(response, content, error_msg)
def test__do_retrieve_scopes_failure_w_json_error(self):
@@ -1824,14 +1824,14 @@ class OAuth2WebServerFlowTest(unittest2.TestCase):
def test_step1_get_device_and_user_codes_non_json_failure(self):
status = int(http_client.BAD_REQUEST)
content = 'Nope not JSON.'
error_msg = 'Invalid response %s.' % (status,)
error_msg = 'Invalid response {0}.'.format(status)
self._step1_get_device_and_user_codes_fail_helper(status, content,
error_msg)
def test_step1_get_device_and_user_codes_basic_failure(self):
status = int(http_client.INTERNAL_SERVER_ERROR)
content = b'{}'
error_msg = 'Invalid response %s.' % (status,)
error_msg = 'Invalid response {0}.'.format(status)
self._step1_get_device_and_user_codes_fail_helper(status, content,
error_msg)
@@ -1839,7 +1839,8 @@ class OAuth2WebServerFlowTest(unittest2.TestCase):
status = int(http_client.BAD_GATEWAY)
base_error = 'ZOMG user codes failure.'
content = json.dumps({'error': base_error})
error_msg = 'Invalid response %s. Error: %s' % (status, base_error)
error_msg = 'Invalid response {0}. Error: {1}'.format(status,
base_error)
self._step1_get_device_and_user_codes_fail_helper(status, content,
error_msg)
@@ -2163,7 +2164,8 @@ class FlowFromCachedClientsecrets(unittest2.TestCase):
filename = object()
cache = object()
err_msg = 'This OAuth 2.0 flow is unsupported: %r' % (client_type,)
err_msg = ('This OAuth 2.0 flow is unsupported: '
'{0!r}'.format(client_type))
with self.assertRaisesRegexp(client.UnknownClientSecretsFlowError,
err_msg):
flow_from_clientsecrets(filename, None, cache=cache)

View File

@@ -40,7 +40,8 @@ class TestClientRedirectServer(unittest2.TestCase):
httpd = tools.ClientRedirectServer(('localhost', 0),
tools.ClientRedirectHandler)
code = 'foo'
url = 'http://localhost:%i?code=%s' % (httpd.server_address[1], code)
url = 'http://localhost:{0}?code={1}'.format(
httpd.server_address[1], code)
t = threading.Thread(target=httpd.handle_request)
t.setDaemon(True)
t.start()