Add ExtractList to runtime.

This commit is contained in:
Daniel Smith 2014-09-12 16:51:07 -07:00
parent 6eeb967d3d
commit 7d50aa8ba8
2 changed files with 47 additions and 0 deletions

View File

@ -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
}

View File

@ -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)
}
}
}