Skip to content

Commit ff4f508

Browse files
kakkoyunamberpixels
authored andcommitted
Fix: handle nil variableLabels in Desc.String() method and add tests for nil label values (prometheus#1687)
Fixes prometheus#1684 Signed-off-by: Kemal Akkoyun <[email protected]> Signed-off-by: Eugene <[email protected]>
1 parent fdc1865 commit ff4f508

File tree

2 files changed

+42
-6
lines changed

2 files changed

+42
-6
lines changed

prometheus/desc.go

+9-6
Original file line numberDiff line numberDiff line change
@@ -189,12 +189,15 @@ func (d *Desc) String() string {
189189
fmt.Sprintf("%s=%q", lp.GetName(), lp.GetValue()),
190190
)
191191
}
192-
vlStrings := make([]string, 0, len(d.variableLabels.names))
193-
for _, vl := range d.variableLabels.names {
194-
if fn, ok := d.variableLabels.labelConstraints[vl]; ok && fn != nil {
195-
vlStrings = append(vlStrings, fmt.Sprintf("c(%s)", vl))
196-
} else {
197-
vlStrings = append(vlStrings, vl)
192+
vlStrings := []string{}
193+
if d.variableLabels != nil {
194+
vlStrings = make([]string, 0, len(d.variableLabels.names))
195+
for _, vl := range d.variableLabels.names {
196+
if fn, ok := d.variableLabels.labelConstraints[vl]; ok && fn != nil {
197+
vlStrings = append(vlStrings, fmt.Sprintf("c(%s)", vl))
198+
} else {
199+
vlStrings = append(vlStrings, vl)
200+
}
198201
}
199202
}
200203
return fmt.Sprintf(

prometheus/desc_test.go

+33
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,36 @@ func TestNewDescInvalidLabelValues(t *testing.T) {
2828
t.Errorf("NewDesc: expected error because: %s", desc.err)
2929
}
3030
}
31+
32+
func TestNewDescNilLabelValues(t *testing.T) {
33+
desc := NewDesc(
34+
"sample_label",
35+
"sample label",
36+
nil,
37+
nil,
38+
)
39+
if desc.err != nil {
40+
t.Errorf("NewDesc: unexpected error: %s", desc.err)
41+
}
42+
}
43+
44+
func TestNewDescWithNilLabelValues_String(t *testing.T) {
45+
desc := NewDesc(
46+
"sample_label",
47+
"sample label",
48+
nil,
49+
nil,
50+
)
51+
if desc.String() != `Desc{fqName: "sample_label", help: "sample label", constLabels: {}, variableLabels: {}}` {
52+
t.Errorf("String: unexpected output: %s", desc.String())
53+
}
54+
}
55+
56+
func TestNewInvalidDesc_String(t *testing.T) {
57+
desc := NewInvalidDesc(
58+
nil,
59+
)
60+
if desc.String() != `Desc{fqName: "", help: "", constLabels: {}, variableLabels: {}}` {
61+
t.Errorf("String: unexpected output: %s", desc.String())
62+
}
63+
}

0 commit comments

Comments
 (0)