Files
ccp/internal/api/api_test.go
adamf 453cef40af
Test and publish / test (push) Successful in 1m40s
Test and publish / publish (push) Successful in 3m45s
Add goal notifications and collector health
2026-10-23 20:45:51 +01:00

252 lines
9.1 KiB
Go

package api
import (
"context"
"encoding/json"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"ccp/internal/auth"
"ccp/internal/store"
"ccp/internal/summary"
"ccp/internal/testdb"
)
// Needs TEST_DATABASE_URL; see internal/testdb.
func setup(t *testing.T) (*httptest.Server, string) {
t.Parallel()
ctx := context.Background()
st := store.New(testdb.New(t))
_, key, err := st.CreateDevice(ctx, "test", "hyprland")
if err != nil {
t.Fatal(err)
}
if _, err := st.CreateGoal(ctx, store.Goal{Kind: "app_focus", Label: "kitty", Op: ">=", TargetS: 3600}); err != nil {
t.Fatal(err)
}
srv := httptest.NewServer(New(st, auth.AllowAll{}, time.UTC, slog.New(slog.NewTextHandler(io.Discard, nil))))
t.Cleanup(srv.Close)
return srv, key
}
func do(t *testing.T, method, url, key, body string) (int, map[string]any) {
t.Helper()
req, _ := http.NewRequest(method, url, strings.NewReader(body))
if key != "" {
req.Header.Set("Authorization", "Bearer "+key)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
var out map[string]any
json.NewDecoder(resp.Body).Decode(&out)
return resp.StatusCode, out
}
func TestIngestAndSummary(t *testing.T) {
srv, key := setup(t)
day := time.Now().UTC().Add(-48 * time.Hour).Format(time.DateOnly)
// The second event crosses midnight; only its first hour belongs to `day`.
batch := `{"events":[
{"id":"e1","kind":"app_focus","label":"kitty","started_at":"` + day + `T09:00:00Z","ended_at":"` + day + `T10:30:00Z","attrs":{"title":"nvim"}},
{"id":"e2","kind":"app_focus","label":"firefox","started_at":"` + day + `T23:00:00Z","ended_at":"` + day + `T23:59:59Z"}
]}`
if code, _ := do(t, "POST", srv.URL+"/api/v1/desktop/events", "", batch); code != http.StatusUnauthorized {
t.Fatalf("no key: got %d", code)
}
if code, _ := do(t, "POST", srv.URL+"/api/v1/desktop/events", "trk_wrong", batch); code != http.StatusUnauthorized {
t.Fatalf("bad key: got %d", code)
}
code, body := do(t, "POST", srv.URL+"/api/v1/desktop/events", key, batch)
if code != http.StatusOK || body["inserted"] != 2.0 {
t.Fatalf("first upload: %d %v", code, body)
}
code, body = do(t, "POST", srv.URL+"/api/v1/desktop/events", key, batch)
if code != http.StatusOK || body["inserted"] != 0.0 {
t.Fatalf("re-upload should be idempotent: %d %v", code, body)
}
code, body = do(t, "POST", srv.URL+"/api/v1/desktop/events", key, `{"events":[{"id":"x","kind":"walk","started_at":"`+day+`T09:00:00Z","ended_at":"`+day+`T10:00:00Z"}]}`)
if code != http.StatusUnprocessableEntity {
t.Fatalf("wrong kind for endpoint: %d %v", code, body)
}
code, body = do(t, "GET", srv.URL+"/api/v1/summary/daily?date="+day, key, "")
if code != http.StatusOK {
t.Fatalf("summary: %d %v", code, body)
}
if got := body["by_kind"].(map[string]any)["app_focus"]; got != float64(5400+3599) {
t.Errorf("app_focus total = %v", got)
}
goal := body["goals"].([]any)[0].(map[string]any)
if goal["actual_s"] != 5400.0 || goal["met"] != true {
t.Errorf("goal = %v", goal)
}
code, body = do(t, "GET", srv.URL+"/api/v1/activities?from="+day+"T00:00:00Z&to="+day+"T23:59:59Z&kind=app_focus", key, "")
if code != http.StatusOK || len(body["activities"].([]any)) != 2 {
t.Fatalf("activities: %d %v", code, body)
}
}
func TestLocation(t *testing.T) {
srv, key := setup(t)
at := func(d time.Duration) string {
return `"at":"` + time.Now().UTC().Add(d).Format(time.RFC3339) + `"`
}
post := func(event, body string) map[string]any {
t.Helper()
code, out := do(t, "POST", srv.URL+"/api/v1/location/"+event, key, body)
if code != http.StatusOK {
t.Fatalf("%s %s: %d %v", event, body, code, out)
}
return out
}
// A bare POST means home, now.
if out := post("leave", `{`+at(-3*time.Hour)+`}`); out["place"] != "away" || out["changed"] != true {
t.Fatalf("first leave: %v", out)
}
if out := post("arrive?place=Gym", `{`+at(-2*time.Hour)+`}`); out["place"] != "gym" {
t.Fatalf("arrive gym: %v", out)
}
// Leaving home while at the gym is stale and changes nothing.
if out := post("leave", `{`+at(-90*time.Minute)+`}`); out["place"] != "gym" || out["changed"] != false {
t.Fatalf("stale leave: %v", out)
}
post("leave/gym", `{`+at(-time.Hour)+`}`)
post("arrive", "")
if out := post("arrive", ""); out["changed"] != false {
t.Fatalf("repeat arrive should be a no-op: %v", out)
}
code, body := do(t, "GET", srv.URL+"/api/v1/activities?kind=place", key, "")
acts := body["activities"].([]any)
if code != http.StatusOK || len(acts) != 4 {
t.Fatalf("activities: %d %v", code, body)
}
var labels []string
for _, a := range acts {
labels = append(labels, a.(map[string]any)["label"].(string))
}
if strings.Join(labels, ",") != "away,gym,away,home" {
t.Errorf("labels = %v", labels)
}
if d := acts[0].(map[string]any)["duration_s"]; d != 3600.0 {
t.Errorf("first away = %v s", d)
}
// The open home interval reads as running until now.
if end, _ := time.Parse(time.RFC3339Nano, acts[3].(map[string]any)["ended_at"].(string)); time.Since(end) > time.Minute {
t.Errorf("open interval ended at %v", end)
}
if code, _ := do(t, "POST", srv.URL+"/api/v1/location/teleport", key, ""); code != http.StatusNotFound {
t.Errorf("unknown event: %d", code)
}
}
func TestSamplesReportsAndSettings(t *testing.T) {
srv, key := setup(t)
ts := time.Now().UTC().Add(-time.Hour).Truncate(time.Second)
body := `{"samples":[{"id":"s1","source":"watch","metric":"steps","ts":"` + ts.Format(time.RFC3339) + `","value":12,"unit":"count"}]}`
code, out := do(t, "POST", srv.URL+"/api/v1/samples", key, body)
if code != http.StatusOK || out["inserted"] != 1.0 {
t.Fatalf("sample ingest: %d %v", code, out)
}
code, out = do(t, "POST", srv.URL+"/api/v1/samples", key, body)
if code != http.StatusOK || out["inserted"] != 0.0 {
t.Fatalf("sample idempotency: %d %v", code, out)
}
code, out = do(t, "GET", srv.URL+"/api/v1/summary/range?from="+ts.Add(-time.Minute).Format(time.RFC3339)+"&to="+ts.Add(time.Minute).Format(time.RFC3339), key, "")
if code != http.StatusOK || len(out["samples"].([]any)) != 1 {
t.Fatalf("range summary: %d %v", code, out)
}
ntfyBody := make(chan string, 1)
ntfy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
ntfyBody <- string(body)
w.WriteHeader(http.StatusOK)
}))
t.Cleanup(ntfy.Close)
config := `{"enabled":true,"ntfy_server":"` + ntfy.URL + `","ntfy_topic":"goals","retention_days":30}`
code, out = do(t, "PUT", srv.URL+"/api/v1/notifications/config", "", config)
if code != http.StatusOK || out["ntfy_topic"] != "goals" {
t.Fatalf("notification config: %d %v", code, out)
}
code, out = do(t, "POST", srv.URL+"/api/v1/notifications/goals/check", "", "")
if code != http.StatusOK || out["sent"] != 1.0 || out["at_risk"] != 1.0 {
t.Fatalf("goal notification: %d %v", code, out)
}
select {
case body := <-ntfyBody:
if !strings.Contains(body, "Goal at risk") {
t.Fatalf("ntfy body = %q", body)
}
case <-time.After(time.Second):
t.Fatal("timed out waiting for ntfy request")
}
code, out = do(t, "POST", srv.URL+"/api/v1/notifications/goals/check", "", "")
if code != http.StatusOK || out["sent"] != 0.0 || out["at_risk"] != 1.0 {
t.Fatalf("duplicate goal notification: %d %v", code, out)
}
code, out = do(t, "GET", srv.URL+"/api/v1/health/collectors", "", "")
collectors := out["collectors"].([]any)
if code != http.StatusOK || len(collectors) != 1 {
t.Fatalf("collector health: %d %v", code, out)
}
collector := collectors[0].(map[string]any)
if collector["status"] != "healthy" || collector["activity_count"] != 0.0 || collector["sample_count"] != 1.0 {
t.Fatalf("collector health entry: %v", collector)
}
code, out = do(t, "POST", srv.URL+"/api/v1/reports", "", `{"period_start":"`+ts.Format(time.RFC3339)+`","period_end":"`+ts.Add(time.Hour).Format(time.RFC3339)+`","model":"test","body":"summary"}`)
if code != http.StatusCreated || out["id"] == nil {
t.Fatalf("report create: %d %v", code, out)
}
}
func TestValidateNtfyServer(t *testing.T) {
for _, tc := range []struct {
name string
value string
valid bool
}{
{"https", "https://ntfy.example", true},
{"http", "http://127.0.0.1:8080/ntfy", true},
{"relative", "ntfy.example", false},
{"unsupported scheme", "ftp://ntfy.example", false},
{"missing host", "https:///topic", false},
{"malformed", "https://[::1", false},
{"userinfo", "https://user:[email protected]", false},
} {
t.Run(tc.name, func(t *testing.T) {
_, err := validateNtfyServer(tc.value)
if (err == nil) != tc.valid {
t.Fatalf("validateNtfyServer(%q) error = %v, valid = %v", tc.value, err, tc.valid)
}
})
}
}
func TestGoalAtRisk(t *testing.T) {
if !goalAtRisk(summary.GoalResult{Goal: store.Goal{Op: ">=", TargetS: 100}, ActualS: 49}, 0.5) {
t.Error("goal below elapsed-day pace should be at risk")
}
if goalAtRisk(summary.GoalResult{Goal: store.Goal{Op: ">=", TargetS: 100}, ActualS: 50}, 0.5) {
t.Error("goal on elapsed-day pace should not be at risk")
}
if !goalAtRisk(summary.GoalResult{Goal: store.Goal{Op: "<=", TargetS: 100}, ActualS: 101}, 0.1) {
t.Error("over-limit goal should be at risk")
}
}