Files
summercms/modules/postcard/inline_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

246 lines
10 KiB
Go

package postcard
import (
"bytes"
"context"
"errors"
"log/slog"
"strings"
"testing"
"testing/fstest"
"time"
)
const (
inlineBrandColour = "#445566"
inlineMedia = "@media only screen and (max-width: 600px) { .inner-body { width: 100% !important; } }"
)
var inlineVars = map[string]any{"Name": "Ada", "Link": "https://example.com/go"}
// defaultLayoutWithCSS is the built-in default layout as a database layout
// whose CSS is css.
func defaultLayoutWithCSS(css string, optOut bool) map[string]LayoutOverride {
def, _ := NewCatalog().Layout(defaultLayoutName)
return map[string]LayoutOverride{defaultLayoutName: {HTML: def.HTML, Text: def.Text, CSS: css, DisableAutoInlineCSS: optOut}}
}
func TestInlineCSS(t *testing.T) {
t.Parallel()
brand := &Brand{ButtonPrimaryBg: inlineBrandColour}
ov := &Overrides{Brand: brand, Layouts: defaultLayoutWithCSS(inlineMedia, false)}
m, drv := partialsMailer(t, Options{}, ov)
inlined := sendTemplate(t, m, drv, "acme.blog::mail.welcome", inlineVars)
// The same message with inlining off: the mailer's no-op inliner seam.
plainMailer, plainDrv := partialsMailer(t, Options{}, ov)
plainMailer.(*mailer).inline = noInline
plain := sendTemplate(t, plainMailer, plainDrv, "acme.blog::mail.welcome", inlineVars)
t.Run("button_colour", func(t *testing.T) {
if style := buttonStyle(t, inlined.HTML); !strings.Contains(style, "background-color:"+inlineBrandColour) {
t.Errorf("button style = %q, want the brand primary colour inline", style)
}
if style := buttonStyle(t, plain.HTML); style != "" {
t.Errorf("without inlining the button has style %q", style)
}
})
t.Run("doctype", func(t *testing.T) {
const doctype = `<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">`
if !strings.HasPrefix(inlined.HTML, doctype) {
t.Errorf("DOCTYPE lost:\n%.200s", inlined.HTML)
}
if strings.Count(inlined.HTML, "<!DOCTYPE") != 1 {
t.Errorf("DOCTYPE repeated:\n%.300s", inlined.HTML)
}
})
t.Run("media_query", func(t *testing.T) {
css := styleBlock(t, inlined.HTML)
if !strings.Contains(css, "@media only screen and (max-width: 600px)") || !strings.Contains(css, ".inner-body") {
t.Errorf("the layout's media query is not in a style element:\n%s", css)
}
for _, tag := range withClass(inlined.HTML, "table", "inner-body") {
if strings.Contains(tag.attrs["style"], "100% !important") {
t.Errorf("a media-query rule reached an element: %q", tag.attrs["style"])
}
}
})
t.Run("text_unchanged", func(t *testing.T) {
if inlined.Text != plain.Text || inlined.Subject != plain.Subject {
t.Errorf("inlining changed the text part or the subject:\n%q\n%q", inlined.Text, plain.Text)
}
if inlined.HTML == plain.HTML {
t.Error("inlining changed nothing in the HTML")
}
if unstyled(inlined.HTML) == inlined.HTML {
t.Error("the inlined HTML has no style attributes")
}
})
t.Run("safety_check", func(t *testing.T) {
if err := validateHTML(inlined.HTML); err != nil {
t.Errorf("the inlined HTML fails the safety checks: %v", err)
}
// A layout override whose CSS holds a javascript: URL never passed
// save validation (Editor.Validate refuses it); injected as a raw
// fixture, it fails the safety check and the file version is sent.
plugin := acmeBlog{}
cat := NewCatalog()
if err := cat.Register(plugin.ID(), plugin.MailTemplatesFS(), plugin.MailTemplates(), plugin.MailLayouts()); err != nil {
t.Fatal(err)
}
unsafe := Overrides{Layouts: map[string]LayoutOverride{
"acme.blog::mail.layouts.blog": {
HTML: `<html><head><style>{{ .css }}</style></head><body><div class="blog-mail">{{ .Content }}</div></body></html>`,
Text: "{{ .Content }}",
CSS: `.blog-mail { background: url("javascript:alert(1)"); }`,
},
}}
assertFileFallback(t, cat, fileWelcome(t), Options{Overrides: fakeOverrides{ov: unsafe}}, true)
// The same CSS in an inlined style attribute is caught by the check
// that runs on the inliner's output.
if err := validateHTML(`<div style="background: url(&#34;javascript:alert(1)&#34;)">x</div>`); err == nil {
t.Error("the safety check accepts a javascript: URL in a style attribute")
}
})
}
func TestInlineCSSOptOut(t *testing.T) {
t.Parallel()
brand := &Brand{ButtonPrimaryBg: inlineBrandColour}
const buttonBody = "{{ partial \"button\" \"url\" \"https://example.com\" \"body\" \"Go\" }}\n"
const plainLayout = "<html><head><style>{{ .brandCss }}</style></head><body>{{ .Content }}</body></html>\n"
// optedOut checks a message whose layout kept its CSS in the style block.
optedOut := func(t *testing.T, html string) {
t.Helper()
if style := buttonStyle(t, html); style != "" {
t.Errorf("the button has an inlined style %q", style)
}
if css := styleBlock(t, html); !strings.Contains(css, inlineBrandColour) {
t.Errorf("the style block lost the brand CSS:\n%s", css)
}
}
inlinedButton := func(t *testing.T, html string) {
t.Helper()
if style := buttonStyle(t, html); !strings.Contains(style, inlineBrandColour) {
t.Errorf("the button carries no inlined brand colour: %q", style)
}
}
t.Run("file_header_key", func(t *testing.T) {
for _, value := range []string{"true", "TRUE", "1", "yes", "false", "0", ""} {
header := "name = \"Plain\"\n"
if value != "" {
header += "disable_auto_inline_css = " + value + "\n"
}
fsys := fstest.MapFS{
"views/mail/plain.htm": {Data: []byte("subject = \"Plain\"\nlayout = \"plain\"\n==\n" + buttonBody)},
"views/mail/layouts/plain.htm": {Data: []byte(header + "==\n{{ .Content }}\n==\n" + plainLayout)},
}
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)
}
want := value == "true" || value == "TRUE" || value == "1" || value == "yes"
if f, _ := cat.Layout("acme.shop::mail.layouts.plain"); f.DisableAutoInlineCSS != want {
t.Errorf("header %q: LayoutFile.DisableAutoInlineCSS = %v, want %v", value, f.DisableAutoInlineCSS, want)
}
drv := NewMemoryDriver()
msg := sendTemplate(t, NewMailer(cat, drv, Options{Overrides: fakeOverrides{ov: Overrides{Brand: brand}}}), drv, "acme.shop::mail.plain", nil)
if want {
optedOut(t, msg.HTML)
} else {
inlinedButton(t, msg.HTML)
}
}
for _, f := range NewCatalog().Layouts() {
if f.DisableAutoInlineCSS {
t.Errorf("built-in layout %s opts out of inlining", f.Name)
}
}
})
t.Run("override_column", func(t *testing.T) {
m, drv := partialsMailer(t, Options{}, &Overrides{Brand: brand, Layouts: defaultLayoutWithCSS("", true)})
optedOut(t, sendTemplate(t, m, drv, "acme.blog::mail.welcome", inlineVars).HTML)
m, drv = partialsMailer(t, Options{}, &Overrides{Brand: brand, Layouts: defaultLayoutWithCSS("", false)})
inlinedButton(t, sendTemplate(t, m, drv, "acme.blog::mail.welcome", inlineVars).HTML)
})
t.Run("layout_draft", func(t *testing.T) {
ed, _ := newEditor(t, &Overrides{Brand: brand})
draft := Draft{Kind: KindLayout, HTML: plainLayout, Text: "{{ .Content }}"}
prev, err := ed.Preview(context.Background(), draft)
if err != nil {
t.Fatal(err)
}
inlinedButton(t, prev.HTML)
draft.DisableAutoInlineCSS = true
if prev, err = ed.Preview(context.Background(), draft); err != nil {
t.Fatal(err)
}
optedOut(t, prev.HTML)
if derr := ed.Validate(context.Background(), draft); derr != nil {
t.Errorf("a layout draft with the opt-out does not validate: %v", derr)
}
})
}
func TestInlineFailure(t *testing.T) {
t.Parallel()
brand := &Brand{ButtonPrimaryBg: inlineBrandColour}
m, drv := partialsMailer(t, Options{CSS: inlineMedia}, &Overrides{Brand: brand})
mm := m.(*mailer)
var logs bytes.Buffer
mm.log = slog.New(slog.NewTextHandler(&logs, nil))
calls := 0
mm.inline = func(string) (string, error) { calls++; return "", errors.New("inliner broke") }
failed := sendTemplate(t, m, drv, "acme.blog::mail.welcome", inlineVars)
sendTemplate(t, m, drv, "acme.blog::mail.welcome", inlineVars)
if calls != 2 {
t.Fatalf("the inliner ran %d times, want 2", calls)
}
// The un-inlined HTML is sent: exactly what a no-op inliner produces.
ref, refDrv := partialsMailer(t, Options{CSS: inlineMedia}, &Overrides{Brand: brand})
ref.(*mailer).inline = noInline
want := sendTemplate(t, ref, refDrv, "acme.blog::mail.welcome", inlineVars)
if failed.HTML != want.HTML || failed.Text != want.Text {
t.Errorf("an inliner error did not send the un-inlined message:\n%s\nwant\n%s", failed.HTML, want.HTML)
}
if style := buttonStyle(t, failed.HTML); style != "" {
t.Errorf("the button has a style %q after an inliner error", style)
}
if css := styleBlock(t, failed.HTML); !strings.Contains(css, inlineBrandColour) || !strings.Contains(css, "@media") {
t.Errorf("the style block lost CSS after an inliner error:\n%s", css)
}
// One warning per layout per minute: two sends in the default layout
// warn once; the system layout is another key.
out := logs.String()
if n := strings.Count(out, "level=WARN"); n != 1 || !strings.Contains(out, "inliner broke") || !strings.Contains(out, "layout="+defaultLayoutName) {
t.Fatalf("log = %q, want one warning naming the error and the layout", out)
}
sendTemplate(t, m, drv, "acme.blog::mail.auto", nil)
if n := strings.Count(logs.String(), "level=WARN"); n != 2 || !strings.Contains(logs.String(), "layout="+systemLayoutName) {
t.Errorf("log = %q, want a second warning for the system layout", logs.String())
}
// The gate behind it repeats a key after warnInterval.
var g warnGate
now := time.Now()
if !g.allow("inline:"+defaultLayoutName, now) || g.allow("inline:"+defaultLayoutName, now.Add(warnInterval-time.Second)) {
t.Error("the warning gate did not hold a key for the interval")
}
if !g.allow("inline:"+defaultLayoutName, now.Add(warnInterval)) {
t.Error("the warning gate did not repeat a key after the interval")
}
// The real inliner takes ordinary HTML without an error.
if _, err := inlineCSS("<html><head><style>p{color:red}</style></head><body><p>x</p></body></html>"); err != nil {
t.Errorf("inlineCSS on plain HTML: %v", err)
}
}