Skip to content
quarry Artifact [49facd10bf]
Login

Artifact [49facd10bf]

Artifact 49facd10bf23fd0fc8acce5b4a9426b3473e297b944fdd93300bc839992cdbc0:


package markup

import (
	"strings"
	"testing"

	xhtml "golang.org/x/net/html"
)

// ghParse parses rendered output so a test asserts on elements,
// attributes and nesting, not on the bytes the renderer happened to emit.
func ghParse(t *testing.T, out []byte) *xhtml.Node {
	t.Helper()
	doc, err := xhtml.Parse(strings.NewReader(string(out)))
	if err != nil {
		t.Fatalf("FAIL: rendered output does not parse: %v", err)
	}
	return doc
}

func ghWalk(n *xhtml.Node, f func(*xhtml.Node)) {
	f(n)
	for c := n.FirstChild; c != nil; c = c.NextSibling {
		ghWalk(c, f)
	}
}

func ghAttr(n *xhtml.Node, key string) string {
	for _, a := range n.Attr {
		if a.Key == key {
			return a.Val
		}
	}
	return ""
}

func ghHasClass(n *xhtml.Node, c string) bool {
	return n.Type == xhtml.ElementNode && ghAttr(n, "class") == c
}

func ghFind(doc *xhtml.Node, match func(*xhtml.Node) bool) []*xhtml.Node {
	var out []*xhtml.Node
	ghWalk(doc, func(n *xhtml.Node) {
		if match(n) {
			out = append(out, n)
		}
	})
	return out
}

func ghTag(name string) func(*xhtml.Node) bool {
	return func(n *xhtml.Node) bool { return n.Type == xhtml.ElementNode && n.Data == name }
}

func ghUnder(n *xhtml.Node, names ...string) bool {
	for p := n.Parent; p != nil; p = p.Parent {
		for _, name := range names {
			if p.Type == xhtml.ElementNode && p.Data == name {
				return true
			}
		}
	}
	return false
}

func ghRender(t *testing.T, src string) (*xhtml.Node, []byte) {
	t.Helper()
	SetImageProxy(nil)
	out, err := Render([]byte(src), nil)
	if err != nil {
		t.Fatalf("FAIL: render: %v", err)
	}
	return ghParse(t, out), out
}

func ghEmoji(doc *xhtml.Node) []*xhtml.Node {
	return ghFind(doc, func(n *xhtml.Node) bool { return ghHasClass(n, "emoji") })
}

func ghIDs(doc *xhtml.Node, tag string) []string {
	var out []string
	for _, n := range ghFind(doc, ghTag(tag)) {
		if id := ghAttr(n, "id"); id != "" {
			out = append(out, id)
		}
	}
	return out
}

func ghIn(list []string, s string) bool {
	for _, v := range list {
		if v == s {
			return true
		}
	}
	return false
}

func TestEmojiShortcodesInTextAndHeadings(t *testing.T) {
	doc, out := ghRender(t, "## :anger: Table of Contents\n\nship it :tada: now, and :+1:\n")

	spans := ghEmoji(doc)
	if len(spans) != 3 {
		t.Fatalf("FAIL: want 3 emoji spans, got %d: %s", len(spans), out)
	}
	for _, s := range spans {
		alias := ghAttr(s, "data-alias")
		if gemoji[alias] == "" || s.FirstChild == nil || s.FirstChild.Data != gemoji[alias] {
			t.Errorf("FAIL: span for %q does not hold that emoji: %s", alias, out)
		}
	}
	var inHeading, inParagraph int
	for _, s := range spans {
		if ghUnder(s, "h3") {
			inHeading++
		}
		if ghUnder(s, "p") {
			inParagraph++
		}
	}
	if inHeading != 1 || inParagraph != 2 {
		t.Errorf("FAIL: emoji in heading=%d paragraph=%d, want 1 and 2", inHeading, inParagraph)
	}
	if strings.Contains(string(out), ":tada:") || strings.Contains(string(out), ":anger:") {
		t.Errorf("FAIL: a shortcode survived: %s", out)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestEmojiShortcodesLeaveCodeAlone(t *testing.T) {
	doc, out := ghRender(t, "inline `:tada:` here\n\n```\n:tada: fenced\n```\n\n    :tada: indented\n\n<code>:tada:</code> and <kbd>:tada:</kbd>\n")

	if n := len(ghEmoji(doc)); n != 0 {
		t.Errorf("FAIL: %d emoji spans in a document of code: %s", n, out)
	}
	if got := strings.Count(string(out), ":tada:"); got < 5 {
		t.Errorf("FAIL: only %d of 5 code shortcodes kept verbatim: %s", got, out)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestEmojiNeedsNonWordNeighbours(t *testing.T) {
	doc, out := ghRender(t, "a:b:c and 10:30:45 and x:tada:y and :nosuchname: and https://example.com/:tada:/page and (:tada:)\n")

	spans := ghEmoji(doc)
	if len(spans) != 1 {
		t.Fatalf("FAIL: want only the parenthesised shortcode converted, got %d: %s", len(spans), out)
	}
	if !ghUnder(spans[0], "p") || ghUnder(spans[0], "a") {
		t.Errorf("FAIL: the converted shortcode is not plain paragraph text: %s", out)
	}
	for _, a := range ghFind(doc, ghTag("a")) {
		if !strings.Contains(ghAttr(a, "href"), ":tada:") {
			t.Errorf("FAIL: a link's target was changed: %s", out)
		}
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// The README of the-book-of-secret-knowledge, in miniature.
const githubReadme = "## :notebook_with_decorative_cover:&nbsp;&nbsp;What is it?\n\n" +
	"#### CLI Tools <sup>[[TOC]](#anger-table-of-contents)</sup>\n\n" +
	"##### :black_small_square: Shells\n\n" +
	"## :anger: Table of Contents\n\n" +
	"[tools](#cli-tools-toc)\n"

func TestGitHubSlugsAreExtraAnchors(t *testing.T) {
	doc, out := ghRender(t, githubReadme)

	empty := ghFind(doc, func(n *xhtml.Node) bool {
		return n.Data == "a" && ghAttr(n, "id") != "" && n.FirstChild == nil
	})
	var got []string
	for _, a := range empty {
		got = append(got, ghAttr(a, "id"))
		// Each extra anchor sits directly before a heading.
		next := a.NextSibling
		for next != nil && next.Type == xhtml.TextNode {
			next = next.NextSibling
		}
		if next == nil || len(next.Data) != 2 || next.Data[0] != 'h' {
			t.Errorf("FAIL: anchor %q is not directly before a heading: %s", ghAttr(a, "id"), out)
		}
	}
	for _, want := range []string{"cli-tools-toc", "notebook_with_decorative_cover--what-is-it", "black_small_square-shells"} {
		if !ghIn(got, want) {
			t.Errorf("FAIL: no extra anchor %q among %v", want, got)
		}
	}

	// ":anger: Table of Contents" slugs to quarry's own id, so there is
	// no second anchor for it, and no id is written twice.
	seen := map[string]int{}
	ghWalk(doc, func(n *xhtml.Node) {
		if n.Type == xhtml.ElementNode {
			if id := ghAttr(n, "id"); id != "" {
				seen[id]++
			}
		}
	})
	for id, n := range seen {
		if n != 1 {
			t.Errorf("FAIL: id %q appears %d times", id, n)
		}
	}
	if !ghIn(ghIDs(doc, "h3"), "anger-table-of-contents") {
		t.Errorf("FAIL: the heading lost its own id: %s", out)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestGitHubSlugsKeepQuarryIDs(t *testing.T) {
	doc, out := ghRender(t, githubReadme)

	if got := ghIDs(doc, "h3"); !ghIn(got, "notebook-with-decorative-covernbspnbspwhat-is-it") || !ghIn(got, "anger-table-of-contents") {
		t.Errorf("FAIL: level-2 heading ids changed: %v: %s", got, out)
	}
	if got := ghIDs(doc, "h5"); len(got) != 1 || got[0] != "cli-tools-suptocanger-table-of-contentssup" {
		t.Errorf("FAIL: the CLI Tools heading id changed: %v", got)
	}
	if got := ghIDs(doc, "h6"); len(got) != 1 || got[0] != "black-small-square-shells" {
		t.Errorf("FAIL: the Shells heading id changed: %v", got)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestGitHubSlugDeduplicatesRepeats(t *testing.T) {
	doc, out := ghRender(t, "## Foo_Bar!\n\n## Foo_Bar!\n\n## Foo_Bar!\n")

	var extra []string
	for _, a := range ghFind(doc, ghTag("a")) {
		if id := ghAttr(a, "id"); id != "" {
			extra = append(extra, id)
		}
	}
	want := []string{"foo_bar", "foo_bar-1", "foo_bar-2"}
	if strings.Join(extra, ",") != strings.Join(want, ",") {
		t.Errorf("FAIL: extra anchors %v, want %v: %s", extra, want, out)
	}
	if got := ghIDs(doc, "h3"); strings.Join(got, ",") != "foo-bar,foo-bar-1,foo-bar-2" {
		t.Errorf("FAIL: quarry's ids changed: %v", got)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestGitHubSlugAlgorithm(t *testing.T) {
	for in, want := range map[string]string{
		"CLI Tools [TOC]":           "cli-tools-toc",
		":anger: Table of Contents": "anger-table-of-contents",
		"  Hello,  World!":          "hello--world",
		"Café \U0001f525 déjà vu":   "café--déjà-vu",
		"snake_case-and-dash":       "snake_case-and-dash",
	} {
		if got := githubSlug(in); got != want {
			t.Errorf("FAIL: githubSlug(%q) = %q, want %q", in, got, want)
		}
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestRemoteImagesBecomeLinks(t *testing.T) {
	SetOrigin("")
	doc, out := ghRender(t, "![build status](https://ci.example/badge.svg?x=1)\n\n![](https://img.example/a/shot.png)\n\n"+
		"![local](/r/repo/badge.svg) ![rel](img/shot.png)\n\n"+
		`<p align="center"><a href="https://site.example/"><img src="https://img.example/logo.png" alt="logo"></a></p>`+"\n\n"+
		`<img src="https://raw.example/x.png" alt="raw html">`+"\n")

	var imgs []string
	for _, n := range ghFind(doc, ghTag("img")) {
		imgs = append(imgs, ghAttr(n, "src"))
	}
	if strings.Join(imgs, ",") != "/r/repo/badge.svg,img/shot.png" {
		t.Errorf("FAIL: remaining images %v, want only the same-origin ones: %s", imgs, out)
	}
	href := map[string]bool{}
	for _, a := range ghFind(doc, ghTag("a")) {
		href[ghAttr(a, "href")] = true
		// No anchor inside an anchor.
		if ghUnder(a, "a") {
			t.Errorf("FAIL: nested link to %q: %s", ghAttr(a, "href"), out)
		}
	}
	for _, want := range []string{"https://ci.example/badge.svg?x=1", "https://img.example/a/shot.png", "https://raw.example/x.png", "https://site.example/"} {
		if !href[want] {
			t.Errorf("FAIL: no link to %q: %s", want, out)
		}
	}
	if href["https://img.example/logo.png"] {
		t.Errorf("FAIL: an image inside a link was linked again: %s", out)
	}
	for _, a := range ghFind(doc, ghTag("a")) {
		if ghAttr(a, "href") == "https://img.example/a/shot.png" && (a.FirstChild == nil || a.FirstChild.Data != "shot.png") {
			t.Errorf("FAIL: an image with no alt is not labelled by its file name: %s", out)
		}
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestOwnOriginImagesStayImages(t *testing.T) {
	SetOrigin("https://forge.example/")
	t.Cleanup(func() { SetOrigin("") })
	doc, out := ghRender(t, "![own](https://forge.example/r/repo/badge.svg) ![other](https://forge.example.evil.test/x.png)\n")

	imgs := ghFind(doc, ghTag("img"))
	if len(imgs) != 1 || ghAttr(imgs[0], "src") != "https://forge.example/r/repo/badge.svg" {
		t.Errorf("FAIL: want exactly the forge's own image kept: %s", out)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestOutlineSkipsEmojiAndSup(t *testing.T) {
	_, out := ghRender(t, githubReadme)
	_, outline := Outline(out)

	if len(outline) != 4 {
		t.Fatalf("FAIL: outline has %d headings, want 4: %+v", len(outline), outline)
	}
	for _, h := range outline {
		if strings.ContainsAny(h.Text, ":[]") || strings.Contains(h.Text, " ") || h.Text != strings.TrimSpace(h.Text) {
			t.Errorf("FAIL: outline entry %q carries markup residue", h.Text)
		}
		for _, r := range h.Text {
			if r > 0x2000 {
				t.Errorf("FAIL: outline entry %q carries an emoji", h.Text)
			}
		}
	}
	if outline[1].Level != 5 || outline[1].ID != "cli-tools-suptocanger-table-of-contentssup" {
		t.Errorf("FAIL: level-4 chapter not reported as written: %+v", outline[1])
	}
	if !t.Failed() {
		t.Log("ok")
	}
}