oficina / base Public

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

Plain git — no account needed to clone.

Download

Download this file

1//go:build browser
2
3package browsertest
4
5import (
6 "context"
7 "database/sql"
8 "html"
9 "io"
10 "log/slog"
11 "net/http"
12 "path/filepath"
13 "regexp"
14 "sync"
15 "testing"
16 "time"
17
18 "github.com/chromedp/chromedp"
19
20 "amadan.net/rastrillo/rastrillo"
21 "amadan.net/rastrillo/rastrillo/db"
22 "amadan.net/rastrillo/rastrillo/harness"
23 _ "amadan.net/rastrillo/rastrillo/locales/en"
24 "amadan.net/rastrillo/rastrillo/migrate"
25 "amadan.net/rastrillo/rastrillo/pow"
26
27 "amadan.net/oficina/base/internal/config"
28 "amadan.net/oficina/base/internal/store"
29 "amadan.net/oficina/base/internal/web"
30)
31
32const (
33 ownerAddress = "paul@acme.test"
34 ownerName = "Paul Campbell"
35 baseName = "Acme Ltd"
36 // timelessFont is preloaded by every page. It is git-ignored and fetched
37 // by make fonts, so on a machine without it the browser gets a 404 and
38 // the page falls back to DM Sans, as designed.
39 timelessFont = "/static/fonts/timeless/1.094/TimelessSansVF.woff2"
40)
41
42var quiet = slog.New(slog.NewTextHandler(io.Discard, nil))
43
44// mailbox keeps every message Base sends.
45type mailbox struct {
46 mu sync.Mutex
47 bodies []string
48}
49
50func (m *mailbox) Send(_ context.Context, _, _, body string) error {
51 m.mu.Lock()
52 defer m.mu.Unlock()
53 m.bodies = append(m.bodies, body)
54 return nil
55}
56
57func (m *mailbox) count() int { m.mu.Lock(); defer m.mu.Unlock(); return len(m.bodies) }
58
59var linkRE = regexp.MustCompile(`https?://[^\s"<>]+/auth/verify\?[^\s"<>]+`)
60
61// lastLink is the sign-in link in the latest message.
62func (m *mailbox) lastLink(t *testing.T) string {
63 t.Helper()
64 m.mu.Lock()
65 defer m.mu.Unlock()
66 if len(m.bodies) == 0 {
67 t.Fatal("Base sent no email")
68 }
69 body := html.UnescapeString(m.bodies[len(m.bodies)-1])
70 link := linkRE.FindString(body)
71 if link == "" {
72 t.Fatalf("no sign-in link in:\n%s", body)
73 }
74 return link
75}
76
77type noInstaller struct{}
78
79func (noInstaller) Start(context.Context, string) error { return nil }
80func (noInstaller) Uninstall(context.Context, string) error { return nil }
81
82// baseApp is one Base over its own database, with the owner seeded.
83type baseApp struct {
84 cfg config.Config
85 db *sql.DB
86 mail *mailbox
87 handler http.Handler // wrapped as production wraps it
88}
89
90// baseConfig is the configuration every test starts from.
91func baseConfig(origin string) config.Config {
92 return config.Config{Origin: origin, Name: baseName, Owner: ownerAddress, InstanceKey: "browser-instance-key",
93 AllowLoggedMail: true, Slug: "acme", AppsDomain: "test", Timezone: time.UTC}
94}
95
96// newBase builds Base as cmd/base/main.go does: BootSchema applied, the owner
97// bootstrapped, web.App wrapped by rastrillo's serving stack.
98func newBase(t *testing.T, cfg config.Config) *baseApp {
99 t.Helper()
100 d, err := db.Open(filepath.Join(t.TempDir(), "base.db"), quiet)
101 if err != nil {
102 t.Fatal(err)
103 }
104 t.Cleanup(func() { d.Close() })
105 ctx := context.Background()
106 if _, err := migrate.Apply(ctx, d, store.BootSchema); err != nil {
107 t.Fatal(err)
108 }
109 if err := store.Bootstrap(ctx, d.Writer(), cfg.Owner); err != nil {
110 t.Fatal(err)
111 }
112 if _, err := d.Writer().Exec(`UPDATE members SET name = ?`, ownerName); err != nil {
113 t.Fatal(err)
114 }
115 b := &baseApp{cfg: cfg, db: d.Writer(), mail: &mailbox{}}
116 h, err := web.App(d, cfg, b.mail, noInstaller{}, quiet)
117 if err != nil {
118 t.Fatalf("web.App: %v", err)
119 }
120 b.handler = served(t, h)
121 return b
122}
123
124// served wraps h in what rastrillo.Serve puts around an app in production
125// (cmd/base and appboot): the framework's endpoints, panic recovery and the
126// security headers, default CSP and Referrer-Policy included. Only the
127// listener differs.
128func served(t *testing.T, h http.Handler) http.Handler {
129 t.Helper()
130 mux := http.NewServeMux()
131 mux.Handle("/", h)
132 out, closeAll, err := rastrillo.Handler(rastrillo.Options{Mux: mux, Logger: quiet})
133 if err != nil {
134 t.Fatalf("rastrillo.Handler: %v", err)
135 }
136 t.Cleanup(func() { closeAll() })
137 return out
138}
139
140// driveBudget bounds one drive: a wait for something that never comes fails
141// as itself instead of hanging the suite until go test's own timeout.
142const driveBudget = 30 * time.Second
143
144// drive runs steps under driveBudget and fails the test with what was on
145// screen, as the harness's own Run does.
146func drive(t *testing.T, rig *harness.Rig, steps ...chromedp.Action[chromedp.Void]) {
147 t.Helper()
148 ctx, cancel := context.WithTimeout(rig.Context(), driveBudget)
149 defer cancel()
150 if err := chromedp.Do(ctx, steps...); err != nil {
151 here, _ := chromedp.Run(rig.Context(), chromedp.Location())
152 text, _ := chromedp.Run(rig.Context(), chromedp.Evaluate[string](`document.body ? document.body.innerText : ""`))
153 t.Fatalf("drive failed at %s: %v\non screen:\n%s", here, err, text)
154 }
155}
156
157// newRig starts Chromium with the harness's watchers. The font every page
158// preloads may be missing on this machine; that 404 is expected.
159func newRig(t *testing.T, build func(origin string) http.Handler) *harness.Rig {
160 t.Helper()
161 rig := harness.New(t, build)
162 rig.Allow(http.MethodGet, timelessFont, http.StatusNotFound)
163 return rig
164}
165
166// signInByEmail signs the owner in at origin the way a person does: type the
167// address, press Continue, open the emailed link and press Sign in. It ends
168// on Home.
169func signInByEmail(t *testing.T, rig *harness.Rig, origin string, mail *mailbox) {
170 t.Helper()
171 address := `input[name="address"]`
172 drive(t, rig, chromedp.Navigate(origin+"/signin"), chromedp.WaitVisible(chromedp.CSS(address)))
173 rig.Screen(".card", "the sign-in page")
174 drive(t, rig,
175 chromedp.SendKeys(chromedp.CSS(address), ownerAddress),
176 // Base refuses a sign-in form sent sooner than a person could read it.
177 chromedp.Sleep(pow.DefaultMinAge+300*time.Millisecond),
178 chromedp.Click(chromedp.CSS(`form[action="/auth/begin"] button[type="submit"]`)),
179 chromedp.WaitVisible(chromedp.CSS(`form[action="/auth/forget"]`)),
180 )
181 rig.Screen(".card", "Check your email")
182 signIn := `form[action$="/auth/verify"] button[type="submit"]`
183 drive(t, rig, chromedp.Navigate(mail.lastLink(t)), chromedp.WaitVisible(chromedp.CSS(signIn)))
184 rig.Screen(".card", "the emailed link's page")
185 drive(t, rig, chromedp.Click(chromedp.CSS(signIn)), chromedp.WaitVisible(chromedp.CSS(".hello")))
186 rig.Screen("main", "Home")
187 if here := harness.Read(rig, chromedp.Location()); here != origin+"/" {
188 t.Fatalf("signing in by email ended at %s", here)
189 }
190}
191