-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlimiter_test.go
More file actions
65 lines (50 loc) · 1.29 KB
/
limiter_test.go
File metadata and controls
65 lines (50 loc) · 1.29 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
// Copyright 2025 FishGoddess. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package goes
import (
"sync"
"testing"
"time"
)
// go test -v -cover -run=^TestLimiter$
func TestLimiter(t *testing.T) {
limit := 16
limiter := NewLimiter(uint(limit))
var countMap = make(map[int64]int, 16)
var lock sync.Mutex
totalCount := 10 * limit
for i := 0; i < totalCount; i++ {
limiter.Go(func() {
now := time.Now().UnixMilli() / 10
lock.Lock()
countMap[now] = countMap[now] + 1
lock.Unlock()
time.Sleep(10 * time.Millisecond)
})
}
limiter.Wait()
gotTotalCount := 0
for now, count := range countMap {
gotTotalCount = gotTotalCount + count
if count != limit {
t.Fatalf("now %d: count %d != limit %d", now, count, limit)
}
}
if gotTotalCount != totalCount {
t.Fatalf("gotTotalCount %d != totalCount %d", gotTotalCount, totalCount)
}
}
// go test -v -cover -run=^TestLimiterMinMax$
func TestLimiterMinMax(t *testing.T) {
limiter := NewLimiter(minLimit - 1)
got := cap(limiter.tokens)
if got != minLimit {
t.Fatalf("got %d != want %d", got, minLimit)
}
limiter = NewLimiter(maxLimit + 1)
got = cap(limiter.tokens)
if got != maxLimit {
t.Fatalf("got %d != want %d", got, maxLimit)
}
}