Merge pull request #4449 from smarterclayton/allow_setlist_on_lists

Allow runtime.SetList() on an api.List
pull/6/head
Daniel Smith 2015-02-17 11:33:35 -08:00
commit 309a81d8da
2 changed files with 29 additions and 0 deletions

View File

@ -83,6 +83,9 @@ func ExtractList(obj Object) ([]Object, error) {
return list, nil return list, nil
} }
// objectSliceType is the type of a slice of Objects
var objectSliceType = reflect.TypeOf([]Object{})
// SetList sets the given list object's Items member have the elements given in // SetList sets the given list object's Items member have the elements given in
// objects. // objects.
// Returns an error if list is not a List type (does not have an Items member), // Returns an error if list is not a List type (does not have an Items member),
@ -96,6 +99,10 @@ func SetList(list Object, objects []Object) error {
if err != nil { if err != nil {
return err return err
} }
if items.Type() == objectSliceType {
items.Set(reflect.ValueOf(objects))
return nil
}
slice := reflect.MakeSlice(items.Type(), len(objects), len(objects)) slice := reflect.MakeSlice(items.Type(), len(objects), len(objects))
for i := range objects { for i := range objects {
dest := slice.Index(i) dest := slice.Index(i)

View File

@ -22,6 +22,7 @@ import (
"github.com/GoogleCloudPlatform/kubernetes/pkg/api" "github.com/GoogleCloudPlatform/kubernetes/pkg/api"
"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime" "github.com/GoogleCloudPlatform/kubernetes/pkg/runtime"
"github.com/GoogleCloudPlatform/kubernetes/pkg/util"
"github.com/google/gofuzz" "github.com/google/gofuzz"
) )
@ -152,6 +153,27 @@ func TestSetList(t *testing.T) {
} }
} }
func TestSetListToRuntimeObjectArray(t *testing.T) {
pl := &api.List{}
list := []runtime.Object{
&api.Pod{ObjectMeta: api.ObjectMeta{Name: "1"}},
&api.Pod{ObjectMeta: api.ObjectMeta{Name: "2"}},
&api.Pod{ObjectMeta: api.ObjectMeta{Name: "3"}},
}
err := runtime.SetList(pl, list)
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], pl.Items[i]; e != a {
t.Fatalf("%d: unmatched: %s", i, util.ObjectDiff(e, a))
}
}
}
func TestSetExtractListRoundTrip(t *testing.T) { func TestSetExtractListRoundTrip(t *testing.T) {
fuzzer := fuzz.New().NilChance(0).NumElements(1, 5) fuzzer := fuzz.New().NilChance(0).NumElements(1, 5)
for i := 0; i < 5; i++ { for i := 0; i < 5; i++ {