Files
puppy-tracker/server/integration_test.go
T
Alexander Heldt 15211e32b0 Add a read-only integration feed of walks and meals
GET /api/integration/events?since=<unix ms> returns one account's walk
starts and meals that happened or changed since then, tombstones
included, for other services on the same host. It is authenticated
with a bearer token rather than a session and cannot write anything.

Enabled with -integration-token-file (services.puppy-tracker
.integration.tokenFile); -integration-user picks the account, and
defaults to the only one.
2026-09-29 19:13:28 +00:00

72 lines
2.2 KiB
Go

package main
import (
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
)
func TestIntegrationEvents(t *testing.T) {
db, err := openDB(filepath.Join(t.TempDir(), "puppy.db"))
if err != nil {
t.Fatal(err)
}
defer db.Close()
db.Exec(`INSERT INTO users (id, email, password, created) VALUES ('u1', 'a@x', 'h', 0)`)
db.Exec(`INSERT INTO users (id, email, password, created) VALUES ('u2', 'b@x', 'h', 0)`)
store := newStore(db)
store.sync("u1", "", "", []Event{
{ID: "walk", Type: "walk-start", At: 1000, UpdatedAt: 1000},
{ID: "meal", Type: "eat", At: 2000, UpdatedAt: 2000},
{ID: "pee", Type: "pee", At: 2000, UpdatedAt: 2000},
{ID: "old", Type: "eat", At: 10, UpdatedAt: 10},
{ID: "gone", Type: "eat", At: 10, UpdatedAt: 3000, Deleted: true},
})
store.sync("u2", "", "", []Event{{ID: "theirs", Type: "eat", At: 2000, UpdatedAt: 2000}})
get := func(in *Integration, auth, since string) (int, []integrationEvent) {
req := httptest.NewRequest("GET", "/api/integration/events?since="+since, nil)
if auth != "" {
req.Header.Set("Authorization", "Bearer "+auth)
}
rec := httptest.NewRecorder()
in.handleEvents(rec, req)
var body struct{ Events []integrationEvent }
json.NewDecoder(rec.Body).Decode(&body)
return rec.Code, body.Events
}
in := &Integration{db: db, token: "tok", email: "A@x"}
if code, _ := get(in, "", "0"); code != http.StatusUnauthorized {
t.Errorf("no token = %d", code)
}
if code, _ := get(in, "nope", "0"); code != http.StatusUnauthorized {
t.Errorf("wrong token = %d", code)
}
code, evs := get(in, "tok", "500")
if code != 200 {
t.Fatalf("code = %d", code)
}
got := map[string]bool{}
for _, e := range evs {
got[e.ID] = e.Deleted
}
// Recent walks and meals, plus the tombstone updated since; not the pee,
// not the old meal, not the other account's.
if len(got) != 3 || !got["gone"] {
t.Errorf("events = %+v", evs)
}
for _, id := range []string{"walk", "meal"} {
if _, ok := got[id]; !ok {
t.Errorf("missing %s", id)
}
}
// With two accounts, no configured user is ambiguous.
if code, _ := get(&Integration{db: db, token: "tok"}, "tok", "0"); code != http.StatusConflict {
t.Errorf("ambiguous = %d", code)
}
}