response buffer: increase coverage, fix buffer dup when tempfile, simplify == as buffer always responds to read

This commit is contained in:
HoneyryderChuck 2025-09-03 14:56:54 +01:00
parent b42f1ae6b1
commit e98c72e3c5
2 changed files with 37 additions and 17 deletions

View File

@ -29,7 +29,9 @@ module HTTPX
when StringIO
StringIO.new(other.buffer.string, mode: File::RDONLY)
else
other.buffer.class.new(other.buffer.path, encoding: Encoding::BINARY, mode: File::RDONLY)
other.buffer.class.new(other.buffer.path, encoding: Encoding::BINARY, mode: File::RDONLY).tap do |temp|
FileUtils.copy_file(other.buffer.path, temp.path)
end
end
end
@ -75,22 +77,15 @@ module HTTPX
super || begin
return false unless other.is_a?(Response::Buffer)
if @buffer.nil?
other.buffer.nil?
elsif @buffer.respond_to?(:read) &&
other.respond_to?(:read)
buffer_pos = @buffer.pos
other_pos = other.buffer.pos
@buffer.rewind
other.buffer.rewind
begin
FileUtils.compare_stream(@buffer, other.buffer)
ensure
@buffer.pos = buffer_pos
other.buffer.pos = other_pos
end
else
to_s == other.to_s
buffer_pos = @buffer.pos
other_pos = other.buffer.pos
@buffer.rewind
other.buffer.rewind
begin
FileUtils.compare_stream(@buffer, other.buffer)
ensure
@buffer.pos = buffer_pos
other.buffer.pos = other_pos
end
end
end

View File

@ -157,6 +157,31 @@ class ResponseTest < Minitest::Test
assert body.buffer.instance_variable_get(:@buffer).is_a?(Tempfile), "body should buffer to file after going over threshold"
end
def test_response_body_dup
body = Response::Body.new(Response.new(request, 200, "2.0", {}), Options.new(body_threshold_size: 10))
body.extend(Module.new do
attr_reader :buffer
end)
assert body.buffer.nil?, "body should not buffer anything"
body.write("hello")
body_dup = body.dup
body_dup.extend(Module.new do
attr_reader :buffer
end)
assert body.buffer != body_dup.buffer
assert body_dup.buffer.instance_variable_get(:@buffer).is_a?(StringIO), "body should buffer to memory"
assert body_dup.buffer.instance_variable_get(:@buffer).string == "hello", "body should contain original content"
body.write(" world")
body_dup = body.dup
body_dup.extend(Module.new do
attr_reader :buffer
end)
assert body.buffer != body_dup.buffer
assert body.buffer.instance_variable_get(:@buffer).is_a?(Tempfile), "body should buffer to file after going over threshold"
assert File.read(body_dup.buffer.instance_variable_get(:@buffer)) == "hello world", "body should contain original content"
end
def test_response_body_filename
body = Response::Body.new(Response.new(request, 200, "2.0", {}), Options.new)
assert body.filename.nil?