/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: 2020-04-05 19:11:34 UTC
  • mto: (7490.7.16 work)
  • mto: This revision was merged to the branch mainline in revision 7501.
  • Revision ID: jelmer@jelmer.uk-20200405191134-0aebh8ikiwygxma5
Populate the .gitignore file.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2007, 2009 Canonical Ltd
 
1
# Copyright (C) 2007, 2009, 2010, 2011 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
 
from cStringIO import StringIO
18
 
from email.Message import Message
 
17
try:
 
18
    from email.message import Message
 
19
except ImportError:  # python < 3
 
20
    from email.Message import Message
19
21
import errno
20
22
import smtplib
21
23
import socket
22
24
 
23
 
from bzrlib import (
 
25
from breezy import (
24
26
    config,
25
27
    email_message,
26
 
    errors,
27
28
    smtp_connection,
28
29
    tests,
29
30
    ui,
40
41
 
41
42
class StubSMTPFactory(object):
42
43
    """A fake SMTP connection to test the connection setup."""
 
44
 
43
45
    def __init__(self, fail_on=None, smtp_features=None):
44
46
        self._fail_on = fail_on or []
45
47
        self._calls = []
91
93
class TestSMTPConnection(tests.TestCaseInTempDir):
92
94
 
93
95
    def get_connection(self, text, smtp_factory=None):
94
 
        my_config = config.GlobalConfig()
95
 
        config_file = StringIO(text)
96
 
        my_config._get_parser(config_file)
97
 
        return smtp_connection.SMTPConnection(my_config,
98
 
                                              _smtp_factory=smtp_factory)
 
96
        my_config = config.MemoryStack(text)
 
97
        return smtp_connection.SMTPConnection(
 
98
            my_config, _smtp_factory=smtp_factory)
99
99
 
100
100
    def test_defaults(self):
101
 
        conn = self.get_connection('')
 
101
        conn = self.get_connection(b'')
102
102
        self.assertEqual('localhost', conn._smtp_server)
103
103
        self.assertEqual(None, conn._smtp_username)
104
104
        self.assertEqual(None, conn._smtp_password)
105
105
 
106
106
    def test_smtp_server(self):
107
 
        conn = self.get_connection('[DEFAULT]\nsmtp_server=host:10\n')
 
107
        conn = self.get_connection(b'smtp_server=host:10')
108
108
        self.assertEqual('host:10', conn._smtp_server)
109
109
 
110
110
    def test_missing_server(self):
111
 
        conn = self.get_connection('', smtp_factory=connection_refuser)
112
 
        self.assertRaises(errors.DefaultSMTPConnectionRefused, conn._connect)
113
 
        conn = self.get_connection('[DEFAULT]\nsmtp_server=smtp.example.com\n',
 
111
        conn = self.get_connection(b'', smtp_factory=connection_refuser)
 
112
        self.assertRaises(smtp_connection.DefaultSMTPConnectionRefused,
 
113
                          conn._connect)
 
114
        conn = self.get_connection(b'smtp_server=smtp.example.com',
114
115
                                   smtp_factory=connection_refuser)
115
 
        self.assertRaises(errors.SMTPConnectionRefused, conn._connect)
 
116
        self.assertRaises(smtp_connection.SMTPConnectionRefused, conn._connect)
116
117
 
117
118
    def test_smtp_username(self):
118
 
        conn = self.get_connection('')
 
119
        conn = self.get_connection(b'')
119
120
        self.assertIs(None, conn._smtp_username)
120
121
 
121
 
        conn = self.get_connection('[DEFAULT]\nsmtp_username=joebody\n')
 
122
        conn = self.get_connection(b'smtp_username=joebody')
122
123
        self.assertEqual(u'joebody', conn._smtp_username)
123
124
 
124
125
    def test_smtp_password_from_config(self):
125
 
        conn = self.get_connection('')
 
126
        conn = self.get_connection(b'')
126
127
        self.assertIs(None, conn._smtp_password)
127
128
 
128
 
        conn = self.get_connection('[DEFAULT]\nsmtp_password=mypass\n')
 
129
        conn = self.get_connection(b'smtp_password=mypass')
129
130
        self.assertEqual(u'mypass', conn._smtp_password)
130
131
 
131
132
    def test_smtp_password_from_user(self):
132
133
        user = 'joe'
133
134
        password = 'hispass'
134
135
        factory = WideOpenSMTPFactory()
135
 
        conn = self.get_connection('[DEFAULT]\nsmtp_username=%s\n' % user,
136
 
                                   smtp_factory=factory)
 
136
        conn = self.get_connection(
 
137
            b'[DEFAULT]\nsmtp_username=%s\n' % user.encode('ascii'),
 
138
            smtp_factory=factory)
137
139
        self.assertIs(None, conn._smtp_password)
138
140
 
139
141
        ui.ui_factory = ui.CannedInputUIFactory([password])
144
146
        user = 'joe'
145
147
        password = 'hispass'
146
148
        factory = WideOpenSMTPFactory()
147
 
        conn = self.get_connection('[DEFAULT]\nsmtp_username=%s\n' % user,
148
 
                                   smtp_factory=factory)
 
149
        conn = self.get_connection(
 
150
            b'[DEFAULT]\nsmtp_username=%s\n' % user.encode('ascii'),
 
151
            smtp_factory=factory)
149
152
        self.assertEqual(user, conn._smtp_username)
150
153
        self.assertIs(None, conn._smtp_password)
151
154
        # Create a config file with the right password
152
155
        conf = config.AuthenticationConfig()
153
156
        conf._get_config().update({'smtptest':
154
 
                                       {'scheme': 'smtp', 'user':user,
155
 
                                        'password': password}})
 
157
                                   {'scheme': 'smtp', 'user': user,
 
158
                                    'password': password}})
156
159
        conf._save()
157
160
 
158
161
        conn._connect()
159
162
        self.assertEqual(password, conn._smtp_password)
160
163
 
161
164
    def test_authenticate_with_byte_strings(self):
162
 
        user = 'joe'
163
 
        password = 'h\xC3\xACspass'
 
165
        user = b'joe'
 
166
        unicode_pass = u'h\xECspass'
 
167
        utf8_pass = unicode_pass.encode('utf-8')
164
168
        factory = WideOpenSMTPFactory()
165
169
        conn = self.get_connection(
166
 
            '[DEFAULT]\nsmtp_username=%s\nsmtp_password=%s\n'
167
 
            % (user, password), smtp_factory=factory)
168
 
        self.assertEqual(u'h\xECspass', conn._smtp_password)
 
170
            b'[DEFAULT]\nsmtp_username=%s\nsmtp_password=%s\n'
 
171
            % (user, utf8_pass), smtp_factory=factory)
 
172
        self.assertEqual(unicode_pass, conn._smtp_password)
169
173
        conn._connect()
170
174
        self.assertEqual([('connect', 'localhost'),
171
175
                          ('ehlo',),
172
176
                          ('has_extn', 'starttls'),
173
 
                          ('login', user, password)], factory._calls)
 
177
                          ('login', user, utf8_pass)], factory._calls)
174
178
        smtp_username, smtp_password = factory._calls[-1][1:]
175
 
        self.assertIsInstance(smtp_username, str)
176
 
        self.assertIsInstance(smtp_password, str)
 
179
        self.assertIsInstance(smtp_username, bytes)
 
180
        self.assertIsInstance(smtp_password, bytes)
177
181
 
178
182
    def test_create_connection(self):
179
183
        factory = StubSMTPFactory()
180
 
        conn = self.get_connection('', smtp_factory=factory)
 
184
        conn = self.get_connection(b'', smtp_factory=factory)
181
185
        conn._create_connection()
182
186
        self.assertEqual([('connect', 'localhost'),
183
187
                          ('ehlo',),
186
190
    def test_create_connection_ehlo_fails(self):
187
191
        # Check that we call HELO if EHLO failed.
188
192
        factory = StubSMTPFactory(fail_on=['ehlo'])
189
 
        conn = self.get_connection('', smtp_factory=factory)
 
193
        conn = self.get_connection(b'', smtp_factory=factory)
190
194
        conn._create_connection()
191
195
        self.assertEqual([('connect', 'localhost'),
192
196
                          ('ehlo',),
196
200
    def test_create_connection_ehlo_helo_fails(self):
197
201
        # Check that we raise an exception if both EHLO and HELO fail.
198
202
        factory = StubSMTPFactory(fail_on=['ehlo', 'helo'])
199
 
        conn = self.get_connection('', smtp_factory=factory)
200
 
        self.assertRaises(errors.SMTPError, conn._create_connection)
 
203
        conn = self.get_connection(b'', smtp_factory=factory)
 
204
        self.assertRaises(smtp_connection.SMTPError, conn._create_connection)
201
205
        self.assertEqual([('connect', 'localhost'),
202
206
                          ('ehlo',),
203
207
                          ('helo',)], factory._calls)
206
210
        # Check that STARTTLS plus a second EHLO are called if the
207
211
        # server says it supports the feature.
208
212
        factory = StubSMTPFactory(smtp_features=['starttls'])
209
 
        conn = self.get_connection('', smtp_factory=factory)
 
213
        conn = self.get_connection(b'', smtp_factory=factory)
210
214
        conn._create_connection()
211
215
        self.assertEqual([('connect', 'localhost'),
212
216
                          ('ehlo',),
219
223
        # support STARTTLS, but then fails when we try to activate it.
220
224
        factory = StubSMTPFactory(fail_on=['starttls'],
221
225
                                  smtp_features=['starttls'])
222
 
        conn = self.get_connection('', smtp_factory=factory)
223
 
        self.assertRaises(errors.SMTPError, conn._create_connection)
 
226
        conn = self.get_connection(b'', smtp_factory=factory)
 
227
        self.assertRaises(smtp_connection.SMTPError, conn._create_connection)
224
228
        self.assertEqual([('connect', 'localhost'),
225
229
                          ('ehlo',),
226
230
                          ('has_extn', 'starttls'),
241
245
        from_, to = smtp_connection.SMTPConnection.get_message_addresses(msg)
242
246
        self.assertEqual('jrandom@example.com', from_)
243
247
        self.assertEqual(sorted(['john@doe.com', 'jane@doe.com',
244
 
            'pperez@ejemplo.com', 'user@localhost']), sorted(to))
 
248
                                 'pperez@ejemplo.com', 'user@localhost']), sorted(to))
245
249
 
246
 
        # now with bzrlib's EmailMessage
 
250
        # now with breezy's EmailMessage
247
251
        msg = email_message.EmailMessage(
248
252
            '"J. Random Developer" <jrandom@example.com>',
249
253
            ['John Doe <john@doe.com>', 'Jane Doe <jane@doe.com>',
250
 
             u'Pepe P\xe9rez <pperez@ejemplo.com>', 'user@localhost' ],
 
254
             u'Pepe P\xe9rez <pperez@ejemplo.com>', 'user@localhost'],
251
255
            'subject')
252
256
 
253
257
        from_, to = smtp_connection.SMTPConnection.get_message_addresses(msg)
254
258
        self.assertEqual('jrandom@example.com', from_)
255
259
        self.assertEqual(sorted(['john@doe.com', 'jane@doe.com',
256
 
            'pperez@ejemplo.com', 'user@localhost']), sorted(to))
 
260
                                 'pperez@ejemplo.com', 'user@localhost']), sorted(to))
257
261
 
258
262
    def test_destination_address_required(self):
259
 
        class FakeConfig:
260
 
            def get_user_option(self, option):
261
 
                return None
262
 
 
263
263
        msg = Message()
264
264
        msg['From'] = '"J. Random Developer" <jrandom@example.com>'
265
265
        self.assertRaises(
266
 
            errors.NoDestinationAddress,
267
 
            smtp_connection.SMTPConnection(FakeConfig()).send_email, msg)
 
266
            smtp_connection.NoDestinationAddress,
 
267
            smtp_connection.SMTPConnection(config.MemoryStack(b"")
 
268
                                           ).send_email, msg)
268
269
 
269
270
        msg = email_message.EmailMessage('from@from.com', '', 'subject')
270
271
        self.assertRaises(
271
 
            errors.NoDestinationAddress,
272
 
            smtp_connection.SMTPConnection(FakeConfig()).send_email, msg)
 
272
            smtp_connection.NoDestinationAddress,
 
273
            smtp_connection.SMTPConnection(config.MemoryStack(b"")
 
274
                                           ).send_email, msg)
273
275
 
274
276
        msg = email_message.EmailMessage('from@from.com', [], 'subject')
275
277
        self.assertRaises(
276
 
            errors.NoDestinationAddress,
277
 
            smtp_connection.SMTPConnection(FakeConfig()).send_email, msg)
 
278
            smtp_connection.NoDestinationAddress,
 
279
            smtp_connection.SMTPConnection(config.MemoryStack(b"")
 
280
                                           ).send_email, msg)