From 3722d1205149f67f8a87490c51c6871a92fa1dae Mon Sep 17 00:00:00 2001 From: Emil Madsen Date: Fri, 1 May 2020 11:36:47 +0200 Subject: [PATCH] Added cumulative counter test --- exporter/metrics_test.go | 42 +++++++++++++++++++++++++++++++++++----- 1 file changed, 37 insertions(+), 5 deletions(-) diff --git a/exporter/metrics_test.go b/exporter/metrics_test.go index b134e01e..c053d4a0 100644 --- a/exporter/metrics_test.go +++ b/exporter/metrics_test.go @@ -77,6 +77,29 @@ func TestCounter(t *testing.T) { } } +func TestCounterValue(t *testing.T) { + regex := initCumulativeRegex(t) + counterCfg := newMetricConfig(t, &configuration.MetricConfig{ + Name: "rainfall", + Value: "{{.rainfall}}", + }) + counter := NewCounterMetric(counterCfg, regex, nil) + + counter.ProcessMatch("Rainfall in Berlin: 32", nil) + counter.ProcessMatch("Rainfall in Berlin: 5", nil) + + switch c := counter.Collector().(type) { + case prometheus.Counter: + m := io_prometheus_client.Metric{} + c.Write(&m) + if *m.Counter.Value != float64(37) { + t.Errorf("Expected 37 as counter value, but got %v.", *m.Counter.Value) + } + default: + t.Errorf("Unexpected type of metric: %v", reflect.TypeOf(c)) + } +} + func TestLogfileLabel(t *testing.T) { regex := initCounterRegex(t) counterCfg := newMetricConfig(t, &configuration.MetricConfig{ @@ -163,16 +186,16 @@ func TestGauge(t *testing.T) { } func TestGaugeCumulative(t *testing.T) { - regex := initGaugeRegex(t) + regex := initCumulativeRegex(t) gaugeCfg := newMetricConfig(t, &configuration.MetricConfig{ - Name: "temperature", - Value: "{{.temperature}}", + Name: "rainfall", + Value: "{{.rainfall}}", Cumulative: true, }) gauge := NewGaugeMetric(gaugeCfg, regex, nil) - gauge.ProcessMatch("Temperature in Berlin: 32", nil) - gauge.ProcessMatch("Temperature in Moscow: -5", nil) + gauge.ProcessMatch("Rainfall in Berlin: 32", nil) + gauge.ProcessMatch("Rainfall in Moscow: -5", nil) switch c := gauge.Collector().(type) { case prometheus.Gauge: @@ -226,6 +249,15 @@ func initGaugeRegex(t *testing.T) *oniguruma.Regex { return regex } +func initCumulativeRegex(t *testing.T) *oniguruma.Regex { + patterns := loadPatternDir(t) + regex, err := Compile("Rainfall in %{WORD:city}: %{INT:rainfall}", patterns) + if err != nil { + t.Error(err) + } + return regex +} + func newMetricConfig(t *testing.T, cfg *configuration.MetricConfig) *configuration.MetricConfig { // Handle default for counter's value if cfg.Type == "counter" && len(cfg.Value) == 0 {