Debian Codegraph @

cpython27/Lib/email/test/test_email_renamed.py

raw symbols SCIP
1 # Copyright (C) 2001-2007 Python Software Foundation
2 # Contact: [email protected]
3 # email package unit tests
4
5 import os
6 import sys
7 import time
8 import base64
9 import difflib
10 import unittest
11 import warnings
12 from cStringIO import StringIO
13
14 import email
15
16 from email.charset import Charset
17 from email.header import Header, decode_header, make_header
18 from email.parser import Parser, HeaderParser
19 from email.generator import Generator, DecodedGenerator
20 from email.message import Message
21 from email.mime.application import MIMEApplication
22 from email.mime.audio import MIMEAudio
23 from email.mime.text import MIMEText
24 from email.mime.image import MIMEImage
25 from email.mime.base import MIMEBase
26 from email.mime.message import MIMEMessage
27 from email.mime.multipart import MIMEMultipart
28 from email import utils
29 from email import errors
30 from email import encoders
31 from email import iterators
32 from email import base64mime
33 from email import quoprimime
34
35 from test.test_support import findfile, run_unittest
36 from email.test import __file__ as landmark
37
38
39 NL = '\n'
40 EMPTYSTRING = ''
41 SPACE = ' '
42
43
44
45 def openfile(filename, mode='r'):
46 path = os.path.join(os.path.dirname(landmark), 'data', filename)
47 return open(path, mode)
48
49
50
51 # Base test class
52 class TestEmailBase(unittest.TestCase):
53 def ndiffAssertEqual(self, first, second):
54 """Like assertEqual except use ndiff for readable output."""
55 if first != second:
56 sfirst = str(first)
57 ssecond = str(second)
58 diff = difflib.ndiff(sfirst.splitlines(), ssecond.splitlines())
59 fp = StringIO()
60 print >> fp, NL, NL.join(diff)
61 raise self.failureException, fp.getvalue()
62
63 def _msgobj(self, filename):
64 fp = openfile(findfile(filename))
65 try:
66 msg = email.message_from_file(fp)
67 finally:
68 fp.close()
69 return msg
70
71
72
73 # Test various aspects of the Message class's API
74 class TestMessageAPI(TestEmailBase):
75 def test_get_all(self):
76 eq = self.assertEqual
77 msg = self._msgobj('msg_20.txt')
78 eq(msg.get_all('cc'), ['[email protected]', '[email protected]', '[email protected]'])
79 eq(msg.get_all('xx', 'n/a'), 'n/a')
80
81 def test_getset_charset(self):
82 eq = self.assertEqual
83 msg = Message()
84 eq(msg.get_charset(), None)
85 charset = Charset('iso-8859-1')
86 msg.set_charset(charset)
87 eq(msg['mime-version'], '1.0')
88 eq(msg.get_content_type(), 'text/plain')
89 eq(msg['content-type'], 'text/plain; charset="iso-8859-1"')
90 eq(msg.get_param('charset'), 'iso-8859-1')
91 eq(msg['content-transfer-encoding'], 'quoted-printable')
92 eq(msg.get_charset().input_charset, 'iso-8859-1')
93 # Remove the charset
94 msg.set_charset(None)
95 eq(msg.get_charset(), None)
96 eq(msg['content-type'], 'text/plain')
97 # Try adding a charset when there's already MIME headers present
98 msg = Message()
99 msg['MIME-Version'] = '2.0'
100 msg['Content-Type'] = 'text/x-weird'
101 msg['Content-Transfer-Encoding'] = 'quinted-puntable'
102 msg.set_charset(charset)
103 eq(msg['mime-version'], '2.0')
104 eq(msg['content-type'], 'text/x-weird; charset="iso-8859-1"')
105 eq(msg['content-transfer-encoding'], 'quinted-puntable')
106
107 def test_set_charset_from_string(self):
108 eq = self.assertEqual
109 msg = Message()
110 msg.set_charset('us-ascii')
111 eq(msg.get_charset().input_charset, 'us-ascii')
112 eq(msg['content-type'], 'text/plain; charset="us-ascii"')
113
114 def test_set_payload_with_charset(self):
115 msg = Message()
116 charset = Charset('iso-8859-1')
117 msg.set_payload('This is a string payload', charset)
118 self.assertEqual(msg.get_charset().input_charset, 'iso-8859-1')
119
120 def test_get_charsets(self):
121 eq = self.assertEqual
122
123 msg = self._msgobj('msg_08.txt')
124 charsets = msg.get_charsets()
125 eq(charsets, [None, 'us-ascii', 'iso-8859-1', 'iso-8859-2', 'koi8-r'])
126
127 msg = self._msgobj('msg_09.txt')
128 charsets = msg.get_charsets('dingbat')
129 eq(charsets, ['dingbat', 'us-ascii', 'iso-8859-1', 'dingbat',
130 'koi8-r'])
131
132 msg = self._msgobj('msg_12.txt')
133 charsets = msg.get_charsets()
134 eq(charsets, [None, 'us-ascii', 'iso-8859-1', None, 'iso-8859-2',
135 'iso-8859-3', 'us-ascii', 'koi8-r'])
136
137 def test_get_filename(self):
138 eq = self.assertEqual
139
140 msg = self._msgobj('msg_04.txt')
141 filenames = [p.get_filename() for p in msg.get_payload()]
142 eq(filenames, ['msg.txt', 'msg.txt'])
143
144 msg = self._msgobj('msg_07.txt')
145 subpart = msg.get_payload(1)
146 eq(subpart.get_filename(), 'dingusfish.gif')
147
148 def test_get_filename_with_name_parameter(self):
149 eq = self.assertEqual
150
151 msg = self._msgobj('msg_44.txt')
152 filenames = [p.get_filename() for p in msg.get_payload()]
153 eq(filenames, ['msg.txt', 'msg.txt'])
154
155 def test_get_boundary(self):
156 eq = self.assertEqual
157 msg = self._msgobj('msg_07.txt')
158 # No quotes!
159 eq(msg.get_boundary(), 'BOUNDARY')
160
161 def test_set_boundary(self):
162 eq = self.assertEqual
163 # This one has no existing boundary parameter, but the Content-Type:
164 # header appears fifth.
165 msg = self._msgobj('msg_01.txt')
166 msg.set_boundary('BOUNDARY')
167 header, value = msg.items()[4]
168 eq(header.lower(), 'content-type')
169 eq(value, 'text/plain; charset="us-ascii"; boundary="BOUNDARY"')
170 # This one has a Content-Type: header, with a boundary, stuck in the
171 # middle of its headers. Make sure the order is preserved; it should
172 # be fifth.
173 msg = self._msgobj('msg_04.txt')
174 msg.set_boundary('BOUNDARY')
175 header, value = msg.items()[4]
176 eq(header.lower(), 'content-type')
177 eq(value, 'multipart/mixed; boundary="BOUNDARY"')
178 # And this one has no Content-Type: header at all.
179 msg = self._msgobj('msg_03.txt')
180 self.assertRaises(errors.HeaderParseError,
181 msg.set_boundary, 'BOUNDARY')
182
183 def test_get_decoded_payload(self):
184 eq = self.assertEqual
185 msg = self._msgobj('msg_10.txt')
186 # The outer message is a multipart
187 eq(msg.get_payload(decode=True), None)
188 # Subpart 1 is 7bit encoded
189 eq(msg.get_payload(0).get_payload(decode=True),
190 'This is a 7bit encoded message.\n')
191 # Subpart 2 is quopri
192 eq(msg.get_payload(1).get_payload(decode=True),
193 '\xa1This is a Quoted Printable encoded message!\n')
194 # Subpart 3 is base64
195 eq(msg.get_payload(2).get_payload(decode=True),
196 'This is a Base64 encoded message.')
197 # Subpart 4 is base64 with a trailing newline, which
198 # used to be stripped (issue 7143).
199 eq(msg.get_payload(3).get_payload(decode=True),
200 'This is a Base64 encoded message.\n')
201 # Subpart 5 has no Content-Transfer-Encoding: header.
202 eq(msg.get_payload(4).get_payload(decode=True),
203 'This has no Content-Transfer-Encoding: header.\n')
204
205 def test_get_decoded_uu_payload(self):
206 eq = self.assertEqual
207 msg = Message()
208 msg.set_payload('begin 666 -\n+:&5L;&\\@=V]R;&0 \n \nend\n')
209 for cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'):
210 msg['content-transfer-encoding'] = cte
211 eq(msg.get_payload(decode=True), 'hello world')
212 # Now try some bogus data
213 msg.set_payload('foo')
214 eq(msg.get_payload(decode=True), 'foo')
215
216 def test_decoded_generator(self):
217 eq = self.assertEqual
218 msg = self._msgobj('msg_07.txt')
219 fp = openfile('msg_17.txt')
220 try:
221 text = fp.read()
222 finally:
223 fp.close()
224 s = StringIO()
225 g = DecodedGenerator(s)
226 g.flatten(msg)
227 eq(s.getvalue(), text)
228
229 def test__contains__(self):
230 msg = Message()
231 msg['From'] = 'Me'
232 msg['to'] = 'You'
233 # Check for case insensitivity
234 self.assertIn('from', msg)
235 self.assertIn('From', msg)
236 self.assertIn('FROM', msg)
237 self.assertIn('to', msg)
238 self.assertIn('To', msg)
239 self.assertIn('TO', msg)
240
241 def test_as_string(self):
242 eq = self.assertEqual
243 msg = self._msgobj('msg_01.txt')
244 fp = openfile('msg_01.txt')
245 try:
246 # BAW 30-Mar-2009 Evil be here. So, the generator is broken with
247 # respect to long line breaking. It's also not idempotent when a
248 # header from a parsed message is continued with tabs rather than
249 # spaces. Before we fixed bug 1974 it was reversedly broken,
250 # i.e. headers that were continued with spaces got continued with
251 # tabs. For Python 2.x there's really no good fix and in Python
252 # 3.x all this stuff is re-written to be right(er). Chris Withers
253 # convinced me that using space as the default continuation
254 # character is less bad for more applications.
255 text = fp.read().replace('\t', ' ')
256 finally:
257 fp.close()
258 self.ndiffAssertEqual(text, msg.as_string())
259 fullrepr = str(msg)
260 lines = fullrepr.split('\n')
261 self.assertTrue(lines[0].startswith('From '))
262 eq(text, NL.join(lines[1:]))
263
264 def test_bad_param(self):
265 msg = email.message_from_string("Content-Type: blarg; baz; boo\n")
266 self.assertEqual(msg.get_param('baz'), '')
267
268 def test_missing_filename(self):
269 msg = email.message_from_string("From: foo\n")
270 self.assertEqual(msg.get_filename(), None)
271
272 def test_bogus_filename(self):
273 msg = email.message_from_string(
274 "Content-Disposition: blarg; filename\n")
275 self.assertEqual(msg.get_filename(), '')
276
277 def test_missing_boundary(self):
278 msg = email.message_from_string("From: foo\n")
279 self.assertEqual(msg.get_boundary(), None)
280
281 def test_get_params(self):
282 eq = self.assertEqual
283 msg = email.message_from_string(
284 'X-Header: foo=one; bar=two; baz=three\n')
285 eq(msg.get_params(header='x-header'),
286 [('foo', 'one'), ('bar', 'two'), ('baz', 'three')])
287 msg = email.message_from_string(
288 'X-Header: foo; bar=one; baz=two\n')
289 eq(msg.get_params(header='x-header'),
290 [('foo', ''), ('bar', 'one'), ('baz', 'two')])
291 eq(msg.get_params(), None)
292 msg = email.message_from_string(
293 'X-Header: foo; bar="one"; baz=two\n')
294 eq(msg.get_params(header='x-header'),
295 [('foo', ''), ('bar', 'one'), ('baz', 'two')])
296
297 def test_get_param_liberal(self):
298 msg = Message()
299 msg['Content-Type'] = 'Content-Type: Multipart/mixed; boundary = "CPIMSSMTPC06p5f3tG"'
300 self.assertEqual(msg.get_param('boundary'), 'CPIMSSMTPC06p5f3tG')
301
302 def test_get_param(self):
303 eq = self.assertEqual
304 msg = email.message_from_string(
305 "X-Header: foo=one; bar=two; baz=three\n")
306 eq(msg.get_param('bar', header='x-header'), 'two')
307 eq(msg.get_param('quuz', header='x-header'), None)
308 eq(msg.get_param('quuz'), None)
309 msg = email.message_from_string(
310 'X-Header: foo; bar="one"; baz=two\n')
311 eq(msg.get_param('foo', header='x-header'), '')
312 eq(msg.get_param('bar', header='x-header'), 'one')
313 eq(msg.get_param('baz', header='x-header'), 'two')
314 # XXX: We are not RFC-2045 compliant! We cannot parse:
315 # msg["Content-Type"] = 'text/plain; weird="hey; dolly? [you] @ <\\"home\\">?"'
316 # msg.get_param("weird")
317 # yet.
318
319 def test_get_param_funky_continuation_lines(self):
320 msg = self._msgobj('msg_22.txt')
321 self.assertEqual(msg.get_payload(1).get_param('name'), 'wibble.JPG')
322
323 def test_get_param_with_semis_in_quotes(self):
324 msg = email.message_from_string(
325 'Content-Type: image/pjpeg; name="Jim&amp;&amp;Jill"\n')
326 self.assertEqual(msg.get_param('name'), 'Jim&amp;&amp;Jill')
327 self.assertEqual(msg.get_param('name', unquote=False),
328 '"Jim&amp;&amp;Jill"')
329
330 def test_has_key(self):
331 msg = email.message_from_string('Header: exists')
332 self.assertTrue(msg.has_key('header'))
333 self.assertTrue(msg.has_key('Header'))
334 self.assertTrue(msg.has_key('HEADER'))
335 self.assertFalse(msg.has_key('headeri'))
336
337 def test_set_param(self):
338 eq = self.assertEqual
339 msg = Message()
340 msg.set_param('charset', 'iso-2022-jp')
341 eq(msg.get_param('charset'), 'iso-2022-jp')
342 msg.set_param('importance', 'high value')
343 eq(msg.get_param('importance'), 'high value')
344 eq(msg.get_param('importance', unquote=False), '"high value"')
345 eq(msg.get_params(), [('text/plain', ''),
346 ('charset', 'iso-2022-jp'),
347 ('importance', 'high value')])
348 eq(msg.get_params(unquote=False), [('text/plain', ''),
349 ('charset', '"iso-2022-jp"'),
350 ('importance', '"high value"')])
351 msg.set_param('charset', 'iso-9999-xx', header='X-Jimmy')
352 eq(msg.get_param('charset', header='X-Jimmy'), 'iso-9999-xx')
353
354 def test_del_param(self):
355 eq = self.assertEqual
356 msg = self._msgobj('msg_05.txt')
357 eq(msg.get_params(),
358 [('multipart/report', ''), ('report-type', 'delivery-status'),
359 ('boundary', 'D1690A7AC1.996856090/mail.example.com')])
360 old_val = msg.get_param("report-type")
361 msg.del_param("report-type")
362 eq(msg.get_params(),
363 [('multipart/report', ''),
364 ('boundary', 'D1690A7AC1.996856090/mail.example.com')])
365 msg.set_param("report-type", old_val)
366 eq(msg.get_params(),
367 [('multipart/report', ''),
368 ('boundary', 'D1690A7AC1.996856090/mail.example.com'),
369 ('report-type', old_val)])
370
371 def test_del_param_on_other_header(self):
372 msg = Message()
373 msg.add_header('Content-Disposition', 'attachment', filename='bud.gif')
374 msg.del_param('filename', 'content-disposition')
375 self.assertEqual(msg['content-disposition'], 'attachment')
376
377 def test_set_type(self):
378 eq = self.assertEqual
379 msg = Message()
380 self.assertRaises(ValueError, msg.set_type, 'text')
381 msg.set_type('text/plain')
382 eq(msg['content-type'], 'text/plain')
383 msg.set_param('charset', 'us-ascii')
384 eq(msg['content-type'], 'text/plain; charset="us-ascii"')
385 msg.set_type('text/html')
386 eq(msg['content-type'], 'text/html; charset="us-ascii"')
387
388 def test_set_type_on_other_header(self):
389 msg = Message()
390 msg['X-Content-Type'] = 'text/plain'
391 msg.set_type('application/octet-stream', 'X-Content-Type')
392 self.assertEqual(msg['x-content-type'], 'application/octet-stream')
393
394 def test_get_content_type_missing(self):
395 msg = Message()
396 self.assertEqual(msg.get_content_type(), 'text/plain')
397
398 def test_get_content_type_missing_with_default_type(self):
399 msg = Message()
400 msg.set_default_type('message/rfc822')
401 self.assertEqual(msg.get_content_type(), 'message/rfc822')
402
403 def test_get_content_type_from_message_implicit(self):
404 msg = self._msgobj('msg_30.txt')
405 self.assertEqual(msg.get_payload(0).get_content_type(),
406 'message/rfc822')
407
408 def test_get_content_type_from_message_explicit(self):
409 msg = self._msgobj('msg_28.txt')
410 self.assertEqual(msg.get_payload(0).get_content_type(),
411 'message/rfc822')
412
413 def test_get_content_type_from_message_text_plain_implicit(self):
414 msg = self._msgobj('msg_03.txt')
415 self.assertEqual(msg.get_content_type(), 'text/plain')
416
417 def test_get_content_type_from_message_text_plain_explicit(self):
418 msg = self._msgobj('msg_01.txt')
419 self.assertEqual(msg.get_content_type(), 'text/plain')
420
421 def test_get_content_maintype_missing(self):
422 msg = Message()
423 self.assertEqual(msg.get_content_maintype(), 'text')
424
425 def test_get_content_maintype_missing_with_default_type(self):
426 msg = Message()
427 msg.set_default_type('message/rfc822')
428 self.assertEqual(msg.get_content_maintype(), 'message')
429
430 def test_get_content_maintype_from_message_implicit(self):
431 msg = self._msgobj('msg_30.txt')
432 self.assertEqual(msg.get_payload(0).get_content_maintype(), 'message')
433
434 def test_get_content_maintype_from_message_explicit(self):
435 msg = self._msgobj('msg_28.txt')
436 self.assertEqual(msg.get_payload(0).get_content_maintype(), 'message')
437
438 def test_get_content_maintype_from_message_text_plain_implicit(self):
439 msg = self._msgobj('msg_03.txt')
440 self.assertEqual(msg.get_content_maintype(), 'text')
441
442 def test_get_content_maintype_from_message_text_plain_explicit(self):
443 msg = self._msgobj('msg_01.txt')
444 self.assertEqual(msg.get_content_maintype(), 'text')
445
446 def test_get_content_subtype_missing(self):
447 msg = Message()
448 self.assertEqual(msg.get_content_subtype(), 'plain')
449
450 def test_get_content_subtype_missing_with_default_type(self):
451 msg = Message()
452 msg.set_default_type('message/rfc822')
453 self.assertEqual(msg.get_content_subtype(), 'rfc822')
454
455 def test_get_content_subtype_from_message_implicit(self):
456 msg = self._msgobj('msg_30.txt')
457 self.assertEqual(msg.get_payload(0).get_content_subtype(), 'rfc822')
458
459 def test_get_content_subtype_from_message_explicit(self):
460 msg = self._msgobj('msg_28.txt')
461 self.assertEqual(msg.get_payload(0).get_content_subtype(), 'rfc822')
462
463 def test_get_content_subtype_from_message_text_plain_implicit(self):
464 msg = self._msgobj('msg_03.txt')
465 self.assertEqual(msg.get_content_subtype(), 'plain')
466
467 def test_get_content_subtype_from_message_text_plain_explicit(self):
468 msg = self._msgobj('msg_01.txt')
469 self.assertEqual(msg.get_content_subtype(), 'plain')
470
471 def test_get_content_maintype_error(self):
472 msg = Message()
473 msg['Content-Type'] = 'no-slash-in-this-string'
474 self.assertEqual(msg.get_content_maintype(), 'text')
475
476 def test_get_content_subtype_error(self):
477 msg = Message()
478 msg['Content-Type'] = 'no-slash-in-this-string'
479 self.assertEqual(msg.get_content_subtype(), 'plain')
480
481 def test_replace_header(self):
482 eq = self.assertEqual
483 msg = Message()
484 msg.add_header('First', 'One')
485 msg.add_header('Second', 'Two')
486 msg.add_header('Third', 'Three')
487 eq(msg.keys(), ['First', 'Second', 'Third'])
488 eq(msg.values(), ['One', 'Two', 'Three'])
489 msg.replace_header('Second', 'Twenty')
490 eq(msg.keys(), ['First', 'Second', 'Third'])
491 eq(msg.values(), ['One', 'Twenty', 'Three'])
492 msg.add_header('First', 'Eleven')
493 msg.replace_header('First', 'One Hundred')
494 eq(msg.keys(), ['First', 'Second', 'Third', 'First'])
495 eq(msg.values(), ['One Hundred', 'Twenty', 'Three', 'Eleven'])
496 self.assertRaises(KeyError, msg.replace_header, 'Fourth', 'Missing')
497
498 def test_broken_base64_payload(self):
499 x = 'AwDp0P7//y6LwKEAcPa/6Q=9'
500 msg = Message()
501 msg['content-type'] = 'audio/x-midi'
502 msg['content-transfer-encoding'] = 'base64'
503 msg.set_payload(x)
504 self.assertEqual(msg.get_payload(decode=True), x)
505
506
507
508 # Test the email.encoders module
509 class TestEncoders(unittest.TestCase):
510 def test_encode_empty_payload(self):
511 eq = self.assertEqual
512 msg = Message()
513 msg.set_charset('us-ascii')
514 eq(msg['content-transfer-encoding'], '7bit')
515
516 def test_default_cte(self):
517 eq = self.assertEqual
518 # With no explicit _charset its us-ascii, and all are 7-bit
519 msg = MIMEText('hello world')
520 eq(msg['content-transfer-encoding'], '7bit')
521 # Similar, but with 8-bit data
522 msg = MIMEText('hello \xf8 world')
523 eq(msg['content-transfer-encoding'], '8bit')
524 # And now with a different charset
525 msg = MIMEText('hello \xf8 world', _charset='iso-8859-1')
526 eq(msg['content-transfer-encoding'], 'quoted-printable')
527
528
529
530 # Test long header wrapping
531 class TestLongHeaders(TestEmailBase):
532 def test_split_long_continuation(self):
533 eq = self.ndiffAssertEqual
534 msg = email.message_from_string("""\
535 Subject: bug demonstration
536 \t12345678911234567892123456789312345678941234567895123456789612345678971234567898112345678911234567892123456789112345678911234567892123456789
537 \tmore text
538
539 test
540 """)
541 sfp = StringIO()
542 g = Generator(sfp)
543 g.flatten(msg)
544 eq(sfp.getvalue(), """\
545 Subject: bug demonstration
546 12345678911234567892123456789312345678941234567895123456789612345678971234567898112345678911234567892123456789112345678911234567892123456789
547 more text
548
549 test
550 """)
551
552 def test_another_long_almost_unsplittable_header(self):
553 eq = self.ndiffAssertEqual
554 hstr = """\
555 bug demonstration
556 \t12345678911234567892123456789312345678941234567895123456789612345678971234567898112345678911234567892123456789112345678911234567892123456789
557 \tmore text"""
558 h = Header(hstr, continuation_ws='\t')
559 eq(h.encode(), """\
560 bug demonstration
561 \t12345678911234567892123456789312345678941234567895123456789612345678971234567898112345678911234567892123456789112345678911234567892123456789
562 \tmore text""")
563 h = Header(hstr)
564 eq(h.encode(), """\
565 bug demonstration
566 12345678911234567892123456789312345678941234567895123456789612345678971234567898112345678911234567892123456789112345678911234567892123456789
567 more text""")
568
569 def test_long_nonstring(self):
570 eq = self.ndiffAssertEqual
571 g = Charset("iso-8859-1")
572 cz = Charset("iso-8859-2")
573 utf8 = Charset("utf-8")
574 g_head = "Die Mieter treten hier ein werden mit einem Foerderband komfortabel den Korridor entlang, an s\xfcdl\xfcndischen Wandgem\xe4lden vorbei, gegen die rotierenden Klingen bef\xf6rdert. "
575 cz_head = "Finan\xe8ni metropole se hroutily pod tlakem jejich d\xf9vtipu.. "
576 utf8_head = u"\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das Nunstuck git und Slotermeyer? Ja! Beiherhund das Oder die Flipperwaldt gersput.\u300d\u3068\u8a00\u3063\u3066\u3044\u307e\u3059\u3002".encode("utf-8")
577 h = Header(g_head, g, header_name='Subject')
578 h.append(cz_head, cz)
579 h.append(utf8_head, utf8)
580 msg = Message()
581 msg['Subject'] = h
582 sfp = StringIO()
583 g = Generator(sfp)
584 g.flatten(msg)
585 eq(sfp.getvalue(), """\
586 Subject: =?iso-8859-1?q?Die_Mieter_treten_hier_ein_werden_mit_einem_Foerd?=
587 =?iso-8859-1?q?erband_komfortabel_den_Korridor_entlang=2C_an_s=FCdl=FCndi?=
588 =?iso-8859-1?q?schen_Wandgem=E4lden_vorbei=2C_gegen_die_rotierenden_Kling?=
589 =?iso-8859-1?q?en_bef=F6rdert=2E_?= =?iso-8859-2?q?Finan=E8ni_met?=
590 =?iso-8859-2?q?ropole_se_hroutily_pod_tlakem_jejich_d=F9vtipu=2E=2E_?=
591 =?utf-8?b?5q2j56K644Gr6KiA44GG44Go57+76Kiz44Gv44GV44KM44Gm44GE?=
592 =?utf-8?b?44G+44Gb44KT44CC5LiA6YOo44Gv44OJ44Kk44OE6Kqe44Gn44GZ44GM44CB?=
593 =?utf-8?b?44GC44Go44Gv44Gn44Gf44KJ44KB44Gn44GZ44CC5a6f6Zqb44Gr44Gv44CM?=
594 =?utf-8?q?Wenn_ist_das_Nunstuck_git_und_Slotermeyer=3F_Ja!_Beiherhund_das?=
595 =?utf-8?b?IE9kZXIgZGllIEZsaXBwZXJ3YWxkdCBnZXJzcHV0LuOAjeOBqOiogOOBow==?=
596 =?utf-8?b?44Gm44GE44G+44GZ44CC?=
597
598 """)
599 eq(h.encode(), """\
600 =?iso-8859-1?q?Die_Mieter_treten_hier_ein_werden_mit_einem_Foerd?=
601 =?iso-8859-1?q?erband_komfortabel_den_Korridor_entlang=2C_an_s=FCdl=FCndi?=
602 =?iso-8859-1?q?schen_Wandgem=E4lden_vorbei=2C_gegen_die_rotierenden_Kling?=
603 =?iso-8859-1?q?en_bef=F6rdert=2E_?= =?iso-8859-2?q?Finan=E8ni_met?=
604 =?iso-8859-2?q?ropole_se_hroutily_pod_tlakem_jejich_d=F9vtipu=2E=2E_?=
605 =?utf-8?b?5q2j56K644Gr6KiA44GG44Go57+76Kiz44Gv44GV44KM44Gm44GE?=
606 =?utf-8?b?44G+44Gb44KT44CC5LiA6YOo44Gv44OJ44Kk44OE6Kqe44Gn44GZ44GM44CB?=
607 =?utf-8?b?44GC44Go44Gv44Gn44Gf44KJ44KB44Gn44GZ44CC5a6f6Zqb44Gr44Gv44CM?=
608 =?utf-8?q?Wenn_ist_das_Nunstuck_git_und_Slotermeyer=3F_Ja!_Beiherhund_das?=
609 =?utf-8?b?IE9kZXIgZGllIEZsaXBwZXJ3YWxkdCBnZXJzcHV0LuOAjeOBqOiogOOBow==?=
610 =?utf-8?b?44Gm44GE44G+44GZ44CC?=""")
611
612 def test_long_header_encode(self):
613 eq = self.ndiffAssertEqual
614 h = Header('wasnipoop; giraffes="very-long-necked-animals"; '
615 'spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"',
616 header_name='X-Foobar-Spoink-Defrobnit')
617 eq(h.encode(), '''\
618 wasnipoop; giraffes="very-long-necked-animals";
619 spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"''')
620
621 def test_long_header_encode_with_tab_continuation(self):
622 eq = self.ndiffAssertEqual
623 h = Header('wasnipoop; giraffes="very-long-necked-animals"; '
624 'spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"',
625 header_name='X-Foobar-Spoink-Defrobnit',
626 continuation_ws='\t')
627 eq(h.encode(), '''\
628 wasnipoop; giraffes="very-long-necked-animals";
629 \tspooge="yummy"; hippos="gargantuan"; marshmallows="gooey"''')
630
631 def test_header_splitter(self):
632 eq = self.ndiffAssertEqual
633 msg = MIMEText('')
634 # It'd be great if we could use add_header() here, but that doesn't
635 # guarantee an order of the parameters.
636 msg['X-Foobar-Spoink-Defrobnit'] = (
637 'wasnipoop; giraffes="very-long-necked-animals"; '
638 'spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"')
639 sfp = StringIO()
640 g = Generator(sfp)
641 g.flatten(msg)
642 eq(sfp.getvalue(), '''\
643 Content-Type: text/plain; charset="us-ascii"
644 MIME-Version: 1.0
645 Content-Transfer-Encoding: 7bit
646 X-Foobar-Spoink-Defrobnit: wasnipoop; giraffes="very-long-necked-animals";
647 spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"
648
649 ''')
650
651 def test_no_semis_header_splitter(self):
652 eq = self.ndiffAssertEqual
653 msg = Message()
654 msg['From'] = '[email protected]'
655 msg['References'] = SPACE.join(['<%[email protected]>' % i for i in range(10)])
656 msg.set_payload('Test')
657 sfp = StringIO()
658 g = Generator(sfp)
659 g.flatten(msg)
660 eq(sfp.getvalue(), """\
661 From: [email protected]
662 References: <[email protected]> <[email protected]> <[email protected]> <[email protected]> <[email protected]>
663 <[email protected]> <[email protected]> <[email protected]> <[email protected]> <[email protected]>
664
665 Test""")
666
667 def test_no_split_long_header(self):
668 eq = self.ndiffAssertEqual
669 hstr = 'References: ' + 'x' * 80
670 h = Header(hstr, continuation_ws='\t')
671 eq(h.encode(), """\
672 References: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx""")
673
674 def test_splitting_multiple_long_lines(self):
675 eq = self.ndiffAssertEqual
676 hstr = """\
677 from babylon.socal-raves.org (localhost [127.0.0.1]); by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81; for <[email protected]>; Sat, 2 Feb 2002 17:00:06 -0800 (PST)
678 \tfrom babylon.socal-raves.org (localhost [127.0.0.1]); by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81; for <[email protected]>; Sat, 2 Feb 2002 17:00:06 -0800 (PST)
679 \tfrom babylon.socal-raves.org (localhost [127.0.0.1]); by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81; for <[email protected]>; Sat, 2 Feb 2002 17:00:06 -0800 (PST)
680 """
681 h = Header(hstr, continuation_ws='\t')
682 eq(h.encode(), """\
683 from babylon.socal-raves.org (localhost [127.0.0.1]);
684 \tby babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81;
685 \tfor <[email protected]>;
686 \tSat, 2 Feb 2002 17:00:06 -0800 (PST)
687 \tfrom babylon.socal-raves.org (localhost [127.0.0.1]);
688 \tby babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81;
689 \tfor <[email protected]>;
690 \tSat, 2 Feb 2002 17:00:06 -0800 (PST)
691 \tfrom babylon.socal-raves.org (localhost [127.0.0.1]);
692 \tby babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81;
693 \tfor <[email protected]>;
694 \tSat, 2 Feb 2002 17:00:06 -0800 (PST)""")
695
696 def test_splitting_first_line_only_is_long(self):
697 eq = self.ndiffAssertEqual
698 hstr = """\
699 from modemcable093.139-201-24.que.mc.videotron.ca ([24.201.139.93] helo=cthulhu.gerg.ca)
700 \tby kronos.mems-exchange.org with esmtp (Exim 4.05)
701 \tid 17k4h5-00034i-00
702 \tfor [email protected]; Wed, 28 Aug 2002 11:25:20 -0400"""
703 h = Header(hstr, maxlinelen=78, header_name='Received',
704 continuation_ws='\t')
705 eq(h.encode(), """\
706 from modemcable093.139-201-24.que.mc.videotron.ca ([24.201.139.93]
707 \thelo=cthulhu.gerg.ca)
708 \tby kronos.mems-exchange.org with esmtp (Exim 4.05)
709 \tid 17k4h5-00034i-00
710 \tfor [email protected]; Wed, 28 Aug 2002 11:25:20 -0400""")
711
712 def test_long_8bit_header(self):
713 eq = self.ndiffAssertEqual
714 msg = Message()
715 h = Header('Britische Regierung gibt', 'iso-8859-1',
716 header_name='Subject')
717 h.append('gr\xfcnes Licht f\xfcr Offshore-Windkraftprojekte')
718 msg['Subject'] = h
719 eq(msg.as_string(), """\
720 Subject: =?iso-8859-1?q?Britische_Regierung_gibt?= =?iso-8859-1?q?gr=FCnes?=
721 =?iso-8859-1?q?_Licht_f=FCr_Offshore-Windkraftprojekte?=
722
723 """)
724
725 def test_long_8bit_header_no_charset(self):
726 eq = self.ndiffAssertEqual
727 msg = Message()
728 msg['Reply-To'] = 'Britische Regierung gibt gr\xfcnes Licht f\xfcr Offshore-Windkraftprojekte <[email protected]>'
729 eq(msg.as_string(), """\
730 Reply-To: Britische Regierung gibt gr\xfcnes Licht f\xfcr Offshore-Windkraftprojekte <[email protected]>
731
732 """)
733
734 def test_long_to_header(self):
735 eq = self.ndiffAssertEqual
736 to = '"Someone Test #A" <[email protected]>,<[email protected]>,"Someone Test #B" <[email protected]>, "Someone Test #C" <[email protected]>, "Someone Test #D" <[email protected]>'
737 msg = Message()
738 msg['To'] = to
739 eq(msg.as_string(0), '''\
740 To: "Someone Test #A" <[email protected]>, <[email protected]>,
741 "Someone Test #B" <[email protected]>,
742 "Someone Test #C" <[email protected]>,
743 "Someone Test #D" <[email protected]>
744
745 ''')
746
747 def test_long_line_after_append(self):
748 eq = self.ndiffAssertEqual
749 s = 'This is an example of string which has almost the limit of header length.'
750 h = Header(s)
751 h.append('Add another line.')
752 eq(h.encode(), """\
753 This is an example of string which has almost the limit of header length.
754 Add another line.""")
755
756 def test_shorter_line_with_append(self):
757 eq = self.ndiffAssertEqual
758 s = 'This is a shorter line.'
759 h = Header(s)
760 h.append('Add another sentence. (Surprise?)')
761 eq(h.encode(),
762 'This is a shorter line. Add another sentence. (Surprise?)')
763
764 def test_long_field_name(self):
765 eq = self.ndiffAssertEqual
766 fn = 'X-Very-Very-Very-Long-Header-Name'
767 gs = "Die Mieter treten hier ein werden mit einem Foerderband komfortabel den Korridor entlang, an s\xfcdl\xfcndischen Wandgem\xe4lden vorbei, gegen die rotierenden Klingen bef\xf6rdert. "
768 h = Header(gs, 'iso-8859-1', header_name=fn)
769 # BAW: this seems broken because the first line is too long
770 eq(h.encode(), """\
771 =?iso-8859-1?q?Die_Mieter_treten_hier_?=
772 =?iso-8859-1?q?ein_werden_mit_einem_Foerderband_komfortabel_den_Korridor_?=
773 =?iso-8859-1?q?entlang=2C_an_s=FCdl=FCndischen_Wandgem=E4lden_vorbei=2C_g?=
774 =?iso-8859-1?q?egen_die_rotierenden_Klingen_bef=F6rdert=2E_?=""")
775
776 def test_long_received_header(self):
777 h = 'from FOO.TLD (vizworld.acl.foo.tld [123.452.678.9]) by hrothgar.la.mastaler.com (tmda-ofmipd) with ESMTP; Wed, 05 Mar 2003 18:10:18 -0700'
778 msg = Message()
779 msg['Received-1'] = Header(h, continuation_ws='\t')
780 msg['Received-2'] = h
781 self.ndiffAssertEqual(msg.as_string(), """\
782 Received-1: from FOO.TLD (vizworld.acl.foo.tld [123.452.678.9]) by
783 \throthgar.la.mastaler.com (tmda-ofmipd) with ESMTP;
784 \tWed, 05 Mar 2003 18:10:18 -0700
785 Received-2: from FOO.TLD (vizworld.acl.foo.tld [123.452.678.9]) by
786 hrothgar.la.mastaler.com (tmda-ofmipd) with ESMTP;
787 Wed, 05 Mar 2003 18:10:18 -0700
788
789 """)
790
791 def test_string_headerinst_eq(self):
792 h = '<15975.17901.207240.414604@sgigritzmann1.mathematik.tu-muenchen.de> (David Bremner\'s message of "Thu, 6 Mar 2003 13:58:21 +0100")'
793 msg = Message()
794 msg['Received'] = Header(h, header_name='Received-1',
795 continuation_ws='\t')
796 msg['Received'] = h
797 self.ndiffAssertEqual(msg.as_string(), """\
798 Received: <15975.17901.207240.414604@sgigritzmann1.mathematik.tu-muenchen.de>
799 \t(David Bremner's message of "Thu, 6 Mar 2003 13:58:21 +0100")
800 Received: <15975.17901.207240.414604@sgigritzmann1.mathematik.tu-muenchen.de>
801 (David Bremner's message of "Thu, 6 Mar 2003 13:58:21 +0100")
802
803 """)
804
805 def test_long_unbreakable_lines_with_continuation(self):
806 eq = self.ndiffAssertEqual
807 msg = Message()
808 t = """\
809 iVBORw0KGgoAAAANSUhEUgAAADAAAAAwBAMAAAClLOS0AAAAGFBMVEUAAAAkHiJeRUIcGBi9
810 locQDQ4zJykFBAXJfWDjAAACYUlEQVR4nF2TQY/jIAyFc6lydlG5x8Nyp1Y69wj1PN2I5gzp"""
811 msg['Face-1'] = t
812 msg['Face-2'] = Header(t, header_name='Face-2')
813 eq(msg.as_string(), """\
814 Face-1: iVBORw0KGgoAAAANSUhEUgAAADAAAAAwBAMAAAClLOS0AAAAGFBMVEUAAAAkHiJeRUIcGBi9
815 locQDQ4zJykFBAXJfWDjAAACYUlEQVR4nF2TQY/jIAyFc6lydlG5x8Nyp1Y69wj1PN2I5gzp
816 Face-2: iVBORw0KGgoAAAANSUhEUgAAADAAAAAwBAMAAAClLOS0AAAAGFBMVEUAAAAkHiJeRUIcGBi9
817 locQDQ4zJykFBAXJfWDjAAACYUlEQVR4nF2TQY/jIAyFc6lydlG5x8Nyp1Y69wj1PN2I5gzp
818
819 """)
820
821 def test_another_long_multiline_header(self):
822 eq = self.ndiffAssertEqual
823 m = '''\
824 Received: from siimage.com ([172.25.1.3]) by zima.siliconimage.com with Microsoft SMTPSVC(5.0.2195.4905);
825 Wed, 16 Oct 2002 07:41:11 -0700'''
826 msg = email.message_from_string(m)
827 eq(msg.as_string(), '''\
828 Received: from siimage.com ([172.25.1.3]) by zima.siliconimage.com with
829 Microsoft SMTPSVC(5.0.2195.4905); Wed, 16 Oct 2002 07:41:11 -0700
830
831 ''')
832
833 def test_long_lines_with_different_header(self):
834 eq = self.ndiffAssertEqual
835 h = """\
836 List-Unsubscribe: <https://lists.sourceforge.net/lists/listinfo/spamassassin-talk>,
837 <mailto:[email protected]?subject=unsubscribe>"""
838 msg = Message()
839 msg['List'] = h
840 msg['List'] = Header(h, header_name='List')
841 self.ndiffAssertEqual(msg.as_string(), """\
842 List: List-Unsubscribe: <https://lists.sourceforge.net/lists/listinfo/spamassassin-talk>,
843 <mailto:[email protected]?subject=unsubscribe>
844 List: List-Unsubscribe: <https://lists.sourceforge.net/lists/listinfo/spamassassin-talk>,
845 <mailto:[email protected]?subject=unsubscribe>
846
847 """)
848
849
850
851 # Test mangling of "From " lines in the body of a message
852 class TestFromMangling(unittest.TestCase):
853 def setUp(self):
854 self.msg = Message()
855 self.msg['From'] = '[email protected]'
856 self.msg.set_payload("""\
857 From the desk of A.A.A.:
858 Blah blah blah
859 """)
860
861 def test_mangled_from(self):
862 s = StringIO()
863 g = Generator(s, mangle_from_=True)
864 g.flatten(self.msg)
865 self.assertEqual(s.getvalue(), """\
866 From: [email protected]
867
868 >From the desk of A.A.A.:
869 Blah blah blah
870 """)
871
872 def test_dont_mangle_from(self):
873 s = StringIO()
874 g = Generator(s, mangle_from_=False)
875 g.flatten(self.msg)
876 self.assertEqual(s.getvalue(), """\
877 From: [email protected]
878
879 From the desk of A.A.A.:
880 Blah blah blah
881 """)
882
883
884
885 # Test the basic MIMEAudio class
886 class TestMIMEAudio(unittest.TestCase):
887 def setUp(self):
888 # Make sure we pick up the audiotest.au that lives in email/test/data.
889 # In Python, there's an audiotest.au living in Lib/test but that isn't
890 # included in some binary distros that don't include the test
891 # package. The trailing empty string on the .join() is significant
892 # since findfile() will do a dirname().
893 datadir = os.path.join(os.path.dirname(landmark), 'data', '')
894 fp = open(findfile('audiotest.au', datadir), 'rb')
895 try:
896 self._audiodata = fp.read()
897 finally:
898 fp.close()
899 self._au = MIMEAudio(self._audiodata)
900
901 def test_guess_minor_type(self):
902 self.assertEqual(self._au.get_content_type(), 'audio/basic')
903
904 def test_encoding(self):
905 payload = self._au.get_payload()
906 self.assertEqual(base64.decodestring(payload), self._audiodata)
907
908 def test_checkSetMinor(self):
909 au = MIMEAudio(self._audiodata, 'fish')
910 self.assertEqual(au.get_content_type(), 'audio/fish')
911
912 def test_add_header(self):
913 eq = self.assertEqual
914 self._au.add_header('Content-Disposition', 'attachment',
915 filename='audiotest.au')
916 eq(self._au['content-disposition'],
917 'attachment; filename="audiotest.au"')
918 eq(self._au.get_params(header='content-disposition'),
919 [('attachment', ''), ('filename', 'audiotest.au')])
920 eq(self._au.get_param('filename', header='content-disposition'),
921 'audiotest.au')
922 missing = []
923 eq(self._au.get_param('attachment', header='content-disposition'), '')
924 self.assertIs(self._au.get_param('foo', failobj=missing,
925 header='content-disposition'),
926 missing)
927 # Try some missing stuff
928 self.assertIs(self._au.get_param('foobar', missing), missing)
929 self.assertIs(self._au.get_param('attachment', missing,
930 header='foobar'), missing)
931
932
933
934 # Test the basic MIMEImage class
935 class TestMIMEImage(unittest.TestCase):
936 def setUp(self):
937 fp = openfile('PyBanner048.gif')
938 try:
939 self._imgdata = fp.read()
940 finally:
941 fp.close()
942 self._im = MIMEImage(self._imgdata)
943
944 def test_guess_minor_type(self):
945 self.assertEqual(self._im.get_content_type(), 'image/gif')
946
947 def test_encoding(self):
948 payload = self._im.get_payload()
949 self.assertEqual(base64.decodestring(payload), self._imgdata)
950
951 def test_checkSetMinor(self):
952 im = MIMEImage(self._imgdata, 'fish')
953 self.assertEqual(im.get_content_type(), 'image/fish')
954
955 def test_add_header(self):
956 eq = self.assertEqual
957 self._im.add_header('Content-Disposition', 'attachment',
958 filename='dingusfish.gif')
959 eq(self._im['content-disposition'],
960 'attachment; filename="dingusfish.gif"')
961 eq(self._im.get_params(header='content-disposition'),
962 [('attachment', ''), ('filename', 'dingusfish.gif')])
963 eq(self._im.get_param('filename', header='content-disposition'),
964 'dingusfish.gif')
965 missing = []
966 eq(self._im.get_param('attachment', header='content-disposition'), '')
967 self.assertIs(self._im.get_param('foo', failobj=missing,
968 header='content-disposition'),
969 missing)
970 # Try some missing stuff
971 self.assertIs(self._im.get_param('foobar', missing), missing)
972 self.assertIs(self._im.get_param('attachment', missing,
973 header='foobar'), missing)
974
975
976
977 # Test the basic MIMEApplication class
978 class TestMIMEApplication(unittest.TestCase):
979 def test_headers(self):
980 eq = self.assertEqual
981 msg = MIMEApplication('\xfa\xfb\xfc\xfd\xfe\xff')
982 eq(msg.get_content_type(), 'application/octet-stream')
983 eq(msg['content-transfer-encoding'], 'base64')
984
985 def test_body(self):
986 eq = self.assertEqual
987 bytes = '\xfa\xfb\xfc\xfd\xfe\xff'
988 msg = MIMEApplication(bytes)
989 eq(msg.get_payload(), '+vv8/f7/')
990 eq(msg.get_payload(decode=True), bytes)
991
992 def test_binary_body_with_encode_7or8bit(self):
993 # Issue 17171.
994 bytesdata = b'\xfa\xfb\xfc\xfd\xfe\xff'
995 msg = MIMEApplication(bytesdata, _encoder=encoders.encode_7or8bit)
996 # Treated as a string, this will be invalid code points.
997 self.assertEqual(msg.get_payload(), bytesdata)
998 self.assertEqual(msg.get_payload(decode=True), bytesdata)
999 self.assertEqual(msg['Content-Transfer-Encoding'], '8bit')
1000 s = StringIO()
1001 g = Generator(s)
1002 g.flatten(msg)
1003 wireform = s.getvalue()
1004 msg2 = email.message_from_string(wireform)
1005 self.assertEqual(msg.get_payload(), bytesdata)
1006 self.assertEqual(msg2.get_payload(decode=True), bytesdata)
1007 self.assertEqual(msg2['Content-Transfer-Encoding'], '8bit')
1008
1009 def test_binary_body_with_encode_noop(self):
1010 # Issue 16564: This does not produce an RFC valid message, since to be
1011 # valid it should have a CTE of binary. But the below works, and is
1012 # documented as working this way.
1013 bytesdata = b'\xfa\xfb\xfc\xfd\xfe\xff'
1014 msg = MIMEApplication(bytesdata, _encoder=encoders.encode_noop)
1015 self.assertEqual(msg.get_payload(), bytesdata)
1016 self.assertEqual(msg.get_payload(decode=True), bytesdata)
1017 s = StringIO()
1018 g = Generator(s)
1019 g.flatten(msg)
1020 wireform = s.getvalue()
1021 msg2 = email.message_from_string(wireform)
1022 self.assertEqual(msg.get_payload(), bytesdata)
1023 self.assertEqual(msg2.get_payload(decode=True), bytesdata)
1024
1025
1026 # Test the basic MIMEText class
1027 class TestMIMEText(unittest.TestCase):
1028 def setUp(self):
1029 self._msg = MIMEText('hello there')
1030
1031 def test_types(self):
1032 eq = self.assertEqual
1033 eq(self._msg.get_content_type(), 'text/plain')
1034 eq(self._msg.get_param('charset'), 'us-ascii')
1035 missing = []
1036 self.assertIs(self._msg.get_param('foobar', missing), missing)
1037 self.assertIs(self._msg.get_param('charset', missing, header='foobar'),
1038 missing)
1039
1040 def test_payload(self):
1041 self.assertEqual(self._msg.get_payload(), 'hello there')
1042 self.assertFalse(self._msg.is_multipart())
1043
1044 def test_charset(self):
1045 eq = self.assertEqual
1046 msg = MIMEText('hello there', _charset='us-ascii')
1047 eq(msg.get_charset().input_charset, 'us-ascii')
1048 eq(msg['content-type'], 'text/plain; charset="us-ascii"')
1049
1050
1051
1052 # Test complicated multipart/* messages
1053 class TestMultipart(TestEmailBase):
1054 def setUp(self):
1055 fp = openfile('PyBanner048.gif')
1056 try:
1057 data = fp.read()
1058 finally:
1059 fp.close()
1060
1061 container = MIMEBase('multipart', 'mixed', boundary='BOUNDARY')
1062 image = MIMEImage(data, name='dingusfish.gif')
1063 image.add_header('content-disposition', 'attachment',
1064 filename='dingusfish.gif')
1065 intro = MIMEText('''\
1066 Hi there,
1067
1068 This is the dingus fish.
1069 ''')
1070 container.attach(intro)
1071 container.attach(image)
1072 container['From'] = 'Barry <[email protected]>'
1073 container['To'] = 'Dingus Lovers <[email protected]>'
1074 container['Subject'] = 'Here is your dingus fish'
1075
1076 now = 987809702.54848599
1077 timetuple = time.localtime(now)
1078 if timetuple[-1] == 0:
1079 tzsecs = time.timezone
1080 else:
1081 tzsecs = time.altzone
1082 if tzsecs > 0:
1083 sign = '-'
1084 else:
1085 sign = '+'
1086 tzoffset = ' %s%04d' % (sign, tzsecs // 36)
1087 container['Date'] = time.strftime(
1088 '%a, %d %b %Y %H:%M:%S',
1089 time.localtime(now)) + tzoffset
1090 self._msg = container
1091 self._im = image
1092 self._txt = intro
1093
1094 def test_hierarchy(self):
1095 # convenience
1096 eq = self.assertEqual
1097 raises = self.assertRaises
1098 # tests
1099 m = self._msg
1100 self.assertTrue(m.is_multipart())
1101 eq(m.get_content_type(), 'multipart/mixed')
1102 eq(len(m.get_payload()), 2)
1103 raises(IndexError, m.get_payload, 2)
1104 m0 = m.get_payload(0)
1105 m1 = m.get_payload(1)
1106 self.assertIs(m0, self._txt)
1107 self.assertIs(m1, self._im)
1108 eq(m.get_payload(), [m0, m1])
1109 self.assertFalse(m0.is_multipart())
1110 self.assertFalse(m1.is_multipart())
1111
1112 def test_empty_multipart_idempotent(self):
1113 text = """\
1114 Content-Type: multipart/mixed; boundary="BOUNDARY"
1115 MIME-Version: 1.0
1116 Subject: A subject
1117 To: [email protected]
1118 From: [email protected]
1119
1120
1121 --BOUNDARY
1122
1123
1124 --BOUNDARY--
1125 """
1126 msg = Parser().parsestr(text)
1127 self.ndiffAssertEqual(text, msg.as_string())
1128
1129 def test_no_parts_in_a_multipart_with_none_epilogue(self):
1130 outer = MIMEBase('multipart', 'mixed')
1131 outer['Subject'] = 'A subject'
1132 outer['To'] = '[email protected]'
1133 outer['From'] = '[email protected]'
1134 outer.set_boundary('BOUNDARY')
1135 self.ndiffAssertEqual(outer.as_string(), '''\
1136 Content-Type: multipart/mixed; boundary="BOUNDARY"
1137 MIME-Version: 1.0
1138 Subject: A subject
1139 To: [email protected]
1140 From: [email protected]
1141
1142 --BOUNDARY
1143
1144 --BOUNDARY--
1145 ''')
1146
1147 def test_no_parts_in_a_multipart_with_empty_epilogue(self):
1148 outer = MIMEBase('multipart', 'mixed')
1149 outer['Subject'] = 'A subject'
1150 outer['To'] = '[email protected]'
1151 outer['From'] = '[email protected]'
1152 outer.preamble = ''
1153 outer.epilogue = ''
1154 outer.set_boundary('BOUNDARY')
1155 self.ndiffAssertEqual(outer.as_string(), '''\
1156 Content-Type: multipart/mixed; boundary="BOUNDARY"
1157 MIME-Version: 1.0
1158 Subject: A subject
1159 To: [email protected]
1160 From: [email protected]
1161
1162
1163 --BOUNDARY
1164
1165 --BOUNDARY--
1166 ''')
1167
1168 def test_one_part_in_a_multipart(self):
1169 eq = self.ndiffAssertEqual
1170 outer = MIMEBase('multipart', 'mixed')
1171 outer['Subject'] = 'A subject'
1172 outer['To'] = '[email protected]'
1173 outer['From'] = '[email protected]'
1174 outer.set_boundary('BOUNDARY')
1175 msg = MIMEText('hello world')
1176 outer.attach(msg)
1177 eq(outer.as_string(), '''\
1178 Content-Type: multipart/mixed; boundary="BOUNDARY"
1179 MIME-Version: 1.0
1180 Subject: A subject
1181 To: [email protected]
1182 From: [email protected]
1183
1184 --BOUNDARY
1185 Content-Type: text/plain; charset="us-ascii"
1186 MIME-Version: 1.0
1187 Content-Transfer-Encoding: 7bit
1188
1189 hello world
1190 --BOUNDARY--
1191 ''')
1192
1193 def test_seq_parts_in_a_multipart_with_empty_preamble(self):
1194 eq = self.ndiffAssertEqual
1195 outer = MIMEBase('multipart', 'mixed')
1196 outer['Subject'] = 'A subject'
1197 outer['To'] = '[email protected]'
1198 outer['From'] = '[email protected]'
1199 outer.preamble = ''
1200 msg = MIMEText('hello world')
1201 outer.attach(msg)
1202 outer.set_boundary('BOUNDARY')
1203 eq(outer.as_string(), '''\
1204 Content-Type: multipart/mixed; boundary="BOUNDARY"
1205 MIME-Version: 1.0
1206 Subject: A subject
1207 To: [email protected]
1208 From: [email protected]
1209
1210
1211 --BOUNDARY
1212 Content-Type: text/plain; charset="us-ascii"
1213 MIME-Version: 1.0
1214 Content-Transfer-Encoding: 7bit
1215
1216 hello world
1217 --BOUNDARY--
1218 ''')
1219
1220
1221 def test_seq_parts_in_a_multipart_with_none_preamble(self):
1222 eq = self.ndiffAssertEqual
1223 outer = MIMEBase('multipart', 'mixed')
1224 outer['Subject'] = 'A subject'
1225 outer['To'] = '[email protected]'
1226 outer['From'] = '[email protected]'
1227 outer.preamble = None
1228 msg = MIMEText('hello world')
1229 outer.attach(msg)
1230 outer.set_boundary('BOUNDARY')
1231 eq(outer.as_string(), '''\
1232 Content-Type: multipart/mixed; boundary="BOUNDARY"
1233 MIME-Version: 1.0
1234 Subject: A subject
1235 To: [email protected]
1236 From: [email protected]
1237
1238 --BOUNDARY
1239 Content-Type: text/plain; charset="us-ascii"
1240 MIME-Version: 1.0
1241 Content-Transfer-Encoding: 7bit
1242
1243 hello world
1244 --BOUNDARY--
1245 ''')
1246
1247
1248 def test_seq_parts_in_a_multipart_with_none_epilogue(self):
1249 eq = self.ndiffAssertEqual
1250 outer = MIMEBase('multipart', 'mixed')
1251 outer['Subject'] = 'A subject'
1252 outer['To'] = '[email protected]'
1253 outer['From'] = '[email protected]'
1254 outer.epilogue = None
1255 msg = MIMEText('hello world')
1256 outer.attach(msg)
1257 outer.set_boundary('BOUNDARY')
1258 eq(outer.as_string(), '''\
1259 Content-Type: multipart/mixed; boundary="BOUNDARY"
1260 MIME-Version: 1.0
1261 Subject: A subject
1262 To: [email protected]
1263 From: [email protected]
1264
1265 --BOUNDARY
1266 Content-Type: text/plain; charset="us-ascii"
1267 MIME-Version: 1.0
1268 Content-Transfer-Encoding: 7bit
1269
1270 hello world
1271 --BOUNDARY--
1272 ''')
1273
1274
1275 def test_seq_parts_in_a_multipart_with_empty_epilogue(self):
1276 eq = self.ndiffAssertEqual
1277 outer = MIMEBase('multipart', 'mixed')
1278 outer['Subject'] = 'A subject'
1279 outer['To'] = '[email protected]'
1280 outer['From'] = '[email protected]'
1281 outer.epilogue = ''
1282 msg = MIMEText('hello world')
1283 outer.attach(msg)
1284 outer.set_boundary('BOUNDARY')
1285 eq(outer.as_string(), '''\
1286 Content-Type: multipart/mixed; boundary="BOUNDARY"
1287 MIME-Version: 1.0
1288 Subject: A subject
1289 To: [email protected]
1290 From: [email protected]
1291
1292 --BOUNDARY
1293 Content-Type: text/plain; charset="us-ascii"
1294 MIME-Version: 1.0
1295 Content-Transfer-Encoding: 7bit
1296
1297 hello world
1298 --BOUNDARY--
1299 ''')
1300
1301
1302 def test_seq_parts_in_a_multipart_with_nl_epilogue(self):
1303 eq = self.ndiffAssertEqual
1304 outer = MIMEBase('multipart', 'mixed')
1305 outer['Subject'] = 'A subject'
1306 outer['To'] = '[email protected]'
1307 outer['From'] = '[email protected]'
1308 outer.epilogue = '\n'
1309 msg = MIMEText('hello world')
1310 outer.attach(msg)
1311 outer.set_boundary('BOUNDARY')
1312 eq(outer.as_string(), '''\
1313 Content-Type: multipart/mixed; boundary="BOUNDARY"
1314 MIME-Version: 1.0
1315 Subject: A subject
1316 To: [email protected]
1317 From: [email protected]
1318
1319 --BOUNDARY
1320 Content-Type: text/plain; charset="us-ascii"
1321 MIME-Version: 1.0
1322 Content-Transfer-Encoding: 7bit
1323
1324 hello world
1325 --BOUNDARY--
1326
1327 ''')
1328
1329 def test_message_external_body(self):
1330 eq = self.assertEqual
1331 msg = self._msgobj('msg_36.txt')
1332 eq(len(msg.get_payload()), 2)
1333 msg1 = msg.get_payload(1)
1334 eq(msg1.get_content_type(), 'multipart/alternative')
1335 eq(len(msg1.get_payload()), 2)
1336 for subpart in msg1.get_payload():
1337 eq(subpart.get_content_type(), 'message/external-body')
1338 eq(len(subpart.get_payload()), 1)
1339 subsubpart = subpart.get_payload(0)
1340 eq(subsubpart.get_content_type(), 'text/plain')
1341
1342 def test_double_boundary(self):
1343 # msg_37.txt is a multipart that contains two dash-boundary's in a
1344 # row. Our interpretation of RFC 2046 calls for ignoring the second
1345 # and subsequent boundaries.
1346 msg = self._msgobj('msg_37.txt')
1347 self.assertEqual(len(msg.get_payload()), 3)
1348
1349 def test_nested_inner_contains_outer_boundary(self):
1350 eq = self.ndiffAssertEqual
1351 # msg_38.txt has an inner part that contains outer boundaries. My
1352 # interpretation of RFC 2046 (based on sections 5.1 and 5.1.2) say
1353 # these are illegal and should be interpreted as unterminated inner
1354 # parts.
1355 msg = self._msgobj('msg_38.txt')
1356 sfp = StringIO()
1357 iterators._structure(msg, sfp)
1358 eq(sfp.getvalue(), """\
1359 multipart/mixed
1360 multipart/mixed
1361 multipart/alternative
1362 text/plain
1363 text/plain
1364 text/plain
1365 text/plain
1366 """)
1367
1368 def test_nested_with_same_boundary(self):
1369 eq = self.ndiffAssertEqual
1370 # msg 39.txt is similarly evil in that it's got inner parts that use
1371 # the same boundary as outer parts. Again, I believe the way this is
1372 # parsed is closest to the spirit of RFC 2046
1373 msg = self._msgobj('msg_39.txt')
1374 sfp = StringIO()
1375 iterators._structure(msg, sfp)
1376 eq(sfp.getvalue(), """\
1377 multipart/mixed
1378 multipart/mixed
1379 multipart/alternative
1380 application/octet-stream
1381 application/octet-stream
1382 text/plain
1383 """)
1384
1385 def test_boundary_in_non_multipart(self):
1386 msg = self._msgobj('msg_40.txt')
1387 self.assertEqual(msg.as_string(), '''\
1388 MIME-Version: 1.0
1389 Content-Type: text/html; boundary="--961284236552522269"
1390
1391 ----961284236552522269
1392 Content-Type: text/html;
1393 Content-Transfer-Encoding: 7Bit
1394
1395 <html></html>
1396
1397 ----961284236552522269--
1398 ''')
1399
1400 def test_boundary_with_leading_space(self):
1401 eq = self.assertEqual
1402 msg = email.message_from_string('''\
1403 MIME-Version: 1.0
1404 Content-Type: multipart/mixed; boundary=" XXXX"
1405
1406 -- XXXX
1407 Content-Type: text/plain
1408
1409
1410 -- XXXX
1411 Content-Type: text/plain
1412
1413 -- XXXX--
1414 ''')
1415 self.assertTrue(msg.is_multipart())
1416 eq(msg.get_boundary(), ' XXXX')
1417 eq(len(msg.get_payload()), 2)
1418
1419 def test_boundary_without_trailing_newline(self):
1420 m = Parser().parsestr("""\
1421 Content-Type: multipart/mixed; boundary="===============0012394164=="
1422 MIME-Version: 1.0
1423
1424 --===============0012394164==
1425 Content-Type: image/file1.jpg
1426 MIME-Version: 1.0
1427 Content-Transfer-Encoding: base64
1428
1429 YXNkZg==
1430 --===============0012394164==--""")
1431 self.assertEqual(m.get_payload(0).get_payload(), 'YXNkZg==')
1432
1433
1434
1435 # Test some badly formatted messages
1436 class TestNonConformant(TestEmailBase):
1437 def test_parse_missing_minor_type(self):
1438 eq = self.assertEqual
1439 msg = self._msgobj('msg_14.txt')
1440 eq(msg.get_content_type(), 'text/plain')
1441 eq(msg.get_content_maintype(), 'text')
1442 eq(msg.get_content_subtype(), 'plain')
1443
1444 def test_same_boundary_inner_outer(self):
1445 msg = self._msgobj('msg_15.txt')
1446 # XXX We can probably eventually do better
1447 inner = msg.get_payload(0)
1448 self.assertTrue(hasattr(inner, 'defects'))
1449 self.assertEqual(len(inner.defects), 1)
1450 self.assertIsInstance(inner.defects[0],
1451 errors.StartBoundaryNotFoundDefect)
1452
1453 def test_multipart_no_boundary(self):
1454 msg = self._msgobj('msg_25.txt')
1455 self.assertIsInstance(msg.get_payload(), str)
1456 self.assertEqual(len(msg.defects), 2)
1457 self.assertIsInstance(msg.defects[0],
1458 errors.NoBoundaryInMultipartDefect)
1459 self.assertIsInstance(msg.defects[1],
1460 errors.MultipartInvariantViolationDefect)
1461
1462 def test_invalid_content_type(self):
1463 eq = self.assertEqual
1464 neq = self.ndiffAssertEqual
1465 msg = Message()
1466 # RFC 2045, $5.2 says invalid yields text/plain
1467 msg['Content-Type'] = 'text'
1468 eq(msg.get_content_maintype(), 'text')
1469 eq(msg.get_content_subtype(), 'plain')
1470 eq(msg.get_content_type(), 'text/plain')
1471 # Clear the old value and try something /really/ invalid
1472 del msg['content-type']
1473 msg['Content-Type'] = 'foo'
1474 eq(msg.get_content_maintype(), 'text')
1475 eq(msg.get_content_subtype(), 'plain')
1476 eq(msg.get_content_type(), 'text/plain')
1477 # Still, make sure that the message is idempotently generated
1478 s = StringIO()
1479 g = Generator(s)
1480 g.flatten(msg)
1481 neq(s.getvalue(), 'Content-Type: foo\n\n')
1482
1483 def test_no_start_boundary(self):
1484 eq = self.ndiffAssertEqual
1485 msg = self._msgobj('msg_31.txt')
1486 eq(msg.get_payload(), """\
1487 --BOUNDARY
1488 Content-Type: text/plain
1489
1490 message 1
1491
1492 --BOUNDARY
1493 Content-Type: text/plain
1494
1495 message 2
1496
1497 --BOUNDARY--
1498 """)
1499
1500 def test_no_separating_blank_line(self):
1501 eq = self.ndiffAssertEqual
1502 msg = self._msgobj('msg_35.txt')
1503 eq(msg.as_string(), """\
1504 From: [email protected]
1505 To: [email protected]
1506 Subject: here's something interesting
1507
1508 counter to RFC 2822, there's no separating newline here
1509 """)
1510
1511 def test_lying_multipart(self):
1512 msg = self._msgobj('msg_41.txt')
1513 self.assertTrue(hasattr(msg, 'defects'))
1514 self.assertEqual(len(msg.defects), 2)
1515 self.assertIsInstance(msg.defects[0],
1516 errors.NoBoundaryInMultipartDefect)
1517 self.assertIsInstance(msg.defects[1],
1518 errors.MultipartInvariantViolationDefect)
1519
1520 def test_missing_start_boundary(self):
1521 outer = self._msgobj('msg_42.txt')
1522 # The message structure is:
1523 #
1524 # multipart/mixed
1525 # text/plain
1526 # message/rfc822
1527 # multipart/mixed [*]
1528 #
1529 # [*] This message is missing its start boundary
1530 bad = outer.get_payload(1).get_payload(0)
1531 self.assertEqual(len(bad.defects), 1)
1532 self.assertIsInstance(bad.defects[0],
1533 errors.StartBoundaryNotFoundDefect)
1534
1535 def test_first_line_is_continuation_header(self):
1536 eq = self.assertEqual
1537 m = ' Line 1\nLine 2\nLine 3'
1538 msg = email.message_from_string(m)
1539 eq(msg.keys(), [])
1540 eq(msg.get_payload(), 'Line 2\nLine 3')
1541 eq(len(msg.defects), 1)
1542 self.assertIsInstance(msg.defects[0],
1543 errors.FirstHeaderLineIsContinuationDefect)
1544 eq(msg.defects[0].line, ' Line 1\n')
1545
1546
1547
1548 # Test RFC 2047 header encoding and decoding
1549 class TestRFC2047(unittest.TestCase):
1550 def test_rfc2047_multiline(self):
1551 eq = self.assertEqual
1552 s = """Re: =?mac-iceland?q?r=8Aksm=9Arg=8Cs?= baz
1553 foo bar =?mac-iceland?q?r=8Aksm=9Arg=8Cs?="""
1554 dh = decode_header(s)
1555 eq(dh, [
1556 ('Re:', None),
1557 ('r\x8aksm\x9arg\x8cs', 'mac-iceland'),
1558 ('baz foo bar', None),
1559 ('r\x8aksm\x9arg\x8cs', 'mac-iceland')])
1560 eq(str(make_header(dh)),
1561 """Re: =?mac-iceland?q?r=8Aksm=9Arg=8Cs?= baz foo bar
1562 =?mac-iceland?q?r=8Aksm=9Arg=8Cs?=""")
1563
1564 def test_whitespace_eater_unicode(self):
1565 eq = self.assertEqual
1566 s = '=?ISO-8859-1?Q?Andr=E9?= Pirard <[email protected]>'
1567 dh = decode_header(s)
1568 eq(dh, [('Andr\xe9', 'iso-8859-1'), ('Pirard <[email protected]>', None)])
1569 hu = unicode(make_header(dh)).encode('latin-1')
1570 eq(hu, 'Andr\xe9 Pirard <[email protected]>')
1571
1572 def test_whitespace_eater_unicode_2(self):
1573 eq = self.assertEqual
1574 s = 'The =?iso-8859-1?b?cXVpY2sgYnJvd24gZm94?= jumped over the =?iso-8859-1?b?bGF6eSBkb2c=?='
1575 dh = decode_header(s)
1576 eq(dh, [('The', None), ('quick brown fox', 'iso-8859-1'),
1577 ('jumped over the', None), ('lazy dog', 'iso-8859-1')])
1578 hu = make_header(dh).__unicode__()
1579 eq(hu, u'The quick brown fox jumped over the lazy dog')
1580
1581 def test_rfc2047_missing_whitespace(self):
1582 s = 'Sm=?ISO-8859-1?B?9g==?=rg=?ISO-8859-1?B?5Q==?=sbord'
1583 dh = decode_header(s)
1584 self.assertEqual(dh, [(s, None)])
1585
1586 def test_rfc2047_with_whitespace(self):
1587 s = 'Sm =?ISO-8859-1?B?9g==?= rg =?ISO-8859-1?B?5Q==?= sbord'
1588 dh = decode_header(s)
1589 self.assertEqual(dh, [('Sm', None), ('\xf6', 'iso-8859-1'),
1590 ('rg', None), ('\xe5', 'iso-8859-1'),
1591 ('sbord', None)])
1592
1593
1594
1595 # Test the MIMEMessage class
1596 class TestMIMEMessage(TestEmailBase):
1597 def setUp(self):
1598 fp = openfile('msg_11.txt')
1599 try:
1600 self._text = fp.read()
1601 finally:
1602 fp.close()
1603
1604 def test_type_error(self):
1605 self.assertRaises(TypeError, MIMEMessage, 'a plain string')
1606
1607 def test_valid_argument(self):
1608 eq = self.assertEqual
1609 subject = 'A sub-message'
1610 m = Message()
1611 m['Subject'] = subject
1612 r = MIMEMessage(m)
1613 eq(r.get_content_type(), 'message/rfc822')
1614 payload = r.get_payload()
1615 self.assertIsInstance(payload, list)
1616 eq(len(payload), 1)
1617 subpart = payload[0]
1618 self.assertIs(subpart, m)
1619 eq(subpart['subject'], subject)
1620
1621 def test_bad_multipart(self):
1622 eq = self.assertEqual
1623 msg1 = Message()
1624 msg1['Subject'] = 'subpart 1'
1625 msg2 = Message()
1626 msg2['Subject'] = 'subpart 2'
1627 r = MIMEMessage(msg1)
1628 self.assertRaises(errors.MultipartConversionError, r.attach, msg2)
1629
1630 def test_generate(self):
1631 # First craft the message to be encapsulated
1632 m = Message()
1633 m['Subject'] = 'An enclosed message'
1634 m.set_payload('Here is the body of the message.\n')
1635 r = MIMEMessage(m)
1636 r['Subject'] = 'The enclosing message'
1637 s = StringIO()
1638 g = Generator(s)
1639 g.flatten(r)
1640 self.assertEqual(s.getvalue(), """\
1641 Content-Type: message/rfc822
1642 MIME-Version: 1.0
1643 Subject: The enclosing message
1644
1645 Subject: An enclosed message
1646
1647 Here is the body of the message.
1648 """)
1649
1650 def test_parse_message_rfc822(self):
1651 eq = self.assertEqual
1652 msg = self._msgobj('msg_11.txt')
1653 eq(msg.get_content_type(), 'message/rfc822')
1654 payload = msg.get_payload()
1655 self.assertIsInstance(payload, list)
1656 eq(len(payload), 1)
1657 submsg = payload[0]
1658 self.assertIsInstance(submsg, Message)
1659 eq(submsg['subject'], 'An enclosed message')
1660 eq(submsg.get_payload(), 'Here is the body of the message.\n')
1661
1662 def test_dsn(self):
1663 eq = self.assertEqual
1664 # msg 16 is a Delivery Status Notification, see RFC 1894
1665 msg = self._msgobj('msg_16.txt')
1666 eq(msg.get_content_type(), 'multipart/report')
1667 self.assertTrue(msg.is_multipart())
1668 eq(len(msg.get_payload()), 3)
1669 # Subpart 1 is a text/plain, human readable section
1670 subpart = msg.get_payload(0)
1671 eq(subpart.get_content_type(), 'text/plain')
1672 eq(subpart.get_payload(), """\
1673 This report relates to a message you sent with the following header fields:
1674
1675 Message-id: <[email protected]>
1676 Date: Sun, 23 Sep 2001 20:10:55 -0700
1677 From: "Ian T. Henry" <[email protected]>
1678 To: SoCal Raves <[email protected]>
1679 Subject: [scr] yeah for Ians!!
1680
1681 Your message cannot be delivered to the following recipients:
1682
1683 Recipient address: [email protected]
1684 Reason: recipient reached disk quota
1685
1686 """)
1687 # Subpart 2 contains the machine parsable DSN information. It
1688 # consists of two blocks of headers, represented by two nested Message
1689 # objects.
1690 subpart = msg.get_payload(1)
1691 eq(subpart.get_content_type(), 'message/delivery-status')
1692 eq(len(subpart.get_payload()), 2)
1693 # message/delivery-status should treat each block as a bunch of
1694 # headers, i.e. a bunch of Message objects.
1695 dsn1 = subpart.get_payload(0)
1696 self.assertIsInstance(dsn1, Message)
1697 eq(dsn1['original-envelope-id'], '[email protected]')
1698 eq(dsn1.get_param('dns', header='reporting-mta'), '')
1699 # Try a missing one <wink>
1700 eq(dsn1.get_param('nsd', header='reporting-mta'), None)
1701 dsn2 = subpart.get_payload(1)
1702 self.assertIsInstance(dsn2, Message)
1703 eq(dsn2['action'], 'failed')
1704 eq(dsn2.get_params(header='original-recipient'),
1705 [('rfc822', ''), ('[email protected]', '')])
1706 eq(dsn2.get_param('rfc822', header='final-recipient'), '')
1707 # Subpart 3 is the original message
1708 subpart = msg.get_payload(2)
1709 eq(subpart.get_content_type(), 'message/rfc822')
1710 payload = subpart.get_payload()
1711 self.assertIsInstance(payload, list)
1712 eq(len(payload), 1)
1713 subsubpart = payload[0]
1714 self.assertIsInstance(subsubpart, Message)
1715 eq(subsubpart.get_content_type(), 'text/plain')
1716 eq(subsubpart['message-id'],
1717 '<[email protected]>')
1718
1719 def test_epilogue(self):
1720 eq = self.ndiffAssertEqual
1721 fp = openfile('msg_21.txt')
1722 try:
1723 text = fp.read()
1724 finally:
1725 fp.close()
1726 msg = Message()
1727 msg['From'] = '[email protected]'
1728 msg['To'] = '[email protected]'
1729 msg['Subject'] = 'Test'
1730 msg.preamble = 'MIME message'
1731 msg.epilogue = 'End of MIME message\n'
1732 msg1 = MIMEText('One')
1733 msg2 = MIMEText('Two')
1734 msg.add_header('Content-Type', 'multipart/mixed', boundary='BOUNDARY')
1735 msg.attach(msg1)
1736 msg.attach(msg2)
1737 sfp = StringIO()
1738 g = Generator(sfp)
1739 g.flatten(msg)
1740 eq(sfp.getvalue(), text)
1741
1742 def test_no_nl_preamble(self):
1743 eq = self.ndiffAssertEqual
1744 msg = Message()
1745 msg['From'] = '[email protected]'
1746 msg['To'] = '[email protected]'
1747 msg['Subject'] = 'Test'
1748 msg.preamble = 'MIME message'
1749 msg.epilogue = ''
1750 msg1 = MIMEText('One')
1751 msg2 = MIMEText('Two')
1752 msg.add_header('Content-Type', 'multipart/mixed', boundary='BOUNDARY')
1753 msg.attach(msg1)
1754 msg.attach(msg2)
1755 eq(msg.as_string(), """\
1756 From: [email protected]
1757 To: [email protected]
1758 Subject: Test
1759 Content-Type: multipart/mixed; boundary="BOUNDARY"
1760
1761 MIME message
1762 --BOUNDARY
1763 Content-Type: text/plain; charset="us-ascii"
1764 MIME-Version: 1.0
1765 Content-Transfer-Encoding: 7bit
1766
1767 One
1768 --BOUNDARY
1769 Content-Type: text/plain; charset="us-ascii"
1770 MIME-Version: 1.0
1771 Content-Transfer-Encoding: 7bit
1772
1773 Two
1774 --BOUNDARY--
1775 """)
1776
1777 def test_default_type(self):
1778 eq = self.assertEqual
1779 fp = openfile('msg_30.txt')
1780 try:
1781 msg = email.message_from_file(fp)
1782 finally:
1783 fp.close()
1784 container1 = msg.get_payload(0)
1785 eq(container1.get_default_type(), 'message/rfc822')
1786 eq(container1.get_content_type(), 'message/rfc822')
1787 container2 = msg.get_payload(1)
1788 eq(container2.get_default_type(), 'message/rfc822')
1789 eq(container2.get_content_type(), 'message/rfc822')
1790 container1a = container1.get_payload(0)
1791 eq(container1a.get_default_type(), 'text/plain')
1792 eq(container1a.get_content_type(), 'text/plain')
1793 container2a = container2.get_payload(0)
1794 eq(container2a.get_default_type(), 'text/plain')
1795 eq(container2a.get_content_type(), 'text/plain')
1796
1797 def test_default_type_with_explicit_container_type(self):
1798 eq = self.assertEqual
1799 fp = openfile('msg_28.txt')
1800 try:
1801 msg = email.message_from_file(fp)
1802 finally:
1803 fp.close()
1804 container1 = msg.get_payload(0)
1805 eq(container1.get_default_type(), 'message/rfc822')
1806 eq(container1.get_content_type(), 'message/rfc822')
1807 container2 = msg.get_payload(1)
1808 eq(container2.get_default_type(), 'message/rfc822')
1809 eq(container2.get_content_type(), 'message/rfc822')
1810 container1a = container1.get_payload(0)
1811 eq(container1a.get_default_type(), 'text/plain')
1812 eq(container1a.get_content_type(), 'text/plain')
1813 container2a = container2.get_payload(0)
1814 eq(container2a.get_default_type(), 'text/plain')
1815 eq(container2a.get_content_type(), 'text/plain')
1816
1817 def test_default_type_non_parsed(self):
1818 eq = self.assertEqual
1819 neq = self.ndiffAssertEqual
1820 # Set up container
1821 container = MIMEMultipart('digest', 'BOUNDARY')
1822 container.epilogue = ''
1823 # Set up subparts
1824 subpart1a = MIMEText('message 1\n')
1825 subpart2a = MIMEText('message 2\n')
1826 subpart1 = MIMEMessage(subpart1a)
1827 subpart2 = MIMEMessage(subpart2a)
1828 container.attach(subpart1)
1829 container.attach(subpart2)
1830 eq(subpart1.get_content_type(), 'message/rfc822')
1831 eq(subpart1.get_default_type(), 'message/rfc822')
1832 eq(subpart2.get_content_type(), 'message/rfc822')
1833 eq(subpart2.get_default_type(), 'message/rfc822')
1834 neq(container.as_string(0), '''\
1835 Content-Type: multipart/digest; boundary="BOUNDARY"
1836 MIME-Version: 1.0
1837
1838 --BOUNDARY
1839 Content-Type: message/rfc822
1840 MIME-Version: 1.0
1841
1842 Content-Type: text/plain; charset="us-ascii"
1843 MIME-Version: 1.0
1844 Content-Transfer-Encoding: 7bit
1845
1846 message 1
1847
1848 --BOUNDARY
1849 Content-Type: message/rfc822
1850 MIME-Version: 1.0
1851
1852 Content-Type: text/plain; charset="us-ascii"
1853 MIME-Version: 1.0
1854 Content-Transfer-Encoding: 7bit
1855
1856 message 2
1857
1858 --BOUNDARY--
1859 ''')
1860 del subpart1['content-type']
1861 del subpart1['mime-version']
1862 del subpart2['content-type']
1863 del subpart2['mime-version']
1864 eq(subpart1.get_content_type(), 'message/rfc822')
1865 eq(subpart1.get_default_type(), 'message/rfc822')
1866 eq(subpart2.get_content_type(), 'message/rfc822')
1867 eq(subpart2.get_default_type(), 'message/rfc822')
1868 neq(container.as_string(0), '''\
1869 Content-Type: multipart/digest; boundary="BOUNDARY"
1870 MIME-Version: 1.0
1871
1872 --BOUNDARY
1873
1874 Content-Type: text/plain; charset="us-ascii"
1875 MIME-Version: 1.0
1876 Content-Transfer-Encoding: 7bit
1877
1878 message 1
1879
1880 --BOUNDARY
1881
1882 Content-Type: text/plain; charset="us-ascii"
1883 MIME-Version: 1.0
1884 Content-Transfer-Encoding: 7bit
1885
1886 message 2
1887
1888 --BOUNDARY--
1889 ''')
1890
1891 def test_mime_attachments_in_constructor(self):
1892 eq = self.assertEqual
1893 text1 = MIMEText('')
1894 text2 = MIMEText('')
1895 msg = MIMEMultipart(_subparts=(text1, text2))
1896 eq(len(msg.get_payload()), 2)
1897 eq(msg.get_payload(0), text1)
1898 eq(msg.get_payload(1), text2)
1899
1900
1901
1902 # A general test of parser->model->generator idempotency. IOW, read a message
1903 # in, parse it into a message object tree, then without touching the tree,
1904 # regenerate the plain text. The original text and the transformed text
1905 # should be identical. Note: that we ignore the Unix-From since that may
1906 # contain a changed date.
1907 class TestIdempotent(TestEmailBase):
1908 def _msgobj(self, filename):
1909 fp = openfile(filename)
1910 try:
1911 data = fp.read()
1912 finally:
1913 fp.close()
1914 msg = email.message_from_string(data)
1915 return msg, data
1916
1917 def _idempotent(self, msg, text):
1918 eq = self.ndiffAssertEqual
1919 s = StringIO()
1920 g = Generator(s, maxheaderlen=0)
1921 g.flatten(msg)
1922 eq(text, s.getvalue())
1923
1924 def test_parse_text_message(self):
1925 eq = self.assertEqual
1926 msg, text = self._msgobj('msg_01.txt')
1927 eq(msg.get_content_type(), 'text/plain')
1928 eq(msg.get_content_maintype(), 'text')
1929 eq(msg.get_content_subtype(), 'plain')
1930 eq(msg.get_params()[1], ('charset', 'us-ascii'))
1931 eq(msg.get_param('charset'), 'us-ascii')
1932 eq(msg.preamble, None)
1933 eq(msg.epilogue, None)
1934 self._idempotent(msg, text)
1935
1936 def test_parse_untyped_message(self):
1937 eq = self.assertEqual
1938 msg, text = self._msgobj('msg_03.txt')
1939 eq(msg.get_content_type(), 'text/plain')
1940 eq(msg.get_params(), None)
1941 eq(msg.get_param('charset'), None)
1942 self._idempotent(msg, text)
1943
1944 def test_simple_multipart(self):
1945 msg, text = self._msgobj('msg_04.txt')
1946 self._idempotent(msg, text)
1947
1948 def test_MIME_digest(self):
1949 msg, text = self._msgobj('msg_02.txt')
1950 self._idempotent(msg, text)
1951
1952 def test_long_header(self):
1953 msg, text = self._msgobj('msg_27.txt')
1954 self._idempotent(msg, text)
1955
1956 def test_MIME_digest_with_part_headers(self):
1957 msg, text = self._msgobj('msg_28.txt')
1958 self._idempotent(msg, text)
1959
1960 def test_mixed_with_image(self):
1961 msg, text = self._msgobj('msg_06.txt')
1962 self._idempotent(msg, text)
1963
1964 def test_multipart_report(self):
1965 msg, text = self._msgobj('msg_05.txt')
1966 self._idempotent(msg, text)
1967
1968 def test_dsn(self):
1969 msg, text = self._msgobj('msg_16.txt')
1970 self._idempotent(msg, text)
1971
1972 def test_preamble_epilogue(self):
1973 msg, text = self._msgobj('msg_21.txt')
1974 self._idempotent(msg, text)
1975
1976 def test_multipart_one_part(self):
1977 msg, text = self._msgobj('msg_23.txt')
1978 self._idempotent(msg, text)
1979
1980 def test_multipart_no_parts(self):
1981 msg, text = self._msgobj('msg_24.txt')
1982 self._idempotent(msg, text)
1983
1984 def test_no_start_boundary(self):
1985 msg, text = self._msgobj('msg_31.txt')
1986 self._idempotent(msg, text)
1987
1988 def test_rfc2231_charset(self):
1989 msg, text = self._msgobj('msg_32.txt')
1990 self._idempotent(msg, text)
1991
1992 def test_more_rfc2231_parameters(self):
1993 msg, text = self._msgobj('msg_33.txt')
1994 self._idempotent(msg, text)
1995
1996 def test_text_plain_in_a_multipart_digest(self):
1997 msg, text = self._msgobj('msg_34.txt')
1998 self._idempotent(msg, text)
1999
2000 def test_nested_multipart_mixeds(self):
2001 msg, text = self._msgobj('msg_12a.txt')
2002 self._idempotent(msg, text)
2003
2004 def test_message_external_body_idempotent(self):
2005 msg, text = self._msgobj('msg_36.txt')
2006 self._idempotent(msg, text)
2007
2008 def test_content_type(self):
2009 eq = self.assertEqual
2010 # Get a message object and reset the seek pointer for other tests
2011 msg, text = self._msgobj('msg_05.txt')
2012 eq(msg.get_content_type(), 'multipart/report')
2013 # Test the Content-Type: parameters
2014 params = {}
2015 for pk, pv in msg.get_params():
2016 params[pk] = pv
2017 eq(params['report-type'], 'delivery-status')
2018 eq(params['boundary'], 'D1690A7AC1.996856090/mail.example.com')
2019 eq(msg.preamble, 'This is a MIME-encapsulated message.\n')
2020 eq(msg.epilogue, '\n')
2021 eq(len(msg.get_payload()), 3)
2022 # Make sure the subparts are what we expect
2023 msg1 = msg.get_payload(0)
2024 eq(msg1.get_content_type(), 'text/plain')
2025 eq(msg1.get_payload(), 'Yadda yadda yadda\n')
2026 msg2 = msg.get_payload(1)
2027 eq(msg2.get_content_type(), 'text/plain')
2028 eq(msg2.get_payload(), 'Yadda yadda yadda\n')
2029 msg3 = msg.get_payload(2)
2030 eq(msg3.get_content_type(), 'message/rfc822')
2031 self.assertIsInstance(msg3, Message)
2032 payload = msg3.get_payload()
2033 self.assertIsInstance(payload, list)
2034 eq(len(payload), 1)
2035 msg4 = payload[0]
2036 self.assertIsInstance(msg4, Message)
2037 eq(msg4.get_payload(), 'Yadda yadda yadda\n')
2038
2039 def test_parser(self):
2040 eq = self.assertEqual
2041 msg, text = self._msgobj('msg_06.txt')
2042 # Check some of the outer headers
2043 eq(msg.get_content_type(), 'message/rfc822')
2044 # Make sure the payload is a list of exactly one sub-Message, and that
2045 # that submessage has a type of text/plain
2046 payload = msg.get_payload()
2047 self.assertIsInstance(payload, list)
2048 eq(len(payload), 1)
2049 msg1 = payload[0]
2050 self.assertIsInstance(msg1, Message)
2051 eq(msg1.get_content_type(), 'text/plain')
2052 self.assertIsInstance(msg1.get_payload(), str)
2053 eq(msg1.get_payload(), '\n')
2054
2055
2056
2057 # Test various other bits of the package's functionality
2058 class TestMiscellaneous(TestEmailBase):
2059 def test_message_from_string(self):
2060 fp = openfile('msg_01.txt')
2061 try:
2062 text = fp.read()
2063 finally:
2064 fp.close()
2065 msg = email.message_from_string(text)
2066 s = StringIO()
2067 # Don't wrap/continue long headers since we're trying to test
2068 # idempotency.
2069 g = Generator(s, maxheaderlen=0)
2070 g.flatten(msg)
2071 self.assertEqual(text, s.getvalue())
2072
2073 def test_message_from_file(self):
2074 fp = openfile('msg_01.txt')
2075 try:
2076 text = fp.read()
2077 fp.seek(0)
2078 msg = email.message_from_file(fp)
2079 s = StringIO()
2080 # Don't wrap/continue long headers since we're trying to test
2081 # idempotency.
2082 g = Generator(s, maxheaderlen=0)
2083 g.flatten(msg)
2084 self.assertEqual(text, s.getvalue())
2085 finally:
2086 fp.close()
2087
2088 def test_message_from_string_with_class(self):
2089 fp = openfile('msg_01.txt')
2090 try:
2091 text = fp.read()
2092 finally:
2093 fp.close()
2094 # Create a subclass
2095 class MyMessage(Message):
2096 pass
2097
2098 msg = email.message_from_string(text, MyMessage)
2099 self.assertIsInstance(msg, MyMessage)
2100 # Try something more complicated
2101 fp = openfile('msg_02.txt')
2102 try:
2103 text = fp.read()
2104 finally:
2105 fp.close()
2106 msg = email.message_from_string(text, MyMessage)
2107 for subpart in msg.walk():
2108 self.assertIsInstance(subpart, MyMessage)
2109
2110 def test_message_from_file_with_class(self):
2111 # Create a subclass
2112 class MyMessage(Message):
2113 pass
2114
2115 fp = openfile('msg_01.txt')
2116 try:
2117 msg = email.message_from_file(fp, MyMessage)
2118 finally:
2119 fp.close()
2120 self.assertIsInstance(msg, MyMessage)
2121 # Try something more complicated
2122 fp = openfile('msg_02.txt')
2123 try:
2124 msg = email.message_from_file(fp, MyMessage)
2125 finally:
2126 fp.close()
2127 for subpart in msg.walk():
2128 self.assertIsInstance(subpart, MyMessage)
2129
2130 def test__all__(self):
2131 module = __import__('email')
2132 # Can't use sorted() here due to Python 2.3 compatibility
2133 all = module.__all__[:]
2134 all.sort()
2135 self.assertEqual(all, [
2136 # Old names
2137 'Charset', 'Encoders', 'Errors', 'Generator',
2138 'Header', 'Iterators', 'MIMEAudio', 'MIMEBase',
2139 'MIMEImage', 'MIMEMessage', 'MIMEMultipart',
2140 'MIMENonMultipart', 'MIMEText', 'Message',
2141 'Parser', 'Utils', 'base64MIME',
2142 # new names
2143 'base64mime', 'charset', 'encoders', 'errors', 'generator',
2144 'header', 'iterators', 'message', 'message_from_file',
2145 'message_from_string', 'mime', 'parser',
2146 'quopriMIME', 'quoprimime', 'utils',
2147 ])
2148
2149 def test_formatdate(self):
2150 now = time.time()
2151 self.assertEqual(utils.parsedate(utils.formatdate(now))[:6],
2152 time.gmtime(now)[:6])
2153
2154 def test_formatdate_localtime(self):
2155 now = time.time()
2156 self.assertEqual(
2157 utils.parsedate(utils.formatdate(now, localtime=True))[:6],
2158 time.localtime(now)[:6])
2159
2160 def test_formatdate_usegmt(self):
2161 now = time.time()
2162 self.assertEqual(
2163 utils.formatdate(now, localtime=False),
2164 time.strftime('%a, %d %b %Y %H:%M:%S -0000', time.gmtime(now)))
2165 self.assertEqual(
2166 utils.formatdate(now, localtime=False, usegmt=True),
2167 time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(now)))
2168
2169 def test_parsedate_none(self):
2170 self.assertEqual(utils.parsedate(''), None)
2171
2172 def test_parsedate_compact(self):
2173 # The FWS after the comma is optional
2174 self.assertEqual(utils.parsedate('Wed,3 Apr 2002 14:58:26 +0800'),
2175 utils.parsedate('Wed, 3 Apr 2002 14:58:26 +0800'))
2176
2177 def test_parsedate_no_dayofweek(self):
2178 eq = self.assertEqual
2179 eq(utils.parsedate_tz('25 Feb 2003 13:47:26 -0800'),
2180 (2003, 2, 25, 13, 47, 26, 0, 1, -1, -28800))
2181
2182 def test_parsedate_compact_no_dayofweek(self):
2183 eq = self.assertEqual
2184 eq(utils.parsedate_tz('5 Feb 2003 13:47:26 -0800'),
2185 (2003, 2, 5, 13, 47, 26, 0, 1, -1, -28800))
2186
2187 def test_parsedate_acceptable_to_time_functions(self):
2188 eq = self.assertEqual
2189 timetup = utils.parsedate('5 Feb 2003 13:47:26 -0800')
2190 t = int(time.mktime(timetup))
2191 eq(time.localtime(t)[:6], timetup[:6])
2192 eq(int(time.strftime('%Y', timetup)), 2003)
2193 timetup = utils.parsedate_tz('5 Feb 2003 13:47:26 -0800')
2194 t = int(time.mktime(timetup[:9]))
2195 eq(time.localtime(t)[:6], timetup[:6])
2196 eq(int(time.strftime('%Y', timetup[:9])), 2003)
2197
2198 def test_parseaddr_empty(self):
2199 self.assertEqual(utils.parseaddr('<>'), ('', ''))
2200 self.assertEqual(utils.formataddr(utils.parseaddr('<>')), '')
2201
2202 def test_noquote_dump(self):
2203 self.assertEqual(
2204 utils.formataddr(('A Silly Person', '[email protected]')),
2205 'A Silly Person <[email protected]>')
2206
2207 def test_escape_dump(self):
2208 self.assertEqual(
2209 utils.formataddr(('A (Very) Silly Person', '[email protected]')),
2210 r'"A \(Very\) Silly Person" <[email protected]>')
2211 a = r'A \(Special\) Person'
2212 b = '[email protected]'
2213 self.assertEqual(utils.parseaddr(utils.formataddr((a, b))), (a, b))
2214
2215 def test_escape_backslashes(self):
2216 self.assertEqual(
2217 utils.formataddr(('Arthur \Backslash\ Foobar', '[email protected]')),
2218 r'"Arthur \\Backslash\\ Foobar" <[email protected]>')
2219 a = r'Arthur \Backslash\ Foobar'
2220 b = '[email protected]'
2221 self.assertEqual(utils.parseaddr(utils.formataddr((a, b))), (a, b))
2222
2223 def test_name_with_dot(self):
2224 x = 'John X. Doe <[email protected]>'
2225 y = '"John X. Doe" <[email protected]>'
2226 a, b = ('John X. Doe', '[email protected]')
2227 self.assertEqual(utils.parseaddr(x), (a, b))
2228 self.assertEqual(utils.parseaddr(y), (a, b))
2229 # formataddr() quotes the name if there's a dot in it
2230 self.assertEqual(utils.formataddr((a, b)), y)
2231
2232 def test_multiline_from_comment(self):
2233 x = """\
2234 Foo
2235 \tBar <[email protected]>"""
2236 self.assertEqual(utils.parseaddr(x), ('Foo Bar', '[email protected]'))
2237
2238 def test_quote_dump(self):
2239 self.assertEqual(
2240 utils.formataddr(('A Silly; Person', '[email protected]')),
2241 r'"A Silly; Person" <[email protected]>')
2242
2243 def test_fix_eols(self):
2244 eq = self.assertEqual
2245 eq(utils.fix_eols('hello'), 'hello')
2246 eq(utils.fix_eols('hello\n'), 'hello\r\n')
2247 eq(utils.fix_eols('hello\r'), 'hello\r\n')
2248 eq(utils.fix_eols('hello\r\n'), 'hello\r\n')
2249 eq(utils.fix_eols('hello\n\r'), 'hello\r\n\r\n')
2250
2251 def test_charset_richcomparisons(self):
2252 eq = self.assertEqual
2253 ne = self.assertNotEqual
2254 cset1 = Charset()
2255 cset2 = Charset()
2256 eq(cset1, 'us-ascii')
2257 eq(cset1, 'US-ASCII')
2258 eq(cset1, 'Us-AsCiI')
2259 eq('us-ascii', cset1)
2260 eq('US-ASCII', cset1)
2261 eq('Us-AsCiI', cset1)
2262 ne(cset1, 'usascii')
2263 ne(cset1, 'USASCII')
2264 ne(cset1, 'UsAsCiI')
2265 ne('usascii', cset1)
2266 ne('USASCII', cset1)
2267 ne('UsAsCiI', cset1)
2268 eq(cset1, cset2)
2269 eq(cset2, cset1)
2270
2271 def test_getaddresses(self):
2272 eq = self.assertEqual
2273 eq(utils.getaddresses(['[email protected] (Al Person)',
2274 'Bud Person <[email protected]>']),
2275 [('Al Person', '[email protected]'),
2276 ('Bud Person', '[email protected]')])
2277
2278 def test_getaddresses_nasty(self):
2279 eq = self.assertEqual
2280 eq(utils.getaddresses(['foo: ;']), [('', '')])
2281 eq(utils.getaddresses(
2282 ['[]*-- =~$']),
2283 [('', ''), ('', ''), ('', '*--')])
2284 eq(utils.getaddresses(
2285 ['foo: ;', '"Jason R. Mastaler" <[email protected]>']),
2286 [('', ''), ('Jason R. Mastaler', '[email protected]')])
2287
2288 def test_getaddresses_embedded_comment(self):
2289 """Test proper handling of a nested comment"""
2290 eq = self.assertEqual
2291 addrs = utils.getaddresses(['User ((nested comment)) <[email protected]>'])
2292 eq(addrs[0][1], '[email protected]')
2293
2294 def test_utils_quote_unquote(self):
2295 eq = self.assertEqual
2296 msg = Message()
2297 msg.add_header('content-disposition', 'attachment',
2298 filename='foo\\wacky"name')
2299 eq(msg.get_filename(), 'foo\\wacky"name')
2300
2301 def test_get_body_encoding_with_bogus_charset(self):
2302 charset = Charset('not a charset')
2303 self.assertEqual(charset.get_body_encoding(), 'base64')
2304
2305 def test_get_body_encoding_with_uppercase_charset(self):
2306 eq = self.assertEqual
2307 msg = Message()
2308 msg['Content-Type'] = 'text/plain; charset=UTF-8'
2309 eq(msg['content-type'], 'text/plain; charset=UTF-8')
2310 charsets = msg.get_charsets()
2311 eq(len(charsets), 1)
2312 eq(charsets[0], 'utf-8')
2313 charset = Charset(charsets[0])
2314 eq(charset.get_body_encoding(), 'base64')
2315 msg.set_payload('hello world', charset=charset)
2316 eq(msg.get_payload(), 'aGVsbG8gd29ybGQ=\n')
2317 eq(msg.get_payload(decode=True), 'hello world')
2318 eq(msg['content-transfer-encoding'], 'base64')
2319 # Try another one
2320 msg = Message()
2321 msg['Content-Type'] = 'text/plain; charset="US-ASCII"'
2322 charsets = msg.get_charsets()
2323 eq(len(charsets), 1)
2324 eq(charsets[0], 'us-ascii')
2325 charset = Charset(charsets[0])
2326 eq(charset.get_body_encoding(), encoders.encode_7or8bit)
2327 msg.set_payload('hello world', charset=charset)
2328 eq(msg.get_payload(), 'hello world')
2329 eq(msg['content-transfer-encoding'], '7bit')
2330
2331 def test_charsets_case_insensitive(self):
2332 lc = Charset('us-ascii')
2333 uc = Charset('US-ASCII')
2334 self.assertEqual(lc.get_body_encoding(), uc.get_body_encoding())
2335
2336 def test_partial_falls_inside_message_delivery_status(self):
2337 eq = self.ndiffAssertEqual
2338 # The Parser interface provides chunks of data to FeedParser in 8192
2339 # byte gulps. SF bug #1076485 found one of those chunks inside
2340 # message/delivery-status header block, which triggered an
2341 # unreadline() of NeedMoreData.
2342 msg = self._msgobj('msg_43.txt')
2343 sfp = StringIO()
2344 iterators._structure(msg, sfp)
2345 eq(sfp.getvalue(), """\
2346 multipart/report
2347 text/plain
2348 message/delivery-status
2349 text/plain
2350 text/plain
2351 text/plain
2352 text/plain
2353 text/plain
2354 text/plain
2355 text/plain
2356 text/plain
2357 text/plain
2358 text/plain
2359 text/plain
2360 text/plain
2361 text/plain
2362 text/plain
2363 text/plain
2364 text/plain
2365 text/plain
2366 text/plain
2367 text/plain
2368 text/plain
2369 text/plain
2370 text/plain
2371 text/plain
2372 text/plain
2373 text/plain
2374 text/plain
2375 text/rfc822-headers
2376 """)
2377
2378
2379
2380 # Test the iterator/generators
2381 class TestIterators(TestEmailBase):
2382 def test_body_line_iterator(self):
2383 eq = self.assertEqual
2384 neq = self.ndiffAssertEqual
2385 # First a simple non-multipart message
2386 msg = self._msgobj('msg_01.txt')
2387 it = iterators.body_line_iterator(msg)
2388 lines = list(it)
2389 eq(len(lines), 6)
2390 neq(EMPTYSTRING.join(lines), msg.get_payload())
2391 # Now a more complicated multipart
2392 msg = self._msgobj('msg_02.txt')
2393 it = iterators.body_line_iterator(msg)
2394 lines = list(it)
2395 eq(len(lines), 43)
2396 fp = openfile('msg_19.txt')
2397 try:
2398 neq(EMPTYSTRING.join(lines), fp.read())
2399 finally:
2400 fp.close()
2401
2402 def test_typed_subpart_iterator(self):
2403 eq = self.assertEqual
2404 msg = self._msgobj('msg_04.txt')
2405 it = iterators.typed_subpart_iterator(msg, 'text')
2406 lines = []
2407 subparts = 0
2408 for subpart in it:
2409 subparts += 1
2410 lines.append(subpart.get_payload())
2411 eq(subparts, 2)
2412 eq(EMPTYSTRING.join(lines), """\
2413 a simple kind of mirror
2414 to reflect upon our own
2415 a simple kind of mirror
2416 to reflect upon our own
2417 """)
2418
2419 def test_typed_subpart_iterator_default_type(self):
2420 eq = self.assertEqual
2421 msg = self._msgobj('msg_03.txt')
2422 it = iterators.typed_subpart_iterator(msg, 'text', 'plain')
2423 lines = []
2424 subparts = 0
2425 for subpart in it:
2426 subparts += 1
2427 lines.append(subpart.get_payload())
2428 eq(subparts, 1)
2429 eq(EMPTYSTRING.join(lines), """\
2430
2431 Hi,
2432
2433 Do you like this message?
2434
2435 -Me
2436 """)
2437
2438
2439
2440 class TestParsers(TestEmailBase):
2441 def test_header_parser(self):
2442 eq = self.assertEqual
2443 # Parse only the headers of a complex multipart MIME document
2444 fp = openfile('msg_02.txt')
2445 try:
2446 msg = HeaderParser().parse(fp)
2447 finally:
2448 fp.close()
2449 eq(msg['from'], '[email protected]')
2450 eq(msg['to'], '[email protected]')
2451 eq(msg.get_content_type(), 'multipart/mixed')
2452 self.assertFalse(msg.is_multipart())
2453 self.assertIsInstance(msg.get_payload(), str)
2454
2455 def test_whitespace_continuation(self):
2456 eq = self.assertEqual
2457 # This message contains a line after the Subject: header that has only
2458 # whitespace, but it is not empty!
2459 msg = email.message_from_string("""\
2460 From: [email protected]
2461 To: [email protected]
2462 Subject: the next line has a space on it
2463 \x20
2464 Date: Mon, 8 Apr 2002 15:09:19 -0400
2465 Message-ID: spam
2466
2467 Here's the message body
2468 """)
2469 eq(msg['subject'], 'the next line has a space on it\n ')
2470 eq(msg['message-id'], 'spam')
2471 eq(msg.get_payload(), "Here's the message body\n")
2472
2473 def test_whitespace_continuation_last_header(self):
2474 eq = self.assertEqual
2475 # Like the previous test, but the subject line is the last
2476 # header.
2477 msg = email.message_from_string("""\
2478 From: [email protected]
2479 To: [email protected]
2480 Date: Mon, 8 Apr 2002 15:09:19 -0400
2481 Message-ID: spam
2482 Subject: the next line has a space on it
2483 \x20
2484
2485 Here's the message body
2486 """)
2487 eq(msg['subject'], 'the next line has a space on it\n ')
2488 eq(msg['message-id'], 'spam')
2489 eq(msg.get_payload(), "Here's the message body\n")
2490
2491 def test_crlf_separation(self):
2492 eq = self.assertEqual
2493 fp = openfile('msg_26.txt', mode='rb')
2494 try:
2495 msg = Parser().parse(fp)
2496 finally:
2497 fp.close()
2498 eq(len(msg.get_payload()), 2)
2499 part1 = msg.get_payload(0)
2500 eq(part1.get_content_type(), 'text/plain')
2501 eq(part1.get_payload(), 'Simple email with attachment.\r\n\r\n')
2502 part2 = msg.get_payload(1)
2503 eq(part2.get_content_type(), 'application/riscos')
2504
2505 def test_multipart_digest_with_extra_mime_headers(self):
2506 eq = self.assertEqual
2507 neq = self.ndiffAssertEqual
2508 fp = openfile('msg_28.txt')
2509 try:
2510 msg = email.message_from_file(fp)
2511 finally:
2512 fp.close()
2513 # Structure is:
2514 # multipart/digest
2515 # message/rfc822
2516 # text/plain
2517 # message/rfc822
2518 # text/plain
2519 eq(msg.is_multipart(), 1)
2520 eq(len(msg.get_payload()), 2)
2521 part1 = msg.get_payload(0)
2522 eq(part1.get_content_type(), 'message/rfc822')
2523 eq(part1.is_multipart(), 1)
2524 eq(len(part1.get_payload()), 1)
2525 part1a = part1.get_payload(0)
2526 eq(part1a.is_multipart(), 0)
2527 eq(part1a.get_content_type(), 'text/plain')
2528 neq(part1a.get_payload(), 'message 1\n')
2529 # next message/rfc822
2530 part2 = msg.get_payload(1)
2531 eq(part2.get_content_type(), 'message/rfc822')
2532 eq(part2.is_multipart(), 1)
2533 eq(len(part2.get_payload()), 1)
2534 part2a = part2.get_payload(0)
2535 eq(part2a.is_multipart(), 0)
2536 eq(part2a.get_content_type(), 'text/plain')
2537 neq(part2a.get_payload(), 'message 2\n')
2538
2539 def test_three_lines(self):
2540 # A bug report by Andrew McNamara
2541 lines = ['From: Andrew Person <[email protected]',
2542 'Subject: Test',
2543 'Date: Tue, 20 Aug 2002 16:43:45 +1000']
2544 msg = email.message_from_string(NL.join(lines))
2545 self.assertEqual(msg['date'], 'Tue, 20 Aug 2002 16:43:45 +1000')
2546
2547 def test_strip_line_feed_and_carriage_return_in_headers(self):
2548 eq = self.assertEqual
2549 # For [ 1002475 ] email message parser doesn't handle \r\n correctly
2550 value1 = 'text'
2551 value2 = 'more text'
2552 m = 'Header: %s\r\nNext-Header: %s\r\n\r\nBody\r\n\r\n' % (
2553 value1, value2)
2554 msg = email.message_from_string(m)
2555 eq(msg.get('Header'), value1)
2556 eq(msg.get('Next-Header'), value2)
2557
2558 def test_rfc2822_header_syntax(self):
2559 eq = self.assertEqual
2560 m = '>From: foo\nFrom: bar\n!"#QUX;~: zoo\n\nbody'
2561 msg = email.message_from_string(m)
2562 eq(len(msg.keys()), 3)
2563 keys = msg.keys()
2564 keys.sort()
2565 eq(keys, ['!"#QUX;~', '>From', 'From'])
2566 eq(msg.get_payload(), 'body')
2567
2568 def test_rfc2822_space_not_allowed_in_header(self):
2569 eq = self.assertEqual
2570 m = '>From [email protected] 11:25:53\nFrom: bar\n!"#QUX;~: zoo\n\nbody'
2571 msg = email.message_from_string(m)
2572 eq(len(msg.keys()), 0)
2573
2574 def test_rfc2822_one_character_header(self):
2575 eq = self.assertEqual
2576 m = 'A: first header\nB: second header\nCC: third header\n\nbody'
2577 msg = email.message_from_string(m)
2578 headers = msg.keys()
2579 headers.sort()
2580 eq(headers, ['A', 'B', 'CC'])
2581 eq(msg.get_payload(), 'body')
2582
2583
2584
2585 class TestBase64(unittest.TestCase):
2586 def test_len(self):
2587 eq = self.assertEqual
2588 eq(base64mime.base64_len('hello'),
2589 len(base64mime.encode('hello', eol='')))
2590 for size in range(15):
2591 if size == 0 : bsize = 0
2592 elif size <= 3 : bsize = 4
2593 elif size <= 6 : bsize = 8
2594 elif size <= 9 : bsize = 12
2595 elif size <= 12: bsize = 16
2596 else : bsize = 20
2597 eq(base64mime.base64_len('x'*size), bsize)
2598
2599 def test_decode(self):
2600 eq = self.assertEqual
2601 eq(base64mime.decode(''), '')
2602 eq(base64mime.decode('aGVsbG8='), 'hello')
2603 eq(base64mime.decode('aGVsbG8=', 'X'), 'hello')
2604 eq(base64mime.decode('aGVsbG8NCndvcmxk\n', 'X'), 'helloXworld')
2605
2606 def test_encode(self):
2607 eq = self.assertEqual
2608 eq(base64mime.encode(''), '')
2609 eq(base64mime.encode('hello'), 'aGVsbG8=\n')
2610 # Test the binary flag
2611 eq(base64mime.encode('hello\n'), 'aGVsbG8K\n')
2612 eq(base64mime.encode('hello\n', 0), 'aGVsbG8NCg==\n')
2613 # Test the maxlinelen arg
2614 eq(base64mime.encode('xxxx ' * 20, maxlinelen=40), """\
2615 eHh4eCB4eHh4IHh4eHggeHh4eCB4eHh4IHh4eHgg
2616 eHh4eCB4eHh4IHh4eHggeHh4eCB4eHh4IHh4eHgg
2617 eHh4eCB4eHh4IHh4eHggeHh4eCB4eHh4IHh4eHgg
2618 eHh4eCB4eHh4IA==
2619 """)
2620 # Test the eol argument
2621 eq(base64mime.encode('xxxx ' * 20, maxlinelen=40, eol='\r\n'), """\
2622 eHh4eCB4eHh4IHh4eHggeHh4eCB4eHh4IHh4eHgg\r
2623 eHh4eCB4eHh4IHh4eHggeHh4eCB4eHh4IHh4eHgg\r
2624 eHh4eCB4eHh4IHh4eHggeHh4eCB4eHh4IHh4eHgg\r
2625 eHh4eCB4eHh4IA==\r
2626 """)
2627
2628 def test_header_encode(self):
2629 eq = self.assertEqual
2630 he = base64mime.header_encode
2631 eq(he('hello'), '=?iso-8859-1?b?aGVsbG8=?=')
2632 eq(he('hello\nworld'), '=?iso-8859-1?b?aGVsbG8NCndvcmxk?=')
2633 # Test the charset option
2634 eq(he('hello', charset='iso-8859-2'), '=?iso-8859-2?b?aGVsbG8=?=')
2635 # Test the keep_eols flag
2636 eq(he('hello\nworld', keep_eols=True),
2637 '=?iso-8859-1?b?aGVsbG8Kd29ybGQ=?=')
2638 # Test the maxlinelen argument
2639 eq(he('xxxx ' * 20, maxlinelen=40), """\
2640 =?iso-8859-1?b?eHh4eCB4eHh4IHh4eHggeHg=?=
2641 =?iso-8859-1?b?eHggeHh4eCB4eHh4IHh4eHg=?=
2642 =?iso-8859-1?b?IHh4eHggeHh4eCB4eHh4IHg=?=
2643 =?iso-8859-1?b?eHh4IHh4eHggeHh4eCB4eHg=?=
2644 =?iso-8859-1?b?eCB4eHh4IHh4eHggeHh4eCA=?=
2645 =?iso-8859-1?b?eHh4eCB4eHh4IHh4eHgg?=""")
2646 # Test the eol argument
2647 eq(he('xxxx ' * 20, maxlinelen=40, eol='\r\n'), """\
2648 =?iso-8859-1?b?eHh4eCB4eHh4IHh4eHggeHg=?=\r
2649 =?iso-8859-1?b?eHggeHh4eCB4eHh4IHh4eHg=?=\r
2650 =?iso-8859-1?b?IHh4eHggeHh4eCB4eHh4IHg=?=\r
2651 =?iso-8859-1?b?eHh4IHh4eHggeHh4eCB4eHg=?=\r
2652 =?iso-8859-1?b?eCB4eHh4IHh4eHggeHh4eCA=?=\r
2653 =?iso-8859-1?b?eHh4eCB4eHh4IHh4eHgg?=""")
2654
2655
2656
2657 class TestQuopri(unittest.TestCase):
2658 def setUp(self):
2659 self.hlit = [chr(x) for x in range(ord('a'), ord('z')+1)] + \
2660 [chr(x) for x in range(ord('A'), ord('Z')+1)] + \
2661 [chr(x) for x in range(ord('0'), ord('9')+1)] + \
2662 ['!', '*', '+', '-', '/', ' ']
2663 self.hnon = [chr(x) for x in range(256) if chr(x) not in self.hlit]
2664 assert len(self.hlit) + len(self.hnon) == 256
2665 self.blit = [chr(x) for x in range(ord(' '), ord('~')+1)] + ['\t']
2666 self.blit.remove('=')
2667 self.bnon = [chr(x) for x in range(256) if chr(x) not in self.blit]
2668 assert len(self.blit) + len(self.bnon) == 256
2669
2670 def test_header_quopri_check(self):
2671 for c in self.hlit:
2672 self.assertFalse(quoprimime.header_quopri_check(c))
2673 for c in self.hnon:
2674 self.assertTrue(quoprimime.header_quopri_check(c))
2675
2676 def test_body_quopri_check(self):
2677 for c in self.blit:
2678 self.assertFalse(quoprimime.body_quopri_check(c))
2679 for c in self.bnon:
2680 self.assertTrue(quoprimime.body_quopri_check(c))
2681
2682 def test_header_quopri_len(self):
2683 eq = self.assertEqual
2684 hql = quoprimime.header_quopri_len
2685 enc = quoprimime.header_encode
2686 for s in ('hello', 'h@e@l@l@o@'):
2687 # Empty charset and no line-endings. 7 == RFC chrome
2688 eq(hql(s), len(enc(s, charset='', eol=''))-7)
2689 for c in self.hlit:
2690 eq(hql(c), 1)
2691 for c in self.hnon:
2692 eq(hql(c), 3)
2693
2694 def test_body_quopri_len(self):
2695 eq = self.assertEqual
2696 bql = quoprimime.body_quopri_len
2697 for c in self.blit:
2698 eq(bql(c), 1)
2699 for c in self.bnon:
2700 eq(bql(c), 3)
2701
2702 def test_quote_unquote_idempotent(self):
2703 for x in range(256):
2704 c = chr(x)
2705 self.assertEqual(quoprimime.unquote(quoprimime.quote(c)), c)
2706
2707 def test_header_encode(self):
2708 eq = self.assertEqual
2709 he = quoprimime.header_encode
2710 eq(he('hello'), '=?iso-8859-1?q?hello?=')
2711 eq(he('hello\nworld'), '=?iso-8859-1?q?hello=0D=0Aworld?=')
2712 # Test the charset option
2713 eq(he('hello', charset='iso-8859-2'), '=?iso-8859-2?q?hello?=')
2714 # Test the keep_eols flag
2715 eq(he('hello\nworld', keep_eols=True), '=?iso-8859-1?q?hello=0Aworld?=')
2716 # Test a non-ASCII character
2717 eq(he('hello\xc7there'), '=?iso-8859-1?q?hello=C7there?=')
2718 # Test the maxlinelen argument
2719 eq(he('xxxx ' * 20, maxlinelen=40), """\
2720 =?iso-8859-1?q?xxxx_xxxx_xxxx_xxxx_xx?=
2721 =?iso-8859-1?q?xx_xxxx_xxxx_xxxx_xxxx?=
2722 =?iso-8859-1?q?_xxxx_xxxx_xxxx_xxxx_x?=
2723 =?iso-8859-1?q?xxx_xxxx_xxxx_xxxx_xxx?=
2724 =?iso-8859-1?q?x_xxxx_xxxx_?=""")
2725 # Test the eol argument
2726 eq(he('xxxx ' * 20, maxlinelen=40, eol='\r\n'), """\
2727 =?iso-8859-1?q?xxxx_xxxx_xxxx_xxxx_xx?=\r
2728 =?iso-8859-1?q?xx_xxxx_xxxx_xxxx_xxxx?=\r
2729 =?iso-8859-1?q?_xxxx_xxxx_xxxx_xxxx_x?=\r
2730 =?iso-8859-1?q?xxx_xxxx_xxxx_xxxx_xxx?=\r
2731 =?iso-8859-1?q?x_xxxx_xxxx_?=""")
2732
2733 def test_decode(self):
2734 eq = self.assertEqual
2735 eq(quoprimime.decode(''), '')
2736 eq(quoprimime.decode('hello'), 'hello')
2737 eq(quoprimime.decode('hello', 'X'), 'hello')
2738 eq(quoprimime.decode('hello\nworld', 'X'), 'helloXworld')
2739
2740 def test_encode(self):
2741 eq = self.assertEqual
2742 eq(quoprimime.encode(''), '')
2743 eq(quoprimime.encode('hello'), 'hello')
2744 # Test the binary flag
2745 eq(quoprimime.encode('hello\r\nworld'), 'hello\nworld')
2746 eq(quoprimime.encode('hello\r\nworld', 0), 'hello\nworld')
2747 # Test the maxlinelen arg
2748 eq(quoprimime.encode('xxxx ' * 20, maxlinelen=40), """\
2749 xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx=
2750 xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxx=
2751 x xxxx xxxx xxxx xxxx=20""")
2752 # Test the eol argument
2753 eq(quoprimime.encode('xxxx ' * 20, maxlinelen=40, eol='\r\n'), """\
2754 xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx=\r
2755 xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxx=\r
2756 x xxxx xxxx xxxx xxxx=20""")
2757 eq(quoprimime.encode("""\
2758 one line
2759
2760 two line"""), """\
2761 one line
2762
2763 two line""")
2764
2765
2766
2767 # Test the Charset class
2768 class TestCharset(unittest.TestCase):
2769 def tearDown(self):
2770 from email import charset as CharsetModule
2771 try:
2772 del CharsetModule.CHARSETS['fake']
2773 except KeyError:
2774 pass
2775
2776 def test_idempotent(self):
2777 eq = self.assertEqual
2778 # Make sure us-ascii = no Unicode conversion
2779 c = Charset('us-ascii')
2780 s = 'Hello World!'
2781 sp = c.to_splittable(s)
2782 eq(s, c.from_splittable(sp))
2783 # test 8-bit idempotency with us-ascii
2784 s = '\xa4\xa2\xa4\xa4\xa4\xa6\xa4\xa8\xa4\xaa'
2785 sp = c.to_splittable(s)
2786 eq(s, c.from_splittable(sp))
2787
2788 def test_body_encode(self):
2789 eq = self.assertEqual
2790 # Try a charset with QP body encoding
2791 c = Charset('iso-8859-1')
2792 eq('hello w=F6rld', c.body_encode('hello w\xf6rld'))
2793 # Try a charset with Base64 body encoding
2794 c = Charset('utf-8')
2795 eq('aGVsbG8gd29ybGQ=\n', c.body_encode('hello world'))
2796 # Try a charset with None body encoding
2797 c = Charset('us-ascii')
2798 eq('hello world', c.body_encode('hello world'))
2799 # Try the convert argument, where input codec != output codec
2800 c = Charset('euc-jp')
2801 # With apologies to Tokio Kikuchi ;)
2802 try:
2803 eq('\x1b$B5FCO;~IW\x1b(B',
2804 c.body_encode('\xb5\xc6\xc3\xcf\xbb\xfe\xc9\xd7'))
2805 eq('\xb5\xc6\xc3\xcf\xbb\xfe\xc9\xd7',
2806 c.body_encode('\xb5\xc6\xc3\xcf\xbb\xfe\xc9\xd7', False))
2807 except LookupError:
2808 # We probably don't have the Japanese codecs installed
2809 pass
2810 # Testing SF bug #625509, which we have to fake, since there are no
2811 # built-in encodings where the header encoding is QP but the body
2812 # encoding is not.
2813 from email import charset as CharsetModule
2814 CharsetModule.add_charset('fake', CharsetModule.QP, None)
2815 c = Charset('fake')
2816 eq('hello w\xf6rld', c.body_encode('hello w\xf6rld'))
2817
2818 def test_unicode_charset_name(self):
2819 charset = Charset(u'us-ascii')
2820 self.assertEqual(str(charset), 'us-ascii')
2821 self.assertRaises(errors.CharsetError, Charset, 'asc\xffii')
2822
2823
2824
2825 # Test multilingual MIME headers.
2826 class TestHeader(TestEmailBase):
2827 def test_simple(self):
2828 eq = self.ndiffAssertEqual
2829 h = Header('Hello World!')
2830 eq(h.encode(), 'Hello World!')
2831 h.append(' Goodbye World!')
2832 eq(h.encode(), 'Hello World! Goodbye World!')
2833
2834 def test_simple_surprise(self):
2835 eq = self.ndiffAssertEqual
2836 h = Header('Hello World!')
2837 eq(h.encode(), 'Hello World!')
2838 h.append('Goodbye World!')
2839 eq(h.encode(), 'Hello World! Goodbye World!')
2840
2841 def test_header_needs_no_decoding(self):
2842 h = 'no decoding needed'
2843 self.assertEqual(decode_header(h), [(h, None)])
2844
2845 def test_long(self):
2846 h = Header("I am the very model of a modern Major-General; I've information vegetable, animal, and mineral; I know the kings of England, and I quote the fights historical from Marathon to Waterloo, in order categorical; I'm very well acquainted, too, with matters mathematical; I understand equations, both the simple and quadratical; about binomial theorem I'm teeming with a lot o' news, with many cheerful facts about the square of the hypotenuse.",
2847 maxlinelen=76)
2848 for l in h.encode(splitchars=' ').split('\n '):
2849 self.assertLessEqual(len(l), 76)
2850
2851 def test_multilingual(self):
2852 eq = self.ndiffAssertEqual
2853 g = Charset("iso-8859-1")
2854 cz = Charset("iso-8859-2")
2855 utf8 = Charset("utf-8")
2856 g_head = "Die Mieter treten hier ein werden mit einem Foerderband komfortabel den Korridor entlang, an s\xfcdl\xfcndischen Wandgem\xe4lden vorbei, gegen die rotierenden Klingen bef\xf6rdert. "
2857 cz_head = "Finan\xe8ni metropole se hroutily pod tlakem jejich d\xf9vtipu.. "
2858 utf8_head = u"\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das Nunstuck git und Slotermeyer? Ja! Beiherhund das Oder die Flipperwaldt gersput.\u300d\u3068\u8a00\u3063\u3066\u3044\u307e\u3059\u3002".encode("utf-8")
2859 h = Header(g_head, g)
2860 h.append(cz_head, cz)
2861 h.append(utf8_head, utf8)
2862 enc = h.encode()
2863 eq(enc, """\
2864 =?iso-8859-1?q?Die_Mieter_treten_hier_ein_werden_mit_einem_Foerderband_ko?=
2865 =?iso-8859-1?q?mfortabel_den_Korridor_entlang=2C_an_s=FCdl=FCndischen_Wan?=
2866 =?iso-8859-1?q?dgem=E4lden_vorbei=2C_gegen_die_rotierenden_Klingen_bef=F6?=
2867 =?iso-8859-1?q?rdert=2E_?= =?iso-8859-2?q?Finan=E8ni_metropole_se_hroutily?=
2868 =?iso-8859-2?q?_pod_tlakem_jejich_d=F9vtipu=2E=2E_?= =?utf-8?b?5q2j56K6?=
2869 =?utf-8?b?44Gr6KiA44GG44Go57+76Kiz44Gv44GV44KM44Gm44GE44G+44Gb44KT44CC?=
2870 =?utf-8?b?5LiA6YOo44Gv44OJ44Kk44OE6Kqe44Gn44GZ44GM44CB44GC44Go44Gv44Gn?=
2871 =?utf-8?b?44Gf44KJ44KB44Gn44GZ44CC5a6f6Zqb44Gr44Gv44CMV2VubiBpc3QgZGFz?=
2872 =?utf-8?q?_Nunstuck_git_und_Slotermeyer=3F_Ja!_Beiherhund_das_Oder_die_Fl?=
2873 =?utf-8?b?aXBwZXJ3YWxkdCBnZXJzcHV0LuOAjeOBqOiogOOBo+OBpuOBhOOBvuOBmQ==?=
2874 =?utf-8?b?44CC?=""")
2875 eq(decode_header(enc),
2876 [(g_head, "iso-8859-1"), (cz_head, "iso-8859-2"),
2877 (utf8_head, "utf-8")])
2878 ustr = unicode(h)
2879 eq(ustr.encode('utf-8'),
2880 'Die Mieter treten hier ein werden mit einem Foerderband '
2881 'komfortabel den Korridor entlang, an s\xc3\xbcdl\xc3\xbcndischen '
2882 'Wandgem\xc3\xa4lden vorbei, gegen die rotierenden Klingen '
2883 'bef\xc3\xb6rdert. Finan\xc4\x8dni metropole se hroutily pod '
2884 'tlakem jejich d\xc5\xafvtipu.. \xe6\xad\xa3\xe7\xa2\xba\xe3\x81'
2885 '\xab\xe8\xa8\x80\xe3\x81\x86\xe3\x81\xa8\xe7\xbf\xbb\xe8\xa8\xb3'
2886 '\xe3\x81\xaf\xe3\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3'
2887 '\x81\xbe\xe3\x81\x9b\xe3\x82\x93\xe3\x80\x82\xe4\xb8\x80\xe9\x83'
2888 '\xa8\xe3\x81\xaf\xe3\x83\x89\xe3\x82\xa4\xe3\x83\x84\xe8\xaa\x9e'
2889 '\xe3\x81\xa7\xe3\x81\x99\xe3\x81\x8c\xe3\x80\x81\xe3\x81\x82\xe3'
2890 '\x81\xa8\xe3\x81\xaf\xe3\x81\xa7\xe3\x81\x9f\xe3\x82\x89\xe3\x82'
2891 '\x81\xe3\x81\xa7\xe3\x81\x99\xe3\x80\x82\xe5\xae\x9f\xe9\x9a\x9b'
2892 '\xe3\x81\xab\xe3\x81\xaf\xe3\x80\x8cWenn ist das Nunstuck git '
2893 'und Slotermeyer? Ja! Beiherhund das Oder die Flipperwaldt '
2894 'gersput.\xe3\x80\x8d\xe3\x81\xa8\xe8\xa8\x80\xe3\x81\xa3\xe3\x81'
2895 '\xa6\xe3\x81\x84\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82')
2896 # Test make_header()
2897 newh = make_header(decode_header(enc))
2898 eq(newh, enc)
2899
2900 def test_header_ctor_default_args(self):
2901 eq = self.ndiffAssertEqual
2902 h = Header()
2903 eq(h, '')
2904 h.append('foo', Charset('iso-8859-1'))
2905 eq(h, '=?iso-8859-1?q?foo?=')
2906
2907 def test_explicit_maxlinelen(self):
2908 eq = self.ndiffAssertEqual
2909 hstr = 'A very long line that must get split to something other than at the 76th character boundary to test the non-default behavior'
2910 h = Header(hstr)
2911 eq(h.encode(), '''\
2912 A very long line that must get split to something other than at the 76th
2913 character boundary to test the non-default behavior''')
2914 h = Header(hstr, header_name='Subject')
2915 eq(h.encode(), '''\
2916 A very long line that must get split to something other than at the
2917 76th character boundary to test the non-default behavior''')
2918 h = Header(hstr, maxlinelen=1024, header_name='Subject')
2919 eq(h.encode(), hstr)
2920
2921 def test_us_ascii_header(self):
2922 eq = self.assertEqual
2923 s = 'hello'
2924 x = decode_header(s)
2925 eq(x, [('hello', None)])
2926 h = make_header(x)
2927 eq(s, h.encode())
2928
2929 def test_string_charset(self):
2930 eq = self.assertEqual
2931 h = Header()
2932 h.append('hello', 'iso-8859-1')
2933 eq(h, '=?iso-8859-1?q?hello?=')
2934
2935 ## def test_unicode_error(self):
2936 ## raises = self.assertRaises
2937 ## raises(UnicodeError, Header, u'[P\xf6stal]', 'us-ascii')
2938 ## raises(UnicodeError, Header, '[P\xf6stal]', 'us-ascii')
2939 ## h = Header()
2940 ## raises(UnicodeError, h.append, u'[P\xf6stal]', 'us-ascii')
2941 ## raises(UnicodeError, h.append, '[P\xf6stal]', 'us-ascii')
2942 ## raises(UnicodeError, Header, u'\u83ca\u5730\u6642\u592b', 'iso-8859-1')
2943
2944 def test_utf8_shortest(self):
2945 eq = self.assertEqual
2946 h = Header(u'p\xf6stal', 'utf-8')
2947 eq(h.encode(), '=?utf-8?q?p=C3=B6stal?=')
2948 h = Header(u'\u83ca\u5730\u6642\u592b', 'utf-8')
2949 eq(h.encode(), '=?utf-8?b?6I+K5Zyw5pmC5aSr?=')
2950
2951 def test_bad_8bit_header(self):
2952 raises = self.assertRaises
2953 eq = self.assertEqual
2954 x = 'Ynwp4dUEbay Auction Semiar- No Charge \x96 Earn Big'
2955 raises(UnicodeError, Header, x)
2956 h = Header()
2957 raises(UnicodeError, h.append, x)
2958 eq(str(Header(x, errors='replace')), x)
2959 h.append(x, errors='replace')
2960 eq(str(h), x)
2961
2962 def test_encoded_adjacent_nonencoded(self):
2963 eq = self.assertEqual
2964 h = Header()
2965 h.append('hello', 'iso-8859-1')
2966 h.append('world')
2967 s = h.encode()
2968 eq(s, '=?iso-8859-1?q?hello?= world')
2969 h = make_header(decode_header(s))
2970 eq(h.encode(), s)
2971
2972 def test_whitespace_eater(self):
2973 eq = self.assertEqual
2974 s = 'Subject: =?koi8-r?b?8NLP18XSy8EgzsEgxsnOwczYztk=?= =?koi8-r?q?=CA?= zz.'
2975 parts = decode_header(s)
2976 eq(parts, [('Subject:', None), ('\xf0\xd2\xcf\xd7\xc5\xd2\xcb\xc1 \xce\xc1 \xc6\xc9\xce\xc1\xcc\xd8\xce\xd9\xca', 'koi8-r'), ('zz.', None)])
2977 hdr = make_header(parts)
2978 eq(hdr.encode(),
2979 'Subject: =?koi8-r?b?8NLP18XSy8EgzsEgxsnOwczYztnK?= zz.')
2980
2981 def test_broken_base64_header(self):
2982 raises = self.assertRaises
2983 s = 'Subject: =?EUC-KR?B?CSixpLDtKSC/7Liuvsax4iC6uLmwMcijIKHaILzSwd/H0SC8+LCjwLsgv7W/+Mj3I ?='
2984 raises(errors.HeaderParseError, decode_header, s)
2985
2986
2987
2988 # Test RFC 2231 header parameters (en/de)coding
2989 class TestRFC2231(TestEmailBase):
2990 def test_get_param(self):
2991 eq = self.assertEqual
2992 msg = self._msgobj('msg_29.txt')
2993 eq(msg.get_param('title'),
2994 ('us-ascii', 'en', 'This is even more ***fun*** isn\'t it!'))
2995 eq(msg.get_param('title', unquote=False),
2996 ('us-ascii', 'en', '"This is even more ***fun*** isn\'t it!"'))
2997
2998 def test_set_param(self):
2999 eq = self.assertEqual
3000 msg = Message()
3001 msg.set_param('title', 'This is even more ***fun*** isn\'t it!',
3002 charset='us-ascii')
3003 eq(msg.get_param('title'),
3004 ('us-ascii', '', 'This is even more ***fun*** isn\'t it!'))
3005 msg.set_param('title', 'This is even more ***fun*** isn\'t it!',
3006 charset='us-ascii', language='en')
3007 eq(msg.get_param('title'),
3008 ('us-ascii', 'en', 'This is even more ***fun*** isn\'t it!'))
3009 msg = self._msgobj('msg_01.txt')
3010 msg.set_param('title', 'This is even more ***fun*** isn\'t it!',
3011 charset='us-ascii', language='en')
3012 self.ndiffAssertEqual(msg.as_string(), """\
3013 Return-Path: <[email protected]>
3014 Delivered-To: [email protected]
3015 Received: by mail.zzz.org (Postfix, from userid 889)
3016 id 27CEAD38CC; Fri, 4 May 2001 14:05:44 -0400 (EDT)
3017 MIME-Version: 1.0
3018 Content-Transfer-Encoding: 7bit
3019 Message-ID: <[email protected]>
3020 From: [email protected] (John X. Doe)
3021 To: [email protected]
3022 Subject: This is a test message
3023 Date: Fri, 4 May 2001 14:05:44 -0400
3024 Content-Type: text/plain; charset=us-ascii;
3025 title*="us-ascii'en'This%20is%20even%20more%20%2A%2A%2Afun%2A%2A%2A%20isn%27t%20it%21"
3026
3027
3028 Hi,
3029
3030 Do you like this message?
3031
3032 -Me
3033 """)
3034
3035 def test_del_param(self):
3036 eq = self.ndiffAssertEqual
3037 msg = self._msgobj('msg_01.txt')
3038 msg.set_param('foo', 'bar', charset='us-ascii', language='en')
3039 msg.set_param('title', 'This is even more ***fun*** isn\'t it!',
3040 charset='us-ascii', language='en')
3041 msg.del_param('foo', header='Content-Type')
3042 eq(msg.as_string(), """\
3043 Return-Path: <[email protected]>
3044 Delivered-To: [email protected]
3045 Received: by mail.zzz.org (Postfix, from userid 889)
3046 id 27CEAD38CC; Fri, 4 May 2001 14:05:44 -0400 (EDT)
3047 MIME-Version: 1.0
3048 Content-Transfer-Encoding: 7bit
3049 Message-ID: <[email protected]>
3050 From: [email protected] (John X. Doe)
3051 To: [email protected]
3052 Subject: This is a test message
3053 Date: Fri, 4 May 2001 14:05:44 -0400
3054 Content-Type: text/plain; charset="us-ascii";
3055 title*="us-ascii'en'This%20is%20even%20more%20%2A%2A%2Afun%2A%2A%2A%20isn%27t%20it%21"
3056
3057
3058 Hi,
3059
3060 Do you like this message?
3061
3062 -Me
3063 """)
3064
3065 def test_rfc2231_get_content_charset(self):
3066 eq = self.assertEqual
3067 msg = self._msgobj('msg_32.txt')
3068 eq(msg.get_content_charset(), 'us-ascii')
3069
3070 def test_rfc2231_no_language_or_charset(self):
3071 m = '''\
3072 Content-Transfer-Encoding: 8bit
3073 Content-Disposition: inline; filename="file____C__DOCUMENTS_20AND_20SETTINGS_FABIEN_LOCAL_20SETTINGS_TEMP_nsmail.htm"
3074 Content-Type: text/html; NAME*0=file____C__DOCUMENTS_20AND_20SETTINGS_FABIEN_LOCAL_20SETTINGS_TEM; NAME*1=P_nsmail.htm
3075
3076 '''
3077 msg = email.message_from_string(m)
3078 param = msg.get_param('NAME')
3079 self.assertFalse(isinstance(param, tuple))
3080 self.assertEqual(
3081 param,
3082 'file____C__DOCUMENTS_20AND_20SETTINGS_FABIEN_LOCAL_20SETTINGS_TEMP_nsmail.htm')
3083
3084 def test_rfc2231_no_language_or_charset_in_filename(self):
3085 m = '''\
3086 Content-Disposition: inline;
3087 \tfilename*0*="''This%20is%20even%20more%20";
3088 \tfilename*1*="%2A%2A%2Afun%2A%2A%2A%20";
3089 \tfilename*2="is it not.pdf"
3090
3091 '''
3092 msg = email.message_from_string(m)
3093 self.assertEqual(msg.get_filename(),
3094 'This is even more ***fun*** is it not.pdf')
3095
3096 def test_rfc2231_no_language_or_charset_in_filename_encoded(self):
3097 m = '''\
3098 Content-Disposition: inline;
3099 \tfilename*0*="''This%20is%20even%20more%20";
3100 \tfilename*1*="%2A%2A%2Afun%2A%2A%2A%20";
3101 \tfilename*2="is it not.pdf"
3102
3103 '''
3104 msg = email.message_from_string(m)
3105 self.assertEqual(msg.get_filename(),
3106 'This is even more ***fun*** is it not.pdf')
3107
3108 def test_rfc2231_partly_encoded(self):
3109 m = '''\
3110 Content-Disposition: inline;
3111 \tfilename*0="''This%20is%20even%20more%20";
3112 \tfilename*1*="%2A%2A%2Afun%2A%2A%2A%20";
3113 \tfilename*2="is it not.pdf"
3114
3115 '''
3116 msg = email.message_from_string(m)
3117 self.assertEqual(
3118 msg.get_filename(),
3119 'This%20is%20even%20more%20***fun*** is it not.pdf')
3120
3121 def test_rfc2231_partly_nonencoded(self):
3122 m = '''\
3123 Content-Disposition: inline;
3124 \tfilename*0="This%20is%20even%20more%20";
3125 \tfilename*1="%2A%2A%2Afun%2A%2A%2A%20";
3126 \tfilename*2="is it not.pdf"
3127
3128 '''
3129 msg = email.message_from_string(m)
3130 self.assertEqual(
3131 msg.get_filename(),
3132 'This%20is%20even%20more%20%2A%2A%2Afun%2A%2A%2A%20is it not.pdf')
3133
3134 def test_rfc2231_no_language_or_charset_in_boundary(self):
3135 m = '''\
3136 Content-Type: multipart/alternative;
3137 \tboundary*0*="''This%20is%20even%20more%20";
3138 \tboundary*1*="%2A%2A%2Afun%2A%2A%2A%20";
3139 \tboundary*2="is it not.pdf"
3140
3141 '''
3142 msg = email.message_from_string(m)
3143 self.assertEqual(msg.get_boundary(),
3144 'This is even more ***fun*** is it not.pdf')
3145
3146 def test_rfc2231_no_language_or_charset_in_charset(self):
3147 # This is a nonsensical charset value, but tests the code anyway
3148 m = '''\
3149 Content-Type: text/plain;
3150 \tcharset*0*="This%20is%20even%20more%20";
3151 \tcharset*1*="%2A%2A%2Afun%2A%2A%2A%20";
3152 \tcharset*2="is it not.pdf"
3153
3154 '''
3155 msg = email.message_from_string(m)
3156 self.assertEqual(msg.get_content_charset(),
3157 'this is even more ***fun*** is it not.pdf')
3158
3159 def test_rfc2231_bad_encoding_in_filename(self):
3160 m = '''\
3161 Content-Disposition: inline;
3162 \tfilename*0*="bogus'xx'This%20is%20even%20more%20";
3163 \tfilename*1*="%2A%2A%2Afun%2A%2A%2A%20";
3164 \tfilename*2="is it not.pdf"
3165
3166 '''
3167 msg = email.message_from_string(m)
3168 self.assertEqual(msg.get_filename(),
3169 'This is even more ***fun*** is it not.pdf')
3170
3171 def test_rfc2231_bad_encoding_in_charset(self):
3172 m = """\
3173 Content-Type: text/plain; charset*=bogus''utf-8%E2%80%9D
3174
3175 """
3176 msg = email.message_from_string(m)
3177 # This should return None because non-ascii characters in the charset
3178 # are not allowed.
3179 self.assertEqual(msg.get_content_charset(), None)
3180
3181 def test_rfc2231_bad_character_in_charset(self):
3182 m = """\
3183 Content-Type: text/plain; charset*=ascii''utf-8%E2%80%9D
3184
3185 """
3186 msg = email.message_from_string(m)
3187 # This should return None because non-ascii characters in the charset
3188 # are not allowed.
3189 self.assertEqual(msg.get_content_charset(), None)
3190
3191 def test_rfc2231_bad_character_in_filename(self):
3192 m = '''\
3193 Content-Disposition: inline;
3194 \tfilename*0*="ascii'xx'This%20is%20even%20more%20";
3195 \tfilename*1*="%2A%2A%2Afun%2A%2A%2A%20";
3196 \tfilename*2*="is it not.pdf%E2"
3197
3198 '''
3199 msg = email.message_from_string(m)
3200 self.assertEqual(msg.get_filename(),
3201 u'This is even more ***fun*** is it not.pdf\ufffd')
3202
3203 def test_rfc2231_unknown_encoding(self):
3204 m = """\
3205 Content-Transfer-Encoding: 8bit
3206 Content-Disposition: inline; filename*=X-UNKNOWN''myfile.txt
3207
3208 """
3209 msg = email.message_from_string(m)
3210 self.assertEqual(msg.get_filename(), 'myfile.txt')
3211
3212 def test_rfc2231_single_tick_in_filename_extended(self):
3213 eq = self.assertEqual
3214 m = """\
3215 Content-Type: application/x-foo;
3216 \tname*0*=\"Frank's\"; name*1*=\" Document\"
3217
3218 """
3219 msg = email.message_from_string(m)
3220 charset, language, s = msg.get_param('name')
3221 eq(charset, None)
3222 eq(language, None)
3223 eq(s, "Frank's Document")
3224
3225 def test_rfc2231_single_tick_in_filename(self):
3226 m = """\
3227 Content-Type: application/x-foo; name*0=\"Frank's\"; name*1=\" Document\"
3228
3229 """
3230 msg = email.message_from_string(m)
3231 param = msg.get_param('name')
3232 self.assertFalse(isinstance(param, tuple))
3233 self.assertEqual(param, "Frank's Document")
3234
3235 def test_rfc2231_tick_attack_extended(self):
3236 eq = self.assertEqual
3237 m = """\
3238 Content-Type: application/x-foo;
3239 \tname*0*=\"us-ascii'en-us'Frank's\"; name*1*=\" Document\"
3240
3241 """
3242 msg = email.message_from_string(m)
3243 charset, language, s = msg.get_param('name')
3244 eq(charset, 'us-ascii')
3245 eq(language, 'en-us')
3246 eq(s, "Frank's Document")
3247
3248 def test_rfc2231_tick_attack(self):
3249 m = """\
3250 Content-Type: application/x-foo;
3251 \tname*0=\"us-ascii'en-us'Frank's\"; name*1=\" Document\"
3252
3253 """
3254 msg = email.message_from_string(m)
3255 param = msg.get_param('name')
3256 self.assertFalse(isinstance(param, tuple))
3257 self.assertEqual(param, "us-ascii'en-us'Frank's Document")
3258
3259 def test_rfc2231_no_extended_values(self):
3260 eq = self.assertEqual
3261 m = """\
3262 Content-Type: application/x-foo; name=\"Frank's Document\"
3263
3264 """
3265 msg = email.message_from_string(m)
3266 eq(msg.get_param('name'), "Frank's Document")
3267
3268 def test_rfc2231_encoded_then_unencoded_segments(self):
3269 eq = self.assertEqual
3270 m = """\
3271 Content-Type: application/x-foo;
3272 \tname*0*=\"us-ascii'en-us'My\";
3273 \tname*1=\" Document\";
3274 \tname*2*=\" For You\"
3275
3276 """
3277 msg = email.message_from_string(m)
3278 charset, language, s = msg.get_param('name')
3279 eq(charset, 'us-ascii')
3280 eq(language, 'en-us')
3281 eq(s, 'My Document For You')
3282
3283 def test_rfc2231_unencoded_then_encoded_segments(self):
3284 eq = self.assertEqual
3285 m = """\
3286 Content-Type: application/x-foo;
3287 \tname*0=\"us-ascii'en-us'My\";
3288 \tname*1*=\" Document\";
3289 \tname*2*=\" For You\"
3290
3291 """
3292 msg = email.message_from_string(m)
3293 charset, language, s = msg.get_param('name')
3294 eq(charset, 'us-ascii')
3295 eq(language, 'en-us')
3296 eq(s, 'My Document For You')
3297
3298
3299
3300 def _testclasses():
3301 mod = sys.modules[__name__]
3302 return [getattr(mod, name) for name in dir(mod) if name.startswith('Test')]
3303
3304
3305 def suite():
3306 suite = unittest.TestSuite()
3307 for testclass in _testclasses():
3308 suite.addTest(unittest.makeSuite(testclass))
3309 return suite
3310
3311
3312 def test_main():
3313 for testclass in _testclasses():
3314 run_unittest(testclass)
3315
3316
3317
3318 if __name__ == '__main__':
3319 unittest.main(defaultTest='suite')