admission_test.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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 autoprovision
  14. import (
  15. "context"
  16. "fmt"
  17. "testing"
  18. "time"
  19. corev1 "k8s.io/api/core/v1"
  20. "k8s.io/apimachinery/pkg/api/errors"
  21. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  22. "k8s.io/apimachinery/pkg/runtime"
  23. "k8s.io/apimachinery/pkg/util/wait"
  24. "k8s.io/apiserver/pkg/admission"
  25. genericadmissioninitializer "k8s.io/apiserver/pkg/admission/initializer"
  26. admissiontesting "k8s.io/apiserver/pkg/admission/testing"
  27. "k8s.io/client-go/informers"
  28. clientset "k8s.io/client-go/kubernetes"
  29. "k8s.io/client-go/kubernetes/fake"
  30. core "k8s.io/client-go/testing"
  31. api "k8s.io/kubernetes/pkg/apis/core"
  32. )
  33. // newHandlerForTest returns the admission controller configured for testing.
  34. func newHandlerForTest(c clientset.Interface) (admission.MutationInterface, informers.SharedInformerFactory, error) {
  35. f := informers.NewSharedInformerFactory(c, 5*time.Minute)
  36. handler := NewProvision()
  37. pluginInitializer := genericadmissioninitializer.New(c, f, nil, nil)
  38. pluginInitializer.Initialize(handler)
  39. err := admission.ValidateInitialization(handler)
  40. return handler, f, err
  41. }
  42. // newMockClientForTest creates a mock client that returns a client configured for the specified list of namespaces.
  43. func newMockClientForTest(namespaces []string) *fake.Clientset {
  44. mockClient := &fake.Clientset{}
  45. mockClient.AddReactor("list", "namespaces", func(action core.Action) (bool, runtime.Object, error) {
  46. namespaceList := &corev1.NamespaceList{
  47. ListMeta: metav1.ListMeta{
  48. ResourceVersion: fmt.Sprintf("%d", len(namespaces)),
  49. },
  50. }
  51. for i, ns := range namespaces {
  52. namespaceList.Items = append(namespaceList.Items, corev1.Namespace{
  53. ObjectMeta: metav1.ObjectMeta{
  54. Name: ns,
  55. ResourceVersion: fmt.Sprintf("%d", i),
  56. },
  57. })
  58. }
  59. return true, namespaceList, nil
  60. })
  61. return mockClient
  62. }
  63. // newPod returns a new pod for the specified namespace
  64. func newPod(namespace string) api.Pod {
  65. return api.Pod{
  66. ObjectMeta: metav1.ObjectMeta{Name: "123", Namespace: namespace},
  67. Spec: api.PodSpec{
  68. Volumes: []api.Volume{{Name: "vol"}},
  69. Containers: []api.Container{{Name: "ctr", Image: "image"}},
  70. },
  71. }
  72. }
  73. // hasCreateNamespaceAction returns true if it has the create namespace action
  74. func hasCreateNamespaceAction(mockClient *fake.Clientset) bool {
  75. for _, action := range mockClient.Actions() {
  76. if action.GetVerb() == "create" && action.GetResource().Resource == "namespaces" {
  77. return true
  78. }
  79. }
  80. return false
  81. }
  82. // TestAdmission verifies a namespace is created on create requests for namespace managed resources
  83. func TestAdmission(t *testing.T) {
  84. namespace := "test"
  85. mockClient := newMockClientForTest([]string{})
  86. handler, informerFactory, err := newHandlerForTest(mockClient)
  87. if err != nil {
  88. t.Errorf("unexpected error initializing handler: %v", err)
  89. }
  90. informerFactory.Start(wait.NeverStop)
  91. pod := newPod(namespace)
  92. err = admissiontesting.WithReinvocationTesting(t, handler).Admit(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)
  93. if err != nil {
  94. t.Errorf("unexpected error returned from admission handler")
  95. }
  96. if !hasCreateNamespaceAction(mockClient) {
  97. t.Errorf("expected create namespace action")
  98. }
  99. }
  100. // TestAdmissionNamespaceExists verifies that no client call is made when a namespace already exists
  101. func TestAdmissionNamespaceExists(t *testing.T) {
  102. namespace := "test"
  103. mockClient := newMockClientForTest([]string{namespace})
  104. handler, informerFactory, err := newHandlerForTest(mockClient)
  105. if err != nil {
  106. t.Errorf("unexpected error initializing handler: %v", err)
  107. }
  108. informerFactory.Start(wait.NeverStop)
  109. pod := newPod(namespace)
  110. err = admissiontesting.WithReinvocationTesting(t, handler).Admit(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)
  111. if err != nil {
  112. t.Errorf("unexpected error returned from admission handler")
  113. }
  114. if hasCreateNamespaceAction(mockClient) {
  115. t.Errorf("unexpected create namespace action")
  116. }
  117. }
  118. // TestAdmissionDryRun verifies that no client call is made on a dry run request
  119. func TestAdmissionDryRun(t *testing.T) {
  120. namespace := "test"
  121. mockClient := newMockClientForTest([]string{})
  122. handler, informerFactory, err := newHandlerForTest(mockClient)
  123. if err != nil {
  124. t.Errorf("unexpected error initializing handler: %v", err)
  125. }
  126. informerFactory.Start(wait.NeverStop)
  127. pod := newPod(namespace)
  128. err = admissiontesting.WithReinvocationTesting(t, handler).Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, true, nil), nil)
  129. if err != nil {
  130. t.Errorf("unexpected error returned from admission handler")
  131. }
  132. if hasCreateNamespaceAction(mockClient) {
  133. t.Errorf("unexpected create namespace action")
  134. }
  135. }
  136. // TestIgnoreAdmission validates that a request is ignored if its not a create
  137. func TestIgnoreAdmission(t *testing.T) {
  138. namespace := "test"
  139. mockClient := newMockClientForTest([]string{})
  140. handler, informerFactory, err := newHandlerForTest(mockClient)
  141. if err != nil {
  142. t.Errorf("unexpected error initializing handler: %v", err)
  143. }
  144. informerFactory.Start(wait.NeverStop)
  145. chainHandler := admissiontesting.WithReinvocationTesting(t, admission.NewChainHandler(handler))
  146. pod := newPod(namespace)
  147. err = admissiontesting.WithReinvocationTesting(t, chainHandler).Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil)
  148. if err != nil {
  149. t.Errorf("unexpected error returned from admission handler")
  150. }
  151. if hasCreateNamespaceAction(mockClient) {
  152. t.Errorf("unexpected create namespace action")
  153. }
  154. }
  155. func TestAdmissionWithLatentCache(t *testing.T) {
  156. namespace := "test"
  157. mockClient := newMockClientForTest([]string{})
  158. mockClient.AddReactor("create", "namespaces", func(action core.Action) (bool, runtime.Object, error) {
  159. return true, nil, errors.NewAlreadyExists(api.Resource("namespaces"), namespace)
  160. })
  161. handler, informerFactory, err := newHandlerForTest(mockClient)
  162. if err != nil {
  163. t.Errorf("unexpected error initializing handler: %v", err)
  164. }
  165. informerFactory.Start(wait.NeverStop)
  166. pod := newPod(namespace)
  167. err = admissiontesting.WithReinvocationTesting(t, handler).Admit(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)
  168. if err != nil {
  169. t.Errorf("unexpected error returned from admission handler")
  170. }
  171. if !hasCreateNamespaceAction(mockClient) {
  172. t.Errorf("expected create namespace action")
  173. }
  174. }