webmock 3.32.0 → 3.34.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: d20abb34dbaefa2fb02ae23a25f33f0762415ead54721033fd7c9ea53a399a9a
4
- data.tar.gz: 8160f5688d2afa4bd0bf8671ddbf05be797ab7c064a03af7fa7386de7baf424e
3
+ metadata.gz: b66b694440da9739d8d23ccd8a260260739199235f076f4854387f7029c0c976
4
+ data.tar.gz: 96abe5bbe31e475bcec618aff66d43ac724b7cf15b08883ae864d62cac826e7c
5
5
  SHA512:
6
- metadata.gz: 5fee3bec940d62b056f45cda8e62fab7839bb3d376f4db0b7db64b8a2e2a32ebe48d31b31a84f3c1e8a0662f9e9dd4aa924c44ef4e69a4eb6f63d40a8909c2aa
7
- data.tar.gz: 38bae4b2800d672db58e5677d40288d5d0d9323414171056bcd19b56ab04432b6a2e64e1c99a600ca8ff5da86bbac29c588eefc3e2705cb792b549bb17b94a5b
6
+ metadata.gz: 99395c27d7c6c270f37309e69da7f3688c43b8f158327d23b62b9829b3fff7a667280542017c71f18e2b822de6639394b2aeaa078aae7b7c67d7fd497363e918
7
+ data.tar.gz: 9378a048d2a03b1309eff3b5264ddca35e4f9268399a92e98147fa0e2d60e376d31ca2f1ccaca912f6d7ca859268b1d9ce173530e885c5055b99f3c2632bfd46
data/CHANGELOG.md CHANGED
@@ -1,5 +1,71 @@
1
1
  # Changelog
2
2
 
3
+ # 3.34.0
4
+
5
+ * Allow `with(query: :any)` to match any query string (#1099)
6
+
7
+ `stub_request(:get, "www.example.com").with(query: :any)` matches requests with any query string, or none. RSpec's `anything` works the same way. Previously, this raised `NoMethodError`, and you had to write `with(query: hash_including({}))`.
8
+
9
+ Use a URL without query parameters when passing `query: :any`. Otherwise, WebMock raises `ArgumentError`.
10
+
11
+ Thanks to [nightpool](https://github.com/nightpool)
12
+
13
+ * Raise a clear `ArgumentError` for an unsupported `query` option
14
+
15
+ Previously, a value such as `with(query: :all)` raised `NoMethodError` (undefined method `split`). The new error lists the supported values.
16
+
17
+ * Show `anything` for keys given without a value to `hash_including` or `hash_excluding` outside RSpec
18
+
19
+ Previously, with Minitest or Test::Unit, messages showed `#<WebMock::Matchers::AnyArgMatcher:0x...>`, for example for `with(query: hash_including(:a))`. RSpec's own matchers already showed `anything`.
20
+
21
+ * Provide `HTTP_HOST` to `to_rack` apps when the client has not supplied a Host header (#1084)
22
+
23
+ Previously, requests from some HTTP clients reached the Rack app without `HTTP_HOST`. This caused host checks such as Sinatra's `HostAuthorization` to see an empty host.
24
+
25
+ WebMock now fills in the host from the request URL, including the port when it is not the default. An explicit Host header is preserved.
26
+
27
+ Thanks to [Benoit Tigeot](https://github.com/benoittgt)
28
+
29
+ * Fix Rack compatibility for `to_rack` apps
30
+
31
+ The request environment now passes `Rack::Lint`.
32
+
33
+ `SERVER_PORT` and `CONTENT_LENGTH` are now strings. If your app or tests read them directly, use string comparisons, such as `env['SERVER_PORT'] == "80"`. The environment also includes `SERVER_PROTOCOL`.
34
+
35
+ `CONTENT_TYPE` is omitted when the request has no content type. The `Content-Length` header is passed only as `CONTENT_LENGTH`, without an extra `HTTP_CONTENT_LENGTH` entry. `Transfer-Encoding` is removed because the body has already been decoded.
36
+
37
+ Repeated header values are joined into one string. Header values and the body read from `rack.input` now use binary (`ASCII-8BIT`) strings.
38
+
39
+ # 3.33.0
40
+
41
+ * Return `effective_url` as a String for stubbed Typhoeus responses (#869)
42
+
43
+ Previously, this was an `Addressable::URI`. If your code calls methods such as `effective_url.host`, parse the returned string into a URI first.
44
+
45
+ The URL keeps the request's port, query order and encoding. It follows curl's formatting: for example, `http://example.com:80` becomes `http://example.com:80/`. Stubbed timeouts now provide an `effective_url` too.
46
+
47
+ Thanks to [Tom Brammar](https://github.com/tbrammar)
48
+
49
+ * Fix incorrect removal of default ports from displayed URLs
50
+
51
+ WebMock could accidentally remove `:80` or `:443` from a URL's path or query. For example, an error message could show `/foo/bar` instead of `/foo:80/bar`.
52
+
53
+ Only the host's default port is now removed. This also works when the port is immediately followed by a query string, as in `http://example.com:80?a=b`.
54
+
55
+ * Set `return_code` to `:ok` for completed stubbed Typhoeus requests (#736)
56
+
57
+ `return_code` is now `:ok` and `return_message` is now `"No error"`; both were previously `nil`. This includes HTTP error responses such as 404: `:ok` means the transfer completed. Stubbed timeouts still return `:operation_timedout`.
58
+
59
+ Thanks to [Michael Spiz](https://github.com/spizm)
60
+
61
+ * Fix the raw headers returned by stubbed Typhoeus responses
62
+
63
+ The `response_headers` string now uses the stubbed HTTP status. For example, a 404 stub no longer reports `HTTP/1.1 200 OK`.
64
+
65
+ Stubs without headers now return an empty `headers` hash (`{}`) instead of `nil`. Their `response_headers` contains the status line instead of being `nil`.
66
+
67
+ The raw headers use binary string encoding, matching real responses. For timeouts, `response_headers` is now an empty string.
68
+
3
69
  # 3.32.0
4
70
 
5
71
  * Make a `Net::HTTP` object created while WebMock was enabled behave like any other `Net::HTTP` object after `WebMock.disable!` (#1067)
data/README.md CHANGED
@@ -299,6 +299,15 @@ Net::HTTP.get('www.example.com',
299
299
  '/thing/5.json?x=1&y=2&z=3&anyParam=4') # ===> Success
300
300
  ```
301
301
 
302
+ ### Matching any query params
303
+
304
+ ```ruby
305
+ stub_request(:get, "www.example.com").with(query: :any)
306
+
307
+ RestClient.get("http://www.example.com/?q=example") # ===> Success
308
+ RestClient.get("http://www.example.com/") # ===> Success
309
+ ```
310
+
302
311
  ### Matching query params using hash
303
312
 
304
313
  ```ruby
@@ -52,8 +52,8 @@ if defined?(Typhoeus)
52
52
  Typhoeus.on_complete.delete_if {|v| v == AFTER_REQUEST_CALLBACK }
53
53
  end
54
54
 
55
- def self.build_request_signature(req)
56
- uri = WebMock::Util::URI.heuristic_parse(req.url)
55
+ def self.build_request_signature(req, url = req.url)
56
+ uri = WebMock::Util::URI.heuristic_parse(url)
57
57
  uri.path = uri.normalized_path.gsub("[^:]//","/")
58
58
 
59
59
  headers = req.options[:headers]
@@ -89,42 +89,69 @@ if defined?(Typhoeus)
89
89
  webmock_response
90
90
  end
91
91
 
92
- def self.generate_typhoeus_response(request_signature, webmock_response)
93
- response = if webmock_response.should_timeout
94
- ::Typhoeus::Response.new(
92
+ def self.generate_typhoeus_response(webmock_response, url)
93
+ response_options = if webmock_response.should_timeout
94
+ {
95
95
  code: 0,
96
96
  status_message: "",
97
97
  body: "",
98
98
  headers: {},
99
99
  return_code: :operation_timedout,
100
- total_time: 0.0,
101
- starttransfer_time: 0.0,
102
- appconnect_time: 0.0,
103
- pretransfer_time: 0.0,
104
- connect_time: 0.0,
105
- namelookup_time: 0.0,
106
- redirect_time: 0.0
107
- )
100
+ response_headers: ""
101
+ }
108
102
  else
109
- ::Typhoeus::Response.new(
103
+ {
110
104
  code: webmock_response.status[0],
111
105
  status_message: webmock_response.status[1],
112
106
  body: webmock_response.body,
113
107
  headers: webmock_response.headers,
114
- effective_url: request_signature.uri,
115
- total_time: 0.0,
116
- starttransfer_time: 0.0,
117
- appconnect_time: 0.0,
118
- pretransfer_time: 0.0,
119
- connect_time: 0.0,
120
- namelookup_time: 0.0,
121
- redirect_time: 0.0
122
- )
108
+ return_code: :ok,
109
+ response_headers: response_headers_string(webmock_response)
110
+ }
123
111
  end
112
+ response = ::Typhoeus::Response.new(response_options.merge(
113
+ effective_url: effective_url(url),
114
+ total_time: 0.0,
115
+ starttransfer_time: 0.0,
116
+ appconnect_time: 0.0,
117
+ pretransfer_time: 0.0,
118
+ connect_time: 0.0,
119
+ namelookup_time: 0.0,
120
+ redirect_time: 0.0
121
+ ))
124
122
  response.mock = :webmock
125
123
  response
126
124
  end
127
125
 
126
+ # Without response_headers, Typhoeus builds them for a mocked response
127
+ # from its return_code, as in "HTTP/1.1 ok Mock Reason Phrase".
128
+ def self.response_headers_string(webmock_response)
129
+ code, reason = webmock_response.status
130
+ lines = ["HTTP/1.1 #{code} #{reason}"]
131
+ (webmock_response.headers || {}).each do |name, values|
132
+ Array(values).each { |value| lines << "#{name}: #{value}" }
133
+ end
134
+ # Bytes, as in a real response, so values in different encodings join.
135
+ lines.map(&:b).join("\r\n") + "\r\n\r\n"
136
+ end
137
+
138
+ # The request URL as curl reports it: with its port, query and encoding as
139
+ # given, but with a lower case scheme, http:// when there is none, dot
140
+ # segments resolved, "/" for an empty path and no empty query or
141
+ # fragment. Like curl's, it is a binary string.
142
+ def self.effective_url(url)
143
+ # A scheme needs at least one slash after it, so localhost:3000 has
144
+ # none. heuristic_parse turns http:/ and http:/// into http://.
145
+ url = "http://#{url}" unless url.match?(%r{\A[a-z][a-z0-9+.\-]*:/}i)
146
+ uri = WebMock::Util::URI.heuristic_parse(url)
147
+ uri.scheme = uri.scheme.downcase
148
+ uri.path = Addressable::URI.normalize_path(uri.path)
149
+ uri.path = "/" if uri.path.empty?
150
+ uri.query = nil if uri.query == ""
151
+ uri.fragment = nil if uri.fragment == ""
152
+ uri.to_s.b
153
+ end
154
+
128
155
  def self.request_hash(request_signature)
129
156
  hash = {}
130
157
 
@@ -160,14 +187,15 @@ if defined?(Typhoeus)
160
187
  res = true
161
188
 
162
189
  unless WebMock::HttpLibAdapters::TyphoeusAdapter.disabled?
163
- request_signature = ::WebMock::HttpLibAdapters::TyphoeusAdapter.build_request_signature(request)
190
+ # Typhoeus builds a curl handle to work out the URL, so do it once.
191
+ url = request.url
192
+ request_signature = ::WebMock::HttpLibAdapters::TyphoeusAdapter.build_request_signature(request, url)
164
193
  request.block_connection = false;
165
194
 
166
195
  ::WebMock::RequestRegistry.instance.requested_signatures.put(request_signature)
167
196
 
168
197
  if webmock_response = ::WebMock::StubRegistry.instance.response_for_request(request_signature)
169
- # ::WebMock::HttpLibAdapters::TyphoeusAdapter.stub_typhoeus(request_signature, webmock_response, self)
170
- response = ::WebMock::HttpLibAdapters::TyphoeusAdapter.generate_typhoeus_response(request_signature, webmock_response)
198
+ response = ::WebMock::HttpLibAdapters::TyphoeusAdapter.generate_typhoeus_response(webmock_response, url)
171
199
  if request.respond_to?(:on_headers)
172
200
  request.execute_headers_callbacks(response)
173
201
  end
@@ -10,6 +10,10 @@ module WebMock
10
10
  def ==(other)
11
11
  true
12
12
  end
13
+
14
+ def inspect
15
+ "anything"
16
+ end
13
17
  end
14
18
  end
15
19
  end
@@ -27,37 +27,56 @@ module WebMock
27
27
 
28
28
  def build_rack_env(request)
29
29
  uri = request.uri
30
+ port = uri.inferred_port
30
31
  headers = (request.headers || {}).dup
31
- body = request.body || ''
32
+ body = (request.body || '').b
33
+ content_type = headers.delete('Content-Type')
34
+ headers.delete('Content-Length')
35
+ # The body is already decoded, as a server passes it on.
36
+ headers.delete('Transfer-Encoding')
32
37
 
33
38
  env = {
34
39
  # CGI variables specified by Rack
35
- 'REQUEST_METHOD' => request.method.to_s.upcase,
36
- 'CONTENT_TYPE' => headers.delete('Content-Type'),
37
- 'CONTENT_LENGTH' => body.bytesize,
38
- 'PATH_INFO' => uri.path,
39
- 'QUERY_STRING' => uri.query || '',
40
- 'SERVER_NAME' => uri.host,
41
- 'SERVER_PORT' => uri.port,
42
- 'SCRIPT_NAME' => ""
40
+ 'REQUEST_METHOD' => request.method.to_s.upcase,
41
+ 'CONTENT_LENGTH' => body.bytesize.to_s,
42
+ 'PATH_INFO' => uri.path,
43
+ 'QUERY_STRING' => uri.query || '',
44
+ 'SERVER_NAME' => uri.host,
45
+ 'SERVER_PORT' => port.to_s,
46
+ 'SERVER_PROTOCOL' => 'HTTP/1.1',
47
+ 'SCRIPT_NAME' => ""
43
48
  }
49
+ env['CONTENT_TYPE'] = header_value('Content-Type', content_type) if content_type
44
50
 
45
51
  env['HTTP_AUTHORIZATION'] = 'Basic ' + [uri.userinfo].pack('m').delete("\r\n") if uri.userinfo
46
52
 
47
53
  # Rack-specific variables
48
54
  env['rack.input'] = StringIO.new(body)
49
55
  env['rack.errors'] = $stderr
50
- if !Rack.const_defined?(:RELEASE) || Rack::RELEASE < "3"
51
- env['rack.version'] = Rack::VERSION
56
+ if !Rack.const_defined?(:RELEASE) || Gem::Version.new(Rack::RELEASE) < Gem::Version.new("3")
57
+ env['rack.version'] = Rack::VERSION
58
+ env['rack.multithread'] = false
59
+ env['rack.multiprocess'] = false
52
60
  end
53
61
  env['rack.url_scheme'] = uri.scheme
54
62
  env['rack.run_once'] = true
55
63
 
56
64
  headers.each do |k, v|
57
- env["HTTP_#{k.tr('-','_').upcase}"] = v
65
+ env["HTTP_#{k.tr('-','_').upcase}"] = header_value(k, v)
58
66
  end
59
67
 
68
+ # Many clients add Host only when sending, so fill it in as they would.
69
+ env['HTTP_HOST'] ||= port == uri.default_port ? uri.host : "#{uri.host}:#{port}"
70
+
60
71
  env
61
72
  end
73
+
74
+ private
75
+
76
+ # Like a server, pass header values as bytes and join repeated ones. Rack
77
+ # splits cookies on "; ", so join those that way.
78
+ def header_value(name, value)
79
+ Array(value).map { |v| v.to_s.b }.join(name == 'Cookie' ? '; ' : WebMock::Util::Headers::JOIN)
80
+ end
62
81
  end
63
82
  end
@@ -10,6 +10,10 @@ module WebMock
10
10
  def rSpecHashExcludingMatcher?(matcher)
11
11
  matcher.class.name =~ /R?Spec::Mocks::ArgumentMatchers::HashExcludingMatcher/
12
12
  end
13
+
14
+ def rSpecAnyArgMatcher?(matcher)
15
+ matcher.class.name =~ /R?Spec::Mocks::ArgumentMatchers::AnyArgMatcher/
16
+ end
13
17
  end
14
18
 
15
19
  class RequestPattern
@@ -129,6 +133,10 @@ module WebMock
129
133
  def add_query_params(query_params)
130
134
  @query_params = if query_params.is_a?(Hash)
131
135
  query_params
136
+ elsif query_params.equal?(:any) \
137
+ || query_params.is_a?(WebMock::Matchers::AnyArgMatcher) \
138
+ || rSpecAnyArgMatcher?(query_params)
139
+ WebMock::Matchers::AnyArgMatcher.new(nil)
132
140
  elsif query_params.is_a?(WebMock::Matchers::HashIncludingMatcher) \
133
141
  || query_params.is_a?(WebMock::Matchers::HashExcludingMatcher)
134
142
  query_params
@@ -136,8 +144,10 @@ module WebMock
136
144
  WebMock::Matchers::HashIncludingMatcher.from_rspec_matcher(query_params)
137
145
  elsif rSpecHashExcludingMatcher?(query_params)
138
146
  WebMock::Matchers::HashExcludingMatcher.from_rspec_matcher(query_params)
139
- else
147
+ elsif query_params.nil? || query_params.is_a?(String)
140
148
  WebMock::Util::QueryMapper.query_to_values(query_params, notation: Config.instance.query_values_notation)
149
+ else
150
+ raise ArgumentError, "Query should be a String, Hash, :any, nil, or a hash_including or hash_excluding matcher. Got: #{query_params.class}"
141
151
  end
142
152
  end
143
153
 
@@ -153,6 +163,10 @@ module WebMock
153
163
 
154
164
  private
155
165
 
166
+ def raise_any_query_with_uri_query
167
+ raise ArgumentError, "query: :any can't be combined with a query in the URI #{pattern_inspect}, because no request would match. Remove the query from the URI."
168
+ end
169
+
156
170
  def pattern_inspect
157
171
  @pattern.inspect
158
172
  end
@@ -180,12 +194,17 @@ module WebMock
180
194
 
181
195
  class URIAddressablePattern < URIPattern
182
196
  def add_query_params(query_params)
197
+ super(query_params)
198
+ # With query params, the template is matched against the URI without its
199
+ # query, so a literal query in the template can never match.
200
+ if @query_params.is_a?(WebMock::Matchers::AnyArgMatcher) && @pattern.pattern.gsub(/\{[^}]*\}/, '').include?('?')
201
+ raise_any_query_with_uri_query
202
+ end
183
203
  @@add_query_params_warned ||= false
184
204
  if not @@add_query_params_warned
185
205
  @@add_query_params_warned = true
186
206
  warn "WebMock warning: ignoring query params in RFC 6570 template and checking them with WebMock"
187
207
  end
188
- super(query_params)
189
208
  end
190
209
 
191
210
  private
@@ -230,6 +249,9 @@ module WebMock
230
249
  query_hash = (WebMock::Util::QueryMapper.query_to_values(@pattern.query, notation: Config.instance.query_values_notation) || {}).merge(@query_params)
231
250
  @pattern.query = WebMock::Util::QueryMapper.values_to_query(query_hash, notation: WebMock::Config.instance.query_values_notation)
232
251
  @query_params = nil
252
+ elsif @query_params.is_a?(WebMock::Matchers::AnyArgMatcher) && @pattern.query
253
+ # The URI is then compared without its query, so it could never match.
254
+ raise_any_query_with_uri_query
233
255
  end
234
256
  end
235
257
 
@@ -58,8 +58,8 @@ module WebMock
58
58
 
59
59
  def self.strip_default_port_from_uri_string(uri_string)
60
60
  case uri_string
61
- when %r{^http://} then uri_string.sub(%r{:80(/|$)}, '\1')
62
- when %r{^https://} then uri_string.sub(%r{:443(/|$)}, '\1')
61
+ when %r{^http://} then uri_string.sub(%r{\A(http://[^/?#]+):80(?=[/?#]|\z)}, '\1')
62
+ when %r{^https://} then uri_string.sub(%r{\A(https://[^/?#]+):443(?=[/?#]|\z)}, '\1')
63
63
  else uri_string
64
64
  end
65
65
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module WebMock
4
- VERSION = '3.32.0' unless defined?(::WebMock::VERSION)
4
+ VERSION = '3.34.0' unless defined?(::WebMock::VERSION)
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: webmock
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.32.0
4
+ version: 3.34.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Bartosz Blimke
@@ -360,9 +360,9 @@ licenses:
360
360
  - MIT
361
361
  metadata:
362
362
  bug_tracker_uri: https://github.com/bblimke/webmock/issues
363
- changelog_uri: https://github.com/bblimke/webmock/blob/v3.32.0/CHANGELOG.md
364
- documentation_uri: https://www.rubydoc.info/gems/webmock/3.32.0
365
- source_code_uri: https://github.com/bblimke/webmock/tree/v3.32.0
363
+ changelog_uri: https://github.com/bblimke/webmock/blob/v3.34.0/CHANGELOG.md
364
+ documentation_uri: https://www.rubydoc.info/gems/webmock/3.34.0
365
+ source_code_uri: https://github.com/bblimke/webmock/tree/v3.34.0
366
366
  wiki_uri: https://github.com/bblimke/webmock/wiki
367
367
  rdoc_options: []
368
368
  require_paths: