// setListSelfLink sets the self link of a list to the base URL, then sets the self links
// on all child objects returned. Returns the number of items in the list.
func setListSelfLink(obj runtime.Object, req *restful.Request, namer ScopeNamer) (int, error) {
	if !meta.IsListType(obj) {
		return 0, nil
	}

	uri, err := namer.GenerateListLink(req)
	if err != nil {
		return 0, err
	}
	if err := namer.SetSelfLink(obj, uri); err != nil {
		glog.V(4).Infof("Unable to set self link on object: %v", err)
	}

	count := 0
	err = meta.EachListItem(obj, func(obj runtime.Object) error {
		count++
		return setSelfLink(obj, req, namer)
	})
	return count, err
}
예제 #2
0
func TestEachListItem(t *testing.T) {
	list1 := []runtime.Object{
		&api.Pod{ObjectMeta: api.ObjectMeta{Name: "1"}},
		&api.Service{ObjectMeta: api.ObjectMeta{Name: "2"}},
	}
	list2 := &v1.List{
		Items: []runtime.RawExtension{
			{Raw: []byte("foo")},
			{Raw: []byte("bar")},
			{Object: &v1.Pod{ObjectMeta: v1.ObjectMeta{Name: "other"}}},
		},
	}
	list3 := &fakePtrValueList{
		Items: []*api.Pod{
			{ObjectMeta: api.ObjectMeta{Name: "1"}},
			{ObjectMeta: api.ObjectMeta{Name: "2"}},
		},
	}
	list4 := &api.PodList{
		Items: []api.Pod{
			{ObjectMeta: api.ObjectMeta{Name: "1"}},
			{ObjectMeta: api.ObjectMeta{Name: "2"}},
			{ObjectMeta: api.ObjectMeta{Name: "3"}},
		},
	}
	list5 := &v1.PodList{
		Items: []v1.Pod{
			{ObjectMeta: v1.ObjectMeta{Name: "1"}},
			{ObjectMeta: v1.ObjectMeta{Name: "2"}},
			{ObjectMeta: v1.ObjectMeta{Name: "3"}},
		},
	}

	testCases := []struct {
		in  runtime.Object
		out []interface{}
	}{
		{
			in:  &api.List{},
			out: []interface{}{},
		},
		{
			in:  &v1.List{},
			out: []interface{}{},
		},
		{
			in:  &v1.PodList{},
			out: []interface{}{},
		},
		{
			in:  &api.List{Items: list1},
			out: []interface{}{list1[0], list1[1]},
		},
		{
			in:  list2,
			out: []interface{}{nil, nil, list2.Items[2].Object},
		},
		{
			in:  list3,
			out: []interface{}{list3.Items[0], list3.Items[1]},
		},
		{
			in:  list4,
			out: []interface{}{&list4.Items[0], &list4.Items[1], &list4.Items[2]},
		},
		{
			in:  list5,
			out: []interface{}{&list5.Items[0], &list5.Items[1], &list5.Items[2]},
		},
	}
	for i, test := range testCases {
		list := []runtime.Object{}
		err := meta.EachListItem(test.in, func(obj runtime.Object) error {
			list = append(list, obj)
			return nil
		})
		if err != nil {
			t.Fatalf("%d: each: Unexpected error %v", i, err)
		}
		if e, a := len(test.out), len(list); e != a {
			t.Fatalf("%d: each: Expected %v, got %v", i, e, a)
		}
		for j, e := range test.out {
			if e != list[j] {
				t.Fatalf("%d: each: Expected list[%d] to be %#v, but found %#v", i, j, e, list[j])
			}
		}
	}
}