webmock 3.39.0 → 3.42.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: f4a748dba8ab25b81fc4cd65b9cd09e7bc4fff957bb3bd0c92ef91b12ad9202e
4
- data.tar.gz: f4a161fa5bffd45a09a44d70f99045a28f90cc508cb30ea7c719e6b4acb3f63e
3
+ metadata.gz: 9bff4bef02b737edabff51c5a68f52b06ad2ee9b5280f11fd0b97ed93b85d13d
4
+ data.tar.gz: c9e3641f5610080b0c8968e2d8169b25ff0f78df0880e5ea07355fbc96012add
5
5
  SHA512:
6
- metadata.gz: e49c29028d6809a07bef2fab63f9a3d09c1b7a7ec9cf6c279ee4b0d56e23e636dd546692b737fb2e7017e66844e8aeb711dfb91aade297d82e2078304d84c003
7
- data.tar.gz: 5a240000226bfd4f60a22387bb6c1040c9fe00b16ceb9894c98bed42427d64523d2db41f05daaea0b1e5ea960f57b94a3a41ca42171fbe08ee6c7d6241362472
6
+ metadata.gz: 511313f001e32b777eacaf1666b51775f0690c63fc61551f12835dc55c3be54490c8111f21eaa3a4f772a3b26fed1a2f349bd39f352b6014d5509511c25681f5
7
+ data.tar.gz: a3623cc22f1c9719739fd3a804546acc619ef2a04624f343d162fbcb1ba49db5a3399a619fb5c6e0ae2842ab6f52e1d4e1a5affe366fa7ffa42149403bbf7063
data/CHANGELOG.md CHANGED
@@ -1,5 +1,67 @@
1
1
  # Changelog
2
2
 
3
+ # 3.42.0
4
+
5
+ * Fix VCR failing to replay responses recorded with the `auto_inflate` feature of the `http` gem (#1154)
6
+
7
+ Previously, for a real request made with `HTTP.use(:auto_inflate)`, `after_request` callbacks got the inflated body together with the `Content-Encoding: gzip` header of the compressed one. VCR, hooked into WebMock, recorded both, and replaying the cassette raised `Zlib::DataError: incorrect header check`, because the feature tried to inflate the body again. With VCR's `decode_compressed_response` option, recording raised `Zlib::GzipFile::Error` instead.
8
+
9
+ Callbacks now get the inflated body without the `Content-Encoding` header, as they do for a body that Net::HTTP inflates. A `Content-Length` header, when the response has one, gives the size of the inflated body. The response the client returns is unchanged, and so are the headers of a response with an empty body, such as one to a HEAD request.
10
+
11
+ A cassette recorded this way replays the response with those headers, while the real response keeps the headers of the compressed body.
12
+
13
+ This doesn't cover a client that inflates with a subclass of the feature, or responses returned by the `caching` feature of `http` 6. Callbacks get those as before.
14
+
15
+ Cassettes recorded with older versions that have the `Content-Encoding` header on an inflated body still fail. Record them again, or remove that header from their responses. Their `Content-Length` is still that of the compressed body.
16
+
17
+ # 3.41.0
18
+
19
+ WebMock now parses JSON request bodies with Ruby's `JSON.parse`, instead of its old parser, which converted JSON to YAML and failed on or misread some valid JSON. Every body pattern that matched on 3.40.0 still matches. If one matches only as the old parser reads the body, WebMock prints a deprecation warning, because 4.0 drops the old parser and the pattern won't match there.
20
+
21
+ * Match JSON request bodies with an escaped backslash in a string (#432)
22
+
23
+ Previously, a hash body pattern didn't match a JSON body with an escaped backslash inside a string, such as JSON inside JSON, because the old parser failed on it. For example, `with(body: {data: '{"url":"/p?a=1\u0026b=2"}'})` didn't match the body `{"data":"{\"url\":\"/p?a=1\\u0026b=2\"}"}`. It now matches.
24
+
25
+ Strings that the old parser changed now match too, for example `"a\u000ab"`, which it read as `"a b"`.
26
+
27
+ * Match numbers with an exponent in JSON request bodies
28
+
29
+ Previously, a number such as `1e2` or `1e+20` in a JSON body was read as a String, so `with(body: {amount: 1e20})` didn't match the body `{"amount":1e+20}`, which `to_json` generates for that hash with recent json versions, such as the one in Ruby 4.0. It now matches.
30
+
31
+ * Deprecate body patterns that match a JSON request body only as the old parser reads it
32
+
33
+ The old parser read some bodies that aren't valid JSON, and some values differently from `JSON.parse`. For example, `with(body: {a: 1})` matches the body `{a: 1}`, and `with(body: {amount: "1e+20"})` matches the body `{"amount":1e+20}`, because the old parser read that number as a String. Such a pattern still matches, and WebMock prints a warning once for each pattern:
34
+
35
+ ```
36
+ WebMock deprecation warning: the body pattern {"a" => 1} matched the request body "{a: 1}" only as WebMock's old JSON parser reads it. WebMock 4.0 drops that parser, so it won't match. Send valid JSON, for example from to_json, and write the pattern for what JSON.parse returns.
37
+ ```
38
+
39
+ To fix it, send valid JSON, for example `{a: 1}.to_json`, and write the pattern for what `JSON.parse` returns, such as `{amount: 1e20}`.
40
+
41
+ * Don't raise Psych errors for JSON request bodies such as one with an unquoted date
42
+
43
+ Previously, with Psych 4 or later (the default since Ruby 3.1), a JSON body such as `{"a": 2020-01-01}`, which isn't valid JSON, raised `Psych::DisallowedClass` when a stub had a hash body pattern, instead of WebMock's error for an unregistered request. It now doesn't match the pattern.
44
+
45
+ * Name a future major version in the deprecation warning for statuses such as `:ok`
46
+
47
+ The deprecation warning for a status such as `:ok`, added in 3.38.0, said that WebMock 4.0 would raise `ArgumentError` for it. 4.0 changes how JSON request bodies are read and doesn't change statuses yet, so the warning now names a future major version.
48
+
49
+ # 3.40.0
50
+
51
+ * Add support for `Curl::Multi` (#535)
52
+
53
+ Previously, WebMock didn't see requests sent with `Curl::Multi`. A handle added with `multi.add` and sent with `multi.perform` went to the real server, even when a stub matched it or real connections were disabled, and WebMock didn't record it.
54
+
55
+ Now a handle that matches a stub gets the stubbed response during `multi.perform`, and one that is neither stubbed nor allowed raises `WebMock::NetConnectNotAllowedError` from `multi.add`. Allowed requests still run together in curb's own multi loop. WebMock records both, and `WebMock.after_request` callbacks get both.
56
+
57
+ If your tests send `Curl::Multi` requests to real servers, stub them or allow their hosts, for example with `WebMock.disable_net_connect!(allow: "api.example.com")`. VCR, hooked into WebMock, now records and replays these requests too, and raises `VCR::Errors::UnhandledHTTPRequestError` for one that a cassette doesn't have, so record such cassettes again.
58
+
59
+ Thanks to [Todd Fisher](https://github.com/taf2)
60
+
61
+ * Drop curb callbacks on `Curl::Easy#reset` for stubbed requests, as curb does
62
+
63
+ Previously, a callback such as `on_complete`, set before `reset`, still ran for a stubbed request made after it. Curb drops every callback on `reset`, so a real request didn't run it. If your tests rely on such a callback, set it again after `reset`.
64
+
3
65
  # 3.39.0
4
66
 
5
67
  * Fix tracing libraries that wrap HTTPClient failing on stubbed requests (#1010)
data/README.md CHANGED
@@ -23,7 +23,7 @@ Supported HTTP libraries
23
23
  ------------------------
24
24
 
25
25
  * [Async::HTTP::Client](https://github.com/socketry/async-http)
26
- * [Curb](https://github.com/taf2/curb) (`Curl::Easy` only). `Curl::Multi` sends real requests even when a matching stub exists and `WebMock.disable_net_connect!` is in effect.
26
+ * [Curb](https://github.com/taf2/curb) (`Curl::Easy` and `Curl::Multi`)
27
27
  * [EM-HTTP-Request](https://github.com/igrigorik/em-http-request)
28
28
  * [Excon](https://github.com/excon/excon)
29
29
  * [HTTPClient](https://github.com/nahi/httpclient)
@@ -570,6 +570,20 @@ stub_request(:any, 'www.example.net').to_timeout
570
570
  RestClient.post('www.example.net', 'abc') # ===> RestClient::RequestTimeout
571
571
  ```
572
572
 
573
+ ### Curb multi requests
574
+
575
+ `Curl::Multi` matches each handle against stubs when it is added. An unstubbed
576
+ handle raises `WebMock::NetConnectNotAllowedError` from `multi.add` unless its
577
+ URL is allowed by WebMock's network settings. Stubbed handles complete when
578
+ `multi.perform` runs; allowed handles still run together on curb's native multi
579
+ loop. Both kinds of requests are recorded and invoke callbacks, including
580
+ `WebMock.after_request`. Callbacks registered with `real_requests_only: true`
581
+ receive only real transfers.
582
+
583
+ This also applies to `Curl::Multi.get`, `post`, `put` and `http`, and the `Curl.get`
584
+ and `Curl.post` convenience methods. Create the multi and easy handles after
585
+ WebMock is enabled, as with `Curl::Easy` requests.
586
+
573
587
  ### Multiple responses for repeated requests
574
588
 
575
589
  ```ruby
@@ -1487,6 +1501,7 @@ People who submitted patches and new features or suggested improvements. Many th
1487
1501
  * Hamza Tarar
1488
1502
  * John Gallagher
1489
1503
  * Yegor Bugayenko
1504
+ * Todd Fisher
1490
1505
 
1491
1506
  For a full list of contributors you can visit the
1492
1507
  [contributors](https://github.com/bblimke/webmock/contributors) page.
@@ -22,14 +22,20 @@ if defined?(Curl)
22
22
 
23
23
  OriginalCurlEasy = Curl::Easy unless const_defined?(:OriginalCurlEasy)
24
24
 
25
+ OriginalCurlMulti = Curl::Multi unless const_defined?(:OriginalCurlMulti)
26
+
25
27
  def self.enable!
26
28
  Curl.send(:remove_const, :Easy)
27
29
  Curl.send(:const_set, :Easy, Curl::WebMockCurlEasy)
30
+ Curl.send(:remove_const, :Multi)
31
+ Curl.send(:const_set, :Multi, Curl::WebMockCurlMulti)
28
32
  end
29
33
 
30
34
  def self.disable!
31
35
  Curl.send(:remove_const, :Easy)
32
36
  Curl.send(:const_set, :Easy, OriginalCurlEasy)
37
+ Curl.send(:remove_const, :Multi)
38
+ Curl.send(:const_set, :Multi, OriginalCurlMulti)
33
39
  end
34
40
 
35
41
  # Borrowed from Patron:
@@ -61,6 +67,82 @@ if defined?(Curl)
61
67
  end
62
68
 
63
69
  module Curl
70
+ class WebMockCurlMulti < Curl::Multi
71
+ # Intercept the native attachment boundary, retaining curb's public add,
72
+ # remove, request table and native event loop for allowed transfers.
73
+ def _add(easy)
74
+ # A handle of curb's own Curl::Easy class, such as a subclass defined
75
+ # before WebMock was loaded, one made while WebMock was disabled or a
76
+ # copy made with Curl::Easy#dup, makes its request without WebMock, as
77
+ # it always has. Easy#perform runs such handles through a multi too.
78
+ return super if !easy.is_a?(WebMockCurlEasy) || easy.webmock_performing_easy?
79
+
80
+ begin
81
+ signature, response = easy.webmock_request
82
+ rescue Exception # NetConnectNotAllowedError inherits directly from Exception.
83
+ # Older curb versions insert into requests before calling _add.
84
+ requests.delete(easy.object_id)
85
+ easy.webmock_restore_multi_url
86
+ raise
87
+ end
88
+ if response
89
+ easy.multi = self
90
+ webmock_pending[easy.object_id] = [easy, signature, response]
91
+ else
92
+ easy.webmock_record_multi_request(signature)
93
+ super
94
+ end
95
+ end
96
+
97
+ def _remove(easy)
98
+ if webmock_pending.delete(easy.object_id)
99
+ easy.multi = nil
100
+ return self
101
+ end
102
+ super
103
+ end
104
+
105
+ def perform(&block)
106
+ complete_webmock_requests
107
+ super do |multi|
108
+ begin
109
+ complete_webmock_requests
110
+ block.call(multi) if block
111
+ end until webmock_pending.empty?
112
+ end
113
+ end
114
+
115
+ private
116
+
117
+ def webmock_pending
118
+ @webmock_pending ||= {}
119
+ end
120
+
121
+ def complete_webmock_requests
122
+ until webmock_pending.empty?
123
+ easy, signature, response = webmock_pending.values.first
124
+ # Curb 1.5 takes a handle out of the multi on reset or close without
125
+ # calling _remove, so it no longer belongs to this multi.
126
+ attached = requests.key?(easy.object_id)
127
+ # Detach before callbacks so they can remove or requeue handles.
128
+ remove(easy)
129
+ webmock_pending.delete(easy.object_id)
130
+ next unless attached
131
+
132
+ if easy.webmock_follow_multi_redirect(signature, response)
133
+ add(easy)
134
+ else
135
+ begin
136
+ easy.multi = self
137
+ easy.webmock_complete_multi_request(signature, response)
138
+ ensure
139
+ easy.multi = nil if easy.multi == self && !requests.key?(easy.object_id)
140
+ end
141
+ end
142
+ end
143
+ end
144
+ end
145
+
64
146
  class WebMockCurlEasy < Curl::Easy
65
147
  # Curb's native PostField cannot be duplicated. Its public attributes
66
148
  # describe the field without running a content callback or opening a file.
@@ -81,7 +163,10 @@ if defined?(Curl)
81
163
  end
82
164
  private_constant :MultipartField
83
165
 
84
- def curb_or_webmock
166
+ def webmock_request
167
+ @webmock_method ||= :get
168
+ clear_webmock_response
169
+ webmock_clear_multi_request
85
170
  request_signature = build_request_signature
86
171
  recorded = signature_for_history(request_signature)
87
172
  if request_signature.method == :put && @put_data.respond_to?(:read)
@@ -90,13 +175,22 @@ if defined?(Curl)
90
175
 
91
176
  webmock_response = WebMock::StubRegistry.instance.response_for_request(
92
177
  request_signature, record: recorded)
178
+ unless webmock_response || WebMock.net_connect_allowed?(request_signature.uri)
179
+ raise WebMock::NetConnectNotAllowedError.new(request_signature)
180
+ end
181
+ [request_signature, webmock_response]
182
+ end
183
+
184
+ def curb_or_webmock
185
+ request_signature, webmock_response = webmock_request
93
186
  if webmock_response
94
187
  build_curb_response(webmock_response)
95
188
  WebMock::CallbackRegistry.invoke_callbacks(
96
189
  {lib: :curb}, request_signature, webmock_response)
97
190
  invoke_curb_callbacks
98
191
  true
99
- elsif WebMock.net_connect_allowed?(request_signature.uri)
192
+ else
193
+ @webmock_performing_easy = true
100
194
  res = yield
101
195
  if WebMock::CallbackRegistry.any_callbacks?
102
196
  webmock_response = build_webmock_response
@@ -105,9 +199,104 @@ if defined?(Curl)
105
199
  webmock_response)
106
200
  end
107
201
  res
202
+ end
203
+ ensure
204
+ @webmock_performing_easy = false
205
+ end
206
+
207
+ def webmock_performing_easy?
208
+ @webmock_performing_easy
209
+ end
210
+
211
+ def webmock_record_multi_request(signature)
212
+ @webmock_multi_request = signature
213
+ on_complete(&@on_complete)
214
+ end
215
+
216
+ def webmock_clear_multi_request
217
+ @webmock_multi_request = nil
218
+ end
219
+
220
+ %w[body header].each do |part|
221
+ define_method("on_#{part}") do |&block|
222
+ instance_variable_set("@on_#{part}", block)
223
+ if block
224
+ super() do |data|
225
+ if @webmock_multi_request
226
+ buffer = instance_variable_get("@webmock_#{part}") || +""
227
+ buffer << data
228
+ instance_variable_set("@webmock_#{part}", buffer)
229
+ end
230
+ block.call(data)
231
+ end
232
+ else
233
+ super(&block)
234
+ end
235
+ end
236
+ end
237
+
238
+ def on_complete(&block)
239
+ @on_complete = block
240
+ super do |easy|
241
+ signature = @webmock_multi_request
242
+ webmock_restore_multi_url
243
+ webmock_clear_multi_request
244
+ if signature && WebMock::CallbackRegistry.any_callbacks?
245
+ WebMock::CallbackRegistry.invoke_callbacks(
246
+ {lib: :curb, real_request: true}, signature, build_webmock_response)
247
+ end
248
+ block.call(easy) if block
249
+ end
250
+ end
251
+
252
+ def webmock_follow_multi_redirect(signature, response)
253
+ location = response.headers && response.headers['Location']
254
+ return false unless follow_location? && (300..399).include?(response.status[0]) && location
255
+ return false if response.should_timeout || response.exception
256
+
257
+ @webmock_multi_redirects ||= 0
258
+ limit = max_redirects || 50
259
+ if limit >= 0 && @webmock_multi_redirects >= limit
260
+ @webmock_last_result = 47 # CURLE_TOO_MANY_REDIRECTS
261
+ return false
262
+ end
263
+ WebMock::CallbackRegistry.invoke_callbacks({lib: :curb}, signature, response)
264
+ @webmock_multi_original_url ||= url
265
+ @webmock_multi_redirects += 1
266
+ self.url = WebMock::Util::URI.heuristic_parse(url).join(location).to_s
267
+ true
268
+ end
269
+
270
+ def webmock_restore_multi_url
271
+ return unless @webmock_multi_original_url
272
+ @last_effective_url = last_effective_url
273
+ self.url = @webmock_multi_original_url
274
+ @webmock_multi_original_url = @webmock_multi_redirects = nil
275
+ end
276
+
277
+ def webmock_complete_multi_request(signature, response)
278
+ if response.should_timeout
279
+ @body_str = ""
280
+ @header_str = ""
281
+ @response_code = 0
282
+ @webmock_last_result = 28 # CURLE_OPERATION_TIMEDOUT
108
283
  else
109
- raise WebMock::NetConnectNotAllowedError.new(request_signature)
284
+ build_curb_response(response, follow_redirects: false)
285
+ @webmock_last_result ||= 0
110
286
  end
287
+ webmock_restore_multi_url
288
+ WebMock::CallbackRegistry.invoke_callbacks({lib: :curb}, signature, response)
289
+ invoke_curb_callbacks(multi: true)
290
+ end
291
+
292
+ def last_result
293
+ @webmock_last_result || super
294
+ end
295
+
296
+ def clear_webmock_response
297
+ @body_str = @header_str = @response_code = @content_type = nil
298
+ @last_effective_url = @transfer_encoding = @webmock_last_result = nil
299
+ @webmock_body = @webmock_header = nil
111
300
  end
112
301
 
113
302
  def signature_for_history(signature)
@@ -138,7 +327,7 @@ if defined?(Curl)
138
327
  nil
139
328
  end
140
329
 
141
- if defined?( @on_debug )
330
+ if @on_debug
142
331
  @on_debug.call("Trying 127.0.0.1...\r\n", 0)
143
332
  @on_debug.call('Connected to ' + uri.hostname + "\r\n", 0)
144
333
  @debug_method = method.upcase
@@ -188,7 +377,7 @@ if defined?(Curl)
188
377
  end
189
378
  end
190
379
 
191
- def build_curb_response(webmock_response)
380
+ def build_curb_response(webmock_response, follow_redirects: true)
192
381
  raise Curl::Err::TimeoutError if webmock_response.should_timeout
193
382
  webmock_response.raise_error_if_any
194
383
 
@@ -197,7 +386,7 @@ if defined?(Curl)
197
386
 
198
387
  @header_str = "HTTP/1.1 #{webmock_response.status[0]} #{webmock_response.status[1]}\r\n".dup
199
388
 
200
- @on_debug.call(@header_str, 1) if defined?( @on_debug )
389
+ @on_debug.call(@header_str, 1) if @on_debug
201
390
 
202
391
  if webmock_response.headers
203
392
  # Each cookie gets a line of its own, as servers send them.
@@ -205,14 +394,14 @@ if defined?(Curl)
205
394
  values = k == "Set-Cookie" ? Array(v) : [v.is_a?(Array) ? v.join(", ") : v]
206
395
  values.map do |value|
207
396
  header = "#{k}: #{value}"
208
- @on_debug.call(header + "\r\n", 1) if defined?( @on_debug )
397
+ @on_debug.call(header + "\r\n", 1) if @on_debug
209
398
  header
210
399
  end
211
400
  end.join("\r\n")
212
- @on_debug.call("\r\n", 1) if defined?( @on_debug )
401
+ @on_debug.call("\r\n", 1) if @on_debug
213
402
 
214
403
  location = webmock_response.headers['Location']
215
- if self.follow_location? && location
404
+ if follow_redirects && self.follow_location? && location
216
405
  @last_effective_url = location
217
406
  webmock_follow_location(location)
218
407
  end
@@ -235,10 +424,10 @@ if defined?(Curl)
235
424
  self.url = first_url
236
425
  end
237
426
 
238
- def invoke_curb_callbacks
239
- @on_progress.call(0.0,1.0,0.0,1.0) if defined?( @on_progress )
240
- self.header_str.lines.each { |header_line| @on_header.call header_line } if defined?( @on_header )
241
- if defined?( @on_body )
427
+ def invoke_curb_callbacks(multi: false)
428
+ @on_progress.call(0.0,1.0,0.0,1.0) if @on_progress
429
+ self.header_str.lines.each { |header_line| @on_header.call header_line } if @on_header
430
+ if @on_body
242
431
  if chunked_response?
243
432
  self.body_str.each do |chunk|
244
433
  @on_body.call(chunk)
@@ -247,15 +436,24 @@ if defined?(Curl)
247
436
  @on_body.call(self.body_str)
248
437
  end
249
438
  end
250
- @on_complete.call(self) if defined?( @on_complete )
439
+ completed_code = response_code
440
+ completed_result = last_result if multi
441
+ @on_complete.call(self) if @on_complete
442
+
443
+ if multi && completed_result != 0
444
+ @on_failure.call(self, Curl::Easy.error(completed_result)) if @on_failure
445
+ return
446
+ end
251
447
 
252
- case response_code
448
+ case completed_code
253
449
  when 200..299
254
- @on_success.call(self) if defined?( @on_success )
450
+ @on_success.call(self) if @on_success
451
+ when 300..399
452
+ @on_redirect.call(self, Curl::Easy.error(0)) if multi && @on_redirect && max_redirects != 0
255
453
  when 400..499
256
- @on_missing.call(self, self.response_code) if defined?( @on_missing )
454
+ @on_missing.call(self, multi ? Curl::Easy.error(0) : self.response_code) if @on_missing
257
455
  when 500..599
258
- @on_failure.call(self, self.response_code) if defined?( @on_failure )
456
+ @on_failure.call(self, multi ? Curl::Easy.error(0) : self.response_code) if @on_failure
259
457
  end
260
458
  end
261
459
 
@@ -265,9 +463,9 @@ if defined?(Curl)
265
463
 
266
464
  def build_webmock_response
267
465
  status, headers =
268
- WebMock::HttpLibAdapters::CurbAdapter.parse_header_string(self.header_str)
466
+ WebMock::HttpLibAdapters::CurbAdapter.parse_header_string((@webmock_header || self.header_str).to_s)
269
467
 
270
- if defined?( @on_debug )
468
+ if @on_debug
271
469
  http_response = ["HTTP/1.0 #{@debug_method} #{@debug_path}"]
272
470
  headers.each do |name, value|
273
471
  http_response << "#{name}: #{value}"
@@ -279,7 +477,7 @@ if defined?(Curl)
279
477
 
280
478
  webmock_response = WebMock::Response.new
281
479
  webmock_response.status = [self.response_code, status]
282
- webmock_response.body = self.body_str
480
+ webmock_response.body = @webmock_body || self.body_str
283
481
  webmock_response.headers = headers
284
482
  webmock_response
285
483
  end
@@ -395,7 +593,7 @@ if defined?(Curl)
395
593
  @content_type ||= super
396
594
  end
397
595
 
398
- %w[ success failure missing header body complete progress debug ].each do |callback|
596
+ %w[ success failure missing redirect progress debug ].each do |callback|
399
597
  class_eval <<-METHOD, __FILE__, __LINE__
400
598
  def on_#{callback} &block
401
599
  @on_#{callback} = block
@@ -410,12 +608,14 @@ if defined?(Curl)
410
608
 
411
609
  def reset
412
610
  @put_data = nil
611
+ clear_webmock_response
612
+ webmock_clear_multi_request
413
613
  reset_webmock_method
414
- instance_variable_set(:@body_str, nil)
415
- instance_variable_set(:@content_type, nil)
416
- instance_variable_set(:@header_str, nil)
417
- instance_variable_set(:@last_effective_url, nil)
418
- instance_variable_set(:@response_code, nil)
614
+ @webmock_multi_original_url = @webmock_multi_redirects = nil
615
+ # Curb's reset drops every callback, so a stubbed request, or a real one
616
+ # WebMock records, doesn't run the ones set before it either.
617
+ @on_success = @on_failure = @on_missing = @on_redirect = @on_complete = nil
618
+ @on_body = @on_header = @on_progress = @on_debug = nil
419
619
  super
420
620
  end
421
621
  end
@@ -7,6 +7,9 @@ module HTTP
7
7
 
8
8
  webmock_response.status = [status.to_i, reason]
9
9
 
10
+ # The caller gets the body before it is read, to see what it reads from.
11
+ body = self.body
12
+ yield body if block_given?
10
13
  webmock_response.body = body.to_s
11
14
  # This call is used to reset the body of the response to enable it to be streamed if necessary.
12
15
  # The `body.to_s` call above reads the body, which allows WebMock to trigger any registered callbacks.
@@ -87,10 +87,68 @@ module HTTP
87
87
  def perform
88
88
  return unless ::WebMock.net_connect_allowed?(request_signature.uri)
89
89
  response = @perform.call
90
- invoke_callbacks(response.to_webmock, real_request: true)
90
+ invoke_callbacks(webmock_response_for(response), real_request: true)
91
91
  response
92
92
  end
93
93
 
94
+ # The response that callbacks get for a real one. HTTP.rb's auto_inflate
95
+ # feature inflates the body and keeps the headers of the compressed one.
96
+ # WebMock replays a stub through the features, so a stub returning these
97
+ # headers with the inflated body, such as a VCR cassette, would be
98
+ # inflated again. Callbacks get headers that describe the inflated body.
99
+ def webmock_response_for(response)
100
+ return response.to_webmock unless ::WebMock::CallbackRegistry.any_callbacks? && auto_inflate?
101
+
102
+ inflated = false
103
+ webmock_response = response.to_webmock { |body| inflated = reads_from_inflater?(body) }
104
+ describe_inflated_body(webmock_response) if inflated
105
+ webmock_response
106
+ end
107
+
108
+ # Whether the client inflates with HTTP.rb's own feature. A subclass may
109
+ # do anything with the headers and the body, so its responses are left
110
+ # as they are.
111
+ def auto_inflate?
112
+ return false unless defined?(::HTTP::Features::AutoInflate)
113
+
114
+ features = @options.features.values.grep(::HTTP::Features::AutoInflate)
115
+ features.any? && features.all? { |feature| exactly?(::HTTP::Features::AutoInflate, feature) }
116
+ end
117
+
118
+ # Only evidence counts, so that callbacks never get other headers for a
119
+ # body that is still compressed. HTTP.rb shows inflation only in the
120
+ # stream the body reads from, which its logging feature may wrap. With
121
+ # HTTP.rb 6's caching feature the body is a String, which shows nothing.
122
+ # A subclass may do anything with what it reads, so it shows nothing too.
123
+ def reads_from_inflater?(body)
124
+ return false unless defined?(::HTTP::Response::Inflater) && exactly?(::HTTP::Response::Body, body)
125
+
126
+ stream = body.instance_variable_get(:@stream)
127
+ if defined?(::HTTP::Features::Logging::BodyLogger) && exactly?(::HTTP::Features::Logging::BodyLogger, stream)
128
+ stream = stream.instance_variable_get(:@stream)
129
+ end
130
+ exactly?(::HTTP::Response::Inflater, stream)
131
+ end
132
+
133
+ CLASS_OF = ::Kernel.instance_method(:class)
134
+ private_constant :CLASS_OF
135
+
136
+ # Asks Ruby and not the object, which may say anything of itself.
137
+ def exactly?(klass, object)
138
+ klass.equal?(CLASS_OF.bind(object).call)
139
+ end
140
+
141
+ # No Content-Encoding, as for a body Net::HTTP inflates, and its own
142
+ # length. A response with an empty body, such as one to HEAD, keeps its
143
+ # headers: they tell of a body that isn't there to be inflated again.
144
+ def describe_inflated_body(webmock_response)
145
+ return if webmock_response.body.empty?
146
+
147
+ headers = webmock_response.headers
148
+ headers.delete("Content-Encoding")
149
+ headers["Content-Length"] = webmock_response.body.bytesize.to_s if headers.key?("Content-Length")
150
+ end
151
+
94
152
  def halt
95
153
  raise ::WebMock::NetConnectNotAllowedError.new request_signature
96
154
  end
@@ -54,11 +54,14 @@ module WebMock
54
54
  return false unless expected.is_a?(String) && actual.is_a?(String) && expected != actual
55
55
  return false unless request_signature.json_headers?
56
56
 
57
- expected_json = parse_json(expected)
57
+ # The advice is to declare the body as JSON.parse(json_string), so
58
+ # the stub's string must parse with JSON.parse itself. The request
59
+ # body is read as WebMock reads it for matching.
60
+ expected_json = parse_json { ::JSON.parse(expected) }
58
61
  return false unless expected_json.is_a?(Hash) || expected_json.is_a?(Array)
59
62
 
60
63
  # eql? compares nested values strictly, so 1 and 1.0 are different.
61
- expected_json.eql?(parse_json(actual))
64
+ expected_json.eql?(parse_json { WebMock::Util::Parsers::JSON.parse(actual) })
62
65
  end
63
66
 
64
67
  def self.matches_except_body?(request_pattern, request_signature)
@@ -67,9 +70,9 @@ module WebMock
67
70
  (request_pattern.headers_pattern.nil? || request_pattern.headers_pattern.matches?(request_signature.headers))
68
71
  end
69
72
 
70
- def self.parse_json(string)
71
- ::JSON.parse(string)
72
- rescue ::JSON::JSONError, EncodingError
73
+ def self.parse_json
74
+ yield
75
+ rescue ::JSON::JSONError, EncodingError, WebMock::Util::Parsers::ParseError
73
76
  nil
74
77
  end
75
78
  private_class_method :parts_of, :body_differs_only_in_formatting?, :matches_except_body?, :parse_json
@@ -1,7 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "hashdiff"
4
- require "json"
5
4
 
6
5
  module WebMock
7
6
  class RequestBodyDiff
@@ -40,14 +39,15 @@ module WebMock
40
39
  request_stub_body.is_a?(Hash) || request_stub_parseable_json?
41
40
  end
42
41
 
42
+ # Bodies are read as WebMock reads them for matching.
43
43
  def request_signature_body_hash
44
- JSON.parse(request_signature.body)
44
+ WebMock::Util::Parsers::JSON.parse(request_signature.body)
45
45
  end
46
46
 
47
47
  def request_stub_body_hash
48
48
  return request_stub_body if request_stub_body.is_a?(Hash)
49
49
 
50
- JSON.parse(request_stub_body)
50
+ WebMock::Util::Parsers::JSON.parse(request_stub_body)
51
51
  end
52
52
 
53
53
  def request_stub_body
@@ -67,9 +67,9 @@ module WebMock
67
67
  def parseable_json?(body_pattern)
68
68
  return false unless body_pattern.is_a?(String)
69
69
 
70
- JSON.parse(body_pattern)
70
+ WebMock::Util::Parsers::JSON.parse(body_pattern)
71
71
  true
72
- rescue JSON::ParserError
72
+ rescue WebMock::Util::Parsers::ParseError
73
73
  false
74
74
  end
75
75
  end
@@ -437,11 +437,11 @@ module WebMock
437
437
 
438
438
  if (@pattern).is_a?(Hash)
439
439
  return true if @pattern.empty?
440
- matching_body_hashes?(body_as_hash(body, content_type), @pattern, content_type)
440
+ matching_parsed_body?(body, content_type) { |parsed| matching_body_hashes?(parsed, @pattern, content_type) }
441
441
  elsif (@pattern).is_a?(Array)
442
- matching_body_array?(body_as_hash(body, content_type), @pattern, content_type)
442
+ matching_parsed_body?(body, content_type) { |parsed| matching_body_array?(parsed, @pattern, content_type) }
443
443
  elsif (@pattern).is_a?(WebMock::Matchers::HashArgumentMatcher)
444
- @pattern == body_as_hash(body, content_type)
444
+ matching_parsed_body?(body, content_type) { |parsed| @pattern == parsed }
445
445
  else
446
446
  empty_string?(@pattern) && empty_string?(body) ||
447
447
  @pattern == body ||
@@ -455,6 +455,68 @@ module WebMock
455
455
 
456
456
  private
457
457
 
458
+ WARNED_LEGACY_JSON = {}
459
+ private_constant :WARNED_LEGACY_JSON
460
+
461
+ # WebMock 3.40.0 and earlier read JSON bodies with a YAML based parser,
462
+ # which reads some bodies that aren't valid JSON and some values
463
+ # differently from the json gem. When the pattern doesn't match the json
464
+ # gem's reading and the old parser reads the body differently, the old
465
+ # reading decides, as in 3.40.0, with a warning once for each pattern
466
+ # when it matches.
467
+ def matching_parsed_body?(body, content_type)
468
+ parsed = body_as_hash(body, content_type)
469
+ begin
470
+ return true if yield(parsed)
471
+ rescue SignalException, SystemExit
472
+ raise
473
+ rescue Exception => error
474
+ # A value in the pattern, such as a lambda or an RSpec expectation,
475
+ # may expect what the old parser reads, so the old reading decides.
476
+ end
477
+
478
+ json = body && WebMock::Util::ContentType.body_format(content_type) == :json
479
+ legacy = legacy_json(body) if json
480
+ if !json || legacy.eql?(parsed)
481
+ raise error if error
482
+ return false
483
+ end
484
+
485
+ # As in 3.40.0, including an error the pattern raises for it.
486
+ matched = yield(legacy)
487
+ warn_legacy_json(body, parsed) if matched
488
+ matched
489
+ end
490
+
491
+ def legacy_json(body)
492
+ WebMock::Util::Parsers::JSON.parse_legacy(body)
493
+ rescue WebMock::Util::Parsers::ParseError
494
+ nil
495
+ end
496
+
497
+ def warn_legacy_json(body, parsed)
498
+ pattern = to_s
499
+ # Without object addresses, so equal patterns, such as ones with a
500
+ # lambda built in each example, warn once.
501
+ key = pattern.gsub(/#<([\w:]+?):0x\h+/, '#<\\1').hash
502
+ return if WARNED_LEGACY_JSON[key]
503
+ WARNED_LEGACY_JSON[key] = true
504
+ advice =
505
+ if parsed.nil?
506
+ "Send valid JSON, for example from to_json, and write the pattern for what JSON.parse returns."
507
+ else
508
+ "Write the pattern for what JSON.parse returns: #{shorten(parsed.inspect)}."
509
+ end
510
+ WebMock::Deprecation.warning(
511
+ "the body pattern #{shorten(pattern)} matched the request body #{shorten(body).inspect} " \
512
+ "only as WebMock's old JSON parser reads it. WebMock 4.0 drops that parser, so it won't match. #{advice}"
513
+ )
514
+ end
515
+
516
+ def shorten(text)
517
+ text.length > 100 ? "#{text[0, 100]}..." : text
518
+ end
519
+
458
520
  def body_as_hash(body, content_type)
459
521
  return if body.nil?
460
522
 
@@ -135,7 +135,7 @@ module WebMock
135
135
  rack_hint = code.is_a?(Symbol) ? ", or Rack::Utils.status_code(#{code.inspect}) in a Rack app" : ""
136
136
  WebMock::Deprecation.warning(
137
137
  "status #{key} is not an HTTP status code, so HTTP clients get a broken status from it. " \
138
- "Use a number such as 200#{rack_hint}. WebMock 4.0 will raise ArgumentError for it."
138
+ "Use a number such as 200#{rack_hint}. A future major version of WebMock will raise ArgumentError for it."
139
139
  )
140
140
  end
141
141
 
@@ -1,25 +1,56 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # This is a copy of https://github.com/jnunemaker/crack/blob/master/lib/crack/json.rb
3
+ # parse_legacy is a copy of https://github.com/jnunemaker/crack/blob/master/lib/crack/json.rb
4
4
  # with date parsing removed
5
5
  # Copyright (c) 2004-2008 David Heinemeier Hansson
6
6
  # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
7
7
  # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
8
  # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
9
9
 
10
+ require "json"
10
11
  require_relative "parse_error"
11
12
 
12
13
  module WebMock
13
14
  module Util
14
15
  module Parsers
15
16
  class JSON
17
+ # Deep enough for any real body, and shallow enough for every json
18
+ # gem version to parse in a thread's stack.
19
+ MAX_NESTING = 1000
20
+
16
21
  def self.parse(json)
22
+ # JSON texts may start with a byte order mark, which parsers may ignore.
23
+ json = to_utf8(json).delete_prefix("\uFEFF")
24
+ ::JSON.parse(json, allow_duplicate_key: true, max_nesting: MAX_NESTING)
25
+ rescue ::JSON::JSONError, EncodingError => e
26
+ raise ParseError, "Invalid JSON string: #{e.message}"
27
+ end
28
+
29
+ # The YAML based parser WebMock used up to 3.40.0. It reads some
30
+ # bodies that aren't valid JSON, such as {a: 1}, and some values
31
+ # differently from the json gem, such as 1e+20 as a String.
32
+ # WebMock 4.0 drops it.
33
+ def self.parse_legacy(json)
17
34
  yaml = unescape(convert_json_to_yaml(json))
18
35
  YAML.load(yaml)
19
- rescue ArgumentError, Psych::SyntaxError => e
36
+ rescue ArgumentError, EncodingError, Psych::Exception => e
20
37
  raise ParseError, "Invalid JSON string: #{yaml}, Error: #{e.inspect}"
21
38
  end
22
39
 
40
+ # The json gem reads bytes that aren't valid in their encoding, so
41
+ # such a body, for example a binary upload, is rejected here. A
42
+ # binary or US-ASCII string, as read from a socket or from a file in
43
+ # a C locale, is taken as UTF-8.
44
+ def self.to_utf8(json)
45
+ if json.encoding == Encoding::BINARY || json.encoding == Encoding::US_ASCII
46
+ json = json.dup.force_encoding(Encoding::UTF_8)
47
+ end
48
+ raise ParseError, "Invalid JSON string: it isn't valid #{json.encoding}" unless json.valid_encoding?
49
+
50
+ json.encoding == Encoding::UTF_8 ? json : json.encode(Encoding::UTF_8)
51
+ end
52
+ private_class_method :to_utf8
53
+
23
54
  protected
24
55
 
25
56
  def self.unescape(str)
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module WebMock
4
- VERSION = '3.39.0' unless defined?(::WebMock::VERSION)
4
+ VERSION = '3.42.0' unless defined?(::WebMock::VERSION)
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: webmock
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.39.0
4
+ version: 3.42.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Bartosz Blimke
@@ -363,9 +363,9 @@ licenses:
363
363
  - MIT
364
364
  metadata:
365
365
  bug_tracker_uri: https://github.com/bblimke/webmock/issues
366
- changelog_uri: https://github.com/bblimke/webmock/blob/v3.39.0/CHANGELOG.md
367
- documentation_uri: https://www.rubydoc.info/gems/webmock/3.39.0
368
- source_code_uri: https://github.com/bblimke/webmock/tree/v3.39.0
366
+ changelog_uri: https://github.com/bblimke/webmock/blob/v3.42.0/CHANGELOG.md
367
+ documentation_uri: https://www.rubydoc.info/gems/webmock/3.42.0
368
+ source_code_uri: https://github.com/bblimke/webmock/tree/v3.42.0
369
369
  wiki_uri: https://github.com/bblimke/webmock/wiki
370
370
  rdoc_options: []
371
371
  require_paths: