webmock 3.35.0 → 3.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -62,11 +62,35 @@ if defined?(Curl)
62
62
 
63
63
  module Curl
64
64
  class WebMockCurlEasy < Curl::Easy
65
+ # Curb's native PostField cannot be duplicated. Its public attributes
66
+ # describe the field without running a content callback or opening a file.
67
+ MultipartField = Struct.new(:name, :content, :content_type, :local_file, :remote_file) do
68
+ def self.from(field)
69
+ new(*members.map { |attribute| field.public_send(attribute)&.to_s })
70
+ end
71
+
72
+ def to_s
73
+ return super unless content && !local_file && !remote_file
74
+ Curl::PostField.content(name, content).to_s
75
+ end
76
+
77
+ def initialize_copy(original)
78
+ super
79
+ each_pair { |attribute, value| self[attribute] = value.dup }
80
+ end
81
+ end
82
+ private_constant :MultipartField
83
+
65
84
  def curb_or_webmock
66
85
  request_signature = build_request_signature
67
- WebMock::RequestRegistry.instance.requested_signatures.put(request_signature)
86
+ recorded = signature_for_history(request_signature)
87
+ if request_signature.method == :put && @put_data.respond_to?(:read)
88
+ request_signature = request_signature.with_upload_body(@put_data)
89
+ end
68
90
 
69
- if webmock_response = WebMock::StubRegistry.instance.response_for_request(request_signature)
91
+ webmock_response = WebMock::StubRegistry.instance.response_for_request(
92
+ request_signature, record: recorded)
93
+ if webmock_response
70
94
  build_curb_response(webmock_response)
71
95
  WebMock::CallbackRegistry.invoke_callbacks(
72
96
  {lib: :curb}, request_signature, webmock_response)
@@ -86,6 +110,13 @@ if defined?(Curl)
86
110
  end
87
111
  end
88
112
 
113
+ def signature_for_history(signature)
114
+ body = signature.body
115
+ return signature unless body.is_a?(Curl::PostField) || (body.is_a?(Array) && multipart_form_post?)
116
+ signature.with_body_values { |field| MultipartField.from(field) }
117
+ end
118
+ private :signature_for_history
119
+
89
120
  def build_request_signature
90
121
  method = @webmock_method.to_s.downcase.to_sym
91
122
 
@@ -98,7 +129,11 @@ if defined?(Curl)
98
129
  when :post, :patch
99
130
  self.post_body || @post_body
100
131
  when :put
101
- @put_data
132
+ if @put_data.respond_to?(:read)
133
+ WebMock::Util::UploadBody.read(@put_data, headers)
134
+ else
135
+ @put_data
136
+ end
102
137
  else
103
138
  nil
104
139
  end
@@ -270,10 +305,19 @@ if defined?(Curl)
270
305
  end
271
306
  end
272
307
 
273
- def http_put data = nil
308
+ def http_put(data = nil)
309
+ # put_data= can supply the upcoming request's body until perform resets the method.
310
+ data = @put_data if data.nil? && @webmock_method == :put
274
311
  @webmock_method = :put
275
- @put_data = data if data
276
- super
312
+ @put_data = data
313
+ return super('') if data.nil?
314
+ return super(data) if data.is_a?(String) || data.respond_to?(:read) || multipart_form_post?
315
+
316
+ # Curb joins other positional arguments as it would form fields.
317
+ @put_data = [data].join('&')
318
+ super(@put_data)
319
+ ensure
320
+ @put_data = nil
277
321
  end
278
322
  alias put http_put
279
323
 
@@ -293,10 +337,12 @@ if defined?(Curl)
293
337
  @post_body = nil
294
338
  end
295
339
 
296
- def put_data= data
340
+ def put_data=(data)
341
+ body = data.respond_to?(:read) ? data : data&.to_s
342
+ super(body)
297
343
  @webmock_method = :put
298
- @put_data = data
299
- super
344
+ @put_data = body
345
+ data
300
346
  end
301
347
 
302
348
  def post_body= data
@@ -359,6 +405,8 @@ if defined?(Curl)
359
405
  end
360
406
 
361
407
  def reset
408
+ @put_data = nil
409
+ reset_webmock_method
362
410
  instance_variable_set(:@body_str, nil)
363
411
  instance_variable_set(:@content_type, nil)
364
412
  instance_variable_set(:@header_str, nil)
@@ -107,8 +107,6 @@ if defined?(EventMachine::HttpClient)
107
107
  end
108
108
 
109
109
  def send_request(head, body)
110
- WebMock::RequestRegistry.instance.requested_signatures.put(request_signature)
111
-
112
110
  if stubbed_webmock_response
113
111
  WebMock::CallbackRegistry.invoke_callbacks({lib: :em_http_request}, request_signature, stubbed_webmock_response)
114
112
  @uri ||= nil
@@ -144,7 +142,13 @@ if defined?(EventMachine::HttpClient)
144
142
 
145
143
  def stubbed_webmock_response
146
144
  unless defined?(@stubbed_webmock_response)
147
- @stubbed_webmock_response = WebMock::StubRegistry.instance.response_for_request(request_signature)
145
+ signature = request_signature
146
+ recorded = if signature.body.respond_to?(:read) && signature.body.respond_to?(:eof?)
147
+ signature.with_body_values { |stream| WebMock::Util::UploadBody.read(stream, signature.headers) }
148
+ else
149
+ signature
150
+ end
151
+ @stubbed_webmock_response = WebMock::StubRegistry.instance.response_for_request(signature, record: recorded)
148
152
  end
149
153
 
150
154
  @stubbed_webmock_response
@@ -53,7 +53,7 @@ if defined?(Excon)
53
53
 
54
54
  def self.handle_request(params)
55
55
  mock_request = self.build_request params.dup
56
- WebMock::RequestRegistry.instance.requested_signatures.put(mock_request)
56
+ WebMock::RequestRegistry.instance.put(mock_request)
57
57
 
58
58
  if mock_response = WebMock::StubRegistry.instance.response_for_request(mock_request)
59
59
  self.perform_callbacks(mock_request, mock_response, real_request: false)
@@ -29,7 +29,7 @@ module HTTP
29
29
  end
30
30
 
31
31
  def register_request(signature)
32
- ::WebMock::RequestRegistry.instance.requested_signatures.put(signature)
32
+ ::WebMock::RequestRegistry.instance.put(signature)
33
33
  end
34
34
 
35
35
  def replay
@@ -9,6 +9,7 @@ rescue LoadError
9
9
  end
10
10
 
11
11
  if defined?(::HTTPClient)
12
+ require 'delegate'
12
13
 
13
14
  module WebMock
14
15
  module HttpLibAdapters
@@ -45,84 +46,107 @@ if defined?(::HTTPClient)
45
46
  end
46
47
 
47
48
  module WebMockHTTPClients
48
- WEBMOCK_HTTPCLIENT_RESPONSES = :webmock_httpclient_responses
49
- WEBMOCK_HTTPCLIENT_REQUEST_SIGNATURES = :webmock_httpclient_request_signatures
50
-
51
- REQUEST_RESPONSE_LOCK = Mutex.new
49
+ # HTTPClient publishes headers before it writes the body to the caller's
50
+ # pipe. Capture the chunks upstream so callbacks never read from that pipe.
51
+ class RecordingSession < SimpleDelegator
52
+ def initialize(session, body)
53
+ super(session)
54
+ @body = body
55
+ end
52
56
 
53
- def do_get_block(req, proxy, conn, &block)
54
- do_get(req, proxy, conn, false, &block)
57
+ def get_body
58
+ __getobj__.get_body do |chunk|
59
+ @body << chunk.b
60
+ yield chunk
61
+ end
62
+ end
55
63
  end
56
64
 
57
- def do_get_stream(req, proxy, conn, &block)
58
- do_get(req, proxy, conn, true, &block)
65
+ class RecordingSessionManager < Struct.new(:manager, :body)
66
+ def query(req, proxy)
67
+ RecordingSession.new(manager.query(req, proxy), body)
68
+ end
69
+
70
+ def keep(session)
71
+ manager.keep(session.__getobj__)
72
+ end
59
73
  end
60
74
 
61
- def do_get(req, proxy, conn, stream = false, &block)
62
- clear_thread_variables unless conn.async_thread
75
+ class RecordingConnection
76
+ attr_reader :response, :body
63
77
 
64
- request_signature = build_request_signature(req, :reuse_existing)
78
+ def initialize(connection)
79
+ @connection = connection
80
+ @body = ''.b
81
+ end
65
82
 
66
- WebMock::RequestRegistry.instance.requested_signatures.put(request_signature)
83
+ def push(response)
84
+ @response = response
85
+ # HTTPClient's loopback responses bypass the session entirely.
86
+ @body.replace(response.content.string) if response.content.is_a?(StringIO)
87
+ @connection.push(response)
88
+ end
89
+ end
67
90
 
68
- if webmock_responses[request_signature]
69
- webmock_response = webmock_responses.delete(request_signature)
70
- response = build_httpclient_response(webmock_response, stream, req.header, &block)
71
- @request_filter.each do |filter|
72
- filter.filter_response(req, response)
73
- end
91
+ class ResponseFilter < Struct.new(:filter)
92
+ def filter_request(_req)
93
+ end
94
+
95
+ def filter_response(req, response)
96
+ filter.filter_response(req, response)
97
+ end
98
+ end
99
+ private_constant :RecordingConnection, :RecordingSessionManager, :RecordingSession, :ResponseFilter
100
+
101
+ def do_get_block(req, proxy, conn, &block)
102
+ filters = apply_request_filters(req, proxy)
103
+ request_signature = build_request_signature(req)
104
+ WebMock::RequestRegistry.instance.put(request_signature)
105
+ webmock_response = WebMock::StubRegistry.instance.response_for_request(request_signature)
106
+ if webmock_response
107
+ response = build_httpclient_response(webmock_response, false, req.header, &block)
108
+ filters.each { |filter| filter.filter_response(req, response) }
74
109
  res = conn.push(response)
75
110
  WebMock::CallbackRegistry.invoke_callbacks(
76
111
  {lib: :httpclient}, request_signature, webmock_response)
77
112
  res
78
113
  elsif WebMock.net_connect_allowed?(request_signature.uri)
79
- # in case there is a nil entry in the hash...
80
- webmock_responses.delete(request_signature)
81
-
82
- res = if stream
83
- do_get_stream_without_webmock(req, proxy, conn, &block)
84
- elsif block
85
- body = ''
86
- do_get_block_without_webmock(req, proxy, conn) do |http_res, chunk|
87
- if chunk && chunk.bytesize > 0
88
- body += chunk
89
- block.call(http_res, chunk)
90
- end
91
- end
92
- else
93
- do_get_block_without_webmock(req, proxy, conn)
94
- end
95
- res = conn.pop
96
- conn.push(res)
97
- if WebMock::CallbackRegistry.any_callbacks?
98
- webmock_response = build_webmock_response(res, body)
99
- WebMock::CallbackRegistry.invoke_callbacks(
100
- {lib: :httpclient, real_request: true}, request_signature,
101
- webmock_response)
102
- end
103
- res
114
+ clone(freeze: false).send_prepared_sync_request(req, proxy, conn, filters, request_signature, &block)
104
115
  else
105
116
  raise WebMock::NetConnectNotAllowedError.new(request_signature)
106
117
  end
107
118
  end
108
119
 
109
120
  def do_request_async(method, uri, query, body, extheader)
110
- clear_thread_variables
111
121
  req = create_request(method, uri, query, body, extheader)
122
+ proxy = no_proxy?(uri) ? nil : @proxy
123
+ filters = apply_request_filters(req, proxy)
112
124
  request_signature = build_request_signature(req)
113
- webmock_request_signatures << request_signature
125
+ WebMock::RequestRegistry.instance.put(request_signature)
114
126
 
115
- if webmock_responses[request_signature]
116
- webmock_response = webmock_responses.delete(request_signature)
117
- async_conn_for_stubbed_request(req, request_signature, webmock_response)
118
- elsif WebMock.net_connect_allowed?(request_signature.uri)
119
- conn = super
120
- conn.async_thread[WEBMOCK_HTTPCLIENT_REQUEST_SIGNATURES] = Thread.current[WEBMOCK_HTTPCLIENT_REQUEST_SIGNATURES]
121
- conn.async_thread[WEBMOCK_HTTPCLIENT_RESPONSES] = Thread.current[WEBMOCK_HTTPCLIENT_RESPONSES]
122
- conn
123
- else
127
+ webmock_response = WebMock::StubRegistry.instance.response_for_request(request_signature)
128
+ unless webmock_response || WebMock.net_connect_allowed?(request_signature.uri)
124
129
  raise WebMock::NetConnectNotAllowedError.new(request_signature)
125
130
  end
131
+
132
+ # Keep the prepared request, including any headers its filters assigned.
133
+ # HTTPClient's do_request_async would create a second request in the worker.
134
+ conn = ::HTTPClient::Connection.new
135
+ conn.async_thread = Thread.new do
136
+ begin
137
+ if webmock_response
138
+ response = build_httpclient_response(webmock_response, true, req.header)
139
+ filters.each { |filter| filter.filter_response(req, response) }
140
+ conn.push(response)
141
+ WebMock::CallbackRegistry.invoke_callbacks({lib: :httpclient}, request_signature, webmock_response)
142
+ else
143
+ clone(freeze: false).send_prepared_async_request(req, proxy, conn, filters, request_signature)
144
+ end
145
+ rescue Exception => e
146
+ conn.push e
147
+ end
148
+ end
149
+ conn
126
150
  end
127
151
 
128
152
  def build_httpclient_response(webmock_response, stream = false, req_header = nil, &block)
@@ -167,13 +191,13 @@ if defined?(::HTTPClient)
167
191
  webmock_response
168
192
  end
169
193
 
170
- def build_request_signature(req, reuse_existing = false)
171
- @request_filter.each do |filter|
172
- filter.filter_request(req)
173
- end
174
-
194
+ def build_request_signature(req)
175
195
  uri = WebMock::Util::URI.heuristic_parse(req.header.request_uri.to_s)
176
- uri.query = WebMock::Util::QueryMapper.values_to_query(req.header.request_query, notation: WebMock::Config.instance.query_values_notation) if req.header.request_query
196
+ if req.header.request_query
197
+ # HTTPClient sends the query argument after the query in the URI
198
+ query = WebMock::Util::QueryMapper.values_to_query(req.header.request_query, notation: WebMock::Config.instance.query_values_notation)
199
+ uri.query = [uri.query, query].reject { |part| part.to_s.empty? }.join('&')
200
+ end
177
201
  uri.port = req.header.request_uri.port
178
202
 
179
203
  headers = req.header.all.inject({}) do |hdrs, header|
@@ -183,38 +207,65 @@ if defined?(::HTTPClient)
183
207
  end
184
208
  headers = headers_from_session(uri).merge(headers)
185
209
 
186
- signature = WebMock::RequestSignature.new(
210
+ WebMock::RequestSignature.new(
187
211
  req.header.request_method.downcase.to_sym,
188
212
  uri.to_s,
189
213
  body: req.http_body.dump,
190
214
  headers: headers
191
215
  )
192
-
193
- # reuse a previous identical signature object if we stored one for later use
194
- if reuse_existing && previous_signature = previous_signature_for(signature)
195
- return previous_signature
196
- end
197
-
198
- signature
199
216
  end
200
217
 
201
- def webmock_responses
202
- Thread.current[WEBMOCK_HTTPCLIENT_RESPONSES] ||= Hash.new do |hash, request_signature|
203
- hash[request_signature] = WebMock::StubRegistry.instance.response_for_request(request_signature)
218
+ protected
219
+
220
+ # Only the per-request copy changes its filter list. It shares the client's
221
+ # sessions and lets HTTPClient run the response filters at the normal time.
222
+ def send_prepared_sync_request(req, proxy, conn, filters, request_signature, &block)
223
+ @request_filter = filters.map { |filter| ResponseFilter.new(filter) }
224
+ if block
225
+ body = ''
226
+ do_get_block_without_webmock(req, proxy, conn) do |http_res, chunk|
227
+ if chunk && chunk.bytesize > 0
228
+ body += chunk
229
+ block.call(http_res, chunk)
230
+ end
231
+ end
232
+ else
233
+ do_get_block_without_webmock(req, proxy, conn)
204
234
  end
235
+ res = conn.pop
236
+ conn.push(res)
237
+ if WebMock::CallbackRegistry.any_callbacks?
238
+ webmock_response = build_webmock_response(res, body)
239
+ WebMock::CallbackRegistry.invoke_callbacks(
240
+ {lib: :httpclient, real_request: true}, request_signature,
241
+ webmock_response)
242
+ end
243
+ res
205
244
  end
206
245
 
207
- def webmock_request_signatures
208
- Thread.current[WEBMOCK_HTTPCLIENT_REQUEST_SIGNATURES] ||= []
209
- end
246
+ def send_prepared_async_request(req, proxy, conn, filters, request_signature)
247
+ @request_filter = filters.map { |filter| ResponseFilter.new(filter) }
248
+ if WebMock::CallbackRegistry.any_callbacks?
249
+ recorder = RecordingConnection.new(conn)
250
+ @session_manager = RecordingSessionManager.new(@session_manager, recorder.body)
251
+ end
210
252
 
211
- def previous_signature_for(signature)
212
- return nil unless index = webmock_request_signatures.index(signature)
213
- webmock_request_signatures.delete_at(index)
253
+ protect_keep_alive_disconnected { do_get_stream(req, proxy, recorder || conn) }
254
+ if recorder
255
+ response = build_webmock_response(recorder.response, recorder.body)
256
+ WebMock::CallbackRegistry.invoke_callbacks({lib: :httpclient, real_request: true}, request_signature, response)
257
+ end
214
258
  end
215
259
 
216
260
  private
217
261
 
262
+ def apply_request_filters(req, proxy)
263
+ # Recent HTTPClient versions select the applicable proxy filters here.
264
+ return filter_request(req, proxy) if respond_to?(:filter_request, true)
265
+
266
+ @request_filter.each { |filter| filter.filter_request(req) }
267
+ end
268
+
218
269
  # some of the headers sent by HTTPClient are derived from
219
270
  # the client session
220
271
  def headers_from_session(uri)
@@ -225,40 +276,10 @@ if defined?(::HTTPClient)
225
276
  hdrs
226
277
  end
227
278
  end
228
-
229
- def clear_thread_variables
230
- Thread.current[WEBMOCK_HTTPCLIENT_REQUEST_SIGNATURES] = nil
231
- Thread.current[WEBMOCK_HTTPCLIENT_RESPONSES] = nil
232
- end
233
-
234
- # The async thread must not go through do_get, which would rebuild the request signature.
235
- # Rebuilding calls headers_from_session again, and the session sets a Date header with
236
- # 1 second resolution, so a signature built later can differ from the one the response was
237
- # cached under, which makes the thread evaluate the stub registry again and consume
238
- # an extra response from the stub sequence. The thread only delivers what the caller
239
- # already evaluated, mirroring do_get's stubbed branch.
240
- def async_conn_for_stubbed_request(req, request_signature, webmock_response)
241
- conn = HTTPClient::Connection.new
242
- conn.async_thread = Thread.new do
243
- begin
244
- WebMock::RequestRegistry.instance.requested_signatures.put(request_signature)
245
- response = build_httpclient_response(webmock_response, true, req.header)
246
- @request_filter.each do |filter|
247
- filter.filter_response(req, response)
248
- end
249
- conn.push(response)
250
- WebMock::CallbackRegistry.invoke_callbacks({lib: :httpclient}, request_signature, webmock_response)
251
- rescue Exception => e
252
- conn.push e
253
- end
254
- end
255
- conn
256
- end
257
279
  end
258
280
 
259
281
  class WebMockHTTPClient < HTTPClient
260
282
  alias_method :do_get_block_without_webmock, :do_get_block
261
- alias_method :do_get_stream_without_webmock, :do_get_stream
262
283
 
263
284
  include WebMockHTTPClients
264
285
  end
@@ -266,7 +287,6 @@ if defined?(::HTTPClient)
266
287
  if defined? ::JSONClient
267
288
  class WebMockJSONClient < JSONClient
268
289
  alias_method :do_get_block_without_webmock, :do_get_block
269
- alias_method :do_get_stream_without_webmock, :do_get_stream
270
290
 
271
291
  include WebMockHTTPClients
272
292
  end
@@ -54,7 +54,7 @@ if defined?(Manticore)
54
54
 
55
55
  def response_object_for(request, context, &block)
56
56
  request_signature = generate_webmock_request_signature(request, context)
57
- WebMock::RequestRegistry.instance.requested_signatures.put(request_signature)
57
+ WebMock::RequestRegistry.instance.put(request_signature)
58
58
 
59
59
  if webmock_response = registered_response_for(request_signature)
60
60
  webmock_response.raise_error_if_any
@@ -100,7 +100,7 @@ module WebMock
100
100
 
101
101
  request_signature = WebMock::NetHTTPUtility.request_signature_from_request(self, request, body)
102
102
 
103
- WebMock::RequestRegistry.instance.requested_signatures.put(request_signature)
103
+ WebMock::RequestRegistry.instance.put(request_signature)
104
104
 
105
105
  if webmock_response = WebMock::StubRegistry.instance.response_for_request(request_signature)
106
106
  # Close the real connection left by an earlier request, if any.
@@ -118,6 +118,8 @@ module WebMock
118
118
  {lib: :net_http, real_request: true}, request_signature, webmock_response)
119
119
  end
120
120
  response.extend Net::WebMockHTTPResponse
121
+ # Net::HTTP has read the body and applied its encoding already
122
+ response.instance_variable_set(:@__body_encoding_applied, true)
121
123
  block.call response if block
122
124
  response
123
125
  end
@@ -181,7 +183,9 @@ module WebMock
181
183
  body = webmock_response.body
182
184
  body = nil if webmock_response.status[0].to_s == '204'
183
185
 
184
- response.instance_variable_set(:@body, body)
186
+ # A copy, so that changing the response body, for example its
187
+ # encoding, does not change the stubbed body
188
+ response.instance_variable_set(:@body, body&.dup)
185
189
  webmock_response.headers.to_a.each do |name, values|
186
190
  values = [values] unless values.is_a?(Array)
187
191
  values.each do |value|
@@ -192,6 +196,7 @@ module WebMock
192
196
  response.instance_variable_set(:@read, true)
193
197
 
194
198
  response.uri = request_uri
199
+ response.body_encoding = response_body_encoding if respond_to?(:response_body_encoding)
195
200
 
196
201
  response.extend Net::WebMockHTTPResponse
197
202
 
@@ -202,6 +207,7 @@ module WebMock
202
207
  webmock_response.raise_error_if_any
203
208
 
204
209
  yield response if block_given?
210
+ response.send(:webmock_apply_body_encoding)
205
211
 
206
212
  response
207
213
  end
@@ -289,6 +295,8 @@ module WebMock
289
295
  end
290
296
 
291
297
  path = WebMock::Util::URI.heuristic_parse(path).request_uri if path =~ /^http/
298
+ # OPTIONS * (asterisk form) has no path; a URI can only hold it as /*
299
+ path = "/*" if path == "*" && request.method == "OPTIONS"
292
300
 
293
301
  uri = get_uri(net_http, path)
294
302
  method = request.method.downcase.to_sym
@@ -20,17 +20,43 @@ module Net
20
20
  if !(defined?(@__read_body_previously_called).nil?) && @__read_body_previously_called
21
21
  return super
22
22
  end
23
- return @body if dest.nil? && block.nil?
23
+ if dest.nil? && block.nil?
24
+ webmock_apply_body_encoding
25
+ return @body
26
+ end
24
27
  raise ArgumentError.new("both arg and block given for HTTP method") if dest && block
25
28
  return nil if @body.nil?
26
29
 
27
30
  dest ||= ::Net::ReadAdapter.new(block)
28
- dest << @body.dup
31
+ dest << @body
29
32
  @body = dest
33
+ webmock_apply_body_encoding
34
+ @body
30
35
  ensure
31
36
  # allow subsequent calls to #read_body to proceed as normal, without our hack...
32
37
  @__read_body_previously_called = true
33
38
  end
39
+
40
+ private
41
+
42
+ # Net::HTTPResponse#read_body applies the encoding set with #body_encoding=
43
+ # (or Net::HTTP#response_body_encoding=) once, to the body it reads, which
44
+ # happens in the request block or right after it. A stubbed body is set
45
+ # without reading, so apply the encoding the first time the body is read
46
+ # or when the request block returns, and ignore later changes to it.
47
+ def webmock_apply_body_encoding
48
+ return if defined?(@__body_encoding_applied) && @__body_encoding_applied
49
+ @__body_encoding_applied = true
50
+
51
+ encoding = defined?(@body_encoding) && @body_encoding
52
+ # A frozen body was assigned in the request block, which Net::HTTP
53
+ # would replace with the body it reads, so leave it as it is
54
+ return unless encoding && @body.is_a?(String) && !@body.frozen?
55
+
56
+ # Net::HTTP detects the encoding from the bytes it read
57
+ encoding = detect_encoding(@body.b) unless encoding.is_a?(Encoding)
58
+ @body.force_encoding(encoding) if encoding
59
+ end
34
60
  end
35
61
  end
36
62
 
@@ -43,11 +43,11 @@ if defined?(::Patron::Session)
43
43
  return super unless block
44
44
 
45
45
  req = build_request(action, url, headers, **options)
46
- request_signature, webmock_response = PatronAdapter.register_request(req)
46
+ request_signature, webmock_response, recorded_body = PatronAdapter.register_request(req)
47
47
 
48
48
  if webmock_response
49
49
  PatronAdapter.stream_stubbed_response(webmock_response, request_signature,
50
- default_response_charset, &block)
50
+ default_response_charset, recorded_body.to_s.bytesize, &block)
51
51
  else
52
52
  # Callbacks run once the head has arrived, so they also run
53
53
  # when the block leaves before the end of the body
@@ -181,13 +181,28 @@ if defined?(::Patron::Session)
181
181
  uri.path = uri.normalized_path.gsub("[^:]//","/")
182
182
 
183
183
  if [:put, :post, :patch].include?(req.action)
184
- if req.file_name
185
- if !File.exist?(req.file_name) || !File.readable?(req.file_name)
184
+ data = req.upload_data
185
+ path = req.file_name || (data.to_path if data.respond_to?(:to_path))
186
+ if path
187
+ if !File.exist?(path) || !File.readable?(path)
186
188
  raise ArgumentError.new("Unable to open specified file.")
187
189
  end
188
- request_body = File.read(req.file_name)
189
- elsif req.upload_data
190
- request_body = req.upload_data
190
+ request_body = if !File.file?(path)
191
+ # Leave a named pipe or device for Patron to open.
192
+ path.to_s
193
+ elsif req.file_name
194
+ # Keep the encoding used by existing post_file and put_file stubs.
195
+ File.read(path)
196
+ else
197
+ File.binread(path)
198
+ end
199
+ elsif data.respond_to?(:read) && OriginalPatronSession.public_method_defined?(:stream)
200
+ # Patron 1.1 added streaming uploads and Session#stream together.
201
+ request_body = WebMock::Util::UploadBody.read(data, req.headers)
202
+ elsif data
203
+ # A multipart post keeps its form fields as a Hash. The copy
204
+ # lets stubs and callbacks still receive the caller's Hash.
205
+ request_body = data.is_a?(Hash) ? data.dup : data.to_s
191
206
  else
192
207
  raise ArgumentError.new("Must provide either data or a filename when doing a PUT or POST")
193
208
  end
@@ -240,15 +255,19 @@ if defined?(::Patron::Session)
240
255
  # Records the request and returns its signature with the stubbed
241
256
  # response, which is nil when a real request is allowed
242
257
  def self.register_request(req)
243
- request_signature = build_request_signature(req)
244
- WebMock::RequestRegistry.instance.requested_signatures.put(request_signature)
258
+ recorded = build_request_signature(req)
259
+ request_signature = recorded
260
+ if recorded.body && !req.file_name && req.upload_data && !req.upload_data.equal?(recorded.body)
261
+ request_signature = recorded.with_upload_body(req.upload_data)
262
+ end
245
263
 
246
- webmock_response = WebMock::StubRegistry.instance.response_for_request(request_signature)
264
+ webmock_response = WebMock::StubRegistry.instance.response_for_request(
265
+ request_signature, record: recorded)
247
266
  if webmock_response.nil? && !WebMock.net_connect_allowed?(request_signature.uri)
248
267
  raise WebMock::NetConnectNotAllowedError.new(request_signature)
249
268
  end
250
269
 
251
- [request_signature, webmock_response]
270
+ [request_signature, webmock_response, recorded.body]
252
271
  end
253
272
 
254
273
  def self.invoke_callbacks(request_signature, webmock_response)
@@ -266,7 +285,7 @@ if defined?(::Patron::Session)
266
285
 
267
286
  # Callbacks run before the block, so they also run when it leaves
268
287
  # before the end of the body
269
- def self.stream_stubbed_response(webmock_response, request_signature, default_response_charset)
288
+ def self.stream_stubbed_response(webmock_response, request_signature, default_response_charset, uploaded_bytes)
270
289
  head = build_patron_response(webmock_response, default_response_charset, with_body: false)
271
290
  invoke_callbacks(request_signature, webmock_response)
272
291
  # Kept out of the stream, so the stream has only the methods of
@@ -285,7 +304,7 @@ if defined?(::Patron::Session)
285
304
  redirect_count: head.redirect_count,
286
305
  header_data: build_header_data(webmock_response),
287
306
  downloaded_bytes: body.pos,
288
- uploaded_bytes: request_signature.body.to_s.bytesize,
307
+ uploaded_bytes: uploaded_bytes,
289
308
  timings: {},
290
309
  complete: body.eof?,
291
310
  default_charset: default_response_charset