Skip to content

Commit e5be1a6

Browse files
patrickjabergkoic
andcommitted
Fix FrozenError in Typhoeus streaming response body
When stubbing a response for the Typhoeus adapter, and the Typhoeus request has an `on_body` callback, a `FrozenError` exception is raised when attempting to concatenate the current chunk of the response to the existing response body (i.e. `response.body << chunk`). FWIW, my use case for this is to abort a request as early as possible when the response body exceeds a given size, specifically when the response doesn't have a `Content-Length` header. The example below illustrates the issue: ```ruby require "bundler/inline" gemfile do source "https://rubygems.org" gem "typhoeus", "1.4.1" gem "webmock", "3.24.0" end WebMock.enable! WebMock.stub_request(:get, "https://example.com").to_return(status: "200", body: "body") request = Typhoeus::Request.new("https://example.com") request.on_body do |chunk, response| response.body << chunk end request.run ``` This change initializes the Typhoeus response body to a non-frozen, mutable string when using the `on_body` callback. Use String#dup to maintain encoding per feedback Co-authored-by: Koichi ITO <koic.ito@gmail.com>
1 parent 5c99e1a commit e5be1a6

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

lib/webmock/http_lib_adapters/typhoeus_hydra_adapter.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ def self.request_hash(request_signature)
172172
request.execute_headers_callbacks(response)
173173
end
174174
if request.respond_to?(:streaming?) && request.streaming?
175-
response.options[:response_body] = ""
175+
response.options[:response_body] = "".dup
176176
request.on_body.each { |callback| callback.call(webmock_response.body, response) }
177177
end
178178
request.finish(response)

spec/acceptance/typhoeus/typhoeus_hydra_spec.rb

+13
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,19 @@
125125
expect(test_complete).to eq("")
126126
end
127127

128+
it "should initialize the streaming response body with a mutible (non-frozen) string" do
129+
skip("This test requires a newer version of Typhoeus") unless @request.respond_to?(:on_body)
130+
131+
stub_request(:any, "example.com").to_return(body: "body")
132+
133+
@request.on_body do |body_chunk, response|
134+
response.body << body_chunk
135+
end
136+
hydra.queue @request
137+
138+
expect{ hydra.run }.not_to raise_error
139+
end
140+
128141
it "should call on_headers with 2xx response" do
129142
body = "on_headers fired"
130143
stub_request(:any, "example.com").to_return(body: body, headers: {'X-Test' => '1'})

0 commit comments

Comments
 (0)