webmock 3.36.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.
@@ -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,11 +191,7 @@ 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
196
  if req.header.request_query
177
197
  # HTTPClient sends the query argument after the query in the URI
@@ -187,38 +207,65 @@ if defined?(::HTTPClient)
187
207
  end
188
208
  headers = headers_from_session(uri).merge(headers)
189
209
 
190
- signature = WebMock::RequestSignature.new(
210
+ WebMock::RequestSignature.new(
191
211
  req.header.request_method.downcase.to_sym,
192
212
  uri.to_s,
193
213
  body: req.http_body.dump,
194
214
  headers: headers
195
215
  )
196
-
197
- # reuse a previous identical signature object if we stored one for later use
198
- if reuse_existing && previous_signature = previous_signature_for(signature)
199
- return previous_signature
200
- end
201
-
202
- signature
203
216
  end
204
217
 
205
- def webmock_responses
206
- Thread.current[WEBMOCK_HTTPCLIENT_RESPONSES] ||= Hash.new do |hash, request_signature|
207
- 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)
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)
208
242
  end
243
+ res
209
244
  end
210
245
 
211
- def webmock_request_signatures
212
- Thread.current[WEBMOCK_HTTPCLIENT_REQUEST_SIGNATURES] ||= []
213
- 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
214
252
 
215
- def previous_signature_for(signature)
216
- return nil unless index = webmock_request_signatures.index(signature)
217
- 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
218
258
  end
219
259
 
220
260
  private
221
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
+
222
269
  # some of the headers sent by HTTPClient are derived from
223
270
  # the client session
224
271
  def headers_from_session(uri)
@@ -229,40 +276,10 @@ if defined?(::HTTPClient)
229
276
  hdrs
230
277
  end
231
278
  end
232
-
233
- def clear_thread_variables
234
- Thread.current[WEBMOCK_HTTPCLIENT_REQUEST_SIGNATURES] = nil
235
- Thread.current[WEBMOCK_HTTPCLIENT_RESPONSES] = nil
236
- end
237
-
238
- # The async thread must not go through do_get, which would rebuild the request signature.
239
- # Rebuilding calls headers_from_session again, and the session sets a Date header with
240
- # 1 second resolution, so a signature built later can differ from the one the response was
241
- # cached under, which makes the thread evaluate the stub registry again and consume
242
- # an extra response from the stub sequence. The thread only delivers what the caller
243
- # already evaluated, mirroring do_get's stubbed branch.
244
- def async_conn_for_stubbed_request(req, request_signature, webmock_response)
245
- conn = HTTPClient::Connection.new
246
- conn.async_thread = Thread.new do
247
- begin
248
- WebMock::RequestRegistry.instance.requested_signatures.put(request_signature)
249
- response = build_httpclient_response(webmock_response, true, req.header)
250
- @request_filter.each do |filter|
251
- filter.filter_response(req, response)
252
- end
253
- conn.push(response)
254
- WebMock::CallbackRegistry.invoke_callbacks({lib: :httpclient}, request_signature, webmock_response)
255
- rescue Exception => e
256
- conn.push e
257
- end
258
- end
259
- conn
260
- end
261
279
  end
262
280
 
263
281
  class WebMockHTTPClient < HTTPClient
264
282
  alias_method :do_get_block_without_webmock, :do_get_block
265
- alias_method :do_get_stream_without_webmock, :do_get_stream
266
283
 
267
284
  include WebMockHTTPClients
268
285
  end
@@ -270,7 +287,6 @@ if defined?(::HTTPClient)
270
287
  if defined? ::JSONClient
271
288
  class WebMockJSONClient < JSONClient
272
289
  alias_method :do_get_block_without_webmock, :do_get_block
273
- alias_method :do_get_stream_without_webmock, :do_get_stream
274
290
 
275
291
  include WebMockHTTPClients
276
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.
@@ -295,6 +295,8 @@ module WebMock
295
295
  end
296
296
 
297
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"
298
300
 
299
301
  uri = get_uri(net_http, path)
300
302
  method = request.method.downcase.to_sym
@@ -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
@@ -2,6 +2,7 @@
2
2
 
3
3
  begin
4
4
  require 'typhoeus'
5
+ require 'pathname'
5
6
  rescue LoadError
6
7
  # typhoeus not found
7
8
  end
@@ -63,10 +64,8 @@ if defined?(Typhoeus)
63
64
  end
64
65
 
65
66
  body = req.options[:body]
66
-
67
- if body.is_a?(Hash)
68
- body = WebMock::Util::QueryMapper.values_to_query(body)
69
- end
67
+ form = body.is_a?(Hash)
68
+ body = WebMock::Util::QueryMapper.values_to_query(body) if form
70
69
 
71
70
  request_signature = WebMock::RequestSignature.new(
72
71
  req.options[:method] || :get,
@@ -75,11 +74,53 @@ if defined?(Typhoeus)
75
74
  headers: headers
76
75
  )
77
76
 
77
+ add_form_content_type(request_signature, req) if form
78
78
  req.instance_variable_set(:@__webmock_request_signature, request_signature)
79
79
 
80
80
  request_signature
81
81
  end
82
82
 
83
+ # libcurl adds this header when Ethon sends a Hash body as a URL
84
+ # encoded form: for a POST, even with an empty form, and for other
85
+ # methods with a form that isn't empty, except PUT, which Ethon
86
+ # uploads, and HEAD, which sends no body. A multipart form, with a
87
+ # file or the multipart option, is sent with a boundary instead, which
88
+ # isn't recorded. Ethon's own form decides whether a form is empty or
89
+ # multipart, since that differs between Ethon versions. A Content-Type
90
+ # given as content_type counts as set, since WebMock reads header
91
+ # names that way, though libcurl then sends both headers. With the
92
+ # nobody option, or when Ethon can't read the form, such as for a
93
+ # file without a path, no header is recorded, as before.
94
+ def self.add_form_content_type(signature, req)
95
+ headers = signature.headers || {}
96
+ return if headers.key?('Content-Type') || req.options[:nobody] || !defined?(::Ethon::Easy::Form)
97
+
98
+ form = ::Ethon::Easy::Form.new(nil, req.options[:body], req.options[:multipart])
99
+ if form.empty?
100
+ return unless signature.method == :post
101
+ else
102
+ return if [:put, :head].include?(signature.method)
103
+ form.params_encoding = req.options.fetch(:params_encoding, :typhoeus)
104
+ return if form.multipart?
105
+ end
106
+
107
+ signature.headers = headers.merge('Content-Type' => 'application/x-www-form-urlencoded')
108
+ rescue StandardError
109
+ nil
110
+ end
111
+
112
+ def self.signature_for_history(signature)
113
+ return signature unless signature.body.is_a?(Array)
114
+
115
+ # Ethon uploads file parts by path and stringifies non-scalar form values.
116
+ signature.with_body_values do |value|
117
+ case value
118
+ when File, Tempfile then Pathname.new(value.path)
119
+ when String, Numeric, Symbol, TrueClass, FalseClass, NilClass then value
120
+ else value.to_s
121
+ end
122
+ end
123
+ end
83
124
 
84
125
  def self.build_webmock_response(typhoeus_response)
85
126
  webmock_response = WebMock::Response.new
@@ -192,9 +233,9 @@ if defined?(Typhoeus)
192
233
  request_signature = ::WebMock::HttpLibAdapters::TyphoeusAdapter.build_request_signature(request, url)
193
234
  request.block_connection = false;
194
235
 
195
- ::WebMock::RequestRegistry.instance.requested_signatures.put(request_signature)
236
+ recorded = ::WebMock::HttpLibAdapters::TyphoeusAdapter.signature_for_history(request_signature)
196
237
 
197
- if webmock_response = ::WebMock::StubRegistry.instance.response_for_request(request_signature)
238
+ if webmock_response = ::WebMock::StubRegistry.instance.response_for_request(request_signature, record: recorded)
198
239
  response = ::WebMock::HttpLibAdapters::TyphoeusAdapter.generate_typhoeus_response(webmock_response, url)
199
240
  if request.respond_to?(:on_headers)
200
241
  request.execute_headers_callbacks(response)