/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_email_message.py

  • Committer: Jelmer Vernooij
  • Date: 2020-02-18 01:57:45 UTC
  • mto: This revision was merged to the branch mainline in revision 7493.
  • Revision ID: jelmer@jelmer.uk-20200218015745-q2ss9tsk74h4nh61
drop use of future.

Show diffs side-by-side

added added

removed removed

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