jiebi/CodeConvo huggingface dataset:
gcePDDetachPollTime = 10 * time.Second nodeStatusTimeout   = 10 * time.Minute nodeStatusPollTime  = 1 * time.Second <ins> podEvictTimeout     = 2 * time.Minute </ins> maxReadRetry        = 3 minNodes            = 2 ) var _ = SIGDescribe("Pod Disks", func() { var ( <ins> ns         string cs         clientset.Interface </ins> podClient  v1core.PodInterface nodeClient v1core.NodeInterface host0Name  types.NodeName
BeforeEach(func() { framework.SkipUnlessNodeCountIsAtLeast(minNodes) <ins> cs = f.ClientSet ns = f.Namespace.Name </ins> <del> podClient = f.ClientSet.Core().Pods(f.Namespace.Name) nodeClient = f.ClientSet.Core().Nodes() nodes = framework.GetReadySchedulableNodesOrDie(f.ClientSet) </del> <ins> podClient = cs.Core().Pods(ns) nodeClient = cs.Core().Nodes() nodes = framework.GetReadySchedulableNodesOrDie(cs) </ins> Expect(len(nodes.Items)).To(BeNumerically(">=", minNodes), fmt.Sprintf("Requires at least %d nodes", minNodes)) host0Name = types.NodeName(nodes.Items[0].ObjectMeta.Name) host1Name = types.NodeName(nodes.Items[1].ObjectMeta.Name)
} }) <del> Context("detach from a disrupted node [Slow] [Disruptive]", func() { </del> <ins> Context("detach in a disrupted environment [Slow] [Disruptive]", func() { </ins> const ( deleteNode    = 1 // delete physical node deleteNodeObj = 2 // delete node's api object only <ins> evictPod      = 3 // evict host0Pod on node0 </ins> ) type testT struct { <del> descr  string // It description nodeOp int    // disruptive operation performed on target node </del> <ins> descr     string // It description disruptOp int    // disruptive operation performed on target node </ins> } tests := []testT{ { <del> descr:  "node is deleted", nodeOp: deleteNode, </del> <ins> descr:     "node is deleted", disruptOp: deleteNode, </ins> }, { <del> descr:  "node's API object is deleted", nodeOp: deleteNodeObj, </del> <ins> descr:     "node's API object is deleted", disruptOp: deleteNodeObj, }, { descr:     "pod is evicted", disruptOp: evictPod, </ins> }, } for _, t := range tests { <del> nodeOp := t.nodeOp </del> <ins> disruptOp := t.disruptOp </ins> It(fmt.Sprintf("when %s", t.descr), func() { framework.SkipUnlessProviderIs("gce") origNodeCnt := len(nodes.Items) // healhy nodes running kublet
diskName, err := framework.CreatePDWithRetry() framework.ExpectNoError(err, "Error creating a pd") <del> targetNode := &nodes.Items[0] </del> <ins> targetNode := &nodes.Items[0] // for node delete ops </ins> host0Pod := testPDPod([]string{diskName}, host0Name, false, 1) containerName := "mycontainer" defer func() { By("defer: cleaning up PD-RW test env") framework.Logf("defer cleanup errors can usually be ignored") <del> if nodeOp == deleteNode { podClient.Delete(host0Pod.Name, metav1.NewDeleteOptions(0)) } </del> <ins> By("defer: delete host0Pod") podClient.Delete(host0Pod.Name, metav1.NewDeleteOptions(0)) By("defer: detach and delete PDs") </ins> detachAndDeletePDs(diskName, []types.NodeName{host0Name}) <del> if nodeOp == deleteNodeObj { targetNode.ObjectMeta.SetResourceVersion("0") // need to set the resource version or else the Create() fails _, err := nodeClient.Create(targetNode) framework.ExpectNoError(err, "defer: Unable to re-create the deleted node") </del> <ins> if disruptOp == deleteNode || disruptOp == deleteNodeObj { if disruptOp == deleteNodeObj { targetNode.ObjectMeta.SetResourceVersion("0") // need to set the resource version or else the Create() fails By("defer: re-create host0 node object") _, err := nodeClient.Create(targetNode) framework.ExpectNoError(err, fmt.Sprintf("defer: Unable to re-create the deleted node object %q", targetNode.Name)) } By("defer: verify the number of ready nodes") numNodes := countReadyNodes(cs, host0Name) // if this defer is reached due to an Expect then nested // Expects are lost, so use Failf here if numNodes != origNodeCnt { framework.Failf("defer: Requires current node count (%d) to return to original node count (%d)", numNodes, origNodeCnt) } </ins> } <del> numNodes := countReadyNodes(f.ClientSet, host0Name) Expect(numNodes).To(Equal(origNodeCnt), fmt.Sprintf("defer: Requires current node count (%d) to return to original node count (%d)", numNodes, origNodeCnt)) </del> }() By("creating host0Pod on node0") _, err = podClient.Create(host0Pod) framework.ExpectNoError(err, fmt.Sprintf("Failed to create host0Pod: %v", err)) <ins> By("waiting for host0Pod to be running") </ins> framework.ExpectNoError(f.WaitForPodRunningSlow(host0Pod.Name)) By("writing content to host0Pod")
By("verifying PD is present in node0's VolumeInUse list") framework.ExpectNoError(waitForPDInVolumesInUse(nodeClient, diskName, host0Name, nodeStatusTimeout, true /* should exist*/)) <del> if nodeOp == deleteNode { </del> <ins> if disruptOp == deleteNode { </ins> By("getting gce instances") gceCloud, err := framework.GetGCECloud() framework.ExpectNoError(err, fmt.Sprintf("Unable to create gcloud client err=%v", err))
By("deleting host0") resp, err := gceCloud.DeleteInstance(framework.TestContext.CloudConfig.ProjectID, framework.TestContext.CloudConfig.Zone, string(host0Name)) framework.ExpectNoError(err, fmt.Sprintf("Failed to delete host0Pod: err=%v response=%#v", err, resp)) <del> By("expecting host0 node to be recreated") numNodes := countReadyNodes(f.ClientSet, host0Name) </del> <ins> By("expecting host0 node to be re-created") numNodes := countReadyNodes(cs, host0Name) </ins> Expect(numNodes).To(Equal(origNodeCnt), fmt.Sprintf("Requires current node count (%d) to return to original node count (%d)", numNodes, origNodeCnt)) output, err = gceCloud.ListInstanceNames(framework.TestContext.CloudConfig.ProjectID, framework.TestContext.CloudConfig.Zone) framework.ExpectNoError(err, fmt.Sprintf("Unable to get list of node instances err=%v output=%s", err, output)) Expect(false, strings.Contains(string(output), string(host0Name))) <del> } else if nodeOp == deleteNodeObj { </del> <ins> } else if disruptOp == deleteNodeObj { </ins> By("deleting host0's node api object") framework.ExpectNoError(nodeClient.Delete(string(host0Name), metav1.NewDeleteOptions(0)), "Unable to delete host0's node object") By("deleting host0Pod") framework.ExpectNoError(podClient.Delete(host0Pod.Name, metav1.NewDeleteOptions(0)), "Unable to delete host0Pod") <ins> } else if disruptOp == evictPod { evictTarget := &policy.Eviction{ ObjectMeta: metav1.ObjectMeta{ Name:      host0Pod.Name, Namespace: ns, }, } By("evicting host0Pod") err = wait.PollImmediate(framework.Poll, podEvictTimeout, func() (bool, error) { err = cs.CoreV1().Pods(ns).Evict(evictTarget) if err != nil { return false, nil } else { return true, nil } }) Expect(err).NotTo(HaveOccurred(), fmt.Sprintf("failed to evict host0Pod after %v", podEvictTimeout)) </ins> } By("waiting for pd to detach from host0")
ARCH?=amd64 HYPERKUBE_BIN?=_output/dockerized/bin/linux/$(ARCH)/hyperkube <del> BASEIMAGE=gcr.io/google-containers/debian-hyperkube-base-$(ARCH):0.2 </del> <ins> BASEIMAGE=gcr.io/google-containers/debian-hyperkube-base-$(ARCH):0.3 </ins> TEMP_DIR:=$(shell mktemp -d -t hyperkubeXXXXXX) all: build
} if len(o.Output) > 0 { <del> return o.PrintObject(o.Cmd, o.Local, o.Mapper, obj, o.Out) </del> <ins> if err := o.PrintObject(o.Cmd, o.Local, o.Mapper, obj, o.Out); err != nil { return err } continue </ins> } cmdutil.PrintSuccess(o.Mapper, o.ShortOutput, o.Out, info.Mapping.Resource, info.Name, false, "env updated")
t.Errorf("did not set env: %s", buf.String()) } } <ins> func TestSetMultiResourcesEnvLocal(t *testing.T) { f, tf, codec, ns := cmdtesting.NewAPIFactory() tf.Client = &fake.RESTClient{ GroupVersion:         legacyscheme.Registry.GroupOrDie(api.GroupName).GroupVersion, NegotiatedSerializer: ns, Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { t.Fatalf("unexpected request: %s %#vn%#v", req.Method, req.URL, req) return nil, nil }), } tf.Namespace = "test" tf.ClientConfig = &restclient.Config{ContentConfig: restclient.ContentConfig{GroupVersion: &legacyscheme.Registry.GroupOrDie(api.GroupName).GroupVersion}} buf := bytes.NewBuffer([]byte{}) cmd := NewCmdEnv(f, os.Stdin, buf, buf) cmd.SetOutput(buf) cmd.Flags().Set("output", "name") cmd.Flags().Set("local", "true") mapper, typer := f.Object() tf.Printer = &printers.NamePrinter{Decoders: []runtime.Decoder{codec}, Typer: typer, Mapper: mapper} opts := EnvOptions{FilenameOptions: resource.FilenameOptions{ Filenames: []string{"../../../../test/fixtures/pkg/kubectl/cmd/set/multi-resource-yaml.yaml"}}, Out:   buf, Local: true} err := opts.Complete(f, cmd, []string{"env=prod"}) if err == nil { err = opts.RunEnv(f) } if err != nil { t.Fatalf("unexpected error: %v", err) } expectedOut := "replicationcontrollers/first-rcnreplicationcontrollers/second-rcn" if buf.String() != expectedOut { t.Errorf("expected out:n%snbut got:n%s", expectedOut, buf.String()) } } </ins>
} } } <ins> func TestSetMultiResourcesImageLocal(t *testing.T) { f, tf, codec, ns := cmdtesting.NewAPIFactory() tf.Client = &fake.RESTClient{ GroupVersion:         legacyscheme.Registry.GroupOrDie(api.GroupName).GroupVersion, NegotiatedSerializer: ns, Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { t.Fatalf("unexpected request: %s %#vn%#v", req.Method, req.URL, req) return nil, nil }), } tf.Namespace = "test" tf.ClientConfig = &restclient.Config{ContentConfig: restclient.ContentConfig{GroupVersion: &legacyscheme.Registry.GroupOrDie(api.GroupName).GroupVersion}} buf := bytes.NewBuffer([]byte{}) cmd := NewCmdImage(f, buf, buf) cmd.SetOutput(buf) cmd.Flags().Set("output", "name") cmd.Flags().Set("local", "true") mapper, typer := f.Object() tf.Printer = &printers.NamePrinter{Decoders: []runtime.Decoder{codec}, Typer: typer, Mapper: mapper} opts := ImageOptions{FilenameOptions: resource.FilenameOptions{ Filenames: []string{"../../../../test/fixtures/pkg/kubectl/cmd/set/multi-resource-yaml.yaml"}}, Out:   buf, Local: true} err := opts.Complete(f, cmd, []string{"*=thingy"}) if err == nil { err = opts.Validate() } if err == nil { err = opts.Run() } if err != nil { t.Fatalf("unexpected error: %v", err) } expectedOut := "replicationcontrollers/first-rcnreplicationcontrollers/second-rcn" if buf.String() != expectedOut { t.Errorf("expected out:n%snbut got:n%s", expectedOut, buf.String()) } } </ins>
} if o.Local || cmdutil.GetDryRunFlag(o.Cmd) { <del> return o.PrintObject(o.Cmd, o.Local, o.Mapper, info.Object, o.Out) </del> <ins> if err := o.PrintObject(o.Cmd, o.Local, o.Mapper, info.Object, o.Out); err != nil { return err } continue </ins> } obj, err := resource.NewHelper(info.Client, info.Mapping).Patch(info.Namespace, info.Name, types.StrategicMergePatchType, patch.Patch)
t.Errorf("did not set resources: %s", buf.String()) } } <ins> func TestSetMultiResourcesLimitsLocal(t *testing.T) { f, tf, codec, ns := cmdtesting.NewAPIFactory() tf.Client = &fake.RESTClient{ GroupVersion:         legacyscheme.Registry.GroupOrDie(api.GroupName).GroupVersion, NegotiatedSerializer: ns, Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { t.Fatalf("unexpected request: %s %#vn%#v", req.Method, req.URL, req) return nil, nil }), } tf.Namespace = "test" tf.ClientConfig = &restclient.Config{ContentConfig: restclient.ContentConfig{GroupVersion: &legacyscheme.Registry.GroupOrDie(api.GroupName).GroupVersion}} buf := bytes.NewBuffer([]byte{}) cmd := NewCmdResources(f, buf, buf) cmd.SetOutput(buf) cmd.Flags().Set("output", "name") cmd.Flags().Set("local", "true") mapper, typer := f.Object() tf.Printer = &printers.NamePrinter{Decoders: []runtime.Decoder{codec}, Typer: typer, Mapper: mapper} opts := ResourcesOptions{FilenameOptions: resource.FilenameOptions{ Filenames: []string{"../../../../test/fixtures/pkg/kubectl/cmd/set/multi-resource-yaml.yaml"}}, Out:               buf, Local:             true, Limits:            "cpu=200m,memory=512Mi", Requests:          "cpu=200m,memory=512Mi", ContainerSelector: "*"} err := opts.Complete(f, cmd, []string{}) if err == nil { err = opts.Validate() } if err == nil { err = opts.Run() } if err != nil { t.Fatalf("unexpected error: %v", err) } expectedOut := "replicationcontrollers/first-rcnreplicationcontrollers/second-rcn" if buf.String() != expectedOut { t.Errorf("expected out:n%snbut got:n%s", expectedOut, buf.String()) } } </ins>
} if o.Local || o.DryRun { <del> return o.PrintObject(o.Mapper, info.Object, o.Out) </del> <ins> if err := o.PrintObject(o.Mapper, info.Object, o.Out); err != nil { return err } continue </ins> } obj, err := resource.NewHelper(info.Client, info.Mapping).Patch(info.Namespace, info.Name, types.StrategicMergePatchType, patch.Patch)
<ins> apiVersion: v1 kind: ReplicationController metadata: name: first-rc spec: replicas: 1 selector: app: mock template: metadata: labels: app: mock spec: containers: - name: mock-container image: gcr.io/google-containers/pause:2.0 --- apiVersion: v1 kind: ReplicationController metadata: name: second-rc spec: replicas: 1 selector: app: mock template: metadata: labels: app: mock spec: containers: - name: mock-container image: gcr.io/google-containers/pause:2.0 </ins>  No newline at end of file
name = "all-srcs", srcs = [ ":package-srcs", <ins> "//staging/src/k8s.io/apiserver/plugin/pkg/audit/buffered:all-srcs", </ins> "//staging/src/k8s.io/apiserver/plugin/pkg/audit/log:all-srcs", "//staging/src/k8s.io/apiserver/plugin/pkg/audit/webhook:all-srcs", ],
<ins> load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") go_library( name = "go_default_library", srcs = [ "buffered.go", "doc.go", ], importpath = "k8s.io/apiserver/plugin/pkg/audit/buffered", visibility = ["//visibility:public"], deps = [ "//vendor/k8s.io/apimachinery/pkg/util/runtime:go_default_library", "//vendor/k8s.io/apimachinery/pkg/util/wait:go_default_library", "//vendor/k8s.io/apiserver/pkg/apis/audit:go_default_library", "//vendor/k8s.io/apiserver/pkg/audit:go_default_library", "//vendor/k8s.io/client-go/util/flowcontrol:go_default_library", ], ) go_test( name = "go_default_test", srcs = ["buffered_test.go"], embed = [":go_default_library"], deps = [ "//vendor/github.com/stretchr/testify/require:go_default_library", "//vendor/k8s.io/apimachinery/pkg/util/wait:go_default_library", "//vendor/k8s.io/apiserver/pkg/apis/audit:go_default_library", "//vendor/k8s.io/apiserver/pkg/audit:go_default_library", ], ) filegroup( name = "package-srcs", srcs = glob(["**"]), tags = ["automanaged"], visibility = ["//visibility:private"], ) filegroup( name = "all-srcs", srcs = [":package-srcs"], tags = ["automanaged"], visibility = ["//visibility:public"], ) </ins>
<ins> /* Copyright 2018 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 buffered provides an implementation for the audit.Backend interface // that batches incoming audit events and sends batches to the delegate audit.Backend. package buffered // import "k8s.io/apiserver/plugin/pkg/audit/buffered" </ins>
// ServiceAnnotationLoadBalancerInternal is the annotation used on the service // to indicate that we want an internal loadbalancer service. <del> // If the value of ServiceAnnotationLoadBalancerInternal is false, it indicates that we want an external loadbalancer service. Default to true. </del> <ins> // If the value of ServiceAnnotationLoadBalancerInternal is false, it indicates that we want an external loadbalancer service. Default to false. </ins> ServiceAnnotationLoadBalancerInternal = "service.beta.kubernetes.io/openstack-internal-load-balancer" )
glog.V(4).Infof("EnsureLoadBalancer using floatingPool: %v", floatingPool) var internalAnnotation bool <del> internal := getStringFromServiceAnnotation(apiService, ServiceAnnotationLoadBalancerInternal, "true") </del> <ins> internal := getStringFromServiceAnnotation(apiService, ServiceAnnotationLoadBalancerInternal, "false") </ins> switch internal { case "true": glog.V(4).Infof("Ensure an internal loadbalancer service.")
glog.V(4).Infof("Ensure an external loadbalancer service.") internalAnnotation = false } else { <del> return nil, fmt.Errorf("floating-network-id or loadbalancer.openstack.org/floating-network-id should be specified when service.beta.kubernetes.io/openstack-internal-load-balancer is false") </del> <ins> return nil, fmt.Errorf("floating-network-id or loadbalancer.openstack.org/floating-network-id should be specified when ensuring an external loadbalancer service.") </ins> } default: return nil, fmt.Errorf("unknow service.beta.kubernetes.io/openstack-internal-load-balancer annotation: %v, specify "true" or "false".",
pod, err = c.CoreV1().Pods(ns).Get(pod.Name, metav1.GetOptions{}) Expect(err).NotTo(HaveOccurred()) <del> // Wait for `VolumeStatsAggPeriod' to grab metrics time.Sleep(1 * time.Minute) // Grab kubelet metrics from the node the pod was scheduled on kubeMetrics, err := metricsGrabber.GrabFromKubelet(pod.Spec.NodeName) Expect(err).NotTo(HaveOccurred(), "Error getting kubelet metrics : %v", err) framework.Logf("Deleting pod %q/%q", pod.Namespace, pod.Name) framework.ExpectNoError(framework.DeletePodWithWait(f, c, pod)) </del> // Verify volume stat metrics were collected for the referenced PVC volumeStatKeys := []string{ kubeletmetrics.VolumeStatsUsedBytesKey,
kubeletmetrics.VolumeStatsInodesFreeKey, kubeletmetrics.VolumeStatsInodesUsedKey, } <ins> // Poll kubelet metrics waiting for the volume to be picked up // by the volume stats collector var kubeMetrics metrics.KubeletMetrics waitErr := wait.Poll(30*time.Second, 5*time.Minute, func() (bool, error) { framework.Logf("Grabbing Kubelet metrics") // Grab kubelet metrics from the node the pod was scheduled on var err error kubeMetrics, err = metricsGrabber.GrabFromKubelet(pod.Spec.NodeName) if err != nil { framework.Logf("Error fetching kubelet metrics") return false, err } key := volumeStatKeys[0] kubeletKeyName := fmt.Sprintf("%s_%s", kubeletmetrics.KubeletSubsystem, key) if !findVolumeStatMetric(kubeletKeyName, pvc.Namespace, pvc.Name, kubeMetrics) { return false, nil } return true, nil }) Expect(waitErr).NotTo(HaveOccurred(), "Error finding volume metrics : %v", waitErr) </ins> for _, key := range volumeStatKeys { kubeletKeyName := fmt.Sprintf("%s_%s", kubeletmetrics.KubeletSubsystem, key) <del> verifyVolumeStatMetric(kubeletKeyName, pvc.Namespace, pvc.Name, kubeMetrics) </del> <ins> found := findVolumeStatMetric(kubeletKeyName, pvc.Namespace, pvc.Name, kubeMetrics) Expect(found).To(BeTrue(), "PVC %s, Namespace %s not found for %s", pvc.Name, pvc.Namespace, kubeletKeyName) </ins> } <ins> framework.Logf("Deleting pod %q/%q", pod.Namespace, pod.Name) framework.ExpectNoError(framework.DeletePodWithWait(f, c, pod)) </ins> }) })
return result } <del> // Verifies the specified metrics are in `kubeletMetrics` func verifyVolumeStatMetric(metricKeyName string, namespace string, pvcName string, kubeletMetrics metrics.KubeletMetrics) { </del> <ins> // Finds the sample in the specified metric from `KubeletMetrics` tagged with // the specified namespace and pvc name func findVolumeStatMetric(metricKeyName string, namespace string, pvcName string, kubeletMetrics metrics.KubeletMetrics) bool { </ins> found := false errCount := 0 <ins> framework.Logf("Looking for sample in metric `%s` tagged with namespace `%s`, PVC `%s`", metricKeyName, namespace, pvcName) </ins> if samples, ok := kubeletMetrics[metricKeyName]; ok { for _, sample := range samples { <ins> framework.Logf("Found sample %s", sample.String()) </ins> samplePVC, ok := sample.Metric["persistentvolumeclaim"] if !ok { framework.Logf("Error getting pvc for metric %s, sample %s", metricKeyName, sample.String())
PortOpenCheck{port: 10252}, HTTPProxyCheck{Proto: "https", Host: cfg.API.AdvertiseAddress, Port: int(cfg.API.BindPort)}, DirAvailableCheck{Path: filepath.Join(kubeadmconstants.KubernetesDir, kubeadmconstants.ManifestsSubDirName)}, <del> DirAvailableCheck{Path: "/var/lib/kubelet"}, </del> FileContentCheck{Path: bridgenf, Content: []byte{'1'}}, SwapCheck{}, InPathCheck{executable: "ip", mandatory: true},
ServiceCheck{Service: "docker", CheckIfActive: true}, PortOpenCheck{port: 10250}, DirAvailableCheck{Path: filepath.Join(kubeadmconstants.KubernetesDir, kubeadmconstants.ManifestsSubDirName)}, <del> DirAvailableCheck{Path: "/var/lib/kubelet"}, </del> FileAvailableCheck{Path: cfg.CACertPath}, FileAvailableCheck{Path: filepath.Join(kubeadmconstants.KubernetesDir, kubeadmconstants.KubeletKubeConfigFileName)}, FileContentCheck{Path: bridgenf, Content: []byte{'1'}},
RequireKubeConfig:       false, KubeConfig:              flag.NewStringFlag("/var/lib/kubelet/kubeconfig"), ContainerRuntimeOptions: *NewContainerRuntimeOptions(), <del> CertDirectory:           "/var/run/kubernetes", </del> <ins> CertDirectory:           "/var/lib/kubelet/pki", </ins> RootDirectory:           v1alpha1.DefaultRootDir, // DEPRECATED: auto detecting cloud providers goes against the initiative // for out-of-tree cloud providers as we'll now depend on cAdvisor integrations
"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured:go_default_library", "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", <ins> "//vendor/k8s.io/apimachinery/pkg/types:go_default_library", </ins> "//vendor/k8s.io/apimachinery/pkg/util/wait:go_default_library", "//vendor/k8s.io/apimachinery/pkg/watch:go_default_library", "//vendor/k8s.io/apiserver/pkg/util/feature:go_default_library",
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" <ins> "k8s.io/apimachinery/pkg/types" </ins> "k8s.io/apimachinery/pkg/util/wait" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/dynamic"
} } <ins> func TestPatch(t *testing.T) { stopCh, apiExtensionClient, clientPool, err := testserver.StartDefaultServer() if err != nil { t.Fatal(err) } defer close(stopCh) noxuDefinition := testserver.NewNoxuCustomResourceDefinition(apiextensionsv1beta1.ClusterScoped) noxuVersionClient, err := testserver.CreateNewCustomResourceDefinition(noxuDefinition, apiExtensionClient, clientPool) if err != nil { t.Fatal(err) } ns := "not-the-default" noxuNamespacedResourceClient := noxuVersionClient.Resource(&metav1.APIResource{ Name:       noxuDefinition.Spec.Names.Plural, Namespaced: true, }, ns) noxuInstanceToCreate := testserver.NewNoxuInstance(ns, "foo") createdNoxuInstance, err := noxuNamespacedResourceClient.Create(noxuInstanceToCreate) if err != nil { t.Fatal(err) } patch := []byte(`{"num": {"num2":999}}`) createdNoxuInstance, err = noxuNamespacedResourceClient.Patch("foo", types.MergePatchType, patch) if err != nil { t.Fatalf("unexpected error: %v", err) } // a patch with no change createdNoxuInstance, err = noxuNamespacedResourceClient.Patch("foo", types.MergePatchType, patch) if err != nil { t.Fatalf("unexpected error: %v", err) } // an empty patch createdNoxuInstance, err = noxuNamespacedResourceClient.Patch("foo", types.MergePatchType, []byte(`{}`)) if err != nil { t.Fatalf("unexpected error: %v", err) } originalJSON, err := runtime.Encode(unstructured.UnstructuredJSONScheme, createdNoxuInstance) if err != nil { t.Fatalf("unexpected error: %v", err) } gottenNoxuInstance, err := runtime.Decode(unstructured.UnstructuredJSONScheme, originalJSON) if err != nil { t.Fatalf("unexpected error: %v", err) } // Check if int is preserved. unstructuredObj := gottenNoxuInstance.(*unstructured.Unstructured).Object num := unstructuredObj["num"].(map[string]interface{}) num1 := num["num1"].(int64) num2 := num["num2"].(int64) if num1 != 9223372036854775807 || num2 != 999 { t.Errorf("Expected %v, got %v, %v", `9223372036854775807, 999`, num1, num2) } } </ins> func TestCrossNamespaceListWatch(t *testing.T) { stopCh, apiExtensionClient, clientPool, err := testserver.StartDefaultServer() if err != nil {