From f812de13202898b5fad892c500c18db6e0e7ae29 Mon Sep 17 00:00:00 2001 From: prateek Date: Thu, 2 Jan 2025 10:56:30 +1100 Subject: [PATCH] Fixes missing labesl from the generated metrics and adds a test for it --- metrics/serve.go | 3 ++- metrics/serve_test.go | 46 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/metrics/serve.go b/metrics/serve.go index 6f3a3d6..bd53c51 100644 --- a/metrics/serve.go +++ b/metrics/serve.go @@ -514,7 +514,8 @@ func (c *Collector) Run() error { labelValues = append(labelValues, split[1]) } - mutableState := &metricState{seriesCount: c.cfg.SeriesCount} + c.labelKeys = labelKeys + mutableState := &metricState{seriesCount: c.cfg.SeriesCount, labelValues: labelValues} // unsafe means you need to lock c.mu to use it. unsafeReadOnlyGetState := func() metricState { return *mutableState } diff --git a/metrics/serve_test.go b/metrics/serve_test.go index 39dc060..65fe2a2 100644 --- a/metrics/serve_test.go +++ b/metrics/serve_test.go @@ -414,3 +414,49 @@ func TestRunMetricsSpikeChange(t *testing.T) { } } } + +func TestCollectorLabels(t *testing.T) { + testCfg := Config{ + GaugeMetricCount: 1, + LabelCount: 2, + SeriesCount: 100, + MaxSeriesCount: 30, + MinSeriesCount: 10, + SpikeMultiplier: 1.5, + MetricLength: 1, + LabelLength: 1, + SeriesOperationMode: spikeOpMode, + ConstLabels: []string{"constLabel=test"}, + } + + assert.NoError(t, testCfg.Validate()) + + reg := prometheus.NewRegistry() + col := NewCollector(testCfg) + reg.MustRegister(col) + + go col.Run() + t.Cleanup(func() { + col.Stop(nil) + }) + + time.Sleep((2 * time.Second)) + metricsFamilies, err := reg.Gather() + assert.NotEmpty(t, metricsFamilies) + assert.NoError(t,err) + + for _, mf := range metricsFamilies { + for _, m := range mf.Metric { + labels := m.GetLabel() + labelMap := make(map[string]string) + for _, l := range labels { + labelMap[l.GetName()] = l.GetValue() + } + assert.Equal(t, "test", labelMap["constLabel"]) + assert.Contains(t, labelMap, "label_key_k_0") + assert.Contains(t, labelMap, "label_key_k_1") + assert.Contains(t, labelMap, "series_id") + assert.Contains(t, labelMap, "cycle_id") + } + } +} \ No newline at end of file