oficina / base Public

Clone
git clone https://amadan.net/oficina/base

Plain git — no account needed to clone.

Download

Download this file

1package webtest
2
3import (
4 "context"
5 "encoding/json"
6 "net/http"
7 "net/url"
8 "strconv"
9 "strings"
10 "testing"
11 "time"
12
13 "amadan.net/oficina/base/internal/equipo"
14 "amadan.net/oficina/base/internal/equipo/equipotest"
15 "amadan.net/oficina/base/internal/store"
16)
17
18// capsOfLast is the Base-Capabilities header of the newest call to path,
19// and whether the header was there at all.
20func capsOfLast(t *testing.T, f *equipotest.Fake, path string) (string, bool) {
21 t.Helper()
22 calls := f.Calls(path)
23 if len(calls) == 0 {
24 t.Fatalf("no call to %s", path)
25 }
26 v, ok := calls[len(calls)-1].Header["Base-Capabilities"]
27 if !ok {
28 return "", false
29 }
30 return strings.Join(v, ","), true
31}
32
33const snapshotPath = "/api/v1/assistant/snapshot"
34
35// wantCaps fails unless the newest call to path carried
36// Base-Capabilities: lookup_answers (have) or none at all (!have).
37func wantCaps(t *testing.T, f *equipotest.Fake, path, where string, have bool) {
38 t.Helper()
39 caps, ok := capsOfLast(t, f, path)
40 if have && (!ok || caps != equipo.CapLookupAnswers) || !have && ok {
41 t.Errorf("%s: Base-Capabilities %q (%v), want it %v", where, caps, ok, have)
42 }
43}
44
45// A member who uses only the web is told, on Equipo's every call, that
46// Base draws lookup answers.
47func TestAskCapsWebOnly(t *testing.T) {
48 a, f := newAskApp(t)
49 a.approveEquipo(f)
50 if r := a.get("/ask"); r.Code != 200 {
51 t.Fatalf("/ask: %d", r.Code)
52 }
53 wantCaps(t, f, snapshotPath, "the web", true)
54}
55
56// One native app that called without saying it draws lookups withholds
57// the capability for the member, on the web too, until it calls with it,
58// or until it was last seen more than 30 days ago.
59func TestAskCapsWithheldForOldNative(t *testing.T) {
60 web, app, f := newNativeAskApp(t)
61 web.approveEquipo(f)
62 want := func(where string, have bool) { t.Helper(); wantCaps(t, f, snapshotPath, where, have) }
63 app.askState()
64 want("an old app's own read", false)
65 if r := web.get("/ask"); r.Code != 200 {
66 t.Fatalf("/ask: %d", r.Code)
67 }
68 want("the web, while the old app is in use", false)
69
70 app.header = http.Header{"Base-Client-Capabilities": {"job_actions, " + equipo.CapLookupAnswers}}
71 app.askState()
72 want("the app, upgraded", true)
73 web.get("/ask")
74 want("the web, once the app is upgraded", true)
75
76 // A write says nothing of what the app draws: it changes nothing.
77 bare := *app
78 bare.header = nil
79 if r := bare.nativeForm("/ask/messages", url.Values{"text": {"Hi"}, "key": {"caps-w"}}); r.Code != 200 {
80 t.Fatalf("send: %d %s", r.Code, r.Body)
81 }
82 web.get("/ask")
83 want("the web, after the upgraded app wrote", true)
84
85 app.header = nil
86 app.askState()
87 want("the app, downgraded", false)
88
89 // The app's kit sets no header of its own: the same list as a query
90 // parameter counts alike.
91 if r := app.nativeGet("/ask/state?client_caps=" + equipo.CapLookupAnswers); r.Code != 200 {
92 t.Fatalf("/ask/state: %d", r.Code)
93 }
94 want("the app, saying so in the query", true)
95 app.askState()
96 want("the app, downgraded again", false)
97 if _, err := web.DB.Exec(`UPDATE ask_clients SET seen_at = ?`, time.Now().Add(-31*24*time.Hour).UTC()); err != nil {
98 t.Fatal(err)
99 }
100 web.get("/ask")
101 want("the web, the old app unseen for 31 days", true)
102}
103
104// Every relayed call carries the header: the snapshot, the event stream,
105// a message, a card's answer, Carry on now and the time zone. The host's
106// registration carries it too, with its body as it always was.
107func TestCapabilityHeaderOnEveryCall(t *testing.T) {
108 web, app, f := newNativeAskApp(t)
109 // The member's app says what it draws before they connect.
110 app.header = http.Header{"Base-Client-Capabilities": {equipo.CapLookupAnswers}}
111 app.askState()
112 web.approveEquipo(f)
113 web.get("/ask")
114 for i := 0; i < 200 && len(f.Calls("/api/v1/assistant/time-zone")) == 0; i++ {
115 time.Sleep(10 * time.Millisecond)
116 }
117 card := f.AskQuestion("Which colour?", "Blue", "Green")
118 job := f.AskJob("A form")
119 f.PauseJob(job, "Paused until 21:00", "It has reached the limit on its plan for now.", true)
120 if r := web.post("/ask/messages", url.Values{"text": {"Hello"}, "key": {"caps-1"}}); r.Code != 303 {
121 t.Fatalf("send: %d %s", r.Code, r.Body)
122 }
123 if r := web.post("/ask/cards/"+card+"/answer", url.Values{"choice": {"Blue"}, "revision": {"1"}, "key": {"caps-2"}}); r.Code != 303 {
124 t.Fatalf("answer: %d %s", r.Code, r.Body)
125 }
126 rev := int64(3) // asked, paused, carry_on offered: the fake's revisions
127 if r := web.post("/ask/cards/"+job+"/carry_on", url.Values{"revision": {strconv.FormatInt(rev, 10)}, "key": {"caps-3"}}); r.Code != 303 {
128 t.Fatalf("carry on: %d %s", r.Code, r.Body)
129 }
130 web.events(t, "0", func(got []sseFrame) bool { return len(got) >= 2 })
131 for _, p := range []string{snapshotPath, "/api/v1/assistant/events", "/api/v1/assistant/messages",
132 "/api/v1/assistant/cards/" + card + "/answer", "/api/v1/assistant/cards/" + job + "/carry_on",
133 "/api/v1/assistant/time-zone", "/api/v1/assistant/host"} {
134 wantCaps(t, f, p, p, true)
135 }
136 hosts := f.Hosts()
137 var body map[string]string
138 if err := json.Unmarshal([]byte(hosts[len(hosts)-1].Body), &body); err != nil || len(body) != 2 || body["origin"] == "" || body["token"] == "" {
139 t.Errorf("host body %q: %v", hosts[len(hosts)-1].Body, err)
140 }
141 n, err := store.MemberNumber(context.Background(), web.DB, web.ownerID())
142 if err != nil {
143 t.Fatal(err)
144 }
145 // The web is never recorded as a client: only the app is.
146 if got, err := store.AskClients(context.Background(), web.DB, n, time.Time{}); err != nil || len(got) != 1 {
147 t.Errorf("clients recorded: %+v %v", got, err)
148 }
149}
150
151// A native session Base has never heard from on /ask (an app opened
152// before this Base, or one whose record failed before a restart) holds
153// the member back (Astra round 2); one whose first request is a write is
154// recorded as drawing nothing (round 1), and a write keeps an old app's
155// 30-day window open.
156func TestAskCapsNativeWriteFirst(t *testing.T) {
157 web, app, f := newNativeAskApp(t)
158 web.approveEquipo(f)
159 web.get("/ask")
160 wantCaps(t, f, snapshotPath, "an app never heard from", false)
161 if r := app.nativeForm("/ask/messages", url.Values{"text": {"Hi"}, "key": {"first-w"}}); r.Code != 200 {
162 t.Fatalf("send: %d %s", r.Code, r.Body)
163 }
164 web.get("/ask")
165 wantCaps(t, f, snapshotPath, "an app seen only writing", false)
166 old := time.Now().Add(-29 * 24 * time.Hour).UTC()
167 if _, err := web.DB.Exec(`UPDATE ask_clients SET seen_at = ?`, old); err != nil {
168 t.Fatal(err)
169 }
170 if r := app.nativeForm("/ask/messages", url.Values{"text": {"Again"}, "key": {"first-w2"}}); r.Code != 200 {
171 t.Fatalf("send: %d %s", r.Code, r.Body)
172 }
173 var seen time.Time
174 if err := web.DB.QueryRow(`SELECT seen_at FROM ask_clients`).Scan(&seen); err != nil || !seen.After(old.Add(time.Hour)) {
175 t.Errorf("a write didn't keep the app's window open: %v %v", seen, err)
176 }
177 app.header = http.Header{"Base-Client-Capabilities": {equipo.CapLookupAnswers}}
178 app.askState()
179 web.get("/ask")
180 wantCaps(t, f, snapshotPath, "once the app said so", true)
181}
182
183// When Base can't record what an app said, the member is told to draw
184// nothing until it can, on every request, not just that one (Astra
185// round 1, P1-3).
186func TestAskCapsRecordFailureHoldsBack(t *testing.T) {
187 web, app, f := newNativeAskApp(t)
188 web.approveEquipo(f)
189 want := func(where string, have bool) { t.Helper(); web.get("/ask"); wantCaps(t, f, snapshotPath, where, have) }
190 app.header = http.Header{"Base-Client-Capabilities": {equipo.CapLookupAnswers}}
191 app.askState()
192 want("the app says it draws them", true)
193 for _, q := range []string{
194 `CREATE TRIGGER no_insert BEFORE INSERT ON ask_clients BEGIN SELECT RAISE(ABORT, 'refused'); END`,
195 `CREATE TRIGGER no_update BEFORE UPDATE ON ask_clients BEGIN SELECT RAISE(ABORT, 'refused'); END`,
196 } {
197 if _, err := web.DB.Exec(q); err != nil {
198 t.Fatal(err)
199 }
200 }
201 // Downgraded, its read can't be recorded: held back from then on,
202 // and not only in this process (the app's row is gone, and its
203 // session is one Base knows nothing of).
204 app.header = nil
205 app.askState()
206 want("the app's downgrade went unrecorded", false)
207 var rows int
208 if err := web.DB.QueryRow(`SELECT count(*) FROM ask_clients`).Scan(&rows); err != nil || rows != 0 {
209 t.Errorf("%d rows left for a client Base couldn't record: %v", rows, err)
210 }
211 // A write that can't be recorded either holds it back too, and one
212 // that can doesn't undo that.
213 if r := app.nativeForm("/ask/messages", url.Values{"text": {"Hi"}, "key": {"held-w"}}); r.Code != 200 {
214 t.Fatalf("send: %d", r.Code)
215 }
216 want("after a write", false)
217 for _, q := range []string{`DROP TRIGGER no_insert`, `DROP TRIGGER no_update`} {
218 if _, err := web.DB.Exec(q); err != nil {
219 t.Fatal(err)
220 }
221 }
222 if r := app.nativeForm("/ask/messages", url.Values{"text": {"Again"}, "key": {"held-w2"}}); r.Code != 200 {
223 t.Fatalf("send: %d", r.Code)
224 }
225 want("after a recorded write", false)
226 app.header = http.Header{"Base-Client-Capabilities": {equipo.CapLookupAnswers}}
227 app.askState()
228 want("once recorded", true)
229}
230