faraday 0.13.0 → 2.0.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 +5 -5
- data/CHANGELOG.md +496 -0
- data/LICENSE.md +1 -1
- data/README.md +28 -328
- data/Rakefile +7 -0
- data/examples/client_spec.rb +97 -0
- data/examples/client_test.rb +118 -0
- data/lib/faraday/adapter/test.rb +127 -68
- data/lib/faraday/adapter.rb +71 -22
- data/lib/faraday/adapter_registry.rb +30 -0
- data/lib/faraday/connection.rb +314 -226
- data/lib/faraday/encoders/flat_params_encoder.rb +105 -0
- data/lib/faraday/encoders/nested_params_encoder.rb +176 -0
- data/lib/faraday/error.rb +121 -37
- data/lib/faraday/logging/formatter.rb +106 -0
- data/lib/faraday/methods.rb +6 -0
- data/lib/faraday/middleware.rb +18 -25
- data/lib/faraday/middleware_registry.rb +65 -0
- data/lib/faraday/options/connection_options.rb +22 -0
- data/lib/faraday/options/env.rb +181 -0
- data/lib/faraday/options/proxy_options.rb +32 -0
- data/lib/faraday/options/request_options.rb +22 -0
- data/lib/faraday/options/ssl_options.rb +59 -0
- data/lib/faraday/options.rb +41 -195
- data/lib/faraday/parameters.rb +4 -196
- data/lib/faraday/rack_builder.rb +91 -74
- data/lib/faraday/request/authorization.rb +37 -29
- data/lib/faraday/request/instrumentation.rb +47 -27
- data/lib/faraday/request/json.rb +55 -0
- data/lib/faraday/request/url_encoded.rb +45 -23
- data/lib/faraday/request.rb +74 -32
- data/lib/faraday/response/json.rb +54 -0
- data/lib/faraday/response/logger.rb +22 -69
- data/lib/faraday/response/raise_error.rb +57 -14
- data/lib/faraday/response.rb +26 -33
- data/lib/faraday/utils/headers.rb +139 -0
- data/lib/faraday/utils/params_hash.rb +61 -0
- data/lib/faraday/utils.rb +47 -251
- data/lib/faraday/version.rb +5 -0
- data/lib/faraday.rb +104 -197
- data/spec/external_adapters/faraday_specs_setup.rb +14 -0
- data/spec/faraday/adapter/test_spec.rb +377 -0
- data/spec/faraday/adapter_registry_spec.rb +28 -0
- data/spec/faraday/adapter_spec.rb +55 -0
- data/spec/faraday/connection_spec.rb +787 -0
- data/spec/faraday/error_spec.rb +60 -0
- data/spec/faraday/middleware_spec.rb +52 -0
- data/spec/faraday/options/env_spec.rb +70 -0
- data/spec/faraday/options/options_spec.rb +297 -0
- data/spec/faraday/options/proxy_options_spec.rb +44 -0
- data/spec/faraday/options/request_options_spec.rb +19 -0
- data/spec/faraday/params_encoders/flat_spec.rb +42 -0
- data/spec/faraday/params_encoders/nested_spec.rb +142 -0
- data/spec/faraday/rack_builder_spec.rb +302 -0
- data/spec/faraday/request/authorization_spec.rb +83 -0
- data/spec/faraday/request/instrumentation_spec.rb +74 -0
- data/spec/faraday/request/json_spec.rb +111 -0
- data/spec/faraday/request/url_encoded_spec.rb +82 -0
- data/spec/faraday/request_spec.rb +109 -0
- data/spec/faraday/response/json_spec.rb +117 -0
- data/spec/faraday/response/logger_spec.rb +220 -0
- data/spec/faraday/response/raise_error_spec.rb +172 -0
- data/spec/faraday/response_spec.rb +75 -0
- data/spec/faraday/utils/headers_spec.rb +82 -0
- data/spec/faraday/utils_spec.rb +117 -0
- data/spec/faraday_spec.rb +37 -0
- data/spec/spec_helper.rb +132 -0
- data/spec/support/disabling_stub.rb +14 -0
- data/spec/support/fake_safe_buffer.rb +15 -0
- data/spec/support/helper_methods.rb +96 -0
- data/spec/support/shared_examples/adapter.rb +104 -0
- data/spec/support/shared_examples/params_encoder.rb +18 -0
- data/spec/support/shared_examples/request_method.rb +249 -0
- data/spec/support/streaming_response_checker.rb +35 -0
- metadata +71 -34
- data/lib/faraday/adapter/em_http.rb +0 -243
- data/lib/faraday/adapter/em_http_ssl_patch.rb +0 -56
- data/lib/faraday/adapter/em_synchrony/parallel_manager.rb +0 -66
- data/lib/faraday/adapter/em_synchrony.rb +0 -106
- data/lib/faraday/adapter/excon.rb +0 -80
- data/lib/faraday/adapter/httpclient.rb +0 -128
- data/lib/faraday/adapter/net_http.rb +0 -135
- data/lib/faraday/adapter/net_http_persistent.rb +0 -54
- data/lib/faraday/adapter/patron.rb +0 -83
- data/lib/faraday/adapter/rack.rb +0 -58
- data/lib/faraday/adapter/typhoeus.rb +0 -123
- data/lib/faraday/autoload.rb +0 -84
- data/lib/faraday/request/basic_authentication.rb +0 -13
- data/lib/faraday/request/multipart.rb +0 -68
- data/lib/faraday/request/retry.rb +0 -164
- data/lib/faraday/request/token_authentication.rb +0 -15
- data/lib/faraday/upload_io.rb +0 -67
data/README.md
CHANGED
@@ -1,333 +1,36 @@
|
|
1
|
-
# Faraday
|
1
|
+
# [][website]
|
2
2
|
|
3
3
|
[](https://rubygems.org/gems/faraday)
|
4
|
-
[](https://codeclimate.com/github/lostisland/faraday)
|
7
|
-
[](https://gitter.im/lostisland/faraday?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
|
4
|
+
[](https://github.com/lostisland/faraday/actions?query=workflow%3ACI)
|
5
|
+
[](https://github.com/lostisland/faraday/discussions)
|
8
6
|
|
9
7
|
|
10
|
-
Faraday is an HTTP client
|
11
|
-
adapters (such as Net::HTTP) and embraces the concept of Rack middleware when
|
12
|
-
|
8
|
+
Faraday is an HTTP client library abstraction layer that provides a common interface over many
|
9
|
+
adapters (such as Net::HTTP) and embraces the concept of Rack middleware when processing the request/response cycle.
|
10
|
+
You probably don't want to use Faraday directly in your project, as it will lack an actual client library to perform
|
11
|
+
requests. Instead, you probably want to have a look at [Awesome Faraday][awesome] for a list of available adapters.
|
13
12
|
|
14
|
-
|
13
|
+
## FARADAY 2.0
|
15
14
|
|
16
|
-
|
17
|
-
|
18
|
-
* [Excon][]
|
19
|
-
* [Patron][]
|
20
|
-
* [EventMachine][]
|
21
|
-
* [HTTPClient][]
|
15
|
+
You're reading the README and looking at the code of our upcoming v2.0 release (the `main` branch, currently in alpha).
|
16
|
+
If you're here to read about our latest v1.x release, then please head over to the [1.x branch](https://github.com/lostisland/faraday/tree/1.x).
|
22
17
|
|
23
|
-
|
24
|
-
Rack::Test, and a Test adapter for stubbing requests by hand.
|
18
|
+
## Getting Started
|
25
19
|
|
26
|
-
|
27
|
-
|
28
|
-
Available at [rubydoc.info](http://www.rubydoc.info/gems/faraday).
|
29
|
-
|
30
|
-
## Usage
|
31
|
-
|
32
|
-
### Basic Use
|
33
|
-
|
34
|
-
```ruby
|
35
|
-
response = Faraday.get 'http://sushi.com/nigiri/sake.json'
|
36
|
-
```
|
37
|
-
A simple `get` request can be performed by using the syntax described above. This works if you don't need to set up anything; you can roll with just the default middleware
|
38
|
-
stack and default adapter (see [Faraday::RackBuilder#initialize](https://github.com/lostisland/faraday/blob/master/lib/faraday/rack_builder.rb)).
|
39
|
-
|
40
|
-
A more flexible way to use Faraday is to start with a Connection object. If you want to keep the same defaults, you can use this syntax:
|
41
|
-
|
42
|
-
```ruby
|
43
|
-
conn = Faraday.new(:url => 'http://www.example.com')
|
44
|
-
response = conn.get '/users' # GET http://www.example.com/users'
|
45
|
-
```
|
46
|
-
|
47
|
-
Connections can also take an options hash as a parameter or be configured by using a block. Checkout the section called [Advanced middleware usage](#advanced-middleware-usage) for more details about how to use this block for configurations.
|
48
|
-
Since the default middleware stack uses url\_encoded middleware and default adapter, use them on building your own middleware stack.
|
49
|
-
|
50
|
-
```ruby
|
51
|
-
conn = Faraday.new(:url => 'http://sushi.com') do |faraday|
|
52
|
-
faraday.request :url_encoded # form-encode POST params
|
53
|
-
faraday.response :logger # log requests to STDOUT
|
54
|
-
faraday.adapter Faraday.default_adapter # make requests with Net::HTTP
|
55
|
-
end
|
56
|
-
|
57
|
-
# Filter sensitive information from logs with a regex matcher
|
58
|
-
|
59
|
-
conn = Faraday.new(:url => 'http://sushi.com/api_key=s3cr3t') do |faraday|
|
60
|
-
faraday.request :url_encoded # form-encode POST params
|
61
|
-
faraday.response :logger do | logger |
|
62
|
-
logger.filter(/(api_key=)(\w+)/,'\1[REMOVED]')
|
63
|
-
end
|
64
|
-
faraday.adapter Faraday.default_adapter # make requests with Net::HTTP
|
65
|
-
end
|
66
|
-
```
|
67
|
-
|
68
|
-
Once you have the connection object, use it to make HTTP requests. You can pass paramters to it in a few different ways:
|
69
|
-
|
70
|
-
```ruby
|
71
|
-
## GET ##
|
72
|
-
|
73
|
-
response = conn.get '/nigiri/sake.json' # GET http://sushi.com/nigiri/sake.json
|
74
|
-
response.body
|
75
|
-
|
76
|
-
conn.get '/nigiri', { :name => 'Maguro' } # GET http://sushi.com/nigiri?name=Maguro
|
77
|
-
|
78
|
-
conn.get do |req| # GET http://sushi.com/search?page=2&limit=100
|
79
|
-
req.url '/search', :page => 2
|
80
|
-
req.params['limit'] = 100
|
81
|
-
end
|
82
|
-
|
83
|
-
## POST ##
|
84
|
-
|
85
|
-
conn.post '/nigiri', { :name => 'Maguro' } # POST "name=maguro" to http://sushi.com/nigiri
|
86
|
-
```
|
87
|
-
|
88
|
-
Some configuration options can be adjusted per request:
|
89
|
-
|
90
|
-
```ruby
|
91
|
-
# post payload as JSON instead of "www-form-urlencoded" encoding:
|
92
|
-
conn.post do |req|
|
93
|
-
req.url '/nigiri'
|
94
|
-
req.headers['Content-Type'] = 'application/json'
|
95
|
-
req.body = '{ "name": "Unagi" }'
|
96
|
-
end
|
97
|
-
|
98
|
-
## Per-request options ##
|
99
|
-
|
100
|
-
conn.get do |req|
|
101
|
-
req.url '/search'
|
102
|
-
req.options.timeout = 5 # open/read timeout in seconds
|
103
|
-
req.options.open_timeout = 2 # connection open timeout in seconds
|
104
|
-
end
|
105
|
-
```
|
106
|
-
|
107
|
-
And you can inject arbitrary data into the request using the `context` option:
|
108
|
-
|
109
|
-
```ruby
|
110
|
-
# Anything you inject using context option will be available in the env on all middlewares
|
111
|
-
|
112
|
-
conn.get do |req|
|
113
|
-
req.url '/search'
|
114
|
-
req.options.context = {
|
115
|
-
foo: 'foo',
|
116
|
-
bar: 'bar'
|
117
|
-
}
|
118
|
-
end
|
119
|
-
```
|
120
|
-
|
121
|
-
### Changing how parameters are serialized
|
122
|
-
|
123
|
-
Sometimes you need to send the same URL parameter multiple times with different
|
124
|
-
values. This requires manually setting the parameter encoder and can be done on
|
125
|
-
either per-connection or per-request basis.
|
126
|
-
|
127
|
-
```ruby
|
128
|
-
# per-connection setting
|
129
|
-
conn = Faraday.new :request => { :params_encoder => Faraday::FlatParamsEncoder }
|
130
|
-
|
131
|
-
conn.get do |req|
|
132
|
-
# per-request setting:
|
133
|
-
# req.options.params_encoder = my_encoder
|
134
|
-
req.params['roll'] = ['california', 'philadelphia']
|
135
|
-
end
|
136
|
-
# GET 'http://sushi.com?roll=california&roll=philadelphia'
|
137
|
-
```
|
138
|
-
|
139
|
-
The value of Faraday `params_encoder` can be any object that responds to:
|
140
|
-
|
141
|
-
* `encode(hash) #=> String`
|
142
|
-
* `decode(string) #=> Hash`
|
143
|
-
|
144
|
-
The encoder will affect both how query strings are processed and how POST bodies
|
145
|
-
get serialized. The default encoder is Faraday::NestedParamsEncoder.
|
146
|
-
|
147
|
-
## Authentication
|
148
|
-
|
149
|
-
Basic and Token authentication are handled by Faraday::Request::BasicAuthentication and Faraday::Request::TokenAuthentication respectively. These can be added as middleware manually or through the helper methods.
|
150
|
-
|
151
|
-
```ruby
|
152
|
-
Faraday.new(...) do |conn|
|
153
|
-
conn.basic_auth('username', 'password')
|
154
|
-
end
|
155
|
-
|
156
|
-
Faraday.new(...) do |conn|
|
157
|
-
conn.token_auth('authentication-token')
|
158
|
-
end
|
159
|
-
```
|
160
|
-
|
161
|
-
## Advanced middleware usage
|
162
|
-
|
163
|
-
The order in which middleware is stacked is important. Like with Rack, the
|
164
|
-
first middleware on the list wraps all others, while the last middleware is the
|
165
|
-
innermost one, so that must be the adapter.
|
166
|
-
|
167
|
-
```ruby
|
168
|
-
Faraday.new(...) do |conn|
|
169
|
-
# POST/PUT params encoders:
|
170
|
-
conn.request :multipart
|
171
|
-
conn.request :url_encoded
|
172
|
-
|
173
|
-
# Last middleware must be the adapter:
|
174
|
-
conn.adapter :net_http
|
175
|
-
end
|
176
|
-
```
|
177
|
-
|
178
|
-
This request middleware setup affects POST/PUT requests in the following way:
|
179
|
-
|
180
|
-
1. `Request::Multipart` checks for files in the payload, otherwise leaves
|
181
|
-
everything untouched;
|
182
|
-
2. `Request::UrlEncoded` encodes as "application/x-www-form-urlencoded" if not
|
183
|
-
already encoded or of another type
|
184
|
-
|
185
|
-
Swapping middleware means giving the other priority. Specifying the
|
186
|
-
"Content-Type" for the request is explicitly stating which middleware should
|
187
|
-
process it.
|
188
|
-
|
189
|
-
Examples:
|
190
|
-
|
191
|
-
```ruby
|
192
|
-
# uploading a file:
|
193
|
-
payload[:profile_pic] = Faraday::UploadIO.new('/path/to/avatar.jpg', 'image/jpeg')
|
194
|
-
|
195
|
-
# "Multipart" middleware detects files and encodes with "multipart/form-data":
|
196
|
-
conn.put '/profile', payload
|
197
|
-
```
|
198
|
-
|
199
|
-
## Writing middleware
|
200
|
-
|
201
|
-
Middleware are classes that implement a `call` instance method. They hook into
|
202
|
-
the request/response cycle.
|
203
|
-
|
204
|
-
```ruby
|
205
|
-
def call(request_env)
|
206
|
-
# do something with the request
|
207
|
-
# request_env[:request_headers].merge!(...)
|
208
|
-
|
209
|
-
@app.call(request_env).on_complete do |response_env|
|
210
|
-
# do something with the response
|
211
|
-
# response_env[:response_headers].merge!(...)
|
212
|
-
end
|
213
|
-
end
|
214
|
-
```
|
215
|
-
|
216
|
-
It's important to do all processing of the response only in the `on_complete`
|
217
|
-
block. This enables middleware to work in parallel mode where requests are
|
218
|
-
asynchronous.
|
219
|
-
|
220
|
-
The `env` is a hash with symbol keys that contains info about the request and,
|
221
|
-
later, response. Some keys are:
|
222
|
-
|
223
|
-
```
|
224
|
-
# request phase
|
225
|
-
:method - :get, :post, ...
|
226
|
-
:url - URI for the current request; also contains GET parameters
|
227
|
-
:body - POST parameters for :post/:put requests
|
228
|
-
:request_headers
|
229
|
-
|
230
|
-
# response phase
|
231
|
-
:status - HTTP response status code, such as 200
|
232
|
-
:body - the response body
|
233
|
-
:response_headers
|
234
|
-
```
|
235
|
-
|
236
|
-
## Ad-hoc adapters customization
|
237
|
-
|
238
|
-
Faraday is intended to be a generic interface between your code and the adapter. However, sometimes you need to access a feature specific to one of the adapters that is not covered in Faraday's interface.
|
239
|
-
|
240
|
-
When that happens, you can pass a block when specifying the adapter to customize it. The block parameter will change based on the adapter you're using. See below for some examples.
|
241
|
-
|
242
|
-
### NetHttp
|
243
|
-
```ruby
|
244
|
-
conn = Faraday.new(...) do |f|
|
245
|
-
f.adapter :net_http do |http| # yields Net::HTTP
|
246
|
-
http.idle_timeout = 100
|
247
|
-
http.verify_callback = lambda do | preverify_ok, cert_store |
|
248
|
-
# do something here...
|
249
|
-
end
|
250
|
-
end
|
251
|
-
end
|
252
|
-
```
|
253
|
-
|
254
|
-
### NetHttpPersistent
|
255
|
-
```ruby
|
256
|
-
conn = Faraday.new(...) do |f|
|
257
|
-
f.adapter :net_http_persistent do |http| # yields Net::HTTP::Persistent
|
258
|
-
http.idle_timeout = 100
|
259
|
-
http.retry_change_requests = true
|
260
|
-
end
|
261
|
-
end
|
262
|
-
```
|
263
|
-
|
264
|
-
### Patron
|
265
|
-
```ruby
|
266
|
-
conn = Faraday.new(...) do |f|
|
267
|
-
f.adapter :patron do |session| # yields Patron::Session
|
268
|
-
session.max_redirects = 10
|
269
|
-
end
|
270
|
-
end
|
271
|
-
```
|
272
|
-
|
273
|
-
### HTTPClient
|
274
|
-
```ruby
|
275
|
-
conn = Faraday.new(...) do |f|
|
276
|
-
f.adapter :httpclient do |client| # yields HTTPClient
|
277
|
-
client.keep_alive_timeout = 20
|
278
|
-
client.ssl_config.timeout = 25
|
279
|
-
end
|
280
|
-
end
|
281
|
-
```
|
282
|
-
|
283
|
-
## Using Faraday for testing
|
284
|
-
|
285
|
-
```ruby
|
286
|
-
# It's possible to define stubbed request outside a test adapter block.
|
287
|
-
stubs = Faraday::Adapter::Test::Stubs.new do |stub|
|
288
|
-
stub.get('/tamago') { |env| [200, {}, 'egg'] }
|
289
|
-
end
|
290
|
-
|
291
|
-
# You can pass stubbed request to the test adapter or define them in a block
|
292
|
-
# or a combination of the two.
|
293
|
-
test = Faraday.new do |builder|
|
294
|
-
builder.adapter :test, stubs do |stub|
|
295
|
-
stub.get('/ebi') { |env| [ 200, {}, 'shrimp' ]}
|
296
|
-
end
|
297
|
-
end
|
298
|
-
|
299
|
-
# It's also possible to stub additional requests after the connection has
|
300
|
-
# been initialized. This is useful for testing.
|
301
|
-
stubs.get('/uni') { |env| [ 200, {}, 'urchin' ]}
|
302
|
-
|
303
|
-
resp = test.get '/tamago'
|
304
|
-
resp.body # => 'egg'
|
305
|
-
resp = test.get '/ebi'
|
306
|
-
resp.body # => 'shrimp'
|
307
|
-
resp = test.get '/uni'
|
308
|
-
resp.body # => 'urchin'
|
309
|
-
resp = test.get '/else' #=> raises "no such stub" error
|
310
|
-
|
311
|
-
# If you like, you can treat your stubs as mocks by verifying that all of
|
312
|
-
# the stubbed calls were made. NOTE that this feature is still fairly
|
313
|
-
# experimental: It will not verify the order or count of any stub, only that
|
314
|
-
# it was called once during the course of the test.
|
315
|
-
stubs.verify_stubbed_calls
|
316
|
-
```
|
20
|
+
The best starting point is the [Faraday Website][website], with its introduction and explanation.
|
21
|
+
Need more details? See the [Faraday API Documentation][apidoc] to see how it works internally.
|
317
22
|
|
318
23
|
## Supported Ruby versions
|
319
24
|
|
320
|
-
This library aims to support and is [tested against][
|
321
|
-
implementations
|
322
|
-
|
323
|
-
|
324
|
-
* [JRuby][] 1.7+
|
325
|
-
* [Rubinius][] 2+
|
25
|
+
This library aims to support and is [tested against][actions] the currently officially supported Ruby
|
26
|
+
implementations. This means that, even without a major release, we could add or drop support for Ruby versions,
|
27
|
+
following their [EOL](https://endoflife.date/ruby).
|
28
|
+
Currently that means we support Ruby 2.6+
|
326
29
|
|
327
30
|
If something doesn't work on one of these Ruby versions, it's a bug.
|
328
31
|
|
329
32
|
This library may inadvertently work (or seem to work) on other Ruby
|
330
|
-
implementations, however support will only be provided for the versions listed
|
33
|
+
implementations and versions, however support will only be provided for the versions listed
|
331
34
|
above.
|
332
35
|
|
333
36
|
If you would like this library to support another Ruby version, you may
|
@@ -340,21 +43,18 @@ of a major release, support for that Ruby version may be dropped.
|
|
340
43
|
## Contribute
|
341
44
|
|
342
45
|
Do you want to contribute to Faraday?
|
343
|
-
Open the issues page and check for the `
|
344
|
-
But before you start coding, please read our [Contributing Guide]
|
46
|
+
Open the issues page and check for the `help wanted` label!
|
47
|
+
But before you start coding, please read our [Contributing Guide][contributing]
|
345
48
|
|
346
49
|
## Copyright
|
347
|
-
|
348
|
-
|
349
|
-
|
350
|
-
|
351
|
-
[
|
352
|
-
[
|
353
|
-
[
|
354
|
-
[
|
355
|
-
[patron]: http://toland.github.io/patron/
|
356
|
-
[eventmachine]: https://github.com/igrigorik/em-http-request#readme
|
357
|
-
[httpclient]: https://github.com/nahi/httpclient
|
50
|
+
© 2009 - 2021, the [Faraday Team][faraday_team]. Website and branding design by [Elena Lo Piccolo](https://elelopic.design).
|
51
|
+
|
52
|
+
[awesome]: https://github.com/lostisland/awesome-faraday/#adapters
|
53
|
+
[website]: https://lostisland.github.io/faraday
|
54
|
+
[faraday_team]: https://lostisland.github.io/faraday/team
|
55
|
+
[contributing]: https://github.com/lostisland/faraday/blob/master/.github/CONTRIBUTING.md
|
56
|
+
[apidoc]: https://www.rubydoc.info/github/lostisland/faraday
|
57
|
+
[actions]: https://github.com/lostisland/faraday/actions
|
358
58
|
[jruby]: http://jruby.org/
|
359
59
|
[rubinius]: http://rubini.us/
|
360
60
|
[license]: LICENSE.md
|
data/Rakefile
ADDED
@@ -0,0 +1,97 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
# Requires Ruby with rspec and faraday gems.
|
4
|
+
# rspec client_spec.rb
|
5
|
+
|
6
|
+
require 'faraday'
|
7
|
+
require 'json'
|
8
|
+
|
9
|
+
# Example API client
|
10
|
+
class Client
|
11
|
+
def initialize(conn)
|
12
|
+
@conn = conn
|
13
|
+
end
|
14
|
+
|
15
|
+
def sushi(jname, params: {})
|
16
|
+
res = @conn.get("/#{jname}", params)
|
17
|
+
data = JSON.parse(res.body)
|
18
|
+
data['name']
|
19
|
+
end
|
20
|
+
end
|
21
|
+
|
22
|
+
RSpec.describe Client do
|
23
|
+
let(:stubs) { Faraday::Adapter::Test::Stubs.new }
|
24
|
+
let(:conn) { Faraday.new { |b| b.adapter(:test, stubs) } }
|
25
|
+
let(:client) { Client.new(conn) }
|
26
|
+
|
27
|
+
it 'parses name' do
|
28
|
+
stubs.get('/ebi') do |env|
|
29
|
+
# optional: you can inspect the Faraday::Env
|
30
|
+
expect(env.url.path).to eq('/ebi')
|
31
|
+
[
|
32
|
+
200,
|
33
|
+
{ 'Content-Type': 'application/javascript' },
|
34
|
+
'{"name": "shrimp"}'
|
35
|
+
]
|
36
|
+
end
|
37
|
+
|
38
|
+
# uncomment to trigger stubs.verify_stubbed_calls failure
|
39
|
+
# stubs.get('/unused') { [404, {}, ''] }
|
40
|
+
|
41
|
+
expect(client.sushi('ebi')).to eq('shrimp')
|
42
|
+
stubs.verify_stubbed_calls
|
43
|
+
end
|
44
|
+
|
45
|
+
it 'handles 404' do
|
46
|
+
stubs.get('/ebi') do
|
47
|
+
[
|
48
|
+
404,
|
49
|
+
{ 'Content-Type': 'application/javascript' },
|
50
|
+
'{}'
|
51
|
+
]
|
52
|
+
end
|
53
|
+
expect(client.sushi('ebi')).to be_nil
|
54
|
+
stubs.verify_stubbed_calls
|
55
|
+
end
|
56
|
+
|
57
|
+
it 'handles exception' do
|
58
|
+
stubs.get('/ebi') do
|
59
|
+
raise Faraday::ConnectionFailed
|
60
|
+
end
|
61
|
+
|
62
|
+
expect { client.sushi('ebi') }.to raise_error(Faraday::ConnectionFailed)
|
63
|
+
stubs.verify_stubbed_calls
|
64
|
+
end
|
65
|
+
|
66
|
+
context 'When the test stub is run in strict_mode' do
|
67
|
+
let(:stubs) { Faraday::Adapter::Test::Stubs.new(strict_mode: true) }
|
68
|
+
|
69
|
+
it 'verifies the all parameter values are identical' do
|
70
|
+
stubs.get('/ebi?abc=123') do
|
71
|
+
[
|
72
|
+
200,
|
73
|
+
{ 'Content-Type': 'application/javascript' },
|
74
|
+
'{"name": "shrimp"}'
|
75
|
+
]
|
76
|
+
end
|
77
|
+
|
78
|
+
# uncomment to raise Stubs::NotFound
|
79
|
+
# expect(client.sushi('ebi', params: { abc: 123, foo: 'Kappa' })).to eq('shrimp')
|
80
|
+
expect(client.sushi('ebi', params: { abc: 123 })).to eq('shrimp')
|
81
|
+
stubs.verify_stubbed_calls
|
82
|
+
end
|
83
|
+
end
|
84
|
+
|
85
|
+
context 'When the Faraday connection is configured with FlatParamsEncoder' do
|
86
|
+
let(:conn) { Faraday.new(request: { params_encoder: Faraday::FlatParamsEncoder }) { |b| b.adapter(:test, stubs) } }
|
87
|
+
|
88
|
+
it 'handles the same multiple URL parameters' do
|
89
|
+
stubs.get('/ebi?a=x&a=y&a=z') { [200, { 'Content-Type' => 'application/json' }, '{"name": "shrimp"}'] }
|
90
|
+
|
91
|
+
# uncomment to raise Stubs::NotFound
|
92
|
+
# expect(client.sushi('ebi', params: { a: %w[x y] })).to eq('shrimp')
|
93
|
+
expect(client.sushi('ebi', params: { a: %w[x y z] })).to eq('shrimp')
|
94
|
+
stubs.verify_stubbed_calls
|
95
|
+
end
|
96
|
+
end
|
97
|
+
end
|
@@ -0,0 +1,118 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
# Requires Ruby with test-unit and faraday gems.
|
4
|
+
# ruby client_test.rb
|
5
|
+
|
6
|
+
require 'faraday'
|
7
|
+
require 'json'
|
8
|
+
require 'test/unit'
|
9
|
+
|
10
|
+
# Example API client
|
11
|
+
class Client
|
12
|
+
def initialize(conn)
|
13
|
+
@conn = conn
|
14
|
+
end
|
15
|
+
|
16
|
+
def sushi(jname, params: {})
|
17
|
+
res = @conn.get("/#{jname}", params)
|
18
|
+
data = JSON.parse(res.body)
|
19
|
+
data['name']
|
20
|
+
end
|
21
|
+
end
|
22
|
+
|
23
|
+
# Example API client test
|
24
|
+
class ClientTest < Test::Unit::TestCase
|
25
|
+
def test_sushi_name
|
26
|
+
stubs = Faraday::Adapter::Test::Stubs.new
|
27
|
+
stubs.get('/ebi') do |env|
|
28
|
+
# optional: you can inspect the Faraday::Env
|
29
|
+
assert_equal '/ebi', env.url.path
|
30
|
+
[
|
31
|
+
200,
|
32
|
+
{ 'Content-Type': 'application/javascript' },
|
33
|
+
'{"name": "shrimp"}'
|
34
|
+
]
|
35
|
+
end
|
36
|
+
|
37
|
+
# uncomment to trigger stubs.verify_stubbed_calls failure
|
38
|
+
# stubs.get('/unused') { [404, {}, ''] }
|
39
|
+
|
40
|
+
cli = client(stubs)
|
41
|
+
assert_equal 'shrimp', cli.sushi('ebi')
|
42
|
+
stubs.verify_stubbed_calls
|
43
|
+
end
|
44
|
+
|
45
|
+
def test_sushi_not_found
|
46
|
+
stubs = Faraday::Adapter::Test::Stubs.new
|
47
|
+
stubs.get('/ebi') do
|
48
|
+
[
|
49
|
+
404,
|
50
|
+
{ 'Content-Type': 'application/javascript' },
|
51
|
+
'{}'
|
52
|
+
]
|
53
|
+
end
|
54
|
+
|
55
|
+
cli = client(stubs)
|
56
|
+
assert_nil cli.sushi('ebi')
|
57
|
+
stubs.verify_stubbed_calls
|
58
|
+
end
|
59
|
+
|
60
|
+
def test_sushi_exception
|
61
|
+
stubs = Faraday::Adapter::Test::Stubs.new
|
62
|
+
stubs.get('/ebi') do
|
63
|
+
raise Faraday::ConnectionFailed
|
64
|
+
end
|
65
|
+
|
66
|
+
cli = client(stubs)
|
67
|
+
assert_raise Faraday::ConnectionFailed do
|
68
|
+
cli.sushi('ebi')
|
69
|
+
end
|
70
|
+
stubs.verify_stubbed_calls
|
71
|
+
end
|
72
|
+
|
73
|
+
def test_strict_mode
|
74
|
+
stubs = Faraday::Adapter::Test::Stubs.new(strict_mode: true)
|
75
|
+
stubs.get('/ebi?abc=123') do
|
76
|
+
[
|
77
|
+
200,
|
78
|
+
{ 'Content-Type': 'application/javascript' },
|
79
|
+
'{"name": "shrimp"}'
|
80
|
+
]
|
81
|
+
end
|
82
|
+
|
83
|
+
cli = client(stubs)
|
84
|
+
assert_equal 'shrimp', cli.sushi('ebi', params: { abc: 123 })
|
85
|
+
|
86
|
+
# uncomment to raise Stubs::NotFound
|
87
|
+
# assert_equal 'shrimp', cli.sushi('ebi', params: { abc: 123, foo: 'Kappa' })
|
88
|
+
stubs.verify_stubbed_calls
|
89
|
+
end
|
90
|
+
|
91
|
+
def test_non_default_params_encoder
|
92
|
+
stubs = Faraday::Adapter::Test::Stubs.new(strict_mode: true)
|
93
|
+
stubs.get('/ebi?a=x&a=y&a=z') do
|
94
|
+
[
|
95
|
+
200,
|
96
|
+
{ 'Content-Type': 'application/javascript' },
|
97
|
+
'{"name": "shrimp"}'
|
98
|
+
]
|
99
|
+
end
|
100
|
+
conn = Faraday.new(request: { params_encoder: Faraday::FlatParamsEncoder }) do |builder|
|
101
|
+
builder.adapter :test, stubs
|
102
|
+
end
|
103
|
+
|
104
|
+
cli = Client.new(conn)
|
105
|
+
assert_equal 'shrimp', cli.sushi('ebi', params: { a: %w[x y z] })
|
106
|
+
|
107
|
+
# uncomment to raise Stubs::NotFound
|
108
|
+
# assert_equal 'shrimp', cli.sushi('ebi', params: { a: %w[x y] })
|
109
|
+
stubs.verify_stubbed_calls
|
110
|
+
end
|
111
|
+
|
112
|
+
def client(stubs)
|
113
|
+
conn = Faraday.new do |builder|
|
114
|
+
builder.adapter :test, stubs
|
115
|
+
end
|
116
|
+
Client.new(conn)
|
117
|
+
end
|
118
|
+
end
|