Path: blob/main/components/ws-daemon/pkg/cpulimit/limiter_test.go
2500 views
// Copyright (c) 2020 Gitpod GmbH. All rights reserved.1// Licensed under the GNU Affero General Public License (AGPL).2// See License.AGPL.txt in the project root for license information.34package cpulimit_test56import (7"encoding/json"8"fmt"9"testing"1011"github.com/gitpod-io/gitpod/ws-daemon/pkg/cpulimit"12"github.com/google/go-cmp/cmp"13)1415func TestBucketLimiter(t *testing.T) {16defaultBuckets := []cpulimit.Bucket{17{Budget: 50, Limit: 100},18{Budget: 30, Limit: 50},19{Budget: 20, Limit: 20},20{Budget: 10, Limit: 5},21}2223tests := []struct {24Desc string25Buckets []cpulimit.Bucket26BudgetSpent cpulimit.CPUTime27ExpectedLimit cpulimit.Bandwidth28}{29{"empty bucket list", []cpulimit.Bucket{}, 50, 0},30{"in first bucket", defaultBuckets, 40, 100},31{"in second bucket", defaultBuckets, 70, 50},32{"in third bucket", defaultBuckets, 90, 20},33{"in last bucket", defaultBuckets, 105, 5},34{"beyond total budget", defaultBuckets, 200, 5},35}3637for _, test := range tests {38t.Run(test.Desc, func(t *testing.T) {39limiter := cpulimit.BucketLimiter(test.Buckets)40ws := &cpulimit.WorkspaceHistory{41LastUpdate: &cpulimit.Workspace{42Usage: test.BudgetSpent,43},44UsageT0: 0,45}4647limit, _ := limiter.Limit(ws)48if limit != test.ExpectedLimit {49t.Errorf("unexpected limit %d: expected %d", limit, test.ExpectedLimit)50}51})52}53}5455func TestUnmarshalBucket(t *testing.T) {56tests := []struct {57Input string58Expectation cpulimit.Bucket59}{60{`{"budget": 20, "limit": 50}`, cpulimit.Bucket{Budget: 20, Limit: 50}},61}6263for i, test := range tests {64t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {65var act cpulimit.Bucket66err := json.Unmarshal([]byte(test.Input), &act)67if err != nil {68t.Error(err)69return70}7172if diff := cmp.Diff(test.Expectation, act); diff != "" {73t.Errorf("unexpected bucket (-want +got):\n%s", diff)74}75})76}77}787980