oficina / mapa Public

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

Plain git — no account needed to clone.

Download

Download this file

1//go:build browser
2
3// Gate 7, scriptless (spec §11): the walk through today's note, ⌘K,
4// create, link, save and conflict, in a real Chromium with JavaScript
5// off and then on. The harness fails on any console error, failed
6// request or 4xx/5xx, and on any JS value leaked to the screen.
7//
8// make browser
9//
10// It needs a Chromium: on PATH, via RASTRILLO_CHROME, or in a Playwright
11// cache. A skip is not a pass.
12package mapatest
13
14import (
15 "context"
16 "io"
17 "log/slog"
18 "net/http"
19 "net/http/httptest"
20 "path/filepath"
21 "strconv"
22 "strings"
23 "testing"
24 "time"
25
26 "amadan.net/rastrillo/rastrillo/blobs"
27 "amadan.net/rastrillo/rastrillo/db"
28 "amadan.net/rastrillo/rastrillo/harness"
29 "github.com/chromedp/cdproto/cdp"
30 "github.com/chromedp/cdproto/emulation"
31 "github.com/chromedp/chromedp"
32 "github.com/chromedp/chromedp/kb"
33
34 "amadan.net/oficina/mapa/internal/mapa"
35)
36
37// browserRig is the app signed in as Ana, at the rig's own origin, and
38// the store, so Bo can write in between as a teammate would. Every
39// request asks for en-IE, the team's default, whatever the browser's
40// own Accept-Language says (build note 85).
41func browserRig(t *testing.T, pages int,
42 options ...harness.Option) (*harness.Rig, *mapa.Store) {
43 return browserRigOf(t, pages, "en-IE", nil, options...)
44}
45
46// browserRigAsking is browserRig with each request's Accept-Language
47// replaced by language; "" leaves the browser's own.
48func browserRigAsking(t *testing.T, pages int, language string,
49 options ...harness.Option) (*harness.Rig, *mapa.Store) {
50 return browserRigOf(t, pages, language, nil, options...)
51}
52
53// browserRigWith is browserRig with its images kept in a directory, as
54// development keeps them, seen through wrap when there is one: the
55// images' L9 holds uploads in flight with it.
56func browserRigWith(t *testing.T, pages int,
57 wrap func(blobs.Store) blobs.Store,
58 options ...harness.Option) (*harness.Rig, *mapa.Store) {
59 return browserRigOf(t, pages, "en-IE", wrap, options...)
60}
61
62// browserRigOf is the rig asking for language, its images seen through
63// wrap when there is one.
64func browserRigOf(t *testing.T, pages int, language string,
65 wrap func(blobs.Store) blobs.Store,
66 options ...harness.Option) (*harness.Rig, *mapa.Store) {
67 var store *mapa.Store
68 rig := harness.New(t, func(origin string) http.Handler {
69 logger := slog.New(slog.NewTextHandler(io.Discard, nil))
70 database, err := db.Open(filepath.Join(t.TempDir(), "mapa.db"),
71 logger)
72 if err != nil {
73 t.Fatal(err)
74 }
75 t.Cleanup(func() { database.Close() })
76 env := testEnv(Ana + "," + Bo)
77 env["MAPA_ORIGIN"] = origin
78 config, err := mapa.LoadConfig(func(key string) string {
79 return env[key]
80 })
81 if err != nil {
82 t.Fatal(err)
83 }
84 images, err := blobs.Dir(filepath.Join(t.TempDir(), "images"))
85 if err != nil {
86 t.Fatal(err)
87 }
88 if wrap != nil {
89 images = wrap(images)
90 }
91 config.Images.Objects = images
92 built, err := mapa.AppForTest(database, config, logger, Ana)
93 if err != nil {
94 t.Fatal(err)
95 }
96 store = built.Store
97 if err := mapa.SeedSynthetic(context.Background(), store, Bo,
98 pages); err != nil {
99 t.Fatal(err)
100 }
101 return asking(language, built.Mux)
102 }, options...)
103 return rig, store
104}
105
106// asking sets every request's Accept-Language to language, unless it
107// is "".
108func asking(language string, next http.Handler) http.Handler {
109 if language == "" {
110 return next
111 }
112 return http.HandlerFunc(func(writer http.ResponseWriter,
113 request *http.Request) {
114 request.Header.Set("Accept-Language", language)
115 next.ServeHTTP(writer, request)
116 })
117}
118
119// scripts turns JavaScript on or off for the pages that load next.
120func scripts(on bool) chromedp.Action[chromedp.Void] {
121 return chromedp.Func(func(ctx context.Context,
122 target *chromedp.Target) error {
123 _, err := cdp.Call(ctx, target, emulation.SetScriptExecutionDisabled,
124 emulation.SetScriptExecutionDisabledParams{Value: !on})
125 return err
126 })
127}
128
129// written is a page's text as read, never the script's live preview.
130const written = `article[mapa-body]:not([mapa-preview])`
131
132// save is the page's Save: the primary submit of its form.
133const save = `main form button[type="submit"][rst-btn~="primary"]`
134
135// press activates a control the way a keyboard does: focus, then Enter.
136func press(selector string) chromedp.Action[chromedp.Void] {
137 return chromedp.Steps(chromedp.Focus(selector), chromedp.KeyEvent("\r"))
138}
139
140// drive runs steps with a deadline, so a step that cannot happen fails
141// the test instead of waiting for ever.
142func drive(t *testing.T, rig *harness.Rig,
143 steps ...chromedp.Action[chromedp.Void]) {
144 t.Helper()
145 ctx, cancel := context.WithTimeout(rig.Context(), 20*time.Second)
146 defer cancel()
147 if err := chromedp.Do(ctx, steps...); err != nil {
148 t.Fatalf("a step did not happen: %v", err)
149 }
150}
151
152// read runs one action that returns a value, with a deadline.
153func read[T any](t *testing.T, rig *harness.Rig, action chromedp.Action[T]) T {
154 t.Helper()
155 ctx, cancel := context.WithTimeout(rig.Context(), 20*time.Second)
156 defer cancel()
157 value, err := chromedp.Run(ctx, action)
158 if err != nil {
159 t.Fatalf("could not read the page: %v", err)
160 }
161 return value
162}
163
164func text(t *testing.T, rig *harness.Rig, selector string) string {
165 t.Helper()
166 return read(t, rig, chromedp.Text(selector))
167}
168
169func TestGate7TheWalkWithScriptsOff(t *testing.T) {
170 rig, store := browserRig(t, 0)
171 rig.Run(scripts(false))
172 walk(t, rig, store, false)
173}
174
175func TestGate7TheWalkWithScriptsOn(t *testing.T) {
176 rig, store := browserRig(t, 0)
177 rig.Run(scripts(true))
178 walk(t, rig, store, true)
179}
180
181// walk is gate 7's walk: today's note, search, create, link, save,
182// conflict.
183func walk(t *testing.T, rig *harness.Rig, store *mapa.Store, live bool) {
184 t.Helper()
185 drive(t, rig, chromedp.Navigate(rig.Origin+"/"))
186 writeToday(t, rig, live)
187 rig.Screen(`[mapa-actions] a[href$="/edit"]`, "today, written")
188 if !strings.Contains(text(t, rig, written), "about the pilot") {
189 t.Fatal("today's note did not save")
190 }
191 if live {
192 searchByPalette(t, rig)
193 } else {
194 searchByPage(t, rig)
195 }
196 rig.Screen(`main input[name="title"]`, "create, offered")
197 createAcme(t, rig)
198 rig.Screen("header[mapa-page-head]", "the new page")
199 if !strings.Contains(text(t, rig, "#backlinks ~ *, [mapa-linked]"),
200 "November") {
201 t.Fatal("the new page does not show today's note linking to it")
202 }
203 saveAndConflict(t, rig, store, live)
204 if live {
205 historyInPlace(t, rig)
206 }
207 historyAndRestore(t, rig)
208}
209
210// createAcme creates the offered page, then writes its text. New page
211// is one title field (build note 77), so the text is written on the
212// page, here through Edit as Markdown, the floor.
213func createAcme(t *testing.T, rig *harness.Rig) {
214 t.Helper()
215 drive(t, rig, press(save), chromedp.WaitVisible("h1[mapa-title]"))
216 path := strings.TrimPrefix(read(t, rig, chromedp.Location()),
217 rig.Origin)
218 drive(t, rig, chromedp.Navigate(rig.Origin+path+"/edit"),
219 chromedp.SendKeys("textarea[mapa-editor]", "Acme is a customer."),
220 press(save))
221}
222
223// writeToday writes today's note: in the page editor with scripts, and
224// with them off through Edit as Markdown, the floor (level-up §6.10).
225func writeToday(t *testing.T, rig *harness.Rig, live bool) {
226 if !live {
227 rig.Screen(`[mapa-actions] a[href$="/edit"]`, "today, unwritten")
228 drive(t, rig, chromedp.Click(`[mapa-actions] a[href$="/edit"]`),
229 chromedp.WaitVisible("textarea[mapa-editor]"),
230 chromedp.SendKeys("textarea[mapa-editor]",
231 "Met [[Acme]] about the pilot."),
232 press(save))
233 return
234 }
235 rig.Screen(mounted, "today, unwritten")
236 drive(t, rig, caretAt(0),
237 chromedp.KeyEvent("Met [[Acme]] about the pilot."),
238 chromedp.KeyEvent("s", mod()))
239 read(t, rig, chromedp.Poll[bool](`mapaEditor.saver.version === "0" &&
240 mapaEditor.saver.base !== "0"`))
241 drive(t, rig, chromedp.Reload(), chromedp.WaitVisible(mounted))
242}
243
244// searchByPage is ⌘K without scripts: GET /search?q= as a full page,
245// and its Create offer.
246func searchByPage(t *testing.T, rig *harness.Rig) {
247 drive(t, rig, chromedp.Navigate(rig.Origin+"/search"))
248 rig.Screen(`input[name="q"]`, "search")
249 drive(t, rig,
250 chromedp.SendKeys(`input[name="q"]`, "Acme"),
251 chromedp.Submit(`input[name="q"]`),
252 )
253 rig.Screen("[mapa-create] a", "search results")
254 create := read(t, rig, chromedp.AttributeValue("[mapa-create] a",
255 "href")).Value
256 drive(t, rig, chromedp.Navigate(rig.Origin+create))
257}
258
259// searchByPalette is ⌘K with scripts: the box over everything, and its
260// Create offer, chosen with the keyboard.
261func searchByPalette(t *testing.T, rig *harness.Rig) {
262 drive(t, rig,
263 chromedp.KeyEvent("k", chromedp.KeyModifiers(
264 chromedp.ModifierCtrl)),
265 chromedp.WaitVisible("dialog[mapa-palette] input"),
266 chromedp.SendKeys("dialog[mapa-palette] input", "Acme"),
267 // The answer to the whole word, not to "Acm": each keystroke
268 // asks, and an earlier answer can be on screen first.
269 chromedp.WaitVisible(
270 `[mapa-palette-results] a[href="/new?title=Acme"]`),
271 )
272 if !strings.Contains(text(t, rig, "[mapa-palette-results]"), "Create") {
273 t.Fatal("⌘K does not offer to create Acme")
274 }
275 // Create is the last choice: up from the first wraps to it.
276 drive(t, rig, chromedp.KeyEvent(kb.ArrowUp), chromedp.KeyEvent("\r"))
277}
278
279// saveAndConflict edits the page, has Bo save the same block meanwhile,
280// and settles the conflict by choosing.
281func saveAndConflict(t *testing.T, rig *harness.Rig, store *mapa.Store,
282 live bool) {
283 path := strings.TrimPrefix(read(t, rig, chromedp.Location()),
284 rig.Origin)
285 drive(t, rig, chromedp.Navigate(rig.Origin+path+"/edit"))
286 rig.Screen("textarea[mapa-editor]", "the editor")
287 drive(t, rig,
288 chromedp.SendKeys("textarea[mapa-editor]", "Ana's words. "),
289 )
290 if live {
291 assistedEditing(t, rig)
292 }
293 writeAsBo(t, store, path)
294 drive(t, rig, press(save))
295 rig.Screen("form[mapa-conflict]", "the conflict view")
296 drive(t, rig,
297 chromedp.Focus(`input[value="mine"]`),
298 chromedp.KeyEvent(" "),
299 press(`form[mapa-conflict] button[type="submit"]`),
300 )
301 rig.Screen("header[mapa-page-head]", "after choosing")
302 got := text(t, rig, written)
303 if !strings.Contains(got, "Ana's words") || strings.Contains(got, "Bo") {
304 t.Fatalf("the choice did not stick: %q", got)
305 }
306}
307
308// writeAsBo saves the page's only block as Bo, through the store.
309func writeAsBo(t *testing.T, store *mapa.Store, path string) {
310 t.Helper()
311 ctx := context.Background()
312 pageID, _, err := store.RowID(ctx, strings.TrimPrefix(path, "/p/"))
313 if err != nil {
314 t.Fatal(err)
315 }
316 viewer, _ := store.Viewer(ctx, Bo, nil)
317 history, err := store.History(ctx, viewer, pageID, 0)
318 if err != nil || len(history.Versions) == 0 {
319 t.Fatalf("history: %v", err)
320 }
321 if _, err := store.Commit(ctx, Bo, pageID, history.Versions[0].Revision,
322 "Acme, as Bo has it."); err != nil {
323 t.Fatal(err)
324 }
325}
326
327// assistedEditing is what scripts add to the editor: the preview, [[
328// completion, and an autosave that writes a draft and not the page.
329func assistedEditing(t *testing.T, rig *harness.Rig) {
330 drive(t, rig,
331 chromedp.SendKeys("textarea[mapa-editor]", " See [[Acm"),
332 chromedp.WaitVisible("[mapa-suggest] li"),
333 chromedp.KeyEvent("\r"),
334 chromedp.WaitVisible("[mapa-preview] a"),
335 chromedp.Sleep(2*time.Second),
336 )
337 value := read(t, rig, chromedp.Value("textarea[mapa-editor]"))
338 if !strings.Contains(value, "See [[Acme]]") {
339 t.Fatalf("[[ completion left %q", value)
340 }
341 status := text(t, rig, "[mapa-status]")
342 if !strings.Contains(status, "Draft saved") {
343 t.Fatalf("no autosave: %q", status)
344 }
345}
346
347// TestKeystrokeToResults is §6.1's second warm target, at gate 6's size:
348// from a keystroke in ⌘K to its results, p95 ≤ 100 ms, same machine.
349//
350// **What is asserted is keystroke to results in the page**, timed inside
351// the page from the keystroke to the result list changing: the app's
352// whole part, request and render included. Paint follows in the next
353// frame on a real screen. Headless Chromium has no display to pace its
354// frames, and its next animation frame arrived 20 to 150 ms late with
355// the list long since rendered, so that figure is logged, not asserted
356// (spec §15, build note). Keys are typed from the page, as an input
357// event, because a DevTools key event is held for the renderer's next
358// frame for the same reason.
359func TestKeystrokeToResults(t *testing.T) {
360 ctx := plainBrowser(t, fixturePages)
361 run := func(steps ...chromedp.Action[chromedp.Void]) {
362 t.Helper()
363 if err := chromedp.Do(ctx, steps...); err != nil {
364 t.Fatal(err)
365 }
366 }
367 run(chromedp.WaitVisible(`input[name="q"]`),
368 chromedp.KeyEvent("k", chromedp.KeyModifiers(chromedp.ModifierCtrl)),
369 chromedp.WaitVisible("dialog[mapa-palette] input"),
370 chromedp.Evaluate[chromedp.Void](keystrokeTimer))
371 words := mapa.SyntheticWords()
372 for _, word := range []string{"w", words[3], words[400], "stra bra",
373 mapa.SyntheticTitle(4321)} {
374 for _, key := range word {
375 run(chromedp.Evaluate[chromedp.Void](
376 "__type("+strconv.Quote(string(key))+")"),
377 chromedp.Sleep(120*time.Millisecond))
378 }
379 run(chromedp.Evaluate[chromedp.Void]("__clear()"),
380 chromedp.Sleep(120*time.Millisecond))
381 }
382 rendered := timings(t, ctx, "__rendered.slice(1)")
383 painted := timings(t, ctx, "__painted.slice(1)")
384 p95 := percentile(rendered, 95)
385 t.Logf("keystroke to results, %d keystrokes at %d pages: p50 %v, "+
386 "p95 %v; headless next frame p50 %v, p95 %v", len(rendered),
387 fixturePages, percentile(rendered, 50), p95,
388 percentile(painted, 50), percentile(painted, 95))
389 if p95 > 100*time.Millisecond {
390 t.Errorf("p95 is %v, over §6.1's 100 ms", p95)
391 }
392}
393
394func timings(t *testing.T, ctx context.Context,
395 expression string) []time.Duration {
396 t.Helper()
397 times, err := chromedp.Run(ctx, chromedp.Evaluate[[]float64](expression))
398 if err != nil || len(times) < 30 {
399 t.Fatalf("%d keystrokes timed: %v", len(times), err)
400 }
401 out := make([]time.Duration, len(times))
402 for at, millis := range times {
403 out[at] = time.Duration(millis * float64(time.Millisecond))
404 }
405 return out
406}
407
408// keystrokeTimer types into ⌘K from the page and times each keystroke to
409// the result list changing, and to the frame after.
410const keystrokeTimer = `(function () {
411 window.__rendered = [];
412 window.__painted = [];
413 var input = document.querySelector("dialog[mapa-palette] input");
414 var list = document.querySelector("[mapa-palette-results]");
415 var started = 0;
416 window.__type = function (key) {
417 started = performance.now();
418 input.value += key;
419 input.dispatchEvent(new Event("input"));
420 };
421 window.__clear = function () { started = 0; input.value = ""; };
422 new MutationObserver(function () {
423 if (!started) return;
424 var from = started;
425 started = 0;
426 __rendered.push(performance.now() - from);
427 requestAnimationFrame(function () {
428 __painted.push(performance.now() - from);
429 });
430 }).observe(list, { childList: true });
431})()`
432
433// plainBrowser serves the app with pages synthetic pages and opens its
434// search page in a headless Chromium with chromedp's defaults.
435func plainBrowser(t *testing.T, pages int) context.Context {
436 logger := slog.New(slog.NewTextHandler(io.Discard, nil))
437 database, err := db.Open(filepath.Join(t.TempDir(), "mapa.db"), logger)
438 if err != nil {
439 t.Fatal(err)
440 }
441 t.Cleanup(func() { database.Close() })
442 listener := httptest.NewUnstartedServer(nil)
443 origin := "http://" + listener.Listener.Addr().String()
444 env := testEnv(Ana + "," + Bo)
445 env["MAPA_ORIGIN"] = origin
446 config, err := mapa.LoadConfig(func(key string) string { return env[key] })
447 if err != nil {
448 t.Fatal(err)
449 }
450 built, err := mapa.AppForTest(database, config, logger, Ana)
451 if err != nil {
452 t.Fatal(err)
453 }
454 mapa.SeedSynthetic(context.Background(), built.Store, Bo, pages)
455 listener.Config.Handler = built.Mux
456 listener.Start()
457 t.Cleanup(listener.Close)
458 options := append(chromedp.DefaultExecAllocatorOptions[:],
459 chromedp.ExecPath(harness.ChromePath(t)))
460 allocator, cancelAllocator := chromedp.NewExecAllocator(
461 context.Background(), options...)
462 ctx, cancel := chromedp.NewContext(allocator)
463 t.Cleanup(func() { cancel(); cancelAllocator() })
464 err = chromedp.Do(ctx, chromedp.Navigate(origin+"/search"))
465 if err != nil {
466 t.Fatal(err)
467 }
468 return ctx
469}
470
471// Review H1: an idle commit that merges a teammate's edit, then a Save,
472// keeps both edits. Before the fix the Save went out from the unmerged
473// textarea over the merged revision and quietly undid the teammate's.
474func TestAnIdleMergeThenSaveKeepsBothEdits(t *testing.T) {
475 rig, store := browserRig(t, 0)
476 ctx := context.Background()
477 page, err := store.CreateTeamPage(ctx, Bo, "Plan", "One.\n\nTwo.")
478 if err != nil {
479 t.Fatal(err)
480 }
481 path := rig.Origin + mapa.PagePath(page)
482 drive(t, rig, scripts(true), chromedp.Navigate(path+"/edit"))
483 rig.Screen("textarea[mapa-editor]", "Ana's editor")
484 drive(t, rig, chromedp.Evaluate[chromedp.Void](
485 `document.documentElement.setAttribute("data-mapa-idle", "300")`))
486 if _, err := store.Commit(ctx, Bo, page.ID, page.Revision,
487 "One.\n\nTwo, as Bo has it."); err != nil {
488 t.Fatal(err)
489 }
490 drive(t, rig, chromedp.SendKeys("textarea[mapa-editor]", "Ana: "),
491 chromedp.Sleep(3*time.Second))
492 status := text(t, rig, "[mapa-status]")
493 drive(t, rig, press(save))
494 rig.Screen("header[mapa-page-head]", "after Save")
495 got := text(t, rig, written)
496 if !strings.Contains(got, "Ana: One.") ||
497 !strings.Contains(got, "Two, as Bo has it.") {
498 t.Fatalf("an edit was lost: %q", got)
499 }
500 if !strings.Contains(status, "merged") {
501 t.Fatalf("the idle commit did not report a merge: %q", status)
502 }
503}
504