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 "crypto/sha256"
6 "encoding/hex"
7 "encoding/json"
8 "fmt"
9 "html"
10 "net/http"
11 "os"
12 "path/filepath"
13 "regexp"
14 "strings"
15 "testing"
16
17 "amadan.net/oficina/slides/internal/slides/fonts"
18)
19
20// This file holds the browser's half of "one font set everywhere" to
21// the Go half. The faces reach a slide surface through the font gate's
22// manifest (fontgate.go: <meta name="slides-fonts">), not through a
23// stylesheet, so the twelve URLs, the fallback stacks and the served
24// bytes are all things that can drift silently. These tests are what
25// notice.
26
27func slidesCSS(t *testing.T) string {
28 t.Helper()
29 b, err := os.ReadFile(filepath.Join("..", "slides", "static", "slides.css"))
30 if err != nil {
31 t.Fatalf("read slides.css: %v", err)
32 }
33 return string(b)
34}
35
36// manifestFace is one face of the font gate's manifest.
37type manifestFace struct {
38 family, style, weight, url string
39}
40
41var manifestMeta = regexp.MustCompile(`<meta name="slides-fonts" content="([^"]*)">`)
42
43// gateManifest reads the font gate's manifest off a rendered page.
44// Families are the catalog's three; Uploaded the deck's own fonts,
45// keyed "u:" + css. A face's weight is raw JSON: a number, or for a
46// variable face the CSS range as a string ("100 900").
47type gateManifest struct {
48 Need []string `json:"need"`
49 Families map[string]gateManifestFamily `json:"families"`
50 Themes map[string][2]string `json:"themes"`
51 DefaultTheme string `json:"defaultTheme"`
52 Code string `json:"code"`
53 Uploaded map[string]gateManifestFamily `json:"uploaded"`
54}
55
56type gateManifestFamily struct {
57 CSS string `json:"css"`
58 Faces []struct {
59 Weight json.RawMessage `json:"weight"`
60 Style string `json:"style"`
61 URL string `json:"url"`
62 Format string `json:"format"`
63 } `json:"faces"`
64}
65
66func readManifest(t *testing.T, page string) (gateManifest, bool) {
67 t.Helper()
68 m := manifestMeta.FindStringSubmatch(page)
69 if m == nil {
70 return gateManifest{}, false
71 }
72 var out gateManifest
73 if err := json.Unmarshal([]byte(html.UnescapeString(m[1])), &out); err != nil {
74 t.Fatalf("the font manifest is not JSON: %v\n%s", err, m[1])
75 }
76 return out, true
77}
78
79func manifestFaces(m gateManifest) []manifestFace {
80 var out []manifestFace
81 for _, key := range []string{"sans", "serif", "mono"} {
82 f := m.Families[key]
83 for _, face := range f.Faces {
84 out = append(out, manifestFace{family: f.CSS, style: face.Style, weight: string(face.Weight), url: face.URL})
85 }
86 }
87 return out
88}
89
90// sampleViewer is the sample deck's viewer, signed in: a slide surface,
91// so it carries the manifest.
92func sampleViewer(t *testing.T) (*testApp, string, []*http.Cookie) {
93 t.Helper()
94 a := newApp(t)
95 cookies := signedIn(t, a, allowedAddress)
96 list := mustGet(t, a, "/", http.StatusOK, cookies).Body.String()
97 deck := deckPath.FindString(list)
98 if deck == "" {
99 t.Fatal("the sample deck is not on the list")
100 }
101 return a, deck, cookies
102}
103
104// No stylesheet declares a web face: a declared face is one the browser
105// fetches and draws on its own initiative, which with swap (what this
106// file used to say) is a flash by definition, and with block is
107// invisible text. The faces exist only through the font gate.
108func TestSlidesCSSDeclaresNoFontFace(t *testing.T) {
109 // The rules, not the comments, which say what used to be here.
110 css := regexp.MustCompile(`(?s)/\*.*?\*/`).ReplaceAllString(slidesCSS(t), "")
111 for _, banned := range []string{"@font-face", "font-display", ".ttf", ".woff2"} {
112 if strings.Contains(css, banned) {
113 t.Errorf("slides.css names %q; the faces are the font gate's alone (fontgate.go)", banned)
114 }
115 }
116}
117
118// Every one of the twelve embedded faces is in the manifest, once,
119// under its own family name and with the weight and slope that select
120// it, at its woff2. A face the engine measures with and the browser
121// cannot fetch is the divergence this whole font set exists to close.
122func TestTheFontManifestDeclaresEveryEmbeddedFace(t *testing.T) {
123 a, deck, cookies := sampleViewer(t)
124 m, ok := readManifest(t, mustGet(t, a, deck+"?slide=1", http.StatusOK, cookies).Body.String())
125 if !ok {
126 t.Fatal("the viewer carries no font manifest")
127 }
128 got := map[string]string{}
129 for _, r := range manifestFaces(m) {
130 key := fmt.Sprintf("%s|%s|%s", r.family, r.style, r.weight)
131 if prev, dup := got[key]; dup {
132 t.Errorf("%s is declared twice (%s and %s)", key, prev, r.url)
133 }
134 got[key] = r.url
135 }
136 for _, f := range fonts.All() {
137 style, weight := "normal", 400
138 if f.Italic {
139 style = "italic"
140 }
141 if f.Bold {
142 weight = 700
143 }
144 base := strings.TrimSuffix(f.File(), ".ttf")
145 key := fmt.Sprintf("%s|%s|%d", f.Family.CSSName(), style, weight)
146 url, ok := got[key]
147 if !ok {
148 t.Errorf("the manifest declares no face for %s.woff2 (%s)", base, key)
149 continue
150 }
151 if !strings.HasPrefix(url, "/static/fonts/"+base+".") {
152 t.Errorf("%s is declared as %q, which is not that face's file", key, url)
153 }
154 delete(got, key)
155 }
156 for key, url := range got {
157 t.Errorf("the manifest declares %s (%s), which is not a face this build embeds", key, url)
158 }
159}
160
161// The URLs carry a content hash so rastrillo's asset handler serves
162// them immutable rather than no-cache: a slide is a page load, and
163// refetching a family on every next-slide link is not a cost worth
164// paying for files that never change.
165func TestTheFontManifestURLsCarryTheirContentHash(t *testing.T) {
166 a, deck, cookies := sampleViewer(t)
167 m, _ := readManifest(t, mustGet(t, a, deck+"?slide=1", http.StatusOK, cookies).Body.String())
168 faces := manifestFaces(m)
169 if len(faces) != 12 {
170 t.Fatalf("the manifest has %d faces", len(faces))
171 }
172 for _, r := range faces {
173 name := strings.TrimPrefix(r.url, "/static/fonts/")
174 parts := strings.Split(name, ".")
175 if len(parts) != 3 || parts[2] != "woff2" || len(parts[1]) != 16 {
176 t.Errorf("%q is not /static/fonts/<face>.<16 hex>.woff2", r.url)
177 continue
178 }
179 b, err := os.ReadFile(filepath.Join("..", "slides", "static", "fonts", parts[0]+".woff2"))
180 if err != nil {
181 t.Errorf("%s: %v", r.url, err)
182 continue
183 }
184 sum := sha256.Sum256(b)
185 if want := hex.EncodeToString(sum[:])[:16]; parts[1] != want {
186 t.Errorf("%s carries hash %s, the file's is %s", r.url, parts[1], want)
187 }
188 }
189}
190
191// The stylesheet's own fallback stacks — what a section that arrived
192// without inline custom properties renders as — name the same faces
193// the themes do.
194func TestSlidesCSSFallbackStacksAreTheEmbeddedFamilies(t *testing.T) {
195 css := slidesCSS(t)
196 for _, c := range []struct {
197 prop string
198 fam fonts.Family
199 }{
200 {"--slides-font-heading", fonts.Serif},
201 {"--slides-font-body", fonts.Sans},
202 {"--slides-font-code", fonts.Mono},
203 } {
204 want := c.prop + ": " + c.fam.Stack() + ";"
205 if !strings.Contains(css, want) {
206 t.Errorf("slides.css does not set %q", want)
207 }
208 }
209}
210
211// The end of the wire: the app serves the bytes at the URL the
212// manifest names, with the immutable Cache-Control the hash buys.
213func TestTheAppServesTheDeclaredFontFiles(t *testing.T) {
214 a, deck, cookies := sampleViewer(t)
215 m, _ := readManifest(t, mustGet(t, a, deck+"?slide=1", http.StatusOK, cookies).Body.String())
216 faces := manifestFaces(m)
217 if len(faces) != 12 {
218 t.Fatalf("the viewer's font manifest names %d faces, want twelve", len(faces))
219 }
220 for _, r := range faces {
221 rec := get(t, a, r.url)
222 if rec.Code != http.StatusOK {
223 t.Errorf("GET %s: %d", r.url, rec.Code)
224 continue
225 }
226 if got := rec.Header().Get("Cache-Control"); !strings.Contains(got, "immutable") {
227 t.Errorf("GET %s: Cache-Control %q, want an immutable one", r.url, got)
228 }
229 if rec.Body.Len() < 100_000 || !bytes.HasPrefix(rec.Body.Bytes(), []byte("wOF2")) {
230 t.Errorf("GET %s returned %d bytes that are not a woff2", r.url, rec.Body.Len())
231 }
232 }
233}
234
235// The licence travels with the fonts, as the OFL requires of anything
236// redistributing them — and a slide surface is redistribution.
237func TestTheAppServesTheFontLicence(t *testing.T) {
238 a := newApp(t)
239 rec := get(t, a, "/static/fonts/LICENSE-OFL-1.1.txt")
240 if rec.Code != http.StatusOK {
241 t.Fatalf("GET the font licence: %d", rec.Code)
242 }
243 if !strings.Contains(rec.Body.String(), "SIL OPEN FONT LICENSE") {
244 t.Error("the served licence is not the OFL")
245 }
246}
247