oficina / estilo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package colophon
2
3import (
4 "bytes"
5 "html/template"
6 "net/url"
7 "regexp"
8 "strings"
9 "testing"
10
11 "amadan.net/oficina/estilo.git/credits"
12 "amadan.net/oficina/estilo.git/internal/tokencheck"
13)
14
15// The catalog is the one place every app's Colophon reads a project's
16// description from, so every entry in it must be whole: a blurb, who made
17// it, the licence it is under, and links to its home and its source.
18func TestCatalogEntriesAreComplete(t *testing.T) {
19 projects := Catalog()
20 if len(projects) < 50 {
21 t.Fatalf("the catalog has %d projects; the checks below would pass nearly vacuously", len(projects))
22 }
23 if err := Validate(projects); err != nil {
24 t.Fatal(err)
25 }
26}
27
28func TestValidateRefusesAnIncompleteEntry(t *testing.T) {
29 good := Project{ID: "yjs", Name: "Yjs", Kind: Library, Blurb: "A CRDT for shared editing. It merges edits without a server deciding the order.", Author: "Kevin Jahns", Licence: Licence{SPDX: "MIT", Name: "MIT License"}, Home: "https://yjs.dev", Source: "https://github.com/yjs/yjs", Packages: []Ref{{Ecosystem: NPM, Name: "yjs"}}, Uses: map[string]string{"docs": "The editor keeps the document in it."}}
30 if err := Validate([]Project{good}); err != nil {
31 t.Fatalf("a complete entry was refused: %v", err)
32 }
33 for name, spoil := range map[string]func(*Project){
34 "no blurb": func(p *Project) { p.Blurb = "" },
35 "blurb in lower case": func(p *Project) { p.Blurb = "a CRDT for shared editing." },
36 "three sentences": func(p *Project) { p.Blurb = "One thing. Another thing. A third thing." },
37 "no author": func(p *Project) { p.Author = " " },
38 "no licence name": func(p *Project) { p.Licence.Name = "" },
39 "no licence identifier": func(p *Project) { p.Licence.SPDX = "" },
40 "no home": func(p *Project) { p.Home = "" },
41 "plain-http source": func(p *Project) { p.Source = "http://github.com/yjs/yjs" },
42 "script url": func(p *Project) { p.Home = "javascript:alert(1)" },
43 "no packages": func(p *Project) { p.Packages = nil },
44 "unknown kind": func(p *Project) { p.Kind = "gadget" },
45 "unknown ecosystem": func(p *Project) { p.Packages = []Ref{{Ecosystem: "maven", Name: "x"}} },
46 "bad id": func(p *Project) { p.ID = "Yjs Project" },
47 "empty usage note": func(p *Project) { p.Uses = map[string]string{"docs": ""} },
48 "usage not a sentence": func(p *Project) { p.Uses = map[string]string{"docs": "the editor"} },
49 } {
50 p := good
51 p.Packages = append([]Ref(nil), good.Packages...)
52 p.Uses = map[string]string{"docs": good.Uses["docs"]}
53 spoil(&p)
54 if err := Validate([]Project{p}); err == nil {
55 t.Errorf("%s: accepted", name)
56 }
57 }
58 twin := good
59 twin.ID = "yjs-again"
60 if err := Validate([]Project{good, twin}); err == nil || !strings.Contains(err.Error(), "npm:yjs") {
61 t.Errorf("one package claimed by two projects was accepted: %v", err)
62 }
63 same := good
64 if err := Validate([]Project{good, same}); err == nil {
65 t.Error("a duplicate id was accepted")
66 }
67}
68
69func notice(text string) []credits.Notice { return []credits.Notice{{Name: "LICENSE", Text: text}} }
70
71func testCatalog() []Project {
72 return []Project{
73 {ID: "yjs", Name: "Yjs", Kind: Library, Blurb: "A CRDT.", Author: "Kevin Jahns", Licence: Licence{"MIT", "MIT License"}, Home: "https://yjs.dev", Source: "https://github.com/yjs/yjs", Packages: []Ref{{NPM, "yjs"}}, Uses: map[string]string{"docs": "Holds the document."}},
74 {ID: "prosemirror", Name: "ProseMirror", Kind: Library, Blurb: "An editor toolkit.", Author: "Marijn Haverbeke", Licence: Licence{"MIT", "MIT License"}, Home: "https://prosemirror.net", Source: "https://github.com/ProseMirror", Packages: []Ref{{NPM, "prosemirror-model"}, {NPM, "prosemirror-view"}}, Uses: map[string]string{"docs": "Draws the editor."}},
75 {ID: "chi", Name: "chi", Kind: Library, Blurb: "A router.", Author: "Peter Kieltyka", Licence: Licence{"MIT", "MIT License"}, Home: "https://go-chi.io", Source: "https://github.com/go-chi/chi", Packages: []Ref{{Go, "github.com/go-chi/chi/v5"}}, Uses: map[string]string{"docs": "Routes requests."}},
76 {ID: "carlito", Name: "Carlito", Kind: Typeface, Blurb: "A sans serif.", Author: "tyPoland", Licence: Licence{"OFL-1.1", "SIL Open Font License 1.1"}, Home: "https://github.com/googlefonts/carlito", Source: "https://github.com/googlefonts/carlito", Packages: []Ref{{Font, "Carlito"}}, Uses: map[string]string{"docs": "The default font."}},
77 {ID: "esbuild", Name: "esbuild", Kind: Tool, Blurb: "A bundler.", Author: "Evan Wallace", Licence: Licence{"MIT", "MIT License"}, Home: "https://esbuild.github.io", Source: "https://github.com/evanw/esbuild", Packages: []Ref{{NPM, "esbuild"}}, Uses: map[string]string{"docs": "Builds the editor."}},
78 {ID: "wasmi", Name: "wasmi", Kind: Library, Blurb: "A wasm interpreter.", Author: "Parity", Licence: Licence{"MIT OR Apache-2.0", "MIT or Apache 2.0"}, Home: "https://github.com/wasmi-labs/wasmi", Source: "https://github.com/wasmi-labs/wasmi", Packages: []Ref{{Cargo, "wasmi"}, {Cargo, "wasmi_core"}}, Uses: map[string]string{"docs": "Tests the core.", "docs-native": "Runs the core."}},
79 {ID: "signin", Name: "signin", Kind: Library, Blurb: "Sign-in.", Author: "Keymail", Licence: Licence{NoAssertion, "No licence published"}, Home: "https://pkg.go.dev/github.com/keymaildev/signin", Source: "https://github.com/keymaildev/signin", Packages: []Ref{{Go, "github.com/keymaildev/signin"}}, Uses: map[string]string{"docs": "Signs people in."}},
80 }
81}
82
83func shippedSet() []Package {
84 return []Package{
85 {Ecosystem: NPM, Name: "yjs", Version: "13.6.27", Notices: notice("yjs")},
86 {Ecosystem: NPM, Name: "prosemirror-view", Version: "1.42.3", Notices: notice("pmv")},
87 {Ecosystem: NPM, Name: "prosemirror-model", Version: "1.25.11", Notices: notice("pmm")},
88 {Ecosystem: Go, Name: "github.com/go-chi/chi/v5", Version: "v5.3.2", Notices: notice("chi")},
89 {Ecosystem: Font, Name: "Carlito", Notices: notice("OFL")},
90 {Ecosystem: NPM, Name: "esbuild", Version: "0.28.2", Tool: true, Notices: notice("esbuild")},
91 {Ecosystem: Cargo, Name: "wasmi", Version: "0.32.3", Tool: true, Notices: notice("wasmi")},
92 {Ecosystem: Go, Name: "github.com/keymaildev/signin", Version: "v0.1.1"},
93 }
94}
95
96func TestBuildGroupsEveryShippedPackageUnderItsProject(t *testing.T) {
97 c, err := build(testCatalog(), "docs", shippedSet())
98 if err != nil {
99 t.Fatal(err)
100 }
101 var order []string
102 for _, s := range c.Sections {
103 var names []string
104 for _, e := range s.Entries {
105 names = append(names, e.ID)
106 }
107 order = append(order, s.ID+"="+strings.Join(names, ","))
108 }
109 // Typefaces first, then libraries by runtime, then tools. A library
110 // that this app only builds or tests with (wasmi, a dev-dependency of
111 // the web core) is a tool here, whatever it is elsewhere.
112 if got, want := strings.Join(order, " "), "typefaces=carlito go=chi,signin javascript=prosemirror,yjs tools=esbuild,wasmi"; got != want {
113 t.Fatalf("sections = %s, want %s", got, want)
114 }
115 pm, ok := c.Entry("prosemirror")
116 if !ok || len(pm.Packages) != 2 || pm.Packages[0].Name != "prosemirror-model" || pm.Usage != "Draws the editor." || pm.Blurb != "An editor toolkit." {
117 t.Fatalf("ProseMirror's two packages or its words were lost: %+v", pm)
118 }
119 if got := pm.VersionText(); got != "prosemirror-model 1.25.11, prosemirror-view 1.42.3" {
120 t.Errorf("VersionText = %q", got)
121 }
122 if y, _ := c.Entry("yjs"); y.VersionText() != "13.6.27" {
123 t.Errorf("a one-package project's version is %q", y.VersionText())
124 }
125 if n := c.Count(); n["typefaces"] != 1 || n["javascript"] != 2 || n["total"] != 7 {
126 t.Errorf("Count = %v", n)
127 }
128}
129
130// The test every app's Colophon leans on: the shipped set and the Colophon
131// may not differ. Each way they can is refused, by name.
132func TestBuildRefusesMissingStaleAndIncompleteEntries(t *testing.T) {
133 cases := map[string]struct {
134 app string
135 shipped func([]Package) []Package
136 want string
137 }{
138 "a shipped package with no catalog entry": {"docs", func(p []Package) []Package {
139 return append(p, Package{Ecosystem: Cargo, Name: "yrs", Version: "0.23.5", Notices: notice("yrs")})
140 }, "cargo:yrs has no catalog entry"},
141 "a shipped project with no usage note for the app": {"docs-native", func(p []Package) []Package {
142 return []Package{p[0]}
143 }, "yjs has no usage note for docs-native"},
144 "a usage note for a project the app no longer ships": {"docs", func(p []Package) []Package {
145 return p[1:]
146 }, "yjs has a usage note for docs but docs does not ship it"},
147 "a package without its licence text": {"docs", func(p []Package) []Package {
148 p[0].Notices = nil
149 return p
150 }, "npm:yjs 13.6.27 carries no licence text"},
151 "an unnamed package": {"docs", func(p []Package) []Package {
152 return append(p, Package{Ecosystem: NPM})
153 }, "a package without an ecosystem or name"},
154 }
155 for name, tc := range cases {
156 t.Run(name, func(t *testing.T) {
157 _, err := build(testCatalog(), tc.app, tc.shipped(shippedSet()))
158 if err == nil || !strings.Contains(err.Error(), tc.want) {
159 t.Fatalf("err = %v, want it to say %q", err, tc.want)
160 }
161 })
162 }
163}
164
165func TestBuildMergesAPackageSeenTwice(t *testing.T) {
166 p := shippedSet()
167 // The same crate from two builds: once shipped, once only as a tool.
168 p = append(p, Package{Ecosystem: Cargo, Name: "wasmi", Version: "0.32.3", Notices: notice("wasmi")})
169 c, err := build(testCatalog(), "docs", p)
170 if err != nil {
171 t.Fatal(err)
172 }
173 w, _ := c.Entry("wasmi")
174 if len(w.Packages) != 1 || w.Packages[0].Tool {
175 t.Fatalf("wasmi = %+v, want one shipped package", w.Packages)
176 }
177 if c.sectionOf("wasmi") != "rust" {
178 t.Errorf("a shipped wasmi is in %q", c.sectionOf("wasmi"))
179 }
180}
181
182func parse(t *testing.T) *template.Template {
183 t.Helper()
184 return template.Must(template.New("").ParseFS(Templates(), "templates/*.html"))
185}
186
187func page(t *testing.T, c Colophon, labels Labels) string {
188 t.Helper()
189 var out bytes.Buffer
190 if err := parse(t).ExecuteTemplate(&out, "estilo/colophon", Page{Title: "Colophon", Intro: []string{"What Docs is made with."}, Labels: labels, LicenceBase: "/help/colophon/", Colophon: c}); err != nil {
191 t.Fatal(err)
192 }
193 return out.String()
194}
195
196func TestPageNamesEachProjectAndLinksItsLicenceHomeAndSource(t *testing.T) {
197 c, err := build(testCatalog(), "docs", shippedSet())
198 if err != nil {
199 t.Fatal(err)
200 }
201 html := page(t, c, English)
202 for _, want := range []string{
203 "<h1>Colophon</h1>", "<p>What Docs is made with.</p>",
204 `<h2 id="colophon-typefaces">Typefaces</h2>`, `<h2 id="colophon-go">Go libraries</h2>`,
205 `<h2 id="colophon-javascript">JavaScript libraries</h2>`, `<h2 id="colophon-tools">Tools</h2>`,
206 `<h3 lang="en"><bdi>ProseMirror</bdi></h3>`, "An editor toolkit. Draws the editor.",
207 "<dt>By</dt>", `<dd lang="en">Marijn Haverbeke</dd>`,
208 `<a href="/help/colophon/prosemirror">MIT License</a>`,
209 `<a href="https://prosemirror.net" rel="noreferrer" referrerpolicy="no-referrer">Home page</a>`,
210 `<a href="https://github.com/ProseMirror" rel="noreferrer" referrerpolicy="no-referrer">Source</a>`,
211 // Home and source the same address: one link that says so.
212 `<a href="https://github.com/googlefonts/carlito" rel="noreferrer" referrerpolicy="no-referrer">Home page and source</a>`,
213 `<a href="#colophon-javascript">JavaScript libraries</a>`,
214 } {
215 if !strings.Contains(html, want) {
216 t.Errorf("the page lost %q", want)
217 }
218 }
219 if strings.Contains(html, "<script") || strings.Contains(html, " on") && regexp.MustCompile(`\son[a-z]+=`).MatchString(html) {
220 t.Error("the page carries script; it must work without")
221 }
222 if regexp.MustCompile(`<h[4-6]`).MatchString(html) {
223 t.Error("the page skips heading levels")
224 }
225 // Every section is in the contents, and every entry has its own anchor.
226 if strings.Count(html, `<a href="#colophon-`) != len(c.Sections) {
227 t.Error("the contents and the sections disagree")
228 }
229 for _, s := range c.Sections {
230 for _, e := range s.Entries {
231 if !strings.Contains(html, `id="colophon-`+e.ID+`"`) {
232 t.Errorf("%s has no anchor", e.ID)
233 }
234 }
235 }
236}
237
238func TestPageEscapesCatalogTextAndRefusesUnsafeLinks(t *testing.T) {
239 cat := testCatalog()
240 cat[0].Name = "<img src=x onerror=alert(1)>"
241 cat[0].Blurb = "Fast & <b>small</b>."
242 cat[0].Home = "javascript:alert(1)"
243 c, err := build(cat, "docs", shippedSet())
244 if err != nil {
245 t.Fatal(err)
246 }
247 html := page(t, c, English)
248 if strings.Contains(html, "<img") || strings.Contains(html, "<b>") || !strings.Contains(html, "Fast &amp; &lt;b&gt;small&lt;/b&gt;.") {
249 t.Fatal("catalog text was interpreted as markup")
250 }
251 if strings.Contains(html, `href="javascript:`) {
252 t.Fatal("an unsafe home URL reached a link")
253 }
254}
255
256// Every label is the caller's, so a page in any of the twelve locales is
257// the caller's translation and the catalog's original words.
258func TestLabelsAreTheCallers(t *testing.T) {
259 c, err := build(testCatalog(), "docs", shippedSet())
260 if err != nil {
261 t.Fatal(err)
262 }
263 for _, label := range []string{"Foinse oscailte", "Código abierto", "オープンソース", "المصدر المفتوح"} {
264 l := English
265 l.By, l.Licence, l.Home, l.Source, l.HomeAndSource, l.Contents = label+"-by", label+"-licence", label+"-home", label+"-source", label+"-both", label+"-contents"
266 l.Sections = map[string]string{}
267 for k := range English.Sections {
268 l.Sections[k] = label + "-" + k
269 }
270 html := page(t, c, l)
271 for _, want := range []string{label + "-by", label + "-licence", label + "-home", label + "-source", label + "-both", label + "-contents", label + "-typefaces", label + "-tools"} {
272 if !strings.Contains(html, template.HTMLEscapeString(want)) {
273 t.Errorf("%s lost", want)
274 }
275 }
276 }
277}
278
279func TestLicencePageShowsEveryPackagesOriginalText(t *testing.T) {
280 c, err := build(testCatalog(), "docs", shippedSet())
281 if err != nil {
282 t.Fatal(err)
283 }
284 pm, _ := c.Entry("prosemirror")
285 pm.Packages[0].Notices = []credits.Notice{{Name: "LICENSE", Text: "\nCopyright <Marijn>\nPermission & conditions"}}
286 var out bytes.Buffer
287 if err := parse(t).ExecuteTemplate(&out, "estilo/colophon-licence", LicencePage{Title: "ProseMirror: licence", Back: "/help/colophon#colophon-prosemirror", Labels: English, Entry: pm}); err != nil {
288 t.Fatal(err)
289 }
290 html := out.String()
291 for _, want := range []string{
292 "<h1>ProseMirror: licence</h1>",
293 `<a href="/help/colophon#colophon-prosemirror">Back to the colophon</a>`,
294 `<h2 lang="en"><bdi>prosemirror-model</bdi> 1.25.11</h2>`, `<h2 lang="en"><bdi>prosemirror-view</bdi> 1.42.3</h2>`,
295 // The parser drops a <pre>'s first newline, so the template adds one.
296 "<pre lang=\"en\">\n\nCopyright &lt;Marijn&gt;\nPermission &amp; conditions</pre>",
297 } {
298 if !strings.Contains(html, want) {
299 t.Errorf("the licence page lost %q", want)
300 }
301 }
302 signin, _ := c.Entry("signin")
303 out.Reset()
304 if err := parse(t).ExecuteTemplate(&out, "estilo/colophon-licence", LicencePage{Title: "signin", Back: "/help/colophon", Labels: English, Entry: signin}); err != nil {
305 t.Fatal(err)
306 }
307 if !strings.Contains(out.String(), English.Missing) {
308 t.Error("a package published without a licence file does not say so")
309 }
310}
311
312// The no-flash rule (AGENTS.md row 9): the Colophon is chrome, set in the
313// system UI face it inherits. Its stylesheet declares no face and fetches
314// nothing.
315func TestStylesheetDeclaresNoFaceAndReadsOnlyDefinedTokens(t *testing.T) {
316 css := string(CSS())
317 for _, banned := range []string{"@font-face", "url(", "@import"} {
318 if strings.Contains(css, banned) {
319 t.Errorf("colophon.css contains %s", banned)
320 }
321 }
322 for _, m := range regexp.MustCompile(`font(-family)?\s*:\s*([^;}]+)`).FindAllStringSubmatch(css, -1) {
323 if strings.TrimSpace(m[2]) != "inherit" {
324 t.Errorf("colophon.css sets a font: %q", m[0])
325 }
326 }
327 missing, n := tokencheck.Undefined(CSS())
328 if n == 0 || len(missing) > 0 {
329 t.Fatalf("colophon.css reads %d tokens, undefined: %v", n, missing)
330 }
331 // 24px targets for every link (WCAG 2.5.8, without the spacing exception).
332 if !strings.Contains(css, "min-block-size: 24px") {
333 t.Error("links lost their 24px target")
334 }
335}
336
337func TestEnglishLabelsCoverEverySection(t *testing.T) {
338 for _, id := range sectionOrder {
339 if English.Sections[id] == "" {
340 t.Errorf("no English heading for %s", id)
341 }
342 }
343 for _, p := range Catalog() {
344 for _, u := range []string{p.Home, p.Source} {
345 if parsed, err := url.Parse(u); err != nil || parsed.Host == "" {
346 t.Errorf("%s: %q", p.ID, u)
347 }
348 }
349 }
350}
351
352// A tool is not in what the app ships, so its licence text is not
353// required; the licence page says why there is none and where it is.
354func TestAToolNeedsNoLicenceTextAndSaysWhereItIs(t *testing.T) {
355 p := shippedSet()
356 p[5].Notices = nil // esbuild
357 c, err := build(testCatalog(), "docs", p)
358 if err != nil {
359 t.Fatal(err)
360 }
361 e, _ := c.Entry("esbuild")
362 var out bytes.Buffer
363 if err := parse(t).ExecuteTemplate(&out, "estilo/colophon-licence", LicencePage{Title: "esbuild", Back: "/help/colophon", Labels: English, Entry: e}); err != nil {
364 t.Fatal(err)
365 }
366 html := out.String()
367 if !strings.Contains(html, template.HTMLEscapeString(English.NotIncluded)) || !strings.Contains(html, `<a href="https://github.com/evanw/esbuild" rel="noreferrer" referrerpolicy="no-referrer">Source</a>`) {
368 t.Fatalf("a tool's licence page does not say where its licence is:\n%s", html)
369 }
370 if strings.Contains(html, English.Missing) {
371 t.Error("a tool's licence page says it was published without one")
372 }
373}
374
375// A blurb may open with any capital, not only an ASCII one: Validate runs
376// at init, so a byte-wise check would stop every consumer starting.
377func TestValidateReadsTheFirstLetterNotTheFirstByte(t *testing.T) {
378 p := testCatalog()[3]
379 for blurb, ok := range map[string]bool{
380 "Łukasz Dziedzic drew it, after his Lato.": true,
381 "Égalité is a serif.": true,
382 "łukasz drew it.": false,
383 } {
384 p.Blurb = blurb
385 if err := Validate([]Project{p}); (err == nil) != ok {
386 t.Errorf("%q: accepted=%v, want %v (%v)", blurb, err == nil, ok, err)
387 }
388 }
389}
390
391// One note for every app (Uses["*"]) saves writing "Yrs uses it." once per
392// app; an app's own note wins, and a default is never stale.
393func TestADefaultUsageNoteServesEveryAppWithoutItsOwn(t *testing.T) {
394 cat := testCatalog()
395 cat[0].Uses = map[string]string{"*": "Holds every document.", "docs-native": "Holds the app's documents."}
396 cat[1].Uses = map[string]string{"*": "Draws the editor."}
397 cat[5].Uses = map[string]string{"docs": "Tests the core."}
398 c, err := build(cat, "docs", shippedSet())
399 if err != nil {
400 t.Fatal(err)
401 }
402 if y, _ := c.Entry("yjs"); y.Usage != "Holds every document." {
403 t.Errorf("docs reads %q, want the default", y.Usage)
404 }
405 native, err := build(cat, "docs-native", []Package{shippedSet()[0]})
406 if err != nil {
407 t.Fatal(err)
408 }
409 if y, _ := native.Entry("yjs"); y.Usage != "Holds the app's documents." {
410 t.Errorf("docs-native reads %q, want its own note", y.Usage)
411 }
412 // prosemirror's default names no app, so not shipping it is not stale.
413 if _, err := build(cat, "docs-native", []Package{shippedSet()[0]}); err != nil {
414 t.Errorf("an unshipped project's default note was called stale: %v", err)
415 }
416}
417
418// The catalog's words appear on US-English pages (Docs' catalog is en-US),
419// so they are written in US English.
420func TestCatalogIsInUSEnglish(t *testing.T) {
421 british := regexp.MustCompile(`(?i)\b(licen[cs]e[ds]? published|licence\w*|\w+isation|\w+ised|\w+ises|normalis\w*|synchronis\w*|maths|colour\w*|centre)\b`)
422 for _, p := range Catalog() {
423 texts := []string{p.Blurb, p.Licence.Name}
424 for _, u := range p.Uses {
425 texts = append(texts, u)
426 }
427 for _, s := range texts {
428 for _, w := range british.FindAllString(s, -1) {
429 if strings.EqualFold(w, "license published") || strings.HasPrefix(strings.ToLower(w), "license") {
430 continue
431 }
432 t.Errorf("%s: %q is British English", p.ID, w)
433 }
434 }
435 }
436}
437
438// The catalog's words and the licence texts are English on a page in the
439// caller's locale, and say so (WCAG 3.1.2); the caller's labels around them
440// keep the page's language. Checked with a Spanish caller: no label is
441// inside a lang="en" element, and every English node is.
442func TestOnlyTheCatalogsEnglishIsMarkedAsEnglish(t *testing.T) {
443 c, err := build(testCatalog(), "docs", shippedSet())
444 if err != nil {
445 t.Fatal(err)
446 }
447 es := English
448 es.Contents, es.By, es.Licence, es.Version = "En esta página", "Autoría", "Licencia", "Versión"
449 es.Home, es.Source, es.HomeAndSource = "Página principal", "Código fuente", "Página principal y código fuente"
450 es.Back, es.Missing, es.NotIncluded = "Volver al colofón", "Este paquete no trae archivo de licencia.", "Es una herramienta; su licencia no se copia aquí."
451 es.Sections = map[string]string{}
452 for k, v := range English.Sections {
453 es.Sections[k] = "ES " + v
454 }
455 labels := []string{es.By, es.Licence, es.Version, es.Home, es.Source, es.HomeAndSource, es.Back, es.Missing, es.NotIncluded, es.Contents}
456 html := page(t, c, es)
457 english := englishText(t, html)
458 for _, l := range labels {
459 if strings.Contains(english, template.HTMLEscapeString(l)) {
460 t.Errorf("the label %q is inside a lang=\"en\" element", l)
461 }
462 }
463 for _, s := range c.Sections {
464 for _, e := range s.Entries {
465 for _, want := range []string{e.Name, template.HTMLEscapeString(e.Blurb), template.HTMLEscapeString(e.Author), template.HTMLEscapeString(e.Licence.Name)} {
466 if !strings.Contains(english, want) {
467 t.Errorf("%s: %q is not marked English", e.ID, want)
468 }
469 }
470 }
471 }
472 for _, id := range []string{"prosemirror", "esbuild", "signin"} {
473 e, _ := c.Entry(id)
474 var out bytes.Buffer
475 if err := parse(t).ExecuteTemplate(&out, "estilo/colophon-licence", LicencePage{Title: "t", Back: "/b", Labels: es, Entry: e}); err != nil {
476 t.Fatal(err)
477 }
478 english := englishText(t, out.String())
479 for _, l := range labels {
480 if strings.Contains(english, template.HTMLEscapeString(l)) {
481 t.Errorf("%s licence page: the label %q is inside a lang=\"en\" element", id, l)
482 }
483 }
484 for _, p := range e.Packages {
485 for _, n := range p.Notices {
486 if !strings.Contains(english, template.HTMLEscapeString(n.Text)) || !strings.Contains(english, n.Name) {
487 t.Errorf("%s: %s's %s is not marked English", id, p.Name, n.Name)
488 }
489 }
490 }
491 }
492}
493
494var tagPattern = regexp.MustCompile(`<(/?)([a-z][a-z0-9]*)([^>]*)>`)
495
496// englishText is the text of html that sits inside an element marked
497// lang="en", joined: a small tag walker, enough for these templates (they
498// close every element they open).
499func englishText(t *testing.T, html string) string {
500 t.Helper()
501 var stack []bool
502 var out strings.Builder
503 last := 0
504 inEnglish := func() bool {
505 for _, en := range stack {
506 if en {
507 return true
508 }
509 }
510 return false
511 }
512 for _, m := range tagPattern.FindAllStringSubmatchIndex(html, -1) {
513 if inEnglish() {
514 out.WriteString(html[last:m[0]])
515 out.WriteString("\n")
516 }
517 last = m[1]
518 closing, attrs := html[m[2]:m[3]] == "/", html[m[6]:m[7]]
519 if closing {
520 if len(stack) == 0 {
521 t.Fatalf("unbalanced </%s>", html[m[4]:m[5]])
522 }
523 stack = stack[:len(stack)-1]
524 continue
525 }
526 stack = append(stack, strings.Contains(attrs, `lang="en"`))
527 }
528 return out.String()
529}
530
531// At 320px a label beside a long value must not be squeezed: flex shrinks
532// a dt that overflow-wrap lets break anywhere ("Ver/si/on"). Docs'
533// browser check measures it; this holds the rule in the stylesheet.
534func TestADefinitionLabelNeverShrinks(t *testing.T) {
535 if !regexp.MustCompile(`\[estilo-colophon-entry\] dt \{[^}]*flex: none`).MatchString(string(CSS())) {
536 t.Error("colophon.css lets a dt shrink")
537 }
538}
539
540// A default note ("*") names the dependents it speaks of (Via); an app
541// whose package is not reached through any of them, in what it ships, has
542// no true note, and Build says so.
543func TestADefaultNoteMustNameADependentThatShips(t *testing.T) {
544 cat := testCatalog()
545 itoa := Project{ID: "itoa", Name: "itoa", Kind: Library, Blurb: "Writes integers as text.", Author: "David Tolnay", Licence: Licence{"MIT", "MIT License"}, Home: "https://crates.io/crates/itoa", Source: "https://github.com/dtolnay/itoa", Packages: []Ref{{Cargo, "itoa"}}, Uses: map[string]string{"*": "serde_json uses it."}, Via: []string{"serde-json"}}
546 sj := Project{ID: "serde-json", Name: "serde_json", Kind: Library, Blurb: "JSON for Serde.", Author: "Erick Tryzelaar and David Tolnay", Licence: Licence{"MIT", "MIT License"}, Home: "https://crates.io/crates/serde_json", Source: "https://github.com/serde-rs/json", Packages: []Ref{{Cargo, "serde_json"}}, Uses: map[string]string{"docs": "Yrs uses it."}}
547 cat = append(cat, itoa, sj)
548 if err := Validate(cat); err != nil {
549 t.Fatal(err)
550 }
551 withSJ := append(shippedSet(),
552 Package{Ecosystem: Cargo, Name: "serde_json", Version: "1.0.151", Notices: notice("sj")},
553 Package{Ecosystem: Cargo, Name: "itoa", Version: "1.0.18", Via: []string{"serde_json"}, Notices: notice("itoa")})
554 if _, err := build(cat, "docs", withSJ); err != nil {
555 t.Fatalf("itoa via a shipped serde_json was refused: %v", err)
556 }
557 // Reached only through something else: the note would be false.
558 other := append(shippedSet(),
559 Package{Ecosystem: Cargo, Name: "itoa", Version: "1.0.18", Via: []string{"ryu"}, Notices: notice("itoa")})
560 _, err := build(cat, "docs", other)
561 if err == nil || !strings.Contains(err.Error(), "itoa's default note names serde-json, which docs does not reach it through") {
562 t.Fatalf("err = %v", err)
563 }
564 // A cargo project with a default note must say whom it names.
565 itoa.Via = nil
566 if err := Validate([]Project{itoa}); err == nil || !strings.Contains(err.Error(), "via") {
567 t.Fatalf("a default note naming no dependent was accepted: %v", err)
568 }
569}
570
571// A default note that names several dependents ("DashMap and aHash use
572// it.") is true only where every one of them uses the crate, and a
573// dependent the app only builds or tests with does not count: it is not
574// in what ships.
575func TestADefaultNoteNeedsEveryNamedDependentShipping(t *testing.T) {
576 base := func() []Project {
577 cat := testCatalog()
578 mk := func(id, crate, note string, via ...string) Project {
579 p := Project{ID: id, Name: crate, Kind: Library, Blurb: "A crate.", Author: "Someone", Licence: Licence{"MIT", "MIT License"}, Home: "https://crates.io/crates/" + crate, Source: "https://github.com/x/" + crate, Packages: []Ref{{Cargo, crate}}, Uses: map[string]string{"docs": "Ships."}}
580 if note != "" {
581 p.Uses = map[string]string{"*": note}
582 p.Via = via
583 }
584 return p
585 }
586 return append(cat, mk("once-cell", "once_cell", "DashMap and aHash use it.", "dashmap", "ahash"), mk("dashmap", "dashmap", ""), mk("ahash", "ahash", ""))
587 }
588 pkg := func(name string, tool bool, via ...string) Package {
589 return Package{Ecosystem: Cargo, Name: name, Version: "1.0.0", Tool: tool, Via: via, Notices: notice(name)}
590 }
591 for name, tc := range map[string]struct {
592 shipped []Package
593 ok bool
594 }{
595 "both name it and both ship": {[]Package{pkg("dashmap", false), pkg("ahash", false), pkg("once_cell", false, "ahash", "dashmap")}, true},
596 "only one of the two uses it": {[]Package{pkg("dashmap", false), pkg("ahash", false), pkg("once_cell", false, "dashmap")}, false},
597 "one of the two is only a tool": {[]Package{pkg("dashmap", false), pkg("ahash", true), pkg("once_cell", false, "ahash", "dashmap")}, false},
598 "the crate itself is only a tool": {[]Package{pkg("dashmap", true), pkg("ahash", true), pkg("once_cell", true, "ahash", "dashmap")}, true},
599 } {
600 t.Run(name, func(t *testing.T) {
601 _, err := build(base(), "docs", append(shippedSet(), tc.shipped...))
602 if (err == nil) != tc.ok {
603 t.Fatalf("accepted=%v, want %v (%v)", err == nil, tc.ok, err)
604 }
605 })
606 }
607}
608