本文整理汇总了Golang中k8s/io/kubernetes/pkg/api/testapi.Codec函数的典型用法代码示例。如果您正苦于以下问题:Golang Codec函数的具体用法?Golang Codec怎么用?Golang Codec使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Codec函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestSetWithoutResourceVersioner
func TestSetWithoutResourceVersioner(t *testing.T) {
obj := &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}
fakeClient := tools.NewFakeEtcdClient(t)
helper := newEtcdHelper(fakeClient, testapi.Codec(), etcdtest.PathPrefix())
helper.versioner = nil
returnedObj := &api.Pod{}
err := helper.Set("/some/key", obj, returnedObj, 3)
key := etcdtest.AddPrefix("/some/key")
if err != nil {
t.Errorf("Unexpected error %#v", err)
}
data, err := testapi.Codec().Encode(obj)
if err != nil {
t.Errorf("Unexpected error %#v", err)
}
expect := string(data)
got := fakeClient.Data[key].R.Node.Value
if expect != got {
t.Errorf("Wanted %v, got %v", expect, got)
}
if e, a := uint64(3), fakeClient.LastSetTTL; e != a {
t.Errorf("Wanted %v, got %v", e, a)
}
if obj.ResourceVersion != returnedObj.ResourceVersion || obj.Name != returnedObj.Name {
t.Errorf("If set was successful but returned object did not have correct resource version")
}
}
示例2: makeTestServer
func makeTestServer(t *testing.T, namespace, name string, podResponse, controllerResponse, updateResponse serverResponse) (*httptest.Server, *util.FakeHandler) {
fakePodHandler := util.FakeHandler{
StatusCode: podResponse.statusCode,
ResponseBody: runtime.EncodeOrDie(testapi.Codec(), podResponse.obj.(runtime.Object)),
}
fakeControllerHandler := util.FakeHandler{
StatusCode: controllerResponse.statusCode,
ResponseBody: runtime.EncodeOrDie(testapi.Codec(), controllerResponse.obj.(runtime.Object)),
}
fakeUpdateHandler := util.FakeHandler{
StatusCode: updateResponse.statusCode,
ResponseBody: runtime.EncodeOrDie(testapi.Codec(), updateResponse.obj.(runtime.Object)),
}
mux := http.NewServeMux()
mux.Handle(testapi.ResourcePath("pods", namespace, ""), &fakePodHandler)
mux.Handle(testapi.ResourcePath(replicationControllerResourceName(), "", ""), &fakeControllerHandler)
if namespace != "" {
mux.Handle(testapi.ResourcePath(replicationControllerResourceName(), namespace, ""), &fakeControllerHandler)
}
if name != "" {
mux.Handle(testapi.ResourcePath(replicationControllerResourceName(), namespace, name), &fakeUpdateHandler)
}
mux.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) {
t.Errorf("unexpected request: %v", req.RequestURI)
res.WriteHeader(http.StatusNotFound)
})
return httptest.NewServer(mux), &fakeUpdateHandler
}
示例3: setObjectsForList
func (t *Tester) setObjectsForList(objects []runtime.Object) []runtime.Object {
result := make([]runtime.Object, len(objects))
key := etcdtest.AddPrefix(t.storage.KeyRootFunc(t.tester.TestContext()))
if len(objects) > 0 {
nodes := make([]*etcd.Node, len(objects))
for i, obj := range objects {
encoded := runtime.EncodeOrDie(testapi.Codec(), obj)
decoded, _ := testapi.Codec().Decode([]byte(encoded))
nodes[i] = &etcd.Node{Value: encoded}
result[i] = decoded
}
t.fakeClient.Data[key] = tools.EtcdResponseWithError{
R: &etcd.Response{
Node: &etcd.Node{
Nodes: nodes,
},
},
E: nil,
}
} else {
t.fakeClient.Data[key] = tools.EtcdResponseWithError{
R: &etcd.Response{},
E: t.fakeClient.NewError(tools.EtcdErrorCodeNotFound),
}
}
return result
}
示例4: TestEtcdGet
func TestEtcdGet(t *testing.T) {
ctx := api.NewDefaultContext()
registry, fakeClient, _ := newStorage(t)
autoscaler := validNewHorizontalPodAutoscaler("foo3")
name := autoscaler.Name
key, _ := registry.KeyFunc(ctx, name)
key = etcdtest.AddPrefix(key)
fakeClient.Set(key, runtime.EncodeOrDie(testapi.Codec(), autoscaler), 0)
response, err := fakeClient.Get(key, false, false)
if err != nil {
t.Fatalf("Unexpected error %v", err)
}
var autoscalerOut expapi.HorizontalPodAutoscaler
err = testapi.Codec().DecodeInto([]byte(response.Node.Value), &autoscalerOut)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
obj, err := registry.Get(ctx, name)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
got := obj.(*expapi.HorizontalPodAutoscaler)
autoscaler.ObjectMeta.ResourceVersion = got.ObjectMeta.ResourceVersion
if e, a := autoscaler, got; !api.Semantic.DeepEqual(*e, *a) {
t.Errorf("Unexpected autoscaler: %#v, expected %#v", e, a)
}
}
示例5: TestEtcdUpdateEndpoints
func TestEtcdUpdateEndpoints(t *testing.T) {
ctx := api.NewContext()
storage, fakeClient := newStorage(t)
node := validChangedNode()
key, _ := storage.KeyFunc(ctx, node.Name)
key = etcdtest.AddPrefix(key)
fakeClient.Set(key, runtime.EncodeOrDie(testapi.Codec(), validNewNode()), 0)
_, _, err := storage.Update(ctx, node)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
response, err := fakeClient.Get(key, false, false)
if err != nil {
t.Fatalf("Unexpected error %v", err)
}
var nodeOut api.Node
err = testapi.Codec().DecodeInto([]byte(response.Node.Value), &nodeOut)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
node.ObjectMeta.ResourceVersion = nodeOut.ObjectMeta.ResourceVersion
if !api.Semantic.DeepEqual(node, &nodeOut) {
t.Errorf("Unexpected node: %#v, expected %#v", &nodeOut, node)
}
}
示例6: TestEtcdUpdatePersistentVolumeClaims
func TestEtcdUpdatePersistentVolumeClaims(t *testing.T) {
ctx := api.NewDefaultContext()
storage, _, fakeClient := newStorage(t)
persistentVolume := validChangedPersistentVolumeClaim()
key, _ := storage.KeyFunc(ctx, "foo")
key = etcdtest.AddPrefix(key)
fakeClient.Set(key, runtime.EncodeOrDie(testapi.Codec(), validNewPersistentVolumeClaim("foo", api.NamespaceDefault)), 0)
_, _, err := storage.Update(ctx, persistentVolume)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
response, err := fakeClient.Get(key, false, false)
if err != nil {
t.Fatalf("Unexpected error %v", err)
}
var persistentVolumeOut api.PersistentVolumeClaim
err = testapi.Codec().DecodeInto([]byte(response.Node.Value), &persistentVolumeOut)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
persistentVolume.ObjectMeta.ResourceVersion = persistentVolumeOut.ObjectMeta.ResourceVersion
if !api.Semantic.DeepEqual(persistentVolume, &persistentVolumeOut) {
t.Errorf("Unexpected persistentVolume: %#v, expected %#v", &persistentVolumeOut, persistentVolume)
}
}
示例7: SetObjectsForKey
func SetObjectsForKey(fakeClient *tools.FakeEtcdClient, key string, objects []runtime.Object) []runtime.Object {
result := make([]runtime.Object, len(objects))
if len(objects) > 0 {
nodes := make([]*etcd.Node, len(objects))
for i, obj := range objects {
encoded := runtime.EncodeOrDie(testapi.Codec(), obj)
decoded, _ := testapi.Codec().Decode([]byte(encoded))
nodes[i] = &etcd.Node{Value: encoded}
result[i] = decoded
}
fakeClient.Data[key] = tools.EtcdResponseWithError{
R: &etcd.Response{
Node: &etcd.Node{
Nodes: nodes,
},
},
E: nil,
}
} else {
fakeClient.Data[key] = tools.EtcdResponseWithError{
R: &etcd.Response{},
E: fakeClient.NewError(tools.EtcdErrorCodeNotFound),
}
}
return result
}
示例8: TestEtcdUpdateEndpoints
func TestEtcdUpdateEndpoints(t *testing.T) {
ctx := api.NewDefaultContext()
storage, fakeClient := newStorage(t)
endpoints := validChangedEndpoints()
key, _ := storage.KeyFunc(ctx, "foo")
key = etcdtest.AddPrefix(key)
fakeClient.Set(key, runtime.EncodeOrDie(testapi.Codec(), validNewEndpoints()), 0)
_, _, err := storage.Update(ctx, endpoints)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
response, err := fakeClient.Get(key, false, false)
if err != nil {
t.Fatalf("Unexpected error %v", err)
}
var endpointsOut api.Endpoints
err = testapi.Codec().DecodeInto([]byte(response.Node.Value), &endpointsOut)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
endpoints.ObjectMeta.ResourceVersion = endpointsOut.ObjectMeta.ResourceVersion
if !api.Semantic.DeepEqual(endpoints, &endpointsOut) {
t.Errorf("Unexpected endpoints: %#v, expected %#v", &endpointsOut, endpoints)
}
}
示例9: TestEtcdListServices
func TestEtcdListServices(t *testing.T) {
ctx := api.NewDefaultContext()
fakeClient := tools.NewFakeEtcdClient(t)
registry, rest := NewTestEtcdRegistry(fakeClient)
key := rest.KeyRootFunc(ctx)
key = etcdtest.AddPrefix(key)
fakeClient.Data[key] = tools.EtcdResponseWithError{
R: &etcd.Response{
Node: &etcd.Node{
Nodes: []*etcd.Node{
{
Value: runtime.EncodeOrDie(testapi.Codec(), makeTestService("foo")),
},
{
Value: runtime.EncodeOrDie(testapi.Codec(), makeTestService("bar")),
},
},
},
},
E: nil,
}
services, err := registry.ListServices(ctx, labels.Everything(), fields.Everything())
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if len(services.Items) != 2 || services.Items[0].Name != "foo" || services.Items[1].Name != "bar" {
t.Errorf("Unexpected service list: %#v", services)
}
}
示例10: TestDoRequestNewWayFile
func TestDoRequestNewWayFile(t *testing.T) {
reqObj := &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}
reqBodyExpected, err := testapi.Codec().Encode(reqObj)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
file, err := ioutil.TempFile("", "foo")
if err != nil {
t.Errorf("unexpected error: %v", err)
}
_, err = file.Write(reqBodyExpected)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
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: "user", Password: "pass"})
wasCreated := true
obj, err := c.Verb("POST").
Prefix("foo/bar", "baz").
Timeout(time.Second).
Body(file.Name()).
Do().WasCreated(&wasCreated).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)
}
if wasCreated {
t.Errorf("expected object was not created")
}
tmpStr := string(reqBodyExpected)
requestURL := testapi.ResourcePathWithPrefix("foo/bar/baz", "", "", "")
requestURL += "?timeout=1s"
fakeHandler.ValidateRequest(t, requestURL, "POST", &tmpStr)
if fakeHandler.RequestReceived.Header["Authorization"] == nil {
t.Errorf("Request is missing authorization header: %#v", *fakeHandler.RequestReceived)
}
}
示例11: TestWatch
func TestWatch(t *testing.T) {
client := framework.NewEtcdClient()
etcdStorage := etcd.NewEtcdStorage(client, testapi.Codec(), etcdtest.PathPrefix())
framework.WithEtcdKey(func(key string) {
key = etcdtest.AddPrefix(key)
resp, err := client.Set(key, runtime.EncodeOrDie(testapi.Codec(), &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}), 0)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
expectedVersion := resp.Node.ModifiedIndex
// watch should load the object at the current index
w, err := etcdStorage.Watch(key, 0, storage.Everything)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
event := <-w.ResultChan()
if event.Type != watch.Added || event.Object == nil {
t.Fatalf("expected first value to be set to ADDED, got %#v", event)
}
// version should match what we set
pod := event.Object.(*api.Pod)
if pod.ResourceVersion != strconv.FormatUint(expectedVersion, 10) {
t.Errorf("expected version %d, got %#v", expectedVersion, pod)
}
// should be no events in the stream
select {
case event, ok := <-w.ResultChan():
if !ok {
t.Fatalf("channel closed unexpectedly")
}
t.Fatalf("unexpected object in channel: %#v", event)
default:
}
// should return the previously deleted item in the watch, but with the latest index
resp, err = client.Delete(key, false)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
expectedVersion = resp.Node.ModifiedIndex
event = <-w.ResultChan()
if event.Type != watch.Deleted {
t.Errorf("expected deleted event %#v", event)
}
pod = event.Object.(*api.Pod)
if pod.ResourceVersion != strconv.FormatUint(expectedVersion, 10) {
t.Errorf("expected version %d, got %#v", expectedVersion, pod)
}
})
}
示例12: TestDecoder
func TestDecoder(t *testing.T) {
table := []watch.EventType{watch.Added, watch.Deleted, watch.Modified, watch.Error}
for _, eventType := range table {
out, in := io.Pipe()
decoder := NewDecoder(out, testapi.Codec())
expect := &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}
encoder := json.NewEncoder(in)
go func() {
data, err := testapi.Codec().Encode(expect)
if err != nil {
t.Fatalf("Unexpected error %v", err)
}
if err := encoder.Encode(&WatchEvent{eventType, runtime.RawExtension{RawJSON: json.RawMessage(data)}}); err != nil {
t.Errorf("Unexpected error %v", err)
}
in.Close()
}()
done := make(chan struct{})
go func() {
action, got, err := decoder.Decode()
if err != nil {
t.Fatalf("Unexpected error %v", err)
}
if e, a := eventType, action; e != a {
t.Errorf("Expected %v, got %v", e, a)
}
if e, a := expect, got; !api.Semantic.DeepDerivative(e, a) {
t.Errorf("Expected %v, got %v", e, a)
}
t.Logf("Exited read")
close(done)
}()
<-done
done = make(chan struct{})
go func() {
_, _, err := decoder.Decode()
if err == nil {
t.Errorf("Unexpected nil error")
}
close(done)
}()
<-done
decoder.Close()
}
}
示例13: TestDeleteNamespace
func TestDeleteNamespace(t *testing.T) {
storage, fakeClient := newStorage(t)
fakeClient.ChangeIndex = 1
ctx := api.NewContext()
key, err := storage.Etcd.KeyFunc(ctx, "foo")
key = etcdtest.AddPrefix(key)
fakeClient.Data[key] = tools.EtcdResponseWithError{
R: &etcd.Response{
Node: &etcd.Node{
Value: runtime.EncodeOrDie(testapi.Codec(), &api.Namespace{
ObjectMeta: api.ObjectMeta{
Name: "foo",
},
Status: api.NamespaceStatus{Phase: api.NamespaceActive},
}),
ModifiedIndex: 1,
CreatedIndex: 1,
},
},
}
_, err = storage.Delete(api.NewContext(), "foo", nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
示例14: TestDelete
func TestDelete(t *testing.T) {
ctx := api.NewDefaultContext()
storage, fakeEtcdClient, _ := newStorage(t)
test := resttest.New(t, storage, fakeEtcdClient.SetError)
rsrc := validNewThirdPartyResource("foo2")
key, _ := storage.KeyFunc(ctx, "foo2")
key = etcdtest.AddPrefix(key)
createFn := func() runtime.Object {
fakeEtcdClient.Data[key] = tools.EtcdResponseWithError{
R: &etcd.Response{
Node: &etcd.Node{
Value: runtime.EncodeOrDie(testapi.Codec(), rsrc),
ModifiedIndex: 1,
},
},
}
return rsrc
}
gracefulSetFn := func() bool {
if fakeEtcdClient.Data[key].R.Node == nil {
return false
}
return fakeEtcdClient.Data[key].R.Node.TTL == 30
}
test.TestDeleteNoGraceful(createFn, gracefulSetFn)
}
示例15: newStorage
func newStorage(t *testing.T) (*REST, *tools.FakeEtcdClient, storage.Interface) {
fakeEtcdClient := tools.NewFakeEtcdClient(t)
fakeEtcdClient.TestIndex = true
etcdStorage := etcdstorage.NewEtcdStorage(fakeEtcdClient, testapi.Codec(), etcdtest.PathPrefix())
storage := NewREST(etcdStorage)
return storage, fakeEtcdClient, etcdStorage
}