/lib-python/2.7/email/test/test_email.py
Python | 3529 lines | 3431 code | 43 blank | 55 comment | 9 complexity | 365340ec651367d3cf81fdff842ea2a4 MD5 | raw file
Large files files are truncated, but you can click here to view the full file
- # Copyright (C) 2001-2010 Python Software Foundation
- # Contact: email-sig@python.org
- # email package unit tests
- import os
- import sys
- import time
- import base64
- import difflib
- import unittest
- import warnings
- from cStringIO import StringIO
- import email
- from email.Charset import Charset
- from email.Header import Header, decode_header, make_header
- from email.Parser import Parser, HeaderParser
- from email.Generator import Generator, DecodedGenerator
- from email.Message import Message
- from email.MIMEAudio import MIMEAudio
- from email.MIMEText import MIMEText
- from email.MIMEImage import MIMEImage
- from email.MIMEBase import MIMEBase
- from email.MIMEMessage import MIMEMessage
- from email.MIMEMultipart import MIMEMultipart
- from email import Utils
- from email import Errors
- from email import Encoders
- from email import Iterators
- from email import base64MIME
- from email import quopriMIME
- from test.test_support import findfile, run_unittest
- from email.test import __file__ as landmark
- NL = '\n'
- EMPTYSTRING = ''
- SPACE = ' '
- def openfile(filename, mode='r'):
- path = os.path.join(os.path.dirname(landmark), 'data', filename)
- return open(path, mode)
- # Base test class
- class TestEmailBase(unittest.TestCase):
- def ndiffAssertEqual(self, first, second):
- """Like assertEqual except use ndiff for readable output."""
- if first != second:
- sfirst = str(first)
- ssecond = str(second)
- diff = difflib.ndiff(sfirst.splitlines(), ssecond.splitlines())
- fp = StringIO()
- print >> fp, NL, NL.join(diff)
- raise self.failureException, fp.getvalue()
- def _msgobj(self, filename):
- fp = openfile(findfile(filename))
- try:
- msg = email.message_from_file(fp)
- finally:
- fp.close()
- return msg
- # Test various aspects of the Message class's API
- class TestMessageAPI(TestEmailBase):
- def test_get_all(self):
- eq = self.assertEqual
- msg = self._msgobj('msg_20.txt')
- eq(msg.get_all('cc'), ['ccc@zzz.org', 'ddd@zzz.org', 'eee@zzz.org'])
- eq(msg.get_all('xx', 'n/a'), 'n/a')
- def test_getset_charset(self):
- eq = self.assertEqual
- msg = Message()
- eq(msg.get_charset(), None)
- charset = Charset('iso-8859-1')
- msg.set_charset(charset)
- eq(msg['mime-version'], '1.0')
- eq(msg.get_content_type(), 'text/plain')
- eq(msg['content-type'], 'text/plain; charset="iso-8859-1"')
- eq(msg.get_param('charset'), 'iso-8859-1')
- eq(msg['content-transfer-encoding'], 'quoted-printable')
- eq(msg.get_charset().input_charset, 'iso-8859-1')
- # Remove the charset
- msg.set_charset(None)
- eq(msg.get_charset(), None)
- eq(msg['content-type'], 'text/plain')
- # Try adding a charset when there's already MIME headers present
- msg = Message()
- msg['MIME-Version'] = '2.0'
- msg['Content-Type'] = 'text/x-weird'
- msg['Content-Transfer-Encoding'] = 'quinted-puntable'
- msg.set_charset(charset)
- eq(msg['mime-version'], '2.0')
- eq(msg['content-type'], 'text/x-weird; charset="iso-8859-1"')
- eq(msg['content-transfer-encoding'], 'quinted-puntable')
- def test_set_charset_from_string(self):
- eq = self.assertEqual
- msg = Message()
- msg.set_charset('us-ascii')
- eq(msg.get_charset().input_charset, 'us-ascii')
- eq(msg['content-type'], 'text/plain; charset="us-ascii"')
- def test_set_payload_with_charset(self):
- msg = Message()
- charset = Charset('iso-8859-1')
- msg.set_payload('This is a string payload', charset)
- self.assertEqual(msg.get_charset().input_charset, 'iso-8859-1')
- def test_get_charsets(self):
- eq = self.assertEqual
- msg = self._msgobj('msg_08.txt')
- charsets = msg.get_charsets()
- eq(charsets, [None, 'us-ascii', 'iso-8859-1', 'iso-8859-2', 'koi8-r'])
- msg = self._msgobj('msg_09.txt')
- charsets = msg.get_charsets('dingbat')
- eq(charsets, ['dingbat', 'us-ascii', 'iso-8859-1', 'dingbat',
- 'koi8-r'])
- msg = self._msgobj('msg_12.txt')
- charsets = msg.get_charsets()
- eq(charsets, [None, 'us-ascii', 'iso-8859-1', None, 'iso-8859-2',
- 'iso-8859-3', 'us-ascii', 'koi8-r'])
- def test_get_filename(self):
- eq = self.assertEqual
- msg = self._msgobj('msg_04.txt')
- filenames = [p.get_filename() for p in msg.get_payload()]
- eq(filenames, ['msg.txt', 'msg.txt'])
- msg = self._msgobj('msg_07.txt')
- subpart = msg.get_payload(1)
- eq(subpart.get_filename(), 'dingusfish.gif')
- def test_get_filename_with_name_parameter(self):
- eq = self.assertEqual
- msg = self._msgobj('msg_44.txt')
- filenames = [p.get_filename() for p in msg.get_payload()]
- eq(filenames, ['msg.txt', 'msg.txt'])
- def test_get_boundary(self):
- eq = self.assertEqual
- msg = self._msgobj('msg_07.txt')
- # No quotes!
- eq(msg.get_boundary(), 'BOUNDARY')
- def test_set_boundary(self):
- eq = self.assertEqual
- # This one has no existing boundary parameter, but the Content-Type:
- # header appears fifth.
- msg = self._msgobj('msg_01.txt')
- msg.set_boundary('BOUNDARY')
- header, value = msg.items()[4]
- eq(header.lower(), 'content-type')
- eq(value, 'text/plain; charset="us-ascii"; boundary="BOUNDARY"')
- # This one has a Content-Type: header, with a boundary, stuck in the
- # middle of its headers. Make sure the order is preserved; it should
- # be fifth.
- msg = self._msgobj('msg_04.txt')
- msg.set_boundary('BOUNDARY')
- header, value = msg.items()[4]
- eq(header.lower(), 'content-type')
- eq(value, 'multipart/mixed; boundary="BOUNDARY"')
- # And this one has no Content-Type: header at all.
- msg = self._msgobj('msg_03.txt')
- self.assertRaises(Errors.HeaderParseError,
- msg.set_boundary, 'BOUNDARY')
- def test_make_boundary(self):
- msg = MIMEMultipart('form-data')
- # Note that when the boundary gets created is an implementation
- # detail and might change.
- self.assertEqual(msg.items()[0][1], 'multipart/form-data')
- # Trigger creation of boundary
- msg.as_string()
- self.assertEqual(msg.items()[0][1][:33],
- 'multipart/form-data; boundary="==')
- # XXX: there ought to be tests of the uniqueness of the boundary, too.
- def test_message_rfc822_only(self):
- # Issue 7970: message/rfc822 not in multipart parsed by
- # HeaderParser caused an exception when flattened.
- fp = openfile(findfile('msg_46.txt'))
- msgdata = fp.read()
- parser = email.Parser.HeaderParser()
- msg = parser.parsestr(msgdata)
- out = StringIO()
- gen = email.Generator.Generator(out, True, 0)
- gen.flatten(msg, False)
- self.assertEqual(out.getvalue(), msgdata)
- def test_get_decoded_payload(self):
- eq = self.assertEqual
- msg = self._msgobj('msg_10.txt')
- # The outer message is a multipart
- eq(msg.get_payload(decode=True), None)
- # Subpart 1 is 7bit encoded
- eq(msg.get_payload(0).get_payload(decode=True),
- 'This is a 7bit encoded message.\n')
- # Subpart 2 is quopri
- eq(msg.get_payload(1).get_payload(decode=True),
- '\xa1This is a Quoted Printable encoded message!\n')
- # Subpart 3 is base64
- eq(msg.get_payload(2).get_payload(decode=True),
- 'This is a Base64 encoded message.')
- # Subpart 4 is base64 with a trailing newline, which
- # used to be stripped (issue 7143).
- eq(msg.get_payload(3).get_payload(decode=True),
- 'This is a Base64 encoded message.\n')
- # Subpart 5 has no Content-Transfer-Encoding: header.
- eq(msg.get_payload(4).get_payload(decode=True),
- 'This has no Content-Transfer-Encoding: header.\n')
- def test_get_decoded_uu_payload(self):
- eq = self.assertEqual
- msg = Message()
- msg.set_payload('begin 666 -\n+:&5L;&\\@=V]R;&0 \n \nend\n')
- for cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'):
- msg['content-transfer-encoding'] = cte
- eq(msg.get_payload(decode=True), 'hello world')
- # Now try some bogus data
- msg.set_payload('foo')
- eq(msg.get_payload(decode=True), 'foo')
- def test_decode_bogus_uu_payload_quietly(self):
- msg = Message()
- msg.set_payload('begin 664 foo.txt\n%<W1F=0000H \n \nend\n')
- msg['Content-Transfer-Encoding'] = 'x-uuencode'
- old_stderr = sys.stderr
- try:
- sys.stderr = sfp = StringIO()
- # We don't care about the payload
- msg.get_payload(decode=True)
- finally:
- sys.stderr = old_stderr
- self.assertEqual(sfp.getvalue(), '')
- def test_decoded_generator(self):
- eq = self.assertEqual
- msg = self._msgobj('msg_07.txt')
- fp = openfile('msg_17.txt')
- try:
- text = fp.read()
- finally:
- fp.close()
- s = StringIO()
- g = DecodedGenerator(s)
- g.flatten(msg)
- eq(s.getvalue(), text)
- def test__contains__(self):
- msg = Message()
- msg['From'] = 'Me'
- msg['to'] = 'You'
- # Check for case insensitivity
- self.assertTrue('from' in msg)
- self.assertTrue('From' in msg)
- self.assertTrue('FROM' in msg)
- self.assertTrue('to' in msg)
- self.assertTrue('To' in msg)
- self.assertTrue('TO' in msg)
- def test_as_string(self):
- eq = self.assertEqual
- msg = self._msgobj('msg_01.txt')
- fp = openfile('msg_01.txt')
- try:
- # BAW 30-Mar-2009 Evil be here. So, the generator is broken with
- # respect to long line breaking. It's also not idempotent when a
- # header from a parsed message is continued with tabs rather than
- # spaces. Before we fixed bug 1974 it was reversedly broken,
- # i.e. headers that were continued with spaces got continued with
- # tabs. For Python 2.x there's really no good fix and in Python
- # 3.x all this stuff is re-written to be right(er). Chris Withers
- # convinced me that using space as the default continuation
- # character is less bad for more applications.
- text = fp.read().replace('\t', ' ')
- finally:
- fp.close()
- eq(text, msg.as_string())
- fullrepr = str(msg)
- lines = fullrepr.split('\n')
- self.assertTrue(lines[0].startswith('From '))
- eq(text, NL.join(lines[1:]))
- def test_bad_param(self):
- msg = email.message_from_string("Content-Type: blarg; baz; boo\n")
- self.assertEqual(msg.get_param('baz'), '')
- def test_missing_filename(self):
- msg = email.message_from_string("From: foo\n")
- self.assertEqual(msg.get_filename(), None)
- def test_bogus_filename(self):
- msg = email.message_from_string(
- "Content-Disposition: blarg; filename\n")
- self.assertEqual(msg.get_filename(), '')
- def test_missing_boundary(self):
- msg = email.message_from_string("From: foo\n")
- self.assertEqual(msg.get_boundary(), None)
- def test_get_params(self):
- eq = self.assertEqual
- msg = email.message_from_string(
- 'X-Header: foo=one; bar=two; baz=three\n')
- eq(msg.get_params(header='x-header'),
- [('foo', 'one'), ('bar', 'two'), ('baz', 'three')])
- msg = email.message_from_string(
- 'X-Header: foo; bar=one; baz=two\n')
- eq(msg.get_params(header='x-header'),
- [('foo', ''), ('bar', 'one'), ('baz', 'two')])
- eq(msg.get_params(), None)
- msg = email.message_from_string(
- 'X-Header: foo; bar="one"; baz=two\n')
- eq(msg.get_params(header='x-header'),
- [('foo', ''), ('bar', 'one'), ('baz', 'two')])
- def test_get_param_liberal(self):
- msg = Message()
- msg['Content-Type'] = 'Content-Type: Multipart/mixed; boundary = "CPIMSSMTPC06p5f3tG"'
- self.assertEqual(msg.get_param('boundary'), 'CPIMSSMTPC06p5f3tG')
- def test_get_param(self):
- eq = self.assertEqual
- msg = email.message_from_string(
- "X-Header: foo=one; bar=two; baz=three\n")
- eq(msg.get_param('bar', header='x-header'), 'two')
- eq(msg.get_param('quuz', header='x-header'), None)
- eq(msg.get_param('quuz'), None)
- msg = email.message_from_string(
- 'X-Header: foo; bar="one"; baz=two\n')
- eq(msg.get_param('foo', header='x-header'), '')
- eq(msg.get_param('bar', header='x-header'), 'one')
- eq(msg.get_param('baz', header='x-header'), 'two')
- # XXX: We are not RFC-2045 compliant! We cannot parse:
- # msg["Content-Type"] = 'text/plain; weird="hey; dolly? [you] @ <\\"home\\">?"'
- # msg.get_param("weird")
- # yet.
- def test_get_param_funky_continuation_lines(self):
- msg = self._msgobj('msg_22.txt')
- self.assertEqual(msg.get_payload(1).get_param('name'), 'wibble.JPG')
- def test_get_param_with_semis_in_quotes(self):
- msg = email.message_from_string(
- 'Content-Type: image/pjpeg; name="Jim&&Jill"\n')
- self.assertEqual(msg.get_param('name'), 'Jim&&Jill')
- self.assertEqual(msg.get_param('name', unquote=False),
- '"Jim&&Jill"')
- def test_get_param_with_quotes(self):
- msg = email.message_from_string(
- 'Content-Type: foo; bar*0="baz\\"foobar"; bar*1="\\"baz"')
- self.assertEqual(msg.get_param('bar'), 'baz"foobar"baz')
- msg = email.message_from_string(
- "Content-Type: foo; bar*0=\"baz\\\"foobar\"; bar*1=\"\\\"baz\"")
- self.assertEqual(msg.get_param('bar'), 'baz"foobar"baz')
- def test_has_key(self):
- msg = email.message_from_string('Header: exists')
- self.assertTrue(msg.has_key('header'))
- self.assertTrue(msg.has_key('Header'))
- self.assertTrue(msg.has_key('HEADER'))
- self.assertFalse(msg.has_key('headeri'))
- def test_set_param(self):
- eq = self.assertEqual
- msg = Message()
- msg.set_param('charset', 'iso-2022-jp')
- eq(msg.get_param('charset'), 'iso-2022-jp')
- msg.set_param('importance', 'high value')
- eq(msg.get_param('importance'), 'high value')
- eq(msg.get_param('importance', unquote=False), '"high value"')
- eq(msg.get_params(), [('text/plain', ''),
- ('charset', 'iso-2022-jp'),
- ('importance', 'high value')])
- eq(msg.get_params(unquote=False), [('text/plain', ''),
- ('charset', '"iso-2022-jp"'),
- ('importance', '"high value"')])
- msg.set_param('charset', 'iso-9999-xx', header='X-Jimmy')
- eq(msg.get_param('charset', header='X-Jimmy'), 'iso-9999-xx')
- def test_del_param(self):
- eq = self.assertEqual
- msg = self._msgobj('msg_05.txt')
- eq(msg.get_params(),
- [('multipart/report', ''), ('report-type', 'delivery-status'),
- ('boundary', 'D1690A7AC1.996856090/mail.example.com')])
- old_val = msg.get_param("report-type")
- msg.del_param("report-type")
- eq(msg.get_params(),
- [('multipart/report', ''),
- ('boundary', 'D1690A7AC1.996856090/mail.example.com')])
- msg.set_param("report-type", old_val)
- eq(msg.get_params(),
- [('multipart/report', ''),
- ('boundary', 'D1690A7AC1.996856090/mail.example.com'),
- ('report-type', old_val)])
- def test_del_param_on_other_header(self):
- msg = Message()
- msg.add_header('Content-Disposition', 'attachment', filename='bud.gif')
- msg.del_param('filename', 'content-disposition')
- self.assertEqual(msg['content-disposition'], 'attachment')
- def test_set_type(self):
- eq = self.assertEqual
- msg = Message()
- self.assertRaises(ValueError, msg.set_type, 'text')
- msg.set_type('text/plain')
- eq(msg['content-type'], 'text/plain')
- msg.set_param('charset', 'us-ascii')
- eq(msg['content-type'], 'text/plain; charset="us-ascii"')
- msg.set_type('text/html')
- eq(msg['content-type'], 'text/html; charset="us-ascii"')
- def test_set_type_on_other_header(self):
- msg = Message()
- msg['X-Content-Type'] = 'text/plain'
- msg.set_type('application/octet-stream', 'X-Content-Type')
- self.assertEqual(msg['x-content-type'], 'application/octet-stream')
- def test_get_content_type_missing(self):
- msg = Message()
- self.assertEqual(msg.get_content_type(), 'text/plain')
- def test_get_content_type_missing_with_default_type(self):
- msg = Message()
- msg.set_default_type('message/rfc822')
- self.assertEqual(msg.get_content_type(), 'message/rfc822')
- def test_get_content_type_from_message_implicit(self):
- msg = self._msgobj('msg_30.txt')
- self.assertEqual(msg.get_payload(0).get_content_type(),
- 'message/rfc822')
- def test_get_content_type_from_message_explicit(self):
- msg = self._msgobj('msg_28.txt')
- self.assertEqual(msg.get_payload(0).get_content_type(),
- 'message/rfc822')
- def test_get_content_type_from_message_text_plain_implicit(self):
- msg = self._msgobj('msg_03.txt')
- self.assertEqual(msg.get_content_type(), 'text/plain')
- def test_get_content_type_from_message_text_plain_explicit(self):
- msg = self._msgobj('msg_01.txt')
- self.assertEqual(msg.get_content_type(), 'text/plain')
- def test_get_content_maintype_missing(self):
- msg = Message()
- self.assertEqual(msg.get_content_maintype(), 'text')
- def test_get_content_maintype_missing_with_default_type(self):
- msg = Message()
- msg.set_default_type('message/rfc822')
- self.assertEqual(msg.get_content_maintype(), 'message')
- def test_get_content_maintype_from_message_implicit(self):
- msg = self._msgobj('msg_30.txt')
- self.assertEqual(msg.get_payload(0).get_content_maintype(), 'message')
- def test_get_content_maintype_from_message_explicit(self):
- msg = self._msgobj('msg_28.txt')
- self.assertEqual(msg.get_payload(0).get_content_maintype(), 'message')
- def test_get_content_maintype_from_message_text_plain_implicit(self):
- msg = self._msgobj('msg_03.txt')
- self.assertEqual(msg.get_content_maintype(), 'text')
- def test_get_content_maintype_from_message_text_plain_explicit(self):
- msg = self._msgobj('msg_01.txt')
- self.assertEqual(msg.get_content_maintype(), 'text')
- def test_get_content_subtype_missing(self):
- msg = Message()
- self.assertEqual(msg.get_content_subtype(), 'plain')
- def test_get_content_subtype_missing_with_default_type(self):
- msg = Message()
- msg.set_default_type('message/rfc822')
- self.assertEqual(msg.get_content_subtype(), 'rfc822')
- def test_get_content_subtype_from_message_implicit(self):
- msg = self._msgobj('msg_30.txt')
- self.assertEqual(msg.get_payload(0).get_content_subtype(), 'rfc822')
- def test_get_content_subtype_from_message_explicit(self):
- msg = self._msgobj('msg_28.txt')
- self.assertEqual(msg.get_payload(0).get_content_subtype(), 'rfc822')
- def test_get_content_subtype_from_message_text_plain_implicit(self):
- msg = self._msgobj('msg_03.txt')
- self.assertEqual(msg.get_content_subtype(), 'plain')
- def test_get_content_subtype_from_message_text_plain_explicit(self):
- msg = self._msgobj('msg_01.txt')
- self.assertEqual(msg.get_content_subtype(), 'plain')
- def test_get_content_maintype_error(self):
- msg = Message()
- msg['Content-Type'] = 'no-slash-in-this-string'
- self.assertEqual(msg.get_content_maintype(), 'text')
- def test_get_content_subtype_error(self):
- msg = Message()
- msg['Content-Type'] = 'no-slash-in-this-string'
- self.assertEqual(msg.get_content_subtype(), 'plain')
- def test_replace_header(self):
- eq = self.assertEqual
- msg = Message()
- msg.add_header('First', 'One')
- msg.add_header('Second', 'Two')
- msg.add_header('Third', 'Three')
- eq(msg.keys(), ['First', 'Second', 'Third'])
- eq(msg.values(), ['One', 'Two', 'Three'])
- msg.replace_header('Second', 'Twenty')
- eq(msg.keys(), ['First', 'Second', 'Third'])
- eq(msg.values(), ['One', 'Twenty', 'Three'])
- msg.add_header('First', 'Eleven')
- msg.replace_header('First', 'One Hundred')
- eq(msg.keys(), ['First', 'Second', 'Third', 'First'])
- eq(msg.values(), ['One Hundred', 'Twenty', 'Three', 'Eleven'])
- self.assertRaises(KeyError, msg.replace_header, 'Fourth', 'Missing')
- def test_broken_base64_payload(self):
- x = 'AwDp0P7//y6LwKEAcPa/6Q=9'
- msg = Message()
- msg['content-type'] = 'audio/x-midi'
- msg['content-transfer-encoding'] = 'base64'
- msg.set_payload(x)
- self.assertEqual(msg.get_payload(decode=True), x)
- def test_get_content_charset(self):
- msg = Message()
- msg.set_charset('us-ascii')
- self.assertEqual('us-ascii', msg.get_content_charset())
- msg.set_charset(u'us-ascii')
- self.assertEqual('us-ascii', msg.get_content_charset())
- # Issue 5871: reject an attempt to embed a header inside a header value
- # (header injection attack).
- def test_embeded_header_via_Header_rejected(self):
- msg = Message()
- msg['Dummy'] = Header('dummy\nX-Injected-Header: test')
- self.assertRaises(Errors.HeaderParseError, msg.as_string)
- def test_embeded_header_via_string_rejected(self):
- msg = Message()
- msg['Dummy'] = 'dummy\nX-Injected-Header: test'
- self.assertRaises(Errors.HeaderParseError, msg.as_string)
- # Test the email.Encoders module
- class TestEncoders(unittest.TestCase):
- def test_encode_empty_payload(self):
- eq = self.assertEqual
- msg = Message()
- msg.set_charset('us-ascii')
- eq(msg['content-transfer-encoding'], '7bit')
- def test_default_cte(self):
- eq = self.assertEqual
- # 7bit data and the default us-ascii _charset
- msg = MIMEText('hello world')
- eq(msg['content-transfer-encoding'], '7bit')
- # Similar, but with 8bit data
- msg = MIMEText('hello \xf8 world')
- eq(msg['content-transfer-encoding'], '8bit')
- # And now with a different charset
- msg = MIMEText('hello \xf8 world', _charset='iso-8859-1')
- eq(msg['content-transfer-encoding'], 'quoted-printable')
- def test_encode7or8bit(self):
- # Make sure a charset whose input character set is 8bit but
- # whose output character set is 7bit gets a transfer-encoding
- # of 7bit.
- eq = self.assertEqual
- msg = email.MIMEText.MIMEText('\xca\xb8', _charset='euc-jp')
- eq(msg['content-transfer-encoding'], '7bit')
- # Test long header wrapping
- class TestLongHeaders(TestEmailBase):
- def test_split_long_continuation(self):
- eq = self.ndiffAssertEqual
- msg = email.message_from_string("""\
- Subject: bug demonstration
- \t12345678911234567892123456789312345678941234567895123456789612345678971234567898112345678911234567892123456789112345678911234567892123456789
- \tmore text
- test
- """)
- sfp = StringIO()
- g = Generator(sfp)
- g.flatten(msg)
- eq(sfp.getvalue(), """\
- Subject: bug demonstration
- 12345678911234567892123456789312345678941234567895123456789612345678971234567898112345678911234567892123456789112345678911234567892123456789
- more text
- test
- """)
- def test_another_long_almost_unsplittable_header(self):
- eq = self.ndiffAssertEqual
- hstr = """\
- bug demonstration
- \t12345678911234567892123456789312345678941234567895123456789612345678971234567898112345678911234567892123456789112345678911234567892123456789
- \tmore text"""
- h = Header(hstr, continuation_ws='\t')
- eq(h.encode(), """\
- bug demonstration
- \t12345678911234567892123456789312345678941234567895123456789612345678971234567898112345678911234567892123456789112345678911234567892123456789
- \tmore text""")
- h = Header(hstr)
- eq(h.encode(), """\
- bug demonstration
- 12345678911234567892123456789312345678941234567895123456789612345678971234567898112345678911234567892123456789112345678911234567892123456789
- more text""")
- def test_long_nonstring(self):
- eq = self.ndiffAssertEqual
- g = Charset("iso-8859-1")
- cz = Charset("iso-8859-2")
- utf8 = Charset("utf-8")
- 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. "
- cz_head = "Finan\xe8ni metropole se hroutily pod tlakem jejich d\xf9vtipu.. "
- 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")
- h = Header(g_head, g, header_name='Subject')
- h.append(cz_head, cz)
- h.append(utf8_head, utf8)
- msg = Message()
- msg['Subject'] = h
- sfp = StringIO()
- g = Generator(sfp)
- g.flatten(msg)
- eq(sfp.getvalue(), """\
- Subject: =?iso-8859-1?q?Die_Mieter_treten_hier_ein_werden_mit_einem_Foerd?=
- =?iso-8859-1?q?erband_komfortabel_den_Korridor_entlang=2C_an_s=FCdl=FCndi?=
- =?iso-8859-1?q?schen_Wandgem=E4lden_vorbei=2C_gegen_die_rotierenden_Kling?=
- =?iso-8859-1?q?en_bef=F6rdert=2E_?= =?iso-8859-2?q?Finan=E8ni_met?=
- =?iso-8859-2?q?ropole_se_hroutily_pod_tlakem_jejich_d=F9vtipu=2E=2E_?=
- =?utf-8?b?5q2j56K644Gr6KiA44GG44Go57+76Kiz44Gv44GV44KM44Gm44GE?=
- =?utf-8?b?44G+44Gb44KT44CC5LiA6YOo44Gv44OJ44Kk44OE6Kqe44Gn44GZ44GM44CB?=
- =?utf-8?b?44GC44Go44Gv44Gn44Gf44KJ44KB44Gn44GZ44CC5a6f6Zqb44Gr44Gv44CM?=
- =?utf-8?q?Wenn_ist_das_Nunstuck_git_und_Slotermeyer=3F_Ja!_Beiherhund_das?=
- =?utf-8?b?IE9kZXIgZGllIEZsaXBwZXJ3YWxkdCBnZXJzcHV0LuOAjeOBqOiogOOBow==?=
- =?utf-8?b?44Gm44GE44G+44GZ44CC?=
- """)
- eq(h.encode(), """\
- =?iso-8859-1?q?Die_Mieter_treten_hier_ein_werden_mit_einem_Foerd?=
- =?iso-8859-1?q?erband_komfortabel_den_Korridor_entlang=2C_an_s=FCdl=FCndi?=
- =?iso-8859-1?q?schen_Wandgem=E4lden_vorbei=2C_gegen_die_rotierenden_Kling?=
- =?iso-8859-1?q?en_bef=F6rdert=2E_?= =?iso-8859-2?q?Finan=E8ni_met?=
- =?iso-8859-2?q?ropole_se_hroutily_pod_tlakem_jejich_d=F9vtipu=2E=2E_?=
- =?utf-8?b?5q2j56K644Gr6KiA44GG44Go57+76Kiz44Gv44GV44KM44Gm44GE?=
- =?utf-8?b?44G+44Gb44KT44CC5LiA6YOo44Gv44OJ44Kk44OE6Kqe44Gn44GZ44GM44CB?=
- =?utf-8?b?44GC44Go44Gv44Gn44Gf44KJ44KB44Gn44GZ44CC5a6f6Zqb44Gr44Gv44CM?=
- =?utf-8?q?Wenn_ist_das_Nunstuck_git_und_Slotermeyer=3F_Ja!_Beiherhund_das?=
- =?utf-8?b?IE9kZXIgZGllIEZsaXBwZXJ3YWxkdCBnZXJzcHV0LuOAjeOBqOiogOOBow==?=
- =?utf-8?b?44Gm44GE44G+44GZ44CC?=""")
- def test_long_header_encode(self):
- eq = self.ndiffAssertEqual
- h = Header('wasnipoop; giraffes="very-long-necked-animals"; '
- 'spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"',
- header_name='X-Foobar-Spoink-Defrobnit')
- eq(h.encode(), '''\
- wasnipoop; giraffes="very-long-necked-animals";
- spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"''')
- def test_long_header_encode_with_tab_continuation(self):
- eq = self.ndiffAssertEqual
- h = Header('wasnipoop; giraffes="very-long-necked-animals"; '
- 'spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"',
- header_name='X-Foobar-Spoink-Defrobnit',
- continuation_ws='\t')
- eq(h.encode(), '''\
- wasnipoop; giraffes="very-long-necked-animals";
- \tspooge="yummy"; hippos="gargantuan"; marshmallows="gooey"''')
- def test_header_splitter(self):
- eq = self.ndiffAssertEqual
- msg = MIMEText('')
- # It'd be great if we could use add_header() here, but that doesn't
- # guarantee an order of the parameters.
- msg['X-Foobar-Spoink-Defrobnit'] = (
- 'wasnipoop; giraffes="very-long-necked-animals"; '
- 'spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"')
- sfp = StringIO()
- g = Generator(sfp)
- g.flatten(msg)
- eq(sfp.getvalue(), '''\
- Content-Type: text/plain; charset="us-ascii"
- MIME-Version: 1.0
- Content-Transfer-Encoding: 7bit
- X-Foobar-Spoink-Defrobnit: wasnipoop; giraffes="very-long-necked-animals";
- spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"
- ''')
- def test_no_semis_header_splitter(self):
- eq = self.ndiffAssertEqual
- msg = Message()
- msg['From'] = 'test@dom.ain'
- msg['References'] = SPACE.join(['<%d@dom.ain>' % i for i in range(10)])
- msg.set_payload('Test')
- sfp = StringIO()
- g = Generator(sfp)
- g.flatten(msg)
- eq(sfp.getvalue(), """\
- From: test@dom.ain
- References: <0@dom.ain> <1@dom.ain> <2@dom.ain> <3@dom.ain> <4@dom.ain>
- <5@dom.ain> <6@dom.ain> <7@dom.ain> <8@dom.ain> <9@dom.ain>
- Test""")
- def test_no_split_long_header(self):
- eq = self.ndiffAssertEqual
- hstr = 'References: ' + 'x' * 80
- h = Header(hstr, continuation_ws='\t')
- eq(h.encode(), """\
- References: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx""")
- def test_splitting_multiple_long_lines(self):
- eq = self.ndiffAssertEqual
- hstr = """\
- from babylon.socal-raves.org (localhost [127.0.0.1]); by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81; for <mailman-admin@babylon.socal-raves.org>; Sat, 2 Feb 2002 17:00:06 -0800 (PST)
- \tfrom babylon.socal-raves.org (localhost [127.0.0.1]); by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81; for <mailman-admin@babylon.socal-raves.org>; Sat, 2 Feb 2002 17:00:06 -0800 (PST)
- \tfrom babylon.socal-raves.org (localhost [127.0.0.1]); by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81; for <mailman-admin@babylon.socal-raves.org>; Sat, 2 Feb 2002 17:00:06 -0800 (PST)
- """
- h = Header(hstr, continuation_ws='\t')
- eq(h.encode(), """\
- from babylon.socal-raves.org (localhost [127.0.0.1]);
- \tby babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81;
- \tfor <mailman-admin@babylon.socal-raves.org>;
- \tSat, 2 Feb 2002 17:00:06 -0800 (PST)
- \tfrom babylon.socal-raves.org (localhost [127.0.0.1]);
- \tby babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81;
- \tfor <mailman-admin@babylon.socal-raves.org>;
- \tSat, 2 Feb 2002 17:00:06 -0800 (PST)
- \tfrom babylon.socal-raves.org (localhost [127.0.0.1]);
- \tby babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81;
- \tfor <mailman-admin@babylon.socal-raves.org>;
- \tSat, 2 Feb 2002 17:00:06 -0800 (PST)""")
- def test_splitting_first_line_only_is_long(self):
- eq = self.ndiffAssertEqual
- hstr = """\
- from modemcable093.139-201-24.que.mc.videotron.ca ([24.201.139.93] helo=cthulhu.gerg.ca)
- \tby kronos.mems-exchange.org with esmtp (Exim 4.05)
- \tid 17k4h5-00034i-00
- \tfor test@mems-exchange.org; Wed, 28 Aug 2002 11:25:20 -0400"""
- h = Header(hstr, maxlinelen=78, header_name='Received',
- continuation_ws='\t')
- eq(h.encode(), """\
- from modemcable093.139-201-24.que.mc.videotron.ca ([24.201.139.93]
- \thelo=cthulhu.gerg.ca)
- \tby kronos.mems-exchange.org with esmtp (Exim 4.05)
- \tid 17k4h5-00034i-00
- \tfor test@mems-exchange.org; Wed, 28 Aug 2002 11:25:20 -0400""")
- def test_long_8bit_header(self):
- eq = self.ndiffAssertEqual
- msg = Message()
- h = Header('Britische Regierung gibt', 'iso-8859-1',
- header_name='Subject')
- h.append('gr\xfcnes Licht f\xfcr Offshore-Windkraftprojekte')
- msg['Subject'] = h
- eq(msg.as_string(), """\
- Subject: =?iso-8859-1?q?Britische_Regierung_gibt?= =?iso-8859-1?q?gr=FCnes?=
- =?iso-8859-1?q?_Licht_f=FCr_Offshore-Windkraftprojekte?=
- """)
- def test_long_8bit_header_no_charset(self):
- eq = self.ndiffAssertEqual
- msg = Message()
- msg['Reply-To'] = 'Britische Regierung gibt gr\xfcnes Licht f\xfcr Offshore-Windkraftprojekte <a-very-long-address@example.com>'
- eq(msg.as_string(), """\
- Reply-To: Britische Regierung gibt gr\xfcnes Licht f\xfcr Offshore-Windkraftprojekte <a-very-long-address@example.com>
- """)
- def test_long_to_header(self):
- eq = self.ndiffAssertEqual
- to = '"Someone Test #A" <someone@eecs.umich.edu>,<someone@eecs.umich.edu>,"Someone Test #B" <someone@umich.edu>, "Someone Test #C" <someone@eecs.umich.edu>, "Someone Test #D" <someone@eecs.umich.edu>'
- msg = Message()
- msg['To'] = to
- eq(msg.as_string(0), '''\
- To: "Someone Test #A" <someone@eecs.umich.edu>, <someone@eecs.umich.edu>,
- "Someone Test #B" <someone@umich.edu>,
- "Someone Test #C" <someone@eecs.umich.edu>,
- "Someone Test #D" <someone@eecs.umich.edu>
- ''')
- def test_long_line_after_append(self):
- eq = self.ndiffAssertEqual
- s = 'This is an example of string which has almost the limit of header length.'
- h = Header(s)
- h.append('Add another line.')
- eq(h.encode(), """\
- This is an example of string which has almost the limit of header length.
- Add another line.""")
- def test_shorter_line_with_append(self):
- eq = self.ndiffAssertEqual
- s = 'This is a shorter line.'
- h = Header(s)
- h.append('Add another sentence. (Surprise?)')
- eq(h.encode(),
- 'This is a shorter line. Add another sentence. (Surprise?)')
- def test_long_field_name(self):
- eq = self.ndiffAssertEqual
- fn = 'X-Very-Very-Very-Long-Header-Name'
- 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. "
- h = Header(gs, 'iso-8859-1', header_name=fn)
- # BAW: this seems broken because the first line is too long
- eq(h.encode(), """\
- =?iso-8859-1?q?Die_Mieter_treten_hier_?=
- =?iso-8859-1?q?ein_werden_mit_einem_Foerderband_komfortabel_den_Korridor_?=
- =?iso-8859-1?q?entlang=2C_an_s=FCdl=FCndischen_Wandgem=E4lden_vorbei=2C_g?=
- =?iso-8859-1?q?egen_die_rotierenden_Klingen_bef=F6rdert=2E_?=""")
- def test_long_received_header(self):
- 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'
- msg = Message()
- msg['Received-1'] = Header(h, continuation_ws='\t')
- msg['Received-2'] = h
- self.assertEqual(msg.as_string(), """\
- Received-1: from FOO.TLD (vizworld.acl.foo.tld [123.452.678.9]) by
- \throthgar.la.mastaler.com (tmda-ofmipd) with ESMTP;
- \tWed, 05 Mar 2003 18:10:18 -0700
- Received-2: 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
- """)
- def test_string_headerinst_eq(self):
- h = '<15975.17901.207240.414604@sgigritzmann1.mathematik.tu-muenchen.de> (David Bremner\'s message of "Thu, 6 Mar 2003 13:58:21 +0100")'
- msg = Message()
- msg['Received'] = Header(h, header_name='Received',
- continuation_ws='\t')
- msg['Received'] = h
- self.ndiffAssertEqual(msg.as_string(), """\
- Received: <15975.17901.207240.414604@sgigritzmann1.mathematik.tu-muenchen.de>
- \t(David Bremner's message of "Thu, 6 Mar 2003 13:58:21 +0100")
- Received: <15975.17901.207240.414604@sgigritzmann1.mathematik.tu-muenchen.de>
- (David Bremner's message of "Thu, 6 Mar 2003 13:58:21 +0100")
- """)
- def test_long_unbreakable_lines_with_continuation(self):
- eq = self.ndiffAssertEqual
- msg = Message()
- t = """\
- iVBORw0KGgoAAAANSUhEUgAAADAAAAAwBAMAAAClLOS0AAAAGFBMVEUAAAAkHiJeRUIcGBi9
- locQDQ4zJykFBAXJfWDjAAACYUlEQVR4nF2TQY/jIAyFc6lydlG5x8Nyp1Y69wj1PN2I5gzp"""
- msg['Face-1'] = t
- msg['Face-2'] = Header(t, header_name='Face-2')
- eq(msg.as_string(), """\
- Face-1: iVBORw0KGgoAAAANSUhEUgAAADAAAAAwBAMAAAClLOS0AAAAGFBMVEUAAAAkHiJeRUIcGBi9
- locQDQ4zJykFBAXJfWDjAAACYUlEQVR4nF2TQY/jIAyFc6lydlG5x8Nyp1Y69wj1PN2I5gzp
- Face-2: iVBORw0KGgoAAAANSUhEUgAAADAAAAAwBAMAAAClLOS0AAAAGFBMVEUAAAAkHiJeRUIcGBi9
- locQDQ4zJykFBAXJfWDjAAACYUlEQVR4nF2TQY/jIAyFc6lydlG5x8Nyp1Y69wj1PN2I5gzp
- """)
- def test_another_long_multiline_header(self):
- eq = self.ndiffAssertEqual
- m = '''\
- Received: from siimage.com ([172.25.1.3]) by zima.siliconimage.com with Microsoft SMTPSVC(5.0.2195.4905);
- Wed, 16 Oct 2002 07:41:11 -0700'''
- msg = email.message_from_string(m)
- eq(msg.as_string(), '''\
- Received: from siimage.com ([172.25.1.3]) by zima.siliconimage.com with
- Microsoft SMTPSVC(5.0.2195.4905); Wed, 16 Oct 2002 07:41:11 -0700
- ''')
- def test_long_lines_with_different_header(self):
- eq = self.ndiffAssertEqual
- h = """\
- List-Unsubscribe: <https://lists.sourceforge.net/lists/listinfo/spamassassin-talk>,
- <mailto:spamassassin-talk-request@lists.sourceforge.net?subject=unsubscribe>"""
- msg = Message()
- msg['List'] = h
- msg['List'] = Header(h, header_name='List')
- eq(msg.as_string(), """\
- List: List-Unsubscribe: <https://lists.sourceforge.net/lists/listinfo/spamassassin-talk>,
- <mailto:spamassassin-talk-request@lists.sourceforge.net?subject=unsubscribe>
- List: List-Unsubscribe: <https://lists.sourceforge.net/lists/listinfo/spamassassin-talk>,
- <mailto:spamassassin-talk-request@lists.sourceforge.net?subject=unsubscribe>
- """)
- # Test mangling of "From " lines in the body of a message
- class TestFromMangling(unittest.TestCase):
- def setUp(self):
- self.msg = Message()
- self.msg['From'] = 'aaa@bbb.org'
- self.msg.set_payload("""\
- From the desk of A.A.A.:
- Blah blah blah
- """)
- def test_mangled_from(self):
- s = StringIO()
- g = Generator(s, mangle_from_=True)
- g.flatten(self.msg)
- self.assertEqual(s.getvalue(), """\
- From: aaa@bbb.org
- >From the desk of A.A.A.:
- Blah blah blah
- """)
- def test_dont_mangle_from(self):
- s = StringIO()
- g = Generator(s, mangle_from_=False)
- g.flatten(self.msg)
- self.assertEqual(s.getvalue(), """\
- From: aaa@bbb.org
- From the desk of A.A.A.:
- Blah blah blah
- """)
- # Test the basic MIMEAudio class
- class TestMIMEAudio(unittest.TestCase):
- def setUp(self):
- # Make sure we pick up the audiotest.au that lives in email/test/data.
- # In Python, there's an audiotest.au living in Lib/test but that isn't
- # included in some binary distros that don't include the test
- # package. The trailing empty string on the .join() is significant
- # since findfile() will do a dirname().
- datadir = os.path.join(os.path.dirname(landmark), 'data', '')
- fp = open(findfile('audiotest.au', datadir), 'rb')
- try:
- self._audiodata = fp.read()
- finally:
- fp.close()
- self._au = MIMEAudio(self._audiodata)
- def test_guess_minor_type(self):
- self.assertEqual(self._au.get_content_type(), 'audio/basic')
- def test_encoding(self):
- payload = self._au.get_payload()
- self.assertEqual(base64.decodestring(payload), self._audiodata)
- def test_checkSetMinor(self):
- au = MIMEAudio(self._audiodata, 'fish')
- self.assertEqual(au.get_content_type(), 'audio/fish')
- def test_add_header(self):
- eq = self.assertEqual
- unless = self.assertTrue
- self._au.add_header('Content-Disposition', 'attachment',
- filename='audiotest.au')
- eq(self._au['content-disposition'],
- 'attachment; filename="audiotest.au"')
- eq(self._au.get_params(header='content-disposition'),
- [('attachment', ''), ('filename', 'audiotest.au')])
- eq(self._au.get_param('filename', header='content-disposition'),
- 'audiotest.au')
- missing = []
- eq(self._au.get_param('attachment', header='content-disposition'), '')
- unless(self._au.get_param('foo', failobj=missing,
- header='content-disposition') is missing)
- # Try some missing stuff
- unless(self._au.get_param('foobar', missing) is missing)
- unless(self._au.get_param('attachment', missing,
- header='foobar') is missing)
- # Test the basic MIMEImage class
- class TestMIMEImage(unittest.TestCase):
- def setUp(self):
- fp = openfile('PyBanner048.gif')
- try:
- self._imgdata = fp.read()
- finally:
- fp.close()
- self._im = MIMEImage(self._imgdata)
- def test_guess_minor_type(self):
- self.assertEqual(self._im.get_content_type(), 'image/gif')
- def test_encoding(self):
- payload = self._im.get_payload()
- self.assertEqual(base64.decodestring(payload), self._imgdata)
- def test_checkSetMinor(self):
- im = MIMEImage(self._imgdata, 'fish')
- self.assertEqual(im.get_content_type(), 'image/fish')
- def test_add_header(self):
- eq = self.assertEqual
- unless = self.assertTrue
- self._im.add_header('Content-Disposition', 'attachment',
- filename='dingusfish.gif')
- eq(self._im['content-disposition'],
- 'attachment; filename="dingusfish.gif"')
- eq(self._im.get_params(header='content-disposition'),
- [('attachment', ''), ('filename', 'dingusfish.gif')])
- eq(self._im.get_param('filename', header='content-disposition'),
- 'dingusfish.gif')
- missing = []
- eq(self._im.get_param('attachment', header='content-disposition'), '')
- unless(self._im.get_param('foo', failobj=missing,
- header='content-disposition') is missing)
- # Try some missing stuff
- unless(self._im.get_param('foobar', missing) is missing)
- unless(self._im.get_param('attachment', missing,
- header='foobar') is missing)
- # Test the basic MIMEText class
- class TestMIMEText(unittest.TestCase):
- def setUp(self):
- self._msg = MIMEText('hello there')
- def test_types(self):
- eq = self.assertEqual
- unless = self.assertTrue
- eq(self._msg.get_content_type(), 'text/plain')
- eq(self._msg.get_param('charset'), 'us-ascii')
- missing = []
- unless(self._msg.get_param('foobar', missing) is missing)
- unless(self._msg.get_param('charset', missing, header='foobar')
- is missing)
- def test_payload(self):
- self.assertEqual(self._msg.get_payload(), 'hello there')
- self.assertTrue(not self._msg.is_multipart())
- def test_charset(self):
- eq = self.assertEqual
- msg = MIMEText('hello there', _charset='us-ascii')
- eq(msg.get_charset().input_charset, 'us-ascii')
- eq(msg['content-type'], 'text/plain; charset="us-ascii"')
- def test_7bit_unicode_input(self):
- eq = self.assertEqual
- msg = MIMEText(u'hello there', _charset='us-ascii')
- eq(msg.get_charset().input_charset, 'us-ascii')
- eq(msg['content-type'], 'text/plain; charset="us-ascii"')
- def test_7bit_unicode_input_no_charset(self):
- eq = self.assertEqual
- msg = MIMEText(u'hello there')
- eq(msg.get_charset(), 'us-ascii')
- eq(msg['content-type'], 'text/plain; charset="us-ascii"')
- self.assertTrue('hello there' in msg.as_string())
- def test_8bit_unicode_input(self):
- teststr = u'\u043a\u0438\u0440\u0438\u043b\u0438\u0446\u0430'
- eq = self.assertEqual
- msg = MIMEText(teststr, _charset='utf-8')
- eq(msg.get_charset().output_charset, 'utf-8')
- eq(msg['content-type'], 'text/plain; charset="utf-8"')
- eq(msg.get_payload(decode=True), teststr.encode('utf-8'))
- def test_8bit_unicode_input_no_charset(self):
- teststr = u'\u043a\u0438\u0440\u0438\u043b\u0438\u0446\u0430'
- self.assertRaises(UnicodeEncodeError, MIMEText, teststr)
- # Test complicated multipart/* messages
- class TestMultipart(TestEmailBase):
- def setUp(self):
- fp = openfile('PyBanner048.gif')
- try:
- data = fp.read()
- finally:
- fp.close()
- container = MIMEBase('multipart', 'mixed', boundary='BOUNDARY')
- image = MIMEImage(data, name='dingusfish.gif')
- image.add_header('content-disposition', 'attachment',
- filename='dingusfish.gif')
- intro = MIMEText('''\
- Hi there,
- This is the dingus fish.
- ''')
- container.attach(intro)
- container.attach(image)
- container['From'] = 'Barry <barry@digicool.com>'
- container['To'] = 'Dingus Lovers <cravindogs@cravindogs.com>'
- container['Subject'] = 'Here is your dingus fish'
- now = 987809702.54848599
- timetuple = time.localtime(now)
- if timetuple[-1] == 0:
- tzsecs = time.timezone
- else:
- tzsecs = time.altzone
- if tzsecs > 0:
- sign = '-'
- else:
- sign = '+'
- tzoffset = ' %s%04d' % (sign, tzsecs // 36)
- container['Date'] = time.strftime(
- '%a, %d %b %Y %H:%M:%S',
- time.localtime(now)) + tzoffset
- self._msg = container
- self._im = image
- self._txt = intro
- def test_hierarchy(self):
- # convenience
- eq = self.assertEqual
- unless = self.assertTrue
- raises = self.assertRaises
- # tests
- m = self._msg
- unless(m.is_multipart())
- eq(m.get_content_type(), 'multipart/mixed')
- eq(len(m.get_payload()), 2)
- raises(IndexError, m.get_payload, 2)
- m0 = m.get_payload(0)
- m1 = m.get_payload(1)
- unless(m0 is self._txt)
- unless(m1 is self._im)
- eq(m.get_payload(), [m0, m1])
- unless(not m0.is_multipart())
- unless(not m1.is_multipart())
- def test_empty_multipart_idempotent(self):
- text = """\
- Content-Type: multipart/mixed; boundary="BOUNDARY"
- MIME-Version: 1.0
- Subject: A subject
- To: aperson@dom.ain
- From: bperson@dom.ain
- --BOUNDARY
- --BOUNDARY--
- """
- msg = Parser().parsestr(text)
- self.ndiffAssertEqual(text, msg.as_string())
- def test_no_parts_in_a_multipart_with_none_epilogue(self):
- outer = MIMEBase('multipart', 'mixed')
- outer['Subject'] = 'A subject'
- outer['To'] = 'aperson@dom.ain'
- outer['From'] = 'bperson@dom.ain'
- outer.set_boundary('BOUNDARY')
- self.ndiffAssertEqual(outer.as_string(), '''\
- Content-Type: multipart/mixed; boundary="BOUNDARY"
- MIME-Version: 1.0
- Subject: A subject
- To: aperson@dom.ain
- From: bperson@dom.ain
- --BOUNDARY
- --BOUNDARY--''')
- def test_no_parts_in_a_multipart_with_empty_epilogue(self):
- outer = MIMEBase('multipart', 'mixed')
- outer['Subject'] = 'A subject'
- outer['To'] = 'aperson@dom.ain'
- outer['From'] = 'bperson@dom.ain'
- outer.preamble = ''
- outer.epilogue = ''
- outer.set_boundary('BOUNDARY')
- self.ndiffAssertEqual(outer.as_string(), '''\
- Content-Type: multipart/mixed; boundary="BOUNDARY"
- MIME-Version: 1.0
- Subject: A subject
- To: aperson@dom.ain
- From: bperson@dom.ain
- --BOUNDARY
- --BOUNDARY--
- ''')
- def test_one_part_in_a_multipart(self):
- eq = self.ndiffAssertEqual
- outer = MIMEBase('multipart', 'mixed')
- outer['Subject'] = 'A subject'
- outer['To'] = 'aperson@dom.ain'
- outer['From'] = 'bperson@dom.ain'
- outer.set_boundary('BOUNDARY')
- msg = MIMEText('hello world')
- outer.attach(msg)
- eq(outer.as_string(), '''\
- Content-Type: multipart/mixed; boundary="BOUNDARY"
- MIME-Version: 1.0
- Subject: A subject
- To: aperson@dom.ain
- From: bperson@dom.ain
- --BOUNDARY
- Content-Type: text/plain; charset="us-ascii"
- MIME-Version: 1.0
- Content-Transfer-Encoding: 7bit
- hello world
- --BOUNDARY--''')
- def test_seq_parts_in_a_multipart_with_empty_preamble(self):
- eq = self.ndiffAssertEqual
- outer = MIMEBase('multipart', 'mixed')
- outer['Subject'] = 'A subject'
- outer['To'] = 'aperson@dom.ain'
- outer['From'] = 'bperson@dom.ain'
- outer.preamble = ''
- msg = MIMEText('hello world')
- outer.attach(msg)
- outer.set_boundary('BOUNDARY')
- eq(outer.as_string(), '''\
- Content-Type: multipart/mixed; boundary="BOUNDARY"
- MIME-Version: 1.0
- Subject: A subject
- To: aperson@dom.ain
- From: bperson@dom.ain
- --BOUNDARY
- Content-Type: text/plain; charset="us-ascii"
- MIME-Version: 1.0
- Content-Transfer-Encoding: 7bit
- hello world
- --BOUNDARY--''')
- def test_seq_parts_in_a_multipart_with_none_preamble(self):
- eq = self.ndiffAssertEqual
- outer = MIMEBase('multipart', 'mixed')
- outer['Subject'] = 'A subject'
- outer['To'] = 'aperson@dom.ain'
- outer['From'] = 'bperson@dom.ain'
- outer.preamble = None
- msg = MIMEText('hello world')
- outer.attach(msg)
- outer.set_boundary('BOUNDARY')
- eq(outer.as_string(), '''\
- Content-Type: multipart/mixed; …
Large files files are truncated, but you can click here to view the full file