mirror of
https://github.com/k3s-io/kubernetes.git
synced 2025-07-31 15:25:57 +00:00
Merge pull request #1306 from lavalamp/scheduler
Add ExtractList to runtime.
This commit is contained in:
commit
424447d3b0
@ -243,3 +243,28 @@ func (metaInsertion) Interpret(in interface{}) (version, kind string) {
|
||||
m := in.(*metaInsertion)
|
||||
return m.JSONBase.APIVersion, m.JSONBase.Kind
|
||||
}
|
||||
|
||||
// Extract list returns obj's Items element as an array of runtime.Objects.
|
||||
// Returns an error if obj is not a List type (does not have an Items member).
|
||||
func ExtractList(obj Object) ([]Object, error) {
|
||||
v := reflect.ValueOf(obj)
|
||||
if !v.IsValid() {
|
||||
return nil, fmt.Errorf("nil object")
|
||||
}
|
||||
items := v.Elem().FieldByName("Items")
|
||||
if !items.IsValid() {
|
||||
return nil, fmt.Errorf("no Items field")
|
||||
}
|
||||
if items.Kind() != reflect.Slice {
|
||||
return nil, fmt.Errorf("Items field is not a slice")
|
||||
}
|
||||
list := make([]Object, items.Len())
|
||||
for i := range list {
|
||||
item, ok := items.Index(i).Addr().Interface().(Object)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("item in index %v isn't an object", i)
|
||||
}
|
||||
list[i] = item
|
||||
}
|
||||
return list, nil
|
||||
}
|
||||
|
@ -57,3 +57,25 @@ func TestBadJSONRejection(t *testing.T) {
|
||||
t.Errorf("Kind is set but doesn't match the object type: %s", badJSONKindMismatch)
|
||||
}*/
|
||||
}
|
||||
|
||||
func TestExtractList(t *testing.T) {
|
||||
pl := &api.PodList{
|
||||
Items: []api.Pod{
|
||||
{JSONBase: api.JSONBase{ID: "1"}},
|
||||
{JSONBase: api.JSONBase{ID: "2"}},
|
||||
{JSONBase: api.JSONBase{ID: "3"}},
|
||||
},
|
||||
}
|
||||
list, err := runtime.ExtractList(pl)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error %v", err)
|
||||
}
|
||||
if e, a := len(list), len(pl.Items); e != a {
|
||||
t.Fatalf("Expected %v, got %v", e, a)
|
||||
}
|
||||
for i := range list {
|
||||
if e, a := list[i].(*api.Pod).ID, pl.Items[i].ID; e != a {
|
||||
t.Fatalf("Expected %v, got %v", e, a)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user