From e597e594ad88dc02d70f7d3521d0d3bdc23739bb Mon Sep 17 00:00:00 2001 From: Eric Wong Date: Wed, 2 Feb 2011 16:54:07 -0800 Subject: test_helper: simplify random port binding Duh... --- t/bin/unused_listen | 17 ++--------------- test/test_helper.rb | 19 +++---------------- 2 files changed, 5 insertions(+), 31 deletions(-) diff --git a/t/bin/unused_listen b/t/bin/unused_listen index b638f54..cd536f1 100755 --- a/t/bin/unused_listen +++ b/t/bin/unused_listen @@ -7,24 +7,11 @@ require 'tmpdir' default_port = 8080 addr = ENV['UNICORN_TEST_ADDR'] || '127.0.0.1' -retries = 100 -base = 5000 port = sock = lock_path = nil begin - begin - port = base + rand(32768 - base) - while port == default_port - port = base + rand(32768 - base) - end - - sock = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0) - sock.bind(Socket.pack_sockaddr_in(port, addr)) - sock.listen(5) - rescue Errno::EADDRINUSE, Errno::EACCES - sock.close rescue nil - retry if (retries -= 1) >= 0 - end + sock = TCPServer.new(addr, 0) + port = sock.addr[1] # since we'll end up closing the random port we just got, there's a race # condition could allow the random port we just chose to reselect itself diff --git a/test/test_helper.rb b/test/test_helper.rb index c4e56a2..c87cc1a 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -100,30 +100,17 @@ end # for a race condition is very small). You may also set UNICORN_TEST_ADDR # to override the default test address (127.0.0.1). def unused_port(addr = '127.0.0.1') - retries = 100 - base = 5000 port = sock = nil begin - begin - port = base + rand(32768 - base) - while port == Unicorn::Const::DEFAULT_PORT - port = base + rand(32768 - base) - end - - sock = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0) - sock.bind(Socket.pack_sockaddr_in(port, addr)) - sock.listen(5) - rescue Errno::EADDRINUSE, Errno::EACCES - sock.close rescue nil - retry if (retries -= 1) >= 0 - end + sock = TCPServer.new(addr, 0) + port = sock.addr[1] # since we'll end up closing the random port we just got, there's a race # condition could allow the random port we just chose to reselect itself # when running tests in parallel with gmake. Create a lock file while # we have the port here to ensure that does not happen . lock_path = "#{Dir::tmpdir}/unicorn_test.#{addr}:#{port}.lock" - lock = File.open(lock_path, File::WRONLY|File::CREAT|File::EXCL, 0600) + File.open(lock_path, File::WRONLY|File::CREAT|File::EXCL, 0600) at_exit { File.unlink(lock_path) rescue nil } rescue Errno::EEXIST sock.close rescue nil -- cgit v1.2.3-24-ge0c7