Go · 2697 bytes Raw Blame History
1 // SPDX-License-Identifier: AGPL-3.0-or-later
2
3 package email
4
5 import (
6 "bytes"
7 "context"
8 "strings"
9 "testing"
10 )
11
12 func TestEnvelopeAddress_StripsDisplayName(t *testing.T) {
13 t.Parallel()
14 cases := []struct{ in, want string }{
15 {"shithub <noreply@shithub.local>", "noreply@shithub.local"},
16 {"<bare@example.com>", "bare@example.com"},
17 {"plain@example.com", "plain@example.com"},
18 {"Name With Spaces <a@b>", "a@b"},
19 {"malformed <still works", "malformed <still works"},
20 }
21 for _, c := range cases {
22 if got := envelopeAddress(c.in); got != c.want {
23 t.Errorf("envelopeAddress(%q): want %q, got %q", c.in, c.want, got)
24 }
25 }
26 }
27
28 func TestStdoutSender_WritesBothBodies(t *testing.T) {
29 t.Parallel()
30 var buf bytes.Buffer
31 s := NewStdoutSender(&buf)
32 if err := s.Send(context.Background(), Message{
33 From: "noreply@x", To: "alice@x", Subject: "hi",
34 HTML: "<b>hi</b>", Text: "hi",
35 }); err != nil {
36 t.Fatalf("Send: %v", err)
37 }
38 out := buf.String()
39 for _, want := range []string{"From: noreply@x", "To: alice@x", "Subject: hi", "[text]", "[html]", "<b>hi</b>"} {
40 if !strings.Contains(out, want) {
41 t.Errorf("missing %q in output:\n%s", want, out)
42 }
43 }
44 }
45
46 func TestVerifyMessage_RendersBothBodies(t *testing.T) {
47 t.Parallel()
48 b := Branding{SiteName: "shithub", BaseURL: "https://example", From: "noreply@example"}
49 m, err := VerifyMessage(b, "alice@example", "alice", "TOKEN-XYZ")
50 if err != nil {
51 t.Fatalf("VerifyMessage: %v", err)
52 }
53 for _, body := range []string{m.HTML, m.Text} {
54 if !strings.Contains(body, "https://example/verify-email/TOKEN-XYZ") {
55 t.Errorf("verify body missing link: %s", body)
56 }
57 if !strings.Contains(body, "shithub") {
58 t.Errorf("verify body missing site name")
59 }
60 }
61 if m.Subject == "" || m.From != "noreply@example" || m.To != "alice@example" {
62 t.Fatalf("envelope wrong: %+v", m)
63 }
64 }
65
66 func TestResetMessage_RendersBothBodies(t *testing.T) {
67 t.Parallel()
68 b := Branding{SiteName: "shithub", BaseURL: "https://example", From: "noreply@example"}
69 m, err := ResetMessage(b, "alice@example", "T")
70 if err != nil {
71 t.Fatalf("ResetMessage: %v", err)
72 }
73 for _, body := range []string{m.HTML, m.Text} {
74 if !strings.Contains(body, "https://example/password/reset/T") {
75 t.Errorf("reset body missing link: %s", body)
76 }
77 }
78 }
79
80 func TestBuildMultipart_StructureSane(t *testing.T) {
81 t.Parallel()
82 body := buildMultipart(Message{From: "f", To: "t", Subject: "s", HTML: "H", Text: "T"})
83 out := string(body)
84 for _, want := range []string{
85 "From: f", "To: t", "Subject: s",
86 "multipart/alternative", "text/plain", "text/html",
87 "H", "T",
88 } {
89 if !strings.Contains(out, want) {
90 t.Errorf("missing %q in:\n%s", want, out)
91 }
92 }
93 }
94