admission_test.go 7.4 KB

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