package equipo_test import ( "bufio" "context" "crypto/ed25519" "crypto/rand" "encoding/json" "errors" "net/http" "net/http/httptest" "os" "strings" "testing" "time" "amadan.net/rastrillo/rastrillo/budget" "amadan.net/oficina/base/internal/equipo" "amadan.net/oficina/base/internal/equipo/equipotest" ) func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } // signIn runs the device flow against f, approving the code at once. func signIn(t *testing.T, f *equipotest.Fake, c *equipo.Client) equipo.Credential { t.Helper() ctx := context.Background() pub, key, _ := ed25519.GenerateKey(rand.Reader) ch, err := c.BeginDevice(ctx, pub, "Base (Acme)") if err != nil { t.Fatal(err) } proof, err := equipo.Prove(key, ch, rand.Text()) if err != nil { t.Fatal(err) } if _, err := c.Exchange(ctx, proof); !errors.Is(err, equipo.ErrPending) { t.Fatalf("before approval: %v, want ErrPending", err) } if err := f.Approve(ch.UserCode); err != nil { t.Fatal(err) } cred, err := c.Exchange(ctx, proof) if err != nil { t.Fatal(err) } return cred } func TestDeviceFlowAndRevoke(t *testing.T) { f := equipotest.New(t) c := equipo.New(f.URL) cred := signIn(t, f, c) if !strings.HasPrefix(cred.Token, "equipo.person.v1.") || cred.Revision != 3 || cred.ExpiresAt.IsZero() { t.Fatalf("credential: %+v", cred) } for _, call := range f.Calls("") { if call.Header.Get("Idempotency-Key") == "" || call.Header.Get("Cookie") != "" || call.Header.Get("Origin") != "" { t.Errorf("%s %s headers: %v", call.Method, call.Path, call.Header) } } ctx := context.Background() if _, err := c.Snapshot(ctx, cred.Token); err != nil { t.Fatal(err) } if err := c.RevokeDevice(ctx, cred.Token, cred.ID, cred.Revision); err != nil { t.Fatal(err) } if _, err := c.Snapshot(ctx, cred.Token); !errors.Is(err, equipo.ErrUnauthenticated) { t.Fatalf("after revoke: %v, want ErrUnauthenticated", err) } } func TestExpiredCode(t *testing.T) { f := equipotest.New(t) c := equipo.New(f.URL) ctx := context.Background() pub, key, _ := ed25519.GenerateKey(rand.Reader) ch, err := c.BeginDevice(ctx, pub, "Base") if err != nil { t.Fatal(err) } f.Expire() proof, _ := equipo.Prove(key, ch, rand.Text()) if _, err := c.Exchange(ctx, proof); !errors.Is(err, equipo.ErrExpired) { t.Fatalf("expired: %v", err) } } func TestSendCarriesBearerAndKey(t *testing.T) { f := equipotest.New(t) c := equipo.New(f.URL) cred := signIn(t, f, c) sent, err := c.Send(context.Background(), cred.Token, "What can I do", "k-1", nil) if err != nil { t.Fatal(err) } if sent.Message.Text != "What can I do" || sent.Turn.ID == "" || sent.Turn.State != "queued" { t.Fatalf("sent: %+v", sent) } calls := f.Calls("/api/v1/assistant/messages") if len(calls) != 1 { t.Fatalf("calls: %+v", calls) } h := calls[0].Header if h.Get("Authorization") != "Bearer "+cred.Token || h.Get("Idempotency-Key") != "k-1" { t.Errorf("headers: %v", h) } var body map[string]string if err := json.Unmarshal([]byte(calls[0].Body), &body); err != nil || body["idempotency_key"] != "k-1" { t.Errorf("body: %s", calls[0].Body) } } func TestSealIsPerMember(t *testing.T) { s := equipo.NewSealer("instance-key") blob, err := s.Seal("member-a", []byte("equipo.person.v1.secret")) if err != nil { t.Fatal(err) } if strings.Contains(string(blob), "secret") { t.Fatal("sealed blob holds the plaintext") } if got, err := s.Open("member-a", blob); err != nil || string(got) != "equipo.person.v1.secret" { t.Fatalf("open: %q %v", got, err) } if _, err := s.Open("member-b", blob); err == nil { t.Fatal("another member's key opened it") } if _, err := equipo.NewSealer("other-key").Open("member-a", blob); err == nil { t.Fatal("another instance key opened it") } } // An Equipo that never answers the stream's headers does not hold Base. func TestEventsHeaderTimeout(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { <-r.Context().Done() })) defer srv.Close() c := equipo.New(srv.URL) c.StreamHeaderTimeout = 100 * time.Millisecond start := time.Now() if _, err := c.Events(context.Background(), "token", ""); err == nil || time.Since(start) > 2*time.Second { t.Fatalf("Events: %v after %s", err, time.Since(start)) } } // Every chat call goes to the Assistant's routes with the member's bearer; // the Coordinator's routes are never called. func TestClientUsesAssistantRoutes(t *testing.T) { f := equipotest.New(t) c := equipo.New(f.URL) cred := signIn(t, f, c) ctx := context.Background() q := f.AskQuestion("Which one?", "a", "b") f.Hold = true snap, err := c.Snapshot(ctx, cred.Token) if err != nil || len(snap.Cards) != 1 || !snap.Available || snap.Me.Address != "paul@tito.io" { t.Fatalf("snapshot: %+v %v", snap, err) } sent, err := c.Send(ctx, cred.Token, "What can I do", "k-1", nil) if err != nil { t.Fatal(err) } if err := c.Cancel(ctx, cred.Token, sent.Turn.ID, "k-2"); err != nil { t.Fatal(err) } if _, err := c.Answer(ctx, cred.Token, q, "a", 1, "k-3"); err != nil { t.Fatal(err) } res, err := c.Events(ctx, cred.Token, "41") if err != nil { t.Fatal(err) } res.Body.Close() // A fake host token, built here so no token-shaped literal lands in // the repository. hostToken := "bh_" + strings.Repeat("A", 43) if err := c.RegisterHost(ctx, cred.Token, "https://base.example.test", hostToken); err != nil { t.Fatal(err) } want := map[string]string{ "GET /api/v1/assistant/snapshot": "", "POST /api/v1/assistant/messages": "", "POST /api/v1/assistant/turns/" + sent.Turn.ID + "/cancel": "", "POST /api/v1/assistant/cards/" + q + "/answer": "", "GET /api/v1/assistant/events": "", "PUT /api/v1/assistant/host": "", } for _, call := range f.Calls("") { if strings.HasPrefix(call.Path, "/api/v1/auth/") { continue } key := call.Method + " " + call.Path if _, ok := want[key]; !ok { t.Errorf("called %s", key) continue } if call.Header.Get("Authorization") != "Bearer "+cred.Token { t.Errorf("%s without the bearer: %v", key, call.Header) } delete(want, key) } for key := range want { t.Errorf("never called %s", key) } for _, old := range []string{"/api/v1/snapshot", "/api/v1/messages", "/api/v1/events"} { if n := len(f.Calls(old)); n != 0 { t.Errorf("%d calls to %s", n, old) } } hosts := f.Hosts() if len(hosts) != 1 || strings.TrimSpace(hosts[0].Body) != `{"origin":"https://base.example.test","token":"`+hostToken+`"}` { t.Fatalf("hosts: %+v", hosts) } } // Without a runner Equipo refuses a message: 409 no_runner, which Base // can tell from runner_too_old. func TestSendWithoutRunner(t *testing.T) { f := equipotest.New(t) c := equipo.New(f.URL) cred := signIn(t, f, c) f.NoRunner() _, err := c.Send(context.Background(), cred.Token, "What can I do", "k-1", nil) if !errors.Is(err, equipo.ErrNoRunner) || errors.Is(err, equipo.ErrRunnerTooOld) { t.Fatalf("send: %v, want ErrNoRunner", err) } if snap, err := c.Snapshot(context.Background(), cred.Token); err != nil || snap.Available || len(snap.Messages) != 0 { t.Fatalf("snapshot: %+v %v", snap, err) } } // Base keeps the four card kinds the Assistant draws, with their own // fields and only web links; any other kind stays in Equipo. func TestCardClean(t *testing.T) { opts := []equipo.Option{{Value: "go", Label: "Go ahead"}, {Value: "later", Label: "Not yet"}} for name, c := range map[string]struct { in equipo.Card want string }{ "confirm": {equipo.Card{ID: "c1", Revision: 2, Kind: "confirm", State: "open", Question: "Send it?", Options: opts, Links: []equipo.Link{{Label: "See it", URL: "https://x.test/a"}}}, `{"id":"c1","revision":2,"kind":"confirm","state":"open","question":"Send it?","options":[{"value":"go","label":"Go ahead"},{"value":"later","label":"Not yet"}],"links":[{"label":"See it","url":"https://x.test/a"}],"result":""}`}, "connect": {equipo.Card{ID: "c2", Revision: 1, Kind: "connect", State: "resolved", Question: "Connect Calendar", Result: "Connected", Links: []equipo.Link{{Label: "Connect", URL: "https://connect.test/consent?x=1"}}}, `{"id":"c2","revision":1,"kind":"connect","state":"resolved","question":"Connect Calendar","options":[],"links":[{"label":"Connect","url":"https://connect.test/consent?x=1"}],"result":"Connected"}`}, "unsafe links": {equipo.Card{ID: "c3", Kind: "outcome", State: "open", Links: []equipo.Link{ {Label: "a", URL: "javascript:alert(1)"}, {Label: "b", URL: "/tasks/tk1"}, {Label: "c", URL: "https://user:pw@x.test/"}, {Label: "d", URL: "https://ok.test/"}}}, `{"id":"c3","revision":0,"kind":"outcome","state":"open","question":"","options":[],"links":[{"label":"d","url":"https://ok.test/"}],"result":""}`}, } { got, ok := c.in.Clean() raw, _ := json.Marshal(got) if !ok || string(raw) != c.want { t.Errorf("%s: %v\n got %s\nwant %s", name, ok, raw, c.want) } } for _, kind := range []string{"task", "merge", "publish", "project", ""} { if _, ok := (equipo.Card{ID: "c6", Kind: kind, State: "open"}).Clean(); ok { t.Errorf("a %q card was kept", kind) } } var in equipo.Card raw := `{"id":"c7","revision":1,"kind":"question","state":"open","question":"Which?","options":[{"value":"a","label":"A"}],"links":[],"result":"","task_id":"tk1","site":{"app":"x"}}` if err := json.Unmarshal([]byte(raw), &in); err != nil { t.Fatal(err) } const want = `{"id":"c7","revision":1,"kind":"question","state":"open","question":"Which?","options":[{"value":"a","label":"A"}],"links":[],"result":""}` if out, _ := json.Marshal(in); string(out) != want { t.Errorf("decoded with extra fields: %s", out) } got, ok := in.Clean() if out, _ := json.Marshal(got); !ok || string(out) != want { t.Errorf("extra fields: %v %s", ok, out) } } // A card shows while it is open, and afterwards only if it says how it // ended. func TestCardShown(t *testing.T) { for _, c := range []struct { state, result string want bool }{{"open", "", true}, {"answered", "", false}, {"answered", "Done", true}, {"resolved", "Published", true}, {"resolved", "", false}} { if got := (equipo.Card{Kind: "outcome", State: c.state, Result: c.result}).Shown(); got != c.want { t.Errorf("%s %q: shown %v", c.state, c.result, got) } } } // A job card keeps what Base draws of it: no options, the Equipo link's // rel and no other, its detail and start time. A job in a state it does // not know stays in Equipo; detail is a job's only, and an attached // card's job id must look like one. func TestCardCleanJob(t *testing.T) { start := time.Date(2026, 11, 13, 9, 30, 0, 0, time.UTC) in := equipo.Card{ID: "c_1", Revision: 3, Kind: equipo.CardJob, State: equipo.JobReady, Question: "Add a booking page", Options: []equipo.Option{{Value: "go", Label: "Go"}}, Result: "Ready to look at", Detail: "Have a look before it goes live.", StartedAt: &start, Links: []equipo.Link{{Label: "See it", URL: "https://preview.test/"}, {Label: "Odd", URL: "https://odd.test/", Rel: "other"}, {Label: "Open in Equipo", URL: "https://equipo.test/jobs/h_1", Rel: equipo.LinkEquipo}}} got, ok := in.Clean() raw, _ := json.Marshal(got) const want = `{"id":"c_1","revision":3,"kind":"job","state":"ready","question":"Add a booking page","options":[],"links":[{"label":"See it","url":"https://preview.test/"},{"label":"Odd","url":"https://odd.test/"},{"label":"Open in Equipo","url":"https://equipo.test/jobs/h_1","rel":"equipo"}],"result":"Ready to look at","detail":"Have a look before it goes live.","started_at":"2026-11-13T09:30:00Z"}` if !ok || string(raw) != want { t.Errorf("job: %v\n got %s\nwant %s", ok, raw, want) } if l, ok := got.Go(); !ok || l.URL != "https://preview.test/" { t.Errorf("Go: %v %+v", ok, l) } if l, ok := got.Equipo(); !ok || l.URL != "https://equipo.test/jobs/h_1" { t.Errorf("Equipo: %v %+v", ok, l) } only := equipo.Card{Kind: equipo.CardJob, State: equipo.JobWorking, Links: in.Links[2:]} if l, ok := only.Go(); ok { t.Errorf("a job with only its Equipo link has a Go link: %+v", l) } for _, state := range []string{equipo.JobWorking, equipo.JobAsking, equipo.JobDone, equipo.JobStopped} { if _, ok := (equipo.Card{ID: "c_2", Kind: equipo.CardJob, State: state}).Clean(); !ok { t.Errorf("a %s job was dropped", state) } } for _, state := range []string{"pending", "open", ""} { if _, ok := (equipo.Card{ID: "c_2", Kind: equipo.CardJob, State: state}).Clean(); ok { t.Errorf("a %q job was kept", state) } } outcome, ok := equipo.Card{ID: "c_3", Kind: equipo.CardOutcome, State: "open", Detail: "More", StartedAt: &start, Job: "c_1", Links: []equipo.Link{{Label: "See it", URL: "https://preview.test/"}}}.Clean() raw, _ = json.Marshal(outcome) const wantOutcome = `{"id":"c_3","revision":0,"kind":"outcome","state":"open","question":"","options":[],"links":[{"label":"See it","url":"https://preview.test/"}],"result":"","job":"c_1"}` if !ok || string(raw) != wantOutcome { t.Errorf("outcome: %v\n got %s\nwant %s", ok, raw, wantOutcome) } if l, ok := outcome.Go(); ok { t.Errorf("an outcome card has a job's Go link: %+v", l) } if l, ok := (equipo.Card{Kind: equipo.CardOutcome, Links: in.Links[2:]}).Equipo(); ok { t.Errorf("an outcome card has a job's Equipo link: %+v", l) } for job, keep := range map[string]bool{"c_1": true, "C-9_x": true, strings.Repeat("a", 128): true, "../x": false, "c 1": false, "c/1": false, strings.Repeat("a", 129): false, "": false} { got, _ := (equipo.Card{ID: "c_4", Kind: equipo.CardOutcome, State: "open", Job: job}).Clean() if (got.Job == job && job != "") != keep || !keep && got.Job != "" { t.Errorf("job %q: kept %q", job, got.Job) } } if !(equipo.Card{Kind: equipo.CardJob, State: equipo.JobWorking}).Shown() { t.Error("a working job is not shown") } } // The fake raises and moves job cards as Equipo does: the Equipo link // stays last, each change is a new revision and an event; a go-ahead can // belong to a job, and a turn of any kind can appear. func TestFakeJobCards(t *testing.T) { f := equipotest.New(t) c := equipo.New(f.URL) cred := signIn(t, f, c) ctx := context.Background() id := f.AskJob("Add a booking page") f.SetJob(id, equipo.JobReady, "Ready to look at", "Have a look.", equipo.Link{Label: "See it", URL: "https://preview.test/"}) go1 := f.AskOutcomeFor(id, "This is ready. Go ahead?", []equipo.Option{{Value: "go", Label: "Go ahead"}}, nil) tid := f.EmitTurn("team_update", equipo.TurnRunning) snap, err := c.Snapshot(ctx, cred.Token) if err != nil || len(snap.Cards) != 2 || len(snap.Turns) != 1 { t.Fatalf("snapshot: %+v %v", snap, err) } job, ok := snap.Cards[0].Clean() if !ok || job.ID != id || job.Revision != 2 || job.State != equipo.JobReady || job.Question != "Add a booking page" || job.Result != "Ready to look at" || job.Detail != "Have a look." || job.StartedAt == nil || time.Since(*job.StartedAt) > time.Minute { t.Errorf("job: %v %+v", ok, job) } if l, ok := job.Go(); !ok || l.URL != "https://preview.test/" { t.Errorf("Go: %v %+v", ok, l) } if l, ok := job.Equipo(); !ok || len(job.Links) != 2 || job.Links[1] != l || l.Label != "Open in Equipo" || !strings.HasPrefix(l.URL, f.URL+"/jobs/h_") { t.Errorf("Equipo link: %v %+v", ok, job.Links) } if o := snap.Cards[1]; o.ID != go1 || o.Kind != equipo.CardOutcome || o.Job != id || o.State != "open" { t.Errorf("attached card: %+v", o) } if tr := snap.Turns[0]; tr.ID != tid || tr.Kind != "team_update" || tr.State != equipo.TurnRunning { t.Errorf("turn: %+v", tr) } sctx, cancel := context.WithTimeout(ctx, 2*time.Second) defer cancel() res, err := c.Events(sctx, cred.Token, "40") if err != nil { t.Fatal(err) } defer res.Body.Close() var seen []string sc := bufio.NewScanner(res.Body) for len(seen) < 4 && sc.Scan() { if line, ok := strings.CutPrefix(sc.Text(), "event: "); ok { seen = append(seen, line) } } if strings.Join(seen, " ") != "card card card turn" { t.Errorf("events: %v", seen) } } // readFrames reads the stream's frames (each its lines) until one holds // until, or the stream ends. func readFrames(t *testing.T, sc *bufio.Scanner, until string) []string { t.Helper() var frames []string var cur []string for sc.Scan() { if sc.Text() != "" { cur = append(cur, sc.Text()) continue } if len(cur) == 0 { continue } f := strings.Join(cur, "\n") cur = nil frames = append(frames, f) if strings.Contains(f, until) { return frames } } t.Fatalf("the stream ended before %q: %q", until, frames) return nil } // The fake sends a glance as Equipo does: live only, without an id line // and with cursor 0, so the cursor runs on unbroken past it; a stream // that reconnects with its cursor never gets it again. func TestFakeGlanceIsLiveOnly(t *testing.T) { f := equipotest.New(t) f.Hold = true c := equipo.New(f.URL) cred := signIn(t, f, c) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() sent, err := c.Send(ctx, cred.Token, "What's on today?", "k-1", nil) if err != nil { t.Fatal(err) } res, err := c.Events(ctx, cred.Token, "40") if err != nil { t.Fatal(err) } defer res.Body.Close() sc := bufio.NewScanner(res.Body) readFrames(t, sc, `"state":"running"`) f.Glance(sent.Turn.ID, "Checking your diary") f.Say("Two meetings.") frames := readFrames(t, sc, "Two meetings.") if len(frames) != 2 { t.Fatalf("frames after the glance: %q", frames) } if want := "event: glance\ndata: "; !strings.HasPrefix(frames[0], want) || !strings.Contains(frames[0], `"cursor":0,`) || !strings.Contains(frames[0], `"data":{"text":"Checking your diary","turn_id":"`+sent.Turn.ID+`"}`) { t.Errorf("the glance: %q", frames[0]) } if !strings.HasPrefix(frames[1], "id: 44\nevent: message\n") { t.Errorf("after the glance: %q", frames[1]) } again, err := c.Events(ctx, cred.Token, "40") if err != nil { t.Fatal(err) } defer again.Body.Close() frames = readFrames(t, bufio.NewScanner(again.Body), "Two meetings.") for _, fr := range frames { if strings.Contains(fr, "glance") { t.Errorf("replayed the glance: %q", frames) } } } // A paused job is kept, with carry_on when Equipo offers it; carry_on on a // job in any other state, or on another kind of card, is dropped. A job // card from an Equipo that never sends carry_on cleans to the same JSON // as before (no carry_on key at all). func TestCardCleanPausedJob(t *testing.T) { got, ok := equipo.Card{ID: "c_1", Revision: 4, Kind: equipo.CardJob, State: equipo.JobPaused, Question: "Bakery website", Result: "Paused until 21:00", Detail: "It will carry on by itself at 21:00 (in 9 hours).", CarryOn: true}.Clean() raw, _ := json.Marshal(got) const want = `{"id":"c_1","revision":4,"kind":"job","state":"paused","question":"Bakery website","options":[],"links":[],"result":"Paused until 21:00","detail":"It will carry on by itself at 21:00 (in 9 hours).","carry_on":true}` if !ok || string(raw) != want { t.Errorf("paused: %v\n got %s\nwant %s", ok, raw, want) } for _, c := range []equipo.Card{ {ID: "c_2", Kind: equipo.CardJob, State: equipo.JobWorking, CarryOn: true}, {ID: "c_4", Kind: equipo.CardOutcome, State: "open", CarryOn: true}, } { got, _ := c.Clean() if raw, _ := json.Marshal(got); got.CarryOn || strings.Contains(string(raw), "carry_on") { t.Errorf("%s %s kept carry_on: %s", c.Kind, c.State, raw) } } } // A stopped job keeps carry_on: a job held because building was turned // off, once it is on again, carries on when the person says so (plan // AD4). Any card that isn't a job never has it. func TestCardCleanStoppedCarryOn(t *testing.T) { got, ok := equipo.Card{ID: "c_1", Revision: 2, Kind: equipo.CardJob, State: equipo.JobStopped, Question: "Bakery website", Result: "Stopped", Detail: "Building is on again. You can carry on with this, or drop it.", CarryOn: true}.Clean() if !ok || !got.CarryOn { t.Errorf("stopped job: %v %+v", ok, got) } for _, c := range []equipo.Card{ {ID: "c_2", Kind: equipo.CardOutcome, State: "open", CarryOn: true}, {ID: "c_3", Kind: equipo.CardQuestion, State: equipo.JobStopped, CarryOn: true}, {ID: "c_4", Kind: equipo.CardJob, State: equipo.JobReady, CarryOn: true}, } { if got, _ := c.Clean(); got.CarryOn { t.Errorf("%s %s kept carry_on", c.Kind, c.State) } } } // CarryOnNow posts {revision, idempotency_key} with the key as the // Idempotency-Key and reads the card back from {"card"}; the same key // replays the answer; Equipo's 409s come back as errors with their codes. func TestCarryOnNow(t *testing.T) { f := equipotest.New(t) c := equipo.New(f.URL) cred := signIn(t, f, c) ctx := context.Background() job := f.AskJob("Bakery website") f.PauseJob(job, "Paused until 21:00", "It will carry on by itself at 21:00.", true) var e *equipo.Error if _, err := c.CarryOnNow(ctx, cred.Token, job, 1, "k-1"); !errors.As(err, &e) || e.Status != 409 || e.Code != "card_stale" { t.Errorf("stale: %v", err) } card, err := c.CarryOnNow(ctx, cred.Token, job, 3, "k-2") if err != nil || card.ID != job || card.State != equipo.JobWorking || card.Revision != 4 { t.Fatalf("carry on: %+v %v", card, err) } calls := f.Calls("/api/v1/assistant/cards/" + job + "/carry_on") if last := calls[len(calls)-1]; strings.TrimSpace(last.Body) != `{"idempotency_key":"k-2","revision":3}` || last.Header.Get("Idempotency-Key") != "k-2" { t.Errorf("sent: %+v", last) } if again, err := c.CarryOnNow(ctx, cred.Token, job, 3, "k-2"); err != nil || again.Revision != 4 || again.State != equipo.JobWorking { t.Errorf("replayed: %+v %v", again, err) } // Equipo replays a key with the card as it is now, not as it was. f.SetJob(job, equipo.JobReady, "Ready to try", "Have a look.") if again, err := c.CarryOnNow(ctx, cred.Token, job, 3, "k-2"); err != nil || again.Revision != 5 || again.State != equipo.JobReady { t.Errorf("replayed after a move: %+v %v", again, err) } if _, err := c.CarryOnNow(ctx, cred.Token, "c_nothing", 1, "k-2"); !errors.As(err, &e) || e.Status != 404 { t.Errorf("no such card, with a key seen before: %v", err) } if _, err := c.CarryOnNow(ctx, cred.Token, job, 5, "k-3"); !errors.As(err, &e) || e.Code != "not_paused" { t.Errorf("not paused: %v", err) } f.PauseJob(job, "Paused until 22:00", "", false) if _, err := c.CarryOnNow(ctx, cred.Token, job, 6, "k-4"); !errors.As(err, &e) || e.Code != "carry_on_unavailable" { t.Errorf("unavailable: %v", err) } } // Base opts in to the paused state on the snapshot and the event stream // (job_states=paused). Without it, as for an older Base, Equipo sends a // paused job as working, with its result and detail and no carry_on. func TestPausedIsOptIn(t *testing.T) { f := equipotest.New(t) c := equipo.New(f.URL) cred := signIn(t, f, c) ctx := context.Background() job := f.AskJob("Bakery website") f.PauseJob(job, "Paused until 21:00", "It will carry on by itself at 21:00.", true) snap, err := c.Snapshot(ctx, cred.Token) if err != nil || len(snap.Cards) != 1 || snap.Cards[0].State != equipo.JobPaused || !snap.Cards[0].CarryOn { t.Fatalf("opted in: %+v %v", snap.Cards, err) } if calls := f.Calls("/api/v1/assistant/snapshot"); calls[len(calls)-1].Query != "job_states=paused" { t.Errorf("snapshot's query %q", calls[len(calls)-1].Query) } res, err := c.Events(ctx, cred.Token, "40") if err != nil { t.Fatal(err) } res.Body.Close() if calls := f.Calls("/api/v1/assistant/events"); calls[len(calls)-1].Query != "job_states=paused&after=40" { t.Errorf("events' query %q", calls[len(calls)-1].Query) } // An older Base, asking without it. req, _ := http.NewRequest(http.MethodGet, f.URL+"/api/v1/assistant/snapshot", nil) req.Header.Set("Authorization", "Bearer "+cred.Token) raw, err := http.DefaultClient.Do(req) if err != nil { t.Fatal(err) } defer raw.Body.Close() var old equipo.Snapshot if json.NewDecoder(raw.Body).Decode(&old) != nil || len(old.Cards) != 1 || old.Cards[0].State != equipo.JobWorking || old.Cards[0].CarryOn || old.Cards[0].Result != "Paused until 21:00" { t.Errorf("without the opt-in: %+v", old.Cards) } } // SetTimeZone is PUT time-zone {time_zone}; a zone Equipo does not know is // 422 invalid_input. func TestSetTimeZone(t *testing.T) { f := equipotest.New(t) c := equipo.New(f.URL) cred := signIn(t, f, c) ctx := context.Background() const dublin = "Europe/Dublin" if err := c.SetTimeZone(ctx, cred.Token, dublin); err != nil || f.TimeZone() != dublin { t.Fatalf("set: %v, zone %q", err, f.TimeZone()) } if calls := f.Calls("/api/v1/assistant/time-zone"); len(calls) != 1 || calls[0].Method != http.MethodPut || strings.TrimSpace(calls[0].Body) != `{"only_if_unset":true,"time_zone":"Europe/Dublin"}` || calls[0].Header.Get("Idempotency-Key") == "" { t.Errorf("sent: %+v", calls) } // Base's zone replaces the one Base set before (BASE_TIMEZONE changed), // never one the person's own device set. if err := c.SetTimeZone(ctx, cred.Token, "Europe/Madrid"); err != nil || f.TimeZone() != "Europe/Madrid" { t.Errorf("Base's new zone: %v, zone %q", err, f.TimeZone()) } f.SetTimeZone("Europe/Berlin") if err := c.SetTimeZone(ctx, cred.Token, dublin); err != nil || f.TimeZone() != "Europe/Berlin" { t.Errorf("over the person's own: %v, zone %q", err, f.TimeZone()) } var e *equipo.Error if err := c.SetTimeZone(ctx, cred.Token, "Mars/Olympus"); !errors.As(err, &e) || e.Status != 422 || e.Code != "invalid_input" { t.Errorf("unknown zone: %v", err) } }