Skip to content

Commit

Permalink
Fixes #37413 - Let the kernel assign a TCP port in tests
Browse files Browse the repository at this point in the history
This binds on port 0, which lets the kernel decide which port to use.
The port is then read back from the listener. Because the kernel knows
which ports it's allowed to bind to, it removes the risk of a failure
due to collisions or policies.
  • Loading branch information
ekohl committed May 8, 2024
1 parent 3f079df commit bf8b44f
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions test/test_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,19 +39,24 @@ def setup
end

def launch(protocol: 'https', plugins: [], settings: {})
port = 1024 + rand(63_000)
port = 0
@settings = Proxy::Settings::Global.new(settings.merge("#{protocol}_port" => port))
@t = Thread.new do
launcher = Proxy::Launcher.new(@settings)
app = launcher.public_send("#{protocol}_app", port, plugins)
launcher.webrick_server(app.merge(AccessLog: [Logger.new('/dev/null')]), ['localhost'], port).start
server = launcher.webrick_server(app.merge(AccessLog: [Logger.new('/dev/null')]), ['localhost'], port)
# Read back the actual port it bound to
@settings["#{protocol}_port"] = server.listeners[0].addr[1]
server.start
end
Timeout.timeout(2) do
sleep(0.1) until can_connect?('localhost', @settings.send("#{protocol}_port"))
sleep(0.1) until can_connect?('localhost', @settings["#{protocol}_port"])
end
end

def can_connect?(host, port)
return false if port == 0

TCPSocket.new(host, port).close
true
rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
Expand Down

0 comments on commit bf8b44f

Please sign in to comment.