-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
throttle_test.go
103 lines (89 loc) · 2.24 KB
/
throttle_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
package rest
import (
"net/http"
"net/http/httptest"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestThrottle(t *testing.T) {
thrMw := Throttle(10)
var calls int32
ts := httptest.NewServer(thrMw(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
atomic.AddInt32(&calls, 1)
time.Sleep(200 * time.Millisecond)
})))
defer ts.Close()
var okStatus, badStatus int32
var wg sync.WaitGroup
wg.Add(100)
for i := 0; i < 100; i++ {
go func() {
defer wg.Done()
resp, err := http.Get(ts.URL)
require.NoError(t, err)
defer resp.Body.Close()
switch resp.StatusCode {
case 200:
atomic.AddInt32(&okStatus, 1)
case 503:
atomic.AddInt32(&badStatus, 1)
default:
t.Errorf("unexpected status %d", resp.StatusCode)
}
}()
}
wg.Wait()
// two more calls, should pass
resp, err := http.Get(ts.URL)
require.NoError(t, err)
_ = resp.Body.Close()
resp, err = http.Get(ts.URL)
require.NoError(t, err)
_ = resp.Body.Close()
assert.Equal(t, int32(12), atomic.LoadInt32(&calls))
assert.Equal(t, int32(10), atomic.LoadInt32(&okStatus))
assert.Equal(t, int32(90), atomic.LoadInt32(&badStatus))
}
func TestThrottleDisabled(t *testing.T) {
thrMw := Throttle(0)
var calls int32
ts := httptest.NewServer(thrMw(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
atomic.AddInt32(&calls, 1)
time.Sleep(200 * time.Millisecond)
})))
defer ts.Close()
var okStatus, badStatus int32
var wg sync.WaitGroup
wg.Add(100)
for i := 0; i < 100; i++ {
go func() {
defer wg.Done()
resp, err := http.Get(ts.URL)
require.NoError(t, err)
defer resp.Body.Close()
switch resp.StatusCode {
case 200:
atomic.AddInt32(&okStatus, 1)
case 503:
atomic.AddInt32(&badStatus, 1)
default:
t.Errorf("unexpected status %d", resp.StatusCode)
}
}()
}
wg.Wait()
// two more calls, should pass
resp, err := http.Get(ts.URL)
require.NoError(t, err)
_ = resp.Body.Close()
resp, err = http.Get(ts.URL)
require.NoError(t, err)
_ = resp.Body.Close()
assert.Equal(t, int32(102), atomic.LoadInt32(&calls))
assert.Equal(t, int32(100), atomic.LoadInt32(&okStatus))
assert.Equal(t, int32(0), atomic.LoadInt32(&badStatus))
}