From 256ac64f4e31f615f021250d51c7ed2beaed0edb Mon Sep 17 00:00:00 2001 From: Muhammad Waqar Date: Sat, 25 Jul 2026 02:21:22 -0400 Subject: [PATCH] fix: eliminate port race in setupFakeEnvoyStats test helper net.Listen(":0") followed by l.Close() and a later ListenAndServe() on the resulting port number leaves a window where another process (or a concurrently running test) can grab that exact ephemeral port before the re-bind happens, causing TestGetTotalConnections to fail with connection errors on loaded machines. Serve on the already-bound listener directly via s.Serve(l) so the port is never released. Signed-off-by: Muhammad Waqar --- internal/cmd/envoy/shutdown_manager_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/cmd/envoy/shutdown_manager_test.go b/internal/cmd/envoy/shutdown_manager_test.go index e827056d2c..d6a53e6761 100644 --- a/internal/cmd/envoy/shutdown_manager_test.go +++ b/internal/cmd/envoy/shutdown_manager_test.go @@ -21,9 +21,9 @@ import ( // setupFakeEnvoyStats set up an HTTP server return content func setupFakeEnvoyStats(t *testing.T, content string) *http.Server { + // Reuse the bound listener instead of closing and re-binding the port. l, err := net.Listen("tcp", ":0") //nolint: gosec require.NoError(t, err) - require.NoError(t, l.Close()) mux := http.NewServeMux() mux.HandleFunc("/", func(writer http.ResponseWriter, _ *http.Request) { writer.Header().Set("Content-Type", "application/json") @@ -39,7 +39,7 @@ func setupFakeEnvoyStats(t *testing.T, content string) *http.Server { } t.Logf("start to listen at %s ", addr) go func() { - if err := s.ListenAndServe(); err != nil { + if err := s.Serve(l); err != nil { fmt.Println("fail to listen: ", err) } }()