How to use Kind method of dummy Package

Best Testkube code snippet using dummy.Kind

webhook_test.go

Source:webhook_test.go Github

copy

Full Screen

...43 winOptionsFactory := func(containerName string) *corev1.WindowsSecurityContextOptions {44 return buildWindowsOptions(containerName+"-cred-spec", containerName+"-cred-spec-contents")45 }46 runWebhookValidateOrMutateTests(t, winOptionsFactory, map[string]webhookValidateOrMutateTest{47 "with matching name & content, it passes": func(t *testing.T, pod *corev1.Pod, optionsSelector winOptionsSelector, _ gmsaResourceKind, _ string) {48 webhook := newWebhook(kubeClientFactory())49 setWindowsOptions(optionsSelector(pod), dummyCredSpecName, dummyCredSpecContents)50 response, err := webhook.validateCreateRequest(context.Background(), pod, dummyNamespace)51 assert.Nil(t, err)52 require.NotNil(t, response)53 assert.True(t, response.Allowed)54 },55 "if the cred spec contents are not byte-to-byte equal to that of the one named, but still represent equivalent JSONs, it passes": func(t *testing.T, pod *corev1.Pod, optionsSelector winOptionsSelector, _ gmsaResourceKind, _ string) {56 webhook := newWebhook(kubeClientFactory())57 setWindowsOptions(58 optionsSelector(pod),59 dummyCredSpecName,60 `{"All in all you're just another": {"the":"wall","brick": "in"},"We don't need no":["education", "thought control","dark sarcasm in the classroom"]}`,61 )62 response, err := webhook.validateCreateRequest(context.Background(), pod, dummyNamespace)63 assert.Nil(t, err)64 require.NotNil(t, response)65 assert.True(t, response.Allowed)66 },67 "if the cred spec contents are not that of the one named, it fails": func(t *testing.T, pod *corev1.Pod, optionsSelector winOptionsSelector, resourceKind gmsaResourceKind, resourceName string) {68 webhook := newWebhook(kubeClientFactory())69 setWindowsOptions(70 optionsSelector(pod),71 dummyCredSpecName,72 `{"We don't need no": ["money"], "All in all you're just another": {"brick": "in", "the": "wall"}}`,73 )74 response, err := webhook.validateCreateRequest(context.Background(), pod, dummyNamespace)75 assert.Nil(t, response)76 assertPodAdmissionErrorContains(t, err, pod, http.StatusUnprocessableEntity,77 "the GMSA cred spec contents for %s %q does not match the contents of GMSA resource %q",78 resourceKind, resourceName, dummyCredSpecName)79 },80 "if the cred spec contents are not byte-to-byte equal to that of the one named, and are not even a valid JSON object, it fails": func(t *testing.T, pod *corev1.Pod, optionsSelector winOptionsSelector, resourceKind gmsaResourceKind, resourceName string) {81 webhook := newWebhook(kubeClientFactory())82 setWindowsOptions(optionsSelector(pod), dummyCredSpecName, "i ain't no JSON object")83 response, err := webhook.validateCreateRequest(context.Background(), pod, dummyNamespace)84 assert.Nil(t, response)85 assertPodAdmissionErrorContains(t, err, pod, http.StatusUnprocessableEntity,86 "the GMSA cred spec contents for %s %q does not match the contents of GMSA resource %q",87 resourceKind, resourceName, dummyCredSpecName)88 },89 "if the contents are set, but the name one isn't provided, it fails": func(t *testing.T, pod *corev1.Pod, optionsSelector winOptionsSelector, resourceKind gmsaResourceKind, resourceName string) {90 webhook := newWebhook(kubeClientFactory())91 setWindowsOptions(optionsSelector(pod), "", dummyCredSpecContents)92 response, err := webhook.validateCreateRequest(context.Background(), pod, dummyNamespace)93 assert.Nil(t, response)94 assertPodAdmissionErrorContains(t, err, pod, http.StatusUnprocessableEntity,95 "%s %q has a GMSA cred spec set, but does not define the name of the corresponding resource",96 resourceKind, resourceName)97 },98 "if the service account is not authorized to use the cred-spec, it fails": func(t *testing.T, pod *corev1.Pod, optionsSelector winOptionsSelector, _ gmsaResourceKind, _ string) {99 dummyReason := "dummy reason"100 client := kubeClientFactory()101 client.isAuthorizedToUseCredSpecFunc = func(ctx context.Context, serviceAccountName, namespace, credSpecName string) (authorized bool, reason string) {102 if credSpecName == dummyCredSpecName {103 assert.Equal(t, dummyServiceAccoutName, serviceAccountName)104 assert.Equal(t, dummyNamespace, namespace)105 return false, dummyReason106 }107 return true, ""108 }109 webhook := newWebhook(client)110 setWindowsOptions(optionsSelector(pod), dummyCredSpecName, dummyCredSpecContents)111 response, err := webhook.validateCreateRequest(context.Background(), pod, dummyNamespace)112 assert.Nil(t, response)113 assertPodAdmissionErrorContains(t, err, pod, http.StatusForbidden,114 "service account %q is not authorized to `use` GMSA cred spec %q, reason: %q",115 dummyServiceAccoutName, dummyCredSpecName, dummyReason)116 },117 "if there is an error when retrieving the cred-spec's contents, it fails": func(t *testing.T, pod *corev1.Pod, optionsSelector winOptionsSelector, _ gmsaResourceKind, _ string) {118 dummyError := fmt.Errorf("dummy error")119 client := kubeClientFactory()120 previousRetrieveCredSpecContentsFunc := client.retrieveCredSpecContentsFunc121 client.retrieveCredSpecContentsFunc = func(ctx context.Context, credSpecName string) (contents string, httpCode int, err error) {122 if credSpecName == dummyCredSpecName {123 return "", http.StatusNotFound, dummyError124 }125 return previousRetrieveCredSpecContentsFunc(ctx, credSpecName)126 }127 webhook := newWebhook(client)128 setWindowsOptions(optionsSelector(pod), dummyCredSpecName, dummyCredSpecContents)129 response, err := webhook.validateCreateRequest(context.Background(), pod, dummyNamespace)130 assert.Nil(t, response)131 assertPodAdmissionErrorContains(t, err, pod, http.StatusNotFound, dummyError.Error())132 },133 })134}135func TestMutateCreateRequest(t *testing.T) {136 for testCaseName, winOptionsFactory := range map[string]func() *corev1.WindowsSecurityContextOptions{137 "with empty GMSA settings, it passes and does nothing": func() *corev1.WindowsSecurityContextOptions {138 return &corev1.WindowsSecurityContextOptions{}139 },140 "with no GMSA settings, it passes and does nothing": func() *corev1.WindowsSecurityContextOptions {141 return nil142 },143 } {144 t.Run(testCaseName, func(t *testing.T) {145 webhook := newWebhook(nil)146 pod := buildPod(dummyServiceAccoutName, winOptionsFactory(), map[string]*corev1.WindowsSecurityContextOptions{dummyContainerName: winOptionsFactory()})147 response, err := webhook.mutateCreateRequest(context.Background(), pod)148 assert.Nil(t, err)149 require.NotNil(t, response)150 assert.True(t, response.Allowed)151 })152 }153 kubeClientFactory := func() *dummyKubeClient {154 return &dummyKubeClient{155 retrieveCredSpecContentsFunc: func(ctx context.Context, credSpecName string) (contents string, httpCode int, err error) {156 if credSpecName == dummyCredSpecName {157 contents = dummyCredSpecContents158 } else {159 contents = credSpecName + "-contents"160 }161 return162 },163 }164 }165 winOptionsFactory := func(containerName string) *corev1.WindowsSecurityContextOptions {166 return buildWindowsOptions(containerName+"-cred-spec", "")167 }168 runWebhookValidateOrMutateTests(t, winOptionsFactory, map[string]webhookValidateOrMutateTest{169 "with a GMSA cred spec name, it passes and inlines the cred-spec's contents": func(t *testing.T, pod *corev1.Pod, optionsSelector winOptionsSelector, resourceKind gmsaResourceKind, resourceName string) {170 webhook := newWebhook(kubeClientFactory())171 setWindowsOptions(optionsSelector(pod), dummyCredSpecName, "")172 response, err := webhook.mutateCreateRequest(context.Background(), pod)173 assert.Nil(t, err)174 require.NotNil(t, response)175 assert.True(t, response.Allowed)176 if assert.NotNil(t, response.PatchType) {177 assert.Equal(t, admissionV1.PatchTypeJSONPatch, *response.PatchType)178 }179 patchPath := func(kind gmsaResourceKind, name string) string {180 partialPath := ""181 if kind == containerKind {182 containerIndex := -1183 for i, container := range pod.Spec.Containers {184 if container.Name == name {185 containerIndex = i186 break187 }188 }189 if containerIndex == -1 {190 t.Fatalf("Did not find any container named %q", name)191 }192 partialPath = fmt.Sprintf("/containers/%d", containerIndex)193 }194 return fmt.Sprintf("/spec%s/securityContext/windowsOptions/gmsaCredentialSpec", partialPath)195 }196 // maps the contents to the expected patch for that container197 expectedPatches := make(map[string]map[string]string)198 for i := 0; i < len(pod.Spec.Containers)-1; i++ {199 credSpecContents := extraContainerName(i) + "-cred-spec-contents"200 expectedPatches[credSpecContents] = map[string]string{201 "op": "add",202 "path": patchPath(containerKind, extraContainerName(i)),203 "value": credSpecContents,204 }205 }206 // and the patch for this test's specific cred spec207 expectedPatches[dummyCredSpecContents] = map[string]string{208 "op": "add",209 "path": patchPath(resourceKind, resourceName),210 "value": dummyCredSpecContents,211 }212 var patches []map[string]string213 if err := json.Unmarshal(response.Patch, &patches); assert.Nil(t, err) && assert.Equal(t, len(pod.Spec.Containers), len(patches)) {214 for _, patch := range patches {215 if value, hasValue := patch["value"]; assert.True(t, hasValue) {216 if expectedPatch, present := expectedPatches[value]; assert.True(t, present, "value %s not found in expected patches", value) {217 assert.Equal(t, expectedPatch, patch)218 }219 }220 }221 }222 },223 "it the cred spec's contents are already set, along with its name, it passes and doesn't overwrite the provided contents": func(t *testing.T, pod *corev1.Pod, optionsSelector winOptionsSelector, _ gmsaResourceKind, _ string) {224 webhook := newWebhook(kubeClientFactory())225 setWindowsOptions(optionsSelector(pod), dummyCredSpecName, `{"pre-set GMSA": "cred contents"}`)226 response, err := webhook.mutateCreateRequest(context.Background(), pod)227 assert.Nil(t, err)228 // all the patches we receive should be for the extra containers229 expectedPatchesLen := len(pod.Spec.Containers) - 1230 if expectedPatchesLen == 0 {231 assert.Nil(t, response.PatchType)232 assert.Nil(t, response.Patch)233 } else {234 var patches []map[string]string235 if err := json.Unmarshal(response.Patch, &patches); assert.Nil(t, err) && assert.Equal(t, expectedPatchesLen, len(patches)) {236 for _, patch := range patches {237 if path, hasPath := patch["path"]; assert.True(t, hasPath) {238 assert.NotContains(t, path, dummyCredSpecName)239 }240 }241 }242 }243 },244 "if there is an error when retrieving the cred-spec's contents, it fails": func(t *testing.T, pod *corev1.Pod, optionsSelector winOptionsSelector, _ gmsaResourceKind, _ string) {245 dummyError := fmt.Errorf("dummy error")246 client := kubeClientFactory()247 previousRetrieveCredSpecContentsFunc := client.retrieveCredSpecContentsFunc248 client.retrieveCredSpecContentsFunc = func(ctx context.Context, credSpecName string) (contents string, httpCode int, err error) {249 if credSpecName == dummyCredSpecName {250 return "", http.StatusNotFound, dummyError251 }252 return previousRetrieveCredSpecContentsFunc(ctx, credSpecName)253 }254 webhook := newWebhook(client)255 setWindowsOptions(optionsSelector(pod), dummyCredSpecName, "")256 response, err := webhook.mutateCreateRequest(context.Background(), pod)257 assert.Nil(t, response)258 assertPodAdmissionErrorContains(t, err, pod, http.StatusNotFound, dummyError.Error())259 },260 })261}262func TestValidateUpdateRequest(t *testing.T) {263 for testCaseName, winOptionsFactory := range map[string]func() *corev1.WindowsSecurityContextOptions{264 "with empty GMSA settings, it passes and does nothing": func() *corev1.WindowsSecurityContextOptions {265 return &corev1.WindowsSecurityContextOptions{}266 },267 "with no GMSA settings, it passes and does nothing": func() *corev1.WindowsSecurityContextOptions {268 return nil269 },270 } {271 t.Run(testCaseName, func(t *testing.T) {272 pod := buildPod(dummyServiceAccoutName, winOptionsFactory(), map[string]*corev1.WindowsSecurityContextOptions{dummyContainerName: winOptionsFactory()})273 oldPod := buildPod(dummyServiceAccoutName, winOptionsFactory(), map[string]*corev1.WindowsSecurityContextOptions{dummyContainerName: winOptionsFactory()})274 response, err := validateUpdateRequest(pod, oldPod)275 assert.Nil(t, err)276 require.NotNil(t, response)277 assert.True(t, response.Allowed)278 })279 }280 winOptionsFactory := func(containerName string) *corev1.WindowsSecurityContextOptions {281 return buildWindowsOptions(containerName+"-cred-spec", containerName+"-cred-spec-contents")282 }283 runWebhookValidateOrMutateTests(t, winOptionsFactory, map[string]webhookValidateOrMutateTest{284 "if there was no changes to GMSA settings, it passes": func(t *testing.T, pod *corev1.Pod, optionsSelector winOptionsSelector, _ gmsaResourceKind, _ string) {285 setWindowsOptions(optionsSelector(pod), dummyCredSpecName, dummyCredSpecContents)286 oldPod := pod.DeepCopy()287 response, err := validateUpdateRequest(pod, oldPod)288 assert.Nil(t, err)289 require.NotNil(t, response)290 assert.True(t, response.Allowed)291 },292 "if there was a change to a GMSA name, it fails": func(t *testing.T, pod *corev1.Pod, optionsSelector winOptionsSelector, resourceKind gmsaResourceKind, resourceName string) {293 setWindowsOptions(optionsSelector(pod), "new-cred-spec-name", dummyCredSpecContents)294 oldPod := pod.DeepCopy()295 setWindowsOptions(optionsSelector(oldPod), dummyCredSpecName, "")296 response, err := validateUpdateRequest(pod, oldPod)297 assert.Nil(t, response)298 assertPodAdmissionErrorContains(t, err, pod, http.StatusForbidden,299 "cannot update an existing pod's GMSA settings (GMSA name modified on %s %q)",300 resourceKind, resourceName)301 },302 "if there was a change to a GMSA contents, it fails": func(t *testing.T, pod *corev1.Pod, optionsSelector winOptionsSelector, resourceKind gmsaResourceKind, resourceName string) {303 setWindowsOptions(optionsSelector(pod), dummyCredSpecName, "new-cred-spec-contents")304 oldPod := pod.DeepCopy()305 setWindowsOptions(optionsSelector(oldPod), "", dummyCredSpecContents)306 response, err := validateUpdateRequest(pod, oldPod)307 assert.Nil(t, response)308 assertPodAdmissionErrorContains(t, err, pod, http.StatusForbidden,309 "cannot update an existing pod's GMSA settings (GMSA contents modified on %s %q)",310 resourceKind, resourceName)311 },312 "if there were changes to both GMSA name & contents, it fails": func(t *testing.T, pod *corev1.Pod, optionsSelector winOptionsSelector, resourceKind gmsaResourceKind, resourceName string) {313 setWindowsOptions(optionsSelector(pod), "new-cred-spec-name", "new-cred-spec-contents")314 oldPod := pod.DeepCopy()315 setWindowsOptions(optionsSelector(oldPod), dummyCredSpecName, dummyCredSpecContents)316 response, err := validateUpdateRequest(pod, oldPod)317 assert.Nil(t, response)318 assertPodAdmissionErrorContains(t, err, pod, http.StatusForbidden,319 "cannot update an existing pod's GMSA settings (GMSA name and contents modified on %s %q)",320 resourceKind, resourceName)321 },322 })323}324func TestEqualStringPointers(t *testing.T) {325 ptrToString := func(s *string) string {326 if s == nil {327 return "nil"328 }329 return " = " + *s330 }331 foo := "foo"332 bar := "bar"333 for _, testCase := range []struct {334 s1 *string335 s2 *string336 expectedResult bool337 }{338 {339 s1: nil,340 s2: nil,341 expectedResult: true,342 },343 {344 s1: &foo,345 s2: nil,346 expectedResult: false,347 },348 {349 s1: &foo,350 s2: &foo,351 expectedResult: true,352 },353 {354 s1: &foo,355 s2: &bar,356 expectedResult: false,357 },358 } {359 for _, ptrs := range [][]*string{360 {testCase.s1, testCase.s2},361 {testCase.s2, testCase.s1},362 } {363 s1 := ptrs[0]364 s2 := ptrs[1]365 testName := fmt.Sprintf("with s1 %s and s2 %s, should return %v",366 ptrToString(s1),367 ptrToString(s2),368 testCase.expectedResult)369 t.Run(testName, func(t *testing.T) {370 assert.Equal(t, testCase.expectedResult, equalStringPointers(s1, s2))371 })372 }373 }374}375/* Helpers below */376type containerWindowsOptionsFactory func(containerName string) *corev1.WindowsSecurityContextOptions377type winOptionsSelector func(pod *corev1.Pod) *corev1.WindowsSecurityContextOptions378// a webhookValidateOrMutateTest function should run a test on one of the webhook's validate or mutate379// functions, given a selector to extract the WindowsSecurityOptions struct it can play with from the pod.380// It should assume that the pod it receives has any number of extra containers with correct381// (in the sense of the test) windows security options generated by a relevant containerWindowsOptionsFactory.382type webhookValidateOrMutateTest func(t *testing.T, pod *corev1.Pod, optionsSelector winOptionsSelector, resourceKind gmsaResourceKind, resourceName string)383// runWebhookValidateOrMutateTests runs the given tests with 0 to 5 extra containers with correct windows384// security options as generated by winOptionsFactory.385func runWebhookValidateOrMutateTests(t *testing.T, winOptionsFactory containerWindowsOptionsFactory, tests map[string]webhookValidateOrMutateTest) {386 for extraContainersCount := 0; extraContainersCount <= 5; extraContainersCount++ {387 containerNamesAndWindowsOptions := make(map[string]*corev1.WindowsSecurityContextOptions)388 for i := 0; i < extraContainersCount; i++ {389 containerName := extraContainerName(i)390 containerNamesAndWindowsOptions[containerName] = winOptionsFactory(containerName)391 }392 testNameSuffix := ""393 if extraContainersCount > 0 {394 testNameSuffix = fmt.Sprintf(" and %d extra containers", extraContainersCount)395 }396 for _, resourceKind := range []gmsaResourceKind{podKind, containerKind} {397 for testName, testFunc := range tests {398 podWindowsOptions := &corev1.WindowsSecurityContextOptions{}399 containerNamesAndWindowsOptions[dummyContainerName] = &corev1.WindowsSecurityContextOptions{}400 pod := buildPod(dummyServiceAccoutName, podWindowsOptions, containerNamesAndWindowsOptions)401 var optionsSelector winOptionsSelector402 var resourceName string403 switch resourceKind {404 case podKind:405 optionsSelector = func(pod *corev1.Pod) *corev1.WindowsSecurityContextOptions {406 if pod != nil && pod.Spec.SecurityContext != nil {407 return pod.Spec.SecurityContext.WindowsOptions408 }409 return nil410 }411 resourceName = dummyPodName412 case containerKind:413 optionsSelector = func(pod *corev1.Pod) *corev1.WindowsSecurityContextOptions {414 if pod != nil {415 for _, container := range pod.Spec.Containers {416 if container.Name == dummyContainerName {417 if container.SecurityContext != nil {418 return container.SecurityContext.WindowsOptions419 }420 return nil421 }422 }423 }424 return nil425 }426 resourceName = dummyContainerName427 default:428 t.Fatalf("Unknown resource kind: %q", resourceKind)429 }430 t.Run(fmt.Sprintf("%s - with %s-level windows options%s", testName, resourceKind, testNameSuffix), func(t *testing.T) {431 testFunc(t, pod, optionsSelector, resourceKind, resourceName)432 })433 }434 }435 }436}437func extraContainerName(i int) string {438 return fmt.Sprintf("extra-container-%d", i)439}440func assertPodAdmissionErrorContains(t *testing.T, err *podAdmissionError, pod *corev1.Pod, httpCode int, msgFormat string, msgArgs ...interface{}) bool {441 if !assert.NotNil(t, err) {442 return false443 }444 result := assert.Equal(t, pod, err.pod)445 result = assert.Equal(t, httpCode, err.code) && result...

Full Screen

Full Screen

main_test.go

Source:main_test.go Github

copy

Full Screen

...28 {"ingresses"},29 {"cronjobs"},30 {"persistentvolumeclaims"},31}32func TestKindService_CleanupKindWithErrorOnGetList(t *testing.T) {33 for _, entry := range listErrorTests {34 config := loader.Config{}35 kindService, _, fakeClientSet := getKindServiceInterface(config)36 fakeClientSet.PrependReactor("list", entry.resource, testingKube.ErrorReturnFunc)37 assert.EqualError(t, kindService.CleanupKind("foobar"), "explode", fmt.Sprintf("Test failed for resource %s", entry.resource))38 }39}40var deleteErrorTests = []struct {41 resource string42 list runtime.Object43}{44 {"secrets", &coreV1.SecretList{Items: []coreV1.Secret{{ObjectMeta: meta.ObjectMeta{Name: "default-token-fff"}}, {ObjectMeta: meta.ObjectMeta{Name: "dummy"}}}}},45 {"configmaps", &coreV1.ConfigMapList{Items: []coreV1.ConfigMap{{ObjectMeta: meta.ObjectMeta{Name: "dummy"}}}}},46 {"services", &coreV1.ServiceList{Items: []coreV1.Service{{ObjectMeta: meta.ObjectMeta{Name: "dummy"}}}}},47 {"persistentvolumeclaims", &coreV1.PersistentVolumeClaimList{Items: []coreV1.PersistentVolumeClaim{{ObjectMeta: meta.ObjectMeta{Name: "dummy"}}}}},48 {"deployments", &apps.DeploymentList{Items: []apps.Deployment{{ObjectMeta: meta.ObjectMeta{Name: "dummy"}}}}},49 {"ingresses", &extensions.IngressList{Items: []extensions.Ingress{{ObjectMeta: meta.ObjectMeta{Name: "dummy"}}}}},50 {"cronjobs", &batch.CronJobList{Items: []batch.CronJob{{ObjectMeta: meta.ObjectMeta{Name: "dummy"}}}}},51}52func TestKindService_CleanupKindWithErrorOnDeleteKind(t *testing.T) {53 for _, entry := range deleteErrorTests {54 config := loader.Config{}55 kindService, _, fakeClientSet := getKindServiceInterface(config)56 fakeClientSet.PrependReactor("list", entry.resource, testingKube.GetObjectReturnFunc(entry.list))57 fakeClientSet.PrependReactor("delete", entry.resource, testingKube.ErrorReturnFunc)58 assert.EqualError(t, kindService.CleanupKind("foobar"), "explode", fmt.Sprintf("Test failed for resource %s", entry.resource))59 }60}61var deleteTests = []struct {62 resource string63 list runtime.Object64 out string65}{66 {"secrets", &coreV1.SecretList{Items: []coreV1.Secret{{ObjectMeta: meta.ObjectMeta{Name: "default-token-fff"}}, {ObjectMeta: meta.ObjectMeta{Name: "dummy"}}}}, "Secret \"dummy\" was removed.\n"},67 {"configmaps", &coreV1.ConfigMapList{Items: []coreV1.ConfigMap{{ObjectMeta: meta.ObjectMeta{Name: "dummy"}}}}, "ConfigMap \"dummy\" was removed.\n"},68 {"services", &coreV1.ServiceList{Items: []coreV1.Service{{ObjectMeta: meta.ObjectMeta{Name: "dummy"}}}}, "Service \"dummy\" was removed.\n"},69 {"persistentvolumeclaims", &coreV1.PersistentVolumeClaimList{Items: []coreV1.PersistentVolumeClaim{{ObjectMeta: meta.ObjectMeta{Name: "dummy"}}}}, "PersistentVolumeClaim \"dummy\" was removed.\n"},70 {"deployments", &apps.DeploymentList{Items: []apps.Deployment{{ObjectMeta: meta.ObjectMeta{Name: "dummy"}}}}, "Deployment \"dummy\" was removed.\n"},71 {"ingresses", &extensions.IngressList{Items: []extensions.Ingress{{ObjectMeta: meta.ObjectMeta{Name: "dummy"}}}}, "Ingress \"dummy\" was removed.\n"},72 {"cronjobs", &batch.CronJobList{Items: []batch.CronJob{{ObjectMeta: meta.ObjectMeta{Name: "dummy"}}}}, "CronJob \"dummy\" was removed.\n"},73}74func TestKindService_CleanupKind(t *testing.T) {75 for _, entry := range deleteTests {76 config := loader.Config{}77 kindService, _, fakeClientSet := getKindService(config)78 fakeClientSet.PrependReactor("list", entry.resource, testingKube.GetObjectReturnFunc(entry.list))79 fakeClientSet.PrependReactor("delete", entry.resource, testingKube.NilReturnFunc)80 kindService.usedKind.secret = append(kindService.usedKind.secret, "foobarUsed")81 output := captureOutput(func() {82 assert.NoError(t, kindService.CleanupKind("foobar"), fmt.Sprintf("Test failed for resource %s", entry.resource))83 })84 assert.Equal(t, entry.out, output, fmt.Sprintf("Test failed for resource %s", entry.resource))85 assert.Len(t, fakeClientSet.Actions(), 8)86 }87}88var secret = `kind: Secret89apiVersion: v190type: Opaque91metadata:92 name: dummy`93var configMap = `kind: ConfigMap94apiVersion: v195metadata:96 name: dummy`97var service = `kind: Service98apiVersion: v199metadata:100 name: dummy`101var serviceWithAnnotation = `kind: Service102apiVersion: v1103metadata:104 name: dummy105 annotations:106 "tourstream.eu/ingress": "true"`107var persistentVolumeClaim = `kind: PersistentVolumeClaim108apiVersion: v1109metadata:110 name: dummy`111var persistentVolume = `kind: PersistentVolume112apiVersion: v1113metadata:114 name: dummy`115var deployment = `kind: Deployment116apiVersion: apps/v1117metadata:118 name: dummy`119var deploymentWithAnnotation = `kind: Deployment120apiVersion: apps/v1121metadata:122 name: dummy123 annotations:124 imageUpdateStrategy: "latest-branching"125spec:126 replicas: 1127 template:128 spec:129 containers:130 - name: deploy131 image: eu.gcr.io/foobar/app`132var ingress = `kind: Ingress133apiVersion: extensions/v1beta1134metadata:135 name: dummy`136var cronjob = `kind: CronJob137apiVersion: batch/v1beta1138metadata:139 name: dummy`140var cronjobWithAnnotation = `kind: CronJob141apiVersion: batch/v1beta1142metadata:143 name: dummy144 annotations:145 imageUpdateStrategy: "latest-branching"146spec:147 schedule: "*/30 * * * *"148 jobTemplate:149 spec:150 template:151 spec:152 containers:153 - name: cron154 image: busy155 - name: cron-with-gcr156 image: eu.gcr.io/foobar/app`157var insertTests = []struct {158 resource string159 kind string160 out string161}{162 {"secrets", secret, "Secret \"dummy\" was generated.\n"},163 {"configmaps", configMap, "ConfigMap \"dummy\" was generated.\n"},164 {"services", service, "Service \"dummy\" was generated.\n"},165 {"persistentvolumeclaims", persistentVolumeClaim, "PersistentVolumeClaim \"dummy\" was generated.\n"},166 {"persistentvolumes", persistentVolume, "PersistentVolume \"dummy\" was generated.\n"},167 {"deployments", deployment, "Deployment \"dummy\" was generated.\n"},168 {"ingresses", ingress, "Ingress \"dummy\" was generated.\n"},169 {"cronjobs", cronjob, "CronJob \"dummy\" was generated.\n"},170}171var upsertTests = []struct {172 resource string173 kind string174 out string175 object runtime.Object176}{177 {"secrets", secret, "Secret \"dummy\" was updated.\n", nil},178 {"configmaps", configMap, "ConfigMap \"dummy\" was updated.\n", nil},179 {"services", service, "Service \"dummy\" was updated.\n", &coreV1.Service{ObjectMeta: meta.ObjectMeta{Name: "dummy"}}},180 {"services", serviceWithAnnotation, "Service \"dummy\" was updated.\n", &coreV1.Service{ObjectMeta: meta.ObjectMeta{Name: "dummy"}}},181 {"persistentvolumeclaims", persistentVolumeClaim, "PersistentVolumeClaim \"dummy\" was updated.\n", &coreV1.PersistentVolumeClaim{ObjectMeta: meta.ObjectMeta{Name: "dummy"}}},182 {"persistentvolumes", persistentVolume, "PersistentVolume \"dummy\" was updated.\n", nil},183 {"deployments", deployment, "Deployment \"dummy\" was updated.\n", nil},184 {"ingresses", ingress, "Ingress \"dummy\" was updated.\n", nil},185 {"cronjobs", cronjob, "CronJob \"dummy\" was updated.\n", nil},186}187var setImageTests = []struct {188 resource string189 kind string190 out string191 object runtime.Object192}{193 {"cronjobs", cronjobWithAnnotation, "CronJob \"dummy\" was updated.\n", nil},194 {"deployments", deploymentWithAnnotation, "Deployment \"dummy\" was updated.\n", nil},195}196func TestKindService_ApplyKindShouldFailWithErrorDuringDecode(t *testing.T) {197 kindService, _, _ := getKindServiceInterface(loader.Config{})198 var kind = `kind: Pod2199apiVersion: v1200metadata:201 name: dummy`202 assert.EqualError(t, kindService.ApplyKind("foobar", []string{kind}, "foobar"), "no kind \"Pod2\" is registered for version \"v1\"")203}204func TestKindService_ApplyKindShouldFailWithInvalidKind(t *testing.T) {205 kindService, _, _ := getKindServiceInterface(loader.Config{})206 var kind = `kind: Pod207apiVersion: v1208metadata:209 name: dummy`210 assert.EqualError(t, kindService.ApplyKind("foobar", []string{kind}, "foobar"), "kind Pod is not supported")211}212func TestKindService_ApplyKindInsertWithError(t *testing.T) {213 for _, entry := range insertTests {214 config := loader.Config{}215 kindService, _, fakeClientSet := getKindServiceInterface(config)216 fakeClientSet.PrependReactor("get", entry.resource, testingKube.ErrorReturnFunc)217 fakeClientSet.PrependReactor("create", entry.resource, testingKube.ErrorReturnFunc)218 assert.EqualError(t, kindService.ApplyKind("foobar", []string{entry.kind}, "foobar"), "explode", fmt.Sprintf("Test failed for resource %s", entry.resource))219 }220}221func TestKindService_ApplyKindInsert(t *testing.T) {222 for _, entry := range insertTests {223 config := loader.Config{}224 kindService, _, fakeClientSet := getKindServiceInterface(config)225 fakeClientSet.PrependReactor("get", entry.resource, testingKube.ErrorReturnFunc)226 fakeClientSet.PrependReactor("create", entry.resource, testingKube.NilReturnFunc)227 output := captureOutput(func() {228 assert.NoError(t, kindService.ApplyKind("foobar", []string{entry.kind}, "foobar"), fmt.Sprintf("Test failed for resource %s", entry.resource))229 })230 assert.Equal(t, entry.out, output, fmt.Sprintf("Test failed for resource %s", entry.resource))231 }232}233func TestKindService_ApplyKindUpdateWithError(t *testing.T) {234 for _, entry := range upsertTests {235 config := loader.Config{}236 kindService, _, fakeClientSet := getKindServiceInterface(config)237 fakeClientSet.PrependReactor("get", entry.resource, testingKube.GetObjectReturnFunc(entry.object))238 fakeClientSet.PrependReactor("update", entry.resource, testingKube.ErrorReturnFunc)239 assert.EqualError(t, kindService.ApplyKind("foobar", []string{entry.kind}, "foobar"), "explode", fmt.Sprintf("Test failed for resource %s", entry.resource))240 }241}242func TestKindService_ApplyKindUpdate(t *testing.T) {243 for _, entry := range upsertTests {244 config := loader.Config{}245 kindService, _, fakeClientSet := getKindServiceInterface(config)246 fakeClientSet.PrependReactor("get", entry.resource, testingKube.GetObjectReturnFunc(entry.object))247 fakeClientSet.PrependReactor("update", entry.resource, testingKube.NilReturnFunc)248 output := captureOutput(func() {249 assert.NoError(t, kindService.ApplyKind("foobar", []string{entry.kind}, "foobar"), fmt.Sprintf("Test failed for resource %s", entry.resource))250 })251 assert.Equal(t, entry.out, output, fmt.Sprintf("Test failed for resource %s", entry.resource))252 }253}254func TestKindService_ApplyKindUpdateWithContainers(t *testing.T) {255 for _, entry := range setImageTests {256 config := loader.Config{}257 kindService, imageServiceMock, fakeClientSet := getKindServiceInterface(config)258 fakeClientSet.PrependReactor("get", entry.resource, testingKube.GetObjectReturnFunc(entry.object))259 fakeClientSet.PrependReactor("update", entry.resource, testingKube.NilReturnFunc)260 imageServiceMock.On("List", loader.Cleanup{ImagePath: "eu.gcr.io/foobar/app"}).Return(new(model.TagCollection), nil)261 output := captureOutput(func() {262 assert.NoError(t, kindService.ApplyKind("dummy-foobar2", []string{entry.kind}, "foobar"), fmt.Sprintf("Test failed for resource %s", entry.resource))263 })264 assert.Equal(t, entry.out, output, fmt.Sprintf("Test failed for resource %s", entry.resource))265 }266}267func TestKindService_ApplyKindUpdateWithContainersError(t *testing.T) {268 for _, entry := range setImageTests {269 config := loader.Config{}270 kindService, imageServiceMock, _ := getKindServiceInterface(config)271 imageServiceMock.On("List", loader.Cleanup{ImagePath: "eu.gcr.io/foobar/app"}).Return(nil, errors.New("explode"))272 assert.Error(t, kindService.ApplyKind("foobar", []string{entry.kind}, "foobar"), fmt.Sprintf("Test failed for resource %s", entry.resource))273 }274}275func TestKindService_SetImageForContainer(t *testing.T) {276 var dataProvider = []struct {277 namespace string278 tags []string279 imagePath string280 }{281 {"foobar", []string{"staging-foobar-latest", "staging-foobar-3"}, "gcr.io/path/app:staging-foobar-3"},282 {"production", []string{"latest", "prod-3"}, "gcr.io/path/app:prod-3"},283 {"staging", []string{"staging-latest", "staging-3"}, "gcr.io/path/app:staging-3"},284 }285 for _, entry := range dataProvider {286 kindService, imageServiceMock, _ := getKindService(loader.Config{})287 tags := new(model.TagCollection)288 tags.Manifests = map[string]model.Manifest{}289 tags.Manifests["stuff"] = model.Manifest{290 Tags: entry.tags,291 }292 imageServiceMock.On("List", loader.Cleanup{ImagePath: "gcr.io/path/app"}).Return(tags, nil)293 containers := []coreV1.Container{294 {Image: "gcr.io/path/app"},295 }296 kindService.setImageForContainer(map[string]string{"imageUpdateStrategy": "latest-branching"}, containers, entry.namespace)297 assert.Equal(t, entry.imagePath, containers[0].Image)298 }299}300func getKindServiceInterface(config loader.Config) (KindInterface, *mocks.ImagesInterface, *fake.Clientset) {301 imageServiceMock := new(mocks.ImagesInterface)302 fakeClientSet := fake.NewSimpleClientset()303 return NewKind(fakeClientSet, imageServiceMock, config), imageServiceMock, fakeClientSet304}305func getKindService(config loader.Config) (*kindService, *mocks.ImagesInterface, *fake.Clientset) {306 imageServiceMock := new(mocks.ImagesInterface)307 fakeClientSet := fake.NewSimpleClientset()308 k := new(kindService)309 k.clientSet = fakeClientSet310 k.imagesService = imageServiceMock311 k.config = config312 k.usedKind = usedKind{}313 k.decoder = scheme.Codecs.UniversalDeserializer()314 return k, imageServiceMock, fakeClientSet315}316func captureOutput(f func()) string {317 oldWriter := writer318 var buf bytes.Buffer319 defer func() {320 writer = oldWriter321 }()322 writer = &buf323 f()324 return buf.String()325}...

Full Screen

Full Screen

rule_possible_type_extensions_test.go

Source:rule_possible_type_extensions_test.go Github

copy

Full Screen

...114 extend input FooEnum @dummy115 extend scalar FooInputObject @dummy116 `,117 errs: (*graphql.Errors)(nil).118 Add(validation.ExtendingDifferentTypeKindError("FooScalar", "scalar", 0, 0)).119 Add(validation.ExtendingDifferentTypeKindError("FooObject", "object", 0, 0)).120 Add(validation.ExtendingDifferentTypeKindError("FooInterface", "interface", 0, 0)).121 Add(validation.ExtendingDifferentTypeKindError("FooUnion", "union", 0, 0)).122 Add(validation.ExtendingDifferentTypeKindError("FooEnum", "enum", 0, 0)).123 Add(validation.ExtendingDifferentTypeKindError("FooInputObject", "input object", 0, 0)),124 },125 {126 msg: "extending types within existing schema",127 schema: mustBuildSchema(nil, []byte(`128 scalar FooScalar129 type FooObject130 interface FooInterface131 union FooUnion132 enum FooEnum133 input FooInputObject134 `)),135 query: `136 extend scalar FooScalar @dummy137 extend type FooObject @dummy138 extend interface FooInterface @dummy139 extend union FooUnion @dummy140 extend enum FooEnum @dummy141 extend input FooInputObject @dummy142 `,143 },144 {145 msg: "extending unknown types within existing schema",146 schema: mustBuildSchema(nil, []byte(`type Known`)),147 query: `148 extend scalar Unknown @dummy149 extend type Unknown @dummy150 extend interface Unknown @dummy151 extend union Unknown @dummy152 extend enum Unknown @dummy153 extend input Unknown @dummy154 `,155 errs: (*graphql.Errors)(nil).156 Add(validation.ExtendingUnknownTypeError("Unknown", 0, 0)).157 Add(validation.ExtendingUnknownTypeError("Unknown", 0, 0)).158 Add(validation.ExtendingUnknownTypeError("Unknown", 0, 0)).159 Add(validation.ExtendingUnknownTypeError("Unknown", 0, 0)).160 Add(validation.ExtendingUnknownTypeError("Unknown", 0, 0)).161 Add(validation.ExtendingUnknownTypeError("Unknown", 0, 0)),162 },163 {164 msg: "extending types with different kinds within existing schema",165 schema: mustBuildSchema(nil, []byte(`166 scalar FooScalar167 type FooObject168 interface FooInterface169 union FooUnion170 enum FooEnum171 input FooInputObject172 `)),173 query: `174 extend type FooScalar @dummy175 extend interface FooObject @dummy176 extend union FooInterface @dummy177 extend enum FooUnion @dummy178 extend input FooEnum @dummy179 extend scalar FooInputObject @dummy180 `,181 errs: (*graphql.Errors)(nil).182 Add(validation.ExtendingDifferentTypeKindError("FooScalar", "scalar", 0, 0)).183 Add(validation.ExtendingDifferentTypeKindError("FooObject", "object", 0, 0)).184 Add(validation.ExtendingDifferentTypeKindError("FooInterface", "interface", 0, 0)).185 Add(validation.ExtendingDifferentTypeKindError("FooUnion", "union", 0, 0)).186 Add(validation.ExtendingDifferentTypeKindError("FooEnum", "enum", 0, 0)).187 Add(validation.ExtendingDifferentTypeKindError("FooInputObject", "input object", 0, 0)),188 },189 }190 sdlRuleTester(t, tt, rules.PossibleTypeExtensions)191}...

Full Screen

Full Screen

Kind

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 v := reflect.ValueOf(x)4}5import (6func main() {7 v := reflect.ValueOf(x)8}9import (10func main() {11 v := reflect.ValueOf(x)12}13import (14func main() {15 var x complex128 = cmplx.Sqrt(-5 + 12i)16 v := reflect.ValueOf(x)17}

Full Screen

Full Screen

Kind

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main() {3 fmt.Println(d.Kind())4}5import "fmt"6func main() {7 fmt.Println(d.Kind())8}9import "fmt"10func main() {11 fmt.Println(d.Kind())12}13import "fmt"14func main() {15 fmt.Println(d.Kind())16}17import "fmt"18func main() {19 fmt.Println(d.Kind())20}21import "fmt"22func main() {23 fmt.Println(d.Kind())24}25import "fmt"26func main() {27 fmt.Println(d.Kind())28}29import "fmt"30func main() {31 fmt.Println(d.Kind())32}33import "fmt"34func main() {35 fmt.Println(d.Kind())36}37import "fmt"38func main() {39 fmt.Println(d.Kind())40}41import "fmt"42func main() {43 fmt.Println(d.Kind())44}45import "fmt"46func main() {47 fmt.Println(d.Kind())48}49import "fmt"50func main() {

Full Screen

Full Screen

Kind

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 d := dummy{}4 fmt.Println(reflect.TypeOf(d))5 fmt.Println(reflect.TypeOf(d).Kind())6}7import (8func main() {9 d := dummy{}10 fmt.Println(reflect.TypeOf(d).Name())11}12import (13func main() {14 d := dummy{}15 fmt.Println(reflect.TypeOf(d).PkgPath())16}17import (18func main() {19 d := dummy{}20 fmt.Println(reflect.TypeOf(d).Size())21}

Full Screen

Full Screen

Kind

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main() {3 fmt.Println(d.Kind())4}5type dummy struct{}6func (d dummy) Kind() string {7}8The above code will print dummy . The reason is that when we call d.Kind() , the compiler sees that the method Kind is defined on dummy . The compiler then generates the following code for us:9func (d dummy) Kind() string {10}11func main() {12 fmt.Println(d.Kind())13}14The compiler generates the code for us, but the compiler doesn’t know the type of d . So it generates the code for the type dummy , and so the method Kind is defined on dummy . So when we call d.Kind() , the compiler sees that the method Kind is defined on dummy , and so it generates the following code for us:15func (d dummy) Kind() string {16}17func main() {18 fmt.Println(d.Kind())19}20The compiler generates the code for us, but the compiler doesn’t know the type of d . So it generates the code for the type dummy , and so the method Kind is defined on dummy . So when we call d.Kind() , the compiler sees that the method Kind is defined on dummy , and so it generates the following code for us:21func (d dummy) Kind() string {22}23func main() {24 fmt.Println(d.Kind())25}

Full Screen

Full Screen

Kind

Using AI Code Generation

copy

Full Screen

1import (2type dummy struct {3}4func (d *dummy) Kind() string {5}6func main() {7 d := dummy{}8 fmt.Println(d.Kind())9}10Recommended Posts: Go | Kind() Method in reflect package11Go | TypeOf() Method in reflect package12Go | ValueOf() Method in reflect package13Go | NumMethod() Method in reflect package14Go | NumField() Method in reflect pack

Full Screen

Full Screen

Kind

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main() {3 fmt.Println("Kind of d1 is ", d1.Kind())4}5import "fmt"6func main() {7 fmt.Println("Kind of d1 is ", d1.Kind())8}9import "fmt"10func main() {11 fmt.Println("Kind of d1 is ", d1.Kind())12}13import "fmt"14func main() {15 fmt.Println("Kind of d1 is ", d1.Kind())16}17import "fmt"18func main() {19 fmt.Println("Kind of d1 is ", d1.Kind())20}21import "fmt"22func main() {23 fmt.Println("Kind of d1 is ", d1.Kind())24}25import "fmt"26func main() {27 fmt.Println("Kind of d1 is ", d1.Kind())28}29import "fmt"30func main() {31 fmt.Println("Kind of d1 is ", d1.Kind())32}33import "fmt"34func main() {35 fmt.Println("Kind of d1 is ", d1.Kind())36}37import "fmt"38func main() {39 fmt.Println("Kind of d1 is ", d1.Kind())40}41import "fmt"

Full Screen

Full Screen

Kind

Using AI Code Generation

copy

Full Screen

1import "fmt"2type Dummy struct {3}4func (d *Dummy) Kind() string {5}6func main() {7 d := &Dummy{value: 10}8 fmt.Println(d.Kind())9}

Full Screen

Full Screen

Kind

Using AI Code Generation

copy

Full Screen

1import "fmt"2type dummy struct {3}4func main() {5fmt.Println("Type of i is", d.Kind(i))6fmt.Println("Type of f is", d.Kind(f))7fmt.Println("Type of s is", d.Kind(s))8fmt.Println("Type of d is", d.Kind(d))9}10func (d dummy) Kind(i interface{}) string {11switch i.(type) {12}13}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Testkube automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful