From 0f1d8cb27187353f35c83d99fa0550c8e5ee1863 Mon Sep 17 00:00:00 2001 From: HoneyryderChuck Date: Sat, 24 Jul 2021 01:30:11 +0100 Subject: [PATCH] make Response#to_s non-destructive, and keep the body around for most cases, this didn't make sense, i.e. response bodies were so small, and the user is fine with keeping it all in mem, whereas clearing the string is more confusing. And it breaks pattern matching when matching body multiple times. --- lib/httpx/response.rb | 24 +++++++++++++++++------- test/response_test.rb | 6 ++++++ 2 files changed, 23 insertions(+), 7 deletions(-) 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