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: 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)
}
}
// Non-breaking spaces fall out, as on GitHub: "cover: What" runs together.
for _, want := range []string{"cli-tools-toc", "notebook_with_decorative_coverwhat-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, "\n\n\n\n"+
" \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, " \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")
}
}
// anchorIDs lists the ids of the empty anchors in a document, and
// checks each sits directly before a heading.
func anchorIDs(t *testing.T, doc *xhtml.Node) []string {
t.Helper()
var got []string
for _, a := range ghFind(doc, func(n *xhtml.Node) bool {
return n.Data == "a" && n.Type == xhtml.ElementNode && ghAttr(n, "id") != "" && n.FirstChild == nil
}) {
got = append(got, ghAttr(a, "id"))
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", ghAttr(a, "id"))
}
}
return got
}
// A heading that opens with an emoji slugs to a leading hyphen; quarry's
// own id for it is refused by the sanitizer, so the GitHub anchor is the
// only one that works.
func TestGitHubAnchorForEmojiLedHeading(t *testing.T) {
doc, out := ghRender(t, "## \U0001f525 Fire\n\n## ✨ Features\n")
got := anchorIDs(t, doc)
for _, want := range []string{"-fire", "-features"} {
if !ghIn(got, want) {
t.Errorf("FAIL: no anchor %q among %v: %s", want, got, out)
}
}
if !t.Failed() {
t.Log("ok")
}
}
// Combining marks are part of a GitHub slug, and survive into the id.
func TestGitHubAnchorKeepsNonASCIIAndMarks(t *testing.T) {
doc, out := ghRender(t, "## हिन्दी भाषा\n\n## Café Noir\n")
got := anchorIDs(t, doc)
for _, want := range []string{githubSlug("हिन्दी भाषा"), "café-noir"} {
if !ghIn(got, want) {
t.Errorf("FAIL: no anchor %q among %q: %s", want, got, out)
}
}
if !t.Failed() {
t.Log("ok")
}
}
// The sanitizer's id rule for a document's own anchors is unchanged: the
// wide ids belong to the renderer alone.
func TestDocumentAnchorIDsStillStripped(t *testing.T) {
doc, out := ghRender(t, "<a id=\"__proto__\"></a><a id=\"-x\"></a><a id=\"été\"></a><a id=\"fine\"></a>\n\n## \\_\\_proto\\_\\_\n")
var got []string
for _, a := range ghFind(doc, ghTag("a")) {
if id := ghAttr(a, "id"); id != "" {
got = append(got, id)
}
}
if len(got) != 1 || got[0] != "fine" {
t.Errorf("FAIL: anchor ids %q, want only the one the old rule allows: %s", got, out)
}
if !t.Failed() {
t.Log("ok")
}
}
// A marker the document writes by hand is not an anchor.
func TestDocumentCannotForgeAnchorMarker(t *testing.T) {
doc, out := ghRender(t, "qgh0000000000000000:evil;\n\n## Real\n")
for _, a := range ghFind(doc, ghTag("a")) {
if ghAttr(a, "id") == "evil" {
t.Errorf("FAIL: a document minted an anchor: %s", out)
}
}
if !t.Failed() {
t.Log("ok")
}
}
func TestRemotePictureSourceDropped(t *testing.T) {
doc, out := ghRender(t, `<picture><source srcset="https://img.example/dark.png 1x, https://img.example/dark2.png 2x" media="(prefers-color-scheme: dark)"><source srcset="/local/a.png"><img src="https://img.example/light.png" alt="logo"></picture>`)
srcs := ghFind(doc, ghTag("source"))
if len(srcs) != 1 || ghAttr(srcs[0], "srcset") != "/local/a.png" {
t.Errorf("FAIL: want only the same-origin source kept: %s", out)
}
if n := len(ghFind(doc, ghTag("img"))); n != 0 {
t.Errorf("FAIL: remote img left in the picture: %s", out)
}
if !t.Failed() {
t.Log("ok")
}
}
// Only a <sup> that holds a link is navigation; plain superscript is
// part of the heading's name.
func TestOutlineKeepsPlainSup(t *testing.T) {
_, outline := Outline([]byte(`<h2 id="a">E = mc<sup>2</sup></h2><h2 id="b">Top <sup><a href="#x">[TOC]</a></sup></h2>`))
if len(outline) != 2 {
t.Fatalf("FAIL: outline = %+v", outline)
}
if !strings.Contains(outline[0].Text, "2") {
t.Errorf("FAIL: the superscript was dropped from %q", outline[0].Text)
}
if strings.ContainsAny(outline[1].Text, "[]") {
t.Errorf("FAIL: the link back to the top stayed in %q", outline[1].Text)
}
if !t.Failed() {
t.Log("ok")
}
}
// The README's own heading lines, byte for byte, get the anchors its own
// links name: GitHub drops a non-breaking space and hyphenates only a
// plain space.
func TestGitHubSlugsMatchTheREADMEsOwnLinks(t *testing.T) {
src := "## :notebook_with_decorative_cover: What is it?\n\n" +
"## :anger: Table of Contents\n\n" +
"#### CLI Tools [<sup>[TOC]</sup>](#anger-table-of-contents)\n\n" +
"##### Tool: [who](https://en.wikipedia.org/wiki/Who_(Unix))\n"
doc, out := ghRender(t, src)
ids := map[string]bool{}
ghWalk(doc, func(n *xhtml.Node) {
if id := ghAttr(n, "id"); id != "" {
ids[id] = true
}
})
for _, want := range []string{"notebook_with_decorative_cover-what-is-it", "anger-table-of-contents", "cli-tools-toc", "tool-who"} {
if !ids[want] {
t.Errorf("FAIL: no element with id %q, which the README links to: %s", want, out)
}
}
if !t.Failed() {
t.Log("ok")
}
}