| new file mode 100644 |
| index 0000000..ca7e517 |
| --- /dev/null |
| +++ b/internal/webtest/ask_native_contract_test.go |
| @@ -0,0 +1,420 @@ |
| +package webtest |
| + |
| +import ( |
| + "bufio" |
| + "context" |
| + "crypto/tls" |
| + "encoding/json" |
| + "io" |
| + "net/http" |
| + "net/url" |
| + "reflect" |
| + "sort" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/carlos/base/internal/config" |
| + "amadan.net/carlos/base/internal/equipo/equipotest" |
| +) |
| + |
| +// Ask's JSON contract (docs/api/base-native-v1.md), as the native app uses |
| +// it: every call carries the native session cookie, Origin and |
| +// Accept: application/json, and no Sec-Fetch-Site. These are the routes and |
| +// shapes ask.js relies on; a change to one breaks a test here. |
| + |
| +// newNativeAskApp is Base with Oficina ID and Ask on, the owner linked |
| +// (and signed in locally in the returned browser), and the owner's native |
| +// app signed in. |
| +func newNativeAskApp(t *testing.T) (web, app *testApp, f *equipotest.Fake) { |
| + t.Helper() |
| + f = equipotest.New(t) |
| + web = newHomeAppWith(t, func(c *config.Config) { c.EquipoOrigin = f.URL }) |
| + web.link(ownerAddress, "subject-owner") |
| + return web, web.nativeSignIn("subject-owner"), f |
| +} |
| + |
| +// nativeForm is a form POST as the native app makes one to Ask. |
| +func (a *testApp) nativeForm(target string, form url.Values) Resp { |
| + a.t.Helper() |
| + req, _ := http.NewRequest(http.MethodPost, a.base+target, strings.NewReader(form.Encode())) |
| + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + req.Header.Set("Origin", homeOrigin) |
| + req.Header.Set("Accept", "application/json") |
| + return a.do(req) |
| +} |
| + |
| +// keysOf is the sorted keys of a JSON object. |
| +func keysOf(t *testing.T, raw string) []string { |
| + t.Helper() |
| + var m map[string]json.RawMessage |
| + if err := json.Unmarshal([]byte(raw), &m); err != nil { |
| + t.Fatalf("not an object: %q: %v", raw, err) |
| + } |
| + var out []string |
| + for k := range m { |
| + out = append(out, k) |
| + } |
| + sort.Strings(out) |
| + return out |
| +} |
| + |
| +func wantKeys(t *testing.T, where, raw string, want ...string) { |
| + t.Helper() |
| + sort.Strings(want) |
| + if got := keysOf(t, raw); !reflect.DeepEqual(got, want) { |
| + t.Errorf("%s keys %v, want %v\n%s", where, got, want, raw) |
| + } |
| +} |
| + |
| +func wantBody(t *testing.T, where string, r Resp, code int, body string) { |
| + t.Helper() |
| + if r.Code != code || strings.TrimSpace(r.Body) != body { |
| + t.Errorf("%s: %d %s, want %d %s", where, r.Code, strings.TrimSpace(r.Body), code, body) |
| + } |
| +} |
| + |
| +// askState is /ask/state's answer, its parts kept raw for their shapes. |
| +type askState struct { |
| + State string `json:"state"` |
| + Messages []json.RawMessage `json:"messages"` |
| + Jobs []json.RawMessage `json:"jobs"` |
| + Cards []json.RawMessage `json:"cards"` |
| + Turn json.RawMessage `json:"turn"` |
| + Status string `json:"status"` |
| + Cursor int64 `json:"cursor"` |
| +} |
| + |
| +func (a *testApp) askState() (askState, Resp) { |
| + a.t.Helper() |
| + r := a.nativeGet("/ask/state") |
| + if r.Code != 200 || r.Header.Get("Cache-Control") != "no-store" || r.Header.Get("Content-Type") != "application/json" { |
| + a.t.Fatalf("/ask/state: %d %q %q %s", r.Code, r.Header.Get("Cache-Control"), r.Header.Get("Content-Type"), r.Body) |
| + } |
| + var s askState |
| + if err := json.Unmarshal([]byte(r.Body), &s); err != nil { |
| + a.t.Fatal(err) |
| + } |
| + return s, r |
| +} |
| + |
| +var stateKeys = []string{"state", "messages", "jobs", "cards", "turn", "status", "cursor"} |
| + |
| +func TestAskContractBeforeConnecting(t *testing.T) { |
| + _, app, _ := newNativeAskApp(t) |
| + s, r := app.askState() |
| + wantKeys(t, "state", r.Body, stateKeys...) |
| + if strings.TrimSpace(r.Body) != `{"state":"connect","messages":[],"jobs":[],"cards":[],"turn":null,"status":"","cursor":0}` || s.State != "connect" { |
| + t.Errorf("not connected: %s", r.Body) |
| + } |
| + wantBody(t, "send", app.nativeForm("/ask/messages", url.Values{"text": {"Hello"}, "key": {"k1"}}), 409, `{"state":"connect"}`) |
| + wantBody(t, "cancel", app.nativeForm("/ask/turns/t_1/cancel", url.Values{"key": {"k2"}}), 409, `{"state":"connect"}`) |
| + wantBody(t, "answer", app.nativeForm("/ask/cards/c_1/answer", url.Values{"choice": {"x"}, "revision": {"1"}, "key": {"k3"}}), 409, `{"state":"connect"}`) |
| + frames := app.events(t, "0", func([]sseFrame) bool { return false }) |
| + if len(frames) != 1 || frames[0].Event != "state" || frames[0].Data != `{"state":"connect"}` || frames[0].ID != "" { |
| + t.Errorf("events while not connected: %+v", frames) |
| + } |
| +} |
| + |
| +func TestAskContractConversation(t *testing.T) { |
| + web, app, f := newNativeAskApp(t) |
| + web.approveEquipo(f) |
| + s, r := app.askState() |
| + wantKeys(t, "state", r.Body, stateKeys...) |
| + if s.State != "ready" || s.Messages == nil || s.Jobs == nil || s.Cards == nil || string(s.Turn) != "null" || s.Status != "" { |
| + t.Fatalf("connected state: %s", r.Body) |
| + } |
| + |
| + // Send: the message and its turn; the same key again is the same message. |
| + form := url.Values{"text": {"What can I do?"}, "key": {"native-1"}} |
| + sent := app.nativeForm("/ask/messages", form) |
| + if sent.Code != 200 || sent.Header.Get("Cache-Control") != "no-store" { |
| + t.Fatalf("send: %d %s", sent.Code, sent.Body) |
| + } |
| + wantKeys(t, "send", sent.Body, "message", "turn") |
| + var out struct { |
| + Message, Turn json.RawMessage |
| + } |
| + _ = json.Unmarshal([]byte(sent.Body), &out) |
| + wantKeys(t, "message", string(out.Message), "id", "role", "text", "turn_id", "created_at") |
| + wantKeys(t, "turn", string(out.Turn), "id", "kind", "state", "reason") |
| + var m struct{ ID, Role, Text string } |
| + _ = json.Unmarshal(out.Message, &m) |
| + if m.Role != "person" || m.Text != "What can I do?" { |
| + t.Errorf("message: %s", out.Message) |
| + } |
| + again := app.nativeForm("/ask/messages", form) |
| + var m2 struct{ Message struct{ ID string } } |
| + if again.Code != 200 || json.Unmarshal([]byte(again.Body), &m2) != nil || m2.Message.ID != m.ID { |
| + t.Errorf("resend with the same key: %d %s", again.Code, again.Body) |
| + } |
| + wantBody(t, "empty", app.nativeForm("/ask/messages", url.Values{"text": {" "}, "key": {"native-2"}}), 422, `{"state":"ready"}`) |
| + |
| + // The reply is in the next read. |
| + var after askState |
| + for i := 0; i < 200; i++ { |
| + if after, _ = app.askState(); len(after.Messages) == 2 && string(after.Turn) == "null" { |
| + break |
| + } |
| + time.Sleep(10 * time.Millisecond) |
| + } |
| + if len(after.Messages) != 2 || after.Cursor <= s.Cursor { |
| + t.Fatalf("after the reply: %d messages, cursor %d (was %d)", len(after.Messages), after.Cursor, s.Cursor) |
| + } |
| + wantKeys(t, "state message", string(after.Messages[1]), "id", "role", "text", "turn_id", "created_at") |
| +} |
| + |
| +func TestAskContractEvents(t *testing.T) { |
| + web, app, f := newNativeAskApp(t) |
| + web.approveEquipo(f) |
| + s, _ := app.askState() |
| + f.Hold = true |
| + frames := app.events(t, strconv.FormatInt(s.Cursor, 10), func(got []sseFrame) bool { |
| + if len(got) == 1 { |
| + // The stream is open: send, glance, then answer. |
| + go func() { |
| + r := app.nativeForm("/ask/messages", url.Values{"text": {"Make a form"}, "key": {"ev-1"}}) |
| + var out struct{ Turn struct{ ID string } } |
| + _ = json.Unmarshal([]byte(r.Body), &out) |
| + for f.Turn(out.Turn.ID) != "running" { |
| + time.Sleep(5 * time.Millisecond) |
| + } |
| + f.Glance(out.Turn.ID, "Looking at your **forms**") |
| + time.Sleep(20 * time.Millisecond) |
| + f.Answer(out.Turn.ID, "Here it is.", true) |
| + }() |
| + } |
| + last := got[len(got)-1] |
| + return last.Event == "turn" && strings.Contains(last.Data, `"state":"replied"`) |
| + }) |
| + if frames[0].Retry != "3000" { |
| + t.Errorf("first frame %+v, want retry: 3000", frames[0]) |
| + } |
| + seen := map[string]bool{} |
| + for _, fr := range frames[1:] { |
| + if fr.Comment { |
| + continue |
| + } |
| + seen[fr.Event] = true |
| + var env struct { |
| + Type string `json:"type"` |
| + Data json.RawMessage `json:"data"` |
| + } |
| + if err := json.Unmarshal([]byte(fr.Data), &env); err != nil || env.Type != fr.Event { |
| + t.Fatalf("frame %+v: %v", fr, err) |
| + } |
| + wantKeys(t, fr.Event+" frame", fr.Data, "type", "data") |
| + switch fr.Event { |
| + case "glance": |
| + if fr.ID != "" { |
| + t.Errorf("a glance carried an id: %+v", fr) |
| + } |
| + wantKeys(t, "glance event", string(env.Data), "turn_id", "text") |
| + if !strings.Contains(string(env.Data), `"text":"Looking at your forms"`) { |
| + t.Errorf("glance: %s", env.Data) |
| + } |
| + default: |
| + if _, err := strconv.ParseUint(fr.ID, 10, 63); err != nil { |
| + t.Errorf("%s frame without a numeric id: %+v", fr.Event, fr) |
| + } |
| + } |
| + switch fr.Event { |
| + case "message": |
| + wantKeys(t, "message event", string(env.Data), "id", "role", "text", "turn_id", "created_at") |
| + case "turn": |
| + wantKeys(t, "turn event", string(env.Data), "id", "kind", "state", "reason") |
| + case "delta": |
| + wantKeys(t, "delta event", string(env.Data), "turn_id", "offset", "text") |
| + } |
| + } |
| + for _, want := range []string{"message", "turn", "delta", "glance"} { |
| + if !seen[want] { |
| + t.Errorf("no %s event in %+v", want, frames) |
| + } |
| + } |
| +} |
| + |
| +func TestAskContractCancel(t *testing.T) { |
| + web, app, f := newNativeAskApp(t) |
| + web.approveEquipo(f) |
| + f.Hold = true |
| + r := app.nativeForm("/ask/messages", url.Values{"text": {"Something long"}, "key": {"c-1"}}) |
| + var out struct{ Turn struct{ ID string } } |
| + if json.Unmarshal([]byte(r.Body), &out) != nil || out.Turn.ID == "" { |
| + t.Fatalf("send: %d %s", r.Code, r.Body) |
| + } |
| + for f.Turn(out.Turn.ID) != "running" { |
| + time.Sleep(5 * time.Millisecond) |
| + } |
| + s, _ := app.askState() |
| + if !strings.Contains(string(s.Turn), out.Turn.ID) || s.Status != "Thinking…" { |
| + t.Errorf("running: turn %s status %q", s.Turn, s.Status) |
| + } |
| + wantBody(t, "cancel", app.nativeForm("/ask/turns/"+out.Turn.ID+"/cancel", url.Values{"key": {"c-2"}}), 200, `{"state":"ready"}`) |
| + wantBody(t, "cancel again", app.nativeForm("/ask/turns/"+out.Turn.ID+"/cancel", url.Values{"key": {"c-3"}}), 409, `{"state":"ready"}`) |
| +} |
| + |
| +func TestAskContractCards(t *testing.T) { |
| + web, app, f := newNativeAskApp(t) |
| + web.approveEquipo(f) |
| + job := f.AskJob("Christmas order form") |
| + f.AskKindFor("confirm", job, "Go ahead?", goOptions, nil) |
| + q := f.AskQuestion("Which colour?", "red", "blue") |
| + s, r := app.askState() |
| + if len(s.Jobs) != 1 || len(s.Cards) != 1 { |
| + t.Fatalf("jobs and cards: %s", r.Body) |
| + } |
| + wantKeys(t, "card", string(s.Cards[0]), "id", "revision", "kind", "state", "question", "options", "links", "result") |
| + wantKeys(t, "job", string(s.Jobs[0]), "id", "revision", "kind", "state", "question", "options", "links", "result", "detail", "started_at", "cards") |
| + var j struct { |
| + Kind, State, Question string |
| + Cards []json.RawMessage |
| + } |
| + if json.Unmarshal(s.Jobs[0], &j) != nil || j.Kind != "job" || j.Question != "Christmas order form" || len(j.Cards) != 1 { |
| + t.Fatalf("job: %s", s.Jobs[0]) |
| + } |
| + wantKeys(t, "job's card", string(j.Cards[0]), "id", "revision", "kind", "state", "question", "options", "links", "result", "job") |
| + |
| + // Answer at the revision seen: the card, the message and turn it started. |
| + a := app.nativeForm("/ask/cards/"+q+"/answer", url.Values{"choice": {"red"}, "revision": {"1"}, "key": {"a-1"}}) |
| + if a.Code != 200 { |
| + t.Fatalf("answer: %d %s", a.Code, a.Body) |
| + } |
| + wantKeys(t, "answer", a.Body, "card", "message", "turn") |
| + var ans struct { |
| + Card struct{ ID, State, Result string } |
| + Message *struct{ Text string } |
| + Turn *struct{ ID string } |
| + } |
| + if json.Unmarshal([]byte(a.Body), &ans) != nil || ans.Card.ID != q || ans.Card.State != "answered" || ans.Message == nil || ans.Message.Text != "red" || ans.Turn == nil { |
| + t.Errorf("answer: %s", a.Body) |
| + } |
| + // An outcome card's answer starts nothing. |
| + o := f.AskOutcome("Publish it?", goOptions, nil) |
| + wantBody(t, "outcome", app.nativeForm("/ask/cards/"+o+"/answer", url.Values{"choice": {"go"}, "revision": {"1"}, "key": {"a-2"}}), 200, |
| + `{"card":{"id":"`+o+`","revision":2,"kind":"outcome","state":"answered","question":"Publish it?","options":[{"value":"go","label":"Go ahead"},{"value":"later","label":"Not yet"}],"links":[],"result":"Go ahead"},"message":null,"turn":null}`) |
| + // Stale: the card moved on. |
| + q2 := f.AskQuestion("Which size?", "S", "M") |
| + f.SetCard(q2, "open", "") |
| + wantBody(t, "stale", app.nativeForm("/ask/cards/"+q2+"/answer", url.Values{"choice": {"S"}, "revision": {"1"}, "key": {"a-3"}}), 409, `{"state":"ready"}`) |
| +} |
| + |
| +// Equipo refusing the key is Ask's 401 {"state":"reconnect"}, not Base's |
| +// own {"code":"unauthenticated"}: the session is fine. |
| +func TestAskContractLostKey(t *testing.T) { |
| + web, app, f := newNativeAskApp(t) |
| + web.approveEquipo(f) |
| + f.RevokeAll() |
| + wantBody(t, "send", app.nativeForm("/ask/messages", url.Values{"text": {"Hi"}, "key": {"l-1"}}), 401, `{"state":"reconnect"}`) |
| + if s, _ := app.askState(); s.State != "reconnect" { |
| + t.Errorf("state after a refused key: %s", s.State) |
| + } |
| + if r := app.nativeGet("/api/v1/me"); r.Code != 200 { |
| + t.Errorf("the session ended with the key: %d", r.Code) |
| + } |
| +} |
| + |
| +// sseFrame is one frame of an event stream, as the native client parses it. |
| +type sseFrame struct { |
| + ID, Event, Data, Retry string |
| + Comment bool |
| +} |
| + |
| +// events opens /ask/events?after= as the native app does and reads frames |
| +// until done says so or the stream ends. The first frame is the retry. |
| +func (a *testApp) events(t *testing.T, after string, done func([]sseFrame) bool) []sseFrame { |
| + t.Helper() |
| + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| + defer cancel() |
| + req, _ := http.NewRequestWithContext(ctx, http.MethodGet, a.base+"/ask/events?after="+after, nil) |
| + req.Header.Set("Origin", homeOrigin) |
| + req.Header.Set("Accept", "text/event-stream") |
| + for _, c := range a.client.Jar.Cookies(req.URL) { |
| + req.AddCookie(c) |
| + } |
| + res := serveStreaming(a.client.Transport.(handlerTransport).h, req) |
| + defer res.Body.Close() |
| + if res.StatusCode != 200 || res.Header.Get("Content-Type") != "text/event-stream" || res.Header.Get("Cache-Control") != "no-store" { |
| + t.Fatalf("events: %d %v", res.StatusCode, res.Header) |
| + } |
| + var frames []sseFrame |
| + var cur sseFrame |
| + sc := bufio.NewScanner(res.Body) |
| + for sc.Scan() { |
| + line := sc.Text() |
| + switch { |
| + case line == "": |
| + frames = append(frames, cur) |
| + cur = sseFrame{} |
| + if done(frames) { |
| + return frames |
| + } |
| + case strings.HasPrefix(line, ":"): |
| + cur.Comment = true |
| + default: |
| + name, value, _ := strings.Cut(line, ": ") |
| + switch name { |
| + case "id": |
| + cur.ID = value |
| + case "event": |
| + cur.Event = value |
| + case "data": |
| + cur.Data = value |
| + case "retry": |
| + cur.Retry = value |
| + } |
| + } |
| + } |
| + if ctx.Err() != nil { |
| + t.Fatalf("the stream timed out after %+v", frames) |
| + } |
| + // Drop the retry frame for a stream that ends at once (a state event). |
| + if len(frames) > 0 && frames[0].Retry != "" && frames[0].Event == "" { |
| + return frames[1:] |
| + } |
| + return frames |
| +} |
| + |
| +// serveStreaming serves req with h in the background and answers as soon |
| +// as the headers are written, with a body that streams what h writes. The |
| +// in-process transport waits for the whole response, which a stream never |
| +// ends. |
| +func serveStreaming(h http.Handler, req *http.Request) *http.Response { |
| + in := req.Clone(req.Context()) |
| + in.RequestURI, in.Host, in.RemoteAddr, in.TLS = req.URL.RequestURI(), req.URL.Host, "192.0.2.10:4321", &tls.ConnectionState{} |
| + pr, pw := io.Pipe() |
| + w := &pipeWriter{header: http.Header{}, pw: pw, ready: make(chan struct{})} |
| + go func() { |
| + h.ServeHTTP(w, in) |
| + w.WriteHeader(http.StatusOK) |
| + pw.Close() |
| + }() |
| + <-w.ready |
| + return &http.Response{StatusCode: w.status, Header: w.sent, Body: pr, Request: req} |
| +} |
| + |
| +type pipeWriter struct { |
| + header, sent http.Header |
| + pw *io.PipeWriter |
| + status int |
| + once sync.Once |
| + ready chan struct{} |
| +} |
| + |
| +func (p *pipeWriter) Header() http.Header { return p.header } |
| + |
| +func (p *pipeWriter) WriteHeader(code int) { |
| + p.once.Do(func() { |
| + p.status, p.sent = code, p.header.Clone() |
| + close(p.ready) |
| + }) |
| +} |
| + |
| +func (p *pipeWriter) Write(b []byte) (int, error) { |
| + p.WriteHeader(http.StatusOK) |
| + return p.pw.Write(b) |
| +} |
| + |
| +func (p *pipeWriter) Flush() {} |