test_email.py

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

PY
1,770
字号
        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>,\t"Someone Test #B" <someone@umich.edu>,\t"Someone Test #C" <someone@eecs.umich.edu>,\t"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 -0700Received-2: 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""")    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-1'] = Header(h, header_name='Received-1',                                   continuation_ws='\t')        msg['Received-2'] = h        self.assertEqual(msg.as_string(), """\Received-1: <15975.17901.207240.414604@sgigritzmann1.mathematik.tu-muenchen.de>\t(David Bremner's message of "Thu, 6 Mar 2003 13:58:21 +0100")Received-2: <15975.17901.207240.414604@sgigritzmann1.mathematik.tu-muenchen.de>\t(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\tlocQDQ4zJykFBAXJfWDjAAACYUlEQVR4nF2TQY/jIAyFc6lydlG5x8Nyp1Y69wj1PN2I5gzpFace-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);\tWed, 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\tMicrosoft 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>,\t<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 messageclass 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.orgFrom the desk of A.A.A.:Blah blah blah""")# Test the basic MIMEAudio classclass 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_type(), 'audio/basic')    def test_encoding(self):        payload = self._au.get_payload()        self.assertEqual(base64.decodestring(payload), self._audiodata)    def checkSetMinor(self):        au = MIMEAudio(self._audiodata, 'fish')        self.assertEqual(im.get_type(), 'audio/fish')    def test_custom_encoder(self):        eq = self.assertEqual        def encoder(msg):            orig = msg.get_payload()            msg.set_payload(0)            msg['Content-Transfer-Encoding'] = 'broken64'        au = MIMEAudio(self._audiodata, _encoder=encoder)        eq(au.get_payload(), 0)        eq(au['content-transfer-encoding'], 'broken64')    def test_add_header(self):        eq = self.assertEqual        unless = self.failUnless        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 classclass 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_type(), 'image/gif')    def test_encoding(self):        payload = self._im.get_payload()        self.assertEqual(base64.decodestring(payload), self._imgdata)    def checkSetMinor(self):        im = MIMEImage(self._imgdata, 'fish')        self.assertEqual(im.get_type(), 'image/fish')    def test_custom_encoder(self):        eq = self.assertEqual        def encoder(msg):            orig = msg.get_payload()            msg.set_payload(0)            msg['Content-Transfer-Encoding'] = 'broken64'        im = MIMEImage(self._imgdata, _encoder=encoder)        eq(im.get_payload(), 0)        eq(im['content-transfer-encoding'], 'broken64')    def test_add_header(self):        eq = self.assertEqual        unless = self.failUnless        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 classclass TestMIMEText(unittest.TestCase):    def setUp(self):        self._msg = MIMEText('hello there')    def test_types(self):        eq = self.assertEqual        unless = self.failUnless        eq(self._msg.get_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.failUnless(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"')# Test a more complicated multipart/mixed type messageclass TestMultipartMixed(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

⌨️ 快捷键说明

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