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{Owner: siteProject(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 count := func(name string, labels map[string]string) float64 {
46 var total float64
47 for _, family := range families {
48 if family.GetName() != name {
49 continue
50 }
51 metrics:
52 for _, m := range family.GetMetric() {
53 matched := 0
54 for _, l := range m.GetLabel() {
55 if want, ok := labels[l.GetName()]; ok {
56 if want != l.GetValue() {
57 continue metrics
58 }
59 matched++
60 }
61 }
62 if matched == len(labels) {
63 total += m.GetCounter().GetValue()
64 }
65 }
66 }
67 return total
68 }
69 if got := count("pico_http_requests_total", map[string]string{"user": user.Name}); got != 2 {
70 t.Errorf("requests for %s = %v, want 2", user.Name, got)
71 }
72 if got := count("pico_http_requests_total", map[string]string{"user": user.Name, "resource": "test"}); got != 2 {
73 t.Errorf("requests for %s/test = %v, want 2", user.Name, got)
74 }
75}