webmock 3.34.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.
Files changed (42) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +358 -0
  3. data/README.md +222 -3
  4. data/lib/webmock/api.rb +4 -0
  5. data/lib/webmock/errors.rb +1 -1
  6. data/lib/webmock/http_lib_adapters/async_http_client_adapter.rb +51 -7
  7. data/lib/webmock/http_lib_adapters/curb_adapter.rb +291 -39
  8. data/lib/webmock/http_lib_adapters/em_http_request_adapter.rb +11 -3
  9. data/lib/webmock/http_lib_adapters/excon_adapter.rb +23 -2
  10. data/lib/webmock/http_lib_adapters/http_rb/webmock.rb +33 -4
  11. data/lib/webmock/http_lib_adapters/http_rb_adapter.rb +4 -1
  12. data/lib/webmock/http_lib_adapters/httpclient_adapter.rb +132 -110
  13. data/lib/webmock/http_lib_adapters/manticore_adapter.rb +1 -1
  14. data/lib/webmock/http_lib_adapters/net_http.rb +66 -3
  15. data/lib/webmock/http_lib_adapters/net_http_response.rb +28 -2
  16. data/lib/webmock/http_lib_adapters/patron_adapter.rb +242 -40
  17. data/lib/webmock/http_lib_adapters/typhoeus_hydra_adapter.rb +65 -7
  18. data/lib/webmock/json_body_hint.rb +8 -5
  19. data/lib/webmock/request_body_diff.rb +16 -6
  20. data/lib/webmock/request_execution_verifier.rb +13 -2
  21. data/lib/webmock/request_pattern.rb +236 -36
  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 +23 -2
  25. data/lib/webmock/request_stub.rb +8 -4
  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 +33 -2
  35. data/lib/webmock/util/query_mapper.rb +56 -37
  36. data/lib/webmock/util/upload_body.rb +63 -0
  37. data/lib/webmock/util/uri.rb +21 -12
  38. data/lib/webmock/util/values_stringifier.rb +54 -0
  39. data/lib/webmock/version.rb +1 -1
  40. data/lib/webmock/webmock.rb +35 -4
  41. data/lib/webmock.rb +3 -0
  42. metadata +7 -4
@@ -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}. A future major version of WebMock 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]
@@ -62,18 +62,19 @@ module WebMock
62
62
  request_stub_for(request_signature)
63
63
  end
64
64
 
65
- def response_for_request(request_signature)
66
- stub = request_stub_for(request_signature)
65
+ def response_for_request(request_signature, record: nil)
66
+ if record
67
+ remember = RequestRegistry.instance.put(record, track_live_matches: !record.equal?(request_signature))
68
+ end
69
+ stub = request_stub_for(request_signature, &remember)
67
70
  stub ? evaluate_response_for_request(stub.response, request_signature) : nil
68
71
  end
69
72
 
70
73
  private
71
74
 
72
- def request_stub_for(request_signature)
75
+ def request_stub_for(request_signature, &remember)
73
76
  (global_stubs[:before_local_stubs] + request_stubs + global_stubs[:after_local_stubs])
74
- .detect { |registered_request_stub|
75
- registered_request_stub.request_pattern.matches?(request_signature)
76
- }
77
+ .detect { |stub| stub.request_pattern.matches?(request_signature, &remember) }
77
78
  end
78
79
 
79
80
  def evaluate_response_for_request(response, request_signature)
@@ -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
@@ -5,19 +5,32 @@ require 'thread'
5
5
  module WebMock
6
6
  module Util
7
7
  class HashCounter
8
+ # The key the counter holds, its count, and when it was last put.
9
+ Entry = Struct.new(:key, :count, :position)
10
+
8
11
  attr_accessor :hash
9
12
 
10
13
  def initialize
11
14
  self.hash = Hash.new(0)
12
- @order = {}
15
+ @entries = {}
13
16
  @max = 0
14
17
  @lock = ::Mutex.new
15
18
  end
16
19
 
20
+ # Returns the key the counter holds: a copy of the first one put for an
21
+ # equal key. The copy is also what the counter looks keys up by, so a
22
+ # caller changing its key later cannot change the counts.
17
23
  def put(key, num=1)
18
24
  @lock.synchronize do
19
- hash[key] += num
20
- @order[key] = @max += 1
25
+ entry = @entries[key]
26
+ unless entry
27
+ copy = key.dup
28
+ entry = @entries[copy] = Entry.new(copy, 0, 0)
29
+ end
30
+ entry.count += num
31
+ entry.position = @max += 1
32
+ hash[entry.key] = entry.count
33
+ entry.key
21
34
  end
22
35
  end
23
36
 
@@ -27,18 +40,24 @@ module WebMock
27
40
  end
28
41
  end
29
42
 
43
+ # The block runs on a snapshot, outside the lock, so it can make
44
+ # requests or call WebMock without deadlocking.
30
45
  def select(&block)
31
46
  return unless block_given?
32
47
 
33
- @lock.synchronize do
34
- hash.select(&block)
35
- end
48
+ snapshot.select(&block)
49
+ end
50
+
51
+ def snapshot
52
+ @lock.synchronize { hash.dup }
36
53
  end
37
54
 
55
+ # Like select, it yields from a snapshot, outside the lock.
38
56
  def each(&block)
39
- @order.to_a.sort_by { |a| a[1] }.each do |a|
40
- yield(a[0], hash[a[0]])
57
+ entries = @lock.synchronize do
58
+ @entries.values.sort_by(&:position).map { |entry| [entry.key, entry.count] }
41
59
  end
60
+ entries.each { |key, count| yield(key, count) }
42
61
  end
43
62
  end
44
63
  end
@@ -18,10 +18,32 @@ module WebMock
18
18
  [k,v]
19
19
  }.inject([]) {|r,x| r + x}]
20
20
  else
21
- arg
21
+ options[:deep] ? with_string_keys(arg) : arg
22
22
  end
23
23
  end
24
24
 
25
+ # RSpec's hash_including and hash_excluding nested in a pattern keep
26
+ # their keys as given, so they get string keys here, as do hashes in
27
+ # array_including and array_excluding. They stay RSpec matchers, which
28
+ # compare nested values the way RSpec does. A matcher without keys to
29
+ # change is kept as it is.
30
+ def self.with_string_keys(arg)
31
+ # Defined in request_pattern.rb, which this file can be loaded without.
32
+ return arg unless defined?(WebMock::RSpecMatcherDetector)
33
+
34
+ name = if WebMock::RSpecMatcherDetector.rSpecHashMatcher?(arg)
35
+ :@expected
36
+ elsif WebMock::RSpecMatcherDetector.rSpecArrayMatcher?(arg)
37
+ arg.instance_variable_defined?(:@expected) ? :@expected : :@unexpected
38
+ end
39
+ return arg unless name
40
+
41
+ expected = arg.instance_variable_get(name)
42
+ converted = stringify_keys!(expected, deep: true)
43
+ converted == expected ? arg : arg.class.new(converted)
44
+ end
45
+ private_class_method :with_string_keys
46
+
25
47
  end
26
48
  end
27
49
  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,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)
@@ -65,7 +65,7 @@ module WebMock::Util
65
65
  if options[:notation] == :flat_array
66
66
  accumulator << [key, value]
67
67
  else
68
- accumulator[key] = value.kind_of?(Hash) ? dehash(value) : value
68
+ accumulator[key] = dehash_value(value)
69
69
  end
70
70
  accumulator
71
71
  end
@@ -125,44 +125,34 @@ module WebMock::Util
125
125
  def fill_accumulator_for_subscript(accumulator, key, value)
126
126
  current_node = accumulator
127
127
  subkeys = key.split(/(?=\[[^\[\]]+)/)
128
- subkeys[0..-2].each do |subkey|
128
+ subkeys[0..-2].each_with_index do |subkey, index|
129
129
  node = subkey =~ /\[\]\z/ ? [] : {}
130
+ current_node = array_element_for(current_node, subkeys[index..-1]) if current_node.is_a? Array
130
131
  subkey = subkey.gsub(/[\[\]]/, '')
131
- if current_node.is_a? Array
132
- container = current_node.find { |n| n.is_a?(Hash) && n.has_key?(subkey) }
133
- if container
134
- current_node = container[subkey]
135
- else
136
- current_node << {subkey => node}
137
- current_node = node
138
- end
139
- else
140
- current_node[subkey] = node unless current_node[subkey]
141
- current_node = current_node[subkey]
142
- end
132
+ current_node[subkey] = node unless current_node[subkey]
133
+ current_node = current_node[subkey]
143
134
  end
144
135
  last_key = subkeys.last
145
136
  array_value = !!(last_key =~ /\[\]$/)
146
137
  last_key = last_key.gsub(/[\[\]]/, '')
147
138
  if current_node.is_a? Array
148
- last_container = current_node.select { |n| n.is_a?(Hash) }.last
149
- if last_container && !last_container.has_key?(last_key)
150
- if array_value
151
- last_container[last_key] ||= []
152
- last_container[last_key] << value
153
- else
154
- last_container[last_key] = value
155
- end
139
+ # Unlike in Rack, a final key that the last hash already has starts
140
+ # a new hash even with [], so a[][b][]=1&a[][b][]=2 makes two hashes
141
+ last = current_node.last
142
+ current_node << {} unless last.is_a?(Hash) && !last.key?(last_key)
143
+ if array_value
144
+ (current_node.last[last_key] ||= []) << value
156
145
  else
157
- if array_value
158
- current_node << {last_key => [value]}
159
- else
160
- current_node << {last_key => value}
161
- end
146
+ current_node.last[last_key] = value
162
147
  end
163
148
  else
164
149
  if array_value
165
- current_node[last_key] ||= []
150
+ if current_node.is_a?(Hash)
151
+ current_node[last_key] = [current_node[last_key]].compact unless current_node[last_key].is_a?(Array)
152
+ else
153
+ # A value is in the way, as in x=5&x[5][]=1, so do what older versions did
154
+ current_node[last_key] ||= []
155
+ end
166
156
  current_node[last_key] << value unless value.nil?
167
157
  else
168
158
  current_node[last_key] = value
@@ -170,6 +160,30 @@ module WebMock::Util
170
160
  end
171
161
  end
172
162
 
163
+ # Returns the hash in an array of hashes that a nested key goes into.
164
+ # As in Rack, that is the last hash, unless the rest of the key is
165
+ # already set there, so a[][b][c]=1&a[][b][c]=2 makes two hashes.
166
+ def array_element_for(array, subkeys)
167
+ last = array.last
168
+ return last if last.is_a?(Hash) && key_path_free?(last, subkeys)
169
+ array << {}
170
+ array.last
171
+ end
172
+
173
+ # Whether the rest of a key fits into the hash without replacing a
174
+ # value. A part ending in [] fits while it holds an array.
175
+ def key_path_free?(hash, subkeys)
176
+ subkeys.each_with_index do |subkey, index|
177
+ key = subkey.gsub(/[\[\]]/, '')
178
+ return true unless hash.key?(key)
179
+ value = hash[key]
180
+ return value.is_a?(Array) if subkey.end_with?('[]')
181
+ return false if index == subkeys.size - 1 || !value.is_a?(Hash)
182
+ hash = value
183
+ end
184
+ false
185
+ end
186
+
173
187
  ##
174
188
  # Sets the query component for this URI from a Hash object.
175
189
  # This method produces a query string using the :subscript notation.
@@ -219,20 +233,25 @@ module WebMock::Util
219
233
  end
220
234
 
221
235
  def dehash(hash)
222
- hash.each do |(key, value)|
223
- if value.is_a?(::Hash)
224
- hash[key] = self.dehash(value)
225
- end
226
- end
227
- if hash != {} && hash.keys.all? { |key| key =~ /^\d+$/ }
228
- hash.sort.inject([]) do |accu, (_, value)|
229
- accu << value; accu
230
- end
236
+ hash.transform_values! { |value| dehash_value(value) }
237
+ if hash != {} && hash.keys.all? { |key| key =~ /\A\d+\z/ }
238
+ # By number, then by text, so "01" and "1" keep a fixed order
239
+ hash.sort_by { |key, _| [key.to_i, key] }.map(&:last)
231
240
  else
232
241
  hash
233
242
  end
234
243
  end
235
244
 
245
+ # A query such as a[][b][0][c]=1 produces an array whose element holds
246
+ # {"0" => ...}, so the numeric keys have to be collapsed inside arrays too.
247
+ def dehash_value(value)
248
+ case value
249
+ when ::Hash then dehash(value)
250
+ when ::Array then value.map { |element| dehash_value(element) }
251
+ else value
252
+ end
253
+ end
254
+
236
255
  ##
237
256
  # Joins and converts parent and value into a properly encoded and
238
257
  # ordered URL query.
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'stringio'
4
+
5
+ module WebMock
6
+ module Util
7
+ module UploadBody
8
+ def self.read(stream, headers)
9
+ # Only inspect readers whose buffering and pushback semantics we know.
10
+ # A wrapper can delegate ungetbyte to a file while transforming read.
11
+ read_owner = stream.method(:read).owner
12
+ if defined?(Tempfile) && stream.is_a?(Tempfile) && read_owner == Tempfile.instance_method(:read).owner
13
+ stream = stream.to_io
14
+ read_owner = stream.method(:read).owner
15
+ end
16
+ gzip = defined?(Zlib::GzipReader) && read_owner == Zlib::GzipReader
17
+ source = gzip ? stream.to_io : stream
18
+ return stream.to_s unless (read_owner == IO || read_owner == StringIO || gzip) &&
19
+ (source.is_a?(StringIO) || (source.is_a?(IO) && source.stat.file?))
20
+
21
+ _, length = headers.find { |name, _| name.to_s.casecmp?('Content-Length') }
22
+ return ''.b if length && length.to_i.zero?
23
+
24
+ if gzip
25
+ # Rewinding a gzip reader loses its pushed-back, uncompressed bytes.
26
+ # GzipReader#ungetc accepts the whole string, including binary data.
27
+ pushback = :ungetc
28
+ elsif source.is_a?(IO)
29
+ # Flush pending writes before checking the descriptor offset.
30
+ # sysseek rejects buffered input, which IO#pos would discard.
31
+ stream.read(0)
32
+ begin
33
+ position = stream.sysseek(0, IO::SEEK_CUR)
34
+ rescue IOError
35
+ pushback = :ungetbyte
36
+ end
37
+ else
38
+ position = stream.pos
39
+ end
40
+ body = ''.b
41
+ each_chunk(stream, length&.to_i) { |chunk| body << chunk.b }
42
+ body
43
+ ensure
44
+ if pushback && body && !body.empty?
45
+ stream.public_send(pushback, body)
46
+ elsif position
47
+ stream.seek(position)
48
+ end
49
+ end
50
+
51
+ def self.each_chunk(stream, length)
52
+ while length.nil? || length > 0
53
+ size = length ? [length, 64 * 1024].min : 64 * 1024
54
+ chunk = stream.read(size)
55
+ break if chunk.nil? || chunk.empty?
56
+ yield chunk
57
+ length -= chunk.bytesize if length
58
+ end
59
+ end
60
+ private_class_method :each_chunk
61
+ end
62
+ end
63
+ end
@@ -13,16 +13,20 @@ module WebMock
13
13
  hash[key] = Addressable::URI.heuristic_parse(key)
14
14
  end
15
15
 
16
- NORMALIZED_URIS = Hash.new do |hash, uri|
17
- normalized_uri = WebMock::Util::URI.heuristic_parse(uri)
18
- if normalized_uri.query_values
19
- sorted_query_values = sort_query_values(WebMock::Util::QueryMapper.query_to_values(normalized_uri.query, notation: Config.instance.query_values_notation) || {})
20
- normalized_uri.query = WebMock::Util::QueryMapper.values_to_query(sorted_query_values, notation: WebMock::Config.instance.query_values_notation)
16
+ # Keyed by query notation, then by URI, so changing
17
+ # Config.instance.query_values_notation applies to URIs seen before.
18
+ NORMALIZED_URIS = Hash.new do |by_notation, notation|
19
+ by_notation[notation] = Hash.new do |hash, uri|
20
+ normalized_uri = WebMock::Util::URI.heuristic_parse(uri)
21
+ if normalized_uri.query_values
22
+ sorted_query_values = sort_query_values(WebMock::Util::QueryMapper.query_to_values(normalized_uri.query, notation: notation) || {})
23
+ normalized_uri.query = WebMock::Util::QueryMapper.values_to_query(sorted_query_values, notation: notation)
24
+ end
25
+ normalized_uri = normalized_uri.normalize #normalize! is slower
26
+ normalized_uri.query = normalized_uri.query.gsub("+", "%2B") if normalized_uri.query
27
+ normalized_uri.port = normalized_uri.inferred_port unless normalized_uri.port
28
+ hash[uri] = normalized_uri
21
29
  end
22
- normalized_uri = normalized_uri.normalize #normalize! is slower
23
- normalized_uri.query = normalized_uri.query.gsub("+", "%2B") if normalized_uri.query
24
- normalized_uri.port = normalized_uri.inferred_port unless normalized_uri.port
25
- hash[uri] = normalized_uri
26
30
  end
27
31
 
28
32
  def self.heuristic_parse(uri)
@@ -32,7 +36,7 @@ module WebMock
32
36
  def self.normalize_uri(uri)
33
37
  return uri if uri.is_a?(Regexp)
34
38
  uri = 'http://' + uri unless uri.match('^https?://') if uri.is_a?(String)
35
- NORMALIZED_URIS[uri].dup
39
+ NORMALIZED_URIS[Config.instance.query_values_notation][uri].dup
36
40
  end
37
41
 
38
42
  def self.variations_of_uri_as_strings(uri_object, only_with_scheme: false)
@@ -76,8 +80,13 @@ module WebMock
76
80
  private
77
81
 
78
82
  def self.sort_query_values(query_values)
79
- sorted_query_values = query_values.sort
80
- query_values.is_a?(Hash) ? Hash[*sorted_query_values.inject([]) { |values, pair| values + pair}] : sorted_query_values
83
+ if query_values.is_a?(Hash)
84
+ Hash[*query_values.sort.inject([]) { |values, pair| values + pair}]
85
+ else
86
+ # Pairs from :flat_array. A key without "=" has a nil value, which
87
+ # can't be compared with a string, so it comes first.
88
+ query_values.sort_by { |key, value| value.nil? ? [key, 0, ""] : [key, 1, value] }
89
+ end
81
90
  end
82
91
 
83
92
  def self.uris_with_inferred_port_and_without(uris)