gitlab.com/gitlab-org/labkit@v1.21.0/metrics/http_round_tripper/http_round_tripper_test.go (about)

     1  package http_round_tripper
     2  
     3  import (
     4  	"net/http"
     5  	"net/http/httptest"
     6  	"strings"
     7  	"testing"
     8  
     9  	"github.com/prometheus/client_golang/prometheus"
    10  	"github.com/prometheus/client_golang/prometheus/testutil"
    11  	"github.com/stretchr/testify/require"
    12  )
    13  
    14  type roundTripFunc func(req *http.Request) *http.Response
    15  
    16  func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
    17  	return f(req), nil
    18  }
    19  
    20  func TestNewFactory(t *testing.T) {
    21  	factoryOpts := []FactoryOption{
    22  		WithNamespace("namespace"),
    23  		WithLabels("label1", "label2"),
    24  		WithRequestDurationBuckets([]float64{1, 2, 3}),
    25  	}
    26  
    27  	opts := []Option{
    28  		WithLabelValues(map[string]string{"label1": "1", "label2": "1"}),
    29  	}
    30  
    31  	applyMetrics := NewFactory(factoryOpts...)
    32  
    33  	var invoked bool
    34  	roundTripper := applyMetrics(roundTripFunc(func(req *http.Request) *http.Response {
    35  		invoked = true
    36  
    37  		return &http.Response{}
    38  	}), opts...)
    39  
    40  	r := httptest.NewRequest("GET", "http://example.com", nil)
    41  	roundTripper.RoundTrip(r)
    42  
    43  	metrics := []string{
    44  		"namespace_http_" + inFlightRequestsMetricName,
    45  		"namespace_http_" + requestsTotalMetricName,
    46  	}
    47  
    48  	expected := strings.NewReader(`
    49  				# HELP namespace_http_in_flight_requests A gauge of requests currently being handled.
    50  				# TYPE namespace_http_in_flight_requests gauge
    51  				namespace_http_in_flight_requests 0
    52  				# HELP namespace_http_requests_total A counter for total number of requests.
    53  				# TYPE namespace_http_requests_total counter
    54  				namespace_http_requests_total{code="200",label1="1",label2="1",method="get"} 1
    55  			`)
    56  	err := testutil.GatherAndCompare(prometheus.DefaultGatherer, expected, metrics...)
    57  	require.NoError(t, err)
    58  
    59  	// Duration value is unreliable, so let's just check that the metric is counted
    60  	count, err := testutil.GatherAndCount(prometheus.DefaultGatherer, "namespace_http_"+requestDurationSecondsMetricName)
    61  	require.NoError(t, err)
    62  	require.Equal(t, 1, count)
    63  
    64  	require.True(t, invoked, "request was not executed")
    65  }