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, "") return content, true } var logoSpan = regexp.MustCompile(`]*>([^<]*)`) 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
]*>([^<]*)
`) // 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, "