How to use PatchJSON method of config Package

Best Syzkaller code snippet using config.PatchJSON

webhook_test.go

Source:webhook_test.go Github

copy

Full Screen

1package injector2import (3 "encoding/json"4 "fmt"5 "path/filepath"6 "reflect"7 "testing"8 "github.com/linkerd/linkerd2/controller/proxy-injector/fake"9 "github.com/linkerd/linkerd2/pkg/charts/linkerd2"10 "github.com/linkerd/linkerd2/pkg/inject"11 pkgK8s "github.com/linkerd/linkerd2/pkg/k8s"12 admissionv1beta1 "k8s.io/api/admission/v1beta1"13 corev1 "k8s.io/api/core/v1"14 v1 "k8s.io/api/core/v1"15 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"16 "k8s.io/apimachinery/pkg/runtime"17)18type unmarshalledPatch []map[string]interface{}19var (20 values, _ = linkerd2.NewValues()21)22func confNsEnabled() *inject.ResourceConfig {23 return inject.24 NewResourceConfig(values, inject.OriginWebhook).25 WithNsAnnotations(map[string]string{pkgK8s.ProxyInjectAnnotation: pkgK8s.ProxyInjectEnabled})26}27func confNsDisabled() *inject.ResourceConfig {28 return inject.NewResourceConfig(values, inject.OriginWebhook).WithNsAnnotations(map[string]string{})29}30func confNsWithOpaquePorts() *inject.ResourceConfig {31 return inject.32 NewResourceConfig(values, inject.OriginWebhook).33 WithNsAnnotations(map[string]string{34 pkgK8s.ProxyInjectAnnotation: pkgK8s.ProxyInjectEnabled,35 pkgK8s.ProxyOpaquePortsAnnotation: "3306",36 })37}38func confNsWithoutOpaquePorts() *inject.ResourceConfig {39 return inject.40 NewResourceConfig(values, inject.OriginWebhook).41 WithNsAnnotations(map[string]string{pkgK8s.ProxyInjectAnnotation: pkgK8s.ProxyInjectEnabled})42}43func confNsWithConfigAnnotations() *inject.ResourceConfig {44 return inject.45 NewResourceConfig(values, inject.OriginWebhook).46 WithNsAnnotations(map[string]string{47 pkgK8s.ProxyInjectAnnotation: pkgK8s.ProxyInjectEnabled,48 pkgK8s.ProxyIgnoreOutboundPortsAnnotation: "34567",49 pkgK8s.ProxyWaitBeforeExitSecondsAnnotation: "300",50 "config.linkerd.io/invalid-key": "invalid-value",51 })52}53func TestGetPodPatch(t *testing.T) {54 values.Proxy.DisableIdentity = true55 factory := fake.NewFactory(filepath.Join("fake", "data"))56 nsEnabled, err := factory.Namespace("namespace-inject-enabled.yaml")57 if err != nil {58 t.Fatalf("Unexpected error: %s", err)59 }60 nsDisabled, err := factory.Namespace("namespace-inject-disabled.yaml")61 if err != nil {62 t.Fatalf("Unexpected error: %s", err)63 }64 t.Run("by checking annotations", func(t *testing.T) {65 var testCases = []struct {66 filename string67 ns *corev1.Namespace68 conf *inject.ResourceConfig69 }{70 {71 filename: "pod-inject-empty.yaml",72 ns: nsEnabled,73 conf: confNsEnabled(),74 },75 {76 filename: "pod-inject-enabled.yaml",77 ns: nsEnabled,78 conf: confNsEnabled(),79 },80 {81 filename: "pod-inject-enabled.yaml",82 ns: nsDisabled,83 conf: confNsDisabled(),84 },85 {86 filename: "pod-with-debug-disabled.yaml",87 ns: nsDisabled,88 conf: confNsDisabled(),89 },90 }91 expectedPatchBytes, err := factory.FileContents("pod.patch.json")92 if err != nil {93 t.Fatalf("Unexpected error: %s", err)94 }95 expectedPatch, err := unmarshalPatch(expectedPatchBytes)96 if err != nil {97 t.Fatalf("Unexpected error: %s", err)98 }99 for id, testCase := range testCases {100 testCase := testCase // pin101 t.Run(fmt.Sprintf("%d", id), func(t *testing.T) {102 pod, err := factory.FileContents(testCase.filename)103 if err != nil {104 t.Fatalf("Unexpected error: %s", err)105 }106 fakeReq := getFakePodReq(pod)107 fullConf := testCase.conf.108 WithKind(fakeReq.Kind.Kind).109 WithOwnerRetriever(ownerRetrieverFake)110 _, err = fullConf.ParseMetaAndYAML(fakeReq.Object.Raw)111 if err != nil {112 t.Fatal(err)113 }114 patchJSON, err := fullConf.GetPodPatch(true)115 if err != nil {116 t.Fatalf("Unexpected PatchForAdmissionRequest error: %s", err)117 }118 actualPatch, err := unmarshalPatch(patchJSON)119 if err != nil {120 t.Fatalf("Unexpected error: %s", err)121 }122 if !reflect.DeepEqual(expectedPatch, actualPatch) {123 t.Fatalf("The actual patch didn't match what was expected.\nExpected: %s\nActual: %s",124 expectedPatchBytes, patchJSON)125 }126 })127 }128 })129 t.Run("by checking annotations with debug", func(t *testing.T) {130 expectedPatchBytes, err := factory.FileContents("pod-with-debug.patch.json")131 if err != nil {132 t.Fatalf("Unexpected error: %s", err)133 }134 expectedPatch, err := unmarshalPatch(expectedPatchBytes)135 if err != nil {136 t.Fatalf("Unexpected error: %s", err)137 }138 pod, err := factory.FileContents("pod-with-debug-enabled.yaml")139 if err != nil {140 t.Fatalf("Unexpected error: %s", err)141 }142 fakeReq := getFakePodReq(pod)143 conf := confNsEnabled().WithKind(fakeReq.Kind.Kind).WithOwnerRetriever(ownerRetrieverFake)144 _, err = conf.ParseMetaAndYAML(fakeReq.Object.Raw)145 if err != nil {146 t.Fatal(err)147 }148 patchJSON, err := conf.GetPodPatch(true)149 if err != nil {150 t.Fatalf("Unexpected PatchForAdmissionRequest error: %s", err)151 }152 actualPatch, err := unmarshalPatch(patchJSON)153 if err != nil {154 t.Fatalf("Unexpected error: %s", err)155 }156 if !reflect.DeepEqual(expectedPatch, actualPatch) {157 t.Fatalf("The actual patch didn't match what was expected.\nExpected: %s\nActual: %s",158 expectedPatchBytes, patchJSON)159 }160 })161 t.Run("by checking pod inherits config annotations from namespace", func(t *testing.T) {162 expectedPatchBytes, err := factory.FileContents("pod-with-ns-annotations.patch.json")163 if err != nil {164 t.Fatalf("Unexpected error: %s", err)165 }166 expectedPatch, err := unmarshalPatch(expectedPatchBytes)167 if err != nil {168 t.Fatalf("Unexpected error: %s", err)169 }170 pod, err := factory.FileContents("pod-inject-enabled.yaml")171 if err != nil {172 t.Fatalf("Unexpected error: %s", err)173 }174 fakeReq := getFakePodReq(pod)175 conf := confNsWithConfigAnnotations().176 WithKind(fakeReq.Kind.Kind).177 WithOwnerRetriever(ownerRetrieverFake)178 _, err = conf.ParseMetaAndYAML(fakeReq.Object.Raw)179 if err != nil {180 t.Fatal(err)181 }182 // The namespace has two config annotations: one valid and one invalid183 // the pod patch should only contain the valid annotation.184 conf.AppendNamespaceAnnotations()185 patchJSON, err := conf.GetPodPatch(true)186 if err != nil {187 t.Fatalf("Unexpected PatchForAdmissionRequest error: %s", err)188 }189 actualPatch, err := unmarshalPatch(patchJSON)190 if err != nil {191 t.Fatalf("Unexpected error: %s", err)192 }193 if !reflect.DeepEqual(expectedPatch, actualPatch) {194 t.Fatalf("The actual patch didn't match what was expected.\nExpected: %s\nActual: %s", expectedPatchBytes, patchJSON)195 }196 })197 t.Run("by checking container spec", func(t *testing.T) {198 deployment, err := factory.FileContents("deployment-with-injected-proxy.yaml")199 if err != nil {200 t.Fatalf("Unexpected error: %s", err)201 }202 fakeReq := getFakePodReq(deployment)203 conf := confNsDisabled().WithKind(fakeReq.Kind.Kind)204 patchJSON, err := conf.GetPodPatch(true)205 if err != nil {206 t.Fatalf("Unexpected PatchForAdmissionRequest error: %s", err)207 }208 if len(patchJSON) == 0 {209 t.Errorf("Expected empty patch")210 }211 })212}213func TestGetAnnotationPatch(t *testing.T) {214 factory := fake.NewFactory(filepath.Join("fake", "data"))215 nsWithOpaquePorts, err := factory.Namespace("namespace-with-opaque-ports.yaml")216 if err != nil {217 t.Fatalf("Unexpected error: %s", err)218 }219 nsWithoutOpaquePorts, err := factory.Namespace("namespace-inject-enabled.yaml")220 if err != nil {221 t.Fatalf("Unexpected error: %s", err)222 }223 t.Run("by checking patch annotations", func(t *testing.T) {224 servicePatchBytes, err := factory.FileContents("annotation.patch.json")225 if err != nil {226 t.Fatalf("Unexpected error: %s", err)227 }228 servicePatch, err := unmarshalPatch(servicePatchBytes)229 if err != nil {230 t.Fatalf("Unexpected error: %s", err)231 }232 podPatchBytes, err := factory.FileContents("annotation.patch.json")233 if err != nil {234 t.Fatalf("Unexpected error: %s", err)235 }236 podPatch, err := unmarshalPatch(podPatchBytes)237 if err != nil {238 t.Fatalf("Unexpected error: %s", err)239 }240 var testCases = []struct {241 name string242 filename string243 ns *corev1.Namespace244 conf *inject.ResourceConfig245 expectedPatchBytes []byte246 expectedPatch unmarshalledPatch247 }{248 {249 name: "service without opaque ports and namespace with",250 filename: "service-without-opaque-ports.yaml",251 ns: nsWithOpaquePorts,252 conf: confNsWithOpaquePorts(),253 expectedPatchBytes: servicePatchBytes,254 expectedPatch: servicePatch,255 },256 {257 name: "service with opaque ports and namespace with",258 filename: "service-with-opaque-ports.yaml",259 ns: nsWithOpaquePorts,260 conf: confNsWithOpaquePorts(),261 },262 {263 name: "service with opaque ports and namespace without",264 filename: "service-with-opaque-ports.yaml",265 ns: nsWithoutOpaquePorts,266 conf: confNsWithoutOpaquePorts(),267 },268 {269 name: "service without opaque ports and namespace without",270 filename: "service-without-opaque-ports.yaml",271 ns: nsWithoutOpaquePorts,272 conf: confNsWithoutOpaquePorts(),273 },274 {275 name: "pod without opaque ports and namespace with",276 filename: "pod-without-opaque-ports.yaml",277 ns: nsWithOpaquePorts,278 conf: confNsWithOpaquePorts(),279 expectedPatchBytes: podPatchBytes,280 expectedPatch: podPatch,281 },282 {283 name: "pod with opaque ports and namespace with",284 filename: "pod-with-opaque-ports.yaml",285 ns: nsWithOpaquePorts,286 conf: confNsWithOpaquePorts(),287 },288 {289 name: "pod with opaque ports and namespace without",290 filename: "pod-with-opaque-ports.yaml",291 ns: nsWithoutOpaquePorts,292 conf: confNsWithoutOpaquePorts(),293 },294 }295 for _, testCase := range testCases {296 testCase := testCase // pin297 t.Run(testCase.name, func(t *testing.T) {298 service, err := factory.FileContents(testCase.filename)299 if err != nil {300 t.Fatalf("Unexpected error: %s", err)301 }302 fakeReq := getFakeServiceReq(service)303 fullConf := testCase.conf.304 WithKind(fakeReq.Kind.Kind).305 WithOwnerRetriever(ownerRetrieverFake)306 _, err = fullConf.ParseMetaAndYAML(fakeReq.Object.Raw)307 if err != nil {308 t.Fatal(err)309 }310 var patchJSON []byte311 opaquePorts, ok := fullConf.GetConfigAnnotation(pkgK8s.ProxyOpaquePortsAnnotation)312 if ok {313 fullConf.AppendPodAnnotation(pkgK8s.ProxyOpaquePortsAnnotation, opaquePorts)314 patchJSON, err = fullConf.CreateAnnotationPatch(opaquePorts)315 if err != nil {316 t.Fatalf("Unexpected PatchForAdmissionRequest error: %s", err)317 }318 }319 if len(testCase.expectedPatchBytes) != 0 && len(patchJSON) == 0 {320 t.Fatalf("There was no patch, but one was expected: %s", testCase.expectedPatchBytes)321 } else if len(testCase.expectedPatchBytes) == 0 && len(patchJSON) != 0 {322 t.Fatalf("No patch was expected, but one was returned: %s", patchJSON)323 }324 if len(testCase.expectedPatchBytes) == 0 {325 return326 }327 actualPatch, err := unmarshalPatch(patchJSON)328 if err != nil {329 t.Fatalf("Unexpected error: %s", err)330 }331 if !reflect.DeepEqual(testCase.expectedPatch, actualPatch) {332 t.Fatalf("The actual patch didn't match what was expected.\nExpected: %s\nActual: %s",333 testCase.expectedPatchBytes, patchJSON)334 }335 })336 }337 })338}339func getFakePodReq(b []byte) *admissionv1beta1.AdmissionRequest {340 return &admissionv1beta1.AdmissionRequest{341 Kind: metav1.GroupVersionKind{Kind: "Pod"},342 Name: "foobar",343 Namespace: "linkerd",344 Object: runtime.RawExtension{Raw: b},345 }346}347func getFakeServiceReq(b []byte) *admissionv1beta1.AdmissionRequest {348 return &admissionv1beta1.AdmissionRequest{349 Kind: metav1.GroupVersionKind{Kind: "Service"},350 Name: "foobar",351 Namespace: "linkerd",352 Object: runtime.RawExtension{Raw: b},353 }354}355func ownerRetrieverFake(p *v1.Pod) (string, string) {356 return pkgK8s.Deployment, "owner-deployment"357}358func unmarshalPatch(patchJSON []byte) (unmarshalledPatch, error) {359 var actualPatch unmarshalledPatch360 err := json.Unmarshal(patchJSON, &actualPatch)361 if err != nil {362 return nil, err363 }364 return actualPatch, nil365}...

Full Screen

Full Screen

webhook_server_test.go

Source:webhook_server_test.go Github

copy

Full Screen

1package pkg2import (3 "encoding/json"4 "fmt"5 "testing"6 jsonpatch "github.com/evanphx/json-patch"7 "gopkg.in/yaml.v3"8)9/*10Load yaml configs11*/12func TestLoadConfig01(t *testing.T) {13 data := `14initContainers:15- name: init-busybox16 image: busybox:1.3017 imagePullPolicy: IfNotPresent18 command: ["sh", "-c", "sleep 3; echo \"init process done.\""]19volumes:20- name: busybox-conf21 configMap:22 name: busybox-configmap23`24 // Note: fields of struct Config should be public.25 var cfg Config26 if err := yaml.Unmarshal([]byte(data), &cfg); err != nil {27 t.Fatal(err)28 }29 fmt.Printf("config: %+v", cfg)30}31func TestLoadConfig02(t *testing.T) {32 data := `33initContainers:34- name: init-busybox35 image: busybox:1.3036 imagePullPolicy: IfNotPresent37 command: ["sh", "-c", "sleep 3; echo \"init process done.\""]38# volumes:39# - name: busybox-conf40# configMap:41# name: busybox-configmap42`43 var cfg Config44 if err := yaml.Unmarshal([]byte(data), &cfg); err != nil {45 t.Fatal(err)46 }47 fmt.Printf("config: %+v", cfg)48}49/*50Json Patch51github: https://github.com/evanphx/json-patch52jsonpatch syntax: https://tools.ietf.org/html/rfc6902#appendix-A.153*/54func TestJsonPatch01(t *testing.T) {55 original := []byte(`{"name": "John", "age": 24, "height": 3.21}`)56 // jsonpatch op: replace and remove57 patchJSON := []byte(`[58 {"op": "replace", "path": "/name", "value": "Jane"},59 {"op": "remove", "path": "/height"}60 ]`)61 patch, err := jsonpatch.DecodePatch(patchJSON)62 if err != nil {63 t.Fatal(err)64 }65 modified, err := patch.Apply(original)66 if err != nil {67 t.Fatal(err)68 }69 fmt.Println("Original document:", string(original))70 fmt.Println("MOdified document:", string(modified))71}72func TestJsonPatch02(t *testing.T) {73 original := []byte(`{"name": "John", "age": 24, "height": 3.21}`)74 // use json patch op struct75 patchReplace := patchOperation{76 Op: "replace",77 Path: "/name",78 Value: "Henry",79 }80 patchRemove := patchOperation{81 Op: "remove",82 Path: "/height",83 }84 patches := []patchOperation{patchReplace, patchRemove}85 patchJSON, err := json.Marshal(patches)86 if err != nil {87 t.Fatal(err)88 }89 patch, err := jsonpatch.DecodePatch(patchJSON)90 if err != nil {91 t.Fatal(err)92 }93 modified, err := patch.Apply(original)94 if err != nil {95 t.Fatal(err)96 }97 fmt.Println("Original document:", string(original))98 fmt.Println("MOdified document:", string(modified))99}100func TestJsonPatch03(t *testing.T) {101 original := []byte(`{"name": "John", "age": 24, "skills": ["Java", "C#"]}`)102 // jsonpatch op: add a item to list103 patchJSON := []byte(`[104 {"op": "replace", "path": "/name", "value": "Henry"},105 {"op": "add", "path": "/skills/-", "value": "Golang"}106 ]`)107 patch, err := jsonpatch.DecodePatch(patchJSON)108 if err != nil {109 t.Fatal(err)110 }111 modified, err := patch.Apply(original)112 if err != nil {113 t.Fatal(err)114 }115 fmt.Println("Original document:", string(original))116 fmt.Println("Modified document:", string(modified))117}...

Full Screen

Full Screen

PatchJSON

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 panic(fmt.Errorf("Fatal error config file: %s \n", err))4 }5 panic(fmt.Errorf("Fatal error config file: %s \n", err))6 }7}

Full Screen

Full Screen

PatchJSON

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 config := &bluemix.Config{4 BluemixAPIKey: os.Getenv("BLUEMIX_API_KEY"),5 }6 sess, err := session.New(config)7 if err != nil {8 fmt.Println("Error occured while creating session")9 }10 cisClient, err := cisv1.New(sess)11 if err != nil {12 fmt.Println("Error occured while creating service")13 }14 zoneID, err := cisClient.Zones().GetZoneIDByName("example.com", "example.com")15 if err != nil {16 fmt.Println("Error occured while getting zone id")17 }18 config, err = cisClient.Config().GetConfig(zoneID)19 if err != nil {20 fmt.Println("Error occured while getting the config")21 }

Full Screen

Full Screen

PatchJSON

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 cfg, err := config.ReadDefault("config.ini")4 if err != nil {5 fmt.Println(err)6 }7 cfg.PatchJSON("config.json")8 fmt.Println(cfg)9}10{11 "section": {12 }13}

Full Screen

Full Screen

PatchJSON

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 panic(fmt.Errorf("Fatal error config file: %s \n", err))4 }5 viper.Set("name", "david")6 viper.Set("age", 22)7 viper.Set("location", "boston")8 viper.Set("friends", []string{"john", "jane"})9 viper.Set("skills", map[string]string{"java": "good", "python": "excellent"})10 viper.Set("hobbies", []string{"soccer", "music"})11 viper.Set("hobbies", []string{"soccer", "music", "hiking"})12 viper.Set("hobbies", []string{"soccer", "hiking"})13 viper.Set("hobbies", []string{"soccer", "music", "hiking", "reading"})14 viper.Set("hobbies", []string{"soccer", "music", "hiking", "reading", "cooking"})15 viper.Set("hobbies", []string{"soccer", "music", "hiking", "reading", "cooking", "programming"})16 viper.Set("hobbies", []string{"soccer", "music", "hiking", "reading", "cooking", "programming", "hacking"})17 viper.Set("hobbies", []string{"soccer", "music", "hiking", "reading", "cooking", "programming", "hacking", "swimming"})18 viper.Set("hobbies", []string{"soccer", "music", "hiking", "reading", "cooking", "programming", "hacking", "swimming", "travelling"})19 viper.Set("hobbies", []string{"soccer", "music", "hiking", "reading", "cooking", "programming", "hacking", "swimming", "travelling", "fishing"})20 viper.Set("hobbies", []string{"soccer", "music", "hiking", "

Full Screen

Full Screen

PatchJSON

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 viper.SetConfigName("config")4 viper.AddConfigPath("/home/shubham/go/src/github.com/shubhamgupta2956/Go-Practice/Config")5 err := viper.ReadInConfig()6 if err != nil {7 fmt.Println("Error while reading config file", err)8 }9 fmt.Println("Initial value of key1 is", viper.Get("key1"))10 err = viper.PatchConfig("/home/shubham/go/src/github.com/shubhamgupta2956/Go-Practice/Config/patch.json")11 if err != nil {12 fmt.Println("Error while patching config file", err)13 }14 fmt.Println("New value of key1 is", viper.Get("key1"))15}163. WatchConfig()17import (18func main() {19 viper.SetConfigName("config")20 viper.AddConfigPath("/home/shubham/go/src/github.com/shubhamgupta2956/Go-Practice/Config")21 err := viper.ReadInConfig()22 if err != nil {23 fmt.Println("Error while reading config file", err)24 }25 fmt.Println("Initial value of key1 is", viper.Get("key1"))26 viper.WatchConfig()27 time.Sleep(10 * time.Second)28 fmt.Println("New value of key1 is", viper.Get("key1"))29}304. SetEnvPrefix()31import (32func main() {33 viper.SetConfigName("config")

Full Screen

Full Screen

PatchJSON

Using AI Code Generation

copy

Full Screen

1import (2type Config struct {3 Content map[string]interface{} `json:"content,omitempty"`4}5func main() {6 config := Config{}7 configBytes, err := ioutil.ReadFile("config.yaml")8 if err != nil {9 panic(err)10 }11 jsonBytes, err := yaml.YAMLToJSON(configBytes)12 if err != nil {13 panic(err)14 }15 err = yaml.Unmarshal(jsonBytes, &config)16 if err != nil {17 panic(err)18 }19 patch := Config{}20 patchBytes, err := ioutil.ReadFile("patch.yaml")21 if err != nil {22 panic(err)23 }24 jsonBytes, err = yaml.YAMLToJSON(patchBytes)25 if err != nil {26 panic(err)27 }28 err = yaml.Unmarshal(jsonBytes, &patch)29 if err != nil {30 panic(err)31 }32 err = config.PatchJSON(patch)33 if err != nil {34 panic(err)35 }36 jsonBytes, err = yaml.Marshal(config)37 if err != nil {38 panic(err)39 }40 yamlBytes, err := yaml.JSONToYAML(jsonBytes)41 if err != nil {42 panic(err)43 }44 err = ioutil.WriteFile("output.yaml", yamlBytes, 0644)45 if err != nil {46 panic(err)47 }48}49func (config *Config) PatchJSON(patch Config) error {50 err := mergo.Merge(&config.Content, patch.Content, mergo.WithOverride)51 if err != nil {52 }53}

Full Screen

Full Screen

Automation Testing Tutorials

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

LambdaTest Learning Hubs:

YouTube

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

Run Syzkaller automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful