summaryrefslogtreecommitdiffstats
path: root/vendor/gopkg.in/gomail.v2/auth_test.go
blob: 428ef3467cb03f99f6ce485973cb17a5e0f0e199 (plain)
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
package gomail

import (
	"net/smtp"
	"testing"
)

const (
	testUser = "user"
	testPwd  = "pwd"
	testHost = "smtp.example.com"
)

type authTest struct {
	auths      []string
	challenges []string
	tls        bool
	wantData   []string
	wantError  bool
}

func TestNoAdvertisement(t *testing.T) {
	testLoginAuth(t, &authTest{
		auths:     []string{},
		tls:       false,
		wantError: true,
	})
}

func TestNoAdvertisementTLS(t *testing.T) {
	testLoginAuth(t, &authTest{
		auths:      []string{},
		challenges: []string{"Username:", "Password:"},
		tls:        true,
		wantData:   []string{"", testUser, testPwd},
	})
}

func TestLogin(t *testing.T) {
	testLoginAuth(t, &authTest{
		auths:      []string{"PLAIN", "LOGIN"},
		challenges: []string{"Username:", "Password:"},
		tls:        false,
		wantData:   []string{"", testUser, testPwd},
	})
}

func TestLoginTLS(t *testing.T) {
	testLoginAuth(t, &authTest{
		auths:      []string{"LOGIN"},
		challenges: []string{"Username:", "Password:"},
		tls:        true,
		wantData:   []string{"", testUser, testPwd},
	})
}

func testLoginAuth(t *testing.T, test *authTest) {
	auth := &loginAuth{
		username: testUser,
		password: testPwd,
		host:     testHost,
	}
	server := &smtp.ServerInfo{
		Name: testHost,
		TLS:  test.tls,
		Auth: test.auths,
	}
	proto, toServer, err := auth.Start(server)
	if err != nil && !test.wantError {
		t.Fatalf("loginAuth.Start(): %v", err)
	}
	if err != nil && test.wantError {
		return
	}
	if proto != "LOGIN" {
		t.Errorf("invalid protocol, got %q, want LOGIN", proto)
	}

	i := 0
	got := string(toServer)
	if got != test.wantData[i] {
		t.Errorf("Invalid response, got %q, want %q", got, test.wantData[i])
	}

	for _, challenge := range test.challenges {
		i++
		if i >= len(test.wantData) {
			t.Fatalf("unexpected challenge: %q", challenge)
		}

		toServer, err = auth.Next([]byte(challenge), true)
		if err != nil {
			t.Fatalf("loginAuth.Auth(): %v", err)
		}
		got = string(toServer)
		if got != test.wantData[i] {
			t.Errorf("Invalid response, got %q, want %q", got, test.wantData[i])
		}
	}
}