From 44c2bf148895863eede773997c9db6763bc8c845 Mon Sep 17 00:00:00 2001 From: Seth Hoenig Date: Tue, 2 Aug 2022 09:57:58 -0500 Subject: [PATCH] checks: better goroutine handling for test tcp server This PR hopefully fixes a race condition of our little test tcp server that the check observer is making connections against for test cases. The tcp listener would either startup too slow or exit too soon. --- .../serviceregistration/checks/client_test.go | 25 +++++++++++++------ 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/client/serviceregistration/checks/client_test.go b/client/serviceregistration/checks/client_test.go index 2f6cb7fb4..660395025 100644 --- a/client/serviceregistration/checks/client_test.go +++ b/client/serviceregistration/checks/client_test.go @@ -311,7 +311,7 @@ func TestChecker_Do_TCP(t *testing.T) { switch tc.tcpMode { case "ok": // simulate tcp server by listening - go tcpServer(ctx, tc.tcpPort) + tcpServer(t, ctx, tc.tcpPort) case "hang": // simulate tcp hang by setting an already expired context timeout, stop := context.WithDeadline(ctx, now.Add(-1*time.Second)) @@ -327,16 +327,25 @@ func TestChecker_Do_TCP(t *testing.T) { } } -func tcpServer(ctx context.Context, port int) { +// tcpServer will start a tcp listener that accepts connections and closes them. +// The caller can close the listener by cancelling ctx. +func tcpServer(t *testing.T, ctx context.Context, port int) { var lc net.ListenConfig - l, _ := lc.Listen(ctx, "tcp", net.JoinHostPort( + l, err := lc.Listen(ctx, "tcp", net.JoinHostPort( "localhost", fmt.Sprintf("%d", port), )) - defer func() { + must.NoError(t, err, must.Sprint("port", port)) + t.Cleanup(func() { _ = l.Close() - }() - con, _ := l.Accept() - defer func() { - _ = con.Close() + }) + + go func() { + // caller can stop us by cancelling ctx + for { + _, acceptErr := l.Accept() + if acceptErr != nil { + return + } + } }() }