Fix: handle nil variableLabels in Desc.String() method and add tests for nil label values

Fixes #1684

Signed-off-by: Kemal Akkoyun <kakkoyun@gmail.com>
This commit is contained in:
Kemal Akkoyun 2024-11-19 17:01:47 +01:00
parent 291b0b0c42
commit 7b0b4c33bf
No known key found for this signature in database
GPG Key ID: F87BBA59F14F65D1
2 changed files with 42 additions and 6 deletions

View File

@ -189,7 +189,9 @@ func (d *Desc) String() string {
fmt.Sprintf("%s=%q", lp.GetName(), lp.GetValue()),
)
}
vlStrings := make([]string, 0, len(d.variableLabels.names))
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))
@ -197,6 +199,7 @@ func (d *Desc) String() string {
vlStrings = append(vlStrings, vl)
}
}
}
return fmt.Sprintf(
"Desc{fqName: %q, help: %q, constLabels: {%s}, variableLabels: {%s}}",
d.fqName,

View File

@ -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())
}
}