Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/ws-daemon/pkg/cpulimit/limiter_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 cpulimit_test
6
7
import (
8
"encoding/json"
9
"fmt"
10
"testing"
11
12
"github.com/gitpod-io/gitpod/ws-daemon/pkg/cpulimit"
13
"github.com/google/go-cmp/cmp"
14
)
15
16
func TestBucketLimiter(t *testing.T) {
17
defaultBuckets := []cpulimit.Bucket{
18
{Budget: 50, Limit: 100},
19
{Budget: 30, Limit: 50},
20
{Budget: 20, Limit: 20},
21
{Budget: 10, Limit: 5},
22
}
23
24
tests := []struct {
25
Desc string
26
Buckets []cpulimit.Bucket
27
BudgetSpent cpulimit.CPUTime
28
ExpectedLimit cpulimit.Bandwidth
29
}{
30
{"empty bucket list", []cpulimit.Bucket{}, 50, 0},
31
{"in first bucket", defaultBuckets, 40, 100},
32
{"in second bucket", defaultBuckets, 70, 50},
33
{"in third bucket", defaultBuckets, 90, 20},
34
{"in last bucket", defaultBuckets, 105, 5},
35
{"beyond total budget", defaultBuckets, 200, 5},
36
}
37
38
for _, test := range tests {
39
t.Run(test.Desc, func(t *testing.T) {
40
limiter := cpulimit.BucketLimiter(test.Buckets)
41
ws := &cpulimit.WorkspaceHistory{
42
LastUpdate: &cpulimit.Workspace{
43
Usage: test.BudgetSpent,
44
},
45
UsageT0: 0,
46
}
47
48
limit, _ := limiter.Limit(ws)
49
if limit != test.ExpectedLimit {
50
t.Errorf("unexpected limit %d: expected %d", limit, test.ExpectedLimit)
51
}
52
})
53
}
54
}
55
56
func TestUnmarshalBucket(t *testing.T) {
57
tests := []struct {
58
Input string
59
Expectation cpulimit.Bucket
60
}{
61
{`{"budget": 20, "limit": 50}`, cpulimit.Bucket{Budget: 20, Limit: 50}},
62
}
63
64
for i, test := range tests {
65
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
66
var act cpulimit.Bucket
67
err := json.Unmarshal([]byte(test.Input), &act)
68
if err != nil {
69
t.Error(err)
70
return
71
}
72
73
if diff := cmp.Diff(test.Expectation, act); diff != "" {
74
t.Errorf("unexpected bucket (-want +got):\n%s", diff)
75
}
76
})
77
}
78
}
79
80