Files
summercms/modules/postcard/partials_smoke_test.go
Jakub Zych 09a5338d9a feat(postcard): header, logo, footer and padding in the system and minimal layouts
- system.htm: the header partial (logo or site name) above the card and
  the copyright footer below it; its text wrapper ends with the footer
- brand CSS: the system layout's content cell keeps WinterCMS's 35px
  side padding (the 35px 0 override is gone)
- minimal.htm: the logo above the message when logoUrl is set
- TestMailPartialsSmoke/built_in_layouts covers the three layouts and the
  inlined brand colour on the button in each
- 35-06 Task 3 (G-35-8)
2026-11-13 21:17:02 +01:00

639 lines
29 KiB
Go

package postcard
import (
"bytes"
"context"
"errors"
"io/fs"
"log/slog"
"regexp"
"strconv"
"strings"
"testing"
"testing/fstest"
"time"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/pact"
)
// partialsPlugin is a fixture plugin that ships only mail partials.
type partialsPlugin struct {
id string
fsys fs.FS
partials []string
}
func (p partialsPlugin) ID() string { return p.id }
func (p partialsPlugin) MailPartialsFS() fs.FS { return p.fsys }
func (p partialsPlugin) MailPartials() []string { return p.partials }
// mailPlugin is a fixture plugin that ships templates and, optionally,
// partials.
type mailPlugin struct {
partialsPlugin
templates []string
layouts map[string]string
}
func (p mailPlugin) MailTemplatesFS() fs.FS { return p.fsys }
func (p mailPlugin) MailTemplates() []string { return p.templates }
func (p mailPlugin) MailLayouts() map[string]string { return p.layouts }
// templatesOnly hides the partial capability of a mailPlugin.
type templatesOnly struct{ p mailPlugin }
func (t templatesOnly) ID() string { return t.p.id }
func (t templatesOnly) MailTemplatesFS() fs.FS { return t.p.fsys }
func (t templatesOnly) MailTemplates() []string { return t.p.templates }
func (t templatesOnly) MailLayouts() map[string]string { return t.p.layouts }
var (
_ pact.HasMailPartials = partialsPlugin{}
_ pact.HasMailPartials = mailPlugin{}
_ pact.HasMailTemplates = mailPlugin{}
_ pact.HasMailTemplates = templatesOnly{}
)
// buttonTag finds the opening tag of the button partial's link.
var buttonTag = regexp.MustCompile(`<a [^>]*button-primary[^>]*>`)
// buttonStyle returns the style attribute of the button partial's link, or
// empty when it has none.
func buttonStyle(t *testing.T, html string) string {
t.Helper()
tag := buttonTag.FindString(html)
if tag == "" {
t.Fatalf("no button in %s", html)
}
_, style, ok := strings.Cut(tag, ` style="`)
if !ok {
return ""
}
style, _, _ = strings.Cut(style, `"`)
return style
}
// copyright is the footer line of the built-in layouts without a site name.
func copyright() string { return "© " + strconv.Itoa(time.Now().Year()) }
// fakeOverrides is an OverrideSource with a fixed answer.
type fakeOverrides struct{ ov Overrides }
func (f fakeOverrides) MailOverrides(context.Context, string) (Overrides, error) { return f.ov, nil }
const noteHTM = `name = "Note"
==
NOTE: {{ .text }}
==
<div class="note">{{ .text }}</div>
`
func partialsFS() fstest.MapFS {
return fstest.MapFS{
"views/mail/welcome.htm": {Data: []byte("subject = \"Welcome\"\n==\nHi {{ .Name }}\n\n{{ partial \"button\" \"url\" .Link \"body\" \"Go\" }}\n\nBye\n")},
"views/mail/note.htm": {Data: []byte("subject = \"Note\"\nlayout = \"blog\"\n==\n{{ partial \"acme.blog::mail.partials.note\" \"text\" .Text }}\n")},
"views/mail/auto.htm": {Data: []byte("subject = \"Auto\"\nlayout = \"system\"\n==\nDone.\n")},
"views/mail/bare.htm": {Data: []byte("subject = \"Bare\"\nlayout = \"minimal\"\n==\nDone.\n")},
"views/mail/layouts/blog.htm": {Data: []byte(`name = "Blog"
==
{{ .Content }}
{{ partial "acme.blog::mail.partials.note" "text" "footer" }}
==
<div class="blog-mail">{{ .Content }}{{ partial "acme.blog::mail.partials.note" "text" "footer" }}</div>
<style>{{ .brandCss }}{{ .css }}</style>
`)},
"views/mail/partials/note.htm": {Data: []byte(noteHTM)},
}
}
func blogPlugin() mailPlugin {
return mailPlugin{
partialsPlugin: partialsPlugin{id: "acme.blog", fsys: partialsFS(), partials: []string{"acme.blog::mail.partials.note"}},
templates: []string{"acme.blog::mail.welcome", "acme.blog::mail.note", "acme.blog::mail.auto", "acme.blog::mail.bare"},
layouts: map[string]string{"blog": "acme.blog::mail.layouts.blog"},
}
}
// partialsMailer registers the blog fixture in a fresh catalog and returns a
// mailer over it with the given overrides.
func partialsMailer(t *testing.T, opts Options, ov *Overrides) (Mailer, *MemoryDriver) {
t.Helper()
p := blogPlugin()
cat := NewCatalog()
if err := cat.RegisterPartials(p.id, p.fsys, p.partials); err != nil {
t.Fatalf("RegisterPartials: %v", err)
}
if err := cat.Register(p.id, p.fsys, p.templates, p.layouts); err != nil {
t.Fatalf("Register: %v", err)
}
if ov != nil {
opts.Overrides = fakeOverrides{ov: *ov}
}
drv := NewMemoryDriver()
return NewMailer(cat, drv, opts), drv
}
func sendTemplate(t *testing.T, m Mailer, drv *MemoryDriver, name string, vars map[string]any) RenderedMessage {
t.Helper()
if err := m.Send(context.Background(), Message{Template: name, To: []string{"ada@example.com"}, Vars: vars}); err != nil {
t.Fatalf("Send %s: %v", name, err)
}
return lastMessage(t, drv)
}
func bootPartials[P interface{ ID() string }](t *testing.T, plugins ...P) (*backpack.App, error) {
t.Helper()
app := backpack.New(nil)
if err := Activate(app, plugins); err != nil {
t.Fatalf("Activate: %v", err)
}
for _, p := range plugins {
if err := BootPlugin(app, p); err != nil {
return app, err
}
}
return app, nil
}
// TestMailPartialsSmoke covers mail partials end to end without a database:
// the pact capability and its boot errors, partial calls in Markdown bodies
// and in layouts, the built-in layouts, and layout and partial overrides
// from an OverrideSource.
func TestMailPartialsSmoke(t *testing.T) {
t.Parallel()
t.Run("capability", func(t *testing.T) {
if _, err := bootPartials(t, blogPlugin()); err != nil {
t.Fatalf("a plugin with templates and a partial does not boot: %v", err)
}
fsys := partialsFS()
cases := []struct {
name string
partials []string
want []string
}{
{"foreign namespace", []string{"acme.other::mail.partials.note"}, []string{"not owned", "acme.other::mail.partials.note"}},
{"outside mail.partials", []string{"acme.blog::mail.note"}, []string{"acme.blog::mail.note", "mail.partials."}},
{"missing file", []string{"acme.blog::mail.partials.gone"}, []string{"missing partial acme.blog::mail.partials.gone"}},
{"duplicate", []string{"acme.blog::mail.partials.note", "acme.blog::mail.partials.note"}, []string{"duplicate partial acme.blog::mail.partials.note"}},
{"path escape", []string{"acme.blog::mail.partials.a/../b"}, []string{"invalid mail name"}},
}
for _, tc := range cases {
_, err := bootPartials(t, partialsPlugin{id: "acme.blog", fsys: fsys, partials: tc.partials})
if err == nil {
t.Errorf("%s: BootPlugin succeeded", tc.name)
continue
}
for _, want := range tc.want {
if !strings.Contains(err.Error(), want) {
t.Errorf("%s: error %q lacks %q", tc.name, err, want)
}
}
}
// The built-in names cannot be taken by a plugin.
if err := NewCatalog().RegisterPartials("postcard", fsys, []string{"postcard::mail.partials.button"}); err == nil || !strings.Contains(err.Error(), "duplicate partial") {
t.Errorf("re-registering a built-in partial = %v", err)
}
})
t.Run("partials_only_plugin", func(t *testing.T) {
// acme.kit ships only a partial; acme.blog's template calls it.
kit := partialsPlugin{id: "acme.kit", partials: []string{"acme.kit::mail.partials.badge"}, fsys: fstest.MapFS{
"views/mail/partials/badge.htm": {Data: []byte("name = \"Badge\"\n==\n[{{ .label }}]\n==\n<span class=\"badge\">{{ .label }}</span>\n")},
}}
blog := mailPlugin{
partialsPlugin: partialsPlugin{id: "acme.blog", fsys: fstest.MapFS{
"views/mail/hello.htm": {Data: []byte("subject = \"Hello\"\n==\nNew: {{ partial \"acme.kit::mail.partials.badge\" \"label\" \"beta\" }}\n")},
}},
templates: []string{"acme.blog::mail.hello"},
}
app := backpack.New(nil)
if err := Activate(app, []partialsPlugin{kit}); err != nil {
t.Fatal(err)
}
if err := BootPlugin(app, kit); err != nil {
t.Fatalf("a plugin with only partials does not boot: %v", err)
}
// blog implements both capabilities but declares no partial.
if err := BootPlugin(app, blog); err != nil {
t.Fatalf("BootPlugin blog: %v", err)
}
// A plugin with only templates still boots.
if _, err := bootPartials(t, templatesOnly{p: blog}); err != nil {
t.Fatalf("a plugin with only templates does not boot: %v", err)
}
got, _ := app.Lookup[Mailer]()
m := got.(*mailer)
msg := sendTemplate(t, m, m.driver.(*MemoryDriver), "acme.blog::mail.hello", nil)
if !strings.Contains(msg.HTML, `<p>New: <span class="badge">beta</span></p>`) {
t.Errorf("HTML = %q, want the other plugin's partial inline", msg.HTML)
}
if !strings.Contains(msg.Text, "New: [beta]") {
t.Errorf("text = %q", msg.Text)
}
})
t.Run("body", func(t *testing.T) {
m, drv := partialsMailer(t, Options{}, nil)
msg := sendTemplate(t, m, drv, "acme.blog::mail.welcome", map[string]any{"Name": "Ada", "Link": "https://example.com/go?a=1&b=2"})
if strings.Contains(msg.HTML, "raw HTML omitted") {
t.Errorf("the partial was dropped by Markdown:\n%s", msg.HTML)
}
for _, want := range []string{
"<p>Hi Ada</p>\n<table class=\"action\"",
`<a class="button button-primary" href="https://example.com/go?a=1&amp;b=2" target="_blank">Go</a>`,
"</table>\n<p>Bye</p>",
} {
if !strings.Contains(msg.HTML, want) {
t.Errorf("HTML lacks %q:\n%s", want, msg.HTML)
}
}
if strings.Contains(msg.HTML, "MAILPARTIAL") || strings.Contains(msg.Text, "MAILPARTIAL") {
t.Errorf("a token was left in the message:\n%s\n%s", msg.HTML, msg.Text)
}
if msg.Text != "Hi Ada\n\nGo <https://example.com/go?a=1&b=2>\n\nBye\n\n-------------------\n"+copyright() {
t.Errorf("text = %q", msg.Text)
}
// The type argument picks the button class.
cat := NewCatalog()
fsys := fstest.MapFS{"views/mail/b.htm": {Data: []byte("subject = \"B\"\n==\n{{ partial \"button\" \"url\" \"https://example.com\" \"body\" \"Pay\" \"type\" \"positive\" }}\n\n{{ partial \"panel\" \"body\" \"Keep **this**.\" }}\n\n{{ partial \"table\" \"body\" .Table }}\n\n{{ partial \"subcopy\" \"body\" \"Small print.\" }}\n")}}
if err := cat.Register("acme.blog", fsys, []string{"acme.blog::mail.b"}, nil); err != nil {
t.Fatal(err)
}
drv2 := NewMemoryDriver()
msg = sendTemplate(t, NewMailer(cat, drv2, Options{}), drv2, "acme.blog::mail.b", map[string]any{"Table": "| Item | Qty |\n|---|---|\n| Pen | 2 |"})
for _, want := range []string{
`class="button button-positive"`,
`<table class="panel`, "<p>Keep <strong>this</strong>.</p>",
`<div class="table">`, "<th>Item</th>", "<td>Pen</td>",
`<table class="subcopy"`, "<p>Small print.</p>",
} {
if !strings.Contains(msg.HTML, want) {
t.Errorf("built-in partials: HTML lacks %q:\n%s", want, msg.HTML)
}
}
for _, want := range []string{"Pay <https://example.com>", "Keep **this**.", "| Pen | 2 |", "-----\nSmall print."} {
if !strings.Contains(msg.Text, want) {
t.Errorf("built-in partials: text lacks %q:\n%s", want, msg.Text)
}
}
})
t.Run("forged_token", func(t *testing.T) {
m, drv := partialsMailer(t, Options{}, nil)
forged := "MAILPARTIAL1 MAILPARTIAL" + strings.Repeat("0", 32) + "X1X"
msg := sendTemplate(t, m, drv, "acme.blog::mail.welcome", map[string]any{"Name": forged, "Link": "https://example.com"})
if !strings.Contains(msg.HTML, "<p>Hi "+forged+"</p>") {
t.Errorf("a forged token in a variable was not left as text:\n%s", msg.HTML)
}
if n := strings.Count(msg.HTML, `class="button`); n != 1 {
t.Errorf("%d buttons rendered, want 1:\n%s", n, msg.HTML)
}
if !strings.Contains(msg.Text, "Hi "+forged) {
t.Errorf("text = %q", msg.Text)
}
// Tokens carry a fresh random nonce per render.
a, b := newPartialRun(NewCatalog(), nil), newPartialRun(NewCatalog(), nil)
ta, err := a.bodyCall("button", "url", "https://example.com", "body", "Go")
if err != nil {
t.Fatal(err)
}
tb, err := b.bodyCall("button", "url", "https://example.com", "body", "Go")
if err != nil {
t.Fatal(err)
}
if ta == tb {
t.Errorf("two renders produced the same token %q", ta)
}
for _, tok := range []string{ta, tb} {
if !strings.HasPrefix(tok, "MAILPARTIAL") || len(tok) < len("MAILPARTIAL")+32 || strings.Trim(tok, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") != "" {
t.Errorf("token %q is not MAILPARTIAL plus an alphanumeric nonce", tok)
}
}
})
t.Run("errors", func(t *testing.T) {
cases := map[string]struct {
body string
want []string
}{
"unknown": {`{{ partial "nope" "a" "b" }}`, []string{"unknown partial", "postcard::mail.partials.nope"}},
"unknown_ns": {`{{ partial "acme.blog::mail.partials.nope" }}`, []string{"unknown partial", "acme.blog::mail.partials.nope"}},
"odd": {`{{ partial "button" "url" }}`, []string{"postcard::mail.partials.button", "key and a value"}},
"key_type": {`{{ partial "button" 1 "x" }}`, []string{"postcard::mail.partials.button", "not a string"}},
"unsafe_html": {`{{ partial "panel" "body" "Type javascript: here" }}`, []string{"dangerous"}},
}
for name, tc := range cases {
cat := NewCatalog()
fsys := fstest.MapFS{"views/mail/x.htm": {Data: []byte("subject = \"X\"\n==\n" + tc.body + "\n")}}
if err := cat.Register("acme.blog", fsys, []string{"acme.blog::mail.x"}, nil); err != nil {
t.Fatalf("%s: Register: %v", name, err)
}
drv := NewMemoryDriver()
err := NewMailer(cat, drv, Options{}).Send(context.Background(), Message{Template: "acme.blog::mail.x", To: []string{"ada@example.com"}})
if err == nil {
t.Errorf("%s: Send succeeded", name)
continue
}
for _, want := range tc.want {
if !strings.Contains(err.Error(), want) {
t.Errorf("%s: error %q lacks %q", name, err, want)
}
}
if len(drv.Messages()) != 0 {
t.Errorf("%s: a message was sent", name)
}
}
// partial is not available inside a partial.
nested := fstest.MapFS{"views/mail/partials/outer.htm": {Data: []byte("name = \"Outer\"\n==\nx\n==\n{{ partial \"button\" }}\n")}}
cat := NewCatalog()
if err := cat.RegisterPartials("acme.blog", nested, []string{"acme.blog::mail.partials.outer"}); err != nil {
t.Fatal(err)
}
if _, err := newPartialRun(cat, nil).htmlCall("acme.blog::mail.partials.outer"); err == nil || !strings.Contains(err.Error(), `function "partial" not defined`) {
t.Errorf("a partial calling partial = %v", err)
}
})
t.Run("built_in_layouts", func(t *testing.T) {
const logo = "https://cdn.example.com/u/logo.png"
header := "<td class=\"header\">\n<img src=\"" + logo + "\" class=\"logo\" alt=\"Acme Mail\"/>"
// The system layout with a logo: the header above the card, the
// card with the subcopy, the footer below, and the content cell's
// side padding.
m, drv := partialsMailer(t, Options{CSS: "p{color:red}"}, &Overrides{Brand: &Brand{LogoURL: logo, SiteName: "Acme Mail"}})
msg := sendTemplate(t, m, drv, "acme.blog::mail.auto", nil)
html := unstyled(msg.HTML)
for _, want := range []string{
`class="wrapper layout-system"`, header, "<p>Done.</p>",
`<table class="subcopy"`, "<strong>This is an automatic message. Please do not reply to it.</strong>",
`<table class="footer"`, "<p>" + copyright() + " Acme Mail</p>",
} {
if !strings.Contains(html, want) {
t.Errorf("system layout: HTML lacks %q:\n%s", want, html)
}
}
if h, card, foot := strings.Index(html, `class="header"`), strings.Index(html, `class="inner-body"`), strings.Index(html, `class="footer"`); h > card || card > foot {
t.Errorf("system layout: header %d, card %d, footer %d are out of order", h, card, foot)
}
// mail.css is inlined onto the paragraph, after the brand CSS.
if !regexp.MustCompile(`<p style="[^"]*;color:red[;"][^>]*>Done\.</p>`).MatchString(msg.HTML) {
t.Errorf("system layout: mail.css is not inlined:\n%s", msg.HTML)
}
if !strings.Contains(msg.HTML, `<td class="content-cell" style="padding:35px">`) || strings.Contains(msg.HTML, "padding:35px 0") {
t.Errorf("system layout: the content cell lost its side padding:\n%s", msg.HTML)
}
if msg.Text != "Done.\n\n\n---\nThis is an automatic message. Please do not reply to it.\n\n-------------------\n"+copyright()+" Acme Mail" {
t.Errorf("system layout: text = %q", msg.Text)
}
// Without a logo the header shows the site name.
m, drv = partialsMailer(t, Options{}, &Overrides{Brand: &Brand{SiteName: "Acme Mail"}})
if html := unstyled(sendTemplate(t, m, drv, "acme.blog::mail.auto", nil).HTML); !strings.Contains(html, "<td class=\"header\">\n<span>Acme Mail</span>") || strings.Contains(html, "<img") {
t.Errorf("system layout without a logo:\n%s", html)
}
// The minimal layout shows the logo above the message.
m, drv = partialsMailer(t, Options{CSS: "p{color:red}"}, &Overrides{Brand: &Brand{LogoURL: logo, SiteName: "Acme Mail"}})
msg = sendTemplate(t, m, drv, "acme.blog::mail.bare", nil)
if html := unstyled(msg.HTML); !strings.Contains(html, "<p><img src=\""+logo+"\" class=\"logo\" alt=\"Acme Mail\"/></p>\n<p>Done.</p>") || strings.Contains(html, "layout-system") {
t.Errorf("minimal layout with a logo: HTML = %q", html)
}
if msg.Text != "Done." {
t.Errorf("minimal layout: text = %q", msg.Text)
}
// Without a logo its body holds only the message.
m, drv = partialsMailer(t, Options{CSS: "p{color:red}"}, nil)
msg = sendTemplate(t, m, drv, "acme.blog::mail.bare", nil)
if !strings.Contains(msg.HTML, "<body>\n<p style=\"color:red\">Done.</p>\n\n\n</body>") || strings.Contains(msg.HTML, "content-body") || strings.Contains(msg.HTML, "layout-system") {
t.Errorf("minimal layout: HTML = %q", msg.HTML)
}
// Every rule was inlined or matched nothing: no style block is left.
if strings.Contains(msg.HTML, "<style") {
t.Errorf("minimal layout: style block left = %q", msg.HTML)
}
if msg.Text != "Done." {
t.Errorf("minimal layout: text = %q", msg.Text)
}
// Every built-in layout styles the button with the brand colour.
button := "{{ partial \"button\" \"url\" \"https://example.com\" \"body\" \"Go\" }}\n"
buttons := fstest.MapFS{
"views/mail/d.htm": {Data: []byte("subject = \"D\"\n==\n" + button)},
"views/mail/s.htm": {Data: []byte("subject = \"S\"\nlayout = \"system\"\n==\n" + button)},
"views/mail/m.htm": {Data: []byte("subject = \"M\"\nlayout = \"minimal\"\n==\n" + button)},
}
cat := NewCatalog()
if err := cat.Register("acme.shop", buttons, []string{"acme.shop::mail.d", "acme.shop::mail.s", "acme.shop::mail.m"}, nil); err != nil {
t.Fatal(err)
}
drvB := NewMemoryDriver()
mb := NewMailer(cat, drvB, Options{Overrides: fakeOverrides{ov: Overrides{Brand: &Brand{ButtonPrimaryBg: "#445566"}}}})
for _, name := range []string{"acme.shop::mail.d", "acme.shop::mail.s", "acme.shop::mail.m"} {
msg := sendTemplate(t, mb, drvB, name, nil)
if style := buttonStyle(t, msg.HTML); !strings.Contains(unstyled(msg.HTML), `class="button button-primary"`) || !strings.Contains(style, "background-color:#445566") {
t.Errorf("%s: button style %q", name, style)
}
}
// A plugin's own alias named system wins over the built-in one.
fsys := fstest.MapFS{
"views/mail/auto.htm": {Data: []byte("subject = \"Auto\"\nlayout = \"system\"\n==\nDone.\n")},
"views/mail/layouts/system.htm": {Data: []byte("name = \"Mine\"\n==\n{{ .Content }}\n==\n<div class=\"mine\">{{ .Content }}</div>\n")},
}
cat = NewCatalog()
if err := cat.Register("acme.shop", fsys, []string{"acme.shop::mail.auto"}, map[string]string{"system": "acme.shop::mail.layouts.system"}); err != nil {
t.Fatal(err)
}
drv2 := NewMemoryDriver()
msg = sendTemplate(t, NewMailer(cat, drv2, Options{}), drv2, "acme.shop::mail.auto", nil)
if !strings.Contains(msg.HTML, `<div class="mine">`) || strings.Contains(msg.HTML, "layout-system") {
t.Errorf("a plugin alias named system did not win: %q", msg.HTML)
}
// An alias that is neither the plugin's nor built in still fails at boot.
bad := fstest.MapFS{"views/mail/x.htm": {Data: []byte("subject = \"X\"\nlayout = \"fancy\"\n==\nx\n")}}
if err := NewCatalog().Register("acme.shop", bad, []string{"acme.shop::mail.x"}, nil); err == nil || !strings.Contains(err.Error(), "unknown layout fancy") {
t.Errorf("unknown alias = %v", err)
}
})
t.Run("inline", func(t *testing.T) {
brand := &Brand{ButtonPrimaryBg: "#445566"}
welcome := map[string]any{"Name": "Ada", "Link": "https://example.com/go"}
const media = "@media only screen and (max-width: 600px) { .inner-body { width: 100% !important; } }"
// The default layout: the brand CSS is on the elements, the DOCTYPE
// and the classes are kept, and the safety checks still pass.
m, drv := partialsMailer(t, Options{CSS: media}, &Overrides{Brand: brand})
inlined := sendTemplate(t, m, drv, "acme.blog::mail.welcome", welcome)
if !strings.HasPrefix(inlined.HTML, `<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"`) {
t.Errorf("the DOCTYPE line was lost:\n%s", inlined.HTML)
}
if style := buttonStyle(t, inlined.HTML); !strings.Contains(style, "background-color:#445566") {
t.Errorf("the button carries no inlined brand colour: style=%q\n%s", style, inlined.HTML)
}
if !strings.Contains(inlined.HTML, `class="inner-body"`) || validateHTML(inlined.HTML) != nil {
t.Errorf("classes lost or the inlined HTML fails the safety checks:\n%s", inlined.HTML)
}
// A media query cannot be inlined: it stays in a style element.
if css := styleBlock(t, inlined.HTML); !strings.Contains(css, "@media only screen and (max-width: 600px)") || !strings.Contains(css, ".inner-body") {
t.Errorf("the media query is not in a style element:\n%s", css)
}
if strings.Contains(inlined.HTML, "width:100% !important") {
t.Errorf("a media-query rule reached an element:\n%s", inlined.HTML)
}
// optedOut checks a message whose layout kept its style block only.
optedOut := func(name string, msg RenderedMessage) {
t.Helper()
if style := buttonStyle(t, msg.HTML); style != "" {
t.Errorf("%s: the button has an inlined style %q", name, style)
}
if css := styleBlock(t, msg.HTML); !strings.Contains(css, "#445566") {
t.Errorf("%s: the style block lost the brand CSS:\n%s", name, css)
}
}
// A file layout with the header key opts out.
for _, value := range []string{"true", "1", "Yes"} {
fsys := fstest.MapFS{
"views/mail/plain.htm": {Data: []byte("subject = \"Plain\"\nlayout = \"plain\"\n==\n{{ partial \"button\" \"url\" \"https://example.com\" \"body\" \"Go\" }}\n")},
"views/mail/layouts/plain.htm": {Data: []byte("name = \"Plain\"\ndisable_auto_inline_css = " + value + "\n==\n{{ .Content }}\n==\n<html><head><style>{{ .brandCss }}</style></head><body>{{ .Content }}</body></html>\n")},
}
cat := NewCatalog()
if err := cat.Register("acme.shop", fsys, []string{"acme.shop::mail.plain"}, map[string]string{"plain": "acme.shop::mail.layouts.plain"}); err != nil {
t.Fatal(err)
}
if f, ok := cat.Layout("acme.shop::mail.layouts.plain"); !ok || !f.DisableAutoInlineCSS {
t.Errorf("header value %q: LayoutFile = %+v", value, f)
}
drv := NewMemoryDriver()
optedOut("file layout "+value, sendTemplate(t, NewMailer(cat, drv, Options{Overrides: fakeOverrides{ov: Overrides{Brand: brand}}}), drv, "acme.shop::mail.plain", nil))
}
if f, _ := NewCatalog().Layout(defaultLayoutName); f.DisableAutoInlineCSS {
t.Error("the built-in default layout opts out")
}
// A database layout with the column set opts out; without it, it inlines.
def, _ := NewCatalog().Layout(defaultLayoutName)
ov := &Overrides{Brand: brand, Layouts: map[string]LayoutOverride{defaultLayoutName: {HTML: def.HTML, Text: def.Text, DisableAutoInlineCSS: true}}}
m, drv = partialsMailer(t, Options{}, ov)
dbOptedOut := sendTemplate(t, m, drv, "acme.blog::mail.welcome", welcome)
optedOut("database layout", dbOptedOut)
if dbOptedOut.Text != inlined.Text {
t.Errorf("the text part changed with the opt-out: %q, want %q", dbOptedOut.Text, inlined.Text)
}
ov.Layouts[defaultLayoutName] = LayoutOverride{HTML: def.HTML, Text: def.Text}
m, drv = partialsMailer(t, Options{}, ov)
if style := buttonStyle(t, sendTemplate(t, m, drv, "acme.blog::mail.welcome", welcome).HTML); !strings.Contains(style, "#445566") {
t.Errorf("a database layout without the column did not inline: %q", style)
}
// A layout draft with the flag previews the same way.
ed, _ := newEditor(t, &Overrides{Brand: brand})
draft := Draft{Kind: KindLayout, HTML: `<html><head><style>{{ .brandCss }}</style></head><body>{{ .Content }}</body></html>`, Text: "{{ .Content }}"}
prev, err := ed.Preview(context.Background(), draft)
if err != nil {
t.Fatal(err)
}
if style := buttonStyle(t, prev.HTML); !strings.Contains(style, "#445566") {
t.Errorf("a layout draft without the flag did not inline: %q", style)
}
draft.DisableAutoInlineCSS = true
if prev, err = ed.Preview(context.Background(), draft); err != nil {
t.Fatal(err)
}
optedOut("layout draft", RenderedMessage{HTML: prev.HTML})
// An inliner error sends the un-inlined HTML and warns once.
m, drv = partialsMailer(t, Options{CSS: media}, &Overrides{Brand: brand})
mm := m.(*mailer)
var logs bytes.Buffer
mm.log = slog.New(slog.NewTextHandler(&logs, nil))
mm.inline = func(string) (string, error) { return "", errors.New("inliner broke") }
failed := sendTemplate(t, m, drv, "acme.blog::mail.welcome", welcome)
sendTemplate(t, m, drv, "acme.blog::mail.welcome", welcome)
optedOut("inliner error", failed)
if n := strings.Count(logs.String(), "level=WARN"); n != 1 || !strings.Contains(logs.String(), "inliner broke") {
t.Errorf("log = %q, want one warning naming the error", logs.String())
}
if failed.Text != inlined.Text {
t.Errorf("the text part changed with inlining: %q, want %q", failed.Text, inlined.Text)
}
})
t.Run("layout_partials", func(t *testing.T) {
m, drv := partialsMailer(t, Options{}, nil)
msg := sendTemplate(t, m, drv, "acme.blog::mail.note", map[string]any{"Text": "<b>hi</b>"})
want := `<div class="blog-mail"><div class="note">&lt;b&gt;hi&lt;/b&gt;</div>` + "\n" + `<div class="note">footer</div></div>`
if !strings.Contains(msg.HTML, want) {
t.Errorf("HTML = %q, want the body partial and the layout partial", msg.HTML)
}
if msg.Text != "NOTE: <b>hi</b>\nNOTE: footer" {
t.Errorf("text = %q", msg.Text)
}
})
t.Run("overrides", func(t *testing.T) {
ov := Overrides{
// A customized file layout, by its full name. Both layouts keep
// their style block (no inlining), so the order of the CSS slots
// shows in it.
Layouts: map[string]LayoutOverride{
"acme.blog::mail.layouts.blog": {Name: "Blog", HTML: `<div class="custom-blog">{{ .Content }}</div><style>{{ .brandCss }}{{ .css }}</style>`, Text: "[custom] {{ .Content }}", CSS: ".custom{margin:0}", DisableAutoInlineCSS: true},
// A database-only layout, by its code.
"promo": {Name: "Promo", HTML: `<div class="promo">{{ .Content }}{{ partial "acme.blog::mail.partials.note" "text" "promo" }}</div><style>{{ .css }}</style>`, Text: "PROMO {{ .Content }}", CSS: ".promo{margin:0}", DisableAutoInlineCSS: true},
},
Partials: map[string]PartialOverride{
"acme.blog::mail.partials.note": {HTML: `<aside>{{ .text }}</aside>`, Text: "* {{ .text }}"},
// An override of a partial that no plugin ships is ignored.
"acme.blog::mail.partials.gone": {HTML: "x", Text: "x"},
},
}
m, drv := partialsMailer(t, Options{CSS: "p{color:red}", BrandCSS: ".brand{color:blue}"}, &ov)
msg := sendTemplate(t, m, drv, "acme.blog::mail.note", map[string]any{"Text": "hi"})
if !strings.Contains(msg.HTML, `<div class="custom-blog"><aside>hi</aside>`) {
t.Errorf("HTML = %q, want the customized layout and partial", msg.HTML)
}
if !strings.Contains(msg.HTML, "<style>.brand{color:blue}.custom{margin:0}\np{color:red}</style>") {
t.Errorf("style block = %q, want the layout CSS before mail.css", msg.HTML)
}
if msg.Text != "[custom] * hi" {
t.Errorf("text = %q", msg.Text)
}
// A template override moves the template to the database-only layout.
ov.Template = &TemplateOverride{Subject: "Promo", Body: "Sale.", Layout: "promo"}
m, drv = partialsMailer(t, Options{CSS: "p{color:red}"}, &ov)
msg = sendTemplate(t, m, drv, "acme.blog::mail.welcome", nil)
if msg.Subject != "Promo" || !strings.Contains(msg.HTML, `<div class="promo"><p>Sale.</p>`+"\n"+`<aside>promo</aside></div><style>.promo{margin:0}`+"\np{color:red}</style>") {
t.Errorf("database-only layout: %q / %q", msg.Subject, msg.HTML)
}
if msg.Text != "PROMO Sale." {
t.Errorf("database-only layout: text = %q", msg.Text)
}
// A customized default layout applies to templates on the default layout.
ov = Overrides{Layouts: map[string]LayoutOverride{defaultLayoutName: {HTML: `<main>{{ .Content }}</main>`, Text: "{{ .Content }} (sent by acme)"}}}
m, drv = partialsMailer(t, Options{}, &ov)
msg = sendTemplate(t, m, drv, "acme.blog::mail.welcome", map[string]any{"Name": "Ada", "Link": "https://example.com"})
if !strings.HasPrefix(msg.HTML, "<main><p>Hi Ada</p>") || !strings.HasSuffix(msg.Text, "Bye (sent by acme)") {
t.Errorf("customized default layout: %q / %q", msg.HTML, msg.Text)
}
// A partial override that does not render falls back to the files.
ov = Overrides{Partials: map[string]PartialOverride{"acme.blog::mail.partials.note": {HTML: `{{ .text.missing.field }}`, Text: "x"}}}
m, drv = partialsMailer(t, Options{}, &ov)
msg = sendTemplate(t, m, drv, "acme.blog::mail.note", map[string]any{"Text": "hi"})
if !strings.Contains(msg.HTML, `<div class="note">hi</div>`) {
t.Errorf("a failing partial override did not fall back to the file: %q", msg.HTML)
}
})
}