How to use convertJson method of pkg Package

Best Keploy code snippet using pkg.convertJson

observe_builds_test.go

Source:observe_builds_test.go Github

copy

Full Screen

1package builds2import (3 "strings"4 "testing"5 corev1 "k8s.io/api/core/v1"6 "k8s.io/apimachinery/pkg/api/equality"7 "k8s.io/apimachinery/pkg/api/resource"8 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"9 "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"10 "k8s.io/client-go/tools/cache"11 configv1 "github.com/openshift/api/config/v1"12 configlistersv1 "github.com/openshift/client-go/config/listers/config/v1"13 "github.com/openshift/library-go/pkg/operator/events"14 "github.com/openshift/cluster-openshift-controller-manager-operator/pkg/operator/configobservation"15)16func TestObserveBuildControllerConfig(t *testing.T) {17 memLimit, err := resource.ParseQuantity("1G")18 truePtr := true19 falsePtr := false20 if err != nil {21 t.Fatal(err)22 }23 tests := []struct {24 name string25 buildConfig *configv1.Build26 expectError bool27 }{28 {29 name: "no build config",30 },31 {32 name: "valid build config with resource limits",33 buildConfig: &configv1.Build{34 ObjectMeta: metav1.ObjectMeta{35 Name: "cluster",36 },37 Spec: configv1.BuildSpec{38 BuildDefaults: configv1.BuildDefaults{39 Resources: corev1.ResourceRequirements{40 Limits: corev1.ResourceList{41 corev1.ResourceMemory: memLimit,42 },43 Requests: corev1.ResourceList{44 corev1.ResourceMemory: memLimit,45 },46 },47 },48 },49 },50 },51 {52 name: "valid build config",53 buildConfig: &configv1.Build{54 ObjectMeta: metav1.ObjectMeta{55 Name: "cluster",56 },57 Spec: configv1.BuildSpec{58 BuildDefaults: configv1.BuildDefaults{59 DefaultProxy: &configv1.ProxySpec{60 HTTPProxy: "http://user:pass@someproxy.net",61 HTTPSProxy: "https://user:pass@someproxy.net",62 NoProxy: "image-resgistry.cluster.svc.local",63 },64 GitProxy: &configv1.ProxySpec{65 HTTPProxy: "http://my-proxy",66 HTTPSProxy: "https://my-proxy",67 NoProxy: "https://no-proxy",68 },69 Env: []corev1.EnvVar{70 {71 Name: "FOO",72 Value: "BAR",73 },74 },75 ImageLabels: []configv1.ImageLabel{76 {77 Name: "build.openshift.io",78 Value: "test",79 },80 },81 Resources: corev1.ResourceRequirements{82 Requests: corev1.ResourceList{83 corev1.ResourceMemory: memLimit,84 },85 },86 },87 BuildOverrides: configv1.BuildOverrides{88 ImageLabels: []configv1.ImageLabel{89 {90 Name: "build.openshift.io",91 Value: "teset2",92 },93 },94 NodeSelector: map[string]string{95 "foo": "bar",96 },97 Tolerations: []corev1.Toleration{98 {99 Key: "somekey",100 Operator: corev1.TolerationOpExists,101 Effect: corev1.TaintEffectNoSchedule,102 },103 },104 },105 },106 },107 },108 {109 name: "valid build config forcePull true",110 buildConfig: &configv1.Build{111 ObjectMeta: metav1.ObjectMeta{112 Name: "cluster",113 },114 Spec: configv1.BuildSpec{115 BuildDefaults: configv1.BuildDefaults{116 DefaultProxy: &configv1.ProxySpec{117 HTTPProxy: "http://user:pass@someproxy.net",118 HTTPSProxy: "https://user:pass@someproxy.net",119 NoProxy: "image-resgistry.cluster.svc.local",120 },121 GitProxy: &configv1.ProxySpec{122 HTTPProxy: "http://my-proxy",123 HTTPSProxy: "https://my-proxy",124 NoProxy: "https://no-proxy",125 },126 Env: []corev1.EnvVar{127 {128 Name: "FOO",129 Value: "BAR",130 },131 },132 ImageLabels: []configv1.ImageLabel{133 {134 Name: "build.openshift.io",135 Value: "test",136 },137 },138 Resources: corev1.ResourceRequirements{139 Requests: corev1.ResourceList{140 corev1.ResourceMemory: memLimit,141 },142 },143 },144 BuildOverrides: configv1.BuildOverrides{145 ImageLabels: []configv1.ImageLabel{146 {147 Name: "build.openshift.io",148 Value: "teset2",149 },150 },151 NodeSelector: map[string]string{152 "foo": "bar",153 },154 Tolerations: []corev1.Toleration{155 {156 Key: "somekey",157 Operator: corev1.TolerationOpExists,158 Effect: corev1.TaintEffectNoSchedule,159 },160 },161 ForcePull: &truePtr,162 },163 },164 },165 },166 {167 name: "valid build config forcePull false",168 buildConfig: &configv1.Build{169 ObjectMeta: metav1.ObjectMeta{170 Name: "cluster",171 },172 Spec: configv1.BuildSpec{173 BuildDefaults: configv1.BuildDefaults{174 DefaultProxy: &configv1.ProxySpec{175 HTTPProxy: "http://user:pass@someproxy.net",176 HTTPSProxy: "https://user:pass@someproxy.net",177 NoProxy: "image-resgistry.cluster.svc.local",178 },179 GitProxy: &configv1.ProxySpec{180 HTTPProxy: "http://my-proxy",181 HTTPSProxy: "https://my-proxy",182 NoProxy: "https://no-proxy",183 },184 Env: []corev1.EnvVar{185 {186 Name: "FOO",187 Value: "BAR",188 },189 },190 ImageLabels: []configv1.ImageLabel{191 {192 Name: "build.openshift.io",193 Value: "test",194 },195 },196 Resources: corev1.ResourceRequirements{197 Requests: corev1.ResourceList{198 corev1.ResourceMemory: memLimit,199 },200 },201 },202 BuildOverrides: configv1.BuildOverrides{203 ImageLabels: []configv1.ImageLabel{204 {205 Name: "build.openshift.io",206 Value: "teset2",207 },208 },209 NodeSelector: map[string]string{210 "foo": "bar",211 },212 Tolerations: []corev1.Toleration{213 {214 Key: "somekey",215 Operator: corev1.TolerationOpExists,216 Effect: corev1.TaintEffectNoSchedule,217 },218 },219 ForcePull: &falsePtr,220 },221 },222 },223 },224 {225 name: "empty proxy values",226 buildConfig: &configv1.Build{227 ObjectMeta: metav1.ObjectMeta{228 Name: "cluster",229 },230 Spec: configv1.BuildSpec{231 BuildDefaults: configv1.BuildDefaults{232 DefaultProxy: &configv1.ProxySpec{233 HTTPProxy: "",234 HTTPSProxy: "https://user:pass@someproxy.net",235 NoProxy: "",236 },237 GitProxy: &configv1.ProxySpec{238 HTTPProxy: "http://my-proxy",239 HTTPSProxy: "",240 NoProxy: "https://no-proxy",241 },242 },243 },244 },245 },246 {247 name: "default proxy",248 buildConfig: &configv1.Build{249 ObjectMeta: metav1.ObjectMeta{250 Name: "cluster",251 },252 Spec: configv1.BuildSpec{253 BuildDefaults: configv1.BuildDefaults{254 DefaultProxy: &configv1.ProxySpec{255 HTTPProxy: "http://user:pass@someproxy.net",256 HTTPSProxy: "https://user:pass@someproxy.net",257 NoProxy: "image-resgistry.cluster.svc.local",258 },259 },260 },261 },262 },263 {264 name: "default proxy with env vars",265 buildConfig: &configv1.Build{266 ObjectMeta: metav1.ObjectMeta{267 Name: "cluster",268 },269 Spec: configv1.BuildSpec{270 BuildDefaults: configv1.BuildDefaults{271 DefaultProxy: &configv1.ProxySpec{272 HTTPProxy: "http://user:pass@someproxy.net",273 HTTPSProxy: "https://user:pass@someproxy.net",274 NoProxy: "image-resgistry.cluster.svc.local",275 },276 Env: []corev1.EnvVar{277 {278 Name: "HTTP_PROXY",279 Value: "http://other:user@otherproxy.com",280 },281 {282 Name: "HTTPS_PROXY",283 Value: "https://other:user@otherproxy.com",284 },285 {286 Name: "NO_PROXY",287 Value: "somedomain",288 },289 },290 },291 },292 },293 },294 {295 name: "git proxy",296 buildConfig: &configv1.Build{297 ObjectMeta: metav1.ObjectMeta{298 Name: "cluster",299 },300 Spec: configv1.BuildSpec{301 BuildDefaults: configv1.BuildDefaults{302 GitProxy: &configv1.ProxySpec{303 HTTPProxy: "http://user:pass@someproxy.net",304 HTTPSProxy: "https://user:pass@someproxy.net",305 NoProxy: "image-resgistry.cluster.svc.local",306 },307 },308 },309 },310 },311 }312 for _, test := range tests {313 t.Run(test.name, func(t *testing.T) {314 indexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{})315 if test.buildConfig != nil {316 indexer.Add(test.buildConfig)317 }318 listers := configobservation.Listers{319 BuildConfigLister: configlistersv1.NewBuildLister(indexer),320 }321 config := map[string]interface{}{}322 observed, err := ObserveBuildControllerConfig(listers, events.NewInMemoryRecorder(""), config)323 if err != nil {324 if !test.expectError {325 t.Fatalf("unexpected error observing build controller config: %v", err)326 }327 }328 if test.expectError {329 if err == nil {330 t.Error("expected error to be thrown, but was not")331 }332 if len(observed) > 0 {333 t.Error("expected returned config to be empty")334 }335 return336 }337 if test.buildConfig == nil {338 if len(observed) > 0 {339 t.Errorf("expected empty observed config, got %v", observed)340 }341 return342 }343 expectedEnv := test.buildConfig.Spec.BuildDefaults.Env344 testNestedField(observed, expectedEnv, "build.buildDefaults.env", false, t)345 testNestedField(observed, test.buildConfig.Spec.BuildDefaults.ImageLabels, "build.buildDefaults.imageLabels", false, t)346 testNestedField(observed, test.buildConfig.Spec.BuildDefaults.Resources, "build.buildDefaults.resources", false, t)347 testNestedField(observed, test.buildConfig.Spec.BuildOverrides.ImageLabels, "build.buildOverrides.imageLabels", false, t)348 testNestedField(observed, test.buildConfig.Spec.BuildOverrides.NodeSelector, "build.buildOverrides.nodeSelector", false, t)349 testNestedField(observed, test.buildConfig.Spec.BuildOverrides.Tolerations, "build.buildOverrides.tolerations", false, t)350 testNestedField(observed, test.buildConfig.Spec.BuildOverrides.ForcePull, "build.buildOverrides.forcePull", false, t)351 testNestedField(observed, nil, "build.buildDefaults.gitHTTPProxy", false, t)352 testNestedField(observed, nil, "build.buildDefaults.gitHTTPSProxy", false, t)353 testNestedField(observed, nil, "build.buildDefaults.gitNoProxy", false, t)354 })355 }356}357func testNestedField(obj map[string]interface{}, expectedVal interface{}, field string, existIfEmpty bool, t *testing.T) {358 nestedField := strings.Split(field, ".")359 switch expected := expectedVal.(type) {360 case *bool:361 value, found, err := unstructured.NestedBool(obj, nestedField...)362 if err != nil {363 t.Fatalf("failed to read nested string %s: %v", field, err)364 }365 if expected != nil && *expected != value {366 t.Errorf("expected field %s to be %t, got %v", field, expectedVal, value)367 }368 if existIfEmpty && !found {369 t.Errorf("expected field %s to exist, even if empty", field)370 }371 case string:372 value, found, err := unstructured.NestedString(obj, nestedField...)373 if err != nil {374 t.Fatalf("failed to read nested string %s: %v", field, err)375 }376 if expected != value {377 t.Errorf("expected field %s to be %s, got %s", field, expectedVal, value)378 }379 if existIfEmpty && !found {380 t.Errorf("expected field %s to exist, even if empty", field)381 }382 case map[string]string:383 value, found, err := unstructured.NestedStringMap(obj, nestedField...)384 if err != nil {385 t.Fatal(err)386 }387 if !equality.Semantic.DeepEqual(value, expected) {388 t.Errorf("expected %s to be %v, got %v", field, expected, value)389 }390 if existIfEmpty && !found {391 t.Errorf("expected field %s to exist, even if empty", field)392 }393 case []corev1.EnvVar:394 value, found, err := unstructured.NestedSlice(obj, nestedField...)395 if err != nil {396 t.Fatal(err)397 }398 rawExpected, err := configobservation.ConvertJSON(expected)399 if err != nil {400 t.Fatalf("unable to test field %s: %v", field, err)401 }402 if !equality.Semantic.DeepEqual(value, rawExpected) {403 t.Errorf("expected %s to be %v, got %v", field, rawExpected, value)404 }405 if existIfEmpty && !found {406 t.Errorf("expected field %s to exist, even if empty", field)407 }408 case []corev1.Toleration:409 value, found, err := unstructured.NestedSlice(obj, nestedField...)410 if err != nil {411 t.Fatal(err)412 }413 rawExpected, err := configobservation.ConvertJSON(expected)414 if err != nil {415 t.Fatalf("unable to test field %s: %v", field, err)416 }417 if !equality.Semantic.DeepEqual(value, rawExpected) {418 t.Errorf("expected %s to be %v, got %v", field, expected, value)419 }420 if existIfEmpty && !found {421 t.Errorf("expected field %s to exist, even if empty", field)422 }423 case []configv1.ImageLabel:424 value, found, err := unstructured.NestedSlice(obj, nestedField...)425 if err != nil {426 t.Fatal(err)427 }428 rawExpected, err := configobservation.ConvertJSON(expected)429 if err != nil {430 t.Fatalf("unable to test field %s: %v", field, err)431 }432 if !equality.Semantic.DeepEqual(value, rawExpected) {433 t.Errorf("expected %s to be %v, got %v", field, expected, value)434 }435 if existIfEmpty && !found {436 t.Errorf("expected field %s to exist, even if empty", field)437 }438 case []interface{}:439 value, found, err := unstructured.NestedSlice(obj, nestedField...)440 if err != nil {441 t.Fatalf("unable to test field %s: %v", field, err)442 }443 rawExpected, err := configobservation.ConvertJSON(expected)444 if err != nil {445 t.Fatalf("unable to test field %s: %v", field, err)446 }447 if !equality.Semantic.DeepEqual(value, rawExpected) {448 t.Errorf("expected %s to be %v, got %v", field, expected, value)449 }450 if existIfEmpty && !found {451 t.Errorf("expected field %s to exist, even if empty", field)452 }453 default:454 value, found, err := unstructured.NestedFieldCopy(obj, nestedField...)455 if err != nil {456 t.Fatalf("unable to test field %s: %v", field, err)457 }458 rawExpected, err := configobservation.ConvertJSON(expected)459 if err != nil {460 t.Fatalf("unable to test field %s: %v", field, err)461 }462 if !equality.Semantic.DeepEqual(rawExpected, value) {463 t.Errorf("expected %s to be %#v; got %#v", field, expected, value)464 }465 if existIfEmpty && !found {466 t.Errorf("expected field %s to exist, even if empty", field)467 }468 }469}...

Full Screen

Full Screen

util.go

Source:util.go Github

copy

Full Screen

1package configobservation2import (3 "bytes"4 "encoding/json"5 "fmt"6 "io/ioutil"7 "strings"8 "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"9)10// ObserveField sets the nested fieldName's value in the provided observedConfig.11// If the provided value is nil, no value is set.12// If skipIfEmpty is true, the value13func ObserveField(observedConfig map[string]interface{}, val interface{}, fieldName string, skipIfEmpty bool) error {14 nestedFields := strings.Split(fieldName, ".")15 if val == nil {16 return nil17 }18 var err error19 switch v := val.(type) {20 case int64, bool:21 err = unstructured.SetNestedField(observedConfig, v, nestedFields...)22 case *bool:23 if skipIfEmpty && val == nil {24 return nil25 } else if !skipIfEmpty && val == nil {26 return fmt.Errorf("cannot observe nil value for bool pointer field %s", fieldName)27 }28 err = unstructured.SetNestedField(observedConfig, *v, nestedFields...)29 case string:30 if skipIfEmpty && len(v) == 0 {31 return nil32 }33 err = unstructured.SetNestedField(observedConfig, v, nestedFields...)34 case []interface{}:35 if skipIfEmpty && len(v) == 0 {36 return nil37 }38 err = unstructured.SetNestedSlice(observedConfig, v, nestedFields...)39 case map[string]string:40 if skipIfEmpty && len(v) == 0 {41 return nil42 }43 err = unstructured.SetNestedStringMap(observedConfig, v, nestedFields...)44 case map[string]interface{}:45 if skipIfEmpty && len(v) == 0 {46 return nil47 }48 err = unstructured.SetNestedMap(observedConfig, v, nestedFields...)49 default:50 data, err := ConvertJSON(v)51 if err != nil {52 return err53 }54 if skipIfEmpty && data == nil {55 return nil56 }57 err = unstructured.SetNestedField(observedConfig, data, nestedFields...)58 }59 return err60}61// ConvertJSON is a function tailored to convert slices of various types into62// slices of interface{}, it also works with object os various types, converting63// them into map[string]interface{}. This function copies the original data.64func ConvertJSON(o interface{}) (interface{}, error) {65 if o == nil {66 return nil, nil67 }68 buf := &bytes.Buffer{}69 if err := json.NewEncoder(buf).Encode(o); err != nil {70 return nil, err71 }72 jsonEncoded, err := ioutil.ReadAll(buf)73 if err != nil {74 return nil, err75 }76 sliceRet := []interface{}{}77 if err := json.Unmarshal(jsonEncoded, &sliceRet); err == nil {78 return sliceRet, nil79 }80 mapRet := map[string]interface{}{}81 if err := json.Unmarshal(jsonEncoded, &mapRet); err != nil {82 return nil, err83 }84 return mapRet, err85}...

Full Screen

Full Screen

export.go

Source:export.go Github

copy

Full Screen

1package internal2import (3 "encoding/csv"4 "encoding/json"5 "fmt"6 "io/ioutil"7 "os"8 "github.com/pterm/pterm"9)10type FuncInfoExport struct {11 FileName string `json:"file"`12 PkgFileName string `json:"pkg_file"`13 FunctionName string `json:"function"`14 StartLine int `json:"start_line"`15 EndLine int `json:"end_line"`16 UncoveredLines int `json:"uncovered_lines"`17}18func ExportJSON(filename string, fi []*funcInfo) (err error) {19 funcInfosJSON := convertJSON(fi)20 if err != nil {21 return err22 }23 data, err := json.MarshalIndent(funcInfosJSON, "", " ")24 if err != nil {25 return err26 }27 if filename == "" {28 pterm.Println(string(data))29 return nil30 }31 if err = ioutil.WriteFile(filename, data, 0644); err != nil {32 return err33 }34 pterm.Info.Printf("Saved results to %s!\n", filename)35 return nil36}37func convertJSON(funcInfos []*funcInfo) []FuncInfoExport {38 var occurences []FuncInfoExport39 for _, fi := range funcInfos {40 functionInfo := FuncInfoExport{41 FileName: fi.fileName,42 PkgFileName: fi.pkgFileName,43 FunctionName: fi.functionName,44 StartLine: fi.startLine,45 EndLine: fi.endLine,46 UncoveredLines: fi.uncoveredLines,47 }48 occurences = append(occurences, functionInfo)49 }50 return occurences51}52func ExportCSV(filename string, fi []*funcInfo) error {53 records := convertCSV(fi)54 if filename == "" {55 w := csv.NewWriter(os.Stdout)56 err := w.WriteAll(records)57 if err != nil {58 return err59 }60 return nil61 }62 file, err := os.Create(filename)63 if err != nil {64 return err65 }66 w := csv.NewWriter(file)67 err = w.WriteAll(records)68 if err != nil {69 return err70 }71 pterm.Info.Printf("Saved results to %s!\n", filename)72 return nil73}74func convertCSV(funcInfos []*funcInfo) [][]string {75 records := [][]string{{"file", "pkg_file", "function", "start_line", "end_line", "uncovered_lines"}}76 for _, fi := range funcInfos {77 functionInfo := []string{fi.fileName, fi.pkgFileName, fi.functionName, fmt.Sprint(fi.startLine), fmt.Sprint(fi.endLine), fmt.Sprint(fi.uncoveredLines)}78 records = append(records, functionInfo)79 }80 return records81}...

Full Screen

Full Screen

convertJson

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 var jsonStr = `{"name":"John","age":30,"cars":["Ford","BMW","Fiat"]}`4 var result = pkg.ConvertJson(jsonStr)5 fmt.Println(result)6}7import (8func ConvertJson(jsonStr string) map[string]interface{} {9 var result map[string]interface{}10 json.Unmarshal([]byte(jsonStr), &result)11}

Full Screen

Full Screen

convertJson

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 jsonStr := `{"foo":"bar"}`4 err := json.Unmarshal([]byte(jsonStr), &pkgObj)5 if err != nil {6 fmt.Println(err)7 }8 fmt.Println(pkgObj)9 fmt.Println(pkgObj.Foo)10}11{bar}

Full Screen

Full Screen

convertJson

Using AI Code Generation

copy

Full Screen

1func main() {2 pkg := pkg.New()3 pkg.ConvertJson()4}5func main() {6 pkg := pkg.New()7 pkg.ConvertJson()8}9func main() {10 pkg := pkg.New()11 pkg.ConvertJson()12}13func main() {14 pkg := pkg.New()15 pkg.ConvertJson()16}17func main() {18 pkg := pkg.New()19 pkg.ConvertJson()20}21func main() {22 pkg := pkg.New()23 pkg.ConvertJson()24}25func main() {26 pkg := pkg.New()27 pkg.ConvertJson()28}29func main() {30 pkg := pkg.New()31 pkg.ConvertJson()32}33func main() {34 pkg := pkg.New()35 pkg.ConvertJson()36}37func main() {38 pkg := pkg.New()

Full Screen

Full Screen

convertJson

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, playground")4 jsonStr := `{5 { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },6 { "name":"BMW", "models":[ "320", "X3", "X5" ] },7 { "name":"Fiat", "models":[ "500", "Panda" ] }8 }`9 res := pkg.ConvertJson(jsonStr)10 fmt.Println(res)11}12import (13type Car struct {14}15type Person struct {16}17func ConvertJson(jsonStr string) Person {18 json.Unmarshal([]byte(jsonStr), &person)19 fmt.Println(person)20}21{John 30 [{Ford [Fiesta Focus Mustang]} {BMW [320 X3 X5]} {Fiat [500 Panda]}]}

Full Screen

Full Screen

convertJson

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 jsonStr := `{4 }`5 var jsonObj interface{}6 err := json.Unmarshal([]byte(jsonStr), &jsonObj)7 if err != nil {8 panic(err)9 }10 goStruct := pkg.ConvertJson(jsonObj, "Product")11 fmt.Println(goStruct)12}13type Product struct {14}

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 Keploy 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