/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2535.2.5 by Adeodato Simó
Fix copyright statement not to contain "by".
1
# Copyright (C) 2005, 2007 Canonical Ltd
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
17
from cStringIO import StringIO
18
from email.Message import Message
2694.2.1 by Aaron Bentley
Make error handling nicer when SMTP server not working
19
import errno
20
import smtplib
21
import socket
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
22
2694.2.1 by Aaron Bentley
Make error handling nicer when SMTP server not working
23
from bzrlib import (
24
    config,
25
    errors,
26
    )
2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
27
from bzrlib.email_message import EmailMessage
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
28
from bzrlib.errors import NoDestinationAddress
29
from bzrlib.tests import TestCase
30
from bzrlib.smtp_connection import SMTPConnection
31
32
2694.2.1 by Aaron Bentley
Make error handling nicer when SMTP server not working
33
def connection_refuser():
34
    def connect(server):
35
        raise socket.error(errno.ECONNREFUSED, 'Connection Refused')
36
    smtp = smtplib.SMTP()
37
    smtp.connect = connect
38
    return smtp
39
40
2898.2.2 by James Henstridge
Fix test helper class naming, per John's review comments.
41
class StubSMTPFactory(object):
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
42
    """A fake SMTP connection to test the connection setup."""
43
    def __init__(self, fail_on=None, smtp_features=None):
44
        self._fail_on = fail_on or []
45
        self._calls = []
46
        self._smtp_features = smtp_features or []
47
        self._ehlo_called = False
48
49
    def __call__(self):
50
        # The factory pretends to be a connection
51
        return self
52
53
    def connect(self, server):
54
        self._calls.append(('connect', server))
55
56
    def helo(self):
57
        self._calls.append(('helo',))
58
        if 'helo' in self._fail_on:
59
            return 500, 'helo failure'
60
        else:
61
            return 200, 'helo success'
62
63
    def ehlo(self):
64
        self._calls.append(('ehlo',))
65
        if 'ehlo' in self._fail_on:
66
            return 500, 'ehlo failure'
67
        else:
68
            self._ehlo_called = True
69
            return 200, 'ehlo success'
70
71
    def has_extn(self, extension):
72
        self._calls.append(('has_extn', extension))
73
        return self._ehlo_called and extension in self._smtp_features
74
75
    def starttls(self):
76
        self._calls.append(('starttls',))
77
        if 'starttls' in self._fail_on:
78
            return 500, 'starttls failure'
79
        else:
80
            self._ehlo_called = True
81
            return 200, 'starttls success'
82
83
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
84
class TestSMTPConnection(TestCase):
85
2694.2.1 by Aaron Bentley
Make error handling nicer when SMTP server not working
86
    def get_connection(self, text, smtp_factory=None):
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
87
        my_config = config.GlobalConfig()
88
        config_file = StringIO(text)
89
        my_config._get_parser(config_file)
2694.2.1 by Aaron Bentley
Make error handling nicer when SMTP server not working
90
        return SMTPConnection(my_config, _smtp_factory=smtp_factory)
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
91
92
    def test_defaults(self):
93
        conn = self.get_connection('')
94
        self.assertEqual('localhost', conn._smtp_server)
95
        self.assertEqual(None, conn._smtp_username)
96
        self.assertEqual(None, conn._smtp_password)
97
98
    def test_smtp_server(self):
99
        conn = self.get_connection('[DEFAULT]\nsmtp_server=host:10\n')
100
        self.assertEqual('host:10', conn._smtp_server)
101
2694.2.1 by Aaron Bentley
Make error handling nicer when SMTP server not working
102
    def test_missing_server(self):
103
        conn = self.get_connection('', smtp_factory=connection_refuser)
104
        self.assertRaises(errors.DefaultSMTPConnectionRefused, conn._connect)
105
        conn = self.get_connection('[DEFAULT]\nsmtp_server=smtp.example.com\n',
106
                                   smtp_factory=connection_refuser)
107
        self.assertRaises(errors.SMTPConnectionRefused, conn._connect)
108
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
109
    def test_smtp_username(self):
110
        conn = self.get_connection('')
111
        self.assertIs(None, conn._smtp_username)
112
113
        conn = self.get_connection('[DEFAULT]\nsmtp_username=joebody\n')
114
        self.assertEqual(u'joebody', conn._smtp_username)
115
116
    def test_smtp_password(self):
117
        conn = self.get_connection('')
118
        self.assertIs(None, conn._smtp_password)
119
120
        conn = self.get_connection('[DEFAULT]\nsmtp_password=mypass\n')
121
        self.assertEqual(u'mypass', conn._smtp_password)
122
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
123
    def test_create_connection(self):
2898.2.2 by James Henstridge
Fix test helper class naming, per John's review comments.
124
        factory = StubSMTPFactory()
125
        conn = self.get_connection('', smtp_factory=factory)
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
126
        conn._create_connection()
127
        self.assertEqual([('connect', 'localhost'),
128
                          ('ehlo',),
2898.2.2 by James Henstridge
Fix test helper class naming, per John's review comments.
129
                          ('has_extn', 'starttls')], factory._calls)
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
130
131
    def test_create_connection_ehlo_fails(self):
132
        # Check that we call HELO if EHLO failed.
2898.2.2 by James Henstridge
Fix test helper class naming, per John's review comments.
133
        factory = StubSMTPFactory(fail_on=['ehlo'])
134
        conn = self.get_connection('', smtp_factory=factory)
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
135
        conn._create_connection()
136
        self.assertEqual([('connect', 'localhost'),
137
                          ('ehlo',),
138
                          ('helo',),
2898.2.2 by James Henstridge
Fix test helper class naming, per John's review comments.
139
                          ('has_extn', 'starttls')], factory._calls)
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
140
141
    def test_create_connection_ehlo_helo_fails(self):
142
        # Check that we raise an exception if both EHLO and HELO fail.
2898.2.2 by James Henstridge
Fix test helper class naming, per John's review comments.
143
        factory = StubSMTPFactory(fail_on=['ehlo', 'helo'])
144
        conn = self.get_connection('', smtp_factory=factory)
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
145
        self.assertRaises(errors.SMTPError, conn._create_connection)
146
        self.assertEqual([('connect', 'localhost'),
147
                          ('ehlo',),
2898.2.2 by James Henstridge
Fix test helper class naming, per John's review comments.
148
                          ('helo',)], factory._calls)
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
149
150
    def test_create_connection_starttls(self):
151
        # Check that STARTTLS plus a second EHLO are called if the
152
        # server says it supports the feature.
2898.2.2 by James Henstridge
Fix test helper class naming, per John's review comments.
153
        factory = StubSMTPFactory(smtp_features=['starttls'])
154
        conn = self.get_connection('', smtp_factory=factory)
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
155
        conn._create_connection()
156
        self.assertEqual([('connect', 'localhost'),
157
                          ('ehlo',),
158
                          ('has_extn', 'starttls'),
159
                          ('starttls',),
2898.2.2 by James Henstridge
Fix test helper class naming, per John's review comments.
160
                          ('ehlo',)], factory._calls)
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
161
162
    def test_create_connection_starttls_fails(self):
163
        # Check that we raise an exception if the server claims to
164
        # support STARTTLS, but then fails when we try to activate it.
2898.2.2 by James Henstridge
Fix test helper class naming, per John's review comments.
165
        factory = StubSMTPFactory(fail_on=['starttls'],
166
                                  smtp_features=['starttls'])
167
        conn = self.get_connection('', smtp_factory=factory)
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
168
        self.assertRaises(errors.SMTPError, conn._create_connection)
169
        self.assertEqual([('connect', 'localhost'),
170
                          ('ehlo',),
171
                          ('has_extn', 'starttls'),
2898.2.2 by James Henstridge
Fix test helper class naming, per John's review comments.
172
                          ('starttls',)], factory._calls)
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
173
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
174
    def test_get_message_addresses(self):
175
        msg = Message()
176
177
        from_, to = SMTPConnection.get_message_addresses(msg)
178
        self.assertEqual('', from_)
179
        self.assertEqual([], to)
180
181
        msg['From'] = '"J. Random Developer" <jrandom@example.com>'
182
        msg['To'] = 'John Doe <john@doe.com>, Jane Doe <jane@doe.com>'
183
        msg['CC'] = u'Pepe P\xe9rez <pperez@ejemplo.com>'
184
        msg['Bcc'] = 'user@localhost'
185
186
        from_, to = SMTPConnection.get_message_addresses(msg)
187
        self.assertEqual('jrandom@example.com', from_)
188
        self.assertEqual(sorted(['john@doe.com', 'jane@doe.com',
189
            'pperez@ejemplo.com', 'user@localhost']), sorted(to))
190
2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
191
        # now with bzrlib's EmailMessage
192
        msg = EmailMessage('"J. Random Developer" <jrandom@example.com>', [
193
            'John Doe <john@doe.com>', 'Jane Doe <jane@doe.com>',
194
            u'Pepe P\xe9rez <pperez@ejemplo.com>', 'user@localhost' ],
195
            'subject')
196
197
        from_, to = SMTPConnection.get_message_addresses(msg)
198
        self.assertEqual('jrandom@example.com', from_)
199
        self.assertEqual(sorted(['john@doe.com', 'jane@doe.com',
200
            'pperez@ejemplo.com', 'user@localhost']), sorted(to))
201
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
202
    def test_destination_address_required(self):
203
        class FakeConfig:
204
            def get_user_option(self, option):
205
                return None
206
207
        msg = Message()
208
        msg['From'] = '"J. Random Developer" <jrandom@example.com>'
209
        self.assertRaises(NoDestinationAddress,
210
                SMTPConnection(FakeConfig()).send_email, msg)
2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
211
212
        msg = EmailMessage('from@from.com', '', 'subject')
213
        self.assertRaises(NoDestinationAddress,
214
                SMTPConnection(FakeConfig()).send_email, msg)
215
216
        msg = EmailMessage('from@from.com', [], 'subject')
217
        self.assertRaises(NoDestinationAddress,
218
                SMTPConnection(FakeConfig()).send_email, msg)