webmock 3.35.0 → 3.37.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,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
@@ -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
@@ -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
@@ -80,6 +81,18 @@ if defined?(Typhoeus)
80
81
  request_signature
81
82
  end
82
83
 
84
+ def self.signature_for_history(signature)
85
+ return signature unless signature.body.is_a?(Array)
86
+
87
+ # Ethon uploads file parts by path and stringifies non-scalar form values.
88
+ signature.with_body_values do |value|
89
+ case value
90
+ when File, Tempfile then Pathname.new(value.path)
91
+ when String, Numeric, Symbol, TrueClass, FalseClass, NilClass then value
92
+ else value.to_s
93
+ end
94
+ end
95
+ end
83
96
 
84
97
  def self.build_webmock_response(typhoeus_response)
85
98
  webmock_response = WebMock::Response.new
@@ -192,9 +205,9 @@ if defined?(Typhoeus)
192
205
  request_signature = ::WebMock::HttpLibAdapters::TyphoeusAdapter.build_request_signature(request, url)
193
206
  request.block_connection = false;
194
207
 
195
- ::WebMock::RequestRegistry.instance.requested_signatures.put(request_signature)
208
+ recorded = ::WebMock::HttpLibAdapters::TyphoeusAdapter.signature_for_history(request_signature)
196
209
 
197
- if webmock_response = ::WebMock::StubRegistry.instance.response_for_request(request_signature)
210
+ if webmock_response = ::WebMock::StubRegistry.instance.response_for_request(request_signature, record: recorded)
198
211
  response = ::WebMock::HttpLibAdapters::TyphoeusAdapter.generate_typhoeus_response(webmock_response, url)
199
212
  if request.respond_to?(:on_headers)
200
213
  request.execute_headers_callbacks(response)
@@ -20,6 +20,10 @@ module WebMock
20
20
 
21
21
  attr_reader :method_pattern, :uri_pattern, :body_pattern, :headers_pattern, :with_block
22
22
 
23
+ # History uses an opaque key so it needn't retain a matcher block or
24
+ # an upload captured by that block. Changing the pattern replaces the key.
25
+ attr_reader :match_token
26
+
23
27
  def initialize(method, uri, options = {})
24
28
  @method_pattern = MethodPattern.new(method)
25
29
  @uri_pattern = create_uri_pattern(uri)
@@ -27,21 +31,26 @@ module WebMock
27
31
  @headers_pattern = nil
28
32
  @with_block = nil
29
33
  assign_options(options)
34
+ @match_token = Object.new if @body_pattern
30
35
  end
31
36
 
32
37
  def with(options = {}, &block)
33
38
  raise ArgumentError.new('#with method invoked with no arguments. Either options hash or block must be specified. Created a block with do..end? Try creating it with curly braces {} instead.') if options.empty? && !block_given?
34
39
  assign_options(options)
35
40
  @with_block = block
41
+ @match_token = (@body_pattern || @with_block) && Object.new
36
42
  self
37
43
  end
38
44
 
39
45
  def matches?(request_signature)
40
- @method_pattern.matches?(request_signature.method) &&
41
- @uri_pattern.matches?(request_signature.uri) &&
42
- (@body_pattern.nil? || @body_pattern.matches?(request_signature.body, request_signature.content_type)) &&
46
+ return false unless @method_pattern.matches?(request_signature.method) && @uri_pattern.matches?(request_signature.uri)
47
+
48
+ token = @match_token
49
+ matched = (@body_pattern.nil? || body_matches?(request_signature)) &&
43
50
  (@headers_pattern.nil? || @headers_pattern.matches?(request_signature.headers)) &&
44
51
  (@with_block.nil? || @with_block.call(request_signature))
52
+ yield(token, matched) if token && block_given?
53
+ matched
45
54
  end
46
55
 
47
56
  def to_s
@@ -55,6 +64,10 @@ module WebMock
55
64
 
56
65
  private
57
66
 
67
+ def body_matches?(request)
68
+ serialized_body = request.serialized_body if request.respond_to?(:serialized_body)
69
+ @body_pattern.matches?(request.body, request.content_type, serialized_body)
70
+ end
58
71
 
59
72
  def assign_options(options)
60
73
  options = WebMock::Util::HashKeysStringifier.stringify_keys!(options, deep: true)
@@ -295,11 +308,18 @@ module WebMock
295
308
  end
296
309
  end
297
310
 
298
- def matches?(body, content_type = "")
311
+ def matches?(body, content_type = "", serialized_body = nil)
299
312
  # Checked on the raw value, so body patterns used with mixed case
300
313
  # multipart content types keep working as in earlier versions.
301
314
  assert_non_multipart_body(content_type)
302
315
 
316
+ if serialized_body
317
+ case @pattern
318
+ when String, Regexp, Hash, Array, WebMock::Matchers::HashArgumentMatcher, nil
319
+ body = serialized_body
320
+ end
321
+ end
322
+
303
323
  if (@pattern).is_a?(Hash)
304
324
  return true if @pattern.empty?
305
325
  matching_body_hashes?(body_as_hash(body, content_type), @pattern, content_type)