package api_test import ( "context" "io" "net/http" "net/http/httptest" "strconv" "strings" "testing" "time" "github.com/google/uuid" "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" ) // scrape returns the value of every series of the API's metrics, keyed by // name and labels as the text format prints them. func (e *env) scrape(t *testing.T) map[string]float64 { t.Helper() rec := httptest.NewRecorder() e.metrics.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/metrics", nil)) if rec.Code != http.StatusOK || !strings.HasPrefix(rec.Header().Get("Content-Type"), "text/plain") { t.Fatalf("metrics answered %d %q", rec.Code, rec.Header().Get("Content-Type")) } body, _ := io.ReadAll(rec.Body) out := map[string]float64{} for _, line := range strings.Split(string(body), "\n") { if line == "" || strings.HasPrefix(line, "#") { continue } i := strings.LastIndexByte(line, ' ') v, err := strconv.ParseFloat(line[i+1:], 64) if err != nil { t.Fatalf("bad metric line %q", line) } out[line[:i]] = v } return out } func TestMetrics(t *testing.T) { e := newEnv(t) key := uniq("metrics-") tok, region := e.platformChecker(t, key) owner := e.browser(t) owner.signup("o@"+uniq("id")+".test", uniq("id-")) _, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{ "name": "m", "type": "tcp", "target": "example.com:443", "interval_seconds": 3600, "regions": []string{region}, }) monitor := uuid.MustParse(m["id"].(string)) client := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "test").WithHTTPClient(e.srv.Client()) at := time.Now().Truncate(time.Millisecond) batch := []agentapi.Result{ {MonitorID: monitor, ScheduledAt: at, StartedAt: at, OK: true}, {MonitorID: monitor, ScheduledAt: at.Add(time.Second), StartedAt: at.Add(time.Second), OK: false}, {MonitorID: uuid.New(), ScheduledAt: at, StartedAt: at, OK: true}, } for range 2 { if err := client.Report(context.Background(), batch); err != nil { t.Fatal(err) } } got := e.scrape(t) for series, want := range map[string]float64{ `uptimesebi_check_results_total{ok="true",region="` + key + `"}`: 1, `uptimesebi_check_results_total{ok="false",region="` + key + `"}`: 1, `uptimesebi_check_results_rejected_total{reason="duplicate"}`: 3, `uptimesebi_check_results_rejected_total{reason="unknown_monitor"}`: 1, `uptimesebi_checker_instances{region="` + key + `"}`: 0, `uptimesebi_platform_metrics_error`: 0, } { if v, ok := got[series]; !ok || v != want { t.Errorf("%s = %v (present %v), want %v", series, v, ok, want) } } // Other tests share the database, so totals are at least ours. for series, least := range map[string]float64{ `uptimesebi_orgs`: 1, `uptimesebi_users`: 1, `uptimesebi_monitors{enabled="true",type="tcp"}`: 1, `uptimesebi_regions{online="false"}`: 1, } { if got[series] < least { t.Errorf("%s = %v, want at least %v", series, got[series], least) } } }