github.com/deemoprobe/k8s-first-commit@v0.0.0-20230430165612-a541f1982be3/pkg/cloudcfg/cloudcfg_test.go (about)

     1  /*
     2  Copyright 2014 Google Inc. All rights reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  package cloudcfg
    17  
    18  import (
    19  	"encoding/json"
    20  	"io/ioutil"
    21  	"net/http"
    22  	"net/http/httptest"
    23  	"testing"
    24  
    25  	. "github.com/GoogleCloudPlatform/kubernetes/pkg/api"
    26  	"github.com/GoogleCloudPlatform/kubernetes/pkg/util"
    27  )
    28  
    29  // TODO: This doesn't reduce typing enough to make it worth the less readable errors. Remove.
    30  func expectNoError(t *testing.T, err error) {
    31  	if err != nil {
    32  		t.Errorf("Unexpected error: %#v", err)
    33  	}
    34  }
    35  
    36  type Action struct {
    37  	action string
    38  	value  interface{}
    39  }
    40  
    41  type FakeKubeClient struct {
    42  	actions []Action
    43  	tasks   TaskList
    44  	ctrl    ReplicationController
    45  }
    46  
    47  func (client *FakeKubeClient) ListTasks(labelQuery map[string]string) (TaskList, error) {
    48  	client.actions = append(client.actions, Action{action: "list-tasks"})
    49  	return client.tasks, nil
    50  }
    51  
    52  func (client *FakeKubeClient) GetTask(name string) (Task, error) {
    53  	client.actions = append(client.actions, Action{action: "get-task", value: name})
    54  	return Task{}, nil
    55  }
    56  
    57  func (client *FakeKubeClient) DeleteTask(name string) error {
    58  	client.actions = append(client.actions, Action{action: "delete-task", value: name})
    59  	return nil
    60  }
    61  
    62  func (client *FakeKubeClient) CreateTask(task Task) (Task, error) {
    63  	client.actions = append(client.actions, Action{action: "create-task"})
    64  	return Task{}, nil
    65  }
    66  
    67  func (client *FakeKubeClient) UpdateTask(task Task) (Task, error) {
    68  	client.actions = append(client.actions, Action{action: "update-task", value: task.ID})
    69  	return Task{}, nil
    70  }
    71  
    72  func (client *FakeKubeClient) GetReplicationController(name string) (ReplicationController, error) {
    73  	client.actions = append(client.actions, Action{action: "get-controller", value: name})
    74  	return client.ctrl, nil
    75  }
    76  
    77  func (client *FakeKubeClient) CreateReplicationController(controller ReplicationController) (ReplicationController, error) {
    78  	client.actions = append(client.actions, Action{action: "create-controller", value: controller})
    79  	return ReplicationController{}, nil
    80  }
    81  
    82  func (client *FakeKubeClient) UpdateReplicationController(controller ReplicationController) (ReplicationController, error) {
    83  	client.actions = append(client.actions, Action{action: "update-controller", value: controller})
    84  	return ReplicationController{}, nil
    85  }
    86  
    87  func (client *FakeKubeClient) DeleteReplicationController(controller string) error {
    88  	client.actions = append(client.actions, Action{action: "delete-controller", value: controller})
    89  	return nil
    90  }
    91  
    92  func (client *FakeKubeClient) GetService(name string) (Service, error) {
    93  	client.actions = append(client.actions, Action{action: "get-controller", value: name})
    94  	return Service{}, nil
    95  }
    96  
    97  func (client *FakeKubeClient) CreateService(controller Service) (Service, error) {
    98  	client.actions = append(client.actions, Action{action: "create-service", value: controller})
    99  	return Service{}, nil
   100  }
   101  
   102  func (client *FakeKubeClient) UpdateService(controller Service) (Service, error) {
   103  	client.actions = append(client.actions, Action{action: "update-service", value: controller})
   104  	return Service{}, nil
   105  }
   106  
   107  func (client *FakeKubeClient) DeleteService(controller string) error {
   108  	client.actions = append(client.actions, Action{action: "delete-service", value: controller})
   109  	return nil
   110  }
   111  
   112  func validateAction(expectedAction, actualAction Action, t *testing.T) {
   113  	if expectedAction != actualAction {
   114  		t.Errorf("Unexpected action: %#v, expected: %#v", actualAction, expectedAction)
   115  	}
   116  }
   117  
   118  func TestUpdateWithTasks(t *testing.T) {
   119  	client := FakeKubeClient{
   120  		tasks: TaskList{
   121  			Items: []Task{
   122  				Task{JSONBase: JSONBase{ID: "task-1"}},
   123  				Task{JSONBase: JSONBase{ID: "task-2"}},
   124  			},
   125  		},
   126  	}
   127  	Update("foo", &client, 0)
   128  	if len(client.actions) != 4 {
   129  		t.Errorf("Unexpected action list %#v", client.actions)
   130  	}
   131  	validateAction(Action{action: "get-controller", value: "foo"}, client.actions[0], t)
   132  	validateAction(Action{action: "list-tasks"}, client.actions[1], t)
   133  	validateAction(Action{action: "update-task", value: "task-1"}, client.actions[2], t)
   134  	validateAction(Action{action: "update-task", value: "task-2"}, client.actions[3], t)
   135  }
   136  
   137  func TestUpdateNoTasks(t *testing.T) {
   138  	client := FakeKubeClient{}
   139  	Update("foo", &client, 0)
   140  	if len(client.actions) != 2 {
   141  		t.Errorf("Unexpected action list %#v", client.actions)
   142  	}
   143  	validateAction(Action{action: "get-controller", value: "foo"}, client.actions[0], t)
   144  	validateAction(Action{action: "list-tasks"}, client.actions[1], t)
   145  }
   146  
   147  func TestDoRequest(t *testing.T) {
   148  	expectedBody := `{ "items": []}`
   149  	fakeHandler := util.FakeHandler{
   150  		StatusCode:   200,
   151  		ResponseBody: expectedBody,
   152  	}
   153  	testServer := httptest.NewTLSServer(&fakeHandler)
   154  	request, _ := http.NewRequest("GET", testServer.URL+"/foo/bar", nil)
   155  	body, err := DoRequest(request, "user", "pass")
   156  	if request.Header["Authorization"] == nil {
   157  		t.Errorf("Request is missing authorization header: %#v", *request)
   158  	}
   159  	if err != nil {
   160  		t.Error("Unexpected error")
   161  	}
   162  	if body != expectedBody {
   163  		t.Errorf("Expected body: '%s', saw: '%s'", expectedBody, body)
   164  	}
   165  	fakeHandler.ValidateRequest(t, "/foo/bar", "GET", &fakeHandler.ResponseBody)
   166  }
   167  
   168  func TestRunController(t *testing.T) {
   169  	fakeClient := FakeKubeClient{}
   170  	name := "name"
   171  	image := "foo/bar"
   172  	replicas := 3
   173  	RunController(image, name, replicas, &fakeClient, "8080:80", -1)
   174  	if len(fakeClient.actions) != 1 || fakeClient.actions[0].action != "create-controller" {
   175  		t.Errorf("Unexpected actions: %#v", fakeClient.actions)
   176  	}
   177  	controller := fakeClient.actions[0].value.(ReplicationController)
   178  	if controller.ID != name ||
   179  		controller.DesiredState.Replicas != replicas ||
   180  		controller.DesiredState.TaskTemplate.DesiredState.Manifest.Containers[0].Image != image {
   181  		t.Errorf("Unexpected controller: %#v", controller)
   182  	}
   183  }
   184  
   185  func TestRunControllerWithService(t *testing.T) {
   186  	fakeClient := FakeKubeClient{}
   187  	name := "name"
   188  	image := "foo/bar"
   189  	replicas := 3
   190  	RunController(image, name, replicas, &fakeClient, "", 8000)
   191  	if len(fakeClient.actions) != 2 ||
   192  		fakeClient.actions[0].action != "create-controller" ||
   193  		fakeClient.actions[1].action != "create-service" {
   194  		t.Errorf("Unexpected actions: %#v", fakeClient.actions)
   195  	}
   196  	controller := fakeClient.actions[0].value.(ReplicationController)
   197  	if controller.ID != name ||
   198  		controller.DesiredState.Replicas != replicas ||
   199  		controller.DesiredState.TaskTemplate.DesiredState.Manifest.Containers[0].Image != image {
   200  		t.Errorf("Unexpected controller: %#v", controller)
   201  	}
   202  }
   203  
   204  func TestStopController(t *testing.T) {
   205  	fakeClient := FakeKubeClient{}
   206  	name := "name"
   207  	StopController(name, &fakeClient)
   208  	if len(fakeClient.actions) != 2 {
   209  		t.Errorf("Unexpected actions: %#v", fakeClient.actions)
   210  	}
   211  	if fakeClient.actions[0].action != "get-controller" ||
   212  		fakeClient.actions[0].value.(string) != name {
   213  		t.Errorf("Unexpected action: %#v", fakeClient.actions[0])
   214  	}
   215  	controller := fakeClient.actions[1].value.(ReplicationController)
   216  	if fakeClient.actions[1].action != "update-controller" ||
   217  		controller.DesiredState.Replicas != 0 {
   218  		t.Errorf("Unexpected action: %#v", fakeClient.actions[1])
   219  	}
   220  }
   221  
   222  func TestCloudCfgDeleteController(t *testing.T) {
   223  	fakeClient := FakeKubeClient{}
   224  	name := "name"
   225  	err := DeleteController(name, &fakeClient)
   226  	expectNoError(t, err)
   227  	if len(fakeClient.actions) != 2 {
   228  		t.Errorf("Unexpected actions: %#v", fakeClient.actions)
   229  	}
   230  	if fakeClient.actions[0].action != "get-controller" ||
   231  		fakeClient.actions[0].value.(string) != name {
   232  		t.Errorf("Unexpected action: %#v", fakeClient.actions[0])
   233  	}
   234  	if fakeClient.actions[1].action != "delete-controller" ||
   235  		fakeClient.actions[1].value.(string) != name {
   236  		t.Errorf("Unexpected action: %#v", fakeClient.actions[1])
   237  	}
   238  }
   239  
   240  func TestCloudCfgDeleteControllerWithReplicas(t *testing.T) {
   241  	fakeClient := FakeKubeClient{
   242  		ctrl: ReplicationController{
   243  			DesiredState: ReplicationControllerState{
   244  				Replicas: 2,
   245  			},
   246  		},
   247  	}
   248  	name := "name"
   249  	err := DeleteController(name, &fakeClient)
   250  	if len(fakeClient.actions) != 1 {
   251  		t.Errorf("Unexpected actions: %#v", fakeClient.actions)
   252  	}
   253  	if fakeClient.actions[0].action != "get-controller" ||
   254  		fakeClient.actions[0].value.(string) != name {
   255  		t.Errorf("Unexpected action: %#v", fakeClient.actions[0])
   256  	}
   257  	if err == nil {
   258  		t.Errorf("Unexpected non-error.")
   259  	}
   260  }
   261  
   262  func TestRequestWithBodyNoSuchFile(t *testing.T) {
   263  	request, err := RequestWithBody("non/existent/file.json", "http://www.google.com", "GET")
   264  	if request != nil {
   265  		t.Error("Unexpected non-nil result")
   266  	}
   267  	if err == nil {
   268  		t.Error("Unexpected non-error")
   269  	}
   270  }
   271  
   272  func TestRequestWithBody(t *testing.T) {
   273  	file, err := ioutil.TempFile("", "foo")
   274  	expectNoError(t, err)
   275  	data, err := json.Marshal(Task{JSONBase: JSONBase{ID: "foo"}})
   276  	expectNoError(t, err)
   277  	_, err = file.Write(data)
   278  	expectNoError(t, err)
   279  	request, err := RequestWithBody(file.Name(), "http://www.google.com", "GET")
   280  	if request == nil {
   281  		t.Error("Unexpected nil result")
   282  	}
   283  	if err != nil {
   284  		t.Errorf("Unexpected error: %#v")
   285  	}
   286  	dataOut, err := ioutil.ReadAll(request.Body)
   287  	expectNoError(t, err)
   288  	if string(data) != string(dataOut) {
   289  		t.Errorf("Mismatched data. Expected %s, got %s", data, dataOut)
   290  	}
   291  }
   292  
   293  func validatePort(t *testing.T, p Port, external int, internal int) {
   294  	if p.HostPort != external || p.ContainerPort != internal {
   295  		t.Errorf("Unexpected port: %#v != (%d, %d)", p, external, internal)
   296  	}
   297  }
   298  
   299  func TestMakePorts(t *testing.T) {
   300  	ports := makePorts("8080:80,8081:8081,443:444")
   301  	if len(ports) != 3 {
   302  		t.Errorf("Unexpected ports: %#v", ports)
   303  	}
   304  
   305  	validatePort(t, ports[0], 8080, 80)
   306  	validatePort(t, ports[1], 8081, 8081)
   307  	validatePort(t, ports[2], 443, 444)
   308  }