remote-write: refactor TestClientRetryAfter

The new version features a set of test cases that simplify the addition
of new HTTP status codes.

Signed-off-by: William Dumont <william.dumont@grafana.com>
This commit is contained in:
William Dumont 2023-09-07 16:36:29 +02:00 committed by Bryan Boreham
parent 9b85354acd
commit febd62a23e

View file

@ -85,12 +85,21 @@ func TestStoreHTTPErrorHandling(t *testing.T) {
} }
func TestClientRetryAfter(t *testing.T) { func TestClientRetryAfter(t *testing.T) {
server := httptest.NewServer( setupServer := func(statusCode int) *httptest.Server {
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return httptest.NewServer(
http.Error(w, longErrMessage, http.StatusTooManyRequests) http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
}), http.Error(w, longErrMessage, statusCode)
) }),
defer server.Close() )
}
getClientConfig := func(serverURL *url.URL, retryOnRateLimit bool) *ClientConfig {
return &ClientConfig{
URL: &config_util.URL{URL: serverURL},
Timeout: model.Duration(time.Second),
RetryOnRateLimit: retryOnRateLimit,
}
}
getClient := func(conf *ClientConfig) WriteClient { getClient := func(conf *ClientConfig) WriteClient {
hash, err := toHash(conf) hash, err := toHash(conf)
@ -100,30 +109,31 @@ func TestClientRetryAfter(t *testing.T) {
return c return c
} }
serverURL, err := url.Parse(server.URL) testCases := []struct {
require.NoError(t, err) name string
statusCode int
conf := &ClientConfig{ retryOnRateLimit bool
URL: &config_util.URL{URL: serverURL}, expectedRecoverable bool
Timeout: model.Duration(time.Second), }{
RetryOnRateLimit: false, {"TooManyRequests - No Retry", http.StatusTooManyRequests, false, false},
{"TooManyRequests - With Retry", http.StatusTooManyRequests, true, true},
} }
var recErr RecoverableError for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
server := setupServer(tc.statusCode)
defer server.Close()
c := getClient(conf) serverURL, err := url.Parse(server.URL)
err = c.Store(context.Background(), []byte{}, 0) require.NoError(t, err)
require.False(t, errors.As(err, &recErr), "Recoverable error not expected.")
conf = &ClientConfig{ c := getClient(getClientConfig(serverURL, tc.retryOnRateLimit))
URL: &config_util.URL{URL: serverURL},
Timeout: model.Duration(time.Second), var recErr RecoverableError
RetryOnRateLimit: true, err = c.Store(context.Background(), []byte{}, 0)
require.Equal(t, tc.expectedRecoverable, errors.As(err, &recErr), "Mismatch in expected recoverable error status.")
})
} }
c = getClient(conf)
err = c.Store(context.Background(), []byte{}, 0)
require.True(t, errors.As(err, &recErr), "Recoverable error was expected.")
} }
func TestRetryAfterDuration(t *testing.T) { func TestRetryAfterDuration(t *testing.T) {