github.com/anycable/anycable-go@v1.5.1/metrics/prometheus_test.go (about) 1 package metrics 2 3 import ( 4 "log/slog" 5 "net/http" 6 "net/http/httptest" 7 "regexp" 8 "strings" 9 "testing" 10 11 "github.com/stretchr/testify/assert" 12 "github.com/stretchr/testify/require" 13 ) 14 15 func TestPrometheus(t *testing.T) { 16 m := NewMetrics(nil, 10, slog.Default()) 17 18 m.RegisterCounter("test_total", "Total number of smth") 19 m.RegisterCounter("any_total", "Total number of anything") 20 m.RegisterGauge("tests", "Number of active smth") 21 m.RegisterGauge("any_tests", "Number of active anything") 22 23 m.Gauge("tests").Set(123) 24 m.Counter("test_total").Add(3) 25 26 actual := m.Prometheus() 27 28 assert.Contains(t, actual, 29 ` 30 # HELP anycable_go_test_total Total number of smth 31 # TYPE anycable_go_test_total counter 32 anycable_go_test_total 3 33 `, 34 ) 35 36 assert.Contains(t, actual, 37 ` 38 # HELP anycable_go_any_total Total number of anything 39 # TYPE anycable_go_any_total counter 40 anycable_go_any_total 0 41 `, 42 ) 43 44 assert.Contains(t, actual, 45 ` 46 # HELP anycable_go_tests Number of active smth 47 # TYPE anycable_go_tests gauge 48 anycable_go_tests 123 49 `, 50 ) 51 52 assert.Contains(t, actual, 53 ` 54 # HELP anycable_go_any_tests Number of active anything 55 # TYPE anycable_go_any_tests gauge 56 anycable_go_any_tests 0 57 `, 58 ) 59 } 60 61 func TestPrometheusWithTags(t *testing.T) { 62 m := NewMetrics(nil, 10, slog.Default()) 63 m.DefaultTags(map[string]string{"env": "dev", "instance": "R2D2"}) 64 65 m.RegisterCounter("test_total", "Total number of smth") 66 m.RegisterGauge("tests", "Number of active smth") 67 68 m.Gauge("tests").Set(123) 69 m.Counter("test_total").Add(3) 70 71 actual := m.Prometheus() 72 73 r := regexp.MustCompile(`anycable_go_test_total{(.+)}\s+(\d+)`) 74 matches := r.FindStringSubmatch(actual) 75 76 require.NotNil(t, matches) 77 78 tagsStr := matches[1] 79 valStr := matches[2] 80 81 tags := strings.Split(tagsStr, ", ") 82 83 assert.Contains(t, tags, `env="dev"`) 84 assert.Contains(t, tags, `instance="R2D2"`) 85 86 assert.Equal(t, "3", valStr) 87 } 88 89 func TestPrometheusHandler(t *testing.T) { 90 m := NewMetrics(nil, 10, slog.Default()) 91 92 m.RegisterCounter("test_total", "Total number of smth") 93 m.RegisterCounter("any_total", "Total number of anything") 94 95 m.Counter("test_total").Add(3) 96 97 req, err := http.NewRequest("GET", "/", nil) 98 if err != nil { 99 t.Fatal(err) 100 } 101 102 rr := httptest.NewRecorder() 103 handler := http.HandlerFunc(m.PrometheusHandler) 104 105 handler.ServeHTTP(rr, req) 106 107 assert.Equal(t, http.StatusOK, rr.Code) 108 109 body := rr.Body.String() 110 111 assert.Contains(t, body, "anycable_go_test_total 3") 112 assert.Contains(t, body, "anycable_go_any_total 0") 113 }