func TestCreateSetsFields(t *testing.T) { fakeEtcdClient, etcdStorage := newEtcdStorage(t) storage, _, _ := NewStorage(etcdStorage) namespace := validNewNamespace() _, err := storage.Create(api.NewContext(), namespace) if err != fakeEtcdClient.Err { t.Fatalf("unexpected error: %v", err) } actual := &api.Namespace{} ctx := api.NewContext() key, err := storage.Etcd.KeyFunc(ctx, "foo") if err != nil { t.Fatalf("unexpected key error: %v", err) } if err := etcdStorage.Get(key, actual, false); err != nil { t.Fatalf("unexpected extraction error: %v", err) } if actual.Name != namespace.Name { t.Errorf("unexpected namespace: %#v", actual) } if len(actual.UID) == 0 { t.Errorf("expected namespace UID to be set: %#v", actual) } if actual.Status.Phase != api.NamespaceActive { t.Errorf("expected namespace phase to be set to active, but %v", actual.Status.Phase) } }
// TestValidNamespace validates that namespace rules are enforced on a resource prior to create or update func TestValidNamespace(t *testing.T) { ctx := api.NewDefaultContext() namespace, _ := api.NamespaceFrom(ctx) resource := api.ReplicationController{} if !api.ValidNamespace(ctx, &resource.ObjectMeta) { t.Errorf("expected success") } if namespace != resource.Namespace { t.Errorf("expected resource to have the default namespace assigned during validation") } resource = api.ReplicationController{ObjectMeta: api.ObjectMeta{Namespace: "other"}} if api.ValidNamespace(ctx, &resource.ObjectMeta) { t.Errorf("Expected error that resource and context errors do not match because resource has different namespace") } ctx = api.NewContext() if api.ValidNamespace(ctx, &resource.ObjectMeta) { t.Errorf("Expected error that resource and context errors do not match since context has no namespace") } ctx = api.NewContext() ns := api.NamespaceValue(ctx) if ns != "" { t.Errorf("Expected the empty string") } }
func TestListEmptyResourceQuotaList(t *testing.T) { fakeEtcdClient, etcdStorage := newEtcdStorage(t) fakeEtcdClient.ChangeIndex = 1 storage, _ := NewStorage(etcdStorage) ctx := api.NewContext() key := storage.Etcd.KeyRootFunc(ctx) key = etcdtest.AddPrefix(key) fakeEtcdClient.Data[key] = tools.EtcdResponseWithError{ R: &etcd.Response{}, E: fakeEtcdClient.NewError(tools.EtcdErrorCodeNotFound), } resourcequotas, err := storage.List(api.NewContext(), labels.Everything(), fields.Everything()) if err != nil { t.Fatalf("unexpected error: %v", err) } if len(resourcequotas.(*api.ResourceQuotaList).Items) != 0 { t.Errorf("Unexpected non-zero resourcequota list: %#v", resourcequotas) } if resourcequotas.(*api.ResourceQuotaList).ResourceVersion != "1" { t.Errorf("Unexpected resource version: %#v", resourcequotas) } }
func TestDeleteNamespace(t *testing.T) { fakeEtcdClient, etcdStorage := newEtcdStorage(t) fakeEtcdClient.ChangeIndex = 1 storage, _, _ := NewStorage(etcdStorage) ctx := api.NewContext() key, err := storage.Etcd.KeyFunc(ctx, "foo") key = etcdtest.AddPrefix(key) fakeEtcdClient.Data[key] = tools.EtcdResponseWithError{ R: &etcd.Response{ Node: &etcd.Node{ Value: runtime.EncodeOrDie(latest.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) } }
func TestGet(t *testing.T) { expect := validNewNamespace() expect.Status.Phase = api.NamespaceActive storage, fakeEtcdClient, _ := newStorage(t) ctx := api.NewContext() key, err := storage.Etcd.KeyFunc(ctx, "foo") key = etcdtest.AddPrefix(key) if err != nil { t.Fatalf("unexpected key error: %v", err) } fakeEtcdClient.Data[key] = tools.EtcdResponseWithError{ R: &etcd.Response{ Node: &etcd.Node{ Value: runtime.EncodeOrDie(latest.Codec, expect), }, }, } obj, err := storage.Get(api.NewContext(), "foo") namespace := obj.(*api.Namespace) if err != nil { t.Fatalf("unexpected error: %v", err) } expect.Status.Phase = api.NamespaceActive if e, a := expect, namespace; !api.Semantic.DeepEqual(e, a) { t.Errorf("Unexpected namespace: %s", util.ObjectDiff(e, a)) } }
func TestVerbRestrictionsWork(t *testing.T) { test1 := &authorizeTest{ context: kapi.WithUser(kapi.WithNamespace(kapi.NewContext(), "adze"), &user.DefaultInfo{Name: "Valerie"}), attributes: &DefaultAuthorizationAttributes{ Verb: "get", Resource: "buildConfigs", }, expectedAllowed: true, expectedReason: "allowed by rule in adze", } test1.clusterPolicies = newDefaultClusterPolicies() test1.policies = newAdzePolicies() test1.clusterBindings = newDefaultClusterPolicyBindings() test1.bindings = newAdzeBindings() test1.test(t) test2 := &authorizeTest{ context: kapi.WithUser(kapi.WithNamespace(kapi.NewContext(), "adze"), &user.DefaultInfo{Name: "Valerie"}), attributes: &DefaultAuthorizationAttributes{ Verb: "create", Resource: "buildConfigs", }, expectedAllowed: false, expectedReason: `User "Valerie" cannot create buildConfigs in project "adze"`, } test2.clusterPolicies = newDefaultClusterPolicies() test2.policies = newAdzePolicies() test2.clusterBindings = newDefaultClusterPolicyBindings() test2.bindings = newAdzeBindings() test2.test(t) }
func TestResourceRestrictionsWithWeirdWork(t *testing.T) { test1 := &authorizeTest{ context: kapi.WithUser(kapi.WithNamespace(kapi.NewContext(), "adze"), &user.DefaultInfo{Name: "Rachel"}), attributes: &DefaultAuthorizationAttributes{ Verb: "get", Resource: "BUILDCONFIGS", }, expectedAllowed: true, expectedReason: "allowed by rule in adze", } test1.clusterPolicies = newDefaultClusterPolicies() test1.policies = newAdzePolicies() test1.clusterBindings = newDefaultClusterPolicyBindings() test1.bindings = newAdzeBindings() test1.test(t) test2 := &authorizeTest{ context: kapi.WithUser(kapi.WithNamespace(kapi.NewContext(), "adze"), &user.DefaultInfo{Name: "Rachel"}), attributes: &DefaultAuthorizationAttributes{ Verb: "get", Resource: "buildconfigs", }, expectedAllowed: true, expectedReason: "allowed by rule in adze", } test2.clusterPolicies = newDefaultClusterPolicies() test2.policies = newAdzePolicies() test2.clusterBindings = newDefaultClusterPolicyBindings() test2.bindings = newAdzeBindings() test2.test(t) }
func TestEtcdListRoutesInDifferentNamespaces(t *testing.T) { fakeClient := tools.NewFakeEtcdClient(t) namespaceAlfa := kapi.WithNamespace(kapi.NewContext(), "alfa") namespaceBravo := kapi.WithNamespace(kapi.NewContext(), "bravo") fakeClient.Data["/routes/alfa"] = tools.EtcdResponseWithError{ R: &etcd.Response{ Node: &etcd.Node{ Nodes: []*etcd.Node{ { Value: runtime.EncodeOrDie(latest.Codec, &api.Route{ObjectMeta: kapi.ObjectMeta{Name: "foo1"}}), }, }, }, }, E: nil, } fakeClient.Data["/routes/bravo"] = tools.EtcdResponseWithError{ R: &etcd.Response{ Node: &etcd.Node{ Nodes: []*etcd.Node{ { Value: runtime.EncodeOrDie(latest.Codec, &api.Route{ObjectMeta: kapi.ObjectMeta{Name: "foo2"}}), }, { Value: runtime.EncodeOrDie(latest.Codec, &api.Route{ObjectMeta: kapi.ObjectMeta{Name: "bar2"}}), }, }, }, }, E: nil, } registry := NewTestEtcd(fakeClient) routesAlfa, err := registry.ListRoutes(namespaceAlfa, labels.Everything()) if err != nil { t.Errorf("unexpected error: %v", err) } if len(routesAlfa.Items) != 1 || routesAlfa.Items[0].Name != "foo1" { t.Errorf("Unexpected builds list: %#v", routesAlfa) } routesBravo, err := registry.ListRoutes(namespaceBravo, labels.Everything()) if err != nil { t.Errorf("unexpected error: %v", err) } if len(routesBravo.Items) != 2 || routesBravo.Items[0].Name != "foo2" || routesBravo.Items[1].Name != "bar2" { t.Errorf("Unexpected builds list: %#v", routesBravo) } }
func TestGetEndpointsMissingService(t *testing.T) { registry := ®istrytest.ServiceRegistry{ Err: errors.NewNotFound("service", "foo"), } storage := NewREST(registry) ctx := api.NewContext() // returns service not found _, err := storage.Get(ctx, "foo") if !errors.IsNotFound(err) || !reflect.DeepEqual(err, errors.NewNotFound("service", "foo")) { t.Errorf("expected NotFound error, got %#v", err) } // returns empty endpoints registry.Err = nil registry.Service = &api.Service{ ObjectMeta: api.ObjectMeta{Name: "foo"}, } obj, err := storage.Get(ctx, "foo") if err != nil { t.Fatalf("unexpected error: %v", err) } if obj.(*api.Endpoints).Endpoints != nil { t.Errorf("unexpected endpoints: %#v", obj) } }
func TestGet(t *testing.T) { expect := validNewPod() expect.Status.Phase = api.PodRunning expect.Spec.NodeName = "machine" fakeEtcdClient, etcdStorage := newEtcdStorage(t) key := etcdtest.AddPrefix("/pods/test/foo") fakeEtcdClient.Data[key] = tools.EtcdResponseWithError{ R: &etcd.Response{ Node: &etcd.Node{ Value: runtime.EncodeOrDie(latest.Codec, expect), }, }, } storage := NewStorage(etcdStorage, nil).Pod obj, err := storage.Get(api.WithNamespace(api.NewContext(), "test"), "foo") pod := obj.(*api.Pod) if err != nil { t.Fatalf("unexpected error: %v", err) } if e, a := expect, pod; !api.Semantic.DeepEqual(e, a) { t.Errorf("Unexpected pod: %s", util.ObjectDiff(e, a)) } }
func NewReadOnlyClusterPolicyCache(registry clusterpolicyregistry.WatchingRegistry) readOnlyClusterPolicyCache { ctx := kapi.WithNamespace(kapi.NewContext(), kapi.NamespaceAll) indexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{"namespace": cache.MetaNamespaceIndexFunc}) reflector := cache.NewReflector( &cache.ListWatch{ ListFunc: func() (runtime.Object, error) { return registry.ListClusterPolicies(ctx, labels.Everything(), fields.Everything()) }, WatchFunc: func(resourceVersion string) (watch.Interface, error) { return registry.WatchClusterPolicies(ctx, labels.Everything(), fields.Everything(), resourceVersion) }, }, &authorizationapi.ClusterPolicy{}, indexer, 2*time.Minute, ) return readOnlyClusterPolicyCache{ registry: registry, indexer: indexer, reflector: *reflector, keyFunc: cache.MetaNamespaceKeyFunc, } }
func TestListPodsCacheError(t *testing.T) { podRegistry := registrytest.NewPodRegistry(nil) podRegistry.Pods = &api.PodList{ Items: []api.Pod{ { ObjectMeta: api.ObjectMeta{ Name: "foo", }, }, }, } storage := REST{ registry: podRegistry, podCache: &fakeCache{errorToReturn: client.ErrPodInfoNotAvailable}, } ctx := api.NewContext() pods, err := storage.List(ctx, labels.Everything(), labels.Everything()) if err != nil { t.Fatalf("Expected no error, got %#v", err) } pl := pods.(*api.PodList) if len(pl.Items) != 1 { t.Fatalf("Unexpected 0-len pod list: %+v", pl) } if e, a := api.PodUnknown, pl.Items[0].Status.Phase; e != a { t.Errorf("Expected %v, got %v", e, a) } }
func TestUpdateCannotChangeRoleRefError(t *testing.T) { ctx := kapi.WithUser(kapi.WithNamespace(kapi.NewContext(), "unittest"), &user.DefaultInfo{Name: "system:admin"}) storage := makeTestStorage() obj, err := storage.Create(ctx, &authorizationapi.RoleBinding{ ObjectMeta: kapi.ObjectMeta{Name: "my-different"}, RoleRef: kapi.ObjectReference{Name: "admin"}, }) if err != nil { t.Errorf("unexpected error: %v", err) return } original := obj.(*authorizationapi.RoleBinding) roleBinding := &authorizationapi.RoleBinding{ ObjectMeta: kapi.ObjectMeta{Name: "my-different", ResourceVersion: original.ResourceVersion}, RoleRef: kapi.ObjectReference{Name: "cluster-admin"}, } _, _, err = storage.Update(ctx, roleBinding) if err == nil { t.Errorf("Missing expected error") return } expectedErr := "cannot change roleRef" if !strings.Contains(err.Error(), expectedErr) { t.Errorf("Expected %v, got %v", expectedErr, err.Error()) } }
// TestGetClusterPolicy tests that a ReadOnlyPolicyClient GetPolicy() call correctly retrieves a cluster policy // when the namespace given is equal to the empty string func TestGetClusterPolicy(t *testing.T) { testClient, policyStopChannel, bindingStopChannel, testChannel := beforeTestingSetup_readonlycache() defer close(policyStopChannel) defer close(bindingStopChannel) var clusterPolicy *authorizationapi.Policy var err error namespace := "" context := kapi.WithNamespace(kapi.NewContext(), namespace) name := "uniqueClusterPolicyName" util.Until(func() { clusterPolicy, err = testClient.GetPolicy(context, name) if (err == nil) && (clusterPolicy != nil) && (clusterPolicy.Name == name) && (clusterPolicy.Namespace == namespace) { close(testChannel) } }, 1*time.Millisecond, testChannel) switch { case err != nil: t.Errorf("Error getting cluster policy using GetPolicy(): %v", err) case clusterPolicy == nil: t.Error("Policy is nil") case clusterPolicy.Name != name: t.Errorf("Expected policy.Name to be '%s', but got '%s'", name, clusterPolicy.Name) case clusterPolicy.Namespace != "": t.Errorf("Expected policy.Namespace to be '%s', but got '%s'", namespace, clusterPolicy.Namespace) } }
func TestEtcdListPersistentVolumes(t *testing.T) { ctx := api.NewContext() storage, _, fakeClient, _ := newStorage(t) key := storage.KeyRootFunc(ctx) key = etcdtest.AddPrefix(key) fakeClient.Data[key] = tools.EtcdResponseWithError{ R: &etcd.Response{ Node: &etcd.Node{ Nodes: []*etcd.Node{ { Value: runtime.EncodeOrDie(latest.Codec, validNewPersistentVolume("foo")), }, { Value: runtime.EncodeOrDie(latest.Codec, validNewPersistentVolume("bar")), }, }, }, }, E: nil, } pvObj, err := storage.List(ctx, labels.Everything(), fields.Everything()) if err != nil { t.Errorf("unexpected error: %v", err) } pvs := pvObj.(*api.PersistentVolumeList) if len(pvs.Items) != 2 || pvs.Items[0].Name != "foo" || pvs.Items[1].Name != "bar" { t.Errorf("Unexpected persistentVolume list: %#v", pvs) } }
func TestAllowedWithMissingBinding(t *testing.T) { test := &authorizeTest{ context: kapi.WithUser(kapi.WithNamespace(kapi.NewContext(), "adze"), &user.DefaultInfo{Name: "Anna"}), attributes: &DefaultAuthorizationAttributes{ Verb: "update", Resource: "roles", }, expectedAllowed: true, expectedReason: "allowed by rule in adze", } test.clusterPolicies = newDefaultClusterPolicies() test.policies = append(test.policies, newAdzePolicies()...) test.clusterBindings = newDefaultClusterPolicyBindings() test.bindings = append(test.bindings, newAdzeBindings()...) test.bindings[0].RoleBindings["missing"] = &authorizationapi.RoleBinding{ ObjectMeta: kapi.ObjectMeta{ Name: "missing", }, RoleRef: kapi.ObjectReference{ Name: "not-a-real-binding", }, Users: util.NewStringSet("Anna"), } test.test(t) }
func TestDeniedWithError(t *testing.T) { test := &authorizeTest{ context: kapi.WithUser(kapi.WithNamespace(kapi.NewContext(), "adze"), &user.DefaultInfo{Name: "Anna"}), attributes: &DefaultAuthorizationAttributes{ Verb: "update", Resource: "roles", }, expectedAllowed: false, expectedError: "my special error", } test.clusterPolicies = newDefaultClusterPolicies() test.policies = append(test.policies, newAdzePolicies()...) test.clusterBindings = newDefaultClusterPolicyBindings() test.bindings = append(test.bindings, newAdzeBindings()...) test.bindings[0].RoleBindings["missing"] = &authorizationapi.RoleBinding{ ObjectMeta: kapi.ObjectMeta{ Name: "missing", }, RoleRef: kapi.ObjectReference{ Name: "not-a-real-binding", }, Users: util.NewStringSet("Anna"), } test.policyRetrievalError = errors.New("my special error") test.test(t) }
func TestUpdateImageStreamConflictingNamespace(t *testing.T) { fakeEtcdClient, helper := newHelper(t) fakeEtcdClient.Data["/imagestreams/legal-name/bar"] = tools.EtcdResponseWithError{ R: &etcd.Response{ Node: &etcd.Node{ Value: runtime.EncodeOrDie(latest.Codec, &api.ImageStream{ ObjectMeta: kapi.ObjectMeta{Name: "bar", Namespace: "default"}, }), ModifiedIndex: 2, }, }, } storage, _ := NewREST(helper, noDefaultRegistry, &fakeSubjectAccessReviewRegistry{}) ctx := kapi.WithUser(kapi.WithNamespace(kapi.NewContext(), "legal-name"), &fakeUser{}) obj, created, err := storage.Update(ctx, &api.ImageStream{ ObjectMeta: kapi.ObjectMeta{Name: "bar", Namespace: "some-value", ResourceVersion: "2"}, }) if obj != nil || created { t.Error("Expected a nil obj, but we got a value") } checkExpectedNamespaceError(t, err) }
func TestGetPod(t *testing.T) { podRegistry := registrytest.NewPodRegistry(nil) podRegistry.Pod = &api.Pod{ ObjectMeta: api.ObjectMeta{Name: "foo"}, Status: api.PodStatus{Host: "machine"}, } storage := REST{ registry: podRegistry, podCache: &fakeCache{statusToReturn: &api.PodStatus{Phase: api.PodRunning}}, } ctx := api.NewContext() obj, err := storage.Get(ctx, "foo") pod := obj.(*api.Pod) if err != nil { t.Errorf("unexpected error: %v", err) } expect := *podRegistry.Pod expect.Status.Phase = api.PodRunning // TODO: when host is moved to spec, remove this line. expect.Status.Host = "machine" if e, a := &expect, pod; !reflect.DeepEqual(e, a) { t.Errorf("Unexpected pod. Expected %#v, Got %#v", e, a) } }
func TestEndpointsRegistryList(t *testing.T) { registry := registrytest.NewServiceRegistry() storage := NewREST(registry) registry.EndpointsList = api.EndpointsList{ ListMeta: api.ListMeta{ResourceVersion: "1"}, Items: []api.Endpoints{ {ObjectMeta: api.ObjectMeta{Name: "foo"}}, {ObjectMeta: api.ObjectMeta{Name: "bar"}}, }, } ctx := api.NewContext() s, _ := storage.List(ctx, labels.Everything(), labels.Everything()) sl := s.(*api.EndpointsList) if len(sl.Items) != 2 { t.Fatalf("Expected 2 endpoints, but got %v", len(sl.Items)) } if e, a := "foo", sl.Items[0].Name; e != a { t.Errorf("Expected %v, but got %v", e, a) } if e, a := "bar", sl.Items[1].Name; e != a { t.Errorf("Expected %v, but got %v", e, a) } if sl.ResourceVersion != "1" { t.Errorf("Unexpected resource version: %#v", sl) } }
// UpdateAllContainers updates information about all containers. // Callers should let one call to UpdateAllContainers finish before // calling again, or risk having new info getting clobbered by delayed // old info. func (p *PodCache) UpdateAllContainers() { p.resetNodeExistenceCache() ctx := api.NewContext() pods, err := p.pods.ListPods(ctx, labels.Everything()) if err != nil { glog.Errorf("Error getting pod list: %v", err) return } // TODO: this algorithm is 1 goroutine & RPC per pod. With a little work, // it should be possible to make it 1 per *node*, which will be important // at very large scales. (To be clear, the goroutines shouldn't matter-- // it's the RPCs that need to be minimized.) var wg sync.WaitGroup for i := range pods.Items { pod := &pods.Items[i] wg.Add(1) go func() { defer wg.Done() err := p.updatePodStatus(pod) if err != nil && err != client.ErrPodInfoNotAvailable { glog.Errorf("Error getting info for pod %v/%v: %v", pod.Namespace, pod.Name, err) } }() } wg.Wait() }
func TestEtcdGetPersistentVolumes(t *testing.T) { ctx := api.NewContext() storage, _, fakeClient, _ := newStorage(t) persistentVolume := validNewPersistentVolume("foo") name := persistentVolume.Name key, _ := storage.KeyFunc(ctx, name) key = etcdtest.AddPrefix(key) fakeClient.Set(key, runtime.EncodeOrDie(latest.Codec, persistentVolume), 0) response, err := fakeClient.Get(key, false, false) if err != nil { t.Fatalf("Unexpected error %v", err) } var persistentVolumeOut api.PersistentVolume err = latest.Codec.DecodeInto([]byte(response.Node.Value), &persistentVolumeOut) if err != nil { t.Errorf("unexpected error: %v", err) } obj, err := storage.Get(ctx, name) if err != nil { t.Errorf("unexpected error: %v", err) } got := obj.(*api.PersistentVolume) persistentVolume.ObjectMeta.ResourceVersion = got.ObjectMeta.ResourceVersion if e, a := persistentVolume, got; !api.Semantic.DeepEqual(*e, *a) { t.Errorf("Unexpected persistentVolume: %#v, expected %#v", e, a) } }
func TestUpdateError(t *testing.T) { ctx := kapi.WithUser(kapi.WithNamespace(kapi.NewContext(), "unittest"), &user.DefaultInfo{Name: "system:admin"}) storage := makeTestStorage() obj, err := storage.Create(ctx, &authorizationapi.RoleBinding{ ObjectMeta: kapi.ObjectMeta{Name: "my-different"}, RoleRef: kapi.ObjectReference{Name: "admin"}, }) if err != nil { t.Errorf("unexpected error: %v", err) return } original := obj.(*authorizationapi.RoleBinding) roleBinding := &authorizationapi.RoleBinding{ ObjectMeta: kapi.ObjectMeta{Name: "my-roleBinding", ResourceVersion: original.ResourceVersion}, RoleRef: kapi.ObjectReference{Name: "admin"}, } _, _, err = storage.Update(ctx, roleBinding) if err == nil { t.Errorf("Missing expected error") return } if !kapierrors.IsNotFound(err) { t.Errorf("Unexpected error %v", err) } }
func TestEtcdUpdatePersistentVolumes(t *testing.T) { ctx := api.NewContext() storage, _, fakeClient, _ := newStorage(t) persistentVolume := validChangedPersistentVolume() key, _ := storage.KeyFunc(ctx, "foo") key = etcdtest.AddPrefix(key) fakeClient.Set(key, runtime.EncodeOrDie(latest.Codec, validNewPersistentVolume("foo")), 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.PersistentVolume err = latest.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) } }
func TestFillCurrentState(t *testing.T) { fakeLister := fakePodLister{ l: api.PodList{ Items: []api.Pod{ {ObjectMeta: api.ObjectMeta{Name: "foo"}}, {ObjectMeta: api.ObjectMeta{Name: "bar"}}, }, }, } mockRegistry := registrytest.ControllerRegistry{} storage := REST{ registry: &mockRegistry, podLister: &fakeLister, } controller := api.ReplicationController{ Spec: api.ReplicationControllerSpec{ Selector: map[string]string{ "foo": "bar", }, }, } ctx := api.NewContext() storage.fillCurrentState(ctx, &controller) if controller.Status.Replicas != 2 { t.Errorf("expected 2, got: %d", controller.Status.Replicas) } if !reflect.DeepEqual(fakeLister.s, labels.Set(controller.Spec.Selector).AsSelector()) { t.Errorf("unexpected output: %#v %#v", labels.Set(controller.Spec.Selector).AsSelector(), fakeLister.s) } }
func TestDeleteNamespaceWithCompleteFinalizers(t *testing.T) { now := util.Now() fakeEtcdClient, etcdStorage := newEtcdStorage(t) fakeEtcdClient.ChangeIndex = 1 key := etcdtest.AddPrefix("/namespaces/foo") fakeEtcdClient.Data[key] = tools.EtcdResponseWithError{ R: &etcd.Response{ Node: &etcd.Node{ Value: runtime.EncodeOrDie(latest.Codec, &api.Namespace{ ObjectMeta: api.ObjectMeta{ Name: "foo", DeletionTimestamp: &now, }, Spec: api.NamespaceSpec{ Finalizers: []api.FinalizerName{}, }, Status: api.NamespaceStatus{Phase: api.NamespaceActive}, }), ModifiedIndex: 1, CreatedIndex: 1, }, }, } storage, _, _ := NewStorage(etcdStorage) _, err := storage.Delete(api.NewContext(), "foo", nil) if err != nil { t.Fatalf("unexpected error: %v", err) } }
func TestUpdateOldUserMatches(t *testing.T) { user, identity := makeAssociated() expectedActions := []test.Action{ // Existing mapping lookup {"GetIdentity", identity.Name}, {"GetUser", user.Name}, } mapping := &api.UserIdentityMapping{ ObjectMeta: kapi.ObjectMeta{ResourceVersion: identity.ResourceVersion}, Identity: kapi.ObjectReference{Name: identity.Name}, User: kapi.ObjectReference{Name: user.Name}, } actions, _, _, rest := setupRegistries(identity, user) createdMapping, created, err := rest.Update(kapi.NewContext(), mapping) if err != nil { t.Errorf("Unexpected error: %v", err) } if created { t.Errorf("Unexpected created") } verifyActions(expectedActions, *actions, t) verifyMapping(createdMapping, user, identity, t) }
func TestUpdateWithMismatchedResourceVersion(t *testing.T) { // Starting conditions associatedUser1, associatedIdentity1User1 := makeAssociated() unassociatedUser2 := makeUser() // Finishing conditions _, unassociatedIdentity1 := disassociate(associatedUser1, associatedIdentity1User1) expectedActions := []test.Action{ // Existing mapping lookup {"GetIdentity", associatedIdentity1User1.Name}, {"GetUser", associatedUser1.Name}, } mapping := &api.UserIdentityMapping{ ObjectMeta: kapi.ObjectMeta{ResourceVersion: "123"}, Identity: kapi.ObjectReference{Name: unassociatedIdentity1.Name}, User: kapi.ObjectReference{Name: unassociatedUser2.Name}, } actions, _, _, rest := setupRegistries(associatedIdentity1User1, associatedUser1, unassociatedUser2) _, _, err := rest.Update(kapi.NewContext(), mapping) if err == nil { t.Errorf("Expected error") } if !kerrs.IsConflict(err) { t.Errorf("Unexpected error: %v", err) } verifyActions(expectedActions, *actions, t) }
func TestDelete(t *testing.T) { ctx := api.NewContext() storage, _, fakeEtcdClient, _ := newStorage(t) test := resttest.New(t, storage, fakeEtcdClient.SetError).ClusterScope() pv := validChangedPersistentVolume() key, _ := storage.KeyFunc(ctx, pv.Name) key = etcdtest.AddPrefix(key) createFn := func() runtime.Object { fakeEtcdClient.Data[key] = tools.EtcdResponseWithError{ R: &etcd.Response{ Node: &etcd.Node{ Value: runtime.EncodeOrDie(latest.Codec, pv), ModifiedIndex: 1, }, }, } return pv } gracefulSetFn := func() bool { if fakeEtcdClient.Data[key].R.Node == nil { return false } return fakeEtcdClient.Data[key].R.Node.TTL == 30 } test.TestDeleteNoGraceful(createFn, gracefulSetFn) }
func TestCreateIdentityUpdateError(t *testing.T) { associatedUser, associatedIdentity := makeAssociated() unassociatedUser, unassociatedIdentity := disassociate(associatedUser, associatedIdentity) expectedActions := []test.Action{ {"GetIdentity", unassociatedIdentity.Name}, {"GetUser", unassociatedUser.Name}, {"UpdateUser", associatedUser}, {"UpdateIdentity", associatedIdentity}, } mapping := &api.UserIdentityMapping{ Identity: kapi.ObjectReference{Name: unassociatedIdentity.Name}, User: kapi.ObjectReference{Name: unassociatedUser.Name}, } actions, _, identityRegistry, rest := setupRegistries(unassociatedIdentity, unassociatedUser) identityRegistry.UpdateErr = errors.New("Update error") _, err := rest.Create(kapi.NewContext(), mapping) if err == nil { t.Errorf("Expected error, got none") } if err != identityRegistry.UpdateErr { t.Errorf("Unexpected error: %#v", err) } verifyActions(expectedActions, *actions, t) }