jiebi/CodeConvo huggingface dataset:
}}, expected: errors.New("kubernetes.io/foo is an invalid extended resource name"), }, <ins> { name: "invalid redeclared custom predicate", policy: api.Policy{ Predicates: []api.PredicatePolicy{ {Name: "customPredicate1", Argument: &api.PredicateArgument{ServiceAffinity: &api.ServiceAffinity{Labels: []string{"label1"}}}}, {Name: "customPredicate2", Argument: &api.PredicateArgument{ServiceAffinity: &api.ServiceAffinity{Labels: []string{"label2"}}}}, }, }, expected: errors.New("Predicate 'customPredicate2' redeclares custom predicate 'ServiceAffinity', from:'customPredicate1'"), }, { name: "invalid redeclared custom priority", policy: api.Policy{ Priorities: []api.PriorityPolicy{ {Name: "customPriority1", Weight: 1, Argument: &api.PriorityArgument{ServiceAntiAffinity: &api.ServiceAntiAffinity{Label: "label1"}}}, {Name: "customPriority2", Weight: 1, Argument: &api.PriorityArgument{ServiceAntiAffinity: &api.ServiceAntiAffinity{Label: "label2"}}}, }, }, expected: errors.New("Priority 'customPriority2' redeclares custom priority 'ServiceAntiAffinity', from:'customPriority1'"), }, </ins> } for _, test := range tests {
function wait_node_ready(){ # check the nodes information after kubelet daemon start local nodes_stats="${KUBECTL} --kubeconfig '${CERT_DIR}/admin.kubeconfig' get nodes" <del> local node_name=$KUBELET_HOST </del> <ins> local node_name=$HOSTNAME_OVERRIDE </ins> local system_node_wait_time=30 local interval_time=2 kube::util::wait_for_success "$system_node_wait_time" "$interval_time" "$nodes_stats | grep $node_name"
checkNode := func(i int) { // We check the nodes starting from where we left off in the previous scheduling cycle, // this is to make sure all nodes have the same chance of being examined across pods. <del> nodeInfo := g.nodeInfoSnapshot.NodeInfoList[(g.lastProcessedNodeIndex+i)%allNodes] </del> <ins> nodeInfo := g.nodeInfoSnapshot.NodeInfoList[(g.nextStartNodeIndex+i)%allNodes] </ins> fits, failedPredicates, status, err := g.podFitsOnNode( ctx, state,
// are found. workqueue.ParallelizeUntil(ctx, 16, allNodes, checkNode) processedNodes := int(filteredLen) + len(filteredNodesStatuses) + len(failedPredicateMap) <del> g.lastProcessedNodeIndex = (g.lastProcessedNodeIndex + processedNodes) % allNodes </del> <ins> g.nextStartNodeIndex = (g.nextStartNodeIndex + processedNodes) % allNodes </ins> filtered = filtered[:filteredLen] if err := errCh.ReceiveError(); err != nil {
} } } <ins> func TestFairEvaluationForNodes(t *testing.T) { defer algorithmpredicates.SetPredicatesOrderingDuringTest(order)() predicates := map[string]algorithmpredicates.FitPredicate{"true": truePredicate} numAllNodes := 500 nodeNames := make([]string, 0, numAllNodes) for i := 0; i < numAllNodes; i++ { nodeNames = append(nodeNames, strconv.Itoa(i)) } nodes := makeNodeList(nodeNames) g := makeScheduler(predicates, nodes) // To make numAllNodes % nodesToFind != 0 g.percentageOfNodesToScore = 30 nodesToFind := int(g.numFeasibleNodesToFind(int32(numAllNodes))) // Iterating over all nodes more than twice for i := 0; i < 2*(numAllNodes/nodesToFind+1); i++ { nodesThatFit, _, _, err := g.findNodesThatFit(context.Background(), framework.NewCycleState(), &v1.Pod{}) if err != nil { t.Errorf("unexpected error: %v", err) } if len(nodesThatFit) != nodesToFind { t.Errorf("got %d nodes filtered, want %d", len(nodesThatFit), nodesToFind) } if g.nextStartNodeIndex != (i+1)*nodesToFind%numAllNodes { t.Errorf("got %d lastProcessedNodeIndex, want %d", g.nextStartNodeIndex, (i+1)*nodesToFind%numAllNodes) } } } </ins>
"//pkg/api/v1/endpoints:go_default_library", "//staging/src/k8s.io/api/core/v1:go_default_library", "//staging/src/k8s.io/api/discovery/v1alpha1:go_default_library", <ins> "//staging/src/k8s.io/apimachinery/pkg/api/equality:go_default_library", </ins> "//staging/src/k8s.io/apimachinery/pkg/api/errors:go_default_library", "//staging/src/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", "//staging/src/k8s.io/apimachinery/pkg/runtime:go_default_library",
import ( corev1 "k8s.io/api/core/v1" discovery "k8s.io/api/discovery/v1alpha1" <ins> apiequality "k8s.io/apimachinery/pkg/api/equality" </ins> "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" corev1client "k8s.io/client-go/kubernetes/typed/core/v1"
// returned. func (adapter *EndpointsAdapter) Create(namespace string, endpoints *corev1.Endpoints) (*corev1.Endpoints, error) { endpoints, err := adapter.endpointClient.Endpoints(namespace).Create(endpoints) <del> if err == nil && adapter.endpointSliceClient != nil { _, err = adapter.ensureEndpointSliceFromEndpoints(namespace, endpoints) </del> <ins> if err == nil { err = adapter.EnsureEndpointSliceFromEndpoints(namespace, endpoints) </ins> } return endpoints, err }
// updated. The updated Endpoints object or an error will be returned. func (adapter *EndpointsAdapter) Update(namespace string, endpoints *corev1.Endpoints) (*corev1.Endpoints, error) { endpoints, err := adapter.endpointClient.Endpoints(namespace).Update(endpoints) <del> if err == nil && adapter.endpointSliceClient != nil { _, err = adapter.ensureEndpointSliceFromEndpoints(namespace, endpoints) </del> <ins> if err == nil { err = adapter.EnsureEndpointSliceFromEndpoints(namespace, endpoints) </ins> } return endpoints, err } <del> // ensureEndpointSliceFromEndpoints accepts a namespace and Endpoints resource // and creates or updates a corresponding EndpointSlice. The EndpointSlice // and/or an error will be returned. func (adapter *EndpointsAdapter) ensureEndpointSliceFromEndpoints(namespace string, endpoints *corev1.Endpoints) (*discovery.EndpointSlice, error) { </del> <ins> // EnsureEndpointSliceFromEndpoints accepts a namespace and Endpoints resource // and creates or updates a corresponding EndpointSlice if an endpointSliceClient // exists. An error will be returned if it fails to sync the EndpointSlice. func (adapter *EndpointsAdapter) EnsureEndpointSliceFromEndpoints(namespace string, endpoints *corev1.Endpoints) error { if adapter.endpointSliceClient == nil { return nil } </ins> endpointSlice := endpointSliceFromEndpoints(endpoints) <del> _, err := adapter.endpointSliceClient.EndpointSlices(namespace).Get(endpointSlice.Name, metav1.GetOptions{}) </del> <ins> currentEndpointSlice, err := adapter.endpointSliceClient.EndpointSlices(namespace).Get(endpointSlice.Name, metav1.GetOptions{}) </ins> if err != nil { if errors.IsNotFound(err) { <del> return adapter.endpointSliceClient.EndpointSlices(namespace).Create(endpointSlice) </del> <ins> if _, err = adapter.endpointSliceClient.EndpointSlices(namespace).Create(endpointSlice); errors.IsAlreadyExists(err) { err = nil } </ins> } <del> return nil, err </del> <ins> return err } if apiequality.Semantic.DeepEqual(currentEndpointSlice.Endpoints, endpointSlice.Endpoints) && apiequality.Semantic.DeepEqual(currentEndpointSlice.Ports, endpointSlice.Ports) && apiequality.Semantic.DeepEqual(currentEndpointSlice.Labels, endpointSlice.Labels) { return nil </ins> } <del> return adapter.endpointSliceClient.EndpointSlices(namespace).Update(endpointSlice) </del> <ins> _, err = adapter.endpointSliceClient.EndpointSlices(namespace).Update(endpointSlice) return err </ins> } // endpointSliceFromEndpoints generates an EndpointSlice from an Endpoints
Subsets:    []corev1.EndpointSubset{subset}, }, epSlice } <ins> func TestEndpointsAdapterEnsureEndpointSliceFromEndpoints(t *testing.T) { endpoints1, epSlice1 := generateEndpointsAndSlice("foo", "testing", []int{80, 443}, []string{"10.1.2.3", "10.1.2.4"}) endpoints2, epSlice2 := generateEndpointsAndSlice("foo", "testing", []int{80, 443}, []string{"10.1.2.3", "10.1.2.4", "10.1.2.5"}) testCases := map[string]struct { endpointSlicesEnabled bool expectedError         error expectedEndpointSlice *discovery.EndpointSlice endpointSlices        []*discovery.EndpointSlice namespaceParam        string endpointsParam        *corev1.Endpoints }{ "existing-endpointslice-no-change": { endpointSlicesEnabled: true, expectedError:         nil, expectedEndpointSlice: epSlice1, endpointSlices:        []*discovery.EndpointSlice{epSlice1}, namespaceParam:        "testing", endpointsParam:        endpoints1, }, "existing-endpointslice-change": { endpointSlicesEnabled: true, expectedError:         nil, expectedEndpointSlice: epSlice2, endpointSlices:        []*discovery.EndpointSlice{epSlice1}, namespaceParam:        "testing", endpointsParam:        endpoints2, }, "missing-endpointslice": { endpointSlicesEnabled: true, expectedError:         nil, expectedEndpointSlice: epSlice1, endpointSlices:        []*discovery.EndpointSlice{}, namespaceParam:        "testing", endpointsParam:        endpoints1, }, "endpointslices-disabled": { endpointSlicesEnabled: false, expectedError:         nil, expectedEndpointSlice: nil, endpointSlices:        []*discovery.EndpointSlice{}, namespaceParam:        "testing", endpointsParam:        endpoints1, }, } for name, testCase := range testCases { t.Run(name, func(t *testing.T) { client := fake.NewSimpleClientset() epAdapter := EndpointsAdapter{endpointClient: client.CoreV1()} if testCase.endpointSlicesEnabled { epAdapter.endpointSliceClient = client.DiscoveryV1alpha1() } for _, endpointSlice := range testCase.endpointSlices { _, err := client.DiscoveryV1alpha1().EndpointSlices(endpointSlice.Namespace).Create(endpointSlice) if err != nil { t.Fatalf("Error creating EndpointSlice: %v", err) } } err := epAdapter.EnsureEndpointSliceFromEndpoints(testCase.namespaceParam, testCase.endpointsParam) if !apiequality.Semantic.DeepEqual(testCase.expectedError, err) { t.Errorf("Expected error: %v, got: %v", testCase.expectedError, err) } endpointSlice, err := client.DiscoveryV1alpha1().EndpointSlices(testCase.namespaceParam).Get(testCase.endpointsParam.Name, metav1.GetOptions{}) if err != nil && !errors.IsNotFound(err) { t.Fatalf("Error getting Endpoint Slice: %v", err) } if !apiequality.Semantic.DeepEqual(endpointSlice, testCase.expectedEndpointSlice) { t.Errorf("Expected Endpoint Slice: %v, got: %v", testCase.expectedEndpointSlice, endpointSlice) } }) } } </ins>
// Next, we compare the current list of endpoints with the list of master IP keys formatCorrect, ipCorrect, portsCorrect := checkEndpointSubsetFormatWithLease(e, masterIPs, endpointPorts, reconcilePorts) if formatCorrect && ipCorrect && portsCorrect { <del> return nil </del> <ins> return r.epAdapter.EnsureEndpointSliceFromEndpoints(corev1.NamespaceDefault, e) </ins> } if !formatCorrect {
func (m *podContainerManagerImpl) Destroy(podCgroup CgroupName) error { // Try killing all the processes attached to the pod cgroup if err := m.tryKillingCgroupProcesses(podCgroup); err != nil { <del> klog.V(3).Infof("failed to kill all the processes attached to the %v cgroups", podCgroup) </del> <ins> klog.Warningf("failed to kill all the processes attached to the %v cgroups", podCgroup) </ins> return fmt.Errorf("failed to kill all the processes attached to the %v cgroups : %v", podCgroup, err) }
// TODO(liggitt): drop this once golang json parser limits stack depth (https://github.com/golang/go/issues/31789) if len(p.patchBytes) > 1024*1024 { v := []interface{}{} <del> if err := json.Unmarshal(p.patchBytes, v); err != nil { </del> <ins> if err := json.Unmarshal(p.patchBytes, &v); err != nil { </ins> return nil, errors.NewBadRequest(fmt.Sprintf("error decoding patch: %v", err)) } }
// TODO(liggitt): drop this once golang json parser limits stack depth (https://github.com/golang/go/issues/31789) if len(p.patchBytes) > 1024*1024 { v := map[string]interface{}{} <del> if err := json.Unmarshal(p.patchBytes, v); err != nil { </del> <ins> if err := json.Unmarshal(p.patchBytes, &v); err != nil { </ins> return nil, errors.NewBadRequest(fmt.Sprintf("error decoding patch: %v", err)) } }
t.Errorf("expected success or bad request err, got %v", err) } }) <ins> t.Run("JSONPatchType should handle a valid patch just under the max limit", func(t *testing.T) { patchBody := []byte(`[{"op":"add","path":"/foo","value":0` + strings.Repeat(" ", 3*1024*1024-100) + `}]`) err = rest.Patch(types.JSONPatchType).AbsPath(fmt.Sprintf("/api/v1/namespaces/default/secrets/test")). Body(patchBody).Do().Error() if err != nil { t.Errorf("unexpected error: %v", err) } }) </ins> t.Run("MergePatchType should handle a patch just under the max limit", func(t *testing.T) { patchBody := []byte(`{"value":` + strings.Repeat("[", 3*1024*1024/2-100) + strings.Repeat("]", 3*1024*1024/2-100) + `}`) err = rest.Patch(types.MergePatchType).AbsPath(fmt.Sprintf("/api/v1/namespaces/default/secrets/test")).
t.Errorf("expected success or bad request err, got %v", err) } }) <ins> t.Run("MergePatchType should handle a valid patch just under the max limit", func(t *testing.T) { patchBody := []byte(`{"value":0` + strings.Repeat(" ", 3*1024*1024-100) + `}`) err = rest.Patch(types.MergePatchType).AbsPath(fmt.Sprintf("/api/v1/namespaces/default/secrets/test")). Body(patchBody).Do().Error() if err != nil { t.Errorf("unexpected error: %v", err) } }) </ins> t.Run("StrategicMergePatchType should handle a patch just under the max limit", func(t *testing.T) { patchBody := []byte(`{"value":` + strings.Repeat("[", 3*1024*1024/2-100) + strings.Repeat("]", 3*1024*1024/2-100) + `}`) err = rest.Patch(types.StrategicMergePatchType).AbsPath(fmt.Sprintf("/api/v1/namespaces/default/secrets/test")).
t.Errorf("expected success or bad request err, got %v", err) } }) <ins> t.Run("StrategicMergePatchType should handle a valid patch just under the max limit", func(t *testing.T) { patchBody := []byte(`{"value":0` + strings.Repeat(" ", 3*1024*1024-100) + `}`) err = rest.Patch(types.StrategicMergePatchType).AbsPath(fmt.Sprintf("/api/v1/namespaces/default/secrets/test")). Body(patchBody).Do().Error() if err != nil { t.Errorf("unexpected error: %v", err) } }) </ins> t.Run("ApplyPatchType should handle a patch just under the max limit", func(t *testing.T) { patchBody := []byte(`{"value":` + strings.Repeat("[", 3*1024*1024/2-100) + strings.Repeat("]", 3*1024*1024/2-100) + `}`) err = rest.Patch(types.ApplyPatchType).Param("fieldManager", "test").AbsPath(fmt.Sprintf("/api/v1/namespaces/default/secrets/test")).
t.Errorf("expected success or bad request err, got %#v", err) } }) <ins> t.Run("ApplyPatchType should handle a valid patch just under the max limit", func(t *testing.T) { patchBody := []byte(`{"apiVersion":"v1","kind":"Secret"` + strings.Repeat(" ", 3*1024*1024-100) + `}`) err = rest.Patch(types.ApplyPatchType).Param("fieldManager", "test").AbsPath(fmt.Sprintf("/api/v1/namespaces/default/secrets/test")). Body(patchBody).Do().Error() if err != nil { t.Errorf("unexpected error: %v", err) } }) </ins> t.Run("Delete should limit the request body size", func(t *testing.T) { err = c.Delete().AbsPath(fmt.Sprintf("/api/v1/namespaces/default/secrets/test")). Body(hugeData).Do().Error()
} } <ins> func TestApplyPruneObjects(t *testing.T) { cmdtesting.InitTestErrorHandler(t) nameRC, currentRC := readAndAnnotateReplicationController(t, filenameRC) pathRC := "/namespaces/test/replicationcontrollers/" + nameRC for _, fn := range testingOpenAPISchemaFns { t.Run("test apply returns correct output", func(t *testing.T) { tf := cmdtesting.NewTestFactory().WithNamespace("test") defer tf.Cleanup() tf.UnstructuredClient = &fake.RESTClient{ NegotiatedSerializer: resource.UnstructuredPlusDefaultContentConfig().NegotiatedSerializer, Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { switch p, m := req.URL.Path, req.Method; { case p == pathRC && m == "GET": bodyRC := ioutil.NopCloser(bytes.NewReader(currentRC)) return &http.Response{StatusCode: http.StatusOK, Header: cmdtesting.DefaultHeader(), Body: bodyRC}, nil case p == pathRC && m == "PATCH": validatePatchApplication(t, req) bodyRC := ioutil.NopCloser(bytes.NewReader(currentRC)) return &http.Response{StatusCode: http.StatusOK, Header: cmdtesting.DefaultHeader(), Body: bodyRC}, nil default: t.Fatalf("unexpected request: %#vn%#v", req.URL, req) return nil, nil } }), } tf.OpenAPISchemaFunc = fn tf.ClientConfigVal = cmdtesting.DefaultClientConfig() ioStreams, _, buf, errBuf := genericclioptions.NewTestIOStreams() cmd := NewCmdApply("kubectl", tf, ioStreams) cmd.Flags().Set("filename", filenameRC) cmd.Flags().Set("prune", "true") cmd.Flags().Set("namespace", "test") cmd.Flags().Set("output", "yaml") cmd.Flags().Set("all", "true") cmd.Run(cmd, []string{}) if !strings.Contains(buf.String(), "test-rc") { t.Fatalf("unexpected output: %snexpected to contain: %s", buf.String(), "test-rc") } if errBuf.String() != "" { t.Fatalf("unexpected error output: %s", errBuf.String()) } }) } } </ins> func TestApplyObjectOutput(t *testing.T) { cmdtesting.InitTestErrorHandler(t) nameRC, currentRC := readAndAnnotateReplicationController(t, filenameRC)
return &svcPort, nil } } <del> return nil, errors.NewServiceUnavailable(fmt.Sprintf("no service port %q found for service %q", port, svc.Name)) </del> <ins> return nil, errors.NewServiceUnavailable(fmt.Sprintf("no service port %d found for service %q", port, svc.Name)) </ins> } // ResourceLocation returns a URL to which one can send traffic for the specified service.
reflect.DeepEqual(s.EnableTCPReset, t.EnableTCPReset) && reflect.DeepEqual(s.DisableOutboundSnat, t.DisableOutboundSnat) <del> if wantLB { </del> <ins> if wantLB && s.IdleTimeoutInMinutes != nil && t.IdleTimeoutInMinutes != nil { </ins> return properties && reflect.DeepEqual(s.IdleTimeoutInMinutes, t.IdleTimeoutInMinutes) } return properties
expected: false, }, { <ins> msg: "rule names match while idletimeout unmatch should return false", existingRule: []network.LoadBalancingRule{ { Name: to.StringPtr("httpRule"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ IdleTimeoutInMinutes: to.Int32Ptr(1), }, }, }, curRule: network.LoadBalancingRule{ Name: to.StringPtr("httpRule"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ IdleTimeoutInMinutes: to.Int32Ptr(2), }, }, expected: false, }, { msg: "rule names match while idletimeout nil should return true", existingRule: []network.LoadBalancingRule{ { Name:                              to.StringPtr("httpRule"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{}, }, }, curRule: network.LoadBalancingRule{ Name: to.StringPtr("httpRule"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ IdleTimeoutInMinutes: to.Int32Ptr(2), }, }, expected: true, }, { </ins> msg: "rule names match while LoadDistribution unmatch should return false", existingRule: []network.LoadBalancingRule{ {
# Translate a published version <bucket>/<version> (e.g. "release/stable") to version number. set_binary_version "${release}" if [[ -z "${KUBERNETES_SKIP_RELEASE_VALIDATION-}" ]]; then <del> if [[ ${KUBE_VERSION} =~ ${KUBE_CI_VERSION_REGEX} ]]; then </del> <ins> if [[ ${KUBE_VERSION} =~ ${KUBE_RELEASE_VERSION_REGEX} ]]; then # Use KUBERNETES_RELEASE_URL for Releases and Pre-Releases # ie. 1.18.0 or 1.19.0-beta.0 KUBERNETES_RELEASE_URL="${KUBERNETES_RELEASE_URL}" elif [[ ${KUBE_VERSION} =~ ${KUBE_CI_VERSION_REGEX} ]]; then </ins> # Override KUBERNETES_RELEASE_URL to point to the CI bucket; # this will be used by get-kube-binaries.sh. <ins> # ie. v1.19.0-beta.0.318+b618411f1edb98 </ins> KUBERNETES_RELEASE_URL="${KUBERNETES_CI_RELEASE_URL}" <del> elif ! [[ ${KUBE_VERSION} =~ ${KUBE_RELEASE_VERSION_REGEX} ]]; then </del> <ins> else </ins> echo "Version doesn't match regexp" >&2 exit 1 fi
# See the License for the specific language governing permissions and # limitations under the License. <ins> # This script generates `/pkg/kubelet/apis/podresources/v1alpha1/api.pb.go` # from the protobuf file `/pkg/kubelet/apis/podresources/v1alpha1/api.proto` # for pods. # Usage: `hack/update-generated-pod-resources.sh`. </ins> set -o errexit set -o nounset set -o pipefail
# See the License for the specific language governing permissions and # limitations under the License. <ins> # This script genertates `*/api.pb.go` from the protobuf file `*/api.proto`. # Usage: #     hack/update-generated-protobuf-dockerized.sh "${APIROOTS}" #     An example APIROOT is: "k8s.io/api/admissionregistration/v1" </ins> set -o errexit set -o nounset set -o pipefail
func VerifyExecInPodSucceed(f *framework.Framework, pod *v1.Pod, shExec string) { _, err := PodExec(f, pod, shExec) if err != nil { <del> if err, ok := err.(uexec.CodeExitError); ok { exitCode := err.ExitStatus() </del> <ins> if exiterr, ok := err.(uexec.CodeExitError); ok { exitCode := exiterr.ExitStatus() </ins> framework.ExpectNoError(err, "%q should succeed, but failed with exit code %d and error message %q", <del> shExec, exitCode, err) </del> <ins> shExec, exitCode, exiterr) </ins> } else { framework.ExpectNoError(err, "%q should succeed, but failed with error message %q",
func VerifyExecInPodFail(f *framework.Framework, pod *v1.Pod, shExec string, exitCode int) { _, err := PodExec(f, pod, shExec) if err != nil { <del> if err, ok := err.(clientexec.ExitError); ok { actualExitCode := err.ExitStatus() </del> <ins> if exiterr, ok := err.(clientexec.ExitError); ok { actualExitCode := exiterr.ExitStatus() </ins> framework.ExpectEqual(actualExitCode, exitCode, "%q should fail with exit code %d, but failed with exit code %d and error message %q", <del> shExec, exitCode, actualExitCode, err) </del> <ins> shExec, exitCode, actualExitCode, exiterr) </ins> } else { framework.ExpectNoError(err, "%q should fail with exit code %d, but failed with error message %q",
<ins> /* Copyright 2020 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. */ package scheduler import ( "testing" "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" utilfeature "k8s.io/apiserver/pkg/util/feature" featuregatetesting "k8s.io/component-base/featuregate/testing" "k8s.io/kubernetes/pkg/features" ) func TestNodeResourceLimits(t *testing.T) { defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.ResourceLimitsPriorityFunction, true)() context := initTest(t, "node-resource-limits") defer cleanupTest(t, context) // Add one node expectedNode, err := createNode(context.clientSet, "test-node1", &v1.ResourceList{ v1.ResourcePods:   *resource.NewQuantity(32, resource.DecimalSI), v1.ResourceCPU:    *resource.NewMilliQuantity(2000, resource.DecimalSI), v1.ResourceMemory: *resource.NewQuantity(2000, resource.DecimalSI), }) if err != nil { t.Fatalf("Cannot create node: %v", err) } // Add another node with less resource _, err = createNode(context.clientSet, "test-node2", &v1.ResourceList{ v1.ResourcePods:   *resource.NewQuantity(32, resource.DecimalSI), v1.ResourceCPU:    *resource.NewMilliQuantity(1000, resource.DecimalSI), v1.ResourceMemory: *resource.NewQuantity(1000, resource.DecimalSI), }) if err != nil { t.Fatalf("Cannot create node: %v", err) } podName := "pod-with-resource-limits" pod, err := runPausePod(context.clientSet, initPausePod(context.clientSet, &pausePodConfig{ Name:      podName, Namespace: context.ns.Name, Resources: &v1.ResourceRequirements{Requests: v1.ResourceList{ v1.ResourceCPU:    *resource.NewMilliQuantity(500, resource.DecimalSI), v1.ResourceMemory: *resource.NewQuantity(500, resource.DecimalSI)}, }, })) if err != nil { t.Fatalf("Error running pause pod: %v", err) } if pod.Spec.NodeName != expectedNode.Name { t.Errorf("pod %v got scheduled on an unexpected node: %v. Expected node: %v.", podName, pod.Spec.NodeName, expectedNode.Name) } else { t.Logf("pod %v got successfully scheduled on node %v.", podName, pod.Spec.NodeName) } } </ins>