Replace context in WaitForPort with timeout.
This commit is contained in:
parent
aa7c9ae7c5
commit
e1c3ec8cd0
2 changed files with 10 additions and 19 deletions
|
@ -1,7 +1,6 @@
|
||||||
package testtool
|
package testtool
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"os"
|
"os"
|
||||||
|
@ -29,21 +28,24 @@ func GetFreePort() (string, error) {
|
||||||
|
|
||||||
// WaitForPort tries to connect to given local port with constant backoff.
|
// WaitForPort tries to connect to given local port with constant backoff.
|
||||||
//
|
//
|
||||||
// Can be canceled via ctx.
|
// Returns error if port is not ready after timeout.
|
||||||
func WaitForPort(ctx context.Context, port string) {
|
func WaitForPort(timeout time.Duration, port string) error {
|
||||||
|
stopTimer := time.NewTimer(timeout)
|
||||||
|
defer stopTimer.Stop()
|
||||||
|
|
||||||
t := time.NewTicker(time.Millisecond * 100)
|
t := time.NewTicker(time.Millisecond * 100)
|
||||||
defer t.Stop()
|
defer t.Stop()
|
||||||
|
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-stopTimer.C:
|
||||||
return
|
return fmt.Errorf("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)
|
_, _ = fmt.Fprintf(os.Stderr, "waiting for port: %s\n", err)
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
return
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,7 +1,6 @@
|
||||||
package testtool
|
package testtool
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
|
@ -27,22 +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)
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
require.NoError(t, WaitForPort(time.Second, port))
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
WaitForPort(ctx, port)
|
|
||||||
|
|
||||||
require.NoError(t, ctx.Err())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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)
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
require.Error(t, WaitForPort(time.Second, p))
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
WaitForPort(ctx, p)
|
|
||||||
|
|
||||||
require.Error(t, ctx.Err())
|
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue