Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/supervisor/pkg/dropwriter/dropwriter_test.go
2500 views
1
// Copyright (c) 2020 Gitpod GmbH. All rights reserved.
2
// Licensed under the GNU Affero General Public License (AGPL).
3
// See License.AGPL.txt in the project root for license information.
4
5
package dropwriter_test
6
7
import (
8
"testing"
9
"time"
10
11
"github.com/gitpod-io/gitpod/supervisor/pkg/dropwriter"
12
)
13
14
func TestBucket(t *testing.T) {
15
steps := func(dt time.Duration, c int) []time.Duration {
16
res := make([]time.Duration, c)
17
for i := range res {
18
res[i] = dt
19
}
20
return res
21
}
22
constv := func(v int64, c int) []int64 {
23
res := make([]int64, c)
24
for i := range res {
25
res[i] = v
26
}
27
return res
28
}
29
clock := func(dt []time.Duration) dropwriter.Clock {
30
i := 0
31
t := time.Time{}
32
return func() time.Time {
33
ot := t
34
t = t.Add(dt[i])
35
i++
36
return ot
37
}
38
}
39
40
tests := []struct {
41
Name string
42
Bucket *dropwriter.Bucket
43
Reqs []int64
44
Expectations []int64
45
}{
46
{
47
Name: "below limit",
48
Bucket: dropwriter.NewBucketClock(20, 15, clock(steps(1300*time.Millisecond, 10))),
49
Reqs: constv(10, 10),
50
Expectations: constv(10, 10),
51
},
52
{
53
Name: "above limit",
54
Bucket: dropwriter.NewBucketClock(1, 1, clock(steps(1300*time.Millisecond, 10))),
55
Reqs: constv(10, 10),
56
Expectations: constv(1, 10),
57
},
58
{
59
Name: "upfront peak",
60
Bucket: dropwriter.NewBucketClock(20, 5, clock(steps(1300*time.Millisecond, 10))),
61
Reqs: append(constv(10, 1), constv(1, 9)...),
62
Expectations: append(constv(10, 1), constv(1, 9)...),
63
},
64
{
65
Name: "mid peak",
66
Bucket: dropwriter.NewBucketClock(20, 5, clock(steps(1300*time.Millisecond, 10))),
67
Reqs: append(constv(1, 4), append(constv(30, 1), constv(1, 5)...)...),
68
Expectations: append(constv(1, 4), append(constv(20, 1), constv(1, 5)...)...),
69
},
70
}
71
72
for _, test := range tests {
73
t.Run(test.Name, func(t *testing.T) {
74
for step := range test.Reqs {
75
grant := test.Bucket.TakeAvailable(test.Reqs[step])
76
if grant != test.Expectations[step] {
77
t.Errorf("step %d: did not receive expected tokens: requested %d, expected %d, received %d", step, test.Reqs[step], test.Expectations[step], grant)
78
}
79
}
80
})
81
}
82
}
83
84