github.com/yankunsam/loki/v2@v2.6.3-0.20220817130409-389df5235c27/pkg/logql/syntax/walk_test.go (about) 1 package syntax 2 3 import ( 4 "testing" 5 6 "github.com/prometheus/prometheus/model/labels" 7 "github.com/stretchr/testify/require" 8 ) 9 10 func Test_Walkable(t *testing.T) { 11 type table struct { 12 desc string 13 expr string 14 want int 15 } 16 tests := []table{ 17 { 18 desc: "vector aggregate query", 19 expr: `sum by (cluster) (rate({job="foo"} |= "bar" | logfmt | bazz="buzz" [5m]))`, 20 want: 8, 21 }, 22 { 23 desc: "bin op query", 24 expr: `(sum by(cluster)(rate({job="foo"} |= "bar" | logfmt | bazz="buzz"[5m])) / sum by(cluster)(rate({job="foo"} |= "bar" | logfmt | bazz="buzz"[5m])))`, 25 want: 16, 26 }, 27 } 28 for _, test := range tests { 29 test := test 30 t.Run(test.desc, func(t *testing.T) { 31 expr, err := ParseExpr(test.expr) 32 require.Nil(t, err) 33 34 var cnt int 35 expr.Walk(func(_ interface{}) { cnt++ }) 36 require.Equal(t, test.want, cnt) 37 }) 38 } 39 } 40 41 func Test_AppendMatchers(t *testing.T) { 42 type table struct { 43 desc string 44 expr string 45 want string 46 matchers []*labels.Matcher 47 } 48 tests := []table{ 49 { 50 desc: "vector range query", 51 expr: `sum by(cluster)(rate({job="foo"} |= "bar" | logfmt | bazz="buzz"[5m]))`, 52 want: `sum by(cluster)(rate({job="foo", namespace="a"} |= "bar" | logfmt | bazz="buzz"[5m]))`, 53 matchers: []*labels.Matcher{ 54 { 55 Name: "namespace", 56 Type: labels.MatchEqual, 57 Value: "a", 58 }, 59 }, 60 }, 61 { 62 desc: "bin op query", 63 expr: `sum by(cluster)(rate({job="foo"} |= "bar" | logfmt | bazz="buzz"[5m])) / sum by(cluster)(rate({job="foo"} |= "bar" | logfmt | bazz="buzz"[5m]))`, 64 want: `(sum by(cluster)(rate({job="foo", namespace="a"} |= "bar" | logfmt | bazz="buzz"[5m])) / sum by(cluster)(rate({job="foo", namespace="a"} |= "bar" | logfmt | bazz="buzz"[5m])))`, 65 matchers: []*labels.Matcher{ 66 { 67 Name: "namespace", 68 Type: labels.MatchEqual, 69 Value: "a", 70 }, 71 }, 72 }, 73 } 74 for _, test := range tests { 75 test := test 76 t.Run(test.desc, func(t *testing.T) { 77 expr, err := ParseExpr(test.expr) 78 require.NoError(t, err) 79 80 expr.Walk(func(e interface{}) { 81 switch me := e.(type) { 82 case *MatchersExpr: 83 me.AppendMatchers(test.matchers) 84 default: 85 // Do nothing 86 } 87 }) 88 require.Equal(t, test.want, expr.String()) 89 }) 90 } 91 }