-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsmtp_parse_test.go
125 lines (112 loc) · 2.63 KB
/
smtp_parse_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package main
import (
"fmt"
"bytes"
"io"
"net"
"strings"
"testing"
)
type MockConn struct {
net.Conn
buf *bytes.Buffer
}
func (conn *MockConn) Read(dst []byte) (int, error) {
n, e := conn.buf.Read(dst)
return n, e
}
func (conn *MockConn) Write(src []byte) (int, error) {
return len(src), nil
}
func (conn *MockConn) Close() error {
return nil
}
type SmtpParseTest struct {
rawData []byte
expectMail *Mail
expectErr error
}
func newSmtpParseTestWithLines(lines []string, expectMail *Mail, expectErr error) SmtpParseTest {
lines = append(lines, "")
rawData := []byte(strings.Join(lines, "\r\n"))
return SmtpParseTest{
rawData: rawData,
expectMail: expectMail,
expectErr: expectErr,
}
}
func TestSmtpParse(t *testing.T) {
tests := []SmtpParseTest{
newSmtpParseTestWithLines(
[]string{
"HELO localhost",
"MAIL FROM:<send@example.com>",
"RCPT TO:<recv@example.com>",
"DATA",
"From: Sender Name <send@example.com>",
"Content-Type: text/html; charset=UTF-8",
"Subject: Plain ASCII Subject Test",
"",
"This is a test",
".",
},
&Mail{
Recver: "recv@example.com",
ContentType: "text/html; charset=UTF-8",
SenderName: "Sender Name",
Subject: "Plain ASCII Subject Test",
Content: "This is a test",
},
nil,
),
newSmtpParseTestWithLines(
[]string{
"HELO localhost",
"MAIL FROM:<send2@example.com>",
"RCPT TO:<recv2@example.com>",
"DATA",
"From: =?UTF-8?B?5Y+R6YCB6ICF?= <send2@example.com>",
"Content-Type: text/html; charset=UTF-8",
"Subject: =?UTF-8?B?VVRGLTgg5rWL6K+V?=",
"",
"这是一条带有中文 UTF-8 邮件正文测试",
"并且它有多行",
".",
},
&Mail{
Recver: "recv2@example.com",
ContentType: "text/html; charset=UTF-8",
SenderName: "发送者",
Subject: "UTF-8 测试",
Content: "这是一条带有中文 UTF-8 邮件正文测试\r\n并且它有多行",
},
nil,
),
newSmtpParseTestWithLines(
[]string{
"HELO",
},
nil,
io.EOF,
),
}
for i, test := range tests {
succ, errMsg := testSmtpParseSingle(test)
if !succ {
t.Errorf("#%d test failed: %s", i, errMsg)
}
}
}
func testSmtpParseSingle(test SmtpParseTest) (bool, string) {
conn := &MockConn{
buf: bytes.NewBuffer(bytes.Clone(test.rawData)),
}
gotMail, gotErr := ParseSmtp(conn)
if gotErr != test.expectErr {
return false, fmt.Sprintf("expect err: %+v; got err: %+v", test.expectErr, gotErr)
}
if gotErr == nil && *gotMail != *test.expectMail {
return false, fmt.Sprintf("expect mail: %+v; parsed mail: %+v", test.expectMail, gotMail)
}
return true, ""
}