Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
send_email: Allow close() to work on persistent SMTP backend.
Alex Vandivere0f5981bcfef
diff --git a/zerver/tests/test_send_email.py b/zerver/tests/test_send_email.pyindex 08302a447c4..de3ecde4a7a 100644--- a/zerver/tests/test_send_email.py+++ b/zerver/tests/test_send_email.py@@ -151,11 +151,6 @@ class TestSendEmail(ZulipTestCase):self.assertEqual(_open_call.call_count, 1)self.assertEqual(backend.connection.noop.call_count, 0)self.assertEqual(backend.opened_at, timezone_now())- # Test that close() is a no-op and does not drop the connection.- connection_before = backend.connection- backend.close()- self.assertEqual(backend.connection, connection_before)- self.assertIsNotNone(backend.connection)close_call.reset_mock()_open_call.reset_mock()@@ -249,6 +244,23 @@ class TestSendEmail(ZulipTestCase):self.assertEqual(old_connection_mock.noop.call_count, 0)self.assertEqual(_open_call.call_count, 2)+ def test_open_returns_false_for_new_connection(self) -> None:+ """open() returns False even for new connections, which+ prevents Django's send_messages from auto-closing the+ persistent connection."""+ backend = PersistentSMTPEmailBackend()+ with mock.patch.object(EmailBackend, "open", return_value=True):+ result = backend.open()+ self.assertIs(result, False)++ def test_close_clears_connection(self) -> None:+ """close() actually closes the connection, enabling error+ recovery in send_immediate_email."""+ backend = PersistentSMTPEmailBackend()+ backend.connection = mock.MagicMock(spec=SMTP)+ backend.close()+ self.assertIsNone(backend.connection)+def test_send_email_exceptions(self) -> None:hamlet = self.example_user("hamlet")from_name = FromAddress.security_email_from_name(language="en")diff --git a/zproject/email_backends.py b/zproject/email_backends.pyindex daaec6bf3cd..91d55f8a3c9 100644--- a/zproject/email_backends.py+++ b/zproject/email_backends.py@@ -124,10 +124,12 @@ class PersistentSMTPEmailBackend(EmailBackend):return is_opened@override- def open(self, **kwargs: Any) -> bool | None:+ def open(self, **kwargs: Any) -> bool:is_opened = self._open(**kwargs)if is_opened:- return True+ # Return False (not True) so that Django's send_messages+ # does not auto-close the connection after sending.+ return Falsestatus = Nonetime_elapsed = (timezone_now() - self.opened_at).total_seconds() / 60@@ -146,15 +148,5 @@ class PersistentSMTPEmailBackend(EmailBackend):# Close and connect again.super().close()self._open()- # We return false here as Django will then have- # to leave the connection alive for next entries.- return False- # The connection was already open, the noop succeeded.return False-- @override- def close(self) -> None:- # We override close to a no-op so that Django's send_messages- # does not close the connection after sending a batch of emails.- pass