This repository has been archived by the owner on Apr 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
concurrent_limiter_test.go
120 lines (109 loc) · 2.43 KB
/
concurrent_limiter_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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package concurrentlimiter
import (
"errors"
"fmt"
"net/http/httptest"
"os"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/vicanso/elton"
)
func TestNoLockFunction(t *testing.T) {
assert := assert.New(t)
defer func() {
r := recover()
assert.Equal(r.(error), errRequireLockFunction)
}()
New(Config{})
}
func TestConcurrentLimiter(t *testing.T) {
m := new(sync.Map)
fn := New(Config{
Keys: []string{
":ip",
"h:X-Token",
"q:type",
"p:id",
"account",
},
Lock: func(key string, c *elton.Context) (success bool, unlock func(), err error) {
if key != "192.0.2.1,xyz,1,123,tree.xie" {
err = errors.New("key is invalid")
return
}
_, loaded := m.LoadOrStore(key, 1)
// 如果已存在,则获取销失败
if loaded {
return
}
success = true
// 删除锁
unlock = func() {
m.Delete(key)
}
return
},
})
req := httptest.NewRequest("POST", "/users/login?type=1", nil)
resp := httptest.NewRecorder()
c := elton.NewContext(resp, req)
req.Header.Set("X-Token", "xyz")
c.RequestBody = []byte(`{
"account": "tree.xie"
}`)
c.Params = map[string]string{
"id": "123",
}
t.Run("first", func(t *testing.T) {
assert := assert.New(t)
done := false
c.Next = func() error {
done = true
return nil
}
err := fn(c)
assert.Nil(err)
assert.True(done)
})
t.Run("too frequently", func(t *testing.T) {
assert := assert.New(t)
done := false
c.Next = func() error {
time.Sleep(100 * time.Millisecond)
done = true
return nil
}
go func() {
time.Sleep(10 * time.Millisecond)
e := fn(c)
assert.Equal(e.Error(), "category=elton-concurrent-limiter, message=submit too frequently")
}()
err := fn(c)
// 登录限制,192.0.2.1,xyz,1,123,tree.xie
assert.Nil(err)
assert.True(done)
})
t.Run("lock function return error", func(t *testing.T) {
assert := assert.New(t)
c.Params = map[string]string{}
err := fn(c)
assert.Equal(err.Error(), "message=key is invalid")
})
}
// https://stackoverflow.com/questions/50120427/fail-unit-tests-if-coverage-is-below-certain-percentage
func TestMain(m *testing.M) {
// call flag.Parse() here if TestMain uses flags
rc := m.Run()
// rc 0 means we've passed,
// and CoverMode will be non empty if run with -cover
if rc == 0 && testing.CoverMode() != "" {
c := testing.Coverage()
if c < 0.9 {
fmt.Println("Tests passed but coverage failed at", c)
rc = -1
}
}
os.Exit(rc)
}