Skip to content

Commit

Permalink
add retry logic to flaky http test
Browse files Browse the repository at this point in the history
  • Loading branch information
jackgopack4 committed Nov 12, 2024
1 parent 7b31c96 commit 2a5b31d
Showing 1 changed file with 25 additions and 4 deletions.
29 changes: 25 additions & 4 deletions service/telemetry/metrics_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"fmt"
"net/http"
"testing"
"time"

io_prometheus_client "github.com/prometheus/client_model/go"
"github.com/prometheus/common/expfmt"
Expand Down Expand Up @@ -201,14 +202,34 @@ func createTestMetrics(t *testing.T, mp metric.MeterProvider) {
}

func getMetricsFromPrometheus(t *testing.T, endpoint string) map[string]*io_prometheus_client.MetricFamily {
req, err := http.NewRequest(http.MethodGet, endpoint, nil)
client := &http.Client{
Timeout: 10 * time.Second,
}
var (
req *http.Request
err error
resp *http.Response
)
req, err = http.NewRequest(http.MethodGet, endpoint, nil)
require.NoError(t, err)

rr, err := http.DefaultClient.Do(req)
require.NoError(t, err)
maxRetries := 5
for i := 0; i < maxRetries; i++ {
resp, err = client.Do(req)
if err == nil && resp.StatusCode == http.StatusOK {
break
}

if i < maxRetries-1 {
time.Sleep(2 * time.Second) // Wait before retrying
}
}
require.NoError(t, err, "failed to get metrics from Prometheus after %d attempts", maxRetries)
require.Equal(t, http.StatusOK, resp.StatusCode, "unexpected status code after %d attempts", maxRetries)
defer resp.Body.Close()

var parser expfmt.TextParser
parsed, err := parser.TextToMetricFamilies(rr.Body)
parsed, err := parser.TextToMetricFamilies(resp.Body)
require.NoError(t, err)

return parsed
Expand Down

0 comments on commit 2a5b31d

Please sign in to comment.