/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5557.1.15 by John Arbash Meinel
Merge bzr.dev 5597 to resolve NEWS, aka bzr-2.3.txt
1
# Copyright (C) 2007, 2009, 2010, 2011 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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
16
7479.2.1 by Jelmer Vernooij
Drop python2 support.
17
from email.message import Message
2694.2.1 by Aaron Bentley
Make error handling nicer when SMTP server not working
18
import errno
19
import smtplib
20
import socket
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
21
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
22
from breezy import (
2694.2.1 by Aaron Bentley
Make error handling nicer when SMTP server not working
23
    config,
2900.2.11 by Vincent Ladeuil
Make smtp aware of authentication config.
24
    email_message,
25
    smtp_connection,
26
    tests,
27
    ui,
2694.2.1 by Aaron Bentley
Make error handling nicer when SMTP server not working
28
    )
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
29
30
2694.2.1 by Aaron Bentley
Make error handling nicer when SMTP server not working
31
def connection_refuser():
32
    def connect(server):
33
        raise socket.error(errno.ECONNREFUSED, 'Connection Refused')
34
    smtp = smtplib.SMTP()
35
    smtp.connect = connect
36
    return smtp
37
38
2898.2.2 by James Henstridge
Fix test helper class naming, per John's review comments.
39
class StubSMTPFactory(object):
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
40
    """A fake SMTP connection to test the connection setup."""
7143.15.2 by Jelmer Vernooij
Run autopep8.
41
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
42
    def __init__(self, fail_on=None, smtp_features=None):
43
        self._fail_on = fail_on or []
44
        self._calls = []
45
        self._smtp_features = smtp_features or []
46
        self._ehlo_called = False
47
48
    def __call__(self):
49
        # The factory pretends to be a connection
50
        return self
51
52
    def connect(self, server):
53
        self._calls.append(('connect', server))
54
55
    def helo(self):
56
        self._calls.append(('helo',))
57
        if 'helo' in self._fail_on:
58
            return 500, 'helo failure'
59
        else:
60
            return 200, 'helo success'
61
62
    def ehlo(self):
63
        self._calls.append(('ehlo',))
64
        if 'ehlo' in self._fail_on:
65
            return 500, 'ehlo failure'
66
        else:
67
            self._ehlo_called = True
68
            return 200, 'ehlo success'
69
70
    def has_extn(self, extension):
71
        self._calls.append(('has_extn', extension))
72
        return self._ehlo_called and extension in self._smtp_features
73
74
    def starttls(self):
75
        self._calls.append(('starttls',))
76
        if 'starttls' in self._fail_on:
77
            return 500, 'starttls failure'
78
        else:
79
            self._ehlo_called = True
80
            return 200, 'starttls success'
81
82
2900.2.17 by Vincent Ladeuil
merge bzr.dev
83
class WideOpenSMTPFactory(StubSMTPFactory):
84
    """A fake smtp server that implements login by accepting anybody."""
85
86
    def login(self, user, password):
4147.1.1 by James Henstridge
Ensure that byte strings are passed to SMTP.login(), as passing unicode
87
        self._calls.append(('login', user, password))
2900.2.11 by Vincent Ladeuil
Make smtp aware of authentication config.
88
89
90
class TestSMTPConnection(tests.TestCaseInTempDir):
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
91
2694.2.1 by Aaron Bentley
Make error handling nicer when SMTP server not working
92
    def get_connection(self, text, smtp_factory=None):
6393.1.1 by Vincent Ladeuil
Provides MemoryStack to simplify configuration setup in tests
93
        my_config = config.MemoryStack(text)
6379.8.2 by Jelmer Vernooij
Update tests.
94
        return smtp_connection.SMTPConnection(
95
            my_config, _smtp_factory=smtp_factory)
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
96
97
    def test_defaults(self):
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
98
        conn = self.get_connection(b'')
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
99
        self.assertEqual('localhost', conn._smtp_server)
100
        self.assertEqual(None, conn._smtp_username)
101
        self.assertEqual(None, conn._smtp_password)
102
103
    def test_smtp_server(self):
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
104
        conn = self.get_connection(b'smtp_server=host:10')
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
105
        self.assertEqual('host:10', conn._smtp_server)
106
2694.2.1 by Aaron Bentley
Make error handling nicer when SMTP server not working
107
    def test_missing_server(self):
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
108
        conn = self.get_connection(b'', smtp_factory=connection_refuser)
6734.1.1 by Jelmer Vernooij
Fix more imports.
109
        self.assertRaises(smtp_connection.DefaultSMTPConnectionRefused,
110
                          conn._connect)
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
111
        conn = self.get_connection(b'smtp_server=smtp.example.com',
2694.2.1 by Aaron Bentley
Make error handling nicer when SMTP server not working
112
                                   smtp_factory=connection_refuser)
6734.1.1 by Jelmer Vernooij
Fix more imports.
113
        self.assertRaises(smtp_connection.SMTPConnectionRefused, conn._connect)
2694.2.1 by Aaron Bentley
Make error handling nicer when SMTP server not working
114
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
115
    def test_smtp_username(self):
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
116
        conn = self.get_connection(b'')
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
117
        self.assertIs(None, conn._smtp_username)
118
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
119
        conn = self.get_connection(b'smtp_username=joebody')
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
120
        self.assertEqual(u'joebody', conn._smtp_username)
121
2900.2.11 by Vincent Ladeuil
Make smtp aware of authentication config.
122
    def test_smtp_password_from_config(self):
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
123
        conn = self.get_connection(b'')
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
124
        self.assertIs(None, conn._smtp_password)
125
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
126
        conn = self.get_connection(b'smtp_password=mypass')
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
127
        self.assertEqual(u'mypass', conn._smtp_password)
128
2900.2.12 by Vincent Ladeuil
Since all schemes query AuthenticationConfig then prompt user, make that
129
    def test_smtp_password_from_user(self):
130
        user = 'joe'
131
        password = 'hispass'
2900.2.17 by Vincent Ladeuil
merge bzr.dev
132
        factory = WideOpenSMTPFactory()
7045.4.12 by Jelmer Vernooij
Fix remaining smtp tests.
133
        conn = self.get_connection(
7143.15.2 by Jelmer Vernooij
Run autopep8.
134
            b'[DEFAULT]\nsmtp_username=%s\n' % user.encode('ascii'),
135
            smtp_factory=factory)
2900.2.12 by Vincent Ladeuil
Since all schemes query AuthenticationConfig then prompt user, make that
136
        self.assertIs(None, conn._smtp_password)
137
4449.3.40 by Martin Pool
Update SMTP tests to use CannedInputUIFactory
138
        ui.ui_factory = ui.CannedInputUIFactory([password])
2900.2.12 by Vincent Ladeuil
Since all schemes query AuthenticationConfig then prompt user, make that
139
        conn._connect()
140
        self.assertEqual(password, conn._smtp_password)
141
2900.2.11 by Vincent Ladeuil
Make smtp aware of authentication config.
142
    def test_smtp_password_from_auth_config(self):
143
        user = 'joe'
144
        password = 'hispass'
2900.2.17 by Vincent Ladeuil
merge bzr.dev
145
        factory = WideOpenSMTPFactory()
7045.4.12 by Jelmer Vernooij
Fix remaining smtp tests.
146
        conn = self.get_connection(
147
            b'[DEFAULT]\nsmtp_username=%s\n' % user.encode('ascii'),
148
            smtp_factory=factory)
2900.2.11 by Vincent Ladeuil
Make smtp aware of authentication config.
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':
7143.15.2 by Jelmer Vernooij
Run autopep8.
154
                                   {'scheme': 'smtp', 'user': user,
155
                                    'password': password}})
2900.2.11 by Vincent Ladeuil
Make smtp aware of authentication config.
156
        conf._save()
157
158
        conn._connect()
159
        self.assertEqual(password, conn._smtp_password)
160
4147.1.1 by James Henstridge
Ensure that byte strings are passed to SMTP.login(), as passing unicode
161
    def test_authenticate_with_byte_strings(self):
7045.4.8 by Jelmer Vernooij
Fix another 128 tests on python 3.
162
        user = b'joe'
5345.2.4 by Vincent Ladeuil
Fix fallouts, including an unclear test.
163
        unicode_pass = u'h\xECspass'
164
        utf8_pass = unicode_pass.encode('utf-8')
4147.1.1 by James Henstridge
Ensure that byte strings are passed to SMTP.login(), as passing unicode
165
        factory = WideOpenSMTPFactory()
166
        conn = self.get_connection(
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
167
            b'[DEFAULT]\nsmtp_username=%s\nsmtp_password=%s\n'
6379.8.2 by Jelmer Vernooij
Update tests.
168
            % (user, utf8_pass), smtp_factory=factory)
5345.2.4 by Vincent Ladeuil
Fix fallouts, including an unclear test.
169
        self.assertEqual(unicode_pass, conn._smtp_password)
4147.1.1 by James Henstridge
Ensure that byte strings are passed to SMTP.login(), as passing unicode
170
        conn._connect()
171
        self.assertEqual([('connect', 'localhost'),
172
                          ('ehlo',),
173
                          ('has_extn', 'starttls'),
5345.2.4 by Vincent Ladeuil
Fix fallouts, including an unclear test.
174
                          ('login', user, utf8_pass)], factory._calls)
4147.1.2 by James Henstridge
Encode usernames and passwords as UTF-8 rather than ASCII. While
175
        smtp_username, smtp_password = factory._calls[-1][1:]
7045.4.12 by Jelmer Vernooij
Fix remaining smtp tests.
176
        self.assertIsInstance(smtp_username, bytes)
177
        self.assertIsInstance(smtp_password, bytes)
4147.1.1 by James Henstridge
Ensure that byte strings are passed to SMTP.login(), as passing unicode
178
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
179
    def test_create_connection(self):
2898.2.2 by James Henstridge
Fix test helper class naming, per John's review comments.
180
        factory = StubSMTPFactory()
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
181
        conn = self.get_connection(b'', smtp_factory=factory)
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
182
        conn._create_connection()
183
        self.assertEqual([('connect', 'localhost'),
184
                          ('ehlo',),
2898.2.2 by James Henstridge
Fix test helper class naming, per John's review comments.
185
                          ('has_extn', 'starttls')], factory._calls)
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
186
187
    def test_create_connection_ehlo_fails(self):
188
        # Check that we call HELO if EHLO failed.
2898.2.2 by James Henstridge
Fix test helper class naming, per John's review comments.
189
        factory = StubSMTPFactory(fail_on=['ehlo'])
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
190
        conn = self.get_connection(b'', smtp_factory=factory)
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
191
        conn._create_connection()
192
        self.assertEqual([('connect', 'localhost'),
193
                          ('ehlo',),
194
                          ('helo',),
2898.2.2 by James Henstridge
Fix test helper class naming, per John's review comments.
195
                          ('has_extn', 'starttls')], factory._calls)
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
196
197
    def test_create_connection_ehlo_helo_fails(self):
198
        # 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.
199
        factory = StubSMTPFactory(fail_on=['ehlo', 'helo'])
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
200
        conn = self.get_connection(b'', smtp_factory=factory)
6734.1.1 by Jelmer Vernooij
Fix more imports.
201
        self.assertRaises(smtp_connection.SMTPError, conn._create_connection)
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
202
        self.assertEqual([('connect', 'localhost'),
203
                          ('ehlo',),
2898.2.2 by James Henstridge
Fix test helper class naming, per John's review comments.
204
                          ('helo',)], factory._calls)
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
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.
2898.2.2 by James Henstridge
Fix test helper class naming, per John's review comments.
209
        factory = StubSMTPFactory(smtp_features=['starttls'])
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
210
        conn = self.get_connection(b'', smtp_factory=factory)
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
211
        conn._create_connection()
212
        self.assertEqual([('connect', 'localhost'),
213
                          ('ehlo',),
214
                          ('has_extn', 'starttls'),
215
                          ('starttls',),
2898.2.2 by James Henstridge
Fix test helper class naming, per John's review comments.
216
                          ('ehlo',)], factory._calls)
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
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.
2898.2.2 by James Henstridge
Fix test helper class naming, per John's review comments.
221
        factory = StubSMTPFactory(fail_on=['starttls'],
222
                                  smtp_features=['starttls'])
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
223
        conn = self.get_connection(b'', smtp_factory=factory)
6734.1.1 by Jelmer Vernooij
Fix more imports.
224
        self.assertRaises(smtp_connection.SMTPError, conn._create_connection)
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
225
        self.assertEqual([('connect', 'localhost'),
226
                          ('ehlo',),
227
                          ('has_extn', 'starttls'),
2898.2.2 by James Henstridge
Fix test helper class naming, per John's review comments.
228
                          ('starttls',)], factory._calls)
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
229
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
230
    def test_get_message_addresses(self):
231
        msg = Message()
232
2900.2.11 by Vincent Ladeuil
Make smtp aware of authentication config.
233
        from_, to = smtp_connection.SMTPConnection.get_message_addresses(msg)
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
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
2900.2.11 by Vincent Ladeuil
Make smtp aware of authentication config.
242
        from_, to = smtp_connection.SMTPConnection.get_message_addresses(msg)
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
243
        self.assertEqual('jrandom@example.com', from_)
244
        self.assertEqual(sorted(['john@doe.com', 'jane@doe.com',
7143.15.2 by Jelmer Vernooij
Run autopep8.
245
                                 'pperez@ejemplo.com', 'user@localhost']), sorted(to))
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
246
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
247
        # now with breezy's EmailMessage
2900.2.11 by Vincent Ladeuil
Make smtp aware of authentication config.
248
        msg = email_message.EmailMessage(
249
            '"J. Random Developer" <jrandom@example.com>',
250
            ['John Doe <john@doe.com>', 'Jane Doe <jane@doe.com>',
7143.15.2 by Jelmer Vernooij
Run autopep8.
251
             u'Pepe P\xe9rez <pperez@ejemplo.com>', 'user@localhost'],
2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
252
            'subject')
253
2900.2.11 by Vincent Ladeuil
Make smtp aware of authentication config.
254
        from_, to = smtp_connection.SMTPConnection.get_message_addresses(msg)
2625.6.1 by Adeodato Simó
New EmailMessage class, façade around email.Message and MIMEMultipart.
255
        self.assertEqual('jrandom@example.com', from_)
256
        self.assertEqual(sorted(['john@doe.com', 'jane@doe.com',
7143.15.2 by Jelmer Vernooij
Run autopep8.
257
                                 'pperez@ejemplo.com', 'user@localhost']), sorted(to))
2900.2.12 by Vincent Ladeuil
Since all schemes query AuthenticationConfig then prompt user, make that
258
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
259
    def test_destination_address_required(self):
260
        msg = Message()
261
        msg['From'] = '"J. Random Developer" <jrandom@example.com>'
2900.2.11 by Vincent Ladeuil
Make smtp aware of authentication config.
262
        self.assertRaises(
6734.1.1 by Jelmer Vernooij
Fix more imports.
263
            smtp_connection.NoDestinationAddress,
7045.4.12 by Jelmer Vernooij
Fix remaining smtp tests.
264
            smtp_connection.SMTPConnection(config.MemoryStack(b"")
6393.1.1 by Vincent Ladeuil
Provides MemoryStack to simplify configuration setup in tests
265
                                           ).send_email, msg)
2900.2.11 by Vincent Ladeuil
Make smtp aware of authentication config.
266
267
        msg = email_message.EmailMessage('from@from.com', '', 'subject')
268
        self.assertRaises(
6734.1.1 by Jelmer Vernooij
Fix more imports.
269
            smtp_connection.NoDestinationAddress,
7045.4.12 by Jelmer Vernooij
Fix remaining smtp tests.
270
            smtp_connection.SMTPConnection(config.MemoryStack(b"")
6393.1.1 by Vincent Ladeuil
Provides MemoryStack to simplify configuration setup in tests
271
                                           ).send_email, msg)
2900.2.11 by Vincent Ladeuil
Make smtp aware of authentication config.
272
273
        msg = email_message.EmailMessage('from@from.com', [], 'subject')
274
        self.assertRaises(
6734.1.1 by Jelmer Vernooij
Fix more imports.
275
            smtp_connection.NoDestinationAddress,
7045.4.12 by Jelmer Vernooij
Fix remaining smtp tests.
276
            smtp_connection.SMTPConnection(config.MemoryStack(b"")
6393.1.1 by Vincent Ladeuil
Provides MemoryStack to simplify configuration setup in tests
277
                                           ).send_email, msg)