~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_smtp_connection.py

  • Committer: Vincent Ladeuil
  • Date: 2007-10-24 13:56:34 UTC
  • mto: (3928.1.1 bzr.integration)
  • mto: This revision was merged to the branch mainline in revision 3929.
  • Revision ID: v.ladeuil+lp@free.fr-20071024135634-d8os3by1g6f45q12
Fix python2.6 deprecation warnings (still 4 failures 5 errors in test suite).

* bzrlib/osutils.py: 
Wrap md5 and sha imports to be compatible with python 2.4, 2.5,
2.6.
Replace all sha.new() calls by sha() calls they are reputedly
faster (not profiled).

* bzrlib/weave.py: 
Update sha import, fix use.     

* bzrlib/transport/http/_urllib2_wrappers.py: 
Update sha and md5 imports, fix uses.

* bzrlib/tests/test_testament.py: 
Update sha import.

* bzrlib/tests/test_knit.py: 
Update sha import, fix uses.    

* bzrlib/tests/test_hashcache.py: 
Update sha import, fix use.     

* bzrlib/tests/repository_implementations/test_check_reconcile.py: 
Update sha import, fix use.     

* bzrlib/tests/HTTPTestUtil.py: 
Update md5 import, fix uses. Delete useless sha import.

* bzrlib/testament.py: 
Update sha import.

* bzrlib/hashcache.py: 
Update sha import.

* bzrlib/revisionspec.py:
(RevisionSpec.__new__): Remove useless parameters since python2.6
is stricter.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2007 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
from cStringIO import StringIO
 
18
from email.Message import Message
 
19
import errno
 
20
import smtplib
 
21
import socket
 
22
 
 
23
from bzrlib import (
 
24
    config,
 
25
    errors,
 
26
    )
 
27
from bzrlib.email_message import EmailMessage
 
28
from bzrlib.errors import NoDestinationAddress
 
29
from bzrlib.tests import TestCase
 
30
from bzrlib.smtp_connection import SMTPConnection
 
31
 
 
32
 
 
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
 
 
41
class StubSMTPFactory(object):
 
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
 
 
84
class TestSMTPConnection(TestCase):
 
85
 
 
86
    def get_connection(self, text, smtp_factory=None):
 
87
        my_config = config.GlobalConfig()
 
88
        config_file = StringIO(text)
 
89
        my_config._get_parser(config_file)
 
90
        return SMTPConnection(my_config, _smtp_factory=smtp_factory)
 
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
 
 
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
 
 
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
 
 
123
    def test_create_connection(self):
 
124
        factory = StubSMTPFactory()
 
125
        conn = self.get_connection('', smtp_factory=factory)
 
126
        conn._create_connection()
 
127
        self.assertEqual([('connect', 'localhost'),
 
128
                          ('ehlo',),
 
129
                          ('has_extn', 'starttls')], factory._calls)
 
130
 
 
131
    def test_create_connection_ehlo_fails(self):
 
132
        # Check that we call HELO if EHLO failed.
 
133
        factory = StubSMTPFactory(fail_on=['ehlo'])
 
134
        conn = self.get_connection('', smtp_factory=factory)
 
135
        conn._create_connection()
 
136
        self.assertEqual([('connect', 'localhost'),
 
137
                          ('ehlo',),
 
138
                          ('helo',),
 
139
                          ('has_extn', 'starttls')], factory._calls)
 
140
 
 
141
    def test_create_connection_ehlo_helo_fails(self):
 
142
        # Check that we raise an exception if both EHLO and HELO fail.
 
143
        factory = StubSMTPFactory(fail_on=['ehlo', 'helo'])
 
144
        conn = self.get_connection('', smtp_factory=factory)
 
145
        self.assertRaises(errors.SMTPError, conn._create_connection)
 
146
        self.assertEqual([('connect', 'localhost'),
 
147
                          ('ehlo',),
 
148
                          ('helo',)], factory._calls)
 
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.
 
153
        factory = StubSMTPFactory(smtp_features=['starttls'])
 
154
        conn = self.get_connection('', smtp_factory=factory)
 
155
        conn._create_connection()
 
156
        self.assertEqual([('connect', 'localhost'),
 
157
                          ('ehlo',),
 
158
                          ('has_extn', 'starttls'),
 
159
                          ('starttls',),
 
160
                          ('ehlo',)], factory._calls)
 
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.
 
165
        factory = StubSMTPFactory(fail_on=['starttls'],
 
166
                                  smtp_features=['starttls'])
 
167
        conn = self.get_connection('', smtp_factory=factory)
 
168
        self.assertRaises(errors.SMTPError, conn._create_connection)
 
169
        self.assertEqual([('connect', 'localhost'),
 
170
                          ('ehlo',),
 
171
                          ('has_extn', 'starttls'),
 
172
                          ('starttls',)], factory._calls)
 
173
 
 
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
 
 
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
 
 
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)
 
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)