Skip to content

Commit 8ee7ae1

Browse files
authored
test: deflake pprof/TestRun_enabled (#1411)
**Description** This fixes the flaky pprof/TestRun_enabled test. Signed-off-by: Takeshi Yoneda <[email protected]>
1 parent 6963125 commit 8ee7ae1

File tree

1 file changed

+28
-13
lines changed

1 file changed

+28
-13
lines changed

internal/pprof/pprof_test.go

Lines changed: 28 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,38 +7,53 @@ package pprof
77

88
import (
99
"context"
10+
"fmt"
1011
"io"
1112
"net/http"
13+
"strings"
1214
"testing"
15+
"time"
1316

1417
"github.com/stretchr/testify/require"
18+
19+
internaltesting "github.com/envoyproxy/ai-gateway/internal/testing"
1520
)
1621

1722
func TestRun_disabled(t *testing.T) {
1823
t.Setenv(DisableEnvVarKey, "anything")
1924
ctx, cancel := context.WithCancel(context.Background())
25+
defer cancel()
2026
Run(ctx)
2127
// Try accessing the pprof server here if needed.
2228
response, err := http.Get("http://localhost:6060/debug/pprof/") //nolint:bodyclose
2329
require.Error(t, err)
2430
require.Nil(t, response)
25-
cancel()
2631
}
2732

2833
func TestRun_enabled(t *testing.T) {
2934
ctx, cancel := context.WithCancel(context.Background())
35+
defer cancel()
3036
Run(ctx)
31-
// Try accessing the pprof server here if needed.
32-
resp, err := http.Get("http://localhost:6060/debug/pprof/cmdline")
33-
require.NoError(t, err)
34-
defer func() {
35-
require.NoError(t, resp.Body.Close())
36-
}()
37-
require.NotNil(t, resp)
38-
body, err := io.ReadAll(resp.Body)
39-
require.NoError(t, err)
40-
require.Contains(t, string(body),
37+
// Use eventually to avoid flake when the server is not yet started by the time we access it.
38+
internaltesting.RequireEventuallyNoError(t, func() error {
39+
resp, err := http.Get("http://localhost:6060/debug/pprof/cmdline")
40+
if err != nil {
41+
return err
42+
}
43+
defer func() {
44+
_ = resp.Body.Close()
45+
}()
46+
if resp.StatusCode != http.StatusOK {
47+
return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
48+
}
49+
body, err := io.ReadAll(resp.Body)
50+
if err != nil {
51+
return err
52+
}
4153
// Test binary name should be present in the cmdline output.
42-
"pprof.test")
43-
cancel()
54+
if !strings.Contains(string(body), "pprof.test") {
55+
return fmt.Errorf("unexpected body: %s", string(body))
56+
}
57+
return nil
58+
}, 3*time.Second, 100*time.Millisecond)
4459
}

0 commit comments

Comments
 (0)