Files
summercms/modules/postcard/layouts_test.go
Jakub Zych a0dde086d2 test(postcard): locale fallback, built-in layouts, partials and CSS inlining
- TestTemplateBase, TestTemplateFor and TestSendLocaleFallback pin the
  <template>-<locale> resolution and the order the override source is asked
- TestEnsureLocaleRows (Postgres): rows only for non-default locales without
  files, idempotent, customized content kept while file_hash follows the
  base, base_code from SyncIndex, reset of a fallback row, migrations roll back
- TestBuiltinLayoutsLogo, TestHeaderFooterPartials, TestButtonPartial and
  TestSiteName cover the finished default, system and minimal layouts
- TestInlineCSS, TestInlineCSSOptOut and TestInlineFailure cover inlining,
  the per-layout opt-out and the fallback when the inliner fails
- check-phase35.sh requires the new names (GO_TESTS, DOCKER_TESTS)
2026-11-13 21:31:44 +01:00

394 lines
14 KiB
Go

package postcard
import (
"regexp"
"strings"
"testing"
"testing/fstest"
)
// htmlTag is one opening tag of rendered HTML. Inlining re-serialises the
// HTML (attribute order, added style attributes), so tests read tags by
// attribute instead of comparing markup.
type htmlTag struct {
name string
attrs map[string]string
start, end int // the tag's byte range in the HTML
}
var (
openTagRe = regexp.MustCompile(`<([a-zA-Z][a-zA-Z0-9]*)(\s[^>]*)?>`)
tagAttrRe = regexp.MustCompile(`([a-zA-Z_:][-a-zA-Z0-9_:.]*)\s*=\s*"([^"]*)"`)
)
// htmlTags returns the opening tags called name, in document order.
func htmlTags(html, name string) []htmlTag {
var out []htmlTag
for _, m := range openTagRe.FindAllStringSubmatchIndex(html, -1) {
if !strings.EqualFold(html[m[2]:m[3]], name) {
continue
}
tag := htmlTag{name: name, attrs: map[string]string{}, start: m[0], end: m[1]}
if m[4] >= 0 {
for _, a := range tagAttrRe.FindAllStringSubmatch(html[m[4]:m[5]], -1) {
tag.attrs[strings.ToLower(a[1])] = a[2]
}
}
out = append(out, tag)
}
return out
}
func (h htmlTag) hasClass(class string) bool {
for _, c := range strings.Fields(h.attrs["class"]) {
if c == class {
return true
}
}
return false
}
// withClass returns the tags called name that carry class.
func withClass(html, name, class string) []htmlTag {
var out []htmlTag
for _, tag := range htmlTags(html, name) {
if tag.hasClass(class) {
out = append(out, tag)
}
}
return out
}
// headerCell returns the content of the built-in header partial's cell, and
// whether there is one.
func headerCell(html string) (string, bool) {
cells := withClass(html, "td", "header")
if len(cells) == 0 {
return "", false
}
rest := html[cells[0].end:]
content, _, _ := strings.Cut(rest, "</td>")
return content, true
}
var logoSpan = regexp.MustCompile(`<span[^>]*>([^<]*)</span>`)
const testLogo = "https://cdn.example.com/logo.png"
// builtinLayoutCases are the blog fixture's templates on the three built-in
// layouts, with a text the message body starts with.
var builtinLayoutCases = []struct {
layout, template, content string
header bool
}{
{"default", "acme.blog::mail.welcome", "Hi Ada", true},
{"system", "acme.blog::mail.auto", "Done.", true},
{"minimal", "acme.blog::mail.bare", "Done.", false},
}
// brandedSend sends template through the blog fixture with brand (nil: no
// override source) and mail.from from.
func brandedSend(t *testing.T, brand *Brand, from, template string) RenderedMessage {
t.Helper()
var ov *Overrides
if brand != nil {
ov = &Overrides{Brand: brand}
}
m, drv := partialsMailer(t, Options{From: from}, ov)
return sendTemplate(t, m, drv, template, map[string]any{"Name": "Ada", "Link": "https://example.com/go"})
}
func TestBuiltinLayoutsLogo(t *testing.T) {
t.Parallel()
brands := []struct {
name string
brand *Brand
from string
logo bool
alt string
title string // the site name the header shows without a logo
}{
{name: "logo_and_name", brand: &Brand{LogoURL: testLogo, SiteName: "Acme Mail"}, logo: true, alt: "Acme Mail"},
{name: "logo_only", brand: &Brand{LogoURL: testLogo}, from: "shop@example.com", logo: true, alt: ""},
{name: "name_only", brand: &Brand{SiteName: "Acme Mail"}, title: "Acme Mail"},
{name: "neither", brand: &Brand{}, from: "shop@example.com"},
{name: "no_branding", from: "shop@example.com"},
}
for _, b := range brands {
for _, l := range builtinLayoutCases {
t.Run(b.name+"/"+l.layout, func(t *testing.T) {
msg := brandedSend(t, b.brand, b.from, l.template)
html := msg.HTML
logos := withClass(html, "img", "logo")
cell, hasHeader := headerCell(html)
switch {
case b.logo:
if len(logos) != 1 {
t.Fatalf("%d logo images, want 1:\n%s", len(logos), html)
}
img := logos[0]
if img.attrs["src"] != testLogo {
t.Errorf("logo src = %q, want %q", img.attrs["src"], testLogo)
}
if alt, ok := img.attrs["alt"]; !ok || alt != b.alt {
t.Errorf("logo alt = %q (present %v), want %q", alt, ok, b.alt)
}
if l.header {
// In the header cell of the default and system layouts.
if !hasHeader || !strings.Contains(cell, `src="`+testLogo+`"`) {
t.Errorf("the logo is not in the header cell:\n%s", html)
}
} else {
// Above the message in the minimal layout, which has no header.
if hasHeader {
t.Errorf("the minimal layout has a header cell:\n%s", html)
}
if at := strings.Index(html, l.content); at < 0 || img.start > at {
t.Errorf("the logo is not above the message:\n%s", html)
}
}
default:
if len(logos) != 0 {
t.Errorf("a logo image without a Branding logo:\n%s", html)
}
}
switch {
case !l.header:
if hasHeader {
t.Errorf("the minimal layout has a header cell:\n%s", html)
}
case b.title != "":
m := logoSpan.FindStringSubmatch(cell)
if !hasHeader || m == nil || m[1] != b.title {
t.Errorf("the header does not show the site name %q:\n%s", b.title, html)
}
case !b.logo:
if hasHeader {
t.Errorf("a header row without a logo or a site name:\n%s", html)
}
}
})
}
}
}
// partialsFixture is a plugin whose templates call the header and footer
// partials directly, in a layout without CSS (nothing is inlined).
func partialsFixture(t *testing.T) (Mailer, *MemoryDriver) {
t.Helper()
fsys := fstest.MapFS{
"views/mail/layouts/plain.htm": {Data: []byte("name = \"Plain\"\n==\n{{ .Content }}\n==\n<table class=\"plain\">{{ .Content }}</table>\n")},
"views/mail/header.htm": {Data: []byte("subject = \"Header\"\nlayout = \"plain\"\n==\n{{ partial \"header\" \"logo\" .logo \"body\" .name \"url\" .url }}\n")},
"views/mail/footer.htm": {Data: []byte("subject = \"Footer\"\nlayout = \"plain\"\n==\n{{ partial \"footer\" \"body\" .body }}\n")},
}
cat := NewCatalog()
if err := cat.Register("acme.parts", fsys, []string{"acme.parts::mail.header", "acme.parts::mail.footer"}, map[string]string{"plain": "acme.parts::mail.layouts.plain"}); err != nil {
t.Fatal(err)
}
drv := NewMemoryDriver()
return NewMailer(cat, drv, Options{}), drv
}
var footerPara = regexp.MustCompile(`<p[^>]*>([^<]*)</p>`)
// footerText returns the paragraph of the footer partial's table.
func footerText(t *testing.T, html string) string {
t.Helper()
tables := withClass(html, "table", "footer")
if len(tables) != 1 {
t.Fatalf("%d footer tables, want 1:\n%s", len(tables), html)
}
cells := withClass(html[tables[0].end:], "td", "content-cell")
if len(cells) == 0 {
t.Fatalf("no content cell in the footer:\n%s", html)
}
m := footerPara.FindStringSubmatch(html[tables[0].end+cells[0].end:])
if m == nil {
t.Fatalf("no paragraph in the footer:\n%s", html)
}
return m[1]
}
func TestHeaderFooterPartials(t *testing.T) {
t.Parallel()
m, drv := partialsFixture(t)
header := []struct {
name, logo, url string
wantImg, wantA bool
}{
{name: "logo", logo: testLogo, wantImg: true},
{name: "name_only"},
{name: "url_with_logo", logo: testLogo, url: "https://acme.example/", wantImg: true, wantA: true},
{name: "url_with_name", url: "https://acme.example/", wantA: true},
}
for _, tc := range header {
t.Run("header/"+tc.name, func(t *testing.T) {
msg := sendTemplate(t, m, drv, "acme.parts::mail.header", map[string]any{"logo": tc.logo, "name": "Acme Mail", "url": tc.url})
cell, ok := headerCell(msg.HTML)
if !ok || !strings.Contains(msg.HTML, "<tr>") {
t.Fatalf("no header row:\n%s", msg.HTML)
}
imgs := htmlTags(cell, "img")
if tc.wantImg {
if len(imgs) != 1 || imgs[0].attrs["src"] != tc.logo || imgs[0].attrs["alt"] != "Acme Mail" || !imgs[0].hasClass("logo") {
t.Errorf("header image = %+v, want img.logo src %s alt Acme Mail:\n%s", imgs, tc.logo, cell)
}
if strings.Contains(cell, "<span") {
t.Errorf("a span next to the logo:\n%s", cell)
}
} else {
if len(imgs) != 0 {
t.Errorf("an image without a logo:\n%s", cell)
}
if !strings.Contains(cell, "Acme Mail") {
t.Errorf("the header does not show the name:\n%s", cell)
}
}
links := htmlTags(cell, "a")
if tc.wantA {
if len(links) != 1 || links[0].attrs["href"] != tc.url {
t.Fatalf("header link = %+v, want href %s:\n%s", links, tc.url, cell)
}
// The link wraps the logo or the name.
inner, _, _ := strings.Cut(cell[links[0].end:], "</a>")
if tc.wantImg && !strings.Contains(inner, "<img") || !tc.wantImg && inner != "Acme Mail" {
t.Errorf("the link does not wrap the content: %q", inner)
}
} else {
if len(links) != 0 {
t.Errorf("a link without a url:\n%s", cell)
}
if !tc.wantImg && !strings.Contains(cell, "<span>Acme Mail</span>") {
t.Errorf("the name is not in a span:\n%s", cell)
}
}
if strings.TrimSpace(msg.Text) != "Acme Mail" {
t.Errorf("header text = %q, want the name", msg.Text)
}
})
}
for _, body := range []string{"© 2031 Acme Mail", "© 2031"} {
t.Run("footer/"+body, func(t *testing.T) {
msg := sendTemplate(t, m, drv, "acme.parts::mail.footer", map[string]any{"body": body})
if got := footerText(t, msg.HTML); got != body {
t.Errorf("footer paragraph = %q, want %q", got, body)
}
if want := "-------------------\n" + body; strings.TrimSpace(msg.Text) != want {
t.Errorf("footer text = %q, want %q", msg.Text, want)
}
})
}
// The built-in layouts fill the footer with © year and the site name.
for _, l := range builtinLayoutCases[:2] {
for _, name := range []string{"Acme Mail", ""} {
t.Run("layout/"+l.layout+"/"+name, func(t *testing.T) {
msg := brandedSend(t, &Brand{SiteName: name}, "", l.template)
want := strings.TrimSpace(copyright() + " " + name)
if got := footerText(t, msg.HTML); got != want {
t.Errorf("footer = %q, want %q", got, want)
}
if !strings.HasSuffix(strings.TrimRight(msg.Text, "\n"), "-------------------\n"+want) {
t.Errorf("text part does not end with the footer %q:\n%s", want, msg.Text)
}
})
}
}
}
func TestButtonPartial(t *testing.T) {
t.Parallel()
const url = "https://example.com/activate?code=a1"
body := "Before.\n\n" +
"{{ partial \"button\" \"url\" .url \"body\" \"Go\" }}\n\n" +
"{{ partial \"button\" \"url\" .url \"body\" \"Yes\" \"type\" \"positive\" }}\n\n" +
"{{ partial \"button\" \"url\" .url \"body\" \"No\" \"type\" \"negative\" }}\n\nAfter.\n"
fsys := fstest.MapFS{}
for _, layout := range []string{"default", "system", "minimal"} {
fsys["views/mail/action_"+layout+".htm"] = &fstest.MapFile{Data: []byte("subject = \"Action\"\nlayout = \"" + layout + "\"\n==\n" + body)}
}
cat := NewCatalog()
names := []string{"acme.act::mail.action_default", "acme.act::mail.action_system", "acme.act::mail.action_minimal"}
if err := cat.Register("acme.act", fsys, names, nil); err != nil {
t.Fatal(err)
}
drv := NewMemoryDriver()
m := NewMailer(cat, drv, Options{})
want := []struct{ text, class string }{
{"Go", "button button-primary"},
{"Yes", "button button-positive"},
{"No", "button button-negative"},
}
for _, name := range names {
t.Run(name, func(t *testing.T) {
msg := sendTemplate(t, m, drv, name, map[string]any{"url": url})
var buttons []htmlTag
for _, a := range htmlTags(msg.HTML, "a") {
if a.hasClass("button") {
buttons = append(buttons, a)
}
}
if len(buttons) != len(want) {
t.Fatalf("%d buttons, want %d:\n%s", len(buttons), len(want), msg.HTML)
}
for i, w := range want {
b := buttons[i]
if b.attrs["class"] != w.class {
t.Errorf("button %d class = %q, want %q", i, b.attrs["class"], w.class)
}
// html/template escapes the query's = sign in the href.
if href := strings.ReplaceAll(b.attrs["href"], "&#61;", "="); href != url {
t.Errorf("button %d href = %q, want %q", i, b.attrs["href"], url)
}
if label, _, _ := strings.Cut(msg.HTML[b.end:], "</a>"); label != w.text {
t.Errorf("button %d label = %q, want %q", i, label, w.text)
}
if line := w.text + " <" + url + ">"; !strings.Contains(msg.Text, line) {
t.Errorf("text part lacks %q:\n%s", line, msg.Text)
}
}
if strings.Contains(msg.Text, "<a ") || strings.Contains(msg.Text, "MAILPARTIAL") {
t.Errorf("text part holds HTML or a partial token:\n%s", msg.Text)
}
if !strings.Contains(msg.Text, "Before.") || !strings.Contains(msg.Text, "After.") {
t.Errorf("text part lost the body:\n%s", msg.Text)
}
})
}
}
func TestSiteName(t *testing.T) {
t.Parallel()
cases := []struct {
name string
brand *Brand
from string
want string
}{
{"branding_wins", &Brand{SiteName: " Acme Mail "}, "Acme Shop <shop@example.com>", "Acme Mail"},
{"empty_uses_from", &Brand{}, "Acme Shop <shop@example.com>", "Acme Shop"},
{"blank_uses_from", &Brand{SiteName: " "}, `"Acme Shop" <shop@example.com>`, "Acme Shop"},
{"no_branding_uses_from", nil, "Acme Shop <shop@example.com>", "Acme Shop"},
{"from_without_name", nil, "shop@example.com", ""},
{"from_unparsable", &Brand{}, "not an address", ""},
{"from_empty", nil, "", ""},
}
for _, tc := range cases {
if got := siteName(tc.brand, tc.from); got != tc.want {
t.Errorf("%s: siteName(%+v, %q) = %q, want %q", tc.name, tc.brand, tc.from, got, tc.want)
}
}
// The mail.from fallback reaches the header and the footer of a send.
msg := brandedSend(t, nil, "Acme Shop <shop@example.com>", "acme.blog::mail.welcome")
cell, ok := headerCell(msg.HTML)
if m := logoSpan.FindStringSubmatch(cell); !ok || m == nil || m[1] != "Acme Shop" {
t.Errorf("header does not show the mail.from name:\n%s", msg.HTML)
}
if got := footerText(t, msg.HTML); got != copyright()+" Acme Shop" {
t.Errorf("footer = %q, want %q", got, copyright()+" Acme Shop")
}
}