package server import ( "bufio" "context" "regexp" "testing" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" "edge-infra.dev/pkg/lib/server/inmemorylistener" ) // Add prometheus metric using promauto var metricFooBarBazTotal = promauto.NewGauge(prometheus.GaugeOpts{ Name: "foo_bar_baz_total", Help: "foo_bar_baz_total counts the number of foobarbaz", }) // Create a metric using promauto and see if the metrics are being served. func TestMetricsServesScrapeData(t *testing.T) { metricFooBarBazTotal.Inc() var l = inmemorylistener.New() var httpc = l.HTTPClient() var s, err = NewMetricsServer(OptionListener(l)) if err != nil { t.Fatal(err) } go s.Run() //nolint:errcheck defer s.Shutdown(context.Background()) //nolint:errcheck // Wait for ready. for { resp, err := httpc.Get("http://localhost/metrics") if err == nil && resp.StatusCode == 200 { t.Logf("server ready") break } t.Logf("server not ready: %v", err) } resp, err := httpc.Get("http://localhost/metrics") if err != nil { t.Fatal(err) } var scanner = bufio.NewScanner(resp.Body) var reMatchFooBarBaz = regexp.MustCompile("^foo_bar_baz_total[ \t]*[0-9]+$") var found bool for scanner.Scan() { txt := scanner.Text() if reMatchFooBarBaz.MatchString(txt) { found = true t.Logf("Found metric line: %q", txt) } } if err := scanner.Err(); err != nil { t.Fatal(err) } if !found { t.Fatalf("Did not find metric foo_bar_baz_total") } }