package colophon import ( "bytes" "html/template" "net/url" "regexp" "strings" "testing" "amadan.net/oficina/estilo.git/credits" "amadan.net/oficina/estilo.git/internal/tokencheck" ) // The catalog is the one place every app's Colophon reads a project's // description from, so every entry in it must be whole: a blurb, who made // it, the licence it is under, and links to its home and its source. func TestCatalogEntriesAreComplete(t *testing.T) { projects := Catalog() if len(projects) < 50 { t.Fatalf("the catalog has %d projects; the checks below would pass nearly vacuously", len(projects)) } if err := Validate(projects); err != nil { t.Fatal(err) } } func TestValidateRefusesAnIncompleteEntry(t *testing.T) { 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."}} if err := Validate([]Project{good}); err != nil { t.Fatalf("a complete entry was refused: %v", err) } for name, spoil := range map[string]func(*Project){ "no blurb": func(p *Project) { p.Blurb = "" }, "blurb in lower case": func(p *Project) { p.Blurb = "a CRDT for shared editing." }, "three sentences": func(p *Project) { p.Blurb = "One thing. Another thing. A third thing." }, "no author": func(p *Project) { p.Author = " " }, "no licence name": func(p *Project) { p.Licence.Name = "" }, "no licence identifier": func(p *Project) { p.Licence.SPDX = "" }, "no home": func(p *Project) { p.Home = "" }, "plain-http source": func(p *Project) { p.Source = "http://github.com/yjs/yjs" }, "script url": func(p *Project) { p.Home = "javascript:alert(1)" }, "no packages": func(p *Project) { p.Packages = nil }, "unknown kind": func(p *Project) { p.Kind = "gadget" }, "unknown ecosystem": func(p *Project) { p.Packages = []Ref{{Ecosystem: "maven", Name: "x"}} }, "bad id": func(p *Project) { p.ID = "Yjs Project" }, "empty usage note": func(p *Project) { p.Uses = map[string]string{"docs": ""} }, "usage not a sentence": func(p *Project) { p.Uses = map[string]string{"docs": "the editor"} }, } { p := good p.Packages = append([]Ref(nil), good.Packages...) p.Uses = map[string]string{"docs": good.Uses["docs"]} spoil(&p) if err := Validate([]Project{p}); err == nil { t.Errorf("%s: accepted", name) } } twin := good twin.ID = "yjs-again" if err := Validate([]Project{good, twin}); err == nil || !strings.Contains(err.Error(), "npm:yjs") { t.Errorf("one package claimed by two projects was accepted: %v", err) } same := good if err := Validate([]Project{good, same}); err == nil { t.Error("a duplicate id was accepted") } } func notice(text string) []credits.Notice { return []credits.Notice{{Name: "LICENSE", Text: text}} } func testCatalog() []Project { return []Project{ {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."}}, {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."}}, {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."}}, {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."}}, {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."}}, {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."}}, {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."}}, } } func shippedSet() []Package { return []Package{ {Ecosystem: NPM, Name: "yjs", Version: "13.6.27", Notices: notice("yjs")}, {Ecosystem: NPM, Name: "prosemirror-view", Version: "1.42.3", Notices: notice("pmv")}, {Ecosystem: NPM, Name: "prosemirror-model", Version: "1.25.11", Notices: notice("pmm")}, {Ecosystem: Go, Name: "github.com/go-chi/chi/v5", Version: "v5.3.2", Notices: notice("chi")}, {Ecosystem: Font, Name: "Carlito", Notices: notice("OFL")}, {Ecosystem: NPM, Name: "esbuild", Version: "0.28.2", Tool: true, Notices: notice("esbuild")}, {Ecosystem: Cargo, Name: "wasmi", Version: "0.32.3", Tool: true, Notices: notice("wasmi")}, {Ecosystem: Go, Name: "github.com/keymaildev/signin", Version: "v0.1.1"}, } } func TestBuildGroupsEveryShippedPackageUnderItsProject(t *testing.T) { c, err := build(testCatalog(), "docs", shippedSet()) if err != nil { t.Fatal(err) } var order []string for _, s := range c.Sections { var names []string for _, e := range s.Entries { names = append(names, e.ID) } order = append(order, s.ID+"="+strings.Join(names, ",")) } // Typefaces first, then libraries by runtime, then tools. A library // that this app only builds or tests with (wasmi, a dev-dependency of // the web core) is a tool here, whatever it is elsewhere. if got, want := strings.Join(order, " "), "typefaces=carlito go=chi,signin javascript=prosemirror,yjs tools=esbuild,wasmi"; got != want { t.Fatalf("sections = %s, want %s", got, want) } pm, ok := c.Entry("prosemirror") if !ok || len(pm.Packages) != 2 || pm.Packages[0].Name != "prosemirror-model" || pm.Usage != "Draws the editor." || pm.Blurb != "An editor toolkit." { t.Fatalf("ProseMirror's two packages or its words were lost: %+v", pm) } if got := pm.VersionText(); got != "prosemirror-model 1.25.11, prosemirror-view 1.42.3" { t.Errorf("VersionText = %q", got) } if y, _ := c.Entry("yjs"); y.VersionText() != "13.6.27" { t.Errorf("a one-package project's version is %q", y.VersionText()) } if n := c.Count(); n["typefaces"] != 1 || n["javascript"] != 2 || n["total"] != 7 { t.Errorf("Count = %v", n) } } // The test every app's Colophon leans on: the shipped set and the Colophon // may not differ. Each way they can is refused, by name. func TestBuildRefusesMissingStaleAndIncompleteEntries(t *testing.T) { cases := map[string]struct { app string shipped func([]Package) []Package want string }{ "a shipped package with no catalog entry": {"docs", func(p []Package) []Package { return append(p, Package{Ecosystem: Cargo, Name: "yrs", Version: "0.23.5", Notices: notice("yrs")}) }, "cargo:yrs has no catalog entry"}, "a shipped project with no usage note for the app": {"docs-native", func(p []Package) []Package { return []Package{p[0]} }, "yjs has no usage note for docs-native"}, "a usage note for a project the app no longer ships": {"docs", func(p []Package) []Package { return p[1:] }, "yjs has a usage note for docs but docs does not ship it"}, "a package without its licence text": {"docs", func(p []Package) []Package { p[0].Notices = nil return p }, "npm:yjs 13.6.27 carries no licence text"}, "an unnamed package": {"docs", func(p []Package) []Package { return append(p, Package{Ecosystem: NPM}) }, "a package without an ecosystem or name"}, } for name, tc := range cases { t.Run(name, func(t *testing.T) { _, err := build(testCatalog(), tc.app, tc.shipped(shippedSet())) if err == nil || !strings.Contains(err.Error(), tc.want) { t.Fatalf("err = %v, want it to say %q", err, tc.want) } }) } } func TestBuildMergesAPackageSeenTwice(t *testing.T) { p := shippedSet() // The same crate from two builds: once shipped, once only as a tool. p = append(p, Package{Ecosystem: Cargo, Name: "wasmi", Version: "0.32.3", Notices: notice("wasmi")}) c, err := build(testCatalog(), "docs", p) if err != nil { t.Fatal(err) } w, _ := c.Entry("wasmi") if len(w.Packages) != 1 || w.Packages[0].Tool { t.Fatalf("wasmi = %+v, want one shipped package", w.Packages) } if c.sectionOf("wasmi") != "rust" { t.Errorf("a shipped wasmi is in %q", c.sectionOf("wasmi")) } } func parse(t *testing.T) *template.Template { t.Helper() return template.Must(template.New("").ParseFS(Templates(), "templates/*.html")) } func page(t *testing.T, c Colophon, labels Labels) string { t.Helper() var out bytes.Buffer 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 { t.Fatal(err) } return out.String() } func TestPageNamesEachProjectAndLinksItsLicenceHomeAndSource(t *testing.T) { c, err := build(testCatalog(), "docs", shippedSet()) if err != nil { t.Fatal(err) } html := page(t, c, English) for _, want := range []string{ "

Colophon

", "

What Docs is made with.

", `

Typefaces

`, `

Go libraries

`, `

JavaScript libraries

`, `

Tools

`, `

ProseMirror

`, "An editor toolkit. Draws the editor.", "
By
", `
Marijn Haverbeke
`, `MIT License`, `Home page`, `Source`, // Home and source the same address: one link that says so. `Home page and source`, `JavaScript libraries`, } { if !strings.Contains(html, want) { t.Errorf("the page lost %q", want) } } if strings.Contains(html, "") || !strings.Contains(html, "Fast & <b>small</b>.") { t.Fatal("catalog text was interpreted as markup") } if strings.Contains(html, `href="javascript:`) { t.Fatal("an unsafe home URL reached a link") } } // Every label is the caller's, so a page in any of the twelve locales is // the caller's translation and the catalog's original words. func TestLabelsAreTheCallers(t *testing.T) { c, err := build(testCatalog(), "docs", shippedSet()) if err != nil { t.Fatal(err) } for _, label := range []string{"Foinse oscailte", "Código abierto", "オープンソース", "المصدر المفتوح"} { l := English l.By, l.Licence, l.Home, l.Source, l.HomeAndSource, l.Contents = label+"-by", label+"-licence", label+"-home", label+"-source", label+"-both", label+"-contents" l.Sections = map[string]string{} for k := range English.Sections { l.Sections[k] = label + "-" + k } html := page(t, c, l) for _, want := range []string{label + "-by", label + "-licence", label + "-home", label + "-source", label + "-both", label + "-contents", label + "-typefaces", label + "-tools"} { if !strings.Contains(html, template.HTMLEscapeString(want)) { t.Errorf("%s lost", want) } } } } func TestLicencePageShowsEveryPackagesOriginalText(t *testing.T) { c, err := build(testCatalog(), "docs", shippedSet()) if err != nil { t.Fatal(err) } pm, _ := c.Entry("prosemirror") pm.Packages[0].Notices = []credits.Notice{{Name: "LICENSE", Text: "\nCopyright \nPermission & conditions"}} var out bytes.Buffer if err := parse(t).ExecuteTemplate(&out, "estilo/colophon-licence", LicencePage{Title: "ProseMirror: licence", Back: "/help/colophon#colophon-prosemirror", Labels: English, Entry: pm}); err != nil { t.Fatal(err) } html := out.String() for _, want := range []string{ "

ProseMirror: licence

", `Back to the colophon`, `

prosemirror-model 1.25.11

`, `

prosemirror-view 1.42.3

`, // The parser drops a
's first newline, so the template adds one.
		"
\n\nCopyright <Marijn>\nPermission & conditions
", } { if !strings.Contains(html, want) { t.Errorf("the licence page lost %q", want) } } signin, _ := c.Entry("signin") out.Reset() if err := parse(t).ExecuteTemplate(&out, "estilo/colophon-licence", LicencePage{Title: "signin", Back: "/help/colophon", Labels: English, Entry: signin}); err != nil { t.Fatal(err) } if !strings.Contains(out.String(), English.Missing) { t.Error("a package published without a licence file does not say so") } } // The no-flash rule (AGENTS.md row 9): the Colophon is chrome, set in the // system UI face it inherits. Its stylesheet declares no face and fetches // nothing. func TestStylesheetDeclaresNoFaceAndReadsOnlyDefinedTokens(t *testing.T) { css := string(CSS()) for _, banned := range []string{"@font-face", "url(", "@import"} { if strings.Contains(css, banned) { t.Errorf("colophon.css contains %s", banned) } } for _, m := range regexp.MustCompile(`font(-family)?\s*:\s*([^;}]+)`).FindAllStringSubmatch(css, -1) { if strings.TrimSpace(m[2]) != "inherit" { t.Errorf("colophon.css sets a font: %q", m[0]) } } missing, n := tokencheck.Undefined(CSS()) if n == 0 || len(missing) > 0 { t.Fatalf("colophon.css reads %d tokens, undefined: %v", n, missing) } // 24px targets for every link (WCAG 2.5.8, without the spacing exception). if !strings.Contains(css, "min-block-size: 24px") { t.Error("links lost their 24px target") } } func TestEnglishLabelsCoverEverySection(t *testing.T) { for _, id := range sectionOrder { if English.Sections[id] == "" { t.Errorf("no English heading for %s", id) } } for _, p := range Catalog() { for _, u := range []string{p.Home, p.Source} { if parsed, err := url.Parse(u); err != nil || parsed.Host == "" { t.Errorf("%s: %q", p.ID, u) } } } } // A tool is not in what the app ships, so its licence text is not // required; the licence page says why there is none and where it is. func TestAToolNeedsNoLicenceTextAndSaysWhereItIs(t *testing.T) { p := shippedSet() p[5].Notices = nil // esbuild c, err := build(testCatalog(), "docs", p) if err != nil { t.Fatal(err) } e, _ := c.Entry("esbuild") var out bytes.Buffer if err := parse(t).ExecuteTemplate(&out, "estilo/colophon-licence", LicencePage{Title: "esbuild", Back: "/help/colophon", Labels: English, Entry: e}); err != nil { t.Fatal(err) } html := out.String() if !strings.Contains(html, template.HTMLEscapeString(English.NotIncluded)) || !strings.Contains(html, `Source`) { t.Fatalf("a tool's licence page does not say where its licence is:\n%s", html) } if strings.Contains(html, English.Missing) { t.Error("a tool's licence page says it was published without one") } } // A blurb may open with any capital, not only an ASCII one: Validate runs // at init, so a byte-wise check would stop every consumer starting. func TestValidateReadsTheFirstLetterNotTheFirstByte(t *testing.T) { p := testCatalog()[3] for blurb, ok := range map[string]bool{ "Łukasz Dziedzic drew it, after his Lato.": true, "Égalité is a serif.": true, "łukasz drew it.": false, } { p.Blurb = blurb if err := Validate([]Project{p}); (err == nil) != ok { t.Errorf("%q: accepted=%v, want %v (%v)", blurb, err == nil, ok, err) } } } // One note for every app (Uses["*"]) saves writing "Yrs uses it." once per // app; an app's own note wins, and a default is never stale. func TestADefaultUsageNoteServesEveryAppWithoutItsOwn(t *testing.T) { cat := testCatalog() cat[0].Uses = map[string]string{"*": "Holds every document.", "docs-native": "Holds the app's documents."} cat[1].Uses = map[string]string{"*": "Draws the editor."} cat[5].Uses = map[string]string{"docs": "Tests the core."} c, err := build(cat, "docs", shippedSet()) if err != nil { t.Fatal(err) } if y, _ := c.Entry("yjs"); y.Usage != "Holds every document." { t.Errorf("docs reads %q, want the default", y.Usage) } native, err := build(cat, "docs-native", []Package{shippedSet()[0]}) if err != nil { t.Fatal(err) } if y, _ := native.Entry("yjs"); y.Usage != "Holds the app's documents." { t.Errorf("docs-native reads %q, want its own note", y.Usage) } // prosemirror's default names no app, so not shipping it is not stale. if _, err := build(cat, "docs-native", []Package{shippedSet()[0]}); err != nil { t.Errorf("an unshipped project's default note was called stale: %v", err) } } // The catalog's words appear on US-English pages (Docs' catalog is en-US), // so they are written in US English. func TestCatalogIsInUSEnglish(t *testing.T) { 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`) for _, p := range Catalog() { texts := []string{p.Blurb, p.Licence.Name} for _, u := range p.Uses { texts = append(texts, u) } for _, s := range texts { for _, w := range british.FindAllString(s, -1) { if strings.EqualFold(w, "license published") || strings.HasPrefix(strings.ToLower(w), "license") { continue } t.Errorf("%s: %q is British English", p.ID, w) } } } } // The catalog's words and the licence texts are English on a page in the // caller's locale, and say so (WCAG 3.1.2); the caller's labels around them // keep the page's language. Checked with a Spanish caller: no label is // inside a lang="en" element, and every English node is. func TestOnlyTheCatalogsEnglishIsMarkedAsEnglish(t *testing.T) { c, err := build(testCatalog(), "docs", shippedSet()) if err != nil { t.Fatal(err) } es := English es.Contents, es.By, es.Licence, es.Version = "En esta página", "Autoría", "Licencia", "Versión" es.Home, es.Source, es.HomeAndSource = "Página principal", "Código fuente", "Página principal y código fuente" 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í." es.Sections = map[string]string{} for k, v := range English.Sections { es.Sections[k] = "ES " + v } labels := []string{es.By, es.Licence, es.Version, es.Home, es.Source, es.HomeAndSource, es.Back, es.Missing, es.NotIncluded, es.Contents} html := page(t, c, es) english := englishText(t, html) for _, l := range labels { if strings.Contains(english, template.HTMLEscapeString(l)) { t.Errorf("the label %q is inside a lang=\"en\" element", l) } } for _, s := range c.Sections { for _, e := range s.Entries { for _, want := range []string{e.Name, template.HTMLEscapeString(e.Blurb), template.HTMLEscapeString(e.Author), template.HTMLEscapeString(e.Licence.Name)} { if !strings.Contains(english, want) { t.Errorf("%s: %q is not marked English", e.ID, want) } } } } for _, id := range []string{"prosemirror", "esbuild", "signin"} { e, _ := c.Entry(id) var out bytes.Buffer if err := parse(t).ExecuteTemplate(&out, "estilo/colophon-licence", LicencePage{Title: "t", Back: "/b", Labels: es, Entry: e}); err != nil { t.Fatal(err) } english := englishText(t, out.String()) for _, l := range labels { if strings.Contains(english, template.HTMLEscapeString(l)) { t.Errorf("%s licence page: the label %q is inside a lang=\"en\" element", id, l) } } for _, p := range e.Packages { for _, n := range p.Notices { if !strings.Contains(english, template.HTMLEscapeString(n.Text)) || !strings.Contains(english, n.Name) { t.Errorf("%s: %s's %s is not marked English", id, p.Name, n.Name) } } } } } var tagPattern = regexp.MustCompile(`<(/?)([a-z][a-z0-9]*)([^>]*)>`) // englishText is the text of html that sits inside an element marked // lang="en", joined: a small tag walker, enough for these templates (they // close every element they open). func englishText(t *testing.T, html string) string { t.Helper() var stack []bool var out strings.Builder last := 0 inEnglish := func() bool { for _, en := range stack { if en { return true } } return false } for _, m := range tagPattern.FindAllStringSubmatchIndex(html, -1) { if inEnglish() { out.WriteString(html[last:m[0]]) out.WriteString("\n") } last = m[1] closing, attrs := html[m[2]:m[3]] == "/", html[m[6]:m[7]] if closing { if len(stack) == 0 { t.Fatalf("unbalanced ", html[m[4]:m[5]]) } stack = stack[:len(stack)-1] continue } stack = append(stack, strings.Contains(attrs, `lang="en"`)) } return out.String() } // At 320px a label beside a long value must not be squeezed: flex shrinks // a dt that overflow-wrap lets break anywhere ("Ver/si/on"). Docs' // browser check measures it; this holds the rule in the stylesheet. func TestADefinitionLabelNeverShrinks(t *testing.T) { if !regexp.MustCompile(`\[estilo-colophon-entry\] dt \{[^}]*flex: none`).MatchString(string(CSS())) { t.Error("colophon.css lets a dt shrink") } } // A default note ("*") names the dependents it speaks of (Via); an app // whose package is not reached through any of them, in what it ships, has // no true note, and Build says so. func TestADefaultNoteMustNameADependentThatShips(t *testing.T) { cat := testCatalog() 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"}} 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."}} cat = append(cat, itoa, sj) if err := Validate(cat); err != nil { t.Fatal(err) } withSJ := append(shippedSet(), Package{Ecosystem: Cargo, Name: "serde_json", Version: "1.0.151", Notices: notice("sj")}, Package{Ecosystem: Cargo, Name: "itoa", Version: "1.0.18", Via: []string{"serde_json"}, Notices: notice("itoa")}) if _, err := build(cat, "docs", withSJ); err != nil { t.Fatalf("itoa via a shipped serde_json was refused: %v", err) } // Reached only through something else: the note would be false. other := append(shippedSet(), Package{Ecosystem: Cargo, Name: "itoa", Version: "1.0.18", Via: []string{"ryu"}, Notices: notice("itoa")}) _, err := build(cat, "docs", other) if err == nil || !strings.Contains(err.Error(), "itoa's default note names serde-json, which docs does not reach it through") { t.Fatalf("err = %v", err) } // A cargo project with a default note must say whom it names. itoa.Via = nil if err := Validate([]Project{itoa}); err == nil || !strings.Contains(err.Error(), "via") { t.Fatalf("a default note naming no dependent was accepted: %v", err) } } // A default note that names several dependents ("DashMap and aHash use // it.") is true only where every one of them uses the crate, and a // dependent the app only builds or tests with does not count: it is not // in what ships. func TestADefaultNoteNeedsEveryNamedDependentShipping(t *testing.T) { base := func() []Project { cat := testCatalog() mk := func(id, crate, note string, via ...string) Project { 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."}} if note != "" { p.Uses = map[string]string{"*": note} p.Via = via } return p } return append(cat, mk("once-cell", "once_cell", "DashMap and aHash use it.", "dashmap", "ahash"), mk("dashmap", "dashmap", ""), mk("ahash", "ahash", "")) } pkg := func(name string, tool bool, via ...string) Package { return Package{Ecosystem: Cargo, Name: name, Version: "1.0.0", Tool: tool, Via: via, Notices: notice(name)} } for name, tc := range map[string]struct { shipped []Package ok bool }{ "both name it and both ship": {[]Package{pkg("dashmap", false), pkg("ahash", false), pkg("once_cell", false, "ahash", "dashmap")}, true}, "only one of the two uses it": {[]Package{pkg("dashmap", false), pkg("ahash", false), pkg("once_cell", false, "dashmap")}, false}, "one of the two is only a tool": {[]Package{pkg("dashmap", false), pkg("ahash", true), pkg("once_cell", false, "ahash", "dashmap")}, false}, "the crate itself is only a tool": {[]Package{pkg("dashmap", true), pkg("ahash", true), pkg("once_cell", true, "ahash", "dashmap")}, true}, } { t.Run(name, func(t *testing.T) { _, err := build(base(), "docs", append(shippedSet(), tc.shipped...)) if (err == nil) != tc.ok { t.Fatalf("accepted=%v, want %v (%v)", err == nil, tc.ok, err) } }) } }