From 052dfc214132a36af6cfc2a21e9e3e159e3eaea9 Mon Sep 17 00:00:00 2001 From: "M. J. Fromberger" Date: Fri, 1 Oct 2021 11:44:19 -0700 Subject: [PATCH] Add basic unit tests for the metrics package. --- metrics/metrics_test.go | 95 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 metrics/metrics_test.go diff --git a/metrics/metrics_test.go b/metrics/metrics_test.go new file mode 100644 index 0000000..722933d --- /dev/null +++ b/metrics/metrics_test.go @@ -0,0 +1,95 @@ +package metrics_test + +import ( + "testing" + + "github.com/creachadair/jrpc2/metrics" +) + +func getCount(m *metrics.M, name string) int64 { + c := make(map[string]int64) + m.Snapshot(metrics.Snapshot{Counter: c}) + return c[name] +} + +func getMax(m *metrics.M, name string) int64 { + mv := make(map[string]int64) + m.Snapshot(metrics.Snapshot{MaxValue: mv}) + return mv[name] +} + +func getLabel(m *metrics.M, name string) interface{} { + vs := make(map[string]interface{}) + m.Snapshot(metrics.Snapshot{Label: vs}) + return vs[name] +} + +func TestMetrics(t *testing.T) { + m := metrics.New() + wantCount := func(name string, want int64) { + t.Helper() + got := getCount(m, name) + if got != want { + t.Errorf("Counter %q: got %d, want %d", name, got, want) + } + } + wantMax := func(name string, want int64) { + t.Helper() + got := getMax(m, name) + if got != want { + t.Errorf("MaxValue %q: got %d, want %d", name, got, want) + } + } + wantLabel := func(name string, want interface{}) { + t.Helper() + got := getLabel(m, name) + if got != want { + t.Errorf("Label %q: got %v, want %v", name, got, want) + } + } + + wantCount("foo", 0) + m.Count("foo", 1) + wantCount("foo", 1) + m.Count("foo", 4) + wantCount("foo", 5) + m.Count("foo", -3) + wantCount("foo", 2) + + wantMax("max", 0) + m.SetMaxValue("max", 10) + wantMax("max", 10) + m.SetMaxValue("max", 5) + wantMax("max", 10) + m.SetMaxValue("max", 12) + wantMax("max", 12) + + m.CountAndSetMax("bar", 1) + wantCount("bar", 1) + wantMax("bar", 1) + m.CountAndSetMax("bar", 4) + wantCount("bar", 5) + wantMax("bar", 4) + m.CountAndSetMax("bar", -3) + wantCount("bar", 2) + wantMax("bar", 4) + m.CountAndSetMax("bar", 3) + wantCount("bar", 5) + wantMax("bar", 4) + + wantLabel("hey", nil) + m.SetLabel("hey", "you") + wantLabel("hey", "you") + m.SetLabel("hey", nil) + wantLabel("hey", nil) + + wantLabel("quux", nil) + m.EditLabel("quux", func(v interface{}) interface{} { + return "x" + }) + wantLabel("quux", "x") + m.EditLabel("quux", func(v interface{}) interface{} { + return v.(string) + "2" + }) + wantLabel("quux", "x2") +}