oficina / mapa Public

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

Plain git — no account needed to clone.

Download

Download this file

1package mapa
2
3import (
4 "context"
5 "net/http"
6 "net/http/httptest"
7 "strings"
8 "testing"
9
10 "amadan.net/rastrillo/rastrillo/blobs"
11
12 "amadan.net/oficina/notion.git/notion"
13 "amadan.net/oficina/notion.git/notiontest"
14)
15
16// The image step against Mapa images itself (gate I14, spec §12), over a
17// directory object store: AddImage, CopyImage and the attaching commit
18// are the real ones.
19
20// useImages binds a directory object store to the world's Mapa.
21func (world *importWorld) useImages(quotas ...int64) {
22 world.t.Helper()
23 objects, err := blobs.Dir(world.t.TempDir())
24 if err != nil {
25 world.t.Fatal(err)
26 }
27 setup := ImageSetup{Objects: objects}
28 if len(quotas) == 2 {
29 setup.QuotaPerson, setup.QuotaTeam = quotas[0], quotas[1]
30 }
31 world.store.UseImages(setup)
32}
33
34// imagePage is a workspace with one page holding one hosted image.
35func imagePage(t *testing.T) (*small, string) {
36 ws := newSmall()
37 url := ws.Host("diagram.png", picture(t, 1))
38 ids := ws.Add(ws.handbook, notiontest.Image(url,
39 notiontest.Text("A diagram")))
40 return ws, ids[0]
41}
42
43// imagesOf is the images rows attached to a page, and pending ones.
44func (world *importWorld) imagesOf(pageID int64) (attached, pending int64) {
45 return world.count("images", "page_id = ?", pageID),
46 world.count("images", "page_id IS NULL")
47}
48
49// I14: a Notion-hosted image becomes a Mapa image, attached by the
50// page's own commit; an external one stays a link; and an unchanged
51// image is not downloaded again.
52//
53// Mutation (make mutate, first red 2026-11-17): ImportCreate commits
54// with attachNothing.
55func TestI14AnImageIsAddedAndAttached(t *testing.T) {
56 ws, _ := imagePage(t)
57 ws.Add(ws.handbook, notiontest.Image("https://example.com/photo.jpg",
58 notiontest.Text("A photo")))
59 world := newImportWorld(t, ws.Workspace)
60 world.useImages()
61 world.connect(ana)
62 world.importAs(ana)
63 page, record, _ := world.pageTitled("Handbook")
64 if attached, pending := world.imagesOf(page.ID); attached != 1 ||
65 pending != 0 {
66 t.Fatalf("after the import: %d attached, %d pending", attached,
67 pending)
68 }
69 if !strings.Contains(record.Body, "![A diagram](/i/") ||
70 !strings.Contains(record.Body,
71 "[A photo](https://example.com/photo.jpg)") {
72 t.Errorf("the body does not hold the image and the link: %q",
73 record.Body)
74 }
75 world.server.Reset()
76 if run := world.importAs(ana); run.Unchanged != 3 ||
77 world.fileRequests() != 0 {
78 t.Errorf("a re-run: %+v, %d fetched", run, world.fileRequests())
79 }
80}
81
82// I14: an image the page no longer holds (swept, or removed by a
83// teammate) is fetched again; one whose block changed is too.
84//
85// Mutation (make mutate, first red 2026-11-17): reuse skips the Held
86// check.
87func TestI14AnImageGoneOrChangedIsFetchedAgain(t *testing.T) {
88 ws, block := imagePage(t)
89 world := newImportWorld(t, ws.Workspace)
90 world.useImages()
91 world.connect(ana)
92 world.importAs(ana)
93 page, _, _ := world.pageTitled("Handbook")
94 world.store.database.Where("page_id = ?", page.ID).Delete(&ImageRow{})
95 world.server.Reset()
96 world.importAs(ana)
97 if world.fileRequests() != 1 {
98 t.Errorf("an image no longer held: %d fetched",
99 world.fileRequests())
100 }
101 changeImage(t, ws, block, 2)
102 world.server.Reset()
103 world.importAs(ana)
104 if world.fileRequests() != 1 {
105 t.Errorf("a changed image block: %d fetched", world.fileRequests())
106 }
107 if _, pending := world.imagesOf(page.ID); pending != 0 {
108 t.Errorf("the update left %d images pending", pending)
109 }
110}
111
112// I14: the same Notion image on a second page is copied there, not
113// downloaded again (one image, one place).
114//
115// Mutation (make mutate, first red 2026-11-17): no copy is tried.
116func TestI14ABlockOnASecondPageIsCopied(t *testing.T) {
117 ws, block := imagePage(t)
118 shared, _ := ws.Block(block)
119 ws.Children[ws.onboarding] = append(ws.Children[ws.onboarding], shared)
120 world := newImportWorld(t, ws.Workspace)
121 world.useImages()
122 world.connect(ana)
123 world.importAs(ana)
124 handbook, _, _ := world.pageTitled("Handbook")
125 onboarding, _, _ := world.pageTitled("Onboarding")
126 first, _ := world.imagesOf(handbook.ID)
127 second, _ := world.imagesOf(onboarding.ID)
128 if first != 1 || second != 1 || world.fileRequests() != 1 {
129 t.Errorf("one image on two pages: %d and %d attached, %d fetched",
130 first, second, world.fileRequests())
131 }
132}
133
134// I14: a refused image leaves its line and a written page, and a
135// permanent refusal is not downloaded again while the block is the same.
136//
137// Mutation (make mutate, first red 2026-11-17): a permanent refusal is
138// not remembered.
139func TestI14ARefusalIsALineAndRemembered(t *testing.T) {
140 ws := newSmall()
141 ids := ws.Add(ws.handbook, notiontest.Image(ws.Host("notes.png",
142 []byte("not a picture at all"))))
143 world := newImportWorld(t, ws.Workspace)
144 world.useImages()
145 world.connect(ana)
146 world.importAs(ana)
147 _, record, found := world.pageTitled("Handbook")
148 if !found || !strings.Contains(record.Body,
149 "(Image not imported: notes.png, not a PNG, JPEG, GIF or WebP)") {
150 t.Fatalf("the refused image's page: %q", record.Body)
151 }
152 world.server.Reset()
153 world.importAs(ana)
154 if world.fileRequests() != 0 {
155 t.Errorf("a permanent refusal was fetched again")
156 }
157 // The file replaced with a picture in the same minute: the refusal
158 // was the old file's, so the new one is fetched (Fable L5).
159 changeImage(t, ws, ids[0], 10)
160 world.server.Reset()
161 world.importAs(ana)
162 _, record, _ = world.pageTitled("Handbook")
163 if world.fileRequests() != 1 || !strings.Contains(record.Body, "](/i/") {
164 t.Errorf("a refused file replaced: %d fetched, body %q",
165 world.fileRequests(), record.Body)
166 }
167}
168
169// Fable L1: a file replaced between Survey and Write is downloaded as
170// it is now, and kept under the key of what was downloaded, so the next
171// run fetches nothing.
172//
173// Mutation (make mutate, first red 2026-11-22): the key kept is the
174// staged file's.
175func TestI14AFileReplacedMidRunIsKeyedAsDownloaded(t *testing.T) {
176 ws, block := imagePage(t)
177 world := newImportWorld(t, ws.Workspace)
178 world.useImages()
179 world.connect(ana)
180 atPoint(t, "survey:walked", 1, func() {
181 world.server.Lock()
182 defer world.server.Unlock()
183 changeImage(t, ws, block, 11)
184 })
185 world.importAs(ana)
186 importCrash = nil
187 world.server.Reset()
188 // (The page itself updates: changeImage drops the caption.)
189 world.importAs(ana)
190 if world.fileRequests() != 0 {
191 t.Errorf("the run after fetched %d", world.fileRequests())
192 }
193}
194
195// I14: the first quota refusal stops downloads for the run and names
196// the allowance.
197//
198// Mutation (make mutate, first red 2026-11-17): a quota refusal does
199// not stop downloads.
200func TestI14TheFirstQuotaRefusalStopsDownloads(t *testing.T) {
201 ws := newSmall()
202 ws.Add(ws.handbook, notiontest.Image(ws.Host("a.png", picture(t, 1))),
203 notiontest.Image(ws.Host("b.png", picture(t, 2))))
204 world := newImportWorld(t, ws.Workspace)
205 world.useImages(1, 1<<30)
206 world.connect(ana)
207 world.importAs(ana)
208 _, record, _ := world.pageTitled("Handbook")
209 if world.fileRequests() != 1 || strings.Count(record.Body,
210 "your own image allowance is full") != 2 {
211 t.Errorf("over quota: %d fetched, body %q", world.fileRequests(),
212 record.Body)
213 }
214}
215
216// I14 and Low 5: a page kept, or found deleted, after its images were
217// added holds them nowhere; they are removed at once.
218//
219// Mutations (make mutate, first red 2026-11-17): a kept page's images
220// left pending; a deleted page's images left pending.
221func TestI14ANotWrittenPagesImagesGoAtOnce(t *testing.T) {
222 for _, act := range []string{"kept", "deleted"} {
223 t.Run(act, func(t *testing.T) {
224 ws, block := imagePage(t)
225 world := newImportWorld(t, ws.Workspace)
226 world.useImages()
227 world.connect(ana)
228 world.importAs(ana)
229 page, _, _ := world.pageTitled("Handbook")
230 changeImage(t, ws, block, 3)
231 atPoint(t, "write:rendered", 1, func() {
232 world.notWritten(act, page)
233 })
234 world.server.Reset()
235 world.importAs(ana)
236 if world.fileRequests() != 1 {
237 t.Fatalf("%s: the changed image was not fetched", act)
238 }
239 if _, pending := world.imagesOf(page.ID); pending != 0 {
240 t.Errorf("%s: %d images left pending", act, pending)
241 }
242 })
243 }
244}
245
246// notWritten keeps or deletes a page as a teammate, mid-run.
247func (world *importWorld) notWritten(act string, page Page) {
248 if act == "deleted" {
249 world.store.Delete(ctx(), bo, page.ID)
250 return
251 }
252 world.store.Commit(ctx(), bo, page.ID, page.Revision, "Bo's.")
253}
254
255// changeImage replaces an image block's file, as an edit in Notion does:
256// a new file (a new file id in its URL), the same block. Its
257// last_edited_time does not move: Notion rounds it to the minute (spec
258// §25 note 17), so a replacement in the minute the last run read it
259// carries the time that run saw, and only the file's key tells.
260func changeImage(t *testing.T, ws *small, block string, seed int) {
261 t.Helper()
262 changed, ok := ws.Block(block)
263 if !ok {
264 t.Fatal("no such block")
265 }
266 minute := changed["last_edited_time"]
267 fresh := notiontest.Image(ws.Host("changed.png", picture(t, seed)))
268 changed["image"] = fresh["image"]
269 if changed["last_edited_time"] != minute {
270 t.Fatal("the replacement moved the edit time")
271 }
272}
273
274// hostedURL is an image block's file URL, as the workspace holds it.
275func hostedURL(t *testing.T, ws *small, block string) string {
276 t.Helper()
277 found, ok := ws.Block(block)
278 if !ok {
279 t.Fatal("no such block")
280 }
281 image, _ := found["image"].(map[string]any)
282 file, _ := image["file"].(map[string]any)
283 url, _ := file["url"].(string)
284 return url
285}
286
287// I14 at the shape a real workspace sends (spec §19 step 4, §25 note
288// 17): every hosted file in the first real run was at the virtual-hosted
289// prod-files-secure bucket, which the documented pair alone refused. The
290// fixture is that shape, production's own pin takes it, and it is
291// downloaded and attached through the fake; the documentation's
292// path-style shape still is too.
293//
294// Its mutation is the module's (M5, "no virtual-hosted pair, the
295// fixtures"): Mapa's make mutate cannot edit a dependency. Red by hand
296// on 2026-11-22, against the module with that pair removed through a
297// replace.
298func TestI14TheRealFileShapeIsDownloadedAndAttached(t *testing.T) {
299 ws, block := imagePage(t)
300 path := ws.PathStyle("old.png", picture(t, 7))
301 ws.Add(ws.onboarding, notiontest.Image(path, notiontest.Text("Old")))
302 url := hostedURL(t, ws, block)
303 if !strings.HasPrefix(url, "https://prod-files-secure.s3."+
304 "us-west-2.amazonaws.com/"+notiontest.FileWorkspace+"/") {
305 t.Fatalf("the fixture's file is not the real shape: %s", url)
306 }
307 files := notion.NewFiles()
308 if !files.Allowed(url) || !files.Allowed(path) {
309 t.Fatal("production's file pin refuses a shape Notion sends")
310 }
311 world := newImportWorld(t, ws.Workspace)
312 world.useImages()
313 world.connect(ana)
314 world.importAs(ana)
315 for _, title := range []string{"Handbook", "Onboarding"} {
316 page, record, _ := world.pageTitled(title)
317 attached, _ := world.imagesOf(page.ID)
318 if attached != 1 || !strings.Contains(record.Body, "](/i/") ||
319 strings.Contains(record.Body, "Image not imported") {
320 t.Errorf("%s: %d attached, body %q", title, attached,
321 record.Body)
322 }
323 }
324 if world.fileRequests() != 2 {
325 t.Errorf("%d files fetched, want 2", world.fileRequests())
326 }
327}
328
329// I14 against the minute-rounded edit time: an image replaced in Notion
330// within the minute the last run read it (so its block's edit time is
331// the one that run kept) is downloaded on the next run and the page
332// updated, twice in a row; a run after that downloads nothing.
333//
334// Mutation (make mutate, first red 2026-11-22): reuse ignores the
335// file's key, which is what comparing the unchanged edit time did.
336func TestI14AnImageReplacedInTheSameMinuteIsFetched(t *testing.T) {
337 ws, block := imagePage(t)
338 world := newImportWorld(t, ws.Workspace)
339 world.useImages()
340 world.connect(ana)
341 world.importAs(ana)
342 _, before, _ := world.pageTitled("Handbook")
343 for seed := 8; seed <= 9; seed++ {
344 changeImage(t, ws, block, seed)
345 world.server.Reset()
346 run := world.importAs(ana)
347 _, after, _ := world.pageTitled("Handbook")
348 if world.fileRequests() != 1 || run.Updated != 1 ||
349 after.Body == before.Body {
350 t.Fatalf("a replacement in the same minute: %d fetched, %+v",
351 world.fileRequests(), run)
352 }
353 before = after
354 }
355 world.server.Reset()
356 if run := world.importAs(ana); world.fileRequests() != 0 ||
357 run.Updated != 0 {
358 t.Errorf("the run after: %d fetched, %+v", world.fileRequests(), run)
359 }
360}
361
362// sameFile: an empty key, a row's from before keys, matches nothing.
363func TestAnEmptyFileKeyMatchesNothing(t *testing.T) {
364 if sameFile("", "") || sameFile("", "h/a") || !sameFile("h/a", "h/a") {
365 t.Error("sameFile")
366 }
367}
368
369// L15 and round 2's M2: a kept page is decided before its images, so a
370// changed image on it is not fetched.
371func TestL15AKeptPagesImageIsNotFetched(t *testing.T) {
372 ws, block := imagePage(t)
373 world := newImportWorld(t, ws.Workspace)
374 world.useImages()
375 world.connect(ana)
376 world.importAs(ana)
377 page, _, _ := world.pageTitled("Handbook")
378 if _, err := world.store.Commit(ctx(), bo, page.ID, page.Revision,
379 "Bo's."); err != nil {
380 t.Fatal(err)
381 }
382 changeImage(t, ws, block, 4)
383 world.server.Reset()
384 world.importAs(ana)
385 if world.fileRequests() != 0 {
386 t.Error("a kept page's changed image was fetched")
387 }
388}
389
390// Low 5: the fix-up pass after a Resume renders a page's images from the
391// lines it last wrote, so the body keeps them.
392//
393// Mutation (make mutate, first red 2026-11-17): the fix-up renders with
394// no image lines.
395func TestLow5TheFixUpKeepsImagesAfterAResume(t *testing.T) {
396 ws := notiontest.NewWorkspace("fixup-images")
397 alpha := ws.Page("", notiontest.Text("Alpha"))
398 beta := ws.Page("", notiontest.Text("Beta"))
399 ws.Add(alpha, notiontest.Para(notiontest.PageMention(beta, "Beta")),
400 notiontest.Image(ws.Host("a.png", picture(t, 5))))
401 world := newImportWorld(t, ws)
402 world.useImages()
403 world.connect(ana)
404 lease, err := world.store.StartRun(ctx(), ana, false)
405 if err != nil {
406 t.Fatal(err)
407 }
408 seen := 0
409 importCrash = func(point string) error {
410 if point == "write:rendered" {
411 if seen++; seen == 2 {
412 world.store.CreateTeamPage(ctx(), bo, "Beta", "Bo's.")
413 return errCrashed
414 }
415 }
416 return nil
417 }
418 t.Cleanup(func() { importCrash = nil })
419 world.finish(lease, ana)
420 importCrash = nil
421 world.store.InterruptRuns(ctx())
422 world.resumeIfNeeded(lease)
423 _, record, _ := world.pageTitled("Alpha")
424 if !strings.Contains(record.Body, "](/i/") ||
425 !strings.Contains(record.Body, "Beta (Notion)") {
426 t.Errorf("Alpha after its fix-up: %q", record.Body)
427 }
428}
429
430// §12: the Start page shows both image allowances, and a report whose
431// run stopped on one says which, at its top.
432func TestI14ThePageShowsTheAllowances(t *testing.T) {
433 ws := newSmall()
434 ws.Add(ws.handbook, notiontest.Image(ws.Host("a.png", picture(t, 1))))
435 world := newImportWorld(t, ws.Workspace)
436 world.useImages(1, 1<<30)
437 world.connect(ana)
438 request := httptest.NewRequest(http.MethodGet, importPath, nil)
439 request = request.WithContext(context.WithValue(request.Context(),
440 testPersonKey{}, ana))
441 world.app.testIdentity, world.app.allowUnauthenticated = ana, true
442 page := httptest.NewRecorder()
443 world.app.importPage(page, request)
444 if !strings.Contains(page.Body.String(), "the team's image allowance") {
445 t.Errorf("the Start page does not show the allowances")
446 }
447 world.importAs(ana)
448 page = httptest.NewRecorder()
449 world.app.importPage(page, request)
450 if !strings.Contains(page.Body.String(),
451 "Images stopped: your own image allowance is full") {
452 t.Errorf("the report does not say which allowance stopped it")
453 }
454}
455
456// Round 3, M2: an image shown on two pages and changed in Notion is
457// downloaded once, and both pages get the new picture: neither copies
458// the other's old one.
459//
460// Mutation (make mutate, first red 2026-11-17): a copy ignores the
461// block's edit time.
462func TestI14AChangedSharedImageIsFetchedOnce(t *testing.T) {
463 ws, block := imagePage(t)
464 shared, _ := ws.Block(block)
465 ws.Children[ws.onboarding] = append(ws.Children[ws.onboarding], shared)
466 world := newImportWorld(t, ws.Workspace)
467 world.useImages()
468 world.connect(ana)
469 world.importAs(ana)
470 _, before, _ := world.pageTitled("Onboarding")
471 changeImage(t, ws, block, 6)
472 world.server.Reset()
473 world.importAs(ana)
474 _, after, _ := world.pageTitled("Onboarding")
475 if world.fileRequests() != 1 || after.Body == before.Body {
476 t.Errorf("a changed shared image: %d fetched, Onboarding "+
477 "changed %v", world.fileRequests(), after.Body != before.Body)
478 }
479}
480