webmock 3.36.0 → 4.0.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 (41) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +335 -0
  3. data/README.md +227 -6
  4. data/lib/webmock/api.rb +4 -0
  5. data/lib/webmock/callback_registry.rb +14 -7
  6. data/lib/webmock/errors.rb +1 -1
  7. data/lib/webmock/http_lib_adapters/async_http_client_adapter.rb +18 -1
  8. data/lib/webmock/http_lib_adapters/curb_adapter.rb +292 -46
  9. data/lib/webmock/http_lib_adapters/em_http_request_adapter.rb +11 -3
  10. data/lib/webmock/http_lib_adapters/excon_adapter.rb +23 -2
  11. data/lib/webmock/http_lib_adapters/http_rb/response.rb +3 -0
  12. data/lib/webmock/http_lib_adapters/http_rb/webmock.rb +92 -5
  13. data/lib/webmock/http_lib_adapters/httpclient_adapter.rb +127 -109
  14. data/lib/webmock/http_lib_adapters/manticore_adapter.rb +1 -1
  15. data/lib/webmock/http_lib_adapters/net_http.rb +78 -10
  16. data/lib/webmock/http_lib_adapters/patron_adapter.rb +32 -13
  17. data/lib/webmock/http_lib_adapters/typhoeus_hydra_adapter.rb +65 -7
  18. data/lib/webmock/json_body_hint.rb +119 -12
  19. data/lib/webmock/request_body_diff.rb +16 -6
  20. data/lib/webmock/request_execution_verifier.rb +19 -6
  21. data/lib/webmock/request_pattern.rb +178 -33
  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 +33 -4
  25. data/lib/webmock/request_stub.rb +32 -7
  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 +23 -54
  35. data/lib/webmock/util/upload_body.rb +63 -0
  36. data/lib/webmock/util/uri.rb +21 -12
  37. data/lib/webmock/util/values_stringifier.rb +54 -0
  38. data/lib/webmock/version.rb +1 -1
  39. data/lib/webmock/webmock.rb +35 -4
  40. data/lib/webmock.rb +3 -0
  41. metadata +10 -7
@@ -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
@@ -62,12 +63,19 @@ if defined?(Typhoeus)
62
63
  headers['Authorization'] = WebMock::Util::Headers.basic_auth_header(req.options[:userpwd])
63
64
  end
64
65
 
65
- body = req.options[:body]
66
-
67
- if body.is_a?(Hash)
68
- 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)
69
73
  end
70
74
 
75
+ body = req.options[:body]
76
+ form = body.is_a?(Hash)
77
+ body = WebMock::Util::QueryMapper.values_to_query(body) if form
78
+
71
79
  request_signature = WebMock::RequestSignature.new(
72
80
  req.options[:method] || :get,
73
81
  uri.to_s,
@@ -75,11 +83,53 @@ if defined?(Typhoeus)
75
83
  headers: headers
76
84
  )
77
85
 
86
+ add_form_content_type(request_signature, req) if form
78
87
  req.instance_variable_set(:@__webmock_request_signature, request_signature)
79
88
 
80
89
  request_signature
81
90
  end
82
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
+
121
+ def self.signature_for_history(signature)
122
+ return signature unless signature.body.is_a?(Array)
123
+
124
+ # Ethon uploads file parts by path and stringifies non-scalar form values.
125
+ signature.with_body_values do |value|
126
+ case value
127
+ when File, Tempfile then Pathname.new(value.path)
128
+ when String, Numeric, Symbol, TrueClass, FalseClass, NilClass then value
129
+ else value.to_s
130
+ end
131
+ end
132
+ end
83
133
 
84
134
  def self.build_webmock_response(typhoeus_response)
85
135
  webmock_response = WebMock::Response.new
@@ -163,7 +213,12 @@ if defined?(Typhoeus)
163
213
 
164
214
  AFTER_REQUEST_CALLBACK = Proc.new do |response|
165
215
  request = response.request
166
- 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)
167
222
  webmock_response =
168
223
  ::WebMock::HttpLibAdapters::TyphoeusAdapter.
169
224
  build_webmock_response(response)
@@ -192,9 +247,9 @@ if defined?(Typhoeus)
192
247
  request_signature = ::WebMock::HttpLibAdapters::TyphoeusAdapter.build_request_signature(request, url)
193
248
  request.block_connection = false;
194
249
 
195
- ::WebMock::RequestRegistry.instance.requested_signatures.put(request_signature)
250
+ recorded = ::WebMock::HttpLibAdapters::TyphoeusAdapter.signature_for_history(request_signature)
196
251
 
197
- if webmock_response = ::WebMock::StubRegistry.instance.response_for_request(request_signature)
252
+ if webmock_response = ::WebMock::StubRegistry.instance.response_for_request(request_signature, record: recorded)
198
253
  response = ::WebMock::HttpLibAdapters::TyphoeusAdapter.generate_typhoeus_response(webmock_response, url)
199
254
  if request.respond_to?(:on_headers)
200
255
  request.execute_headers_callbacks(response)
@@ -207,6 +262,9 @@ if defined?(Typhoeus)
207
262
  webmock_response.raise_error_if_any
208
263
  res = false
209
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)
210
268
  raise WebMock::NetConnectNotAllowedError.new(request_signature)
211
269
  end
212
270
  end
@@ -3,10 +3,21 @@
3
3
  require "json"
4
4
 
5
5
  module WebMock
6
+ # Hints in failure messages about JSON request bodies.
7
+ #
6
8
  # A body declared as a string must match the request body exactly, which for
7
9
  # JSON includes key order and whitespace. When a request fails to match only
8
10
  # because of that, failure messages suggest declaring the body as a hash.
9
11
  # See #485.
12
+ #
13
+ # A body declared as a hash, an array, hash_including or hash_excluding is
14
+ # matched against the body as JSON.parse reads it, unless it matches any
15
+ # body, as {} does, while WebMock 3.x also read some invalid JSON, such as
16
+ # {a: 1}. When a request fails to match only because its body isn't valid
17
+ # JSON, failure messages say so.
18
+ #
19
+ # A hint is extra, so an error while working one out, for example from a
20
+ # header pattern, means no hint rather than a broken failure message.
10
21
  module JsonBodyHint
11
22
  ADVICE = "A body declared as a string must match exactly. To match it as JSON, " \
12
23
  "declare it as a hash, for example with(body: JSON.parse(json_string))."
@@ -17,6 +28,20 @@ module WebMock
17
28
  EXPECTATION_HINT = "Hint: a request was made with the same JSON body as expected, " \
18
29
  "but formatted differently, for example with keys in another order. #{ADVICE}"
19
30
 
31
+ INVALID_JSON_ADVICE = "WebMock 4.0 and later read JSON request bodies only with JSON.parse, " \
32
+ "while earlier versions also matched some bodies that aren't valid JSON, such as {a: 1}."
33
+
34
+ BYTE_ORDER_MARK = [0xEF, 0xBB, 0xBF].pack("C*").freeze
35
+ private_constant :BYTE_ORDER_MARK
36
+
37
+ # %s is the parser's error.
38
+ INVALID_JSON_HINTS = {
39
+ stub: "Hint: the request body isn't valid JSON (%s), so a stub above with a body declared as " \
40
+ "a hash, an array, hash_including or hash_excluding can't match it. #{INVALID_JSON_ADVICE}",
41
+ expectation: "Hint: a request was made with a body that isn't valid JSON (%s), " \
42
+ "so it can't match the expected body. #{INVALID_JSON_ADVICE}"
43
+ }.freeze
44
+
20
45
  # True when one of the patterns declares its body as a JSON object or array
21
46
  # string, the request has a JSON content type and a body that parses to the
22
47
  # same JSON but is written differently, and the method, URI and headers of
@@ -31,14 +56,46 @@ module WebMock
31
56
  # The body is checked first, since that runs no user code, so URI and
32
57
  # header matchers are only evaluated when a hint is otherwise possible.
33
58
  def self.applies?(request_pattern, request_signature)
34
- patterns = parts_of(request_pattern)
35
- return false unless patterns.all? { |pattern| pattern.is_a?(RequestPattern) && pattern.with_block.nil? }
36
-
37
- with_body = patterns.select(&:body_pattern)
38
- return false unless with_body.size == 1
39
- return false unless body_differs_only_in_formatting?(with_body.first.body_pattern, request_signature)
59
+ patterns, body_pattern = body_pattern_of(request_pattern)
60
+ return false unless body_pattern && body_differs_only_in_formatting?(body_pattern, request_signature)
40
61
 
41
62
  patterns.all? { |pattern| matches_except_body?(pattern, request_signature) }
63
+ rescue StandardError
64
+ false
65
+ end
66
+
67
+ # The hint for an expected request that didn't match: that the JSON is
68
+ # formatted differently, or that the body isn't valid JSON. At most one of
69
+ # them fits, since one needs a body declared as a string and the other a
70
+ # hash, an array, hash_including or hash_excluding.
71
+ def self.expectation_hint(request_pattern, request_signature)
72
+ return EXPECTATION_HINT if applies?(request_pattern, request_signature)
73
+
74
+ invalid_json_hint([request_pattern], request_signature, :expectation)
75
+ end
76
+
77
+ # The hint, for kind :stub or :expectation, when the request body isn't
78
+ # valid JSON and that is the only reason one of the patterns doesn't
79
+ # match: it declares its body as a hash, an array, hash_including or
80
+ # hash_excluding, which doesn't match a body that doesn't parse, and the
81
+ # method, URI and headers of all of its parts match the request. The
82
+ # body is parsed at most once, and only when a pattern could get the hint.
83
+ def self.invalid_json_hint(request_patterns, request_signature, kind)
84
+ candidates = request_patterns.filter_map { |request_pattern| body_pattern_of(request_pattern) }
85
+ # Method patterns run no user code, so they can rule out patterns
86
+ # before the body is parsed.
87
+ candidates.select! do |patterns, body_pattern|
88
+ body_pattern.parses_body? && patterns.all? { |pattern| pattern.method_pattern.matches?(request_signature.method) }
89
+ end
90
+ return if candidates.empty? || !request_signature.json_headers?
91
+
92
+ # The body that a hash or array pattern reads, as in BodyPattern#matches?.
93
+ error = parse_error(request_signature.serialized_body || request_signature.body)
94
+ return unless error && candidates.any? { |patterns, body_pattern| fails_only_on_body?(patterns, body_pattern, request_signature) }
95
+
96
+ format(INVALID_JSON_HINTS.fetch(kind), short_error(error))
97
+ rescue StandardError
98
+ nil
42
99
  end
43
100
 
44
101
  # A pattern made of parts that must all match, such as an RSpec expectation
@@ -48,17 +105,66 @@ module WebMock
48
105
  parts.map { |part| part.is_a?(RequestStub) ? part.request_pattern : part }
49
106
  end
50
107
 
108
+ # The parts of the pattern and the body pattern of the only part that
109
+ # declares a body, or nil when none or several do, or when a part has a
110
+ # block given to with.
111
+ def self.body_pattern_of(request_pattern)
112
+ patterns = parts_of(request_pattern)
113
+ return unless patterns.all? { |pattern| pattern.is_a?(RequestPattern) && pattern.with_block.nil? }
114
+
115
+ with_body = patterns.select(&:body_pattern)
116
+ [patterns, with_body.first.body_pattern] if with_body.size == 1
117
+ end
118
+
51
119
  def self.body_differs_only_in_formatting?(body_pattern, request_signature)
52
120
  expected = body_pattern.pattern
53
121
  actual = request_signature.body
54
122
  return false unless expected.is_a?(String) && actual.is_a?(String) && expected != actual
55
123
  return false unless request_signature.json_headers?
56
124
 
57
- expected_json = parse_json(expected)
125
+ # The advice is to declare the body as JSON.parse(json_string), so
126
+ # the stub's string must parse with JSON.parse itself. The request
127
+ # body is read as WebMock reads it for matching.
128
+ expected_json = parse_json { ::JSON.parse(expected) }
58
129
  return false unless expected_json.is_a?(Hash) || expected_json.is_a?(Array)
59
130
 
60
131
  # eql? compares nested values strictly, so 1 and 1.0 are different.
61
- expected_json.eql?(parse_json(actual))
132
+ expected_json.eql?(parse_json { WebMock::Util::Parsers::JSON.parse(actual) })
133
+ end
134
+
135
+ # A body that doesn't parse reaches the body pattern as no body, so it is
136
+ # given none here: the body isn't parsed again, and no user code runs, as
137
+ # the pattern has nothing to compare its values with. Some patterns, such
138
+ # as hash_including({}), match any body, so they get no hint. A pattern
139
+ # that raises, for example a header regexp in an encoding that doesn't
140
+ # fit the request header, gets no hint, while the others still can.
141
+ def self.fails_only_on_body?(patterns, body_pattern, request_signature)
142
+ !body_pattern.matches?(nil, request_signature.content_type) &&
143
+ patterns.all? { |pattern| matches_except_body?(pattern, request_signature) }
144
+ rescue StandardError
145
+ false
146
+ end
147
+
148
+ # The parser's error, or nil when the body parses, is blank after a byte
149
+ # order mark, which the parser drops, or is nested deeper than WebMock
150
+ # reads. None of those is what the hint is about.
151
+ def self.parse_error(body)
152
+ return unless body.is_a?(String) && !body.b.delete_prefix(BYTE_ORDER_MARK).match?(/\A[ \t\r\n]*\z/)
153
+
154
+ WebMock::Util::Parsers::JSON.parse(body)
155
+ nil
156
+ rescue WebMock::Util::Parsers::ParseError => error
157
+ error.message unless error.cause.is_a?(::JSON::NestingError)
158
+ end
159
+
160
+ # Older json versions quote the rest of the body, json 2.5 starts with a
161
+ # line of its C source, such as "809: ", and json 2.8 and 2.9 cut the
162
+ # quote at 32 bytes, which can leave part of a character at the end.
163
+ def self.short_error(message)
164
+ message = message.delete_prefix(WebMock::Util::Parsers::JSON::ERROR_PREFIX)
165
+ cut = message.length > 1000
166
+ message = WebMock::Util::MessageString.utf8(message[0, 1000].scrub("")).gsub(/\s+/, " ").sub(/\A\d+: /, "").strip
167
+ cut || message.length > 100 ? "#{message[0, 100]}..." : message
62
168
  end
63
169
 
64
170
  def self.matches_except_body?(request_pattern, request_signature)
@@ -67,11 +173,12 @@ module WebMock
67
173
  (request_pattern.headers_pattern.nil? || request_pattern.headers_pattern.matches?(request_signature.headers))
68
174
  end
69
175
 
70
- def self.parse_json(string)
71
- ::JSON.parse(string)
72
- rescue ::JSON::JSONError, EncodingError
176
+ def self.parse_json
177
+ yield
178
+ rescue ::JSON::JSONError, EncodingError, WebMock::Util::Parsers::ParseError
73
179
  nil
74
180
  end
75
- private_class_method :parts_of, :body_differs_only_in_formatting?, :matches_except_body?, :parse_json
181
+ private_class_method :parts_of, :body_pattern_of, :body_differs_only_in_formatting?, :fails_only_on_body?,
182
+ :parse_error, :short_error, :matches_except_body?, :parse_json
76
183
  end
77
184
  end
@@ -1,7 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "hashdiff"
4
- require "json"
5
4
 
6
5
  module WebMock
7
6
  class RequestBodyDiff
@@ -14,7 +13,17 @@ module WebMock
14
13
  def body_diff
15
14
  return {} unless request_signature_diffable? && request_stub_diffable?
16
15
 
17
- Hashdiff.diff(request_signature_body_hash, request_stub_body_hash)
16
+ Hashdiff.diff(request_signature_body_hash, request_stub_body_hash) do |_path, actual, expected|
17
+ # A regexp that matches the request's value is not a difference.
18
+ # Anything else, including matchers and lambdas, which building a
19
+ # message must not run, is left to Hashdiff by returning nil.
20
+ begin
21
+ true if expected.is_a?(Regexp) && actual.is_a?(String) && expected.match?(actual)
22
+ rescue EncodingError
23
+ # A regexp and a value in incompatible encodings don't match.
24
+ nil
25
+ end
26
+ end
18
27
  end
19
28
 
20
29
  attr_reader :request_signature, :request_stub
@@ -30,14 +39,15 @@ module WebMock
30
39
  request_stub_body.is_a?(Hash) || request_stub_parseable_json?
31
40
  end
32
41
 
42
+ # Bodies are read as WebMock reads them for matching.
33
43
  def request_signature_body_hash
34
- JSON.parse(request_signature.body)
44
+ WebMock::Util::Parsers::JSON.parse(request_signature.body)
35
45
  end
36
46
 
37
47
  def request_stub_body_hash
38
48
  return request_stub_body if request_stub_body.is_a?(Hash)
39
49
 
40
- JSON.parse(request_stub_body)
50
+ WebMock::Util::Parsers::JSON.parse(request_stub_body)
41
51
  end
42
52
 
43
53
  def request_stub_body
@@ -57,9 +67,9 @@ module WebMock
57
67
  def parseable_json?(body_pattern)
58
68
  return false unless body_pattern.is_a?(String)
59
69
 
60
- JSON.parse(body_pattern)
70
+ WebMock::Util::Parsers::JSON.parse(body_pattern)
61
71
  true
62
- rescue JSON::ParserError
72
+ rescue WebMock::Util::Parsers::ParseError
63
73
  false
64
74
  end
65
75
  end
@@ -55,20 +55,33 @@ 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
 
63
63
  # Only when too few requests matched: with too many, declaring the body
64
- # as a hash would match even more of them.
64
+ # as a hash would match even more of them, and a request whose body isn't
65
+ # valid JSON isn't why there are too many.
65
66
  def json_body_hint
66
67
  return "" unless WebMock.show_body_diff? && too_few_requests_executed?
67
68
 
68
- requests = RequestRegistry.instance.requested_signatures.select do |request_signature, _|
69
- JsonBodyHint.applies?(request_pattern, request_signature)
69
+ RequestRegistry.instance.requested_signatures.each do |request_signature, _|
70
+ hint = JsonBodyHint.expectation_hint(request_pattern, request_signature)
71
+ return "\n\n#{hint}" if hint
70
72
  end
71
- requests.empty? ? "" : "\n\n#{JsonBodyHint::EXPECTATION_HINT}"
73
+ ""
74
+ end
75
+
76
+ # Only when too few requests matched, as for json_body_hint.
77
+ def trailing_slash_hint
78
+ return "" unless too_few_requests_executed?
79
+
80
+ RequestRegistry.instance.requested_signatures.each do |request_signature, _|
81
+ difference = TrailingSlashHint.difference(request_pattern, request_signature)
82
+ return "\n\n#{TrailingSlashHint::EXPECTATION_HINTS[difference]}" if difference
83
+ end
84
+ ""
72
85
  end
73
86
 
74
87
  def too_few_requests_executed?