File: prometheus_test.go

package info (click to toggle)
golang-ptutil 0.0~git20240710.6c4d8ed-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 100 kB
  • sloc: makefile: 2
file content (85 lines) | stat: -rw-r--r-- 1,762 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package safeprom

import (
	"bufio"
	"net/http"
	"net/http/httptest"
	"strconv"
	"strings"
	"testing"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

func TestIncVecWithLabelValues(t *testing.T) {
	ts := httptest.NewServer(promhttp.Handler())
	defer ts.Close()

	metricName := "label_values"
	usersTotal := NewCounterVecRegistered(
		prometheus.CounterOpts{
			Name: metricName,
		},
		[]string{"status"},
	)

	for i := 0; i < 8; i++ {
		usersTotal.WithLabelValues("active").Inc()
		expectedValue(t, ts.URL, metricName, 8)
	}

	usersTotal.WithLabelValues("active").Inc()
	expectedValue(t, ts.URL, metricName, 16)
}

func TestIncVecWith(t *testing.T) {
	ts := httptest.NewServer(promhttp.Handler())
	defer ts.Close()

	metricName := "with"
	usersTotal := NewCounterVecRegistered(
		prometheus.CounterOpts{
			Name: metricName,
		},
		[]string{"status"},
	)

	for i := 0; i < 8; i++ {
		usersTotal.With(prometheus.Labels{"status": "active"}).Inc()
		expectedValue(t, ts.URL, metricName, 8)
	}

	usersTotal.With(prometheus.Labels{"status": "active"}).Inc()
	expectedValue(t, ts.URL, metricName, 16)
}

func expectedValue(t *testing.T, url string, metric string, expected int) {
	res, err := http.Get(url)
	if err != nil {
		t.Fatal(err)
	}
	defer res.Body.Close()

	value := -1
	scanner := bufio.NewScanner(res.Body)
	for scanner.Scan() {
		line := scanner.Text()
		if !strings.HasPrefix(line, metric) {
			continue
		}
		parts := strings.Split(line, " ")
		value, err = strconv.Atoi(parts[len(parts)-1])
		if err != nil {
			t.Fatal(err)
		}
	}

	if value == -1 {
		t.Fatal("Metric", metric, "was not present")
	}

	if value != expected {
		t.Error("Metric value is not", expected, ":", value)
	}
}