From 61a494d303839d67875680a43dcf71955864e0d5 Mon Sep 17 00:00:00 2001 From: Daniel Smith Date: Sun, 22 Jun 2014 14:18:01 -0700 Subject: [PATCH] First step of combination. --- cmd/cloudcfg/cloudcfg.go | 18 ++--- cmd/controller-manager/controller-manager.go | 7 +- cmd/integration/integration.go | 9 +-- cmd/localkube/localkube.go | 7 +- pkg/client/client.go | 71 ++++++++++------- pkg/client/client_test.go | 76 ++++++++++++------- pkg/{cloudcfg => client}/request.go | 29 ++----- pkg/{cloudcfg => client}/request_test.go | 55 ++++++++++++-- pkg/cloudcfg/cloudcfg.go | 7 +- pkg/cloudcfg/cloudcfg_test.go | 50 +----------- pkg/controller/replication_controller_test.go | 56 +++++--------- 11 files changed, 189 insertions(+), 196 deletions(-) rename pkg/{cloudcfg => client}/request.go (86%) rename pkg/{cloudcfg => client}/request_test.go (65%) diff --git a/cmd/cloudcfg/cloudcfg.go b/cmd/cloudcfg/cloudcfg.go index c27d7b26a9b..dabea2fccbd 100644 --- a/cmd/cloudcfg/cloudcfg.go +++ b/cmd/cloudcfg/cloudcfg.go @@ -147,7 +147,7 @@ func executeAPIRequest(method string, auth *kube_client.AuthInfo) bool { return false } - s := cloudcfg.New(*httpServer, auth) + s := kube_client.New(*httpServer, auth) r := s.Verb(verb). Path("api/v1beta1"). Path(parseStorage()). @@ -187,18 +187,16 @@ func executeControllerRequest(method string, auth *kube_client.AuthInfo) bool { return flag.Arg(1) } + c := kube_client.New(*httpServer, auth) + var err error switch method { case "stop": - err = cloudcfg.StopController(parseController(), kube_client.Client{Host: *httpServer, Auth: auth}) + err = cloudcfg.StopController(parseController(), c) case "rm": - err = cloudcfg.DeleteController(parseController(), kube_client.Client{Host: *httpServer, Auth: auth}) + err = cloudcfg.DeleteController(parseController(), c) case "rollingupdate": - client := &kube_client.Client{ - Host: *httpServer, - Auth: auth, - } - err = cloudcfg.Update(parseController(), client, *updatePeriod) + err = cloudcfg.Update(parseController(), c, *updatePeriod) case "run": if len(flag.Args()) != 4 { log.Fatal("usage: cloudcfg [OPTIONS] run ") @@ -209,7 +207,7 @@ func executeControllerRequest(method string, auth *kube_client.AuthInfo) bool { if err != nil { log.Fatalf("Error parsing replicas: %#v", err) } - err = cloudcfg.RunController(image, name, replicas, kube_client.Client{Host: *httpServer, Auth: auth}, *portSpec, *servicePort) + err = cloudcfg.RunController(image, name, replicas, c, *portSpec, *servicePort) case "resize": args := flag.Args() if len(args) < 3 { @@ -220,7 +218,7 @@ func executeControllerRequest(method string, auth *kube_client.AuthInfo) bool { if err != nil { log.Fatalf("Error parsing replicas: %#v", err) } - err = cloudcfg.ResizeController(name, replicas, kube_client.Client{Host: *httpServer, Auth: auth}) + err = cloudcfg.ResizeController(name, replicas, c) default: return false } diff --git a/cmd/controller-manager/controller-manager.go b/cmd/controller-manager/controller-manager.go index 7b24f1a4290..418a6aaba87 100644 --- a/cmd/controller-manager/controller-manager.go +++ b/cmd/controller-manager/controller-manager.go @@ -47,10 +47,9 @@ func main() { // Set up logger for etcd client etcd.SetLogger(log.New(os.Stderr, "etcd ", log.LstdFlags)) - controllerManager := controller.MakeReplicationManager(etcd.NewClient([]string{*etcd_servers}), - client.Client{ - Host: "http://" + *master, - }) + controllerManager := controller.MakeReplicationManager( + etcd.NewClient([]string{*etcd_servers}), + client.New("http://"+*master, nil)) controllerManager.Run(10 * time.Second) select {} diff --git a/cmd/integration/integration.go b/cmd/integration/integration.go index 9a5c49196c0..845b6363b3a 100644 --- a/cmd/integration/integration.go +++ b/cmd/integration/integration.go @@ -49,10 +49,7 @@ func main() { }, "/api/v1beta1") server := httptest.NewServer(apiserver) - controllerManager := controller.MakeReplicationManager(etcd.NewClient(servers), - client.Client{ - Host: server.URL, - }) + controllerManager := controller.MakeReplicationManager(etcd.NewClient(servers), client.New(server.URL, nil)) controllerManager.Run(10 * time.Second) @@ -61,9 +58,7 @@ func main() { // Wait for the synchronization threads to come up. time.Sleep(time.Second * 10) - kubeClient := client.Client{ - Host: server.URL, - } + kubeClient := client.New(server.URL, nil) data, err := ioutil.ReadFile("api/examples/controller.json") if err != nil { log.Fatalf("Unexpected error: %#v", err) diff --git a/cmd/localkube/localkube.go b/cmd/localkube/localkube.go index 804e609ae3f..282ecb726a2 100644 --- a/cmd/localkube/localkube.go +++ b/cmd/localkube/localkube.go @@ -86,10 +86,9 @@ func api_server() { // Starts up a controller manager. Never returns. func controller_manager() { - controllerManager := controller.MakeReplicationManager(etcd.NewClient([]string{*etcd_server}), - client.Client{ - Host: fmt.Sprintf("http://%s:%d", *master_address, *master_port), - }) + controllerManager := controller.MakeReplicationManager( + etcd.NewClient([]string{*etcd_server}), + client.New(fmt.Sprintf("http://%s:%d", *master_address, *master_port), nil)) controllerManager.Run(20 * time.Second) select {} diff --git a/pkg/client/client.go b/pkg/client/client.go index c51a877ab9a..2fc8cb694e0 100644 --- a/pkg/client/client.go +++ b/pkg/client/client.go @@ -59,47 +59,62 @@ type AuthInfo struct { // Client is the actual implementation of a Kubernetes client. // Host is the http://... base for the URL type Client struct { - Host string - Auth *AuthInfo + host string + auth *AuthInfo httpClient *http.Client } -// Underlying base implementation of performing a request. -// method is the HTTP method (e.g. "GET") -// path is the path on the host to hit -// requestBody is the body of the request. Can be nil. -// target the interface to marshal the JSON response into. Can be nil. -func (client Client) rawRequest(method, path string, requestBody io.Reader, target interface{}) ([]byte, error) { - request, err := http.NewRequest(method, client.makeURL(path), requestBody) +// Create a new client object. +func New(host string, auth *AuthInfo) *Client { + return &Client{ + auth: auth, + host: host, + httpClient: &http.Client{ + Transport: &http.Transport{ + TLSClientConfig: &tls.Config{ + InsecureSkipVerify: true, + }, + }, + }, + } +} + +// Execute a request, adds authentication (if auth != nil), and HTTPS cert ignoring. +func (c *Client) doRequest(request *http.Request) ([]byte, error) { + if c.auth != nil { + request.SetBasicAuth(c.auth.User, c.auth.Password) + } + response, err := c.httpClient.Do(request) if err != nil { return []byte{}, err } - if client.Auth != nil { - request.SetBasicAuth(client.Auth.User, client.Auth.Password) - } - tr := &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, - } - var httpClient *http.Client - if client.httpClient != nil { - httpClient = client.httpClient - } else { - httpClient = &http.Client{Transport: tr} - } - response, err := httpClient.Do(request) - if err != nil { - return nil, err - } defer response.Body.Close() body, err := ioutil.ReadAll(response.Body) if err != nil { return body, err } if response.StatusCode < http.StatusOK || response.StatusCode > http.StatusPartialContent { - return nil, fmt.Errorf("request [%s %s] failed (%d) %s: %s", method, client.makeURL(path), response.StatusCode, response.Status, string(body)) + return nil, fmt.Errorf("request [%#v] failed (%d) %s: %s", request, response.StatusCode, response.Status, string(body)) + } + return body, err +} + +// Underlying base implementation of performing a request. +// method is the HTTP method (e.g. "GET") +// path is the path on the host to hit +// requestBody is the body of the request. Can be nil. +// target the interface to marshal the JSON response into. Can be nil. +func (c *Client) rawRequest(method, path string, requestBody io.Reader, target interface{}) ([]byte, error) { + request, err := http.NewRequest(method, c.makeURL(path), requestBody) + if err != nil { + return []byte{}, err + } + body, err := c.doRequest(request) + if err != nil { + return body, err } if target != nil { - err = json.Unmarshal(body, target) + err = api.DecodeInto(body, target) } if err != nil { log.Printf("Failed to parse: %s\n", string(body)) @@ -109,7 +124,7 @@ func (client Client) rawRequest(method, path string, requestBody io.Reader, targ } func (client Client) makeURL(path string) string { - return client.Host + "/api/v1beta1/" + path + return client.host + "/api/v1beta1/" + path } // EncodeSelector transforms a selector expressed as a key/value map, into a diff --git a/pkg/client/client_test.go b/pkg/client/client_test.go index bbdf20edf32..07061e980e8 100644 --- a/pkg/client/client_test.go +++ b/pkg/client/client_test.go @@ -38,7 +38,7 @@ func makeUrl(suffix string) string { func TestListEmptyPods(t *testing.T) { c := &TestClient{ - Request: Request{Method: "GET", Path: "/pods"}, + Request: testRequest{Method: "GET", Path: "/pods"}, Response: Response{StatusCode: 200, Body: api.PodList{}}, } podList, err := c.Setup().ListPods(nil) @@ -47,7 +47,7 @@ func TestListEmptyPods(t *testing.T) { func TestListPods(t *testing.T) { c := &TestClient{ - Request: Request{Method: "GET", Path: "/pods"}, + Request: testRequest{Method: "GET", Path: "/pods"}, Response: Response{StatusCode: 200, Body: api.PodList{ Items: []api.Pod{ @@ -76,7 +76,7 @@ func validateLabels(a, b string) bool { func TestListPodsLabels(t *testing.T) { c := &TestClient{ - Request: Request{Method: "GET", Path: "/pods", Query: url.Values{"labels": []string{"foo=bar,name=baz"}}}, + Request: testRequest{Method: "GET", Path: "/pods", Query: url.Values{"labels": []string{"foo=bar,name=baz"}}}, Response: Response{ StatusCode: 200, Body: api.PodList{ @@ -103,7 +103,7 @@ func TestListPodsLabels(t *testing.T) { func TestGetPod(t *testing.T) { c := &TestClient{ - Request: Request{Method: "GET", Path: "/pods/foo"}, + Request: testRequest{Method: "GET", Path: "/pods/foo"}, Response: Response{ StatusCode: 200, Body: api.Pod{ @@ -123,7 +123,7 @@ func TestGetPod(t *testing.T) { func TestDeletePod(t *testing.T) { c := &TestClient{ - Request: Request{Method: "DELETE", Path: "/pods/foo"}, + Request: testRequest{Method: "DELETE", Path: "/pods/foo"}, Response: Response{StatusCode: 200}, } err := c.Setup().DeletePod("foo") @@ -141,7 +141,7 @@ func TestCreatePod(t *testing.T) { }, } c := &TestClient{ - Request: Request{Method: "POST", Path: "/pods", Body: requestPod}, + Request: testRequest{Method: "POST", Path: "/pods", Body: requestPod}, Response: Response{ StatusCode: 200, Body: requestPod, @@ -163,7 +163,7 @@ func TestUpdatePod(t *testing.T) { }, } c := &TestClient{ - Request: Request{Method: "PUT", Path: "/pods/foo"}, + Request: testRequest{Method: "PUT", Path: "/pods/foo"}, Response: Response{StatusCode: 200, Body: requestPod}, } receivedPod, err := c.Setup().UpdatePod(requestPod) @@ -172,7 +172,7 @@ func TestUpdatePod(t *testing.T) { func TestGetController(t *testing.T) { c := &TestClient{ - Request: Request{Method: "GET", Path: "/replicationControllers/foo"}, + Request: testRequest{Method: "GET", Path: "/replicationControllers/foo"}, Response: Response{ StatusCode: 200, Body: api.ReplicationController{ @@ -200,7 +200,7 @@ func TestUpdateController(t *testing.T) { }, } c := &TestClient{ - Request: Request{Method: "PUT", Path: "/replicationControllers/foo"}, + Request: testRequest{Method: "PUT", Path: "/replicationControllers/foo"}, Response: Response{ StatusCode: 200, Body: api.ReplicationController{ @@ -223,7 +223,7 @@ func TestUpdateController(t *testing.T) { func TestDeleteController(t *testing.T) { c := &TestClient{ - Request: Request{Method: "DELETE", Path: "/replicationControllers/foo"}, + Request: testRequest{Method: "DELETE", Path: "/replicationControllers/foo"}, Response: Response{StatusCode: 200}, } err := c.Setup().DeleteReplicationController("foo") @@ -237,7 +237,7 @@ func TestCreateController(t *testing.T) { }, } c := &TestClient{ - Request: Request{Method: "POST", Path: "/replicationControllers", Body: requestController}, + Request: testRequest{Method: "POST", Path: "/replicationControllers", Body: requestController}, Response: Response{ StatusCode: 200, Body: api.ReplicationController{ @@ -267,7 +267,7 @@ func body(obj interface{}, raw *string) *string { return raw } -type Request struct { +type testRequest struct { Method string Path string Header string @@ -284,7 +284,7 @@ type Response struct { type TestClient struct { *Client - Request Request + Request testRequest Response Response Error bool server *httptest.Server @@ -306,9 +306,9 @@ func (c *TestClient) Setup() *TestClient { } c.server = httptest.NewTLSServer(c.handler) if c.Client == nil { - c.Client = &Client{} + c.Client = New("", nil) } - c.Client.Host = c.server.URL + c.Client.host = c.server.URL c.QueryValidator = map[string]func(string, string) bool{} return c } @@ -355,7 +355,7 @@ func (c *TestClient) Validate(t *testing.T, received interface{}, err error) { func TestGetService(t *testing.T) { c := &TestClient{ - Request: Request{Method: "GET", Path: "/services/1"}, + Request: testRequest{Method: "GET", Path: "/services/1"}, Response: Response{StatusCode: 200, Body: &api.Service{JSONBase: api.JSONBase{ID: "service-1"}}}, } response, err := c.Setup().GetService("1") @@ -364,7 +364,7 @@ func TestGetService(t *testing.T) { func TestCreateService(t *testing.T) { c := (&TestClient{ - Request: Request{Method: "POST", Path: "/services", Body: &api.Service{JSONBase: api.JSONBase{ID: "service-1"}}}, + Request: testRequest{Method: "POST", Path: "/services", Body: &api.Service{JSONBase: api.JSONBase{ID: "service-1"}}}, Response: Response{StatusCode: 200, Body: &api.Service{JSONBase: api.JSONBase{ID: "service-1"}}}, }).Setup() response, err := c.Setup().CreateService(api.Service{JSONBase: api.JSONBase{ID: "service-1"}}) @@ -373,7 +373,7 @@ func TestCreateService(t *testing.T) { func TestUpdateService(t *testing.T) { c := &TestClient{ - Request: Request{Method: "PUT", Path: "/services/service-1", Body: &api.Service{JSONBase: api.JSONBase{ID: "service-1"}}}, + Request: testRequest{Method: "PUT", Path: "/services/service-1", Body: &api.Service{JSONBase: api.JSONBase{ID: "service-1"}}}, Response: Response{StatusCode: 200, Body: &api.Service{JSONBase: api.JSONBase{ID: "service-1"}}}, } response, err := c.Setup().UpdateService(api.Service{JSONBase: api.JSONBase{ID: "service-1"}}) @@ -382,7 +382,7 @@ func TestUpdateService(t *testing.T) { func TestDeleteService(t *testing.T) { c := &TestClient{ - Request: Request{Method: "DELETE", Path: "/services/1"}, + Request: testRequest{Method: "DELETE", Path: "/services/1"}, Response: Response{StatusCode: 200}, } err := c.Setup().DeleteService("1") @@ -391,16 +391,40 @@ func TestDeleteService(t *testing.T) { func TestMakeRequest(t *testing.T) { testClients := []TestClient{ - {Request: Request{Method: "GET", Path: "/good"}, Response: Response{StatusCode: 200}}, - {Request: Request{Method: "GET", Path: "/bad%ZZ"}, Error: true}, - {Client: &Client{Auth: &AuthInfo{"foo", "bar"}}, Request: Request{Method: "GET", Path: "/auth", Header: "Authorization"}, Response: Response{StatusCode: 200}}, - {Client: &Client{httpClient: http.DefaultClient}, Request: Request{Method: "GET", Path: "/nocertificate"}, Error: true}, - {Request: Request{Method: "GET", Path: "/error"}, Response: Response{StatusCode: 500}, Error: true}, - {Request: Request{Method: "POST", Path: "/faildecode"}, Response: Response{StatusCode: 200, Body: "aaaaa"}, Target: &struct{}{}, Error: true}, - {Request: Request{Method: "GET", Path: "/failread"}, Response: Response{StatusCode: 200, Body: "aaaaa"}, Target: &struct{}{}, Error: true}, + {Request: testRequest{Method: "GET", Path: "/good"}, Response: Response{StatusCode: 200}}, + {Request: testRequest{Method: "GET", Path: "/bad%ZZ"}, Error: true}, + {Client: New("", &AuthInfo{"foo", "bar"}), Request: testRequest{Method: "GET", Path: "/auth", Header: "Authorization"}, Response: Response{StatusCode: 200}}, + {Client: &Client{httpClient: http.DefaultClient}, Request: testRequest{Method: "GET", Path: "/nocertificate"}, Error: true}, + {Request: testRequest{Method: "GET", Path: "/error"}, Response: Response{StatusCode: 500}, Error: true}, + {Request: testRequest{Method: "POST", Path: "/faildecode"}, Response: Response{StatusCode: 200, Body: "aaaaa"}, Target: &struct{}{}, Error: true}, + {Request: testRequest{Method: "GET", Path: "/failread"}, Response: Response{StatusCode: 200, Body: "aaaaa"}, Target: &struct{}{}, Error: true}, } for _, c := range testClients { response, err := c.Setup().rawRequest(c.Request.Method, c.Request.Path[1:], nil, c.Target) c.Validate(t, response, err) } } + +func TestDoRequest(t *testing.T) { + expectedBody := `{ "items": []}` + fakeHandler := util.FakeHandler{ + StatusCode: 200, + ResponseBody: expectedBody, + T: t, + } + testServer := httptest.NewTLSServer(&fakeHandler) + request, _ := http.NewRequest("GET", testServer.URL+"/foo/bar", nil) + auth := AuthInfo{User: "user", Password: "pass"} + c := New(testServer.URL, &auth) + body, err := c.doRequest(request) + if request.Header["Authorization"] == nil { + t.Errorf("Request is missing authorization header: %#v", *request) + } + if err != nil { + t.Error("Unexpected error") + } + if string(body) != expectedBody { + t.Errorf("Expected body: '%s', saw: '%s'", expectedBody, body) + } + fakeHandler.ValidateRequest(t, "/foo/bar", "GET", nil) +} diff --git a/pkg/cloudcfg/request.go b/pkg/client/request.go similarity index 86% rename from pkg/cloudcfg/request.go rename to pkg/client/request.go index cea3d98a0a3..3c711fe3763 100644 --- a/pkg/cloudcfg/request.go +++ b/pkg/client/request.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package cloudcfg +package client import ( "bytes" @@ -26,46 +26,33 @@ import ( "time" "github.com/GoogleCloudPlatform/kubernetes/pkg/api" - "github.com/GoogleCloudPlatform/kubernetes/pkg/client" "github.com/GoogleCloudPlatform/kubernetes/pkg/labels" ) // Server contains info locating a kubernetes api server. // Example usage: // auth, err := LoadAuth(filename) -// s := New(url, auth) -// resp, err := s.Verb("GET"). +// c := New(url, auth) +// resp, err := c.Verb("GET"). // Path("api/v1beta1"). // Path("pods"). // Selector("area=staging"). // Timeout(10*time.Second). // Do() // list, ok := resp.(api.PodList) -type Server struct { - auth *client.AuthInfo - rawUrl string -} - -// Create a new server object. -func New(serverUrl string, auth *client.AuthInfo) *Server { - return &Server{ - auth: auth, - rawUrl: serverUrl, - } -} // Begin a request with a verb (GET, POST, PUT, DELETE) -func (s *Server) Verb(verb string) *Request { +func (c *Client) Verb(verb string) *Request { return &Request{ verb: verb, - s: s, + c: c, path: "/", } } // Request allows for building up a request to a server in a chained fashion. type Request struct { - s *Server + c *Client err error verb string path string @@ -118,7 +105,7 @@ func (r *Request) Do() (interface{}, error) { if r.err != nil { return nil, r.err } - finalUrl := r.s.rawUrl + r.path + finalUrl := r.c.host + r.path query := url.Values{} if r.selector != nil { query.Add("labels", r.selector.String()) @@ -150,7 +137,7 @@ func (r *Request) Do() (interface{}, error) { if err != nil { return nil, err } - str, err := doRequest(req, r.s.auth) + str, err := r.c.doRequest(req) if err != nil { return nil, err } diff --git a/pkg/cloudcfg/request_test.go b/pkg/client/request_test.go similarity index 65% rename from pkg/cloudcfg/request_test.go rename to pkg/client/request_test.go index d05fbe63167..41070591cd0 100644 --- a/pkg/cloudcfg/request_test.go +++ b/pkg/client/request_test.go @@ -14,16 +14,16 @@ See the License for the specific language governing permissions and limitations under the License. */ -package cloudcfg +package client import ( + "io/ioutil" "net/http/httptest" "reflect" "testing" "time" "github.com/GoogleCloudPlatform/kubernetes/pkg/api" - "github.com/GoogleCloudPlatform/kubernetes/pkg/client" "github.com/GoogleCloudPlatform/kubernetes/pkg/util" ) @@ -37,7 +37,7 @@ func TestDoRequestNewWay(t *testing.T) { T: t, } testServer := httptest.NewTLSServer(&fakeHandler) - auth := client.AuthInfo{User: "user", Password: "pass"} + auth := AuthInfo{User: "user", Password: "pass"} s := New(testServer.URL, &auth) obj, err := s.Verb("POST"). Path("foo/bar"). @@ -65,7 +65,7 @@ func TestDoRequestNewWay(t *testing.T) { } func TestDoRequestNewWayObj(t *testing.T) { - reqObj := &api.Pod{} + reqObj := &api.Pod{JSONBase: api.JSONBase{ID: "foo"}} reqBodyExpected, _ := api.Encode(reqObj) expectedObj := &api.Service{Port: 12345} expectedBody, _ := api.Encode(expectedObj) @@ -75,7 +75,7 @@ func TestDoRequestNewWayObj(t *testing.T) { T: t, } testServer := httptest.NewTLSServer(&fakeHandler) - auth := client.AuthInfo{User: "user", Password: "pass"} + auth := AuthInfo{User: "user", Password: "pass"} s := New(testServer.URL, &auth) obj, err := s.Verb("POST"). Path("foo/bar"). @@ -102,3 +102,48 @@ func TestDoRequestNewWayObj(t *testing.T) { t.Errorf("Request is missing authorization header: %#v", *fakeHandler.RequestReceived) } } + +func TestDoRequestNewWayFile(t *testing.T) { + reqObj := &api.Pod{JSONBase: api.JSONBase{ID: "foo"}} + reqBodyExpected, err := api.Encode(reqObj) + expectNoError(t, err) + file, err := ioutil.TempFile("", "foo") + expectNoError(t, err) + _, err = file.Write(reqBodyExpected) + expectNoError(t, err) + + expectedObj := &api.Service{Port: 12345} + expectedBody, _ := api.Encode(expectedObj) + fakeHandler := util.FakeHandler{ + StatusCode: 200, + ResponseBody: string(expectedBody), + T: t, + } + testServer := httptest.NewTLSServer(&fakeHandler) + auth := AuthInfo{User: "user", Password: "pass"} + s := New(testServer.URL, &auth) + obj, err := s.Verb("POST"). + Path("foo/bar"). + Path("baz"). + Selector("name=foo"). + Timeout(time.Second). + Body(file.Name()). + Do() + if err != nil { + t.Errorf("Unexpected error: %v %#v", err, err) + return + } + if obj == nil { + t.Error("nil obj") + } else if !reflect.DeepEqual(obj, expectedObj) { + t.Errorf("Expected: %#v, got %#v", expectedObj, obj) + } + tmpStr := string(reqBodyExpected) + fakeHandler.ValidateRequest(t, "/foo/bar/baz", "POST", &tmpStr) + if fakeHandler.RequestReceived.URL.RawQuery != "labels=name%3Dfoo&timeout=1s" { + t.Errorf("Unexpected query: %v", fakeHandler.RequestReceived.URL.RawQuery) + } + if fakeHandler.RequestReceived.Header["Authorization"] == nil { + t.Errorf("Request is missing authorization header: %#v", *fakeHandler.RequestReceived) + } +} diff --git a/pkg/cloudcfg/cloudcfg.go b/pkg/cloudcfg/cloudcfg.go index 0d17707d7aa..0bd6a195a8c 100644 --- a/pkg/cloudcfg/cloudcfg.go +++ b/pkg/cloudcfg/cloudcfg.go @@ -17,13 +17,10 @@ limitations under the License. package cloudcfg import ( - "bytes" - "crypto/tls" "encoding/json" "fmt" "io/ioutil" "log" - "net/http" "os" "strconv" "strings" @@ -90,7 +87,7 @@ func Update(name string, client client.ClientInterface, updatePeriod time.Durati return nil } -// RequestWithBody is a helper method that creates an HTTP request with the specified url, method +/*// RequestWithBody is a helper method that creates an HTTP request with the specified url, method // and a body read from 'configFile' func requestWithBody(configFile, url, method string) (*http.Request, error) { if len(configFile) == 0 { @@ -127,7 +124,7 @@ func doRequest(request *http.Request, auth *client.AuthInfo) ([]byte, error) { defer response.Body.Close() body, err := ioutil.ReadAll(response.Body) return body, err -} +}*/ // StopController stops a controller named 'name' by setting replicas to zero func StopController(name string, client client.ClientInterface) error { diff --git a/pkg/cloudcfg/cloudcfg_test.go b/pkg/cloudcfg/cloudcfg_test.go index 13795309133..eb586c878ba 100644 --- a/pkg/cloudcfg/cloudcfg_test.go +++ b/pkg/cloudcfg/cloudcfg_test.go @@ -19,14 +19,11 @@ package cloudcfg import ( "encoding/json" "io/ioutil" - "net/http" - "net/http/httptest" "os" "testing" "github.com/GoogleCloudPlatform/kubernetes/pkg/api" "github.com/GoogleCloudPlatform/kubernetes/pkg/client" - "github.com/GoogleCloudPlatform/kubernetes/pkg/util" ) // TODO: This doesn't reduce typing enough to make it worth the less readable errors. Remove. @@ -147,29 +144,6 @@ func TestUpdateNoPods(t *testing.T) { validateAction(Action{action: "list-pods"}, client.actions[1], t) } -func TestDoRequest(t *testing.T) { - expectedBody := `{ "items": []}` - fakeHandler := util.FakeHandler{ - StatusCode: 200, - ResponseBody: expectedBody, - T: t, - } - testServer := httptest.NewTLSServer(&fakeHandler) - request, _ := http.NewRequest("GET", testServer.URL+"/foo/bar", nil) - auth := client.AuthInfo{User: "user", Password: "pass"} - body, err := doRequest(request, &auth) - if request.Header["Authorization"] == nil { - t.Errorf("Request is missing authorization header: %#v", *request) - } - if err != nil { - t.Error("Unexpected error") - } - if string(body) != expectedBody { - t.Errorf("Expected body: '%s', saw: '%s'", expectedBody, body) - } - fakeHandler.ValidateRequest(t, "/foo/bar", "GET", nil) -} - func TestRunController(t *testing.T) { fakeClient := FakeKubeClient{} name := "name" @@ -283,6 +257,7 @@ func TestCloudCfgDeleteControllerWithReplicas(t *testing.T) { } } +/* func TestRequestWithBodyNoSuchFile(t *testing.T) { request, err := requestWithBody("non/existent/file.json", "http://www.google.com", "GET") if request != nil { @@ -291,7 +266,7 @@ func TestRequestWithBodyNoSuchFile(t *testing.T) { if err == nil { t.Error("Unexpected non-error") } -} +}*/ func TestLoadAuthInfo(t *testing.T) { testAuthInfo := &client.AuthInfo{ @@ -326,27 +301,6 @@ func TestLoadAuthInfo(t *testing.T) { } } -func TestRequestWithBody(t *testing.T) { - file, err := ioutil.TempFile("", "foo") - expectNoError(t, err) - data, err := json.Marshal(api.Pod{JSONBase: api.JSONBase{ID: "foo"}}) - expectNoError(t, err) - _, err = file.Write(data) - expectNoError(t, err) - request, err := requestWithBody(file.Name(), "http://www.google.com", "GET") - if request == nil { - t.Error("Unexpected nil result") - } - if err != nil { - t.Errorf("Unexpected error: %#v") - } - dataOut, err := ioutil.ReadAll(request.Body) - expectNoError(t, err) - if string(data) != string(dataOut) { - t.Errorf("Mismatched data. Expected %s, got %s", data, dataOut) - } -} - func validatePort(t *testing.T, p api.Port, external int, internal int) { if p.HostPort != external || p.ContainerPort != internal { t.Errorf("Unexpected port: %#v != (%d, %d)", p, external, internal) diff --git a/pkg/controller/replication_controller_test.go b/pkg/controller/replication_controller_test.go index b9be3e1ad12..6a41ddf42e9 100644 --- a/pkg/controller/replication_controller_test.go +++ b/pkg/controller/replication_controller_test.go @@ -111,13 +111,11 @@ func TestSyncReplicationControllerDoesNothing(t *testing.T) { ResponseBody: string(body), } testServer := httptest.NewTLSServer(&fakeHandler) - client := client.Client{ - Host: testServer.URL, - } + client := client.New(testServer.URL, nil) fakePodControl := FakePodControl{} - manager := MakeReplicationManager(nil, &client) + manager := MakeReplicationManager(nil, client) manager.podControl = &fakePodControl controllerSpec := makeReplicationController(2) @@ -133,13 +131,11 @@ func TestSyncReplicationControllerDeletes(t *testing.T) { ResponseBody: string(body), } testServer := httptest.NewTLSServer(&fakeHandler) - client := client.Client{ - Host: testServer.URL, - } + client := client.New(testServer.URL, nil) fakePodControl := FakePodControl{} - manager := MakeReplicationManager(nil, &client) + manager := MakeReplicationManager(nil, client) manager.podControl = &fakePodControl controllerSpec := makeReplicationController(1) @@ -155,13 +151,11 @@ func TestSyncReplicationControllerCreates(t *testing.T) { ResponseBody: string(body), } testServer := httptest.NewTLSServer(&fakeHandler) - client := client.Client{ - Host: testServer.URL, - } + client := client.New(testServer.URL, nil) fakePodControl := FakePodControl{} - manager := MakeReplicationManager(nil, &client) + manager := MakeReplicationManager(nil, client) manager.podControl = &fakePodControl controllerSpec := makeReplicationController(2) @@ -177,9 +171,7 @@ func TestCreateReplica(t *testing.T) { ResponseBody: string(body), } testServer := httptest.NewTLSServer(&fakeHandler) - client := client.Client{ - Host: testServer.URL, - } + client := client.New(testServer.URL, nil) podControl := RealPodControl{ kubeClient: client, @@ -222,13 +214,11 @@ func TestHandleWatchResponseNotSet(t *testing.T) { ResponseBody: string(body), } testServer := httptest.NewTLSServer(&fakeHandler) - client := client.Client{ - Host: testServer.URL, - } + client := client.New(testServer.URL, nil) fakePodControl := FakePodControl{} - manager := MakeReplicationManager(nil, &client) + manager := MakeReplicationManager(nil, client) manager.podControl = &fakePodControl _, err := manager.handleWatchResponse(&etcd.Response{ Action: "update", @@ -243,13 +233,11 @@ func TestHandleWatchResponseNoNode(t *testing.T) { ResponseBody: string(body), } testServer := httptest.NewTLSServer(&fakeHandler) - client := client.Client{ - Host: testServer.URL, - } + client := client.New(testServer.URL, nil) fakePodControl := FakePodControl{} - manager := MakeReplicationManager(nil, &client) + manager := MakeReplicationManager(nil, client) manager.podControl = &fakePodControl _, err := manager.handleWatchResponse(&etcd.Response{ Action: "set", @@ -266,13 +254,11 @@ func TestHandleWatchResponseBadData(t *testing.T) { ResponseBody: string(body), } testServer := httptest.NewTLSServer(&fakeHandler) - client := client.Client{ - Host: testServer.URL, - } + client := client.New(testServer.URL, nil) fakePodControl := FakePodControl{} - manager := MakeReplicationManager(nil, &client) + manager := MakeReplicationManager(nil, client) manager.podControl = &fakePodControl _, err := manager.handleWatchResponse(&etcd.Response{ Action: "set", @@ -292,13 +278,11 @@ func TestHandleWatchResponse(t *testing.T) { ResponseBody: string(body), } testServer := httptest.NewTLSServer(&fakeHandler) - client := client.Client{ - Host: testServer.URL, - } + client := client.New(testServer.URL, nil) fakePodControl := FakePodControl{} - manager := MakeReplicationManager(nil, &client) + manager := MakeReplicationManager(nil, client) manager.podControl = &fakePodControl controller := makeReplicationController(2) @@ -326,13 +310,11 @@ func TestHandleWatchResponseDelete(t *testing.T) { ResponseBody: string(body), } testServer := httptest.NewTLSServer(&fakeHandler) - client := client.Client{ - Host: testServer.URL, - } + client := client.New(testServer.URL, nil) fakePodControl := FakePodControl{} - manager := MakeReplicationManager(nil, &client) + manager := MakeReplicationManager(nil, client) manager.podControl = &fakePodControl controller := makeReplicationController(2) @@ -417,9 +399,7 @@ func TestSyncronize(t *testing.T) { T: t, } testServer := httptest.NewTLSServer(&fakeHandler) - client := client.Client{ - Host: testServer.URL, - } + client := client.New(testServer.URL, nil) manager := MakeReplicationManager(fakeEtcd, client) fakePodControl := FakePodControl{} manager.podControl = &fakePodControl