func TestEventSearch(t *testing.T) { c := &testClient{ Request: testRequest{ Method: "GET", Path: testapi.ResourcePath("events", "baz", ""), Query: url.Values{ api.FieldSelectorQueryParam(testapi.Version()): []string{ getInvolvedObjectNameFieldLabel(testapi.Version()) + "=foo,", "involvedObject.namespace=baz,", "involvedObject.kind=Pod", }, api.LabelSelectorQueryParam(testapi.Version()): []string{}, }, }, Response: Response{StatusCode: 200, Body: &api.EventList{}}, } eventList, err := c.Setup().Events("baz").Search( &api.Pod{ ObjectMeta: api.ObjectMeta{ Name: "foo", Namespace: "baz", SelfLink: testapi.SelfLink("pods", ""), }, }, ) c.Validate(t, eventList, err) }
func TestListObject(t *testing.T) { pods, _ := testData() labelKey := api.LabelSelectorQueryParam(testapi.Version()) b := NewBuilder(latest.RESTMapper, api.Scheme, fakeClientWith("", t, map[string]string{ "/namespaces/test/pods?" + labelKey + "=a%3Db": runtime.EncodeOrDie(latest.Codec, pods), })). SelectorParam("a=b"). NamespaceParam("test"). ResourceTypeOrNameArgs(true, "pods"). Flatten() obj, err := b.Do().Object() if err != nil { t.Fatalf("unexpected error: %v", err) } list, ok := obj.(*api.List) if !ok { t.Fatalf("unexpected object: %#v", obj) } if list.ResourceVersion != pods.ResourceVersion || len(list.Items) != 2 { t.Errorf("unexpected list: %#v", list) } mapping, err := b.Do().ResourceMapping() if err != nil { t.Fatalf("unexpected error: %v", err) } if mapping.Resource != "pods" { t.Errorf("unexpected resource mapping: %#v", mapping) } }
func TestListObjectWithDifferentVersions(t *testing.T) { pods, svc := testData() labelKey := api.LabelSelectorQueryParam(testapi.Version()) obj, err := NewBuilder(latest.RESTMapper, api.Scheme, fakeClientWith("", t, map[string]string{ "/namespaces/test/pods?" + labelKey + "=a%3Db": runtime.EncodeOrDie(latest.Codec, pods), "/namespaces/test/services?" + labelKey + "=a%3Db": runtime.EncodeOrDie(latest.Codec, svc), })). SelectorParam("a=b"). NamespaceParam("test"). ResourceTypeOrNameArgs(true, "pods,services"). Flatten(). Do().Object() if err != nil { t.Fatalf("unexpected error: %v", err) } list, ok := obj.(*api.List) if !ok { t.Fatalf("unexpected object: %#v", obj) } // resource version differs between type lists, so it's not possible to get a single version. if list.ResourceVersion != "" || len(list.Items) != 3 { t.Errorf("unexpected list: %#v", list) } }
func TestSelector(t *testing.T) { pods, svc := testData() labelKey := api.LabelSelectorQueryParam(testapi.Version()) b := NewBuilder(latest.RESTMapper, api.Scheme, fakeClientWith("", t, map[string]string{ "/namespaces/test/pods?" + labelKey + "=a%3Db": runtime.EncodeOrDie(latest.Codec, pods), "/namespaces/test/services?" + labelKey + "=a%3Db": runtime.EncodeOrDie(latest.Codec, svc), })). SelectorParam("a=b"). NamespaceParam("test"). Flatten() test := &testVisitor{} singular := false if b.Do().Err() == nil { t.Errorf("unexpected non-error") } b.ResourceTypeOrNameArgs(true, "pods,service") err := b.Do().IntoSingular(&singular).Visit(test.Handle) if err != nil || singular || len(test.Infos) != 3 { t.Fatalf("unexpected response: %v %t %#v", err, singular, test.Infos) } if !api.Semantic.DeepDerivative([]runtime.Object{&pods.Items[0], &pods.Items[1], &svc.Items[0]}, test.Objects()) { t.Errorf("unexpected visited objects: %#v", test.Objects()) } if _, err := b.Do().ResourceMapping(); err == nil { t.Errorf("unexpected non-error") } }
func TestListMinionsLabels(t *testing.T) { labelSelectorQueryParamName := api.LabelSelectorQueryParam(testapi.Version()) c := &testClient{ Request: testRequest{ Method: "GET", Path: testapi.ResourcePath(getNodesResourceName(), "", ""), Query: buildQueryValues(url.Values{labelSelectorQueryParamName: []string{"foo=bar,name=baz"}})}, Response: Response{ StatusCode: 200, Body: &api.NodeList{ Items: []api.Node{ { ObjectMeta: api.ObjectMeta{ Labels: map[string]string{ "foo": "bar", "name": "baz", }, }, }, }, }, }, } c.Setup() c.QueryValidator[labelSelectorQueryParamName] = validateLabels selector := labels.Set{"foo": "bar", "name": "baz"}.AsSelector() receivedNodeList, err := c.Nodes().List(selector, fields.Everything()) c.Validate(t, receivedNodeList, err) }
func TestListPodsLabels(t *testing.T) { ns := api.NamespaceDefault labelSelectorQueryParamName := api.LabelSelectorQueryParam(testapi.Version()) c := &testClient{ Request: testRequest{ Method: "GET", Path: testapi.ResourcePath("pods", ns, ""), Query: buildQueryValues(url.Values{labelSelectorQueryParamName: []string{"foo=bar,name=baz"}})}, Response: Response{ StatusCode: 200, Body: &api.PodList{ Items: []api.Pod{ { Status: api.PodStatus{ Phase: api.PodRunning, }, ObjectMeta: api.ObjectMeta{ Labels: map[string]string{ "foo": "bar", "name": "baz", }, }, }, }, }, }, } c.Setup() c.QueryValidator[labelSelectorQueryParamName] = validateLabels selector := labels.Set{"foo": "bar", "name": "baz"}.AsSelector() receivedPodList, err := c.Pods(ns).List(selector, fields.Everything()) c.Validate(t, receivedPodList, err) }
func TestListServicesLabels(t *testing.T) { ns := api.NamespaceDefault labelSelectorQueryParamName := api.LabelSelectorQueryParam(testapi.Default.Version()) c := &testClient{ Request: testRequest{ Method: "GET", Path: testapi.Default.ResourcePath("services", ns, ""), Query: buildQueryValues(url.Values{labelSelectorQueryParamName: []string{"foo=bar,name=baz"}})}, Response: Response{StatusCode: 200, Body: &api.ServiceList{ Items: []api.Service{ { ObjectMeta: api.ObjectMeta{ Name: "name", Labels: map[string]string{ "foo": "bar", "name": "baz", }, }, Spec: api.ServiceSpec{ Selector: map[string]string{ "one": "two", }, }, }, }, }, }, } c.Setup(t) c.QueryValidator[labelSelectorQueryParamName] = validateLabels selector := labels.Set{"foo": "bar", "name": "baz"}.AsSelector() receivedServiceList, err := c.Services(ns).List(selector) c.Validate(t, receivedServiceList, err) }
func TestDeleteMultipleSelector(t *testing.T) { pods, svc, _ := testData() f, tf, codec := NewAPIFactory() tf.Printer = &testPrinter{} tf.Client = &client.FakeRESTClient{ Codec: codec, Client: client.HTTPClientFunc(func(req *http.Request) (*http.Response, error) { switch p, m := req.URL.Path, req.Method; { case p == "/namespaces/test/pods" && m == "GET": if req.URL.Query().Get(api.LabelSelectorQueryParam(testapi.Version())) != "a=b" { t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) } return &http.Response{StatusCode: 200, Body: objBody(codec, pods)}, nil case p == "/namespaces/test/services" && m == "GET": if req.URL.Query().Get(api.LabelSelectorQueryParam(testapi.Version())) != "a=b" { t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) } return &http.Response{StatusCode: 200, Body: objBody(codec, svc)}, nil case strings.HasPrefix(p, "/namespaces/test/pods/") && m == "DELETE": return &http.Response{StatusCode: 200, Body: objBody(codec, &pods.Items[0])}, nil case strings.HasPrefix(p, "/namespaces/test/services/") && m == "DELETE": return &http.Response{StatusCode: 200, Body: objBody(codec, &svc.Items[0])}, nil default: t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) return nil, nil } }), } tf.Namespace = "test" buf := bytes.NewBuffer([]byte{}) cmd := NewCmdDelete(f, buf) cmd.Flags().Set("selector", "a=b") cmd.Flags().Set("cascade", "false") cmd.Flags().Set("output", "name") cmd.Run(cmd, []string{"pods,services"}) if buf.String() != "pod/foo\npod/bar\nservice/baz\n" { t.Errorf("unexpected output: %s", buf.String()) } }
func (c *testClient) ValidateCommon(t *testing.T, err error) { defer c.server.Close() if c.Error { if err == nil { t.Errorf("error expected for %#v, got none", c.Request) } return } if err != nil { t.Errorf("no error expected for %#v, got: %v", c.Request, err) } if c.handler.RequestReceived == nil { t.Errorf("handler had an empty request, %#v", c) return } requestBody := body(c.Request.Body, c.Request.RawBody) actualQuery := c.handler.RequestReceived.URL.Query() t.Logf("got query: %v", actualQuery) t.Logf("path: %v", c.Request.Path) // We check the query manually, so blank it out so that FakeHandler.ValidateRequest // won't check it. c.handler.RequestReceived.URL.RawQuery = "" c.handler.ValidateRequest(t, path.Join(c.Request.Path), c.Request.Method, requestBody) for key, values := range c.Request.Query { validator, ok := c.QueryValidator[key] if !ok { switch key { case api.LabelSelectorQueryParam(testapi.Version()): validator = validateLabels case api.FieldSelectorQueryParam(testapi.Version()): validator = validateFields default: validator = func(a, b string) bool { return a == b } } } observed := actualQuery.Get(key) wanted := strings.Join(values, "") if !validator(wanted, observed) { t.Errorf("Unexpected query arg for key: %s. Expected %s, Received %s", key, wanted, observed) } } if c.Request.Header != "" { if c.handler.RequestReceived.Header.Get(c.Request.Header) == "" { t.Errorf("header %q not found in request %#v", c.Request.Header, c.handler.RequestReceived) } } if expected, received := requestBody, c.handler.RequestBody; expected != nil && *expected != received { t.Errorf("bad body for request %#v: expected %s, got %s", c.Request, *expected, received) } }
// LabelsSelectorParam adds the given selector as a query parameter func (r *Request) LabelsSelectorParam(s labels.Selector) *Request { if r.err != nil { return r } if s == nil { return r } if s.Empty() { return r } return r.setParam(api.LabelSelectorQueryParam(r.apiVersion), s.String()) }
func TestGetMultipleTypeObjectsWithSelector(t *testing.T) { pods, svc, _ := testData() f, tf, codec := NewAPIFactory() tf.Printer = &testPrinter{} tf.Client = &fake.RESTClient{ Codec: codec, Client: fake.HTTPClientFunc(func(req *http.Request) (*http.Response, error) { if req.URL.Query().Get(api.LabelSelectorQueryParam(testapi.Default.Version())) != "a=b" { t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) } switch req.URL.Path { case "/namespaces/test/pods": return &http.Response{StatusCode: 200, Body: objBody(codec, pods)}, nil case "/namespaces/test/services": return &http.Response{StatusCode: 200, Body: objBody(codec, svc)}, nil default: t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) return nil, nil } }), } tf.Namespace = "test" buf := bytes.NewBuffer([]byte{}) cmd := NewCmdGet(f, buf) cmd.SetOutput(buf) cmd.Flags().Set("selector", "a=b") cmd.Run(cmd, []string{"pods,services"}) expected, err := extractResourceList([]runtime.Object{pods, svc}) if err != nil { t.Fatalf("unexpected error: %v", err) } actual := tf.Printer.(*testPrinter).Objects if !reflect.DeepEqual(expected, actual) { t.Errorf("unexpected object: %#v", actual) } if len(buf.String()) == 0 { t.Errorf("unexpected empty output") } }
func TestDoRequestNewWayObj(t *testing.T) { reqObj := &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}} reqBodyExpected, _ := testapi.Codec().Encode(reqObj) expectedObj := &api.Service{Spec: api.ServiceSpec{Ports: []api.ServicePort{{ Protocol: "TCP", Port: 12345, TargetPort: util.NewIntOrStringFromInt(12345), }}}} expectedBody, _ := testapi.Codec().Encode(expectedObj) fakeHandler := util.FakeHandler{ StatusCode: 200, ResponseBody: string(expectedBody), T: t, } testServer := httptest.NewServer(&fakeHandler) c := NewOrDie(&Config{Host: testServer.URL, Version: testapi.Version(), Username: "******", Password: "******"}) obj, err := c.Verb("POST"). Suffix("baz"). Name("bar"). Resource("foo"). LabelsSelectorParam(labels.Set{"name": "foo"}.AsSelector()). Timeout(time.Second). Body(reqObj). Do().Get() if err != nil { t.Errorf("Unexpected error: %v %#v", err, err) return } if obj == nil { t.Error("nil obj") } else if !api.Semantic.DeepDerivative(expectedObj, obj) { t.Errorf("Expected: %#v, got %#v", expectedObj, obj) } tmpStr := string(reqBodyExpected) requestURL := testapi.ResourcePath("foo", "", "bar/baz") requestURL += "?" + api.LabelSelectorQueryParam(testapi.Version()) + "=name%3Dfoo&timeout=1s" fakeHandler.ValidateRequest(t, requestURL, "POST", &tmpStr) if fakeHandler.RequestReceived.Header["Authorization"] == nil { t.Errorf("Request is missing authorization header: %#v", *fakeHandler.RequestReceived) } }
func TestWatchSelector(t *testing.T) { pods, events := watchTestData() f, tf, codec := NewAPIFactory() tf.Printer = &testPrinter{} tf.Client = &client.FakeRESTClient{ Codec: codec, Client: client.HTTPClientFunc(func(req *http.Request) (*http.Response, error) { if req.URL.Query().Get(api.LabelSelectorQueryParam(testapi.Version())) != "a=b" { t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) } switch req.URL.Path { case "/namespaces/test/pods": return &http.Response{StatusCode: 200, Body: objBody(codec, &api.PodList{Items: pods})}, nil case "/watch/namespaces/test/pods": return &http.Response{StatusCode: 200, Body: watchBody(codec, events)}, nil default: t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) return nil, nil } }), } tf.Namespace = "test" buf := bytes.NewBuffer([]byte{}) cmd := NewCmdGet(f, buf) cmd.SetOutput(buf) cmd.Flags().Set("watch", "true") cmd.Flags().Set("selector", "a=b") cmd.Run(cmd, []string{"pods"}) expected := []runtime.Object{&api.PodList{Items: pods}, events[0].Object, events[1].Object} actual := tf.Printer.(*testPrinter).Objects if !reflect.DeepEqual(expected, actual) { t.Errorf("unexpected object: %#v %#v", expected[0], actual[0]) } if len(buf.String()) == 0 { t.Errorf("unexpected empty output") } }
func TestHelperList(t *testing.T) { tests := []struct { Err bool Req func(*http.Request) bool Resp *http.Response HttpErr error }{ { HttpErr: errors.New("failure"), Err: true, }, { Resp: &http.Response{ StatusCode: http.StatusNotFound, Body: objBody(&api.Status{Status: api.StatusFailure}), }, Err: true, }, { Resp: &http.Response{ StatusCode: http.StatusOK, Body: objBody(&api.PodList{ Items: []api.Pod{{ ObjectMeta: api.ObjectMeta{Name: "foo"}, }, }, }), }, Req: func(req *http.Request) bool { if req.Method != "GET" { t.Errorf("unexpected method: %#v", req) return false } if req.URL.Path != "/namespaces/bar" { t.Errorf("url doesn't contain name: %#v", req.URL) return false } if req.URL.Query().Get(api.LabelSelectorQueryParam(testapi.Default.Version())) != labels.SelectorFromSet(labels.Set{"foo": "baz"}).String() { t.Errorf("url doesn't contain query parameters: %#v", req.URL) return false } return true }, }, } for _, test := range tests { client := &fake.RESTClient{ Codec: testapi.Default.Codec(), Resp: test.Resp, Err: test.HttpErr, } modifier := &Helper{ RESTClient: client, NamespaceScoped: true, } obj, err := modifier.List("bar", testapi.Default.Version(), labels.SelectorFromSet(labels.Set{"foo": "baz"})) if (err != nil) != test.Err { t.Errorf("unexpected error: %t %v", test.Err, err) } if err != nil { continue } if obj.(*api.PodList).Items[0].Name != "foo" { t.Errorf("unexpected object: %#v", obj) } if test.Req != nil && !test.Req(client.Req) { t.Errorf("unexpected request: %#v", client.Req) } } }