Skip to content

Commit 36eec0e

Browse files
authored
Merge pull request #5 from cyx/add-read-timeout
Add read_timeout / open_timeout pass through
2 parents 33649d9 + e4bfbee commit 36eec0e

File tree

3 files changed

+42
-5
lines changed

3 files changed

+42
-5
lines changed

lib/requests.rb

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ def self.request(method, url,
2222
data: nil,
2323
params: nil,
2424
auth: nil,
25-
proxy: nil)
25+
proxy: nil,
26+
options: {})
2627

2728
uri = URI.parse(url)
2829
uri.query = encode_www_form(params) if params
@@ -32,7 +33,7 @@ def self.request(method, url,
3233
basic_auth(headers, *auth) if auth
3334

3435
proxy = proxy.to_h.values_at(:host, :port, :user, :password)
35-
response = Net::HTTP.start(uri.host, uri.port, *proxy, opts(uri)) do |http|
36+
response = Net::HTTP.start(uri.host, uri.port, *proxy, opts(uri, options)) do |http|
3637
http.send_request(method, uri, body, headers)
3738
end
3839

@@ -48,11 +49,13 @@ def self.encode_www_form(params)
4849
URI.encode_www_form(params)
4950
end
5051

51-
def self.opts(uri)
52+
def self.opts(uri, options)
5253
if uri.scheme == 'https'
5354
{ use_ssl: true,
5455
verify_mode: OpenSSL::SSL::VERIFY_PEER,
55-
ca_file: CA_FILE
56+
ca_file: CA_FILE,
57+
read_timeout: options[:read_timeout],
58+
open_timeout: options[:open_timeout],
5659
}
5760
end
5861
end

tests/proxy_test.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
assert_equal ['application/json'], r.headers['content-type']
2727
assert(r.json['args'] && r.json['args']['foo'] == 'bar')
2828

29-
assert_equal ["1.1 0.0.0.0:#{port}"], r.headers['via']
29+
assert_equal ["1.1 vegur, 1.1 0.0.0.0:#{port}"], r.headers['via']
3030

3131
proxy.shutdown
3232
end

tests/requests_test.rb

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,3 +57,37 @@
5757
assert_equal Net::HTTPNotFound, e.response.class
5858
end
5959
end
60+
61+
test 'read timeout' do
62+
begin
63+
Requests.get('http://httpbin.org:10000', options: { read_timeout: 1 })
64+
rescue => err
65+
assert err.kind_of?(Errno::ECONNREFUSED)
66+
end
67+
end
68+
69+
test 'read timeout not failing' do
70+
begin
71+
Requests.get('http://httpbin.org/get', options: { read_timeout: 30 })
72+
rescue => err
73+
flunk(err)
74+
end
75+
end
76+
77+
test 'open timeout' do
78+
begin
79+
Requests.get('http://httpbin.org:10000', options: { open_timeout: 1 })
80+
rescue => err
81+
assert err.kind_of?(Errno::ECONNREFUSED)
82+
else
83+
flunk("expected exception")
84+
end
85+
end
86+
87+
test 'open timeout not failing' do
88+
begin
89+
Requests.get('http://httpbin.org/get', options: { open_timeout: 30 })
90+
rescue => err
91+
flunk(err)
92+
end
93+
end

0 commit comments

Comments
 (0)