-
Notifications
You must be signed in to change notification settings - Fork 0
/
memory_store_test.go
75 lines (62 loc) · 1.85 KB
/
memory_store_test.go
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
package ratelimiter
import (
"testing"
"time"
)
// Helper function to create a new memoryStore
func newMemoryStore(limit int64, window time.Duration, stopCh *chan bool) *memoryStore {
ms := &memoryStore{}
c := RateLimiterConfig{}
c.StopChan = *stopCh
ms.init("temp", limit, window, c)
return ms
}
func TestMemoryStoreInitialization(t *testing.T) {
stopCh := make(chan bool)
ms := newMemoryStore(5, 10*time.Millisecond*10, &stopCh)
if ms.limit != 5 {
t.Errorf("Expected limit to be 5, got %d", ms.limit)
}
if ms.duration != 10*time.Millisecond*10 {
t.Errorf("Expected duration to be 10 seconds, got %v", ms.duration)
}
}
func TestIncrementAndCheck(t *testing.T) {
stopCh := make(chan bool)
ms := newMemoryStore(5, 10*time.Millisecond*10, &stopCh)
for i := int64(0); i < 5; i++ {
ok, _ := ms.incrementAndCheck()
if ms.count != i+1 {
t.Errorf("Expected count to be %d, got %d", i+1, ms.count)
}
if !ok {
t.Errorf("Expected rate to be within limit, but it is not")
}
}
}
func TestResetAfterWindow(t *testing.T) {
stopCh := make(chan bool)
ms := newMemoryStore(5, 1*time.Millisecond*10, &stopCh)
// Allow time for the ticker to reset the count
time.Sleep(2 * time.Millisecond * 10)
// After reset, count should be zero
ok, _ := ms.incrementAndCheck()
if ms.count != 1 {
t.Errorf("Expected count to be 1 after reset, got %d", ms.count)
}
if !ok {
t.Errorf("Expected rate to be within limit, but it is not")
}
}
func TestStopTicker(t *testing.T) {
stopCh := make(chan bool)
ms := newMemoryStore(5, 10*time.Millisecond*10, &stopCh)
// Stop the ticker and ensure it's no longer active
close(stopCh)
time.Sleep(1 * time.Millisecond * 10) // Allow time for goroutine to exit
// Check that incrementAndCheck still functions
ok, _ := ms.incrementAndCheck()
if ok {
t.Errorf("Expected rate to be out out to be out of limits")
}
}