staging: fix "go vet" issues

These issues were not found earlier because "make vet" ignored staging. Some of
these fixes are stylistic and/or don't matter in practice, but all of the
loopclosure issues seem to be real: those tests didn't run as intended.

Here's the full error report:

staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_discovery_controller.go:304:11: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersion struct literal uses unkeyed fields (govet)
				gv := schema.GroupVersion{crd.Spec.Group, v.Name}
				      ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/customresource_handler_test.go:790:119: composites: k8s.io/apimachinery/pkg/runtime/serializer/json.SerializerOptions struct literal uses unkeyed fields (govet)
			delegate := serializerjson.NewSerializerWithOptions(serializerjson.DefaultMetaFactory, unstructuredCreator{}, nil, serializerjson.SerializerOptions{tc.yaml, false, tc.strictDecoding})
			                                                                                                                   ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/compilation.go:171:30: composites: k8s.io/apiserver/pkg/cel.Error struct literal uses unkeyed fields (govet)
		compilationResult.Error = &apiservercel.Error{apiservercel.ErrorTypeInvalid, "compilation failed: " + issues.String()}
		                           ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/compilation.go:175:30: composites: k8s.io/apiserver/pkg/cel.Error struct literal uses unkeyed fields (govet)
		compilationResult.Error = &apiservercel.Error{apiservercel.ErrorTypeInvalid, "cel expression must evaluate to a bool"}
		                           ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/compilation.go:182:30: composites: k8s.io/apiserver/pkg/cel.Error struct literal uses unkeyed fields (govet)
		compilationResult.Error = &apiservercel.Error{apiservercel.ErrorTypeInternal, "unexpected compilation error: " + err.Error()}
		                           ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/compilation.go:201:30: composites: k8s.io/apiserver/pkg/cel.Error struct literal uses unkeyed fields (govet)
		compilationResult.Error = &apiservercel.Error{apiservercel.ErrorTypeInvalid, "program instantiation failed: " + err.Error()}
		                           ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/compilation.go:206:30: composites: k8s.io/apiserver/pkg/cel.Error struct literal uses unkeyed fields (govet)
		compilationResult.Error = &apiservercel.Error{apiservercel.ErrorTypeInternal, "cost estimation failed: " + err.Error()}
		                           ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/algorithm_test.go:38:14: composites: k8s.io/apiextensions-apiserver/pkg/apiserver/schema.JSON struct literal uses unkeyed fields (govet)
				Default: structuralschema.JSON{"foo"},
				         ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/algorithm_test.go:44:15: composites: k8s.io/apiextensions-apiserver/pkg/apiserver/schema.JSON struct literal uses unkeyed fields (govet)
					Default: structuralschema.JSON{"foo"},
					         ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/algorithm_test.go:53:17: composites: k8s.io/apiextensions-apiserver/pkg/apiserver/schema.JSON struct literal uses unkeyed fields (govet)
							Default: structuralschema.JSON{"A"},
							         ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/algorithm_test.go:58:17: composites: k8s.io/apiextensions-apiserver/pkg/apiserver/schema.JSON struct literal uses unkeyed fields (govet)
							Default: structuralschema.JSON{"B"},
							         ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/algorithm_test.go:63:17: composites: k8s.io/apiextensions-apiserver/pkg/apiserver/schema.JSON struct literal uses unkeyed fields (govet)
							Default: structuralschema.JSON{"C"},
							         ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/algorithm_test.go:76:19: composites: k8s.io/apiextensions-apiserver/pkg/apiserver/schema.JSON struct literal uses unkeyed fields (govet)
									Default: structuralschema.JSON{"A"},
									         ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/algorithm_test.go:81:19: composites: k8s.io/apiextensions-apiserver/pkg/apiserver/schema.JSON struct literal uses unkeyed fields (govet)
									Default: structuralschema.JSON{"B"},
									         ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/algorithm_test.go:91:18: composites: k8s.io/apiextensions-apiserver/pkg/apiserver/schema.JSON struct literal uses unkeyed fields (govet)
								Default: structuralschema.JSON{"N"},
								         ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/algorithm_test.go:96:18: composites: k8s.io/apiextensions-apiserver/pkg/apiserver/schema.JSON struct literal uses unkeyed fields (govet)
								Default: structuralschema.JSON{"O"},
								         ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/algorithm_test.go:108:21: composites: k8s.io/apiextensions-apiserver/pkg/apiserver/schema.JSON struct literal uses unkeyed fields (govet)
											Default: structuralschema.JSON{"alpha"},
											         ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/algorithm_test.go:113:21: composites: k8s.io/apiextensions-apiserver/pkg/apiserver/schema.JSON struct literal uses unkeyed fields (govet)
											Default: structuralschema.JSON{"beta"},
											         ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/algorithm_test.go:123:16: composites: k8s.io/apiextensions-apiserver/pkg/apiserver/schema.JSON struct literal uses unkeyed fields (govet)
						Default: structuralschema.JSON{"bar"},
						         ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/algorithm_test.go:133:17: composites: k8s.io/apiextensions-apiserver/pkg/apiserver/schema.JSON struct literal uses unkeyed fields (govet)
							Default: structuralschema.JSON{"A"},
							         ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/algorithm_test.go:147:17: composites: k8s.io/apiextensions-apiserver/pkg/apiserver/schema.JSON struct literal uses unkeyed fields (govet)
							Default: structuralschema.JSON{"A"},
							         ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/algorithm_test.go:159:15: composites: k8s.io/apiextensions-apiserver/pkg/apiserver/schema.JSON struct literal uses unkeyed fields (govet)
					Default: structuralschema.JSON{"A"},
					         ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/algorithm_test.go:169:17: composites: k8s.io/apiextensions-apiserver/pkg/apiserver/schema.JSON struct literal uses unkeyed fields (govet)
						Default:  structuralschema.JSON{"A"},
						          ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/algorithm_test.go:179:17: composites: k8s.io/apiextensions-apiserver/pkg/apiserver/schema.JSON struct literal uses unkeyed fields (govet)
						Default:  structuralschema.JSON{"A"},
						          ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/algorithm_test.go:190:18: composites: k8s.io/apiextensions-apiserver/pkg/apiserver/schema.JSON struct literal uses unkeyed fields (govet)
							Default:  structuralschema.JSON{"A"},
							          ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/algorithm_test.go:202:18: composites: k8s.io/apiextensions-apiserver/pkg/apiserver/schema.JSON struct literal uses unkeyed fields (govet)
							Default:  structuralschema.JSON{"A"},
							          ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/prunenulls_test.go:38:14: composites: k8s.io/apiextensions-apiserver/pkg/apiserver/schema.JSON struct literal uses unkeyed fields (govet)
				Default: structuralschema.JSON{"foo"},
				         ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/prunenulls_test.go:47:17: composites: k8s.io/apiextensions-apiserver/pkg/apiserver/schema.JSON struct literal uses unkeyed fields (govet)
							Default: structuralschema.JSON{"A"},
							         ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/defaulting/prunenulls_test.go:57:18: composites: k8s.io/apiextensions-apiserver/pkg/apiserver/schema.JSON struct literal uses unkeyed fields (govet)
							Default:  structuralschema.JSON{"C"},
							          ^
staging/src/k8s.io/apiextensions-apiserver/test/integration/defaulting_test.go:289:38: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionResource struct literal uses unkeyed fields (govet)
	fooClient := dynamicClient.Resource(schema.GroupVersionResource{crd.Spec.Group, crd.Spec.Versions[0].Name, crd.Spec.Names.Plural})
	                                    ^
staging/src/k8s.io/apiextensions-apiserver/test/integration/listtype_test.go:140:38: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionResource struct literal uses unkeyed fields (govet)
	fooClient := dynamicClient.Resource(schema.GroupVersionResource{crd.Spec.Group, crd.Spec.Versions[0].Name, crd.Spec.Names.Plural})
	                                    ^
staging/src/k8s.io/apiextensions-apiserver/test/integration/objectmeta_test.go:453:38: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionResource struct literal uses unkeyed fields (govet)
	fooClient := dynamicClient.Resource(schema.GroupVersionResource{crd.Spec.Group, crd.Spec.Versions[0].Name, crd.Spec.Names.Plural})
	                                    ^
staging/src/k8s.io/apiextensions-apiserver/test/integration/pruning_test.go:214:38: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionResource struct literal uses unkeyed fields (govet)
	fooClient := dynamicClient.Resource(schema.GroupVersionResource{crd.Spec.Group, crd.Spec.Versions[0].Name, crd.Spec.Names.Plural})
	                                    ^
staging/src/k8s.io/apiextensions-apiserver/test/integration/pruning_test.go:266:38: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionResource struct literal uses unkeyed fields (govet)
	fooClient := dynamicClient.Resource(schema.GroupVersionResource{crd.Spec.Group, crd.Spec.Versions[0].Name, crd.Spec.Names.Plural})
	                                    ^
staging/src/k8s.io/apiextensions-apiserver/test/integration/pruning_test.go:377:38: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionResource struct literal uses unkeyed fields (govet)
	fooClient := dynamicClient.Resource(schema.GroupVersionResource{crd.Spec.Group, crd.Spec.Versions[0].Name, crd.Spec.Names.Plural})
	                                    ^
staging/src/k8s.io/apiextensions-apiserver/test/integration/pruning_test.go:418:38: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionResource struct literal uses unkeyed fields (govet)
	fooClient := dynamicClient.Resource(schema.GroupVersionResource{crd.Spec.Group, crd.Spec.Versions[0].Name, crd.Spec.Names.Plural})
	                                    ^
staging/src/k8s.io/apiextensions-apiserver/test/integration/pruning_test.go:471:38: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionResource struct literal uses unkeyed fields (govet)
	fooClient := dynamicClient.Resource(schema.GroupVersionResource{crd.Spec.Group, crd.Spec.Versions[0].Name, crd.Spec.Names.Plural})
	                                    ^
staging/src/k8s.io/apiextensions-apiserver/test/integration/pruning_test.go:556:38: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionResource struct literal uses unkeyed fields (govet)
	fooClient := dynamicClient.Resource(schema.GroupVersionResource{crd.Spec.Group, crd.Spec.Versions[0].Name, crd.Spec.Names.Plural})
	                                    ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/celcoststability_test.go:1096:32: loopclosure: loop variable validRule captured by func literal (govet)
					s := withRule(*tt.schema, validRule)
					                          ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/celcoststability_test.go:1107:19: loopclosure: loop variable expectedCost captured by func literal (govet)
					if rtCost != expectedCost {
					             ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/celcoststability_test.go:1108:83: loopclosure: loop variable expectedCost captured by func literal (govet)
						t.Fatalf("runtime cost %d does not match expected runtime cost %d", rtCost, expectedCost)
						                                                                            ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/validation_test.go:2009:30: loopclosure: loop variable tt captured by func literal (govet)
			celValidator := validator(tt.schema, true, model.SchemaDeclType(tt.schema, true), PerCallLimit)
			                          ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/validation_test.go:2013:65: loopclosure: loop variable tt captured by func literal (govet)
			errs, _ := celValidator.Validate(ctx, field.NewPath("root"), tt.schema, tt.obj, tt.oldObj, math.MaxInt)
			                                                             ^
staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/validation_test.go:2015:22: loopclosure: loop variable tt captured by func literal (govet)
			for _, e := range tt.errors {
			                  ^
staging/src/k8s.io/apimachinery/pkg/runtime/mapper_test.go:28:67: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionResource struct literal uses unkeyed fields (govet)
	gvr := func(g, v, r string) schema.GroupVersionResource { return schema.GroupVersionResource{g, v, r} }
	                                                                 ^
staging/src/k8s.io/apimachinery/pkg/runtime/mapper_test.go:30:63: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
	gvk := func(g, v, k string) schema.GroupVersionKind { return schema.GroupVersionKind{g, v, k} }
	                                                             ^
staging/src/k8s.io/apimachinery/pkg/runtime/serializer/versioning/versioning.go:150:35: composites: k8s.io/apimachinery/pkg/runtime.WithoutVersionDecoder struct literal uses unkeyed fields (govet)
		if err := d.DecodeNestedObjects(runtime.WithoutVersionDecoder{c.decoder}); err != nil {
		                                ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/predicates/namespace/matcher.go:119:18: composites: k8s.io/apimachinery/pkg/api/errors.StatusError struct literal uses unkeyed fields (govet)
		return false, &apierrors.StatusError{status.Status()}
		               ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/webhook/testing/testcase.go:300:17: composites: k8s.io/api/admissionregistration/v1.MutatingWebhook struct literal uses unkeyed fields (govet)
		mutating[i] = registrationv1.MutatingWebhook{h.Name, h.ClientConfig, h.Rules, h.FailurePolicy, h.MatchPolicy, h.NamespaceSelector, h.ObjectSelector, h.SideEffects, h.TimeoutSeconds, h.AdmissionReviewVersions, nil}
		              ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:70:25: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionResource struct literal uses unkeyed fields (govet)
	mapper.RegisterKindFor(schema.GroupVersionResource{"extensions", "v1beta1", "deployments"}, "", schema.GroupVersionKind{"extensions", "v1beta1", "Deployment"})
	                       ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:71:25: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionResource struct literal uses unkeyed fields (govet)
	mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1", "deployments"}, "", schema.GroupVersionKind{"apps", "v1", "Deployment"})
	                       ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:72:25: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionResource struct literal uses unkeyed fields (govet)
	mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta1", "deployments"}, "", schema.GroupVersionKind{"apps", "v1beta1", "Deployment"})
	                       ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:73:25: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionResource struct literal uses unkeyed fields (govet)
	mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1alpha1", "deployments"}, "", schema.GroupVersionKind{"apps", "v1alpha1", "Deployment"})
	                       ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:75:25: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionResource struct literal uses unkeyed fields (govet)
	mapper.RegisterKindFor(schema.GroupVersionResource{"extensions", "v1beta1", "deployments"}, "scale", schema.GroupVersionKind{"extensions", "v1beta1", "Scale"})
	                       ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:76:25: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionResource struct literal uses unkeyed fields (govet)
	mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1", "deployments"}, "scale", schema.GroupVersionKind{"autoscaling", "v1", "Scale"})
	                       ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:77:25: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionResource struct literal uses unkeyed fields (govet)
	mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta1", "deployments"}, "scale", schema.GroupVersionKind{"apps", "v1beta1", "Scale"})
	                       ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:78:25: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionResource struct literal uses unkeyed fields (govet)
	mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1alpha1", "deployments"}, "scale", schema.GroupVersionKind{"apps", "v1alpha1", "Scale"})
	                       ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:81:25: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionResource struct literal uses unkeyed fields (govet)
	mapper.RegisterKindFor(schema.GroupVersionResource{"example.com", "v1", "widgets"}, "", schema.GroupVersionKind{"", "", ""})
	                       ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:82:25: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionResource struct literal uses unkeyed fields (govet)
	mapper.RegisterKindFor(schema.GroupVersionResource{"example.com", "v2", "widgets"}, "", schema.GroupVersionKind{"", "", ""})
	                       ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go💯59: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			attrs:         admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"apps", "v1", "Deployment"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil),
			                                                       ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:114:61: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			attrs:           admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"apps", "v1", "Deployment"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil),
			                                                         ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:116:22: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			expectMatchKind: &schema.GroupVersionKind{"apps", "v1", "Deployment"},
			                  ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:139:61: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			attrs:           admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"apps", "v1", "Deployment"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil),
			                                                         ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:141:22: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			expectMatchKind: &schema.GroupVersionKind{"apps", "v1", "Deployment"},
			                  ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:159:59: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			attrs:         admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"apps", "v1", "Deployment"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil),
			                                                       ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:179:59: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			attrs:         admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"apps", "v1", "Deployment"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil),
			                                                       ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:199:61: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			attrs:           admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"apps", "v1", "Deployment"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil),
			                                                         ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:201:22: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			expectMatchKind: &schema.GroupVersionKind{"extensions", "v1beta1", "Deployment"},
			                  ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:220:61: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			attrs:           admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"apps", "v1", "Deployment"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil),
			                                                         ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:222:22: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			expectMatchKind: &schema.GroupVersionKind{"apps", "v1beta1", "Deployment"},
			                  ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:246:61: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			attrs:           admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "scale", admission.Create, &metav1.CreateOptions{}, false, nil),
			                                                         ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:248:22: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			expectMatchKind: &schema.GroupVersionKind{"autoscaling", "v1", "Scale"},
			                  ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:266:59: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			attrs:         admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "scale", admission.Create, &metav1.CreateOptions{}, false, nil),
			                                                       ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:286:59: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			attrs:         admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "scale", admission.Create, &metav1.CreateOptions{}, false, nil),
			                                                       ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:306:61: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			attrs:           admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "scale", admission.Create, &metav1.CreateOptions{}, false, nil),
			                                                         ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:308:22: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			expectMatchKind: &schema.GroupVersionKind{"extensions", "v1beta1", "Scale"},
			                  ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:327:61: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			attrs:           admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "scale", admission.Create, &metav1.CreateOptions{}, false, nil),
			                                                         ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:329:22: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			expectMatchKind: &schema.GroupVersionKind{"apps", "v1beta1", "Scale"},
			                  ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:343:61: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			attrs:           admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil),
			                                                         ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:345:22: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			expectMatchKind: &schema.GroupVersionKind{"autoscaling", "v1", "Scale"},
			                  ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:359:59: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			attrs:         admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil),
			                                                       ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:375:61: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			attrs:           admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"extensions", "v1beta1", "deployments"}, "scale", admission.Create, &metav1.CreateOptions{}, false, nil),
			                                                         ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:377:22: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			expectMatchKind: &schema.GroupVersionKind{"autoscaling", "v1", "Scale"},
			                  ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:392:59: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			attrs:         admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"extensions", "v1beta1", "deployments"}, "scale", admission.Create, &metav1.CreateOptions{}, false, nil),
			                                                       ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:413:61: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			attrs:           admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil),
			                                                         ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:415:22: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			expectMatchKind: &schema.GroupVersionKind{"autoscaling", "v1", "Scale"},
			                  ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:435:59: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			attrs:         admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"extensions", "v1beta1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil),
			                                                       ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:450:59: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			attrs:         admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil),
			                                                       ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:460:59: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			attrs:         admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil),
			                                                       ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:475:70: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			attrs:         admission.NewAttributesRecord(&example.Pod{}, nil, schema.GroupVersionKind{"example.apiserver.k8s.io", "v1", "Pod"}, "ns", "name", schema.GroupVersionResource{"example.apiserver.k8s.io", "v1", "pods"}, "", admission.Create, &metav1.CreateOptions{}, false, nil),
			                                                                  ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:491:70: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			attrs:         admission.NewAttributesRecord(&example.Pod{}, nil, schema.GroupVersionKind{"example.apiserver.k8s.io", "v1", "Pod"}, "ns", "name", schema.GroupVersionResource{"example.apiserver.k8s.io", "v1", "pods"}, "", admission.Create, &metav1.CreateOptions{}, false, nil),
			                                                                  ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:507:70: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			attrs:         admission.NewAttributesRecord(&example.Pod{}, nil, schema.GroupVersionKind{"example.apiserver.k8s.io", "v1", "Pod"}, "ns", "name", schema.GroupVersionResource{"example.apiserver.k8s.io", "v1", "pods"}, "", admission.Create, &metav1.CreateOptions{}, false, nil),
			                                                                  ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:523:70: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			attrs:         admission.NewAttributesRecord(&example.Pod{}, nil, schema.GroupVersionKind{"example.apiserver.k8s.io", "v1", "Pod"}, "ns", "name", schema.GroupVersionResource{"example.apiserver.k8s.io", "v1", "pods"}, "", admission.Create, &metav1.CreateOptions{}, false, nil),
			                                                                  ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:591:25: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionResource struct literal uses unkeyed fields (govet)
	mapper.RegisterKindFor(schema.GroupVersionResource{"extensions", "v1beta1", "deployments"}, "", schema.GroupVersionKind{"extensions", "v1beta1", "Deployment"})
	                       ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:592:25: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionResource struct literal uses unkeyed fields (govet)
	mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1", "deployments"}, "", schema.GroupVersionKind{"apps", "v1", "Deployment"})
	                       ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:593:25: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionResource struct literal uses unkeyed fields (govet)
	mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta1", "deployments"}, "", schema.GroupVersionKind{"apps", "v1beta1", "Deployment"})
	                       ^
staging/src/k8s.io/apiserver/pkg/admission/plugin/validatingadmissionpolicy/matching/matching_test.go:594:25: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionResource struct literal uses unkeyed fields (govet)
	mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1alpha1", "deployments"}, "", schema.GroupVersionKind{"apps", "v1alpha1", "Deployment"})
	                       ^
staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/leaselock.go:120:19: composites: k8s.io/apimachinery/pkg/apis/meta/v1.Time struct literal uses unkeyed fields (govet)
		r.AcquireTime = metav1.Time{spec.AcquireTime.Time}
		                ^
staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/leaselock.go:123:17: composites: k8s.io/apimachinery/pkg/apis/meta/v1.Time struct literal uses unkeyed fields (govet)
		r.RenewTime = metav1.Time{spec.RenewTime.Time}
		              ^
staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/leaselock.go:135:26: composites: k8s.io/apimachinery/pkg/apis/meta/v1.MicroTime struct literal uses unkeyed fields (govet)
		AcquireTime:          &metav1.MicroTime{ler.AcquireTime.Time},
		                       ^
staging/src/k8s.io/client-go/tools/leaderelection/resourcelock/leaselock.go:136:26: composites: k8s.io/apimachinery/pkg/apis/meta/v1.MicroTime struct literal uses unkeyed fields (govet)
		RenewTime:            &metav1.MicroTime{ler.RenewTime.Time},
		                       ^
staging/src/k8s.io/client-go/plugin/pkg/client/auth/exec/exec_test.go:1088:28: composites: k8s.io/apimachinery/pkg/apis/meta/v1.Time struct literal uses unkeyed fields (govet)
			ExpirationTimestamp:   &v1.Time{now.Add(time.Hour)},
			                        ^
staging/src/k8s.io/client-go/plugin/pkg/client/auth/exec/exec_test.go:1100:28: composites: k8s.io/apimachinery/pkg/apis/meta/v1.Time struct literal uses unkeyed fields (govet)
			ExpirationTimestamp:   &v1.Time{now.Add(time.Hour)},
			                        ^
staging/src/k8s.io/client-go/plugin/pkg/client/auth/exec/exec_test.go:1110:28: composites: k8s.io/apimachinery/pkg/apis/meta/v1.Time struct literal uses unkeyed fields (govet)
			ExpirationTimestamp:   &v1.Time{now.Add(time.Hour)},
			                        ^
staging/src/k8s.io/client-go/tools/events/event_recorder.go:44:15: composites: k8s.io/apimachinery/pkg/apis/meta/v1.MicroTime struct literal uses unkeyed fields (govet)
	timestamp := metav1.MicroTime{time.Now()}
	             ^
staging/src/k8s.io/client-go/tools/events/eventseries_test.go:95:24: composites: k8s.io/apimachinery/pkg/apis/meta/v1.MicroTime struct literal uses unkeyed fields (govet)
		EventTime:           metav1.MicroTime{time.Now()},
		                     ^
staging/src/k8s.io/client-go/tools/events/eventseries_test.go:299:56: composites: k8s.io/apimachinery/pkg/apis/meta/v1.MicroTime struct literal uses unkeyed fields (govet)
	cachedEvent := recorder.makeEvent(regarding, related, metav1.MicroTime{time.Now()}, v1.EventTypeNormal, "test", "some verbose message: 1", "eventTest", "eventTest-"+hostname, "started")
	                                                      ^
staging/src/k8s.io/client-go/tools/events/eventseries_test.go:385:57: composites: k8s.io/apimachinery/pkg/apis/meta/v1.MicroTime struct literal uses unkeyed fields (govet)
		cachedEvent := recorder.makeEvent(regarding, related, metav1.MicroTime{time.Now()}, v1.EventTypeNormal, "test", "some verbose message: 1", "eventTest", "eventTest-"+hostname, "started")
		                                                      ^
staging/src/k8s.io/client-go/tools/leaderelection/leaderelection_test.go:365:26: composites: k8s.io/apimachinery/pkg/apis/meta/v1.MicroTime struct literal uses unkeyed fields (govet)
		AcquireTime:          &metav1.MicroTime{time.Now()},
		                       ^
staging/src/k8s.io/client-go/tools/leaderelection/leaderelection_test.go:366:26: composites: k8s.io/apimachinery/pkg/apis/meta/v1.MicroTime struct literal uses unkeyed fields (govet)
		RenewTime:            &metav1.MicroTime{time.Now()},
		                       ^
staging/src/k8s.io/client-go/tools/auth/exec/types_test.go:40:53: loopclosure: loop variable cluster captured by func literal (govet)
			testClientAuthenticationClusterTypesAreSynced(t, cluster)
			                                                 ^
staging/src/k8s.io/cli-runtime/pkg/resource/scheme_test.go:44:16: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			expectGVK: &schema.GroupVersionKind{"", "v1", "Status"},
			            ^
staging/src/k8s.io/cli-runtime/pkg/resource/scheme_test.go:50:16: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			expectGVK: &schema.GroupVersionKind{"meta.k8s.io", "v1", "Status"},
			            ^
staging/src/k8s.io/cli-runtime/pkg/resource/scheme_test.go:56:16: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			expectGVK: &schema.GroupVersionKind{"example.com", "v1", "Status"},
			            ^
staging/src/k8s.io/cli-runtime/pkg/resource/scheme_test.go:62:16: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
			expectGVK: &schema.GroupVersionKind{"example.com", "v1", "Foo"},
			            ^
staging/src/k8s.io/cli-runtime/pkg/resource/builder_example_test.go:77:1: tests: ExampleLocalBuilder refers to unknown identifier: LocalBuilder (govet)
func ExampleLocalBuilder() {
^
staging/src/k8s.io/component-base/metrics/desc_test.go:159:26: copylocks: call of reflect.DeepEqual copies lock value: k8s.io/component-base/metrics.Desc contains sync.RWMutex (govet)
			if !reflect.DeepEqual(*descA, *descB) {
			                      ^
staging/src/k8s.io/component-base/logs/json/json_benchmark_test.go:46:6: structtag: struct field secret has json tag but is not exported (govet)
					secret  string `json:"secret"`
					^
staging/src/k8s.io/component-base/logs/json/json_benchmark_test.go:76:6: structtag: struct field secret has json tag but is not exported (govet)
					secret  string `json:"secret"`
					^
staging/src/k8s.io/component-base/logs/json/json_benchmark_test.go:105:6: structtag: struct field secret has json tag but is not exported (govet)
					secret  string `json:"secret"`
					^
staging/src/k8s.io/csi-translation-lib/plugins/vsphere_volume_test.go:31:26: composites: k8s.io/api/core/v1.TopologySelectorTerm struct literal uses unkeyed fields (govet)
	topologySelectorTerm := v1.TopologySelectorTerm{[]v1.TopologySelectorLabelRequirement{
	                        ^
staging/src/k8s.io/csi-translation-lib/plugins/vsphere_volume_test.go:37:40: composites: k8s.io/api/core/v1.TopologySelectorTerm struct literal uses unkeyed fields (govet)
	topologySelectorTermWithBetaLabels := v1.TopologySelectorTerm{[]v1.TopologySelectorLabelRequirement{
	                                      ^
staging/src/k8s.io/csi-translation-lib/plugins/vsphere_volume_test.go:43:34: composites: k8s.io/api/core/v1.TopologySelectorTerm struct literal uses unkeyed fields (govet)
	expectedTopologySelectorTerm := v1.TopologySelectorTerm{[]v1.TopologySelectorLabelRequirement{
	                                ^
staging/src/k8s.io/kms/pkg/hierarchy/hierarchy_test.go:506:5: testinggoroutine: call to (*T).Fatalf from a non-test goroutine (govet)
				t.Fatalf("Encrypt() error = %v", err)
				^
staging/src/k8s.io/kms/pkg/hierarchy/hierarchy_test.go:509:5: testinggoroutine: call to (*T).Fatalf from a non-test goroutine (govet)
				t.Fatalf("Encrypt() annotations = %v, want %v", resp.Annotations, encLocalKEK)
				^
staging/src/k8s.io/kms/pkg/hierarchy/hierarchy_test.go:539:5: testinggoroutine: call to (*T).Fatalf from a non-test goroutine (govet)
				t.Fatalf("Encrypt() error = %v", err)
				^
staging/src/k8s.io/kms/pkg/hierarchy/hierarchy_test.go:542:5: testinggoroutine: call to (*T).Fatalf from a non-test goroutine (govet)
				t.Fatalf("Encrypt() annotations = %v, want %v", resp.Annotations, lk.encKEK)
				^
staging/src/k8s.io/kms/pkg/hierarchy/hierarchy_test.go:589:5: testinggoroutine: call to (*T).Fatalf from a non-test goroutine (govet)
				t.Fatalf("Encrypt() error = %v", err)
				^
staging/src/k8s.io/kms/pkg/hierarchy/hierarchy_test.go:592:5: testinggoroutine: call to (*T).Fatalf from a non-test goroutine (govet)
				t.Fatalf("Encrypt() annotations = %v, want %v", resp.Annotations, encLocalKEK)
				^
staging/src/k8s.io/kms/pkg/hierarchy/hierarchy_test.go:627:5: testinggoroutine: call to (*T).Fatalf from a non-test goroutine (govet)
				t.Fatalf("Encrypt() error = %v", err)
				^
staging/src/k8s.io/kms/pkg/hierarchy/hierarchy_test.go:630:5: testinggoroutine: call to (*T).Fatalf from a non-test goroutine (govet)
				t.Fatalf("Encrypt() annotations = %v, want %v", resp.Annotations, lk.encKEK)
				^
staging/src/k8s.io/kms/pkg/hierarchy/hierarchy_test.go:677:5: testinggoroutine: call to (*T).Fatalf from a non-test goroutine (govet)
				t.Fatalf("Encrypt() error = %v", err)
				^
staging/src/k8s.io/kms/pkg/hierarchy/hierarchy_test.go:680:5: testinggoroutine: call to (*T).Fatalf from a non-test goroutine (govet)
				t.Fatalf("Encrypt() annotations = %v, want %v", resp.Annotations, encLocalKEK)
				^
staging/src/k8s.io/kms/pkg/hierarchy/hierarchy_test.go:717:5: testinggoroutine: call to (*T).Fatalf from a non-test goroutine (govet)
				t.Fatalf("Encrypt() error = %v", err)
				^
staging/src/k8s.io/kms/pkg/hierarchy/hierarchy_test.go:720:5: testinggoroutine: call to (*T).Fatalf from a non-test goroutine (govet)
				t.Fatalf("Encrypt() annotations = %v, want %v", resp.Annotations, lk.encKEK)
				^
staging/src/k8s.io/kubectl/pkg/cmd/debug/debug_test.go:451:25: composites: k8s.io/apimachinery/pkg/apis/meta/v1.Time struct literal uses unkeyed fields (govet)
					CreationTimestamp: metav1.Time{time.Now()},
					                   ^
staging/src/k8s.io/kubectl/pkg/cmd/util/helpers_test.go:341:5: composites: k8s.io/apimachinery/pkg/api/errors.StatusError struct literal uses unkeyed fields (govet)
			&errors.StatusError{metav1.Status{
			 ^
staging/src/k8s.io/kubectl/pkg/cmd/util/helpers_test.go:352:5: composites: k8s.io/apimachinery/pkg/api/errors.StatusError struct literal uses unkeyed fields (govet)
			&errors.StatusError{metav1.Status{
			 ^
staging/src/k8s.io/kubectl/pkg/cmd/util/helpers_test.go:364:5: composites: k8s.io/apimachinery/pkg/api/errors.StatusError struct literal uses unkeyed fields (govet)
			&errors.StatusError{metav1.Status{
			 ^
staging/src/k8s.io/kubectl/pkg/cmd/util/helpers_test.go:374:5: composites: k8s.io/apimachinery/pkg/api/errors.StatusError struct literal uses unkeyed fields (govet)
			&errors.StatusError{metav1.Status{
			 ^
staging/src/k8s.io/kubectl/pkg/cmd/util/helpers_test.go:385:50: composites: k8s.io/apimachinery/pkg/api/errors.StatusError struct literal uses unkeyed fields (govet)
			AddSourceToErr("creating", "configmap.yaml", &errors.StatusError{metav1.Status{
			                                              ^
staging/src/k8s.io/kubectl/pkg/cmd/util/helpers_test.go:395:5: composites: k8s.io/apimachinery/pkg/api/errors.StatusError struct literal uses unkeyed fields (govet)
			&errors.StatusError{metav1.Status{
			 ^
staging/src/k8s.io/kubectl/pkg/explain/v2/funcs_test.go:204:15: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
				"needle": schema.GroupVersionKind{"testgroup.k8s.io", "v1", "Kind"},
				          ^
staging/src/k8s.io/kubectl/pkg/explain/v2/funcs_test.go:206:6: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
					{"randomgroup.k8s.io", "v1", "OtherKind"},
					^
staging/src/k8s.io/kubectl/pkg/explain/v2/funcs_test.go:207:6: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
					{"testgroup.k8s.io", "v1", "OtherKind"},
					^
staging/src/k8s.io/kubectl/pkg/explain/v2/funcs_test.go:208:6: composites: k8s.io/apimachinery/pkg/runtime/schema.GroupVersionKind struct literal uses unkeyed fields (govet)
					{"testgroup.k8s.io", "v1", "Kind"},
					^
staging/src/k8s.io/kubectl/pkg/polymorphichelpers/history_test.go:95:46: composites: k8s.io/apimachinery/pkg/apis/meta/v1.OwnerReference struct literal uses unkeyed fields (govet)
				OwnerReferences: []metav1.OwnerReference{{"apps/v1", "Deployment", deployment.Name, deployment.UID, &trueVar, nil}},
				                                         ^
staging/src/k8s.io/kubectl/pkg/polymorphichelpers/history_test.go:222:46: composites: k8s.io/apimachinery/pkg/apis/meta/v1.OwnerReference struct literal uses unkeyed fields (govet)
				OwnerReferences: []metav1.OwnerReference{{"apps/v1", "StatefulSet", "moons", "1993", &trueVar, nil}},
				                                         ^
staging/src/k8s.io/kubectl/pkg/polymorphichelpers/history_test.go:326:46: composites: k8s.io/apimachinery/pkg/apis/meta/v1.OwnerReference struct literal uses unkeyed fields (govet)
				OwnerReferences: []metav1.OwnerReference{{"apps/v1", "DaemonSet", "moons", "1993", &trueVar, nil}},
				                                         ^
staging/src/k8s.io/kubectl/pkg/util/i18n/i18n_test.go:143:31: loopclosure: loop variable envVar captured by func literal (govet)
					defer func() { os.Setenv(envVar, envVarValue) }()
					                         ^
staging/src/k8s.io/legacy-cloud-providers/aws/aws_assumerole_provider_test.go:95:9: copylocks: range var tt copies lock: struct{name string; fields k8s.io/legacy-cloud-providers/aws.fields; want github.com/aws/aws-sdk-go/aws/credentials.Value; wantProviderCalled bool; sleepBeforeCallingProvider time.Duration; wantErr bool; wantErrString string} contains k8s.io/legacy-cloud-providers/aws.fields contains sync.RWMutex (govet)
	for _, tt := range tests {
	       ^
staging/src/k8s.io/legacy-cloud-providers/vsphere/nodemanager.go:190:5: lostcancel: the cancel function is not used on all paths (possible context leak) (govet)
				ctx, cancel := context.WithCancel(context.Background())
				^
staging/src/k8s.io/legacy-cloud-providers/vsphere/nodemanager.go:236:3: lostcancel: this return statement may be reached without using the cancel var defined on line 190 (govet)
		}()
		^
staging/src/k8s.io/pod-security-admission/policy/registry_test.go:152:35: composites: k8s.io/pod-security-admission/api.LevelVersion struct literal uses unkeyed fields (govet)
		results := registry.EvaluatePod(api.LevelVersion{tc.level, versionOrPanic(tc.version)}, nil, nil)
		                                ^
staging/src/k8s.io/sample-apiserver/pkg/registry/wardle/fischer/etcd.go:50:10: composites: k8s.io/sample-apiserver/pkg/registry.REST struct literal uses unkeyed fields (govet)
	return &registry.REST{store}, nil
	        ^
staging/src/k8s.io/sample-apiserver/pkg/registry/wardle/flunder/etcd.go:50:10: composites: k8s.io/sample-apiserver/pkg/registry.REST struct literal uses unkeyed fields (govet)
	return &registry.REST{store}, nil
	        ^
This commit is contained in:
Patrick Ohly 2023-02-28 21:22:40 +01:00
parent a023a5eb17
commit a58eb1b3da
61 changed files with 446 additions and 406 deletions

View File

@ -22,6 +22,7 @@ linters:
enable: # please keep this alphabetized enable: # please keep this alphabetized
- ginkgolinter - ginkgolinter
- gocritic - gocritic
- govet
- ineffassign - ineffassign
- logcheck - logcheck
- staticcheck - staticcheck

View File

@ -19,26 +19,7 @@ set -o nounset
set -o pipefail set -o pipefail
KUBE_ROOT=$(dirname "${BASH_SOURCE[0]}")/../.. KUBE_ROOT=$(dirname "${BASH_SOURCE[0]}")/../..
source "${KUBE_ROOT}/hack/lib/init.sh"
cd "${KUBE_ROOT}" # Ignore the usual golangci.yaml config because it would
# enable additional linters, then enable just "go vet".
# Filter out arguments that start with "-" and move them to goflags. "${KUBE_ROOT}/hack/verify-golangci-lint.sh" -c none -- --disable-all --enable=govet "$@"
targets=()
goflags=()
for arg; do
if [[ "${arg}" == -* ]]; then
goflags+=("${arg}")
else
targets+=("${arg}")
fi
done
if [[ ${#targets[@]} -eq 0 ]]; then
# Do not run on third_party directories or generated client code or build tools.
while IFS='' read -r line; do
targets+=("${line}")
done < <(go list -e ./... | grep -E -v "/(build|third_party|vendor|staging|clientset_generated|hack)/")
fi
go vet "${goflags[@]:+${goflags[@]}}" "${targets[@]}"

View File

@ -39,4 +39,10 @@ popd >/dev/null
LEVEE_BIN="$(which levee)" LEVEE_BIN="$(which levee)"
CONFIG_FILE="${KUBE_ROOT}/hack/testdata/levee/levee-config.yaml" CONFIG_FILE="${KUBE_ROOT}/hack/testdata/levee/levee-config.yaml"
"${KUBE_ROOT}"/hack/verify-govet.sh -vettool="${LEVEE_BIN}" -config="${CONFIG_FILE}" # Do not run on third_party directories or generated client code or build tools.
targets=()
while IFS='' read -r line; do
targets+=("${line}")
done < <(go list -e ./... | grep -E -v "/(build|third_party|vendor|staging|clientset_generated|hack)/")
go vet -vettool="${LEVEE_BIN}" -config="${CONFIG_FILE}" "${targets[@]}"

View File

@ -1,41 +0,0 @@
#!/usr/bin/env bash
# Copyright 2016 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This script vets all *.go files by running `go vet`. It is equivalent to
# `make vet`.
# Usage: `hack/verify-govet.sh` or `make vet`.
# Note: This script is a vestigial redirection. Please do not add "real" logic.
set -o errexit
set -o nounset
set -o pipefail
KUBE_ROOT=$(dirname "${BASH_SOURCE[0]}")/..
# For help output
ARGHELP=""
if [[ "$#" -gt 0 ]]; then
ARGHELP="WHAT='$*'"
fi
echo "NOTE: $0 has been replaced by 'make vet'"
echo
echo "The equivalent of this invocation is: "
echo " make vet ${ARGHELP}"
echo
echo
make --no-print-directory -C "${KUBE_ROOT}" vet WHAT="$*"

View File

@ -301,7 +301,7 @@ func (c *DiscoveryController) Run(stopCh <-chan struct{}, synchedCh chan<- struc
} }
for _, crd := range crds { for _, crd := range crds {
for _, v := range crd.Spec.Versions { for _, v := range crd.Spec.Versions {
gv := schema.GroupVersion{crd.Spec.Group, v.Name} gv := schema.GroupVersion{Group: crd.Spec.Group, Version: v.Name}
if err := c.sync(gv); err != nil { if err := c.sync(gv); err != nil {
utilruntime.HandleError(fmt.Errorf("failed to initially sync CRD version %v: %v", gv, err)) utilruntime.HandleError(fmt.Errorf("failed to initially sync CRD version %v: %v", gv, err))
return false, nil return false, nil

View File

@ -787,7 +787,7 @@ unknown: foo`
t.Fatal(err) t.Fatal(err)
} }
structuralSchemas[v] = structuralSchema structuralSchemas[v] = structuralSchema
delegate := serializerjson.NewSerializerWithOptions(serializerjson.DefaultMetaFactory, unstructuredCreator{}, nil, serializerjson.SerializerOptions{tc.yaml, false, tc.strictDecoding}) delegate := serializerjson.NewSerializerWithOptions(serializerjson.DefaultMetaFactory, unstructuredCreator{}, nil, serializerjson.SerializerOptions{Yaml: tc.yaml, Strict: tc.strictDecoding})
decoder := &schemaCoercingDecoder{ decoder := &schemaCoercingDecoder{
delegate: delegate, delegate: delegate,
validator: unstructuredSchemaCoercer{ validator: unstructuredSchemaCoercer{

View File

@ -1087,6 +1087,8 @@ func TestCelCostStability(t *testing.T) {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
t.Parallel() t.Parallel()
for validRule, expectedCost := range tt.expectCost { for validRule, expectedCost := range tt.expectCost {
validRule := validRule
expectedCost := expectedCost
testName := validRule testName := validRule
if len(testName) > 127 { if len(testName) > 127 {
testName = testName[:127] testName = testName[:127]

View File

@ -168,18 +168,18 @@ func compileRule(rule apiextensions.ValidationRule, env *cel.Env, perCallLimit u
} }
ast, issues := env.Compile(rule.Rule) ast, issues := env.Compile(rule.Rule)
if issues != nil { if issues != nil {
compilationResult.Error = &apiservercel.Error{apiservercel.ErrorTypeInvalid, "compilation failed: " + issues.String()} compilationResult.Error = &apiservercel.Error{Type: apiservercel.ErrorTypeInvalid, Detail: "compilation failed: " + issues.String()}
return return
} }
if ast.OutputType() != cel.BoolType { if ast.OutputType() != cel.BoolType {
compilationResult.Error = &apiservercel.Error{apiservercel.ErrorTypeInvalid, "cel expression must evaluate to a bool"} compilationResult.Error = &apiservercel.Error{Type: apiservercel.ErrorTypeInvalid, Detail: "cel expression must evaluate to a bool"}
return return
} }
checkedExpr, err := cel.AstToCheckedExpr(ast) checkedExpr, err := cel.AstToCheckedExpr(ast)
if err != nil { if err != nil {
// should be impossible since env.Compile returned no issues // should be impossible since env.Compile returned no issues
compilationResult.Error = &apiservercel.Error{apiservercel.ErrorTypeInternal, "unexpected compilation error: " + err.Error()} compilationResult.Error = &apiservercel.Error{Type: apiservercel.ErrorTypeInternal, Detail: "unexpected compilation error: " + err.Error()}
return return
} }
for _, ref := range checkedExpr.ReferenceMap { for _, ref := range checkedExpr.ReferenceMap {
@ -198,12 +198,12 @@ func compileRule(rule apiextensions.ValidationRule, env *cel.Env, perCallLimit u
cel.InterruptCheckFrequency(checkFrequency), cel.InterruptCheckFrequency(checkFrequency),
) )
if err != nil { if err != nil {
compilationResult.Error = &apiservercel.Error{apiservercel.ErrorTypeInvalid, "program instantiation failed: " + err.Error()} compilationResult.Error = &apiservercel.Error{Type: apiservercel.ErrorTypeInvalid, Detail: "program instantiation failed: " + err.Error()}
return return
} }
costEst, err := env.EstimateCost(ast, estimator) costEst, err := env.EstimateCost(ast, estimator)
if err != nil { if err != nil {
compilationResult.Error = &apiservercel.Error{apiservercel.ErrorTypeInternal, "cost estimation failed: " + err.Error()} compilationResult.Error = &apiservercel.Error{Type: apiservercel.ErrorTypeInternal, Detail: "cost estimation failed: " + err.Error()}
return return
} }
compilationResult.MaxCost = costEst.Max compilationResult.MaxCost = costEst.Max

View File

@ -2003,6 +2003,7 @@ func TestValidationExpressionsAtSchemaLevels(t *testing.T) {
} }
for _, tt := range tests { for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
t.Parallel() t.Parallel()
ctx := context.TODO() ctx := context.TODO()

View File

@ -35,13 +35,13 @@ func TestDefault(t *testing.T) {
{"empty", "null", nil, "null"}, {"empty", "null", nil, "null"},
{"scalar", "4", &structuralschema.Structural{ {"scalar", "4", &structuralschema.Structural{
Generic: structuralschema.Generic{ Generic: structuralschema.Generic{
Default: structuralschema.JSON{"foo"}, Default: structuralschema.JSON{Object: "foo"},
}, },
}, "4"}, }, "4"},
{"scalar array", "[1,2]", &structuralschema.Structural{ {"scalar array", "[1,2]", &structuralschema.Structural{
Items: &structuralschema.Structural{ Items: &structuralschema.Structural{
Generic: structuralschema.Generic{ Generic: structuralschema.Generic{
Default: structuralschema.JSON{"foo"}, Default: structuralschema.JSON{Object: "foo"},
}, },
}, },
}, "[1,2]"}, }, "[1,2]"},
@ -50,17 +50,17 @@ func TestDefault(t *testing.T) {
Properties: map[string]structuralschema.Structural{ Properties: map[string]structuralschema.Structural{
"a": { "a": {
Generic: structuralschema.Generic{ Generic: structuralschema.Generic{
Default: structuralschema.JSON{"A"}, Default: structuralschema.JSON{Object: "A"},
}, },
}, },
"b": { "b": {
Generic: structuralschema.Generic{ Generic: structuralschema.Generic{
Default: structuralschema.JSON{"B"}, Default: structuralschema.JSON{Object: "B"},
}, },
}, },
"c": { "c": {
Generic: structuralschema.Generic{ Generic: structuralschema.Generic{
Default: structuralschema.JSON{"C"}, Default: structuralschema.JSON{Object: "C"},
}, },
}, },
}, },
@ -73,12 +73,12 @@ func TestDefault(t *testing.T) {
Properties: map[string]structuralschema.Structural{ Properties: map[string]structuralschema.Structural{
"a": { "a": {
Generic: structuralschema.Generic{ Generic: structuralschema.Generic{
Default: structuralschema.JSON{"A"}, Default: structuralschema.JSON{Object: "A"},
}, },
}, },
"b": { "b": {
Generic: structuralschema.Generic{ Generic: structuralschema.Generic{
Default: structuralschema.JSON{"B"}, Default: structuralschema.JSON{Object: "B"},
}, },
}, },
}, },
@ -88,12 +88,12 @@ func TestDefault(t *testing.T) {
Properties: map[string]structuralschema.Structural{ Properties: map[string]structuralschema.Structural{
"a": { "a": {
Generic: structuralschema.Generic{ Generic: structuralschema.Generic{
Default: structuralschema.JSON{"N"}, Default: structuralschema.JSON{Object: "N"},
}, },
}, },
"b": { "b": {
Generic: structuralschema.Generic{ Generic: structuralschema.Generic{
Default: structuralschema.JSON{"O"}, Default: structuralschema.JSON{Object: "O"},
}, },
}, },
}, },
@ -105,12 +105,12 @@ func TestDefault(t *testing.T) {
Properties: map[string]structuralschema.Structural{ Properties: map[string]structuralschema.Structural{
"a": { "a": {
Generic: structuralschema.Generic{ Generic: structuralschema.Generic{
Default: structuralschema.JSON{"alpha"}, Default: structuralschema.JSON{Object: "alpha"},
}, },
}, },
"b": { "b": {
Generic: structuralschema.Generic{ Generic: structuralschema.Generic{
Default: structuralschema.JSON{"beta"}, Default: structuralschema.JSON{Object: "beta"},
}, },
}, },
}, },
@ -120,7 +120,7 @@ func TestDefault(t *testing.T) {
}, },
"foo": { "foo": {
Generic: structuralschema.Generic{ Generic: structuralschema.Generic{
Default: structuralschema.JSON{"bar"}, Default: structuralschema.JSON{Object: "bar"},
}, },
}, },
}, },
@ -130,7 +130,7 @@ func TestDefault(t *testing.T) {
Properties: map[string]structuralschema.Structural{ Properties: map[string]structuralschema.Structural{
"a": { "a": {
Generic: structuralschema.Generic{ Generic: structuralschema.Generic{
Default: structuralschema.JSON{"A"}, Default: structuralschema.JSON{Object: "A"},
}, },
}, },
}, },
@ -144,7 +144,7 @@ func TestDefault(t *testing.T) {
Properties: map[string]structuralschema.Structural{ Properties: map[string]structuralschema.Structural{
"a": { "a": {
Generic: structuralschema.Generic{ Generic: structuralschema.Generic{
Default: structuralschema.JSON{"A"}, Default: structuralschema.JSON{Object: "A"},
}, },
}, },
}, },
@ -156,7 +156,7 @@ func TestDefault(t *testing.T) {
}, },
Items: &structuralschema.Structural{ Items: &structuralschema.Structural{
Generic: structuralschema.Generic{ Generic: structuralschema.Generic{
Default: structuralschema.JSON{"A"}, Default: structuralschema.JSON{Object: "A"},
}, },
}, },
}, `["A"]`}, }, `["A"]`},
@ -166,7 +166,7 @@ func TestDefault(t *testing.T) {
"a": { "a": {
Generic: structuralschema.Generic{ Generic: structuralschema.Generic{
Nullable: true, Nullable: true,
Default: structuralschema.JSON{"A"}, Default: structuralschema.JSON{Object: "A"},
}, },
}, },
}, },
@ -176,7 +176,7 @@ func TestDefault(t *testing.T) {
"a": { "a": {
Generic: structuralschema.Generic{ Generic: structuralschema.Generic{
Nullable: false, Nullable: false,
Default: structuralschema.JSON{"A"}, Default: structuralschema.JSON{Object: "A"},
}, },
}, },
}, },
@ -187,7 +187,7 @@ func TestDefault(t *testing.T) {
Structural: &structuralschema.Structural{ Structural: &structuralschema.Structural{
Generic: structuralschema.Generic{ Generic: structuralschema.Generic{
Nullable: true, Nullable: true,
Default: structuralschema.JSON{"A"}, Default: structuralschema.JSON{Object: "A"},
}, },
}, },
}, },
@ -199,7 +199,7 @@ func TestDefault(t *testing.T) {
Structural: &structuralschema.Structural{ Structural: &structuralschema.Structural{
Generic: structuralschema.Generic{ Generic: structuralschema.Generic{
Nullable: false, Nullable: false,
Default: structuralschema.JSON{"A"}, Default: structuralschema.JSON{Object: "A"},
}, },
}, },
}, },

View File

@ -35,7 +35,7 @@ func TestPruneNonNullableNullsWithoutDefaults(t *testing.T) {
{"empty", "null", nil, "null"}, {"empty", "null", nil, "null"},
{"scalar", "4", &structuralschema.Structural{ {"scalar", "4", &structuralschema.Structural{
Generic: structuralschema.Generic{ Generic: structuralschema.Generic{
Default: structuralschema.JSON{"foo"}, Default: structuralschema.JSON{Object: "foo"},
}, },
}, "4"}, }, "4"},
{"scalar array", "[1,null]", nil, "[1,null]"}, {"scalar array", "[1,null]", nil, "[1,null]"},
@ -44,7 +44,7 @@ func TestPruneNonNullableNullsWithoutDefaults(t *testing.T) {
Properties: map[string]structuralschema.Structural{ Properties: map[string]structuralschema.Structural{
"a": { "a": {
Generic: structuralschema.Generic{ Generic: structuralschema.Generic{
Default: structuralschema.JSON{"A"}, Default: structuralschema.JSON{Object: "A"},
}, },
}, },
"b": { "b": {
@ -54,7 +54,7 @@ func TestPruneNonNullableNullsWithoutDefaults(t *testing.T) {
}, },
"c": { "c": {
Generic: structuralschema.Generic{ Generic: structuralschema.Generic{
Default: structuralschema.JSON{"C"}, Default: structuralschema.JSON{Object: "C"},
Nullable: true, Nullable: true,
}, },
}, },

View File

@ -286,7 +286,7 @@ func testDefaulting(t *testing.T, watchCache bool) {
} }
t.Logf("Creating CR and expecting defaulted fields in spec, but status does not exist at all") t.Logf("Creating CR and expecting defaulted fields in spec, but status does not exist at all")
fooClient := dynamicClient.Resource(schema.GroupVersionResource{crd.Spec.Group, crd.Spec.Versions[0].Name, crd.Spec.Names.Plural}) fooClient := dynamicClient.Resource(schema.GroupVersionResource{Group: crd.Spec.Group, Version: crd.Spec.Versions[0].Name, Resource: crd.Spec.Names.Plural})
foo := &unstructured.Unstructured{} foo := &unstructured.Unstructured{}
if err := yaml.Unmarshal([]byte(defaultingFooInstance), &foo.Object); err != nil { if err := yaml.Unmarshal([]byte(defaultingFooInstance), &foo.Object); err != nil {
t.Fatal(err) t.Fatal(err)

View File

@ -137,7 +137,7 @@ func TestListTypes(t *testing.T) {
} }
t.Logf("Creating CR and expect list-type errors") t.Logf("Creating CR and expect list-type errors")
fooClient := dynamicClient.Resource(schema.GroupVersionResource{crd.Spec.Group, crd.Spec.Versions[0].Name, crd.Spec.Names.Plural}) fooClient := dynamicClient.Resource(schema.GroupVersionResource{Group: crd.Spec.Group, Version: crd.Spec.Versions[0].Name, Resource: crd.Spec.Names.Plural})
invalidInstance := &unstructured.Unstructured{} invalidInstance := &unstructured.Unstructured{}
if err := yaml.Unmarshal([]byte(listTypeResourceInstance), &invalidInstance.Object); err != nil { if err := yaml.Unmarshal([]byte(listTypeResourceInstance), &invalidInstance.Object); err != nil {
t.Fatal(err) t.Fatal(err)

View File

@ -450,7 +450,7 @@ func TestEmbeddedResources(t *testing.T) {
} }
t.Logf("Creating CR and expect 'unspecified' fields to be pruned inside ObjectMetas") t.Logf("Creating CR and expect 'unspecified' fields to be pruned inside ObjectMetas")
fooClient := dynamicClient.Resource(schema.GroupVersionResource{crd.Spec.Group, crd.Spec.Versions[0].Name, crd.Spec.Names.Plural}) fooClient := dynamicClient.Resource(schema.GroupVersionResource{Group: crd.Spec.Group, Version: crd.Spec.Versions[0].Name, Resource: crd.Spec.Names.Plural})
foo := &unstructured.Unstructured{} foo := &unstructured.Unstructured{}
if err := yaml.Unmarshal([]byte(embeddedResourceInstance), &foo.Object); err != nil { if err := yaml.Unmarshal([]byte(embeddedResourceInstance), &foo.Object); err != nil {
t.Fatal(err) t.Fatal(err)

View File

@ -211,7 +211,7 @@ func TestPruningCreate(t *testing.T) {
} }
t.Logf("Creating CR and expect 'unspecified' fields to be pruned") t.Logf("Creating CR and expect 'unspecified' fields to be pruned")
fooClient := dynamicClient.Resource(schema.GroupVersionResource{crd.Spec.Group, crd.Spec.Versions[0].Name, crd.Spec.Names.Plural}) fooClient := dynamicClient.Resource(schema.GroupVersionResource{Group: crd.Spec.Group, Version: crd.Spec.Versions[0].Name, Resource: crd.Spec.Names.Plural})
foo := &unstructured.Unstructured{} foo := &unstructured.Unstructured{}
if err := yaml.Unmarshal([]byte(pruningFooInstance), &foo.Object); err != nil { if err := yaml.Unmarshal([]byte(pruningFooInstance), &foo.Object); err != nil {
t.Fatal(err) t.Fatal(err)
@ -263,7 +263,7 @@ func TestPruningStatus(t *testing.T) {
} }
t.Logf("Creating CR and expect 'unspecified' fields to be pruned") t.Logf("Creating CR and expect 'unspecified' fields to be pruned")
fooClient := dynamicClient.Resource(schema.GroupVersionResource{crd.Spec.Group, crd.Spec.Versions[0].Name, crd.Spec.Names.Plural}) fooClient := dynamicClient.Resource(schema.GroupVersionResource{Group: crd.Spec.Group, Version: crd.Spec.Versions[0].Name, Resource: crd.Spec.Names.Plural})
foo := &unstructured.Unstructured{} foo := &unstructured.Unstructured{}
if err := yaml.Unmarshal([]byte(pruningFooInstance), &foo.Object); err != nil { if err := yaml.Unmarshal([]byte(pruningFooInstance), &foo.Object); err != nil {
t.Fatal(err) t.Fatal(err)
@ -374,7 +374,7 @@ func TestPruningFromStorage(t *testing.T) {
} }
t.Logf("Checking that CustomResource is pruned from unknown fields") t.Logf("Checking that CustomResource is pruned from unknown fields")
fooClient := dynamicClient.Resource(schema.GroupVersionResource{crd.Spec.Group, crd.Spec.Versions[0].Name, crd.Spec.Names.Plural}) fooClient := dynamicClient.Resource(schema.GroupVersionResource{Group: crd.Spec.Group, Version: crd.Spec.Versions[0].Name, Resource: crd.Spec.Names.Plural})
foo, err := fooClient.Get(context.TODO(), "foo", metav1.GetOptions{}) foo, err := fooClient.Get(context.TODO(), "foo", metav1.GetOptions{})
if err != nil { if err != nil {
t.Fatalf("unexpected error: %v", err) t.Fatalf("unexpected error: %v", err)
@ -415,7 +415,7 @@ func TestPruningPatch(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
fooClient := dynamicClient.Resource(schema.GroupVersionResource{crd.Spec.Group, crd.Spec.Versions[0].Name, crd.Spec.Names.Plural}) fooClient := dynamicClient.Resource(schema.GroupVersionResource{Group: crd.Spec.Group, Version: crd.Spec.Versions[0].Name, Resource: crd.Spec.Names.Plural})
foo := &unstructured.Unstructured{} foo := &unstructured.Unstructured{}
if err := yaml.Unmarshal([]byte(pruningFooInstance), &foo.Object); err != nil { if err := yaml.Unmarshal([]byte(pruningFooInstance), &foo.Object); err != nil {
t.Fatal(err) t.Fatal(err)
@ -468,7 +468,7 @@ func TestPruningCreatePreservingUnknownFields(t *testing.T) {
} }
t.Logf("Creating CR and expect 'unspecified' field to be pruned") t.Logf("Creating CR and expect 'unspecified' field to be pruned")
fooClient := dynamicClient.Resource(schema.GroupVersionResource{crd.Spec.Group, crd.Spec.Versions[0].Name, crd.Spec.Names.Plural}) fooClient := dynamicClient.Resource(schema.GroupVersionResource{Group: crd.Spec.Group, Version: crd.Spec.Versions[0].Name, Resource: crd.Spec.Names.Plural})
foo := &unstructured.Unstructured{} foo := &unstructured.Unstructured{}
if err := yaml.Unmarshal([]byte(pruningFooInstance), &foo.Object); err != nil { if err := yaml.Unmarshal([]byte(pruningFooInstance), &foo.Object); err != nil {
t.Fatal(err) t.Fatal(err)
@ -553,7 +553,7 @@ func TestPruningEmbeddedResources(t *testing.T) {
} }
t.Logf("Creating CR and expect 'unspecified' field to be pruned") t.Logf("Creating CR and expect 'unspecified' field to be pruned")
fooClient := dynamicClient.Resource(schema.GroupVersionResource{crd.Spec.Group, crd.Spec.Versions[0].Name, crd.Spec.Names.Plural}) fooClient := dynamicClient.Resource(schema.GroupVersionResource{Group: crd.Spec.Group, Version: crd.Spec.Versions[0].Name, Resource: crd.Spec.Names.Plural})
foo := &unstructured.Unstructured{} foo := &unstructured.Unstructured{}
if err := yaml.Unmarshal([]byte(fooSchemaEmbeddedResourceInstance), &foo.Object); err != nil { if err := yaml.Unmarshal([]byte(fooSchemaEmbeddedResourceInstance), &foo.Object); err != nil {
t.Fatal(err) t.Fatal(err)

View File

@ -25,9 +25,13 @@ import (
) )
func TestResourceMapper(t *testing.T) { func TestResourceMapper(t *testing.T) {
gvr := func(g, v, r string) schema.GroupVersionResource { return schema.GroupVersionResource{g, v, r} } gvr := func(g, v, r string) schema.GroupVersionResource {
return schema.GroupVersionResource{Group: g, Version: v, Resource: r}
}
gvk := func(g, v, k string) schema.GroupVersionKind { return schema.GroupVersionKind{g, v, k} } gvk := func(g, v, k string) schema.GroupVersionKind {
return schema.GroupVersionKind{Group: g, Version: v, Kind: k}
}
kindsToRegister := []struct { kindsToRegister := []struct {
gvr schema.GroupVersionResource gvr schema.GroupVersionResource

View File

@ -147,7 +147,7 @@ func (c *codec) Decode(data []byte, defaultGVK *schema.GroupVersionKind, into ru
} }
if d, ok := obj.(runtime.NestedObjectDecoder); ok { if d, ok := obj.(runtime.NestedObjectDecoder); ok {
if err := d.DecodeNestedObjects(runtime.WithoutVersionDecoder{c.decoder}); err != nil { if err := d.DecodeNestedObjects(runtime.WithoutVersionDecoder{Decoder: c.decoder}); err != nil {
if strictErr, ok := runtime.AsStrictDecodingError(err); ok { if strictErr, ok := runtime.AsStrictDecodingError(err); ok {
// save the strictDecodingError let and the caller decide what to do with it // save the strictDecodingError let and the caller decide what to do with it
strictDecodingErrs = append(strictDecodingErrs, strictErr.Errors()...) strictDecodingErrs = append(strictDecodingErrs, strictErr.Errors()...)

View File

@ -53,6 +53,14 @@ func (fc *fakeCriteria) GetParsedObjectSelector() (labels.Selector, error) {
return metav1.LabelSelectorAsSelector(fc.matchResources.ObjectSelector) return metav1.LabelSelectorAsSelector(fc.matchResources.ObjectSelector)
} }
func gvr(group, version, resource string) schema.GroupVersionResource {
return schema.GroupVersionResource{Group: group, Version: version, Resource: resource}
}
func gvk(group, version, kind string) schema.GroupVersionKind {
return schema.GroupVersionKind{Group: group, Version: version, Kind: kind}
}
func TestMatcher(t *testing.T) { func TestMatcher(t *testing.T) {
a := &Matcher{namespaceMatcher: &namespace.Matcher{}, objectMatcher: &object.Matcher{}} a := &Matcher{namespaceMatcher: &namespace.Matcher{}, objectMatcher: &object.Matcher{}}
@ -67,19 +75,19 @@ func TestMatcher(t *testing.T) {
} }
return "" return ""
}) })
mapper.RegisterKindFor(schema.GroupVersionResource{"extensions", "v1beta1", "deployments"}, "", schema.GroupVersionKind{"extensions", "v1beta1", "Deployment"}) mapper.RegisterKindFor(gvr("extensions", "v1beta1", "deployments"), "", gvk("extensions", "v1beta1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1", "deployments"}, "", schema.GroupVersionKind{"apps", "v1", "Deployment"}) mapper.RegisterKindFor(gvr("apps", "v1", "deployments"), "", gvk("apps", "v1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta1", "deployments"}, "", schema.GroupVersionKind{"apps", "v1beta1", "Deployment"}) mapper.RegisterKindFor(gvr("apps", "v1beta1", "deployments"), "", gvk("apps", "v1beta1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1alpha1", "deployments"}, "", schema.GroupVersionKind{"apps", "v1alpha1", "Deployment"}) mapper.RegisterKindFor(gvr("apps", "v1alpha1", "deployments"), "", gvk("apps", "v1alpha1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"extensions", "v1beta1", "deployments"}, "scale", schema.GroupVersionKind{"extensions", "v1beta1", "Scale"}) mapper.RegisterKindFor(gvr("extensions", "v1beta1", "deployments"), "scale", gvk("extensions", "v1beta1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1", "deployments"}, "scale", schema.GroupVersionKind{"autoscaling", "v1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1", "deployments"), "scale", gvk("autoscaling", "v1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta1", "deployments"}, "scale", schema.GroupVersionKind{"apps", "v1beta1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1beta1", "deployments"), "scale", gvk("apps", "v1beta1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1alpha1", "deployments"}, "scale", schema.GroupVersionKind{"apps", "v1alpha1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1alpha1", "deployments"), "scale", gvk("apps", "v1alpha1", "Scale"))
// register invalid kinds to trigger an error // register invalid kinds to trigger an error
mapper.RegisterKindFor(schema.GroupVersionResource{"example.com", "v1", "widgets"}, "", schema.GroupVersionKind{"", "", ""}) mapper.RegisterKindFor(gvr("example.com", "v1", "widgets"), "", gvk("", "", ""))
mapper.RegisterKindFor(schema.GroupVersionResource{"example.com", "v2", "widgets"}, "", schema.GroupVersionKind{"", "", ""}) mapper.RegisterKindFor(gvr("example.com", "v2", "widgets"), "", gvk("", "", ""))
interfaces := &admission.RuntimeObjectInterfaces{EquivalentResourceMapper: mapper} interfaces := &admission.RuntimeObjectInterfaces{EquivalentResourceMapper: mapper}
@ -91,13 +99,13 @@ func TestMatcher(t *testing.T) {
attrs admission.Attributes attrs admission.Attributes
expectMatches bool expectMatches bool
expectMatchKind *schema.GroupVersionKind expectMatchKind schema.GroupVersionKind
expectErr string expectErr string
}{ }{
{ {
name: "no rules (just write)", name: "no rules (just write)",
criteria: &v1alpha1.MatchResources{NamespaceSelector: &metav1.LabelSelector{}, ResourceRules: []v1alpha1.NamedRuleWithOperations{}}, criteria: &v1alpha1.MatchResources{NamespaceSelector: &metav1.LabelSelector{}, ResourceRules: []v1alpha1.NamedRuleWithOperations{}},
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"apps", "v1", "Deployment"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("apps", "v1", "Deployment"), "ns", "name", gvr("apps", "v1", "deployments"), "", admission.Create, &metav1.CreateOptions{}, false, nil),
expectMatches: false, expectMatches: false,
}, },
{ {
@ -111,9 +119,9 @@ func TestMatcher(t *testing.T) {
Rule: v1.Rule{APIGroups: []string{"*"}, APIVersions: []string{"*"}, Resources: []string{"*"}, Scope: &allScopes}, Rule: v1.Rule{APIGroups: []string{"*"}, APIVersions: []string{"*"}, Resources: []string{"*"}, Scope: &allScopes},
}, },
}}}, }}},
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"apps", "v1", "Deployment"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("apps", "v1", "Deployment"), "ns", "name", gvr("apps", "v1", "deployments"), "", admission.Create, &metav1.CreateOptions{}, false, nil),
expectMatches: true, expectMatches: true,
expectMatchKind: &schema.GroupVersionKind{"apps", "v1", "Deployment"}, expectMatchKind: gvk("apps", "v1", "Deployment"),
}, },
{ {
name: "specific rules, prefer exact match", name: "specific rules, prefer exact match",
@ -136,9 +144,9 @@ func TestMatcher(t *testing.T) {
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1"}, Resources: []string{"deployments"}, Scope: &allScopes}, Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1"}, Resources: []string{"deployments"}, Scope: &allScopes},
}, },
}}}, }}},
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"apps", "v1", "Deployment"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("apps", "v1", "Deployment"), "ns", "name", gvr("apps", "v1", "deployments"), "", admission.Create, &metav1.CreateOptions{}, false, nil),
expectMatches: true, expectMatches: true,
expectMatchKind: &schema.GroupVersionKind{"apps", "v1", "Deployment"}, expectMatchKind: gvk("apps", "v1", "Deployment"),
}, },
{ {
name: "specific rules, match miss", name: "specific rules, match miss",
@ -156,7 +164,7 @@ func TestMatcher(t *testing.T) {
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments"}, Scope: &allScopes}, Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments"}, Scope: &allScopes},
}, },
}}}, }}},
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"apps", "v1", "Deployment"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("apps", "v1", "Deployment"), "ns", "name", gvr("apps", "v1", "deployments"), "", admission.Create, &metav1.CreateOptions{}, false, nil),
expectMatches: false, expectMatches: false,
}, },
{ {
@ -176,7 +184,7 @@ func TestMatcher(t *testing.T) {
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments"}, Scope: &allScopes}, Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments"}, Scope: &allScopes},
}, },
}}}, }}},
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"apps", "v1", "Deployment"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("apps", "v1", "Deployment"), "ns", "name", gvr("apps", "v1", "deployments"), "", admission.Create, &metav1.CreateOptions{}, false, nil),
expectMatches: false, expectMatches: false,
}, },
{ {
@ -196,9 +204,9 @@ func TestMatcher(t *testing.T) {
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments"}, Scope: &allScopes}, Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments"}, Scope: &allScopes},
}, },
}}}, }}},
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"apps", "v1", "Deployment"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("apps", "v1", "Deployment"), "ns", "name", gvr("apps", "v1", "deployments"), "", admission.Create, &metav1.CreateOptions{}, false, nil),
expectMatches: true, expectMatches: true,
expectMatchKind: &schema.GroupVersionKind{"extensions", "v1beta1", "Deployment"}, expectMatchKind: gvk("extensions", "v1beta1", "Deployment"),
}, },
{ {
name: "specific rules, equivalent match, prefer apps", name: "specific rules, equivalent match, prefer apps",
@ -217,9 +225,9 @@ func TestMatcher(t *testing.T) {
Rule: v1.Rule{APIGroups: []string{"extensions"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments"}, Scope: &allScopes}, Rule: v1.Rule{APIGroups: []string{"extensions"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments"}, Scope: &allScopes},
}, },
}}}, }}},
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"apps", "v1", "Deployment"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("apps", "v1", "Deployment"), "ns", "name", gvr("apps", "v1", "deployments"), "", admission.Create, &metav1.CreateOptions{}, false, nil),
expectMatches: true, expectMatches: true,
expectMatchKind: &schema.GroupVersionKind{"apps", "v1beta1", "Deployment"}, expectMatchKind: gvk("apps", "v1beta1", "Deployment"),
}, },
{ {
@ -243,9 +251,9 @@ func TestMatcher(t *testing.T) {
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes}, Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes},
}, },
}}}, }}},
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "scale", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("autoscaling", "v1", "Scale"), "ns", "name", gvr("apps", "v1", "deployments"), "scale", admission.Create, &metav1.CreateOptions{}, false, nil),
expectMatches: true, expectMatches: true,
expectMatchKind: &schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, expectMatchKind: gvk("autoscaling", "v1", "Scale"),
}, },
{ {
name: "specific rules, subresource match miss", name: "specific rules, subresource match miss",
@ -263,7 +271,7 @@ func TestMatcher(t *testing.T) {
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes}, Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes},
}, },
}}}, }}},
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "scale", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("autoscaling", "v1", "Scale"), "ns", "name", gvr("apps", "v1", "deployments"), "scale", admission.Create, &metav1.CreateOptions{}, false, nil),
expectMatches: false, expectMatches: false,
}, },
{ {
@ -283,7 +291,7 @@ func TestMatcher(t *testing.T) {
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes}, Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes},
}, },
}}}, }}},
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "scale", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("autoscaling", "v1", "Scale"), "ns", "name", gvr("apps", "v1", "deployments"), "scale", admission.Create, &metav1.CreateOptions{}, false, nil),
expectMatches: false, expectMatches: false,
}, },
{ {
@ -303,9 +311,9 @@ func TestMatcher(t *testing.T) {
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes}, Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes},
}, },
}}}, }}},
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "scale", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("autoscaling", "v1", "Scale"), "ns", "name", gvr("apps", "v1", "deployments"), "scale", admission.Create, &metav1.CreateOptions{}, false, nil),
expectMatches: true, expectMatches: true,
expectMatchKind: &schema.GroupVersionKind{"extensions", "v1beta1", "Scale"}, expectMatchKind: gvk("extensions", "v1beta1", "Scale"),
}, },
{ {
name: "specific rules, subresource equivalent match, prefer apps", name: "specific rules, subresource equivalent match, prefer apps",
@ -324,9 +332,9 @@ func TestMatcher(t *testing.T) {
Rule: v1.Rule{APIGroups: []string{"extensions"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes}, Rule: v1.Rule{APIGroups: []string{"extensions"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes},
}, },
}}}, }}},
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "scale", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("autoscaling", "v1", "Scale"), "ns", "name", gvr("apps", "v1", "deployments"), "scale", admission.Create, &metav1.CreateOptions{}, false, nil),
expectMatches: true, expectMatches: true,
expectMatchKind: &schema.GroupVersionKind{"apps", "v1beta1", "Scale"}, expectMatchKind: gvk("apps", "v1beta1", "Scale"),
}, },
{ {
name: "specific rules, prefer exact match and name match", name: "specific rules, prefer exact match and name match",
@ -340,9 +348,9 @@ func TestMatcher(t *testing.T) {
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1"}, Resources: []string{"deployments"}, Scope: &allScopes}, Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1"}, Resources: []string{"deployments"}, Scope: &allScopes},
}, },
}}}, }}},
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("autoscaling", "v1", "Scale"), "ns", "name", gvr("apps", "v1", "deployments"), "", admission.Create, &metav1.CreateOptions{}, false, nil),
expectMatches: true, expectMatches: true,
expectMatchKind: &schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, expectMatchKind: gvk("autoscaling", "v1", "Scale"),
}, },
{ {
name: "specific rules, prefer exact match and name match miss", name: "specific rules, prefer exact match and name match miss",
@ -356,7 +364,7 @@ func TestMatcher(t *testing.T) {
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1"}, Resources: []string{"deployments"}, Scope: &allScopes}, Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1"}, Resources: []string{"deployments"}, Scope: &allScopes},
}, },
}}}, }}},
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("autoscaling", "v1", "Scale"), "ns", "name", gvr("apps", "v1", "deployments"), "", admission.Create, &metav1.CreateOptions{}, false, nil),
expectMatches: false, expectMatches: false,
}, },
{ {
@ -372,9 +380,9 @@ func TestMatcher(t *testing.T) {
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes}, Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes},
}, },
}}}, }}},
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"extensions", "v1beta1", "deployments"}, "scale", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("autoscaling", "v1", "Scale"), "ns", "name", gvr("extensions", "v1beta1", "deployments"), "scale", admission.Create, &metav1.CreateOptions{}, false, nil),
expectMatches: true, expectMatches: true,
expectMatchKind: &schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, expectMatchKind: gvk("autoscaling", "v1", "Scale"),
}, },
{ {
name: "specific rules, subresource equivalent match, prefer extensions and name match miss", name: "specific rules, subresource equivalent match, prefer extensions and name match miss",
@ -389,7 +397,7 @@ func TestMatcher(t *testing.T) {
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes}, Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes},
}, },
}}}, }}},
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"extensions", "v1beta1", "deployments"}, "scale", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("autoscaling", "v1", "Scale"), "ns", "name", gvr("extensions", "v1beta1", "deployments"), "scale", admission.Create, &metav1.CreateOptions{}, false, nil),
expectMatches: false, expectMatches: false,
}, },
{ {
@ -410,9 +418,9 @@ func TestMatcher(t *testing.T) {
}, },
}}, }},
}, },
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("autoscaling", "v1", "Scale"), "ns", "name", gvr("apps", "v1", "deployments"), "", admission.Create, &metav1.CreateOptions{}, false, nil),
expectMatches: true, expectMatches: true,
expectMatchKind: &schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, expectMatchKind: gvk("autoscaling", "v1", "Scale"),
}, },
{ {
name: "exclude resource miss on match", name: "exclude resource miss on match",
@ -432,7 +440,7 @@ func TestMatcher(t *testing.T) {
}, },
}}, }},
}, },
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"extensions", "v1beta1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("autoscaling", "v1", "Scale"), "ns", "name", gvr("extensions", "v1beta1", "deployments"), "", admission.Create, &metav1.CreateOptions{}, false, nil),
expectMatches: false, expectMatches: false,
}, },
{ {
@ -447,7 +455,7 @@ func TestMatcher(t *testing.T) {
}, },
}}, }},
}, },
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("autoscaling", "v1", "Scale"), "ns", "name", gvr("apps", "v1", "deployments"), "", admission.Create, &metav1.CreateOptions{}, false, nil),
expectMatches: true, expectMatches: true,
}, },
{ {
@ -457,7 +465,7 @@ func TestMatcher(t *testing.T) {
ObjectSelector: &metav1.LabelSelector{}, ObjectSelector: &metav1.LabelSelector{},
ResourceRules: []v1alpha1.NamedRuleWithOperations{{}}, ResourceRules: []v1alpha1.NamedRuleWithOperations{{}},
}, },
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("autoscaling", "v1", "Scale"), "ns", "name", gvr("apps", "v1", "deployments"), "", admission.Create, &metav1.CreateOptions{}, false, nil),
expectMatches: false, expectMatches: false,
}, },
{ {
@ -472,7 +480,7 @@ func TestMatcher(t *testing.T) {
}, },
}}, }},
}, },
attrs: admission.NewAttributesRecord(&example.Pod{}, nil, schema.GroupVersionKind{"example.apiserver.k8s.io", "v1", "Pod"}, "ns", "name", schema.GroupVersionResource{"example.apiserver.k8s.io", "v1", "pods"}, "", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(&example.Pod{}, nil, gvk("example.apiserver.k8s.io", "v1", "Pod"), "ns", "name", gvr("example.apiserver.k8s.io", "v1", "pods"), "", admission.Create, &metav1.CreateOptions{}, false, nil),
expectMatches: false, expectMatches: false,
expectErr: "", expectErr: "",
}, },
@ -488,7 +496,7 @@ func TestMatcher(t *testing.T) {
}, },
}}, }},
}, },
attrs: admission.NewAttributesRecord(&example.Pod{}, nil, schema.GroupVersionKind{"example.apiserver.k8s.io", "v1", "Pod"}, "ns", "name", schema.GroupVersionResource{"example.apiserver.k8s.io", "v1", "pods"}, "", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(&example.Pod{}, nil, gvk("example.apiserver.k8s.io", "v1", "Pod"), "ns", "name", gvr("example.apiserver.k8s.io", "v1", "pods"), "", admission.Create, &metav1.CreateOptions{}, false, nil),
expectMatches: false, expectMatches: false,
expectErr: "bad value", expectErr: "bad value",
}, },
@ -504,7 +512,7 @@ func TestMatcher(t *testing.T) {
}, },
}}, }},
}, },
attrs: admission.NewAttributesRecord(&example.Pod{}, nil, schema.GroupVersionKind{"example.apiserver.k8s.io", "v1", "Pod"}, "ns", "name", schema.GroupVersionResource{"example.apiserver.k8s.io", "v1", "pods"}, "", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(&example.Pod{}, nil, gvk("example.apiserver.k8s.io", "v1", "Pod"), "ns", "name", gvr("example.apiserver.k8s.io", "v1", "pods"), "", admission.Create, &metav1.CreateOptions{}, false, nil),
expectMatches: false, expectMatches: false,
expectErr: "", expectErr: "",
}, },
@ -520,7 +528,7 @@ func TestMatcher(t *testing.T) {
}, },
}}, }},
}, },
attrs: admission.NewAttributesRecord(&example.Pod{}, nil, schema.GroupVersionKind{"example.apiserver.k8s.io", "v1", "Pod"}, "ns", "name", schema.GroupVersionResource{"example.apiserver.k8s.io", "v1", "pods"}, "", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(&example.Pod{}, nil, gvk("example.apiserver.k8s.io", "v1", "Pod"), "ns", "name", gvr("example.apiserver.k8s.io", "v1", "pods"), "", admission.Create, &metav1.CreateOptions{}, false, nil),
expectMatches: false, expectMatches: false,
expectErr: "bad value", expectErr: "bad value",
}, },
@ -540,8 +548,9 @@ func TestMatcher(t *testing.T) {
} else if len(testcase.expectErr) > 0 { } else if len(testcase.expectErr) > 0 {
t.Fatalf("expected error %q, got no error", testcase.expectErr) t.Fatalf("expected error %q, got no error", testcase.expectErr)
} }
if testcase.expectMatchKind != nil { var emptyGVK schema.GroupVersionKind
if *testcase.expectMatchKind != matchKind { if testcase.expectMatchKind != emptyGVK {
if testcase.expectMatchKind != matchKind {
t.Fatalf("expected matchKind %v, got %v", testcase.expectMatchKind, matchKind) t.Fatalf("expected matchKind %v, got %v", testcase.expectMatchKind, matchKind)
} }
} }
@ -588,23 +597,23 @@ func BenchmarkMatcher(b *testing.B) {
} }
return "" return ""
}) })
mapper.RegisterKindFor(schema.GroupVersionResource{"extensions", "v1beta1", "deployments"}, "", schema.GroupVersionKind{"extensions", "v1beta1", "Deployment"}) mapper.RegisterKindFor(gvr("extensions", "v1beta1", "deployments"), "", gvk("extensions", "v1beta1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1", "deployments"}, "", schema.GroupVersionKind{"apps", "v1", "Deployment"}) mapper.RegisterKindFor(gvr("apps", "v1", "deployments"), "", gvk("apps", "v1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta1", "deployments"}, "", schema.GroupVersionKind{"apps", "v1beta1", "Deployment"}) mapper.RegisterKindFor(gvr("apps", "v1beta1", "deployments"), "", gvk("apps", "v1beta1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1alpha1", "deployments"}, "", schema.GroupVersionKind{"apps", "v1alpha1", "Deployment"}) mapper.RegisterKindFor(gvr("apps", "v1alpha1", "deployments"), "", gvk("apps", "v1alpha1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"extensions", "v1beta1", "deployments"}, "scale", schema.GroupVersionKind{"extensions", "v1beta1", "Scale"}) mapper.RegisterKindFor(gvr("extensions", "v1beta1", "deployments"), "scale", gvk("extensions", "v1beta1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1", "deployments"}, "scale", schema.GroupVersionKind{"autoscaling", "v1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1", "deployments"), "scale", gvk("autoscaling", "v1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta1", "deployments"}, "scale", schema.GroupVersionKind{"apps", "v1beta1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1beta1", "deployments"), "scale", gvk("apps", "v1beta1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1alpha1", "deployments"}, "scale", schema.GroupVersionKind{"apps", "v1alpha1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1alpha1", "deployments"), "scale", gvk("apps", "v1alpha1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1", "statefulset"}, "", schema.GroupVersionKind{"apps", "v1", "StatefulSet"}) mapper.RegisterKindFor(gvr("apps", "v1", "statefulset"), "", gvk("apps", "v1", "StatefulSet"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta1", "statefulset"}, "", schema.GroupVersionKind{"apps", "v1beta1", "StatefulSet"}) mapper.RegisterKindFor(gvr("apps", "v1beta1", "statefulset"), "", gvk("apps", "v1beta1", "StatefulSet"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta2", "statefulset"}, "", schema.GroupVersionKind{"apps", "v1beta2", "StatefulSet"}) mapper.RegisterKindFor(gvr("apps", "v1beta2", "statefulset"), "", gvk("apps", "v1beta2", "StatefulSet"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1", "statefulset"}, "scale", schema.GroupVersionKind{"apps", "v1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1", "statefulset"), "scale", gvk("apps", "v1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta1", "statefulset"}, "scale", schema.GroupVersionKind{"apps", "v1beta1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1beta1", "statefulset"), "scale", gvk("apps", "v1beta1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1alpha2", "statefulset"}, "scale", schema.GroupVersionKind{"apps", "v1beta2", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1alpha2", "statefulset"), "scale", gvk("apps", "v1beta2", "Scale"))
nsSelector := make(map[string]string) nsSelector := make(map[string]string)
for i := 0; i < 100; i++ { for i := 0; i < 100; i++ {
@ -632,7 +641,7 @@ func BenchmarkMatcher(b *testing.B) {
} }
criteria := &fakeCriteria{matchResources: mr} criteria := &fakeCriteria{matchResources: mr}
attrs := admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "scale", admission.Create, &metav1.CreateOptions{}, false, nil) attrs := admission.NewAttributesRecord(nil, nil, gvk("autoscaling", "v1", "Scale"), "ns", "name", gvr("apps", "v1", "deployments"), "scale", admission.Create, &metav1.CreateOptions{}, false, nil)
interfaces := &admission.RuntimeObjectInterfaces{EquivalentResourceMapper: mapper} interfaces := &admission.RuntimeObjectInterfaces{EquivalentResourceMapper: mapper}
matcher := &Matcher{namespaceMatcher: &namespace.Matcher{NamespaceLister: namespaceLister}, objectMatcher: &object.Matcher{}} matcher := &Matcher{namespaceMatcher: &namespace.Matcher{NamespaceLister: namespaceLister}, objectMatcher: &object.Matcher{}}
@ -661,23 +670,23 @@ func BenchmarkShouldCallHookWithComplexRule(b *testing.B) {
} }
return "" return ""
}) })
mapper.RegisterKindFor(schema.GroupVersionResource{"extensions", "v1beta1", "deployments"}, "", schema.GroupVersionKind{"extensions", "v1beta1", "Deployment"}) mapper.RegisterKindFor(gvr("extensions", "v1beta1", "deployments"), "", gvk("extensions", "v1beta1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1", "deployments"}, "", schema.GroupVersionKind{"apps", "v1", "Deployment"}) mapper.RegisterKindFor(gvr("apps", "v1", "deployments"), "", gvk("apps", "v1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta1", "deployments"}, "", schema.GroupVersionKind{"apps", "v1beta1", "Deployment"}) mapper.RegisterKindFor(gvr("apps", "v1beta1", "deployments"), "", gvk("apps", "v1beta1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1alpha1", "deployments"}, "", schema.GroupVersionKind{"apps", "v1alpha1", "Deployment"}) mapper.RegisterKindFor(gvr("apps", "v1alpha1", "deployments"), "", gvk("apps", "v1alpha1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"extensions", "v1beta1", "deployments"}, "scale", schema.GroupVersionKind{"extensions", "v1beta1", "Scale"}) mapper.RegisterKindFor(gvr("extensions", "v1beta1", "deployments"), "scale", gvk("extensions", "v1beta1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1", "deployments"}, "scale", schema.GroupVersionKind{"autoscaling", "v1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1", "deployments"), "scale", gvk("autoscaling", "v1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta1", "deployments"}, "scale", schema.GroupVersionKind{"apps", "v1beta1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1beta1", "deployments"), "scale", gvk("apps", "v1beta1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1alpha1", "deployments"}, "scale", schema.GroupVersionKind{"apps", "v1alpha1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1alpha1", "deployments"), "scale", gvk("apps", "v1alpha1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1", "statefulset"}, "", schema.GroupVersionKind{"apps", "v1", "StatefulSet"}) mapper.RegisterKindFor(gvr("apps", "v1", "statefulset"), "", gvk("apps", "v1", "StatefulSet"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta1", "statefulset"}, "", schema.GroupVersionKind{"apps", "v1beta1", "StatefulSet"}) mapper.RegisterKindFor(gvr("apps", "v1beta1", "statefulset"), "", gvk("apps", "v1beta1", "StatefulSet"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta2", "statefulset"}, "", schema.GroupVersionKind{"apps", "v1beta2", "StatefulSet"}) mapper.RegisterKindFor(gvr("apps", "v1beta2", "statefulset"), "", gvk("apps", "v1beta2", "StatefulSet"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1", "statefulset"}, "scale", schema.GroupVersionKind{"apps", "v1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1", "statefulset"), "scale", gvk("apps", "v1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta1", "statefulset"}, "scale", schema.GroupVersionKind{"apps", "v1beta1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1beta1", "statefulset"), "scale", gvk("apps", "v1beta1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1alpha2", "statefulset"}, "scale", schema.GroupVersionKind{"apps", "v1beta2", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1alpha2", "statefulset"), "scale", gvk("apps", "v1beta2", "Scale"))
mr := v1alpha1.MatchResources{ mr := v1alpha1.MatchResources{
MatchPolicy: &equivalentMatch, MatchPolicy: &equivalentMatch,
@ -702,7 +711,7 @@ func BenchmarkShouldCallHookWithComplexRule(b *testing.B) {
} }
criteria := &fakeCriteria{matchResources: mr} criteria := &fakeCriteria{matchResources: mr}
attrs := admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "scale", admission.Create, &metav1.CreateOptions{}, false, nil) attrs := admission.NewAttributesRecord(nil, nil, gvk("autoscaling", "v1", "Scale"), "ns", "name", gvr("apps", "v1", "deployments"), "scale", admission.Create, &metav1.CreateOptions{}, false, nil)
interfaces := &admission.RuntimeObjectInterfaces{EquivalentResourceMapper: mapper} interfaces := &admission.RuntimeObjectInterfaces{EquivalentResourceMapper: mapper}
matcher := &Matcher{namespaceMatcher: &namespace.Matcher{NamespaceLister: namespaceLister}, objectMatcher: &object.Matcher{}} matcher := &Matcher{namespaceMatcher: &namespace.Matcher{NamespaceLister: namespaceLister}, objectMatcher: &object.Matcher{}}
@ -731,23 +740,23 @@ func BenchmarkShouldCallHookWithComplexSelectorAndRule(b *testing.B) {
} }
return "" return ""
}) })
mapper.RegisterKindFor(schema.GroupVersionResource{"extensions", "v1beta1", "deployments"}, "", schema.GroupVersionKind{"extensions", "v1beta1", "Deployment"}) mapper.RegisterKindFor(gvr("extensions", "v1beta1", "deployments"), "", gvk("extensions", "v1beta1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1", "deployments"}, "", schema.GroupVersionKind{"apps", "v1", "Deployment"}) mapper.RegisterKindFor(gvr("apps", "v1", "deployments"), "", gvk("apps", "v1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta1", "deployments"}, "", schema.GroupVersionKind{"apps", "v1beta1", "Deployment"}) mapper.RegisterKindFor(gvr("apps", "v1beta1", "deployments"), "", gvk("apps", "v1beta1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1alpha1", "deployments"}, "", schema.GroupVersionKind{"apps", "v1alpha1", "Deployment"}) mapper.RegisterKindFor(gvr("apps", "v1alpha1", "deployments"), "", gvk("apps", "v1alpha1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"extensions", "v1beta1", "deployments"}, "scale", schema.GroupVersionKind{"extensions", "v1beta1", "Scale"}) mapper.RegisterKindFor(gvr("extensions", "v1beta1", "deployments"), "scale", gvk("extensions", "v1beta1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1", "deployments"}, "scale", schema.GroupVersionKind{"autoscaling", "v1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1", "deployments"), "scale", gvk("autoscaling", "v1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta1", "deployments"}, "scale", schema.GroupVersionKind{"apps", "v1beta1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1beta1", "deployments"), "scale", gvk("apps", "v1beta1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1alpha1", "deployments"}, "scale", schema.GroupVersionKind{"apps", "v1alpha1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1alpha1", "deployments"), "scale", gvk("apps", "v1alpha1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1", "statefulset"}, "", schema.GroupVersionKind{"apps", "v1", "StatefulSet"}) mapper.RegisterKindFor(gvr("apps", "v1", "statefulset"), "", gvk("apps", "v1", "StatefulSet"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta1", "statefulset"}, "", schema.GroupVersionKind{"apps", "v1beta1", "StatefulSet"}) mapper.RegisterKindFor(gvr("apps", "v1beta1", "statefulset"), "", gvk("apps", "v1beta1", "StatefulSet"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta2", "statefulset"}, "", schema.GroupVersionKind{"apps", "v1beta2", "StatefulSet"}) mapper.RegisterKindFor(gvr("apps", "v1beta2", "statefulset"), "", gvk("apps", "v1beta2", "StatefulSet"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1", "statefulset"}, "scale", schema.GroupVersionKind{"apps", "v1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1", "statefulset"), "scale", gvk("apps", "v1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta1", "statefulset"}, "scale", schema.GroupVersionKind{"apps", "v1beta1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1beta1", "statefulset"), "scale", gvk("apps", "v1beta1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1alpha2", "statefulset"}, "scale", schema.GroupVersionKind{"apps", "v1beta2", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1alpha2", "statefulset"), "scale", gvk("apps", "v1beta2", "Scale"))
nsSelector := make(map[string]string) nsSelector := make(map[string]string)
for i := 0; i < 100; i++ { for i := 0; i < 100; i++ {
@ -777,7 +786,7 @@ func BenchmarkShouldCallHookWithComplexSelectorAndRule(b *testing.B) {
} }
criteria := &fakeCriteria{matchResources: mr} criteria := &fakeCriteria{matchResources: mr}
attrs := admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "scale", admission.Create, &metav1.CreateOptions{}, false, nil) attrs := admission.NewAttributesRecord(nil, nil, gvk("autoscaling", "v1", "Scale"), "ns", "name", gvr("apps", "v1", "deployments"), "scale", admission.Create, &metav1.CreateOptions{}, false, nil)
interfaces := &admission.RuntimeObjectInterfaces{EquivalentResourceMapper: mapper} interfaces := &admission.RuntimeObjectInterfaces{EquivalentResourceMapper: mapper}
matcher := &Matcher{namespaceMatcher: &namespace.Matcher{NamespaceLister: namespaceLister}, objectMatcher: &object.Matcher{}} matcher := &Matcher{namespaceMatcher: &namespace.Matcher{NamespaceLister: namespaceLister}, objectMatcher: &object.Matcher{}}

View File

@ -168,7 +168,7 @@ func TestConvertVersionedAttributes(t *testing.T) {
o := admission.NewObjectInterfacesFromScheme(scheme) o := admission.NewObjectInterfacesFromScheme(scheme)
gvk := func(g, v, k string) schema.GroupVersionKind { gvk := func(g, v, k string) schema.GroupVersionKind {
return schema.GroupVersionKind{g, v, k} return schema.GroupVersionKind{Group: g, Version: v, Kind: k}
} }
attrs := func(obj, oldObj runtime.Object) admission.Attributes { attrs := func(obj, oldObj runtime.Object) admission.Attributes {
return admission.NewAttributesRecord(obj, oldObj, schema.GroupVersionKind{}, "", "", schema.GroupVersionResource{}, "", "", nil, false, nil) return admission.NewAttributesRecord(obj, oldObj, schema.GroupVersionKind{}, "", "", schema.GroupVersionResource{}, "", "", nil, false, nil)

View File

@ -21,7 +21,7 @@ import (
"strings" "strings"
"testing" "testing"
"k8s.io/api/admissionregistration/v1" v1 "k8s.io/api/admissionregistration/v1"
corev1 "k8s.io/api/core/v1" corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@ -34,6 +34,14 @@ import (
"k8s.io/apiserver/pkg/admission/plugin/webhook/predicates/object" "k8s.io/apiserver/pkg/admission/plugin/webhook/predicates/object"
) )
func gvr(group, version, resource string) schema.GroupVersionResource {
return schema.GroupVersionResource{Group: group, Version: version, Resource: resource}
}
func gvk(group, version, kind string) schema.GroupVersionKind {
return schema.GroupVersionKind{Group: group, Version: version, Kind: kind}
}
func TestShouldCallHook(t *testing.T) { func TestShouldCallHook(t *testing.T) {
a := &Webhook{namespaceMatcher: &namespace.Matcher{}, objectMatcher: &object.Matcher{}} a := &Webhook{namespaceMatcher: &namespace.Matcher{}, objectMatcher: &object.Matcher{}}
@ -48,19 +56,19 @@ func TestShouldCallHook(t *testing.T) {
} }
return "" return ""
}) })
mapper.RegisterKindFor(schema.GroupVersionResource{"extensions", "v1beta1", "deployments"}, "", schema.GroupVersionKind{"extensions", "v1beta1", "Deployment"}) mapper.RegisterKindFor(gvr("extensions", "v1beta1", "deployments"), "", gvk("extensions", "v1beta1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1", "deployments"}, "", schema.GroupVersionKind{"apps", "v1", "Deployment"}) mapper.RegisterKindFor(gvr("apps", "v1", "deployments"), "", gvk("apps", "v1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta1", "deployments"}, "", schema.GroupVersionKind{"apps", "v1beta1", "Deployment"}) mapper.RegisterKindFor(gvr("apps", "v1beta1", "deployments"), "", gvk("apps", "v1beta1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1alpha1", "deployments"}, "", schema.GroupVersionKind{"apps", "v1alpha1", "Deployment"}) mapper.RegisterKindFor(gvr("apps", "v1alpha1", "deployments"), "", gvk("apps", "v1alpha1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"extensions", "v1beta1", "deployments"}, "scale", schema.GroupVersionKind{"extensions", "v1beta1", "Scale"}) mapper.RegisterKindFor(gvr("extensions", "v1beta1", "deployments"), "scale", gvk("extensions", "v1beta1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1", "deployments"}, "scale", schema.GroupVersionKind{"autoscaling", "v1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1", "deployments"), "scale", gvk("autoscaling", "v1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta1", "deployments"}, "scale", schema.GroupVersionKind{"apps", "v1beta1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1beta1", "deployments"), "scale", gvk("apps", "v1beta1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1alpha1", "deployments"}, "scale", schema.GroupVersionKind{"apps", "v1alpha1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1alpha1", "deployments"), "scale", gvk("apps", "v1alpha1", "Scale"))
// register invalid kinds to trigger an error // register invalid kinds to trigger an error
mapper.RegisterKindFor(schema.GroupVersionResource{"example.com", "v1", "widgets"}, "", schema.GroupVersionKind{"", "", ""}) mapper.RegisterKindFor(gvr("example.com", "v1", "widgets"), "", gvk("", "", ""))
mapper.RegisterKindFor(schema.GroupVersionResource{"example.com", "v2", "widgets"}, "", schema.GroupVersionKind{"", "", ""}) mapper.RegisterKindFor(gvr("example.com", "v2", "widgets"), "", gvk("", "", ""))
interfaces := &admission.RuntimeObjectInterfaces{EquivalentResourceMapper: mapper} interfaces := &admission.RuntimeObjectInterfaces{EquivalentResourceMapper: mapper}
@ -79,7 +87,7 @@ func TestShouldCallHook(t *testing.T) {
{ {
name: "no rules (just write)", name: "no rules (just write)",
webhook: &v1.ValidatingWebhook{NamespaceSelector: &metav1.LabelSelector{}, Rules: []v1.RuleWithOperations{}}, webhook: &v1.ValidatingWebhook{NamespaceSelector: &metav1.LabelSelector{}, Rules: []v1.RuleWithOperations{}},
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"apps", "v1", "Deployment"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("apps", "v1", "Deployment"), "ns", "name", gvr("apps", "v1", "deployments"), "", admission.Create, &metav1.CreateOptions{}, false, nil),
expectCall: false, expectCall: false,
}, },
{ {
@ -92,7 +100,7 @@ func TestShouldCallHook(t *testing.T) {
Operations: []v1.OperationType{"*"}, Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"example.com"}, APIVersions: []string{"v1"}, Resources: []string{"widgets"}, Scope: &allScopes}, Rule: v1.Rule{APIGroups: []string{"example.com"}, APIVersions: []string{"v1"}, Resources: []string{"widgets"}, Scope: &allScopes},
}}}, }}},
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"example.com", "v2", "Widget"}, "ns", "name", schema.GroupVersionResource{"example.com", "v2", "widgets"}, "", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("example.com", "v2", "Widget"), "ns", "name", gvr("example.com", "v2", "widgets"), "", admission.Create, &metav1.CreateOptions{}, false, nil),
expectCall: false, expectCall: false,
expectErr: "unknown kind", expectErr: "unknown kind",
}, },
@ -105,10 +113,10 @@ func TestShouldCallHook(t *testing.T) {
Operations: []v1.OperationType{"*"}, Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"*"}, APIVersions: []string{"*"}, Resources: []string{"*"}, Scope: &allScopes}, Rule: v1.Rule{APIGroups: []string{"*"}, APIVersions: []string{"*"}, Resources: []string{"*"}, Scope: &allScopes},
}}}, }}},
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"apps", "v1", "Deployment"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("apps", "v1", "Deployment"), "ns", "name", gvr("apps", "v1", "deployments"), "", admission.Create, &metav1.CreateOptions{}, false, nil),
expectCall: true, expectCall: true,
expectCallKind: schema.GroupVersionKind{"apps", "v1", "Deployment"}, expectCallKind: gvk("apps", "v1", "Deployment"),
expectCallResource: schema.GroupVersionResource{"apps", "v1", "deployments"}, expectCallResource: gvr("apps", "v1", "deployments"),
expectCallSubresource: "", expectCallSubresource: "",
}, },
{ {
@ -126,10 +134,10 @@ func TestShouldCallHook(t *testing.T) {
Operations: []v1.OperationType{"*"}, Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1"}, Resources: []string{"deployments"}, Scope: &allScopes}, Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1"}, Resources: []string{"deployments"}, Scope: &allScopes},
}}}, }}},
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"apps", "v1", "Deployment"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("apps", "v1", "Deployment"), "ns", "name", gvr("apps", "v1", "deployments"), "", admission.Create, &metav1.CreateOptions{}, false, nil),
expectCall: true, expectCall: true,
expectCallKind: schema.GroupVersionKind{"apps", "v1", "Deployment"}, expectCallKind: gvk("apps", "v1", "Deployment"),
expectCallResource: schema.GroupVersionResource{"apps", "v1", "deployments"}, expectCallResource: gvr("apps", "v1", "deployments"),
expectCallSubresource: "", expectCallSubresource: "",
}, },
{ {
@ -144,7 +152,7 @@ func TestShouldCallHook(t *testing.T) {
Operations: []v1.OperationType{"*"}, Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments"}, Scope: &allScopes}, Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments"}, Scope: &allScopes},
}}}, }}},
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"apps", "v1", "Deployment"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("apps", "v1", "Deployment"), "ns", "name", gvr("apps", "v1", "deployments"), "", admission.Create, &metav1.CreateOptions{}, false, nil),
expectCall: false, expectCall: false,
}, },
{ {
@ -160,7 +168,7 @@ func TestShouldCallHook(t *testing.T) {
Operations: []v1.OperationType{"*"}, Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments"}, Scope: &allScopes}, Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments"}, Scope: &allScopes},
}}}, }}},
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"apps", "v1", "Deployment"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("apps", "v1", "Deployment"), "ns", "name", gvr("apps", "v1", "deployments"), "", admission.Create, &metav1.CreateOptions{}, false, nil),
expectCall: false, expectCall: false,
}, },
{ {
@ -176,10 +184,10 @@ func TestShouldCallHook(t *testing.T) {
Operations: []v1.OperationType{"*"}, Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments"}, Scope: &allScopes}, Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments"}, Scope: &allScopes},
}}}, }}},
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"apps", "v1", "Deployment"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("apps", "v1", "Deployment"), "ns", "name", gvr("apps", "v1", "deployments"), "", admission.Create, &metav1.CreateOptions{}, false, nil),
expectCall: true, expectCall: true,
expectCallKind: schema.GroupVersionKind{"extensions", "v1beta1", "Deployment"}, expectCallKind: gvk("extensions", "v1beta1", "Deployment"),
expectCallResource: schema.GroupVersionResource{"extensions", "v1beta1", "deployments"}, expectCallResource: gvr("extensions", "v1beta1", "deployments"),
expectCallSubresource: "", expectCallSubresource: "",
}, },
{ {
@ -195,10 +203,10 @@ func TestShouldCallHook(t *testing.T) {
Operations: []v1.OperationType{"*"}, Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"extensions"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments"}, Scope: &allScopes}, Rule: v1.Rule{APIGroups: []string{"extensions"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments"}, Scope: &allScopes},
}}}, }}},
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"apps", "v1", "Deployment"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("apps", "v1", "Deployment"), "ns", "name", gvr("apps", "v1", "deployments"), "", admission.Create, &metav1.CreateOptions{}, false, nil),
expectCall: true, expectCall: true,
expectCallKind: schema.GroupVersionKind{"apps", "v1beta1", "Deployment"}, expectCallKind: gvk("apps", "v1beta1", "Deployment"),
expectCallResource: schema.GroupVersionResource{"apps", "v1beta1", "deployments"}, expectCallResource: gvr("apps", "v1beta1", "deployments"),
expectCallSubresource: "", expectCallSubresource: "",
}, },
@ -217,10 +225,10 @@ func TestShouldCallHook(t *testing.T) {
Operations: []v1.OperationType{"*"}, Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes}, Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes},
}}}, }}},
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "scale", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("autoscaling", "v1", "Scale"), "ns", "name", gvr("apps", "v1", "deployments"), "scale", admission.Create, &metav1.CreateOptions{}, false, nil),
expectCall: true, expectCall: true,
expectCallKind: schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, expectCallKind: gvk("autoscaling", "v1", "Scale"),
expectCallResource: schema.GroupVersionResource{"apps", "v1", "deployments"}, expectCallResource: gvr("apps", "v1", "deployments"),
expectCallSubresource: "scale", expectCallSubresource: "scale",
}, },
{ {
@ -235,7 +243,7 @@ func TestShouldCallHook(t *testing.T) {
Operations: []v1.OperationType{"*"}, Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes}, Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes},
}}}, }}},
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "scale", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("autoscaling", "v1", "Scale"), "ns", "name", gvr("apps", "v1", "deployments"), "scale", admission.Create, &metav1.CreateOptions{}, false, nil),
expectCall: false, expectCall: false,
}, },
{ {
@ -251,7 +259,7 @@ func TestShouldCallHook(t *testing.T) {
Operations: []v1.OperationType{"*"}, Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes}, Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes},
}}}, }}},
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "scale", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("autoscaling", "v1", "Scale"), "ns", "name", gvr("apps", "v1", "deployments"), "scale", admission.Create, &metav1.CreateOptions{}, false, nil),
expectCall: false, expectCall: false,
}, },
{ {
@ -267,10 +275,10 @@ func TestShouldCallHook(t *testing.T) {
Operations: []v1.OperationType{"*"}, Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes}, Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes},
}}}, }}},
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "scale", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("autoscaling", "v1", "Scale"), "ns", "name", gvr("apps", "v1", "deployments"), "scale", admission.Create, &metav1.CreateOptions{}, false, nil),
expectCall: true, expectCall: true,
expectCallKind: schema.GroupVersionKind{"extensions", "v1beta1", "Scale"}, expectCallKind: gvk("extensions", "v1beta1", "Scale"),
expectCallResource: schema.GroupVersionResource{"extensions", "v1beta1", "deployments"}, expectCallResource: gvr("extensions", "v1beta1", "deployments"),
expectCallSubresource: "scale", expectCallSubresource: "scale",
}, },
{ {
@ -286,10 +294,10 @@ func TestShouldCallHook(t *testing.T) {
Operations: []v1.OperationType{"*"}, Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"extensions"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes}, Rule: v1.Rule{APIGroups: []string{"extensions"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes},
}}}, }}},
attrs: admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "scale", admission.Create, &metav1.CreateOptions{}, false, nil), attrs: admission.NewAttributesRecord(nil, nil, gvk("autoscaling", "v1", "Scale"), "ns", "name", gvr("apps", "v1", "deployments"), "scale", admission.Create, &metav1.CreateOptions{}, false, nil),
expectCall: true, expectCall: true,
expectCallKind: schema.GroupVersionKind{"apps", "v1beta1", "Scale"}, expectCallKind: gvk("apps", "v1beta1", "Scale"),
expectCallResource: schema.GroupVersionResource{"apps", "v1beta1", "deployments"}, expectCallResource: gvr("apps", "v1beta1", "deployments"),
expectCallSubresource: "scale", expectCallSubresource: "scale",
}, },
} }
@ -368,23 +376,23 @@ func BenchmarkShouldCallHookWithComplexSelector(b *testing.B) {
} }
return "" return ""
}) })
mapper.RegisterKindFor(schema.GroupVersionResource{"extensions", "v1beta1", "deployments"}, "", schema.GroupVersionKind{"extensions", "v1beta1", "Deployment"}) mapper.RegisterKindFor(gvr("extensions", "v1beta1", "deployments"), "", gvk("extensions", "v1beta1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1", "deployments"}, "", schema.GroupVersionKind{"apps", "v1", "Deployment"}) mapper.RegisterKindFor(gvr("apps", "v1", "deployments"), "", gvk("apps", "v1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta1", "deployments"}, "", schema.GroupVersionKind{"apps", "v1beta1", "Deployment"}) mapper.RegisterKindFor(gvr("apps", "v1beta1", "deployments"), "", gvk("apps", "v1beta1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1alpha1", "deployments"}, "", schema.GroupVersionKind{"apps", "v1alpha1", "Deployment"}) mapper.RegisterKindFor(gvr("apps", "v1alpha1", "deployments"), "", gvk("apps", "v1alpha1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"extensions", "v1beta1", "deployments"}, "scale", schema.GroupVersionKind{"extensions", "v1beta1", "Scale"}) mapper.RegisterKindFor(gvr("extensions", "v1beta1", "deployments"), "scale", gvk("extensions", "v1beta1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1", "deployments"}, "scale", schema.GroupVersionKind{"autoscaling", "v1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1", "deployments"), "scale", gvk("autoscaling", "v1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta1", "deployments"}, "scale", schema.GroupVersionKind{"apps", "v1beta1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1beta1", "deployments"), "scale", gvk("apps", "v1beta1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1alpha1", "deployments"}, "scale", schema.GroupVersionKind{"apps", "v1alpha1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1alpha1", "deployments"), "scale", gvk("apps", "v1alpha1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1", "statefulset"}, "", schema.GroupVersionKind{"apps", "v1", "StatefulSet"}) mapper.RegisterKindFor(gvr("apps", "v1", "statefulset"), "", gvk("apps", "v1", "StatefulSet"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta1", "statefulset"}, "", schema.GroupVersionKind{"apps", "v1beta1", "StatefulSet"}) mapper.RegisterKindFor(gvr("apps", "v1beta1", "statefulset"), "", gvk("apps", "v1beta1", "StatefulSet"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta2", "statefulset"}, "", schema.GroupVersionKind{"apps", "v1beta2", "StatefulSet"}) mapper.RegisterKindFor(gvr("apps", "v1beta2", "statefulset"), "", gvk("apps", "v1beta2", "StatefulSet"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1", "statefulset"}, "scale", schema.GroupVersionKind{"apps", "v1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1", "statefulset"), "scale", gvk("apps", "v1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta1", "statefulset"}, "scale", schema.GroupVersionKind{"apps", "v1beta1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1beta1", "statefulset"), "scale", gvk("apps", "v1beta1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1alpha2", "statefulset"}, "scale", schema.GroupVersionKind{"apps", "v1beta2", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1alpha2", "statefulset"), "scale", gvk("apps", "v1beta2", "Scale"))
nsSelector := make(map[string]string) nsSelector := make(map[string]string)
for i := 0; i < 100; i++ { for i := 0; i < 100; i++ {
@ -408,7 +416,7 @@ func BenchmarkShouldCallHookWithComplexSelector(b *testing.B) {
} }
wbAccessor := webhook.NewValidatingWebhookAccessor("webhook", "webhook-cfg", wb) wbAccessor := webhook.NewValidatingWebhookAccessor("webhook", "webhook-cfg", wb)
attrs := admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "scale", admission.Create, &metav1.CreateOptions{}, false, nil) attrs := admission.NewAttributesRecord(nil, nil, gvk("autoscaling", "v1", "Scale"), "ns", "name", gvr("apps", "v1", "deployments"), "scale", admission.Create, &metav1.CreateOptions{}, false, nil)
interfaces := &admission.RuntimeObjectInterfaces{EquivalentResourceMapper: mapper} interfaces := &admission.RuntimeObjectInterfaces{EquivalentResourceMapper: mapper}
a := &Webhook{namespaceMatcher: &namespace.Matcher{NamespaceLister: namespaceLister}, objectMatcher: &object.Matcher{}} a := &Webhook{namespaceMatcher: &namespace.Matcher{NamespaceLister: namespaceLister}, objectMatcher: &object.Matcher{}}
@ -437,23 +445,23 @@ func BenchmarkShouldCallHookWithComplexRule(b *testing.B) {
} }
return "" return ""
}) })
mapper.RegisterKindFor(schema.GroupVersionResource{"extensions", "v1beta1", "deployments"}, "", schema.GroupVersionKind{"extensions", "v1beta1", "Deployment"}) mapper.RegisterKindFor(gvr("extensions", "v1beta1", "deployments"), "", gvk("extensions", "v1beta1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1", "deployments"}, "", schema.GroupVersionKind{"apps", "v1", "Deployment"}) mapper.RegisterKindFor(gvr("apps", "v1", "deployments"), "", gvk("apps", "v1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta1", "deployments"}, "", schema.GroupVersionKind{"apps", "v1beta1", "Deployment"}) mapper.RegisterKindFor(gvr("apps", "v1beta1", "deployments"), "", gvk("apps", "v1beta1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1alpha1", "deployments"}, "", schema.GroupVersionKind{"apps", "v1alpha1", "Deployment"}) mapper.RegisterKindFor(gvr("apps", "v1alpha1", "deployments"), "", gvk("apps", "v1alpha1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"extensions", "v1beta1", "deployments"}, "scale", schema.GroupVersionKind{"extensions", "v1beta1", "Scale"}) mapper.RegisterKindFor(gvr("extensions", "v1beta1", "deployments"), "scale", gvk("extensions", "v1beta1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1", "deployments"}, "scale", schema.GroupVersionKind{"autoscaling", "v1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1", "deployments"), "scale", gvk("autoscaling", "v1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta1", "deployments"}, "scale", schema.GroupVersionKind{"apps", "v1beta1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1beta1", "deployments"), "scale", gvk("apps", "v1beta1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1alpha1", "deployments"}, "scale", schema.GroupVersionKind{"apps", "v1alpha1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1alpha1", "deployments"), "scale", gvk("apps", "v1alpha1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1", "statefulset"}, "", schema.GroupVersionKind{"apps", "v1", "StatefulSet"}) mapper.RegisterKindFor(gvr("apps", "v1", "statefulset"), "", gvk("apps", "v1", "StatefulSet"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta1", "statefulset"}, "", schema.GroupVersionKind{"apps", "v1beta1", "StatefulSet"}) mapper.RegisterKindFor(gvr("apps", "v1beta1", "statefulset"), "", gvk("apps", "v1beta1", "StatefulSet"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta2", "statefulset"}, "", schema.GroupVersionKind{"apps", "v1beta2", "StatefulSet"}) mapper.RegisterKindFor(gvr("apps", "v1beta2", "statefulset"), "", gvk("apps", "v1beta2", "StatefulSet"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1", "statefulset"}, "scale", schema.GroupVersionKind{"apps", "v1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1", "statefulset"), "scale", gvk("apps", "v1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta1", "statefulset"}, "scale", schema.GroupVersionKind{"apps", "v1beta1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1beta1", "statefulset"), "scale", gvk("apps", "v1beta1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1alpha2", "statefulset"}, "scale", schema.GroupVersionKind{"apps", "v1beta2", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1alpha2", "statefulset"), "scale", gvk("apps", "v1beta2", "Scale"))
wb := &v1.ValidatingWebhook{ wb := &v1.ValidatingWebhook{
MatchPolicy: &equivalentMatch, MatchPolicy: &equivalentMatch,
@ -476,7 +484,7 @@ func BenchmarkShouldCallHookWithComplexRule(b *testing.B) {
} }
wbAccessor := webhook.NewValidatingWebhookAccessor("webhook", "webhook-cfg", wb) wbAccessor := webhook.NewValidatingWebhookAccessor("webhook", "webhook-cfg", wb)
attrs := admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "scale", admission.Create, &metav1.CreateOptions{}, false, nil) attrs := admission.NewAttributesRecord(nil, nil, gvk("autoscaling", "v1", "Scale"), "ns", "name", gvr("apps", "v1", "deployments"), "scale", admission.Create, &metav1.CreateOptions{}, false, nil)
interfaces := &admission.RuntimeObjectInterfaces{EquivalentResourceMapper: mapper} interfaces := &admission.RuntimeObjectInterfaces{EquivalentResourceMapper: mapper}
a := &Webhook{namespaceMatcher: &namespace.Matcher{NamespaceLister: namespaceLister}, objectMatcher: &object.Matcher{}} a := &Webhook{namespaceMatcher: &namespace.Matcher{NamespaceLister: namespaceLister}, objectMatcher: &object.Matcher{}}
@ -505,23 +513,23 @@ func BenchmarkShouldCallHookWithComplexSelectorAndRule(b *testing.B) {
} }
return "" return ""
}) })
mapper.RegisterKindFor(schema.GroupVersionResource{"extensions", "v1beta1", "deployments"}, "", schema.GroupVersionKind{"extensions", "v1beta1", "Deployment"}) mapper.RegisterKindFor(gvr("extensions", "v1beta1", "deployments"), "", gvk("extensions", "v1beta1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1", "deployments"}, "", schema.GroupVersionKind{"apps", "v1", "Deployment"}) mapper.RegisterKindFor(gvr("apps", "v1", "deployments"), "", gvk("apps", "v1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta1", "deployments"}, "", schema.GroupVersionKind{"apps", "v1beta1", "Deployment"}) mapper.RegisterKindFor(gvr("apps", "v1beta1", "deployments"), "", gvk("apps", "v1beta1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1alpha1", "deployments"}, "", schema.GroupVersionKind{"apps", "v1alpha1", "Deployment"}) mapper.RegisterKindFor(gvr("apps", "v1alpha1", "deployments"), "", gvk("apps", "v1alpha1", "Deployment"))
mapper.RegisterKindFor(schema.GroupVersionResource{"extensions", "v1beta1", "deployments"}, "scale", schema.GroupVersionKind{"extensions", "v1beta1", "Scale"}) mapper.RegisterKindFor(gvr("extensions", "v1beta1", "deployments"), "scale", gvk("extensions", "v1beta1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1", "deployments"}, "scale", schema.GroupVersionKind{"autoscaling", "v1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1", "deployments"), "scale", gvk("autoscaling", "v1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta1", "deployments"}, "scale", schema.GroupVersionKind{"apps", "v1beta1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1beta1", "deployments"), "scale", gvk("apps", "v1beta1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1alpha1", "deployments"}, "scale", schema.GroupVersionKind{"apps", "v1alpha1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1alpha1", "deployments"), "scale", gvk("apps", "v1alpha1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1", "statefulset"}, "", schema.GroupVersionKind{"apps", "v1", "StatefulSet"}) mapper.RegisterKindFor(gvr("apps", "v1", "statefulset"), "", gvk("apps", "v1", "StatefulSet"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta1", "statefulset"}, "", schema.GroupVersionKind{"apps", "v1beta1", "StatefulSet"}) mapper.RegisterKindFor(gvr("apps", "v1beta1", "statefulset"), "", gvk("apps", "v1beta1", "StatefulSet"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta2", "statefulset"}, "", schema.GroupVersionKind{"apps", "v1beta2", "StatefulSet"}) mapper.RegisterKindFor(gvr("apps", "v1beta2", "statefulset"), "", gvk("apps", "v1beta2", "StatefulSet"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1", "statefulset"}, "scale", schema.GroupVersionKind{"apps", "v1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1", "statefulset"), "scale", gvk("apps", "v1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1beta1", "statefulset"}, "scale", schema.GroupVersionKind{"apps", "v1beta1", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1beta1", "statefulset"), "scale", gvk("apps", "v1beta1", "Scale"))
mapper.RegisterKindFor(schema.GroupVersionResource{"apps", "v1alpha2", "statefulset"}, "scale", schema.GroupVersionKind{"apps", "v1beta2", "Scale"}) mapper.RegisterKindFor(gvr("apps", "v1alpha2", "statefulset"), "scale", gvk("apps", "v1beta2", "Scale"))
nsSelector := make(map[string]string) nsSelector := make(map[string]string)
for i := 0; i < 100; i++ { for i := 0; i < 100; i++ {
@ -549,7 +557,7 @@ func BenchmarkShouldCallHookWithComplexSelectorAndRule(b *testing.B) {
} }
wbAccessor := webhook.NewValidatingWebhookAccessor("webhook", "webhook-cfg", wb) wbAccessor := webhook.NewValidatingWebhookAccessor("webhook", "webhook-cfg", wb)
attrs := admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{"autoscaling", "v1", "Scale"}, "ns", "name", schema.GroupVersionResource{"apps", "v1", "deployments"}, "scale", admission.Create, &metav1.CreateOptions{}, false, nil) attrs := admission.NewAttributesRecord(nil, nil, gvk("autoscaling", "v1", "Scale"), "ns", "name", gvr("apps", "v1", "deployments"), "scale", admission.Create, &metav1.CreateOptions{}, false, nil)
interfaces := &admission.RuntimeObjectInterfaces{EquivalentResourceMapper: mapper} interfaces := &admission.RuntimeObjectInterfaces{EquivalentResourceMapper: mapper}
a := &Webhook{namespaceMatcher: &namespace.Matcher{NamespaceLister: namespaceLister}, objectMatcher: &object.Matcher{}} a := &Webhook{namespaceMatcher: &namespace.Matcher{NamespaceLister: namespaceLister}, objectMatcher: &object.Matcher{}}

View File

@ -116,7 +116,7 @@ func (m *Matcher) MatchNamespaceSelector(p NamespaceSelectorProvider, attr admis
if !ok { if !ok {
return false, apierrors.NewInternalError(err) return false, apierrors.NewInternalError(err)
} }
return false, &apierrors.StatusError{status.Status()} return false, &apierrors.StatusError{ErrStatus: status.Status()}
} }
if err != nil { if err != nil {
return false, apierrors.NewInternalError(err) return false, apierrors.NewInternalError(err)

View File

@ -297,7 +297,18 @@ func ConvertToMutatingTestCases(tests []ValidatingTest, configurationName string
func ConvertToMutatingWebhooks(webhooks []registrationv1.ValidatingWebhook) []registrationv1.MutatingWebhook { func ConvertToMutatingWebhooks(webhooks []registrationv1.ValidatingWebhook) []registrationv1.MutatingWebhook {
mutating := make([]registrationv1.MutatingWebhook, len(webhooks)) mutating := make([]registrationv1.MutatingWebhook, len(webhooks))
for i, h := range webhooks { for i, h := range webhooks {
mutating[i] = registrationv1.MutatingWebhook{h.Name, h.ClientConfig, h.Rules, h.FailurePolicy, h.MatchPolicy, h.NamespaceSelector, h.ObjectSelector, h.SideEffects, h.TimeoutSeconds, h.AdmissionReviewVersions, nil} mutating[i] = registrationv1.MutatingWebhook{
Name: h.Name,
ClientConfig: h.ClientConfig,
Rules: h.Rules,
FailurePolicy: h.FailurePolicy,
MatchPolicy: h.MatchPolicy,
NamespaceSelector: h.NamespaceSelector,
ObjectSelector: h.ObjectSelector,
SideEffects: h.SideEffects,
TimeoutSeconds: h.TimeoutSeconds,
AdmissionReviewVersions: h.AdmissionReviewVersions,
}
} }
return mutating return mutating
} }

View File

@ -2085,7 +2085,7 @@ func watcher(mediaType string, r io.ReadCloser) streaming.Decoder {
} }
func TestGetPartialObjectMetadata(t *testing.T) { func TestGetPartialObjectMetadata(t *testing.T) {
now := metav1.Time{metav1.Now().Rfc3339Copy().Local()} now := metav1.Time{Time: metav1.Now().Rfc3339Copy().Local()}
storage := map[string]rest.Storage{} storage := map[string]rest.Storage{}
simpleStorage := SimpleRESTStorage{ simpleStorage := SimpleRESTStorage{
item: genericapitesting.Simple{ item: genericapitesting.Simple{

View File

@ -100,13 +100,13 @@ func WithStorageVersionPrecondition(handler http.Handler, svm storageversion.Man
} }
// If the resource's StorageVersion is not in the to-be-updated list, let it pass. // If the resource's StorageVersion is not in the to-be-updated list, let it pass.
// Non-persisted resources are not in the to-be-updated list, so they will pass. // Non-persisted resources are not in the to-be-updated list, so they will pass.
gr := schema.GroupResource{requestInfo.APIGroup, requestInfo.Resource} gr := schema.GroupResource{Group: requestInfo.APIGroup, Resource: requestInfo.Resource}
if !svm.PendingUpdate(gr) { if !svm.PendingUpdate(gr) {
handler.ServeHTTP(w, req) handler.ServeHTTP(w, req)
return return
} }
gv := schema.GroupVersion{requestInfo.APIGroup, requestInfo.APIVersion} gv := schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion}
responsewriters.ErrorNegotiated(apierrors.NewServiceUnavailable(fmt.Sprintf("wait for storage version registration to complete for resource: %v, last seen error: %v", gr, svm.LastUpdateError(gr))), s, gv, w, req) responsewriters.ErrorNegotiated(apierrors.NewServiceUnavailable(fmt.Sprintf("wait for storage version registration to complete for resource: %v, last seen error: %v", gr, svm.LastUpdateError(gr))), s, gv, w, req)
}) })
} }

View File

@ -846,7 +846,7 @@ func TestUpdateViaSubresources(t *testing.T) {
APIVersion: "apps/v1", APIVersion: "apps/v1",
FieldsType: "FieldsV1", FieldsType: "FieldsV1",
FieldsV1: &metav1.FieldsV1{ FieldsV1: &metav1.FieldsV1{
[]byte(`{"f:metadata":{"f:labels":{"f:another_field":{}}}}`), Raw: []byte(`{"f:metadata":{"f:labels":{"f:another_field":{}}}}`),
}, },
}, },
}) })

View File

@ -45,7 +45,6 @@ func (*fakeManager) Update(_, newObj runtime.Object, managed internal.Managed, _
func (*fakeManager) Apply(_, _ runtime.Object, _ internal.Managed, _ string, _ bool) (runtime.Object, internal.Managed, error) { func (*fakeManager) Apply(_, _ runtime.Object, _ internal.Managed, _ string, _ bool) (runtime.Object, internal.Managed, error) {
panic("not implemented") panic("not implemented")
return nil, nil, nil
} }
func TestCapManagersManagerMergesEntries(t *testing.T) { func TestCapManagersManagerMergesEntries(t *testing.T) {

View File

@ -473,14 +473,14 @@ func TestSortEncodedManagedFields(t *testing.T) {
{ {
name: "sort drops nanoseconds", name: "sort drops nanoseconds",
managedFields: []metav1.ManagedFieldsEntry{ managedFields: []metav1.ManagedFieldsEntry{
{Manager: "c", Operation: metav1.ManagedFieldsOperationUpdate, Time: &metav1.Time{time.Date(2000, time.January, 0, 0, 0, 0, 1, time.UTC)}}, {Manager: "c", Operation: metav1.ManagedFieldsOperationUpdate, Time: &metav1.Time{Time: time.Date(2000, time.January, 0, 0, 0, 0, 1, time.UTC)}},
{Manager: "a", Operation: metav1.ManagedFieldsOperationUpdate, Time: &metav1.Time{time.Date(2000, time.January, 0, 0, 0, 0, 2, time.UTC)}}, {Manager: "a", Operation: metav1.ManagedFieldsOperationUpdate, Time: &metav1.Time{Time: time.Date(2000, time.January, 0, 0, 0, 0, 2, time.UTC)}},
{Manager: "b", Operation: metav1.ManagedFieldsOperationUpdate, Time: &metav1.Time{time.Date(2000, time.January, 0, 0, 0, 0, 3, time.UTC)}}, {Manager: "b", Operation: metav1.ManagedFieldsOperationUpdate, Time: &metav1.Time{Time: time.Date(2000, time.January, 0, 0, 0, 0, 3, time.UTC)}},
}, },
expected: []metav1.ManagedFieldsEntry{ expected: []metav1.ManagedFieldsEntry{
{Manager: "a", Operation: metav1.ManagedFieldsOperationUpdate, Time: &metav1.Time{time.Date(2000, time.January, 0, 0, 0, 0, 2, time.UTC)}}, {Manager: "a", Operation: metav1.ManagedFieldsOperationUpdate, Time: &metav1.Time{Time: time.Date(2000, time.January, 0, 0, 0, 0, 2, time.UTC)}},
{Manager: "b", Operation: metav1.ManagedFieldsOperationUpdate, Time: &metav1.Time{time.Date(2000, time.January, 0, 0, 0, 0, 3, time.UTC)}}, {Manager: "b", Operation: metav1.ManagedFieldsOperationUpdate, Time: &metav1.Time{Time: time.Date(2000, time.January, 0, 0, 0, 0, 3, time.UTC)}},
{Manager: "c", Operation: metav1.ManagedFieldsOperationUpdate, Time: &metav1.Time{time.Date(2000, time.January, 0, 0, 0, 0, 1, time.UTC)}}, {Manager: "c", Operation: metav1.ManagedFieldsOperationUpdate, Time: &metav1.Time{Time: time.Date(2000, time.January, 0, 0, 0, 0, 1, time.UTC)}},
}, },
}, },
{ {

View File

@ -729,13 +729,8 @@ func setupInFlightWatchRequestHandler(s *GenericAPIServer) *inFlightRequest {
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
return return
} }
select { <-signals.ShuttingDown()
case <-signals.ShuttingDown():
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
return
}
w.WriteHeader(http.StatusInternalServerError)
}) })
s.Handler.NonGoRestfulMux.Handle("/apis/watches.group/v1/namespaces/foo/bar", handler) s.Handler.NonGoRestfulMux.Handle("/apis/watches.group/v1/namespaces/foo/bar", handler)
return inflight return inflight

View File

@ -619,7 +619,7 @@ func TestKMSPluginHealthz(t *testing.T) {
p.service = nil p.service = nil
p.l = nil p.l = nil
p.lastResponse = nil p.lastResponse = nil
p.keyID = kmsv2Probe.keyID p.keyID.Store(kmsv2Probe.keyID.Load())
default: default:
t.Fatalf("unexpected probe type %T", p) t.Fatalf("unexpected probe type %T", p)
} }

View File

@ -230,6 +230,7 @@ func (s *EtcdOptions) Complete(
if len(s.EncryptionProviderConfigFilepath) != 0 { if len(s.EncryptionProviderConfigFilepath) != 0 {
ctxServer := wait.ContextForChannel(stopCh) ctxServer := wait.ContextForChannel(stopCh)
// nolint:govet // The only code path where closeTransformers does not get called is when it gets stored in dynamicTransformers.
ctxTransformers, closeTransformers := context.WithCancel(ctxServer) ctxTransformers, closeTransformers := context.WithCancel(ctxServer)
encryptionConfiguration, err := encryptionconfig.LoadEncryptionConfig(ctxTransformers, s.EncryptionProviderConfigFilepath, s.EncryptionProviderConfigAutomaticReload) encryptionConfiguration, err := encryptionconfig.LoadEncryptionConfig(ctxTransformers, s.EncryptionProviderConfigFilepath, s.EncryptionProviderConfigAutomaticReload)
@ -248,6 +249,7 @@ func (s *EtcdOptions) Complete(
return fmt.Errorf("failed to start kms encryption config hot reload controller. only 1 health check should be available when reload is enabled") return fmt.Errorf("failed to start kms encryption config hot reload controller. only 1 health check should be available when reload is enabled")
} }
// Here the dynamic transformers take ownership of the transformers and their cancellation.
dynamicTransformers := encryptionconfig.NewDynamicTransformers(encryptionConfiguration.Transformers, encryptionConfiguration.HealthChecks[0], closeTransformers, encryptionConfiguration.KMSCloseGracePeriod) dynamicTransformers := encryptionconfig.NewDynamicTransformers(encryptionConfiguration.Transformers, encryptionConfiguration.HealthChecks[0], closeTransformers, encryptionConfiguration.KMSCloseGracePeriod)
// add post start hook to start hot reload controller // add post start hook to start hot reload controller
@ -285,6 +287,7 @@ func (s *EtcdOptions) Complete(
s.complete = true s.complete = true
// nolint:govet // The only code path where closeTransformers does not get called is when it gets stored in dynamicTransformers.
return nil return nil
} }

View File

@ -288,7 +288,8 @@ func RunTestWatchContextCancel(ctx context.Context, t *testing.T, store storage.
func RunTestWatchDeleteEventObjectHaveLatestRV(ctx context.Context, t *testing.T, store storage.Interface) { func RunTestWatchDeleteEventObjectHaveLatestRV(ctx context.Context, t *testing.T, store storage.Interface) {
key, storedObj := testPropagateStore(ctx, t, store, &example.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "test-ns"}}) key, storedObj := testPropagateStore(ctx, t, store, &example.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "test-ns"}})
watchCtx, _ := context.WithTimeout(ctx, wait.ForeverTestTimeout) watchCtx, cancel := context.WithTimeout(ctx, wait.ForeverTestTimeout)
t.Cleanup(cancel)
w, err := store.Watch(watchCtx, key, storage.ListOptions{ResourceVersion: storedObj.ResourceVersion, Predicate: storage.Everything}) w, err := store.Watch(watchCtx, key, storage.ListOptions{ResourceVersion: storedObj.ResourceVersion, Predicate: storage.Everything})
if err != nil { if err != nil {
t.Fatalf("Watch failed: %v", err) t.Fatalf("Watch failed: %v", err)
@ -314,7 +315,8 @@ func RunTestWatchDeleteEventObjectHaveLatestRV(ctx context.Context, t *testing.T
} }
func RunTestWatchInitializationSignal(ctx context.Context, t *testing.T, store storage.Interface) { func RunTestWatchInitializationSignal(ctx context.Context, t *testing.T, store storage.Interface) {
ctx, _ = context.WithTimeout(ctx, 5*time.Second) ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
t.Cleanup(cancel)
initSignal := utilflowcontrol.NewInitializationSignal() initSignal := utilflowcontrol.NewInitializationSignal()
ctx = utilflowcontrol.WithInitializationSignal(ctx, initSignal) ctx = utilflowcontrol.WithInitializationSignal(ctx, initSignal)

View File

@ -655,7 +655,8 @@ func TestWatchDispatchBookmarkEvents(t *testing.T) {
for i, c := range tests { for i, c := range tests {
pred := storage.Everything pred := storage.Everything
pred.AllowWatchBookmarks = c.allowWatchBookmark pred.AllowWatchBookmarks = c.allowWatchBookmark
ctx, _ := context.WithTimeout(context.Background(), c.timeout) ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
t.Cleanup(cancel)
watcher, err := cacher.Watch(ctx, "pods/ns/foo", storage.ListOptions{ResourceVersion: startVersion, Predicate: pred}) watcher, err := cacher.Watch(ctx, "pods/ns/foo", storage.ListOptions{ResourceVersion: startVersion, Predicate: pred})
if err != nil { if err != nil {
t.Fatalf("Unexpected error: %v", err) t.Fatalf("Unexpected error: %v", err)
@ -695,7 +696,8 @@ func TestWatchBookmarksWithCorrectResourceVersion(t *testing.T) {
pred := storage.Everything pred := storage.Everything
pred.AllowWatchBookmarks = true pred.AllowWatchBookmarks = true
ctx, _ := context.WithTimeout(context.Background(), 3*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
t.Cleanup(cancel)
watcher, err := cacher.Watch(ctx, "pods/ns", storage.ListOptions{ResourceVersion: "0", Predicate: pred, Recursive: true}) watcher, err := cacher.Watch(ctx, "pods/ns", storage.ListOptions{ResourceVersion: "0", Predicate: pred, Recursive: true})
if err != nil { if err != nil {
t.Fatalf("Unexpected error: %v", err) t.Fatalf("Unexpected error: %v", err)

View File

@ -144,7 +144,8 @@ func TestTimeouts(t *testing.T) {
service, err = NewGRPCService(ctx, socketName.endpoint, tt.callTimeout) service, err = NewGRPCService(ctx, socketName.endpoint, tt.callTimeout)
if err != nil { if err != nil {
t.Fatalf("failed to create envelope service, error: %v", err) t.Errorf("failed to create envelope service, error: %v", err)
return
} }
defer destroyService(service) defer destroyService(service)
kubeAPIServerWG.Done() kubeAPIServerWG.Done()
@ -159,10 +160,12 @@ func TestTimeouts(t *testing.T) {
f, err := mock.NewBase64Plugin(socketName.path) f, err := mock.NewBase64Plugin(socketName.path)
if err != nil { if err != nil {
t.Fatalf("failed to construct test KMS provider server, error: %v", err) t.Errorf("failed to construct test KMS provider server, error: %v", err)
return
} }
if err := f.Start(); err != nil { if err := f.Start(); err != nil {
t.Fatalf("Failed to start test KMS provider server, error: %v", err) t.Errorf("Failed to start test KMS provider server, error: %v", err)
return
} }
defer f.CleanUp() defer f.CleanUp()
kmsPluginWG.Done() kmsPluginWG.Done()
@ -171,6 +174,9 @@ func TestTimeouts(t *testing.T) {
}() }()
kubeAPIServerWG.Wait() kubeAPIServerWG.Wait()
if t.Failed() {
return
}
_, err = service.Encrypt(data) _, err = service.Encrypt(data)
if err == nil && tt.wantErr != "" { if err == nil && tt.wantErr != "" {

View File

@ -404,6 +404,7 @@ func TestValidateAnnotations(t *testing.T) {
} }
t.Run("success", func(t *testing.T) { t.Run("success", func(t *testing.T) {
for i := range successCases { for i := range successCases {
i := i
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
t.Parallel() t.Parallel()
if err := validateAnnotations(successCases[i]); err != nil { if err := validateAnnotations(successCases[i]); err != nil {
@ -441,6 +442,7 @@ func TestValidateAnnotations(t *testing.T) {
t.Run("name error", func(t *testing.T) { t.Run("name error", func(t *testing.T) {
for i := range annotationsNameErrorCases { for i := range annotationsNameErrorCases {
i := i
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
t.Parallel() t.Parallel()
err := validateAnnotations(annotationsNameErrorCases[i].annotations) err := validateAnnotations(annotationsNameErrorCases[i].annotations)
@ -468,6 +470,7 @@ func TestValidateAnnotations(t *testing.T) {
} }
t.Run("size error", func(t *testing.T) { t.Run("size error", func(t *testing.T) {
for i := range annotationsSizeErrorCases { for i := range annotationsSizeErrorCases {
i := i
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
t.Parallel() t.Parallel()
err := validateAnnotations(annotationsSizeErrorCases[i].annotations) err := validateAnnotations(annotationsSizeErrorCases[i].annotations)

View File

@ -149,7 +149,8 @@ func TestTimeouts(t *testing.T) {
service, err = NewGRPCService(ctx, socketName.endpoint, testProviderName, tt.callTimeout) service, err = NewGRPCService(ctx, socketName.endpoint, testProviderName, tt.callTimeout)
if err != nil { if err != nil {
t.Fatalf("failed to create envelope service, error: %v", err) t.Errorf("failed to create envelope service, error: %v", err)
return
} }
defer destroyService(service) defer destroyService(service)
kubeAPIServerWG.Done() kubeAPIServerWG.Done()
@ -164,10 +165,12 @@ func TestTimeouts(t *testing.T) {
f, err := mock.NewBase64Plugin(socketName.path) f, err := mock.NewBase64Plugin(socketName.path)
if err != nil { if err != nil {
t.Fatalf("failed to construct test KMS provider server, error: %v", err) t.Errorf("failed to construct test KMS provider server, error: %v", err)
return
} }
if err := f.Start(); err != nil { if err := f.Start(); err != nil {
t.Fatalf("Failed to start test KMS provider server, error: %v", err) t.Errorf("Failed to start test KMS provider server, error: %v", err)
return
} }
defer f.CleanUp() defer f.CleanUp()
kmsPluginWG.Done() kmsPluginWG.Done()
@ -176,6 +179,9 @@ func TestTimeouts(t *testing.T) {
}() }()
kubeAPIServerWG.Wait() kubeAPIServerWG.Wait()
if t.Failed() {
return
}
_, err = service.Encrypt(ctx, uid, data) _, err = service.Encrypt(ctx, uid, data)
if err == nil && tt.wantErr != "" { if err == nil && tt.wantErr != "" {

View File

@ -208,9 +208,9 @@ func genFS(t *testing.T, rng *rand.Rand, name string, mayMatchClusterScope bool,
} }
dangleStatus := flowcontrol.ConditionFalse dangleStatus := flowcontrol.ConditionFalse
if rng.Float32() < 0.9 && len(goodPLNames) > 0 { if rng.Float32() < 0.9 && len(goodPLNames) > 0 {
fs.Spec.PriorityLevelConfiguration = flowcontrol.PriorityLevelConfigurationReference{pickSetString(rng, goodPLNames)} fs.Spec.PriorityLevelConfiguration = flowcontrol.PriorityLevelConfigurationReference{Name: pickSetString(rng, goodPLNames)}
} else { } else {
fs.Spec.PriorityLevelConfiguration = flowcontrol.PriorityLevelConfigurationReference{pickSetString(rng, badPLNames)} fs.Spec.PriorityLevelConfiguration = flowcontrol.PriorityLevelConfigurationReference{Name: pickSetString(rng, badPLNames)}
ftr.wellFormed = false ftr.wellFormed = false
dangleStatus = flowcontrol.ConditionTrue dangleStatus = flowcontrol.ConditionTrue
} }
@ -220,7 +220,7 @@ func genFS(t *testing.T, rng *rand.Rand, name string, mayMatchClusterScope bool,
fs.Spec.MatchingPrecedence = rng.Int31n(9997) + 2 fs.Spec.MatchingPrecedence = rng.Int31n(9997) + 2
if rng.Float32() < 0.8 { if rng.Float32() < 0.8 {
fdmt := flowcontrol.FlowDistinguisherMethodType(pickSetString(rng, flowDistinguisherMethodTypes)) fdmt := flowcontrol.FlowDistinguisherMethodType(pickSetString(rng, flowDistinguisherMethodTypes))
fs.Spec.DistinguisherMethod = &flowcontrol.FlowDistinguisherMethod{fdmt} fs.Spec.DistinguisherMethod = &flowcontrol.FlowDistinguisherMethod{Type: fdmt}
} }
fs.Spec.Rules = []flowcontrol.PolicyRulesWithSubjects{} fs.Spec.Rules = []flowcontrol.PolicyRulesWithSubjects{}
everyResourceMatcher := -1 everyResourceMatcher := -1
@ -347,7 +347,7 @@ func genPolicyRuleWithSubjects(t *testing.T, rng *rand.Rand, pfx string, mayMatc
if nRR == 0 { if nRR == 0 {
_, _, skippingNRIs = genNonResourceRule(rng, pfx+"-o", false, someMatchesAllNonResourceRequests) _, _, skippingNRIs = genNonResourceRule(rng, pfx+"-o", false, someMatchesAllNonResourceRequests)
} }
rule := flowcontrol.PolicyRulesWithSubjects{subjects, resourceRules, nonResourceRules} rule := flowcontrol.PolicyRulesWithSubjects{Subjects: subjects, ResourceRules: resourceRules, NonResourceRules: nonResourceRules}
if testDebugLogs { if testDebugLogs {
t.Logf("For pfx=%s, mayMatchClusterScope=%v, someMatchesAllResourceRequests=%v, someMatchesAllNonResourceRequests=%v, marr=%v, manrr=%v: generated prws=%s, mu=%s, su=%s, mrr=%s, mnr=%s, srr=%s, snr=%s", pfx, mayMatchClusterScope, someMatchesAllResourceRequests, someMatchesAllNonResourceRequests, matchAllResourceRequests, matchAllNonResourceRequests, fcfmt.Fmt(rule), fcfmt.Fmt(matchingUIs), fcfmt.Fmt(skippingUIs), fcfmt.Fmt(matchingRRIs), fcfmt.Fmt(matchingNRIs), fcfmt.Fmt(skippingRRIs), fcfmt.Fmt(skippingNRIs)) t.Logf("For pfx=%s, mayMatchClusterScope=%v, someMatchesAllResourceRequests=%v, someMatchesAllNonResourceRequests=%v, marr=%v, manrr=%v: generated prws=%s, mu=%s, su=%s, mrr=%s, mnr=%s, srr=%s, snr=%s", pfx, mayMatchClusterScope, someMatchesAllResourceRequests, someMatchesAllNonResourceRequests, matchAllResourceRequests, matchAllNonResourceRequests, fcfmt.Fmt(rule), fcfmt.Fmt(matchingUIs), fcfmt.Fmt(skippingUIs), fcfmt.Fmt(matchingRRIs), fcfmt.Fmt(matchingNRIs), fcfmt.Fmt(skippingRRIs), fcfmt.Fmt(skippingNRIs))
} }
@ -450,7 +450,7 @@ func genUser(rng *rand.Rand, pfx string) (*flowcontrol.UserSubject, []user.Info,
UID: mui.UID, UID: mui.UID,
Groups: mui.Groups, Groups: mui.Groups,
Extra: mui.Extra}} Extra: mui.Extra}}
return &flowcontrol.UserSubject{mui.Name}, []user.Info{mui}, skips return &flowcontrol.UserSubject{Name: mui.Name}, []user.Info{mui}, skips
} }
var groupCover = []string{"system:authenticated", "system:unauthenticated"} var groupCover = []string{"system:authenticated", "system:unauthenticated"}
@ -462,14 +462,14 @@ func mg(rng *rand.Rand) string {
func mkUserSubject(username string) flowcontrol.Subject { func mkUserSubject(username string) flowcontrol.Subject {
return flowcontrol.Subject{ return flowcontrol.Subject{
Kind: flowcontrol.SubjectKindUser, Kind: flowcontrol.SubjectKindUser,
User: &flowcontrol.UserSubject{username}, User: &flowcontrol.UserSubject{Name: username},
} }
} }
func mkGroupSubject(group string) flowcontrol.Subject { func mkGroupSubject(group string) flowcontrol.Subject {
return flowcontrol.Subject{ return flowcontrol.Subject{
Kind: flowcontrol.SubjectKindGroup, Kind: flowcontrol.SubjectKindGroup,
Group: &flowcontrol.GroupSubject{group}, Group: &flowcontrol.GroupSubject{Name: group},
} }
} }
@ -499,7 +499,7 @@ func genGroup(rng *rand.Rand, pfx string) (*flowcontrol.GroupSubject, []user.Inf
if rng.Intn(2) == 0 { if rng.Intn(2) == 0 {
skipper.Groups = append(skipper.Groups, pfx+"-k") skipper.Groups = append(skipper.Groups, pfx+"-k")
} }
return &flowcontrol.GroupSubject{name}, []user.Info{ui}, []user.Info{skipper} return &flowcontrol.GroupSubject{Name: name}, []user.Info{ui}, []user.Info{skipper}
} }
func genServiceAccount(rng *rand.Rand, pfx string) (*flowcontrol.ServiceAccountSubject, []user.Info, []user.Info) { func genServiceAccount(rng *rand.Rand, pfx string) (*flowcontrol.ServiceAccountSubject, []user.Info, []user.Info) {

View File

@ -128,56 +128,56 @@ func TestLiterals(t *testing.T) {
} }
checkRules(t, true, reqRN, []flowcontrol.PolicyRulesWithSubjects{{ checkRules(t, true, reqRN, []flowcontrol.PolicyRulesWithSubjects{{
Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser, Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser,
User: &flowcontrol.UserSubject{"goodu"}}}, User: &flowcontrol.UserSubject{Name: "goodu"}}},
ResourceRules: []flowcontrol.ResourcePolicyRule{{ ResourceRules: []flowcontrol.ResourcePolicyRule{{
Verbs: []string{"goodverb"}, Verbs: []string{"goodverb"},
APIGroups: []string{"goodapig"}, APIGroups: []string{"goodapig"},
Resources: []string{"goodrscs"}, Resources: []string{"goodrscs"},
Namespaces: []string{"goodns"}}}}, { Namespaces: []string{"goodns"}}}}, {
Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindGroup, Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindGroup,
Group: &flowcontrol.GroupSubject{"goodg1"}}}, Group: &flowcontrol.GroupSubject{Name: "goodg1"}}},
ResourceRules: []flowcontrol.ResourcePolicyRule{{ ResourceRules: []flowcontrol.ResourcePolicyRule{{
Verbs: []string{"goodverb"}, Verbs: []string{"goodverb"},
APIGroups: []string{"goodapig"}, APIGroups: []string{"goodapig"},
Resources: []string{"goodrscs"}, Resources: []string{"goodrscs"},
Namespaces: []string{"goodns"}}}}, { Namespaces: []string{"goodns"}}}}, {
Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser, Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser,
User: &flowcontrol.UserSubject{"*"}}}, User: &flowcontrol.UserSubject{Name: "*"}}},
ResourceRules: []flowcontrol.ResourcePolicyRule{{ ResourceRules: []flowcontrol.ResourcePolicyRule{{
Verbs: []string{"goodverb"}, Verbs: []string{"goodverb"},
APIGroups: []string{"goodapig"}, APIGroups: []string{"goodapig"},
Resources: []string{"goodrscs"}, Resources: []string{"goodrscs"},
Namespaces: []string{"goodns"}}}}, { Namespaces: []string{"goodns"}}}}, {
Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindGroup, Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindGroup,
Group: &flowcontrol.GroupSubject{"*"}}}, Group: &flowcontrol.GroupSubject{Name: "*"}}},
ResourceRules: []flowcontrol.ResourcePolicyRule{{ ResourceRules: []flowcontrol.ResourcePolicyRule{{
Verbs: []string{"goodverb"}, Verbs: []string{"goodverb"},
APIGroups: []string{"goodapig"}, APIGroups: []string{"goodapig"},
Resources: []string{"goodrscs"}, Resources: []string{"goodrscs"},
Namespaces: []string{"goodns"}}}}, { Namespaces: []string{"goodns"}}}}, {
Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser, Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser,
User: &flowcontrol.UserSubject{"goodu"}}}, User: &flowcontrol.UserSubject{Name: "goodu"}}},
ResourceRules: []flowcontrol.ResourcePolicyRule{{ ResourceRules: []flowcontrol.ResourcePolicyRule{{
Verbs: []string{"*"}, Verbs: []string{"*"},
APIGroups: []string{"goodapig"}, APIGroups: []string{"goodapig"},
Resources: []string{"goodrscs"}, Resources: []string{"goodrscs"},
Namespaces: []string{"goodns"}}}}, { Namespaces: []string{"goodns"}}}}, {
Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser, Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser,
User: &flowcontrol.UserSubject{"goodu"}}}, User: &flowcontrol.UserSubject{Name: "goodu"}}},
ResourceRules: []flowcontrol.ResourcePolicyRule{{ ResourceRules: []flowcontrol.ResourcePolicyRule{{
Verbs: []string{"goodverb"}, Verbs: []string{"goodverb"},
APIGroups: []string{"*"}, APIGroups: []string{"*"},
Resources: []string{"goodrscs"}, Resources: []string{"goodrscs"},
Namespaces: []string{"goodns"}}}}, { Namespaces: []string{"goodns"}}}}, {
Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser, Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser,
User: &flowcontrol.UserSubject{"goodu"}}}, User: &flowcontrol.UserSubject{Name: "goodu"}}},
ResourceRules: []flowcontrol.ResourcePolicyRule{{ ResourceRules: []flowcontrol.ResourcePolicyRule{{
Verbs: []string{"goodverb"}, Verbs: []string{"goodverb"},
APIGroups: []string{"goodapig"}, APIGroups: []string{"goodapig"},
Resources: []string{"*"}, Resources: []string{"*"},
Namespaces: []string{"goodns"}}}}, { Namespaces: []string{"goodns"}}}}, {
Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser, Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser,
User: &flowcontrol.UserSubject{"goodu"}}}, User: &flowcontrol.UserSubject{Name: "goodu"}}},
ResourceRules: []flowcontrol.ResourcePolicyRule{{ ResourceRules: []flowcontrol.ResourcePolicyRule{{
Verbs: []string{"goodverb"}, Verbs: []string{"goodverb"},
APIGroups: []string{"goodapig"}, APIGroups: []string{"goodapig"},
@ -186,42 +186,42 @@ func TestLiterals(t *testing.T) {
}) })
checkRules(t, false, reqRN, []flowcontrol.PolicyRulesWithSubjects{{ checkRules(t, false, reqRN, []flowcontrol.PolicyRulesWithSubjects{{
Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser, Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser,
User: &flowcontrol.UserSubject{"badu"}}}, User: &flowcontrol.UserSubject{Name: "badu"}}},
ResourceRules: []flowcontrol.ResourcePolicyRule{{ ResourceRules: []flowcontrol.ResourcePolicyRule{{
Verbs: []string{"goodverb"}, Verbs: []string{"goodverb"},
APIGroups: []string{"goodapig"}, APIGroups: []string{"goodapig"},
Resources: []string{"goodrscs"}, Resources: []string{"goodrscs"},
Namespaces: []string{"goodns"}}}}, { Namespaces: []string{"goodns"}}}}, {
Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindGroup, Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindGroup,
Group: &flowcontrol.GroupSubject{"badg"}}}, Group: &flowcontrol.GroupSubject{Name: "badg"}}},
ResourceRules: []flowcontrol.ResourcePolicyRule{{ ResourceRules: []flowcontrol.ResourcePolicyRule{{
Verbs: []string{"goodverb"}, Verbs: []string{"goodverb"},
APIGroups: []string{"goodapig"}, APIGroups: []string{"goodapig"},
Resources: []string{"goodrscs"}, Resources: []string{"goodrscs"},
Namespaces: []string{"goodns"}}}}, { Namespaces: []string{"goodns"}}}}, {
Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser, Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser,
User: &flowcontrol.UserSubject{"goodu"}}}, User: &flowcontrol.UserSubject{Name: "goodu"}}},
ResourceRules: []flowcontrol.ResourcePolicyRule{{ ResourceRules: []flowcontrol.ResourcePolicyRule{{
Verbs: []string{"badverb"}, Verbs: []string{"badverb"},
APIGroups: []string{"goodapig"}, APIGroups: []string{"goodapig"},
Resources: []string{"goodrscs"}, Resources: []string{"goodrscs"},
Namespaces: []string{"goodns"}}}}, { Namespaces: []string{"goodns"}}}}, {
Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser, Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser,
User: &flowcontrol.UserSubject{"goodu"}}}, User: &flowcontrol.UserSubject{Name: "goodu"}}},
ResourceRules: []flowcontrol.ResourcePolicyRule{{ ResourceRules: []flowcontrol.ResourcePolicyRule{{
Verbs: []string{"goodverb"}, Verbs: []string{"goodverb"},
APIGroups: []string{"badapig"}, APIGroups: []string{"badapig"},
Resources: []string{"goodrscs"}, Resources: []string{"goodrscs"},
Namespaces: []string{"goodns"}}}}, { Namespaces: []string{"goodns"}}}}, {
Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser, Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser,
User: &flowcontrol.UserSubject{"goodu"}}}, User: &flowcontrol.UserSubject{Name: "goodu"}}},
ResourceRules: []flowcontrol.ResourcePolicyRule{{ ResourceRules: []flowcontrol.ResourcePolicyRule{{
Verbs: []string{"goodverb"}, Verbs: []string{"goodverb"},
APIGroups: []string{"goodapig"}, APIGroups: []string{"goodapig"},
Resources: []string{"badrscs"}, Resources: []string{"badrscs"},
Namespaces: []string{"goodns"}}}}, { Namespaces: []string{"goodns"}}}}, {
Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser, Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser,
User: &flowcontrol.UserSubject{"goodu"}}}, User: &flowcontrol.UserSubject{Name: "goodu"}}},
ResourceRules: []flowcontrol.ResourcePolicyRule{{ ResourceRules: []flowcontrol.ResourcePolicyRule{{
Verbs: []string{"goodverb"}, Verbs: []string{"goodverb"},
APIGroups: []string{"goodapig"}, APIGroups: []string{"goodapig"},
@ -230,28 +230,28 @@ func TestLiterals(t *testing.T) {
}) })
checkRules(t, true, reqRU, []flowcontrol.PolicyRulesWithSubjects{{ checkRules(t, true, reqRU, []flowcontrol.PolicyRulesWithSubjects{{
Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser, Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser,
User: &flowcontrol.UserSubject{"goodu"}}}, User: &flowcontrol.UserSubject{Name: "goodu"}}},
ResourceRules: []flowcontrol.ResourcePolicyRule{{ ResourceRules: []flowcontrol.ResourcePolicyRule{{
Verbs: []string{"goodverb"}, Verbs: []string{"goodverb"},
APIGroups: []string{"goodapig"}, APIGroups: []string{"goodapig"},
Resources: []string{"goodrscs"}, Resources: []string{"goodrscs"},
ClusterScope: true}}}, { ClusterScope: true}}}, {
Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser, Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser,
User: &flowcontrol.UserSubject{"goodu"}}}, User: &flowcontrol.UserSubject{Name: "goodu"}}},
ResourceRules: []flowcontrol.ResourcePolicyRule{{ ResourceRules: []flowcontrol.ResourcePolicyRule{{
Verbs: []string{"*"}, Verbs: []string{"*"},
APIGroups: []string{"goodapig"}, APIGroups: []string{"goodapig"},
Resources: []string{"goodrscs"}, Resources: []string{"goodrscs"},
ClusterScope: true}}}, { ClusterScope: true}}}, {
Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser, Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser,
User: &flowcontrol.UserSubject{"goodu"}}}, User: &flowcontrol.UserSubject{Name: "goodu"}}},
ResourceRules: []flowcontrol.ResourcePolicyRule{{ ResourceRules: []flowcontrol.ResourcePolicyRule{{
Verbs: []string{"goodverb"}, Verbs: []string{"goodverb"},
APIGroups: []string{"*"}, APIGroups: []string{"*"},
Resources: []string{"goodrscs"}, Resources: []string{"goodrscs"},
ClusterScope: true}}}, { ClusterScope: true}}}, {
Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser, Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser,
User: &flowcontrol.UserSubject{"goodu"}}}, User: &flowcontrol.UserSubject{Name: "goodu"}}},
ResourceRules: []flowcontrol.ResourcePolicyRule{{ ResourceRules: []flowcontrol.ResourcePolicyRule{{
Verbs: []string{"goodverb"}, Verbs: []string{"goodverb"},
APIGroups: []string{"goodapig"}, APIGroups: []string{"goodapig"},
@ -259,28 +259,28 @@ func TestLiterals(t *testing.T) {
ClusterScope: true}}}}) ClusterScope: true}}}})
checkRules(t, false, reqRU, []flowcontrol.PolicyRulesWithSubjects{{ checkRules(t, false, reqRU, []flowcontrol.PolicyRulesWithSubjects{{
Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser, Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser,
User: &flowcontrol.UserSubject{"goodu"}}}, User: &flowcontrol.UserSubject{Name: "goodu"}}},
ResourceRules: []flowcontrol.ResourcePolicyRule{{ ResourceRules: []flowcontrol.ResourcePolicyRule{{
Verbs: []string{"badverb"}, Verbs: []string{"badverb"},
APIGroups: []string{"goodapig"}, APIGroups: []string{"goodapig"},
Resources: []string{"goodrscs"}, Resources: []string{"goodrscs"},
ClusterScope: true}}}, { ClusterScope: true}}}, {
Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser, Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser,
User: &flowcontrol.UserSubject{"goodu"}}}, User: &flowcontrol.UserSubject{Name: "goodu"}}},
ResourceRules: []flowcontrol.ResourcePolicyRule{{ ResourceRules: []flowcontrol.ResourcePolicyRule{{
Verbs: []string{"goodverb"}, Verbs: []string{"goodverb"},
APIGroups: []string{"badapig"}, APIGroups: []string{"badapig"},
Resources: []string{"goodrscs"}, Resources: []string{"goodrscs"},
ClusterScope: true}}}, { ClusterScope: true}}}, {
Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser, Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser,
User: &flowcontrol.UserSubject{"goodu"}}}, User: &flowcontrol.UserSubject{Name: "goodu"}}},
ResourceRules: []flowcontrol.ResourcePolicyRule{{ ResourceRules: []flowcontrol.ResourcePolicyRule{{
Verbs: []string{"goodverb"}, Verbs: []string{"goodverb"},
APIGroups: []string{"goodapig"}, APIGroups: []string{"goodapig"},
Resources: []string{"badrscs"}, Resources: []string{"badrscs"},
ClusterScope: true}}}, { ClusterScope: true}}}, {
Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser, Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser,
User: &flowcontrol.UserSubject{"goodu"}}}, User: &flowcontrol.UserSubject{Name: "goodu"}}},
ResourceRules: []flowcontrol.ResourcePolicyRule{{ ResourceRules: []flowcontrol.ResourcePolicyRule{{
Verbs: []string{"goodverb"}, Verbs: []string{"goodverb"},
APIGroups: []string{"goodapig"}, APIGroups: []string{"goodapig"},
@ -289,29 +289,29 @@ func TestLiterals(t *testing.T) {
}) })
checkRules(t, true, reqN, []flowcontrol.PolicyRulesWithSubjects{{ checkRules(t, true, reqN, []flowcontrol.PolicyRulesWithSubjects{{
Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser, Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser,
User: &flowcontrol.UserSubject{"goodu"}}}, User: &flowcontrol.UserSubject{Name: "goodu"}}},
NonResourceRules: []flowcontrol.NonResourcePolicyRule{{ NonResourceRules: []flowcontrol.NonResourcePolicyRule{{
Verbs: []string{"goodverb"}, Verbs: []string{"goodverb"},
NonResourceURLs: []string{"/openapi/v2"}}}}, { NonResourceURLs: []string{"/openapi/v2"}}}}, {
Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser, Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser,
User: &flowcontrol.UserSubject{"goodu"}}}, User: &flowcontrol.UserSubject{Name: "goodu"}}},
NonResourceRules: []flowcontrol.NonResourcePolicyRule{{ NonResourceRules: []flowcontrol.NonResourcePolicyRule{{
Verbs: []string{"*"}, Verbs: []string{"*"},
NonResourceURLs: []string{"/openapi/v2"}}}}, { NonResourceURLs: []string{"/openapi/v2"}}}}, {
Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser, Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser,
User: &flowcontrol.UserSubject{"goodu"}}}, User: &flowcontrol.UserSubject{Name: "goodu"}}},
NonResourceRules: []flowcontrol.NonResourcePolicyRule{{ NonResourceRules: []flowcontrol.NonResourcePolicyRule{{
Verbs: []string{"goodverb"}, Verbs: []string{"goodverb"},
NonResourceURLs: []string{"*"}}}}, NonResourceURLs: []string{"*"}}}},
}) })
checkRules(t, false, reqN, []flowcontrol.PolicyRulesWithSubjects{{ checkRules(t, false, reqN, []flowcontrol.PolicyRulesWithSubjects{{
Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser, Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser,
User: &flowcontrol.UserSubject{"goodu"}}}, User: &flowcontrol.UserSubject{Name: "goodu"}}},
NonResourceRules: []flowcontrol.NonResourcePolicyRule{{ NonResourceRules: []flowcontrol.NonResourcePolicyRule{{
Verbs: []string{"badverb"}, Verbs: []string{"badverb"},
NonResourceURLs: []string{"/openapi/v2"}}}}, { NonResourceURLs: []string{"/openapi/v2"}}}}, {
Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser, Subjects: []flowcontrol.Subject{{Kind: flowcontrol.SubjectKindUser,
User: &flowcontrol.UserSubject{"goodu"}}}, User: &flowcontrol.UserSubject{Name: "goodu"}}},
NonResourceRules: []flowcontrol.NonResourcePolicyRule{{ NonResourceRules: []flowcontrol.NonResourcePolicyRule{{
Verbs: []string{"goodverb"}, Verbs: []string{"goodverb"},
NonResourceURLs: []string{"/closedapi/v2"}}}}, NonResourceURLs: []string{"/closedapi/v2"}}}},

View File

@ -70,6 +70,7 @@ func NewTimingRatioHistogram(opts *TimingRatioHistogramOpts) *TimingRatioHistogr
// NewTestableTimingHistogram adds injection of the clock // NewTestableTimingHistogram adds injection of the clock
func NewTestableTimingRatioHistogram(nowFunc func() time.Time, opts *TimingRatioHistogramOpts) *TimingRatioHistogram { func NewTestableTimingRatioHistogram(nowFunc func() time.Time, opts *TimingRatioHistogramOpts) *TimingRatioHistogram {
//nolint:govet // copylocks: assignment copies lock value to ratioedOpts: k8s.io/component-base/metrics.TimingHistogramOpts contains sync.Once contains sync.Mutex
ratioedOpts := opts.TimingHistogramOpts ratioedOpts := opts.TimingHistogramOpts
ratioedOpts.InitialValue /= opts.InitialDenominator ratioedOpts.InitialValue /= opts.InitialDenominator
th := compbasemetrics.NewTestableTimingHistogram(nowFunc, &ratioedOpts) th := compbasemetrics.NewTestableTimingHistogram(nowFunc, &ratioedOpts)

View File

@ -59,7 +59,8 @@ func TestRawConn(t *testing.T) {
defer wg.Done() defer wg.Done()
data, err := ioutil.ReadAll(conn.channels[0]) data, err := ioutil.ReadAll(conn.channels[0])
if err != nil { if err != nil {
t.Fatal(err) t.Error(err)
return
} }
if !reflect.DeepEqual(data, []byte("client")) { if !reflect.DeepEqual(data, []byte("client")) {
t.Errorf("unexpected server read: %v", data) t.Errorf("unexpected server read: %v", data)
@ -75,7 +76,7 @@ func TestRawConn(t *testing.T) {
go func() { go func() {
defer wg.Done() defer wg.Done()
if n, err := conn.channels[1].Write([]byte("server")); err != nil && n != 6 { if n, err := conn.channels[1].Write([]byte("server")); err != nil && n != 6 {
t.Fatalf("%d: %v", n, err) t.Errorf("%d: %v", n, err)
} }
}() }()
@ -141,7 +142,8 @@ func TestBase64Conn(t *testing.T) {
defer wg.Done() defer wg.Done()
data, err := ioutil.ReadAll(conn.channels[0]) data, err := ioutil.ReadAll(conn.channels[0])
if err != nil { if err != nil {
t.Fatal(err) t.Error(err)
return
} }
if !reflect.DeepEqual(data, []byte("client")) { if !reflect.DeepEqual(data, []byte("client")) {
t.Errorf("unexpected server read: %s", string(data)) t.Errorf("unexpected server read: %s", string(data))
@ -157,7 +159,7 @@ func TestBase64Conn(t *testing.T) {
go func() { go func() {
defer wg.Done() defer wg.Done()
if n, err := conn.channels[1].Write([]byte("server")); err != nil && n != 6 { if n, err := conn.channels[1].Write([]byte("server")); err != nil && n != 6 {
t.Fatalf("%d: %v", n, err) t.Errorf("%d: %v", n, err)
} }
}() }()

View File

@ -73,8 +73,8 @@ items:
--- ---
` `
// ExampleLocalBuilderLoad demonstrates using a local resource builder to read typed resources from a manifest // ExampleNewLocalBuilderLoad demonstrates using a local resource builder to read typed resources from a manifest
func ExampleLocalBuilder() { func ExampleNewLocalBuilder() {
// Create a local builder... // Create a local builder...
builder := resource.NewLocalBuilder(). builder := resource.NewLocalBuilder().
// Configure with a scheme to get typed objects in the versions registered with the scheme. // Configure with a scheme to get typed objects in the versions registered with the scheme.

View File

@ -27,6 +27,10 @@ import (
"k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/runtime/schema"
) )
func gvk(group, version, kind string) *schema.GroupVersionKind {
return &schema.GroupVersionKind{Group: group, Version: version, Kind: kind}
}
func TestDynamicCodecDecode(t *testing.T) { func TestDynamicCodecDecode(t *testing.T) {
testcases := []struct { testcases := []struct {
name string name string
@ -41,25 +45,25 @@ func TestDynamicCodecDecode(t *testing.T) {
{ {
name: "v1 Status", name: "v1 Status",
data: []byte(`{"apiVersion":"v1","kind":"Status"}`), data: []byte(`{"apiVersion":"v1","kind":"Status"}`),
expectGVK: &schema.GroupVersionKind{"", "v1", "Status"}, expectGVK: gvk("", "v1", "Status"),
expectObj: &metav1.Status{TypeMeta: metav1.TypeMeta{APIVersion: "v1", Kind: "Status"}}, expectObj: &metav1.Status{TypeMeta: metav1.TypeMeta{APIVersion: "v1", Kind: "Status"}},
}, },
{ {
name: "meta.k8s.io/v1 Status", name: "meta.k8s.io/v1 Status",
data: []byte(`{"apiVersion":"meta.k8s.io/v1","kind":"Status"}`), data: []byte(`{"apiVersion":"meta.k8s.io/v1","kind":"Status"}`),
expectGVK: &schema.GroupVersionKind{"meta.k8s.io", "v1", "Status"}, expectGVK: gvk("meta.k8s.io", "v1", "Status"),
expectObj: &metav1.Status{TypeMeta: metav1.TypeMeta{APIVersion: "meta.k8s.io/v1", Kind: "Status"}}, expectObj: &metav1.Status{TypeMeta: metav1.TypeMeta{APIVersion: "meta.k8s.io/v1", Kind: "Status"}},
}, },
{ {
name: "example.com/v1 Status", name: "example.com/v1 Status",
data: []byte(`{"apiVersion":"example.com/v1","kind":"Status"}`), data: []byte(`{"apiVersion":"example.com/v1","kind":"Status"}`),
expectGVK: &schema.GroupVersionKind{"example.com", "v1", "Status"}, expectGVK: gvk("example.com", "v1", "Status"),
expectObj: &unstructured.Unstructured{Object: map[string]interface{}{"apiVersion": "example.com/v1", "kind": "Status"}}, expectObj: &unstructured.Unstructured{Object: map[string]interface{}{"apiVersion": "example.com/v1", "kind": "Status"}},
}, },
{ {
name: "example.com/v1 Foo", name: "example.com/v1 Foo",
data: []byte(`{"apiVersion":"example.com/v1","kind":"Foo"}`), data: []byte(`{"apiVersion":"example.com/v1","kind":"Foo"}`),
expectGVK: &schema.GroupVersionKind{"example.com", "v1", "Foo"}, expectGVK: gvk("example.com", "v1", "Foo"),
expectObj: &unstructured.Unstructured{Object: map[string]interface{}{"apiVersion": "example.com/v1", "kind": "Foo"}}, expectObj: &unstructured.Unstructured{Object: map[string]interface{}{"apiVersion": "example.com/v1", "kind": "Foo"}},
}, },
} }

View File

@ -1085,7 +1085,7 @@ func TestTLSCredentials(t *testing.T) {
Status: &clientauthentication.ExecCredentialStatus{ Status: &clientauthentication.ExecCredentialStatus{
ClientCertificateData: string(cert), ClientCertificateData: string(cert),
ClientKeyData: string(key), ClientKeyData: string(key),
ExpirationTimestamp: &v1.Time{now.Add(time.Hour)}, ExpirationTimestamp: &v1.Time{Time: now.Add(time.Hour)},
}, },
} }
get(t, "valid TLS cert", false) get(t, "valid TLS cert", false)
@ -1097,7 +1097,7 @@ func TestTLSCredentials(t *testing.T) {
Status: &clientauthentication.ExecCredentialStatus{ Status: &clientauthentication.ExecCredentialStatus{
ClientCertificateData: string(nCert), ClientCertificateData: string(nCert),
ClientKeyData: string(nKey), ClientKeyData: string(nKey),
ExpirationTimestamp: &v1.Time{now.Add(time.Hour)}, ExpirationTimestamp: &v1.Time{Time: now.Add(time.Hour)},
}, },
} }
get(t, "untrusted TLS cert", true) get(t, "untrusted TLS cert", true)
@ -1107,7 +1107,7 @@ func TestTLSCredentials(t *testing.T) {
Status: &clientauthentication.ExecCredentialStatus{ Status: &clientauthentication.ExecCredentialStatus{
ClientCertificateData: string(cert), ClientCertificateData: string(cert),
ClientKeyData: string(key), ClientKeyData: string(key),
ExpirationTimestamp: &v1.Time{now.Add(time.Hour)}, ExpirationTimestamp: &v1.Time{Time: now.Add(time.Hour)},
}, },
} }
get(t, "valid TLS cert again", false) get(t, "valid TLS cert again", false)

View File

@ -35,6 +35,7 @@ func TestClientAuthenticationClusterTypesAreSynced(t *testing.T) {
clientauthenticationv1beta1.Cluster{}, clientauthenticationv1beta1.Cluster{},
clientauthenticationv1.Cluster{}, clientauthenticationv1.Cluster{},
} { } {
cluster := cluster
t.Run(fmt.Sprintf("%T", cluster), func(t *testing.T) { t.Run(fmt.Sprintf("%T", cluster), func(t *testing.T) {
t.Parallel() t.Parallel()
testClientAuthenticationClusterTypesAreSynced(t, cluster) testClientAuthenticationClusterTypesAreSynced(t, cluster)

View File

@ -41,7 +41,7 @@ type recorderImpl struct {
} }
func (recorder *recorderImpl) Eventf(regarding runtime.Object, related runtime.Object, eventtype, reason, action, note string, args ...interface{}) { func (recorder *recorderImpl) Eventf(regarding runtime.Object, related runtime.Object, eventtype, reason, action, note string, args ...interface{}) {
timestamp := metav1.MicroTime{time.Now()} timestamp := metav1.MicroTime{Time: time.Now()}
message := fmt.Sprintf(note, args...) message := fmt.Sprintf(note, args...)
refRegarding, err := reference.GetReference(recorder.scheme, regarding) refRegarding, err := reference.GetReference(recorder.scheme, regarding)
if err != nil { if err != nil {

View File

@ -92,7 +92,7 @@ func TestEventSeriesf(t *testing.T) {
Name: "foo", Name: "foo",
Namespace: "baz", Namespace: "baz",
}, },
EventTime: metav1.MicroTime{time.Now()}, EventTime: metav1.MicroTime{Time: time.Now()},
ReportingController: "eventTest", ReportingController: "eventTest",
ReportingInstance: "eventTest-" + hostname, ReportingInstance: "eventTest-" + hostname,
Action: "started", Action: "started",
@ -296,7 +296,7 @@ func TestFinishSeries(t *testing.T) {
cache := map[eventKey]*eventsv1.Event{} cache := map[eventKey]*eventsv1.Event{}
eventBroadcaster := newBroadcaster(&testEvents, 0, cache).(*eventBroadcasterImpl) eventBroadcaster := newBroadcaster(&testEvents, 0, cache).(*eventBroadcasterImpl)
recorder := eventBroadcaster.NewRecorder(scheme.Scheme, "k8s.io/kube-foo").(*recorderImpl) recorder := eventBroadcaster.NewRecorder(scheme.Scheme, "k8s.io/kube-foo").(*recorderImpl)
cachedEvent := recorder.makeEvent(regarding, related, metav1.MicroTime{time.Now()}, v1.EventTypeNormal, "test", "some verbose message: 1", "eventTest", "eventTest-"+hostname, "started") cachedEvent := recorder.makeEvent(regarding, related, metav1.MicroTime{Time: time.Now()}, v1.EventTypeNormal, "test", "some verbose message: 1", "eventTest", "eventTest-"+hostname, "started")
nonFinishedEvent := cachedEvent.DeepCopy() nonFinishedEvent := cachedEvent.DeepCopy()
nonFinishedEvent.ReportingController = "nonFinished-controller" nonFinishedEvent.ReportingController = "nonFinished-controller"
cachedEvent.Series = &eventsv1.EventSeries{ cachedEvent.Series = &eventsv1.EventSeries{
@ -382,7 +382,7 @@ func TestRefreshExistingEventSeries(t *testing.T) {
cache := map[eventKey]*eventsv1.Event{} cache := map[eventKey]*eventsv1.Event{}
eventBroadcaster := newBroadcaster(&testEvents, 0, cache).(*eventBroadcasterImpl) eventBroadcaster := newBroadcaster(&testEvents, 0, cache).(*eventBroadcasterImpl)
recorder := eventBroadcaster.NewRecorder(scheme.Scheme, "k8s.io/kube-foo").(*recorderImpl) recorder := eventBroadcaster.NewRecorder(scheme.Scheme, "k8s.io/kube-foo").(*recorderImpl)
cachedEvent := recorder.makeEvent(regarding, related, metav1.MicroTime{time.Now()}, v1.EventTypeNormal, "test", "some verbose message: 1", "eventTest", "eventTest-"+hostname, "started") cachedEvent := recorder.makeEvent(regarding, related, metav1.MicroTime{Time: time.Now()}, v1.EventTypeNormal, "test", "some verbose message: 1", "eventTest", "eventTest-"+hostname, "started")
cachedEvent.Series = &eventsv1.EventSeries{ cachedEvent.Series = &eventsv1.EventSeries{
Count: 10, Count: 10,
LastObservedTime: LastObservedTime, LastObservedTime: LastObservedTime,

View File

@ -20,7 +20,6 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"k8s.io/apimachinery/pkg/util/wait"
"sync" "sync"
"testing" "testing"
"time" "time"
@ -32,6 +31,7 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/diff" "k8s.io/apimachinery/pkg/util/diff"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/kubernetes/fake" "k8s.io/client-go/kubernetes/fake"
fakeclient "k8s.io/client-go/testing" fakeclient "k8s.io/client-go/testing"
rl "k8s.io/client-go/tools/leaderelection/resourcelock" rl "k8s.io/client-go/tools/leaderelection/resourcelock"
@ -362,8 +362,8 @@ func TestLeaseSpecToLeaderElectionRecordRoundTrip(t *testing.T) {
oldSpec := coordinationv1.LeaseSpec{ oldSpec := coordinationv1.LeaseSpec{
HolderIdentity: &holderIdentity, HolderIdentity: &holderIdentity,
LeaseDurationSeconds: &leaseDurationSeconds, LeaseDurationSeconds: &leaseDurationSeconds,
AcquireTime: &metav1.MicroTime{time.Now()}, AcquireTime: &metav1.MicroTime{Time: time.Now()},
RenewTime: &metav1.MicroTime{time.Now()}, RenewTime: &metav1.MicroTime{Time: time.Now()},
LeaseTransitions: &leaseTransitions, LeaseTransitions: &leaseTransitions,
} }

View File

@ -117,10 +117,10 @@ func LeaseSpecToLeaderElectionRecord(spec *coordinationv1.LeaseSpec) *LeaderElec
r.LeaderTransitions = int(*spec.LeaseTransitions) r.LeaderTransitions = int(*spec.LeaseTransitions)
} }
if spec.AcquireTime != nil { if spec.AcquireTime != nil {
r.AcquireTime = metav1.Time{spec.AcquireTime.Time} r.AcquireTime = metav1.Time{Time: spec.AcquireTime.Time}
} }
if spec.RenewTime != nil { if spec.RenewTime != nil {
r.RenewTime = metav1.Time{spec.RenewTime.Time} r.RenewTime = metav1.Time{Time: spec.RenewTime.Time}
} }
return &r return &r
@ -132,8 +132,8 @@ func LeaderElectionRecordToLeaseSpec(ler *LeaderElectionRecord) coordinationv1.L
return coordinationv1.LeaseSpec{ return coordinationv1.LeaseSpec{
HolderIdentity: &ler.HolderIdentity, HolderIdentity: &ler.HolderIdentity,
LeaseDurationSeconds: &leaseDurationSeconds, LeaseDurationSeconds: &leaseDurationSeconds,
AcquireTime: &metav1.MicroTime{ler.AcquireTime.Time}, AcquireTime: &metav1.MicroTime{Time: ler.AcquireTime.Time},
RenewTime: &metav1.MicroTime{ler.RenewTime.Time}, RenewTime: &metav1.MicroTime{Time: ler.RenewTime.Time},
LeaseTransitions: &leaseTransitions, LeaseTransitions: &leaseTransitions,
} }
} }

View File

@ -43,7 +43,7 @@ func BenchmarkInfoLoggerInfo(b *testing.B) {
"request", struct { "request", struct {
Method string `json:"method"` Method string `json:"method"`
Timeout int `json:"timeout"` Timeout int `json:"timeout"`
secret string `json:"secret"` secret string
}{ }{
Method: "GET", Method: "GET",
Timeout: 10, Timeout: 10,
@ -73,7 +73,7 @@ func BenchmarkZapLoggerError(b *testing.B) {
"request", struct { "request", struct {
Method string `json:"method"` Method string `json:"method"`
Timeout int `json:"timeout"` Timeout int `json:"timeout"`
secret string `json:"secret"` secret string
}{ }{
Method: "GET", Method: "GET",
Timeout: 10, Timeout: 10,
@ -102,7 +102,7 @@ func BenchmarkZapLoggerV(b *testing.B) {
"request", struct { "request", struct {
Method string `json:"method"` Method string `json:"method"`
Timeout int `json:"timeout"` Timeout int `json:"timeout"`
secret string `json:"secret"` secret string
}{ }{
Method: "GET", Method: "GET",
Timeout: 10, Timeout: 10,

View File

@ -156,6 +156,7 @@ func TestDescClearState(t *testing.T) {
descA.ClearState() descA.ClearState()
// create // create
//nolint:govet // it's okay to compare sync.RWMutex, it's empty
if !reflect.DeepEqual(*descA, *descB) { if !reflect.DeepEqual(*descA, *descB) {
t.Fatal("descriptor state hasn't be cleaned up") t.Fatal("descriptor state hasn't be cleaned up")
} }

View File

@ -28,19 +28,19 @@ import (
func TestTranslatevSphereInTreeStorageClassToCSI(t *testing.T) { func TestTranslatevSphereInTreeStorageClassToCSI(t *testing.T) {
translator := NewvSphereCSITranslator() translator := NewvSphereCSITranslator()
topologySelectorTerm := v1.TopologySelectorTerm{[]v1.TopologySelectorLabelRequirement{ topologySelectorTerm := v1.TopologySelectorTerm{MatchLabelExpressions: []v1.TopologySelectorLabelRequirement{
{ {
Key: v1.LabelTopologyZone, Key: v1.LabelTopologyZone,
Values: []string{"zone-a"}, Values: []string{"zone-a"},
}, },
}} }}
topologySelectorTermWithBetaLabels := v1.TopologySelectorTerm{[]v1.TopologySelectorLabelRequirement{ topologySelectorTermWithBetaLabels := v1.TopologySelectorTerm{MatchLabelExpressions: []v1.TopologySelectorLabelRequirement{
{ {
Key: v1.LabelFailureDomainBetaZone, Key: v1.LabelFailureDomainBetaZone,
Values: []string{"zone-a"}, Values: []string{"zone-a"},
}, },
}} }}
expectedTopologySelectorTerm := v1.TopologySelectorTerm{[]v1.TopologySelectorLabelRequirement{ expectedTopologySelectorTerm := v1.TopologySelectorTerm{MatchLabelExpressions: []v1.TopologySelectorLabelRequirement{
{ {
Key: vSphereCSITopologyZoneKey, Key: vSphereCSITopologyZoneKey,
Values: []string{"zone-a"}, Values: []string{"zone-a"},

View File

@ -508,15 +508,20 @@ func TestRotationKeyUsage(t *testing.T) {
defer wg.Done() defer wg.Done()
resp, err := localKEKService.Encrypt(ctx, "test-uid", []byte(rand.String(32))) resp, err := localKEKService.Encrypt(ctx, "test-uid", []byte(rand.String(32)))
if err != nil { if err != nil {
t.Fatalf("Encrypt() error = %v", err) t.Errorf("Encrypt() error = %v", err)
return
} }
if v, ok := resp.Annotations[referenceKEKAnnotationKey]; !ok || !bytes.Equal(v, encLocalKEK) { if v, ok := resp.Annotations[referenceKEKAnnotationKey]; !ok || !bytes.Equal(v, encLocalKEK) {
t.Fatalf("Encrypt() annotations = %v, want %v", resp.Annotations, encLocalKEK) t.Errorf("Encrypt() annotations = %v, want %v", resp.Annotations, encLocalKEK)
return
} }
record.Store(resp, nil) record.Store(resp, nil)
}() }()
} }
wg.Wait() wg.Wait()
if t.Failed() {
return
}
fakeClock.Step(30 * time.Second) fakeClock.Step(30 * time.Second)
rotated := false rotated := false
@ -541,15 +546,20 @@ func TestRotationKeyUsage(t *testing.T) {
defer wg.Done() defer wg.Done()
resp, err := localKEKService.Encrypt(ctx, "test-uid", []byte(rand.String(32))) resp, err := localKEKService.Encrypt(ctx, "test-uid", []byte(rand.String(32)))
if err != nil { if err != nil {
t.Fatalf("Encrypt() error = %v", err) t.Errorf("Encrypt() error = %v", err)
return
} }
if v, ok := resp.Annotations[referenceKEKAnnotationKey]; !ok || !bytes.Equal(v, lk.encKEK) { if v, ok := resp.Annotations[referenceKEKAnnotationKey]; !ok || !bytes.Equal(v, lk.encKEK) {
t.Fatalf("Encrypt() annotations = %v, want %v", resp.Annotations, lk.encKEK) t.Errorf("Encrypt() annotations = %v, want %v", resp.Annotations, lk.encKEK)
return
} }
record.Store(resp, nil) record.Store(resp, nil)
}() }()
} }
wg.Wait() wg.Wait()
if t.Failed() {
return
}
// check we can decrypt data encrypted with the old and new local KEKs // check we can decrypt data encrypted with the old and new local KEKs
record.Range(func(key, _ any) bool { record.Range(func(key, _ any) bool {
@ -591,15 +601,20 @@ func TestRotationKeyExpiry(t *testing.T) {
defer wg.Done() defer wg.Done()
resp, err := localKEKService.Encrypt(ctx, "test-uid", []byte("test-plaintext")) resp, err := localKEKService.Encrypt(ctx, "test-uid", []byte("test-plaintext"))
if err != nil { if err != nil {
t.Fatalf("Encrypt() error = %v", err) t.Errorf("Encrypt() error = %v", err)
return
} }
if v, ok := resp.Annotations[referenceKEKAnnotationKey]; !ok || !bytes.Equal(v, encLocalKEK) { if v, ok := resp.Annotations[referenceKEKAnnotationKey]; !ok || !bytes.Equal(v, encLocalKEK) {
t.Fatalf("Encrypt() annotations = %v, want %v", resp.Annotations, encLocalKEK) t.Errorf("Encrypt() annotations = %v, want %v", resp.Annotations, encLocalKEK)
return
} }
record.Store(resp, nil) record.Store(resp, nil)
}() }()
} }
wg.Wait() wg.Wait()
if t.Failed() {
return
}
// check local KEK has only been used 3 times and still under the suggested usage // check local KEK has only been used 3 times and still under the suggested usage
if lk.usage.Load() != 3 { if lk.usage.Load() != 3 {
@ -629,15 +644,20 @@ func TestRotationKeyExpiry(t *testing.T) {
defer wg.Done() defer wg.Done()
resp, err := localKEKService.Encrypt(ctx, "test-uid", []byte("test-plaintext")) resp, err := localKEKService.Encrypt(ctx, "test-uid", []byte("test-plaintext"))
if err != nil { if err != nil {
t.Fatalf("Encrypt() error = %v", err) t.Errorf("Encrypt() error = %v", err)
return
} }
if v, ok := resp.Annotations[referenceKEKAnnotationKey]; !ok || !bytes.Equal(v, lk.encKEK) { if v, ok := resp.Annotations[referenceKEKAnnotationKey]; !ok || !bytes.Equal(v, lk.encKEK) {
t.Fatalf("Encrypt() annotations = %v, want %v", resp.Annotations, lk.encKEK) t.Errorf("Encrypt() annotations = %v, want %v", resp.Annotations, lk.encKEK)
return
} }
record.Store(resp, nil) record.Store(resp, nil)
}() }()
} }
wg.Wait() wg.Wait()
if t.Failed() {
return
}
// check we can decrypt data encrypted with the old and new local KEKs // check we can decrypt data encrypted with the old and new local KEKs
record.Range(func(key, _ any) bool { record.Range(func(key, _ any) bool {
@ -679,15 +699,20 @@ func TestRotationRemoteKeyIDChanged(t *testing.T) {
defer wg.Done() defer wg.Done()
resp, err := localKEKService.Encrypt(ctx, "test-uid", []byte("test-plaintext")) resp, err := localKEKService.Encrypt(ctx, "test-uid", []byte("test-plaintext"))
if err != nil { if err != nil {
t.Fatalf("Encrypt() error = %v", err) t.Errorf("Encrypt() error = %v", err)
return
} }
if v, ok := resp.Annotations[referenceKEKAnnotationKey]; !ok || !bytes.Equal(v, encLocalKEK) { if v, ok := resp.Annotations[referenceKEKAnnotationKey]; !ok || !bytes.Equal(v, encLocalKEK) {
t.Fatalf("Encrypt() annotations = %v, want %v", resp.Annotations, encLocalKEK) t.Errorf("Encrypt() annotations = %v, want %v", resp.Annotations, encLocalKEK)
return
} }
record.Store(resp, nil) record.Store(resp, nil)
}() }()
} }
wg.Wait() wg.Wait()
if t.Failed() {
return
}
// check local KEK has only been used 3 times and still under the suggested usage // check local KEK has only been used 3 times and still under the suggested usage
if lk.usage.Load() != 3 { if lk.usage.Load() != 3 {
@ -719,15 +744,20 @@ func TestRotationRemoteKeyIDChanged(t *testing.T) {
defer wg.Done() defer wg.Done()
resp, err := localKEKService.Encrypt(ctx, "test-uid", []byte("test-plaintext")) resp, err := localKEKService.Encrypt(ctx, "test-uid", []byte("test-plaintext"))
if err != nil { if err != nil {
t.Fatalf("Encrypt() error = %v", err) t.Errorf("Encrypt() error = %v", err)
return
} }
if v, ok := resp.Annotations[referenceKEKAnnotationKey]; !ok || !bytes.Equal(v, lk.encKEK) { if v, ok := resp.Annotations[referenceKEKAnnotationKey]; !ok || !bytes.Equal(v, lk.encKEK) {
t.Fatalf("Encrypt() annotations = %v, want %v", resp.Annotations, lk.encKEK) t.Errorf("Encrypt() annotations = %v, want %v", resp.Annotations, lk.encKEK)
return
} }
record.Store(resp, nil) record.Store(resp, nil)
}() }()
} }
wg.Wait() wg.Wait()
if t.Failed() {
return
}
// check we can decrypt data encrypted with the old and new local KEKs // check we can decrypt data encrypted with the old and new local KEKs
record.Range(func(key, _ any) bool { record.Range(func(key, _ any) bool {

View File

@ -448,7 +448,7 @@ func TestGeneratePodCopyWithDebugContainer(t *testing.T) {
"test": "test", "test": "test",
}, },
ResourceVersion: "1", ResourceVersion: "1",
CreationTimestamp: metav1.Time{time.Now()}, CreationTimestamp: metav1.Time{Time: time.Now()},
}, },
Spec: corev1.PodSpec{ Spec: corev1.PodSpec{
Containers: []corev1.Container{ Containers: []corev1.Container{

View File

@ -338,7 +338,7 @@ func TestCheckInvalidErr(t *testing.T) {
DefaultErrorExitCode, DefaultErrorExitCode,
}, },
{ {
&errors.StatusError{metav1.Status{ &errors.StatusError{ErrStatus: metav1.Status{
Status: metav1.StatusFailure, Status: metav1.StatusFailure,
Code: http.StatusUnprocessableEntity, Code: http.StatusUnprocessableEntity,
Reason: metav1.StatusReasonInvalid, Reason: metav1.StatusReasonInvalid,
@ -349,7 +349,7 @@ func TestCheckInvalidErr(t *testing.T) {
}, },
// invalid error that that includes a message but no details // invalid error that that includes a message but no details
{ {
&errors.StatusError{metav1.Status{ &errors.StatusError{ErrStatus: metav1.Status{
Status: metav1.StatusFailure, Status: metav1.StatusFailure,
Code: http.StatusUnprocessableEntity, Code: http.StatusUnprocessableEntity,
Reason: metav1.StatusReasonInvalid, Reason: metav1.StatusReasonInvalid,
@ -361,7 +361,7 @@ func TestCheckInvalidErr(t *testing.T) {
}, },
// webhook response that sets code=422 with no reason // webhook response that sets code=422 with no reason
{ {
&errors.StatusError{metav1.Status{ &errors.StatusError{ErrStatus: metav1.Status{
Status: "Failure", Status: "Failure",
Message: `admission webhook "my.webhook" denied the request without explanation`, Message: `admission webhook "my.webhook" denied the request without explanation`,
Code: 422, Code: 422,
@ -371,7 +371,7 @@ func TestCheckInvalidErr(t *testing.T) {
}, },
// webhook response that sets code=422 with no reason and non-nil details // webhook response that sets code=422 with no reason and non-nil details
{ {
&errors.StatusError{metav1.Status{ &errors.StatusError{ErrStatus: metav1.Status{
Status: "Failure", Status: "Failure",
Message: `admission webhook "my.webhook" denied the request without explanation`, Message: `admission webhook "my.webhook" denied the request without explanation`,
Code: 422, Code: 422,
@ -382,7 +382,7 @@ func TestCheckInvalidErr(t *testing.T) {
}, },
// source-wrapped webhook response that sets code=422 with no reason // source-wrapped webhook response that sets code=422 with no reason
{ {
AddSourceToErr("creating", "configmap.yaml", &errors.StatusError{metav1.Status{ AddSourceToErr("creating", "configmap.yaml", &errors.StatusError{ErrStatus: metav1.Status{
Status: "Failure", Status: "Failure",
Message: `admission webhook "my.webhook" denied the request without explanation`, Message: `admission webhook "my.webhook" denied the request without explanation`,
Code: 422, Code: 422,
@ -392,7 +392,7 @@ func TestCheckInvalidErr(t *testing.T) {
}, },
// webhook response that sets reason=Invalid and code=422 and a message // webhook response that sets reason=Invalid and code=422 and a message
{ {
&errors.StatusError{metav1.Status{ &errors.StatusError{ErrStatus: metav1.Status{
Status: "Failure", Status: "Failure",
Reason: "Invalid", Reason: "Invalid",
Message: `admission webhook "my.webhook" denied the request without explanation`, Message: `admission webhook "my.webhook" denied the request without explanation`,

View File

@ -201,11 +201,11 @@ func TestFuncs(t *testing.T) {
FuncName: "contains", FuncName: "contains",
Source: `{{contains $.haystack $.needle}}`, Source: `{{contains $.haystack $.needle}}`,
Context: map[string]any{ Context: map[string]any{
"needle": schema.GroupVersionKind{"testgroup.k8s.io", "v1", "Kind"}, "needle": schema.GroupVersionKind{Group: "testgroup.k8s.io", Version: "v1", Kind: "Kind"},
"haystack": []schema.GroupVersionKind{ "haystack": []schema.GroupVersionKind{
{"randomgroup.k8s.io", "v1", "OtherKind"}, {Group: "randomgroup.k8s.io", Version: "v1", Kind: "OtherKind"},
{"testgroup.k8s.io", "v1", "OtherKind"}, {Group: "testgroup.k8s.io", Version: "v1", Kind: "OtherKind"},
{"testgroup.k8s.io", "v1", "Kind"}, {Group: "testgroup.k8s.io", Version: "v1", Kind: "Kind"},
}, },
}, },
Expect: `true`, Expect: `true`,

View File

@ -92,7 +92,7 @@ func TestViewDeploymentHistory(t *testing.T) {
Namespace: "default", Namespace: "default",
UID: types.UID(fmt.Sprintf("00000000-0000-0000-0000-00000000000%d", i)), UID: types.UID(fmt.Sprintf("00000000-0000-0000-0000-00000000000%d", i)),
Labels: map[string]string{"foo": "bar"}, Labels: map[string]string{"foo": "bar"},
OwnerReferences: []metav1.OwnerReference{{"apps/v1", "Deployment", deployment.Name, deployment.UID, &trueVar, nil}}, OwnerReferences: []metav1.OwnerReference{{APIVersion: "apps/v1", Kind: "Deployment", Name: deployment.Name, UID: deployment.UID, Controller: &trueVar}},
Annotations: map[string]string{ Annotations: map[string]string{
"deployment.kubernetes.io/revision": fmt.Sprintf("%d", i), "deployment.kubernetes.io/revision": fmt.Sprintf("%d", i),
}, },
@ -219,7 +219,7 @@ func TestViewHistory(t *testing.T) {
Name: "moons", Name: "moons",
Namespace: "default", Namespace: "default",
Labels: map[string]string{"foo": "bar"}, Labels: map[string]string{"foo": "bar"},
OwnerReferences: []metav1.OwnerReference{{"apps/v1", "StatefulSet", "moons", "1993", &trueVar, nil}}, OwnerReferences: []metav1.OwnerReference{{APIVersion: "apps/v1", Kind: "StatefulSet", Name: "moons", UID: "1993", Controller: &trueVar}},
}, },
Data: runtime.RawExtension{Raw: stsRawData}, Data: runtime.RawExtension{Raw: stsRawData},
TypeMeta: metav1.TypeMeta{Kind: "StatefulSet", APIVersion: "apps/v1"}, TypeMeta: metav1.TypeMeta{Kind: "StatefulSet", APIVersion: "apps/v1"},
@ -323,7 +323,7 @@ func TestViewHistory(t *testing.T) {
Name: "moons", Name: "moons",
Namespace: "default", Namespace: "default",
Labels: map[string]string{"foo": "bar"}, Labels: map[string]string{"foo": "bar"},
OwnerReferences: []metav1.OwnerReference{{"apps/v1", "DaemonSet", "moons", "1993", &trueVar, nil}}, OwnerReferences: []metav1.OwnerReference{{APIVersion: "apps/v1", Kind: "DaemonSet", Name: "moons", UID: "1993", Controller: &trueVar}},
}, },
Data: runtime.RawExtension{Raw: daemonSetRaw}, Data: runtime.RawExtension{Raw: daemonSetRaw},
TypeMeta: metav1.TypeMeta{Kind: "StatefulSet", APIVersion: "apps/v1"}, TypeMeta: metav1.TypeMeta{Kind: "StatefulSet", APIVersion: "apps/v1"},

View File

@ -138,6 +138,7 @@ func TestTranslationUsingEnvVar(t *testing.T) {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
for _, envVar := range envVarsToBackup { for _, envVar := range envVarsToBackup {
if envVarValue := os.Getenv(envVar); envVarValue != "" { if envVarValue := os.Getenv(envVar); envVarValue != "" {
envVarValue, envVar := envVarValue, envVar
os.Unsetenv(envVar) os.Unsetenv(envVar)
// Restore env var at the end // Restore env var at the end
defer func() { os.Setenv(envVar, envVarValue) }() defer func() { os.Setenv(envVar, envVarValue) }()

View File

@ -92,6 +92,7 @@ func Test_assumeRoleProviderWithRateLimiting_Retrieve(t *testing.T) {
wantProviderCalled: true, wantProviderCalled: true,
sleepBeforeCallingProvider: 25 * time.Millisecond, sleepBeforeCallingProvider: 25 * time.Millisecond,
}} }}
//nolint:govet // ignore copying of sync.RWMutex, it is empty
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
l := &assumeRoleProviderWithRateLimiting{ l := &assumeRoleProviderWithRateLimiting{

View File

@ -231,6 +231,7 @@ func (nm *NodeManager) DiscoverNode(node *v1.Node) error {
cancel() cancel()
break break
} }
cancel()
} }
wg.Done() wg.Done()
}() }()

View File

@ -149,7 +149,7 @@ type registryTestCase struct {
func (tc *registryTestCase) Run(t *testing.T, registry Evaluator) { func (tc *registryTestCase) Run(t *testing.T, registry Evaluator) {
t.Run(fmt.Sprintf("%s:%s", tc.level, tc.version), func(t *testing.T) { t.Run(fmt.Sprintf("%s:%s", tc.level, tc.version), func(t *testing.T) {
results := registry.EvaluatePod(api.LevelVersion{tc.level, versionOrPanic(tc.version)}, nil, nil) results := registry.EvaluatePod(api.LevelVersion{Level: tc.level, Version: versionOrPanic(tc.version)}, nil, nil)
// Set extract the ForbiddenReasons from the results. // Set extract the ForbiddenReasons from the results.
var actualReasons []string var actualReasons []string

View File

@ -47,5 +47,5 @@ func NewREST(scheme *runtime.Scheme, optsGetter generic.RESTOptionsGetter) (*reg
if err := store.CompleteWithOptions(options); err != nil { if err := store.CompleteWithOptions(options); err != nil {
return nil, err return nil, err
} }
return &registry.REST{store}, nil return &registry.REST{Store: store}, nil
} }

View File

@ -47,5 +47,5 @@ func NewREST(scheme *runtime.Scheme, optsGetter generic.RESTOptionsGetter) (*reg
if err := store.CompleteWithOptions(options); err != nil { if err := store.CompleteWithOptions(options); err != nil {
return nil, err return nil, err
} }
return &registry.REST{store}, nil return &registry.REST{Store: store}, nil
} }