Use retry_with_error in GCECredentials#fetch_access_token

This commit is contained in:
Kazuhiro Serizawa 2017-02-25 21:45:07 +09:00
parent 3014e6ddaf
commit a1a9387c2b
2 changed files with 27 additions and 10 deletions

View File

@ -88,16 +88,19 @@ END
def fetch_access_token(options = {}) def fetch_access_token(options = {})
c = options[:connection] || Faraday.default_connection c = options[:connection] || Faraday.default_connection
c.headers = { 'Metadata-Flavor' => 'Google' } c.headers = { 'Metadata-Flavor' => 'Google' }
resp = c.get(COMPUTE_AUTH_TOKEN_URI)
case resp.status retry_with_error do
when 200 resp = c.get(COMPUTE_AUTH_TOKEN_URI)
Signet::OAuth2.parse_credentials(resp.body, case resp.status
resp.headers['content-type']) when 200
when 404 Signet::OAuth2.parse_credentials(resp.body,
raise(Signet::AuthorizationError, NO_METADATA_SERVER_ERROR) resp.headers['content-type'])
else when 404
msg = "Unexpected error code #{resp.status}" + UNEXPECTED_ERROR_SUFFIX raise(Signet::AuthorizationError, NO_METADATA_SERVER_ERROR)
raise(Signet::AuthorizationError, msg) else
msg = "Unexpected error code #{resp.status}" + UNEXPECTED_ERROR_SUFFIX
raise(Signet::AuthorizationError, msg)
end
end end
end end
end end

View File

@ -77,6 +77,20 @@ describe Google::Auth::GCECredentials do
.to raise_error Signet::AuthorizationError .to raise_error Signet::AuthorizationError
expect(stub).to have_been_requested expect(stub).to have_been_requested
end end
it 'should fail with Signet::AuthorizationError if request times out' do
allow_any_instance_of(Faraday::Connection).to receive(:get)
.and_raise(Faraday::TimeoutError)
expect { @client.fetch_access_token! }
.to raise_error Signet::AuthorizationError
end
it 'should fail with Signet::AuthorizationError if request fails' do
allow_any_instance_of(Faraday::Connection).to receive(:get)
.and_raise(Faraday::ConnectionFailed, nil)
expect { @client.fetch_access_token! }
.to raise_error Signet::AuthorizationError
end
end end
end end