Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ExtractList to runtime. #1306

Merged
merged 1 commit into from
Sep 15, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
25 changes: 25 additions & 0 deletions pkg/runtime/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
22 changes: 22 additions & 0 deletions pkg/runtime/helper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}