admission_test.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package exists
  14. import (
  15. "context"
  16. "fmt"
  17. "testing"
  18. "time"
  19. corev1 "k8s.io/api/core/v1"
  20. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  21. "k8s.io/apimachinery/pkg/runtime"
  22. "k8s.io/apimachinery/pkg/util/wait"
  23. "k8s.io/apiserver/pkg/admission"
  24. genericadmissioninitializer "k8s.io/apiserver/pkg/admission/initializer"
  25. informers "k8s.io/client-go/informers"
  26. "k8s.io/client-go/kubernetes"
  27. "k8s.io/client-go/kubernetes/fake"
  28. core "k8s.io/client-go/testing"
  29. api "k8s.io/kubernetes/pkg/apis/core"
  30. )
  31. // newHandlerForTest returns the admission controller configured for testing.
  32. func newHandlerForTest(c kubernetes.Interface) (admission.ValidationInterface, informers.SharedInformerFactory, error) {
  33. f := informers.NewSharedInformerFactory(c, 5*time.Minute)
  34. handler := NewExists()
  35. pluginInitializer := genericadmissioninitializer.New(c, f, nil, nil)
  36. pluginInitializer.Initialize(handler)
  37. err := admission.ValidateInitialization(handler)
  38. return handler, f, err
  39. }
  40. // newMockClientForTest creates a mock client that returns a client configured for the specified list of namespaces.
  41. func newMockClientForTest(namespaces []string) *fake.Clientset {
  42. mockClient := &fake.Clientset{}
  43. mockClient.AddReactor("list", "namespaces", func(action core.Action) (bool, runtime.Object, error) {
  44. namespaceList := &corev1.NamespaceList{
  45. ListMeta: metav1.ListMeta{
  46. ResourceVersion: fmt.Sprintf("%d", len(namespaces)),
  47. },
  48. }
  49. for i, ns := range namespaces {
  50. namespaceList.Items = append(namespaceList.Items, corev1.Namespace{
  51. ObjectMeta: metav1.ObjectMeta{
  52. Name: ns,
  53. ResourceVersion: fmt.Sprintf("%d", i),
  54. },
  55. })
  56. }
  57. return true, namespaceList, nil
  58. })
  59. return mockClient
  60. }
  61. // newPod returns a new pod for the specified namespace
  62. func newPod(namespace string) api.Pod {
  63. return api.Pod{
  64. ObjectMeta: metav1.ObjectMeta{Name: "123", Namespace: namespace},
  65. Spec: api.PodSpec{
  66. Volumes: []api.Volume{{Name: "vol"}},
  67. Containers: []api.Container{{Name: "ctr", Image: "image"}},
  68. },
  69. }
  70. }
  71. // TestAdmissionNamespaceExists verifies pod is admitted only if namespace exists.
  72. func TestAdmissionNamespaceExists(t *testing.T) {
  73. namespace := "test"
  74. mockClient := newMockClientForTest([]string{namespace})
  75. handler, informerFactory, err := newHandlerForTest(mockClient)
  76. if err != nil {
  77. t.Errorf("unexpected error initializing handler: %v", err)
  78. }
  79. informerFactory.Start(wait.NeverStop)
  80. pod := newPod(namespace)
  81. err = handler.Validate(context.TODO(), admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
  82. if err != nil {
  83. t.Errorf("unexpected error returned from admission handler")
  84. }
  85. }
  86. // TestAdmissionNamespaceDoesNotExist verifies pod is not admitted if namespace does not exist.
  87. func TestAdmissionNamespaceDoesNotExist(t *testing.T) {
  88. namespace := "test"
  89. mockClient := newMockClientForTest([]string{})
  90. mockClient.AddReactor("get", "namespaces", func(action core.Action) (bool, runtime.Object, error) {
  91. return true, nil, fmt.Errorf("nope, out of luck")
  92. })
  93. handler, informerFactory, err := newHandlerForTest(mockClient)
  94. if err != nil {
  95. t.Errorf("unexpected error initializing handler: %v", err)
  96. }
  97. informerFactory.Start(wait.NeverStop)
  98. pod := newPod(namespace)
  99. err = handler.Validate(context.TODO(), admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
  100. if err == nil {
  101. actions := ""
  102. for _, action := range mockClient.Actions() {
  103. actions = actions + action.GetVerb() + ":" + action.GetResource().Resource + ":" + action.GetSubresource() + ", "
  104. }
  105. t.Errorf("expected error returned from admission handler: %v", actions)
  106. }
  107. }