github.com/go-graphite/carbonapi@v0.17.0/expr/functions/linearRegression/function_test.go (about)

     1  package linearRegression
     2  
     3  import (
     4  	"context"
     5  	"math"
     6  	"testing"
     7  
     8  	"github.com/go-graphite/carbonapi/expr/interfaces"
     9  	"github.com/go-graphite/carbonapi/expr/metadata"
    10  	"github.com/go-graphite/carbonapi/expr/types"
    11  	"github.com/go-graphite/carbonapi/pkg/parser"
    12  	th "github.com/go-graphite/carbonapi/tests"
    13  )
    14  
    15  var (
    16  	md []interfaces.FunctionMetadata = New("")
    17  )
    18  
    19  func init() {
    20  	for _, m := range md {
    21  		metadata.RegisterFunction(m.Name, m.F)
    22  	}
    23  }
    24  
    25  func TestLinearRegression(t *testing.T) {
    26  	tests := []th.EvalTestItem{
    27  		{
    28  			"linearRegression(metric1)",
    29  			map[parser.MetricRequest][]*types.MetricData{
    30  				{Metric: "metric1", From: 0, Until: 1}: {
    31  					types.MakeMetricData("metric1",
    32  						[]float64{1, 2, math.NaN(), math.NaN(), 5, 6}, 1, 123),
    33  				},
    34  			},
    35  			[]*types.MetricData{
    36  				types.MakeMetricData("linearRegression(metric1)",
    37  					[]float64{1, 2, 3, 4, 5, 6}, 1, 123).SetTag("linearRegressions", "123, 129"),
    38  			},
    39  		},
    40  	}
    41  
    42  	for _, tt := range tests {
    43  		testName := tt.Target
    44  		t.Run(testName, func(t *testing.T) {
    45  			eval := th.EvaluatorFromFunc(md[0].F)
    46  			th.TestEvalExpr(t, eval, &tt)
    47  		})
    48  	}
    49  
    50  }
    51  
    52  func BenchmarkLinearRegression(b *testing.B) {
    53  	target := "linearRegression(metric1)"
    54  	metrics := map[parser.MetricRequest][]*types.MetricData{
    55  		{Metric: "metric1", From: 0, Until: 1}: {types.MakeMetricData("metric1", []float64{1, 2, math.NaN(), math.NaN(), 5, 6}, 1, 1)},
    56  	}
    57  
    58  	eval := th.EvaluatorFromFunc(md[0].F)
    59  	exp, _, err := parser.ParseExpr(target)
    60  	if err != nil {
    61  		b.Fatalf("failed to parse %s: %+v", target, err)
    62  	}
    63  
    64  	b.ResetTimer()
    65  	for n := 0; n < b.N; n++ {
    66  		g, err := eval.Eval(context.Background(), exp, 0, 1, metrics)
    67  		if err != nil {
    68  			b.Fatalf("failed to eval %s: %+v", target, err)
    69  		}
    70  		_ = g
    71  	}
    72  }