Merge pull request #2305 from AllenZMC/improve-resource

Optimize code to reduce redundancy
This commit is contained in:
karmada-bot 2022-08-02 12:03:58 +08:00 committed by GitHub
commit 730ed3d8fe
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 42 additions and 16 deletions

View File

@ -29,22 +29,7 @@ func EmptyResource() *Resource {
// NewResource creates a new resource object from resource list.
func NewResource(rl corev1.ResourceList) *Resource {
r := &Resource{}
for rName, rQuant := range rl {
switch rName {
case corev1.ResourceCPU:
r.MilliCPU += rQuant.MilliValue()
case corev1.ResourceMemory:
r.Memory += rQuant.Value()
case corev1.ResourcePods:
r.AllowedPodNumber += rQuant.Value()
case corev1.ResourceEphemeralStorage:
r.EphemeralStorage += rQuant.Value()
default:
if lifted.IsScalarResourceName(rName) {
r.AddScalar(rName, rQuant.Value())
}
}
}
r.Add(rl)
return r
}

41
pkg/util/resource_test.go Normal file
View File

@ -0,0 +1,41 @@
package util
import (
"reflect"
"testing"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
)
func TestNewResource(t *testing.T) {
tests := []struct {
name string
rl corev1.ResourceList
want *Resource
}{
{
name: "Resource",
rl: corev1.ResourceList{
corev1.ResourceCPU: *resource.NewMilliQuantity(5, resource.DecimalSI),
corev1.ResourceMemory: *resource.NewQuantity(5, resource.BinarySI),
corev1.ResourcePods: *resource.NewQuantity(5, resource.DecimalSI),
corev1.ResourceEphemeralStorage: *resource.NewQuantity(5, resource.BinarySI),
},
want: &Resource{
MilliCPU: 5,
Memory: 5,
EphemeralStorage: 5,
AllowedPodNumber: 5,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := NewResource(tt.rl); !reflect.DeepEqual(got, tt.want) {
t.Errorf("NewResource() = %v, want %v", got, tt.want)
}
})
}
}