Skip to content
quarry Artifact [faa4c731ac]
Login

Artifact [faa4c731ac]

Artifact faa4c731acd6748813ec3731b50c59eb15f697e7159a19e2cb18ece4c47c1688:


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 },
		"https://forge.example/r/alpha/chat/7")
	if !ok {
		t.Fatal("EmailHTML fell back")
	}
	return got
}

func TestEmailHTMLIsSelfContained(t *testing.T) {
	got := mailOf(t, emailSample)
	for _, banned := range []string{"<style", "<img", "<svg", "<script", ` class=`} {
		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"`,
		`href="https://forge.example/r/alpha/chat/7"`,
	} {
		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 !strings.Contains(got, tag) {
			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 }, "https://x/y"); ok {
		t.Fatal("oversized html was kept")
	}
}