Skip to content

Commit

Permalink
make tests less flaky by waiting for server up
Browse files Browse the repository at this point in the history
  • Loading branch information
umputun committed Dec 9, 2024
1 parent 1222d9f commit 8d7ed39
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
11 changes: 10 additions & 1 deletion app/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,16 @@ func Test_activateServerOnly(t *testing.T) {
assert.NoError(t, err)
close(done)
}()
time.Sleep(time.Millisecond * 100)

// Wait for server to be ready
require.Eventually(t, func() bool {
resp, err := http.Get("http://localhost:9988/ping")
if err != nil {
return false
}
defer resp.Body.Close()
return resp.StatusCode == http.StatusOK
}, time.Second*2, time.Millisecond*50, "server did not start")

resp, err := http.Get("http://localhost:9988/ping")
require.NoError(t, err)
Expand Down
15 changes: 11 additions & 4 deletions app/webapi/webapi_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,6 @@ func TestServer_RunAuth(t *testing.T) {
require.NoError(t, err)
t.Logf("hashed password: %s", string(hashedPassword))

// run two servers - one with plain password and one with bcrypt hash
tests := []struct {
name string
srv *Server
Expand Down Expand Up @@ -117,14 +116,23 @@ func TestServer_RunAuth(t *testing.T) {
assert.NoError(t, err)
close(done)
}()
time.Sleep(100 * time.Millisecond)

// Wait for server to be ready
require.Eventually(t, func() bool {
resp, err := http.Get(fmt.Sprintf("http://localhost:%s/ping", tc.port))
if err != nil {
return false
}
defer resp.Body.Close()
return resp.StatusCode == http.StatusOK
}, time.Second*2, time.Millisecond*50, "server did not start")

t.Run("ping", func(t *testing.T) {
resp, err := http.Get(fmt.Sprintf("http://localhost:%s/ping", tc.port))
assert.NoError(t, err)
t.Log(resp)
defer resp.Body.Close()
assert.Equal(t, http.StatusOK, resp.StatusCode) // no auth on ping
assert.Equal(t, http.StatusOK, resp.StatusCode)
})

t.Run("check unauthorized, no basic auth", func(t *testing.T) {
Expand Down Expand Up @@ -175,7 +183,6 @@ func TestServer_RunAuth(t *testing.T) {
})
}
cancel()
// wait for all servers to complete
for _, done := range doneChannels {
<-done
}
Expand Down

0 comments on commit 8d7ed39

Please sign in to comment.