mirror of https://github.com/hashicorp/consul
Previously we believe it was necessary for all code that required ports to use freeport to prevent conflicts. https://github.com/dnephin/freeport-test shows that it is actually save to use port 0 (`127.0.0.1:0`) as long as it is passed directly to `net.Listen`, and the listener holds the port for as long as it is needed. This works because freeport explicitly avoids the ephemeral port range, and port 0 always uses that range. As you can see from the test output of https://github.com/dnephin/freeport-test, the two systems never use overlapping ports. This commit converts all uses of freeport that were being passed directly to a net.Listen to use port 0 instead. This allows us to remove a bit of wrapping we had around httptest, in a couple places.pull/11677/head
parent
5a61893642
commit
e8312d6b5a
@ -1,33 +0,0 @@
|
||||
package lib
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
|
||||
"github.com/hashicorp/consul/ipaddr"
|
||||
"github.com/hashicorp/consul/sdk/freeport"
|
||||
)
|
||||
|
||||
// NewHTTPTestServer starts and returns an httptest.Server that is listening
|
||||
// on a random port from freeport.Port. When the test case ends the server
|
||||
// will be stopped.
|
||||
//
|
||||
// We can't directly use httptest.Server here because that only thinks a port
|
||||
// is free if it's not bound. Consul tests frequently reserve ports via
|
||||
// `sdk/freeport` so you can have one part of the test try to use a port and
|
||||
// _know_ nothing is listening. If you simply assumed unbound ports were free
|
||||
// you'd end up with test cross-talk and weirdness.
|
||||
func NewHTTPTestServer(t freeport.TestingT, handler http.Handler) *httptest.Server {
|
||||
srv := httptest.NewUnstartedServer(handler)
|
||||
|
||||
addr := ipaddr.FormatAddressPort("127.0.0.1", freeport.Port(t))
|
||||
listener, err := net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to listen on %v", addr)
|
||||
}
|
||||
srv.Listener = listener
|
||||
t.Cleanup(srv.Close)
|
||||
srv.Start()
|
||||
return srv
|
||||
}
|
Loading…
Reference in new issue