1 package mail
2
3 import (
4 "net/smtp"
5 "testing"
6 )
7
8 const (
9 testUser = "user"
10 testPwd = "pwd"
11 testHost = "smtp.example.com"
12 )
13
14 type authTest struct {
15 auths []string
16 challenges []string
17 tls bool
18 wantData []string
19 wantError bool
20 }
21
22 func TestNoAdvertisement(t *testing.T) {
23 testLoginAuth(t, &authTest{
24 auths: []string{},
25 tls: false,
26 wantError: true,
27 })
28 }
29
30 func TestNoAdvertisementTLS(t *testing.T) {
31 testLoginAuth(t, &authTest{
32 auths: []string{},
33 challenges: []string{"Username:", "Password:"},
34 tls: true,
35 wantData: []string{"", testUser, testPwd},
36 })
37 }
38
39 func TestLogin(t *testing.T) {
40 testLoginAuth(t, &authTest{
41 auths: []string{"PLAIN", "LOGIN"},
42 challenges: []string{"Username:", "Password:"},
43 tls: false,
44 wantData: []string{"", testUser, testPwd},
45 })
46 }
47
48 func TestLoginTLS(t *testing.T) {
49 testLoginAuth(t, &authTest{
50 auths: []string{"LOGIN"},
51 challenges: []string{"Username:", "Password:"},
52 tls: true,
53 wantData: []string{"", testUser, testPwd},
54 })
55 }
56
57 func testLoginAuth(t *testing.T, test *authTest) {
58 auth := &loginAuth{
59 username: testUser,
60 password: testPwd,
61 host: testHost,
62 }
63 server := &smtp.ServerInfo{
64 Name: testHost,
65 TLS: test.tls,
66 Auth: test.auths,
67 }
68 proto, toServer, err := auth.Start(server)
69 if err != nil && !test.wantError {
70 t.Fatalf("loginAuth.Start(): %v", err)
71 }
72 if err != nil && test.wantError {
73 return
74 }
75 if proto != "LOGIN" {
76 t.Errorf("invalid protocol, got %q, want LOGIN", proto)
77 }
78
79 i := 0
80 got := string(toServer)
81 if got != test.wantData[i] {
82 t.Errorf("Invalid response, got %q, want %q", got, test.wantData[i])
83 }
84
85 for _, challenge := range test.challenges {
86 i++
87 if i >= len(test.wantData) {
88 t.Fatalf("unexpected challenge: %q", challenge)
89 }
90
91 toServer, err = auth.Next([]byte(challenge), true)
92 if err != nil {
93 t.Fatalf("loginAuth.Auth(): %v", err)
94 }
95 got = string(toServer)
96 if got != test.wantData[i] {
97 t.Errorf("Invalid response, got %q, want %q", got, test.wantData[i])
98 }
99 }
100 }
101
View as plain text