...
1 package mail
2
3 import (
4 "bytes"
5 "errors"
6 "io"
7 "reflect"
8 "testing"
9 )
10
11 const (
12 testTo1 = "to1@example.com"
13 testTo2 = "to2@example.com"
14 testFrom = "from@example.com"
15 testBody = "Test message"
16 testMsg = "To: " + testTo1 + ", " + testTo2 + "\r\n" +
17 "From: " + testFrom + "\r\n" +
18 "MIME-Version: 1.0\r\n" +
19 "Date: Wed, 25 Jun 2014 17:46:00 +0000\r\n" +
20 "Content-Type: text/plain; charset=UTF-8\r\n" +
21 "Content-Transfer-Encoding: quoted-printable\r\n" +
22 "\r\n" +
23 testBody
24 )
25
26 type mockSender SendFunc
27
28 func (s mockSender) Send(from string, to []string, msg io.WriterTo) error {
29 return s(from, to, msg)
30 }
31
32 type mockSendCloser struct {
33 mockSender
34 close func() error
35 }
36
37 func (s *mockSendCloser) Close() error {
38 return s.close()
39 }
40
41 func TestSend(t *testing.T) {
42 s := &mockSendCloser{
43 mockSender: stubSend(t, testFrom, []string{testTo1, testTo2}, testMsg),
44 close: func() error {
45 t.Error("Close() should not be called in Send()")
46 return nil
47 },
48 }
49 if err := Send(s, getTestMessage()); err != nil {
50 t.Errorf("Send(): %v", err)
51 }
52 }
53
54 func TestSendError(t *testing.T) {
55 s := &mockSendCloser{
56 mockSender: func(_ string, _ []string, _ io.WriterTo) error {
57 return errors.New("kaboom")
58 },
59 }
60 wantErr := "gomail: could not send email 1: kaboom"
61 if err := Send(s, getTestMessage()); err == nil || err.Error() != wantErr {
62 t.Errorf("expected Send() error, got %q, want %q", err, wantErr)
63 }
64 }
65
66 func getTestMessage() *Message {
67 m := NewMessage()
68 m.SetHeader("From", testFrom)
69 m.SetHeader("To", testTo1, testTo2)
70 m.SetBody("text/plain", testBody)
71
72 return m
73 }
74
75 func stubSend(t *testing.T, wantFrom string, wantTo []string, wantBody string) mockSender {
76 return func(from string, to []string, msg io.WriterTo) error {
77 if from != wantFrom {
78 t.Errorf("invalid from, got %q, want %q", from, wantFrom)
79 }
80 if !reflect.DeepEqual(to, wantTo) {
81 t.Errorf("invalid to, got %v, want %v", to, wantTo)
82 }
83
84 buf := new(bytes.Buffer)
85 _, err := msg.WriteTo(buf)
86 if err != nil {
87 t.Fatal(err)
88 }
89 compareBodies(t, buf.String(), wantBody)
90
91 return nil
92 }
93 }
94
View as plain text