Skip to content

Commit 563edc8

Browse files
committed
test(vgpumonitor): add unit tests for metric-sending helpers
sendMetric and sendLegacyMetric in cmd/vGPUmonitor/metrics.go had no direct unit test coverage; they were only exercised indirectly through the collector-level Describe/Collect test. Add tests for both the success path and the error path (mismatched label count) of each helper. Signed-off-by: Aditya Raut <araut7798@gmail.com>
1 parent c5e99b6 commit 563edc8

1 file changed

Lines changed: 55 additions & 0 deletions

File tree

‎cmd/vGPUmonitor/metrics_test.go‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,3 +68,58 @@ func TestDescribeCollectSync(t *testing.T) {
6868
t.Errorf("Gather failed (legacy): %v", err)
6969
}
7070
}
71+
72+
func TestSendMetric(t *testing.T) {
73+
desc := prometheus.NewDesc("hami_test_metric", "test metric", []string{"label"}, nil)
74+
ch := make(chan prometheus.Metric, 1)
75+
76+
if err := sendMetric(ch, desc, prometheus.GaugeValue, 1, "value"); err != nil {
77+
t.Fatalf("sendMetric returned unexpected error: %v", err)
78+
}
79+
select {
80+
case <-ch:
81+
default:
82+
t.Fatal("expected a metric to be sent on the channel")
83+
}
84+
85+
// Supplying the wrong number of label values makes NewConstMetric fail,
86+
// and sendMetric must surface that error instead of sending on the channel.
87+
if err := sendMetric(ch, desc, prometheus.GaugeValue, 1); err == nil {
88+
t.Fatal("expected sendMetric to return an error for mismatched labels")
89+
}
90+
select {
91+
case <-ch:
92+
t.Fatal("did not expect a metric to be sent on error")
93+
default:
94+
}
95+
}
96+
97+
func TestSendLegacyMetric(t *testing.T) {
98+
ch := make(chan prometheus.Metric, 1)
99+
100+
// A nil descriptor means the legacy metric is disabled; sendLegacyMetric
101+
// must no-op rather than panic or send a metric.
102+
sendLegacyMetric(ch, nil, prometheus.GaugeValue, 1, "value")
103+
select {
104+
case <-ch:
105+
t.Fatal("did not expect a metric to be sent for a nil descriptor")
106+
default:
107+
}
108+
109+
desc := prometheus.NewDesc("hami_test_legacy_metric", "test legacy metric", []string{"label"}, nil)
110+
111+
// sendLegacyMetric logs and swallows errors from sendMetric rather than panicking.
112+
sendLegacyMetric(ch, desc, prometheus.GaugeValue, 1)
113+
select {
114+
case <-ch:
115+
t.Fatal("did not expect a metric to be sent when sendMetric errors")
116+
default:
117+
}
118+
119+
sendLegacyMetric(ch, desc, prometheus.GaugeValue, 1, "value")
120+
select {
121+
case <-ch:
122+
default:
123+
t.Fatal("expected a metric to be sent on the channel")
124+
}
125+
}

0 commit comments

Comments
 (0)