Skip to content

Commit

Permalink
Merge pull request #249 from yuzhiquan/add-kobjs
Browse files Browse the repository at this point in the history
Implement KObjs function to handle slice of KMetada
  • Loading branch information
k8s-ci-robot committed Jul 5, 2021
2 parents dfd1411 + 7cbd2fc commit 79f9f6b
Show file tree
Hide file tree
Showing 2 changed files with 95 additions and 0 deletions.
17 changes: 17 additions & 0 deletions klog.go
Expand Up @@ -1603,3 +1603,20 @@ func KRef(namespace, name string) ObjectRef {
Namespace: namespace,
}
}

// KObjs returns slice of ObjectRef from an slice of ObjectMeta
func KObjs(arg interface{}) []ObjectRef {
s := reflect.ValueOf(arg)
if s.Kind() != reflect.Slice {
return nil
}
objectRefs := make([]ObjectRef, 0, s.Len())
for i := 0; i < s.Len(); i++ {
if v, ok := s.Index(i).Interface().(KMetadata); ok {
objectRefs = append(objectRefs, KObj(v))
} else {
return nil
}
}
return objectRefs
}
78 changes: 78 additions & 0 deletions klog_test.go
Expand Up @@ -1754,3 +1754,81 @@ func TestKlogFlagPrefix(t *testing.T) {
}
})
}

func TestKObjs(t *testing.T) {
tests := []struct {
name string
obj interface{}
want []ObjectRef
}{
{
name: "test for KObjs function with KMetadata slice",
obj: []kMetadataMock{
{
name: "kube-dns",
ns: "kube-system",
},
{
name: "mi-conf",
},
{},
},
want: []ObjectRef{
{
Name: "kube-dns",
Namespace: "kube-system",
},
{
Name: "mi-conf",
},
{},
},
},
{
name: "test for KObjs function with KMetadata pointer slice",
obj: []*kMetadataMock{
{
name: "kube-dns",
ns: "kube-system",
},
{
name: "mi-conf",
},
nil,
},
want: []ObjectRef{
{
Name: "kube-dns",
Namespace: "kube-system",
},
{
Name: "mi-conf",
},
{},
},
},
{
name: "test for KObjs function with slice does not implement KMetadata",
obj: []int{1, 2, 3, 4, 6},
want: nil,
},
{
name: "test for KObjs function with interface",
obj: "test case",
want: nil,
},
{
name: "test for KObjs function with nil",
obj: nil,
want: nil,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if !reflect.DeepEqual(KObjs(tt.obj), tt.want) {
t.Errorf("\nwant:\t %v\n got:\t %v", tt.want, KObjs(tt.obj))
}
})
}
}

0 comments on commit 79f9f6b

Please sign in to comment.