oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1package slidestest
2
3import (
4 "bytes"
5 "net/http"
6 "net/http/httptest"
7 "os"
8 "path/filepath"
9 "regexp"
10 "strings"
11 "testing"
12 "testing/fstest"
13
14 slides "amadan.net/oficina/slides/internal/slides"
15 "amadan.net/rastrillo/rastrillo"
16)
17
18// hashedStylesheet is the fingerprinted URL shape a page links:
19// /static/tokens.<16 hex>.css.
20var hashedStylesheet = regexp.MustCompile(`/static/tokens\.[0-9a-f]{16}\.css`)
21
22// The scaffold shipped two tests about the placeholder index page and
23// said in AGENTS.md that sign-in would break both, because it does:
24// "/" is behind the session gate now, so a signed-out GET is a 303 with
25// no <link> in its body. They are repointed at /signin, the one screen
26// that is still public — the subject was never the placeholder's
27// wording, it was the framework's asset delivery, and that still earns
28// its place. The placeholder's own "does this render" assertion is
29// covered by TestSigninPageIsPublic (signin_test.go), against a page
30// this app actually has.
31func TestSigninLinksFingerprintedStylesheet(t *testing.T) {
32 h := newApp(t)
33 href := hashedStylesheet.FindString(get(t, h, "/signin").Body.String())
34 if href == "" {
35 t.Fatal("the sign-in page links no fingerprinted stylesheet")
36 }
37 rec := get(t, h, href)
38 if rec.Code != http.StatusOK {
39 t.Fatalf("GET %s: status %d, want 200", href, rec.Code)
40 }
41 if got := rec.Header().Get("Cache-Control"); got != "public, max-age=31536000, immutable" {
42 t.Errorf("GET %s: Cache-Control = %q, want immutable year", href, got)
43 }
44}
45
46// The bare name keeps working, just never long-cached — so a changed
47// file always shows on an ordinary reload.
48func TestBareAssetNameStaysFresh(t *testing.T) {
49 rec := get(t, newApp(t), "/static/tokens.css")
50 if rec.Code != http.StatusOK {
51 t.Fatalf("GET /static/tokens.css: status %d, want 200", rec.Code)
52 }
53 if got := rec.Header().Get("Cache-Control"); got != "no-cache" {
54 t.Errorf("Cache-Control = %q, want no-cache", got)
55 }
56}
57
58// Static assets are mounted outside the session gate on purpose: the
59// sign-in page has to be able to load its own stylesheet before anybody
60// is signed in, or the front door renders unstyled.
61func TestStaticAssetsAreReachableSignedOut(t *testing.T) {
62 rec := get(t, newApp(t), "/static/theme.css")
63 if rec.Code != http.StatusOK {
64 t.Fatalf("GET /static/theme.css signed out: status %d, want 200", rec.Code)
65 }
66}
67
68// ErrorPage is what main.go points Options.ErrorPage at (and the seam
69// to wire into Ctx.ErrorPage as handlers grow); called directly, it
70// pins that a panic's page is the framework's error-page partial, not
71// a stray net/http default.
72func TestErrorPageRendersFrameworkPartial(t *testing.T) {
73 rec := httptest.NewRecorder()
74 req := httptest.NewRequest(http.MethodGet, "/", nil)
75 req.Header.Set("Accept", "text/html")
76 localised(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
77 slides.ErrorPage(w, r, http.StatusInternalServerError, "abc123")
78 })).ServeHTTP(rec, req)
79 if rec.Code != http.StatusInternalServerError {
80 t.Fatalf("ErrorPage: status %d, want %d", rec.Code, http.StatusInternalServerError)
81 }
82 body := rec.Body.String()
83 if !strings.Contains(body, "Something went wrong") {
84 t.Errorf("ErrorPage body missing the 500 title:\n%s", body)
85 }
86 if !strings.Contains(body, "abc123") {
87 t.Errorf("ErrorPage body missing the ref:\n%s", body)
88 }
89}
90
91// Every page failure a browser can navigate to is rendered inside Slides'
92// layout and bar. A fetch that did not ask for HTML remains plain text; the
93// split is by Accept rather than by an accident of which route failed.
94func TestNavigableErrorsUseTheSharedErrorPage(t *testing.T) {
95 a := newApp(t)
96 signedIn := signedIn(t, a, allowedAddress)
97 // The user row is created on the first guarded request; optional chrome
98 // deliberately will not create it while merely resolving an error page.
99 mustGet(t, a, "/", http.StatusOK, signedIn)
100 type errorCase struct {
101 name, path, title string
102 cookies []*http.Cookie
103 }
104 for _, tc := range []errorCase{
105 {"unknown route, signed out", "/no/such/page", "Page not found · Slides", nil},
106 {"unknown route, signed in", "/no/such/page", "Page not found · Slides", signedIn},
107 {"post-only route, signed out", "/signout", "Page not found · Slides", nil},
108 {"post-only route, signed in", "/signout", "Page not found · Slides", signedIn},
109 {"missing deck", "/d/23456789ab", "Deck not available · Slides", signedIn},
110 {"missing share link", "/s/doesnotexist", "Deck not available · Slides", nil},
111 } {
112 t.Run(tc.name, func(t *testing.T) {
113 req := httptest.NewRequest(http.MethodGet, tc.path, nil)
114 req.Header.Set("Accept", "text/html,application/xhtml+xml")
115 for _, c := range tc.cookies {
116 req.AddCookie(c)
117 }
118 rec := httptest.NewRecorder()
119 a.ServeHTTP(rec, req)
120 body := rec.Body.String()
121 if rec.Code != http.StatusNotFound || !strings.HasPrefix(rec.Header().Get("Content-Type"), "text/html") {
122 t.Fatalf("status %d, Content-Type %q; want HTML 404", rec.Code, rec.Header().Get("Content-Type"))
123 }
124 if title := regexp.MustCompile(`<title>([^<]*)</title>`).FindStringSubmatch(body); title == nil || title[1] != tc.title {
125 t.Fatalf("title %v, want %q", title, tc.title)
126 }
127 if !strings.Contains(body, "<header estilo-bar") || !strings.Contains(body, "<div rst-error>") {
128 t.Fatal("error is outside the shared layout and bar")
129 }
130 if account := strings.Contains(body, "<details estilo-account"); account != (tc.cookies != nil) {
131 t.Fatalf("account menu present = %v, want %v", account, tc.cookies != nil)
132 }
133 })
134 }
135 plain := get(t, a, "/no/such/page", signedIn...)
136 if plain.Code != http.StatusNotFound || strings.HasPrefix(plain.Header().Get("Content-Type"), "text/html") || strings.Contains(plain.Body.String(), "<html") {
137 t.Fatalf("non-HTML failure = %d %q, want plain 404", plain.Code, plain.Header().Get("Content-Type"))
138 }
139}
140
141// The only callout vocabulary is estilo's real tones. A valued rst-callout
142// or the old rst-notice spelling looks plausible but receives no callout
143// treatment, so scan every authored template rather than waiting for a path
144// to happen to render one.
145func TestTemplatesUseOnlyCalloutTones(t *testing.T) {
146 files, err := filepath.Glob(filepath.Join("..", "slides", "templates", "*.html"))
147 if err != nil || len(files) == 0 {
148 t.Fatal("find templates", err)
149 }
150 stripComments := regexp.MustCompile(`(?s)\{\{/\*.*?\*/\}\}`)
151 for _, file := range files {
152 body, err := os.ReadFile(file)
153 if err != nil {
154 t.Fatal(err)
155 }
156 source := stripComments.ReplaceAllString(string(body), "")
157 for _, bad := range []string{"rst-notice", `rst-callout="`, `rst-tone="warn"`} {
158 if strings.Contains(source, bad) {
159 t.Errorf("%s uses %q", file, bad)
160 }
161 }
162 }
163}
164
165// The vendored files the door's page links are served as rastrillo.Assets
166// itself serves them, asked of rastrillo rather than re-derived: since
167// v0.31 it minifies a file at one of the framework's vendored paths
168// (static/tokens.css, static/theme.css, static/rastrillo.js and the rest)
169// and serves any other as written. Each fingerprinted link, and the bare
170// name, answer those bytes.
171func TestVendoredAssetsAreServedAsRastrilloServesThem(t *testing.T) {
172 h := newApp(t)
173 page := get(t, h, "/signin").Body.String()
174 for _, name := range []string{"static/tokens.css", "static/theme.css", "static/busy.css", "static/rastrillo.js", "static/busy.js", "static/select.js", "static/datetime.js", "static/calendar.js"} {
175 raw, err := os.ReadFile(filepath.Join("..", "slides", name))
176 if err != nil {
177 t.Fatal(err)
178 }
179 assets := rastrillo.NewAssets(fstest.MapFS{name: {Data: raw}})
180 want := httptest.NewRecorder()
181 assets.Handler().ServeHTTP(want, httptest.NewRequest(http.MethodGet, assets.Path(name), nil))
182 if want.Code != http.StatusOK {
183 t.Fatalf("rastrillo.Assets would not serve %s: %d", name, want.Code)
184 }
185 hashed := assets.Path(name)
186 if !strings.Contains(page, `"`+hashed+`"`) {
187 t.Errorf("the door does not link %s at %s", name, hashed)
188 }
189 for _, path := range []string{hashed, "/" + name} {
190 got := get(t, h, path)
191 if got.Code != http.StatusOK || !bytes.Equal(got.Body.Bytes(), want.Body.Bytes()) {
192 t.Errorf("GET %s: %d, not the bytes rastrillo.Assets serves", path, got.Code)
193 }
194 }
195 }
196}
197