-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub_rate_limiter_test.go
More file actions
87 lines (69 loc) · 2.35 KB
/
github_rate_limiter_test.go
File metadata and controls
87 lines (69 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package ghratelimit
import (
"context"
"fmt"
"net/http"
"testing"
"time"
)
// Mock response with rate limit headers
func mockResponse(remaining int64, reset time.Duration) *http.Response {
// Get the Unix timestamp for the reset time
resetTime := time.Now().Add(reset).Unix()
return &http.Response{
Header: map[string][]string{
"X-Ratelimit-Remaining": {fmt.Sprintf("%d", remaining)},
"X-Ratelimit-Reset": {fmt.Sprintf("%d", resetTime)},
},
}
}
// Test adding a response and triggering throttling
func TestGithubHeaderRateLimiter_AddResponseAndThrottle(t *testing.T) {
limiter := newGitHubHeaderRateLimiter(50)
// Create a response with rate limit headers below the threshold
resp := mockResponse(0, 2*time.Second) // Remaining below the threshold
// Add the response
limiter.AddResponse(resp)
time.Sleep(1 * time.Millisecond)
// Expect throttling to start and block
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
defer cancel()
err := limiter.Acquire(ctx)
if err != context.DeadlineExceeded {
t.Fatalf("expected context deadline exceeded error, got: %v", err)
}
}
// Test that manageThrottle processes responses correctly
func TestGithubHeaderRateLimiter_ManageThrottle(t *testing.T) {
t.Skip()
limiter := newGitHubHeaderRateLimiter(50)
// Create a response with rate limit headers below the threshold
resp := mockResponse(40, 50*time.Millisecond)
// Add the response
limiter.AddResponse(resp)
// Wait for the throttle to be released after the reset time
time.Sleep(100 * time.Millisecond)
// Try to acquire again, it should not block
ctx := context.Background()
err := limiter.Acquire(ctx)
if err != nil {
t.Fatalf("expected acquire to pass, got error: %v", err)
}
}
// Test that releasing with a nil response does not cause issues
func TestRateLimiter_ReleaseNilResponse(t *testing.T) {
limiter := newRateLimiter(http.DefaultTransport, 10)
// Acquire a slot in the rate limiter
ctx := context.Background()
err := limiter.Acquire(ctx)
if err != nil {
t.Fatalf("expected to acquire a slot, got error: %v", err)
}
// Release with a nil response, should not cause any errors
limiter.Release(nil)
// Acquire again to ensure the slot was properly released
err = limiter.Acquire(ctx)
if err != nil {
t.Fatalf("expected to acquire a slot after releasing nil response, got error: %v", err)
}
}