github.com/GuanceCloud/cliutils@v1.1.21/pipeline/ptinput/funcs/fn_valid_json_test.go (about) 1 // Unless explicitly stated otherwise all files in this repository are licensed 2 // under the MIT License. 3 // This product includes software developed at Guance Cloud (https://www.guance.com/). 4 // Copyright 2021-present Guance, Inc. 5 6 package funcs 7 8 import ( 9 "testing" 10 "time" 11 12 "github.com/GuanceCloud/cliutils/pipeline/ptinput" 13 "github.com/GuanceCloud/cliutils/point" 14 tu "github.com/GuanceCloud/cliutils/testutil" 15 ) 16 17 func TestValidJson(t *testing.T) { 18 cases := []struct { 19 name, pl, in string 20 outkey string 21 expect interface{} 22 fail bool 23 }{ 24 { 25 name: "map", 26 in: `{"a":{"first": [2.2, 1.1], "ff": "[2.2, 1.1]","second":2,"third":"aBC","forth":true},"age":47}`, 27 pl: ` 28 if valid_json(_) { 29 d = load_json(_) 30 add_key("abc", d["a"]["first"][0]) 31 } 32 `, 33 outkey: "abc", 34 expect: 2.2, 35 }, 36 { 37 name: "map", 38 in: `{"a"??:{"first": [2.2, 1.1], "ff": "[2.2, 1.1]","second":2,"third":"aBC","forth":true},"age":47}`, 39 pl: ` 40 if valid_json(_) { 41 } else { 42 d = load_json(_) 43 add_key("abc", d["a"]["first"][0]) 44 } 45 `, 46 outkey: "abc", 47 expect: 2.2, 48 fail: true, 49 }, 50 { 51 name: "map", 52 in: ``, 53 pl: "add_key(`in`, valid_json(_))", 54 outkey: "in", 55 expect: false, 56 }, 57 { 58 name: "for-compatibility-with-older-versions", 59 in: `{"a":{"first": [2.2, 1.1], "ff": "[2.2, 1.1]","second":2,"third":"aBC","forth":true},"age":47}`, 60 pl: ` 61 if vaild_json(_) { 62 d = load_json(_) 63 add_key("abc", d["a"]["first"][0]) 64 } 65 `, 66 outkey: "abc", 67 expect: 2.2, 68 }, 69 } 70 71 for idx, tc := range cases { 72 t.Run(tc.name, func(t *testing.T) { 73 runner, err := NewTestingRunner(tc.pl) 74 if err != nil { 75 if tc.fail { 76 t.Logf("[%d]expect error: %s", idx, err) 77 } else { 78 t.Errorf("[%d] failed: %s", idx, err) 79 } 80 return 81 } 82 83 pt := ptinput.NewPlPoint( 84 point.Logging, "test", nil, map[string]any{"message": tc.in}, time.Now()) 85 errR := runScript(runner, pt) 86 87 t.Log(pt.Fields()) 88 if errR != nil { 89 if tc.fail { 90 return 91 } 92 t.Fatal(errR) 93 } else { 94 v, _, _ := pt.Get(tc.outkey) 95 tu.Equals(t, tc.expect, v) 96 t.Logf("[%d] PASS", idx) 97 } 98 }) 99 } 100 }