//go:build browser // The browser drive: the whole app in a real Chromium — loud on any console // error, failed request, 4xx/5xx, or JS value that leaked to the screen // unrendered. Not part of the plain suite: // // go test -tags browser ./... // // It needs a Chromium: on PATH, via RASTRILLO_CHROME, or in a Playwright // cache. A skip is not a pass — with no browser this fails, unless // RASTRILLO_BROWSER_OPTIONAL is set. // // **This file did not compile for most of fichas' life.** It called App with // the scaffold's original signature, and because the build tag keeps it out // of `make ci`, nothing noticed. A test behind a tag has to be run on // purpose, or it rots silently. package fichastest import ( "context" "encoding/base64" "io" "log/slog" "net/http" "path/filepath" "strings" "testing" "time" "amadan.net/rastrillo/rastrillo/db" "amadan.net/rastrillo/rastrillo/harness" "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/emulation" "github.com/chromedp/chromedp" fichas "amadan.net/oficina/fichas/internal/fichas" ) // browserApp is the app signed in as TestOwner, with the rig's own origin, // optionally seeded through the real store. func browserApp(t *testing.T, seed func(context.Context, *db.DB, fichas.Config)) *harness.Rig { return browserAppWith(t, nil, seed) } // browserAppWith is browserApp with its config changed first, by // configure, when that is not nil. func browserAppWith(t *testing.T, configure func(*fichas.Config), seed func(context.Context, *db.DB, fichas.Config)) *harness.Rig { return harness.New(t, func(origin string) http.Handler { logger := slog.New(slog.NewTextHandler(io.Discard, nil)) d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger) if err != nil { t.Fatalf("db.Open: %v", err) } t.Cleanup(func() { d.Close() }) cfg, err := fichas.LoadConfig(func(k string) string { return map[string]string{ "FICHAS_DEK": base64.StdEncoding.EncodeToString(testKey()), "FICHAS_INSTANCE_KEY": "browser", "FICHAS_OWNERS": TestOwner, "FICHAS_ORIGIN": origin, "FICHAS_ALLOW_LOGGED_MAIL": "1", }[k] }) if err != nil { t.Fatalf("LoadConfig: %v", err) } if configure != nil { configure(&cfg) } mux, err := fichas.AppForTest(d, cfg, logger, TestOwner) if err != nil { t.Fatalf("AppForTest: %v", err) } if seed != nil { seed(context.Background(), d, cfg) } return mux }) } func TestBrowserWalk(t *testing.T) { rig := browserApp(t, nil) rig.Run(chromedp.Navigate(rig.Origin + "/")) rig.Screen("body", "home") } // TestLiveSearch types into the search box and checks the results change // WITHOUT a page load — the claim search.js makes. A marker on window survives // only if the page was never reloaded. func TestLiveSearch(t *testing.T) { rig := browserApp(t, func(ctx context.Context, d *db.DB, cfg fichas.Config) { m, err := fichas.EnsureMember(ctx, d.G, cfg.Sealer, TestOwner) if err != nil { t.Fatalf("member: %v", err) } for _, name := range []string{"Brightwater Labs", "Halden Robotics", "Oriel Housing Trust"} { if _, err := fichas.CreateCard(ctx, d.G, cfg.Sealer, fichas.TypeCustomer, fichas.Person(m.ID), map[string]string{fichas.FieldName: name}); err != nil { t.Fatalf("seed: %v", err) } } }) var marker bool var results, location, stageHref, cardsHref string rig.Run( chromedp.Navigate(rig.Origin+"/"), chromedp.WaitVisible(`input[name="q"]`), chromedp.Evaluate[chromedp.Void](`window.__noReload = true`), chromedp.SendKeys(`input[name="q"]`, "halden"), chromedp.Sleep(600*time.Millisecond), harness.Into(&results, chromedp.Text(`[data-live-results]`)), harness.Into(&marker, chromedp.Evaluate[bool](`window.__noReload === true`)), harness.Into(&location, chromedp.Evaluate[string](`location.search`)), harness.Into(&stageHref, chromedp.Evaluate[string](`(document.querySelector('#list-filters a[href*="f_stage="]')||{}).getAttribute ? document.querySelector('#list-filters a[href*="f_stage="]').getAttribute('href') : ''`)), harness.Into(&cardsHref, chromedp.Evaluate[string](`(function(){var a=[...document.querySelectorAll('#list-toolbar a')].find(function(x){return x.textContent.trim()==='Cards'});return a?a.getAttribute('href'):''})()`)), ) // The tabs and filter menus must carry the TYPED search, not the one the // page loaded with — or choosing a filter throws the search away. if !strings.Contains(stageHref, "q=halden") { t.Fatalf("after typing, the Stage filter links to %q, dropping the search", stageHref) } if !strings.Contains(cardsHref, "q=halden") { t.Fatalf("after typing, the Cards tab links to %q, dropping the search", cardsHref) } if !marker { t.Fatal("typing reloaded the page; search.js did not take over the search") } if !strings.Contains(results, "Halden Robotics") || strings.Contains(results, "Brightwater Labs") { t.Fatalf("the results did not narrow as you typed:\n%s", results) } if !strings.Contains(location, "q=halden") { t.Fatalf("the URL did not follow the search (location.search = %q)", location) } rig.Screen("body", "live-search") } // TestCmdEnterSubmits: ⌘↩ in a textarea submits its form. func TestCmdEnterSubmits(t *testing.T) { var id int64 rig := browserApp(t, func(ctx context.Context, d *db.DB, cfg fichas.Config) { m, _ := fichas.EnsureMember(ctx, d.G, cfg.Sealer, TestOwner) c, err := fichas.CreateCard(ctx, d.G, cfg.Sealer, fichas.TypeCustomer, fichas.Person(m.ID), map[string]string{fichas.FieldName: "Brightwater Labs"}) if err != nil { t.Fatalf("seed: %v", err) } id = c.ID }) var timeline string path := rig.Origin + "/cards/" + itoa(id) rig.Run( chromedp.Navigate(path), chromedp.WaitVisible(`textarea[name="f_body"]`), chromedp.SendKeys(`textarea[name="f_body"]`, "Called about the pilot"), chromedp.KeyEvent("\r", chromedp.KeyModifiers(chromedp.ModifierMeta)), // ⌘ chromedp.Sleep(800*time.Millisecond), harness.Into(&timeline, chromedp.Text(`body`)), ) if !strings.Contains(timeline, "Called about the pilot") { t.Fatal("⌘↩ in the call-log textarea did not submit it") } } func itoa(n int64) string { b := []byte{} if n == 0 { return "0" } for n > 0 { b = append([]byte{byte('0' + n%10)}, b...) n /= 10 } return string(b) } // TestAnExpiredSessionIsNotADeadEnd: when the list answer is a redirect to // sign-in, typing must land on sign-in rather than silently doing nothing. func TestAnExpiredSessionIsNotADeadEnd(t *testing.T) { rig := browserApp(t, func(ctx context.Context, d *db.DB, cfg fichas.Config) { m, _ := fichas.EnsureMember(ctx, d.G, cfg.Sealer, TestOwner) fichas.CreateCard(ctx, d.G, cfg.Sealer, fichas.TypeCustomer, fichas.Person(m.ID), map[string]string{fichas.FieldName: "Brightwater Labs"}) }) var path string rig.Run( chromedp.Navigate(rig.Origin+"/"), chromedp.WaitVisible(`input[name="q"]`), // Point the form at a URL that redirects, as an expired session's // list request does, and type. chromedp.Evaluate[chromedp.Void](`document.querySelector('[data-live-search] form').setAttribute('action', '/cards/new?type=nope')`), chromedp.SendKeys(`input[name="q"]`, "x"), chromedp.Sleep(900*time.Millisecond), harness.Into(&path, chromedp.Evaluate[string](`location.pathname`)), ) if path == "/" { t.Fatal("a non-list answer left the page where it was; the search box is a dead end") } } // TestNoZoomOnTap: iOS Safari zooms into any form control under 16px. On a // touch screen every text input must be at least 16px. Emulated as // pointer: coarse, which is how the CSS decides. func TestNoZoomOnTap(t *testing.T) { // Both layouts: the app shell, and sign-in — the plain column with // estilo's chrome, and the field every visit starts by tapping. for _, page := range []struct{ path, ready string }{ {"/cards/new", `input[name="f_name"]`}, // A state of the door: AppForTest is signed in, and a bare /signin // sends a signed-in browser on. {"/signin?force=1", `input[name="address"]`}, // The list's search, and the type designer's forms. {"/", `input[name="q"]`}, {"/cards/1", `textarea`}, {"/cards/1/edit", `input[name="f_name"]`}, {"/t/t_customer/fields/new", `input[name="label"]`}, // the options box shows only for a Choice {"/types/new", `input[name="label"]`}, } { // One card, so the list shows its search bar and there is a card // to log a call against and to edit. rig := browserApp(t, func(ctx context.Context, d *db.DB, cfg fichas.Config) { m, err := fichas.EnsureMember(ctx, d.G, cfg.Sealer, TestOwner) if err != nil { t.Fatalf("member: %v", err) } if _, err := fichas.CreateCard(ctx, d.G, cfg.Sealer, fichas.TypeCustomer, fichas.Person(m.ID), map[string]string{fichas.FieldName: "Brightwater Labs"}); err != nil { t.Fatalf("seed: %v", err) } }) var smallest float64 var coarse bool rig.Run( chromedp.Navigate(rig.Origin+page.path), chromedp.WaitVisible(page.ready), // Touch emulation, then a reload so the page re-evaluates its // media queries. SetEmulatedMedia's "pointer" feature is not // emulated by this Chromium: the first version measured // desktop styles while claiming a phone's. The coarse check // is what caught it. send(emulation.SetTouchEmulationEnabled, emulation.SetTouchEmulationEnabledParams{Enabled: true, MaxTouchPoints: 5}), chromedp.Reload(), chromedp.WaitVisible(page.ready), harness.Into(&coarse, chromedp.Evaluate[bool](`matchMedia('(pointer: coarse)').matches`)), harness.Into(&smallest, chromedp.Evaluate[float64](`Math.min(...[...document.querySelectorAll('input:not([type=checkbox]):not([type=radio]):not([type=hidden]), select, textarea')].map(e => parseFloat(getComputedStyle(e).fontSize)))`)), ) if !coarse { t.Fatalf("%s: the touch-screen emulation did not apply; this would measure desktop styles", page.path) } if smallest < 16 { t.Errorf("%s: a form control is %.1fpx on a touch screen; iOS will zoom when it is tapped", page.path, smallest) } } } // TestTheAccountMenuInTheBar: the account sits at the bar's end (level-up // §3.1), at every width the whole panel is on screen and its Sign out is // the thing a tap at its centre reaches; Escape closes it and gives focus // back to its trigger, and a click outside closes it. func TestTheAccountMenuInTheBar(t *testing.T) { type facts struct { Open bool PanelTop, PanelLeft float64 PanelRite, VW float64 SignOutHit, EdgesHit bool } const measure = `(() => { const d = document.querySelector('[estilo-bar] [estilo-account]'), p = d.querySelector('[estilo-account-panel]') const out = d.querySelector('form[action="/signout"] button') out.scrollIntoView({block: 'nearest'}) const or = out.getBoundingClientRect(), hit = document.elementFromPoint(or.left + or.width / 2, or.top + or.height / 2) const pr = p.getBoundingClientRect(), mid = (pr.top + pr.bottom) / 2 const inP = (x) => { const h = document.elementFromPoint(x, mid); return !!h && p.contains(h) } return {Open: d.open, PanelTop: pr.top, PanelLeft: pr.left, PanelRite: pr.right, VW: document.documentElement.clientWidth, SignOutHit: !!hit && out.contains(hit), EdgesHit: inP(pr.left + 2) && inP(pr.right - 2)} })()` for _, w := range []int64{1440, 390, 320} { rig := browserApp(t, nil) var f facts var closedByEscape, focusBack, closedByOutside bool rig.Run( send(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: w, Height: 800, DeviceScaleFactor: 1}), chromedp.Navigate(rig.Origin+"/"), chromedp.WaitVisible(`[estilo-bar] [estilo-account] > summary`), chromedp.Click(`[estilo-bar] [estilo-account] > summary`), chromedp.Sleep(150*time.Millisecond), harness.Into(&f, chromedp.Evaluate[facts](measure)), chromedp.KeyEvent("\x1b"), chromedp.Sleep(100*time.Millisecond), harness.Into(&closedByEscape, chromedp.Evaluate[bool](`!document.querySelector('[estilo-account]').open`)), harness.Into(&focusBack, chromedp.Evaluate[bool](`document.activeElement === document.querySelector('[estilo-account] > summary')`)), chromedp.Click(`[estilo-bar] [estilo-account] > summary`), chromedp.Sleep(100*time.Millisecond), chromedp.MouseClickXY(20, 700), chromedp.Sleep(100*time.Millisecond), harness.Into(&closedByOutside, chromedp.Evaluate[bool](`!document.querySelector('[estilo-account]').open`)), ) if !f.Open { t.Fatalf("%dpx: the account menu did not open", w) } if f.PanelTop < 0 || f.PanelLeft < 0 || f.PanelRite > f.VW+0.5 { t.Errorf("%dpx: the panel is partly off screen: %+v", w, f) } if !f.EdgesHit { t.Errorf("%dpx: the panel's edge is clipped or covered (%.0f..%.0f)", w, f.PanelLeft, f.PanelRite) } if !f.SignOutHit { t.Errorf("%dpx: a tap at Sign out's centre does not reach it", w) } if !closedByEscape || !focusBack { t.Errorf("%dpx: Escape closed it: %v; focus back on its trigger: %v", w, closedByEscape, focusBack) } if !closedByOutside { t.Errorf("%dpx: a click outside left it open", w) } } } // send is one protocol command as a step: chromedp v0.21's commands are // values, not actions. func send[P any](command cdp.Command[P, cdp.Empty], params P) chromedp.Action[chromedp.Void] { return chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { _, err := cdp.Call(ctx, target, command, params) return err }) } // TestTheNameOpensTheCardAndACellEdits: the name opens the card beside // the list (level-up §5.4, D1), and a click on any other cell edits it in // place and opens nothing (Q10, ruled 2026-11-17). func TestTheNameOpensTheCardAndACellEdits(t *testing.T) { var id int64 rig := browserApp(t, func(ctx context.Context, d *db.DB, cfg fichas.Config) { m, _ := fichas.EnsureMember(ctx, d.G, cfg.Sealer, TestOwner) c, err := fichas.CreateCard(ctx, d.G, cfg.Sealer, fichas.TypeCustomer, fichas.Person(m.ID), map[string]string{fichas.FieldName: "Brightwater Labs", fichas.FieldDomain: "brightwater.example", fichas.FieldPhone: "+353 1 555 0142"}) if err != nil { t.Fatalf("seed: %v", err) } id = c.ID }) var editing bool var before, search string rig.Run( send(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: 1440, Height: 900, DeviceScaleFactor: 1}), chromedp.Navigate(rig.Origin+"/"), chromedp.WaitVisible(`[fichas-grid][role="grid"] tbody tr`), harness.Into(&before, chromedp.Evaluate[string](`location.pathname + location.search`)), chromedp.Click(`[fichas-grid] td[data-field="f_phone"]`), chromedp.WaitVisible(`[fichas-editor] input`), harness.Into(&editing, chromedp.Evaluate[bool](`document.activeElement === document.querySelector('[fichas-editor] input') && location.pathname + location.search === `+"`"+`/`+"`"+``)), chromedp.KeyEvent("\x1b"), chromedp.Click(`[fichas-title-link]`), chromedp.WaitVisible(`[fichas-pane] [fichas-quiet-title]`), harness.Into(&search, chromedp.Evaluate[string](`location.search`)), ) if !editing { t.Error("a click on the phone cell did not open its editor in place") } if search != "?card="+itoa(id) { t.Fatalf("the name opened %q, want the card beside the list", search) } } // TestRailIconsSitOnTheTextsCentreLine: each rail link's icon is centred // on its label. rastrillo v0.35's display: block on these links once put // every icon on the text's baseline, 3.5px high, unnoticed by any test. func TestRailIconsSitOnTheTextsCentreLine(t *testing.T) { rig := browserApp(t, nil) var offsets []float64 rig.Run( // A desktop width: below 800px the rail folds behind Menu. send(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: 1440, Height: 800, DeviceScaleFactor: 1}), chromedp.Navigate(rig.Origin+"/"), chromedp.WaitVisible(`[fichas-rail] a[fichas-rail-item]`), harness.Into(&offsets, chromedp.Evaluate[[]float64](`[...document.querySelectorAll('[fichas-rail] a[fichas-rail-item]')].map(a => { const i = a.querySelector('svg').getBoundingClientRect() const r = document.createRange(); r.selectNodeContents(a.querySelector('[fichas-rail-label]')); const tx = r.getBoundingClientRect() return (i.top + i.height / 2) - (tx.top + tx.height / 2) })`)), ) if len(offsets) < 2 { t.Fatalf("the rail has %d links; want the types and New type", len(offsets)) } for i, off := range offsets { if off < -1 || off > 1 { t.Errorf("rail link %d: its icon is %.1fpx off its label's centre line", i, off) } } } // TestChoiceOptionsShowOnlyForAChoice: the add-field form shows the box // for a Choice's options only while Choice is picked, with no script. func TestChoiceOptionsShowOnlyForAChoice(t *testing.T) { rig := browserApp(t, nil) var before, after bool const shown = `getComputedStyle(document.querySelector('[fichas-choice-options]')).display !== 'none'` rig.Run( chromedp.Navigate(rig.Origin+"/t/t_customer/fields/new"), chromedp.WaitVisible(`input[name="label"]`), harness.Into(&before, chromedp.Evaluate[bool](shown)), chromedp.Evaluate[chromedp.Void](`document.querySelector('input[name="kind"][value="enum"]').click()`), harness.Into(&after, chromedp.Evaluate[bool](shown)), ) if before { t.Error("the options box shows while Text is picked") } if !after { t.Error("the options box does not show once Choice is picked") } } // TestPrimaryButtonsAreFilled: a form's primary submit is filled with the // accent, and a danger submit is not a plain white pill. rst-btn's value // is a word list ("primary lg"); the depth styles once matched only // rst-btn="primary" exactly and turned every form's Save white. func TestPrimaryButtonsAreFilled(t *testing.T) { var id int64 rig := browserApp(t, func(ctx context.Context, d *db.DB, cfg fichas.Config) { m, _ := fichas.EnsureMember(ctx, d.G, cfg.Sealer, TestOwner) c, err := fichas.CreateCard(ctx, d.G, cfg.Sealer, fichas.TypeCustomer, fichas.Person(m.ID), map[string]string{fichas.FieldName: "Brightwater Labs"}) if err != nil { t.Fatalf("seed: %v", err) } id = c.ID }) const fill = `(() => { const probe = document.createElement('span'); probe.style.color = 'var(--rst-accent)'; document.body.append(probe) const accent = getComputedStyle(probe).color; probe.remove() const b = document.querySelector('[rst-page] form [rst-btn~="primary"], [rst-page] form [rst-btn~="danger"]') return { bg: getComputedStyle(b).backgroundColor, accent, label: b.textContent.trim() } })()` type facts struct{ Bg, Accent, Label string } for _, page := range []string{"/cards/new?type=t_customer", "/t/t_customer/fields/new", "/cards/" + itoa(id) + "/delete"} { var f facts rig.Run( chromedp.Navigate(rig.Origin+page), chromedp.WaitVisible(`[rst-page] form [rst-btn]`), harness.Into(&f, chromedp.Evaluate[facts](fill)), ) if strings.HasSuffix(page, "/delete") { if f.Bg == "rgb(255, 255, 255)" || f.Bg == "rgba(0, 0, 0, 0)" { t.Errorf("%s: the danger button %q is not filled (%s)", page, f.Label, f.Bg) } continue } if f.Bg != f.Accent { t.Errorf("%s: the primary %q is %s, not the accent %s", page, f.Label, f.Bg, f.Accent) } } } // TestTheViewTabsSitInTheToolbarsRow: rastrillo puts a margin under a // block of tabs, and in the list's toolbar row it only pushed the row // apart and lifted the tabs off its centre line (Calendar's 18px gap, // oficina/calendar #48). Mutation: deleting the fichas.css rule fails it. func TestTheViewTabsSitInTheToolbarsRow(t *testing.T) { rig := browserApp(t, func(ctx context.Context, d *db.DB, cfg fichas.Config) { m, _ := fichas.EnsureMember(ctx, d.G, cfg.Sealer, TestOwner) fichas.CreateCard(ctx, d.G, cfg.Sealer, fichas.TypeCustomer, fichas.Person(m.ID), map[string]string{fichas.FieldName: "Brightwater Labs"}) }) var margin string var offset float64 rig.Run( chromedp.Navigate(rig.Origin+"/?view=cards"), chromedp.WaitVisible(`[fichas-toolbar] [rst-seg-tabs]`), harness.Into(&margin, chromedp.Evaluate[string](`getComputedStyle(document.querySelector('[fichas-toolbar] > [rst-seg-tabs]')).marginBlockEnd`)), harness.Into(&offset, chromedp.Evaluate[float64](`(() => { const bar = document.querySelector('[fichas-toolbar]').getBoundingClientRect(); const tabs = document.querySelector('[fichas-toolbar] > [rst-seg-tabs]').getBoundingClientRect(); return Math.abs((tabs.top + tabs.bottom) / 2 - (bar.top + bar.bottom) / 2); })()`)), ) if margin != "0px" { t.Errorf("the view tabs keep a %s margin under them in the toolbar row", margin) } if offset > 1 { t.Errorf("the view tabs sit %.1fpx off the toolbar's centre line", offset) } }