open-consul/connect/proxy/proxy_test.go
R.B. Boyer 5c5f21088c sdk: add freelist tracking and ephemeral port range skipping to freeport
This should cut down on test flakiness.

Problems handled:

- If you had enough parallel test cases running, the former circular
approach to handling the port block could hand out the same port to
multiple cases before they each had a chance to bind them, leading to
one of the two tests to fail.

- The freeport library would allocate out of the ephemeral port range.
This has been corrected for Linux (which should cover CI).

- The library now waits until a formerly-in-use port is verified to be
free before putting it back into circulation.
2019-09-17 14:30:43 -05:00

85 lines
2 KiB
Go

package proxy
import (
"context"
"log"
"net"
"os"
"testing"
"github.com/hashicorp/consul/testrpc"
"github.com/hashicorp/consul/agent"
agConnect "github.com/hashicorp/consul/agent/connect"
"github.com/hashicorp/consul/api"
"github.com/hashicorp/consul/connect"
"github.com/hashicorp/consul/sdk/freeport"
"github.com/hashicorp/consul/sdk/testutil/retry"
"github.com/stretchr/testify/require"
)
func TestProxy_public(t *testing.T) {
t.Parallel()
require := require.New(t)
ports := freeport.MustTake(1)
defer freeport.Return(ports)
a := agent.NewTestAgent(t, t.Name(), "")
defer a.Shutdown()
testrpc.WaitForTestAgent(t, a.RPC, "dc1")
client := a.Client()
// Register the service so we can get a leaf cert
_, err := client.Catalog().Register(&api.CatalogRegistration{
Datacenter: "dc1",
Node: "local",
Address: "127.0.0.1",
Service: &api.AgentService{
Service: "echo",
},
}, nil)
require.NoError(err)
// Start the backend service that is being proxied
testApp := NewTestTCPServer(t)
defer testApp.Close()
// Start the proxy
p, err := New(client, NewStaticConfigWatcher(&Config{
ProxiedServiceName: "echo",
PublicListener: PublicListenerConfig{
BindAddress: "127.0.0.1",
BindPort: ports[0],
LocalServiceAddress: testApp.Addr().String(),
},
}), testLogger(t))
require.NoError(err)
defer p.Close()
go p.Serve()
// Create a test connection to the proxy. We retry here a few times
// since this is dependent on the agent actually starting up and setting
// up the CA.
var conn net.Conn
svc, err := connect.NewService("echo", client)
require.NoError(err)
retry.Run(t, func(r *retry.R) {
conn, err = svc.Dial(context.Background(), &connect.StaticResolver{
Addr: TestLocalAddr(ports[0]),
CertURI: agConnect.TestSpiffeIDService(t, "echo"),
})
if err != nil {
r.Fatalf("err: %s", err)
}
})
// Connection works, test it is the right one
TestEchoConn(t, conn, "")
}
func testLogger(t *testing.T) *log.Logger {
return log.New(os.Stderr, "", log.LstdFlags)
}