webmock 3.38.0 → 3.40.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.
@@ -37,14 +37,43 @@ module HTTP
37
37
 
38
38
  return unless webmock_response
39
39
 
40
- raise_timeout_error if webmock_response.should_timeout
41
- webmock_response.raise_error_if_any
40
+ features = @options.features.values
41
+ response = nil
42
+ exchange = ->(_request) { response = replay_response(features, webmock_response) }
43
+ # HTTP.rb 6 instruments a request in around_request, inside the
44
+ # HTTP::Client#perform a stub skips, so the instrumentation runs around
45
+ # a stubbed exchange too. Other features that run around the exchange,
46
+ # such as caching and digest_auth, don't run for a stub. The stub's
47
+ # response is returned whatever an instrumenter returns, and also when
48
+ # one doesn't yield, as before.
49
+ instrumentation(features).reverse.reduce(exchange) do |inner, feature|
50
+ ->(request) { feature.around_request(request) { |r| inner.call(r) } }
51
+ end.call(@request)
52
+ response || replay_response(features, webmock_response)
53
+ end
54
+
55
+ def instrumentation(features)
56
+ return [] unless defined?(::HTTP::Features::Instrumentation) && ::HTTP::Feature.method_defined?(:around_request)
57
+
58
+ features.select { |feature| feature.is_a?(::HTTP::Features::Instrumentation) }
59
+ end
60
+
61
+ def replay_response(features, webmock_response)
62
+ # HTTP::Client calls on_error for an error while sending, which for a
63
+ # stub is its timeout or error, but not for one raised while wrapping
64
+ # the response, as the raise_error feature does for a 500.
65
+ begin
66
+ raise_timeout_error if webmock_response.should_timeout
67
+ webmock_response.raise_error_if_any
68
+ rescue ::HTTP::Error => e
69
+ features.each { |feature| feature.on_error(@request, e) if feature.respond_to?(:on_error) }
70
+ raise
71
+ end
42
72
 
43
73
  invoke_callbacks(webmock_response, real_request: false)
44
74
  response = ::HTTP::Response.from_webmock @request, webmock_response, request_signature
45
75
 
46
76
  # HTTP.rb 6.0+ wraps responses in reverse feature order
47
- features = @options.features.values
48
77
  features = features.reverse if HTTP::VERSION >= "6.0.0"
49
78
  features.each { |feature| response = feature.wrap_response(response) }
50
79
  response
@@ -106,10 +106,12 @@ if defined?(::HTTPClient)
106
106
  if webmock_response
107
107
  response = build_httpclient_response(webmock_response, false, req.header, &block)
108
108
  filters.each { |filter| filter.filter_response(req, response) }
109
- res = conn.push(response)
109
+ conn.push(response)
110
110
  WebMock::CallbackRegistry.invoke_callbacks(
111
111
  {lib: :httpclient}, request_signature, webmock_response)
112
- res
112
+ # Return the response, as HTTPClient#do_get_block does. Libraries that
113
+ # wrap the method to trace requests read its result.
114
+ response
113
115
  elsif WebMock.net_connect_allowed?(request_signature.uri)
114
116
  clone(freeze: false).send_prepared_sync_request(req, proxy, conn, filters, request_signature, &block)
115
117
  else
@@ -304,10 +304,19 @@ module WebMock
304
304
  headers = Hash[*request.to_hash.map {|k,v| [k, v]}.inject([]) {|r,x| r + x}]
305
305
 
306
306
  if request.body_stream
307
- body = request.body_stream.read
307
+ body = read_body_stream(request.body_stream)
308
308
  request.body_stream = nil
309
309
  end
310
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
+
311
320
  if body != nil && body.respond_to?(:read)
312
321
  request.set_body_internal body.read
313
322
  else
@@ -317,6 +326,52 @@ module WebMock
317
326
  WebMock::RequestSignature.new(method, uri, body: request.body, headers: headers)
318
327
  end
319
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
+
320
375
  def self.get_uri(net_http, path = nil)
321
376
  protocol = net_http.use_ssl? ? "https" : "http"
322
377
 
@@ -63,6 +63,15 @@ if defined?(Typhoeus)
63
63
  headers['Authorization'] = WebMock::Util::Headers.basic_auth_header(req.options[:userpwd])
64
64
  end
65
65
 
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)
73
+ end
74
+
66
75
  body = req.options[:body]
67
76
  form = body.is_a?(Hash)
68
77
  body = WebMock::Util::QueryMapper.values_to_query(body) if form
@@ -204,7 +213,12 @@ if defined?(Typhoeus)
204
213
 
205
214
  AFTER_REQUEST_CALLBACK = Proc.new do |response|
206
215
  request = response.request
207
- 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)
208
222
  webmock_response =
209
223
  ::WebMock::HttpLibAdapters::TyphoeusAdapter.
210
224
  build_webmock_response(response)
@@ -248,6 +262,9 @@ if defined?(Typhoeus)
248
262
  webmock_response.raise_error_if_any
249
263
  res = false
250
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)
251
268
  raise WebMock::NetConnectNotAllowedError.new(request_signature)
252
269
  end
253
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
@@ -205,6 +205,22 @@ module WebMock
205
205
  str
206
206
  end
207
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
+
208
224
  private
209
225
 
210
226
  def raise_any_query_with_uri_query
@@ -232,6 +248,12 @@ module WebMock
232
248
  end
233
249
 
234
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
+
235
257
  private
236
258
 
237
259
  def pattern_matches?(uri)
@@ -262,6 +284,10 @@ module WebMock
262
284
  end
263
285
  end
264
286
 
287
+ def to_snippet
288
+ "Addressable::Template.new(#{pattern_inspect})"
289
+ end
290
+
265
291
  private
266
292
 
267
293
  def pattern_matches?(uri)
@@ -345,6 +371,16 @@ module WebMock
345
371
  end
346
372
  end
347
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
+
348
384
  private
349
385
 
350
386
  def pattern_matches?(uri)
@@ -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)}"
@@ -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]
@@ -13,18 +13,24 @@ module WebMock
13
13
  def to_s(with_response = true)
14
14
  request_pattern = @request_stub.request_pattern
15
15
  string = "stub_request(:#{request_pattern.method_pattern.to_s},".dup
16
- string << " \"#{request_pattern.uri_pattern.to_s}\")"
16
+ string << " #{request_pattern.uri_pattern.to_snippet})"
17
17
 
18
18
  with = "".dup
19
19
 
20
+ if (query = request_pattern.uri_pattern.query_snippet)
21
+ with << "\n query: #{query}"
22
+ end
23
+
20
24
  if (request_pattern.body_pattern)
21
- with << "\n body: #{request_pattern.body_pattern.to_s}"
25
+ with << "," unless with.empty?
26
+ # In UTF-8, so a body and headers in other encodings can be joined.
27
+ with << "\n body: #{WebMock::Util::MessageString.utf8(request_pattern.body_pattern.to_s)}"
22
28
  end
23
29
 
24
30
  if (request_pattern.headers_pattern)
25
31
  with << "," unless with.empty?
26
32
 
27
- with << "\n headers: #{request_pattern.headers_pattern.pp_to_s}"
33
+ with << "\n headers: #{WebMock::Util::MessageString.utf8(request_pattern.headers_pattern.pp_to_s)}"
28
34
  end
29
35
  string << ".\n with(#{with})" unless with.empty?
30
36
  if with_response
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ module WebMock
4
+ # Stubs treat "/users" and "/users/" as different URLs, since servers can
5
+ # treat them differently. When a slash at the end of the path is the only
6
+ # reason a request doesn't match, failure messages point it out. See #864.
7
+ module TrailingSlashHint
8
+ STUB_HINTS = {
9
+ added: "Hint: the request URL ends with a slash and the URL of this stub doesn't, " \
10
+ "so they are different URLs.",
11
+ removed: "Hint: the URL of this stub ends with a slash and the request URL doesn't, " \
12
+ "so they are different URLs."
13
+ }.freeze
14
+
15
+ EXPECTATION_HINTS = {
16
+ added: "Hint: a request was made to the expected URL with a slash at the end, " \
17
+ "which is a different URL.",
18
+ removed: "Hint: a request was made to the expected URL without the slash at the end, " \
19
+ "which is a different URL."
20
+ }.freeze
21
+
22
+ # :added when the request path ends with a slash that the URL of the
23
+ # pattern doesn't have, :removed for the reverse, and nil otherwise. Only
24
+ # for a URL given as a string, and only the method and the URL without
25
+ # its query are compared: the hint is about the path, and building a
26
+ # failure message must not run code given to with, or raise.
27
+ def self.difference(request_pattern, request_signature)
28
+ patterns = parts_of(request_pattern)
29
+ return unless patterns.all? { |pattern| pattern.is_a?(RequestPattern) }
30
+ return unless patterns.first.uri_pattern.is_a?(URIStringPattern)
31
+
32
+ path = request_signature.uri.path
33
+ return if path.empty? || path == "/"
34
+
35
+ ends_with_slash = path.end_with?("/")
36
+ toggled = request_signature.uri.dup
37
+ toggled.path = ends_with_slash ? path.chomp("/") : "#{path}/"
38
+ # Other parts, such as the conditions of an expectation, match any URI.
39
+ return unless patterns.first.uri_pattern.matches_without_query?(toggled)
40
+ return unless patterns.all? { |pattern| pattern.method_pattern.matches?(request_signature.method) }
41
+
42
+ ends_with_slash ? :added : :removed
43
+ rescue StandardError
44
+ nil
45
+ end
46
+
47
+ # A pattern made of parts that must all match, such as an RSpec expectation
48
+ # with conditions, responds to #patterns. A stub stands for its pattern.
49
+ def self.parts_of(request_pattern)
50
+ parts = request_pattern.respond_to?(:patterns) ? request_pattern.patterns : [request_pattern]
51
+ parts.map { |part| part.is_a?(RequestStub) ? part.request_pattern : part }
52
+ end
53
+ private_class_method :parts_of
54
+ end
55
+ end
@@ -23,6 +23,23 @@ module WebMock
23
23
  end
24
24
  end
25
25
 
26
+ # The headers of a response. normalize_headers sorts repeated values, so
27
+ # the order they are given in doesn't matter for matching, but of two
28
+ # cookies with the same name a client keeps the last one, so Set-Cookie
29
+ # values are put back in the order given. normalize_headers is called
30
+ # with the headers alone, as before, since some test suites replace it
31
+ # with a method that takes one argument.
32
+ def self.normalize_response_headers(headers)
33
+ normalized = normalize_headers(headers)
34
+ return normalized unless normalized.is_a?(Hash) && normalized["Set-Cookie"].is_a?(Array)
35
+
36
+ cookies = nil
37
+ headers.each do |name, value|
38
+ cookies = value if value.is_a?(Array) && value.size > 1 && normalize_name(name) == "Set-Cookie"
39
+ end
40
+ cookies ? normalized.merge("Set-Cookie" => cookies.map(&:to_s)) : normalized
41
+ end
42
+
26
43
  def self.sorted_headers_string(headers)
27
44
  headers = WebMock::Util::Headers.normalize_headers(headers)
28
45
  str = '{'.dup
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module WebMock
4
+ module Util
5
+ # Failure messages join request bodies of any encoding, which raised
6
+ # Encoding::CompatibilityError for a UTF-8 body next to a binary one.
7
+ # Each part is converted to UTF-8 for display only: bytes that aren't
8
+ # valid UTF-8 are shown escaped, as in "\xFF", and the requests and
9
+ # their signatures keep their own encoding.
10
+ module MessageString
11
+ def self.utf8(value)
12
+ string = value.to_s
13
+ return string if string.ascii_only? || (string.encoding == Encoding::UTF_8 && string.valid_encoding?)
14
+
15
+ if string.encoding == Encoding::BINARY || string.encoding == Encoding::UTF_8
16
+ string.dup.force_encoding(Encoding::UTF_8).scrub { |bytes| escape(bytes) }
17
+ else
18
+ string.encode(Encoding::UTF_8, invalid: :replace, undef: :replace)
19
+ end
20
+ end
21
+
22
+ def self.escape(bytes)
23
+ bytes.unpack("C*").map { |byte| format("\\x%02X", byte) }.join
24
+ end
25
+ private_class_method :escape
26
+ end
27
+ end
28
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module WebMock
4
- VERSION = '3.38.0' unless defined?(::WebMock::VERSION)
4
+ VERSION = '3.40.0' unless defined?(::WebMock::VERSION)
5
5
  end
@@ -82,6 +82,14 @@ module WebMock
82
82
  end
83
83
 
84
84
  def self.net_connect_allowed?(uri = nil)
85
+ net_connect_allowed_by_settings?(uri)
86
+ end
87
+
88
+ # Whether WebMock's own settings allow a real connection. VCR, for one,
89
+ # redefines net_connect_allowed? to allow every request and decides each
90
+ # one in a global stub, so a connection that no stub sees, such as one
91
+ # taken from an async-http connection pool, is checked with this.
92
+ def self.net_connect_allowed_by_settings?(uri = nil)
85
93
  return !!Config.instance.allow_net_connect if uri.nil?
86
94
 
87
95
  if uri.is_a?(String)
data/lib/webmock.rb CHANGED
@@ -16,6 +16,7 @@ require_relative 'webmock/util/headers'
16
16
  require_relative 'webmock/util/content_type'
17
17
  require_relative 'webmock/util/hash_counter'
18
18
  require_relative 'webmock/util/upload_body'
19
+ require_relative 'webmock/util/message_string'
19
20
  require_relative 'webmock/util/hash_keys_stringifier'
20
21
  require_relative 'webmock/util/values_stringifier'
21
22
  require_relative 'webmock/util/parsers/json'
@@ -39,6 +40,7 @@ require_relative 'webmock/stub_request_snippet'
39
40
  require_relative 'webmock/request_signature_snippet'
40
41
  require_relative 'webmock/request_body_diff'
41
42
  require_relative 'webmock/json_body_hint'
43
+ require_relative 'webmock/trailing_slash_hint'
42
44
 
43
45
  require_relative 'webmock/assertion_failure'
44
46
  require_relative 'webmock/request_execution_verifier'
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: webmock
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.38.0
4
+ version: 3.40.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Bartosz Blimke
@@ -341,11 +341,13 @@ files:
341
341
  - lib/webmock/stub_registry.rb
342
342
  - lib/webmock/stub_request_snippet.rb
343
343
  - lib/webmock/test_unit.rb
344
+ - lib/webmock/trailing_slash_hint.rb
344
345
  - lib/webmock/util/content_type.rb
345
346
  - lib/webmock/util/hash_counter.rb
346
347
  - lib/webmock/util/hash_keys_stringifier.rb
347
348
  - lib/webmock/util/hash_validator.rb
348
349
  - lib/webmock/util/headers.rb
350
+ - lib/webmock/util/message_string.rb
349
351
  - lib/webmock/util/parsers/json.rb
350
352
  - lib/webmock/util/parsers/parse_error.rb
351
353
  - lib/webmock/util/parsers/xml.rb
@@ -361,9 +363,9 @@ licenses:
361
363
  - MIT
362
364
  metadata:
363
365
  bug_tracker_uri: https://github.com/bblimke/webmock/issues
364
- changelog_uri: https://github.com/bblimke/webmock/blob/v3.38.0/CHANGELOG.md
365
- documentation_uri: https://www.rubydoc.info/gems/webmock/3.38.0
366
- source_code_uri: https://github.com/bblimke/webmock/tree/v3.38.0
366
+ changelog_uri: https://github.com/bblimke/webmock/blob/v3.40.0/CHANGELOG.md
367
+ documentation_uri: https://www.rubydoc.info/gems/webmock/3.40.0
368
+ source_code_uri: https://github.com/bblimke/webmock/tree/v3.40.0
367
369
  wiki_uri: https://github.com/bblimke/webmock/wiki
368
370
  rdoc_options: []
369
371
  require_paths: