本文整理汇总了Golang中github.com/qingyuancloud/QingYuan/pkg/api/testapi.Codec函数的典型用法代码示例。如果您正苦于以下问题:Golang Codec函数的具体用法?Golang Codec怎么用?Golang Codec使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Codec函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: 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
}
示例2: TestSetObjWithoutResourceVersioner
func TestSetObjWithoutResourceVersioner(t *testing.T) {
obj := &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}
fakeClient := NewFakeEtcdClient(t)
helper := NewEtcdHelper(fakeClient, testapi.Codec(), etcdtest.PathPrefix())
helper.Versioner = nil
returnedObj := &api.Pod{}
err := helper.SetObj("/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")
}
}
示例3: 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)
}
}
示例4: TestWatch
func TestWatch(t *testing.T) {
client := framework.NewEtcdClient()
helper := tools.NewEtcdHelper(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 := helper.Watch(key, 0, tools.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)
}
})
}
示例5: 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{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()
}
}
示例6: NewTestEventEtcdRegistry
func NewTestEventEtcdRegistry(t *testing.T) (*tools.FakeEtcdClient, generic.Registry) {
f := tools.NewFakeEtcdClient(t)
f.TestIndex = true
h := tools.NewEtcdHelper(f, testapi.Codec(), etcdtest.PathPrefix())
return f, NewEtcdRegistry(h, testTTL)
}
示例7: TestDoRequestBearer
func TestDoRequestBearer(t *testing.T) {
status := &api.Status{Status: api.StatusFailure}
expectedBody, _ := latest.Codec.Encode(status)
fakeHandler := util.FakeHandler{
StatusCode: 400,
ResponseBody: string(expectedBody),
T: t,
}
testServer := httptest.NewServer(&fakeHandler)
defer testServer.Close()
request, _ := http.NewRequest("GET", testServer.URL, nil)
c, err := RESTClientFor(&Config{
Host: testServer.URL,
Version: testapi.Version(),
Codec: testapi.Codec(),
BearerToken: "test",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
err = c.Get().Do().Error()
if err == nil {
t.Fatalf("unexpected non-error: %v", err)
}
if fakeHandler.RequestReceived.Header.Get("Authorization") != "Bearer test" {
t.Errorf("Request is missing authorization header: %#v", *request)
}
}
示例8: TestValidateOk
func TestValidateOk(t *testing.T) {
schema, err := loadSchemaForTest()
if err != nil {
t.Errorf("Failed to load: %v", err)
}
tests := []struct {
obj runtime.Object
typeName string
}{
{obj: &api.Pod{}},
{obj: &api.Service{}},
{obj: &api.ReplicationController{}},
}
seed := rand.Int63()
apiObjectFuzzer := apitesting.FuzzerFor(nil, "", rand.NewSource(seed))
for i := 0; i < 5; i++ {
for _, test := range tests {
testObj := test.obj
apiObjectFuzzer.Fuzz(testObj)
data, err := testapi.Codec().Encode(testObj)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
err = schema.ValidateBytes(data)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
}
}
}
示例9: TestSetsCodec
func TestSetsCodec(t *testing.T) {
testCases := map[string]struct {
Err bool
Prefix string
Codec runtime.Codec
}{
testapi.Version(): {false, "/api/" + testapi.Version() + "/", testapi.Codec()},
"invalidVersion": {true, "", nil},
}
for version, expected := range testCases {
client, err := New(&Config{Host: "127.0.0.1", Version: version})
switch {
case err == nil && expected.Err:
t.Errorf("expected error but was nil")
continue
case err != nil && !expected.Err:
t.Errorf("unexpected error %v", err)
continue
case err != nil:
continue
}
if e, a := expected.Prefix, client.RESTClient.baseURL.Path; e != a {
t.Errorf("expected %#v, got %#v", e, a)
}
if e, a := expected.Codec, client.RESTClient.Codec; e != a {
t.Errorf("expected %#v, got %#v", e, a)
}
}
}
示例10: body
func body(obj runtime.Object, raw *string) *string {
if obj != nil {
bs, _ := testapi.Codec().Encode(obj)
body := string(bs)
return &body
}
return raw
}
示例11: TestEtcdDelete
func TestEtcdDelete(t *testing.T) {
podA := &api.Pod{
ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "1"},
Spec: api.PodSpec{NodeName: "machine"},
}
nodeWithPodA := tools.EtcdResponseWithError{
R: &etcd.Response{
Node: &etcd.Node{
Value: runtime.EncodeOrDie(testapi.Codec(), podA),
ModifiedIndex: 1,
CreatedIndex: 1,
},
},
E: nil,
}
emptyNode := tools.EtcdResponseWithError{
R: &etcd.Response{},
E: tools.EtcdErrorNotFound,
}
key := "foo"
table := map[string]struct {
existing tools.EtcdResponseWithError
expect tools.EtcdResponseWithError
errOK func(error) bool
}{
"normal": {
existing: nodeWithPodA,
expect: emptyNode,
errOK: func(err error) bool { return err == nil },
},
"notExisting": {
existing: emptyNode,
expect: emptyNode,
errOK: func(err error) bool { return errors.IsNotFound(err) },
},
}
for name, item := range table {
fakeClient, registry := NewTestGenericEtcdRegistry(t)
path := etcdtest.AddPrefix("pods/foo")
fakeClient.Data[path] = item.existing
obj, err := registry.Delete(api.NewContext(), key, nil)
if !item.errOK(err) {
t.Errorf("%v: unexpected error: %v (%#v)", name, err, obj)
}
if item.expect.E != nil {
item.expect.E.(*etcd.EtcdError).Index = fakeClient.ChangeIndex
}
if e, a := item.expect, fakeClient.Data[path]; !api.Semantic.DeepDerivative(e, a) {
t.Errorf("%v:\n%s", name, util.ObjectDiff(e, a))
}
}
}
示例12: TestEncodeDecodeRoundTrip
func TestEncodeDecodeRoundTrip(t *testing.T) {
testCases := []struct {
Type watch.EventType
Object runtime.Object
Codec runtime.Codec
}{
{
watch.Added,
&api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}},
testapi.Codec(),
},
{
watch.Modified,
&api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}},
testapi.Codec(),
},
{
watch.Deleted,
&api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}},
testapi.Codec(),
},
}
for i, testCase := range testCases {
buf := &bytes.Buffer{}
encoder := NewEncoder(buf, testCase.Codec)
if err := encoder.Encode(&watch.Event{Type: testCase.Type, Object: testCase.Object}); err != nil {
t.Errorf("%d: unexpected error: %v", i, err)
continue
}
decoder := NewDecoder(ioutil.NopCloser(buf), testCase.Codec)
event, obj, err := decoder.Decode()
if err != nil {
t.Errorf("%d: unexpected error: %v", i, err)
continue
}
if !api.Semantic.DeepDerivative(testCase.Object, obj) {
t.Errorf("%d: expected %#v, got %#v", i, testCase.Object, obj)
}
if event != testCase.Type {
t.Errorf("%d: unexpected type: %#v", i, event)
}
}
}
示例13: TestCreateObjNilOutParam
func TestCreateObjNilOutParam(t *testing.T) {
obj := &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}
fakeClient := NewFakeEtcdClient(t)
helper := NewEtcdHelper(fakeClient, testapi.Codec(), etcdtest.PathPrefix())
err := helper.CreateObj("/some/key", obj, nil, 5)
if err != nil {
t.Errorf("Unexpected error %#v", err)
}
}
示例14: testPrinter
func testPrinter(t *testing.T, printer ResourcePrinter, unmarshalFunc func(data []byte, v interface{}) error) {
buf := bytes.NewBuffer([]byte{})
err := printer.PrintObj(&testData, buf)
if err != nil {
t.Fatal(err)
}
var poutput testStruct
// Verify that given function runs without error.
err = unmarshalFunc(buf.Bytes(), &poutput)
if err != nil {
t.Fatal(err)
}
// Use real decode function to undo the versioning process.
poutput = testStruct{}
err = runtime.YAMLDecoder(testapi.Codec()).DecodeInto(buf.Bytes(), &poutput)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(testData, poutput) {
t.Errorf("Test data and unmarshaled data are not equal: %v", util.ObjectDiff(poutput, testData))
}
obj := &api.Pod{
ObjectMeta: api.ObjectMeta{Name: "foo"},
}
buf.Reset()
printer.PrintObj(obj, buf)
var objOut api.Pod
// Verify that given function runs without error.
err = unmarshalFunc(buf.Bytes(), &objOut)
if err != nil {
t.Fatalf("unexpected error: %#v", err)
}
// Use real decode function to undo the versioning process.
objOut = api.Pod{}
err = runtime.YAMLDecoder(testapi.Codec()).DecodeInto(buf.Bytes(), &objOut)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(obj, &objOut) {
t.Errorf("Unexpected inequality:\n%v", util.ObjectDiff(obj, &objOut))
}
}
示例15: TestMigrateKeys
func TestMigrateKeys(t *testing.T) {
withEtcdKey(func(oldPrefix string) {
client := newEtcdClient()
helper := tools.NewEtcdHelper(client, testapi.Codec(), oldPrefix)
key1 := oldPrefix + "/obj1"
key2 := oldPrefix + "/foo/obj2"
key3 := oldPrefix + "/foo/bar/obj3"
// Create a new entres - these are the 'existing' entries with old prefix
_, _ = helper.Client.Create(key1, "foo", 0)
_, _ = helper.Client.Create(key2, "foo", 0)
_, _ = helper.Client.Create(key3, "foo", 0)
// Change the helper to a new prefix
newPrefix := "/qingyuan"
helper = tools.NewEtcdHelper(client, testapi.Codec(), newPrefix)
// Migrate the keys
err := helper.MigrateKeys(oldPrefix)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
// Check the resources are at the correct new location
newNames := []string{
newPrefix + "/obj1",
newPrefix + "/foo/obj2",
newPrefix + "/foo/bar/obj3",
}
for _, name := range newNames {
_, err := helper.Client.Get(name, false, false)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
}
// Check the old locations are removed
if _, err := helper.Client.Get(oldPrefix, false, false); err == nil {
t.Fatalf("Old directory still exists.")
}
})
}