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.
@@ -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)
@@ -3,16 +3,48 @@
3
3
  module WebMock
4
4
 
5
5
  module RSpecMatcherDetector
6
+ extend self
7
+
6
8
  def rSpecHashIncludingMatcher?(matcher)
7
- matcher.class.name =~ /R?Spec::Mocks::ArgumentMatchers::HashIncludingMatcher/
9
+ rspec_argument_matcher_name(matcher) =~ /R?Spec::Mocks::ArgumentMatchers::HashIncludingMatcher/
8
10
  end
9
11
 
10
12
  def rSpecHashExcludingMatcher?(matcher)
11
- matcher.class.name =~ /R?Spec::Mocks::ArgumentMatchers::HashExcludingMatcher/
13
+ rspec_argument_matcher_name(matcher) =~ /R?Spec::Mocks::ArgumentMatchers::HashExcludingMatcher/
12
14
  end
13
15
 
14
16
  def rSpecAnyArgMatcher?(matcher)
15
- matcher.class.name =~ /R?Spec::Mocks::ArgumentMatchers::AnyArgMatcher/
17
+ rspec_argument_matcher_name(matcher) =~ /R?Spec::Mocks::ArgumentMatchers::AnyArgMatcher/
18
+ end
19
+
20
+ def rSpecHashMatcher?(matcher)
21
+ rspec_argument_matcher_name(matcher) =~ /R?Spec::Mocks::ArgumentMatchers::Hash(In|Ex)cludingMatcher/
22
+ end
23
+
24
+ def rSpecArrayMatcher?(matcher)
25
+ rspec_argument_matcher_name(matcher) =~ /R?Spec::Mocks::ArgumentMatchers::Array(In|Ex)cludingMatcher/
26
+ end
27
+
28
+ # The class name of a possible RSpec matcher, or nil for values that
29
+ # can't be one, which are most values in a pattern. A custom matcher can
30
+ # be a BasicObject, which has no #class.
31
+ def rspec_argument_matcher_name(matcher)
32
+ case matcher
33
+ when String, Symbol, Numeric, Regexp, Hash, Array, nil, true, false then nil
34
+ when ::Object then matcher.class.name
35
+ end
36
+ end
37
+
38
+ # Turns RSpec's hash_including or hash_excluding into WebMock's matcher,
39
+ # which compares string keys. Returns anything else as it is.
40
+ def webmock_hash_matcher(matcher)
41
+ if rSpecHashIncludingMatcher?(matcher)
42
+ WebMock::Matchers::HashIncludingMatcher.from_rspec_matcher(matcher)
43
+ elsif rSpecHashExcludingMatcher?(matcher)
44
+ WebMock::Matchers::HashExcludingMatcher.from_rspec_matcher(matcher)
45
+ else
46
+ matcher
47
+ end
16
48
  end
17
49
  end
18
50
 
@@ -20,6 +52,10 @@ module WebMock
20
52
 
21
53
  attr_reader :method_pattern, :uri_pattern, :body_pattern, :headers_pattern, :with_block
22
54
 
55
+ # History uses an opaque key so it needn't retain a matcher block or
56
+ # an upload captured by that block. Changing the pattern replaces the key.
57
+ attr_reader :match_token
58
+
23
59
  def initialize(method, uri, options = {})
24
60
  @method_pattern = MethodPattern.new(method)
25
61
  @uri_pattern = create_uri_pattern(uri)
@@ -27,21 +63,27 @@ module WebMock
27
63
  @headers_pattern = nil
28
64
  @with_block = nil
29
65
  assign_options(options)
66
+ @match_token = Object.new if @body_pattern
30
67
  end
31
68
 
32
69
  def with(options = {}, &block)
33
70
  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
71
  assign_options(options)
35
- @with_block = block
72
+ # A later call with options only keeps the block given earlier.
73
+ @with_block = block if block
74
+ @match_token = (@body_pattern || @with_block) && Object.new
36
75
  self
37
76
  end
38
77
 
39
78
  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)) &&
79
+ return false unless @method_pattern.matches?(request_signature.method) && @uri_pattern.matches?(request_signature.uri)
80
+
81
+ token = @match_token
82
+ matched = (@body_pattern.nil? || body_matches?(request_signature)) &&
43
83
  (@headers_pattern.nil? || @headers_pattern.matches?(request_signature.headers)) &&
44
84
  (@with_block.nil? || @with_block.call(request_signature))
85
+ yield(token, matched) if token && block_given?
86
+ matched
45
87
  end
46
88
 
47
89
  def to_s
@@ -55,6 +97,10 @@ module WebMock
55
97
 
56
98
  private
57
99
 
100
+ def body_matches?(request)
101
+ serialized_body = request.serialized_body if request.respond_to?(:serialized_body)
102
+ @body_pattern.matches?(request.body, request.content_type, serialized_body)
103
+ end
58
104
 
59
105
  def assign_options(options)
60
106
  options = WebMock::Util::HashKeysStringifier.stringify_keys!(options, deep: true)
@@ -131,21 +177,19 @@ module WebMock
131
177
  end
132
178
 
133
179
  def add_query_params(query_params)
134
- @query_params = if query_params.is_a?(Hash)
135
- query_params
180
+ query_params = webmock_hash_matcher(query_params)
181
+ @query_params = if query_params.is_a?(Hash) \
182
+ || query_params.is_a?(WebMock::Matchers::HashIncludingMatcher) \
183
+ || query_params.is_a?(WebMock::Matchers::HashExcludingMatcher)
184
+ # Query values are always strings, so expected values such as 1 or
185
+ # true are compared as "1" and "true", in nested matchers too.
186
+ WebMock::Util::ValuesStringifier.stringify_query_values(query_params)
136
187
  elsif query_params.equal?(:any) \
137
188
  || query_params.is_a?(WebMock::Matchers::AnyArgMatcher) \
138
189
  || rSpecAnyArgMatcher?(query_params)
139
190
  WebMock::Matchers::AnyArgMatcher.new(nil)
140
- elsif query_params.is_a?(WebMock::Matchers::HashIncludingMatcher) \
141
- || query_params.is_a?(WebMock::Matchers::HashExcludingMatcher)
142
- query_params
143
- elsif rSpecHashIncludingMatcher?(query_params)
144
- WebMock::Matchers::HashIncludingMatcher.from_rspec_matcher(query_params)
145
- elsif rSpecHashExcludingMatcher?(query_params)
146
- WebMock::Matchers::HashExcludingMatcher.from_rspec_matcher(query_params)
147
191
  elsif query_params.nil? || query_params.is_a?(String)
148
- WebMock::Util::QueryMapper.query_to_values(query_params, notation: Config.instance.query_values_notation)
192
+ sorted_query_values(WebMock::Util::QueryMapper.query_to_values(query_params, notation: Config.instance.query_values_notation))
149
193
  else
150
194
  raise ArgumentError, "Query should be a String, Hash, :any, nil, or a hash_including or hash_excluding matcher. Got: #{query_params.class}"
151
195
  end
@@ -172,7 +216,18 @@ module WebMock
172
216
  end
173
217
 
174
218
  def query_params_matches?(uri)
175
- @query_params.nil? || @query_params == WebMock::Util::QueryMapper.query_to_values(uri.query, notation: Config.instance.query_values_notation)
219
+ return true if @query_params.nil?
220
+
221
+ actual = WebMock::Util::QueryMapper.query_to_values(uri.query, notation: Config.instance.query_values_notation)
222
+ actual = sorted_query_values(actual) if @query_params.is_a?(Array)
223
+ @query_params == actual
224
+ end
225
+
226
+ # With :flat_array the values are pairs in the order given, so both
227
+ # sides are sorted, as the queries of normalized URIs are. Adapters
228
+ # pass normalized URIs, but a signature can be given any URI.
229
+ def sorted_query_values(values)
230
+ values.is_a?(Array) ? WebMock::Util::URI.sort_query_values(values) : values
176
231
  end
177
232
  end
178
233
 
@@ -230,11 +285,37 @@ module WebMock
230
285
  rescue Addressable::URI::InvalidURIError
231
286
  Addressable::Template.new(@pattern.pattern)
232
287
  end
233
- WebMock::Util::URI.variations_of_uri_as_strings(uri).any? { |u|
288
+ variations = WebMock::Util::URI.variations_of_uri_as_strings(uri)
289
+ # Normalized URIs decode reserved characters such as ":", "/" and "=" in
290
+ # the query, while RFC 6570 query expansion expects them encoded. The
291
+ # strict variations keep the path as normalized, since decoding it
292
+ # could turn an encoded "/" or "?" into a different path.
293
+ # Encoding can only change a query with other characters than these,
294
+ # or with a second "=" in a pair.
295
+ strict_query = uri.query && uri.query.match?(/[^A-Za-z0-9\-._~%=&]|=[^&]*=/) && strictly_encoded_query(uri.query)
296
+ if strict_query && strict_query != uri.query
297
+ suffix = "?#{strict_query}#{"##{uri.fragment}" if uri.fragment}"
298
+ base = uri.omit(:query, :fragment)
299
+ bases = [base]
300
+ bases << base.omit(:port) if base.port == Addressable::URI.port_mapping[base.scheme]
301
+ variations = (variations + bases.map { |b| "#{b}#{suffix}" }).uniq
302
+ end
303
+ variations.any? { |u|
234
304
  template_matches_uri?(template, u)
235
305
  }
236
306
  end
237
307
 
308
+ def strictly_encoded_query(query)
309
+ query.split("&").map { |pair|
310
+ pair.split("=", 2).map { |part|
311
+ Addressable::URI.encode_component(
312
+ Addressable::URI.unencode_component(part),
313
+ Addressable::URI::CharacterClasses::UNRESERVED
314
+ )
315
+ }.join("=")
316
+ }.join("&")
317
+ end
318
+
238
319
  def template_matches_uri?(template, uri)
239
320
  template.match(uri)
240
321
  rescue Addressable::URI::InvalidURIError
@@ -244,12 +325,21 @@ module WebMock
244
325
 
245
326
  class URIStringPattern < URIPattern
246
327
  def add_query_params(query_params)
328
+ # A query hash with a matcher, kept from an earlier call.
329
+ earlier = @query_params if @query_params.is_a?(Hash)
247
330
  super
248
331
  if @query_params.is_a?(Hash) || @query_params.is_a?(String)
249
- query_hash = (WebMock::Util::QueryMapper.query_to_values(@pattern.query, notation: Config.instance.query_values_notation) || {}).merge(@query_params)
250
- @pattern.query = WebMock::Util::QueryMapper.values_to_query(query_hash, notation: WebMock::Config.instance.query_values_notation)
251
- @query_params = nil
252
- elsif @query_params.is_a?(WebMock::Matchers::AnyArgMatcher) && @pattern.query
332
+ query_hash = (WebMock::Util::QueryMapper.query_to_values(@pattern.query, notation: Config.instance.query_values_notation) || {}).merge(earlier || {}).merge(@query_params)
333
+ if WebMock::Util::ValuesStringifier.includes_query_matcher?(query_hash)
334
+ # A matcher can't be written into the URI, so the whole query is
335
+ # compared on its own.
336
+ @pattern.query = nil
337
+ @query_params = query_hash
338
+ else
339
+ @pattern.query = WebMock::Util::QueryMapper.values_to_query(query_hash, notation: WebMock::Config.instance.query_values_notation)
340
+ @query_params = nil
341
+ end
342
+ elsif @query_params.is_a?(WebMock::Matchers::AnyArgMatcher) && (@pattern.query || earlier)
253
343
  # The URI is then compared without its query, so it could never match.
254
344
  raise_any_query_with_uri_query
255
345
  end
@@ -278,28 +368,37 @@ module WebMock
278
368
  class BodyPattern
279
369
  include RSpecMatcherDetector
280
370
 
371
+ # A String body that isn't valid UTF-8, such as an uploaded file, can't
372
+ # be a URL encoded form, so it isn't parsed as one.
373
+ def self.form_parseable?(body)
374
+ return true unless body.is_a?(String)
375
+ return true if body.ascii_only?
376
+
377
+ body = body.dup.force_encoding(Encoding::UTF_8) unless body.encoding == Encoding::UTF_8
378
+ body.valid_encoding?
379
+ end
380
+
281
381
  # Kept so existing references to the constant still resolve.
282
382
  BODY_FORMATS = WebMock::Util::ContentType::BODY_FORMATS
283
383
 
284
384
  attr_reader :pattern
285
385
 
286
386
  def initialize(pattern)
287
- @pattern = if pattern.is_a?(Hash)
288
- normalize_hash(pattern)
289
- elsif rSpecHashIncludingMatcher?(pattern)
290
- WebMock::Matchers::HashIncludingMatcher.from_rspec_matcher(pattern)
291
- elsif rSpecHashExcludingMatcher?(pattern)
292
- WebMock::Matchers::HashExcludingMatcher.from_rspec_matcher(pattern)
293
- else
294
- pattern
295
- end
387
+ @pattern = pattern.is_a?(Hash) ? normalize_hash(pattern) : webmock_hash_matcher(pattern)
296
388
  end
297
389
 
298
- def matches?(body, content_type = "")
390
+ def matches?(body, content_type = "", serialized_body = nil)
299
391
  # Checked on the raw value, so body patterns used with mixed case
300
392
  # multipart content types keep working as in earlier versions.
301
393
  assert_non_multipart_body(content_type)
302
394
 
395
+ if serialized_body
396
+ case @pattern
397
+ when String, Regexp, Hash, Array, WebMock::Matchers::HashArgumentMatcher, nil
398
+ body = serialized_body
399
+ end
400
+ end
401
+
303
402
  if (@pattern).is_a?(Hash)
304
403
  return true if @pattern.empty?
305
404
  matching_body_hashes?(body_as_hash(body, content_type), @pattern, content_type)
@@ -329,6 +428,9 @@ module WebMock
329
428
  when :xml then
330
429
  WebMock::Util::Parsers::XML.parse(body)
331
430
  else
431
+ # A body that isn't valid UTF-8, such as an uploaded file, can't be
432
+ # a URL encoded form, so it doesn't match a hash.
433
+ return unless self.class.form_parseable?(body)
332
434
  WebMock::Util::QueryMapper.query_to_values(body, notation: Config.instance.query_values_notation)
333
435
  end
334
436
  rescue WebMock::Util::Parsers::ParseError
@@ -5,20 +5,81 @@ module WebMock
5
5
  class RequestRegistry
6
6
  include Singleton
7
7
 
8
+ # Used by #atomically, allocated once rather than on every request.
9
+ DEFER_INTERRUPTS = { Object => :on_blocking }.freeze
10
+ private_constant :DEFER_INTERRUPTS
11
+
8
12
  attr_accessor :requested_signatures
9
13
 
10
14
  def initialize
15
+ @lock = ::Mutex.new
11
16
  reset!
12
17
  end
13
18
 
19
+ # The counter and the list change together, under one lock, so they
20
+ # always agree.
14
21
  def reset!
15
- self.requested_signatures = Util::HashCounter.new
22
+ atomically do
23
+ @executed_requests = []
24
+ @live_matches = {}
25
+ self.requested_signatures = Util::HashCounter.new
26
+ end
27
+ end
28
+
29
+ # Records a request made through an HTTP client adapter. The list holds
30
+ # the copy the counter keeps of each distinct request, so a caller reusing
31
+ # its body buffer cannot change it. A repeated request adds only a
32
+ # reference to that copy, so a suite that never resets keeps one copy of
33
+ # each distinct request.
34
+ def put(request_signature, track_live_matches: false)
35
+ stored = nil
36
+ live_matches = atomically do
37
+ stored = requested_signatures.put(request_signature)
38
+ @executed_requests << stored
39
+ @live_matches
40
+ end
41
+ return unless track_live_matches
42
+
43
+ # Matching happens outside the lock. Capture this generation so a
44
+ # concurrent reset cannot attach an old match to a later request.
45
+ lambda do |token, matched|
46
+ @lock.synchronize do
47
+ counts = live_matches[token] ||= {}
48
+ checked, accepted = counts.fetch(stored, [0, 0])
49
+ accepted += 1 if matched
50
+ counts[stored] = [checked + 1, accepted]
51
+ end
52
+ end
53
+ end
54
+
55
+ # Every request made since the last reset, in order, repeats included,
56
+ # as copies, so a test cannot change WebMock's records.
57
+ def executed_requests
58
+ requests = @lock.synchronize { @executed_requests.dup }
59
+ copies = {}.compare_by_identity
60
+ requests.map { |request| copies[request] ||= request.dup }.freeze
16
61
  end
17
62
 
18
63
  def times_executed(request_pattern)
19
- self.requested_signatures.select do |request_signature|
20
- request_pattern.matches?(request_signature)
21
- end.inject(0) { |sum, (_, times_executed)| sum + times_executed }
64
+ pattern, conditions = request_pattern.respond_to?(:patterns) ? request_pattern.patterns : [request_pattern]
65
+ base = pattern.is_a?(RequestStub) ? pattern.request_pattern : pattern
66
+ token = base.match_token if base.is_a?(RequestPattern)
67
+ counts, observations = @lock.synchronize { [requested_signatures.snapshot, @live_matches[token]&.dup] }
68
+
69
+ counts.sum do |signature, total|
70
+ observed = observations && observations[signature]
71
+ if observed
72
+ # The same snapshot can represent both a stream and a string.
73
+ # Only recheck the requests for which the stub wasn't evaluated.
74
+ checked, accepted = observed
75
+ remaining = total - checked
76
+ accepted += remaining if remaining > 0 && pattern.matches?(signature)
77
+ next 0 if accepted > 0 && conditions && !conditions.matches?(signature)
78
+ accepted
79
+ else
80
+ request_pattern.matches?(signature) ? total : 0
81
+ end
82
+ end
22
83
  end
23
84
 
24
85
  def to_s
@@ -33,5 +94,14 @@ module WebMock
33
94
  end
34
95
  end
35
96
 
97
+ private
98
+
99
+ # An interrupt such as Timeout can still stop a thread waiting for the
100
+ # lock, but not one between the two updates, where nothing blocks.
101
+ def atomically(&block)
102
+ Thread.handle_interrupt(DEFER_INTERRUPTS) do
103
+ @lock.synchronize(&block)
104
+ end
105
+ end
36
106
  end
37
107
  end
@@ -5,11 +5,12 @@ module WebMock
5
5
  class RequestSignature
6
6
 
7
7
  attr_accessor :uri, :body
8
- attr_reader :method, :headers
8
+ attr_reader :method, :headers, :serialized_body
9
9
 
10
10
  def initialize(method, uri, options = {})
11
11
  self.method = method
12
12
  self.uri = uri.is_a?(Addressable::URI) ? uri : WebMock::Util::URI.normalize_uri(uri)
13
+ @serialized_body = options[:serialized_body]
13
14
  assign_options(options)
14
15
  end
15
16
 
@@ -23,6 +24,27 @@ module WebMock
23
24
  string
24
25
  end
25
26
 
27
+ # Build a signature for history while preserving the original client
28
+ # objects for stub matchers and callbacks. Keep nested form structure.
29
+ def with_body_values(&block)
30
+ self.class.new(method, uri, body: map_body_values(body, &block), headers: headers)
31
+ end
32
+
33
+ # Keep the native upload available to custom matchers and callbacks while
34
+ # allowing string and structured body patterns to match its contents.
35
+ def with_upload_body(upload)
36
+ self.class.new(method, uri, body: upload, headers: headers, serialized_body: body)
37
+ end
38
+
39
+ # A copy that shares no mutable state with the original.
40
+ def initialize_copy(original)
41
+ super
42
+ @uri = @uri.dup
43
+ @body = map_body_values(@body, &:dup)
44
+ @serialized_body = @serialized_body&.dup
45
+ @headers = @headers&.transform_values { |value| value.is_a?(Array) ? value.map(&:dup) : value.dup }
46
+ end
47
+
26
48
  def method=(method)
27
49
  @method = method.to_sym.downcase
28
50
  end
@@ -32,11 +54,13 @@ module WebMock
32
54
  end
33
55
 
34
56
  def hash
35
- self.to_s.hash
57
+ [method, uri, body, headers].hash
36
58
  end
37
59
 
38
60
  def eql?(other)
39
- self.to_s == other.to_s
61
+ other.is_a?(RequestSignature) &&
62
+ method == other.method && uri.eql?(other.uri) &&
63
+ body.eql?(other.body) && headers.eql?(other.headers)
40
64
  end
41
65
  alias == eql?
42
66
 
@@ -56,6 +80,19 @@ module WebMock
56
80
 
57
81
  private
58
82
 
83
+ def map_body_values(body, &block)
84
+ case body
85
+ when Array
86
+ body.map { |item| map_body_values(item, &block) }
87
+ when Hash
88
+ body.each_with_object({}) do |(key, value), copy|
89
+ copy[map_body_values(key, &block)] = map_body_values(value, &block)
90
+ end
91
+ else
92
+ yield body
93
+ end
94
+ end
95
+
59
96
  def assign_options(options)
60
97
  self.body = options[:body] if options.has_key?(:body)
61
98
  self.headers = options[:headers] if options.has_key?(:headers)
@@ -114,10 +114,14 @@ module WebMock
114
114
  stub = self.new(signature.method.to_sym, signature.uri.to_s)
115
115
 
116
116
  if signature.body.to_s != ''
117
- body = if signature.url_encoded?
118
- WebMock::Util::QueryMapper.query_to_values(signature.body, notation: Config.instance.query_values_notation)
119
- else
120
- signature.body
117
+ body = signature.body
118
+ if signature.url_encoded? && BodyPattern.form_parseable?(body)
119
+ begin
120
+ body = WebMock::Util::QueryMapper.query_to_values(body, notation: Config.instance.query_values_notation)
121
+ rescue ArgumentError
122
+ # Some notations, such as :flat, reject a repeated key, so the
123
+ # stub shows the body as it is.
124
+ end
121
125
  end
122
126
  stub.with(body: body)
123
127
  end
@@ -62,18 +62,19 @@ module WebMock
62
62
  request_stub_for(request_signature)
63
63
  end
64
64
 
65
- def response_for_request(request_signature)
66
- stub = request_stub_for(request_signature)
65
+ def response_for_request(request_signature, record: nil)
66
+ if record
67
+ remember = RequestRegistry.instance.put(record, track_live_matches: !record.equal?(request_signature))
68
+ end
69
+ stub = request_stub_for(request_signature, &remember)
67
70
  stub ? evaluate_response_for_request(stub.response, request_signature) : nil
68
71
  end
69
72
 
70
73
  private
71
74
 
72
- def request_stub_for(request_signature)
75
+ def request_stub_for(request_signature, &remember)
73
76
  (global_stubs[:before_local_stubs] + request_stubs + global_stubs[:after_local_stubs])
74
- .detect { |registered_request_stub|
75
- registered_request_stub.request_pattern.matches?(request_signature)
76
- }
77
+ .detect { |stub| stub.request_pattern.matches?(request_signature, &remember) }
77
78
  end
78
79
 
79
80
  def evaluate_response_for_request(response, request_signature)
@@ -5,19 +5,32 @@ require 'thread'
5
5
  module WebMock
6
6
  module Util
7
7
  class HashCounter
8
+ # The key the counter holds, its count, and when it was last put.
9
+ Entry = Struct.new(:key, :count, :position)
10
+
8
11
  attr_accessor :hash
9
12
 
10
13
  def initialize
11
14
  self.hash = Hash.new(0)
12
- @order = {}
15
+ @entries = {}
13
16
  @max = 0
14
17
  @lock = ::Mutex.new
15
18
  end
16
19
 
20
+ # Returns the key the counter holds: a copy of the first one put for an
21
+ # equal key. The copy is also what the counter looks keys up by, so a
22
+ # caller changing its key later cannot change the counts.
17
23
  def put(key, num=1)
18
24
  @lock.synchronize do
19
- hash[key] += num
20
- @order[key] = @max += 1
25
+ entry = @entries[key]
26
+ unless entry
27
+ copy = key.dup
28
+ entry = @entries[copy] = Entry.new(copy, 0, 0)
29
+ end
30
+ entry.count += num
31
+ entry.position = @max += 1
32
+ hash[entry.key] = entry.count
33
+ entry.key
21
34
  end
22
35
  end
23
36
 
@@ -27,18 +40,24 @@ module WebMock
27
40
  end
28
41
  end
29
42
 
43
+ # The block runs on a snapshot, outside the lock, so it can make
44
+ # requests or call WebMock without deadlocking.
30
45
  def select(&block)
31
46
  return unless block_given?
32
47
 
33
- @lock.synchronize do
34
- hash.select(&block)
35
- end
48
+ snapshot.select(&block)
49
+ end
50
+
51
+ def snapshot
52
+ @lock.synchronize { hash.dup }
36
53
  end
37
54
 
55
+ # Like select, it yields from a snapshot, outside the lock.
38
56
  def each(&block)
39
- @order.to_a.sort_by { |a| a[1] }.each do |a|
40
- yield(a[0], hash[a[0]])
57
+ entries = @lock.synchronize do
58
+ @entries.values.sort_by(&:position).map { |entry| [entry.key, entry.count] }
41
59
  end
60
+ entries.each { |key, count| yield(key, count) }
42
61
  end
43
62
  end
44
63
  end