From 338ec052b4824d3f621629b3bf0f344c7a43c3dc Mon Sep 17 00:00:00 2001 From: Natalia <124304+nessita@users.noreply.github.com> Date: Mon, 8 Apr 2024 12:32:52 -0300 Subject: [PATCH] Refs #35361 -- Added test for Email line length checks when dealing with surrogate pairs. Refs #33173, #34118 and #34900. --- tests/mail/tests.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/tests/mail/tests.py b/tests/mail/tests.py index dd6b72ab49..9e55398d60 100644 --- a/tests/mail/tests.py +++ b/tests/mail/tests.py @@ -92,6 +92,37 @@ class MailTests(HeadersCheckMixin, SimpleTestCase): self.assertEqual(message["From"], "from@example.com") self.assertEqual(message["To"], "to@example.com") + @mock.patch("django.core.mail.message.MIMEText.set_payload") + def test_nonascii_as_string_with_ascii_charset(self, mock_set_payload): + """Line length check should encode the payload supporting `surrogateescape`. + + Following https://github.com/python/cpython/issues/76511, newer + versions of Python (3.11.9, 3.12.3 and 3.13) ensure that a message's + payload is encoded with the provided charset and `surrogateescape` is + used as the error handling strategy. + + This test is heavily based on the test from the fix for the bug above. + Line length checks in SafeMIMEText's set_payload should also use the + same error handling strategy to avoid errors such as: + + UnicodeEncodeError: 'utf-8' codec can't encode <...>: surrogates not allowed + + """ + + def simplified_set_payload(instance, payload, charset): + instance._payload = payload + + mock_set_payload.side_effect = simplified_set_payload + + text = ( + "Text heavily based in Python's text for non-ascii messages: Föö bär" + ).encode("iso-8859-1") + body = text.decode("ascii", errors="surrogateescape") + email = EmailMessage("Subject", body, "from@example.com", ["to@example.com"]) + message = email.message() + mock_set_payload.assert_called_once() + self.assertEqual(message.get_payload(decode=True), text) + def test_multiple_recipients(self): email = EmailMessage( "Subject",