|
| 1 | +package metrics_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "testing" |
| 5 | + |
| 6 | + "github.com/creachadair/jrpc2/metrics" |
| 7 | +) |
| 8 | + |
| 9 | +func getCount(m *metrics.M, name string) int64 { |
| 10 | + c := make(map[string]int64) |
| 11 | + m.Snapshot(metrics.Snapshot{Counter: c}) |
| 12 | + return c[name] |
| 13 | +} |
| 14 | + |
| 15 | +func getMax(m *metrics.M, name string) int64 { |
| 16 | + mv := make(map[string]int64) |
| 17 | + m.Snapshot(metrics.Snapshot{MaxValue: mv}) |
| 18 | + return mv[name] |
| 19 | +} |
| 20 | + |
| 21 | +func getLabel(m *metrics.M, name string) interface{} { |
| 22 | + vs := make(map[string]interface{}) |
| 23 | + m.Snapshot(metrics.Snapshot{Label: vs}) |
| 24 | + return vs[name] |
| 25 | +} |
| 26 | + |
| 27 | +func TestMetrics(t *testing.T) { |
| 28 | + m := metrics.New() |
| 29 | + wantCount := func(name string, want int64) { |
| 30 | + t.Helper() |
| 31 | + got := getCount(m, name) |
| 32 | + if got != want { |
| 33 | + t.Errorf("Counter %q: got %d, want %d", name, got, want) |
| 34 | + } |
| 35 | + } |
| 36 | + wantMax := func(name string, want int64) { |
| 37 | + t.Helper() |
| 38 | + got := getMax(m, name) |
| 39 | + if got != want { |
| 40 | + t.Errorf("MaxValue %q: got %d, want %d", name, got, want) |
| 41 | + } |
| 42 | + } |
| 43 | + wantLabel := func(name string, want interface{}) { |
| 44 | + t.Helper() |
| 45 | + got := getLabel(m, name) |
| 46 | + if got != want { |
| 47 | + t.Errorf("Label %q: got %v, want %v", name, got, want) |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + wantCount("foo", 0) |
| 52 | + m.Count("foo", 1) |
| 53 | + wantCount("foo", 1) |
| 54 | + m.Count("foo", 4) |
| 55 | + wantCount("foo", 5) |
| 56 | + m.Count("foo", -3) |
| 57 | + wantCount("foo", 2) |
| 58 | + |
| 59 | + wantMax("max", 0) |
| 60 | + m.SetMaxValue("max", 10) |
| 61 | + wantMax("max", 10) |
| 62 | + m.SetMaxValue("max", 5) |
| 63 | + wantMax("max", 10) |
| 64 | + m.SetMaxValue("max", 12) |
| 65 | + wantMax("max", 12) |
| 66 | + |
| 67 | + m.CountAndSetMax("bar", 1) |
| 68 | + wantCount("bar", 1) |
| 69 | + wantMax("bar", 1) |
| 70 | + m.CountAndSetMax("bar", 4) |
| 71 | + wantCount("bar", 5) |
| 72 | + wantMax("bar", 4) |
| 73 | + m.CountAndSetMax("bar", -3) |
| 74 | + wantCount("bar", 2) |
| 75 | + wantMax("bar", 4) |
| 76 | + m.CountAndSetMax("bar", 3) |
| 77 | + wantCount("bar", 5) |
| 78 | + wantMax("bar", 4) |
| 79 | + |
| 80 | + wantLabel("hey", nil) |
| 81 | + m.SetLabel("hey", "you") |
| 82 | + wantLabel("hey", "you") |
| 83 | + m.SetLabel("hey", nil) |
| 84 | + wantLabel("hey", nil) |
| 85 | + |
| 86 | + wantLabel("quux", nil) |
| 87 | + m.EditLabel("quux", func(v interface{}) interface{} { |
| 88 | + return "x" |
| 89 | + }) |
| 90 | + wantLabel("quux", "x") |
| 91 | + m.EditLabel("quux", func(v interface{}) interface{} { |
| 92 | + return v.(string) + "2" |
| 93 | + }) |
| 94 | + wantLabel("quux", "x2") |
| 95 | +} |
0 commit comments