@@ -18,8 +18,41 @@ import (
1818 "strings"
1919 "testing"
2020 "time"
21+ "context"
2122)
2223
24+ // waitForServerReady polls the server until it's ready to accept connections
25+ func waitForServerReady (t * testing.T , addr string , useTLS bool , timeout time.Duration ) {
26+ t .Helper ()
27+
28+ ctx , cancel := context .WithTimeout (context .Background (), timeout )
29+ defer cancel ()
30+
31+ for {
32+ select {
33+ case <- ctx .Done ():
34+ t .Fatalf ("server at %s did not become ready within %v" , addr , timeout )
35+ default :
36+ }
37+
38+ var conn net.Conn
39+ var err error
40+
41+ if useTLS {
42+ conn , err = tls .Dial ("tcp" , addr , & tls.Config {InsecureSkipVerify : true })
43+ } else {
44+ conn , err = net .Dial ("tcp" , addr )
45+ }
46+
47+ if err == nil {
48+ conn .Close ()
49+ return // Server is ready
50+ }
51+
52+ time .Sleep (1 * time .Millisecond )
53+ }
54+ }
55+
2356// startCONNECTProxy starts an HTTP or HTTPS CONNECT proxy on a random port.
2457// It returns the proxy URL and a channel that receives the protocol observed by
2558// the proxy handler for each CONNECT request.
@@ -76,13 +109,14 @@ func startCONNECTProxy(t *testing.T, useTLS bool) (proxyURL *url.URL, obsCh <-ch
76109 cert := generateTestCert (t , "127.0.0.1" )
77110 srv .TLSConfig = & tls.Config {Certificates : []tls.Certificate {cert }}
78111 go srv .ServeTLS (ln , "" , "" )
79- // Give the TLS server a moment to start up to avoid race conditions
80- time .Sleep (10 * time .Millisecond )
81112 } else {
82113 go srv .Serve (ln )
83114 }
84115 t .Cleanup (func () { srv .Close () })
85116
117+ // Wait for the server to be ready
118+ waitForServerReady (t , ln .Addr ().String (), useTLS , 5 * time .Second )
119+
86120 scheme := "http"
87121 if useTLS {
88122 scheme = "https"
@@ -146,13 +180,14 @@ func startCONNECTProxyWithAuth(t *testing.T, useTLS bool, wantUser, wantPass str
146180 cert := generateTestCert (t , "127.0.0.1" )
147181 srv .TLSConfig = & tls.Config {Certificates : []tls.Certificate {cert }}
148182 go srv .ServeTLS (ln , "" , "" )
149- // Give the TLS server a moment to start up to avoid race conditions
150- time .Sleep (10 * time .Millisecond )
151183 } else {
152184 go srv .Serve (ln )
153185 }
154186 t .Cleanup (func () { srv .Close () })
155187
188+ // Wait for the server to be ready
189+ waitForServerReady (t , ln .Addr ().String (), useTLS , 5 * time .Second )
190+
156191 scheme := "http"
157192 if useTLS {
158193 scheme = "https"
0 commit comments