package postcard
import (
"context"
"errors"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"testing"
"testing/fstest"
"git.golem15.com/golem15/summercms/modules/backpack"
)
const editorWelcomeHTM = `subject = "Welcome, {{ .Name }}"
description = "Sent after registration"
layout = "blog"
sample.Name = "Ada"
sample.order.code = "ZAM-1"
==
Hi **{{ .Name }}**, order {{ .order.code }} for {{ .company }}.
{{ range .order.items }}- {{ .description }}
{{ end }}
`
func editorFS(welcome string) fstest.MapFS {
return fstest.MapFS{
"views/mail/welcome.htm": {Data: []byte(welcome)},
"views/mail/welcome-en.htm": {Data: []byte("subject = \"Welcome\"\ndescription = \"English welcome\"\n==\nHello.\n")},
"views/mail/layouts/blog.htm": {Data: []byte(`name = "Blog"
==
{{ .Content }}
-- The Acme blog
==
{{ .Content }}
`)},
"views/mail/partials/note.htm": {Data: []byte(noteHTM)},
}
}
const (
editorWelcome = "acme.blog::mail.welcome"
editorBlogLayout = "acme.blog::mail.layouts.blog"
editorNote = "acme.blog::mail.partials.note"
)
func editorPlugin(welcome string) mailPlugin {
return mailPlugin{
partialsPlugin: partialsPlugin{id: "acme.blog", fsys: editorFS(welcome), partials: []string{editorNote}},
templates: []string{editorWelcome, "acme.blog::mail.welcome-en"},
layouts: map[string]string{"blog": editorBlogLayout},
}
}
func editorCatalog(t *testing.T, welcome string) *Catalog {
t.Helper()
p := editorPlugin(welcome)
cat := NewCatalog()
if err := cat.RegisterPartials(p.id, p.fsys, p.partials); err != nil {
t.Fatal(err)
}
if err := cat.Register(p.id, p.fsys, p.templates, p.layouts); err != nil {
t.Fatal(err)
}
return cat
}
// newEditor boots the fixture the way party does and returns the editor of
// the published mailer. ov, when set, replaces the mailer's override source.
func newEditor(t *testing.T, ov *Overrides) (*Editor, *MemoryDriver) {
t.Helper()
app := backpack.New(nil)
plugin := editorPlugin(editorWelcomeHTM)
if err := Activate(app, []mailPlugin{plugin}); err != nil {
t.Fatal(err)
}
if err := BootPlugin(app, plugin); err != nil {
t.Fatal(err)
}
ed, ok := EditorFrom(app)
if !ok {
t.Fatal("EditorFrom found no mailer")
}
ed.m.opts.From = "blog@example.com"
if ov != nil {
ed.m.source = fakeOverrides{ov: *ov}
}
return ed, ed.m.driver.(*MemoryDriver)
}
var hex64 = regexp.MustCompile(`^[0-9a-f]{64}$`)
// TestMailEditorSmoke covers what the admin layer builds on: sample values
// and placeholders, file hashes, the catalog read API, draft validation,
// preview and test send, and the index rows with reset.
func TestMailEditorSmoke(t *testing.T) {
ctx := context.Background()
t.Run("samples", func(t *testing.T) {
parsed, err := parseTemplateFile(editorWelcome, "acme.blog", editorWelcomeHTM)
if err != nil {
t.Fatal(err)
}
if want := map[string]string{"Name": "Ada", "order.code": "ZAM-1"}; !reflect.DeepEqual(parsed.samples, want) {
t.Errorf("samples = %v, want %v", parsed.samples, want)
}
if parsed.subject != "Welcome, {{ .Name }}" || parsed.description != "Sent after registration" || parsed.layout != "blog" {
t.Errorf("header = %q / %q / %q", parsed.subject, parsed.description, parsed.layout)
}
// A file without sample keys parses exactly as before.
plain, err := parseTemplateFile("acme.blog::mail.plain", "acme.blog", "Subject = \"Hi\"\nLAYOUT = 'blog'\n==\nBody.\n")
if err != nil {
t.Fatal(err)
}
if plain.subject != "Hi" || plain.layout != "blog" || plain.body != "Body." || len(plain.samples) != 0 {
t.Errorf("plain file = %+v", plain)
}
// The prefix is matched in any case; the path keeps its case.
mixed, err := parseTemplateFile("acme.blog::mail.mixed", "acme.blog", "SAMPLE.bankDetailsLines = 'x'\nsample. = \"ignored\"\n==\nBody.\n")
if err != nil {
t.Fatal(err)
}
if want := map[string]string{"bankDetailsLines": "x"}; !reflect.DeepEqual(mixed.samples, want) {
t.Errorf("samples = %v, want %v", mixed.samples, want)
}
file, ok := editorCatalog(t, editorWelcomeHTM).Template(editorWelcome)
if !ok || file.Samples["order.code"] != "ZAM-1" {
t.Errorf("TemplateFile.Samples = %v", file.Samples)
}
})
t.Run("walker", func(t *testing.T) {
render := func(src string, samples map[string]string) string {
t.Helper()
out, err := execHTMLFuncs("t", src, placeholderVars(samples, src), map[string]any{
"partial": func(name string, kv ...any) string { return "" },
})
if err != nil {
t.Fatalf("render %q: %v", src, err)
}
return out
}
samples := map[string]string{"Name": "Ada", "order.code": "ZAM-1"}
src := `{{ .Name }} {{ .order.code }} {{ if .employee.first_name }}x{{ end }} {{ range .order.items }}{{ .description }}{{ end }} {{ range .lines }}{{ . }}{{ end }} {{ with .user }}{{ .email }}{{ end }}`
if got, want := render(src, samples), "Ada ZAM-1 x [order.items.description] [lines] [user.email]"; got != want {
t.Errorf("placeholders = %q, want %q", got, want)
}
cases := map[string]struct {
src, want string
samples map[string]string
}{
"if else": {`{{ if .user }}Hi {{ .user.first_name }},{{ else }}Hi,{{ end }}`, "Hi [user.first_name],", nil},
"range fields": {"{{ range .order.items }}- {{ .description }} x {{ .count }}\n{{ end }}", "- [order.items.description] x [order.items.count]\n", nil},
"range variables": {`{{ range $i, $item := .rows }}{{ $item.name }}{{ end }}`, "[rows.name]", nil},
"range one var": {`{{ range $row := .rows }}{{ $row }}{{ end }}`, "[rows]", nil},
"range else": {`{{ range .rows }}{{ .a }}{{ else }}{{ .none }}{{ end }}`, "[rows.a]", nil},
"nested range": {`{{ range .groups }}{{ .title }}:{{ range .items }}{{ .name }}{{ end }}{{ end }}`, "[groups.title]:[groups.items.name]", nil},
"with else": {`{{ with .a.b }}{{ .c }}{{ else }}no{{ end }}`, "[a.b.c]", nil},
"with dot": {`{{ with .note }}{{ . }}{{ end }}`, "[note]", nil},
"root variable": {`{{ range .rows }}{{ $.shop }}{{ end }}`, "[shop]", nil},
"declared var": {`{{ $u := .user }}{{ $u.email }} {{ $u.name }}`, "[user.email] [user.name]", nil},
"chain": {`{{ (.user).email }}`, "[user.email]", nil},
"pipeline": {`{{ .title | printf "%s!" }}`, "[title]!", nil},
"function args": {`{{ printf "%s/%s" .a .b.c }}`, "[a]/[b.c]", nil},
"partial args": {`{{ partial "button" "url" .Link "body" .label.text }}{{ .Link }} {{ .label.text }}`, "[Link] [label.text]", nil},
"range sample": {`{{ range .lines }}{{ . }}{{ end }}`, "One", map[string]string{"lines": "One"}},
"element sample": {`{{ range .items }}{{ .name }}{{ end }}`, "Pen", map[string]string{"items.name": "Pen"}},
"unused sample": {`{{ .a }}`, "[a]", map[string]string{"b.c": "x"}},
"no variables": {`Plain.`, "Plain.", nil},
}
for name, tc := range cases {
if got := render(tc.src, tc.samples); got != tc.want {
t.Errorf("%s: %q, want %q", name, got, tc.want)
}
}
// A sample is available even when the walked sources do not use it.
vars := placeholderVars(map[string]string{"b.c": "x"}, `{{ .a }}`)
if b, ok := vars["b"].(map[string]any); !ok || b["c"] != "x" {
t.Errorf("an unused sample is missing: %v", vars)
}
// A source that does not parse contributes nothing and is not an error here.
if vars := placeholderVars(nil, `{{ .a`, `{{ .b }}`); vars["b"] != "[b]" {
t.Errorf("vars = %v", vars)
}
})
t.Run("validate", func(t *testing.T) {
ed, _ := newEditor(t, nil)
ok := Draft{Kind: KindTemplate, Name: editorWelcome, Subject: "Hi {{ .Name }}", Body: "Order {{ .order.code }} for {{ .customer.address.city }}.\n\n{{ partial \"button\" \"url\" .link \"body\" \"Go\" }}", Layout: editorBlogLayout}
if err := ed.Validate(ctx, ok); err != nil {
t.Fatalf("a valid template draft was refused: %+v", err)
}
layout := Draft{Kind: KindLayout, Name: "promo", HTML: `{{ .Content }}
`, Text: "{{ .Content }}", CSS: ".promo{margin:0}"}
partial := Draft{Kind: KindPartial, Name: editorNote, HTML: `{{ .text }}`, Text: "{{ .text }}"}
for name, d := range map[string]Draft{"layout": layout, "file layout": with(layout, func(d *Draft) { d.Name = editorBlogLayout }), "partial": partial, "empty template layout": with(ok, func(d *Draft) { d.Layout = "" }),
// Text is not a URL: prose with a scheme-like word is not refused.
"prose body": with(ok, func(d *Draft) { d.Body = "See the metadata: field." })} {
if err := ed.Validate(ctx, d); err != nil {
t.Errorf("a valid %s draft was refused: %+v", name, err)
}
}
cases := []struct {
name string
draft Draft
field, rule string
message string // substring of Message
partial string // Name
}{
{"body parse", with(ok, func(d *Draft) { d.Body = "Hi {{ .Name" }), "body", "parse", "line 1", ""},
{"subject parse", with(ok, func(d *Draft) { d.Subject = "{{ .Name" }), "subject", "parse", "", ""},
{"body render", with(ok, func(d *Draft) { d.Body = "{{ len 5 }}" }), "body", "render", "len of type int", ""},
{"body script", with(ok, func(d *Draft) { d.Body = "Hi\n\n" }), "body", "unsafe", "