test_email.py

来自「mallet是自然语言处理、机器学习领域的一个开源项目。」· Python 代码 · 共 1,770 行 · 第 1/5 页

PY
1,770
字号
        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.failUnless        raises = self.assertRaises        # tests        m = self._msg        unless(m.is_multipart())        eq(m.get_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_no_parts_in_a_multipart(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')        msg = MIMEText('hello world')        self.assertEqual(outer.as_string(), '''\Content-Type: multipart/mixed; boundary="BOUNDARY"MIME-Version: 1.0Subject: A subjectTo: aperson@dom.ainFrom: 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.preamble = ''        outer.epilogue = ''        outer.set_boundary('BOUNDARY')        msg = MIMEText('hello world')        outer.attach(msg)        eq(outer.as_string(), '''\Content-Type: multipart/mixed; boundary="BOUNDARY"MIME-Version: 1.0Subject: A subjectTo: aperson@dom.ainFrom: bperson@dom.ain--BOUNDARYContent-Type: text/plain; charset="us-ascii"MIME-Version: 1.0Content-Transfer-Encoding: 7bithello world--BOUNDARY--''')    def test_seq_parts_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.preamble = ''        outer.epilogue = ''        msg = MIMEText('hello world')        outer.attach(msg)        outer.set_boundary('BOUNDARY')        eq(outer.as_string(), '''\Content-Type: multipart/mixed; boundary="BOUNDARY"MIME-Version: 1.0Subject: A subjectTo: aperson@dom.ainFrom: bperson@dom.ain--BOUNDARYContent-Type: text/plain; charset="us-ascii"MIME-Version: 1.0Content-Transfer-Encoding: 7bithello world--BOUNDARY--''')# Test some badly formatted messagesclass TestNonConformant(TestEmailBase):    def test_parse_missing_minor_type(self):        eq = self.assertEqual        msg = self._msgobj('msg_14.txt')        eq(msg.get_type(), 'text')        eq(msg.get_main_type(), None)        eq(msg.get_subtype(), None)    def test_bogus_boundary(self):        fp = openfile(findfile('msg_15.txt'))        try:            data = fp.read()        finally:            fp.close()        p = Parser(strict=True)        # Note, under a future non-strict parsing mode, this would parse the        # message into the intended message tree.        self.assertRaises(Errors.BoundaryError, p.parsestr, data)    def test_multipart_no_boundary(self):        fp = openfile(findfile('msg_25.txt'))        try:            self.assertRaises(Errors.BoundaryError,                              email.message_from_file, fp)        finally:            fp.close()    def test_invalid_content_type(self):        eq = self.assertEqual        neq = self.ndiffAssertEqual        msg = Message()        # RFC 2045, $5.2 says invalid yields text/plain        msg['Content-Type'] = 'text'        eq(msg.get_content_maintype(), 'text')        eq(msg.get_content_subtype(), 'plain')        eq(msg.get_content_type(), 'text/plain')        # Clear the old value and try something /really/ invalid        del msg['content-type']        msg['Content-Type'] = 'foo'        eq(msg.get_content_maintype(), 'text')        eq(msg.get_content_subtype(), 'plain')        eq(msg.get_content_type(), 'text/plain')        # Still, make sure that the message is idempotently generated        s = StringIO()        g = Generator(s)        g.flatten(msg)        neq(s.getvalue(), 'Content-Type: foo\n\n')    def test_no_start_boundary(self):        eq = self.ndiffAssertEqual        msg = self._msgobj('msg_31.txt')        eq(msg.get_payload(), """\--BOUNDARYContent-Type: text/plainmessage 1--BOUNDARYContent-Type: text/plainmessage 2--BOUNDARY--""")    def test_no_separating_blank_line(self):        eq = self.ndiffAssertEqual        msg = self._msgobj('msg_35.txt')        eq(msg.as_string(), """\From: aperson@dom.ainTo: bperson@dom.ainSubject: here's something interestingcounter to RFC 2822, there's no separating newline here""")        # strict=True should raise an exception        self.assertRaises(Errors.HeaderParseError,                          self._msgobj, 'msg_35.txt', True)# Test RFC 2047 header encoding and decodingclass TestRFC2047(unittest.TestCase):    def test_iso_8859_1(self):        eq = self.assertEqual        s = '=?iso-8859-1?q?this=20is=20some=20text?='        eq(Utils.decode(s), 'this is some text')        s = '=?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?='        eq(Utils.decode(s), u'Keld J\xf8rn Simonsen')        s = '=?ISO-8859-1?B?SWYgeW91IGNhbiByZWFkIHRoaXMgeW8=?=' \            '=?ISO-8859-2?B?dSB1bmRlcnN0YW5kIHRoZSBleGFtcGxlLg==?='        eq(Utils.decode(s), 'If you can read this you understand the example.')        s = '=?iso-8859-8?b?7eXs+SDv4SDp7Oj08A==?='        eq(Utils.decode(s),           u'\u05dd\u05d5\u05dc\u05e9 \u05df\u05d1 \u05d9\u05dc\u05d8\u05e4\u05e0')        s = '=?iso-8859-1?q?this=20is?= =?iso-8859-1?q?some=20text?='        eq(Utils.decode(s), u'this issome text')        s = '=?iso-8859-1?q?this=20is_?= =?iso-8859-1?q?some=20text?='        eq(Utils.decode(s), u'this is some text')    def test_encode_header(self):        eq = self.assertEqual        s = 'this is some text'        eq(Utils.encode(s), '=?iso-8859-1?q?this=20is=20some=20text?=')        s = 'Keld_J\xf8rn_Simonsen'        eq(Utils.encode(s), '=?iso-8859-1?q?Keld_J=F8rn_Simonsen?=')        s1 = 'If you can read this yo'        s2 = 'u understand the example.'        eq(Utils.encode(s1, encoding='b'),           '=?iso-8859-1?b?SWYgeW91IGNhbiByZWFkIHRoaXMgeW8=?=')        eq(Utils.encode(s2, charset='iso-8859-2', encoding='b'),           '=?iso-8859-2?b?dSB1bmRlcnN0YW5kIHRoZSBleGFtcGxlLg==?=')    def test_rfc2047_multiline(self):        eq = self.assertEqual        s = """Re: =?mac-iceland?q?r=8Aksm=9Arg=8Cs?= baz foo bar =?mac-iceland?q?r=8Aksm=9Arg=8Cs?="""        dh = decode_header(s)        eq(dh, [            ('Re:', None),            ('r\x8aksm\x9arg\x8cs', 'mac-iceland'),            ('baz foo bar', None),            ('r\x8aksm\x9arg\x8cs', 'mac-iceland')])        eq(str(make_header(dh)),           """Re: =?mac-iceland?q?r=8Aksm=9Arg=8Cs?= baz foo bar =?mac-iceland?q?r=8Aksm=9Arg=8Cs?=""")    def test_whitespace_eater_unicode(self):        eq = self.assertEqual        s = '=?ISO-8859-1?Q?Andr=E9?= Pirard <pirard@dom.ain>'        dh = decode_header(s)        eq(dh, [('Andr\xe9', 'iso-8859-1'), ('Pirard <pirard@dom.ain>', None)])        # Python 2.1's unicode() builtin doesn't call the object's        # __unicode__() method.  Use the following alternative instead.        #hu = unicode(make_header(dh)).encode('latin-1')        hu = make_header(dh).__unicode__().encode('latin-1')        eq(hu, 'Andr\xe9 Pirard <pirard@dom.ain>')# Test the MIMEMessage classclass TestMIMEMessage(TestEmailBase):    def setUp(self):        fp = openfile('msg_11.txt')        try:            self._text = fp.read()        finally:            fp.close()    def test_type_error(self):        self.assertRaises(TypeError, MIMEMessage, 'a plain string')    def test_valid_argument(self):        eq = self.assertEqual        unless = self.failUnless        subject = 'A sub-message'        m = Message()        m['Subject'] = subject        r = MIMEMessage(m)        eq(r.get_type(), 'message/rfc822')        payload = r.get_payload()        unless(type(payload), ListType)        eq(len(payload), 1)        subpart = payload[0]        unless(subpart is m)        eq(subpart['subject'], subject)    def test_bad_multipart(self):        eq = self.assertEqual        msg1 = Message()        msg1['Subject'] = 'subpart 1'        msg2 = Message()        msg2['Subject'] = 'subpart 2'        r = MIMEMessage(msg1)        self.assertRaises(Errors.MultipartConversionError, r.attach, msg2)    def test_generate(self):        # First craft the message to be encapsulated        m = Message()        m['Subject'] = 'An enclosed message'        m.set_payload('Here is the body of the message.\n')        r = MIMEMessage(m)        r['Subject'] = 'The enclosing message'        s = StringIO()        g = Generator(s)        g.flatten(r)        self.assertEqual(s.getvalue(), """\Content-Type: message/rfc822MIME-Version: 1.0Subject: The enclosing messageSubject: An enclosed messageHere is the body of the message.""")    def test_parse_message_rfc822(self):        eq = self.assertEqual        unless = self.failUnless        msg = self._msgobj('msg_11.txt')        eq(msg.get_type(), 'message/rfc822')        payload = msg.get_payload()        unless(isinstance(payload, ListType))        eq(len(payload), 1)        submsg = payload[0]        self.failUnless(isinstance(submsg, Message))        eq(submsg['subject'], 'An enclosed message')        eq(submsg.get_payload(), 'Here is the body of the message.\n')    def test_dsn(self):        eq = self.assertEqual        unless = self.failUnless        # msg 16 is a Delivery Status Notification, see RFC 1894        msg = self._msgobj('msg_16.txt')        eq(msg.get_type(), 'multipart/report')        unless(msg.is_multipart())        eq(len(msg.get_payload()), 3)        # Subpart 1 is a text/plain, human readable section        subpart = msg.get_payload(0)        eq(subpart.get_type(), 'text/plain')        eq(subpart.get_payload(), """\This report relates to a message you sent with the following header fields:  Message-id: <002001c144a6$8752e060$56104586@oxy.edu>  Date: Sun, 23 Sep 2001 20:10:55 -0700  From: "Ian T. Henry" <henryi@oxy.edu>  To: SoCal Raves <scr@socal-raves.org>  Subject: [scr] yeah for Ians!!Your message cannot be delivered to the following recipients:  Recipient address: jangel1@cougar.noc.ucla.edu  Reason: recipient reached disk quota""")        # Subpart 2 contains the machine parsable DSN information.  It        # consists of two blocks of headers, represented by two nested Message        # objects.        subpart = msg.get_payload(1)        eq(subpart.get_type(), 'message/delivery-status')        eq(len(subpart.get_payload()), 2)        # message/delivery-status should treat each block as a bunch of

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?