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
3package mapatest
4
5import (
6 "context"
7 "io"
8 "log/slog"
9 "net/http"
10 "os"
11 "path/filepath"
12 "strings"
13 "testing"
14 "time"
15
16 "amadan.net/rastrillo/rastrillo/db"
17 "amadan.net/rastrillo/rastrillo/harness"
18 "github.com/chromedp/chromedp"
19 "gorm.io/gorm"
20
21 "amadan.net/oficina/mapa/internal/mapa"
22 "amadan.net/oficina/notion.git/notion"
23 "amadan.net/oficina/notion.git/notiontest"
24)
25
26// I15, scriptless (Notion import spec §8.4, §18): connect, start, watch
27// the meta refresh, stop, resume and finish in a real Chromium, with
28// JavaScript off and then on. The harness fails on any console error,
29// failed request or 4xx/5xx. With MAPA_IMPORT_SHOTS set to a directory
30// outside the repository, it also saves a picture of the run at each
31// stage: connect, mid-survey, mid-write, stopped and finished (§18:
32// "the run is looked at in a browser").
33
34func TestI15TheImportWithScriptsOff(t *testing.T) { importWalk(t, false) }
35
36func TestI15TheImportWithScriptsOn(t *testing.T) { importWalk(t, true) }
37
38// importRig is a browser rig where Ana may import from a fake serving
39// the documented workspace.
40func importRig(t *testing.T) (*harness.Rig, *notiontest.Server,
41 func() *gorm.DB) {
42 server := notiontest.Start(notiontest.NewDocumented().Workspace,
43 notion.APIVersion)
44 t.Cleanup(server.Close)
45 var database *db.DB
46 rig := harness.New(t, func(origin string) http.Handler {
47 logger := slog.New(slog.NewTextHandler(io.Discard, nil))
48 var err error
49 database, err = db.Open(filepath.Join(t.TempDir(), "mapa.db"),
50 logger)
51 if err != nil {
52 t.Fatal(err)
53 }
54 t.Cleanup(func() { database.Close() })
55 env := testEnv(Ana + "," + Bo)
56 env["MAPA_ORIGIN"], env["MAPA_IMPORTERS"] = origin, Ana
57 config, err := mapa.LoadConfig(func(key string) string {
58 return env[key]
59 })
60 if err != nil {
61 t.Fatal(err)
62 }
63 built, err := mapa.AppForTest(database, config, logger, Ana)
64 if err != nil {
65 t.Fatal(err)
66 }
67 built.UseNotion(fakeNotion{server: server})
68 t.Cleanup(built.WaitImports)
69 return built.Mux
70 })
71 return rig, server, func() *gorm.DB { return database.G }
72}
73
74func importWalk(t *testing.T, live bool) {
75 rig, server, database := importRig(t)
76 rig.Run(scripts(live))
77 drive(t, rig, chromedp.Navigate(rig.Origin+"/import/notion"))
78 rig.Screen(`input[name="token"]`, "connect")
79 shot(t, rig, live, "1-connect")
80 drive(t, rig, chromedp.SendKeys(`input[name="token"]`, "secret_test"),
81 press(`form[action="/import/notion/connect"] button`),
82 chromedp.WaitVisible(`form[action="/import/notion/start"]`))
83 server.Lock()
84 drive(t, rig, press(`form[action="/import/notion/start"] button`),
85 chromedp.WaitVisible(`form[action="/import/notion/stop"]`))
86 expectIn(t, rig, "Pages read so far: 0.")
87 if !strings.Contains(read(t, rig, chromedp.OuterHTML("head")),
88 `http-equiv="refresh"`) {
89 t.Error("a running import's page does not refresh itself")
90 }
91 shot(t, rig, live, "2-mid-survey")
92 drive(t, rig, press(`form[action="/import/notion/stop"] button`),
93 chromedp.WaitVisible(`form[action="/import/notion/resume"]`))
94 server.Unlock()
95 expectIn(t, rig, "You stopped the import")
96 shot(t, rig, live, "3-stopped")
97 midWrite(t, rig, database, live)
98 drive(t, rig, press(`form[action="/import/notion/resume"] button`))
99 waitFor(t, rig, "Run complete")
100 rig.Screen(`[mapa-import-report]`, "finished")
101 expectIn(t, rig, "Created")
102 shot(t, rig, live, "5-finished")
103}
104
105// midWrite shows the page as it reads at 2 of 5 written: the write
106// phase asks Notion nothing the fake could hold, so this stage is set
107// in the database, as the run would leave it, and read back.
108func midWrite(t *testing.T, rig *harness.Rig, database func() *gorm.DB,
109 live bool) {
110 now := time.Now().UTC()
111 database().Exec("UPDATE notion_runs SET state = 'writing', total = 5,"+
112 " written = 2, heartbeat_at = ?, progress_at = ?", now, now)
113 drive(t, rig, chromedp.Navigate(rig.Origin+"/import/notion"))
114 expectIn(t, rig, "2 of 5 so far.")
115 shot(t, rig, live, "4-mid-write")
116 database().Exec("UPDATE notion_runs SET state = 'stopped', total = 0," +
117 " written = 0")
118 drive(t, rig, chromedp.Navigate(rig.Origin+"/import/notion"),
119 chromedp.WaitVisible(`form[action="/import/notion/resume"]`))
120}
121
122func expectIn(t *testing.T, rig *harness.Rig, words string) {
123 t.Helper()
124 if got := text(t, rig, "main"); !strings.Contains(got, words) {
125 t.Errorf("the page does not say %q:\n%s", words, got)
126 }
127}
128
129// waitFor waits for words to appear, through the page's own refresh.
130// A read that lands while a navigation replaces the page (a form's
131// redirect, the meta refresh) is tried again, not failed: the page it
132// was reading is gone.
133func waitFor(t *testing.T, rig *harness.Rig, words string) {
134 t.Helper()
135 for deadline := time.Now().Add(30 * time.Second); time.Now().
136 Before(deadline); time.Sleep(time.Second) {
137 ctx, cancel := context.WithTimeout(rig.Context(), 5*time.Second)
138 got, err := chromedp.Run(ctx, chromedp.Text("main"))
139 cancel()
140 if err == nil && strings.Contains(got, words) {
141 return
142 }
143 }
144 t.Fatalf("the page never said %q", words)
145}
146
147// shot saves the page to MAPA_IMPORT_SHOTS, when it is set.
148func shot(t *testing.T, rig *harness.Rig, live bool, name string) {
149 dir := os.Getenv("MAPA_IMPORT_SHOTS")
150 if dir == "" {
151 return
152 }
153 if live {
154 name += "-scripts-on"
155 }
156 picture := read(t, rig, chromedp.FullScreenshot(90))
157 if err := os.WriteFile(filepath.Join(dir, name+".png"), picture,
158 0o600); err != nil {
159 t.Fatal(err)
160 }
161}
162