|
| 1 | +/* |
| 2 | + Copyright 2022 GitHub Inc. |
| 3 | + See https://github.com/github/gh-ost/blob/master/LICENSE |
| 4 | +*/ |
| 5 | + |
| 6 | +package metrics |
| 7 | + |
| 8 | +import ( |
| 9 | + "context" |
| 10 | + "runtime" |
| 11 | + "testing" |
| 12 | + "time" |
| 13 | +) |
| 14 | + |
| 15 | +type gaugeSpy struct { |
| 16 | + names []string |
| 17 | + values []float64 |
| 18 | +} |
| 19 | + |
| 20 | +func (g *gaugeSpy) Gauge(name string, value float64, _ ...string) { |
| 21 | + g.names = append(g.names, name) |
| 22 | + g.values = append(g.values, value) |
| 23 | +} |
| 24 | + |
| 25 | +func TestEmitGoRuntimeGauges(t *testing.T) { |
| 26 | + spy := &gaugeSpy{} |
| 27 | + m := &runtime.MemStats{ |
| 28 | + Alloc: 100, |
| 29 | + Sys: 200, |
| 30 | + HeapInuse: 300, |
| 31 | + NumGC: 7, |
| 32 | + PauseTotalNs: 42, |
| 33 | + } |
| 34 | + EmitGoRuntimeGauges(spy, m, 123) |
| 35 | + |
| 36 | + wantNames := []string{ |
| 37 | + "go_runtime.alloc_bytes", |
| 38 | + "go_runtime.sys_bytes", |
| 39 | + "go_runtime.heap_inuse_bytes", |
| 40 | + "go_runtime.num_gc", |
| 41 | + "go_runtime.gc_pause_total_ns", |
| 42 | + "go_runtime.goroutines", |
| 43 | + } |
| 44 | + wantVals := []float64{100, 200, 300, 7, 42, 123} |
| 45 | + |
| 46 | + if len(spy.names) != len(wantNames) { |
| 47 | + t.Fatalf("got %d gauges, want %d", len(spy.names), len(wantNames)) |
| 48 | + } |
| 49 | + for i := range wantNames { |
| 50 | + if spy.names[i] != wantNames[i] || spy.values[i] != wantVals[i] { |
| 51 | + t.Fatalf("[%d] got %s=%v want %s=%v", i, spy.names[i], spy.values[i], wantNames[i], wantVals[i]) |
| 52 | + } |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +func TestEmitGoRuntimeGauges_nilSafe(t *testing.T) { |
| 57 | + EmitGoRuntimeGauges(nil, &runtime.MemStats{}, 1) |
| 58 | + EmitGoRuntimeGauges(&gaugeSpy{}, nil, 1) |
| 59 | +} |
| 60 | + |
| 61 | +func TestStartGoRuntimeReporter_stopsOnCancel(t *testing.T) { |
| 62 | + ctx, cancel := context.WithCancel(context.Background()) |
| 63 | + c := &Client{} // sd nil — should not start |
| 64 | + StartGoRuntimeReporter(ctx, c, time.Millisecond) |
| 65 | + cancel() |
| 66 | + time.Sleep(20 * time.Millisecond) |
| 67 | +} |
0 commit comments