[go: nahoru, domu]

Skip to content

Commit

Permalink
test: use port polling to wait for server to start
Browse files Browse the repository at this point in the history
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 <roidelapluie@o11y.eu>
  • Loading branch information
roidelapluie committed Mar 7, 2023
1 parent c9d6337 commit a672922
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions web/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,11 @@ package web

import (
"context"
"net"
"net/http"
"sync"
"testing"
"time"
)

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

waitForPort(t, port)

login := func(username, password string, code int) {
client := &http.Client{}
req, err := http.NewRequest("GET", "http://localhost"+port, nil)
Expand Down Expand Up @@ -115,6 +119,8 @@ func TestBasicAuthWithFakepassword(t *testing.T) {
close(done)
}()

waitForPort(t, port)

login := func() {
client := &http.Client{}
req, err := http.NewRequest("GET", "http://localhost"+port, nil)
Expand Down Expand Up @@ -163,6 +169,8 @@ func TestByPassBasicAuthVuln(t *testing.T) {
close(done)
}()

waitForPort(t, port)

login := func(username, password string) {
client := &http.Client{}
req, err := http.NewRequest("GET", "http://localhost"+port, nil)
Expand Down Expand Up @@ -211,6 +219,8 @@ func TestHTTPHeaders(t *testing.T) {
close(done)
}()

waitForPort(t, port)

client := &http.Client{}
req, err := http.NewRequest("GET", "http://localhost"+port, nil)
if err != nil {
Expand All @@ -232,3 +242,19 @@ func TestHTTPHeaders(t *testing.T) {
}
}
}

func waitForPort(t *testing.T, addr string) {
start := time.Now()
for {
conn, err := net.DialTimeout("tcp", addr, time.Second)
if err == nil {
conn.Close()
return
}
if time.Since(start) >= 5*time.Second {
t.Fatalf("timeout waiting for port %s: %s", addr, err)
return
}
time.Sleep(time.Millisecond * 100)
}
}

0 comments on commit a672922

Please sign in to comment.