github.com/GuanceCloud/cliutils@v1.1.21/pipeline/ptinput/funcs/fn_timstamp_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 "math" 10 "testing" 11 "time" 12 13 "github.com/GuanceCloud/cliutils/pipeline/ptinput" 14 "github.com/GuanceCloud/cliutils/point" 15 "github.com/stretchr/testify/assert" 16 ) 17 18 func TestTimestamp(t *testing.T) { 19 cases := []struct { 20 name, pl, in string 21 outkey string 22 expect interface{} 23 fail bool 24 }{ 25 { 26 name: "timestamp_default", 27 in: `time_now`, 28 pl: `add_key(time1, timestamp())`, 29 outkey: "time1", 30 expect: time.Now().UnixNano(), 31 fail: false, 32 }, 33 { 34 name: "time_now_ns", 35 in: `time_now`, 36 pl: `add_key(time1, timestamp("ns"))`, 37 outkey: "time1", 38 expect: time.Now().UnixNano(), 39 fail: false, 40 }, 41 { 42 name: "time_now_us", 43 in: `time_now`, 44 pl: `add_key(time1, timestamp("us")* 1000)`, 45 outkey: "time1", 46 expect: time.Now().UnixNano(), 47 fail: false, 48 }, 49 { 50 name: "time_now_ms", 51 in: `time_now`, 52 pl: `add_key(time1, timestamp("ms")*1000000)`, 53 outkey: "time1", 54 expect: time.Now().UnixNano(), 55 fail: false, 56 }, 57 { 58 name: "time_now_s", 59 in: `time_now`, 60 pl: `add_key(time1, timestamp("s")*1000000000)`, 61 outkey: "time1", 62 expect: time.Now().UnixNano(), 63 }, 64 } 65 66 for idx, tc := range cases { 67 t.Run(tc.name, func(t *testing.T) { 68 runner, err := NewTestingRunner(tc.pl) 69 if err != nil { 70 if tc.fail { 71 t.Logf("[%d]expect error: %s", idx, err) 72 } else { 73 t.Errorf("[%d] failed: %s", idx, err) 74 } 75 return 76 } 77 78 pt := ptinput.NewPlPoint( 79 point.Logging, "test", nil, map[string]any{"message": tc.in}, time.Now()) 80 errR := runScript(runner, pt) 81 82 if errR != nil { 83 t.Fatal(errR.Error()) 84 } 85 86 v, _, _ := pt.Get(tc.outkey) 87 tsAct, ok := v.(int64) 88 if !ok { 89 t.Fatalf("type of %s is not int64", tc.outkey) 90 } 91 switch expect := tc.expect.(type) { 92 case int64: 93 assert.GreaterOrEqual(t, 1e9, math.Abs(float64(expect-tsAct))) 94 default: 95 t.Fatal("undefined action") 96 } 97 t.Logf("[%d] PASS", idx) 98 }) 99 } 100 }