183 lines
6.6 KiB
Go
183 lines
6.6 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/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)
|
|
}
|
|
code, out = do(t, "PUT", srv.URL+"/api/v1/notifications/config", "", `{"enabled":true,"ntfy_topic":"goals","retention_days":30}`)
|
|
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/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)
|
|
}
|
|
}
|