main pico / pkg / apps / pgs / site_metrics_test.go
Antonio Mika  ·  2026-10-25
 1package pgs
 2
 3import (
 4	"log/slog"
 5	"net/http/httptest"
 6	"strings"
 7	"testing"
 8
 9	"github.com/picosh/pico/pkg/shared"
10	"github.com/picosh/pico/pkg/shared/router"
11	"github.com/picosh/pico/pkg/storage"
12	"github.com/prometheus/client_golang/prometheus"
13)
14
15func TestSiteMetricsCountCacheHits(t *testing.T) {
16	logger := slog.New(slog.DiscardHandler)
17	dbpool := NewPgsDb(logger)
18	user := dbpool.Users[0]
19	st, err := storage.NewStorageMemory(map[string]map[string]string{
20		shared.GetAssetBucketName(user.ID): {"/test/index.html": "hello"},
21	})
22	if err != nil {
23		t.Fatal(err)
24	}
25	cfg := NewConfig(logger, dbpool, newTestStorage(st), discardPubsub{})
26	cfg.Domain = "pgs.test"
27	httpCache, _ := NewPgsHttpCache(cfg, newWebRouter(cfg))
28	reg := prometheus.NewRegistry()
29	h := router.NewUserMetrics("pgs", reg, router.UserMetricsOpts{SiteUser: siteUser(cfg)}).Handler(httpCache)
30
31	var statuses []string
32	for range 2 {
33		rec := httptest.NewRecorder()
34		h.ServeHTTP(rec, httptest.NewRequest("GET", dbpool.mkpath("/"), nil))
35		statuses = append(statuses, rec.Header().Get("cache-status"))
36	}
37	if !strings.Contains(statuses[1], "hit") {
38		t.Fatalf("second request was not a cache hit: %q", statuses)
39	}
40
41	families, err := reg.Gather()
42	if err != nil {
43		t.Fatal(err)
44	}
45	var count float64
46	for _, family := range families {
47		if family.GetName() != "pico_http_requests_total" {
48			continue
49		}
50		for _, m := range family.GetMetric() {
51			for _, l := range m.GetLabel() {
52				if l.GetName() == "user" && l.GetValue() == user.Name {
53					count += m.GetCounter().GetValue()
54				}
55			}
56		}
57	}
58	if count != 2 {
59		t.Errorf("requests for %s = %v, want 2", user.Name, count)
60	}
61}