Antonio Mika
·
2026-10-25
1package router
2
3import (
4 "net/http"
5 "net/http/httptest"
6 "strings"
7 "testing"
8
9 "github.com/prometheus/client_golang/prometheus"
10)
11
12// metricValue reads a counter, or a histogram's count, from reg.
13func metricValue(t *testing.T, reg *prometheus.Registry, name string, labels map[string]string) float64 {
14 t.Helper()
15 families, err := reg.Gather()
16 if err != nil {
17 t.Fatalf("gather: %v", err)
18 }
19 for _, family := range families {
20 if family.GetName() != name {
21 continue
22 }
23 metrics:
24 for _, m := range family.GetMetric() {
25 for _, l := range m.GetLabel() {
26 if want, ok := labels[l.GetName()]; ok && want != l.GetValue() {
27 continue metrics
28 }
29 }
30 if h := m.GetHistogram(); h != nil {
31 return float64(h.GetSampleCount())
32 }
33 return m.GetCounter().GetValue()
34 }
35 }
36 return 0
37}
38
39func serve(h http.Handler, method, target string) *httptest.ResponseRecorder {
40 rec := httptest.NewRecorder()
41 h.ServeHTTP(rec, httptest.NewRequest(method, target, nil))
42 return rec
43}
44
45func TestUserMetricsSetUser(t *testing.T) {
46 reg := prometheus.NewRegistry()
47 m := NewUserMetrics("test", reg, UserMetricsOpts{})
48 h := m.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
49 SetUser(r, "alice")
50 w.WriteHeader(http.StatusCreated)
51 _, _ = w.Write([]byte("hello"))
52 }))
53
54 serve(h, http.MethodPost, "/")
55
56 labels := map[string]string{"app": "test", "user": "alice", "status": "201", "method": "POST"}
57 if got := metricValue(t, reg, "pico_http_requests_total", labels); got != 1 {
58 t.Errorf("requests = %v, want 1", got)
59 }
60 if got := metricValue(t, reg, "pico_http_request_duration_seconds", labels); got != 1 {
61 t.Errorf("duration samples = %v, want 1", got)
62 }
63 if got := metricValue(t, reg, "pico_http_response_bytes_total", map[string]string{"user": "alice"}); got != 5 {
64 t.Errorf("bytes = %v, want 5", got)
65 }
66}
67
68func TestUserMetricsSiteUser(t *testing.T) {
69 reg := prometheus.NewRegistry()
70 m := NewUserMetrics("test", reg, UserMetricsOpts{
71 SiteUser: func(r *http.Request) string { return strings.Split(r.Host, ".")[0] },
72 })
73 // The handler confirms alice on her first request; later ones stand in
74 // for cache hits that never reach it.
75 confirmed := false
76 h := m.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
77 if !confirmed && r.Host == "alice.example.com" {
78 SetUser(r, "alice")
79 confirmed = true
80 }
81 }))
82
83 serve(h, http.MethodGet, "http://ghost.example.com/")
84 serve(h, http.MethodGet, "http://alice.example.com/")
85 serve(h, http.MethodGet, "http://alice.example.com/")
86
87 if got := metricValue(t, reg, "pico_http_requests_total", map[string]string{"user": "alice"}); got != 2 {
88 t.Errorf("alice requests = %v, want 2", got)
89 }
90 if got := metricValue(t, reg, "pico_http_requests_total", map[string]string{"user": ""}); got != 1 {
91 t.Errorf("unlabeled requests = %v, want 1", got)
92 }
93 if got := metricValue(t, reg, "pico_http_requests_total", map[string]string{"user": "ghost"}); got != 0 {
94 t.Errorf("ghost requests = %v, want 0", got)
95 }
96}
97
98func TestUserMetricsTrustSuccess(t *testing.T) {
99 reg := prometheus.NewRegistry()
100 m := NewUserMetrics("test", reg, UserMetricsOpts{
101 SiteUser: func(r *http.Request) string { return strings.Split(r.Host, ".")[0] },
102 TrustSuccess: true,
103 })
104 h := m.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
105 if r.Host == "ghost.example.com" {
106 http.NotFound(w, r)
107 }
108 }))
109
110 serve(h, http.MethodGet, "http://bob.example.com/")
111 serve(h, http.MethodGet, "http://ghost.example.com/")
112
113 if got := metricValue(t, reg, "pico_http_requests_total", map[string]string{"user": "bob", "status": "200"}); got != 1 {
114 t.Errorf("bob requests = %v, want 1", got)
115 }
116 if got := metricValue(t, reg, "pico_http_requests_total", map[string]string{"user": "", "status": "404"}); got != 1 {
117 t.Errorf("unlabeled 404s = %v, want 1", got)
118 }
119}
120
121func TestUserMetricsMethod(t *testing.T) {
122 reg := prometheus.NewRegistry()
123 h := NewUserMetrics("test", reg, UserMetricsOpts{}).Handler(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
124
125 serve(h, "MADEUP", "/")
126
127 if got := metricValue(t, reg, "pico_http_requests_total", map[string]string{"method": "OTHER"}); got != 1 {
128 t.Errorf("OTHER requests = %v, want 1", got)
129 }
130}
131
132func TestUserMetricsHijack(t *testing.T) {
133 reg := prometheus.NewRegistry()
134 h := NewUserMetrics("test", reg, UserMetricsOpts{}).Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
135 hj, ok := w.(http.Hijacker)
136 if !ok {
137 t.Error("writer does not implement http.Hijacker")
138 return
139 }
140 conn, rw, err := hj.Hijack()
141 if err != nil {
142 t.Errorf("hijack: %v", err)
143 return
144 }
145 _, _ = rw.WriteString("HTTP/1.1 101 Switching Protocols\r\n\r\n")
146 _ = rw.Flush()
147 _ = conn.Close()
148 }))
149 srv := httptest.NewServer(h)
150 defer srv.Close()
151
152 resp, err := http.Get(srv.URL)
153 if err != nil {
154 t.Fatalf("get: %v", err)
155 }
156 _ = resp.Body.Close()
157
158 if got := metricValue(t, reg, "pico_http_requests_total", map[string]string{"status": "101"}); got != 1 {
159 t.Errorf("101 requests = %v, want 1", got)
160 }
161}