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.
This commit is contained in:
HoneyryderChuck 2021-07-24 01:30:11 +01:00
parent 74013fc2a7
commit 0f1d8cb271
2 changed files with 23 additions and 7 deletions

View File

@ -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

View File

@ -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