|
| 1 | +package ratelimiter |
| 2 | + |
| 3 | +import ( |
| 4 | + "testing" |
| 5 | + "time" |
| 6 | +) |
| 7 | + |
| 8 | +func newSlidingWindowCounter(windowSize time.Duration, maxRequests int) *SlidingWindowCounter { |
| 9 | + return NewSlidingWindowCounter(windowSize, maxRequests) |
| 10 | +} |
| 11 | + |
| 12 | +func TestSlidingWindowCounter_AllowRequest(t *testing.T) { |
| 13 | + tests := []struct { |
| 14 | + windowSize time.Duration |
| 15 | + maxRequests int |
| 16 | + requests int |
| 17 | + expectAllowed bool |
| 18 | + }{ |
| 19 | + {time.Second * 10, 5, 5, true}, // within limit |
| 20 | + {time.Second * 10, 5, 6, false}, // exceeding limit |
| 21 | + {time.Second * 10, 5, 10, false}, // far exceeding limit |
| 22 | + {time.Second * 5, 2, 2, true}, // within smaller window |
| 23 | + {time.Second * 5, 2, 3, false}, // exceeding limit in smaller window |
| 24 | + } |
| 25 | + |
| 26 | + for _, tt := range tests { |
| 27 | + t.Run("", func(t *testing.T) { |
| 28 | + swc := newSlidingWindowCounter(tt.windowSize, tt.maxRequests) |
| 29 | + |
| 30 | + for i := 0; i < tt.requests; i++ { |
| 31 | + allowed := swc.AllowRequest() |
| 32 | + if i < tt.maxRequests && !allowed { |
| 33 | + t.Errorf("Request %d was not allowed, but it should be", i) |
| 34 | + } |
| 35 | + if i >= tt.maxRequests && allowed { |
| 36 | + t.Errorf("Request %d was allowed, but it should not be", i) |
| 37 | + } |
| 38 | + } |
| 39 | + }) |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +func TestSlidingWindowCounter_WindowExpiration(t *testing.T) { |
| 44 | + windowSize := time.Second * 2 |
| 45 | + maxRequests := 2 |
| 46 | + |
| 47 | + swc := newSlidingWindowCounter(windowSize, maxRequests) |
| 48 | + |
| 49 | + if !swc.AllowRequest() { |
| 50 | + t.Errorf("First request should be allowed") |
| 51 | + } |
| 52 | + |
| 53 | + if !swc.AllowRequest() { |
| 54 | + t.Errorf("Second request should be allowed") |
| 55 | + } |
| 56 | + |
| 57 | + time.Sleep(windowSize + time.Second) |
| 58 | + |
| 59 | + if swc.AllowRequest() { |
| 60 | + t.Errorf("Request after window expiration should not be allowed") |
| 61 | + } |
| 62 | +} |
0 commit comments