From 337db4dc90385f3fc4623f1df2fba94d346e732b Mon Sep 17 00:00:00 2001 From: Cyril David Date: Fri, 31 Mar 2017 11:57:27 -0700 Subject: [PATCH 1/2] Add read_timeout / open_timeout --- lib/requests.rb | 11 +++++++---- tests/requests_test.rb | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 4 deletions(-) diff --git a/lib/requests.rb b/lib/requests.rb index 45ca912..74a697d 100644 --- a/lib/requests.rb +++ b/lib/requests.rb @@ -22,7 +22,8 @@ def self.request(method, url, data: nil, params: nil, auth: nil, - proxy: nil) + proxy: nil, + options: {}) uri = URI.parse(url) uri.query = encode_www_form(params) if params @@ -32,7 +33,7 @@ def self.request(method, url, basic_auth(headers, *auth) if auth proxy = proxy.to_h.values_at(:host, :port, :user, :password) - response = Net::HTTP.start(uri.host, uri.port, *proxy, opts(uri)) do |http| + response = Net::HTTP.start(uri.host, uri.port, *proxy, opts(uri, options)) do |http| http.send_request(method, uri, body, headers) end @@ -48,11 +49,13 @@ def self.encode_www_form(params) URI.encode_www_form(params) end - def self.opts(uri) + def self.opts(uri, options) if uri.scheme == 'https' { use_ssl: true, verify_mode: OpenSSL::SSL::VERIFY_PEER, - ca_file: CA_FILE + ca_file: CA_FILE, + read_timeout: options[:read_timeout], + open_timeout: options[:open_timeout], } end end diff --git a/tests/requests_test.rb b/tests/requests_test.rb index 1dc38b4..a15a39b 100644 --- a/tests/requests_test.rb +++ b/tests/requests_test.rb @@ -57,3 +57,37 @@ assert_equal Net::HTTPNotFound, e.response.class end end + +test 'read timeout' do + begin + Requests.get('http://httpbin.org:10000', options: { read_timeout: 1 }) + rescue => err + assert err.kind_of?(Errno::ECONNREFUSED) + end +end + +test 'read timeout not failing' do + begin + Requests.get('http://httpbin.org/get', options: { read_timeout: 30 }) + rescue => err + flunk(err) + end +end + +test 'open timeout' do + begin + Requests.get('http://httpbin.org:10000', options: { open_timeout: 1 }) + rescue => err + assert err.kind_of?(Errno::ECONNREFUSED) + else + flunk("expected exception") + end +end + +test 'open timeout not failing' do + begin + Requests.get('http://httpbin.org/get', options: { open_timeout: 30 }) + rescue => err + flunk(err) + end +end From e4bfbee024f837512f91f662d9a4ea74ad1e96a9 Mon Sep 17 00:00:00 2001 From: Cyril David Date: Fri, 31 Mar 2017 11:57:40 -0700 Subject: [PATCH 2/2] Fix random broken test --- tests/proxy_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/proxy_test.rb b/tests/proxy_test.rb index 19551a2..0acb364 100644 --- a/tests/proxy_test.rb +++ b/tests/proxy_test.rb @@ -26,7 +26,7 @@ assert_equal ['application/json'], r.headers['content-type'] assert(r.json['args'] && r.json['args']['foo'] == 'bar') - assert_equal ["1.1 0.0.0.0:#{port}"], r.headers['via'] + assert_equal ["1.1 vegur, 1.1 0.0.0.0:#{port}"], r.headers['via'] proxy.shutdown end