webmock 3.35.0 → 3.38.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: fe7cd5f67ec64e8f66e1ab898f7366c8e63901b9bcab1e5e51e72b7a5438b295
4
+ data.tar.gz: e30145eee641ae21272de856d6b2e56f9f9499e94bab4e975c44aeb30db213a9
5
5
  SHA512:
6
- metadata.gz: e99abdb908ce47c4bba164cfa574a2b94f54e042f7bd55f1ba4f64bf88b43f3c721c7a7e39f8870c7f0d3ecdc139ee79d7c14de0c201ca0937de8355ded288c7
7
- data.tar.gz: 9a75e24decc112843f7e89ee47e68fbf312bec7d23590d0b17c1661295d5b3c2b690cc4800757e1e2c2d62b58990ddd217f492c6e095209c282ed6107d732367
6
+ metadata.gz: e3a5cd28f04f014ff838d1ce81f16372033b11dd91047984e53b15b64e8696af56b3915a624935e913f64a42216db7960059ba7f558ca3ac865b1709843f1165
7
+ data.tar.gz: 7b0a0969e2b24116deeaf70cceb4fc85b7375f55118ccfb80ed4fa48594cecbde9bac650526c7d66ac162fef4d5eba90ac9cf4fee430b9e72de5f640b1cc6d2b
data/CHANGELOG.md CHANGED
@@ -1,5 +1,179 @@
1
1
  # Changelog
2
2
 
3
+ # 3.38.0
4
+
5
+ * Allow or disable real requests only within a block (#1110)
6
+
7
+ `WebMock.allow_net_connect!` and `WebMock.disable_net_connect!` now take a block, for example `WebMock.disable_net_connect!(allow: "api.example.com") { ... }`. The settings apply only while the block runs. When it ends, even with an exception, the settings from before the call come back.
8
+
9
+ Previously, either method ignored a block. In `WebMock.allow_net_connect! { Net::HTTP.get(uri) }`, the request never ran, and real requests stayed allowed until the settings changed again. Code in such a block now runs.
10
+
11
+ The settings are global, so other threads see them while the block runs. Don't run such blocks in several threads at once, because they can restore each other's settings in the wrong order.
12
+
13
+ Thanks to [Yegor Bugayenko](https://github.com/yegor256) for the suggestion
14
+
15
+ * Record the form Content-Type of Typhoeus requests with a hash body (#463)
16
+
17
+ Previously, `Typhoeus.post(url, body: {page: 2})` sent `Content-Type: application/x-www-form-urlencoded`, but WebMock recorded the request without it. A stub with `with(body: {page: 2})` didn't match, and neither did a stub that required that header.
18
+
19
+ WebMock now records the header whenever Typhoeus sends it for a hash body: for a POST, even with an empty hash, and for any other method except PUT and HEAD, unless the form is empty.
20
+
21
+ A request that sets its own Content-Type keeps it. Multipart forms, such as a hash with a file or a request with `multipart: true`, still have no Content-Type recorded, except an empty POST, which Typhoeus sends URL encoded even then. Requests with `nobody: true` have none either.
22
+
23
+ Callbacks, `WebMock.executed_requests` and VCR see the header too, and the stub suggested for an unmatched request includes it and shows a form body as a hash. Update assertions that compare all the headers of such a request. If VCR, hooked into WebMock, matches requests on their headers, record the affected cassettes again.
24
+
25
+ * Keep a `with` block when `with` is called again with options only
26
+
27
+ Previously, `stub_request(:post, url).with { |request| request.body == "yes" }.with(headers: {"X-A" => "1"})` dropped the block, so the stub also matched a request with that header and the body `"no"`. A later `with` call already kept the options it didn't give, such as `body:`, and now keeps the block too. The same applies to `a_request`.
28
+
29
+ A stub or request expectation that matched only because the block was dropped no longer matches. Calling `with` again with a block, or with an option given before, still replaces it.
30
+
31
+ * Match numbers and boolean values in query patterns (#371)
32
+
33
+ Previously, `with(query: hash_including(page: 2))` never matched `?page=2`, because query values in a request are strings and WebMock compared them with the Integer `2`. A plain hash had the same problem when the stub's URI was a regexp, a template or a lambda, as in `stub_request(:get, /example/).with(query: {page: 2})`. With a string URI, an array of numbers such as `{tag: [2, 10]}` didn't match `?tag[]=2&tag[]=10`.
34
+
35
+ WebMock now compares numbers, `true` and `false` in query patterns as strings, including inside nested `hash_including` and `hash_excluding` matchers.
36
+
37
+ This also makes `hash_excluding` work with such values. Previously, `with(query: hash_excluding(page: 2))` matched `?page=2`. A test that passed only because of this will now fail.
38
+
39
+ * Fix nested `hash_including` and `hash_excluding` with symbol keys in RSpec (#900)
40
+
41
+ Previously, in RSpec, `with(body: {user: hash_including(role: "admin")})` never matched the JSON body `{"user":{"role":"admin"}}`. WebMock converted the keys of the outer hash to strings, but not those of a matcher inside it, and the parsed body has string keys. For the same reason, a nested `hash_excluding` with symbol keys never excluded anything, so `with(body: {user: hash_excluding(role: "admin")})` matched that body too.
42
+
43
+ The same applied to query patterns: `with(query: hash_including(filter: hash_excluding(role: "admin")))` matched `?filter[role]=admin`.
44
+
45
+ Nested matchers now get string keys too, as do hashes inside RSpec's `array_including` and `array_excluding`. A test that passed only because a nested `hash_excluding` excluded nothing will now fail.
46
+
47
+ * Fix `hash_including` and `hash_excluding` nested in a query hash
48
+
49
+ Previously, `stub_request(:get, "www.example.com").with(query: {filter: hash_including("role" => "admin")})` never matched `?filter[role]=admin&filter[active]=true`, because WebMock wrote the matcher into the stub's URL as text. With a regexp, a template or a lambda URI, such a stub never matched in RSpec, where `hash_including` and `hash_excluding` are RSpec's own matchers.
50
+
51
+ Such stubs now match with every kind of URI.
52
+
53
+ * Ignore letter case in allowed host names (#819)
54
+
55
+ Previously, `WebMock.disable_net_connect!(allow: "Anachronic.local")` blocked requests to that host, because WebMock compared the allowed name with the request's host, which it writes in lowercase. The same applied to a host with a port, such as `"Anachronic.local:8080"`, and to host names given as `net_http_connect_on_start`.
56
+
57
+ Such requests are now allowed and reach the real server. Host names are not case sensitive, and allowed URLs have ignored the letter case of the host since 3.30.0.
58
+
59
+ * Fix URI templates not matching encoded characters in query values (#468)
60
+
61
+ Previously, `stub_request(:get, Addressable::Template.new("https://example.com/test{?q}"))` didn't match `https://example.com/test?q=env%3Aproduction`, although the template itself matches that URL. The same happened with `?q=env:production`, and with other punctuation such as `/`, `@` or `=`, encoded or not.
62
+
63
+ Both now match. As with string URIs, a stub can't tell such an encoded character from the character itself.
64
+
65
+ * Fix stubs with a hash body pattern raising on binary request bodies (#333)
66
+
67
+ Previously, a stub such as `stub_request(:post, url).with(body: {"name" => "x"})` raised `ArgumentError: invalid byte sequence in UTF-8` when the request body was binary data, such as an uploaded image. Since WebMock checks the newest stub first, this also broke requests that an older stub would have answered.
68
+
69
+ Such a body now doesn't match the hash pattern, so WebMock moves on to the next stub, as it already did for a body that isn't valid JSON.
70
+
71
+ * Fix unstubbed requests with some form bodies raising `ArgumentError` instead of WebMock's error
72
+
73
+ Previously, when a request with a URL encoded body matched no stub, WebMock could raise `ArgumentError` while it built the suggested stub for its error message. This happened when the body was binary data, or when it repeated a key, as in `a=1&a=2`, with `query_values_notation` set to `:flat`.
74
+
75
+ WebMock now raises its usual error, and the suggested stub shows such a body as a string.
76
+
77
+ * Fix Net::HTTP `OPTIONS *` requests raising `Addressable::URI::InvalidURIError` (#982)
78
+
79
+ Previously, `http.request(Net::HTTP::Options.new("*"))` raised `Invalid port number`, even with real connections allowed, because WebMock could not build a URI from the `*` request target.
80
+
81
+ WebMock now records such a request with the path `/*`, so stub it as `stub_request(:options, "www.example.com/*")`. Real requests still send `OPTIONS *`. Stubs and `assert_requested` can't tell such a request from an `OPTIONS` request for the path `/*`.
82
+
83
+ * Apply a changed `query_values_notation` to URLs that WebMock has already seen
84
+
85
+ Previously, after `WebMock::Config.instance.query_values_notation = :flat_array`, a URL that WebMock had already seen kept the query it got with the earlier notation, so `?a=1&a=2` still became `?a=2`. Whether a stub matched depended on which tests ran first.
86
+
87
+ WebMock now reads each request's URL with the current notation. A stub keeps the query as WebMock read it when the stub was declared, so set the notation before declaring stubs.
88
+
89
+ * Match `with(query: "...")` pairs in any order with `:flat_array`
90
+
91
+ Previously, with `WebMock::Config.instance.query_values_notation = :flat_array`, `with(query: "b=2&a=1")` didn't match a request for `?b=2&a=1`, and `with(query: "a=2&a=1")` didn't match `?a=2&a=1`. Only patterns with their pairs in sorted order matched.
92
+
93
+ Such patterns now match their pairs in any order, as a query in the stub's URL already did. A stub can't tell `?a=1&a=2` from `?a=2&a=1`.
94
+
95
+ * Fix URLs that repeat a query key without a value raising with `:flat_array`
96
+
97
+ Previously, with `:flat_array`, any request for a URL such as `?a&a=2` raised `ArgumentError`. It now matches `with(query: "a&a=2")`, but not `with(query: "a=&a=2")`, since the key has no value rather than an empty one.
98
+
99
+ # 3.37.0
100
+
101
+ * Add `executed_requests` to inspect the requests made (#1069)
102
+
103
+ `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)`.
104
+
105
+ Previously, this needed WebMock internals such as `WebMock::RequestRegistry.instance.requested_signatures.hash.keys`, which list each distinct request only once.
106
+
107
+ Thanks to [John Gallagher](https://github.com/johngallagher) for the idea, which we started pairing on at EuRuKo 2024 in Sarajevo.
108
+
109
+ * Fix stub matching for consecutive Curb PUT requests on the same handle
110
+
111
+ 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.
112
+
113
+ * Run HTTPClient request filters once per attempt on real requests
114
+
115
+ 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.
116
+
117
+ * Fix async HTTPClient requests hanging when an `after_request` callback is registered
118
+
119
+ 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.
120
+
121
+ * Match file and stream uploads by their content
122
+
123
+ 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.
124
+
125
+ Blocks given to `stub_request(...).with` still receive the original file or stream.
126
+
127
+ * Count em-http-request requests blocked by `disable_net_connect!`
128
+
129
+ Previously, WebMock did not record them, so `assert_requested` did not count them. They are now counted, as with other HTTP clients.
130
+
131
+ # 3.36.0
132
+
133
+ * Fix matching of indexed arrays nested inside arrays of hashes (#1144)
134
+
135
+ 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.
136
+
137
+ 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.
138
+
139
+ Thanks to [Hamza Tarar](https://github.com/ihamzatarar)
140
+
141
+ * Fix matching of arrays of hashes that repeat a nested key
142
+
143
+ 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.
144
+
145
+ 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.
146
+
147
+ 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.
148
+
149
+ * Apply Net::HTTP `response_body_encoding` to stubbed response bodies (#1138)
150
+
151
+ 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`.
152
+
153
+ 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.
154
+
155
+ Thanks to [Yang Bai](https://github.com/ybai08)
156
+
157
+ * Give each stubbed Net::HTTP response its own copy of the body
158
+
159
+ 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.
160
+
161
+ * Keep the size of async-http responses to HEAD requests (#1143)
162
+
163
+ 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`.
164
+
165
+ 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`.
166
+
167
+ Thanks to [Andrew K. Fader](https://github.com/andrewfader)
168
+
169
+ * Keep the URI query of HTTPClient requests that pass a query argument (#1145)
170
+
171
+ 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.
172
+
173
+ 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.
174
+
175
+ Thanks to [AmeenKhan12345](https://github.com/AmeenKhan12345)
176
+
3
177
  # 3.35.0
4
178
 
5
179
  * Fix `get_file` with Patron 1.1 (#1147)
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) (currently only Curb::Easy)
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.
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)
@@ -74,6 +74,8 @@ rake install
74
74
 
75
75
  WebMock 2.x has changed somewhat since version 1.x. Changes are listed in [CHANGELOG.md](CHANGELOG.md)
76
76
 
77
+ ## Setup
78
+
77
79
  ### Cucumber
78
80
 
79
81
  Create a file `features/support/webmock.rb` with the following contents:
@@ -106,6 +108,48 @@ Add the following code to `test/test_helper.rb`
106
108
  require 'webmock/test_unit'
107
109
  ```
108
110
 
111
+ ### What the test framework integrations do
112
+
113
+ `webmock/rspec`, `webmock/minitest`, `webmock/test_unit` and `webmock/cucumber` do three things:
114
+
115
+ * They enable WebMock. `webmock/rspec` does it in a `before(:suite)` hook and disables WebMock again in `after(:suite)`. The others enable it as soon as they are required.
116
+ * They call `WebMock.reset!` after every example, test or scenario. This removes the stubs declared with `stub_request` and the history of requests, so a stub declared in RSpec's `before(:all)` or `before(:context)`, or in a minitest-hooks `before_all`, is gone after the first example. Declare such stubs in `before(:each)` or `setup` instead, or use [global stubs](#global-stubs), which `WebMock.reset!` keeps. If you override `teardown` in Minitest, call `super`, or WebMock's reset doesn't run.
117
+ * They leave the net connect settings alone. By default WebMock blocks real requests. `WebMock.allow_net_connect!` allows them all, and `WebMock.disable_net_connect!` blocks them again, except for what its options allow, such as `allow_localhost: true`. Each setting stays in effect for every later example until you change it, and each call to `disable_net_connect!` replaces the `allow`, `allow_localhost` and `net_http_connect_on_start` options given before.
118
+
119
+ Requiring one of these files in a spec helper or in any spec file enables WebMock for the whole run, not only for that file. To use WebMock only in some examples, require `webmock` and set it up yourself, for example for RSpec examples tagged with `:webmock`:
120
+
121
+ ```ruby
122
+ require 'webmock'
123
+ require 'webmock/rspec/matchers'
124
+
125
+ WebMock::AssertionFailure.error_class = RSpec::Expectations::ExpectationNotMetError
126
+
127
+ RSpec.configure do |config|
128
+ config.include WebMock::API, :webmock
129
+ config.include WebMock::Matchers, :webmock
130
+
131
+ config.around(:each, :webmock) do |example|
132
+ WebMock.enable!
133
+ WebMock.disable_net_connect!
134
+ example.run
135
+ ensure
136
+ WebMock.reset!
137
+ WebMock.disable!
138
+ end
139
+ end
140
+ ```
141
+
142
+ Examples without the tag then make real requests. Create HTTP clients inside each example: a client created while WebMock was disabled isn't intercepted, and a Curb or HTTPClient object created in a tagged example is still intercepted after it.
143
+
144
+ Enabling WebMock and allowing real requests are separate settings. `WebMock.enable!` and `WebMock.disable!` decide whether WebMock intercepts requests at all. `WebMock.disable_net_connect!` and `WebMock.allow_net_connect!` decide what happens to an intercepted request that no stub matches. While WebMock is disabled, it doesn't intercept requests, so these settings only take effect once it is enabled again.
145
+
146
+ For HTTP clients such as Net::HTTP, HTTPClient and Curb, WebMock intercepts requests by replacing their classes while it is enabled. `webmock/rspec` enables WebMock just before the first example, after your app and spec files have loaded. A class that inherits from `Net::HTTP`, or an HTTP client object such as a `Net::HTTP` or `HTTPClient` instance, created while they load uses the original class, and its requests reach the network. A client that creates its HTTP object for each request is not affected. If your app defines such a class or creates such an object while it loads, enable WebMock right after requiring it:
147
+
148
+ ```ruby
149
+ require 'webmock/rspec'
150
+ WebMock.enable!
151
+ ```
152
+
109
153
  ### Outside a test framework
110
154
 
111
155
  You can also use WebMock outside a test framework:
@@ -335,6 +379,23 @@ RestClient.get("http://www.example.com/?a=b") # ===> Failure
335
379
  RestClient.get("http://www.example.com/?a=c") # ===> Success
336
380
  ```
337
381
 
382
+ ### Matching repeated query params
383
+
384
+ By default WebMock reads a query the way Rack and Rails do, so a key repeated without brackets keeps only its last value: `?a=1&a=2` is read as `?a=2`. To match repeated keys, switch to the `:flat_array` notation and give the query as a string:
385
+
386
+ ```ruby
387
+ WebMock::Config.instance.query_values_notation = :flat_array
388
+
389
+ stub_request(:get, "www.example.com/?a=1&a=2")
390
+ # or
391
+ stub_request(:get, "www.example.com").with(query: "a=1&a=2")
392
+
393
+ RestClient.get("http://www.example.com/?a=1&a=2") # ===> Success
394
+ RestClient.get("http://www.example.com/?a=2") # ===> Failure
395
+ ```
396
+
397
+ The notation applies to every stub and request. Hashes can't describe repeated keys, so with `:flat_array`, `hash_including`, `hash_excluding`, query hashes given with a regexp or template URI, and form bodies given as a hash don't match. Set the notation only in the tests that need it, and set it back to `:subscript` afterwards.
398
+
338
399
  ### Stubbing with custom response
339
400
 
340
401
  ```ruby
@@ -650,6 +711,26 @@ RestClient.get('bbc.com', '/') # ===> Allowed
650
711
  RestClient.get('www.bbc.com', '/') # ===> Failure
651
712
  ```
652
713
 
714
+ ### Real requests can be allowed or disabled only within a block
715
+
716
+ Given a block, `WebMock.allow_net_connect!` and `WebMock.disable_net_connect!` apply their settings only while the block runs and return the block's value. When the block ends, even with an exception, WebMock restores the settings from before the call.
717
+
718
+ ```ruby
719
+ WebMock.disable_net_connect!
720
+
721
+ WebMock.allow_net_connect! do
722
+ Net::HTTP.get('www.something.com', '/') # ===> /.+Something.+/
723
+ end
724
+
725
+ WebMock.disable_net_connect!(allow: 'www.example.org') do
726
+ RestClient.get('www.example.org', '/') # ===> Allowed
727
+ end
728
+
729
+ Net::HTTP.get('www.something.com', '/') # ===> Failure
730
+ ```
731
+
732
+ Settings changed inside the block, for example by another call to `WebMock.disable_net_connect!`, are undone as well. The settings are global, so other threads see them while the block runs, and blocks that overlap in different threads can restore each other's settings in the wrong order. Use the block form only where tests run one at a time in each process.
733
+
653
734
  ## Connecting on Net::HTTP.start
654
735
 
655
736
  HTTP protocol has 3 steps: connect, request and response (or 4 with close). Most Ruby HTTP client libraries
@@ -726,6 +807,8 @@ assert_requested(stub_get)
726
807
  assert_not_requested(stub_post)
727
808
  ```
728
809
 
810
+ See [What an expectation on a stub counts](#what-an-expectation-on-a-stub-counts) for which requests these assertions count.
811
+
729
812
 
730
813
  ### Setting expectations in RSpec on `WebMock` module
731
814
  This style is borrowed from [fakeweb-matcher](http://github.com/pat/fakeweb-matcher)
@@ -802,9 +885,59 @@ expect(stub).to have_been_requested.once.with(body: {"a" => [4, 5, 6]})
802
885
 
803
886
  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
887
 
888
+ ### What an expectation on a stub counts
889
+
890
+ An expectation on a stub, such as `assert_requested(stub)` or `expect(stub).to have_been_requested`, counts the requests since the last `WebMock.reset!` or `WebMock.reset_executed_requests!` that match the stub's pattern. A matching request counts even if another stub answered it, if it was made before the stub was declared, or if it was made after the stub was removed with `remove_request_stub`.
891
+
892
+ ```ruby
893
+ stub_any = stub_request(:post, "www.example.com")
894
+ stub_body = stub_request(:post, "www.example.com").with(body: "abc")
895
+
896
+ Net::HTTP.post(URI("http://www.example.com"), "abc") # answered by stub_body
897
+
898
+ expect(stub_body).to have_been_requested.once # ===> Success
899
+ expect(stub_any).to have_been_requested.once # ===> Success, as its pattern matches too
900
+ ```
901
+
902
+ To make an expectation stricter, give the stub its own conditions, such as `with(body: "")` for requests without a body. In RSpec you can also add them to the expectation with `with`, as shown above. With `assert_requested`, pass the method and URL instead of the stub, for example `assert_requested(:post, "www.example.com", body: "")`. To count from zero, call `WebMock.reset_executed_requests!`.
903
+
904
+ WebMock may run a `with` block once for several identical requests and multiply the count, so keep such blocks free of side effects. To look at every request, use [`executed_requests`](#inspecting-the-requests-made).
905
+
906
+ ### Inspecting the requests made
907
+
908
+ `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.
909
+
910
+ ```ruby
911
+ stub_request(:post, "www.example.com/orders")
912
+
913
+ Net::HTTP.post(URI("http://www.example.com/orders"), '{"name":"John"}', "Content-Type" => "application/json")
914
+
915
+ request = WebMock.executed_requests.last
916
+ request.method # ===> :post
917
+ request.uri.path # ===> "/orders"
918
+ request.headers["Content-Type"] # ===> "application/json"
919
+ JSON.parse(request.body) # ===> {"name" => "John"}
920
+ ```
921
+
922
+ 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:
923
+
924
+ ```ruby
925
+ expect(executed_requests.map { |request| request.uri.path }).to eq(["/orders", "/orders/1/confirm"])
926
+ ```
927
+
928
+ A few things to know:
929
+
930
+ * 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`.
931
+ * The requests are copies, so changing them doesn't change what WebMock recorded.
932
+ * When a Curb, Patron or em-http-request 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`.
933
+ * 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.
934
+ * With these three clients, blocks given to `stub_request(...).with` and `after_request` callbacks still receive the original file or stream, not the bytes. With other clients, such as Net::HTTP and Excon, the stream is read when the request is made, and blocks and callbacks receive the bytes.
935
+ * An expectation on a stub, such as `assert_requested(stub)`, reuses the decision the stub made when the upload happened, so a stub block that checks the stream gives the same result in the expectation. If the stub never saw the request, because another stub answered first or the stub was declared later, the expectation checks the uploaded bytes, as `a_request(...)` and conditions given to the expectation's `with` always do.
936
+ * Depending on the HTTP client, requests that WebMock blocked because real connections are disabled may be listed too.
937
+
805
938
  ## Clearing stubs and request history
806
939
 
807
- If you want to reset all current stubs and history of requests use `WebMock.reset!`
940
+ If you want to reset all current stubs and history of requests use `WebMock.reset!`. [Global stubs](#global-stubs) stay.
808
941
 
809
942
  ```ruby
810
943
  stub_request(:any, "www.example.com")
@@ -820,7 +953,7 @@ assert_not_requested :get, "www.example.com" # ===> Success
820
953
 
821
954
  ## Clearing request counters
822
955
 
823
- If you want to reset **only** the counters of the executed requests use `WebMock.reset_executed_requests!`
956
+ If you want to reset **only** the counters and the list of executed requests, and keep the stubs, use `WebMock.reset_executed_requests!`
824
957
 
825
958
  ```ruby
826
959
  stub = stub_request(:get, "www.example.com")
@@ -840,6 +973,28 @@ expect(stub).not_to have_been_requested
840
973
  expect(stub2).not_to have_been_requested
841
974
  ```
842
975
 
976
+ ## Global stubs
977
+
978
+ `WebMock.reset!` removes the stubs declared with `stub_request`, and `webmock/rspec`, `webmock/minitest`, `webmock/test_unit` and `webmock/cucumber` call it after every test or scenario. To answer some requests in every test, for example calls to a metrics service, declare a global stub once when the test suite starts:
979
+
980
+ ```ruby
981
+ WebMock.globally_stub_request do |request|
982
+ { status: 200, body: "{}" } if request.uri.host == "metrics.example.com"
983
+ end
984
+ ```
985
+
986
+ WebMock calls the block with the request when it reaches the global stub. The block returns a response hash with the same keys as `to_return`, or `nil` to let other stubs handle the request. `WebMock.reset!` doesn't remove global stubs, and there is no way to remove only one, so declare each of them once, for example in RSpec's `before(:suite)`.
987
+
988
+ Global stubs are checked before the stubs declared with `stub_request`. To check a global stub after them instead, so a test can override it with its own stubs, declare it with `:after_local_stubs`:
989
+
990
+ ```ruby
991
+ WebMock.globally_stub_request(:after_local_stubs) do |request|
992
+ { status: 200, body: "{}" } if request.uri.host == "metrics.example.com"
993
+ end
994
+ ```
995
+
996
+ Requests answered by a global stub are recorded like any other, so `a_request`, `assert_requested` and `executed_requests` include them.
997
+
843
998
  ## Disabling and enabling WebMock or only some http client adapters
844
999
 
845
1000
  ```ruby
@@ -877,6 +1032,8 @@ stub_request(:get, "www.example.com").to_return(body: "def")
877
1032
  Net::HTTP.get('www.example.com', '/') # ====> "def"
878
1033
  ```
879
1034
 
1035
+ [Global stubs](#global-stubs) are checked before these stubs, or after them when declared with `:after_local_stubs`.
1036
+
880
1037
  ## Matching URIs
881
1038
 
882
1039
  WebMock will match all different representations of the same URI.
@@ -981,6 +1138,16 @@ WebMock.after_request(except: [:patron],
981
1138
  end
982
1139
  ```
983
1140
 
1141
+ #### Removing callbacks
1142
+
1143
+ Callbacks stay registered after `WebMock.reset!`, so a callback added in one test keeps running in later ones. To remove all callbacks, call:
1144
+
1145
+ ```ruby
1146
+ WebMock.reset_callbacks
1147
+ ```
1148
+
1149
+ This also removes callbacks registered by other libraries, such as VCR, so prefer registering your callbacks once, for example in your test helper.
1150
+
984
1151
  ## Bugs and Issues
985
1152
 
986
1153
  Please submit them here [http://github.com/bblimke/webmock/issues](http://github.com/bblimke/webmock/issues)
@@ -1283,6 +1450,35 @@ People who submitted patches and new features or suggested improvements. Many th
1283
1450
  * Erik Berlin
1284
1451
  * Josch Bockler
1285
1452
  * Leslie Hoare
1453
+ * Chris Gunther
1454
+ * hikmetba-bit
1455
+ * Daniel Pepper
1456
+ * Christian Bruckmayer
1457
+ * Chris
1458
+ * Jan Graichen
1459
+ * Olivier Brisse
1460
+ * Henry Blyth
1461
+ * Sébastien S.
1462
+ * Euisan Kim
1463
+ * Alex
1464
+ * Andy Williams
1465
+ * Tim Mertens
1466
+ * Mike Taylor
1467
+ * James Rodovich
1468
+ * Michael Spiz
1469
+ * Tom Brammar
1470
+ * Benoit Tigeot
1471
+ * nightpool
1472
+ * Andrii Furmanets
1473
+ * thoran
1474
+ * Julik Tarkhanov
1475
+ * Bob Aman
1476
+ * AmeenKhan12345
1477
+ * Andrew K. Fader
1478
+ * Yang Bai
1479
+ * Hamza Tarar
1480
+ * John Gallagher
1481
+ * Yegor Bugayenko
1286
1482
 
1287
1483
  For a full list of contributors you can visit the
1288
1484
  [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