Skip to content

Commit

Permalink
Using promauto to initialize the metric and testutil in tests
Browse files Browse the repository at this point in the history
  • Loading branch information
pBiczysko committed Oct 26, 2019
1 parent 256357e commit 140d01b
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 11 deletions.
4 changes: 2 additions & 2 deletions metrics/prometheus.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package metrics
import (
"github.com/eko/gocache/codec"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
)

const (
Expand All @@ -20,15 +21,14 @@ type Prometheus struct {
}

func initCacheCollector(namespace string) *prometheus.GaugeVec {
c := prometheus.NewGaugeVec(
c := promauto.NewGaugeVec(
prometheus.GaugeOpts{
Name: "collector",
Namespace: namespace,
Help: "This represent the number of items in cache",
},
[]string{"service", "store", "metric"},
)
prometheus.MustRegister(c)
return c
}

Expand Down
22 changes: 13 additions & 9 deletions metrics/prometheus_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
mocksCodec "github.com/eko/gocache/test/mocks/codec"
mocksStore "github.com/eko/gocache/test/mocks/store"
"github.com/prometheus/client_golang/prometheus"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/client_golang/prometheus/testutil"
"github.com/stretchr/testify/assert"
)

Expand All @@ -33,11 +33,13 @@ func TestRecord(t *testing.T) {
metrics.Record("redis", "hit_count", 6)

// Then
dtoMetric := &dto.Metric{}
metric, _ := metrics.collector.GetMetricWithLabelValues("my-test-service-name", "redis", "hit_count")
metric.Write(dtoMetric)
metric, err := metrics.collector.GetMetricWithLabelValues("my-test-service-name", "redis", "hit_count")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
v := testutil.ToFloat64(metric)

assert.Equal(t, float64(6), dtoMetric.GetGauge().GetValue())
assert.Equal(t, float64(6), v)
}

func TestRecordFromCodec(t *testing.T) {
Expand Down Expand Up @@ -105,10 +107,12 @@ func TestRecordFromCodec(t *testing.T) {
}

for _, tc := range testCases {
dtoMetric := &dto.Metric{}
metric, _ := metrics.collector.GetMetricWithLabelValues("my-test-service-name", "redis", tc.metricName)
metric.Write(dtoMetric)
metric, err := metrics.collector.GetMetricWithLabelValues("my-test-service-name", "redis", tc.metricName)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
v := testutil.ToFloat64(metric)

assert.Equal(t, tc.expected, dtoMetric.GetGauge().GetValue())
assert.Equal(t, tc.expected, v)
}
}

0 comments on commit 140d01b

Please sign in to comment.