From 34678e895a5a40da6f444199983fee3f8ce518ee Mon Sep 17 00:00:00 2001 From: elijah Date: Fri, 27 Dec 2013 02:43:24 -0800 Subject: added some network tests for stunnel --- bin/run_tests | 87 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 84 insertions(+), 3 deletions(-) (limited to 'bin') diff --git a/bin/run_tests b/bin/run_tests index 8c5fb492..89fbdb24 100755 --- a/bin/run_tests +++ b/bin/run_tests @@ -93,18 +93,99 @@ class LeapTest < MiniTest::Unit::TestCase yield nil, nil, exc end - def assert_get(url, params=nil) + def assert_get(url, params=nil, options=nil) + options ||= {} get(url, params) do |body, response, error| if body yield body elsif response - fail "Expected a 200 status code from #{url}, but got #{response.code} instead." + fail ["Expected a 200 status code from #{url}, but got #{response.code} instead.", options[:error_msg]].compact.join("\n") else - fail "Expected a response from #{url}, but got \"#{error}\" instead." + fail ["Expected a response from #{url}, but got \"#{error}\" instead.", options[:error_msg]].compact.join("\n") end end end + # + # test if a socket can be connected to + # + + # + # tcp connection helper with timeout + # + def try_tcp_connect(host, port, timeout = 5) + addr = Socket.getaddrinfo(host, nil) + sockaddr = Socket.pack_sockaddr_in(port, addr[0][3]) + + Socket.new(Socket.const_get(addr[0][0]), Socket::SOCK_STREAM, 0).tap do |socket| + socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1) + begin + socket.connect_nonblock(sockaddr) + rescue IO::WaitReadable + if IO.select([socket], nil, nil, timeout) == nil + raise "Connection timeout" + else + socket.connect_nonblock(sockaddr) + end + rescue IO::WaitWritable + if IO.select(nil, [socket], nil, timeout) == nil + raise "Connection timeout" + else + socket.connect_nonblock(sockaddr) + end + end + return socket + end + end + + def try_tcp_write(socket, timeout = 5) + begin + socket.write_nonblock("\0") + rescue IO::WaitReadable + if IO.select([socket], nil, nil, timeout) == nil + raise "Write timeout" + else + retry + end + rescue IO::WaitWritable + if IO.select(nil, [socket], nil, timeout) == nil + raise "Write timeout" + else + retry + end + end + end + + def try_tcp_read(socket, timeout = 5) + begin + socket.read_nonblock(1) + rescue IO::WaitReadable + if IO.select([socket], nil, nil, timeout) == nil + raise "Read timeout" + else + retry + end + rescue IO::WaitWritable + if IO.select(nil, [socket], nil, timeout) == nil + raise "Read timeout" + else + retry + end + end + end + + def assert_tcp_socket(host, port, msg=nil) + begin + socket = try_tcp_connect(host, port, 1) + #try_tcp_write(socket,1) + #try_tcp_read(socket,1) + rescue StandardError => exc + fail ["Failed to open socket #{host}:#{port}", exc].join("\n") + ensure + socket.close if socket + end + end + # # Matches the regexp in the file, and returns the first matched string (or fails if no match). # -- cgit v1.2.3