bosun.org@v0.0.0-20210513094433-e25bc3e69a1f/cmd/bosun/expr/prom_test.go (about)

     1  package expr
     2  
     3  import (
     4  	"strings"
     5  	"testing"
     6  
     7  	"github.com/prometheus/prometheus/promql"
     8  )
     9  
    10  type promQueryTemplateTest struct {
    11  	title string
    12  	promQueryTemplateData
    13  	expect string
    14  }
    15  
    16  var promQueryTemplateTests = []promQueryTemplateTest{
    17  	{
    18  		"minimal query",
    19  		promQueryTemplateData{
    20  			Metric: "up",
    21  			AgFunc: "sum",
    22  		},
    23  		"sum( up) by (  )",
    24  	},
    25  	{
    26  		"query with tags",
    27  		promQueryTemplateData{
    28  			Metric: "up",
    29  			AgFunc: "sum",
    30  			Tags:   "namespace,pod",
    31  		},
    32  		"sum( up) by ( namespace,pod )",
    33  	},
    34  	{
    35  		"query with tags and filter",
    36  		promQueryTemplateData{
    37  			Metric: "up",
    38  			AgFunc: "sum",
    39  			Tags:   "namespace,pod",
    40  			Filter: `service !~ "kubl.*"`,
    41  		},
    42  		`sum( up {service !~ "kubl.*"} ) by ( namespace,pod )`,
    43  	},
    44  	{
    45  		"minimal rate query",
    46  		promQueryTemplateData{
    47  			Metric:       "up",
    48  			AgFunc:       "sum",
    49  			RateDuration: "5m",
    50  		},
    51  		`sum(rate( up [5m] )) by (  )`,
    52  	},
    53  	{
    54  		"rate query with tags and filter",
    55  		promQueryTemplateData{
    56  			Metric:       "up",
    57  			AgFunc:       "sum",
    58  			Tags:         "namespace,pod",
    59  			Filter:       ` service !~ "kubl.*" `,
    60  			RateDuration: "5m",
    61  		},
    62  		`sum(rate( up { service !~ "kubl.*" }  [5m] )) by ( namespace,pod )`,
    63  	},
    64  }
    65  
    66  func TestPromQueryTemplate(t *testing.T) {
    67  	for _, qTest := range promQueryTemplateTests {
    68  		out, err := qTest.RenderString()
    69  		if err != nil {
    70  			t.Errorf("error rendering template for test query %v: %v", qTest.title, err)
    71  			continue
    72  		}
    73  		trimmedOut := strings.TrimSpace(out)
    74  		if trimmedOut != qTest.expect {
    75  			t.Errorf("unexpected output for test query %v: got ```%v``` want ```%v```", qTest.title, trimmedOut, qTest.expect)
    76  		}
    77  		_, err = promql.ParseExpr(trimmedOut)
    78  		if err != nil {
    79  			t.Errorf("failed to parse output of for test query %v as valid promql: %v", qTest, err)
    80  		}
    81  	}
    82  }