webmock 4.1.0 → 4.2.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: 4919cd5204cf89c2d30230526f0dd658326182c16ea82174c88bfb0adce3748e
4
- data.tar.gz: aaddb1abbddaf3f9c6fff1ee15a30c4eddf0bd4eafe6a370b1dc2ec7509b4339
3
+ metadata.gz: c360e82812395f3fd6a367abc7417457db31fd3d203b3876c4dab5ce27c8ea37
4
+ data.tar.gz: a45f10756d7751e6d51511be1c3967843de2875acd10af18f1d0dffc2717014c
5
5
  SHA512:
6
- metadata.gz: cd641f8e94aac2eb9fb0e5305a1f375c871e78138c33f711a508bd07016571adb4b112e4d05c193524d0081d459273aca4153a47b1396ff9b53a6b7197d43b0d
7
- data.tar.gz: 94816f0976ab5d05b283b081b77734c566ea5b4f42ac221893493a0012a0bcafcfa0c9493220f319ff305079df352a9bced0efd9d3347c5d34e73d2b26c690eb
6
+ metadata.gz: ca430a13614968b9e380b561e4271b9601c08531f4fc2cecb3a2f9b1a42602a953f12b7b01e3409b1ba42ff561b1ff9914f3f3976d65aaf1f25531f2e096e240
7
+ data.tar.gz: 25512d9a0a614f92cf6c92661d8ce87f3786fa34cf71bb83062ec048dac0704cad1480776f8351e419c18872ae6d3f1cc4bfcf5a5f59b2ef2b8299c7914cb043
data/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ # 4.2.0
4
+
5
+ * Add support for `body_chunks:` to specify which chunks a streaming HTTP client receives from a stub (#629)
6
+
7
+ With `to_return(body: "hello")`, Net::HTTP yields `"hello"` to the `read_body` block in one call. With `to_return(body_chunks: ["hel", "lo"])`, it calls the block twice, first with `"hel"` and then with `"lo"`. This lets you test how your code handles a message split across two reads.
8
+
9
+ Curb and Typhoeus also deliver the chunks to `on_body`, and Excon delivers them to `response_block`. Reading the whole body returns `"hello"` with any adapter.
10
+
3
11
  # 4.1.0
4
12
 
5
13
  * Match request headers with `hash_including` and `hash_excluding` (#942)
data/README.md CHANGED
@@ -428,6 +428,14 @@ For JSON, `to_return_json` sets it for you:
428
428
  stub_request(:any, "www.example.com").to_return_json(body: {})
429
429
  ```
430
430
 
431
+ Use `body_chunks:` to test how your code handles a message split across multiple reads.
432
+
433
+ ```ruby
434
+ stub_request(:get, "www.example.com/stream").to_return(body_chunks: ["hel", "lo"])
435
+ ```
436
+
437
+ Net::HTTP, Curb, Typhoeus, and Excon support streaming the chunks. Reading the whole body returns `"hello"` with any adapter.
438
+
431
439
  ### Response with body specified as IO object
432
440
 
433
441
  ```ruby
@@ -181,7 +181,9 @@ if defined?(Curl)
181
181
  build_curb_response(webmock_response)
182
182
  WebMock::CallbackRegistry.invoke_callbacks(
183
183
  {lib: :curb}, request_signature, webmock_response)
184
- invoke_curb_callbacks
184
+ # A followed redirect already delivered the final chunked response.
185
+ chunked = @webmock_chunked_response
186
+ invoke_curb_callbacks if chunked.nil? || chunked.equal?(webmock_response)
185
187
  true
186
188
  else
187
189
  @webmock_performing_easy = true
@@ -289,6 +291,7 @@ if defined?(Curl)
289
291
 
290
292
  def clear_webmock_response
291
293
  @body_str = @header_str = @response_code = @content_type = nil
294
+ @webmock_chunked_response = nil
292
295
  @last_effective_url = @transfer_encoding = @webmock_last_result = nil
293
296
  @webmock_body = @webmock_header = nil
294
297
  end
@@ -375,8 +378,16 @@ if defined?(Curl)
375
378
  raise Curl::Err::TimeoutError if webmock_response.should_timeout
376
379
  webmock_response.raise_error_if_any
377
380
 
378
- @body_str = webmock_response.body
379
381
  @response_code = webmock_response.status[0]
382
+ if webmock_response.body_chunks
383
+ @webmock_chunked_response = webmock_response
384
+ @webmock_last_result ||= 0
385
+ unless @on_body
386
+ @body_str = webmock_response.body_chunks_permitted?(@webmock_method) ? webmock_response.body : ''.b
387
+ end
388
+ else
389
+ @body_str = webmock_response.body
390
+ end
380
391
 
381
392
  @header_str = "HTTP/1.1 #{webmock_response.status[0]} #{webmock_response.status[1]}\r\n".dup
382
393
 
@@ -422,7 +433,9 @@ if defined?(Curl)
422
433
  @on_progress.call(0.0,1.0,0.0,1.0) if @on_progress
423
434
  self.header_str.lines.each { |header_line| @on_header.call header_line } if @on_header
424
435
  if @on_body
425
- if chunked_response?
436
+ if @webmock_chunked_response
437
+ deliver_body_chunks
438
+ elsif chunked_response?
426
439
  self.body_str.each do |chunk|
427
440
  @on_body.call(chunk)
428
441
  end
@@ -431,11 +444,16 @@ if defined?(Curl)
431
444
  end
432
445
  end
433
446
  completed_code = response_code
434
- completed_result = last_result if multi
447
+ completed_result = @webmock_last_result
435
448
  @on_complete.call(self) if @on_complete
436
449
 
437
- if multi && completed_result != 0
438
- @on_failure.call(self, Curl::Easy.error(completed_result)) if @on_failure
450
+ if completed_result && completed_result != 0
451
+ error = Curl::Easy.error(completed_result)
452
+ if @on_failure
453
+ @on_failure.call(self, error)
454
+ elsif !multi
455
+ raise error.first, error.last
456
+ end
439
457
  return
440
458
  end
441
459
 
@@ -451,6 +469,20 @@ if defined?(Curl)
451
469
  end
452
470
  end
453
471
 
472
+ def deliver_body_chunks
473
+ return unless @webmock_chunked_response.body_chunks_permitted?(@webmock_method)
474
+ chunks = @webmock_chunked_response.body_chunks || [@webmock_chunked_response.body]
475
+ chunks.each do |chunk|
476
+ size = chunk.bytesize
477
+ written = @on_body.call(chunk.dup)
478
+ if written.is_a?(Integer) && written != size
479
+ @webmock_last_result = 23 # CURLE_WRITE_ERROR
480
+ break
481
+ end
482
+ end
483
+ end
484
+ private :deliver_body_chunks
485
+
454
486
  def chunked_response?
455
487
  defined?( @transfer_encoding ) && @transfer_encoding == 'chunked' && self.body_str.respond_to?(:each)
456
488
  end
@@ -565,6 +597,7 @@ if defined?(Curl)
565
597
  end
566
598
 
567
599
  def body_str
600
+ return @body_str if @webmock_chunked_response
568
601
  @body_str ||= super
569
602
  end
570
603
  alias body body_str
@@ -57,8 +57,7 @@ if defined?(Excon)
57
57
 
58
58
  if mock_response = WebMock::StubRegistry.instance.response_for_request(mock_request)
59
59
  self.perform_callbacks(mock_request, mock_response, real_request: false)
60
- response = self.real_response(mock_response)
61
- response
60
+ self.real_response(mock_response, params)
62
61
  elsif WebMock.net_connect_allowed?(mock_request.uri)
63
62
  conn = new_excon_connection(params)
64
63
  real_response = conn.request(request_params_from(params.merge(mock: false)))
@@ -126,7 +125,7 @@ if defined?(Excon)
126
125
  contents
127
126
  end
128
127
 
129
- def self.real_response(mock)
128
+ def self.real_response(mock, params)
130
129
  raise Excon::Errors::Timeout if mock.should_timeout
131
130
  mock.raise_error_if_any
132
131
  headers = mock.headers || {}
@@ -134,13 +133,56 @@ if defined?(Excon)
134
133
  cookies = Array(headers["Set-Cookie"]).map(&:dup)
135
134
  # Excon joins repeated headers, and lists each cookie in :cookies.
136
135
  headers = headers.merge("Set-Cookie" => join_cookies(cookies)) if cookies.size > 1
137
- {
138
- body: mock.body,
136
+ response = {
139
137
  status: mock.status[0].to_i,
140
138
  reason_phrase: mock.status[1],
141
139
  headers: headers,
142
140
  cookies: cookies
143
141
  }
142
+ chunks = mock.body_chunks
143
+ if chunks && (params[:method].to_s.downcase == 'connect' || !mock.body_chunks_permitted?(params[:method]))
144
+ response[:body] = ''.b
145
+ elsif chunks && params[:response_block] && !unexpected_status?(params, response[:status])
146
+ response[:body] = ''.b
147
+ response[:webmock_body_chunks] = chunks
148
+ else
149
+ response[:body] = mock.body
150
+ end
151
+ response
152
+ end
153
+
154
+ def self.unexpected_status?(params, status)
155
+ params.key?(:expects) && params[:middlewares].include?(::Excon::Middleware::Expects) &&
156
+ !Array(params[:expects]).include?(status)
157
+ end
158
+
159
+ # Deliver during Excon's response phase, including for pipelined requests.
160
+ module ChunkedResponse
161
+ def response_call(datum)
162
+ if datum[:response] && (chunks = datum[:response].delete(:webmock_body_chunks))
163
+ headers = datum[:response][:headers]
164
+ chunked = Array(headers['Transfer-Encoding']).join(',').split(',').last.to_s.strip.casecmp?('chunked')
165
+ total = headers['Content-Length'].to_i if !chunked && headers['Content-Length']
166
+ remaining = total
167
+ each_body_chunk(chunks, chunked ? nil : datum[:chunk_size]) do |part|
168
+ remaining = [remaining - part.bytesize, 0].max if total
169
+ datum[:response_block].call(part, remaining, total)
170
+ end
171
+ end
172
+ super
173
+ end
174
+
175
+ private
176
+
177
+ def each_body_chunk(chunks, limit)
178
+ chunks.each do |chunk|
179
+ if limit && limit > 0 && chunk.bytesize > limit
180
+ (0...chunk.bytesize).step(limit) { |offset| yield chunk.byteslice(offset, limit) }
181
+ else
182
+ yield chunk.dup
183
+ end
184
+ end
185
+ end
144
186
  end
145
187
 
146
188
  # Joined as Excon joins them, or as bytes when they are in
@@ -174,6 +216,8 @@ if defined?(Excon)
174
216
  end
175
217
  end
176
218
 
219
+ Excon::Middleware::Mock.prepend(WebMock::HttpLibAdapters::ExconAdapter::ChunkedResponse)
220
+
177
221
  Excon::Connection.class_eval do
178
222
  def self.new(args = {})
179
223
  args.delete(:__construction_args)
@@ -108,7 +108,7 @@ module WebMock
108
108
  @socket = self.class.socket_type.new
109
109
  WebMock::CallbackRegistry.invoke_callbacks(
110
110
  {lib: :net_http}, request_signature, webmock_response)
111
- build_net_http_response(webmock_response, request.uri, &block)
111
+ build_net_http_response(webmock_response, request, &block)
112
112
  elsif WebMock.net_connect_allowed?(request_signature.uri)
113
113
  check_right_http_connection
114
114
  callback_options = {lib: :net_http, real_request: true}
@@ -189,14 +189,16 @@ module WebMock
189
189
  end
190
190
  end
191
191
 
192
- def build_net_http_response(webmock_response, request_uri, &block)
192
+ def build_net_http_response(webmock_response, request, &block)
193
193
  response = Net::HTTPResponse.send(:response_class, webmock_response.status[0].to_s).new("1.0", webmock_response.status[0].to_s, webmock_response.status[1])
194
- body = webmock_response.body
195
- body = nil if webmock_response.status[0].to_s == '204'
196
-
197
- # A copy, so that changing the response body, for example its
198
- # encoding, does not change the stubbed body
199
- response.instance_variable_set(:@body, body&.dup)
194
+ if chunks = webmock_response.body_chunks
195
+ if request.response_body_permitted? && response.class.body_permitted?
196
+ response.instance_variable_set(:@webmock_body_chunks, chunks)
197
+ end
198
+ elsif response.code != '204'
199
+ # Changing the returned body or its encoding must not change the stub.
200
+ response.instance_variable_set(:@body, webmock_response.body.dup)
201
+ end
200
202
  webmock_response.headers.to_a.each do |name, values|
201
203
  values = [values] unless values.is_a?(Array)
202
204
  values.each do |value|
@@ -206,7 +208,7 @@ module WebMock
206
208
 
207
209
  response.instance_variable_set(:@read, true)
208
210
 
209
- response.uri = request_uri
211
+ response.uri = request.uri
210
212
  response.body_encoding = response_body_encoding if respond_to?(:response_body_encoding)
211
213
 
212
214
  response.extend Net::WebMockHTTPResponse
@@ -16,8 +16,13 @@
16
16
 
17
17
  module Net
18
18
  module WebMockHTTPResponse
19
+ def body=(body)
20
+ @webmock_body_chunks = nil
21
+ super
22
+ end
23
+
19
24
  def read_body(dest = nil, &block)
20
- if !(defined?(@__read_body_previously_called).nil?) && @__read_body_previously_called
25
+ if defined?(@__read_body_previously_called) && @__read_body_previously_called
21
26
  return super
22
27
  end
23
28
  if dest.nil? && block.nil?
@@ -25,16 +30,21 @@ module Net
25
30
  return @body
26
31
  end
27
32
  raise ArgumentError.new("both arg and block given for HTTP method") if dest && block
28
- return nil if @body.nil?
33
+ return nil if @body.nil? && !@webmock_body_chunks
29
34
 
30
35
  dest ||= ::Net::ReadAdapter.new(block)
31
- dest << @body
36
+ if @webmock_body_chunks
37
+ @webmock_body_chunks.each { |chunk| dest << chunk.dup }
38
+ else
39
+ dest << @body
40
+ end
32
41
  @body = dest
33
42
  webmock_apply_body_encoding
34
43
  @body
35
44
  ensure
36
45
  # allow subsequent calls to #read_body to proceed as normal, without our hack...
37
46
  @__read_body_previously_called = true
47
+ @webmock_body_chunks = nil if @body
38
48
  end
39
49
 
40
50
  private
@@ -45,6 +55,7 @@ module Net
45
55
  # without reading, so apply the encoding the first time the body is read
46
56
  # or when the request block returns, and ignore later changes to it.
47
57
  def webmock_apply_body_encoding
58
+ @body = @webmock_body_chunks.join('').force_encoding(Encoding::BINARY) if @webmock_body_chunks && @body.nil?
48
59
  return if defined?(@__body_encoding_applied) && @__body_encoding_applied
49
60
  @__body_encoding_applied = true
50
61
 
@@ -139,7 +139,7 @@ if defined?(Typhoeus)
139
139
  webmock_response
140
140
  end
141
141
 
142
- def self.generate_typhoeus_response(webmock_response, url)
142
+ def self.generate_typhoeus_response(webmock_response, url, omit_body: false)
143
143
  response_options = if webmock_response.should_timeout
144
144
  {
145
145
  code: 0,
@@ -153,7 +153,7 @@ if defined?(Typhoeus)
153
153
  {
154
154
  code: webmock_response.status[0],
155
155
  status_message: webmock_response.status[1],
156
- body: webmock_response.body,
156
+ body: omit_body ? ''.b : webmock_response.body,
157
157
  headers: webmock_response.headers,
158
158
  return_code: :ok,
159
159
  response_headers: response_headers_string(webmock_response)
@@ -173,6 +173,46 @@ if defined?(Typhoeus)
173
173
  response
174
174
  end
175
175
 
176
+ def self.finish_stubbed_request(request, webmock_response, url)
177
+ chunks = webmock_response.body_chunks
178
+ if chunks && (request.options[:nobody] || !webmock_response.body_chunks_permitted?(request.options[:method]) ||
179
+ webmock_response.should_timeout || webmock_response.exception)
180
+ chunks = []
181
+ end
182
+ omit_body = chunks && (chunks.empty? || (request.respond_to?(:streaming?) && request.streaming?))
183
+ response = generate_typhoeus_response(webmock_response, url, omit_body: omit_body)
184
+ request.execute_headers_callbacks(response) if request.respond_to?(:on_headers)
185
+ if request.respond_to?(:streaming?) && request.streaming?
186
+ response.options[:response_body] = "".dup
187
+ if chunks
188
+ stream_body_chunks(request, response, chunks)
189
+ else
190
+ request.on_body.each { |callback| callback.call(webmock_response.body, response) }
191
+ end
192
+ end
193
+ request.finish(response)
194
+ webmock_response.raise_error_if_any
195
+ end
196
+
197
+ # Typhoeus ignores transport errors on mocked responses. Ask it how
198
+ # an unmocked response with the same curl result would report its status.
199
+ module AbortedTransfer
200
+ %i[success? failure? modified?].each do |predicate|
201
+ define_method(predicate) { ::Typhoeus::Response.new(options).public_send(predicate) }
202
+ end
203
+ end
204
+
205
+ def self.stream_body_chunks(request, response, chunks)
206
+ chunks.each do |chunk|
207
+ data = chunk.dup
208
+ if request.on_body.any? { |callback| :abort == callback.call(data, response) }
209
+ response.options[:return_code] = :write_error
210
+ response.extend(AbortedTransfer)
211
+ break
212
+ end
213
+ end
214
+ end
215
+
176
216
  # Without response_headers, Typhoeus builds them for a mocked response
177
217
  # from its return_code, as in "HTTP/1.1 ok Mock Reason Phrase".
178
218
  def self.response_headers_string(webmock_response)
@@ -250,16 +290,7 @@ if defined?(Typhoeus)
250
290
  recorded = ::WebMock::HttpLibAdapters::TyphoeusAdapter.signature_for_history(request_signature)
251
291
 
252
292
  if webmock_response = ::WebMock::StubRegistry.instance.response_for_request(request_signature, record: recorded)
253
- response = ::WebMock::HttpLibAdapters::TyphoeusAdapter.generate_typhoeus_response(webmock_response, url)
254
- if request.respond_to?(:on_headers)
255
- request.execute_headers_callbacks(response)
256
- end
257
- if request.respond_to?(:streaming?) && request.streaming?
258
- response.options[:response_body] = "".dup
259
- request.on_body.each { |callback| callback.call(webmock_response.body, response) }
260
- end
261
- request.finish(response)
262
- webmock_response.raise_error_if_any
293
+ ::WebMock::HttpLibAdapters::TyphoeusAdapter.finish_stubbed_request(request, webmock_response, url)
263
294
  res = false
264
295
  elsif !WebMock.net_connect_allowed?(request_signature.uri)
265
296
  # The request doesn't complete, so the callback that takes the
@@ -38,6 +38,9 @@ module WebMock
38
38
  require_args!(response_hashes, :to_return_json, 'response')
39
39
 
40
40
  json_response_hashes = response_hashes.map do |resp_h|
41
+ if resp_h.key?(:body_chunks) || resp_h.key?('body_chunks')
42
+ raise ArgumentError, "Use #to_return with body_chunks to stream a response"
43
+ end
41
44
  headers, body = resp_h.values_at(:headers, :body)
42
45
 
43
46
  json_body = if body.respond_to?(:call)
@@ -38,10 +38,32 @@ module WebMock
38
38
  end
39
39
 
40
40
  def body
41
+ if @body_chunks && !@body
42
+ @joined_chunks = @body_chunks.join('').force_encoding(Encoding::BINARY).freeze
43
+ @body = @joined_chunks.dup
44
+ end
41
45
  @body || String.new("")
42
46
  end
43
47
 
48
+ def body_chunks
49
+ # An after_request callback can edit the buffered body in place.
50
+ # Once its contents change, its original chunk boundaries no longer apply.
51
+ return [@body] if @joined_chunks && @body != @joined_chunks
52
+ @body_chunks
53
+ end
54
+
55
+ def body_chunks_permitted?(method)
56
+ code = status[0].to_i
57
+ method.to_s.downcase != 'head' && code >= 200 && ![204, 205, 304].include?(code)
58
+ end
59
+
60
+ def initialize_copy(original)
61
+ super
62
+ @body = @body.dup if @joined_chunks
63
+ end
64
+
44
65
  def body=(body)
66
+ @body_chunks = @joined_chunks = nil
45
67
  @body = body
46
68
  assert_valid_body!
47
69
  stringify_body!
@@ -86,10 +108,17 @@ module WebMock
86
108
 
87
109
  def options=(options)
88
110
  options = WebMock::Util::HashKeysStringifier.stringify_keys!(options)
89
- HashValidator.new(options).validate_keys('headers', 'status', 'body', 'exception', 'should_timeout')
111
+ HashValidator.new(options).validate_keys('headers', 'status', 'body', 'body_chunks', 'exception', 'should_timeout')
112
+ if options.key?('body_chunks') && options.key?('body')
113
+ raise ArgumentError, "A stubbed response cannot have both body and body_chunks"
114
+ end
90
115
  self.headers = options['headers']
91
116
  self.status = options['status']
92
- self.body = options['body']
117
+ if options.key?('body_chunks')
118
+ self.body_chunks = options['body_chunks']
119
+ else
120
+ self.body = options['body']
121
+ end
93
122
  self.exception = options['exception']
94
123
  @should_timeout = options['should_timeout']
95
124
  end
@@ -104,7 +133,10 @@ module WebMock
104
133
  end
105
134
 
106
135
  def ==(other)
107
- self.body == other.body &&
136
+ chunks = body_chunks
137
+ other_chunks = other.body_chunks if other.respond_to?(:body_chunks)
138
+ same_body = (chunks || other_chunks) ? chunks == other_chunks : body == other.body
139
+ same_body &&
108
140
  self.headers === other.headers &&
109
141
  self.status == other.status &&
110
142
  self.exception == other.exception &&
@@ -113,6 +145,14 @@ module WebMock
113
145
 
114
146
  private
115
147
 
148
+ def body_chunks=(chunks)
149
+ unless chunks.is_a?(Array) && chunks.all? { |chunk| chunk.is_a?(String) }
150
+ raise ArgumentError, "body_chunks must be an array of strings"
151
+ end
152
+ @body = @joined_chunks = nil
153
+ @body_chunks = chunks.map { |chunk| chunk.b.freeze }.freeze
154
+ end
155
+
116
156
  WARNED_STATUSES = {}
117
157
  private_constant :WARNED_STATUSES
118
158
 
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module WebMock
4
- VERSION = '4.1.0' unless defined?(::WebMock::VERSION)
4
+ VERSION = '4.2.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: 4.1.0
4
+ version: 4.2.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/v4.1.0/CHANGELOG.md
367
- documentation_uri: https://www.rubydoc.info/gems/webmock/4.1.0
368
- source_code_uri: https://github.com/bblimke/webmock/tree/v4.1.0
366
+ changelog_uri: https://github.com/bblimke/webmock/blob/v4.2.0/CHANGELOG.md
367
+ documentation_uri: https://www.rubydoc.info/gems/webmock/4.2.0
368
+ source_code_uri: https://github.com/bblimke/webmock/tree/v4.2.0
369
369
  wiki_uri: https://github.com/bblimke/webmock/wiki
370
370
  rdoc_options: []
371
371
  require_paths: