package api import ( "io" "net/http" "net/http/httptest" "strings" "testing" "time" ) func scrape(t *testing.T, f *fixture, method string) (*http.Response, string) { t.Helper() srv := httptest.NewServer(MetricsHandler(f.node, f.s, `v1"x`, time.Unix(1_800_000_000, 0))) defer srv.Close() req, _ := http.NewRequest(method, srv.URL+"/metrics", nil) resp, err := http.DefaultClient.Do(req) if err != nil { t.Fatal(err) } defer resp.Body.Close() b, _ := io.ReadAll(resp.Body) return resp, string(b) } func TestMetricsShowTheNodesCounters(t *testing.T) { f := newFixture(t, token) if code, body := f.do(t, "POST", "/api/v1/listings", draftJSON, true); code != 200 { t.Fatalf("create: %d %s", code, body) } resp, body := scrape(t, f, "GET") if resp.StatusCode != 200 || !strings.HasPrefix(resp.Header.Get("Content-Type"), "text/plain") { t.Fatalf("status %d, type %q", resp.StatusCode, resp.Header.Get("Content-Type")) } for _, want := range []string{ "# TYPE allmende_peers gauge\nallmende_peers 0\n", `allmende_region_peers{region="u1x"} 0`, "allmende_listings 1\n", "allmende_start_time_seconds 1800000000\n", `allmende_build_info{version="v1\"x"} 1`, // quotes in a label are escaped "# TYPE allmende_guard_peers_banned_total counter\nallmende_guard_peers_banned_total 0\n", `allmende_connections_refused_total{reason="address_full"} 0`, `allmende_connections_refused_total{reason="banned"} 0`, "go_goroutines ", "go_memstats_heap_alloc_bytes ", } { if !strings.Contains(body, want) { t.Errorf("missing %q in:\n%s", want, body) } } } func TestMetricsOnlyAnswerReads(t *testing.T) { f := newFixture(t, token) if resp, _ := scrape(t, f, "POST"); resp.StatusCode != http.StatusMethodNotAllowed { t.Fatalf("POST got %d", resp.StatusCode) } }