Add test helpers to find free tcp ports and wait for ports to become available.

This commit is contained in:
Arseny Balobanov 2020-02-15 22:39:40 +03:00
parent 8f414883a7
commit 37e262c88d
2 changed files with 84 additions and 0 deletions

View file

@ -0,0 +1,57 @@
package testtool
import (
"context"
"fmt"
"net"
"os"
"strconv"
"time"
)
// GetFreePort returns free local tcp port.
func GetFreePort() (string, error) {
addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
if err != nil {
return "", err
}
l, err := net.ListenTCP("tcp", addr)
if err != nil {
return "", err
}
defer func() { _ = l.Close() }()
p := l.Addr().(*net.TCPAddr).Port
return strconv.Itoa(p), nil
}
// WaitForPort tries to connect to given local port with constant backoff.
//
// Can be canceled via ctx.
func WaitForPort(ctx context.Context, port string) {
t := time.NewTicker(time.Millisecond * 100)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
if err := portIsReady(port); err != nil {
_, _ = fmt.Fprintf(os.Stderr, "waiting for port: %s\n", err)
break
}
return
}
}
}
func portIsReady(port string) error {
conn, err := net.Dial("tcp", net.JoinHostPort("localhost", port))
if err != nil {
return err
}
return conn.Close()
}

View file

@ -0,0 +1,27 @@
package testtool
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestGetFreePort(t *testing.T) {
p, err := GetFreePort()
require.NoError(t, err)
require.NotEmpty(t, p)
}
func TestWaitForPort(t *testing.T) {
p, err := GetFreePort()
require.NoError(t, err)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
WaitForPort(ctx, p)
require.Error(t, ctx.Err())
}