...

Source file src/edge-infra.dev/pkg/lib/server/metrics_test.go

Documentation: edge-infra.dev/pkg/lib/server

     1  package server
     2  
     3  import (
     4  	"bufio"
     5  	"context"
     6  	"regexp"
     7  	"testing"
     8  
     9  	"github.com/prometheus/client_golang/prometheus"
    10  	"github.com/prometheus/client_golang/prometheus/promauto"
    11  
    12  	"edge-infra.dev/pkg/lib/server/inmemorylistener"
    13  )
    14  
    15  // Add prometheus metric using promauto
    16  var metricFooBarBazTotal = promauto.NewGauge(prometheus.GaugeOpts{
    17  	Name: "foo_bar_baz_total",
    18  	Help: "foo_bar_baz_total counts the number of foobarbaz",
    19  })
    20  
    21  // Create a metric using promauto and see if the metrics are being served.
    22  func TestMetricsServesScrapeData(t *testing.T) {
    23  	metricFooBarBazTotal.Inc()
    24  	var l = inmemorylistener.New()
    25  	var httpc = l.HTTPClient()
    26  	var s, err = NewMetricsServer(OptionListener(l))
    27  	if err != nil {
    28  		t.Fatal(err)
    29  	}
    30  	go s.Run()                             //nolint:errcheck
    31  	defer s.Shutdown(context.Background()) //nolint:errcheck
    32  
    33  	// Wait for ready.
    34  	for {
    35  		resp, err := httpc.Get("http://localhost/metrics")
    36  		if err == nil && resp.StatusCode == 200 {
    37  			t.Logf("server ready")
    38  			break
    39  		}
    40  		t.Logf("server not ready: %v", err)
    41  	}
    42  
    43  	resp, err := httpc.Get("http://localhost/metrics")
    44  	if err != nil {
    45  		t.Fatal(err)
    46  	}
    47  
    48  	var scanner = bufio.NewScanner(resp.Body)
    49  
    50  	var reMatchFooBarBaz = regexp.MustCompile("^foo_bar_baz_total[ \t]*[0-9]+$")
    51  	var found bool
    52  	for scanner.Scan() {
    53  		txt := scanner.Text()
    54  		if reMatchFooBarBaz.MatchString(txt) {
    55  			found = true
    56  			t.Logf("Found metric line: %q", txt)
    57  		}
    58  	}
    59  
    60  	if err := scanner.Err(); err != nil {
    61  		t.Fatal(err)
    62  	}
    63  
    64  	if !found {
    65  		t.Fatalf("Did not find metric foo_bar_baz_total")
    66  	}
    67  }
    68  

View as plain text