Tighten use of form-encoding to only cases where a JSON body is not ever allowed

This commit is contained in:
Steve Bazyl 2016-09-08 13:40:30 -07:00
parent 6089c866ac
commit e13da8e05e
3 changed files with 20 additions and 4 deletions

View File

@ -105,6 +105,10 @@ module Google
end
end
def allow_form_encoding?
request_representation.nil? && super
end
private
# Attempt to parse a JSON error message, returning the first found error

View File

@ -146,7 +146,7 @@ module Google
self.url = url.expand(params) if url.is_a?(Addressable::Template)
url.query_values = query.merge(url.query_values || {})
if [:post, :put].include?(method) && body.nil?
if allow_form_encoding?
@form_encoded = true
self.body = Addressable::URI.form_encode(url.query_values(Array))
self.header['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
@ -306,6 +306,10 @@ module Google
req.options.open_timeout = options.open_timeout_sec
end
def allow_form_encoding?
[:post, :put].include?(method) && body.nil?
end
private
def form_encoded?

View File

@ -17,7 +17,7 @@ require 'google/apis/core/api_command'
require 'google/apis/core/json_representation'
require 'hurley/test'
RSpec.describe Google::Apis::Core::HttpCommand do
RSpec.describe Google::Apis::Core::ApiCommand do
include TestHelpers
include_context 'HTTP client'
@ -40,20 +40,28 @@ RSpec.describe Google::Apis::Core::HttpCommand do
command = Google::Apis::Core::ApiCommand.new(:post, 'https://www.googleapis.com/zoo/animals')
command.request_representation = representer_class
command.request_object = request
command.query['a'] = 'b'
command
end
before(:example) do
stub_request(:post, 'https://www.googleapis.com/zoo/animals')
stub_request(:post, 'https://www.googleapis.com/zoo/animals?a=b')
.to_return(headers: { 'Content-Type' => 'application/json' }, body: %({}))
end
it 'should serialize the request object' do
command.execute(client)
expect(a_request(:post, 'https://www.googleapis.com/zoo/animals').with do |req|
expect(a_request(:post, 'https://www.googleapis.com/zoo/animals?a=b').with do |req|
be_json_eql(%({"value":"hello"})).matches?(req.body)
end).to have_been_made
end
it 'should not form encode query parameters when body expected but nil' do
command.query['a'] = 'b'
command.request_object = nil
command.execute(client)
expect(a_request(:post, 'https://www.googleapis.com/zoo/animals?a=b').with(body: nil)).to have_been_made
end
end
context('with a JSON response') do