Skip to content
quarry Artifact [a1e1cdc6c9]
Login

Artifact [a1e1cdc6c9]

Artifact a1e1cdc6c96a9c3413e0390eae9293f0ee44da86b342f8adff8f4a55a4377d14:


package markup

import (
	"regexp"
	"strings"
	"testing"
)

const emailSample = "> quoted *line*\n\n" +
	"| a | b |\n|---|--:|\n| 1 | 2 |\n\n" +
	"```go\nfmt.Println(1)\n```\n\n" +
	"![shot](https://cdn.example/x.png) and [rel](/r/alpha/wiki/Home) and [top](#top)\n\n" +
	"> [!WARNING]\n> careful\n"

func mailOf(t *testing.T, src string) string {
	t.Helper()
	got, ok := EmailHTML([]byte(src), nil, func(p string) string { return "https://forge.example" + p })
	if !ok {
		t.Fatal("EmailHTML fell back")
	}
	return string(got)
}

func TestEmailHTMLIsSelfContained(t *testing.T) {
	got := mailOf(t, emailSample)
	for _, banned := range []string{"<style", "<img", "<svg", "<script", "md-"} {
		if strings.Contains(got, banned) {
			t.Errorf("html carries %q", banned)
		}
	}
	for _, m := range regexp.MustCompile(`href="([^"]*)"`).FindAllStringSubmatch(got, -1) {
		if !strings.HasPrefix(m[1], "https://") {
			t.Errorf("non-absolute href %q", m[1])
		}
	}
	for _, want := range []string{
		`href="https://cdn.example/x.png"`,
		`href="https://forge.example/r/alpha/wiki/Home"`,
	} {
		if !strings.Contains(got, want) {
			t.Errorf("missing %s", want)
		}
	}
	for _, tag := range []string{"<blockquote style=", "<table style=", "<th style=", "<td style=", "<pre style=", "<code style=", "<p style=", "<a style="} {
		if !regexp.MustCompile(strings.Replace(tag, " style=", `[^>]* style=`, 1)).MatchString(got) {
			t.Errorf("no inline style on %s", tag)
		}
	}
}

func TestEmailHTMLFallsBackOverTheCap(t *testing.T) {
	big := strings.Repeat("word ", EmailHTMLMax/4)
	if _, ok := EmailHTML([]byte(big), nil, func(p string) string { return p }); ok {
		t.Fatal("oversized html was kept")
	}
}

func TestEmailHTMLKeepsTypographicPunctuation(t *testing.T) {
	const want = "\u201cseen, empty\u201d \u2018x\u2019 a \u2014 b \u2013 c \u2026 \u2192"
	got := mailOf(t, "record "+want+" now")
	if !strings.Contains(got, want) {
		t.Errorf("punctuation changed: %s", got)
	}
}