jiebi/CodeConvo huggingface dataset:
}, }, }, <ins> "attempt status update and verify it doesn't change": { job: batch.Job{ ObjectMeta: getValidObjectMeta(0), Spec: batch.JobSpec{ Selector: validSelector, Template: validPodTemplateSpec, }, Status: batch.JobStatus{ Active: 1, }, }, updatedJob: batch.Job{ ObjectMeta: getValidObjectMeta(0), Spec: batch.JobSpec{ Selector: validSelector, Template: validPodTemplateSpec, }, Status: batch.JobStatus{ Active: 2, }, }, wantJob: batch.Job{ ObjectMeta: getValidObjectMeta(0), Spec: batch.JobSpec{ Selector: validSelector, Template: validPodTemplateSpec, }, Status: batch.JobStatus{ Active: 1, }, }, }, "ensure generation doesn't change over non spec updates": { job: batch.Job{ ObjectMeta: getValidObjectMeta(0), Spec: batch.JobSpec{ Selector: validSelector, Template: validPodTemplateSpec, }, Status: batch.JobStatus{ Active: 1, }, }, updatedJob: batch.Job{ ObjectMeta: getValidObjectMetaWithAnnotations(0, map[string]string{"hello": "world"}), Spec: batch.JobSpec{ Selector: validSelector, Template: validPodTemplateSpec, }, Status: batch.JobStatus{ Active: 2, }, }, wantJob: batch.Job{ ObjectMeta: getValidObjectMetaWithAnnotations(0, map[string]string{"hello": "world"}), Spec: batch.JobSpec{ Selector: validSelector, Template: validPodTemplateSpec, }, Status: batch.JobStatus{ Active: 1, }, }, }, "test updating suspend false->true": { job: batch.Job{ ObjectMeta: getValidObjectMeta(0), Spec: batch.JobSpec{ Selector: validSelector, Template: validPodTemplateSpec, Suspend:  pointer.Bool(false), }, }, updatedJob: batch.Job{ ObjectMeta: getValidObjectMetaWithAnnotations(0, map[string]string{"hello": "world"}), Spec: batch.JobSpec{ Selector: validSelector, Template: validPodTemplateSpec, Suspend:  pointer.Bool(true), }, }, wantJob: batch.Job{ ObjectMeta: getValidObjectMetaWithAnnotations(1, map[string]string{"hello": "world"}), Spec: batch.JobSpec{ Selector: validSelector, Template: validPodTemplateSpec, Suspend:  pointer.Bool(true), }, }, }, "test updating suspend nil -> true": { job: batch.Job{ ObjectMeta: getValidObjectMeta(0), Spec: batch.JobSpec{ Selector: validSelector, Template: validPodTemplateSpec, }, }, updatedJob: batch.Job{ ObjectMeta: getValidObjectMetaWithAnnotations(0, map[string]string{"hello": "world"}), Spec: batch.JobSpec{ Selector: validSelector, Template: validPodTemplateSpec, Suspend:  pointer.Bool(true), }, }, wantJob: batch.Job{ ObjectMeta: getValidObjectMetaWithAnnotations(1, map[string]string{"hello": "world"}), Spec: batch.JobSpec{ Selector: validSelector, Template: validPodTemplateSpec, Suspend:  pointer.Bool(true), }, }, }, </ins> } for name, tc := range cases {
Strategy.PrepareForUpdate(ctx, &tc.updatedJob, &tc.job) if diff := cmp.Diff(tc.wantJob, tc.updatedJob); diff != "" { <del> t.Errorf("Job pod failure policy (-want,+got):n%s", diff) </del> <ins> t.Errorf("Job update differences (-want,+got):n%s", diff) </ins> } }) } } <del> // TestJobStrategy_PrepareForUpdate tests various scenearios for PrepareForCreate </del> <ins> // TestJobStrategy_PrepareForCreate tests various scenarios for PrepareForCreate </ins> func TestJobStrategy_PrepareForCreate(t *testing.T) { validSelector := getValidLabelSelector() validPodTemplateSpec := getValidPodTemplateSpecForSelector(validSelector)
}, }, }, <ins> "job does not allow setting status on create": { job: batch.Job{ ObjectMeta: getValidObjectMeta(0), Spec: batch.JobSpec{ Selector: validSelector, Template: validPodTemplateSpec, }, Status: batch.JobStatus{ Active: 1, }, }, wantJob: batch.Job{ ObjectMeta: getValidObjectMetaWithAnnotations(1, map[string]string{batchv1.JobTrackingFinalizer: ""}), Spec: batch.JobSpec{ Selector: validSelector, Template: validPodTemplateSpec, }, }, }, </ins> } for name, tc := range cases {
} } <del> func TestValidateToleratingBadLabels(t *testing.T) { invalidSelector := getValidLabelSelector() invalidSelector.MatchExpressions = []metav1.LabelSelectorRequirement{{Key: "key", Operator: metav1.LabelSelectorOpNotIn, Values: []string{"bad value"}}} validPodTemplateSpec := getValidPodTemplateSpecForSelector(getValidLabelSelector()) job := &batch.Job{ ObjectMeta: getValidObjectMeta(0), Spec: batch.JobSpec{ Selector:       invalidSelector, ManualSelector: pointer.BoolPtr(true), Template:       validPodTemplateSpec, }, } job.ResourceVersion = "1" oldObj := job.DeepCopy() newObj := job.DeepCopy() context := genericapirequest.NewContext() errorList := Strategy.ValidateUpdate(context, newObj, oldObj) if len(errorList) > 0 { t.Errorf("Unexpected error list with no-op update of bad object: %v", errorList) } } func TestJobStrategyValidateUpdate(t *testing.T) { </del> <ins> func TestJobStrategy_ValidateUpdate(t *testing.T) { </ins> ctx := genericapirequest.NewDefaultContext() validSelector := &metav1.LabelSelector{ MatchLabels: map[string]string{"a": "b"},
}, }, update: func(job *batch.Job) { <del> // change something. </del> job.Annotations["foo"] = "bar" }, }, <ins> "deleting user annotation": { job: &batch.Job{ ObjectMeta: metav1.ObjectMeta{ Name:            "myjob", Namespace:       metav1.NamespaceDefault, ResourceVersion: "0", Annotations: map[string]string{ batch.JobTrackingFinalizer: "", "foo":                      "bar", }, }, Spec: batch.JobSpec{ Selector:       validSelector, Template:       validPodTemplateSpec, ManualSelector: pointer.BoolPtr(true), Parallelism:    pointer.Int32Ptr(1), }, }, update: func(job *batch.Job) { delete(job.Annotations, "foo") }, }, </ins> "updating node selector for unsuspended job disallowed": { job: &batch.Job{ ObjectMeta: metav1.ObjectMeta{
}, mutableSchedulingDirectivesEnabled: false, }, <ins> "invalid label selector": { job: &batch.Job{ ObjectMeta: metav1.ObjectMeta{ Name:            "myjob", Namespace:       metav1.NamespaceDefault, ResourceVersion: "0", Annotations:     map[string]string{"foo": "bar"}, }, Spec: batch.JobSpec{ Selector: &metav1.LabelSelector{ MatchLabels:      map[string]string{"a": "b"}, MatchExpressions: []metav1.LabelSelectorRequirement{{Key: "key", Operator: metav1.LabelSelectorOpNotIn, Values: []string{"bad value"}}}, }, ManualSelector: pointer.BoolPtr(true), Template:       validPodTemplateSpec, }, }, update: func(job *batch.Job) { job.Annotations["hello"] = "world" }, }, </ins> } for name, tc := range cases { t.Run(name, func(t *testing.T) {
} } <del> func TestJobStrategyWithGeneration(t *testing.T) { ctx := genericapirequest.NewDefaultContext() theUID := types.UID("1a2b3c4d5e6f7g8h9i0k") validPodTemplateSpec := api.PodTemplateSpec{ Spec: api.PodSpec{ RestartPolicy: api.RestartPolicyOnFailure, DNSPolicy:     api.DNSClusterFirst, Containers:    []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: api.TerminationMessageReadFile}}, }, } job := &batch.Job{ ObjectMeta: metav1.ObjectMeta{ Name:      "myjob2", Namespace: metav1.NamespaceDefault, UID:       theUID, }, Spec: batch.JobSpec{ Selector: nil, Template: validPodTemplateSpec, }, } Strategy.PrepareForCreate(ctx, job) errs := Strategy.Validate(ctx, job) if len(errs) != 0 { t.Errorf("Unexpected error validating %v", errs) } // Validate the stuff that validation should have validated. if job.Spec.Selector == nil { t.Errorf("Selector not generated") } expectedLabels := make(map[string]string) expectedLabels["controller-uid"] = string(theUID) if !reflect.DeepEqual(job.Spec.Selector.MatchLabels, expectedLabels) { t.Errorf("Expected label selector not generated") } if job.Spec.Template.ObjectMeta.Labels == nil { t.Errorf("Expected template labels not generated") } if v, ok := job.Spec.Template.ObjectMeta.Labels["job-name"]; !ok || v != "myjob2" { t.Errorf("Expected template labels not present") } if v, ok := job.Spec.Template.ObjectMeta.Labels["controller-uid"]; !ok || v != string(theUID) { t.Errorf("Expected template labels not present: ok: %v, v: %v", ok, v) } } func TestJobStatusStrategy(t *testing.T) { </del> <ins> func TestJobStrategy_WarningsOnUpdate(t *testing.T) { </ins> ctx := genericapirequest.NewDefaultContext() <del> if !StatusStrategy.NamespaceScoped() { t.Errorf("Job must be namespace scoped") } if StatusStrategy.AllowCreateOnUpdate() { t.Errorf("Job should not allow create on update") } </del> validSelector := &metav1.LabelSelector{ MatchLabels: map[string]string{"a": "b"}, }
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" semconv "go.opentelemetry.io/otel/semconv/v1.17.0" "go.opentelemetry.io/otel/trace" <ins> "k8s.io/apiserver/pkg/endpoints/request" </ins> tracing "k8s.io/component-base/tracing" )
otelhttp.WithPropagators(tracing.Propagators()), otelhttp.WithPublicEndpoint(), otelhttp.WithTracerProvider(tp), <ins> otelhttp.WithSpanNameFormatter(func(operation string, r *http.Request) string { ctx := r.Context() info, exist := request.RequestInfoFrom(ctx) if !exist || !info.IsResourceRequest { return r.Method } return getSpanNameFromRequestInfo(info, r) }), </ins> } wrappedHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Add the http.target attribute to the otelhttp span
// See https://github.com/open-telemetry/opentelemetry-go/tree/main/example/passthrough return otelhttp.NewHandler(wrappedHandler, "KubernetesAPI", opts...) } <ins> func getSpanNameFromRequestInfo(info *request.RequestInfo, r *http.Request) string { spanName := "/" + info.APIPrefix if info.APIGroup != "" { spanName += "/" + info.APIGroup } spanName += "/" + info.APIVersion if info.Namespace != "" { spanName += "/namespaces/{:namespace}" } spanName += "/" + info.Resource if info.Name != "" { spanName += "/" + "{:name}" } if info.Subresource != "" { spanName += "/" + info.Subresource } return r.Method + " " + spanName } </ins>
}, expectedTrace: []*spanExpectation{ { <del> name: "KubernetesAPI", </del> <ins> name: "POST /api/v1/nodes", </ins> attributes: map[string]func(*commonv1.AnyValue) bool{ "http.user_agent": func(v *commonv1.AnyValue) bool { return strings.HasPrefix(v.GetStringValue(), "tracing.test")
}, expectedTrace: []*spanExpectation{ { <del> name: "KubernetesAPI", </del> <ins> name: "GET /api/v1/nodes/{:name}", </ins> attributes: map[string]func(*commonv1.AnyValue) bool{ "http.user_agent": func(v *commonv1.AnyValue) bool { return strings.HasPrefix(v.GetStringValue(), "tracing.test")
}, expectedTrace: []*spanExpectation{ { <del> name: "KubernetesAPI", </del> <ins> name: "GET /api/v1/nodes", </ins> attributes: map[string]func(*commonv1.AnyValue) bool{ "http.user_agent": func(v *commonv1.AnyValue) bool { return strings.HasPrefix(v.GetStringValue(), "tracing.test")
}, expectedTrace: []*spanExpectation{ { <del> name: "KubernetesAPI", </del> <ins> name: "PUT /api/v1/nodes/{:name}", </ins> attributes: map[string]func(*commonv1.AnyValue) bool{ "http.user_agent": func(v *commonv1.AnyValue) bool { return strings.HasPrefix(v.GetStringValue(), "tracing.test")
}, expectedTrace: []*spanExpectation{ { <del> name: "KubernetesAPI", </del> <ins> name: "PATCH /api/v1/nodes/{:name}", </ins> attributes: map[string]func(*commonv1.AnyValue) bool{ "http.user_agent": func(v *commonv1.AnyValue) bool { return strings.HasPrefix(v.GetStringValue(), "tracing.test")
}, expectedTrace: []*spanExpectation{ { <del> name: "KubernetesAPI", </del> <ins> name: "DELETE /api/v1/nodes/{:name}", </ins> attributes: map[string]func(*commonv1.AnyValue) bool{ "http.user_agent": func(v *commonv1.AnyValue) bool { return strings.HasPrefix(v.GetStringValue(), "tracing.test")
"path/filepath" "strings" <del> "k8s.io/api/core/v1" </del> <ins> v1 "k8s.io/api/core/v1" </ins> utilerrors "k8s.io/apimachinery/pkg/util/errors" utilvalidation "k8s.io/apimachinery/pkg/util/validation" utilfeature "k8s.io/apiserver/pkg/util/feature"
{"nameserver t 1.2.3.4", []string{"1.2.3.4"}, []string{}, []string{}, false}, {"nameserver 1.2.3.4nnameserver 5.6.7.8", []string{"1.2.3.4", "5.6.7.8"}, []string{}, []string{}, false}, {"nameserver 1.2.3.4 #comment", []string{"1.2.3.4"}, []string{}, []string{}, false}, <del> {"search ", []string{}, []string{}, []string{}, false}, // search empty {"search .", []string{}, []string{"."}, []string{}, false}, </del> <ins> {"search ", []string{}, []string{}, []string{}, false},  // search empty {"search .", []string{}, []string{}, []string{}, false}, // ignore lone dot {"search . foo", []string{}, []string{"foo"}, []string{}, false}, {"search foo .", []string{}, []string{"foo"}, []string{}, false}, {"search foo .  bar", []string{}, []string{"foo", "bar"}, []string{}, false}, </ins> {"search foo", []string{}, []string{"foo"}, []string{}, false}, {"search foo bar", []string{}, []string{"foo", "bar"}, []string{}, false}, {"search foo. bar", []string{}, []string{"foo", "bar"}, []string{}, false},
utilruntime.Must(flowcontrolv1beta1.AddToScheme(scheme)) utilruntime.Must(flowcontrolv1beta2.AddToScheme(scheme)) utilruntime.Must(flowcontrolv1beta3.AddToScheme(scheme)) <del> // TODO(#112512): This controls serialization order, for 1.26, we can //  set the serialization version to v1beta2 because vN-1 understands that //  level. In 1.27, we should set the serialization version to v1beta3. utilruntime.Must(scheme.SetVersionPriority(flowcontrolv1beta2.SchemeGroupVersion, flowcontrolv1beta3.SchemeGroupVersion, </del> <ins> utilruntime.Must(scheme.SetVersionPriority(flowcontrolv1beta3.SchemeGroupVersion, flowcontrolv1beta2.SchemeGroupVersion, </ins> flowcontrolv1beta1.SchemeGroupVersion, flowcontrolv1alpha1.SchemeGroupVersion)) }
"admissionregistration.k8s.io/v1/mutatingwebhookconfigurations":    "Sqi0GUgDaX0=", "admissionregistration.k8s.io/v1/validatingwebhookconfigurations":  "B0wHjQmsGNk=", "events.k8s.io/v1/events":                                          "r2yiGXH7wu8=", <del> "flowcontrol.apiserver.k8s.io/v1beta3/flowschemas":                 "G+8IkrqFuJw=", "flowcontrol.apiserver.k8s.io/v1beta3/prioritylevelconfigurations": "wltM4WMeeXs=", "flowcontrol.apiserver.k8s.io/v1beta2/flowschemas":                 "G+8IkrqFuJw=", "flowcontrol.apiserver.k8s.io/v1beta2/prioritylevelconfigurations": "wltM4WMeeXs=", </del> <ins> "flowcontrol.apiserver.k8s.io/v1beta3/flowschemas":                 "9NnFrw7ZEmA=", "flowcontrol.apiserver.k8s.io/v1beta3/prioritylevelconfigurations": "+CwSrEWTDhc=", "flowcontrol.apiserver.k8s.io/v1beta2/flowschemas":                 "9NnFrw7ZEmA=", "flowcontrol.apiserver.k8s.io/v1beta2/prioritylevelconfigurations": "+CwSrEWTDhc=", </ins> }
gvr("flowcontrol.apiserver.k8s.io", "v1alpha1", "flowschemas"): { Stub:             `{"metadata": {"name": "va1"}, "spec": {"priorityLevelConfiguration": {"name": "name1"}}}`, ExpectedEtcdPath: "/registry/flowschemas/va1", <del> ExpectedGVK:      gvkP("flowcontrol.apiserver.k8s.io", "v1beta2", "FlowSchema"), </del> <ins> ExpectedGVK:      gvkP("flowcontrol.apiserver.k8s.io", "v1beta3", "FlowSchema"), </ins> }, // --
gvr("flowcontrol.apiserver.k8s.io", "v1alpha1", "prioritylevelconfigurations"): { Stub:             `{"metadata": {"name": "conf1"}, "spec": {"type": "Limited", "limited": {"assuredConcurrencyShares":3, "limitResponse": {"type": "Reject"}}}}`, ExpectedEtcdPath: "/registry/prioritylevelconfigurations/conf1", <del> ExpectedGVK:      gvkP("flowcontrol.apiserver.k8s.io", "v1beta2", "PriorityLevelConfiguration"), </del> <ins> ExpectedGVK:      gvkP("flowcontrol.apiserver.k8s.io", "v1beta3", "PriorityLevelConfiguration"), </ins> }, // --
gvr("flowcontrol.apiserver.k8s.io", "v1beta1", "flowschemas"): { Stub:             `{"metadata": {"name": "va2"}, "spec": {"priorityLevelConfiguration": {"name": "name1"}}}`, ExpectedEtcdPath: "/registry/flowschemas/va2", <del> ExpectedGVK:      gvkP("flowcontrol.apiserver.k8s.io", "v1beta2", "FlowSchema"), </del> <ins> ExpectedGVK:      gvkP("flowcontrol.apiserver.k8s.io", "v1beta3", "FlowSchema"), </ins> }, // --
gvr("flowcontrol.apiserver.k8s.io", "v1beta1", "prioritylevelconfigurations"): { Stub:             `{"metadata": {"name": "conf2"}, "spec": {"type": "Limited", "limited": {"assuredConcurrencyShares":3, "limitResponse": {"type": "Reject"}}}}`, ExpectedEtcdPath: "/registry/prioritylevelconfigurations/conf2", <del> ExpectedGVK:      gvkP("flowcontrol.apiserver.k8s.io", "v1beta2", "PriorityLevelConfiguration"), </del> <ins> ExpectedGVK:      gvkP("flowcontrol.apiserver.k8s.io", "v1beta3", "PriorityLevelConfiguration"), </ins> }, // --
gvr("flowcontrol.apiserver.k8s.io", "v1beta2", "flowschemas"): { Stub:             `{"metadata": {"name": "fs-1"}, "spec": {"priorityLevelConfiguration": {"name": "name1"}}}`, ExpectedEtcdPath: "/registry/flowschemas/fs-1", <ins> ExpectedGVK:      gvkP("flowcontrol.apiserver.k8s.io", "v1beta3", "FlowSchema"), </ins> }, // --
gvr("flowcontrol.apiserver.k8s.io", "v1beta2", "prioritylevelconfigurations"): { Stub:             `{"metadata": {"name": "conf3"}, "spec": {"type": "Limited", "limited": {"assuredConcurrencyShares":3, "limitResponse": {"type": "Reject"}}}}`, ExpectedEtcdPath: "/registry/prioritylevelconfigurations/conf3", <ins> ExpectedGVK:      gvkP("flowcontrol.apiserver.k8s.io", "v1beta3", "PriorityLevelConfiguration"), </ins> }, // --
gvr("flowcontrol.apiserver.k8s.io", "v1beta3", "flowschemas"): { Stub:             `{"metadata": {"name": "fs-2"}, "spec": {"priorityLevelConfiguration": {"name": "name1"}}}`, ExpectedEtcdPath: "/registry/flowschemas/fs-2", <del> ExpectedGVK:      gvkP("flowcontrol.apiserver.k8s.io", "v1beta2", "FlowSchema"), </del> }, // --
gvr("flowcontrol.apiserver.k8s.io", "v1beta3", "prioritylevelconfigurations"): { Stub:             `{"metadata": {"name": "conf4"}, "spec": {"type": "Limited", "limited": {"nominalConcurrencyShares":3, "limitResponse": {"type": "Reject"}}}}`, ExpectedEtcdPath: "/registry/prioritylevelconfigurations/conf4", <del> ExpectedGVK:      gvkP("flowcontrol.apiserver.k8s.io", "v1beta2", "PriorityLevelConfiguration"), </del> }, // --
oldModifyResponse := proxy.ModifyResponse proxy.ModifyResponse = func(response *http.Response) error { code := response.StatusCode <del> if code >= 300 && code <= 399 { </del> <ins> if code >= 300 && code <= 399 && len(response.Header.Get("Location")) > 0 { </ins> // close the original response response.Body.Close() msg := "the backend attempted to redirect this request, which is not permitted"
name:                      "reject redirection enabled in proxy, backend server sending 301 response", rejectForwardingRedirects: true, serverStatusCode:          301, <ins> redirect:                  "/", </ins> expectStatusCode:          502, expectBody:                []byte(`the backend attempted to redirect this request, which is not permitted`), }, { <ins> name:                      "reject redirection enabled in proxy, backend server sending 304 response with a location header", rejectForwardingRedirects: true, serverStatusCode:          304, redirect:                  "/", expectStatusCode:          502, expectBody:                []byte(`the backend attempted to redirect this request, which is not permitted`), }, { name:                      "reject redirection enabled in proxy, backend server sending 304 response with no location header", rejectForwardingRedirects: true, serverStatusCode:          304, expectStatusCode:          304, expectBody:                []byte{}, // client doesn't read the body for 304 responses }, { </ins> name:                      "reject redirection disabled in proxy, backend server sending 200 response", rejectForwardingRedirects: false, serverStatusCode:          200,
// SelectorFromValidatedSet returns a Selector which will match exactly the given Set. // A nil and empty Sets are considered equivalent to Everything(). // It assumes that Set is already validated and doesn't do any validation. <ins> // Note: this method copies the Set; if the Set is immutable, consider wrapping it with ValidatedSetSelector // instead, which does not copy. </ins> func SelectorFromValidatedSet(ls Set) Selector { if ls == nil || len(ls) == 0 { return internalSelector{}
func ParseToRequirements(selector string, opts ...field.PathOption) ([]Requirement, error) { return parse(selector, field.ToPath(opts...)) } <ins> // ValidatedSetSelector wraps a Set, allowing it to implement the Selector interface. Unlike // Set.AsSelectorPreValidated (which copies the input Set), this type simply wraps the underlying // Set. As a result, it is substantially more efficient. A nil and empty Sets are considered // equivalent to Everything(). // // Callers MUST ensure the underlying Set is not mutated, and that it is already validated. If these // constraints are not met, Set.AsValidatedSelector should be preferred // // None of the Selector methods mutate the underlying Set, but Add() and Requirements() convert to // the less optimized version. type ValidatedSetSelector Set func (s ValidatedSetSelector) Matches(labels Labels) bool { for k, v := range s { if !labels.Has(k) || v != labels.Get(k) { return false } } return true } func (s ValidatedSetSelector) Empty() bool { return len(s) == 0 } func (s ValidatedSetSelector) String() string { keys := make([]string, 0, len(s)) for k := range s { keys = append(keys, k) } // Ensure deterministic output sort.Strings(keys) b := strings.Builder{} for i, key := range keys { v := s[key] b.Grow(len(key) + 2 + len(v)) if i != 0 { b.WriteString(",") } b.WriteString(key) b.WriteString("=") b.WriteString(v) } return b.String() } func (s ValidatedSetSelector) Add(r ...Requirement) Selector { return s.toFullSelector().Add(r...) } func (s ValidatedSetSelector) Requirements() (requirements Requirements, selectable bool) { return s.toFullSelector().Requirements() } func (s ValidatedSetSelector) DeepCopySelector() Selector { res := make(ValidatedSetSelector, len(s)) for k, v := range s { res[k] = v } return res } func (s ValidatedSetSelector) RequiresExactMatch(label string) (value string, found bool) { v, f := s[label] return v, f } func (s ValidatedSetSelector) toFullSelector() Selector { return SelectorFromValidatedSet(Set(s)) } var _ Selector = ValidatedSetSelector{} </ins>
"foo": "foo", "bar": "bar", } <ins> matchee := Set(map[string]string{ "foo":   "foo", "bar":   "bar", "extra": "label", }) </ins> for i := 0; i < b.N; i++ { <del> if SelectorFromValidatedSet(set).Empty() { </del> <ins> s := SelectorFromValidatedSet(set) if s.Empty() { </ins> b.Errorf("Unexpected selector") } <ins> if !s.Matches(matchee) { b.Errorf("Unexpected match") } } } func BenchmarkSetSelector(b *testing.B) { set := map[string]string{ "foo": "foo", "bar": "bar", } matchee := Set(map[string]string{ "foo":   "foo", "bar":   "bar", "extra": "label", }) for i := 0; i < b.N; i++ { s := ValidatedSetSelector(set) if s.Empty() { b.Errorf("Unexpected selector") } if !s.Matches(matchee) { b.Errorf("Unexpected match") } } } func TestSetSelectorString(t *testing.T) { cases := []struct { set Set out string }{ { Set{}, "", }, { Set{"app": "foo"}, "app=foo", }, { Set{"app": "foo", "a": "b"}, "a=b,app=foo", }, } for _, tt := range cases { t.Run(tt.out, func(t *testing.T) { if got := ValidatedSetSelector(tt.set).String(); tt.out != got { t.Fatalf("expected %v, got %v", tt.out, got) } }) </ins> } }
"fmt" "strings" <del> "k8s.io/api/core/v1" </del> <ins> v1 "k8s.io/api/core/v1" </ins> "k8s.io/apimachinery/pkg/api/resource" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/util/validation/field"
if exists { // For GPUs, not only requests can't exceed limits, they also can't be lower, i.e. must be equal. if quantity.Cmp(limitQuantity) != 0 && !v1helper.IsOvercommitAllowed(resourceName) { <del> allErrs = append(allErrs, field.Invalid(reqPath, quantity.String(), fmt.Sprintf("must be equal to %s limit", resourceName))) </del> <ins> allErrs = append(allErrs, field.Invalid(reqPath, quantity.String(), fmt.Sprintf("must be equal to %s limit of %s", resourceName, limitQuantity.String()))) </ins> } else if quantity.Cmp(limitQuantity) > 0 { <del> allErrs = append(allErrs, field.Invalid(reqPath, quantity.String(), fmt.Sprintf("must be less than or equal to %s limit", resourceName))) </del> <ins> allErrs = append(allErrs, field.Invalid(reqPath, quantity.String(), fmt.Sprintf("must be less than or equal to %s limit of %s", resourceName, limitQuantity.String()))) </ins> } } }
package validation import ( <ins> "strings" </ins> "testing" <del> "k8s.io/api/core/v1" </del> <ins> v1 "k8s.io/api/core/v1" </ins> "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/sets"