webmock 3.35.0 → 3.37.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.
@@ -5,20 +5,81 @@ module WebMock
5
5
  class RequestRegistry
6
6
  include Singleton
7
7
 
8
+ # Used by #atomically, allocated once rather than on every request.
9
+ DEFER_INTERRUPTS = { Object => :on_blocking }.freeze
10
+ private_constant :DEFER_INTERRUPTS
11
+
8
12
  attr_accessor :requested_signatures
9
13
 
10
14
  def initialize
15
+ @lock = ::Mutex.new
11
16
  reset!
12
17
  end
13
18
 
19
+ # The counter and the list change together, under one lock, so they
20
+ # always agree.
14
21
  def reset!
15
- self.requested_signatures = Util::HashCounter.new
22
+ atomically do
23
+ @executed_requests = []
24
+ @live_matches = {}
25
+ self.requested_signatures = Util::HashCounter.new
26
+ end
27
+ end
28
+
29
+ # Records a request made through an HTTP client adapter. The list holds
30
+ # the copy the counter keeps of each distinct request, so a caller reusing
31
+ # its body buffer cannot change it. A repeated request adds only a
32
+ # reference to that copy, so a suite that never resets keeps one copy of
33
+ # each distinct request.
34
+ def put(request_signature, track_live_matches: false)
35
+ stored = nil
36
+ live_matches = atomically do
37
+ stored = requested_signatures.put(request_signature)
38
+ @executed_requests << stored
39
+ @live_matches
40
+ end
41
+ return unless track_live_matches
42
+
43
+ # Matching happens outside the lock. Capture this generation so a
44
+ # concurrent reset cannot attach an old match to a later request.
45
+ lambda do |token, matched|
46
+ @lock.synchronize do
47
+ counts = live_matches[token] ||= {}
48
+ checked, accepted = counts.fetch(stored, [0, 0])
49
+ accepted += 1 if matched
50
+ counts[stored] = [checked + 1, accepted]
51
+ end
52
+ end
53
+ end
54
+
55
+ # Every request made since the last reset, in order, repeats included,
56
+ # as copies, so a test cannot change WebMock's records.
57
+ def executed_requests
58
+ requests = @lock.synchronize { @executed_requests.dup }
59
+ copies = {}.compare_by_identity
60
+ requests.map { |request| copies[request] ||= request.dup }.freeze
16
61
  end
17
62
 
18
63
  def times_executed(request_pattern)
19
- self.requested_signatures.select do |request_signature|
20
- request_pattern.matches?(request_signature)
21
- end.inject(0) { |sum, (_, times_executed)| sum + times_executed }
64
+ pattern, conditions = request_pattern.respond_to?(:patterns) ? request_pattern.patterns : [request_pattern]
65
+ base = pattern.is_a?(RequestStub) ? pattern.request_pattern : pattern
66
+ token = base.match_token if base.is_a?(RequestPattern)
67
+ counts, observations = @lock.synchronize { [requested_signatures.snapshot, @live_matches[token]&.dup] }
68
+
69
+ counts.sum do |signature, total|
70
+ observed = observations && observations[signature]
71
+ if observed
72
+ # The same snapshot can represent both a stream and a string.
73
+ # Only recheck the requests for which the stub wasn't evaluated.
74
+ checked, accepted = observed
75
+ remaining = total - checked
76
+ accepted += remaining if remaining > 0 && pattern.matches?(signature)
77
+ next 0 if accepted > 0 && conditions && !conditions.matches?(signature)
78
+ accepted
79
+ else
80
+ request_pattern.matches?(signature) ? total : 0
81
+ end
82
+ end
22
83
  end
23
84
 
24
85
  def to_s
@@ -33,5 +94,14 @@ module WebMock
33
94
  end
34
95
  end
35
96
 
97
+ private
98
+
99
+ # An interrupt such as Timeout can still stop a thread waiting for the
100
+ # lock, but not one between the two updates, where nothing blocks.
101
+ def atomically(&block)
102
+ Thread.handle_interrupt(DEFER_INTERRUPTS) do
103
+ @lock.synchronize(&block)
104
+ end
105
+ end
36
106
  end
37
107
  end
@@ -5,11 +5,12 @@ module WebMock
5
5
  class RequestSignature
6
6
 
7
7
  attr_accessor :uri, :body
8
- attr_reader :method, :headers
8
+ attr_reader :method, :headers, :serialized_body
9
9
 
10
10
  def initialize(method, uri, options = {})
11
11
  self.method = method
12
12
  self.uri = uri.is_a?(Addressable::URI) ? uri : WebMock::Util::URI.normalize_uri(uri)
13
+ @serialized_body = options[:serialized_body]
13
14
  assign_options(options)
14
15
  end
15
16
 
@@ -23,6 +24,27 @@ module WebMock
23
24
  string
24
25
  end
25
26
 
27
+ # Build a signature for history while preserving the original client
28
+ # objects for stub matchers and callbacks. Keep nested form structure.
29
+ def with_body_values(&block)
30
+ self.class.new(method, uri, body: map_body_values(body, &block), headers: headers)
31
+ end
32
+
33
+ # Keep the native upload available to custom matchers and callbacks while
34
+ # allowing string and structured body patterns to match its contents.
35
+ def with_upload_body(upload)
36
+ self.class.new(method, uri, body: upload, headers: headers, serialized_body: body)
37
+ end
38
+
39
+ # A copy that shares no mutable state with the original.
40
+ def initialize_copy(original)
41
+ super
42
+ @uri = @uri.dup
43
+ @body = map_body_values(@body, &:dup)
44
+ @serialized_body = @serialized_body&.dup
45
+ @headers = @headers&.transform_values { |value| value.is_a?(Array) ? value.map(&:dup) : value.dup }
46
+ end
47
+
26
48
  def method=(method)
27
49
  @method = method.to_sym.downcase
28
50
  end
@@ -32,11 +54,13 @@ module WebMock
32
54
  end
33
55
 
34
56
  def hash
35
- self.to_s.hash
57
+ [method, uri, body, headers].hash
36
58
  end
37
59
 
38
60
  def eql?(other)
39
- self.to_s == other.to_s
61
+ other.is_a?(RequestSignature) &&
62
+ method == other.method && uri.eql?(other.uri) &&
63
+ body.eql?(other.body) && headers.eql?(other.headers)
40
64
  end
41
65
  alias == eql?
42
66
 
@@ -56,6 +80,19 @@ module WebMock
56
80
 
57
81
  private
58
82
 
83
+ def map_body_values(body, &block)
84
+ case body
85
+ when Array
86
+ body.map { |item| map_body_values(item, &block) }
87
+ when Hash
88
+ body.each_with_object({}) do |(key, value), copy|
89
+ copy[map_body_values(key, &block)] = map_body_values(value, &block)
90
+ end
91
+ else
92
+ yield body
93
+ end
94
+ end
95
+
59
96
  def assign_options(options)
60
97
  self.body = options[:body] if options.has_key?(:body)
61
98
  self.headers = options[:headers] if options.has_key?(:headers)
@@ -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)
@@ -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
@@ -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,11 +233,7 @@ 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
236
+ hash.transform_values! { |value| dehash_value(value) }
227
237
  if hash != {} && hash.keys.all? { |key| key =~ /\A\d+\z/ }
228
238
  # By number, then by text, so "01" and "1" keep a fixed order
229
239
  hash.sort_by { |key, _| [key.to_i, key] }.map(&:last)
@@ -232,6 +242,16 @@ module WebMock::Util
232
242
  end
233
243
  end
234
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
+
235
255
  ##
236
256
  # Joins and converts parent and value into a properly encoded and
237
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
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module WebMock
4
- VERSION = '3.35.0' unless defined?(::WebMock::VERSION)
4
+ VERSION = '3.37.0' unless defined?(::WebMock::VERSION)
5
5
  end
data/lib/webmock.rb CHANGED
@@ -15,6 +15,7 @@ require_relative 'webmock/util/uri'
15
15
  require_relative 'webmock/util/headers'
16
16
  require_relative 'webmock/util/content_type'
17
17
  require_relative 'webmock/util/hash_counter'
18
+ require_relative 'webmock/util/upload_body'
18
19
  require_relative 'webmock/util/hash_keys_stringifier'
19
20
  require_relative 'webmock/util/values_stringifier'
20
21
  require_relative 'webmock/util/parsers/json'
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.35.0
4
+ version: 3.37.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Bartosz Blimke
@@ -350,6 +350,7 @@ files:
350
350
  - lib/webmock/util/parsers/parse_error.rb
351
351
  - lib/webmock/util/parsers/xml.rb
352
352
  - lib/webmock/util/query_mapper.rb
353
+ - lib/webmock/util/upload_body.rb
353
354
  - lib/webmock/util/uri.rb
354
355
  - lib/webmock/util/values_stringifier.rb
355
356
  - lib/webmock/util/version_checker.rb
@@ -360,9 +361,9 @@ licenses:
360
361
  - MIT
361
362
  metadata:
362
363
  bug_tracker_uri: https://github.com/bblimke/webmock/issues
363
- changelog_uri: https://github.com/bblimke/webmock/blob/v3.35.0/CHANGELOG.md
364
- documentation_uri: https://www.rubydoc.info/gems/webmock/3.35.0
365
- source_code_uri: https://github.com/bblimke/webmock/tree/v3.35.0
364
+ changelog_uri: https://github.com/bblimke/webmock/blob/v3.37.0/CHANGELOG.md
365
+ documentation_uri: https://www.rubydoc.info/gems/webmock/3.37.0
366
+ source_code_uri: https://github.com/bblimke/webmock/tree/v3.37.0
366
367
  wiki_uri: https://github.com/bblimke/webmock/wiki
367
368
  rdoc_options: []
368
369
  require_paths: