/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
6791.2.3 by Jelmer Vernooij
Fix more imports.
17
try:
18
    from email.message import Message
19
except ImportError:  # python < 3
20
    from email.Message import Message
2694.2.1 by Aaron Bentley
Make error handling nicer when SMTP server not working
21
import errno
22
import smtplib
23
import socket
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
24
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
25
from breezy import (
2694.2.1 by Aaron Bentley
Make error handling nicer when SMTP server not working
26
    config,
2900.2.11 by Vincent Ladeuil
Make smtp aware of authentication config.
27
    email_message,
28
    smtp_connection,
29
    tests,
30
    ui,
2694.2.1 by Aaron Bentley
Make error handling nicer when SMTP server not working
31
    )
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
32
33
2694.2.1 by Aaron Bentley
Make error handling nicer when SMTP server not working
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
2898.2.2 by James Henstridge
Fix test helper class naming, per John's review comments.
42
class StubSMTPFactory(object):
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
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
2900.2.17 by Vincent Ladeuil
merge bzr.dev
85
class WideOpenSMTPFactory(StubSMTPFactory):
86
    """A fake smtp server that implements login by accepting anybody."""
87
88
    def login(self, user, password):
4147.1.1 by James Henstridge
Ensure that byte strings are passed to SMTP.login(), as passing unicode
89
        self._calls.append(('login', user, password))
2900.2.11 by Vincent Ladeuil
Make smtp aware of authentication config.
90
91
92
class TestSMTPConnection(tests.TestCaseInTempDir):
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
93
2694.2.1 by Aaron Bentley
Make error handling nicer when SMTP server not working
94
    def get_connection(self, text, smtp_factory=None):
6393.1.1 by Vincent Ladeuil
Provides MemoryStack to simplify configuration setup in tests
95
        my_config = config.MemoryStack(text)
6379.8.2 by Jelmer Vernooij
Update tests.
96
        return smtp_connection.SMTPConnection(
97
            my_config, _smtp_factory=smtp_factory)
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
98
99
    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.
100
        conn = self.get_connection(b'')
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
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):
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
106
        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.
107
        self.assertEqual('host:10', conn._smtp_server)
108
2694.2.1 by Aaron Bentley
Make error handling nicer when SMTP server not working
109
    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.
110
        conn = self.get_connection(b'', smtp_factory=connection_refuser)
6734.1.1 by Jelmer Vernooij
Fix more imports.
111
        self.assertRaises(smtp_connection.DefaultSMTPConnectionRefused,
112
                          conn._connect)
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
113
        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
114
                                   smtp_factory=connection_refuser)
6734.1.1 by Jelmer Vernooij
Fix more imports.
115
        self.assertRaises(smtp_connection.SMTPConnectionRefused, conn._connect)
2694.2.1 by Aaron Bentley
Make error handling nicer when SMTP server not working
116
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
117
    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.
118
        conn = self.get_connection(b'')
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
119
        self.assertIs(None, conn._smtp_username)
120
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
121
        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.
122
        self.assertEqual(u'joebody', conn._smtp_username)
123
2900.2.11 by Vincent Ladeuil
Make smtp aware of authentication config.
124
    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.
125
        conn = self.get_connection(b'')
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
126
        self.assertIs(None, conn._smtp_password)
127
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
128
        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.
129
        self.assertEqual(u'mypass', conn._smtp_password)
130
2900.2.12 by Vincent Ladeuil
Since all schemes query AuthenticationConfig then prompt user, make that
131
    def test_smtp_password_from_user(self):
132
        user = 'joe'
133
        password = 'hispass'
2900.2.17 by Vincent Ladeuil
merge bzr.dev
134
        factory = WideOpenSMTPFactory()
7045.4.12 by Jelmer Vernooij
Fix remaining smtp tests.
135
        conn = self.get_connection(
136
                b'[DEFAULT]\nsmtp_username=%s\n' % user.encode('ascii'),
137
                smtp_factory=factory)
2900.2.12 by Vincent Ladeuil
Since all schemes query AuthenticationConfig then prompt user, make that
138
        self.assertIs(None, conn._smtp_password)
139
4449.3.40 by Martin Pool
Update SMTP tests to use CannedInputUIFactory
140
        ui.ui_factory = ui.CannedInputUIFactory([password])
2900.2.12 by Vincent Ladeuil
Since all schemes query AuthenticationConfig then prompt user, make that
141
        conn._connect()
142
        self.assertEqual(password, conn._smtp_password)
143
2900.2.11 by Vincent Ladeuil
Make smtp aware of authentication config.
144
    def test_smtp_password_from_auth_config(self):
145
        user = 'joe'
146
        password = 'hispass'
2900.2.17 by Vincent Ladeuil
merge bzr.dev
147
        factory = WideOpenSMTPFactory()
7045.4.12 by Jelmer Vernooij
Fix remaining smtp tests.
148
        conn = self.get_connection(
149
            b'[DEFAULT]\nsmtp_username=%s\n' % user.encode('ascii'),
150
            smtp_factory=factory)
2900.2.11 by Vincent Ladeuil
Make smtp aware of authentication config.
151
        self.assertEqual(user, conn._smtp_username)
152
        self.assertIs(None, conn._smtp_password)
153
        # Create a config file with the right password
154
        conf = config.AuthenticationConfig()
155
        conf._get_config().update({'smtptest':
156
                                       {'scheme': 'smtp', 'user':user,
157
                                        'password': password}})
158
        conf._save()
159
160
        conn._connect()
161
        self.assertEqual(password, conn._smtp_password)
162
4147.1.1 by James Henstridge
Ensure that byte strings are passed to SMTP.login(), as passing unicode
163
    def test_authenticate_with_byte_strings(self):
7045.4.8 by Jelmer Vernooij
Fix another 128 tests on python 3.
164
        user = b'joe'
5345.2.4 by Vincent Ladeuil
Fix fallouts, including an unclear test.
165
        unicode_pass = u'h\xECspass'
166
        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
167
        factory = WideOpenSMTPFactory()
168
        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.
169
            b'[DEFAULT]\nsmtp_username=%s\nsmtp_password=%s\n'
6379.8.2 by Jelmer Vernooij
Update tests.
170
            % (user, utf8_pass), smtp_factory=factory)
5345.2.4 by Vincent Ladeuil
Fix fallouts, including an unclear test.
171
        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
172
        conn._connect()
173
        self.assertEqual([('connect', 'localhost'),
174
                          ('ehlo',),
175
                          ('has_extn', 'starttls'),
5345.2.4 by Vincent Ladeuil
Fix fallouts, including an unclear test.
176
                          ('login', user, utf8_pass)], factory._calls)
4147.1.2 by James Henstridge
Encode usernames and passwords as UTF-8 rather than ASCII. While
177
        smtp_username, smtp_password = factory._calls[-1][1:]
7045.4.12 by Jelmer Vernooij
Fix remaining smtp tests.
178
        self.assertIsInstance(smtp_username, bytes)
179
        self.assertIsInstance(smtp_password, bytes)
4147.1.1 by James Henstridge
Ensure that byte strings are passed to SMTP.login(), as passing unicode
180
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
181
    def test_create_connection(self):
2898.2.2 by James Henstridge
Fix test helper class naming, per John's review comments.
182
        factory = StubSMTPFactory()
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
183
        conn = self.get_connection(b'', smtp_factory=factory)
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
184
        conn._create_connection()
185
        self.assertEqual([('connect', 'localhost'),
186
                          ('ehlo',),
2898.2.2 by James Henstridge
Fix test helper class naming, per John's review comments.
187
                          ('has_extn', 'starttls')], factory._calls)
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
188
189
    def test_create_connection_ehlo_fails(self):
190
        # Check that we call HELO if EHLO failed.
2898.2.2 by James Henstridge
Fix test helper class naming, per John's review comments.
191
        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.
192
        conn = self.get_connection(b'', smtp_factory=factory)
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
193
        conn._create_connection()
194
        self.assertEqual([('connect', 'localhost'),
195
                          ('ehlo',),
196
                          ('helo',),
2898.2.2 by James Henstridge
Fix test helper class naming, per John's review comments.
197
                          ('has_extn', 'starttls')], factory._calls)
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
198
199
    def test_create_connection_ehlo_helo_fails(self):
200
        # 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.
201
        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.
202
        conn = self.get_connection(b'', smtp_factory=factory)
6734.1.1 by Jelmer Vernooij
Fix more imports.
203
        self.assertRaises(smtp_connection.SMTPError, conn._create_connection)
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
204
        self.assertEqual([('connect', 'localhost'),
205
                          ('ehlo',),
2898.2.2 by James Henstridge
Fix test helper class naming, per John's review comments.
206
                          ('helo',)], factory._calls)
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
207
208
    def test_create_connection_starttls(self):
209
        # Check that STARTTLS plus a second EHLO are called if the
210
        # server says it supports the feature.
2898.2.2 by James Henstridge
Fix test helper class naming, per John's review comments.
211
        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.
212
        conn = self.get_connection(b'', smtp_factory=factory)
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
213
        conn._create_connection()
214
        self.assertEqual([('connect', 'localhost'),
215
                          ('ehlo',),
216
                          ('has_extn', 'starttls'),
217
                          ('starttls',),
2898.2.2 by James Henstridge
Fix test helper class naming, per John's review comments.
218
                          ('ehlo',)], factory._calls)
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
219
220
    def test_create_connection_starttls_fails(self):
221
        # Check that we raise an exception if the server claims to
222
        # 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.
223
        factory = StubSMTPFactory(fail_on=['starttls'],
224
                                  smtp_features=['starttls'])
7027.3.3 by Jelmer Vernooij
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.
225
        conn = self.get_connection(b'', smtp_factory=factory)
6734.1.1 by Jelmer Vernooij
Fix more imports.
226
        self.assertRaises(smtp_connection.SMTPError, conn._create_connection)
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
227
        self.assertEqual([('connect', 'localhost'),
228
                          ('ehlo',),
229
                          ('has_extn', 'starttls'),
2898.2.2 by James Henstridge
Fix test helper class naming, per John's review comments.
230
                          ('starttls',)], factory._calls)
2898.2.1 by James Henstridge
Update SMTPConnection._create_connection to better follow the SMTP
231
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
232
    def test_get_message_addresses(self):
233
        msg = Message()
234
2900.2.11 by Vincent Ladeuil
Make smtp aware of authentication config.
235
        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.
236
        self.assertEqual('', from_)
237
        self.assertEqual([], to)
238
239
        msg['From'] = '"J. Random Developer" <jrandom@example.com>'
240
        msg['To'] = 'John Doe <john@doe.com>, Jane Doe <jane@doe.com>'
241
        msg['CC'] = u'Pepe P\xe9rez <pperez@ejemplo.com>'
242
        msg['Bcc'] = 'user@localhost'
243
2900.2.11 by Vincent Ladeuil
Make smtp aware of authentication config.
244
        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.
245
        self.assertEqual('jrandom@example.com', from_)
246
        self.assertEqual(sorted(['john@doe.com', 'jane@doe.com',
247
            'pperez@ejemplo.com', 'user@localhost']), sorted(to))
248
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
249
        # now with breezy's EmailMessage
2900.2.11 by Vincent Ladeuil
Make smtp aware of authentication config.
250
        msg = email_message.EmailMessage(
251
            '"J. Random Developer" <jrandom@example.com>',
252
            ['John Doe <john@doe.com>', 'Jane Doe <jane@doe.com>',
253
             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.
254
            'subject')
255
2900.2.11 by Vincent Ladeuil
Make smtp aware of authentication config.
256
        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.
257
        self.assertEqual('jrandom@example.com', from_)
258
        self.assertEqual(sorted(['john@doe.com', 'jane@doe.com',
259
            'pperez@ejemplo.com', 'user@localhost']), sorted(to))
2900.2.12 by Vincent Ladeuil
Since all schemes query AuthenticationConfig then prompt user, make that
260
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
261
    def test_destination_address_required(self):
262
        msg = Message()
263
        msg['From'] = '"J. Random Developer" <jrandom@example.com>'
2900.2.11 by Vincent Ladeuil
Make smtp aware of authentication config.
264
        self.assertRaises(
6734.1.1 by Jelmer Vernooij
Fix more imports.
265
            smtp_connection.NoDestinationAddress,
7045.4.12 by Jelmer Vernooij
Fix remaining smtp tests.
266
            smtp_connection.SMTPConnection(config.MemoryStack(b"")
6393.1.1 by Vincent Ladeuil
Provides MemoryStack to simplify configuration setup in tests
267
                                           ).send_email, msg)
2900.2.11 by Vincent Ladeuil
Make smtp aware of authentication config.
268
269
        msg = email_message.EmailMessage('from@from.com', '', 'subject')
270
        self.assertRaises(
6734.1.1 by Jelmer Vernooij
Fix more imports.
271
            smtp_connection.NoDestinationAddress,
7045.4.12 by Jelmer Vernooij
Fix remaining smtp tests.
272
            smtp_connection.SMTPConnection(config.MemoryStack(b"")
6393.1.1 by Vincent Ladeuil
Provides MemoryStack to simplify configuration setup in tests
273
                                           ).send_email, msg)
2900.2.11 by Vincent Ladeuil
Make smtp aware of authentication config.
274
275
        msg = email_message.EmailMessage('from@from.com', [], 'subject')
276
        self.assertRaises(
6734.1.1 by Jelmer Vernooij
Fix more imports.
277
            smtp_connection.NoDestinationAddress,
7045.4.12 by Jelmer Vernooij
Fix remaining smtp tests.
278
            smtp_connection.SMTPConnection(config.MemoryStack(b"")
6393.1.1 by Vincent Ladeuil
Provides MemoryStack to simplify configuration setup in tests
279
                                           ).send_email, msg)