github.com/GuanceCloud/cliutils@v1.1.21/pipeline/ptinput/funcs/fn_sample_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 ) 15 16 func TestSample(t *testing.T) { 17 cases := []struct { 18 name, pl, in string 19 fail bool 20 outKey string 21 }{ 22 { 23 name: "fifty-fifty", 24 in: `dummy input`, 25 pl: ` 26 if sample(0.5) { 27 add_key(hello, "world") 28 } 29 `, 30 fail: false, 31 outKey: "hello", 32 }, 33 { 34 name: "definite", 35 in: `dummy input`, 36 pl: ` 37 if sample(1) { 38 add_key(hello, "world") 39 } 40 `, 41 fail: false, 42 outKey: "hello", 43 }, 44 { 45 name: "expression as arg", 46 in: `dummy input`, 47 pl: ` 48 if sample(2 * 0.1) { 49 add_key(hello, "world") 50 } 51 `, 52 fail: false, 53 outKey: "hello", 54 }, 55 { 56 name: "negative probability", 57 in: `dummy input`, 58 pl: ` 59 sample(-0.5) 60 `, 61 fail: true, 62 }, 63 { 64 name: "probability out of range", 65 in: `dummy input`, 66 pl: ` 67 sample(2) 68 `, 69 fail: true, 70 }, 71 } 72 73 for idx, tc := range cases { 74 t.Run(tc.name, func(t *testing.T) { 75 runner, err := NewTestingRunner(tc.pl) 76 if err != nil { 77 if tc.fail { 78 t.Logf("[%d]expect error: %s", idx, err) 79 } else { 80 t.Errorf("[%d] failed: %s", idx, err) 81 } 82 return 83 } 84 85 pt := ptinput.NewPlPoint( 86 point.Logging, "test", nil, map[string]any{"message": tc.in}, time.Now()) 87 errR := runScript(runner, pt) 88 89 if errR != nil { 90 t.Fatal(errR.Error()) 91 } 92 93 if v, _, err := pt.Get(tc.outKey); err == nil { 94 t.Logf("k/v pair `%s = %s` has been added to output", tc.outKey, v) 95 } 96 t.Logf("[%d] PASS", idx) 97 }) 98 } 99 }