Skip to content

Commit a672922

Browse files
author
Julien Pivotto
committed
test: use port polling to wait for server to start
Previously tests did not wait for the server to start listening on the port. This could lead to race conditions and flaky tests. This commit adds a port polling loop that waits for the server to start listening on the port before running the tests. Signed-off-by: Julien Pivotto <[email protected]>
1 parent c9d6337 commit a672922

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

web/handler_test.go

+26
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,11 @@ package web
1515

1616
import (
1717
"context"
18+
"net"
1819
"net/http"
1920
"sync"
2021
"testing"
22+
"time"
2123
)
2224

2325
// TestBasicAuthCache validates that the cache is working by calling a password
@@ -47,6 +49,8 @@ func TestBasicAuthCache(t *testing.T) {
4749
close(done)
4850
}()
4951

52+
waitForPort(t, port)
53+
5054
login := func(username, password string, code int) {
5155
client := &http.Client{}
5256
req, err := http.NewRequest("GET", "http://localhost"+port, nil)
@@ -115,6 +119,8 @@ func TestBasicAuthWithFakepassword(t *testing.T) {
115119
close(done)
116120
}()
117121

122+
waitForPort(t, port)
123+
118124
login := func() {
119125
client := &http.Client{}
120126
req, err := http.NewRequest("GET", "http://localhost"+port, nil)
@@ -163,6 +169,8 @@ func TestByPassBasicAuthVuln(t *testing.T) {
163169
close(done)
164170
}()
165171

172+
waitForPort(t, port)
173+
166174
login := func(username, password string) {
167175
client := &http.Client{}
168176
req, err := http.NewRequest("GET", "http://localhost"+port, nil)
@@ -211,6 +219,8 @@ func TestHTTPHeaders(t *testing.T) {
211219
close(done)
212220
}()
213221

222+
waitForPort(t, port)
223+
214224
client := &http.Client{}
215225
req, err := http.NewRequest("GET", "http://localhost"+port, nil)
216226
if err != nil {
@@ -232,3 +242,19 @@ func TestHTTPHeaders(t *testing.T) {
232242
}
233243
}
234244
}
245+
246+
func waitForPort(t *testing.T, addr string) {
247+
start := time.Now()
248+
for {
249+
conn, err := net.DialTimeout("tcp", addr, time.Second)
250+
if err == nil {
251+
conn.Close()
252+
return
253+
}
254+
if time.Since(start) >= 5*time.Second {
255+
t.Fatalf("timeout waiting for port %s: %s", addr, err)
256+
return
257+
}
258+
time.Sleep(time.Millisecond * 100)
259+
}
260+
}

0 commit comments

Comments
 (0)