Files
internet_use_control/internal/apprise/apprise_test.go
Sam Rolfe 3cf353d933 Phase 9: Hub API and Apprise alerts (/capabilities, /ask, /notify)
Build on Phases 1-8. Adds the project side of the frozen Hub contract
(central_ai_llm_master/docs/ask-contract.md) and the alert engine from
AGENTS.md §4 FR-12/FR-13, §8, §11 Phase 9.

- hub: internal/hub implements AskRequest/AskResponse/NotifyRequest and a
  deterministic, read-only Answerer. It answers screen time today/yesterday,
  what is blocked now, and device presence, scoped to one child or all kids.
  Screen time is the foreground-app total per device-day; the domain total is
  used only when a device reports no apps, so a report carrying both is never
  double-counted.
- apprise: internal/apprise is a small Apprise API client (stored key or
  stateless URL mode, optional bearer token, typed notifications).
- alert: internal/alert evaluates device state on an interval and raises one
  Apprise alert per transition: a limit hit (a device becomes blocked) or a
  device offline longer than the threshold. A never-seen device is never
  alerted, and the first observation seeds state without replaying an old
  limit. The alert is recorded before delivery, with its delivery outcome.
- store: migration 005 adds `alerts` (delivery outcome, audited) and
  `alert_state` (per-device dedup). New usage reads from the telemetry detail
  table so the daily answer can be checked independently.
- web: GET /capabilities, POST /ask (read-only) and POST /notify behind the
  shared CONTROL_HUB_TOKEN, separate from the session and admin API tokens.
  /notify accepts the contract's {from,level,message,person} and delivers it
  through Apprise (the future tamper-report path, FR-17).
- cmd/control: start the alert engine (CONTROL_ALERTS_ENABLED,
  CONTROL_ALERT_OFFLINE_AFTER, CONTROL_ALERT_INTERVAL) and add `alerts` and
  `usage` subcommands for read-only inspection.
- deploy/verify-phase9.sh + `make verify-phase9` prove the definition of done;
  version 0.7.0-phase9.

Measured on .13 (2026-10-13):
- GET /capabilities -> internet_use_control topics.
- POST /ask "how long have the kids been on screens today?" -> "The kids have
  had 1h 22m of screen time today." (total_seconds=4925); the independent
  count from the telemetry detail table is also 4925 (app=4925, domain=4800).
- A manual lock raised a delivered limit alert (id 4); an MQTT offline status
  raised a delivered offline alert (id 5); POST /notify delivered (id 6). All
  three report delivered=1 in `alerts`.

Tests: gofmt, go vet ./... and go test ./... pass in golang:1.25-alpine.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-10-13 16:41:07 +11:00

104 lines
2.8 KiB
Go

package apprise
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"testing"
)
func TestConfigured(t *testing.T) {
cases := []struct {
name string
c *Client
want bool
}{
{"nil", nil, false},
{"no base", New("", "key", nil, "", 0), false},
{"base no destination", New("http://x", "", nil, "", 0), false},
{"key mode", New("http://x", "key", nil, "", 0), true},
{"stateless mode", New("http://x", "", []string{"mailto:a@b"}, "", 0), true},
}
for _, tc := range cases {
if got := tc.c.Configured(); got != tc.want {
t.Errorf("%s: Configured() = %v, want %v", tc.name, got, tc.want)
}
}
}
func TestSendKeyMode(t *testing.T) {
var gotPath string
var gotBody map[string]any
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotPath = r.URL.Path
raw, _ := io.ReadAll(r.Body)
_ = json.Unmarshal(raw, &gotBody)
w.WriteHeader(http.StatusOK)
}))
defer srv.Close()
c := New(srv.URL, "sam_email", nil, "", 0)
if err := c.Send(context.Background(), "title", "body"); err != nil {
t.Fatalf("Send: %v", err)
}
if gotPath != "/notify/sam_email" {
t.Errorf("path = %q, want /notify/sam_email", gotPath)
}
if gotBody["title"] != "title" || gotBody["body"] != "body" {
t.Errorf("body = %#v", gotBody)
}
if _, ok := gotBody["urls"]; ok {
t.Errorf("key mode must not send urls: %#v", gotBody)
}
}
func TestSendStatelessModeWithAuthAndType(t *testing.T) {
var gotAuth, gotType string
var gotURLs []any
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotAuth = r.Header.Get("Authorization")
var body map[string]any
raw, _ := io.ReadAll(r.Body)
_ = json.Unmarshal(raw, &body)
gotType, _ = body["type"].(string)
gotURLs, _ = body["urls"].([]any)
w.WriteHeader(http.StatusOK)
}))
defer srv.Close()
c := New(srv.URL, "", []string{"mailto:sam@example.com"}, "secret", 0)
if err := c.SendType(context.Background(), "t", "b", TypeWarning); err != nil {
t.Fatalf("SendType: %v", err)
}
if gotAuth != "Bearer secret" {
t.Errorf("auth = %q", gotAuth)
}
if gotType != TypeWarning {
t.Errorf("type = %q, want %q", gotType, TypeWarning)
}
if len(gotURLs) != 1 || gotURLs[0] != "mailto:sam@example.com" {
t.Errorf("urls = %#v", gotURLs)
}
}
func TestSendErrorStatus(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}))
defer srv.Close()
c := New(srv.URL, "key", nil, "", 0)
if err := c.Send(context.Background(), "t", "b"); err == nil {
t.Fatal("Send() error = nil, want a status error")
}
}
func TestSendNotConfigured(t *testing.T) {
c := New("", "", nil, "", 0)
if err := c.Send(context.Background(), "t", "b"); err == nil {
t.Fatal("Send() error = nil, want not-configured")
}
}