package health import ( "encoding/json" "net/http/httptest" "strings" "testing" "internetpressure.io/probe-agent/internal/protocol" ) func TestEndpoints(t *testing.T) { s := New("ca-qc-01", "0.1.0", []string{"http", "dns"}, Gauges{ Buffered: func() int { return 3 }, SpoolBytes: func() int64 { return 1024 }, ClockOffsetMs: func() int64 { return -14 }, Targets: func() int { return 7 }, }) s.Record(protocol.Measurement{Kind: "http", OK: true}) s.Record(protocol.Measurement{Kind: "dns", OK: false, Error: protocol.ErrDNSTimeout}) s.Record(protocol.Measurement{Kind: "ping", OK: false}) s.RecordFlushFailure() rr := httptest.NewRecorder() s.Handler().ServeHTTP(rr, httptest.NewRequest("GET", "/healthz", nil)) var body map[string]any if err := json.Unmarshal(rr.Body.Bytes(), &body); err != nil { t.Fatal(err) } if body["ok"] != true || body["probe_id"] != "ca-qc-01" || body["buffered"].(float64) != 3 || body["spool_bytes"].(float64) != 1024 || body["targets"].(float64) != 7 || body["clock_offset_ms"].(float64) != -14 { t.Fatalf("healthz: %v", body) } for _, k := range []string{"version", "last_flush", "last_config"} { if _, ok := body[k]; !ok { t.Errorf("healthz missing %s", k) } } rr = httptest.NewRecorder() s.Handler().ServeHTTP(rr, httptest.NewRequest("GET", "/metrics", nil)) m := rr.Body.String() for _, want := range []string{ `ip_probe_measurements_total{kind="http"} 1`, `ip_probe_measurements_total{kind="dns"} 1`, `ip_probe_errors_total{code="dns_timeout"} 1`, `ip_probe_errors_total{code="other"} 1`, "ip_probe_buffered 3", "ip_probe_spool_bytes 1024", "ip_probe_flush_failures_total 1", "ip_probe_clock_offset_ms -14", "ip_probe_targets 7", } { if !strings.Contains(m, want) { t.Errorf("metrics missing %q\n%s", want, m) } } h := s.Snapshot() if h.MeasurementsTotal != 3 || h.ErrorsTotal != 2 || h.Buffered != 3 || h.OS == "" || h.RSSMb <= 0 || h.Goroutines <= 0 { t.Fatalf("snapshot: %+v", h) } }