/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 bzrlib/tests/test_email_message.py

  • Committer: Marius Kruger
  • Date: 2010-07-10 21:28:56 UTC
  • mto: (5384.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 5385.
  • Revision ID: marius.kruger@enerweb.co.za-20100710212856-uq4ji3go0u5se7hx
* Update documentation
* add NEWS

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2007, 2009, 2011, 2014, 2016 Canonical Ltd
 
1
# Copyright (C) 2007 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
 
import sys
18
 
from email.header import decode_header
 
17
from email.Header import decode_header
19
18
 
20
 
from .. import __version__ as _breezy_version
21
 
from ..email_message import EmailMessage
22
 
from ..errors import BzrBadParameterNotUnicode
23
 
from ..sixish import PY3, text_type
24
 
from ..smtp_connection import SMTPConnection
25
 
from .. import tests
 
19
from bzrlib import __version__ as _bzrlib_version
 
20
from bzrlib.email_message import EmailMessage
 
21
from bzrlib.errors import BzrBadParameterNotUnicode
 
22
from bzrlib.smtp_connection import SMTPConnection
 
23
from bzrlib.tests import TestCase
26
24
 
27
25
EMPTY_MESSAGE = '''\
28
26
From: from@from.com
30
28
To: to@to.com
31
29
User-Agent: Bazaar (%s)
32
30
 
33
 
''' % _breezy_version
 
31
''' % _bzrlib_version
34
32
 
35
33
_SIMPLE_MESSAGE = '''\
36
34
MIME-Version: 1.0
41
39
To: to@to.com
42
40
User-Agent: Bazaar (%s)
43
41
 
44
 
%%s''' % _breezy_version
 
42
%%s''' % _bzrlib_version
45
43
 
46
44
SIMPLE_MESSAGE_ASCII = _SIMPLE_MESSAGE % ('us-ascii', '7bit', 'body')
47
45
SIMPLE_MESSAGE_UTF8 = _SIMPLE_MESSAGE % ('utf-8', 'base64', 'YsOzZHk=\n')
65
63
Content-Disposition: inline
66
64
 
67
65
body
68
 
''' % {'version': _breezy_version, 'boundary': BOUNDARY}
69
 
 
70
 
 
71
 
def final_newline_or_not(msg):
72
 
    if sys.version_info >= (2, 7, 6):
73
 
        # Some internals of python's email module changed in an (minor)
74
 
        # incompatible way: a final newline is appended in 2.7.6...
75
 
        msg += '\n'
76
 
    return msg
77
 
 
78
 
 
79
 
def simple_multipart_message():
80
 
    msg = _MULTIPART_HEAD + '--%s--' % BOUNDARY
81
 
    return final_newline_or_not(msg)
82
 
 
83
 
 
84
 
def complex_multipart_message(typ):
85
 
    msg = _MULTIPART_HEAD + '''\
 
66
''' %  { 'version': _bzrlib_version, 'boundary': BOUNDARY }
 
67
 
 
68
SIMPLE_MULTIPART_MESSAGE = _MULTIPART_HEAD + '--%s--' % BOUNDARY
 
69
 
 
70
COMPLEX_MULTIPART_MESSAGE = _MULTIPART_HEAD + '''\
86
71
--%(boundary)s
87
72
MIME-Version: 1.0
88
73
Content-Type: text/%%s; charset="us-ascii"; name="lines.txt"
95
80
d
96
81
e
97
82
 
98
 
--%(boundary)s--''' % {'boundary': BOUNDARY}
99
 
    msg = final_newline_or_not(msg)
100
 
    return msg % (typ,)
101
 
 
102
 
 
103
 
class TestEmailMessage(tests.TestCase):
 
83
--%(boundary)s--''' %  { 'boundary': BOUNDARY }
 
84
 
 
85
 
 
86
class TestEmailMessage(TestCase):
104
87
 
105
88
    def test_empty_message(self):
106
89
        msg = EmailMessage('from@from.com', 'to@to.com', 'subject')
107
 
        self.assertEqualDiff(EMPTY_MESSAGE, msg.as_string())
 
90
        self.assertEqualDiff(EMPTY_MESSAGE , msg.as_string())
108
91
 
109
92
    def test_simple_message(self):
110
93
        pairs = {
111
 
            b'body': SIMPLE_MESSAGE_ASCII,
 
94
            'body': SIMPLE_MESSAGE_ASCII,
112
95
            u'b\xf3dy': SIMPLE_MESSAGE_UTF8,
113
 
            b'b\xc3\xb3dy': SIMPLE_MESSAGE_UTF8,
114
 
            b'b\xf4dy': SIMPLE_MESSAGE_8BIT,
 
96
            'b\xc3\xb3dy': SIMPLE_MESSAGE_UTF8,
 
97
            'b\xf4dy': SIMPLE_MESSAGE_8BIT,
115
98
        }
116
99
        for body, expected in pairs.items():
117
100
            msg = EmailMessage('from@from.com', 'to@to.com', 'subject', body)
118
101
            self.assertEqualDiff(expected, msg.as_string())
119
102
 
120
 
    def test_multipart_message_simple(self):
 
103
    def test_multipart_message(self):
121
104
        msg = EmailMessage('from@from.com', 'to@to.com', 'subject')
122
105
        msg.add_inline_attachment('body')
123
 
        self.assertEqualDiff(simple_multipart_message(),
124
 
                             msg.as_string(BOUNDARY))
 
106
        self.assertEqualDiff(SIMPLE_MULTIPART_MESSAGE, msg.as_string(BOUNDARY))
125
107
 
126
 
    def test_multipart_message_complex(self):
127
108
        msg = EmailMessage('from@from.com', 'to@to.com', 'subject', 'body')
128
109
        msg.add_inline_attachment(u'a\nb\nc\nd\ne\n', 'lines.txt', 'x-subtype')
129
 
        self.assertEqualDiff(complex_multipart_message('x-subtype'),
130
 
                             msg.as_string(BOUNDARY))
 
110
        self.assertEqualDiff(COMPLEX_MULTIPART_MESSAGE % 'x-subtype',
 
111
                msg.as_string(BOUNDARY))
131
112
 
132
113
    def test_headers_accept_unicode_and_utf8(self):
133
 
        for user in [u'Pepe P\xe9rez <pperez@ejemplo.com>',
134
 
                     'Pepe P\xc3\xa9red <pperez@ejemplo.com>']:
135
 
            msg = EmailMessage(user, user, user)  # no exception raised
 
114
        for user in [ u'Pepe P\xe9rez <pperez@ejemplo.com>',
 
115
                'Pepe P\xc3\xa9red <pperez@ejemplo.com>' ]:
 
116
            msg = EmailMessage(user, user, user) # no exception raised
136
117
 
137
118
            for header in ['From', 'To', 'Subject']:
138
119
                value = msg[header]
139
 
                value.encode('ascii')  # no UnicodeDecodeError
 
120
                str(value).decode('ascii') # no UnicodeDecodeError
140
121
 
141
122
    def test_headers_reject_8bit(self):
142
 
        for i in range(3):  # from_address, to_address, subject
143
 
            x = [b'"J. Random Developer" <jrandom@example.com>'] * 3
144
 
            x[i] = b'Pepe P\xe9rez <pperez@ejemplo.com>'
 
123
        for i in range(3): # from_address, to_address, subject
 
124
            x = [ '"J. Random Developer" <jrandom@example.com>' ] * 3
 
125
            x[i] = 'Pepe P\xe9rez <pperez@ejemplo.com>'
145
126
            self.assertRaises(BzrBadParameterNotUnicode, EmailMessage, *x)
146
127
 
147
128
    def test_multiple_destinations(self):
148
 
        to_addresses = ['to1@to.com', 'to2@to.com', 'to3@to.com']
 
129
        to_addresses = [ 'to1@to.com', 'to2@to.com', 'to3@to.com' ]
149
130
        msg = EmailMessage('from@from.com', to_addresses, 'subject')
150
 
        self.assertContainsRe(msg.as_string(), 'To: '
151
 
                              + ', '.join(to_addresses))  # re.M can't be passed, so no ^$
 
131
        self.assertContainsRe(msg.as_string(), 'To: ' +
 
132
                ', '.join(to_addresses)) # re.M can't be passed, so no ^$
152
133
 
153
134
    def test_retrieving_headers(self):
154
135
        msg = EmailMessage('from@from.com', 'to@to.com', 'subject')
155
136
        for header, value in [('From', 'from@from.com'), ('To', 'to@to.com'),
156
 
                              ('Subject', 'subject')]:
 
137
                ('Subject', 'subject')]:
157
138
            self.assertEqual(value, msg.get(header))
158
139
            self.assertEqual(value, msg[header])
159
140
        self.assertEqual(None, msg.get('Does-Not-Exist'))
167
148
        self.assertEqual('to2@to.com', msg['To'])
168
149
        self.assertEqual('cc@cc.com', msg['Cc'])
169
150
 
 
151
    def test_send(self):
 
152
        class FakeConfig:
 
153
            def get_user_option(self, option):
 
154
                return None
 
155
 
 
156
        messages = []
 
157
 
 
158
        def send_as_append(_self, msg):
 
159
            messages.append(msg.as_string(BOUNDARY))
 
160
 
 
161
        old_send_email = SMTPConnection.send_email
 
162
        try:
 
163
            SMTPConnection.send_email = send_as_append
 
164
 
 
165
            EmailMessage.send(FakeConfig(), 'from@from.com', 'to@to.com',
 
166
                    'subject', 'body', u'a\nb\nc\nd\ne\n', 'lines.txt')
 
167
            self.assertEqualDiff(COMPLEX_MULTIPART_MESSAGE % 'plain',
 
168
                    messages[0])
 
169
            messages[:] = []
 
170
 
 
171
            EmailMessage.send(FakeConfig(), 'from@from.com', 'to@to.com',
 
172
                    'subject', 'body', u'a\nb\nc\nd\ne\n', 'lines.txt',
 
173
                    'x-patch')
 
174
            self.assertEqualDiff(COMPLEX_MULTIPART_MESSAGE % 'x-patch',
 
175
                    messages[0])
 
176
            messages[:] = []
 
177
 
 
178
            EmailMessage.send(FakeConfig(), 'from@from.com', 'to@to.com',
 
179
                    'subject', 'body')
 
180
            self.assertEqualDiff(SIMPLE_MESSAGE_ASCII , messages[0])
 
181
            messages[:] = []
 
182
        finally:
 
183
            SMTPConnection.send_email = old_send_email
 
184
 
170
185
    def test_address_to_encoded_header(self):
171
186
        def decode(s):
172
187
            """Convert a RFC2047-encoded string to a unicode string."""
173
 
            if PY3:
174
 
                return ''.join([chunk.decode(encoding or 'ascii')
175
 
                                for chunk, encoding in decode_header(s)])
176
 
            else:
177
 
                # Cope with python2 stripping whitespace.
178
 
                # https://bugs.python.org/issue1467619
179
 
                return ' '.join([chunk.decode(encoding or 'ascii')
180
 
                                 for chunk, encoding in decode_header(s)])
 
188
            return ' '.join([chunk.decode(encoding or 'ascii')
 
189
                             for chunk, encoding in decode_header(s)])
181
190
 
182
191
        address = 'jrandom@example.com'
183
192
        encoded = EmailMessage.address_to_encoded_header(address)
191
200
        encoded = EmailMessage.address_to_encoded_header(address)
192
201
        self.assertEqual(address, encoded)
193
202
 
194
 
        address = u'Pepe P\xe9rez <pperez@ejemplo.com>'  # unicode ok
195
 
        encoded = EmailMessage.address_to_encoded_header(address)
196
 
        # addr must be unencoded
197
 
        self.assertTrue('pperez@ejemplo.com' in encoded)
198
 
        self.assertEqual(address, decode(encoded))
199
 
 
200
 
        address = b'Pepe P\xe9rez <pperez@ejemplo.com>'  # ISO-8859-1 not ok
 
203
        address = u'Pepe P\xe9rez <pperez@ejemplo.com>' # unicode ok
 
204
        encoded = EmailMessage.address_to_encoded_header(address)
 
205
        self.assert_('pperez@ejemplo.com' in encoded) # addr must be unencoded
 
206
        self.assertEquals(address, decode(encoded))
 
207
 
 
208
        address = 'Pepe P\xc3\xa9red <pperez@ejemplo.com>' # UTF-8 ok
 
209
        encoded = EmailMessage.address_to_encoded_header(address)
 
210
        self.assert_('pperez@ejemplo.com' in encoded)
 
211
        self.assertEquals(address, decode(encoded).encode('utf-8'))
 
212
 
 
213
        address = 'Pepe P\xe9rez <pperez@ejemplo.com>' # ISO-8859-1 not ok
201
214
        self.assertRaises(BzrBadParameterNotUnicode,
202
 
                          EmailMessage.address_to_encoded_header, address)
 
215
                EmailMessage.address_to_encoded_header, address)
203
216
 
204
217
    def test_string_with_encoding(self):
205
218
        pairs = {
206
 
            u'Pepe': (b'Pepe', 'ascii'),
207
 
            u'P\xe9rez': (b'P\xc3\xa9rez', 'utf-8'),
208
 
            b'P\xc3\xa9rez': (b'P\xc3\xa9rez', 'utf-8'),
209
 
            b'P\xe8rez': (b'P\xe8rez', '8-bit'),
 
219
                u'Pepe':        ('Pepe', 'ascii'),
 
220
                u'P\xe9rez':    ('P\xc3\xa9rez', 'utf-8'),
 
221
                'Perez':         ('Perez', 'ascii'), # u'Pepe' == 'Pepe'
 
222
                'P\xc3\xa9rez': ('P\xc3\xa9rez', 'utf-8'),
 
223
                'P\xe8rez':     ('P\xe8rez', '8-bit'),
210
224
        }
211
225
        for string_, pair in pairs.items():
212
226
            self.assertEqual(pair, EmailMessage.string_with_encoding(string_))
213
 
 
214
 
 
215
 
class TestSend(tests.TestCase):
216
 
 
217
 
    def setUp(self):
218
 
        super(TestSend, self).setUp()
219
 
        self.messages = []
220
 
 
221
 
        def send_as_append(_self, msg):
222
 
            self.messages.append(msg.as_string(BOUNDARY))
223
 
 
224
 
        self.overrideAttr(SMTPConnection, 'send_email', send_as_append)
225
 
 
226
 
    def send_email(self, attachment=None, attachment_filename=None,
227
 
                   attachment_mime_subtype='plain'):
228
 
        class FakeConfig:
229
 
            def get(self, option):
230
 
                return None
231
 
 
232
 
        EmailMessage.send(FakeConfig(), 'from@from.com', 'to@to.com',
233
 
                          'subject', 'body',
234
 
                          attachment=attachment,
235
 
                          attachment_filename=attachment_filename,
236
 
                          attachment_mime_subtype=attachment_mime_subtype)
237
 
 
238
 
    def assertMessage(self, expected):
239
 
        self.assertLength(1, self.messages)
240
 
        self.assertEqualDiff(expected, self.messages[0])
241
 
 
242
 
    def test_send_plain(self):
243
 
        self.send_email(u'a\nb\nc\nd\ne\n', 'lines.txt')
244
 
        self.assertMessage(complex_multipart_message('plain'))
245
 
 
246
 
    def test_send_patch(self):
247
 
        self.send_email(u'a\nb\nc\nd\ne\n', 'lines.txt', 'x-patch')
248
 
        self.assertMessage(complex_multipart_message('x-patch'))
249
 
 
250
 
    def test_send_simple(self):
251
 
        self.send_email()
252
 
        self.assertMessage(SIMPLE_MESSAGE_ASCII)