webmock 3.37.0 → 3.39.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: dcdb50457447f4b9234934f5211c2ccd45a55e11c164a0faaeb6ba8a47d6949a
4
- data.tar.gz: 28bdd8fac8769c6d3b7f2f63f6070f60f9c602f090ae14f9b957ddbf5bb4f93f
3
+ metadata.gz: f4a748dba8ab25b81fc4cd65b9cd09e7bc4fff957bb3bd0c92ef91b12ad9202e
4
+ data.tar.gz: f4a161fa5bffd45a09a44d70f99045a28f90cc508cb30ea7c719e6b4acb3f63e
5
5
  SHA512:
6
- metadata.gz: 90780a4cf7639e3a09132f59c2479d042eb2ee3c769835b2957d0a508c666a9c0c039884459bdd51aefdaa3f6efae8d3caad58ee80efcf41d8af0e202b04e1ad
7
- data.tar.gz: 4fdddbbae16604e0b21b567e4e69038567c1eefb9e357b03998583379b6d7393e04ea68d490edb3f7175bb5082fcc187d8069402521bdc8072f956018a612ba8
6
+ metadata.gz: e49c29028d6809a07bef2fab63f9a3d09c1b7a7ec9cf6c279ee4b0d56e23e636dd546692b737fb2e7017e66844e8aeb711dfb91aade297d82e2078304d84c003
7
+ data.tar.gz: 5a240000226bfd4f60a22387bb6c1040c9fe00b16ceb9894c98bed42427d64523d2db41f05daaea0b1e5ea960f57b94a3a41ca42171fbe08ee6c7d6241362472
data/CHANGELOG.md CHANGED
@@ -1,5 +1,195 @@
1
1
  # Changelog
2
2
 
3
+ # 3.39.0
4
+
5
+ * Fix tracing libraries that wrap HTTPClient failing on stubbed requests (#1010)
6
+
7
+ Previously, for a stubbed request, WebMock's version of HTTPClient's private `do_get_block` method returned a `Thread::Queue` instead of the response that HTTPClient's own version returns. Libraries that wrap the method to trace requests, such as Datadog's, read that result as the response.
8
+
9
+ It now returns the response, as it already did for real requests.
10
+
11
+ * Match and record Net::HTTP URL encoded forms set with `set_form` (#959)
12
+
13
+ Previously, WebMock saw no body for a request whose form was set with `request.set_form([["foo", "bar"]])`, because Net::HTTP encodes such a form only when it sends the request. A stub such as `with(body: {"foo" => "bar"})` didn't match, and callbacks and VCR recorded the request without its body.
14
+
15
+ WebMock now records the body of a URL encoded form given as a hash or an array of pairs, as Net::HTTP encodes it, and leaves sending the request to Net::HTTP. A multipart form, or a form given as another enumerable, which may be read only once, is recorded without a body, as before. If VCR, hooked into WebMock, matches requests on their body, record cassettes that contain such requests again.
16
+
17
+ * Fix async-websocket connections failing with WebMock enabled (#953)
18
+
19
+ Previously, connecting with `Async::WebSocket::Client` raised `NoMethodError: undefined method 'acquire' for nil`, even to a host that allowed real connections. async-websocket takes a connection from the async-http client's pool, and WebMock's version of the client had no pool.
20
+
21
+ The client now hands out its real connection pool when WebMock's settings allow real connections to the host, and raises `WebMock::NetConnectNotAllowedError` otherwise. WebMock can't stub or record what a library sends over such a connection, and neither can VCR, so with VCR hooked into WebMock, allow the host with `WebMock.disable_net_connect!(allow: ...)`.
22
+
23
+ * Match the Cookie header that Typhoeus sends for the `cookie` option (#813)
24
+
25
+ Previously, `Typhoeus.get(url, cookie: "key=value")` sent `Cookie: key=value`, but WebMock recorded the request without it, so a stub with `with(headers: {"Cookie" => "key=value"})` didn't match.
26
+
27
+ WebMock now records the header, unless the request sets its own Cookie header, which is then the one sent, or uses libcurl's cookie engine with `cookiefile`, `cookiejar` or `cookielist`, which adds its own cookies to it. If VCR, hooked into WebMock, matches requests on their headers, record cassettes that contain such requests again. VCR now records the cookie too, so filter it, for example with `filter_sensitive_data`, if it is a secret.
28
+
29
+ * Fix VCR failing to replay Typhoeus requests when hooked into both Typhoeus and WebMock (#973)
30
+
31
+ Previously, with `hook_into :typhoeus, :webmock`, VCR warned that "There appears to be a bug in WebMock's after_request hook", and replaying a Typhoeus request from a cassette raised `ArgumentError`. VCR's Typhoeus hook answered the request before WebMock saw it, and WebMock still passed the request to `after_request` callbacks, as `nil`.
32
+
33
+ WebMock now leaves out requests it didn't see. On older versions, `hook_into :webmock` alone records and replays Typhoeus requests too.
34
+
35
+ * Run the instrumentation of the `http` gem 6 for stubbed requests (#881)
36
+
37
+ Previously, with version 6 of the `http` gem (HTTP.rb), a stubbed request skipped the instrumentation feature, so `HTTP.use(instrumentation: {instrumenter: ...})` emitted no `request.http` events for it. In every version, a stubbed timeout or `HTTP::Error` emitted no `error.http` event.
38
+
39
+ Stubbed requests now emit the same instrumentation events as real ones. Other features that HTTP.rb 6 runs around a request, such as caching and digest auth, still don't run for stubbed requests.
40
+
41
+ * Fix Net::HTTP uploads raising `ArgumentError` for body streams whose `read` needs a length (#644)
42
+
43
+ Previously, a request with `body_stream` set to an object with `def read(length, buffer = nil)` raised `ArgumentError: wrong number of arguments`, even with real connections allowed, because WebMock called `read` without arguments. Net::HTTP itself always passes a length, so the upload worked without WebMock.
44
+
45
+ WebMock now reads such a stream in chunks.
46
+
47
+ * Fix failure messages raising `Encoding::CompatibilityError` for bodies in different encodings (#668)
48
+
49
+ Previously, the message for an unstubbed request, or for a failed `assert_requested`, could raise `Encoding::CompatibilityError: incompatible character encodings: BINARY (ASCII-8BIT) and UTF-8` instead of showing the failure. This happened when the message listed a UTF-8 body with non ASCII characters, such as a stub `with(body: "café")`, next to a binary one, such as an uploaded image.
50
+
51
+ Such messages now show the failure, with bytes that aren't valid UTF-8 written as escapes, such as `\xFF`.
52
+
53
+ * Show URI templates, regexps and query options as Ruby in the list of registered stubs (#938)
54
+
55
+ Previously, the registered stubs listed for an unstubbed request put every URI in quotes, so a template stub was shown as `stub_request(:get, ""http://localhost:9200/{index}/_search"")`, a regexp as a string, and a query given to `with` was written inside the quotes.
56
+
57
+ The list now shows `stub_request(:get, Addressable::Template.new("http://localhost:9200/{index}/_search"))`, a regexp as a regexp, and a query that isn't part of the URL as `with(query: ...)`. The suggested stub for the unmatched request is unchanged.
58
+
59
+ * Leave out of the body diff the values that a regexp in a stub's body pattern matches (#840)
60
+
61
+ Previously, when a request didn't match a stub such as `with(body: {"email" => /@/}, headers: {"X-Token" => "1"})` because of its headers, the body diff in the message still listed `["~", "email", "milo@carter.net", /@/]`, so the regexp looked like the cause.
62
+
63
+ The diff now leaves out the values that such a regexp matches.
64
+
65
+ * Leave the User-Agent header out of the suggested stub for an unmatched request (#596)
66
+
67
+ Previously, the stub that WebMock suggests, as in "You can stub this request with the following snippet", required the request's `User-Agent`, such as `'User-Agent'=>'Ruby'` or one with the client's version. A stub pasted from it stopped matching when the client was upgraded or the tests ran on another platform.
68
+
69
+ The suggestion now leaves `User-Agent` out, so it matches whatever the client sends. The message still shows the request with all its headers.
70
+
71
+ * Fix loading a YAML or Marshal dump of an em-http-request client while WebMock is enabled (#729)
72
+
73
+ Previously, `YAML.unsafe_load(client.to_yaml)` or `Marshal.load(Marshal.dump(client))` raised `ArgumentError: undefined class/module EventMachine::HttpClient::CookieJar`, because WebMock replaces `EventMachine::HttpClient` with a subclass.
74
+
75
+ Such a dump now loads. A dump made while WebMock is enabled names WebMock's subclass, so load it where WebMock is loaded.
76
+
77
+ * Convert a status given as a string of digits, and deprecate statuses such as `:ok` (#802)
78
+
79
+ Previously, `to_return(status: "201")` gave the code `"2"` in Net::HTTP, because WebMock kept the string and adapters used its first character as the code. `to_return(status: :ok)` gave the code `"o"`, or `0` in some clients, without an error.
80
+
81
+ A string of digits is now converted to a number. A status such as `:ok`, `"ok"` or `200.0` now prints a deprecation warning, and WebMock 4.0 will raise `ArgumentError` for it. Use a number such as `200`, or `Rack::Utils.status_code(:ok)` in a Rack app. A code and reason pair such as `[200, "OK"]` works as before.
82
+
83
+ * Keep each cookie of a stubbed response with several `Set-Cookie` headers, in order (#470)
84
+
85
+ Previously, a raw response such as `to_return(File.read("response.txt"))` with two `Set-Cookie` lines gave clients one comma joined `Set-Cookie` value, which can't be split back, since a cookie such as `a=1; Expires=Wed, 21 Oct 2026 07:28:00 GMT` contains a comma. A stub such as `to_return(headers: {"Set-Cookie" => ["sid=old; Max-Age=0", "sid=new"]})` gave the cookies sorted, so a client applied `sid=old; Max-Age=0` last and deleted the cookie, and Curb got them on one header line.
86
+
87
+ Each client now gets the cookies as it would from a server sending these lines: separately, in the given order, on lines of their own in Curb, and joined in `headers["Set-Cookie"]` and listed in `response[:cookies]` in Excon. Other repeated response headers are unchanged.
88
+
89
+ A test that expected the cookies of such a stub joined, or sorted, now gets them as a real server would send them. For a real response with several cookies, `after_request` callbacks, and so VCR, now get them in the order the server sent them instead of sorted, and for Excon each cookie instead of the joined header, so recordings and snapshots of them can change.
90
+
91
+ * Point out when a request URL and a stub's URL differ in a slash at the end of the path (#864)
92
+
93
+ WebMock treats `http://example.com/users` and `http://example.com/users/` as different URLs, since servers can too. Previously, when a request missed a stub because of that slash, the message didn't say why.
94
+
95
+ The registered stubs listed for an unstubbed request, and the message of a failed `assert_requested` or `have_been_made`, now point out the slash. Matching is unchanged.
96
+
97
+ # 3.38.0
98
+
99
+ * Allow or disable real requests only within a block (#1110)
100
+
101
+ `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.
102
+
103
+ 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.
104
+
105
+ 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.
106
+
107
+ Thanks to [Yegor Bugayenko](https://github.com/yegor256) for the suggestion
108
+
109
+ * Record the form Content-Type of Typhoeus requests with a hash body (#463)
110
+
111
+ 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.
112
+
113
+ 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.
114
+
115
+ 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.
116
+
117
+ 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.
118
+
119
+ * Keep a `with` block when `with` is called again with options only
120
+
121
+ 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`.
122
+
123
+ 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.
124
+
125
+ * Match numbers and boolean values in query patterns (#371)
126
+
127
+ 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`.
128
+
129
+ WebMock now compares numbers, `true` and `false` in query patterns as strings, including inside nested `hash_including` and `hash_excluding` matchers.
130
+
131
+ 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.
132
+
133
+ * Fix nested `hash_including` and `hash_excluding` with symbol keys in RSpec (#900)
134
+
135
+ 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.
136
+
137
+ The same applied to query patterns: `with(query: hash_including(filter: hash_excluding(role: "admin")))` matched `?filter[role]=admin`.
138
+
139
+ 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.
140
+
141
+ * Fix `hash_including` and `hash_excluding` nested in a query hash
142
+
143
+ 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.
144
+
145
+ Such stubs now match with every kind of URI.
146
+
147
+ * Ignore letter case in allowed host names (#819)
148
+
149
+ 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`.
150
+
151
+ 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.
152
+
153
+ * Fix URI templates not matching encoded characters in query values (#468)
154
+
155
+ 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.
156
+
157
+ Both now match. As with string URIs, a stub can't tell such an encoded character from the character itself.
158
+
159
+ * Fix stubs with a hash body pattern raising on binary request bodies (#333)
160
+
161
+ 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.
162
+
163
+ 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.
164
+
165
+ * Fix unstubbed requests with some form bodies raising `ArgumentError` instead of WebMock's error
166
+
167
+ 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`.
168
+
169
+ WebMock now raises its usual error, and the suggested stub shows such a body as a string.
170
+
171
+ * Fix Net::HTTP `OPTIONS *` requests raising `Addressable::URI::InvalidURIError` (#982)
172
+
173
+ 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.
174
+
175
+ 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 `/*`.
176
+
177
+ * Apply a changed `query_values_notation` to URLs that WebMock has already seen
178
+
179
+ 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.
180
+
181
+ 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.
182
+
183
+ * Match `with(query: "...")` pairs in any order with `:flat_array`
184
+
185
+ 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.
186
+
187
+ 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`.
188
+
189
+ * Fix URLs that repeat a query key without a value raising with `:flat_array`
190
+
191
+ 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.
192
+
3
193
  # 3.37.0
4
194
 
5
195
  * Add `executed_requests` to inspect the requests made (#1069)
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
@@ -351,6 +412,12 @@ Set appropriate Content-Type for HTTParty's `parsed_response`.
351
412
  stub_request(:any, "www.example.com").to_return body: '{}', headers: {content_type: 'application/json'}
352
413
  ```
353
414
 
415
+ For JSON, `to_return_json` sets it for you:
416
+
417
+ ```ruby
418
+ stub_request(:any, "www.example.com").to_return_json(body: {})
419
+ ```
420
+
354
421
  ### Response with body specified as IO object
355
422
 
356
423
  ```ruby
@@ -372,6 +439,8 @@ stub_request(:any, "www.example.com").
372
439
  Net::HTTP.get('www.example.com', '/') # ===> "{\"foo\": \"bar\"}"
373
440
  ```
374
441
 
442
+ `to_return_json` encodes the body and sets the `Content-Type` header to `application/json`, so there is no need to call `to_json` or set the header yourself. A `Content-Type` given in `headers` takes precedence.
443
+
375
444
  A `File` or `Pathname` body is returned as it is, so it should hold JSON that is already encoded:
376
445
 
377
446
  ```ruby
@@ -650,6 +719,26 @@ RestClient.get('bbc.com', '/') # ===> Allowed
650
719
  RestClient.get('www.bbc.com', '/') # ===> Failure
651
720
  ```
652
721
 
722
+ ### Real requests can be allowed or disabled only within a block
723
+
724
+ 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.
725
+
726
+ ```ruby
727
+ WebMock.disable_net_connect!
728
+
729
+ WebMock.allow_net_connect! do
730
+ Net::HTTP.get('www.something.com', '/') # ===> /.+Something.+/
731
+ end
732
+
733
+ WebMock.disable_net_connect!(allow: 'www.example.org') do
734
+ RestClient.get('www.example.org', '/') # ===> Allowed
735
+ end
736
+
737
+ Net::HTTP.get('www.something.com', '/') # ===> Failure
738
+ ```
739
+
740
+ 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.
741
+
653
742
  ## Connecting on Net::HTTP.start
654
743
 
655
744
  HTTP protocol has 3 steps: connect, request and response (or 4 with close). Most Ruby HTTP client libraries
@@ -726,6 +815,8 @@ assert_requested(stub_get)
726
815
  assert_not_requested(stub_post)
727
816
  ```
728
817
 
818
+ See [What an expectation on a stub counts](#what-an-expectation-on-a-stub-counts) for which requests these assertions count.
819
+
729
820
 
730
821
  ### Setting expectations in RSpec on `WebMock` module
731
822
  This style is borrowed from [fakeweb-matcher](http://github.com/pat/fakeweb-matcher)
@@ -802,6 +893,24 @@ expect(stub).to have_been_requested.once.with(body: {"a" => [4, 5, 6]})
802
893
 
803
894
  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
895
 
896
+ ### What an expectation on a stub counts
897
+
898
+ 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`.
899
+
900
+ ```ruby
901
+ stub_any = stub_request(:post, "www.example.com")
902
+ stub_body = stub_request(:post, "www.example.com").with(body: "abc")
903
+
904
+ Net::HTTP.post(URI("http://www.example.com"), "abc") # answered by stub_body
905
+
906
+ expect(stub_body).to have_been_requested.once # ===> Success
907
+ expect(stub_any).to have_been_requested.once # ===> Success, as its pattern matches too
908
+ ```
909
+
910
+ 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!`.
911
+
912
+ 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).
913
+
805
914
  ### Inspecting the requests made
806
915
 
807
916
  `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.
@@ -828,14 +937,15 @@ A few things to know:
828
937
 
829
938
  * 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
939
  * 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`.
940
+ * 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`.
832
941
  * 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.
942
+ * 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.
943
+ * 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.
834
944
  * Depending on the HTTP client, requests that WebMock blocked because real connections are disabled may be listed too.
835
945
 
836
946
  ## Clearing stubs and request history
837
947
 
838
- If you want to reset all current stubs and history of requests use `WebMock.reset!`
948
+ If you want to reset all current stubs and history of requests use `WebMock.reset!`. [Global stubs](#global-stubs) stay.
839
949
 
840
950
  ```ruby
841
951
  stub_request(:any, "www.example.com")
@@ -871,6 +981,28 @@ expect(stub).not_to have_been_requested
871
981
  expect(stub2).not_to have_been_requested
872
982
  ```
873
983
 
984
+ ## Global stubs
985
+
986
+ `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:
987
+
988
+ ```ruby
989
+ WebMock.globally_stub_request do |request|
990
+ { status: 200, body: "{}" } if request.uri.host == "metrics.example.com"
991
+ end
992
+ ```
993
+
994
+ 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)`.
995
+
996
+ 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`:
997
+
998
+ ```ruby
999
+ WebMock.globally_stub_request(:after_local_stubs) do |request|
1000
+ { status: 200, body: "{}" } if request.uri.host == "metrics.example.com"
1001
+ end
1002
+ ```
1003
+
1004
+ Requests answered by a global stub are recorded like any other, so `a_request`, `assert_requested` and `executed_requests` include them.
1005
+
874
1006
  ## Disabling and enabling WebMock or only some http client adapters
875
1007
 
876
1008
  ```ruby
@@ -908,6 +1040,8 @@ stub_request(:get, "www.example.com").to_return(body: "def")
908
1040
  Net::HTTP.get('www.example.com', '/') # ====> "def"
909
1041
  ```
910
1042
 
1043
+ [Global stubs](#global-stubs) are checked before these stubs, or after them when declared with `:after_local_stubs`.
1044
+
911
1045
  ## Matching URIs
912
1046
 
913
1047
  WebMock will match all different representations of the same URI.
@@ -1012,6 +1146,16 @@ WebMock.after_request(except: [:patron],
1012
1146
  end
1013
1147
  ```
1014
1148
 
1149
+ #### Removing callbacks
1150
+
1151
+ Callbacks stay registered after `WebMock.reset!`, so a callback added in one test keeps running in later ones. To remove all callbacks, call:
1152
+
1153
+ ```ruby
1154
+ WebMock.reset_callbacks
1155
+ ```
1156
+
1157
+ This also removes callbacks registered by other libraries, such as VCR, so prefer registering your callbacks once, for example in your test helper.
1158
+
1015
1159
  ## Bugs and Issues
1016
1160
 
1017
1161
  Please submit them here [http://github.com/bblimke/webmock/issues](http://github.com/bblimke/webmock/issues)
@@ -1342,6 +1486,7 @@ People who submitted patches and new features or suggested improvements. Many th
1342
1486
  * Yang Bai
1343
1487
  * Hamza Tarar
1344
1488
  * John Gallagher
1489
+ * Yegor Bugayenko
1345
1490
 
1346
1491
  For a full list of contributors you can visit the
1347
1492
  [contributors](https://github.com/bblimke/webmock/contributors) page.
@@ -10,7 +10,7 @@ module WebMock
10
10
  request_signature_snippet.stubbing_instructions,
11
11
  request_signature_snippet.request_stubs,
12
12
  "="*60
13
- ].compact.join("\n\n")
13
+ ].compact.map { |part| Util::MessageString.utf8(part) }.join("\n\n")
14
14
  super(text)
15
15
  end
16
16
 
@@ -103,6 +103,23 @@ if defined?(Async::HTTP)
103
103
  @webmock_client.close
104
104
  end
105
105
 
106
+ # Some libraries, such as async-websocket, take a connection from the
107
+ # pool instead of calling #call. WebMock can't see or stub what they
108
+ # send, so hand out the real pool only when WebMock's own settings
109
+ # allow real connections to the host the pool connects to: the
110
+ # endpoint's, whatever authority the requests name, with a ws or wss
111
+ # endpoint checked as http or https. VCR can't record or replay such
112
+ # connections, so it can't allow them.
113
+ def pool
114
+ host = @endpoint.hostname
115
+ host = "[#{host}]" if host.include?(":") && !host.start_with?("[")
116
+ uri = Addressable::URI.new(scheme: @endpoint.secure? ? "https" : "http", host: host, port: @endpoint.port, path: "/")
117
+ unless WebMock.net_connect_allowed_by_settings?(uri)
118
+ raise WebMock::NetConnectNotAllowedError.new(WebMock::RequestSignature.new(:get, uri))
119
+ end
120
+ @network_client.pool
121
+ end
122
+
106
123
  private
107
124
 
108
125
  def build_request_signature(request)
@@ -200,10 +200,14 @@ if defined?(Curl)
200
200
  @on_debug.call(@header_str, 1) if defined?( @on_debug )
201
201
 
202
202
  if webmock_response.headers
203
- @header_str << webmock_response.headers.map do |k,v|
204
- header = "#{k}: #{v.is_a?(Array) ? v.join(", ") : v}"
205
- @on_debug.call(header + "\r\n", 1) if defined?( @on_debug )
206
- header
203
+ # Each cookie gets a line of its own, as servers send them.
204
+ @header_str << webmock_response.headers.flat_map do |k,v|
205
+ values = k == "Set-Cookie" ? Array(v) : [v.is_a?(Array) ? v.join(", ") : v]
206
+ values.map do |value|
207
+ header = "#{k}: #{value}"
208
+ @on_debug.call(header + "\r\n", 1) if defined?( @on_debug )
209
+ header
210
+ end
207
211
  end.join("\r\n")
208
212
  @on_debug.call("\r\n", 1) if defined?( @on_debug )
209
213
 
@@ -84,6 +84,10 @@ if defined?(EventMachine::HttpClient)
84
84
 
85
85
  class WebMockHttpClient < EventMachine::HttpClient
86
86
  include HttpEncoding
87
+ # A YAML or Marshal dump names the cookie jar EventMachine::HttpClient::CookieJar,
88
+ # which is this class while WebMock is enabled, and loading a dump looks
89
+ # the constant up without the superclass.
90
+ CookieJar = superclass.const_get(:CookieJar, false) if superclass.const_defined?(:CookieJar, false)
87
91
 
88
92
  def uri
89
93
  @req.uri
@@ -129,18 +129,39 @@ if defined?(Excon)
129
129
  def self.real_response(mock)
130
130
  raise Excon::Errors::Timeout if mock.should_timeout
131
131
  mock.raise_error_if_any
132
+ headers = mock.headers || {}
133
+ # Copies, so changes to a response's cookies can't reach the stub.
134
+ cookies = Array(headers["Set-Cookie"]).map(&:dup)
135
+ # Excon joins repeated headers, and lists each cookie in :cookies.
136
+ headers = headers.merge("Set-Cookie" => join_cookies(cookies)) if cookies.size > 1
132
137
  {
133
138
  body: mock.body,
134
139
  status: mock.status[0].to_i,
135
140
  reason_phrase: mock.status[1],
136
- headers: mock.headers || {}
141
+ headers: headers,
142
+ cookies: cookies
137
143
  }
138
144
  end
139
145
 
146
+ # Joined as Excon joins them, or as bytes when they are in
147
+ # incompatible encodings, as a server sends them.
148
+ def self.join_cookies(cookies)
149
+ cookies.join(", ")
150
+ rescue Encoding::CompatibilityError
151
+ cookies.map(&:b).join(", ".b)
152
+ end
153
+
140
154
  def self.mock_response(real)
141
155
  mock = WebMock::Response.new
142
156
  mock.status = [real.status, real.reason_phrase]
143
157
  mock.headers = real.headers
158
+ # Excon joins the cookies of a response in its header, so callbacks,
159
+ # such as VCR's, get each one from the list Excon keeps.
160
+ # Copies, so a callback that changes one doesn't change the response.
161
+ cookies = real.data[:cookies]
162
+ if cookies && cookies.size > 1
163
+ mock.headers = real.headers.to_h.reject { |name, _| name.casecmp?("Set-Cookie") }.merge("Set-Cookie" => cookies.map(&:dup))
164
+ end
144
165
  mock.body = real.body.dup
145
166
  mock
146
167
  end
@@ -37,14 +37,43 @@ module HTTP
37
37
 
38
38
  return unless webmock_response
39
39
 
40
- raise_timeout_error if webmock_response.should_timeout
41
- webmock_response.raise_error_if_any
40
+ features = @options.features.values
41
+ response = nil
42
+ exchange = ->(_request) { response = replay_response(features, webmock_response) }
43
+ # HTTP.rb 6 instruments a request in around_request, inside the
44
+ # HTTP::Client#perform a stub skips, so the instrumentation runs around
45
+ # a stubbed exchange too. Other features that run around the exchange,
46
+ # such as caching and digest_auth, don't run for a stub. The stub's
47
+ # response is returned whatever an instrumenter returns, and also when
48
+ # one doesn't yield, as before.
49
+ instrumentation(features).reverse.reduce(exchange) do |inner, feature|
50
+ ->(request) { feature.around_request(request) { |r| inner.call(r) } }
51
+ end.call(@request)
52
+ response || replay_response(features, webmock_response)
53
+ end
54
+
55
+ def instrumentation(features)
56
+ return [] unless defined?(::HTTP::Features::Instrumentation) && ::HTTP::Feature.method_defined?(:around_request)
57
+
58
+ features.select { |feature| feature.is_a?(::HTTP::Features::Instrumentation) }
59
+ end
60
+
61
+ def replay_response(features, webmock_response)
62
+ # HTTP::Client calls on_error for an error while sending, which for a
63
+ # stub is its timeout or error, but not for one raised while wrapping
64
+ # the response, as the raise_error feature does for a 500.
65
+ begin
66
+ raise_timeout_error if webmock_response.should_timeout
67
+ webmock_response.raise_error_if_any
68
+ rescue ::HTTP::Error => e
69
+ features.each { |feature| feature.on_error(@request, e) if feature.respond_to?(:on_error) }
70
+ raise
71
+ end
42
72
 
43
73
  invoke_callbacks(webmock_response, real_request: false)
44
74
  response = ::HTTP::Response.from_webmock @request, webmock_response, request_signature
45
75
 
46
76
  # HTTP.rb 6.0+ wraps responses in reverse feature order
47
- features = @options.features.values
48
77
  features = features.reverse if HTTP::VERSION >= "6.0.0"
49
78
  features.each { |feature| response = feature.wrap_response(response) }
50
79
  response
@@ -106,10 +106,12 @@ if defined?(::HTTPClient)
106
106
  if webmock_response
107
107
  response = build_httpclient_response(webmock_response, false, req.header, &block)
108
108
  filters.each { |filter| filter.filter_response(req, response) }
109
- res = conn.push(response)
109
+ conn.push(response)
110
110
  WebMock::CallbackRegistry.invoke_callbacks(
111
111
  {lib: :httpclient}, request_signature, webmock_response)
112
- res
112
+ # Return the response, as HTTPClient#do_get_block does. Libraries that
113
+ # wrap the method to trace requests read its result.
114
+ response
113
115
  elsif WebMock.net_connect_allowed?(request_signature.uri)
114
116
  clone(freeze: false).send_prepared_sync_request(req, proxy, conn, filters, request_signature, &block)
115
117
  else