github.com/ethersphere/bee/v2@v2.2.0/pkg/metrics/metrics_test.go (about)

     1  // Copyright 2020 The Swarm Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package metrics_test
     6  
     7  import (
     8  	"strings"
     9  	"testing"
    10  
    11  	"github.com/ethersphere/bee/v2/pkg/metrics"
    12  	"github.com/prometheus/client_golang/prometheus"
    13  )
    14  
    15  func TestPrometheusCollectorsFromFields(t *testing.T) {
    16  	t.Parallel()
    17  
    18  	s := newService()
    19  	collectors := metrics.PrometheusCollectorsFromFields(s)
    20  
    21  	if l := len(collectors); l != 2 {
    22  		t.Fatalf("got %v collectors %+v, want 2", l, collectors)
    23  	}
    24  
    25  	m1 := collectors[0].(prometheus.Metric).Desc().String()
    26  	if !strings.Contains(m1, "api_request_count") {
    27  		t.Errorf("unexpected metric %s", m1)
    28  	}
    29  
    30  	m2 := collectors[1].(prometheus.Metric).Desc().String()
    31  	if !strings.Contains(m2, "api_response_duration_seconds") {
    32  		t.Errorf("unexpected metric %s", m2)
    33  	}
    34  }
    35  
    36  type service struct {
    37  	// valid metrics
    38  	RequestCount     prometheus.Counter
    39  	ResponseDuration prometheus.Histogram
    40  	// invalid metrics
    41  	unexportedCount    prometheus.Counter
    42  	UninitializedCount prometheus.Counter
    43  }
    44  
    45  func newService() *service {
    46  	subsystem := "api"
    47  	return &service{
    48  		RequestCount: prometheus.NewCounter(prometheus.CounterOpts{
    49  			Namespace: metrics.Namespace,
    50  			Subsystem: subsystem,
    51  			Name:      "request_count",
    52  			Help:      "Number of API requests.",
    53  		}),
    54  		ResponseDuration: prometheus.NewHistogram(prometheus.HistogramOpts{
    55  			Namespace: metrics.Namespace,
    56  			Subsystem: subsystem,
    57  			Name:      "response_duration_seconds",
    58  			Help:      "Histogram of API response durations.",
    59  			Buckets:   []float64{0.01, 0.1, 0.25, 0.5, 1, 2.5, 5, 10},
    60  		}),
    61  		unexportedCount: prometheus.NewCounter(prometheus.CounterOpts{
    62  			Namespace: metrics.Namespace,
    63  			Subsystem: subsystem,
    64  			Name:      "unexported_count",
    65  			Help:      "This metrics should not be discoverable by metrics.PrometheusCollectorsFromFields.",
    66  		}),
    67  	}
    68  }