|
| 1 | +package integration |
| 2 | + |
| 3 | +import ( |
| 4 | + "io" |
| 5 | + "net/http" |
| 6 | + "net/http/httptest" |
| 7 | + "strconv" |
| 8 | + "strings" |
| 9 | + "testing" |
| 10 | + "time" |
| 11 | + |
| 12 | + "github.com/checkmarx/ast-cli/internal/wrappers" |
| 13 | + "github.com/stretchr/testify/assert" |
| 14 | +) |
| 15 | + |
| 16 | +func mockAPI(repeatCode, repeatCount int, headerName, headerValue string) func() (*http.Response, error) { |
| 17 | + attempt := 0 |
| 18 | + return func() (*http.Response, error) { |
| 19 | + rec := httptest.NewRecorder() |
| 20 | + if attempt < repeatCount { |
| 21 | + rec.Code = repeatCode |
| 22 | + if headerName != "" { |
| 23 | + rec.Header().Set(headerName, headerValue) |
| 24 | + } |
| 25 | + } else { |
| 26 | + rec.Code = http.StatusOK |
| 27 | + } |
| 28 | + attempt++ |
| 29 | + resp := rec.Result() |
| 30 | + resp.Body = io.NopCloser(strings.NewReader("")) |
| 31 | + return resp, nil |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +func runRateLimitTest(t *testing.T, config *wrappers.SCMRateLimitConfig, repeatCode, repeatCount int, headerName string) { |
| 36 | + reset := strconv.FormatInt(time.Now().Unix(), 10) // simulate immediate retry |
| 37 | + api := mockAPI(repeatCode, repeatCount, headerName, reset) |
| 38 | + |
| 39 | + start := time.Now() |
| 40 | + resp, err := wrappers.WithSCMRateLimitRetry(config, api) |
| 41 | + if resp != nil { |
| 42 | + defer resp.Body.Close() |
| 43 | + } |
| 44 | + |
| 45 | + assert := assert.New(t) |
| 46 | + assert.NoError(err) |
| 47 | + assert.NotNil(resp) |
| 48 | + assert.Equal(http.StatusOK, resp.StatusCode) |
| 49 | + |
| 50 | + elapsed := time.Since(start) |
| 51 | + assert.GreaterOrEqual(elapsed, config.DefaultWaitTime) |
| 52 | +} |
| 53 | + |
| 54 | +func TestGitHubRateLimit_SuccessAfterRetryOne(t *testing.T) { |
| 55 | + runRateLimitTest(t, wrappers.GitHubRateLimitConfig, 429, 1, "X-RateLimit-Reset") |
| 56 | +} |
| 57 | + |
| 58 | +func TestGitHubRateLimit_SuccessAfterRetryTwo(t *testing.T) { |
| 59 | + runRateLimitTest(t, wrappers.GitHubRateLimitConfig, 429, 2, "X-RateLimit-Reset") |
| 60 | +} |
| 61 | + |
| 62 | +func TestGitHubRateLimit_SuccessAfterRetryThree(t *testing.T) { |
| 63 | + runRateLimitTest(t, wrappers.GitHubRateLimitConfig, 403, 3, "X-RateLimit-Reset") |
| 64 | +} |
| 65 | + |
| 66 | +func TestGitLabRateLimit_SuccessAfterRetryOne(t *testing.T) { |
| 67 | + runRateLimitTest(t, wrappers.GitLabRateLimitConfig, 429, 1, "RateLimit-Reset") |
| 68 | +} |
| 69 | + |
| 70 | +func TestBitBucketRateLimit_SuccessAfterRetryOne(t *testing.T) { |
| 71 | + runRateLimitTest(t, wrappers.BitbucketRateLimitConfig, 429, 1, "X-RateLimit-Reset") |
| 72 | +} |
| 73 | + |
| 74 | +func TestAzureRateLimit_SuccessAfterRetryOne(t *testing.T) { |
| 75 | + runRateLimitTest(t, wrappers.AzureRateLimitConfig, 429, 1, "X-Ratelimit-Reset") |
| 76 | +} |
0 commit comments