webmock 3.40.0 → 3.42.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: aa061376d2227028da9e7ca34091d2ec9b5afb3208f740fe5c7d981a903427d3
4
- data.tar.gz: 8699e49411631af8a7d21312b23fdc98799cc0066be20c1df1ad7e8286a626b3
3
+ metadata.gz: 9bff4bef02b737edabff51c5a68f52b06ad2ee9b5280f11fd0b97ed93b85d13d
4
+ data.tar.gz: c9e3641f5610080b0c8968e2d8169b25ff0f78df0880e5ea07355fbc96012add
5
5
  SHA512:
6
- metadata.gz: f8690d37653f8c4719c827dc5a761c30f00d8419240eef5bbad8284dca046bccae7978b4cc9b4094d8122bf5c0d4169be75c9a4c35442516fdd5ff99974d4e61
7
- data.tar.gz: '0583f069649719f6eff6cb01addb0a640ecbe4014ce94e1319699cd8cdc977b1b8367f2a7127c2f109714388adc99c85c522ca63d8cbb99ad92398ff389e859a'
6
+ metadata.gz: 511313f001e32b777eacaf1666b51775f0690c63fc61551f12835dc55c3be54490c8111f21eaa3a4f772a3b26fed1a2f349bd39f352b6014d5509511c25681f5
7
+ data.tar.gz: a3623cc22f1c9719739fd3a804546acc619ef2a04624f343d162fbcb1ba49db5a3399a619fb5c6e0ae2842ab6f52e1d4e1a5affe366fa7ffa42149403bbf7063
data/CHANGELOG.md CHANGED
@@ -1,5 +1,51 @@
1
1
  # Changelog
2
2
 
3
+ # 3.42.0
4
+
5
+ * Fix VCR failing to replay responses recorded with the `auto_inflate` feature of the `http` gem (#1154)
6
+
7
+ Previously, for a real request made with `HTTP.use(:auto_inflate)`, `after_request` callbacks got the inflated body together with the `Content-Encoding: gzip` header of the compressed one. VCR, hooked into WebMock, recorded both, and replaying the cassette raised `Zlib::DataError: incorrect header check`, because the feature tried to inflate the body again. With VCR's `decode_compressed_response` option, recording raised `Zlib::GzipFile::Error` instead.
8
+
9
+ Callbacks now get the inflated body without the `Content-Encoding` header, as they do for a body that Net::HTTP inflates. A `Content-Length` header, when the response has one, gives the size of the inflated body. The response the client returns is unchanged, and so are the headers of a response with an empty body, such as one to a HEAD request.
10
+
11
+ A cassette recorded this way replays the response with those headers, while the real response keeps the headers of the compressed body.
12
+
13
+ This doesn't cover a client that inflates with a subclass of the feature, or responses returned by the `caching` feature of `http` 6. Callbacks get those as before.
14
+
15
+ Cassettes recorded with older versions that have the `Content-Encoding` header on an inflated body still fail. Record them again, or remove that header from their responses. Their `Content-Length` is still that of the compressed body.
16
+
17
+ # 3.41.0
18
+
19
+ WebMock now parses JSON request bodies with Ruby's `JSON.parse`, instead of its old parser, which converted JSON to YAML and failed on or misread some valid JSON. Every body pattern that matched on 3.40.0 still matches. If one matches only as the old parser reads the body, WebMock prints a deprecation warning, because 4.0 drops the old parser and the pattern won't match there.
20
+
21
+ * Match JSON request bodies with an escaped backslash in a string (#432)
22
+
23
+ Previously, a hash body pattern didn't match a JSON body with an escaped backslash inside a string, such as JSON inside JSON, because the old parser failed on it. For example, `with(body: {data: '{"url":"/p?a=1\u0026b=2"}'})` didn't match the body `{"data":"{\"url\":\"/p?a=1\\u0026b=2\"}"}`. It now matches.
24
+
25
+ Strings that the old parser changed now match too, for example `"a\u000ab"`, which it read as `"a b"`.
26
+
27
+ * Match numbers with an exponent in JSON request bodies
28
+
29
+ Previously, a number such as `1e2` or `1e+20` in a JSON body was read as a String, so `with(body: {amount: 1e20})` didn't match the body `{"amount":1e+20}`, which `to_json` generates for that hash with recent json versions, such as the one in Ruby 4.0. It now matches.
30
+
31
+ * Deprecate body patterns that match a JSON request body only as the old parser reads it
32
+
33
+ The old parser read some bodies that aren't valid JSON, and some values differently from `JSON.parse`. For example, `with(body: {a: 1})` matches the body `{a: 1}`, and `with(body: {amount: "1e+20"})` matches the body `{"amount":1e+20}`, because the old parser read that number as a String. Such a pattern still matches, and WebMock prints a warning once for each pattern:
34
+
35
+ ```
36
+ WebMock deprecation warning: the body pattern {"a" => 1} matched the request body "{a: 1}" only as WebMock's old JSON parser reads it. WebMock 4.0 drops that parser, so it won't match. Send valid JSON, for example from to_json, and write the pattern for what JSON.parse returns.
37
+ ```
38
+
39
+ To fix it, send valid JSON, for example `{a: 1}.to_json`, and write the pattern for what `JSON.parse` returns, such as `{amount: 1e20}`.
40
+
41
+ * Don't raise Psych errors for JSON request bodies such as one with an unquoted date
42
+
43
+ Previously, with Psych 4 or later (the default since Ruby 3.1), a JSON body such as `{"a": 2020-01-01}`, which isn't valid JSON, raised `Psych::DisallowedClass` when a stub had a hash body pattern, instead of WebMock's error for an unregistered request. It now doesn't match the pattern.
44
+
45
+ * Name a future major version in the deprecation warning for statuses such as `:ok`
46
+
47
+ The deprecation warning for a status such as `:ok`, added in 3.38.0, said that WebMock 4.0 would raise `ArgumentError` for it. 4.0 changes how JSON request bodies are read and doesn't change statuses yet, so the warning now names a future major version.
48
+
3
49
  # 3.40.0
4
50
 
5
51
  * Add support for `Curl::Multi` (#535)
@@ -7,6 +7,9 @@ module HTTP
7
7
 
8
8
  webmock_response.status = [status.to_i, reason]
9
9
 
10
+ # The caller gets the body before it is read, to see what it reads from.
11
+ body = self.body
12
+ yield body if block_given?
10
13
  webmock_response.body = body.to_s
11
14
  # This call is used to reset the body of the response to enable it to be streamed if necessary.
12
15
  # The `body.to_s` call above reads the body, which allows WebMock to trigger any registered callbacks.
@@ -87,10 +87,68 @@ module HTTP
87
87
  def perform
88
88
  return unless ::WebMock.net_connect_allowed?(request_signature.uri)
89
89
  response = @perform.call
90
- invoke_callbacks(response.to_webmock, real_request: true)
90
+ invoke_callbacks(webmock_response_for(response), real_request: true)
91
91
  response
92
92
  end
93
93
 
94
+ # The response that callbacks get for a real one. HTTP.rb's auto_inflate
95
+ # feature inflates the body and keeps the headers of the compressed one.
96
+ # WebMock replays a stub through the features, so a stub returning these
97
+ # headers with the inflated body, such as a VCR cassette, would be
98
+ # inflated again. Callbacks get headers that describe the inflated body.
99
+ def webmock_response_for(response)
100
+ return response.to_webmock unless ::WebMock::CallbackRegistry.any_callbacks? && auto_inflate?
101
+
102
+ inflated = false
103
+ webmock_response = response.to_webmock { |body| inflated = reads_from_inflater?(body) }
104
+ describe_inflated_body(webmock_response) if inflated
105
+ webmock_response
106
+ end
107
+
108
+ # Whether the client inflates with HTTP.rb's own feature. A subclass may
109
+ # do anything with the headers and the body, so its responses are left
110
+ # as they are.
111
+ def auto_inflate?
112
+ return false unless defined?(::HTTP::Features::AutoInflate)
113
+
114
+ features = @options.features.values.grep(::HTTP::Features::AutoInflate)
115
+ features.any? && features.all? { |feature| exactly?(::HTTP::Features::AutoInflate, feature) }
116
+ end
117
+
118
+ # Only evidence counts, so that callbacks never get other headers for a
119
+ # body that is still compressed. HTTP.rb shows inflation only in the
120
+ # stream the body reads from, which its logging feature may wrap. With
121
+ # HTTP.rb 6's caching feature the body is a String, which shows nothing.
122
+ # A subclass may do anything with what it reads, so it shows nothing too.
123
+ def reads_from_inflater?(body)
124
+ return false unless defined?(::HTTP::Response::Inflater) && exactly?(::HTTP::Response::Body, body)
125
+
126
+ stream = body.instance_variable_get(:@stream)
127
+ if defined?(::HTTP::Features::Logging::BodyLogger) && exactly?(::HTTP::Features::Logging::BodyLogger, stream)
128
+ stream = stream.instance_variable_get(:@stream)
129
+ end
130
+ exactly?(::HTTP::Response::Inflater, stream)
131
+ end
132
+
133
+ CLASS_OF = ::Kernel.instance_method(:class)
134
+ private_constant :CLASS_OF
135
+
136
+ # Asks Ruby and not the object, which may say anything of itself.
137
+ def exactly?(klass, object)
138
+ klass.equal?(CLASS_OF.bind(object).call)
139
+ end
140
+
141
+ # No Content-Encoding, as for a body Net::HTTP inflates, and its own
142
+ # length. A response with an empty body, such as one to HEAD, keeps its
143
+ # headers: they tell of a body that isn't there to be inflated again.
144
+ def describe_inflated_body(webmock_response)
145
+ return if webmock_response.body.empty?
146
+
147
+ headers = webmock_response.headers
148
+ headers.delete("Content-Encoding")
149
+ headers["Content-Length"] = webmock_response.body.bytesize.to_s if headers.key?("Content-Length")
150
+ end
151
+
94
152
  def halt
95
153
  raise ::WebMock::NetConnectNotAllowedError.new request_signature
96
154
  end
@@ -54,11 +54,14 @@ module WebMock
54
54
  return false unless expected.is_a?(String) && actual.is_a?(String) && expected != actual
55
55
  return false unless request_signature.json_headers?
56
56
 
57
- expected_json = parse_json(expected)
57
+ # The advice is to declare the body as JSON.parse(json_string), so
58
+ # the stub's string must parse with JSON.parse itself. The request
59
+ # body is read as WebMock reads it for matching.
60
+ expected_json = parse_json { ::JSON.parse(expected) }
58
61
  return false unless expected_json.is_a?(Hash) || expected_json.is_a?(Array)
59
62
 
60
63
  # eql? compares nested values strictly, so 1 and 1.0 are different.
61
- expected_json.eql?(parse_json(actual))
64
+ expected_json.eql?(parse_json { WebMock::Util::Parsers::JSON.parse(actual) })
62
65
  end
63
66
 
64
67
  def self.matches_except_body?(request_pattern, request_signature)
@@ -67,9 +70,9 @@ module WebMock
67
70
  (request_pattern.headers_pattern.nil? || request_pattern.headers_pattern.matches?(request_signature.headers))
68
71
  end
69
72
 
70
- def self.parse_json(string)
71
- ::JSON.parse(string)
72
- rescue ::JSON::JSONError, EncodingError
73
+ def self.parse_json
74
+ yield
75
+ rescue ::JSON::JSONError, EncodingError, WebMock::Util::Parsers::ParseError
73
76
  nil
74
77
  end
75
78
  private_class_method :parts_of, :body_differs_only_in_formatting?, :matches_except_body?, :parse_json
@@ -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
@@ -40,14 +39,15 @@ module WebMock
40
39
  request_stub_body.is_a?(Hash) || request_stub_parseable_json?
41
40
  end
42
41
 
42
+ # Bodies are read as WebMock reads them for matching.
43
43
  def request_signature_body_hash
44
- JSON.parse(request_signature.body)
44
+ WebMock::Util::Parsers::JSON.parse(request_signature.body)
45
45
  end
46
46
 
47
47
  def request_stub_body_hash
48
48
  return request_stub_body if request_stub_body.is_a?(Hash)
49
49
 
50
- JSON.parse(request_stub_body)
50
+ WebMock::Util::Parsers::JSON.parse(request_stub_body)
51
51
  end
52
52
 
53
53
  def request_stub_body
@@ -67,9 +67,9 @@ module WebMock
67
67
  def parseable_json?(body_pattern)
68
68
  return false unless body_pattern.is_a?(String)
69
69
 
70
- JSON.parse(body_pattern)
70
+ WebMock::Util::Parsers::JSON.parse(body_pattern)
71
71
  true
72
- rescue JSON::ParserError
72
+ rescue WebMock::Util::Parsers::ParseError
73
73
  false
74
74
  end
75
75
  end
@@ -437,11 +437,11 @@ module WebMock
437
437
 
438
438
  if (@pattern).is_a?(Hash)
439
439
  return true if @pattern.empty?
440
- 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) }
441
441
  elsif (@pattern).is_a?(Array)
442
- 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) }
443
443
  elsif (@pattern).is_a?(WebMock::Matchers::HashArgumentMatcher)
444
- @pattern == body_as_hash(body, content_type)
444
+ matching_parsed_body?(body, content_type) { |parsed| @pattern == parsed }
445
445
  else
446
446
  empty_string?(@pattern) && empty_string?(body) ||
447
447
  @pattern == body ||
@@ -455,6 +455,68 @@ module WebMock
455
455
 
456
456
  private
457
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
+
458
520
  def body_as_hash(body, content_type)
459
521
  return if body.nil?
460
522
 
@@ -135,7 +135,7 @@ module WebMock
135
135
  rack_hint = code.is_a?(Symbol) ? ", or Rack::Utils.status_code(#{code.inspect}) in a Rack app" : ""
136
136
  WebMock::Deprecation.warning(
137
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."
138
+ "Use a number such as 200#{rack_hint}. A future major version of WebMock will raise ArgumentError for it."
139
139
  )
140
140
  end
141
141
 
@@ -1,25 +1,56 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # This is a copy of https://github.com/jnunemaker/crack/blob/master/lib/crack/json.rb
3
+ # parse_legacy is a copy of https://github.com/jnunemaker/crack/blob/master/lib/crack/json.rb
4
4
  # with date parsing removed
5
5
  # Copyright (c) 2004-2008 David Heinemeier Hansson
6
6
  # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
7
7
  # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
8
  # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
9
9
 
10
+ require "json"
10
11
  require_relative "parse_error"
11
12
 
12
13
  module WebMock
13
14
  module Util
14
15
  module Parsers
15
16
  class JSON
17
+ # Deep enough for any real body, and shallow enough for every json
18
+ # gem version to parse in a thread's stack.
19
+ MAX_NESTING = 1000
20
+
16
21
  def self.parse(json)
22
+ # JSON texts may start with a byte order mark, which parsers may ignore.
23
+ json = to_utf8(json).delete_prefix("\uFEFF")
24
+ ::JSON.parse(json, allow_duplicate_key: true, max_nesting: MAX_NESTING)
25
+ rescue ::JSON::JSONError, EncodingError => e
26
+ raise ParseError, "Invalid JSON string: #{e.message}"
27
+ end
28
+
29
+ # The YAML based parser WebMock used up to 3.40.0. It reads some
30
+ # bodies that aren't valid JSON, such as {a: 1}, and some values
31
+ # differently from the json gem, such as 1e+20 as a String.
32
+ # WebMock 4.0 drops it.
33
+ def self.parse_legacy(json)
17
34
  yaml = unescape(convert_json_to_yaml(json))
18
35
  YAML.load(yaml)
19
- rescue ArgumentError, Psych::SyntaxError => e
36
+ rescue ArgumentError, EncodingError, Psych::Exception => e
20
37
  raise ParseError, "Invalid JSON string: #{yaml}, Error: #{e.inspect}"
21
38
  end
22
39
 
40
+ # The json gem reads bytes that aren't valid in their encoding, so
41
+ # such a body, for example a binary upload, is rejected here. A
42
+ # binary or US-ASCII string, as read from a socket or from a file in
43
+ # a C locale, is taken as UTF-8.
44
+ def self.to_utf8(json)
45
+ if json.encoding == Encoding::BINARY || json.encoding == Encoding::US_ASCII
46
+ json = json.dup.force_encoding(Encoding::UTF_8)
47
+ end
48
+ raise ParseError, "Invalid JSON string: it isn't valid #{json.encoding}" unless json.valid_encoding?
49
+
50
+ json.encoding == Encoding::UTF_8 ? json : json.encode(Encoding::UTF_8)
51
+ end
52
+ private_class_method :to_utf8
53
+
23
54
  protected
24
55
 
25
56
  def self.unescape(str)
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module WebMock
4
- VERSION = '3.40.0' unless defined?(::WebMock::VERSION)
4
+ VERSION = '3.42.0' unless defined?(::WebMock::VERSION)
5
5
  end
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.40.0
4
+ version: 3.42.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Bartosz Blimke
@@ -363,9 +363,9 @@ licenses:
363
363
  - MIT
364
364
  metadata:
365
365
  bug_tracker_uri: https://github.com/bblimke/webmock/issues
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
366
+ changelog_uri: https://github.com/bblimke/webmock/blob/v3.42.0/CHANGELOG.md
367
+ documentation_uri: https://www.rubydoc.info/gems/webmock/3.42.0
368
+ source_code_uri: https://github.com/bblimke/webmock/tree/v3.42.0
369
369
  wiki_uri: https://github.com/bblimke/webmock/wiki
370
370
  rdoc_options: []
371
371
  require_paths: