/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/tests/test_smtp_connection.py

  • Committer: Jelmer Vernooij
  • Date: 2018-05-06 11:48:54 UTC
  • mto: This revision was merged to the branch mainline in revision 6960.
  • Revision ID: jelmer@jelmer.uk-20180506114854-h4qd9ojaqy8wxjsd
Move .mailmap to root.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2007, 2009, 2010, 2011 Canonical Ltd
 
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
try:
 
18
    from email.message import Message
 
19
except ImportError:  # python < 3
 
20
    from email.Message import Message
 
21
import errno
 
22
import smtplib
 
23
import socket
 
24
 
 
25
from breezy import (
 
26
    config,
 
27
    email_message,
 
28
    smtp_connection,
 
29
    tests,
 
30
    ui,
 
31
    )
 
32
 
 
33
 
 
34
def connection_refuser():
 
35
    def connect(server):
 
36
        raise socket.error(errno.ECONNREFUSED, 'Connection Refused')
 
37
    smtp = smtplib.SMTP()
 
38
    smtp.connect = connect
 
39
    return smtp
 
40
 
 
41
 
 
42
class StubSMTPFactory(object):
 
43
    """A fake SMTP connection to test the connection setup."""
 
44
    def __init__(self, fail_on=None, smtp_features=None):
 
45
        self._fail_on = fail_on or []
 
46
        self._calls = []
 
47
        self._smtp_features = smtp_features or []
 
48
        self._ehlo_called = False
 
49
 
 
50
    def __call__(self):
 
51
        # The factory pretends to be a connection
 
52
        return self
 
53
 
 
54
    def connect(self, server):
 
55
        self._calls.append(('connect', server))
 
56
 
 
57
    def helo(self):
 
58
        self._calls.append(('helo',))
 
59
        if 'helo' in self._fail_on:
 
60
            return 500, 'helo failure'
 
61
        else:
 
62
            return 200, 'helo success'
 
63
 
 
64
    def ehlo(self):
 
65
        self._calls.append(('ehlo',))
 
66
        if 'ehlo' in self._fail_on:
 
67
            return 500, 'ehlo failure'
 
68
        else:
 
69
            self._ehlo_called = True
 
70
            return 200, 'ehlo success'
 
71
 
 
72
    def has_extn(self, extension):
 
73
        self._calls.append(('has_extn', extension))
 
74
        return self._ehlo_called and extension in self._smtp_features
 
75
 
 
76
    def starttls(self):
 
77
        self._calls.append(('starttls',))
 
78
        if 'starttls' in self._fail_on:
 
79
            return 500, 'starttls failure'
 
80
        else:
 
81
            self._ehlo_called = True
 
82
            return 200, 'starttls success'
 
83
 
 
84
 
 
85
class WideOpenSMTPFactory(StubSMTPFactory):
 
86
    """A fake smtp server that implements login by accepting anybody."""
 
87
 
 
88
    def login(self, user, password):
 
89
        self._calls.append(('login', user, password))
 
90
 
 
91
 
 
92
class TestSMTPConnection(tests.TestCaseInTempDir):
 
93
 
 
94
    def get_connection(self, text, smtp_factory=None):
 
95
        my_config = config.MemoryStack(text)
 
96
        return smtp_connection.SMTPConnection(
 
97
            my_config, _smtp_factory=smtp_factory)
 
98
 
 
99
    def test_defaults(self):
 
100
        conn = self.get_connection('')
 
101
        self.assertEqual('localhost', conn._smtp_server)
 
102
        self.assertEqual(None, conn._smtp_username)
 
103
        self.assertEqual(None, conn._smtp_password)
 
104
 
 
105
    def test_smtp_server(self):
 
106
        conn = self.get_connection('smtp_server=host:10')
 
107
        self.assertEqual('host:10', conn._smtp_server)
 
108
 
 
109
    def test_missing_server(self):
 
110
        conn = self.get_connection('', smtp_factory=connection_refuser)
 
111
        self.assertRaises(smtp_connection.DefaultSMTPConnectionRefused,
 
112
                          conn._connect)
 
113
        conn = self.get_connection('smtp_server=smtp.example.com',
 
114
                                   smtp_factory=connection_refuser)
 
115
        self.assertRaises(smtp_connection.SMTPConnectionRefused, conn._connect)
 
116
 
 
117
    def test_smtp_username(self):
 
118
        conn = self.get_connection('')
 
119
        self.assertIs(None, conn._smtp_username)
 
120
 
 
121
        conn = self.get_connection('smtp_username=joebody')
 
122
        self.assertEqual(u'joebody', conn._smtp_username)
 
123
 
 
124
    def test_smtp_password_from_config(self):
 
125
        conn = self.get_connection('')
 
126
        self.assertIs(None, conn._smtp_password)
 
127
 
 
128
        conn = self.get_connection('smtp_password=mypass')
 
129
        self.assertEqual(u'mypass', conn._smtp_password)
 
130
 
 
131
    def test_smtp_password_from_user(self):
 
132
        user = 'joe'
 
133
        password = 'hispass'
 
134
        factory = WideOpenSMTPFactory()
 
135
        conn = self.get_connection('[DEFAULT]\nsmtp_username=%s\n' % user,
 
136
                                   smtp_factory=factory)
 
137
        self.assertIs(None, conn._smtp_password)
 
138
 
 
139
        ui.ui_factory = ui.CannedInputUIFactory([password])
 
140
        conn._connect()
 
141
        self.assertEqual(password, conn._smtp_password)
 
142
 
 
143
    def test_smtp_password_from_auth_config(self):
 
144
        user = 'joe'
 
145
        password = 'hispass'
 
146
        factory = WideOpenSMTPFactory()
 
147
        conn = self.get_connection('[DEFAULT]\nsmtp_username=%s\n' % user,
 
148
                                   smtp_factory=factory)
 
149
        self.assertEqual(user, conn._smtp_username)
 
150
        self.assertIs(None, conn._smtp_password)
 
151
        # Create a config file with the right password
 
152
        conf = config.AuthenticationConfig()
 
153
        conf._get_config().update({'smtptest':
 
154
                                       {'scheme': 'smtp', 'user':user,
 
155
                                        'password': password}})
 
156
        conf._save()
 
157
 
 
158
        conn._connect()
 
159
        self.assertEqual(password, conn._smtp_password)
 
160
 
 
161
    def test_authenticate_with_byte_strings(self):
 
162
        user = 'joe'
 
163
        unicode_pass = u'h\xECspass'
 
164
        utf8_pass = unicode_pass.encode('utf-8')
 
165
        factory = WideOpenSMTPFactory()
 
166
        conn = self.get_connection(
 
167
            '[DEFAULT]\nsmtp_username=%s\nsmtp_password=%s\n'
 
168
            % (user, utf8_pass), smtp_factory=factory)
 
169
        self.assertEqual(unicode_pass, conn._smtp_password)
 
170
        conn._connect()
 
171
        self.assertEqual([('connect', 'localhost'),
 
172
                          ('ehlo',),
 
173
                          ('has_extn', 'starttls'),
 
174
                          ('login', user, utf8_pass)], factory._calls)
 
175
        smtp_username, smtp_password = factory._calls[-1][1:]
 
176
        self.assertIsInstance(smtp_username, str)
 
177
        self.assertIsInstance(smtp_password, str)
 
178
 
 
179
    def test_create_connection(self):
 
180
        factory = StubSMTPFactory()
 
181
        conn = self.get_connection('', smtp_factory=factory)
 
182
        conn._create_connection()
 
183
        self.assertEqual([('connect', 'localhost'),
 
184
                          ('ehlo',),
 
185
                          ('has_extn', 'starttls')], factory._calls)
 
186
 
 
187
    def test_create_connection_ehlo_fails(self):
 
188
        # Check that we call HELO if EHLO failed.
 
189
        factory = StubSMTPFactory(fail_on=['ehlo'])
 
190
        conn = self.get_connection('', smtp_factory=factory)
 
191
        conn._create_connection()
 
192
        self.assertEqual([('connect', 'localhost'),
 
193
                          ('ehlo',),
 
194
                          ('helo',),
 
195
                          ('has_extn', 'starttls')], factory._calls)
 
196
 
 
197
    def test_create_connection_ehlo_helo_fails(self):
 
198
        # Check that we raise an exception if both EHLO and HELO fail.
 
199
        factory = StubSMTPFactory(fail_on=['ehlo', 'helo'])
 
200
        conn = self.get_connection('', smtp_factory=factory)
 
201
        self.assertRaises(smtp_connection.SMTPError, conn._create_connection)
 
202
        self.assertEqual([('connect', 'localhost'),
 
203
                          ('ehlo',),
 
204
                          ('helo',)], factory._calls)
 
205
 
 
206
    def test_create_connection_starttls(self):
 
207
        # Check that STARTTLS plus a second EHLO are called if the
 
208
        # server says it supports the feature.
 
209
        factory = StubSMTPFactory(smtp_features=['starttls'])
 
210
        conn = self.get_connection('', smtp_factory=factory)
 
211
        conn._create_connection()
 
212
        self.assertEqual([('connect', 'localhost'),
 
213
                          ('ehlo',),
 
214
                          ('has_extn', 'starttls'),
 
215
                          ('starttls',),
 
216
                          ('ehlo',)], factory._calls)
 
217
 
 
218
    def test_create_connection_starttls_fails(self):
 
219
        # Check that we raise an exception if the server claims to
 
220
        # support STARTTLS, but then fails when we try to activate it.
 
221
        factory = StubSMTPFactory(fail_on=['starttls'],
 
222
                                  smtp_features=['starttls'])
 
223
        conn = self.get_connection('', smtp_factory=factory)
 
224
        self.assertRaises(smtp_connection.SMTPError, conn._create_connection)
 
225
        self.assertEqual([('connect', 'localhost'),
 
226
                          ('ehlo',),
 
227
                          ('has_extn', 'starttls'),
 
228
                          ('starttls',)], factory._calls)
 
229
 
 
230
    def test_get_message_addresses(self):
 
231
        msg = Message()
 
232
 
 
233
        from_, to = smtp_connection.SMTPConnection.get_message_addresses(msg)
 
234
        self.assertEqual('', from_)
 
235
        self.assertEqual([], to)
 
236
 
 
237
        msg['From'] = '"J. Random Developer" <jrandom@example.com>'
 
238
        msg['To'] = 'John Doe <john@doe.com>, Jane Doe <jane@doe.com>'
 
239
        msg['CC'] = u'Pepe P\xe9rez <pperez@ejemplo.com>'
 
240
        msg['Bcc'] = 'user@localhost'
 
241
 
 
242
        from_, to = smtp_connection.SMTPConnection.get_message_addresses(msg)
 
243
        self.assertEqual('jrandom@example.com', from_)
 
244
        self.assertEqual(sorted(['john@doe.com', 'jane@doe.com',
 
245
            'pperez@ejemplo.com', 'user@localhost']), sorted(to))
 
246
 
 
247
        # now with breezy's EmailMessage
 
248
        msg = email_message.EmailMessage(
 
249
            '"J. Random Developer" <jrandom@example.com>',
 
250
            ['John Doe <john@doe.com>', 'Jane Doe <jane@doe.com>',
 
251
             u'Pepe P\xe9rez <pperez@ejemplo.com>', 'user@localhost' ],
 
252
            'subject')
 
253
 
 
254
        from_, to = smtp_connection.SMTPConnection.get_message_addresses(msg)
 
255
        self.assertEqual('jrandom@example.com', from_)
 
256
        self.assertEqual(sorted(['john@doe.com', 'jane@doe.com',
 
257
            'pperez@ejemplo.com', 'user@localhost']), sorted(to))
 
258
 
 
259
    def test_destination_address_required(self):
 
260
        msg = Message()
 
261
        msg['From'] = '"J. Random Developer" <jrandom@example.com>'
 
262
        self.assertRaises(
 
263
            smtp_connection.NoDestinationAddress,
 
264
            smtp_connection.SMTPConnection(config.MemoryStack("")
 
265
                                           ).send_email, msg)
 
266
 
 
267
        msg = email_message.EmailMessage('from@from.com', '', 'subject')
 
268
        self.assertRaises(
 
269
            smtp_connection.NoDestinationAddress,
 
270
            smtp_connection.SMTPConnection(config.MemoryStack("")
 
271
                                           ).send_email, msg)
 
272
 
 
273
        msg = email_message.EmailMessage('from@from.com', [], 'subject')
 
274
        self.assertRaises(
 
275
            smtp_connection.NoDestinationAddress,
 
276
            smtp_connection.SMTPConnection(config.MemoryStack("")
 
277
                                           ).send_email, msg)