Support testing.TB as logger for WaitForPort.

This commit is contained in:
Arseny Balobanov 2020-02-19 00:22:00 +03:00
parent b67bb030c3
commit b93d1be1dc
2 changed files with 8 additions and 5 deletions

View file

@ -3,7 +3,6 @@ package testtool
import ( import (
"fmt" "fmt"
"net" "net"
"os"
"strconv" "strconv"
"time" "time"
) )
@ -26,10 +25,14 @@ func GetFreePort() (string, error) {
return strconv.Itoa(p), nil return strconv.Itoa(p), nil
} }
type logger interface {
Logf(format string, args ...interface{})
}
// WaitForPort tries to connect to given local port with constant backoff. // WaitForPort tries to connect to given local port with constant backoff.
// //
// Returns error if port is not ready after timeout. // Returns error if port is not ready after timeout.
func WaitForPort(timeout time.Duration, port string) error { func WaitForPort(l logger, timeout time.Duration, port string) error {
stopTimer := time.NewTimer(timeout) stopTimer := time.NewTimer(timeout)
defer stopTimer.Stop() defer stopTimer.Stop()
@ -42,7 +45,7 @@ func WaitForPort(timeout time.Duration, port string) error {
return fmt.Errorf("no server started listening on port %s after timeout %d", port, timeout) return fmt.Errorf("no server started listening on port %s after timeout %d", port, timeout)
case <-t.C: case <-t.C:
if err := portIsReady(port); err != nil { if err := portIsReady(port); err != nil {
_, _ = fmt.Fprintf(os.Stderr, "waiting for port: %s\n", err) l.Logf("waiting for port: %s\n", err)
break break
} }
return nil return nil

View file

@ -26,12 +26,12 @@ func TestWaitForPort(t *testing.T) {
_, port, err := net.SplitHostPort(u.Host) _, port, err := net.SplitHostPort(u.Host)
require.Nil(t, err) require.Nil(t, err)
require.NoError(t, WaitForPort(time.Second, port)) require.NoError(t, WaitForPort(t, time.Second, port))
} }
func TestWaitForPort_timeout(t *testing.T) { func TestWaitForPort_timeout(t *testing.T) {
p, err := GetFreePort() p, err := GetFreePort()
require.NoError(t, err) require.NoError(t, err)
require.Error(t, WaitForPort(time.Second, p)) require.Error(t, WaitForPort(t, time.Second, p))
} }