MCPcopy
hub / github.com/prometheus/client_golang / TestGoCollectorMemStats

Function TestGoCollectorMemStats

prometheus/go_collector_go116_test.go:27–118  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

25)
26
27func TestGoCollectorMemStats(t *testing.T) {
28 var (
29 c = NewGoCollector().(*goCollector)
30 got uint64
31 )
32
33 checkCollect := func(want uint64) {
34 metricCh := make(chan Metric)
35 endCh := make(chan struct{})
36
37 go func() {
38 c.Collect(metricCh)
39 close(endCh)
40 }()
41 Collect:
42 for {
43 select {
44 case metric := <-metricCh:
45 if metric.Desc().fqName != "go_memstats_alloc_bytes" {
46 continue Collect
47 }
48 pb := &dto.Metric{}
49 metric.Write(pb)
50 got = uint64(pb.GetGauge().GetValue())
51 case <-endCh:
52 break Collect
53 }
54 }
55 if want != got {
56 t.Errorf("unexpected value of go_memstats_alloc_bytes, want %d, got %d", want, got)
57 }
58 }
59
60 // Speed up the timing to make the test faster.
61 c.msMaxWait = 5 * time.Millisecond
62 c.msMaxAge = 50 * time.Millisecond
63
64 // Scenario 1: msRead responds slowly, no previous memstats available,
65 // msRead is executed anyway.
66 c.msRead = func(ms *runtime.MemStats) {
67 time.Sleep(20 * time.Millisecond)
68 ms.Alloc = 1
69 }
70 checkCollect(1)
71 // Now msLast is set.
72 c.msMtx.Lock()
73 if want, got := uint64(1), c.msLast.Alloc; want != got {
74 t.Errorf("unexpected of msLast.Alloc, want %d, got %d", want, got)
75 }
76 c.msMtx.Unlock()
77
78 // Scenario 2: msRead responds fast, previous memstats available, new
79 // value collected.
80 c.msRead = func(ms *runtime.MemStats) {
81 ms.Alloc = 2
82 }
83 checkCollect(2)
84 // msLast is set, too.

Callers

nothing calls this directly

Calls 5

NewGoCollectorFunction · 0.70
CollectMethod · 0.65
DescMethod · 0.65
WriteMethod · 0.65
GetValueMethod · 0.45

Tested by

no test coverage detected