github.com/oam-dev/kubevela@v1.9.11/references/common/metrics_test.go (about) 1 /* 2 Copyright 2022 The KubeVela Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package common 18 19 import ( 20 "testing" 21 "time" 22 23 "k8s.io/utils/pointer" 24 "sigs.k8s.io/controller-runtime/pkg/client" 25 "sigs.k8s.io/controller-runtime/pkg/envtest" 26 27 "github.com/oam-dev/kubevela/pkg/utils/common" 28 29 "github.com/stretchr/testify/assert" 30 v1 "k8s.io/api/core/v1" 31 "k8s.io/apimachinery/pkg/api/resource" 32 "k8s.io/metrics/pkg/apis/metrics/v1beta1" 33 ) 34 35 func TestToPercentageStr(t *testing.T) { 36 var v1, v2 int64 37 v1, v2 = 10, 100 38 assert.Equal(t, ToPercentageStr(v1, v2), "10%") 39 v1, v2 = 10, 0 40 assert.Equal(t, ToPercentageStr(v1, v2), "N/A") 41 } 42 43 func TestGetPodResourceSpecAndUsage(t *testing.T) { 44 testEnv := &envtest.Environment{ 45 ControlPlaneStartTimeout: time.Minute * 3, 46 ControlPlaneStopTimeout: time.Minute, 47 UseExistingCluster: pointer.Bool(false), 48 } 49 cfg, err := testEnv.Start() 50 assert.NoError(t, err) 51 52 k8sClient, err := client.New(cfg, client.Options{Scheme: common.Scheme}) 53 assert.NoError(t, err) 54 55 quantityLimitsCPU, _ := resource.ParseQuantity("10m") 56 quantityLimitsMemory, _ := resource.ParseQuantity("10Mi") 57 quantityRequestsCPU, _ := resource.ParseQuantity("100m") 58 quantityRequestsMemory, _ := resource.ParseQuantity("50Mi") 59 quantityUsageCPU, _ := resource.ParseQuantity("8m") 60 quantityUsageMemory, _ := resource.ParseQuantity("20Mi") 61 62 pod := &v1.Pod{ 63 Spec: v1.PodSpec{ 64 Containers: []v1.Container{ 65 { 66 Resources: v1.ResourceRequirements{ 67 Requests: map[v1.ResourceName]resource.Quantity{"memory": quantityRequestsMemory, "cpu": quantityRequestsCPU}, 68 Limits: map[v1.ResourceName]resource.Quantity{"memory": quantityLimitsMemory, "cpu": quantityLimitsCPU}, 69 }, 70 }, 71 }, 72 }, 73 } 74 podMetric := &v1beta1.PodMetrics{ 75 Containers: []v1beta1.ContainerMetrics{ 76 { 77 Name: "", 78 Usage: map[v1.ResourceName]resource.Quantity{ 79 "memory": quantityUsageMemory, "cpu": quantityUsageCPU, 80 }, 81 }, 82 }, 83 } 84 85 spec, usage := GetPodResourceSpecAndUsage(k8sClient, pod, podMetric) 86 assert.Equal(t, usage.CPU, int64(8)) 87 assert.Equal(t, usage.Mem, int64(20971520)) 88 assert.Equal(t, spec.Lcpu, int64(10)) 89 assert.Equal(t, spec.Lmem, int64(10485760)) 90 assert.Equal(t, spec.Rcpu, int64(100)) 91 assert.Equal(t, spec.Rmem, int64(52428800)) 92 }