webmock 3.34.0 → 3.41.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.
Files changed (42) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +358 -0
  3. data/README.md +222 -3
  4. data/lib/webmock/api.rb +4 -0
  5. data/lib/webmock/errors.rb +1 -1
  6. data/lib/webmock/http_lib_adapters/async_http_client_adapter.rb +51 -7
  7. data/lib/webmock/http_lib_adapters/curb_adapter.rb +291 -39
  8. data/lib/webmock/http_lib_adapters/em_http_request_adapter.rb +11 -3
  9. data/lib/webmock/http_lib_adapters/excon_adapter.rb +23 -2
  10. data/lib/webmock/http_lib_adapters/http_rb/webmock.rb +33 -4
  11. data/lib/webmock/http_lib_adapters/http_rb_adapter.rb +4 -1
  12. data/lib/webmock/http_lib_adapters/httpclient_adapter.rb +132 -110
  13. data/lib/webmock/http_lib_adapters/manticore_adapter.rb +1 -1
  14. data/lib/webmock/http_lib_adapters/net_http.rb +66 -3
  15. data/lib/webmock/http_lib_adapters/net_http_response.rb +28 -2
  16. data/lib/webmock/http_lib_adapters/patron_adapter.rb +242 -40
  17. data/lib/webmock/http_lib_adapters/typhoeus_hydra_adapter.rb +65 -7
  18. data/lib/webmock/json_body_hint.rb +8 -5
  19. data/lib/webmock/request_body_diff.rb +16 -6
  20. data/lib/webmock/request_execution_verifier.rb +13 -2
  21. data/lib/webmock/request_pattern.rb +236 -36
  22. data/lib/webmock/request_registry.rb +75 -5
  23. data/lib/webmock/request_signature.rb +44 -5
  24. data/lib/webmock/request_signature_snippet.rb +23 -2
  25. data/lib/webmock/request_stub.rb +8 -4
  26. data/lib/webmock/response.rb +42 -3
  27. data/lib/webmock/stub_registry.rb +7 -6
  28. data/lib/webmock/stub_request_snippet.rb +9 -3
  29. data/lib/webmock/trailing_slash_hint.rb +55 -0
  30. data/lib/webmock/util/hash_counter.rb +27 -8
  31. data/lib/webmock/util/hash_keys_stringifier.rb +23 -1
  32. data/lib/webmock/util/headers.rb +17 -0
  33. data/lib/webmock/util/message_string.rb +28 -0
  34. data/lib/webmock/util/parsers/json.rb +33 -2
  35. data/lib/webmock/util/query_mapper.rb +56 -37
  36. data/lib/webmock/util/upload_body.rb +63 -0
  37. data/lib/webmock/util/uri.rb +21 -12
  38. data/lib/webmock/util/values_stringifier.rb +54 -0
  39. data/lib/webmock/version.rb +1 -1
  40. data/lib/webmock/webmock.rb +35 -4
  41. data/lib/webmock.rb +3 -0
  42. metadata +7 -4
@@ -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
@@ -161,6 +205,22 @@ module WebMock
161
205
  str
162
206
  end
163
207
 
208
+ # Ruby source for the URI argument of stub_request, for snippets.
209
+ def to_snippet
210
+ pattern_inspect
211
+ end
212
+
213
+ # Ruby source for the query option of with, for snippets, or nil.
214
+ def query_snippet
215
+ case @query_params
216
+ when nil then nil
217
+ when WebMock::Matchers::AnyArgMatcher then ":any"
218
+ # Pairs of the :flat_array notation, which a query string describes
219
+ when Array then WebMock::Util::QueryMapper.values_to_query(@query_params, notation: :flat_array).inspect
220
+ else @query_params.inspect
221
+ end
222
+ end
223
+
164
224
  private
165
225
 
166
226
  def raise_any_query_with_uri_query
@@ -172,11 +232,28 @@ module WebMock
172
232
  end
173
233
 
174
234
  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)
235
+ return true if @query_params.nil?
236
+
237
+ actual = WebMock::Util::QueryMapper.query_to_values(uri.query, notation: Config.instance.query_values_notation)
238
+ actual = sorted_query_values(actual) if @query_params.is_a?(Array)
239
+ @query_params == actual
240
+ end
241
+
242
+ # With :flat_array the values are pairs in the order given, so both
243
+ # sides are sorted, as the queries of normalized URIs are. Adapters
244
+ # pass normalized URIs, but a signature can be given any URI.
245
+ def sorted_query_values(values)
246
+ values.is_a?(Array) ? WebMock::Util::URI.sort_query_values(values) : values
176
247
  end
177
248
  end
178
249
 
179
250
  class URICallablePattern < URIPattern
251
+ # A lambda can't be written as Ruby source, so it is shown in quotes, as
252
+ # before.
253
+ def to_snippet
254
+ "\"#{pattern_inspect}\""
255
+ end
256
+
180
257
  private
181
258
 
182
259
  def pattern_matches?(uri)
@@ -207,6 +284,10 @@ module WebMock
207
284
  end
208
285
  end
209
286
 
287
+ def to_snippet
288
+ "Addressable::Template.new(#{pattern_inspect})"
289
+ end
290
+
210
291
  private
211
292
 
212
293
  def pattern_matches?(uri)
@@ -230,11 +311,37 @@ module WebMock
230
311
  rescue Addressable::URI::InvalidURIError
231
312
  Addressable::Template.new(@pattern.pattern)
232
313
  end
233
- WebMock::Util::URI.variations_of_uri_as_strings(uri).any? { |u|
314
+ variations = WebMock::Util::URI.variations_of_uri_as_strings(uri)
315
+ # Normalized URIs decode reserved characters such as ":", "/" and "=" in
316
+ # the query, while RFC 6570 query expansion expects them encoded. The
317
+ # strict variations keep the path as normalized, since decoding it
318
+ # could turn an encoded "/" or "?" into a different path.
319
+ # Encoding can only change a query with other characters than these,
320
+ # or with a second "=" in a pair.
321
+ strict_query = uri.query && uri.query.match?(/[^A-Za-z0-9\-._~%=&]|=[^&]*=/) && strictly_encoded_query(uri.query)
322
+ if strict_query && strict_query != uri.query
323
+ suffix = "?#{strict_query}#{"##{uri.fragment}" if uri.fragment}"
324
+ base = uri.omit(:query, :fragment)
325
+ bases = [base]
326
+ bases << base.omit(:port) if base.port == Addressable::URI.port_mapping[base.scheme]
327
+ variations = (variations + bases.map { |b| "#{b}#{suffix}" }).uniq
328
+ end
329
+ variations.any? { |u|
234
330
  template_matches_uri?(template, u)
235
331
  }
236
332
  end
237
333
 
334
+ def strictly_encoded_query(query)
335
+ query.split("&").map { |pair|
336
+ pair.split("=", 2).map { |part|
337
+ Addressable::URI.encode_component(
338
+ Addressable::URI.unencode_component(part),
339
+ Addressable::URI::CharacterClasses::UNRESERVED
340
+ )
341
+ }.join("=")
342
+ }.join("&")
343
+ end
344
+
238
345
  def template_matches_uri?(template, uri)
239
346
  template.match(uri)
240
347
  rescue Addressable::URI::InvalidURIError
@@ -244,17 +351,36 @@ module WebMock
244
351
 
245
352
  class URIStringPattern < URIPattern
246
353
  def add_query_params(query_params)
354
+ # A query hash with a matcher, kept from an earlier call.
355
+ earlier = @query_params if @query_params.is_a?(Hash)
247
356
  super
248
357
  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
358
+ query_hash = (WebMock::Util::QueryMapper.query_to_values(@pattern.query, notation: Config.instance.query_values_notation) || {}).merge(earlier || {}).merge(@query_params)
359
+ if WebMock::Util::ValuesStringifier.includes_query_matcher?(query_hash)
360
+ # A matcher can't be written into the URI, so the whole query is
361
+ # compared on its own.
362
+ @pattern.query = nil
363
+ @query_params = query_hash
364
+ else
365
+ @pattern.query = WebMock::Util::QueryMapper.values_to_query(query_hash, notation: WebMock::Config.instance.query_values_notation)
366
+ @query_params = nil
367
+ end
368
+ elsif @query_params.is_a?(WebMock::Matchers::AnyArgMatcher) && (@pattern.query || earlier)
253
369
  # The URI is then compared without its query, so it could never match.
254
370
  raise_any_query_with_uri_query
255
371
  end
256
372
  end
257
373
 
374
+ def to_snippet
375
+ "\"#{pattern_inspect}\""
376
+ end
377
+
378
+ # Whether the URI matches apart from its query, for failure message
379
+ # hints, which must not run matchers given for the query.
380
+ def matches_without_query?(uri)
381
+ @pattern.is_a?(Addressable::URI) && uri.omit(:query) === @pattern.omit(:query)
382
+ end
383
+
258
384
  private
259
385
 
260
386
  def pattern_matches?(uri)
@@ -278,35 +404,44 @@ module WebMock
278
404
  class BodyPattern
279
405
  include RSpecMatcherDetector
280
406
 
407
+ # A String body that isn't valid UTF-8, such as an uploaded file, can't
408
+ # be a URL encoded form, so it isn't parsed as one.
409
+ def self.form_parseable?(body)
410
+ return true unless body.is_a?(String)
411
+ return true if body.ascii_only?
412
+
413
+ body = body.dup.force_encoding(Encoding::UTF_8) unless body.encoding == Encoding::UTF_8
414
+ body.valid_encoding?
415
+ end
416
+
281
417
  # Kept so existing references to the constant still resolve.
282
418
  BODY_FORMATS = WebMock::Util::ContentType::BODY_FORMATS
283
419
 
284
420
  attr_reader :pattern
285
421
 
286
422
  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
423
+ @pattern = pattern.is_a?(Hash) ? normalize_hash(pattern) : webmock_hash_matcher(pattern)
296
424
  end
297
425
 
298
- def matches?(body, content_type = "")
426
+ def matches?(body, content_type = "", serialized_body = nil)
299
427
  # Checked on the raw value, so body patterns used with mixed case
300
428
  # multipart content types keep working as in earlier versions.
301
429
  assert_non_multipart_body(content_type)
302
430
 
431
+ if serialized_body
432
+ case @pattern
433
+ when String, Regexp, Hash, Array, WebMock::Matchers::HashArgumentMatcher, nil
434
+ body = serialized_body
435
+ end
436
+ end
437
+
303
438
  if (@pattern).is_a?(Hash)
304
439
  return true if @pattern.empty?
305
- matching_body_hashes?(body_as_hash(body, content_type), @pattern, content_type)
440
+ matching_parsed_body?(body, content_type) { |parsed| matching_body_hashes?(parsed, @pattern, content_type) }
306
441
  elsif (@pattern).is_a?(Array)
307
- matching_body_array?(body_as_hash(body, content_type), @pattern, content_type)
442
+ matching_parsed_body?(body, content_type) { |parsed| matching_body_array?(parsed, @pattern, content_type) }
308
443
  elsif (@pattern).is_a?(WebMock::Matchers::HashArgumentMatcher)
309
- @pattern == body_as_hash(body, content_type)
444
+ matching_parsed_body?(body, content_type) { |parsed| @pattern == parsed }
310
445
  else
311
446
  empty_string?(@pattern) && empty_string?(body) ||
312
447
  @pattern == body ||
@@ -320,6 +455,68 @@ module WebMock
320
455
 
321
456
  private
322
457
 
458
+ WARNED_LEGACY_JSON = {}
459
+ private_constant :WARNED_LEGACY_JSON
460
+
461
+ # WebMock 3.40.0 and earlier read JSON bodies with a YAML based parser,
462
+ # which reads some bodies that aren't valid JSON and some values
463
+ # differently from the json gem. When the pattern doesn't match the json
464
+ # gem's reading and the old parser reads the body differently, the old
465
+ # reading decides, as in 3.40.0, with a warning once for each pattern
466
+ # when it matches.
467
+ def matching_parsed_body?(body, content_type)
468
+ parsed = body_as_hash(body, content_type)
469
+ begin
470
+ return true if yield(parsed)
471
+ rescue SignalException, SystemExit
472
+ raise
473
+ rescue Exception => error
474
+ # A value in the pattern, such as a lambda or an RSpec expectation,
475
+ # may expect what the old parser reads, so the old reading decides.
476
+ end
477
+
478
+ json = body && WebMock::Util::ContentType.body_format(content_type) == :json
479
+ legacy = legacy_json(body) if json
480
+ if !json || legacy.eql?(parsed)
481
+ raise error if error
482
+ return false
483
+ end
484
+
485
+ # As in 3.40.0, including an error the pattern raises for it.
486
+ matched = yield(legacy)
487
+ warn_legacy_json(body, parsed) if matched
488
+ matched
489
+ end
490
+
491
+ def legacy_json(body)
492
+ WebMock::Util::Parsers::JSON.parse_legacy(body)
493
+ rescue WebMock::Util::Parsers::ParseError
494
+ nil
495
+ end
496
+
497
+ def warn_legacy_json(body, parsed)
498
+ pattern = to_s
499
+ # Without object addresses, so equal patterns, such as ones with a
500
+ # lambda built in each example, warn once.
501
+ key = pattern.gsub(/#<([\w:]+?):0x\h+/, '#<\\1').hash
502
+ return if WARNED_LEGACY_JSON[key]
503
+ WARNED_LEGACY_JSON[key] = true
504
+ advice =
505
+ if parsed.nil?
506
+ "Send valid JSON, for example from to_json, and write the pattern for what JSON.parse returns."
507
+ else
508
+ "Write the pattern for what JSON.parse returns: #{shorten(parsed.inspect)}."
509
+ end
510
+ WebMock::Deprecation.warning(
511
+ "the body pattern #{shorten(pattern)} matched the request body #{shorten(body).inspect} " \
512
+ "only as WebMock's old JSON parser reads it. WebMock 4.0 drops that parser, so it won't match. #{advice}"
513
+ )
514
+ end
515
+
516
+ def shorten(text)
517
+ text.length > 100 ? "#{text[0, 100]}..." : text
518
+ end
519
+
323
520
  def body_as_hash(body, content_type)
324
521
  return if body.nil?
325
522
 
@@ -329,6 +526,9 @@ module WebMock
329
526
  when :xml then
330
527
  WebMock::Util::Parsers::XML.parse(body)
331
528
  else
529
+ # A body that isn't valid UTF-8, such as an uploaded file, can't be
530
+ # a URL encoded form, so it doesn't match a hash.
531
+ return unless self.class.form_parseable?(body)
332
532
  WebMock::Util::QueryMapper.query_to_values(body, notation: Config.instance.query_values_notation)
333
533
  end
334
534
  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
@@ -27,11 +88,20 @@ module WebMock
27
88
  else
28
89
  text = "".dup
29
90
  self.requested_signatures.each do |request_signature, times_executed|
30
- text << "#{request_signature} was made #{times_executed} time#{times_executed == 1 ? '' : 's' }\n"
91
+ text << "#{Util::MessageString.utf8(request_signature)} was made #{times_executed} time#{times_executed == 1 ? '' : 's' }\n"
31
92
  end
32
93
  text
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,24 +5,48 @@ 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
 
16
17
  def to_s
17
18
  string = "#{self.method.to_s.upcase}".dup
18
19
  string << " #{WebMock::Util::URI.strip_default_port_from_uri_string(self.uri.to_s)}"
19
- string << " with body '#{body.to_s}'" if body && body.to_s != ''
20
+ # In UTF-8, so a binary body and a UTF-8 header, or a UTF-16 body,
21
+ # can be joined into the message.
22
+ string << " with body '#{WebMock::Util::MessageString.utf8(body)}'" if body && body.to_s != ''
20
23
  if headers && !headers.empty?
21
- string << " with headers #{WebMock::Util::Headers.sorted_headers_string(headers)}"
24
+ string << " with headers #{WebMock::Util::MessageString.utf8(WebMock::Util::Headers.sorted_headers_string(headers))}"
22
25
  end
23
26
  string
24
27
  end
25
28
 
29
+ # Build a signature for history while preserving the original client
30
+ # objects for stub matchers and callbacks. Keep nested form structure.
31
+ def with_body_values(&block)
32
+ self.class.new(method, uri, body: map_body_values(body, &block), headers: headers)
33
+ end
34
+
35
+ # Keep the native upload available to custom matchers and callbacks while
36
+ # allowing string and structured body patterns to match its contents.
37
+ def with_upload_body(upload)
38
+ self.class.new(method, uri, body: upload, headers: headers, serialized_body: body)
39
+ end
40
+
41
+ # A copy that shares no mutable state with the original.
42
+ def initialize_copy(original)
43
+ super
44
+ @uri = @uri.dup
45
+ @body = map_body_values(@body, &:dup)
46
+ @serialized_body = @serialized_body&.dup
47
+ @headers = @headers&.transform_values { |value| value.is_a?(Array) ? value.map(&:dup) : value.dup }
48
+ end
49
+
26
50
  def method=(method)
27
51
  @method = method.to_sym.downcase
28
52
  end
@@ -32,11 +56,13 @@ module WebMock
32
56
  end
33
57
 
34
58
  def hash
35
- self.to_s.hash
59
+ [method, uri, body, headers].hash
36
60
  end
37
61
 
38
62
  def eql?(other)
39
- self.to_s == other.to_s
63
+ other.is_a?(RequestSignature) &&
64
+ method == other.method && uri.eql?(other.uri) &&
65
+ body.eql?(other.body) && headers.eql?(other.headers)
40
66
  end
41
67
  alias == eql?
42
68
 
@@ -56,6 +82,19 @@ module WebMock
56
82
 
57
83
  private
58
84
 
85
+ def map_body_values(body, &block)
86
+ case body
87
+ when Array
88
+ body.map { |item| map_body_values(item, &block) }
89
+ when Hash
90
+ body.each_with_object({}) do |(key, value), copy|
91
+ copy[map_body_values(key, &block)] = map_body_values(value, &block)
92
+ end
93
+ else
94
+ yield body
95
+ end
96
+ end
97
+
59
98
  def assign_options(options)
60
99
  self.body = options[:body] if options.has_key?(:body)
61
100
  self.headers = options[:headers] if options.has_key?(:headers)
@@ -9,9 +9,13 @@ module WebMock
9
9
 
10
10
  def initialize(request_signature)
11
11
  @request_signature = request_signature
12
- @request_stub = RequestStub.from_request_signature(request_signature)
12
+ @request_stub = RequestStub.from_request_signature(signature_for_snippet(request_signature))
13
13
  end
14
14
 
15
+ # Headers that change with the client version or platform. A stub copied
16
+ # with them breaks when the client is upgraded or runs on another machine.
17
+ SNIPPET_OMITTED_HEADERS = %w[User-Agent].freeze
18
+
15
19
  def stubbing_instructions
16
20
  return unless WebMock.show_stubbing_instructions?
17
21
 
@@ -24,17 +28,29 @@ module WebMock
24
28
 
25
29
  text = "registered request stubs:\n".dup
26
30
  WebMock::StubRegistry.instance.request_stubs.each do |stub|
27
- text << "\n#{WebMock::StubRequestSnippet.new(stub).to_s(false)}"
31
+ text << "\n#{WebMock::Util::MessageString.utf8(WebMock::StubRequestSnippet.new(stub).to_s(false))}"
28
32
  if WebMock.show_body_diff?
29
33
  add_body_diff(stub, text)
30
34
  add_json_body_hint(stub, text)
31
35
  end
36
+ add_trailing_slash_hint(stub, text)
32
37
  end
33
38
  text
34
39
  end
35
40
 
36
41
  private
37
42
 
43
+ def signature_for_snippet(request_signature)
44
+ headers = request_signature.headers
45
+ return request_signature unless headers && (headers.keys & SNIPPET_OMITTED_HEADERS).any?
46
+
47
+ # A new signature rather than a copy, which would copy the body, and
48
+ # some bodies, such as Curb's Curl::PostField, can't be copied.
49
+ RequestSignature.new(request_signature.method, request_signature.uri,
50
+ body: request_signature.body,
51
+ headers: headers.reject { |name, _| SNIPPET_OMITTED_HEADERS.include?(name) })
52
+ end
53
+
38
54
  def add_body_diff(stub, text)
39
55
  body_diff_str = signature_stub_body_diff(stub)
40
56
  text << "\n\n#{body_diff_str}" unless body_diff_str.empty?
@@ -46,6 +62,11 @@ module WebMock
46
62
  text << "\n\n#{JsonBodyHint::STUB_HINT}\n"
47
63
  end
48
64
 
65
+ def add_trailing_slash_hint(stub, text)
66
+ difference = TrailingSlashHint.difference(stub.request_pattern, request_signature)
67
+ text << "\n\n#{TrailingSlashHint::STUB_HINTS[difference]}\n" if difference
68
+ end
69
+
49
70
  def signature_stub_body_diff(stub)
50
71
  diff = RequestBodyDiff.new(request_signature, stub).body_diff
51
72
  diff.empty? ? "" : "Body diff:\n #{pretty_print_to_string(diff)}"
@@ -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