webmock 4.1.0 → 4.3.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: c60034709239ce73b68da8da092c4e7e0ed8d0bef698f629ce6dc2a5ac6ceca8
4
+ data.tar.gz: c233fec73699cf7f7b7680207d7858afd09de17990115a1496d6286b1ab24526
5
5
  SHA512:
6
- metadata.gz: cd641f8e94aac2eb9fb0e5305a1f375c871e78138c33f711a508bd07016571adb4b112e4d05c193524d0081d459273aca4153a47b1396ff9b53a6b7197d43b0d
7
- data.tar.gz: 94816f0976ab5d05b283b081b77734c566ea5b4f42ac221893493a0012a0bcafcfa0c9493220f319ff305079df352a9bced0efd9d3347c5d34e73d2b26c690eb
6
+ metadata.gz: b4777a9e9c4fe36fc342ba9589d1c43b514d0c72898c1a4baf91ed0bb572debaaca1b07d82cf4e4bb7aae6915625edecffb26e9ac89572a1362046d9a6af22b6
7
+ data.tar.gz: e13f72478e7a02da4e4f3305f4ea96cdce6a27f6330fc2c0978ce4e2c89b7a45babbde2f77ccef385f31b18c9946f699e3967f5fd7ec682ce19a14dd3804fa83
data/CHANGELOG.md CHANGED
@@ -1,5 +1,29 @@
1
1
  # Changelog
2
2
 
3
+ # 4.3.0
4
+
5
+ * Allow real requests except to destinations listed in `disallow:` (#1058)
6
+
7
+ `WebMock.allow_net_connect!(disallow: ["billing.example.com"])` lets tests reach other hosts. When WebMock intercepts a request to the billing host, it raises `WebMock::NetConnectNotAllowedError` unless a stub matches. `disallow:` accepts the same matchers as `allow:`.
8
+
9
+ Thanks to [sandfortw](https://github.com/sandfortw) for the suggestion
10
+
11
+ * Fix `RequestStub#then` silently ignoring its block (#1037)
12
+
13
+ Previously, `stub.then { |s| s.with(query: {page: "1"}) }` ignored the block. The stub now requires `page=1`, so a request without it no longer matches. With a block, `then` returns the block's result. Without a block, it still chains responses as before.
14
+
15
+ * Fix Excon splitting stubbed chunks when `Transfer-Encoding` is `["gzip", "chunked"]`
16
+
17
+ WebMock now keeps transfer encodings in the order you specify. With `body_chunks: ["ab", "cd"]` and Excon's `chunk_size: 1`, the streaming callback now receives `"ab"` and `"cd"`. Previously it received four single bytes.
18
+
19
+ # 4.2.0
20
+
21
+ * Add support for `body_chunks:` to specify which chunks a streaming HTTP client receives from a stub (#629)
22
+
23
+ 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.
24
+
25
+ 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.
26
+
3
27
  # 4.1.0
4
28
 
5
29
  * 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
@@ -504,7 +512,7 @@ stub_request(:get, "www.example.com").to_return(raw_response_file.read)
504
512
  stub_request(:any, 'www.example.net').
505
513
  to_return { |request| {body: request.body} }
506
514
 
507
- RestClient.post('www.example.net', 'abc') # ===> "abc\n"
515
+ RestClient.post('www.example.net', 'abc') # ===> "abc"
508
516
  ```
509
517
 
510
518
  ### Responses dynamically evaluated from lambda
@@ -513,7 +521,7 @@ RestClient.post('www.example.net', 'abc') # ===> "abc\n"
513
521
  stub_request(:any, 'www.example.net').
514
522
  to_return(lambda { |request| {body: request.body} })
515
523
 
516
- RestClient.post('www.example.net', 'abc') # ===> "abc\n"
524
+ RestClient.post('www.example.net', 'abc') # ===> "abc"
517
525
  ```
518
526
 
519
527
  ### Dynamically evaluated raw responses recorded with `curl -is`
@@ -531,7 +539,7 @@ stub_request(:get, "www.example.com").
531
539
  stub_request(:any, 'www.example.net').
532
540
  to_return(body: lambda { |request| request.body })
533
541
 
534
- RestClient.post('www.example.net', 'abc') # ===> "abc\n"
542
+ RestClient.post('www.example.net', 'abc') # ===> "abc"
535
543
  ```
536
544
 
537
545
  ### Rack responses
@@ -599,27 +607,29 @@ WebMock is enabled, as with `Curl::Easy` requests.
599
607
  ```ruby
600
608
  stub_request(:get, "www.example.com").
601
609
  to_return({body: "abc"}, {body: "def"})
602
- Net::HTTP.get('www.example.com', '/') # ===> "abc\n"
603
- Net::HTTP.get('www.example.com', '/') # ===> "def\n"
610
+ Net::HTTP.get('www.example.com', '/') # ===> "abc"
611
+ Net::HTTP.get('www.example.com', '/') # ===> "def"
604
612
 
605
613
  #after all responses are used the last response will be returned infinitely
606
614
 
607
- Net::HTTP.get('www.example.com', '/') # ===> "def\n"
615
+ Net::HTTP.get('www.example.com', '/') # ===> "def"
608
616
  ```
609
617
 
610
618
  ### Multiple responses using chained `to_return()`, `to_raise()` or `to_timeout` declarations
611
619
 
612
620
  ```ruby
613
621
  stub_request(:get, "www.example.com").
614
- to_return({body: "abc"}).then. #then() is just a syntactic sugar
622
+ to_return({body: "abc"}).then.
615
623
  to_return({body: "def"}).then.
616
624
  to_raise(MyException)
617
625
 
618
- Net::HTTP.get('www.example.com', '/') # ===> "abc\n"
619
- Net::HTTP.get('www.example.com', '/') # ===> "def\n"
626
+ Net::HTTP.get('www.example.com', '/') # ===> "abc"
627
+ Net::HTTP.get('www.example.com', '/') # ===> "def"
620
628
  Net::HTTP.get('www.example.com', '/') # ===> MyException raised
621
629
  ```
622
630
 
631
+ Without a block, `.then` is optional between responses. With a block, `stub.then { |s| ... }` yields the stub and returns the block's result, just like Ruby's `then`.
632
+
623
633
  ### Specifying number of times given response should be returned
624
634
 
625
635
  ```ruby
@@ -627,9 +637,9 @@ stub_request(:get, "www.example.com").
627
637
  to_return({body: "abc"}).times(2).then.
628
638
  to_return({body: "def"})
629
639
 
630
- Net::HTTP.get('www.example.com', '/') # ===> "abc\n"
631
- Net::HTTP.get('www.example.com', '/') # ===> "abc\n"
632
- Net::HTTP.get('www.example.com', '/') # ===> "def\n"
640
+ Net::HTTP.get('www.example.com', '/') # ===> "abc"
641
+ Net::HTTP.get('www.example.com', '/') # ===> "abc"
642
+ Net::HTTP.get('www.example.com', '/') # ===> "def"
633
643
  ```
634
644
 
635
645
  ### Removing unused stubs
@@ -655,6 +665,18 @@ WebMock.disable_net_connect!
655
665
  Net::HTTP.get('www.something.com', '/') # ===> Failure
656
666
  ```
657
667
 
668
+ ### Block real requests to selected hosts or URLs
669
+
670
+ ```ruby
671
+ WebMock.allow_net_connect!(disallow: ["billing.example.com"])
672
+ ```
673
+
674
+ This allows real requests to other hosts. A request to `billing.example.com` needs a matching stub or it raises `WebMock::NetConnectNotAllowedError`. Each call to `allow_net_connect!` replaces the previous list.
675
+
676
+ `disallow:` accepts the same hosts, URLs, regular expressions, and callables as `allow:`. A URL with a path matches that exact path and query, so blocking `https://api.example/charge` still allows `https://api.example/charge?id=1`. Use a host name to block every path on that host.
677
+
678
+ When Patron, Curb, or Typhoeus follows redirects inside libcurl, WebMock checks only the initial request. For direct access to an async-http connection pool, use a host rule because WebMock sees only the pool endpoint.
679
+
658
680
  ### External requests can be disabled while allowing localhost
659
681
 
660
682
  ```ruby
@@ -782,13 +804,13 @@ which can be passed to `WebMock.allow_net_connect!` and `WebMock.disable_net_con
782
804
  WebMock.allow_net_connect!(net_http_connect_on_start: true)
783
805
  ```
784
806
 
785
- This forces WebMock Net::HTTP adapter to always connect on `Net::HTTP.start`. At the time of connection being made there is no information about the request or URL yet, therefore WebMock is not able to decide whether to stub a request or not and all connections are allowed. To enable connections only to a specific domain (e.g. your test server) use:
807
+ With this setting, Net::HTTP opens a connection on `start`, even if a stub later handles the request or `disable_net_connect!` blocks it. To connect on start only for your test server, give its host name.
786
808
 
787
809
  ```ruby
788
810
  WebMock.allow_net_connect!(net_http_connect_on_start: "www.example.com")
789
811
  ```
790
812
 
791
- The path is not known when the connection is made, so a URL with a path given here never matches.
813
+ A host listed in `disallow:` prevents the connection on start. The request path is unknown at that point, so a URL with a path in `net_http_connect_on_start:` never matches. WebMock applies path-specific `disallow:` rules when the request is made.
792
814
 
793
815
  ## Setting Expectations
794
816
 
@@ -12,6 +12,7 @@ module WebMock
12
12
  attr_accessor :allow_net_connect
13
13
  attr_accessor :allow_localhost
14
14
  attr_accessor :allow
15
+ attr_accessor :disallow
15
16
  attr_accessor :net_http_connect_on_start
16
17
  attr_accessor :show_stubbing_instructions
17
18
  attr_accessor :query_values_notation
@@ -5,8 +5,13 @@ module WebMock
5
5
  class NetConnectNotAllowedError < Exception
6
6
  def initialize(request_signature)
7
7
  request_signature_snippet = RequestSignatureSnippet.new(request_signature)
8
+ reason = if Config.instance.disallow
9
+ "Real HTTP connections to this destination are disabled."
10
+ else
11
+ "Real HTTP connections are disabled."
12
+ end
8
13
  text = [
9
- "Real HTTP connections are disabled. Unregistered request: #{request_signature}",
14
+ "#{reason} Unregistered request: #{request_signature}",
10
15
  request_signature_snippet.stubbing_instructions,
11
16
  request_signature_snippet.request_stubs,
12
17
  "="*60
@@ -68,7 +68,6 @@ if defined?(Async::HTTP)
68
68
  request_signature = build_request_signature(request)
69
69
  WebMock::RequestRegistry.instance.put(request_signature)
70
70
  webmock_response = WebMock::StubRegistry.instance.response_for_request(request_signature)
71
- net_connect_allowed = WebMock.net_connect_allowed?(request_signature.uri)
72
71
  real_request = false
73
72
 
74
73
  if webmock_response
@@ -76,11 +75,11 @@ if defined?(Async::HTTP)
76
75
  raise Async::TimeoutError, 'WebMock timeout error' if webmock_response.should_timeout
77
76
  WebMockApplication.add_webmock_response(request, webmock_response)
78
77
  response = @webmock_client.call(request)
79
- elsif net_connect_allowed
78
+ elsif WebMock.net_connect_allowed?(request_signature.uri)
80
79
  response = @network_client.call(request)
81
80
  real_request = true
82
81
  else
83
- raise WebMock::NetConnectNotAllowedError.new(request_signature) unless webmock_response
82
+ raise WebMock::NetConnectNotAllowedError.new(request_signature)
84
83
  end
85
84
 
86
85
  if WebMock::CallbackRegistry.any_callbacks?
@@ -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)
@@ -105,7 +108,7 @@ module WebMock
105
108
  end
106
109
 
107
110
  def then
108
- self
111
+ block_given? ? super : self
109
112
  end
110
113
 
111
114
  def times(number)
@@ -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
 
@@ -23,21 +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.
26
+ # Request matching sorts repeated values. In responses the last cookie
27
+ # of the same name wins, and transfer codings apply in the order given.
28
+ # Some suites replace normalize_headers with a one-argument method.
29
+ ORDERED_RESPONSE_HEADERS = %w[Set-Cookie Transfer-Encoding].freeze
30
+ private_constant :ORDERED_RESPONSE_HEADERS
31
+
32
32
  def self.normalize_response_headers(headers)
33
33
  normalized = normalize_headers(headers)
34
- return normalized unless normalized.is_a?(Hash) && normalized["Set-Cookie"].is_a?(Array)
34
+ return normalized unless normalized.is_a?(Hash) && ORDERED_RESPONSE_HEADERS.any? { |name| normalized[name].is_a?(Array) }
35
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"
36
+ ordered = {}
37
+ headers.each do |name, values|
38
+ next unless values.is_a?(Array)
39
+ name = normalize_name(name)
40
+ ordered[name] = values.map(&:to_s) if ORDERED_RESPONSE_HEADERS.include?(name) && normalized[name].is_a?(Array)
39
41
  end
40
- cookies ? normalized.merge("Set-Cookie" => cookies.map(&:to_s)) : normalized
42
+ normalized.merge(ordered)
41
43
  end
42
44
 
43
45
  def self.sorted_headers_string(headers)
@@ -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.3.0' unless defined?(::WebMock::VERSION)
5
5
  end
@@ -47,6 +47,7 @@ module WebMock
47
47
  return restoring_net_connect_settings { allow_net_connect!(options); block.call } if block
48
48
 
49
49
  Config.instance.allow_net_connect = true
50
+ Config.instance.disallow = options[:disallow]
50
51
  Config.instance.net_http_connect_on_start = options[:net_http_connect_on_start]
51
52
  end
52
53
 
@@ -54,12 +55,13 @@ module WebMock
54
55
  return restoring_net_connect_settings { disable_net_connect!(options); block.call } if block
55
56
 
56
57
  Config.instance.allow_net_connect = false
58
+ Config.instance.disallow = nil
57
59
  Config.instance.allow_localhost = options[:allow_localhost]
58
60
  Config.instance.allow = options[:allow]
59
61
  Config.instance.net_http_connect_on_start = options[:net_http_connect_on_start]
60
62
  end
61
63
 
62
- NET_CONNECT_SETTINGS = %i[allow_net_connect allow_localhost allow net_http_connect_on_start].freeze
64
+ NET_CONNECT_SETTINGS = %i[allow_net_connect allow_localhost allow disallow net_http_connect_on_start].freeze
63
65
  private_constant :NET_CONNECT_SETTINGS
64
66
 
65
67
  # Runs the block, then puts back the net connect settings from before it,
@@ -92,23 +94,21 @@ module WebMock
92
94
  def self.net_connect_allowed_by_settings?(uri = nil)
93
95
  return !!Config.instance.allow_net_connect if uri.nil?
94
96
 
95
- if uri.is_a?(String)
96
- uri = WebMock::Util::URI.normalize_uri(uri)
97
+ if Config.instance.allow_net_connect
98
+ disallow = Config.instance.disallow
99
+ !disallow || !net_connect_explicit_allowed?(disallow, WebMock::Util::URI.normalize_uri(uri))
100
+ else
101
+ uri = WebMock::Util::URI.normalize_uri(uri) if uri.is_a?(String)
102
+ Config.instance.allow_localhost && WebMock::Util::URI.is_uri_localhost?(uri) ||
103
+ Config.instance.allow && net_connect_explicit_allowed?(Config.instance.allow, uri)
97
104
  end
98
-
99
- !!Config.instance.allow_net_connect ||
100
- ( Config.instance.allow_localhost && WebMock::Util::URI.is_uri_localhost?(uri) ||
101
- Config.instance.allow && net_connect_explicit_allowed?(Config.instance.allow, uri) )
102
105
  end
103
106
 
104
107
  def self.net_http_connect_on_start?(uri)
105
- allowed = Config.instance.net_http_connect_on_start || false
106
-
107
- if [true, false].include?(allowed)
108
- allowed
109
- else
110
- net_connect_explicit_allowed?(allowed, uri)
111
- end
108
+ allowed = Config.instance.net_http_connect_on_start
109
+ return false unless allowed
110
+ return false if net_connect_explicit_allowed?(Config.instance.disallow, uri)
111
+ allowed.equal?(true) || net_connect_explicit_allowed?(allowed, uri)
112
112
  end
113
113
 
114
114
  def self.net_connect_explicit_allowed?(allowed, uri=nil)
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.3.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.3.0/CHANGELOG.md
367
+ documentation_uri: https://www.rubydoc.info/gems/webmock/4.3.0
368
+ source_code_uri: https://github.com/bblimke/webmock/tree/v4.3.0
369
369
  wiki_uri: https://github.com/bblimke/webmock/wiki
370
370
  rdoc_options: []
371
371
  require_paths: