Exemplo n.º 1
0
func TestDoRequestNewWayObj(t *testing.T) {
	reqObj := &api.Pod{JSONBase: api.JSONBase{ID: "foo"}}
	reqBodyExpected, _ := runtime.Encode(reqObj)
	expectedObj := &api.Service{Port: 12345}
	expectedBody, _ := runtime.Encode(expectedObj)
	fakeHandler := util.FakeHandler{
		StatusCode:   200,
		ResponseBody: string(expectedBody),
		T:            t,
	}
	testServer := httptest.NewServer(&fakeHandler)
	auth := AuthInfo{User: "******", Password: "******"}
	c := NewOrDie(testServer.URL, &auth)
	obj, err := c.Verb("POST").
		Path("foo/bar").
		Path("baz").
		SelectorParam("labels", 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 !reflect.DeepEqual(obj, expectedObj) {
		t.Errorf("Expected: %#v, got %#v", expectedObj, obj)
	}
	tmpStr := string(reqBodyExpected)
	fakeHandler.ValidateRequest(t, "/api/v1beta1/foo/bar/baz?labels=name%3Dfoo", "POST", &tmpStr)
	if fakeHandler.RequestReceived.Header["Authorization"] == nil {
		t.Errorf("Request is missing authorization header: %#v", *fakeHandler.RequestReceived)
	}
}
Exemplo n.º 2
0
func TestDoRequestAcceptedSuccess(t *testing.T) {
	status := api.Status{Status: api.StatusSuccess}
	expectedBody, _ := runtime.Encode(status)
	fakeHandler := util.FakeHandler{
		StatusCode:   202,
		ResponseBody: string(expectedBody),
		T:            t,
	}
	testServer := httptest.NewServer(&fakeHandler)
	request, _ := http.NewRequest("GET", testServer.URL+"/foo/bar", nil)
	auth := AuthInfo{User: "******", Password: "******"}
	c, err := New(testServer.URL, &auth)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	body, err := c.doRequest(request)
	if request.Header["Authorization"] == nil {
		t.Errorf("Request is missing authorization header: %#v", *request)
	}
	if err != nil {
		t.Errorf("Unexpected error %#v", err)
	}
	statusOut, err := runtime.Decode(body)
	if err != nil {
		t.Errorf("Unexpected error %#v", err)
	}
	if !reflect.DeepEqual(&status, statusOut) {
		t.Errorf("Unexpected mis-match. Expected %#v.  Saw %#v", status, statusOut)
	}
	fakeHandler.ValidateRequest(t, "/foo/bar", "GET", nil)
}
Exemplo n.º 3
0
// Body makes the request use obj as the body. Optional.
// If obj is a string, try to read a file of that name.
// If obj is a []byte, send it directly.
// If obj is an io.Reader, use it directly.
// Otherwise, assume obj is an api type and marshall it correctly.
func (r *Request) Body(obj interface{}) *Request {
	if r.err != nil {
		return r
	}
	switch t := obj.(type) {
	case string:
		data, err := ioutil.ReadFile(t)
		if err != nil {
			r.err = err
			return r
		}
		r.body = bytes.NewBuffer(data)
	case []byte:
		r.body = bytes.NewBuffer(t)
	case io.Reader:
		r.body = t
	default:
		data, err := runtime.Encode(obj)
		if err != nil {
			r.err = err
			return r
		}
		r.body = bytes.NewBuffer(data)
	}
	return r
}
Exemplo n.º 4
0
func TestReadme(t *testing.T) {
	path := "../README.md"
	data, err := ioutil.ReadFile(path)
	if err != nil {
		t.Fatalf("Unable to read file: %v", err)
	}

	match := jsonRegexp.FindStringSubmatch(string(data))
	if match == nil {
		return
	}
	for _, json := range match[1:] {
		expectedType := &api.Pod{}
		if err := runtime.DecodeInto([]byte(json), expectedType); err != nil {
			t.Errorf("%s did not decode correctly: %v\n%s", path, err, string(data))
			return
		}
		if errors := validateObject(expectedType); len(errors) > 0 {
			t.Errorf("%s did not validate correctly: %v", path, errors)
		}
		encoded, err := runtime.Encode(expectedType)
		if err != nil {
			t.Errorf("Could not encode object: %v", err)
			continue
		}
		t.Logf("Found pod %s\n%s", json, encoded)
	}
}
Exemplo n.º 5
0
// PrintObj is an implementation of ResourcePrinter.PrintObj which simply writes the object to the Writer.
func (i *IdentityPrinter) PrintObj(obj interface{}, output io.Writer) error {
	data, err := runtime.Encode(obj)
	if err != nil {
		return err
	}
	return i.Print(data, output)
}
Exemplo n.º 6
0
func TestPolling(t *testing.T) {
	objects := []interface{}{
		&api.Status{Status: api.StatusWorking, Details: &api.StatusDetails{ID: "1234"}},
		&api.Status{Status: api.StatusWorking, Details: &api.StatusDetails{ID: "1234"}},
		&api.Status{Status: api.StatusWorking, Details: &api.StatusDetails{ID: "1234"}},
		&api.Status{Status: api.StatusWorking, Details: &api.StatusDetails{ID: "1234"}},
		&api.Status{Status: api.StatusSuccess},
	}

	callNumber := 0
	testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		data, err := runtime.Encode(objects[callNumber])
		if err != nil {
			t.Errorf("Unexpected encode error")
		}
		callNumber++
		w.Write(data)
	}))

	auth := AuthInfo{User: "******", Password: "******"}
	c := NewOrDie(testServer.URL, &auth)

	trials := []func(){
		func() {
			// Check that we do indeed poll when asked to.
			obj, err := c.Get().PollPeriod(5 * time.Millisecond).Do().Get()
			if err != nil {
				t.Errorf("Unexpected error: %v %#v", err, err)
				return
			}
			if s, ok := obj.(*api.Status); !ok || s.Status != api.StatusSuccess {
				t.Errorf("Unexpected return object: %#v", obj)
				return
			}
			if callNumber != len(objects) {
				t.Errorf("Unexpected number of calls: %v", callNumber)
			}
		},
		func() {
			// Check that we don't poll when asked not to.
			obj, err := c.Get().PollPeriod(0).Do().Get()
			if err == nil {
				t.Errorf("Unexpected non error: %v", obj)
				return
			}
			if se, ok := err.(*StatusErr); !ok || se.Status.Status != api.StatusWorking {
				t.Errorf("Unexpected kind of error: %#v", err)
				return
			}
			if callNumber != 1 {
				t.Errorf("Unexpected number of calls: %v", callNumber)
			}
		},
	}
	for _, f := range trials {
		callNumber = 0
		f()
	}
}
Exemplo n.º 7
0
func body(obj interface{}, raw *string) *string {
	if obj != nil {
		bs, _ := runtime.Encode(obj)
		body := string(bs)
		return &body
	}
	return raw
}
Exemplo n.º 8
0
func (s *ProxyServer) doError(w http.ResponseWriter, err error) {
	w.WriteHeader(http.StatusInternalServerError)
	w.Header().Add("Content-type", "application/json")
	data, _ := runtime.Encode(api.Status{
		Status:  api.StatusFailure,
		Message: fmt.Sprintf("internal error: %#v", err),
	})
	w.Write(data)
}
func TestCreateReplica(t *testing.T) {
	body, _ := runtime.Encode(api.Pod{})
	fakeHandler := util.FakeHandler{
		StatusCode:   200,
		ResponseBody: string(body),
	}
	testServer := httptest.NewTLSServer(&fakeHandler)
	client := client.NewOrDie(testServer.URL, nil)

	podControl := RealPodControl{
		kubeClient: client,
	}

	controllerSpec := api.ReplicationController{
		JSONBase: api.JSONBase{
			Kind: "ReplicationController",
		},
		DesiredState: api.ReplicationControllerState{
			PodTemplate: api.PodTemplate{
				DesiredState: api.PodState{
					Manifest: api.ContainerManifest{
						Containers: []api.Container{
							{
								Image: "foo/bar",
							},
						},
					},
				},
				Labels: map[string]string{
					"name": "foo",
					"type": "production",
				},
			},
		},
	}

	podControl.createReplica(controllerSpec)

	expectedPod := api.Pod{
		JSONBase: api.JSONBase{
			Kind:       "Pod",
			APIVersion: "v1beta1",
		},
		Labels:       controllerSpec.DesiredState.PodTemplate.Labels,
		DesiredState: controllerSpec.DesiredState.PodTemplate.DesiredState,
	}
	fakeHandler.ValidateRequest(t, makeURL("/pods"), "POST", nil)
	actualPod := api.Pod{}
	if err := json.Unmarshal([]byte(fakeHandler.RequestBody), &actualPod); err != nil {
		t.Errorf("Unexpected error: %#v", err)
	}
	if !reflect.DeepEqual(expectedPod, actualPod) {
		t.Logf("Body: %s", fakeHandler.RequestBody)
		t.Errorf("Unexpected mismatch.  Expected\n %#v,\n Got:\n %#v", expectedPod, actualPod)
	}
}
Exemplo n.º 10
0
// ToWireFormat takes input 'data' as either json or yaml, checks that it parses as the
// appropriate object type, and returns json for sending to the API or an error.
func (p *Parser) ToWireFormat(data []byte, storage string) ([]byte, error) {
	prototypeType, found := p.storageToType[storage]
	if !found {
		return nil, fmt.Errorf("unknown storage type: %v", storage)
	}

	obj := reflect.New(prototypeType).Interface()
	err := runtime.DecodeInto(data, obj)
	if err != nil {
		return nil, err
	}
	return runtime.Encode(obj)
}
Exemplo n.º 11
0
func TestEncode_Ptr(t *testing.T) {
	pod := &api.Pod{
		Labels: map[string]string{"name": "foo"},
	}
	obj := interface{}(pod)
	data, err := runtime.Encode(obj)
	obj2, err2 := runtime.Decode(data)
	if err != nil || err2 != nil {
		t.Fatalf("Failure: '%v' '%v'", err, err2)
	}
	if _, ok := obj2.(*api.Pod); !ok {
		t.Fatalf("Got wrong type")
	}
	if !reflect.DeepEqual(obj2, pod) {
		t.Errorf("Expected:\n %#v,\n Got:\n %#v", &pod, obj2)
	}
}
Exemplo n.º 12
0
func TestSyncReplicationControllerCreates(t *testing.T) {
	body, _ := runtime.Encode(newPodList(0))
	fakeHandler := util.FakeHandler{
		StatusCode:   200,
		ResponseBody: string(body),
	}
	testServer := httptest.NewTLSServer(&fakeHandler)
	client := client.NewOrDie(testServer.URL, nil)

	fakePodControl := FakePodControl{}

	manager := NewReplicationManager(client)
	manager.podControl = &fakePodControl

	controllerSpec := newReplicationController(2)

	manager.syncReplicationController(controllerSpec)
	validateSyncReplication(t, &fakePodControl, 2, 0)
}
Exemplo n.º 13
0
func runTest(t *testing.T, source interface{}) {
	name := reflect.TypeOf(source).Elem().Name()
	apiObjectFuzzer.Fuzz(source)
	j, err := runtime.FindJSONBase(source)
	if err != nil {
		t.Fatalf("Unexpected error %v for %#v", err, source)
	}
	j.SetKind("")
	j.SetAPIVersion("")

	data, err := runtime.Encode(source)
	if err != nil {
		t.Errorf("%v: %v (%#v)", name, err, source)
		return
	}

	obj2, err := runtime.Decode(data)
	if err != nil {
		t.Errorf("%v: %v", name, err)
		return
	} else {
		if !reflect.DeepEqual(source, obj2) {
			t.Errorf("1: %v: diff: %v", name, objDiff(source, obj2))
			return
		}
	}
	obj3 := reflect.New(reflect.TypeOf(source).Elem()).Interface()
	err = runtime.DecodeInto(data, obj3)
	if err != nil {
		t.Errorf("2: %v: %v", name, err)
		return
	} else {
		if !reflect.DeepEqual(source, obj3) {
			t.Errorf("3: %v: diff: %v", name, objDiff(source, obj3))
			return
		}
	}
}
Exemplo n.º 14
0
func TestNewBindingStorage(t *testing.T) {
	mockRegistry := MockRegistry{
		OnApplyBinding: func(b *api.Binding) error { return nil },
	}
	b := NewBindingStorage(mockRegistry)

	binding := &api.Binding{
		PodID: "foo",
		Host:  "bar",
	}
	body, err := runtime.Encode(binding)
	if err != nil {
		t.Fatalf("Unexpected encode error %v", err)
	}
	obj := b.New()
	err = runtime.DecodeInto(body, obj)
	if err != nil {
		t.Fatalf("Unexpected error %v", err)
	}
	if e, a := binding, obj; !reflect.DeepEqual(e, a) {
		t.Errorf("Expected %#v, but got %#v", e, a)
	}
}
Exemplo n.º 15
0
func DoParseTest(t *testing.T, storage string, obj interface{}, p *Parser) {
	jsonData, _ := runtime.Encode(obj)
	yamlData, _ := yaml.Marshal(obj)
	t.Logf("Intermediate yaml:\n%v\n", string(yamlData))
	t.Logf("Intermediate json:\n%v\n", string(jsonData))
	jsonGot, jsonErr := p.ToWireFormat(jsonData, storage)
	yamlGot, yamlErr := p.ToWireFormat(yamlData, storage)

	if jsonErr != nil {
		t.Errorf("json err: %#v", jsonErr)
	}
	if yamlErr != nil {
		t.Errorf("yaml err: %#v", yamlErr)
	}
	if string(jsonGot) != string(jsonData) {
		t.Errorf("json output didn't match:\nGot:\n%v\n\nWanted:\n%v\n",
			string(jsonGot), string(jsonData))
	}
	if string(yamlGot) != string(jsonData) {
		t.Errorf("yaml parsed output didn't match:\nGot:\n%v\n\nWanted:\n%v\n",
			string(yamlGot), string(jsonData))
	}
}
Exemplo n.º 16
0
func TestControllerDecode(t *testing.T) {
	mockRegistry := registrytest.ControllerRegistry{}
	storage := RegistryStorage{
		registry: &mockRegistry,
	}
	controller := &api.ReplicationController{
		JSONBase: api.JSONBase{
			ID: "foo",
		},
	}
	body, err := runtime.Encode(controller)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	controllerOut := storage.New()
	if err := runtime.DecodeInto(body, controllerOut); err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	if !reflect.DeepEqual(controller, controllerOut) {
		t.Errorf("Expected %#v, found %#v", controller, controllerOut)
	}
}
Exemplo n.º 17
0
func TestDoRequestAccepted(t *testing.T) {
	status := api.Status{Status: api.StatusWorking}
	expectedBody, _ := runtime.Encode(status)
	fakeHandler := util.FakeHandler{
		StatusCode:   202,
		ResponseBody: string(expectedBody),
		T:            t,
	}
	testServer := httptest.NewServer(&fakeHandler)
	request, _ := http.NewRequest("GET", testServer.URL+"/foo/bar", nil)
	auth := AuthInfo{User: "******", Password: "******"}
	c, err := New(testServer.URL, &auth)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	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 non-error")
		return
	}
	se, ok := err.(*StatusErr)
	if !ok {
		t.Errorf("Unexpected kind of error: %#v", err)
		return
	}
	if !reflect.DeepEqual(se.Status, status) {
		t.Errorf("Unexpected status: %#v", se.Status)
	}
	if body != nil {
		t.Errorf("Expected nil body, but saw: '%s'", body)
	}
	fakeHandler.ValidateRequest(t, "/foo/bar", "GET", nil)
}
Exemplo n.º 18
0
func TestPodDecode(t *testing.T) {
	podRegistry := registrytest.NewPodRegistry(nil)
	storage := RegistryStorage{
		registry: podRegistry,
	}
	expected := &api.Pod{
		JSONBase: api.JSONBase{
			ID: "foo",
		},
	}
	body, err := runtime.Encode(expected)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	actual := storage.New()
	if err := runtime.DecodeInto(body, actual); err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	if !reflect.DeepEqual(expected, actual) {
		t.Errorf("Expected %#v, Got %#v", expected, actual)
	}
}
Exemplo n.º 19
0
func TestBuildDecode(t *testing.T) {
	mockRegistry := test.BuildRegistry{}
	storage := Storage{
		registry: &mockRegistry,
	}
	build := &api.Build{
		JSONBase: kubeapi.JSONBase{
			ID: "foo",
		},
	}
	body, err := runtime.Encode(build)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	buildOut := storage.New()
	if err := runtime.DecodeInto(body, buildOut); err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	if !reflect.DeepEqual(build, buildOut) {
		t.Errorf("Expected %#v, found %#v", build, buildOut)
	}
}
Exemplo n.º 20
0
func (c *KubeConfig) executeAPIRequest(method string, clients map[string]RESTClient) bool {
	storage, path, hasSuffix := storagePathFromArg(c.Arg(1))
	validStorage := checkStorage(storage)
	client, ok := clients[storage]
	if !ok {
		glog.Fatalf("Unsupported storage type %s", storage)
	}

	verb := ""
	setBody := false
	var version uint64
	switch method {
	case "get":
		verb = "GET"
		if !validStorage || !hasSuffix {
			glog.Fatalf("usage: kubecfg [OPTIONS] %s <%s>[/<id>]", method, prettyWireStorage())
		}
	case "list":
		verb = "GET"
		if !validStorage || hasSuffix {
			glog.Fatalf("usage: kubecfg [OPTIONS] %s <%s>", method, prettyWireStorage())
		}
	case "delete":
		verb = "DELETE"
		if !validStorage || !hasSuffix {
			glog.Fatalf("usage: kubecfg [OPTIONS] %s <%s>/<id>", method, prettyWireStorage())
		}
	case "create":
		verb = "POST"
		setBody = true
		if !validStorage || hasSuffix {
			glog.Fatalf("usage: kubecfg [OPTIONS] %s <%s>", method, prettyWireStorage())
		}
	case "update":
		obj, err := client.Verb("GET").Path(path).Do().Get()
		if err != nil {
			glog.Fatalf("error obtaining resource version for update: %v", err)
		}
		jsonBase, err := runtime.FindJSONBase(obj)
		if err != nil {
			glog.Fatalf("error finding json base for update: %v", err)
		}
		version = jsonBase.ResourceVersion()
		verb = "PUT"
		setBody = true
		if !validStorage || !hasSuffix {
			glog.Fatalf("usage: kubecfg [OPTIONS] %s <%s>/<id>", method, prettyWireStorage())
		}
	default:
		return false
	}

	r := client.Verb(verb).
		Path(path).
		ParseSelectorParam("labels", c.Selector)
	if setBody {
		if version != 0 {
			data := c.readConfig(storage)
			obj, err := runtime.Decode(data)
			if err != nil {
				glog.Fatalf("error setting resource version: %v", err)
			}
			jsonBase, err := runtime.FindJSONBase(obj)
			if err != nil {
				glog.Fatalf("error setting resource version: %v", err)
			}
			jsonBase.SetResourceVersion(version)
			data, err = runtime.Encode(obj)
			if err != nil {
				glog.Fatalf("error setting resource version: %v", err)
			}
			r.Body(data)
		} else {
			r.Body(c.readConfig(storage))
		}
	}
	result := r.Do()
	obj, err := result.Get()
	if err != nil {
		glog.Fatalf("Got request error: %v\n", err)
		return false
	}

	var printer kubecfg.ResourcePrinter
	switch {
	case c.JSON:
		printer = &kubecfg.IdentityPrinter{}
	case c.YAML:
		printer = &kubecfg.YAMLPrinter{}
	case len(c.TemplateFile) > 0 || len(c.TemplateStr) > 0:
		var data []byte
		if len(c.TemplateFile) > 0 {
			var err error
			data, err = ioutil.ReadFile(c.TemplateFile)
			if err != nil {
				glog.Fatalf("Error reading template %s, %v\n", c.TemplateFile, err)
				return false
			}
		} else {
			data = []byte(c.TemplateStr)
		}
		tmpl, err := template.New("output").Parse(string(data))
		if err != nil {
			glog.Fatalf("Error parsing template %s, %v\n", string(data), err)
			return false
		}
		printer = &kubecfg.TemplatePrinter{
			Template: tmpl,
		}
	default:
		printer = humanReadablePrinter()
	}

	if err = printer.PrintObj(obj, os.Stdout); err != nil {
		body, _ := result.Raw()
		glog.Fatalf("Failed to print: %v\nRaw received object:\n%#v\n\nBody received: %v", err, obj, string(body))
	}
	fmt.Print("\n")

	return true
}