Skip to content

Commit

Permalink
Fix: handle nil variableLabels in Desc.String() method and add tests …
Browse files Browse the repository at this point in the history
…for nil label values

Fixes #1684

Signed-off-by: Kemal Akkoyun <[email protected]>
  • Loading branch information
kakkoyun committed Nov 19, 2024
1 parent 291b0b0 commit 7b0b4c3
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 6 deletions.
15 changes: 9 additions & 6 deletions prometheus/desc.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
33 changes: 33 additions & 0 deletions prometheus/desc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
}

0 comments on commit 7b0b4c3

Please sign in to comment.