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 "database/sql"
6 "net/url"
7 "regexp"
8 "strings"
9 "sync"
10 "testing"
11 "time"
12
13 "amadan.net/oficina/base/internal/config"
14 "amadan.net/oficina/base/internal/store"
15 "amadan.net/oficina/base/internal/web"
16)
17
18func (a *testApp) setInstall(app, state, errMsg string) {
19 a.t.Helper()
20 ctx := context.Background()
21 if _, err := store.ClaimInstall(ctx, a.DB, app, "acme-"+app+".bab.oncarlos.com"); err != nil {
22 a.t.Fatal(err)
23 }
24 if err := store.SetInstallState(ctx, a.DB, app, state, errMsg); err != nil {
25 a.t.Fatal(err)
26 }
27}
28
29// stepDone reports whether the Home step with this label is ticked.
30func stepDone(t *testing.T, body, label string) bool {
31 t.Helper()
32 m := regexp.MustCompile(`<li class="glass( done)?"[^>]*>(?:<span class="mark">[^<]*</span>)?` + regexp.QuoteMeta(label) + `</li>`).FindStringSubmatch(body)
33 if m == nil {
34 t.Fatalf("no step %q in:\n%s", label, body)
35 }
36 return m[1] != ""
37}
38
39func TestHomeShowsGreetingWithName(t *testing.T) {
40 a := newApp(t)
41 if _, err := a.DB.Exec(`UPDATE members SET name = 'Paul'`); err != nil {
42 t.Fatal(err)
43 }
44 a.signedInOwner()
45 if body := a.get("/").Body; !regexp.MustCompile(`(Good (morning|afternoon|evening)|Hello), Paul\.`).MatchString(body) {
46 t.Fatalf("no greeting:\n%s", body)
47 }
48}
49
50func TestHomeNameFallsBackToEmailLocalPart(t *testing.T) {
51 a := newApp(t)
52 a.signedInOwner()
53 if body := a.get("/").Body; !strings.Contains(body, ", Owner.") {
54 t.Fatalf("greeting lacks capitalised local part:\n%s", body)
55 }
56}
57
58func TestHomeSteps(t *testing.T) {
59 a := newApp(t)
60 a.signedInOwner()
61 body := a.get("/").Body
62 if !stepDone(t, body, "Signed in") || stepDone(t, body, "Invite your team") || stepDone(t, body, "Install your first app") {
63 t.Fatalf("fresh Base steps wrong:\n%s", body)
64 }
65 a.setInstall("welcome", "installed", "") // a default app does not count
66 if body := a.get("/").Body; stepDone(t, body, "Install your first app") {
67 t.Fatalf("default app ticked the install step:\n%s", body)
68 }
69 if r := a.post("/people", invite("maria@acme.co")); r.Code != 303 {
70 t.Fatal(r.Code)
71 }
72 a.setInstall("scratchpad", "installed", "")
73 body = a.get("/").Body
74 for _, s := range []string{"Signed in", "Invite your team", "Install your first app"} {
75 if !stepDone(t, body, s) {
76 t.Errorf("step %q not done:\n%s", s, body)
77 }
78 }
79}
80
81func TestHomeTilesLinkToOrigins(t *testing.T) {
82 a := newApp(t)
83 a.signedInOwner()
84 body := a.get("/").Body
85 for _, h := range []string{`href="/store"`, `href="/people"`, `href="/settings"`} {
86 if !strings.Contains(body, h) {
87 t.Errorf("built-in tile %s missing", h)
88 }
89 }
90 if strings.Contains(body, "acme-scratchpad") {
91 t.Fatal("uninstalled app has a tile")
92 }
93 a.setInstall("scratchpad", "installing", "")
94 if strings.Contains(a.get("/").Body, "acme-scratchpad") {
95 t.Fatal("installing app has a tile")
96 }
97 a.setInstall("scratchpad", "failed", "x")
98 if strings.Contains(a.get("/").Body, "acme-scratchpad") {
99 t.Fatal("failed app has a tile")
100 }
101 a.setInstall("scratchpad", "installing", "")
102 a.setInstall("scratchpad", "installed", "")
103 body = a.get("/").Body
104 re := regexp.MustCompile(`<a class="app" href="https://acme-scratchpad\.bab\.oncarlos\.com/"><span class="icon tile t-rose">`)
105 if !re.MatchString(body) {
106 t.Fatalf("no tile for scratchpad:\n%s", body)
107 }
108}
109
110// Finding 1: a tile links to the host Base installed the app at, even after
111// the slug or apps domain changed.
112func TestHomeTileUsesRecordedHost(t *testing.T) {
113 a := newApp(t)
114 a.signedInOwner()
115 ctx := context.Background()
116 if _, err := store.ClaimInstall(ctx, a.DB, "scratchpad", "oldco-scratchpad.old.example"); err != nil {
117 t.Fatal(err)
118 }
119 if err := store.SetInstallState(ctx, a.DB, "scratchpad", "installed", ""); err != nil {
120 t.Fatal(err)
121 }
122 body := a.get("/").Body
123 if !strings.Contains(body, `<a class="app" href="https://oldco-scratchpad.old.example/">`) || strings.Contains(body, "acme-scratchpad") {
124 t.Fatalf("tile does not use the recorded host:\n%s", body)
125 }
126}
127
128var (
129 appsRE = regexp.MustCompile(`(?s)<nav class="apps glass" aria-label="Apps">\s*<ul class="app-grid">(.*?)</ul>\s*</nav>`)
130 itemRE = regexp.MustCompile(`<li( class="own")?><a class="app" href="([^"]*)"( target="_blank" rel="noopener")?><span class="icon[^"]*">(.*?)</span><span class="label">([^<]*)</span></a></li>`)
131 appIconRE = regexp.MustCompile(`^<img src="(/static/oficina/[a-z]+\.[0-9a-f]+\.svg)" alt="">$`)
132 oficinaApps = []config.OficinaApp{
133 {ID: "fichas", Name: "Fichas", Origin: "https://fichas.oficina.works"},
134 {ID: "calendar", Name: "Calendar", Origin: "https://calendar.oficina.works"},
135 {ID: "equipo", Name: "Equipo", Origin: "https://equipo.bds.oncarlos.com"},
136 }
137)
138
139type homeItem struct {
140 Href, Icon, Name string
141 NewTab, Own bool // Own: one of Base's own pages, which CSS starts on a row of their own
142}
143
144// homeApps is Home's apps panel: one grid of every app.
145func homeApps(t *testing.T, body string) []homeItem {
146 t.Helper()
147 m := appsRE.FindStringSubmatch(body)
148 if m == nil {
149 t.Fatalf("no apps panel:\n%s", body)
150 }
151 var out []homeItem
152 for _, i := range itemRE.FindAllStringSubmatch(m[1], -1) {
153 out = append(out, homeItem{Own: i[1] != "", Href: i[2], NewTab: i[3] != "", Icon: i[4], Name: i[5]})
154 }
155 return out
156}
157
158// Home's apps panel holds every app in one grid, all alike: the team's
159// Oficina apps in the setting's order (each opening in a new tab, with
160// Estilo's icon served from Base), then the installed Store apps (by app
161// id, as the Store keeps them), then Base's own Store, People and
162// Settings. There is no dock. The same markup serves a phone.
163func TestHomeAppsPanel(t *testing.T) {
164 a := newAppConfigured(t, func(*sql.DB, config.Config) web.Installer { return noInstaller{} }, time.UTC,
165 func(c *config.Config) { c.OficinaApps = oficinaApps })
166 a.signedInOwner()
167 a.setInstall("welcome", "installed", "")
168 a.setInstall("scratchpad", "installed", "")
169 body := a.get("/").Body
170 grid := homeApps(t, body)
171 var names []string
172 for _, i := range grid {
173 names = append(names, i.Name)
174 }
175 if want := "Fichas Calendar Equipo Scratchpad Welcome Store People Settings"; strings.Join(names, " ") != want {
176 t.Fatalf("grid %v, want %s", names, want)
177 }
178 for i, want := range oficinaApps {
179 g := grid[i]
180 if g.Href != want.Origin+"/" || !g.NewTab {
181 t.Errorf("%s: href %q, new tab %v", want.Name, g.Href, g.NewTab)
182 }
183 icon := appIconRE.FindStringSubmatch(g.Icon)
184 if icon == nil || !strings.HasPrefix(icon[1], "/static/oficina/"+want.ID+".") {
185 t.Errorf("%s: icon %q", want.Name, g.Icon)
186 continue
187 }
188 if r := a.get(icon[1]); r.Code != 200 || r.Header.Get("Content-Type") != "image/svg+xml" {
189 t.Errorf("%s: %d %q", icon[1], r.Code, r.Header.Get("Content-Type"))
190 }
191 }
192 for _, g := range grid[:5] {
193 if g.Own {
194 t.Errorf("%s is marked as Base's own", g.Name)
195 }
196 }
197 for _, g := range grid[len(oficinaApps):5] {
198 if g.NewTab || !strings.HasPrefix(g.Href, "https://acme-") || !strings.HasPrefix(g.Icon, "<svg") {
199 t.Errorf("installed app %s: href %q, new tab %v, icon %.20q", g.Name, g.Href, g.NewTab, g.Icon)
200 }
201 }
202 for i, href := range []string{"/store", "/people", "/settings"} {
203 if g := grid[5+i]; g.Href != href || g.NewTab || !g.Own || !strings.HasPrefix(g.Icon, "<svg") {
204 t.Errorf("Base's own %s: %+v", href, g)
205 }
206 }
207 for _, gone := range []string{`class="dock"`, `class="rail`, `rail-more`, `action="/rail"`, "Keep expanded", "Collapse", `class="oficina"`} {
208 if strings.Contains(body, gone) {
209 t.Errorf("Home still has %s", gone)
210 }
211 }
212 if r := a.post("/rail", url.Values{"expanded": {"1"}}); r.Code != 404 && r.Code != 405 {
213 t.Errorf("POST /rail: %d, want it gone", r.Code)
214 }
215}
216
217// With no Oficina apps and nothing installed, the grid is Base's own pages.
218func TestHomeAppsPanelEmpty(t *testing.T) {
219 a := newApp(t)
220 a.signedInOwner()
221 if grid := homeApps(t, a.get("/").Body); len(grid) != 3 || grid[0].Href != "/store" {
222 t.Fatalf("grid %v", grid)
223 }
224}
225
226// Every app Base knows has its icon.
227func TestEveryOficinaAppHasAnIcon(t *testing.T) {
228 a := newApp(t)
229 for _, id := range config.OficinaIDs() {
230 if r := a.get("/static/oficina/" + id + ".svg"); r.Code != 200 || !strings.Contains(r.Body, "<svg") {
231 t.Errorf("%s: %d", id, r.Code)
232 }
233 }
234}
235
236// deskClosed reports whether Home draws Ask Base closed on a wide screen:
237// <html class="desk-closed">.
238func deskClosed(t *testing.T, body string) bool {
239 t.Helper()
240 m := regexp.MustCompile(`<html[^>]*>`).FindString(body)
241 if m == "" {
242 t.Fatalf("no <html> in:\n%s", body)
243 }
244 return strings.Contains(m, `class="desk-closed"`)
245}
246
247// Home for a member with Ask Base draws the chat docked beside it, open
248// with the conversation, until they close it: POST /ask/dock (open=0, by
249// the X) draws <html class="desk-closed"> on every later visit, and open=1
250// (the Base button, the field) clears it. It is theirs alone, a cross-site
251// post changes nothing, and without Equipo there is no chat at all.
252func TestHomeDocksAskOpenByDefault(t *testing.T) {
253 a, f := newAskApp(t)
254 a.connectEquipo(f)
255 f.Say("Your week is clear.")
256 home := a.get("/")
257 if home.Code != 200 || deskClosed(t, home.Body) {
258 t.Fatalf("Home: %d, closed %v", home.Code, deskClosed(t, home.Body))
259 }
260 for _, want := range []string{
261 `<aside id="ask-panel" class="ask-panel glass"`,
262 `<li class="msg coordinator"`, "Your week is clear.",
263 `<form class="composer" method="post" action="/ask/messages" `,
264 // The X, and the Base button and the field that bring it back.
265 `<form class="dock-close" method="post" action="/ask/dock"><input type="hidden" name="open" value="0">`,
266 `<form class="base-btn-form" method="post" action="/ask/dock"><input type="hidden" name="open" value="1">`,
267 `<form class="ask-field-form" method="post" action="/ask/dock"><input type="hidden" name="open" value="1">`,
268 // On a phone they are links to /ask, which works without scripts
269 // and keeps no wide-screen choice.
270 `<a class="base-btn" href="/ask" data-ask-open aria-controls="ask-panel" aria-label="Ask Base" title="Ask Base">`,
271 `<a class="ask-field" href="/ask" data-ask-open aria-controls="ask-panel"><span>Ask Base anything</span>`,
272 } {
273 if !strings.Contains(home.Body, want) {
274 t.Errorf("Home lacks %q:\n%s", want, home.Body)
275 }
276 }
277 if strings.Contains(home.Body, "<dialog") {
278 t.Error("Home still draws the chat as a dialog")
279 }
280
281 if r := a.post("/ask/dock", url.Values{"open": {"0"}}); r.Code != 303 || r.Location() != "/" {
282 t.Fatalf("close: %d %q", r.Code, r.Location())
283 }
284 if !deskClosed(t, a.get("/").Body) {
285 t.Error("closed, Home draws it open")
286 }
287 if r := a.postJSON("/ask/dock", url.Values{"open": {"1"}}); r.Code != 204 {
288 t.Fatalf("open by fetch: %d %s", r.Code, r.Body)
289 }
290 if deskClosed(t, a.get("/").Body) {
291 t.Error("opened again, Home draws it closed")
292 }
293 if r := a.postJSON("/ask/dock", url.Values{"open": {"0"}}); r.Code != 204 {
294 t.Fatalf("close by fetch: %d %s", r.Code, r.Body)
295 }
296 if r := a.post("/ask/dock", url.Values{"open": {"1"}}); r.Code != 303 || r.Location() != "/" {
297 t.Fatalf("open: %d %q", r.Code, r.Location())
298 }
299 if deskClosed(t, a.get("/").Body) {
300 t.Error("opened by the form, Home draws it closed")
301 }
302 for _, v := range []string{"", "2", "true"} {
303 if r := a.post("/ask/dock", url.Values{"open": {v}}); r.Code != 400 {
304 t.Errorf("open=%q: %d", v, r.Code)
305 }
306 }
307 if r := a.postFrom("https://evil.example", "/ask/dock", url.Values{"open": {"0"}}); r.Code != 403 {
308 t.Errorf("cross-site close: %d", r.Code)
309 }
310 if deskClosed(t, a.get("/").Body) {
311 t.Error("a cross-site post closed it")
312 }
313
314 // Another member's is their own.
315 a.post("/ask/dock", url.Values{"open": {"0"}})
316 a.post("/people", invite("maria@acme.co"))
317 if r := a.signIn("maria@acme.co"); r.Code != 303 {
318 t.Fatalf("maria sign-in: %d", r.Code)
319 }
320 if body := a.get("/").Body; deskClosed(t, body) || !strings.Contains(body, `<aside id="ask-panel"`) {
321 t.Errorf("the owner's close reached another member:\n%s", body)
322 }
323 owner, _, err := store.MemberByEmail(context.Background(), a.DB, ownerAddress)
324 if err != nil || !owner.AskClosed {
325 t.Errorf("the owner's close: %v %v", owner.AskClosed, err)
326 }
327
328 // Without Equipo: no chat column, no Base button, no field.
329 off := newApp(t)
330 off.signedInOwner()
331 body := off.get("/").Body
332 for _, gone := range []string{`id="ask-panel"`, "base-btn", "ask-field", `action="/ask/dock"`, "Ask Base anything", "<aside"} {
333 if strings.Contains(body, gone) {
334 t.Errorf("Home without Equipo has %q:\n%s", gone, body)
335 }
336 }
337 if deskClosed(t, body) {
338 t.Error("Home without Equipo is drawn closed")
339 }
340 if r := off.post("/ask/dock", url.Values{"open": {"0"}}); r.Code != 404 {
341 t.Errorf("/ask/dock without Equipo: %d", r.Code)
342 }
343}
344
345// Home never waits on Equipo: with the conversation's read stalled, Home
346// answers well inside the client's own 20 s, the chat docked open with
347// its composer and nothing claimed about the conversation (the panel's
348// script reads it). With the chat closed Home does not read it at all.
349func TestHomeDoesNotWaitOnAStalledSnapshot(t *testing.T) {
350 a, f := newAskApp(t)
351 a.connectEquipo(f)
352 f.Say("Your week is clear.")
353 entered, hold := f.HoldNextSnapshot()
354 release := sync.OnceFunc(hold)
355 defer release()
356 start := time.Now()
357 done := make(chan Resp, 1)
358 go func() { done <- a.get("/") }()
359 var home Resp
360 select {
361 case home = <-done:
362 case <-time.After(5 * time.Second):
363 t.Fatal("Home waited more than 5 s on a stalled snapshot")
364 }
365 select {
366 case <-entered:
367 default:
368 t.Fatal("Home never asked for the conversation")
369 }
370 if took := time.Since(start); home.Code != 200 || took > 4*time.Second {
371 t.Fatalf("Home: %d after %v", home.Code, took)
372 }
373 if deskClosed(t, home.Body) {
374 t.Error("Home drew the chat closed")
375 }
376 for _, want := range []string{
377 `<aside id="ask-panel" class="ask-panel glass"`,
378 `<div class="ask-chat" data-when="ready norunner oldrunner">`,
379 `<form class="composer" method="post" action="/ask/messages" `,
380 `<p class="ask-empty" data-empty hidden>`,
381 `<div class="ask-note" data-when="unavailable" hidden>`,
382 } {
383 if !strings.Contains(home.Body, want) {
384 t.Errorf("Home with a stalled snapshot lacks %q:\n%s", want, home.Body)
385 }
386 }
387 if strings.Contains(home.Body, "Your week is clear.") {
388 t.Error("the stalled snapshot was drawn")
389 }
390 release()
391
392 // Closed: Home draws the chat for the script to open, and asks Equipo
393 // nothing.
394 if r := a.post("/ask/dock", url.Values{"open": {"0"}}); r.Code != 303 {
395 t.Fatalf("close: %d", r.Code)
396 }
397 before := len(f.Calls("/api/v1/assistant/snapshot"))
398 closed := a.get("/")
399 if n := len(f.Calls("/api/v1/assistant/snapshot")) - before; n != 0 {
400 t.Errorf("Home with the chat closed read the conversation %d times", n)
401 }
402 if !deskClosed(t, closed.Body) || !strings.Contains(closed.Body, `<form class="composer" method="post" action="/ask/messages" `) ||
403 !strings.Contains(closed.Body, `<p class="ask-empty" data-empty hidden>`) {
404 t.Errorf("Home with the chat closed:\n%s", closed.Body)
405 }
406}
407