allow to pass a custom body class, which only needs to implement the constructor signature and #<<

This commit is contained in:
HoneyryderChuck 2017-12-11 13:10:58 +00:00
parent 40a73f5a7b
commit 15a5ffffdd
5 changed files with 37 additions and 3 deletions

View File

@ -53,6 +53,7 @@ module HTTPX
:request_class => Class.new(Request),
:response_class => Class.new(Response),
:headers_class => Class.new(Headers),
:response_body_class => Response::Body,
}
defaults.merge!(options)
@ -92,7 +93,7 @@ module HTTPX
%w[
params form json body
proxy follow ssl max_retries
request_class response_class headers_class
request_class response_class headers_class response_body_class
io
].each do |method_name|
def_option(method_name)

View File

@ -16,13 +16,15 @@ module HTTPX
def_delegator :@body, :read
def_delegator :@body, :copy_to
def_delegator :@body, :close
def initialize(request, status, headers, **options)
@options = Options.new(options)
@request = request
@status = Integer(status)
@headers = @options.headers_class.new(headers)
@body = Body.new(self, threshold_size: @options.body_threshold_size)
@body = @options.response_body_class.new(self, threshold_size: @options.body_threshold_size)
end
def <<(data)

View File

@ -150,6 +150,36 @@ class HTTP1Test < Minitest::Spec
io.close if io
end
def test_http_buffer_to_custom
uri = build_uri("/")
custom_body = Class.new do
attr_reader :file
def initialize(response, **)
@file = Tempfile.new
end
def <<(data)
@file << data
end
def close
return unless @file
@file.close
@file.unlink
end
end
response = HTTPX.get(uri, response_body_class: custom_body)
assert response.status == 200, "status is unexpected"
assert response.body.is_a?(custom_body), "body should be from custom type"
file = response.body.file
file.rewind
assert file.size == response.headers["content-length"].to_i, "didn't buffer the whole body"
ensure
response.close if response
end
private
def json_body(response)

View File

@ -75,6 +75,7 @@ class OptionsSpec < Minitest::Test
:request_class => bar.request_class,
:response_class => bar.response_class,
:headers_class => bar.headers_class,
:response_body_class => bar.response_body_class,
}, "options haven't merged correctly"
end

View File

@ -16,7 +16,7 @@ class ResponseTest < Minitest::Test
assert resource.headers.is_a?(Headers), "headers should have been coerced"
end
def test_response_body_concat
def test_response_body_write
assert resource.body.empty?, "body should be empty after init"
resource << "data"
assert resource.body == "data", "body should have been updated"