github.com/GuanceCloud/cliutils@v1.1.21/pipeline/ptinput/funcs/fn_replace_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 TestReplace(t *testing.T) { 18 cases := []struct { 19 name string 20 pl, in string 21 outKey string 22 expected interface{} 23 fail bool 24 }{ 25 { 26 name: `normal`, 27 pl: "json(_, `str`)\n" + 28 "replace(`str`, \"(1[0-9]{2})[0-9]{4}([0-9]{4})\", \"$1****$2\")", 29 in: `{"str": "13789123014"}`, 30 outKey: "str", 31 fail: false, 32 expected: "137****3014", 33 }, 34 35 { 36 name: `normal`, 37 pl: "json(_, `str`)\n" + 38 "replace(`str`, \"([a-z]*) \\\\w*\", \"$1 ***\")", 39 in: `{"str": "zhang san"}`, 40 outKey: "str", 41 expected: "zhang ***", 42 fail: false, 43 }, 44 45 { 46 name: `normal`, 47 pl: "json(_, `str`)\n" + 48 "replace(`str`, \"([1-9]{4})[0-9]{10}([0-9]{4})\", \"$1**********$2\")", 49 in: `{"str": "362201200005302565"}`, 50 outKey: "str", 51 expected: "3622**********2565", 52 fail: false, 53 }, 54 55 { 56 name: `normal`, 57 pl: "json(_, `str`)\n" + 58 "replace(`str`, '([\u4e00-\u9fa5])[\u4e00-\u9fa5]([\u4e00-\u9fa5])', \"$1*$2\")", 59 in: `{"str": "小阿卡"}`, 60 outKey: "str", 61 expected: "小*卡", 62 fail: false, 63 }, 64 { 65 name: `normal`, 66 pl: "json(_, `str`)\n" + 67 "replace(str1, '([\u4e00-\u9fa5])[\u4e00-\u9fa5]([\u4e00-\u9fa5])', \"$1*$2\")", 68 in: `{"str": "小阿卡"}`, 69 outKey: "str", 70 expected: "小阿卡", 71 fail: false, 72 }, 73 { 74 name: `not enough args`, 75 pl: "json(_, `str`)\n" + 76 "replace(`str`, '([\u4e00-\u9fa5])[\u4e00-\u9fa5]([\u4e00-\u9fa5])')", 77 in: `{"str": "小阿卡"}`, 78 fail: true, 79 }, 80 { 81 name: `invalid arg type`, 82 pl: "json(_, `str`)\n" + 83 "replace(`str`, 2, \"$1*$2\")", 84 in: `{"str": "小阿卡"}`, 85 fail: true, 86 }, 87 } 88 89 for idx, tc := range cases { 90 t.Run(tc.name, func(t *testing.T) { 91 runner, err := NewTestingRunner(tc.pl) 92 if err != nil { 93 if tc.fail { 94 t.Logf("[%d]expect error: %s", idx, err) 95 } else { 96 t.Errorf("[%d] failed: %s", idx, err) 97 } 98 return 99 } 100 101 pt := ptinput.NewPlPoint( 102 point.Logging, "test", nil, map[string]any{"message": tc.in}, time.Now()) 103 errR := runScript(runner, pt) 104 105 if errR != nil { 106 t.Fatal(errR.Error()) 107 } 108 109 if v, _, e := pt.Get(tc.outKey); e != nil { 110 if !tc.fail { 111 t.Errorf("[%d]expect error: %s", idx, errR.Error()) 112 } 113 } else { 114 tu.Equals(t, tc.expected, v) 115 t.Logf("[%d] PASS", idx) 116 } 117 118 t.Logf("[%d] PASS", idx) 119 }) 120 } 121 }