github.com/muhammadn/cortex@v1.9.1-0.20220510110439-46bb7000d03d/pkg/ruler/client_pool_test.go (about)

     1  package ruler
     2  
     3  import (
     4  	"context"
     5  	"net"
     6  	"testing"
     7  
     8  	"github.com/grafana/dskit/flagext"
     9  	"github.com/grafana/dskit/grpcclient"
    10  	"github.com/prometheus/client_golang/prometheus"
    11  	dto "github.com/prometheus/client_model/go"
    12  	"github.com/stretchr/testify/assert"
    13  	"github.com/stretchr/testify/require"
    14  	"github.com/weaveworks/common/user"
    15  	"google.golang.org/grpc"
    16  )
    17  
    18  func Test_newRulerClientFactory(t *testing.T) {
    19  	// Create a GRPC server used to query the mocked service.
    20  	grpcServer := grpc.NewServer()
    21  	defer grpcServer.GracefulStop()
    22  
    23  	srv := &mockRulerServer{}
    24  	RegisterRulerServer(grpcServer, srv)
    25  
    26  	listener, err := net.Listen("tcp", "localhost:0")
    27  	require.NoError(t, err)
    28  
    29  	go func() {
    30  		require.NoError(t, grpcServer.Serve(listener))
    31  	}()
    32  
    33  	// Create a client factory and query back the mocked service
    34  	// with different clients.
    35  	cfg := grpcclient.Config{}
    36  	flagext.DefaultValues(&cfg)
    37  
    38  	reg := prometheus.NewPedanticRegistry()
    39  	factory := newRulerClientFactory(cfg, reg)
    40  
    41  	for i := 0; i < 2; i++ {
    42  		client, err := factory(listener.Addr().String())
    43  		require.NoError(t, err)
    44  		defer client.Close() //nolint:errcheck
    45  
    46  		ctx := user.InjectOrgID(context.Background(), "test")
    47  		_, err = client.(*rulerExtendedClient).Rules(ctx, &RulesRequest{})
    48  		assert.NoError(t, err)
    49  	}
    50  
    51  	// Assert on the request duration metric, but since it's a duration histogram and
    52  	// we can't predict the exact time it took, we need to workaround it.
    53  	metrics, err := reg.Gather()
    54  	require.NoError(t, err)
    55  
    56  	assert.Len(t, metrics, 1)
    57  	assert.Equal(t, "cortex_ruler_client_request_duration_seconds", metrics[0].GetName())
    58  	assert.Equal(t, dto.MetricType_HISTOGRAM, metrics[0].GetType())
    59  	assert.Len(t, metrics[0].GetMetric(), 1)
    60  	assert.Equal(t, uint64(2), metrics[0].GetMetric()[0].GetHistogram().GetSampleCount())
    61  }
    62  
    63  type mockRulerServer struct{}
    64  
    65  func (m *mockRulerServer) Rules(context.Context, *RulesRequest) (*RulesResponse, error) {
    66  	return &RulesResponse{}, nil
    67  }