webmock 3.40.0 → 3.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: aa061376d2227028da9e7ca34091d2ec9b5afb3208f740fe5c7d981a903427d3
4
- data.tar.gz: 8699e49411631af8a7d21312b23fdc98799cc0066be20c1df1ad7e8286a626b3
3
+ metadata.gz: 1e9683794e823cf95915c85c61925ffbae1c8577b62376c3c08dcf42c856adcd
4
+ data.tar.gz: 46a910e0d7118b4da7083aaa7488f4a3c7f4854926f9afbc37707ea4163f9732
5
5
  SHA512:
6
- metadata.gz: f8690d37653f8c4719c827dc5a761c30f00d8419240eef5bbad8284dca046bccae7978b4cc9b4094d8122bf5c0d4169be75c9a4c35442516fdd5ff99974d4e61
7
- data.tar.gz: '0583f069649719f6eff6cb01addb0a640ecbe4014ce94e1319699cd8cdc977b1b8367f2a7127c2f109714388adc99c85c522ca63d8cbb99ad92398ff389e859a'
6
+ metadata.gz: d0dfedb9926e3aceefe66c995e2b27e59a2b7410dc1b371ebc82e8008565b08ef0606ac97248a83e7d9d190e90f10c878b78ab518d300993a0088b859f790530
7
+ data.tar.gz: 915547cab2193d2170cbc28ec663bc8ff7a63f3fe8352ed1aa6da491cf987ea2a28dd7ea5260e4965ea87131d8b4c8a844523ebf918826cdd6614a715c57ab99
data/CHANGELOG.md CHANGED
@@ -1,5 +1,37 @@
1
1
  # Changelog
2
2
 
3
+ # 3.41.0
4
+
5
+ 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.
6
+
7
+ * Match JSON request bodies with an escaped backslash in a string (#432)
8
+
9
+ 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.
10
+
11
+ Strings that the old parser changed now match too, for example `"a\u000ab"`, which it read as `"a b"`.
12
+
13
+ * Match numbers with an exponent in JSON request bodies
14
+
15
+ 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.
16
+
17
+ * Deprecate body patterns that match a JSON request body only as the old parser reads it
18
+
19
+ 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:
20
+
21
+ ```
22
+ 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.
23
+ ```
24
+
25
+ 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}`.
26
+
27
+ * Don't raise Psych errors for JSON request bodies such as one with an unquoted date
28
+
29
+ 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.
30
+
31
+ * Name a future major version in the deprecation warning for statuses such as `:ok`
32
+
33
+ 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.
34
+
3
35
  # 3.40.0
4
36
 
5
37
  * Add support for `Curl::Multi` (#535)
@@ -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.41.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.41.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.41.0/CHANGELOG.md
367
+ documentation_uri: https://www.rubydoc.info/gems/webmock/3.41.0
368
+ source_code_uri: https://github.com/bblimke/webmock/tree/v3.41.0
369
369
  wiki_uri: https://github.com/bblimke/webmock/wiki
370
370
  rdoc_options: []
371
371
  require_paths: