# Path: modoboa_amavis/sql_email.py
# class SQLemail(Email):
# 
#     """The SQL version of the Email class."""
# 
#     def __init__(self, *args, **kwargs):
#         super().__init__(*args, **kwargs)
#         self.qtype = ""
#         self.qreason = ""
# 
#         qreason = self.msg["X-Amavis-Alert"]
#         if qreason:
#             if "," in qreason:
#                 self.qtype, qreason = qreason.split(",", 1)
#             elif qreason.startswith("BAD HEADER SECTION "):
#                 # Workaround for amavis <= 2.8.0 :p
#                 self.qtype = "BAD HEADER SECTION"
#                 qreason = qreason[19:]
# 
#             qreason = " ".join([x.strip() for x in qreason.splitlines()])
#             self.qreason = qreason
# 
#     def _fetch_message(self):
#         return SQLconnector().get_mail_content(self.mailid)
# 
#     @property
#     def body(self):
#         if self._body is None:
#             super(SQLemail, self).body
#             self._body = fix_utf8_encoding(self._body)
# 
#         # if there's no plain text version available attempt to make one by
#         # sanitising the html version. The output isn't always pretty but it
#         # is readable, better than a blank screen and helps the user decide
#         # if the message is spam or ham.
#         if self.dformat == "plain" and not self.contents["plain"] \
#                 and self.contents["html"]:
#             h = HTML2Text()
#             h.ignore_tables = True
#             h.images_to_alt = True
#             mail_text = h.handle(self.contents["html"])
#             self.contents["plain"] = self._post_process_plain(
#                 smart_text(mail_text))
#             self._body = self.viewmail_plain()
#             self._body = fix_utf8_encoding(self._body)
# 
#         return self._body
# 
#     def render_headers(self, **kwargs):
#         context = {
#             "qtype": self.qtype,
#             "qreason": self.qreason,
#             "headers": self.headers,
#         }
#         return render_to_string("modoboa_amavis/mailheaders.html", context)


import os
from django.test import TestCase
from django.utils.encoding import smart_bytes, smart_text
from ..sql_email import SQLemail

    def _get_expected_output(self, message_id, **kwargs):
        ext = kwargs["dformat"] if "dformat" in kwargs else "plain"
        ext += "_links" if "links" in kwargs and kwargs["links"] else "_nolinks"
        message_path = os.path.join(SAMPLES_DIR,
                                    "%s-output-%s.txt" % (message_id, ext))
        assert os.path.isfile(message_path), "%s does not exist." % message_path

        with open(message_path, "rb") as fp:
            # output should always be unicode (py2) or str (py3)
            mail_text = smart_text(fp.read())

        return mail_text

    def _test_email(self, message_id, **kwargs):
        """Boiler plate code for testing e-mails."""
        expected_output = self._get_expected_output(message_id, **kwargs)
        output = EmailTestImplementation(message_id, **kwargs).body
        self.assertEqual(output, expected_output)

    def test_amavis_aleart_header(self):
        email = EmailTestImplementation("quarantined")
        self.assertEqual(email.qtype, "BAD HEADER SECTION")
        self.assertEqual(email.qreason,
                         "Non-encoded non-ASCII data (and not UTF-8) (char 85 "
                         "hex): Subject: I think I saw you in my dreams\\x{85}")

    def test_email_multipart_with_no_text(self):
        """for a multipart message without a text/plain part convert the
           text/html to text/plain"""

# Path: modoboa_amavis/sql_email.py
# class SQLemail(Email):
# 
#     """The SQL version of the Email class."""
# 
#     def __init__(self, *args, **kwargs):
#         super().__init__(*args, **kwargs)
#         self.qtype = ""
#         self.qreason = ""
# 
#         qreason = self.msg["X-Amavis-Alert"]
#         if qreason:
#             if "," in qreason:
#                 self.qtype, qreason = qreason.split(",", 1)
#             elif qreason.startswith("BAD HEADER SECTION "):
#                 # Workaround for amavis <= 2.8.0 :p
#                 self.qtype = "BAD HEADER SECTION"
#                 qreason = qreason[19:]
# 
#             qreason = " ".join([x.strip() for x in qreason.splitlines()])
#             self.qreason = qreason
# 
#     def _fetch_message(self):
#         return SQLconnector().get_mail_content(self.mailid)
# 
#     @property
#     def body(self):
#         if self._body is None:
#             super(SQLemail, self).body
#             self._body = fix_utf8_encoding(self._body)
# 
#         # if there's no plain text version available attempt to make one by
#         # sanitising the html version. The output isn't always pretty but it
#         # is readable, better than a blank screen and helps the user decide
#         # if the message is spam or ham.
#         if self.dformat == "plain" and not self.contents["plain"] \
#                 and self.contents["html"]:
#             h = HTML2Text()
#             h.ignore_tables = True
#             h.images_to_alt = True
#             mail_text = h.handle(self.contents["html"])
#             self.contents["plain"] = self._post_process_plain(
#                 smart_text(mail_text))
#             self._body = self.viewmail_plain()
#             self._body = fix_utf8_encoding(self._body)
# 
#         return self._body
# 
#     def render_headers(self, **kwargs):
#         context = {
#             "qtype": self.qtype,
#             "qreason": self.qreason,
#             "headers": self.headers,
#         }
#         return render_to_string("modoboa_amavis/mailheaders.html", context)


# Path: modoboa_amavis/tests/test_sql_email.py
import os
from django.test import TestCase
from django.utils.encoding import smart_bytes, smart_text
from ..sql_email import SQLemail


    def _get_expected_output(self, message_id, **kwargs):
        ext = kwargs["dformat"] if "dformat" in kwargs else "plain"
        ext += "_links" if "links" in kwargs and kwargs["links"] else "_nolinks"
        message_path = os.path.join(SAMPLES_DIR,
                                    "%s-output-%s.txt" % (message_id, ext))
        assert os.path.isfile(message_path), "%s does not exist." % message_path

        with open(message_path, "rb") as fp:
            # output should always be unicode (py2) or str (py3)
            mail_text = smart_text(fp.read())

        return mail_text

    def _test_email(self, message_id, **kwargs):
        """Boiler plate code for testing e-mails."""
        expected_output = self._get_expected_output(message_id, **kwargs)
        output = EmailTestImplementation(message_id, **kwargs).body
        self.assertEqual(output, expected_output)

    def test_amavis_aleart_header(self):
        email = EmailTestImplementation("quarantined")
        self.assertEqual(email.qtype, "BAD HEADER SECTION")
        self.assertEqual(email.qreason,
                         "Non-encoded non-ASCII data (and not UTF-8) (char 85 "
                         "hex): Subject: I think I saw you in my dreams\\x{85}")

    def test_email_multipart_with_no_text(self):
        """for a multipart message without a text/plain part convert the
           text/html to text/plain"""

        self._test_email("quarantined")