Create unittest for new mail_utils feature
authorChristian Herdtweck <christian.herdtweck@intra2net.com>
Thu, 24 Jan 2019 15:50:39 +0000 (16:50 +0100)
committerChristian Herdtweck <christian.herdtweck@intra2net.com>
Thu, 7 Feb 2019 15:50:39 +0000 (16:50 +0100)
test/test_mail_utils.py

index 7127780..fb9746e 100644 (file)
 
 import unittest
 import os
+from os.path import isdir, join
+from tempfile import mkdtemp
+from shutil import rmtree
+from email.errors import MultipartInvariantViolationDefect
 
 from src import mail_utils
 
 
-class MailUtilsTest(unittest.TestCase):
+class MailUtilsValidatorTest(unittest.TestCase):
+    """Tests methods of :py:class:`mail_utils.MailValidator`."""
 
     def setUp(self):
         os.mkdir("srcdir")
@@ -226,3 +231,119 @@ class MailUtilsTest(unittest.TestCase):
         finally:
             os.unlink("trgdir/.123")
             os.unlink("trgdir/.5267")
+
+
+EMAIL_TEXT = r"""Return-Path: <autotest-sender@vm1.net.lan>
+Received: from vm1.net.lan ([unix socket])
+         by vm1.net.lan with LMTPA;
+         Thu, 24 Jan 2019 13:44:21 +0100
+X-Sieve: CMU Sieve 2.4
+Received: from localhost (vm1.net.lan [127.0.0.1])
+        by localhost (Postfix) with ESMTP id 94F031F45D
+        for <autotest-recipient@vm1.net.lan>;
+        Thu, 24 Jan 2019 13:44:21 +0100 (CET)
+X-Spam-Status: No, score=-202 required=5 tests=[ALL_INTERNAL=-200,
+        ALL_TRUSTED=-2] autolearn=Intra2net
+X-Spam-Level: 0
+Received: from vm1.net.lan (vm1.net.lan [127.0.0.1])
+        by vm1.net.lan (Postfix) with ESMTP id 310601F4BF
+        for <autotest-recipient@vm1.net.lan>;
+        Thu, 24 Jan 2019 13:43:43 +0100 (CET)
+Content-Type: multipart/mixed; boundary="===============1907573780=="
+MIME-Version: 1.0
+From: autotest-sender@vm1.net.lan
+To: autotest-recipient@vm1.net.lan
+Subject: Emailfilter test 7b25f7a3-115: b'2018\xe5\xb9\xb4\xe5\xba\xa6\xe5\x85
+        \xac\xe5\xbc\x80\xe8\xaf\xbe\xe8\xae\xa1\xe5\x88\x92\xe8\xa1\xa8.xlsx'
+Date: Thu, 24 Jan 2019 13:43:43 +0100
+X-Autotest-Creator: pyi2ncommon.mail_utils.MailValidator.send_email_with_files
+X-Autotest-Signature: Emailfilter-test-7b25f7a3-115
+Message-Id: <20190124124343.310601F4BF@vm1.net.lan>
+
+This is a multi-part message in MIME format.
+
+--===============1907573780==
+Content-Type: text/plain; charset="utf-8"
+MIME-Version: 1.0
+Content-Transfer-Encoding: base64
+
+VGhpcyBpcyBhbiBhdXRvZ2VuZXJhdGVkIGVtYWlsLgo=
+
+--===============1907573780==
+Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
+MIME-Version: 1.0
+Content-Transfer-Encoding: base64
+Content-Disposition: attachment; filename*=utf-8''2018%E5%B9%B4%E5%BA%A6%E5%85%AC%E5%BC%80%E8%AF%BE%E8%AE%A1%E5%88%92%E8%A1%A8.xlsx
+
+UEsDBBQABgAIAAAAIQBztLdlogEAAOsGAAATANMBW0NvbnRlbnRfVHlwZXNdLnhtbCCizwEooAAC
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+...
+LnhtbFBLAQItABQABgAIAAAAIQCjnmWmlgEAABsDAAAQAAAAAAAAAAAAAAAAAKgcAgBkb2NQcm9w
+cy9hcHAueG1sUEsBAi0AFAAGAAgAAAAhAKGUsWUFAQAAfwEAABMAAAAAAAAAAAAAAAAAdB8CAGRv
+Y1Byb3BzL2N1c3RvbS54bWxQSwUGAAAAABcAFwAdBgAAsiECAAAA
+
+--===============1907573780==--
+"""
+
+ENVELOPE_START = "EHLO localhost\n" \
+                 "MAIL FROM:<autotest-sender@vm1.net.lan> BODY=7BIT\n" \
+                 "RCPT TO:<autotest-recipient@vm1.net.lan> " \
+                 "ORCPT=rfc822;autotest-recipient@vm1.net.lan\n" \
+                 "XARCHIVETIME time=1548333902\n" \
+                 "DATA\n"
+
+ENVELOPE_END = '.\n'
+
+ATTACHMENT_FILENAME = '2018年度公开课计划表.xlsx'
+
+
+
+class MailUtilsFunctionTest(unittest.TestCase):
+    """Tests free functions in module :py:mod:`mail_utils`."""
+
+    def setUp(self):
+        """Called at start of test; create a temp dir."""
+        self.temp_dir = mkdtemp(prefix='test_mail_utils_')
+
+    def create_mail(self):
+        """Create a mail file typical for cyrus inbox."""
+        mail_file = join(self.temp_dir, '83.')
+        with open(mail_file, 'x') as writer:
+            writer.write(EMAIL_TEXT)
+        return mail_file
+
+    def create_bsmtp(self):
+        """Create a bsmtp mail file, typical for quarantine."""
+        mail_file = join(self.temp_dir,
+                         'banned-autotest-recipient@vm1.net.lan-310601F4BF')
+        with open(mail_file, 'x') as writer:
+            writer.write(ENVELOPE_START)
+            writer.write(EMAIL_TEXT)
+            writer.write(ENVELOPE_END)
+        return mail_file
+
+    def tearDown(self):
+        """Called at end of test; remove temp dir."""
+        if isdir(self.temp_dir):
+            rmtree(self.temp_dir)
+
+    def test_get_filenames(self):
+        """Test `attachment_filenames` option of `parse_mail_file`."""
+        filename = self.create_mail()
+        msg, attachment_filenames = \
+            mail_utils.parse_mail_file(filename, attachment_filenames=True)
+        if len(msg.defects) == 1:
+            # msg ContentType is multipart/mixed but with only headers,
+            # msg.is_multipart is False.
+            self.assertIsInstance(msg.defects[0],
+                                  MultipartInvariantViolationDefect)
+        else:
+            self.assertListEqual(msg.defects, [])
+        self.assertIsNone(msg.preamble)
+        self.assertIsNone(msg.epilogue)
+        self.assertIn(ATTACHMENT_FILENAME, attachment_filenames)
+        self.assertEqual(len(attachment_filenames), 1)
+        self.assertIn('Subject', msg)
+        self.assertTrue(msg['Subject'].startswith(
+            r"Emailfilter test 7b25f7a3-115: b'2018\xe5\xb9\xb4\xe5\xba"))