Skip to content

Commit 19b0207

Browse files
committed
fix: race condition in TestHealthServer_StartAndShutdown
Pre-bind to :0 to discover the port without racing on hs.addr, then close and let Start re-bind. This avoids the data race between the test goroutine reading hs.addr and the Start goroutine writing it.
1 parent 13ea3fc commit 19b0207

1 file changed

Lines changed: 15 additions & 12 deletions

File tree

internal/telegram/health_test.go

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package telegram
22

33
import (
44
"context"
5+
"net"
56
"net/http"
67
"strings"
78
"testing"
@@ -63,25 +64,27 @@ func TestHealthServer_EmptyAddrDoesNothing(t *testing.T) {
6364
}
6465

6566
func TestHealthServer_StartAndShutdown(t *testing.T) {
66-
hs := NewHealthServer("127.0.0.1:0")
67-
hs.SetReady() // mark ready so health check returns 200
67+
// Pre-bind to :0 to discover the port without racing on hs.addr
68+
ln, err := net.Listen("tcp", "127.0.0.1:0")
69+
if err != nil {
70+
t.Fatalf("failed to listen: %v", err)
71+
}
72+
addr := ln.Addr().String()
73+
ln.Close() // release it so Start can re-bind
74+
75+
hs := NewHealthServer(addr)
76+
hs.SetReady()
6877
ctx, cancel := context.WithCancel(context.Background())
6978

7079
errCh := make(chan error, 1)
7180
go func() {
7281
errCh <- hs.Start(ctx)
7382
}()
7483

75-
// Wait for server to start
76-
var resp *http.Response
77-
var err error
78-
for i := 0; i < 10; i++ {
79-
time.Sleep(50 * time.Millisecond)
80-
resp, err = http.Get("http://" + hs.addr + "/health")
81-
if err == nil {
82-
break
83-
}
84-
}
84+
// Give server time to start
85+
time.Sleep(50 * time.Millisecond)
86+
87+
resp, err := http.Get("http://" + addr + "/health")
8588
if err != nil {
8689
t.Fatalf("Failed to reach health server: %v", err)
8790
}

0 commit comments

Comments
 (0)