webmock 3.35.0 → 3.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: acb33845b6ff4fbb890271cbed06608a6095c823ce57a9be5ca2121090ff117f
4
- data.tar.gz: f3bf9d36ba38af4e134016cf4d941589d271e75cb06d2dc314781d8f1ffe341e
3
+ metadata.gz: dcdb50457447f4b9234934f5211c2ccd45a55e11c164a0faaeb6ba8a47d6949a
4
+ data.tar.gz: 28bdd8fac8769c6d3b7f2f63f6070f60f9c602f090ae14f9b957ddbf5bb4f93f
5
5
  SHA512:
6
- metadata.gz: e99abdb908ce47c4bba164cfa574a2b94f54e042f7bd55f1ba4f64bf88b43f3c721c7a7e39f8870c7f0d3ecdc139ee79d7c14de0c201ca0937de8355ded288c7
7
- data.tar.gz: 9a75e24decc112843f7e89ee47e68fbf312bec7d23590d0b17c1661295d5b3c2b690cc4800757e1e2c2d62b58990ddd217f492c6e095209c282ed6107d732367
6
+ metadata.gz: 90780a4cf7639e3a09132f59c2479d042eb2ee3c769835b2957d0a508c666a9c0c039884459bdd51aefdaa3f6efae8d3caad58ee80efcf41d8af0e202b04e1ad
7
+ data.tar.gz: 4fdddbbae16604e0b21b567e4e69038567c1eefb9e357b03998583379b6d7393e04ea68d490edb3f7175bb5082fcc187d8069402521bdc8072f956018a612ba8
data/CHANGELOG.md CHANGED
@@ -1,5 +1,83 @@
1
1
  # Changelog
2
2
 
3
+ # 3.37.0
4
+
5
+ * Add `executed_requests` to inspect the requests made (#1069)
6
+
7
+ `WebMock.executed_requests` returns every request made since the last reset, in order, including repeated ones. You can assert on each one's body or headers, for example `JSON.parse(WebMock.executed_requests.last.body)`.
8
+
9
+ Previously, this needed WebMock internals such as `WebMock::RequestRegistry.instance.requested_signatures.hash.keys`, which list each distinct request only once.
10
+
11
+ Thanks to [John Gallagher](https://github.com/johngallagher) for the idea, which we started pairing on at EuRuKo 2024 in Sarajevo.
12
+
13
+ * Fix stub matching for consecutive Curb PUT requests on the same handle
14
+
15
+ After `curl.http_put("first")`, WebMock could match a subsequent `curl.http_put` against the previous body. It now matches the second request with an empty body.
16
+
17
+ * Run HTTPClient request filters once per attempt on real requests
18
+
19
+ Previously, WebMock could run a filter twice, so a filter that generated a request ID could send a different ID to the server than the one WebMock recorded.
20
+
21
+ * Fix async HTTPClient requests hanging when an `after_request` callback is registered
22
+
23
+ Previously, with real connections allowed, WebMock read the response body for the callback from the same stream as your code, so reading part of a `get_async` response before calling `join` could hang.
24
+
25
+ * Match file and stream uploads by their content
26
+
27
+ Previously, a body pattern such as `with(body: "abc")` never matched a Curb, Patron or em-http-request request that uploaded a file or stream, because WebMock compared the pattern with the file object. Stubs now compare it with the uploaded bytes for Curb and Patron, and `assert_requested` does so for all three.
28
+
29
+ Blocks given to `stub_request(...).with` still receive the original file or stream.
30
+
31
+ * Count em-http-request requests blocked by `disable_net_connect!`
32
+
33
+ Previously, WebMock did not record them, so `assert_requested` did not count them. They are now counted, as with other HTTP clients.
34
+
35
+ # 3.36.0
36
+
37
+ * Fix matching of indexed arrays nested inside arrays of hashes (#1144)
38
+
39
+ Previously, WebMock read indexed arrays nested inside an array of hashes, such as `a[][b][0][c]=1`, as hashes with `"0"`, `"1"` keys. WebMock writes that form itself, so `with(query: {"a" => [{"b" => [{"c" => "1"}]}]})` with a regexp URI did not match `?a[][b][][c]=1`, and a Typhoeus request with that hash as its body did not match a stub with the same hash.
40
+
41
+ If a stub uses the old shape, such as `{"a" => [{"b" => {"0" => {"c" => "1"}}}]}`, for example one copied from WebMock's suggested stub, use arrays instead.
42
+
43
+ Thanks to [Hamza Tarar](https://github.com/ihamzatarar)
44
+
45
+ * Fix matching of arrays of hashes that repeat a nested key
46
+
47
+ Previously, WebMock put a nested key repeated under `[]` into the first hash of the array, so `items[][address][city]=X&items[][address][city]=Y` was read as one item with the city `Y`. A stub listing both items did not match, and a stub for `X` and `Y` also matched a request for `Z` and `Y`. Rails and Faraday encode arrays of nested hashes this way.
48
+
49
+ Such keys now go into a new hash, as in Rack. If a stub lists such an array as one item, for example one copied from WebMock's suggested stub, list every item.
50
+
51
+ Queries that mix a value and nested keys under the same name, such as `a[][b]=1&a[][b][c]=2` or `a[c]=1&a[c][]=2`, no longer raise `IndexError` or join the values into one string.
52
+
53
+ * Apply Net::HTTP `response_body_encoding` to stubbed response bodies (#1138)
54
+
55
+ Previously, stubbed Net::HTTP responses ignored `Net::HTTP#response_body_encoding=` and `Net::HTTPResponse#body_encoding=`. A body stubbed as binary, for example from a raw response file, stayed `ASCII-8BIT` even with `http.response_body_encoding = true` and a `Content-Type` of `text/plain; charset=utf-8`.
56
+
57
+ Stubbed bodies now get the encoding real responses get: with `true`, the charset from the `Content-Type` header or an HTML `<meta>` tag, and otherwise the encoding the setting names. Without the setting, a body keeps the encoding it was stubbed with.
58
+
59
+ Thanks to [Yang Bai](https://github.com/ybai08)
60
+
61
+ * Give each stubbed Net::HTTP response its own copy of the body
62
+
63
+ Previously, a stubbed Net::HTTP response returned the stubbed body string itself. A body stubbed with a frozen string, such as a literal in a file with `# frozen_string_literal: true`, made `response.body.force_encoding("UTF-8")` raise `FrozenError`, which a real response never does. Changing the body in place, for example with `response.body << "!"`, changed it for later requests to the same stub too.
64
+
65
+ * Keep the size of async-http responses to HEAD requests (#1143)
66
+
67
+ async-http gives the size of a response to a HEAD request as `response.body.length`, not as a header. Previously, a response stubbed with `stub_request(:head, url).to_return(headers: {"Content-Length" => "42"})` ignored the `Content-Length`: its body was `nil` over HTTP/1 and had a length of 0 over HTTP/2. A real response lost its size, with a `nil` body, when a `WebMock.after_request` callback was registered, for example while VCR was recording, and the recorded response had no `Content-Length`.
68
+
69
+ A stubbed response now takes its size from the stubbed `Content-Length`, or from the stubbed body without one, as before. A real response keeps its size when a callback is registered, and the recorded response has it as its `Content-Length`.
70
+
71
+ Thanks to [Andrew K. Fader](https://github.com/andrewfader)
72
+
73
+ * Keep the URI query of HTTPClient requests that pass a query argument (#1145)
74
+
75
+ Previously, WebMock dropped the query in the URI when an HTTPClient request also passed the query argument. `HTTPClient.new.get("http://example.com/?a=1", {"b" => "2"})` requests `/?a=1&b=2`, but WebMock saw `/?b=2`, and with `{}` as the query argument it saw no query at all. A stub or `a_request` expectation could match a URL that was never requested.
76
+
77
+ If a stub or expectation for such a request leaves out the query in the URI, add it, for example `stub_request(:get, "http://example.com/?a=1&b=2")`. Record VCR cassettes with such requests again.
78
+
79
+ Thanks to [AmeenKhan12345](https://github.com/AmeenKhan12345)
80
+
3
81
  # 3.35.0
4
82
 
5
83
  * Fix `get_file` with Patron 1.1 (#1147)
data/README.md CHANGED
@@ -802,6 +802,37 @@ expect(stub).to have_been_requested.once.with(body: {"a" => [4, 5, 6]})
802
802
 
803
803
  Options and a block given to `with` take the same form as in `stub_request(...).with`. The expectation then counts only the requests that match both the stub and those conditions. The stub itself does not change.
804
804
 
805
+ ### Inspecting the requests made
806
+
807
+ `WebMock.executed_requests` lists every request made since the last `WebMock.reset!` or `WebMock.reset_executed_requests!`, in the order they were made, including repeats. It lets you check what your code sent with plain Ruby.
808
+
809
+ ```ruby
810
+ stub_request(:post, "www.example.com/orders")
811
+
812
+ Net::HTTP.post(URI("http://www.example.com/orders"), '{"name":"John"}', "Content-Type" => "application/json")
813
+
814
+ request = WebMock.executed_requests.last
815
+ request.method # ===> :post
816
+ request.uri.path # ===> "/orders"
817
+ request.headers["Content-Type"] # ===> "application/json"
818
+ JSON.parse(request.body) # ===> {"name" => "John"}
819
+ ```
820
+
821
+ In RSpec, Minitest and Test::Unit you can call it as `executed_requests`, and it starts empty in every test. For example, to check which requests were made and in what order:
822
+
823
+ ```ruby
824
+ expect(executed_requests.map { |request| request.uri.path }).to eq(["/orders", "/orders/1/confirm"])
825
+ ```
826
+
827
+ A few things to know:
828
+
829
+ * The URI is normalized, with the port added and the query sorted, so compare its parts, such as `uri.host` or `uri.query_values`, rather than `uri.to_s`.
830
+ * The requests are copies, so changing them doesn't change what WebMock recorded.
831
+ * When a request uploads a file or stream, its body is the uploaded bytes. WebMock reads them without moving the stream, from regular files, tempfiles, `StringIO` and gzip readers over those. Other streams, such as pipes, are listed with the stream's `to_s`.
832
+ * Multipart fields of a Curb PUT are listed with their `name`, `content`, `content_type`, `local_file` and `remote_file`. Files in a Typhoeus body given as an array are listed as `Pathname` objects.
833
+ * Blocks given to `stub_request(...).with` and `after_request` callbacks still receive the original file or stream, and `assert_requested(stub)` counts the requests that stub matched.
834
+ * Depending on the HTTP client, requests that WebMock blocked because real connections are disabled may be listed too.
835
+
805
836
  ## Clearing stubs and request history
806
837
 
807
838
  If you want to reset all current stubs and history of requests use `WebMock.reset!`
@@ -820,7 +851,7 @@ assert_not_requested :get, "www.example.com" # ===> Success
820
851
 
821
852
  ## Clearing request counters
822
853
 
823
- If you want to reset **only** the counters of the executed requests use `WebMock.reset_executed_requests!`
854
+ If you want to reset **only** the counters and the list of executed requests, and keep the stubs, use `WebMock.reset_executed_requests!`
824
855
 
825
856
  ```ruby
826
857
  stub = stub_request(:get, "www.example.com")
@@ -1283,6 +1314,34 @@ People who submitted patches and new features or suggested improvements. Many th
1283
1314
  * Erik Berlin
1284
1315
  * Josch Bockler
1285
1316
  * Leslie Hoare
1317
+ * Chris Gunther
1318
+ * hikmetba-bit
1319
+ * Daniel Pepper
1320
+ * Christian Bruckmayer
1321
+ * Chris
1322
+ * Jan Graichen
1323
+ * Olivier Brisse
1324
+ * Henry Blyth
1325
+ * Sébastien S.
1326
+ * Euisan Kim
1327
+ * Alex
1328
+ * Andy Williams
1329
+ * Tim Mertens
1330
+ * Mike Taylor
1331
+ * James Rodovich
1332
+ * Michael Spiz
1333
+ * Tom Brammar
1334
+ * Benoit Tigeot
1335
+ * nightpool
1336
+ * Andrii Furmanets
1337
+ * thoran
1338
+ * Julik Tarkhanov
1339
+ * Bob Aman
1340
+ * AmeenKhan12345
1341
+ * Andrew K. Fader
1342
+ * Yang Bai
1343
+ * Hamza Tarar
1344
+ * John Gallagher
1286
1345
 
1287
1346
  For a full list of contributors you can visit the
1288
1347
  [contributors](https://github.com/bblimke/webmock/contributors) page.
data/lib/webmock/api.rb CHANGED
@@ -72,6 +72,10 @@ module WebMock
72
72
  WebMock::RequestRegistry.instance.reset!
73
73
  end
74
74
 
75
+ def executed_requests
76
+ WebMock::RequestRegistry.instance.executed_requests
77
+ end
78
+
75
79
  private
76
80
 
77
81
  def convert_uri_method_and_options_to_request_and_options(method, uri, options, &block)
@@ -66,7 +66,7 @@ if defined?(Async::HTTP)
66
66
  request.authority ||= self.authority
67
67
 
68
68
  request_signature = build_request_signature(request)
69
- WebMock::RequestRegistry.instance.requested_signatures.put(request_signature)
69
+ WebMock::RequestRegistry.instance.put(request_signature)
70
70
  webmock_response = WebMock::StubRegistry.instance.response_for_request(request_signature)
71
71
  net_connect_allowed = WebMock.net_connect_allowed?(request_signature.uri)
72
72
  real_request = false
@@ -129,19 +129,32 @@ if defined?(Async::HTTP)
129
129
  end
130
130
 
131
131
  def build_webmock_response(response)
132
- body = response.read
133
- response.body = ::Protocol::HTTP::Body::Buffered.wrap(body)
132
+ # async-http takes the Content-Length out of the headers of a response
133
+ # to a HEAD request and gives it a body that only holds that size.
134
+ # Keep that body, and record the size as the Content-Length sent.
135
+ if head_body?(response.body)
136
+ content_length = response.body.length
137
+ else
138
+ body = response.read
139
+ response.body = ::Protocol::HTTP::Body::Buffered.wrap(body)
140
+ end
134
141
 
135
142
  webmock_response = WebMock::Response.new
136
143
  webmock_response.status = [
137
144
  response.status,
138
145
  WebMock::HttpLibAdapters::AsyncHttpClientAdapter.status_descriptions[response.status]
139
146
  ]
140
- webmock_response.headers = build_webmock_response_headers(response)
147
+ headers = build_webmock_response_headers(response)
148
+ headers['content-length'] = [content_length.to_s] if content_length
149
+ webmock_response.headers = headers
141
150
  webmock_response.body = body
142
151
  webmock_response
143
152
  end
144
153
 
154
+ def head_body?(body)
155
+ defined?(::Protocol::HTTP::Body::Head) && body.is_a?(::Protocol::HTTP::Body::Head)
156
+ end
157
+
145
158
  def build_webmock_response_headers(response)
146
159
  response.headers.each.each_with_object({}) do |(k, v), o|
147
160
  o[k] ||= []
@@ -215,7 +228,8 @@ if defined?(Async::HTTP)
215
228
  def call(request)
216
229
  request.read
217
230
  webmock_response = get_webmock_response(request)
218
- build_response(webmock_response)
231
+ body = request.head? ? head_body(webmock_response) : webmock_response.body
232
+ build_response(webmock_response, body)
219
233
  end
220
234
 
221
235
  def add_webmock_response(request, webmock_response)
@@ -235,7 +249,7 @@ if defined?(Async::HTTP)
235
249
  @webmock_responses ||= {}
236
250
  end
237
251
 
238
- def build_response(webmock_response)
252
+ def build_response(webmock_response, body)
239
253
  headers = (webmock_response.headers || {}).each_with_object([]) do |(k, value), o|
240
254
  next if FRAMING_HEADERS.include?(k.downcase)
241
255
 
@@ -247,9 +261,22 @@ if defined?(Async::HTTP)
247
261
  ::Protocol::HTTP::Response[
248
262
  webmock_response.status[0],
249
263
  headers,
250
- webmock_response.body
264
+ body
251
265
  ]
252
266
  end
267
+
268
+ # async-http answers a HEAD request with the size of the body as the
269
+ # Content-Length, and leaves the body out. A stub's own Content-Length
270
+ # is the size of the body it stands for, so it takes precedence.
271
+ def head_body(webmock_response)
272
+ content_length = Array(webmock_response.headers&.[]('Content-Length')).first.to_s
273
+
274
+ if content_length.match?(/\A\d+\z/) && defined?(::Protocol::HTTP::Body::Head)
275
+ ::Protocol::HTTP::Body::Head.new(content_length.to_i)
276
+ else
277
+ webmock_response.body
278
+ end
279
+ end
253
280
  end
254
281
  end
255
282
  end
@@ -62,11 +62,35 @@ if defined?(Curl)
62
62
 
63
63
  module Curl
64
64
  class WebMockCurlEasy < Curl::Easy
65
+ # Curb's native PostField cannot be duplicated. Its public attributes
66
+ # describe the field without running a content callback or opening a file.
67
+ MultipartField = Struct.new(:name, :content, :content_type, :local_file, :remote_file) do
68
+ def self.from(field)
69
+ new(*members.map { |attribute| field.public_send(attribute)&.to_s })
70
+ end
71
+
72
+ def to_s
73
+ return super unless content && !local_file && !remote_file
74
+ Curl::PostField.content(name, content).to_s
75
+ end
76
+
77
+ def initialize_copy(original)
78
+ super
79
+ each_pair { |attribute, value| self[attribute] = value.dup }
80
+ end
81
+ end
82
+ private_constant :MultipartField
83
+
65
84
  def curb_or_webmock
66
85
  request_signature = build_request_signature
67
- WebMock::RequestRegistry.instance.requested_signatures.put(request_signature)
86
+ recorded = signature_for_history(request_signature)
87
+ if request_signature.method == :put && @put_data.respond_to?(:read)
88
+ request_signature = request_signature.with_upload_body(@put_data)
89
+ end
68
90
 
69
- if webmock_response = WebMock::StubRegistry.instance.response_for_request(request_signature)
91
+ webmock_response = WebMock::StubRegistry.instance.response_for_request(
92
+ request_signature, record: recorded)
93
+ if webmock_response
70
94
  build_curb_response(webmock_response)
71
95
  WebMock::CallbackRegistry.invoke_callbacks(
72
96
  {lib: :curb}, request_signature, webmock_response)
@@ -86,6 +110,13 @@ if defined?(Curl)
86
110
  end
87
111
  end
88
112
 
113
+ def signature_for_history(signature)
114
+ body = signature.body
115
+ return signature unless body.is_a?(Curl::PostField) || (body.is_a?(Array) && multipart_form_post?)
116
+ signature.with_body_values { |field| MultipartField.from(field) }
117
+ end
118
+ private :signature_for_history
119
+
89
120
  def build_request_signature
90
121
  method = @webmock_method.to_s.downcase.to_sym
91
122
 
@@ -98,7 +129,11 @@ if defined?(Curl)
98
129
  when :post, :patch
99
130
  self.post_body || @post_body
100
131
  when :put
101
- @put_data
132
+ if @put_data.respond_to?(:read)
133
+ WebMock::Util::UploadBody.read(@put_data, headers)
134
+ else
135
+ @put_data
136
+ end
102
137
  else
103
138
  nil
104
139
  end
@@ -270,10 +305,19 @@ if defined?(Curl)
270
305
  end
271
306
  end
272
307
 
273
- def http_put data = nil
308
+ def http_put(data = nil)
309
+ # put_data= can supply the upcoming request's body until perform resets the method.
310
+ data = @put_data if data.nil? && @webmock_method == :put
274
311
  @webmock_method = :put
275
- @put_data = data if data
276
- super
312
+ @put_data = data
313
+ return super('') if data.nil?
314
+ return super(data) if data.is_a?(String) || data.respond_to?(:read) || multipart_form_post?
315
+
316
+ # Curb joins other positional arguments as it would form fields.
317
+ @put_data = [data].join('&')
318
+ super(@put_data)
319
+ ensure
320
+ @put_data = nil
277
321
  end
278
322
  alias put http_put
279
323
 
@@ -293,10 +337,12 @@ if defined?(Curl)
293
337
  @post_body = nil
294
338
  end
295
339
 
296
- def put_data= data
340
+ def put_data=(data)
341
+ body = data.respond_to?(:read) ? data : data&.to_s
342
+ super(body)
297
343
  @webmock_method = :put
298
- @put_data = data
299
- super
344
+ @put_data = body
345
+ data
300
346
  end
301
347
 
302
348
  def post_body= data
@@ -359,6 +405,8 @@ if defined?(Curl)
359
405
  end
360
406
 
361
407
  def reset
408
+ @put_data = nil
409
+ reset_webmock_method
362
410
  instance_variable_set(:@body_str, nil)
363
411
  instance_variable_set(:@content_type, nil)
364
412
  instance_variable_set(:@header_str, nil)
@@ -107,8 +107,6 @@ if defined?(EventMachine::HttpClient)
107
107
  end
108
108
 
109
109
  def send_request(head, body)
110
- WebMock::RequestRegistry.instance.requested_signatures.put(request_signature)
111
-
112
110
  if stubbed_webmock_response
113
111
  WebMock::CallbackRegistry.invoke_callbacks({lib: :em_http_request}, request_signature, stubbed_webmock_response)
114
112
  @uri ||= nil
@@ -144,7 +142,13 @@ if defined?(EventMachine::HttpClient)
144
142
 
145
143
  def stubbed_webmock_response
146
144
  unless defined?(@stubbed_webmock_response)
147
- @stubbed_webmock_response = WebMock::StubRegistry.instance.response_for_request(request_signature)
145
+ signature = request_signature
146
+ recorded = if signature.body.respond_to?(:read) && signature.body.respond_to?(:eof?)
147
+ signature.with_body_values { |stream| WebMock::Util::UploadBody.read(stream, signature.headers) }
148
+ else
149
+ signature
150
+ end
151
+ @stubbed_webmock_response = WebMock::StubRegistry.instance.response_for_request(signature, record: recorded)
148
152
  end
149
153
 
150
154
  @stubbed_webmock_response
@@ -53,7 +53,7 @@ if defined?(Excon)
53
53
 
54
54
  def self.handle_request(params)
55
55
  mock_request = self.build_request params.dup
56
- WebMock::RequestRegistry.instance.requested_signatures.put(mock_request)
56
+ WebMock::RequestRegistry.instance.put(mock_request)
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)
@@ -29,7 +29,7 @@ module HTTP
29
29
  end
30
30
 
31
31
  def register_request(signature)
32
- ::WebMock::RequestRegistry.instance.requested_signatures.put(signature)
32
+ ::WebMock::RequestRegistry.instance.put(signature)
33
33
  end
34
34
 
35
35
  def replay