func roundTrip(t *testing.T, codec runtime.Codec, item runtime.Object) { //t.Logf("codec: %#v", codec) printer := spew.ConfigState{DisableMethods: true} name := reflect.TypeOf(item).Elem().Name() data, err := runtime.Encode(codec, item) if err != nil { t.Errorf("%v: %v (%s)", name, err, printer.Sprintf("%#v", item)) return } obj2, err := runtime.Decode(codec, data) if err != nil { t.Errorf("0: %v: %v\nCodec: %v\nData: %s\nSource: %#v", name, err, codec, string(data), printer.Sprintf("%#v", item)) return } if !api.Semantic.DeepEqual(item, obj2) { t.Errorf("\n1: %v: diff: %v\nCodec: %v\nSource:\n\n%#v\n\nEncoded:\n\n%s\n\nFinal:\n\n%#v", name, diff.ObjectGoPrintDiff(item, obj2), codec, printer.Sprintf("%#v", item), string(data), printer.Sprintf("%#v", obj2)) return } obj3 := reflect.New(reflect.TypeOf(item).Elem()).Interface().(runtime.Object) if err := runtime.DecodeInto(codec, data, obj3); err != nil { t.Errorf("2: %v: %v", name, err) return } if !api.Semantic.DeepEqual(item, obj3) { t.Errorf("3: %v: diff: %v\nCodec: %v", name, diff.ObjectDiff(item, obj3), codec) return } }
// equivalentImages executes the provided checks against two docker images, returning true // if the images are equivalent, and recording a test suite error in any other condition. func equivalentImages(t *testing.T, c *docker.Client, a, b string, testFilesystem bool, metadataFn metadataFunc, ignoreFns ...ignoreFunc) bool { imageA, err := c.InspectImage(a) if err != nil { t.Errorf("can't get image %q: %v", a, err) return false } imageB, err := c.InspectImage(b) if err != nil { t.Errorf("can't get image %q: %v", b, err) return false } if !metadataFn(imageA.Config, imageB.Config) { t.Errorf("generated image metadata did not match: %s", diff.ObjectDiff(imageA.Config, imageB.Config)) return false } // for mutation commands, check the layer diff if testFilesystem { differs, onlyA, onlyB, err := compareImageFS(c, a, b) if err != nil { t.Errorf("can't calculate FS differences %q: %v", a, err) return false } for k, v := range differs { if ignoreFuncs(ignoreFns).Ignore(v[0], v[1]) { delete(differs, k) continue } t.Errorf("%s %s differs: %s", a, k, diff.ObjectDiff(v[0], v[1])) } for k, v := range onlyA { if ignoreFuncs(ignoreFns).Ignore(v, nil) { delete(onlyA, k) continue } } for k, v := range onlyB { if ignoreFuncs(ignoreFns).Ignore(nil, v) { delete(onlyB, k) continue } } if len(onlyA)+len(onlyB)+len(differs) > 0 { t.Errorf("a=%v b=%v diff=%v", onlyA, onlyB, differs) return false } } return true }
func roundTrip(t *testing.T, codec runtime.Codec, originalItem runtime.Object) { // Make a copy of the originalItem to give to conversion functions // This lets us know if conversion messed with the input object deepCopy, err := kapi.Scheme.DeepCopy(originalItem) if err != nil { t.Errorf("Could not copy object: %v", err) return } item := deepCopy.(runtime.Object) name := reflect.TypeOf(item).Elem().Name() data, err := runtime.Encode(codec, item) if err != nil { if runtime.IsNotRegisteredError(err) { t.Logf("%v is not registered", name) } t.Errorf("%v: %v (%#v)", name, err, item) return } obj2, err := runtime.Decode(codec, data) if err != nil { t.Errorf("0: %v: %v\nCodec: %v\nData: %s\nSource: %#v", name, err, codec, string(data), originalItem) return } if reflect.TypeOf(item) != reflect.TypeOf(obj2) { obj2conv := reflect.New(reflect.TypeOf(item).Elem()).Interface().(runtime.Object) if err := kapi.Scheme.Convert(obj2, obj2conv); err != nil { t.Errorf("0X: no conversion from %v to %v: %v", reflect.TypeOf(item), reflect.TypeOf(obj2), err) return } obj2 = obj2conv } if !kapi.Semantic.DeepEqual(originalItem, obj2) { t.Errorf("1: %v: diff: %v\nCodec: %v\nData: %s\nSource: %s", name, diff.ObjectDiff(originalItem, obj2), codec, string(data), diff.ObjectGoPrintSideBySide(originalItem, obj2)) return } obj3 := reflect.New(reflect.TypeOf(item).Elem()).Interface().(runtime.Object) if err := runtime.DecodeInto(codec, data, obj3); err != nil { t.Errorf("2: %v: %v", name, err) return } if !kapi.Semantic.DeepEqual(originalItem, obj3) { t.Errorf("3: %v: diff: %v\nCodec: %v", name, diff.ObjectDiff(originalItem, obj3), codec) return } }
func TestUpdateStatus(t *testing.T) { storage, statusStorage, server := newStorage(t) defer server.Terminate(t) ctx := api.NewContext() key, _ := storage.KeyFunc(ctx, "foo") key = etcdtest.AddPrefix(key) pvStart := validNewPersistentVolume("foo") err := storage.Storage.Create(ctx, key, pvStart, nil, 0) if err != nil { t.Errorf("unexpected error: %v", err) } pvIn := &api.PersistentVolume{ ObjectMeta: api.ObjectMeta{ Name: "foo", }, Status: api.PersistentVolumeStatus{ Phase: api.VolumeBound, }, } _, _, err = statusStorage.Update(ctx, pvIn) if err != nil { t.Fatalf("Unexpected error: %v", err) } obj, err := storage.Get(ctx, "foo") if err != nil { t.Errorf("unexpected error: %v", err) } pvOut := obj.(*api.PersistentVolume) // only compare the relevant change b/c metadata will differ if !api.Semantic.DeepEqual(pvIn.Status, pvOut.Status) { t.Errorf("unexpected object: %s", diff.ObjectDiff(pvIn.Status, pvOut.Status)) } }
func BenchmarkNodeConversion(b *testing.B) { data, err := ioutil.ReadFile("node_example.json") if err != nil { b.Fatalf("Unexpected error while reading file: %v", err) } var node api.Node if err := runtime.DecodeInto(testapi.Default.Codec(), data, &node); err != nil { b.Fatalf("Unexpected error decoding node: %v", err) } scheme := api.Scheme var result *api.Node b.ResetTimer() for i := 0; i < b.N; i++ { versionedObj, err := scheme.UnsafeConvertToVersion(&node, *testapi.Default.GroupVersion()) if err != nil { b.Fatalf("Conversion error: %v", err) } obj, err := scheme.UnsafeConvertToVersion(versionedObj, testapi.Default.InternalGroupVersion()) if err != nil { b.Fatalf("Conversion error: %v", err) } result = obj.(*api.Node) } b.StopTimer() if !api.Semantic.DeepDerivative(node, *result) { b.Fatalf("Incorrect conversion: %s", diff.ObjectDiff(node, *result)) } }
func verifyEvents(t *testing.T, expected, actual []*PodLifecycleEvent) { sort.Sort(sortableEvents(expected)) sort.Sort(sortableEvents(actual)) if !reflect.DeepEqual(expected, actual) { t.Errorf("Actual events differ from the expected; diff:\n %v", diff.ObjectDiff(expected, actual)) } }
// checkVolumes compares all expectedVolumes with set of volumes at the end of // the test and reports differences. func (r *volumeReactor) checkVolumes(t *testing.T, expectedVolumes []*api.PersistentVolume) error { r.lock.Lock() defer r.lock.Unlock() expectedMap := make(map[string]*api.PersistentVolume) gotMap := make(map[string]*api.PersistentVolume) // Clear any ResourceVersion from both sets for _, v := range expectedVolumes { v.ResourceVersion = "" expectedMap[v.Name] = v } for _, v := range r.volumes { // We must clone the volume because of golang race check - it was // written by the controller without any locks on it. clone, _ := conversion.NewCloner().DeepCopy(v) v = clone.(*api.PersistentVolume) v.ResourceVersion = "" if v.Spec.ClaimRef != nil { v.Spec.ClaimRef.ResourceVersion = "" } gotMap[v.Name] = v } if !reflect.DeepEqual(expectedMap, gotMap) { // Print ugly but useful diff of expected and received objects for // easier debugging. return fmt.Errorf("Volume check failed [A-expected, B-got]: %s", diff.ObjectDiff(expectedMap, gotMap)) } return nil }
func TestEtcdUpdateNotScheduled(t *testing.T) { storage, _, _, server := newStorage(t) defer server.Terminate(t) defer storage.Store.DestroyFunc() ctx := api.NewDefaultContext() key, _ := storage.KeyFunc(ctx, "foo") key = etcdtest.AddPrefix(key) if _, err := storage.Create(ctx, validNewPod()); err != nil { t.Fatalf("unexpected error: %v", err) } podIn := validChangedPod() _, _, err := storage.Update(ctx, podIn.Name, rest.DefaultUpdatedObjectInfo(podIn, api.Scheme)) if err != nil { t.Errorf("Unexpected error: %v", err) } obj, err := storage.Get(ctx, validNewPod().ObjectMeta.Name) if err != nil { t.Errorf("unexpected error: %v", err) } podOut := obj.(*api.Pod) // validChangedPod only changes the Labels, so were checking the update was valid if !api.Semantic.DeepEqual(podIn.Labels, podOut.Labels) { t.Errorf("objects differ: %v", diff.ObjectDiff(podOut, podIn)) } }
func compareJWTs(a, b jose.JWT) string { if a.Encode() == b.Encode() { return "" } var aClaims, bClaims jose.Claims for _, j := range []struct { claims *jose.Claims jwt jose.JWT }{ {&aClaims, a}, {&bClaims, b}, } { var err error *j.claims, err = j.jwt.Claims() if err != nil { *j.claims = jose.Claims(map[string]interface{}{ "msg": "bad claims", "err": err, }) } } return diff.ObjectDiff(aClaims, bClaims) }
// checkClaims compares all expectedClaims with set of claims at the end of the // test and reports differences. func (r *volumeReactor) checkClaims(t *testing.T, expectedClaims []*api.PersistentVolumeClaim) error { r.lock.Lock() defer r.lock.Unlock() expectedMap := make(map[string]*api.PersistentVolumeClaim) gotMap := make(map[string]*api.PersistentVolumeClaim) for _, c := range expectedClaims { c.ResourceVersion = "" expectedMap[c.Name] = c } for _, c := range r.claims { // We must clone the claim because of golang race check - it was // written by the controller without any locks on it. clone, _ := conversion.NewCloner().DeepCopy(c) c = clone.(*api.PersistentVolumeClaim) c.ResourceVersion = "" gotMap[c.Name] = c } if !reflect.DeepEqual(expectedMap, gotMap) { // Print ugly but useful diff of expected and received objects for // easier debugging. return fmt.Errorf("Claim check failed [A-expected, B-got result]: %s", diff.ObjectDiff(expectedMap, gotMap)) } return nil }
func TestScaleGet(t *testing.T) { storage, server := newStorage(t) defer server.Terminate(t) ctx := api.WithNamespace(api.NewContext(), namespace) rc, err := createController(storage.Controller, *validController, t) if err != nil { t.Fatalf("error setting new replication controller %v: %v", *validController, err) } want := &autoscaling.Scale{ ObjectMeta: api.ObjectMeta{ Name: name, Namespace: namespace, UID: rc.UID, ResourceVersion: rc.ResourceVersion, CreationTimestamp: rc.CreationTimestamp, }, Spec: autoscaling.ScaleSpec{ Replicas: validController.Spec.Replicas, }, Status: autoscaling.ScaleStatus{ Replicas: validController.Status.Replicas, Selector: labels.SelectorFromSet(validController.Spec.Template.Labels).String(), }, } obj, err := storage.Scale.Get(ctx, name) if err != nil { t.Fatalf("error fetching scale for %s: %v", name, err) } got := obj.(*autoscaling.Scale) if !api.Semantic.DeepEqual(want, got) { t.Errorf("unexpected scale: %s", diff.ObjectDiff(want, got)) } }
func runTest(t *testing.T, source interface{}) { name := reflect.TypeOf(source).Elem().Name() TestObjectFuzzer.Fuzz(source) _, codec := GetTestScheme() data, err := runtime.Encode(codec, source.(runtime.Object)) if err != nil { t.Errorf("%v: %v (%#v)", name, err, source) return } obj2, err := runtime.Decode(codec, data) if err != nil { t.Errorf("%v: %v (%v)", name, err, string(data)) return } if !semantic.DeepEqual(source, obj2) { t.Errorf("1: %v: diff: %v", name, diff.ObjectGoPrintSideBySide(source, obj2)) return } obj3 := reflect.New(reflect.TypeOf(source).Elem()).Interface() if err := runtime.DecodeInto(codec, data, obj3.(runtime.Object)); err != nil { t.Errorf("2: %v: %v", name, err) return } if !semantic.DeepEqual(source, obj3) { t.Errorf("3: %v: diff: %v", name, diff.ObjectDiff(source, obj3)) return } }
func TestEncode_Ptr(t *testing.T) { grace := int64(30) pod := &api.Pod{ ObjectMeta: api.ObjectMeta{ Labels: map[string]string{"name": "foo"}, }, Spec: api.PodSpec{ RestartPolicy: api.RestartPolicyAlways, DNSPolicy: api.DNSClusterFirst, TerminationGracePeriodSeconds: &grace, SecurityContext: &api.PodSecurityContext{}, }, } obj := runtime.Object(pod) data, err := runtime.Encode(testapi.Default.Codec(), obj) obj2, err2 := runtime.Decode(testapi.Default.Codec(), 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 !api.Semantic.DeepEqual(obj2, pod) { t.Errorf("\nExpected:\n\n %#v,\n\nGot:\n\n %#vDiff: %v\n\n", pod, obj2, diff.ObjectDiff(obj2, pod)) } }
func TestRoundTripVersionedObject(t *testing.T) { d := &newer.DockerImage{ Config: &newer.DockerConfig{ Env: []string{"A=1", "B=2"}, }, } i := &newer.Image{ ObjectMeta: kapi.ObjectMeta{Name: "foo"}, DockerImageMetadata: *d, DockerImageReference: "foo/bar/baz", } data, err := runtime.Encode(kapi.Codecs.LegacyCodec(v1beta3.SchemeGroupVersion), i) if err != nil { t.Fatalf("unexpected error: %v", err) } obj, err := runtime.Decode(kapi.Codecs.UniversalDecoder(), data) if err != nil { t.Fatalf("unexpected error: %v", err) } image := obj.(*newer.Image) if image.DockerImageMetadataVersion != "1.0" { t.Errorf("did not default to correct metadata version: %#v", image) } image.DockerImageMetadataVersion = "" if !reflect.DeepEqual(i, image) { t.Errorf("unable to round trip object: %s", diff.ObjectDiff(i, image)) } }
// needsReconcile compares the given status with the status in the pod manager (which // in fact comes from apiserver), returns whether the status needs to be reconciled with // the apiserver. Now when pod status is inconsistent between apiserver and kubelet, // kubelet should forcibly send an update to reconclie the inconsistence, because kubelet // should be the source of truth of pod status. // NOTE(random-liu): It's simpler to pass in mirror pod uid and get mirror pod by uid, but // now the pod manager only supports getting mirror pod by static pod, so we have to pass // static pod uid here. // TODO(random-liu): Simplify the logic when mirror pod manager is added. func (m *manager) needsReconcile(uid types.UID, status api.PodStatus) bool { // The pod could be a static pod, so we should translate first. pod, ok := m.podManager.GetPodByUID(uid) if !ok { glog.V(4).Infof("Pod %q has been deleted, no need to reconcile", string(uid)) return false } // If the pod is a static pod, we should check its mirror pod, because only status in mirror pod is meaningful to us. if kubepod.IsStaticPod(pod) { mirrorPod, ok := m.podManager.GetMirrorPodByPod(pod) if !ok { glog.V(4).Infof("Static pod %q has no corresponding mirror pod, no need to reconcile", format.Pod(pod)) return false } pod = mirrorPod } podStatus, err := copyStatus(&pod.Status) if err != nil { return false } normalizeStatus(pod, &podStatus) if isStatusEqual(&podStatus, &status) { // If the status from the source is the same with the cached status, // reconcile is not needed. Just return. return false } glog.V(3).Infof("Pod status is inconsistent with cached status for pod %q, a reconciliation should be triggered:\n %+v", format.Pod(pod), diff.ObjectDiff(podStatus, status)) return true }
func compareSignatures(t *testing.T, a, b imageapi.ImageSignature) { aName := a.Name a.ObjectMeta = b.ObjectMeta a.Name = aName if !reflect.DeepEqual(a, b) { t.Errorf("created and contained signatures differ: %v", diff.ObjectDiff(a, b)) } }
func TestLoadRESTClientConfig(t *testing.T) { testData := []byte(` apiVersion: v1 kind: Config clusters: - cluster: certificate-authority: ca-a.crt server: https://cluster-a.com name: cluster-a - cluster: certificate-authority-data: VGVzdA== server: https://cluster-b.com name: cluster-b contexts: - context: cluster: cluster-a namespace: ns-a user: user-a name: context-a - context: cluster: cluster-b namespace: ns-b user: user-b name: context-b current-context: context-b users: - name: user-a user: token: mytoken-a - name: user-b user: token: mytoken-b `) f, err := ioutil.TempFile("", "kubeconfig") if err != nil { t.Fatal(err) } defer os.Remove(f.Name()) ioutil.WriteFile(f.Name(), testData, os.FileMode(0755)) config, err := loadRESTClientConfig(f.Name()) if err != nil { t.Fatal(err) } expectedConfig := &restclient.Config{ Host: "https://cluster-b.com", TLSClientConfig: restclient.TLSClientConfig{ CAData: []byte(`Test`), }, BearerToken: "mytoken-b", } if !reflect.DeepEqual(config, expectedConfig) { t.Errorf("Unexpected config: %s", diff.ObjectDiff(config, expectedConfig)) } }
func TestGetAttrs(t *testing.T) { eventA := &api.Event{ ObjectMeta: api.ObjectMeta{ Name: "f0118", Namespace: "default", }, InvolvedObject: api.ObjectReference{ Kind: "Pod", Name: "foo", Namespace: "baz", UID: "long uid string", APIVersion: testapi.Default.GroupVersion().String(), ResourceVersion: "0", FieldPath: "", }, Reason: "ForTesting", Source: api.EventSource{Component: "test"}, Type: api.EventTypeNormal, } label, field, err := getAttrs(eventA) if err != nil { t.Fatalf("Unexpected error %v", err) } if e, a := label, (labels.Set{}); !reflect.DeepEqual(e, a) { t.Errorf("diff: %s", diff.ObjectDiff(e, a)) } expect := fields.Set{ "metadata.name": "f0118", "metadata.namespace": "default", "involvedObject.kind": "Pod", "involvedObject.name": "foo", "involvedObject.namespace": "baz", "involvedObject.uid": "long uid string", "involvedObject.apiVersion": testapi.Default.GroupVersion().String(), "involvedObject.resourceVersion": "0", "involvedObject.fieldPath": "", "reason": "ForTesting", "source": "test", "type": api.EventTypeNormal, } if e, a := expect, field; !reflect.DeepEqual(e, a) { t.Errorf("diff: %s", diff.ObjectDiff(e, a)) } }
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 kubectltesting.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 = kubectltesting.TestStruct{} s := yamlserializer.NewDecodingSerializer(testapi.Default.Codec()) if err := runtime.DecodeInto(s, buf.Bytes(), &poutput); err != nil { t.Fatal(err) } if !reflect.DeepEqual(testData, poutput) { t.Errorf("Test data and unmarshaled data are not equal: %v", diff.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{} if err := runtime.DecodeInto(s, buf.Bytes(), &objOut); err != nil { t.Fatal(err) } if !reflect.DeepEqual(obj, &objOut) { t.Errorf("Unexpected inequality:\n%v", diff.ObjectDiff(obj, &objOut)) } }
func TestGet_NoError(t *testing.T) { r := NewTestREST(testResponse{result: probe.Success, data: "ok"}) got, err := r.Get(api.NewContext(), "test1") if err != nil { t.Fatalf("Unexpected error: %v", err) } expect := createTestStatus("test1", api.ConditionTrue, "ok", "") if e, a := expect, got; !reflect.DeepEqual(e, a) { t.Errorf("Got unexpected object. Diff: %s", diff.ObjectDiff(e, a)) } }
// TestProjectFidelity makes sure that the project to namespace round trip does not lose any data func TestProjectFidelity(t *testing.T) { f := fuzz.New().NilChance(0) p := &api.Project{} for i := 0; i < 100; i++ { f.Fuzz(p) p.TypeMeta = unversioned.TypeMeta{} // Ignore TypeMeta namespace := ConvertProject(p) p2 := ConvertNamespace(namespace) if !reflect.DeepEqual(p, p2) { t.Errorf("project data not preserved; the diff is %s", diff.ObjectDiff(p, p2)) } } }
// TestNamespaceFidelity makes sure that the namespace to project round trip does not lose any data func TestNamespaceFidelity(t *testing.T) { f := fuzz.New().NilChance(0) n := &kapi.Namespace{} for i := 0; i < 100; i++ { f.Fuzz(n) n.TypeMeta = unversioned.TypeMeta{} // Ignore TypeMeta project := ConvertNamespace(n) n2 := ConvertProject(project) if !reflect.DeepEqual(n, n2) { t.Errorf("namespace data not preserved; the diff is %s", diff.ObjectDiff(n, n2)) } } }
func (t *testPersister) Persist(cfg map[string]string) error { if len(t.persists) == 0 { return errors.New("unexpected persist call") } var persist testPersist persist, t.persists = t.persists[0], t.persists[1:] if !reflect.DeepEqual(persist.cfg, cfg) { return fmt.Errorf("Unexpected cfg: %v", diff.ObjectDiff(persist.cfg, cfg)) } return persist.returnErr }
func TestUpdateStatus(t *testing.T) { storage, status, server := newStorage(t) defer server.Terminate(t) defer storage.Store.DestroyFunc() ctx := api.NewDefaultContext() key, _ := storage.KeyFunc(ctx, "foo") key = etcdtest.AddPrefix(key) resourcequotaStart := validNewResourceQuota() err := storage.Storage.Create(ctx, key, resourcequotaStart, nil, 0) if err != nil { t.Fatalf("Unexpected error: %v", err) } resourcequotaIn := &api.ResourceQuota{ ObjectMeta: api.ObjectMeta{ Name: "foo", Namespace: api.NamespaceDefault, }, Status: api.ResourceQuotaStatus{ Used: api.ResourceList{ api.ResourceCPU: resource.MustParse("1"), api.ResourceMemory: resource.MustParse("1Gi"), api.ResourcePods: resource.MustParse("1"), api.ResourceServices: resource.MustParse("1"), api.ResourceReplicationControllers: resource.MustParse("1"), api.ResourceQuotas: resource.MustParse("1"), }, Hard: api.ResourceList{ api.ResourceCPU: resource.MustParse("100"), api.ResourceMemory: resource.MustParse("4Gi"), api.ResourcePods: resource.MustParse("10"), api.ResourceServices: resource.MustParse("10"), api.ResourceReplicationControllers: resource.MustParse("10"), api.ResourceQuotas: resource.MustParse("1"), }, }, } _, _, err = status.Update(ctx, resourcequotaIn.Name, rest.DefaultUpdatedObjectInfo(resourcequotaIn, api.Scheme)) if err != nil { t.Fatalf("Unexpected error: %v", err) } obj, err := storage.Get(ctx, "foo") rqOut := obj.(*api.ResourceQuota) // only compare the meaningful update b/c we can't compare due to metadata if !api.Semantic.DeepEqual(resourcequotaIn.Status, rqOut.Status) { t.Errorf("unexpected object: %s", diff.ObjectDiff(resourcequotaIn, rqOut)) } }
func TestList_FailedCheck(t *testing.T) { r := NewTestREST(testResponse{result: probe.Failure, data: ""}) got, err := r.List(api.NewContext(), nil) if err != nil { t.Fatalf("Unexpected error: %v", err) } expect := &api.ComponentStatusList{ Items: []api.ComponentStatus{ *(createTestStatus("test1", api.ConditionFalse, "", ""))}, } if e, a := expect, got; !reflect.DeepEqual(e, a) { t.Errorf("Got unexpected object. Diff: %s", diff.ObjectDiff(e, a)) } }
func (test configCommandTest) run(t *testing.T) string { out, actualConfig := testConfigCommand(test.args, test.startingConfig, t) testSetNilMapsToEmpties(reflect.ValueOf(&test.expectedConfig)) testSetNilMapsToEmpties(reflect.ValueOf(&actualConfig)) testClearLocationOfOrigin(&actualConfig) if !api.Semantic.DeepEqual(test.expectedConfig, actualConfig) { t.Errorf("diff: %v", diff.ObjectDiff(test.expectedConfig, actualConfig)) t.Errorf("expected: %#v\n actual: %#v", test.expectedConfig, actualConfig) } test.checkOutput(out, test.expectedOutputs, t) return out }
func TestImageStreamCreate(t *testing.T) { testutil.RequireEtcd(t) defer testutil.DumpEtcdOnFailure(t) _, clusterAdminKubeConfig, err := testserver.StartTestMasterAPI() if err != nil { t.Fatalf("unexpected error: %v", err) } clusterAdminClient, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig) if err != nil { t.Errorf("unexpected error: %v", err) } err = testutil.CreateNamespace(clusterAdminKubeConfig, testutil.Namespace()) if err != nil { t.Errorf("unexpected error: %v", err) } stream := mockImageStream() if _, err := clusterAdminClient.ImageStreams(testutil.Namespace()).Create(&imageapi.ImageStream{}); err == nil || !errors.IsInvalid(err) { t.Fatalf("Unexpected error: %v", err) } expected, err := clusterAdminClient.ImageStreams(testutil.Namespace()).Create(stream) if err != nil { t.Fatalf("Unexpected error: %v", err) } if expected.Name == "" { t.Errorf("Unexpected empty image Name %v", expected) } actual, err := clusterAdminClient.ImageStreams(testutil.Namespace()).Get(stream.Name) if err != nil { t.Fatalf("Unexpected error: %v", err) } if !reflect.DeepEqual(expected, actual) { t.Errorf("unexpected object: %s", diff.ObjectDiff(expected, actual)) } streams, err := clusterAdminClient.ImageStreams(testutil.Namespace()).List(kapi.ListOptions{}) if err != nil { t.Fatalf("Unexpected error %v", err) } if len(streams.Items) != 1 { t.Errorf("Expected one image, got %#v", streams.Items) } }
func TestGetMultipleTypeObjectsWithDirectReference(t *testing.T) { _, svc, _ := testData() node := &api.Node{ ObjectMeta: api.ObjectMeta{ Name: "foo", }, Spec: api.NodeSpec{ ExternalID: "ext", }, } f, tf, codec, ns := NewAPIFactory() tf.Printer = &testPrinter{} tf.Client = &fake.RESTClient{ NegotiatedSerializer: ns, Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { switch req.URL.Path { case "/nodes/foo": return &http.Response{StatusCode: 200, Header: defaultHeader(), Body: objBody(codec, node)}, nil case "/namespaces/test/services/bar": return &http.Response{StatusCode: 200, Header: defaultHeader(), Body: objBody(codec, &svc.Items[0])}, nil default: t.Fatalf("unexpected request: %#v\n%#v", req.URL, req) return nil, nil } }), } tf.Namespace = "test" buf := bytes.NewBuffer([]byte{}) errBuf := bytes.NewBuffer([]byte{}) cmd := NewCmdGet(f, buf, errBuf) cmd.SetOutput(buf) cmd.Run(cmd, []string{"services/bar", "node/foo"}) expected := []runtime.Object{&svc.Items[0], node} actual := tf.Printer.(*testPrinter).Objects if !api.Semantic.DeepEqual(expected, actual) { t.Errorf("unexpected object: %s", diff.ObjectDiff(expected, actual)) } if len(buf.String()) == 0 { t.Errorf("unexpected empty output") } }
func TestConverter_MapElemAddr(t *testing.T) { type Foo struct { A map[int]int } type Bar struct { A map[string]string } c := NewConverter(DefaultNameFunc) c.Debug = testLogger(t) err := c.RegisterConversionFunc( func(in *int, out *string, s Scope) error { *out = fmt.Sprintf("%v", *in) return nil }, ) if err != nil { t.Fatalf("Unexpected error: %v", err) } err = c.RegisterConversionFunc( func(in *string, out *int, s Scope) error { if str, err := strconv.Atoi(*in); err != nil { return err } else { *out = str return nil } }, ) if err != nil { t.Fatalf("Unexpected error: %v", err) } f := fuzz.New().NilChance(0).NumElements(3, 3) first := Foo{} second := Bar{} f.Fuzz(&first) err = c.Convert(&first, &second, AllowDifferentFieldTypeNames, nil) if err != nil { t.Fatalf("Unexpected error: %v", err) } third := Foo{} err = c.Convert(&second, &third, AllowDifferentFieldTypeNames, nil) if e, a := first, third; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected diff: %v", diff.ObjectDiff(e, a)) } }
func TestDoRequestFailed(t *testing.T) { status := &unversioned.Status{ Code: http.StatusNotFound, Status: unversioned.StatusFailure, Reason: unversioned.StatusReasonNotFound, Message: " \"\" not found", Details: &unversioned.StatusDetails{}, } expectedBody, _ := runtime.Encode(testapi.Default.Codec(), status) fakeHandler := utiltesting.FakeHandler{ StatusCode: 404, ResponseBody: string(expectedBody), T: t, } testServer := httptest.NewServer(&fakeHandler) // TODO: Uncomment when fix #19254 // defer testServer.Close() c, err := RESTClientFor(&Config{ Host: testServer.URL, ContentConfig: ContentConfig{ GroupVersion: testapi.Default.GroupVersion(), Codec: testapi.Default.Codec(), }, }) if err != nil { t.Fatalf("unexpected error: %v", err) } body, err := c.Get().Do().Raw() if err == nil || body != nil { t.Errorf("unexpected non-error: %#v", body) } ss, ok := err.(errors.APIStatus) if !ok { t.Errorf("unexpected error type %v", err) } actual := ss.Status() expected := *status // The decoder will apply the default Version and Kind to the Status. expected.APIVersion = "v1" expected.Kind = "Status" if !reflect.DeepEqual(&expected, &actual) { t.Errorf("Unexpected mis-match: %s", diff.ObjectDiff(status, &actual)) } }