diff --git a/scarpe-components/lib/scarpe/components/port_helpers.rb b/scarpe-components/lib/scarpe/components/port_helpers.rb new file mode 100644 index 000000000..a91f3aed6 --- /dev/null +++ b/scarpe-components/lib/scarpe/components/port_helpers.rb @@ -0,0 +1,30 @@ +# frozen_string_literal: true + +require "socket" + +module Scarpe::Components + module PortHelpers + MAX_SERVER_STARTUP_WAIT = 5.0 + + def port_working?(ip, port_num) + begin + TCPSocket.new(ip, port_num) + rescue Errno::ECONNREFUSED + return false + end + return true + end + + def wait_until_port_working(ip, port_num, max_wait: MAX_SERVER_STARTUP_WAIT) + t_start = Time.now + loop do + if Time.now - t_start > max_wait + raise "Server on port #{port_num} didn't start up in time!" + end + + sleep 0.1 + return if port_working?(ip, port_num) + end + end + end +end \ No newline at end of file diff --git a/scarpe-components/test/test_port_helpers.rb b/scarpe-components/test/test_port_helpers.rb new file mode 100644 index 000000000..1316a3594 --- /dev/null +++ b/scarpe-components/test/test_port_helpers.rb @@ -0,0 +1,12 @@ +# frozen_string_literal: true + +require_relative "test_helper" + +require "scarpe/components/port_helpers" +class TestPortHelpers < Minitest::Test + include Scarpe::Components::PortHelpers + + def test_port_finder + assert_equal false, port_working?("127.0.0.1", 9832), "Port 9832 should be unused!" + end +end