diff --git a/lib/httpx/response.rb b/lib/httpx/response.rb index e30ba8fa..e4f0891e 100644 --- a/lib/httpx/response.rb +++ b/lib/httpx/response.rb @@ -134,18 +134,28 @@ module HTTPX end def to_s - rewind - if @buffer + case @buffer + when StringIO + begin + @buffer.string.force_encoding(@encoding) + rescue ArgumentError + @buffer.string + end + when Tempfile, File + rewind content = @buffer.read begin - return content.force_encoding(@encoding) + content.force_encoding(@encoding) rescue ArgumentError # ex: unknown encoding name - utf - return content + content + ensure + close end + when nil + "".b + else + @buffer end - "".b - ensure - close end alias_method :to_str, :to_s diff --git a/test/response_test.rb b/test/response_test.rb index b7c042ef..ea974cbf 100644 --- a/test/response_test.rb +++ b/test/response_test.rb @@ -43,6 +43,7 @@ class ResponseTest < Minitest::Test def test_response_body_to_s body1 = Response::Body.new(Response.new(request, 200, "2.0", {}), Options.new(body_threshold_size: 1024)) + assert body1 == "", "body should be empty" assert body1.empty?, "body must be empty after initialization" body1.write("foo") assert body1 == "foo", "body must be updated" @@ -62,6 +63,11 @@ class ResponseTest < Minitest::Test body4.write(text) req_text = body4.to_s assert text == req_text, "request body must be in original encoding (#{req_text})" + + payload = "a" * 2048 + body5 = Response::Body.new(Response.new(request, 200, "2.0", {}), Options.new(body_threshold_size: 1024)) + body5.write(payload) + assert body5 == "a" * 2048, "body messed up with file" end def test_response_body_copy_to_memory