diff --git a/pkg/metrics/metrics_test.go b/pkg/metrics/metrics_test.go index 0e1717353a84cc0ce58e2b38961c578eb307be75..369c9a7004468260b9e999bc001f062de27084ad 100644 --- a/pkg/metrics/metrics_test.go +++ b/pkg/metrics/metrics_test.go @@ -7,8 +7,10 @@ import ( "testing" "git.perx.ru/perxis/perxis-go/pkg/id" + "git.perx.ru/perxis/perxis-go/pkg/optional" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" + dto "github.com/prometheus/client_model/go" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -72,4 +74,44 @@ func TestMetrics_Example(t *testing.T) { // fmt.Println(string(b)) assert.Contains(t, string(b), name+"{a=\"v_a1\",b=\"v_b1\",const_1=\"val_1\"} 1") }) + + t.Run("Register multiple metrics with the same name and labels combine into metric family", func(t *testing.T) { + name := "test_counter_" + id.GenerateNewID() + m1 := prometheus.NewCounterVec(prometheus.CounterOpts{Name: name, ConstLabels: prometheus.Labels{"const_1": "val_1"}}, []string{"a1", "b1"}) + m2 := prometheus.NewCounterVec(prometheus.CounterOpts{Name: name, ConstLabels: prometheus.Labels{"const_1": "val_2"}}, []string{"a1", "b1"}) + + registry := prometheus.NewRegistry() + registry.MustRegister(m1) + registry.MustRegister(m2) + + m1.With(prometheus.Labels{"a1": "v_a1", "b1": "v_b1"}).Inc() + m2.With(prometheus.Labels{"a1": "v_a2", "b1": "v_b2"}).Inc() + + metricsFamily, err := registry.Gather() + require.NoError(t, err) + require.Len(t, metricsFamily, 1) + + assert.Equal(t, name, *metricsFamily[0].Name) + require.Len(t, metricsFamily[0].Metric, 2) + + registeredMetric1 := metricsFamily[0].Metric[0] + assert.Equal(t, + []*dto.LabelPair{ + {Name: optional.Ptr("a1"), Value: optional.Ptr("v_a1")}, + {Name: optional.Ptr("b1"), Value: optional.Ptr("v_b1")}, + {Name: optional.Ptr("const_1"), Value: optional.Ptr("val_1")}, + }, + registeredMetric1.Label, + ) + + registeredMetric2 := metricsFamily[0].Metric[1] + assert.Equal(t, + []*dto.LabelPair{ + {Name: optional.Ptr("a1"), Value: optional.Ptr("v_a2")}, + {Name: optional.Ptr("b1"), Value: optional.Ptr("v_b2")}, + {Name: optional.Ptr("const_1"), Value: optional.Ptr("val_2")}, + }, + registeredMetric2.Label, + ) + }) } diff --git a/pkg/optional/optional.go b/pkg/optional/optional.go index 94e89bf6a04708abf853f2e8aaf8d7dbd9e99371..b33d76b98a94b20ca357d6e42d2658ac389ee883 100644 --- a/pkg/optional/optional.go +++ b/pkg/optional/optional.go @@ -8,3 +8,7 @@ var ( func Bool(v bool) *bool { return &v } + +func Ptr[T any](v T) *T { + return &v +}