|
5 | 5 | "net/http/httptest" |
6 | 6 | "os" |
7 | 7 | "testing" |
| 8 | + "time" |
8 | 9 |
|
| 10 | + h "github.com/hashicorp/go-retryablehttp" |
9 | 11 | "github.com/stretchr/testify/require" |
10 | 12 |
|
11 | 13 | "github.com/launchdarkly/ld-find-code-refs/v2/internal/log" |
@@ -234,3 +236,41 @@ func TestCountByProjectAndFlag(t *testing.T) { |
234 | 236 | require.Equal(t, count, want) |
235 | 237 |
|
236 | 238 | } |
| 239 | + |
| 240 | +func TestRateLimitBackoff(t *testing.T) { |
| 241 | + // Backoff instance where the time is always 0 |
| 242 | + backoff := RateLimitBackoff(func() time.Time { return time.Unix(0, 0) }, h.DefaultBackoff) |
| 243 | + |
| 244 | + defaultBackoff := time.Second * time.Duration(1) |
| 245 | + |
| 246 | + invalidRateLimitReset := "abc" |
| 247 | + validRateLimitReset := "2000" |
| 248 | + pastRateLimitReset := "-1000" |
| 249 | + specs := []struct { |
| 250 | + name string |
| 251 | + status int |
| 252 | + rateLimitReset *string |
| 253 | + expected time.Duration |
| 254 | + }{ |
| 255 | + {"falls back to default backoff due to status", http.StatusBadGateway, nil, defaultBackoff}, |
| 256 | + {"falls back to default backoff due to missing header", http.StatusTooManyRequests, nil, defaultBackoff}, |
| 257 | + {"falls back to default backoff due to invalid header", http.StatusTooManyRequests, &invalidRateLimitReset, defaultBackoff}, |
| 258 | + {"returns difference between reset and current time", http.StatusTooManyRequests, &validRateLimitReset, time.Second * time.Duration(2)}, |
| 259 | + {"returns 0 because reset is in past", http.StatusTooManyRequests, &pastRateLimitReset, time.Duration(0)}, |
| 260 | + } |
| 261 | + for _, tt := range specs { |
| 262 | + t.Run(tt.name, func(t *testing.T) { |
| 263 | + resp := &http.Response{ |
| 264 | + StatusCode: tt.status, |
| 265 | + Header: make(http.Header), |
| 266 | + } |
| 267 | + |
| 268 | + if tt.rateLimitReset != nil { |
| 269 | + resp.Header.Set("X-Ratelimit-Reset", *tt.rateLimitReset) |
| 270 | + } |
| 271 | + |
| 272 | + actual := backoff(defaultBackoff, time.Second*time.Duration(10), 0, resp) |
| 273 | + require.Equal(t, tt.expected, actual) |
| 274 | + }) |
| 275 | + } |
| 276 | +} |
0 commit comments