vaguerent/test/unit/vagrant/util/is_port_open_test.rb
Jeff Bonhag ade076cabb
Fixes #11236: Windows port detection (#11244)
This reverts commit 81553263ab812a7fd0a2ab0f627bee139ad6397c.

This fixes a regression with Windows port detection which led to port
collisions not being fixed on `vagrant up`.

PR #8517 changed `IsPortOpen#is_port_open?` to rescue
Errno::EADDRNOTAVAIL, but when we merged it into master, there was code
in `HandleForwardedPortCollisions#port_check` that depended on that
error bubbling up.
2019-12-19 14:46:13 -05:00

64 lines
1.6 KiB
Ruby

require File.expand_path("../../../base", __FILE__)
require "socket"
require "vagrant/util/is_port_open"
describe Vagrant::Util::IsPortOpen do
let(:klass) do
Class.new do
extend Vagrant::Util::IsPortOpen
end
end
let(:open_port) { 52811 }
let(:closed_port) { 52811 }
it "should report open ports" do
# Start a thread which listens on a port
thr = Thread.new do
server = TCPServer.new(open_port)
Thread.current[:running] = true
# Wait until we're told to die
Thread.current[:die] = false
while !Thread.current[:die]
Thread.pass
end
# Die!
server.close
end
# Wait until the server is running
while !thr[:running]
Thread.pass
end
# Verify that we report the port is open
expect(klass.is_port_open?("127.0.0.1", open_port)).to be
# Kill the thread
thr[:die] = true
thr.join
end
it "should report closed ports" do
# This CAN fail, since port 52811 might actually be in use, but I'm
# not sure what to do except choose some random port and hope for the
# best, really.
expect(klass.is_port_open?("127.0.0.1", closed_port)).not_to be
end
it "should handle connection refused" do
expect(TCPSocket).to receive(:new).with("0.0.0.0", closed_port).and_raise(Errno::ECONNREFUSED)
expect(klass.is_port_open?("0.0.0.0", closed_port)).to be(false)
end
it "should raise an error if cannot assign requested address" do
expect(TCPSocket).to receive(:new).with("0.0.0.0", open_port).and_raise(Errno::EADDRNOTAVAIL)
expect { klass.is_port_open?("0.0.0.0", open_port) }.to raise_error(Errno::EADDRNOTAVAIL)
end
end