From 1880f1bc335b2c72d8186563e661db56e71c24bf Mon Sep 17 00:00:00 2001 From: Kemal Akkoyun Date: Mon, 25 Nov 2024 11:13:35 +0100 Subject: [PATCH] Fix: handle nil variableLabels in Desc.String() method and add tests for nil label values (#1687) Fixes #1684 Signed-off-by: Kemal Akkoyun --- prometheus/desc.go | 15 +++++++++------ prometheus/desc_test.go | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 6 deletions(-) diff --git a/prometheus/desc.go b/prometheus/desc.go index 68ffe3c..ad34711 100644 --- a/prometheus/desc.go +++ b/prometheus/desc.go @@ -189,12 +189,15 @@ func (d *Desc) String() string { fmt.Sprintf("%s=%q", lp.GetName(), lp.GetValue()), ) } - vlStrings := make([]string, 0, len(d.variableLabels.names)) - for _, vl := range d.variableLabels.names { - if fn, ok := d.variableLabels.labelConstraints[vl]; ok && fn != nil { - vlStrings = append(vlStrings, fmt.Sprintf("c(%s)", vl)) - } else { - vlStrings = append(vlStrings, vl) + vlStrings := []string{} + if d.variableLabels != nil { + vlStrings = make([]string, 0, len(d.variableLabels.names)) + for _, vl := range d.variableLabels.names { + if fn, ok := d.variableLabels.labelConstraints[vl]; ok && fn != nil { + vlStrings = append(vlStrings, fmt.Sprintf("c(%s)", vl)) + } else { + vlStrings = append(vlStrings, vl) + } } } return fmt.Sprintf( diff --git a/prometheus/desc_test.go b/prometheus/desc_test.go index 5f854db..5a84290 100644 --- a/prometheus/desc_test.go +++ b/prometheus/desc_test.go @@ -28,3 +28,36 @@ func TestNewDescInvalidLabelValues(t *testing.T) { t.Errorf("NewDesc: expected error because: %s", desc.err) } } + +func TestNewDescNilLabelValues(t *testing.T) { + desc := NewDesc( + "sample_label", + "sample label", + nil, + nil, + ) + if desc.err != nil { + t.Errorf("NewDesc: unexpected error: %s", desc.err) + } +} + +func TestNewDescWithNilLabelValues_String(t *testing.T) { + desc := NewDesc( + "sample_label", + "sample label", + nil, + nil, + ) + if desc.String() != `Desc{fqName: "sample_label", help: "sample label", constLabels: {}, variableLabels: {}}` { + t.Errorf("String: unexpected output: %s", desc.String()) + } +} + +func TestNewInvalidDesc_String(t *testing.T) { + desc := NewInvalidDesc( + nil, + ) + if desc.String() != `Desc{fqName: "", help: "", constLabels: {}, variableLabels: {}}` { + t.Errorf("String: unexpected output: %s", desc.String()) + } +}