-
Notifications
You must be signed in to change notification settings - Fork 3
/
throttle_test.go
95 lines (80 loc) · 1.79 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
package core
import (
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestThrottle(t *testing.T) {
throttler := NewThrottle(time.Millisecond * 100)
var c uint32
add := func(v int) {
atomic.AddUint32(&c, uint32(v))
}
get := func() int {
return int(atomic.LoadUint32(&c))
}
// executes immediately
throttler(func() { add(17) })
require.Equal(t, 17, get())
time.Sleep(time.Millisecond * 50)
// queued - 50ms remaining
throttler(func() { add(1) })
require.Equal(t, 17, get())
time.Sleep(time.Millisecond * 20)
// queued - 30ms remaining (overwrites function 2)
throttler(func() { add(5) })
require.Equal(t, 17, get())
time.Sleep(time.Millisecond * 40)
// function 3 executes
require.Equal(t, 22, get())
time.Sleep(time.Millisecond * 100)
// ready
// executes immediately
throttler(func() { add(4) })
require.Equal(t, 26, get())
}
func TestThrottleAsync(t *testing.T) {
throttler := NewThrottle(time.Millisecond * 100)
var c uint32
add := func(v int) {
atomic.AddUint32(&c, uint32(v))
}
get := func() int {
return int(atomic.LoadUint32(&c))
}
// executes immediately
throttler(func() {
go func() {
time.Sleep(time.Millisecond * 150)
add(17)
}()
})
time.Sleep(time.Millisecond * 50)
// queued - 50ms remaining
throttler(func() {
go func() {
time.Sleep(time.Millisecond * 100)
add(1)
}()
})
time.Sleep(time.Millisecond * 20)
// overwrites function 2 - 30ms remaining
throttler(func() {
go func() {
time.Sleep(time.Millisecond * 50)
add(5)
}()
})
time.Sleep(time.Millisecond * 140)
// function 3 executes, throttle ready again
throttler(func() {
go func() {
time.Sleep(time.Millisecond * 150)
add(4)
}()
})
// wait for function 4
time.Sleep(time.Millisecond * 160)
require.Equal(t, 26, get())
}