webmock 3.37.0 → 3.39.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.
@@ -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
@@ -302,10 +304,19 @@ module WebMock
302
304
  headers = Hash[*request.to_hash.map {|k,v| [k, v]}.inject([]) {|r,x| r + x}]
303
305
 
304
306
  if request.body_stream
305
- body = request.body_stream.read
307
+ body = read_body_stream(request.body_stream)
306
308
  request.body_stream = nil
307
309
  end
308
310
 
311
+ # A form set with #set_form is encoded by Net::HTTP when it sends the
312
+ # request. The request is left as it is, so it is sent as without
313
+ # WebMock and encodes its form again when sent again, and the
314
+ # signature gets the body it sends.
315
+ form = request.instance_variable_get(:@body_data)
316
+ if form && body.nil? && request.body.nil?
317
+ return WebMock::RequestSignature.new(method, uri, body: form_body(request, form), headers: headers)
318
+ end
319
+
309
320
  if body != nil && body.respond_to?(:read)
310
321
  request.set_body_internal body.read
311
322
  else
@@ -315,6 +326,52 @@ module WebMock
315
326
  WebMock::RequestSignature.new(method, uri, body: request.body, headers: headers)
316
327
  end
317
328
 
329
+ # Net::HTTP reads a body stream with IO.copy_stream, which always passes
330
+ # a length, so some streams only accept #read with one. Such a stream is
331
+ # read in chunks. A stream that answers #read only through method_missing
332
+ # is read without a length, as before.
333
+ def self.read_body_stream(stream)
334
+ arity = begin
335
+ stream.method(:read).arity
336
+ rescue NameError
337
+ -1
338
+ end
339
+ return stream.read if arity == 0 || arity == -1
340
+
341
+ body = String.new
342
+ # As IO.copy_stream reads it: with a buffer, unless read takes only a
343
+ # length, and until it returns nil or an empty string, or raises
344
+ # EOFError.
345
+ buffer = String.new
346
+ begin
347
+ loop do
348
+ chunk = arity == 1 ? stream.read(16 * 1024) : stream.read(16 * 1024, buffer)
349
+ break if chunk.nil? || chunk.empty?
350
+
351
+ begin
352
+ body << chunk
353
+ rescue Encoding::CompatibilityError
354
+ # Chunks in incompatible encodings are joined as bytes.
355
+ body.force_encoding(Encoding::BINARY) << chunk.b
356
+ end
357
+ end
358
+ rescue EOFError
359
+ end
360
+ body
361
+ end
362
+
363
+ # The body Net::HTTPGenericRequest#send_request_with_body_data sends for
364
+ # a URL encoded form given as a Hash or an Array of pairs, which Net::HTTP
365
+ # encodes again when it sends the request. A multipart form, or a form
366
+ # given as another Enumerable, which may be read only once, gets no body,
367
+ # as before.
368
+ def self.form_body(request, form)
369
+ return unless form.is_a?(Hash) || form.is_a?(Array)
370
+ return if request.content_type =~ /\Amultipart\/form-data\z/i
371
+
372
+ URI.encode_www_form(form)
373
+ end
374
+
318
375
  def self.get_uri(net_http, path = nil)
319
376
  protocol = net_http.use_ssl? ? "https" : "http"
320
377
 
@@ -63,12 +63,19 @@ if defined?(Typhoeus)
63
63
  headers['Authorization'] = WebMock::Util::Headers.basic_auth_header(req.options[:userpwd])
64
64
  end
65
65
 
66
- body = req.options[:body]
67
-
68
- if body.is_a?(Hash)
69
- body = WebMock::Util::QueryMapper.values_to_query(body)
66
+ # libcurl sends the cookie option as a Cookie header, unless the
67
+ # request already has one. With libcurl's cookie engine on, it adds
68
+ # the cookies it keeps to that header, which can't be known here.
69
+ cookie = req.options[:cookie]
70
+ cookie_engine = %i[cookiefile cookiejar cookielist].any? { |option| req.options[option] }
71
+ if cookie && !cookie_engine && (headers || {}).keys.none? { |name| name.to_s.casecmp?('Cookie') }
72
+ headers = (headers || {}).merge('Cookie' => cookie)
70
73
  end
71
74
 
75
+ body = req.options[:body]
76
+ form = body.is_a?(Hash)
77
+ body = WebMock::Util::QueryMapper.values_to_query(body) if form
78
+
72
79
  request_signature = WebMock::RequestSignature.new(
73
80
  req.options[:method] || :get,
74
81
  uri.to_s,
@@ -76,11 +83,41 @@ if defined?(Typhoeus)
76
83
  headers: headers
77
84
  )
78
85
 
86
+ add_form_content_type(request_signature, req) if form
79
87
  req.instance_variable_set(:@__webmock_request_signature, request_signature)
80
88
 
81
89
  request_signature
82
90
  end
83
91
 
92
+ # libcurl adds this header when Ethon sends a Hash body as a URL
93
+ # encoded form: for a POST, even with an empty form, and for other
94
+ # methods with a form that isn't empty, except PUT, which Ethon
95
+ # uploads, and HEAD, which sends no body. A multipart form, with a
96
+ # file or the multipart option, is sent with a boundary instead, which
97
+ # isn't recorded. Ethon's own form decides whether a form is empty or
98
+ # multipart, since that differs between Ethon versions. A Content-Type
99
+ # given as content_type counts as set, since WebMock reads header
100
+ # names that way, though libcurl then sends both headers. With the
101
+ # nobody option, or when Ethon can't read the form, such as for a
102
+ # file without a path, no header is recorded, as before.
103
+ def self.add_form_content_type(signature, req)
104
+ headers = signature.headers || {}
105
+ return if headers.key?('Content-Type') || req.options[:nobody] || !defined?(::Ethon::Easy::Form)
106
+
107
+ form = ::Ethon::Easy::Form.new(nil, req.options[:body], req.options[:multipart])
108
+ if form.empty?
109
+ return unless signature.method == :post
110
+ else
111
+ return if [:put, :head].include?(signature.method)
112
+ form.params_encoding = req.options.fetch(:params_encoding, :typhoeus)
113
+ return if form.multipart?
114
+ end
115
+
116
+ signature.headers = headers.merge('Content-Type' => 'application/x-www-form-urlencoded')
117
+ rescue StandardError
118
+ nil
119
+ end
120
+
84
121
  def self.signature_for_history(signature)
85
122
  return signature unless signature.body.is_a?(Array)
86
123
 
@@ -176,7 +213,12 @@ if defined?(Typhoeus)
176
213
 
177
214
  AFTER_REQUEST_CALLBACK = Proc.new do |response|
178
215
  request = response.request
179
- request_signature = request.instance_variable_get(:@__webmock_request_signature)
216
+ # Another before callback, such as VCR's Typhoeus hook, can answer a
217
+ # request before WebMock's runs, and then WebMock has nothing to
218
+ # report. The signature is taken once, so a request that runs again
219
+ # isn't reported with the one from its earlier run.
220
+ next unless request.instance_variable_defined?(:@__webmock_request_signature)
221
+ request_signature = request.remove_instance_variable(:@__webmock_request_signature)
180
222
  webmock_response =
181
223
  ::WebMock::HttpLibAdapters::TyphoeusAdapter.
182
224
  build_webmock_response(response)
@@ -220,6 +262,9 @@ if defined?(Typhoeus)
220
262
  webmock_response.raise_error_if_any
221
263
  res = false
222
264
  elsif !WebMock.net_connect_allowed?(request_signature.uri)
265
+ # The request doesn't complete, so the callback that takes the
266
+ # signature off it doesn't run.
267
+ request.remove_instance_variable(:@__webmock_request_signature)
223
268
  raise WebMock::NetConnectNotAllowedError.new(request_signature)
224
269
  end
225
270
  end
@@ -14,7 +14,17 @@ module WebMock
14
14
  def body_diff
15
15
  return {} unless request_signature_diffable? && request_stub_diffable?
16
16
 
17
- Hashdiff.diff(request_signature_body_hash, request_stub_body_hash)
17
+ Hashdiff.diff(request_signature_body_hash, request_stub_body_hash) do |_path, actual, expected|
18
+ # A regexp that matches the request's value is not a difference.
19
+ # Anything else, including matchers and lambdas, which building a
20
+ # message must not run, is left to Hashdiff by returning nil.
21
+ begin
22
+ true if expected.is_a?(Regexp) && actual.is_a?(String) && expected.match?(actual)
23
+ rescue EncodingError
24
+ # A regexp and a value in incompatible encodings don't match.
25
+ nil
26
+ end
27
+ end
18
28
  end
19
29
 
20
30
  attr_reader :request_signature, :request_stub
@@ -55,8 +55,8 @@ module WebMock
55
55
 
56
56
  def failure_message_phrase(is_negated=false)
57
57
  negation = is_negated ? "was not" : "was"
58
- "The request #{request_pattern} #{negation} expected to execute #{quantity_phrase(is_negated)}but it executed #{times(times_executed)}" +
59
- (is_negated ? "" : json_body_hint) +
58
+ "The request #{Util::MessageString.utf8(request_pattern)} #{negation} expected to execute #{quantity_phrase(is_negated)}but it executed #{times(times_executed)}" +
59
+ (is_negated ? "" : json_body_hint + trailing_slash_hint) +
60
60
  self.class.executed_requests_message
61
61
  end
62
62
 
@@ -71,6 +71,17 @@ module WebMock
71
71
  requests.empty? ? "" : "\n\n#{JsonBodyHint::EXPECTATION_HINT}"
72
72
  end
73
73
 
74
+ # Only when too few requests matched, as for json_body_hint.
75
+ def trailing_slash_hint
76
+ return "" unless too_few_requests_executed?
77
+
78
+ RequestRegistry.instance.requested_signatures.each do |request_signature, _|
79
+ difference = TrailingSlashHint.difference(request_pattern, request_signature)
80
+ return "\n\n#{TrailingSlashHint::EXPECTATION_HINTS[difference]}" if difference
81
+ end
82
+ ""
83
+ end
84
+
74
85
  def too_few_requests_executed?
75
86
  if @at_least_times_executed
76
87
  times_executed < @at_least_times_executed
@@ -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
 
@@ -37,7 +69,8 @@ module WebMock
37
69
  def with(options = {}, &block)
38
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?
39
71
  assign_options(options)
40
- @with_block = block
72
+ # A later call with options only keeps the block given earlier.
73
+ @with_block = block if block
41
74
  @match_token = (@body_pattern || @with_block) && Object.new
42
75
  self
43
76
  end
@@ -144,21 +177,19 @@ module WebMock
144
177
  end
145
178
 
146
179
  def add_query_params(query_params)
147
- @query_params = if query_params.is_a?(Hash)
148
- 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)
149
187
  elsif query_params.equal?(:any) \
150
188
  || query_params.is_a?(WebMock::Matchers::AnyArgMatcher) \
151
189
  || rSpecAnyArgMatcher?(query_params)
152
190
  WebMock::Matchers::AnyArgMatcher.new(nil)
153
- elsif query_params.is_a?(WebMock::Matchers::HashIncludingMatcher) \
154
- || query_params.is_a?(WebMock::Matchers::HashExcludingMatcher)
155
- query_params
156
- elsif rSpecHashIncludingMatcher?(query_params)
157
- WebMock::Matchers::HashIncludingMatcher.from_rspec_matcher(query_params)
158
- elsif rSpecHashExcludingMatcher?(query_params)
159
- WebMock::Matchers::HashExcludingMatcher.from_rspec_matcher(query_params)
160
191
  elsif query_params.nil? || query_params.is_a?(String)
161
- 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))
162
193
  else
163
194
  raise ArgumentError, "Query should be a String, Hash, :any, nil, or a hash_including or hash_excluding matcher. Got: #{query_params.class}"
164
195
  end
@@ -174,6 +205,22 @@ module WebMock
174
205
  str
175
206
  end
176
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
+
177
224
  private
178
225
 
179
226
  def raise_any_query_with_uri_query
@@ -185,11 +232,28 @@ module WebMock
185
232
  end
186
233
 
187
234
  def query_params_matches?(uri)
188
- @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
189
247
  end
190
248
  end
191
249
 
192
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
+
193
257
  private
194
258
 
195
259
  def pattern_matches?(uri)
@@ -220,6 +284,10 @@ module WebMock
220
284
  end
221
285
  end
222
286
 
287
+ def to_snippet
288
+ "Addressable::Template.new(#{pattern_inspect})"
289
+ end
290
+
223
291
  private
224
292
 
225
293
  def pattern_matches?(uri)
@@ -243,11 +311,37 @@ module WebMock
243
311
  rescue Addressable::URI::InvalidURIError
244
312
  Addressable::Template.new(@pattern.pattern)
245
313
  end
246
- 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|
247
330
  template_matches_uri?(template, u)
248
331
  }
249
332
  end
250
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
+
251
345
  def template_matches_uri?(template, uri)
252
346
  template.match(uri)
253
347
  rescue Addressable::URI::InvalidURIError
@@ -257,17 +351,36 @@ module WebMock
257
351
 
258
352
  class URIStringPattern < URIPattern
259
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)
260
356
  super
261
357
  if @query_params.is_a?(Hash) || @query_params.is_a?(String)
262
- query_hash = (WebMock::Util::QueryMapper.query_to_values(@pattern.query, notation: Config.instance.query_values_notation) || {}).merge(@query_params)
263
- @pattern.query = WebMock::Util::QueryMapper.values_to_query(query_hash, notation: WebMock::Config.instance.query_values_notation)
264
- @query_params = nil
265
- 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)
266
369
  # The URI is then compared without its query, so it could never match.
267
370
  raise_any_query_with_uri_query
268
371
  end
269
372
  end
270
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
+
271
384
  private
272
385
 
273
386
  def pattern_matches?(uri)
@@ -291,21 +404,23 @@ module WebMock
291
404
  class BodyPattern
292
405
  include RSpecMatcherDetector
293
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
+
294
417
  # Kept so existing references to the constant still resolve.
295
418
  BODY_FORMATS = WebMock::Util::ContentType::BODY_FORMATS
296
419
 
297
420
  attr_reader :pattern
298
421
 
299
422
  def initialize(pattern)
300
- @pattern = if pattern.is_a?(Hash)
301
- normalize_hash(pattern)
302
- elsif rSpecHashIncludingMatcher?(pattern)
303
- WebMock::Matchers::HashIncludingMatcher.from_rspec_matcher(pattern)
304
- elsif rSpecHashExcludingMatcher?(pattern)
305
- WebMock::Matchers::HashExcludingMatcher.from_rspec_matcher(pattern)
306
- else
307
- pattern
308
- end
423
+ @pattern = pattern.is_a?(Hash) ? normalize_hash(pattern) : webmock_hash_matcher(pattern)
309
424
  end
310
425
 
311
426
  def matches?(body, content_type = "", serialized_body = nil)
@@ -349,6 +464,9 @@ module WebMock
349
464
  when :xml then
350
465
  WebMock::Util::Parsers::XML.parse(body)
351
466
  else
467
+ # A body that isn't valid UTF-8, such as an uploaded file, can't be
468
+ # a URL encoded form, so it doesn't match a hash.
469
+ return unless self.class.form_parseable?(body)
352
470
  WebMock::Util::QueryMapper.query_to_values(body, notation: Config.instance.query_values_notation)
353
471
  end
354
472
  rescue WebMock::Util::Parsers::ParseError
@@ -88,7 +88,7 @@ module WebMock
88
88
  else
89
89
  text = "".dup
90
90
  self.requested_signatures.each do |request_signature, times_executed|
91
- 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"
92
92
  end
93
93
  text
94
94
  end
@@ -17,9 +17,11 @@ module WebMock
17
17
  def to_s
18
18
  string = "#{self.method.to_s.upcase}".dup
19
19
  string << " #{WebMock::Util::URI.strip_default_port_from_uri_string(self.uri.to_s)}"
20
- 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 != ''
21
23
  if headers && !headers.empty?
22
- 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))}"
23
25
  end
24
26
  string
25
27
  end
@@ -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
@@ -33,7 +33,7 @@ module WebMock
33
33
  def headers=(headers)
34
34
  @headers = headers
35
35
  if @headers && !@headers.is_a?(Proc)
36
- @headers = Util::Headers.normalize_headers(@headers)
36
+ @headers = Util::Headers.normalize_response_headers(@headers)
37
37
  end
38
38
  end
39
39
 
@@ -52,7 +52,16 @@ module WebMock
52
52
  end
53
53
 
54
54
  def status=(status)
55
- @status = status.is_a?(Integer) ? [status, ""] : status
55
+ @status = if status.is_a?(Integer)
56
+ [status, ""]
57
+ elsif status_code?(status)
58
+ # A string such as "201" would reach clients as the code "2"
59
+ [status.to_i, ""]
60
+ else
61
+ # nil and false give the default status, as before.
62
+ check_status(status) unless status.nil? || status == false || status.is_a?(Proc)
63
+ status
64
+ end
56
65
  end
57
66
 
58
67
  def exception
@@ -104,6 +113,32 @@ module WebMock
104
113
 
105
114
  private
106
115
 
116
+ WARNED_STATUSES = {}
117
+ private_constant :WARNED_STATUSES
118
+
119
+ def status_code?(value)
120
+ value.is_a?(String) && value.match?(/\A\d+\z/)
121
+ end
122
+
123
+ # A Symbol, a String that isn't digits or a Float, given as the status or
124
+ # as the code of a pair, reaches clients as a broken status, so it is
125
+ # deprecated. Anything else is kept as given, as before, since some
126
+ # clients read other values, such as an Enumerator, as they should.
127
+ def check_status(status)
128
+ code = status.is_a?(Array) ? status.first : status
129
+ return unless code.is_a?(Symbol) || code.is_a?(String) || code.is_a?(Float)
130
+ return if status_code?(code)
131
+
132
+ key = status.inspect
133
+ return if WARNED_STATUSES[key]
134
+ WARNED_STATUSES[key] = true
135
+ rack_hint = code.is_a?(Symbol) ? ", or Rack::Utils.status_code(#{code.inspect}) in a Rack app" : ""
136
+ WebMock::Deprecation.warning(
137
+ "status #{key} is not an HTTP status code, so HTTP clients get a broken status from it. " \
138
+ "Use a number such as 200#{rack_hint}. WebMock 4.0 will raise ArgumentError for it."
139
+ )
140
+ end
141
+
107
142
  def stringify_body!
108
143
  if @body.is_a?(IO) || @body.is_a?(Pathname)
109
144
  io = @body
@@ -133,7 +168,11 @@ module WebMock
133
168
 
134
169
  options = {}
135
170
  options[:headers] = {}
136
- response.each_header {|name, value| options[:headers][name] = value}
171
+ # Each Set-Cookie line is a cookie of its own, and a cookie such as one
172
+ # with Expires=Wed, 21 Oct 2026 can't be split back out of joined ones.
173
+ response.each_header do |name, value|
174
+ options[:headers][name] = name == "set-cookie" ? response.get_fields(name) : value
175
+ end
137
176
  options[:headers]['transfer-encoding'] = transfer_encoding if transfer_encoding
138
177
  options[:body] = response.read_body
139
178
  options[:status] = [response.code.to_i, response.message]