Good to see you, Ada.
`) {
t.Errorf("HTML = %q, want the override body in the blog layout", got.HTML)
}
if got.Text != "Good to see you, *Ada*.\n\n-- The Acme blog" {
t.Errorf("text = %q", got.Text)
}
if logs.Len() != 0 {
t.Errorf("unexpected log output:\n%s", logs)
}
// No cache: an edit and a reset are both effective on the next send.
customizeWelcome(t, gdb, "Second {{ .name }}", "Edited.", "acme.blog::mail.layouts.blog")
sendWelcome(t, m, "")
if got := lastMessage(t, drv); got.Subject != "Second Ada" {
t.Errorf("subject after an edit = %q", got.Subject)
}
if err := gdb.Exec(`UPDATE `+TemplatesTable+` SET is_custom = FALSE WHERE code = ?`, acmeWelcome).Error; err != nil {
t.Fatal(err)
}
sendWelcome(t, m, "")
if got := lastMessage(t, drv); got.Subject != file.Subject || got.HTML != file.HTML || got.Text != file.Text {
t.Errorf("after is_custom was cleared the row still applies: %+v", got)
}
})
t.Run("override_layout", func(t *testing.T) {
gdb := mailPostgres(t)
m, drv, logs := bootMailApp(t, gdb)
// The override moves the template to postcard's default layout.
customizeWelcome(t, gdb, "Hello", "Plain.", defaultLayoutName)
sendWelcome(t, m, "")
got := lastMessage(t, drv)
if !strings.Contains(got.HTML, "
\n Plain. ") || strings.Contains(got.HTML, "blog-mail") {
t.Errorf("HTML = %q, want the default layout", got.HTML)
}
if logs.Len() != 0 {
t.Errorf("unexpected log output:\n%s", logs)
}
// A layout code that names nothing renders with the default layout
// and says so.
customizeWelcome(t, gdb, "Hello", "Plain.", "gone")
sendWelcome(t, m, "")
got = lastMessage(t, drv)
if !strings.Contains(got.HTML, " | \n Plain. ") {
t.Errorf("HTML = %q, want the default layout for an unknown layout code", got.HTML)
}
if !strings.Contains(logs.String(), "level=WARN") || !strings.Contains(logs.String(), "unknown layout") || !strings.Contains(logs.String(), "layout=gone") {
t.Errorf("log = %q, want a warning naming the layout", logs)
}
})
t.Run("layouts_and_partials", func(t *testing.T) {
gdb := mailPostgres(t)
m, drv, logs := bootMailApp(t, gdb)
stmts := []string{
// A customized file layout that keeps its style block (no
// inlining), a database-only layout and an index row that is not
// customized.
`INSERT INTO ` + LayoutsTable + ` (code, source, name, content_html, content_text, content_css, is_custom, disable_auto_inline_css) VALUES
('acme.blog::mail.layouts.blog', 'acme.blog', 'Blog', '{{ .Content }} ', '[custom] {{ .Content }}', '.custom{margin:0}', TRUE, TRUE),
('promo', NULL, 'Promo', '{{ .Content }}{{ partial "button" "url" "https://example.com" "body" "Shop" }} ', 'PROMO {{ .Content }}', '', TRUE, FALSE),
('` + defaultLayoutName + `', 'postcard', 'Default', '{{ .Content }} ', 'MIRROR {{ .Content }}', '', FALSE, FALSE)`,
// A customized built-in partial.
`INSERT INTO ` + PartialsTable + ` (code, source, name, content_html, content_text, is_custom) VALUES
('postcard::mail.partials.button', 'postcard', 'Button', '{{ .body }}', '{{ .body }}: {{ .url }}', TRUE),
('postcard::mail.partials.panel', 'postcard', 'Panel', 'mirror', 'mirror', FALSE)`,
}
for _, stmt := range stmts {
if err := gdb.Exec(stmt).Error; err != nil {
t.Fatal(err)
}
}
// With no template row the file template is sent in its customized layout.
sendWelcome(t, m, "")
got := lastMessage(t, drv)
if got.Subject != file.Subject || !strings.Contains(got.HTML, `Hi Ada`) ||
!strings.Contains(got.HTML, "") || !strings.HasPrefix(got.Text, "[custom] Hi **Ada**") {
t.Errorf("customized file layout: %+v", got)
}
// A template override on the database-only layout, which calls the
// customized partial.
customizeWelcome(t, gdb, "Sale", "Now.", "promo")
sendWelcome(t, m, "")
got = lastMessage(t, drv)
if got.Subject != "Sale" || !strings.Contains(got.HTML, ` `) {
t.Errorf("database-only layout: %+v", got)
}
if got.Text != "PROMO Now." {
t.Errorf("database-only layout: text = %q", got.Text)
}
// An empty template name asks for everything except a template override.
all, err := NewDBSource(appWith(t, gdb)).MailOverrides(context.Background(), "")
if err != nil {
t.Fatal(err)
}
if all.Template != nil || len(all.Layouts) != 2 || len(all.Partials) != 1 {
t.Errorf("overrides without a template name = %+v", all)
}
if l := all.Layouts["promo"]; l.Name != "Promo" || !strings.HasPrefix(l.Text, "PROMO") || l.DisableAutoInlineCSS {
t.Errorf("promo layout = %+v", l)
}
if l := all.Layouts["acme.blog::mail.layouts.blog"]; !l.DisableAutoInlineCSS {
t.Errorf("blog layout = %+v, want the inlining opt-out", l)
}
if logs.Len() != 0 {
t.Errorf("unexpected log output:\n%s", logs)
}
})
t.Run("file", func(t *testing.T) {
gdb := mailPostgres(t)
m, drv, logs := bootMailApp(t, gdb)
sendWelcome(t, m, "")
got := lastMessage(t, drv)
if got.Subject != file.Subject || got.HTML != file.HTML || got.Text != file.Text {
t.Errorf("without a row the mail differs from the file version:\n got %+v\nwant %+v", got, file)
}
// A row that is not customized (an index row) changes nothing.
if err := gdb.Exec(`INSERT INTO `+TemplatesTable+` (code, source, subject, body) VALUES (?, 'acme.blog', 'Mirror', 'Mirror')`, acmeWelcome).Error; err != nil {
t.Fatal(err)
}
sendWelcome(t, m, "")
got = lastMessage(t, drv)
if got.Subject != file.Subject || got.HTML != file.HTML || got.Text != file.Text {
t.Errorf("a row with is_custom false changed the mail: %+v", got)
}
if logs.Len() != 0 {
t.Errorf("unexpected log output:\n%s", logs)
}
})
t.Run("fallback", func(t *testing.T) {
gdb := mailPostgres(t)
m, drv, logs := bootMailApp(t, gdb)
cases := map[string]string{
// A field of a variable the caller does not pass fails at execution.
"runtime": "Order {{ .order.code }}",
// A body that does not parse.
"parse": "Hi {{ .name",
// A body that renders but fails the safety checks on the result.
"unsafe": "Type javascript: in the address bar.",
}
for name, body := range cases {
logs.Reset()
customizeWelcome(t, gdb, "Hello {{ .name }}", body, "acme.blog::mail.layouts.blog")
sendWelcome(t, m, "")
got := lastMessage(t, drv)
if got.Subject != file.Subject || got.HTML != file.HTML || got.Text != file.Text {
t.Errorf("%s: a failing override did not fall back to the file version: %+v", name, got)
}
out := logs.String()
if !strings.Contains(out, "level=ERROR") || !strings.Contains(out, "postcard: override failed, sending the file version") ||
!strings.Contains(out, "template="+acmeWelcome) || !strings.Contains(out, "error=") {
t.Errorf("%s: log = %q, want the override failure with template and error", name, out)
}
}
// A subject override with a line break is refused the same way.
logs.Reset()
customizeWelcome(t, gdb, "Hello\nBcc: all@example.com", "Fine.", "acme.blog::mail.layouts.blog")
sendWelcome(t, m, "")
if got := lastMessage(t, drv); got.Subject != file.Subject || got.HTML != file.HTML {
t.Errorf("a subject override with a line break was sent: %+v", got)
}
if !strings.Contains(logs.String(), "CR/LF") {
t.Errorf("log = %q, want the CR/LF refusal", logs)
}
})
t.Run("caller_subject", func(t *testing.T) {
gdb := mailPostgres(t)
m, drv, _ := bootMailApp(t, gdb)
customizeWelcome(t, gdb, "Hello {{ .name }}", "Override body.", "acme.blog::mail.layouts.blog")
sendWelcome(t, m, "From the caller, {{ .name }}")
got := lastMessage(t, drv)
if got.Subject != "From the caller, Ada" {
t.Errorf("subject = %q, want the caller's", got.Subject)
}
if !strings.Contains(got.HTML, "Override body.") {
t.Errorf("HTML = %q, want the override body next to the caller's subject", got.HTML)
}
// A caller subject that is refused fails the send as before, and is
// not blamed on the override.
before := len(drv.Messages())
err := m.Send(context.Background(), Message{
Template: acmeWelcome,
To: []string{"ada@example.com"},
Subject: "Hi\r\nBcc: all@example.com",
})
if err == nil || !strings.Contains(err.Error(), "CR/LF") {
t.Errorf("Send with a CR/LF caller subject = %v", err)
}
if len(drv.Messages()) != before {
t.Error("a refused message was sent")
}
})
t.Run("missing_table", func(t *testing.T) {
gdb := mailPostgres(t)
m, drv, logs := bootMailApp(t, gdb)
customizeWelcome(t, gdb, "Hello", "Override.", "")
if err := gdb.Exec(`DROP TABLE ` + TemplatesTable).Error; err != nil {
t.Fatal(err)
}
for range 3 {
sendWelcome(t, m, "")
got := lastMessage(t, drv)
if got.Subject != file.Subject || got.HTML != file.HTML || got.Text != file.Text {
t.Fatalf("with the table missing the mail differs from the file version: %+v", got)
}
}
out := logs.String()
if n := strings.Count(out, "postcard: mail overrides unavailable, sending the file version"); n != 1 {
t.Errorf("warning logged %d times for 3 sends, want 1 (rate-limited):\n%s", n, out)
}
if !strings.Contains(out, "level=WARN") || !strings.Contains(out, TemplatesTable) {
t.Errorf("log = %q, want a warning naming the table", out)
}
})
t.Run("no_db", func(t *testing.T) {
m, drv, logs := bootMailApp(t, nil)
sendWelcome(t, m, "")
got := lastMessage(t, drv)
if got.Subject != file.Subject || got.HTML != file.HTML || got.Text != file.Text {
t.Errorf("without a database the mail differs from the file version: %+v", got)
}
if logs.Len() != 0 {
t.Errorf("unexpected log output:\n%s", logs)
}
})
t.Run("unknown_template", func(t *testing.T) {
m, _, _ := bootMailApp(t, mailPostgres(t))
err := m.Send(context.Background(), Message{Template: "acme.blog::mail.missing", To: []string{"ada@example.com"}})
if err == nil || !strings.Contains(err.Error(), "unknown template acme.blog::mail.missing") {
t.Errorf("Send of an unknown template = %v", err)
}
})
t.Run("locale_fallback", func(t *testing.T) {
gdb := mailPostgres(t)
m, drv, logs := bootMailApp(t, gdb)
// welcome-en ships its own file; de and fr do not.
enFS := fstest.MapFS{"views/mail/welcome-en.htm": {Data: []byte("subject = \"English {{ .name }}\"\nlayout = \"blog\"\n==\nHello {{ .name }}.\n")}}
if err := m.catalog.Register("acme.blog", enFS, []string{acmeWelcome + "-en"}, nil); err != nil {
t.Fatal(err)
}
ctx := context.Background()
locales := []string{"pl", "en", "de"}
if err := SyncIndex(ctx, gdb, m.catalog, locales); err != nil {
t.Fatal(err)
}
if err := EnsureLocaleRows(ctx, gdb, m.catalog, "pl", locales); err != nil {
t.Fatal(err)
}
var rows []struct {
Code string
Locale *string
BaseCode *string
Subject string
FileHash string
}
if err := gdb.Raw(`SELECT code, locale, base_code, subject, file_hash FROM `+TemplatesTable+` WHERE base_code = ? ORDER BY code`, acmeWelcome).Scan(&rows).Error; err != nil {
t.Fatal(err)
}
base, _ := m.catalog.Template(acmeWelcome)
if len(rows) != 3 || rows[0].Code != acmeWelcome || rows[1].Code != acmeWelcome+"-de" || rows[2].Code != acmeWelcome+"-en" {
t.Fatalf("welcome group rows = %+v, want welcome, welcome-de, welcome-en", rows)
}
if de := rows[1]; de.Locale == nil || *de.Locale != "de" || de.Subject != base.Subject || de.FileHash != base.Hash {
t.Errorf("fallback row = %+v, want locale de with the base file's subject and hash", de)
}
// Idempotent: a second run writes nothing new.
if err := EnsureLocaleRows(ctx, gdb, m.catalog, "pl", locales, acmeWelcome); err != nil {
t.Fatal(err)
}
var n int64
gdb.Raw(`SELECT COUNT(*) FROM ` + TemplatesTable).Scan(&n)
if n != 6 { // welcome, welcome-de, welcome-en, notice, notice-de, notice-en
t.Errorf("%d template rows after a second ensure, want 6", n)
}
// fr has no row: the base file.
sendFixture(t, m, acmeWelcome+"-fr", "")
if got := lastMessage(t, drv); got.Subject != "Welcome, Ada" {
t.Errorf("welcome-fr subject = %q, want the base file's", got.Subject)
}
// de customized: its own row.
if err := gdb.Exec(`UPDATE `+TemplatesTable+` SET subject = 'Willkommen {{ .name }}', is_custom = TRUE, base_hash = file_hash WHERE code = ?`, acmeWelcome+"-de").Error; err != nil {
t.Fatal(err)
}
sendFixture(t, m, acmeWelcome+"-de", "")
if got := lastMessage(t, drv); got.Subject != "Willkommen Ada" || !strings.Contains(got.HTML, "blog-mail") {
t.Errorf("welcome-de = %q / %q, want its customization in the blog layout", got.Subject, got.HTML)
}
// The base customized: fr now sends it, de keeps its own.
customizeWelcome(t, gdb, "Base {{ .name }}", "Base body.", "acme.blog::mail.layouts.blog")
sendFixture(t, m, acmeWelcome+"-fr", "")
if got := lastMessage(t, drv); got.Subject != "Base Ada" {
t.Errorf("welcome-fr after the base was customized = %q", got.Subject)
}
sendFixture(t, m, acmeWelcome+"-de", "")
if got := lastMessage(t, drv); got.Subject != "Willkommen Ada" {
t.Errorf("welcome-de after the base was customized = %q", got.Subject)
}
// A name with its own file is unchanged.
sendFixture(t, m, acmeWelcome+"-en", "")
if got := lastMessage(t, drv); got.Subject != "English Ada" {
t.Errorf("welcome-en = %q, want its own file", got.Subject)
}
// Neither a base nor a locale tag: unknown, with today's text.
for _, name := range []string{"acme.blog::mail.missing-de", acmeWelcome + "-deutsch", acmeWelcome + "x"} {
err := m.Send(ctx, Message{Template: name, To: []string{"ada@example.com"}})
if err == nil || !strings.Contains(err.Error(), "unknown template "+name) {
t.Errorf("Send of %s = %v", name, err)
}
}
if f, ok := m.catalog.TemplateFor(acmeWelcome + "-pt-BR"); !ok || f.Name != acmeWelcome {
t.Errorf("TemplateFor(welcome-pt-BR) = %q, %v", f.Name, ok)
}
if logs.Len() != 0 {
t.Errorf("unexpected log output:\n%s", logs)
}
})
t.Run("migrations_roll_back", func(t *testing.T) {
gdb := mailPostgres(t)
mig := gormigrate.New(gdb, gormigrate.DefaultOptions, Migrations)
for range Migrations {
if err := mig.RollbackLast(); err != nil {
t.Fatalf("rollback: %v", err)
}
}
var n int64
if err := gdb.Raw(`SELECT COUNT(*) FROM information_schema.tables WHERE table_name LIKE 'system_mail_%'`).Scan(&n).Error; err != nil {
t.Fatal(err)
}
if n != 0 {
t.Errorf("%d mail tables left after the rollback", n)
}
if err := mig.Migrate(); err != nil {
t.Fatalf("migrate again: %v", err)
}
})
}
|