motorino/internal/build/build_test.go
tgiachi 4ab8f8d122
All checks were successful
check / check (pull_request) Successful in 30s
fix: find code blocks with the Markdown parser and make the escape work everywhere
The hand written fence scanner took a line that starts with a code span for a
fence and missed fences in quotes and lists. The code blocks are now the ones
goldmark finds. A backslash before a placeholder is turned into a marker that
survives the Markdown and the list expansion, so it works in a code span and
next to a block name, and two backslashes are a literal one. The em dash rule
reports the line of the body, refuses padded entities and checks the header keys
by name, the feed leaves protocol-relative links alone, base_url needs a host
and a language file cannot set it.
2026-11-15 10:38:56 +01:00

468 lines
18 KiB
Go

// SPDX-License-Identifier: GPL-3.0-or-later
package build
import (
"os"
"path/filepath"
"strings"
"testing"
)
// htmlFiles returns the relative paths of every HTML file of the output.
func htmlFiles(t *testing.T, out string) []string {
t.Helper()
var files []string
err := filepath.WalkDir(out, func(p string, d os.DirEntry, err error) error {
if err == nil && !d.IsDir() && strings.HasSuffix(p, ".html") {
rel, _ := filepath.Rel(out, p)
files = append(files, filepath.ToSlash(rel))
}
return err
})
if err != nil {
t.Fatal(err)
}
return files
}
// TestBuildWritesPagesAndPaths checks that every page lands at its address.
func TestBuildWritesPagesAndPaths(t *testing.T) {
out, err := runBuild(t, baseFiles())
if err != nil {
t.Fatalf("Build() error = %v", err)
}
for _, rel := range []string{
"index.html", "it/index.html", "manifesto.html", "it/manifesto.html", "es/manifesto.html",
"manifesto-history.html", "it/cronologia-manifesto.html", "people.html", "it/persone.html",
"services.html", "it/servizi.html", "news/index.html",
} {
if _, err := os.Stat(filepath.Join(out, rel)); err != nil {
t.Errorf("missing output %s: %v", rel, err)
}
}
mustContain(t, "services.html", readOut(t, out, "services.html"),
"<title>Services</title>", `<meta name="description" content="About Services.">`,
"<strong>squid (at) kmalloc.org</strong>", `<link rel="me" href="https://social.kmalloc.org/@squid">`)
}
// TestBuildNewsPathsDated checks the address and the byline of a post.
func TestBuildNewsPathsDated(t *testing.T) {
out, err := runBuild(t, baseFiles())
if err != nil {
t.Fatal(err)
}
post := readOut(t, out, "news/2026/09/gnu-linux-day-2026.html")
mustContain(t, "post", post,
"<h1>GNU/Linux Day 2026</h1>", `<time datetime="2026-09-18">2026-09-18</time>`,
"Matteo Bini", `<a href="/news/category/linux-day.html">Linux Day</a>`, `<a href="/news/category/flug.html">FLUG</a>`,
"<title>kmalloc.org: GNU/Linux Day 2026</title>", `<a href="/people.html">people</a>`)
readOut(t, out, "news/2026/11/shop.html")
readOut(t, out, "news/2026/11/status.html")
}
// TestBuildCategoryPages checks the page of each category and its posts.
func TestBuildCategoryPages(t *testing.T) {
out, err := runBuild(t, baseFiles())
if err != nil {
t.Fatal(err)
}
flug := readOut(t, out, "news/category/flug.html")
mustContain(t, "flug", flug, "<h1>Category: FLUG</h1>", "GNU/Linux Day 2026", "A shop")
if strings.Contains(flug, "Status page") {
t.Error("category FLUG lists a post that is not in it")
}
day := readOut(t, out, "news/category/linux-day.html")
mustContain(t, "linux-day", day, "GNU/Linux Day 2026")
if strings.Contains(day, "A shop") {
t.Error("category Linux Day lists a post that is not in it")
}
index := readOut(t, out, "news/index.html")
mustContain(t, "news index", index,
`<a href="/news/category/flug.html">FLUG</a> (2)`, `<a href="/news/category/linux-day.html">Linux Day</a> (1)`)
}
// TestBuildRobotsAllowsEverything checks robots.txt and that no page asks to be
// left out of the index.
func TestBuildRobotsAllowsEverything(t *testing.T) {
out, err := runBuild(t, baseFiles())
if err != nil {
t.Fatal(err)
}
robots := readOut(t, out, "robots.txt")
mustContain(t, "robots.txt", robots,
"User-agent: *", "Allow: /$", "Allow: /?lang=en$", "Allow: /it/servizi.html$", "Allow: /news/$",
"Allow: /news/2026/11/shop.html$", "Allow: /news/category/flug.html$", "Allow: /es/manifesto.html$")
if !strings.HasSuffix(robots, "Disallow: /\n") {
t.Errorf("robots.txt does not end with Disallow: /\n%s", robots)
}
for _, rel := range htmlFiles(t, out) {
if strings.Contains(readOut(t, out, rel), `name="robots"`) {
t.Errorf("%s has a robots meta", rel)
}
}
}
// TestBuildHreflangAndLangLinks checks the links between languages.
func TestBuildHreflangAndLangLinks(t *testing.T) {
out, err := runBuild(t, baseFiles())
if err != nil {
t.Fatal(err)
}
en := readOut(t, out, "services.html")
mustContain(t, "en services", en,
`<link rel="alternate" hreflang="en" href="/services.html">`, `<link rel="alternate" hreflang="it" href="/it/servizi.html">`,
`<a href="/it/servizi.html" hreflang="it" lang="it">Italiano</a>`)
it := readOut(t, out, "it/servizi.html")
mustContain(t, "it services", it, `<a href="/services.html" hreflang="en" lang="en">English</a>`)
// A page with no translation points to the home of another language.
post := readOut(t, out, "news/2026/11/shop.html")
mustContain(t, "post", post, `<a href="/it/" hreflang="it" lang="it">Italiano</a>`)
if strings.Contains(post, `rel="alternate" hreflang`) {
t.Error("a page without translation has alternate links")
}
// The Spanish manifesto has the short header and links to its siblings.
es := readOut(t, out, "es/manifesto.html")
mustContain(t, "es manifesto", es, "Traduccion automatica.", "Traduccion de la version 1.0.",
`<a href="/manifesto.html" hreflang="en" lang="en">English</a>`)
}
// TestBuildMenuMarksTheCurrentPage checks aria-current on the menu.
func TestBuildMenuMarksTheCurrentPage(t *testing.T) {
out, err := runBuild(t, baseFiles())
if err != nil {
t.Fatal(err)
}
mustContain(t, "manifesto", readOut(t, out, "manifesto.html"), `<a href="/manifesto.html" aria-current="page">Manifesto</a>`)
mustContain(t, "post", readOut(t, out, "news/2026/11/shop.html"), `<a href="/news/" aria-current="page">News</a>`)
if strings.Contains(readOut(t, out, "people.html"), `aria-current="page">News`) {
t.Error("the News entry is marked on the People page")
}
}
// TestBuildBlockPlaceholders checks the generated lists inside pages.
func TestBuildBlockPlaceholders(t *testing.T) {
out, err := runBuild(t, baseFiles())
if err != nil {
t.Fatal(err)
}
mustContain(t, "news index", readOut(t, out, "news/index.html"),
`<li><time datetime="2026-11-14">2026-11-14</time> <a href="/news/2026/11/shop.html">A shop</a>: About the shop.</li>`)
home := readOut(t, out, "index.html")
mustContain(t, "home", home, `<h2 id="news">News</h2>`, `<a href="/news/2026/11/shop.html">A shop</a>`)
it := readOut(t, out, "it/index.html")
mustContain(t, "it home", it, `<a href="/news/2026/11/shop.html" hreflang="en" lang="en">A shop</a>`)
if strings.Contains(home, "{{") || strings.Contains(home, "<p><ul>") {
t.Errorf("home has a leftover placeholder or a wrapped list:\n%s", home)
}
}
// TestBuildNoNews checks the pages when the site has no news.
func TestBuildNoNews(t *testing.T) {
files := baseFiles()
for _, name := range []string{"news/gnu-linux-day-2026.md", "news/shop.md", "news/status.md"} {
delete(files, name)
}
out, err := runBuild(t, files)
if err != nil {
t.Fatal(err)
}
mustContain(t, "news index", readOut(t, out, "news/index.html"), "No news yet.")
if strings.Contains(readOut(t, out, "index.html"), `<h2 id="news">`) {
t.Error("the home shows a news section but there are no news")
}
}
// TestBuildUnknownPlaceholderFailsAndWritesNothing checks the all-or-nothing rule.
func TestBuildUnknownPlaceholderFailsAndWritesNothing(t *testing.T) {
files := baseFiles()
files["content/en/people.md"] = page("people", "People", "", "Hello {{nope}}.\n")
out, err := runBuild(t, files)
if err == nil || !strings.Contains(err.Error(), "content/en/people.md") || !strings.Contains(err.Error(), "nope") {
t.Fatalf("Build() error = %v, want it to name content/en/people.md and nope", err)
}
if _, statErr := os.Stat(out); statErr == nil {
entries, _ := os.ReadDir(out)
if len(entries) != 0 {
t.Errorf("the output has %d entries after a failed build", len(entries))
}
}
}
// TestBuildLeavesNonPlaceholders checks that text like {{.Name}} reaches the page.
func TestBuildLeavesNonPlaceholders(t *testing.T) {
files := baseFiles()
files["content/en/people.md"] = page("people", "People", "", "A template looks like `{{.Name}}`.\n")
out, err := runBuild(t, files)
if err != nil {
t.Fatal(err)
}
mustContain(t, "people", readOut(t, out, "people.html"), "<code>{{.Name}}</code>")
}
// TestBuildBlockPlaceholderMustStandAlone checks the rule for generated lists.
func TestBuildBlockPlaceholderMustStandAlone(t *testing.T) {
files := baseFiles()
files["content/en/people.md"] = page("people", "People", "", "Look {{news_list}} here.\n")
_, err := runBuild(t, files)
if err == nil || !strings.Contains(err.Error(), "content/en/people.md") || !strings.Contains(err.Error(), "news_list") {
t.Errorf("Build() error = %v, want it to name content/en/people.md and news_list", err)
}
}
// TestBuildNeedsRequiredPages checks that the menu pages must exist in the default language.
func TestBuildNeedsRequiredPages(t *testing.T) {
files := baseFiles()
delete(files, "content/en/news/index.md")
_, err := runBuild(t, files)
if err == nil || !strings.Contains(err.Error(), "news") {
t.Errorf("Build() error = %v, want it to name the missing news page", err)
}
}
// TestBuildFooterPoweredBy checks the credit line on every page.
func TestBuildFooterPoweredBy(t *testing.T) {
out, err := runBuild(t, baseFiles())
if err != nil {
t.Fatal(err)
}
files := htmlFiles(t, out)
if len(files) < 12 {
t.Fatalf("only %d html files", len(files))
}
for _, rel := range files {
mustContain(t, rel, readOut(t, out, rel), `Powered by <a href="https://git.kmalloc.org/squid/motorino">motorino</a>`)
}
}
// TestBuildGeneratorMeta checks the generator meta on every page.
func TestBuildGeneratorMeta(t *testing.T) {
out, err := runBuild(t, baseFiles())
if err != nil {
t.Fatal(err)
}
for _, rel := range htmlFiles(t, out) {
mustContain(t, rel, readOut(t, out, rel), `<meta name="generator" content="motorino 1.2.3">`)
}
}
// TestBuildManifestoLayoutRewritesEmDash checks the manifesto rewrite and its table of contents.
func TestBuildManifestoLayoutRewritesEmDash(t *testing.T) {
out, err := runBuild(t, baseFiles())
if err != nil {
t.Fatal(err)
}
m := readOut(t, out, "manifesto.html")
mustContain(t, "manifesto", m,
"<h1>Manifesto</h1>", "Version 1.2, <time datetime=\"2026-11-14\">2026-11-14</time>",
`<h2 id="01">01. Antifascist</h2>`, `<h2 id="commitments">Our commitments</h2>`,
`<li><a href="#01">01. Antifascist</a></li>`, `<li><a href="#commitments">Our commitments</a></li>`)
if strings.Contains(m, "—") {
t.Error("the manifesto still has an em dash")
}
}
// TestBuildManifestoVersionOverride checks that a translation can say which
// version of the manifesto it translates, while the other pages use the current one.
func TestBuildManifestoVersionOverride(t *testing.T) {
out, err := runBuild(t, baseFiles())
if err != nil {
t.Fatal(err)
}
mustContain(t, "es manifesto", readOut(t, out, "es/manifesto.html"), `Version 1.0, <time datetime="2026-11-12">2026-11-12</time>`)
mustContain(t, "en manifesto", readOut(t, out, "manifesto.html"), `Version 1.2, <time datetime="2026-11-14">2026-11-14</time>`)
}
// TestBuildEscapesQuotesInTitle checks that a title with quotes cannot break
// out of an attribute such as og:title.
func TestBuildEscapesQuotesInTitle(t *testing.T) {
files := baseFiles()
files["news/quoted.md"] = "Title: A \"shop\" with <mugs>\nDate: 2026-11-15T12:00:00+0100\n-\nText.\n"
out, err := runBuild(t, files)
if err != nil {
t.Fatal(err)
}
post := readOut(t, out, "news/2026/11/quoted.html")
mustContain(t, "post", post, `content="kmalloc.org: A &quot;shop&quot; with &lt;mugs&gt;"`)
if strings.Contains(post, `content="kmalloc.org: A "shop"`) {
t.Error("the title broke out of the attribute")
}
}
// TestBuildRejectsSameAddress checks that two outputs with one address are an
// error naming both sources, instead of one silently replacing the other.
func TestBuildRejectsSameAddress(t *testing.T) {
tests := []struct {
name string
extra map[string]string
want []string
}{
{"two pages", map[string]string{"content/en/it/index.md": page("other", "Other", "", "x\n")},
[]string{"content/en/it/index.md", "content/it/index.md"}},
{"page and category", map[string]string{"content/en/news/category/flug.md": page("flugpage", "Flug", "", "x\n")},
[]string{"content/en/news/category/flug.md", "flug"}},
{"page and post", map[string]string{"content/en/news/2026/11/shop.md": page("shoppage", "Shop", "", "x\n")},
[]string{"content/en/news/2026/11/shop.md", "news/shop.md"}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
files := baseFiles()
for k, v := range tt.extra {
files[k] = v
}
_, err := runBuild(t, files)
if err == nil {
t.Fatal("Build() error = nil")
}
for _, want := range tt.want {
if !strings.Contains(err.Error(), want) {
t.Errorf("error %q does not contain %q", err, want)
}
}
})
}
}
// TestBuildRejectsAssetOverPage checks that an asset cannot take the address of a page.
func TestBuildRejectsAssetOverPage(t *testing.T) {
files := baseFiles()
files["site.json"] = strings.Replace(files["site.json"], `"logo.svg": "static/logo.svg"`, `"index.html": "static/logo.svg"`, 1)
_, err := runBuild(t, files)
if err == nil || !strings.Contains(err.Error(), "index.html") {
t.Errorf("Build() error = %v, want it to name index.html", err)
}
}
// TestBuildEscapesSwitchHref checks that a language switch cannot inject an attribute.
func TestBuildEscapesSwitchHref(t *testing.T) {
files := baseFiles()
files["content/en/services.md"] = page("services", "Services", "Switch: it=/x\" onmouseover=\"y\n", "Body.\n")
out, err := runBuild(t, files)
if err != nil {
t.Fatal(err)
}
got := readOut(t, out, "services.html")
mustContain(t, "services", got, `href="/x&quot; onmouseover=&quot;y"`)
if strings.Contains(got, `onmouseover="y"`) {
t.Error("the switch value injected an attribute")
}
}
// TestBuildRejectsSwitchToUnknownLanguage checks that a typo in Switch is not ignored.
func TestBuildRejectsSwitchToUnknownLanguage(t *testing.T) {
files := baseFiles()
files["content/en/services.md"] = page("services", "Services", "Switch: xx=/x\n", "Body.\n")
_, err := runBuild(t, files)
if err == nil || !strings.Contains(err.Error(), "content/en/services.md") || !strings.Contains(err.Error(), "xx") {
t.Errorf("Build() error = %v, want it to name content/en/services.md and xx", err)
}
}
// TestBuildFeedMakesImagesAbsolute checks that src links get the full address like href links.
func TestBuildFeedMakesImagesAbsolute(t *testing.T) {
files := baseFiles()
files["news/pic.md"] = "Title: Pic\nDate: 2026-11-15T12:00:00+0100\n-\n![the logo](/logo.svg)\n"
out, err := runBuild(t, files)
if err != nil {
t.Fatal(err)
}
mustContain(t, "feed", readOut(t, out, "news/feed.xml"), `src="https://kmalloc.org/logo.svg"`)
}
// TestBuildNewsPageMustBeAFolderIndex checks that the feed has a sound address.
func TestBuildNewsPageMustBeAFolderIndex(t *testing.T) {
files := baseFiles()
delete(files, "content/en/news/index.md")
files["content/en/news.md"] = page("news", "News", "", "{{news_list}}\n")
_, err := runBuild(t, files)
if err == nil || !strings.Contains(err.Error(), "content/en/news.md") || !strings.Contains(err.Error(), "index") {
t.Errorf("Build() error = %v, want it to say that content/en/news.md must be an index", err)
}
}
// TestBuildBlockNameInATitleIsNotAnError checks that a generated list that shows
// the text of a block placeholder (in a news title) is not mistaken for a
// placeholder that is not alone in its paragraph.
func TestBuildBlockNameInATitleIsNotAnError(t *testing.T) {
files := baseFiles()
files["news/tpl.md"] = "Title: Use {{latest_news}} in a page\nDate: 2026-11-15T12:00:00+0100\n-\nA note.\n"
out, err := runBuild(t, files)
if err != nil {
t.Fatalf("Build() error = %v", err)
}
mustContain(t, "home", readOut(t, out, "index.html"), "Use {{latest_news}} in a page")
}
// TestBuildPlaceholdersAndCode checks the three ways a page can use a placeholder
// next to code: a value in a code span (the pages show the GPG fingerprint that
// way), a fenced block that shows a placeholder as written, and an escaped one.
func TestBuildPlaceholdersAndCode(t *testing.T) {
files := baseFiles()
files["content/en/people.md"] = page("people", "People", "", "Value `{{lang}}` and escaped \\{{lang}}.\n\n```\n{{lang}} {{nope}}\n```\n\nAnd {{lang}}.\n")
out, err := runBuild(t, files)
if err != nil {
t.Fatalf("Build() error = %v", err)
}
got := readOut(t, out, "people.html")
mustContain(t, "people", got, "<code>en</code>", "escaped {{lang}}.", "{{lang}} {{nope}}", "And en.")
}
// TestBuildEscapedPlaceholders checks the escape with block placeholders: an
// escaped one inside a sentence or alone in a paragraph is shown, not expanded
// and not an error, and a code span can show a placeholder as written.
func TestBuildEscapedPlaceholders(t *testing.T) {
files := baseFiles()
files["content/en/people.md"] = page("people", "People", "", "See \\{{news_list}} here.\n\n\\{{latest_news}}\n\nAnd `\\{{lang}}`.\n")
out, err := runBuild(t, files)
if err != nil {
t.Fatalf("Build() error = %v", err)
}
got := readOut(t, out, "people.html")
mustContain(t, "people", got, "See {{news_list}} here.", "<p>{{latest_news}}</p>", "<code>{{lang}}</code>")
if strings.Contains(got, "<ul>") {
t.Error("an escaped block placeholder was expanded")
}
}
// TestBuildAssetsCopied checks the assets listed in site.json.
func TestBuildAssetsCopied(t *testing.T) {
out, err := runBuild(t, baseFiles())
if err != nil {
t.Fatal(err)
}
if got := readOut(t, out, "logo.svg"); got != "<svg/>\n" {
t.Errorf("logo.svg = %q", got)
}
}
// TestBuildMissingAssetFails checks that an asset that is not there stops the build.
func TestBuildMissingAssetFails(t *testing.T) {
files := baseFiles()
delete(files, "static/logo.svg")
_, err := runBuild(t, files)
if err == nil || !strings.Contains(err.Error(), "static/logo.svg") {
t.Errorf("Build() error = %v, want it to name static/logo.svg", err)
}
}
// TestBuildFeed checks the feed at the address of the news page.
func TestBuildFeed(t *testing.T) {
out, err := runBuild(t, baseFiles())
if err != nil {
t.Fatal(err)
}
feed := readOut(t, out, "news/feed.xml")
mustContain(t, "feed", feed,
"<guid isPermaLink=\"true\">https://kmalloc.org/news/2026/11/shop.html</guid>",
`&lt;a href="https://kmalloc.org/people.html"&gt;people&lt;/a&gt;`)
}
// TestBuildErrorsOnMissingTemplate checks that a missing layout template is named.
func TestBuildErrorsOnMissingTemplate(t *testing.T) {
files := baseFiles()
delete(files, "templates/pages/manifesto.html")
_, err := runBuild(t, files)
if err == nil || !strings.Contains(err.Error(), "pages/manifesto") {
t.Errorf("Build() error = %v, want it to name pages/manifesto", err)
}
}