| 1 | package mapatest |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "net/http" |
| 6 | "net/http/httptest" |
| 7 | "testing" |
| 8 | ) |
| 9 | |
| 10 | // Prefetch on hover (build note 70): every screen names Mapa's ruleset, |
| 11 | // which prefetches pages and days and never prerenders. |
| 12 | func TestTheSpeculationRulesetPrefetchesPagesAndDays(t *testing.T) { |
| 13 | rig := newRig(t) |
| 14 | for _, path := range []string{"/", "/pages", "/settings"} { |
| 15 | header := rig.get(t, Ana, path).Header().Get("Speculation-Rules") |
| 16 | if header != `"/speculation-rules"` { |
| 17 | t.Errorf("GET %s: Speculation-Rules %q", path, header) |
| 18 | } |
| 19 | } |
| 20 | // Signed out, as the browser may fetch it: it says nothing private. |
| 21 | recorder := httptest.NewRecorder() |
| 22 | rig.built.Mux.ServeHTTP(recorder, |
| 23 | httptest.NewRequest(http.MethodGet, "/speculation-rules", nil)) |
| 24 | if kind := recorder.Header().Get("Content-Type"); recorder.Code != 200 || |
| 25 | kind != "application/speculationrules+json" { |
| 26 | t.Fatalf("the ruleset: %d %q", recorder.Code, kind) |
| 27 | } |
| 28 | var rules map[string][]struct { |
| 29 | Source string |
| 30 | Eagerness string |
| 31 | Where map[string]any |
| 32 | } |
| 33 | if err := json.Unmarshal(recorder.Body.Bytes(), &rules); err != nil { |
| 34 | t.Fatal(err) |
| 35 | } |
| 36 | if len(rules) != 1 || len(rules["prefetch"]) != 1 { |
| 37 | t.Fatalf("the ruleset is not one prefetch rule: %s", |
| 38 | recorder.Body.String()) |
| 39 | } |
| 40 | rule := rules["prefetch"][0] |
| 41 | if rule.Source != "document" || rule.Eagerness != "moderate" { |
| 42 | t.Fatalf("the rule: %+v", rule) |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | // A prefetch is a GET, so it writes nothing (gate 10): a teammate who |
| 47 | // has never written prefetches a page, two days and Today, and no |
| 48 | // table changes: no member row, no draft, no event. |
| 49 | func TestAPrefetchWritesNothing(t *testing.T) { |
| 50 | rig := newRig(t) |
| 51 | page := rig.createPage(t, Ana, "Acme", "Customer since 2024.") |
| 52 | before, events := snapshot(t, rig), rig.count(t, "events") |
| 53 | drafts := rig.count(t, "drafts") |
| 54 | for _, path := range []string{page, "/d/2026-11-12", "/d/1999-01-01", |
| 55 | "/"} { |
| 56 | recorder := httptest.NewRecorder() |
| 57 | request := httptest.NewRequest(http.MethodGet, path, nil) |
| 58 | request.Header.Set("Sec-Purpose", "prefetch") |
| 59 | rig.built.As(Bo).ServeHTTP(recorder, request) |
| 60 | if recorder.Code != http.StatusOK { |
| 61 | t.Fatalf("prefetching %s: %d", path, recorder.Code) |
| 62 | } |
| 63 | } |
| 64 | if snapshot(t, rig) != before || rig.count(t, "events") != events || |
| 65 | rig.count(t, "drafts") != drafts { |
| 66 | t.Fatal("a prefetch wrote to the database") |
| 67 | } |
| 68 | } |
| 69 | |