From a07059c7694ad81c7f49ee6d3f48a9ecaf8582d7 Mon Sep 17 00:00:00 2001 From: Arseny Balobanov Date: Sat, 15 Feb 2020 23:18:14 +0300 Subject: [PATCH] Replace context in WaitForPort with timeout. --- digitalclock/main_test.go | 8 +------- tools/testtool/freeport.go | 14 ++++++++------ tools/testtool/freeport_test.go | 15 ++------------- 3 files changed, 11 insertions(+), 26 deletions(-) diff --git a/digitalclock/main_test.go b/digitalclock/main_test.go index 20e8bff..83b83d8 100644 --- a/digitalclock/main_test.go +++ b/digitalclock/main_test.go @@ -1,7 +1,6 @@ package main import ( - "context" "encoding/json" "fmt" "image" @@ -58,12 +57,7 @@ func startServer(t *testing.T) (port string, stop func()) { <-done } - ctx, cancel := context.WithTimeout(context.Background(), time.Second*30) - defer cancel() - - testtool.WaitForPort(ctx, port) - if ctx.Err() != nil { - err = ctx.Err() + if err = testtool.WaitForPort(time.Second*30, port); err != nil { stop() } diff --git a/tools/testtool/freeport.go b/tools/testtool/freeport.go index 8f07e38..b31ef87 100644 --- a/tools/testtool/freeport.go +++ b/tools/testtool/freeport.go @@ -1,7 +1,6 @@ package testtool import ( - "context" "fmt" "net" "os" @@ -29,21 +28,24 @@ func GetFreePort() (string, error) { // WaitForPort tries to connect to given local port with constant backoff. // -// Can be canceled via ctx. -func WaitForPort(ctx context.Context, port string) { +// Returns error if port is not ready after timeout. +func WaitForPort(timeout time.Duration, port string) error { + stopTimer := time.NewTimer(timeout) + defer stopTimer.Stop() + t := time.NewTicker(time.Millisecond * 100) defer t.Stop() for { select { - case <-ctx.Done(): - return + case <-stopTimer.C: + return fmt.Errorf("timeout") case <-t.C: if err := portIsReady(port); err != nil { _, _ = fmt.Fprintf(os.Stderr, "waiting for port: %s\n", err) break } - return + return nil } } } diff --git a/tools/testtool/freeport_test.go b/tools/testtool/freeport_test.go index 4314c3b..f9cbbbb 100644 --- a/tools/testtool/freeport_test.go +++ b/tools/testtool/freeport_test.go @@ -1,7 +1,6 @@ package testtool import ( - "context" "net" "net/http" "net/http/httptest" @@ -27,22 +26,12 @@ func TestWaitForPort(t *testing.T) { _, port, err := net.SplitHostPort(u.Host) require.Nil(t, err) - ctx, cancel := context.WithTimeout(context.Background(), time.Second) - defer cancel() - - WaitForPort(ctx, port) - - require.NoError(t, ctx.Err()) + require.NoError(t, WaitForPort(time.Second, port)) } func TestWaitForPort_timeout(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()) + require.Error(t, WaitForPort(time.Second, p)) }