Debian Codegraph @

prometheus/collectorfunc_test.go

raw
1 // Copyright 2025 The Prometheus Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package prometheus
15
16 import "testing"
17
18 func TestCollectorFunc(t *testing.T) {
19 testDesc := NewDesc(
20 "test_metric",
21 "A test metric",
22 nil, nil,
23 )
24
25 cf := CollectorFunc(func(ch chan<- Metric) {
26 ch <- MustNewConstMetric(
27 testDesc,
28 GaugeValue,
29 42.0,
30 )
31 })
32
33 ch := make(chan Metric, 1)
34 cf.Collect(ch)
35 close(ch)
36
37 metric := <-ch
38 if metric == nil {
39 t.Fatal("Expected metric, got nil")
40 }
41
42 descCh := make(chan *Desc, 1)
43 cf.Describe(descCh)
44 close(descCh)
45
46 desc := <-descCh
47 if desc == nil {
48 t.Fatal("Expected desc, got nil")
49 }
50
51 if desc.String() != testDesc.String() {
52 t.Fatalf("Expected %s, got %s", testDesc.String(), desc.String())
53 }
54 }
55
56 func TestCollectorFuncWithRegistry(t *testing.T) {
57 reg := NewPedanticRegistry()
58
59 cf := CollectorFunc(func(ch chan<- Metric) {
60 ch <- MustNewConstMetric(
61 NewDesc(
62 "test_metric",
63 "A test metric",
64 nil, nil,
65 ),
66 GaugeValue,
67 42.0,
68 )
69 })
70
71 if err := reg.Register(cf); err != nil {
72 t.Errorf("Failed to register CollectorFunc: %v", err)
73 }
74
75 collectedMetrics, err := reg.Gather()
76 if err != nil {
77 t.Errorf("Failed to gather metrics: %v", err)
78 }
79
80 if len(collectedMetrics) != 1 {
81 t.Errorf("Expected 1 metric family, got %d", len(collectedMetrics))
82 }
83 }