Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

54.0 KB
Raw Blame
"""
Unit tests for mail send tasks.

This module tests the mail sending functionality including:
- Email template rendering with internationalization
- SMTP integration with various configurations
- Retry logic for failed email sends
- Error handling and logging
"""

import logging
import smtplib
from collections.abc import Callable, Mapping, Sequence
from email.message import Message
from unittest.mock import ANY, MagicMock, patch

import pytest
from python_http_client.exceptions import ForbiddenError, UnauthorizedError

from configs.feature import TemplateMode
from extensions.ext_mail import Mail
from libs.email_i18n import EmailI18nConfig, EmailI18nService, EmailLanguage, EmailTemplate, EmailType
from libs.sendgrid import SendGridClient
from libs.smtp import SMTPClient
from services.entities.feature_entities import BrandingModel
from tasks.mail_inner_task import _render_template_with_strategy, send_inner_email_task
from tasks.mail_register_task import (
    send_email_register_mail_task,
    send_email_register_mail_task_when_account_exist,
)
from tasks.mail_reset_password_task import (
    send_reset_password_mail_task,
    send_reset_password_mail_task_when_account_not_exist,
)


class TestEmailTemplateRendering:
    """Test email template rendering with various scenarios."""

    def test_render_template_unsafe_mode(self, config_overrides: Callable[..., None]) -> None:
        """Test template rendering in unsafe mode with Jinja2 syntax."""
        # Arrange
        body = "Hello {{ name }}, your code is {{ code }}"
        substitutions = {"name": "John", "code": "123456"}

        # Act
        config_overrides(MAIL_TEMPLATING_MODE=TemplateMode.UNSAFE)
        result = _render_template_with_strategy(body, substitutions)

        # Assert
        assert result == "Hello John, your code is 123456"

    def test_render_template_sandbox_mode(self, config_overrides: Callable[..., None]) -> None:
        """Test template rendering in sandbox mode for security."""
        # Arrange
        body = "Hello {{ name }}, your code is {{ code }}"
        substitutions = {"name": "Alice", "code": "654321"}

        # Act
        config_overrides(MAIL_TEMPLATING_MODE=TemplateMode.SANDBOX, MAIL_TEMPLATING_TIMEOUT=3)
        result = _render_template_with_strategy(body, substitutions)

        # Assert
        assert result == "Hello Alice, your code is 654321"

    def test_render_template_disabled_mode(self, config_overrides: Callable[..., None]) -> None:
        """Test template rendering when templating is disabled."""
        # Arrange
        body = "Hello {{ name }}, your code is {{ code }}"
        substitutions = {"name": "Bob", "code": "999999"}

        # Act
        config_overrides(MAIL_TEMPLATING_MODE=TemplateMode.DISABLED)
        result = _render_template_with_strategy(body, substitutions)

        # Assert - should return body unchanged
        assert result == "Hello {{ name }}, your code is {{ code }}"

    def test_render_template_sandbox_timeout(self, config_overrides: Callable[..., None]) -> None:
        """Test that sandbox mode respects timeout settings and range limits."""
        # Arrange - template with very large range (exceeds sandbox MAX_RANGE)
        body = "{% for i in range(1000000) %}{{ i }}{% endfor %}"
        substitutions: dict[str, str] = {}

        # Act & Assert - sandbox blocks ranges larger than MAX_RANGE (100000)
        config_overrides(MAIL_TEMPLATING_MODE=TemplateMode.SANDBOX, MAIL_TEMPLATING_TIMEOUT=1)
        with pytest.raises((TimeoutError, RuntimeError, OverflowError)):
            _render_template_with_strategy(body, substitutions)

    def test_render_template_invalid_mode(self, config_overrides: Callable[..., None]) -> None:
        """Test that invalid template mode raises ValueError."""
        # Arrange
        body = "Test"
        substitutions: dict[str, str] = {}

        # Act & Assert
        config_overrides(MAIL_TEMPLATING_MODE="invalid_mode")
        with pytest.raises(ValueError, match="Unsupported mail templating mode"):
            _render_template_with_strategy(body, substitutions)

    def test_render_template_with_special_characters(self, config_overrides: Callable[..., None]) -> None:
        """Test template rendering with special characters and HTML."""
        # Arrange
        body = "<h1>Hello {{ name }}</h1><p>Code: {{ code }}</p>"
        substitutions = {"name": "Test<User>", "code": "ABC&123"}

        # Act
        config_overrides(MAIL_TEMPLATING_MODE=TemplateMode.SANDBOX)
        result = _render_template_with_strategy(body, substitutions)

        # Assert
        assert "Test<User>" in result
        assert "ABC&123" in result

    def test_render_template_missing_variable_sandbox(self, config_overrides: Callable[..., None]) -> None:
        """Test sandbox mode handles missing variables gracefully."""
        # Arrange
        body = "Hello {{ name }}, your code is {{ missing_var }}"
        substitutions = {"name": "John"}

        # Act - sandbox mode renders undefined variables as empty strings by default
        config_overrides(MAIL_TEMPLATING_MODE=TemplateMode.SANDBOX)
        result = _render_template_with_strategy(body, substitutions)

        # Assert - undefined variable is rendered as empty string
        assert "Hello John" in result
        assert "missing_var" not in result  # Variable name should not appear in output


class TestSMTPIntegration:
    """Test SMTP client integration with various configurations."""

    @patch("libs.smtp.smtplib.SMTP_SSL")
    def test_smtp_send_with_tls_ssl(self, mock_smtp_ssl: MagicMock) -> None:
        """Test SMTP send with TLS using SMTP_SSL."""
        # Arrange
        mock_server = MagicMock()
        mock_smtp_ssl.return_value = mock_server

        client = SMTPClient(
            server="smtp.example.com",
            port=465,
            username="[email protected]",
            password="password123",
            _from="[email protected]",
            use_tls=True,
            opportunistic_tls=False,
        )

        mail_data = {"to": "[email protected]", "subject": "Test Subject", "html": "<p>Test Content</p>"}

        # Act
        client.send(mail_data)

        # Assert
        mock_smtp_ssl.assert_called_once_with("smtp.example.com", 465, timeout=10, local_hostname=ANY)
        mock_server.login.assert_called_once_with("[email protected]", "password123")
        mock_server.sendmail.assert_called_once()
        mock_server.quit.assert_called_once()

    @patch("libs.smtp.smtplib.SMTP")
    def test_smtp_send_with_opportunistic_tls(self, mock_smtp: MagicMock) -> None:
        """Test SMTP send with opportunistic TLS (STARTTLS)."""
        # Arrange
        mock_server = MagicMock()
        mock_smtp.return_value = mock_server

        client = SMTPClient(
            server="smtp.example.com",
            port=587,
            username="[email protected]",
            password="password123",
            _from="[email protected]",
            use_tls=True,
            opportunistic_tls=True,
        )

        mail_data = {"to": "[email protected]", "subject": "Test", "html": "<p>Content</p>"}

        # Act
        client.send(mail_data)

        # Assert
        mock_smtp.assert_called_once_with("smtp.example.com", 587, timeout=10, local_hostname=ANY)
        mock_server.ehlo.assert_called()
        mock_server.starttls.assert_called_once()
        assert mock_server.ehlo.call_count == 2  # Before and after STARTTLS
        mock_server.sendmail.assert_called_once()
        mock_server.quit.assert_called_once()

    @patch("libs.smtp.smtplib.SMTP")
    def test_smtp_send_without_tls(self, mock_smtp: MagicMock) -> None:
        """Test SMTP send without TLS encryption."""
        # Arrange
        mock_server = MagicMock()
        mock_smtp.return_value = mock_server

        client = SMTPClient(
            server="smtp.example.com",
            port=25,
            username="[email protected]",
            password="password123",
            _from="[email protected]",
            use_tls=False,
            opportunistic_tls=False,
        )

        mail_data = {"to": "[email protected]", "subject": "Test", "html": "<p>Content</p>"}

        # Act
        client.send(mail_data)

        # Assert
        mock_smtp.assert_called_once_with("smtp.example.com", 25, timeout=10, local_hostname=ANY)
        mock_server.login.assert_called_once()
        mock_server.sendmail.assert_called_once()
        mock_server.quit.assert_called_once()

    @patch("libs.smtp.smtplib.SMTP")
    def test_smtp_send_without_authentication(self, mock_smtp: MagicMock) -> None:
        """Test SMTP send without authentication (empty credentials)."""
        # Arrange
        mock_server = MagicMock()
        mock_smtp.return_value = mock_server

        client = SMTPClient(
            server="smtp.example.com",
            port=25,
            username="",
            password="",
            _from="[email protected]",
            use_tls=False,
            opportunistic_tls=False,
        )

        mail_data = {"to": "[email protected]", "subject": "Test", "html": "<p>Content</p>"}

        # Act
        client.send(mail_data)

        # Assert
        mock_server.login.assert_not_called()  # Should skip login with empty credentials
        mock_server.sendmail.assert_called_once()
        mock_server.quit.assert_called_once()

    @patch("libs.smtp.smtplib.SMTP_SSL")
    def test_smtp_send_authentication_failure(self, mock_smtp_ssl: MagicMock) -> None:
        """Test SMTP send handles authentication failure."""
        # Arrange
        mock_server = MagicMock()
        mock_smtp_ssl.return_value = mock_server
        mock_server.login.side_effect = smtplib.SMTPAuthenticationError(535, b"Authentication failed")

        client = SMTPClient(
            server="smtp.example.com",
            port=465,
            username="[email protected]",
            password="wrong_password",
            _from="[email protected]",
            use_tls=True,
            opportunistic_tls=False,
        )

        mail_data = {"to": "[email protected]", "subject": "Test", "html": "<p>Content</p>"}

        # Act & Assert
        with pytest.raises(smtplib.SMTPAuthenticationError):
            client.send(mail_data)

        mock_server.quit.assert_called_once()  # Should still cleanup

    @patch("libs.smtp.smtplib.SMTP_SSL")
    def test_smtp_send_timeout_error(self, mock_smtp_ssl: MagicMock) -> None:
        """Test SMTP send handles timeout errors."""
        # Arrange
        mock_smtp_ssl.side_effect = TimeoutError("Connection timeout")

        client = SMTPClient(
            server="smtp.example.com",
            port=465,
            username="[email protected]",
            password="password123",
            _from="[email protected]",
            use_tls=True,
            opportunistic_tls=False,
        )

        mail_data = {"to": "[email protected]", "subject": "Test", "html": "<p>Content</p>"}

        # Act & Assert
        with pytest.raises(TimeoutError):
            client.send(mail_data)

    @patch("libs.smtp.smtplib.SMTP_SSL")
    def test_smtp_send_connection_refused(self, mock_smtp_ssl: MagicMock) -> None:
        """Test SMTP send handles connection refused errors."""
        # Arrange
        mock_smtp_ssl.side_effect = ConnectionRefusedError("Connection refused")

        client = SMTPClient(
            server="smtp.example.com",
            port=465,
            username="[email protected]",
            password="password123",
            _from="[email protected]",
            use_tls=True,
            opportunistic_tls=False,
        )

        mail_data = {"to": "[email protected]", "subject": "Test", "html": "<p>Content</p>"}

        # Act & Assert
        with pytest.raises((ConnectionRefusedError, OSError)):
            client.send(mail_data)

    @patch("libs.smtp.smtplib.SMTP_SSL")
    def test_smtp_send_ensures_cleanup_on_error(self, mock_smtp_ssl: MagicMock) -> None:
        """Test SMTP send ensures cleanup even when errors occur."""
        # Arrange
        mock_server = MagicMock()
        mock_smtp_ssl.return_value = mock_server
        mock_server.sendmail.side_effect = smtplib.SMTPException("Send failed")

        client = SMTPClient(
            server="smtp.example.com",
            port=465,
            username="[email protected]",
            password="password123",
            _from="[email protected]",
            use_tls=True,
            opportunistic_tls=False,
        )

        mail_data = {"to": "[email protected]", "subject": "Test", "html": "<p>Content</p>"}

        # Act & Assert
        with pytest.raises(smtplib.SMTPException):
            client.send(mail_data)

        # Verify cleanup was called
        mock_server.quit.assert_called_once()


class TestMailTaskRetryLogic:
    """Test retry logic for mail sending tasks."""

    @patch("tasks.mail_register_task.mail")
    def test_mail_task_skips_when_not_initialized(self, mock_mail: MagicMock) -> None:
        """Test that mail tasks skip execution when mail is not initialized."""
        # Arrange
        mock_mail.is_inited.return_value = False

        # Act
        result = send_email_register_mail_task(language="en-US", to="[email protected]", code="123456")

        # Assert
        assert result is None
        mock_mail.is_inited.assert_called_once()

    @patch("tasks.mail_register_task.get_email_i18n_service")
    @patch("tasks.mail_register_task.mail")
    def test_mail_task_logs_success(
        self, mock_mail: MagicMock, mock_email_service: MagicMock, caplog: pytest.LogCaptureFixture
    ) -> None:
        """Test that successful mail sends are logged properly."""
        # Arrange
        mock_mail.is_inited.return_value = True
        mock_service = MagicMock()
        mock_email_service.return_value = mock_service

        # Act
        with caplog.at_level(logging.INFO, logger="tasks.mail_register_task"):
            send_email_register_mail_task(language="en-US", to="[email protected]", code="123456")

        # Assert
        mock_service.send_email.assert_called_once()
        log_messages = [record.getMessage() for record in caplog.records]
        assert any("Start email register mail to [email protected]" in message for message in log_messages)
        assert any("Send email register mail to [email protected] succeeded" in message for message in log_messages)

    @patch("tasks.mail_register_task.get_email_i18n_service")
    @patch("tasks.mail_register_task.mail")
    def test_mail_task_logs_failure(
        self, mock_mail: MagicMock, mock_email_service: MagicMock, caplog: pytest.LogCaptureFixture
    ) -> None:
        """Test that failed mail sends are logged with exception details."""
        # Arrange
        mock_mail.is_inited.return_value = True
        mock_service = MagicMock()
        mock_service.send_email.side_effect = Exception("SMTP connection failed")
        mock_email_service.return_value = mock_service

        # Act
        with caplog.at_level(logging.ERROR, logger="tasks.mail_register_task"):
            send_email_register_mail_task(language="en-US", to="[email protected]", code="123456")

        # Assert
        assert "Send email register mail to [email protected] failed" in caplog.text
        failure_records = [record for record in caplog.records if record.exc_info is not None]
        assert failure_records

    @patch("tasks.mail_reset_password_task.get_email_i18n_service")
    @patch("tasks.mail_reset_password_task.mail")
    def test_reset_password_task_success(self, mock_mail: MagicMock, mock_email_service: MagicMock) -> None:
        """Test reset password task sends email successfully."""
        # Arrange
        mock_mail.is_inited.return_value = True
        mock_service = MagicMock()
        mock_email_service.return_value = mock_service

        # Act
        send_reset_password_mail_task(language="zh-Hans", to="[email protected]", code="RESET123")

        # Assert
        mock_service.send_email.assert_called_once()
        sent = mock_service.send_email.call_args.kwargs
        assert sent["to"] == "[email protected]"
        assert sent["language_code"] == "zh-Hans"
        assert sent["template_context"] == {"to": "[email protected]", "code": "RESET123"}

    @patch("tasks.mail_reset_password_task.get_email_i18n_service")
    @patch("tasks.mail_reset_password_task.mail")
    def test_reset_password_when_account_not_exist_with_register(
        self, mock_mail: MagicMock, mock_email_service: MagicMock, config_overrides: Callable[..., None]
    ) -> None:
        """Test reset password task when account doesn't exist and registration is allowed."""
        # Arrange
        mock_mail.is_inited.return_value = True
        config_overrides(CONSOLE_WEB_URL="https://console.example.com")
        mock_service = MagicMock()
        mock_email_service.return_value = mock_service

        # Act
        send_reset_password_mail_task_when_account_not_exist(
            language="en-US", to="[email protected]", is_allow_register=True
        )

        # Assert
        mock_service.send_email.assert_called_once()
        sent = mock_service.send_email.call_args.kwargs
        assert sent["to"] == "[email protected]"
        assert sent["template_context"]["sign_up_url"] == "https://console.example.com/signup"

    @patch("tasks.mail_reset_password_task.get_email_i18n_service")
    @patch("tasks.mail_reset_password_task.mail")
    def test_reset_password_when_account_not_exist_without_register(
        self, mock_mail: MagicMock, mock_email_service: MagicMock
    ) -> None:
        """Test reset password task when account doesn't exist and registration is not allowed."""
        # Arrange
        mock_mail.is_inited.return_value = True
        mock_service = MagicMock()
        mock_email_service.return_value = mock_service

        # Act
        send_reset_password_mail_task_when_account_not_exist(
            language="en-US", to="[email protected]", is_allow_register=False
        )

        # Assert
        mock_service.send_email.assert_called_once()
        sent = mock_service.send_email.call_args.kwargs
        assert sent["to"] == "[email protected]"
        assert "template_context" not in sent


class TestMailTaskInternationalization:
    """Test internationalization support in mail tasks."""

    @patch("tasks.mail_register_task.get_email_i18n_service")
    @patch("tasks.mail_register_task.mail")
    def test_mail_task_with_english_language(self, mock_mail: MagicMock, mock_email_service: MagicMock) -> None:
        """Test mail task with English language code."""
        # Arrange
        mock_mail.is_inited.return_value = True
        mock_service = MagicMock()
        mock_email_service.return_value = mock_service

        # Act
        send_email_register_mail_task(language="en-US", to="[email protected]", code="123456")

        # Assert
        call_args = mock_service.send_email.call_args
        assert call_args[1]["language_code"] == "en-US"

    @patch("tasks.mail_register_task.get_email_i18n_service")
    @patch("tasks.mail_register_task.mail")
    def test_mail_task_with_chinese_language(self, mock_mail: MagicMock, mock_email_service: MagicMock) -> None:
        """Test mail task with Chinese language code."""
        # Arrange
        mock_mail.is_inited.return_value = True
        mock_service = MagicMock()
        mock_email_service.return_value = mock_service

        # Act
        send_email_register_mail_task(language="zh-Hans", to="[email protected]", code="123456")

        # Assert
        call_args = mock_service.send_email.call_args
        assert call_args[1]["language_code"] == "zh-Hans"

    @patch("tasks.mail_register_task.get_email_i18n_service")
    @patch("tasks.mail_register_task.mail")
    def test_account_exist_task_includes_urls(
        self, mock_mail: MagicMock, mock_email_service: MagicMock, config_overrides: Callable[..., None]
    ) -> None:
        """Test account exist task includes proper URLs in template context."""
        # Arrange
        mock_mail.is_inited.return_value = True
        config_overrides(CONSOLE_WEB_URL="https://console.example.com")
        mock_service = MagicMock()
        mock_email_service.return_value = mock_service

        # Act
        send_email_register_mail_task_when_account_exist(
            language="en-US", to="[email protected]", account_name="John Doe"
        )

        # Assert
        call_args = mock_service.send_email.call_args
        context = call_args[1]["template_context"]
        assert context["login_url"] == "https://console.example.com/signin"
        assert context["reset_password_url"] == "https://console.example.com/reset-password"
        assert context["account_name"] == "John Doe"


class TestInnerEmailTask:
    """Test inner email task with template rendering."""

    @patch("tasks.mail_inner_task.get_email_i18n_service")
    @patch("tasks.mail_inner_task.mail")
    @patch("tasks.mail_inner_task._render_template_with_strategy")
    def test_inner_email_task_renders_and_sends(
        self, mock_render: MagicMock, mock_mail: MagicMock, mock_email_service: MagicMock
    ) -> None:
        """Test inner email task renders template and sends email."""
        # Arrange
        mock_mail.is_inited.return_value = True
        mock_render.return_value = "<p>Hello John, your code is 123456</p>"
        mock_service = MagicMock()
        mock_email_service.return_value = mock_service

        to_list = ["[email protected]", "[email protected]"]
        subject = "Test Subject"
        body = "<p>Hello {{ name }}, your code is {{ code }}</p>"
        substitutions = {"name": "John", "code": "123456"}

        # Act
        send_inner_email_task(to=to_list, subject=subject, body=body, substitutions=substitutions)

        # Assert
        mock_service.send_raw_email.assert_called_once_with(
            to=to_list, subject=subject, html_content="<p>Hello John, your code is 123456</p>"
        )

    @patch("tasks.mail_inner_task.mail")
    def test_inner_email_task_skips_when_not_initialized(self, mock_mail: MagicMock) -> None:
        """Test inner email task skips when mail is not initialized."""
        # Arrange
        mock_mail.is_inited.return_value = False

        # Act
        result = send_inner_email_task(to=["[email protected]"], subject="Test", body="Body", substitutions={})

        # Assert
        assert result is None

    @patch("tasks.mail_inner_task.get_email_i18n_service")
    @patch("tasks.mail_inner_task.mail")
    @patch("tasks.mail_inner_task._render_template_with_strategy")
    def test_inner_email_task_logs_failure(
        self,
        mock_render: MagicMock,
        mock_mail: MagicMock,
        mock_email_service: MagicMock,
        caplog: pytest.LogCaptureFixture,
    ) -> None:
        """Test inner email task logs failures properly."""
        # Arrange
        mock_mail.is_inited.return_value = True
        mock_render.return_value = "<p>Content</p>"
        mock_service = MagicMock()
        mock_service.send_raw_email.side_effect = Exception("Send failed")
        mock_email_service.return_value = mock_service

        to_list = ["[email protected]"]

        # Act
        with caplog.at_level(logging.ERROR, logger="tasks.mail_inner_task"):
            send_inner_email_task(to=to_list, subject="Test", body="Body", substitutions={})

        # Assert
        assert "Send enterprise mail to ['[email protected]'] failed" in caplog.text
        assert len(caplog.records) == 1
        assert caplog.records[0].exc_info is not None


class TestSendGridIntegration:
    """Test SendGrid client integration."""

    @patch("libs.sendgrid.sendgrid.SendGridAPIClient")
    def test_sendgrid_send_success(self, mock_sg_client: MagicMock) -> None:
        """Test SendGrid client sends email successfully."""
        # Arrange
        mock_client_instance = MagicMock()
        mock_sg_client.return_value = mock_client_instance
        mock_response = MagicMock()
        mock_response.status_code = 202
        mock_client_instance.client.mail.send.post.return_value = mock_response

        client = SendGridClient(sendgrid_api_key="test_api_key", _from="[email protected]")

        mail_data = {"to": "[email protected]", "subject": "Test Subject", "html": "<p>Test Content</p>"}

        # Act
        client.send(mail_data)

        # Assert
        mock_sg_client.assert_called_once_with(api_key="test_api_key")
        mock_client_instance.client.mail.send.post.assert_called_once()

    @patch("libs.sendgrid.sendgrid.SendGridAPIClient")
    def test_sendgrid_send_missing_recipient(self, mock_sg_client: MagicMock) -> None:
        """Test SendGrid client raises error when recipient is missing."""
        # Arrange
        client = SendGridClient(sendgrid_api_key="test_api_key", _from="[email protected]")

        mail_data = {"to": "", "subject": "Test Subject", "html": "<p>Test Content</p>"}

        # Act & Assert
        with pytest.raises(ValueError, match="recipient address is missing"):
            client.send(mail_data)
        mock_sg_client.assert_not_called()

    @patch("libs.sendgrid.sendgrid.SendGridAPIClient")
    def test_sendgrid_send_unauthorized_error(self, mock_sg_client: MagicMock) -> None:
        """Test SendGrid client handles unauthorized errors."""
        # Arrange
        mock_client_instance = MagicMock()
        mock_sg_client.return_value = mock_client_instance
        mock_client_instance.client.mail.send.post.side_effect = UnauthorizedError(401, "Unauthorized", b"", Message())

        client = SendGridClient(sendgrid_api_key="invalid_key", _from="[email protected]")

        mail_data = {"to": "[email protected]", "subject": "Test", "html": "<p>Content</p>"}

        # Act & Assert
        with pytest.raises(UnauthorizedError) as exc_info:
            client.send(mail_data)
        assert exc_info.value.status_code == 401

    @patch("libs.sendgrid.sendgrid.SendGridAPIClient")
    def test_sendgrid_send_forbidden_error(self, mock_sg_client: MagicMock) -> None:
        """Test SendGrid client handles forbidden errors."""
        # Arrange
        mock_client_instance = MagicMock()
        mock_sg_client.return_value = mock_client_instance
        mock_client_instance.client.mail.send.post.side_effect = ForbiddenError(403, "Forbidden", b"", Message())

        client = SendGridClient(sendgrid_api_key="test_api_key", _from="[email protected]")

        mail_data = {"to": "[email protected]", "subject": "Test", "html": "<p>Content</p>"}

        # Act & Assert
        with pytest.raises(ForbiddenError) as exc_info:
            client.send(mail_data)
        assert exc_info.value.status_code == 403

    @patch("libs.sendgrid.sendgrid.SendGridAPIClient")
    def test_sendgrid_send_timeout_error(self, mock_sg_client: MagicMock) -> None:
        """Test SendGrid client handles timeout errors."""
        # Arrange
        mock_client_instance = MagicMock()
        mock_sg_client.return_value = mock_client_instance
        mock_client_instance.client.mail.send.post.side_effect = TimeoutError("Request timeout")

        client = SendGridClient(sendgrid_api_key="test_api_key", _from="[email protected]")

        mail_data = {"to": "[email protected]", "subject": "Test", "html": "<p>Content</p>"}

        # Act & Assert
        with pytest.raises(TimeoutError):
            client.send(mail_data)


class TestMailExtension:
    """Test mail extension initialization and configuration."""

    @pytest.fixture(autouse=True)
    def _smtp_config(self, config_overrides: Callable[..., None]) -> None:
        config_overrides(
            MAIL_TYPE="smtp",
            SMTP_SERVER="smtp.example.com",
            SMTP_PORT=465,
            SMTP_USERNAME="[email protected]",
            SMTP_PASSWORD="password123",
            SMTP_USE_TLS=True,
            SMTP_OPPORTUNISTIC_TLS=False,
            MAIL_DEFAULT_SEND_FROM="[email protected]",
        )

    def test_mail_init_smtp_configuration(self) -> None:
        """Test mail extension initializes SMTP client correctly."""
        # Arrange
        mail = Mail()
        mock_app = MagicMock()

        # Act
        mail.init_app(mock_app)

        # Assert
        assert mail.is_inited() is True
        assert mail._client is not None

    def test_mail_init_without_mail_type(self, config_overrides: Callable[..., None]) -> None:
        """Test mail extension skips initialization when MAIL_TYPE is not set."""
        # Arrange
        config_overrides(MAIL_TYPE=None)

        mail = Mail()
        mock_app = MagicMock()

        # Act
        mail.init_app(mock_app)

        # Assert
        assert mail.is_inited() is False

    def test_mail_send_validates_parameters(self) -> None:
        """Test mail send validates required parameters."""
        # Arrange
        mail = Mail()
        mail._client = MagicMock()
        mail._default_send_from = "[email protected]"

        # Act & Assert - missing to
        with pytest.raises(ValueError, match="mail to is not set"):
            mail.send(to="", subject="Test", html="<p>Content</p>")

        # Act & Assert - missing subject
        with pytest.raises(ValueError, match="mail subject is not set"):
            mail.send(to="[email protected]", subject="", html="<p>Content</p>")

        # Act & Assert - missing html
        with pytest.raises(ValueError, match="mail html is not set"):
            mail.send(to="[email protected]", subject="Test", html="")

    def test_mail_send_uses_default_from(self) -> None:
        """Test mail send uses default from address when not provided."""
        # Arrange
        mail = Mail()
        mock_client = MagicMock()
        mail._client = mock_client
        mail._default_send_from = "[email protected]"

        # Act
        mail.send(to="[email protected]", subject="Test", html="<p>Content</p>")

        # Assert
        mock_client.send.assert_called_once()
        call_args = mock_client.send.call_args[0][0]
        assert call_args["from"] == "[email protected]"


class TestEmailI18nService:
    """Test email internationalization service."""

    @patch("libs.email_i18n.FlaskMailSender")
    @patch("libs.email_i18n.FeatureBrandingService")
    @patch("libs.email_i18n.FlaskEmailRenderer")
    def test_email_service_sends_with_branding(
        self, mock_renderer_class: MagicMock, mock_branding_class: MagicMock, mock_sender_class: MagicMock
    ) -> None:
        """Test email service sends email with branding support."""
        # Arrange
        mock_renderer = MagicMock()
        mock_renderer.render_template.return_value = "<html>Rendered content</html>"
        mock_renderer_class.return_value = mock_renderer

        mock_branding = MagicMock()
        mock_branding.get_branding_config.return_value = BrandingModel(
            enabled=True, application_title="Custom App", logo="logo.png"
        )
        mock_branding_class.return_value = mock_branding

        mock_sender = MagicMock()
        mock_sender_class.return_value = mock_sender

        template = EmailTemplate(
            subject="Test {application_title}",
            template_path="templates/test.html",
            branded_template_path="templates/branded/test.html",
        )

        config = EmailI18nConfig(templates={EmailType.EMAIL_REGISTER: {EmailLanguage.EN_US: template}})

        service = EmailI18nService(
            config=config, renderer=mock_renderer, branding_service=mock_branding, sender=mock_sender
        )

        # Act
        service.send_email(
            email_type=EmailType.EMAIL_REGISTER,
            language_code="en-US",
            to="[email protected]",
            template_context={"code": "123456"},
        )

        # Assert
        mock_renderer.render_template.assert_called_once()
        # Should use branded template
        assert mock_renderer.render_template.call_args[0][0] == "templates/branded/test.html"
        mock_sender.send_email.assert_called_once_with(
            to="[email protected]", subject="Test Custom App", html_content="<html>Rendered content</html>"
        )

    @patch("libs.email_i18n.FlaskMailSender")
    def test_email_service_send_raw_email_single_recipient(self, mock_sender_class: MagicMock) -> None:
        """Test email service sends raw email to single recipient."""
        # Arrange
        mock_sender = MagicMock()
        mock_sender_class.return_value = mock_sender

        service = EmailI18nService(
            config=EmailI18nConfig(),
            renderer=MagicMock(),
            branding_service=MagicMock(),
            sender=mock_sender,
        )

        # Act
        service.send_raw_email(to="[email protected]", subject="Test", html_content="<p>Content</p>")

        # Assert
        mock_sender.send_email.assert_called_once_with(
            to="[email protected]", subject="Test", html_content="<p>Content</p>"
        )

    @patch("libs.email_i18n.FlaskMailSender")
    def test_email_service_send_raw_email_multiple_recipients(self, mock_sender_class: MagicMock) -> None:
        """Test email service sends raw email to multiple recipients."""
        # Arrange
        mock_sender = MagicMock()
        mock_sender_class.return_value = mock_sender

        service = EmailI18nService(
            config=EmailI18nConfig(),
            renderer=MagicMock(),
            branding_service=MagicMock(),
            sender=mock_sender,
        )

        # Act
        service.send_raw_email(
            to=["[email protected]", "[email protected]"], subject="Test", html_content="<p>Content</p>"
        )

        # Assert
        assert mock_sender.send_email.call_count == 2
        mock_sender.send_email.assert_any_call(to="[email protected]", subject="Test", html_content="<p>Content</p>")
        mock_sender.send_email.assert_any_call(to="[email protected]", subject="Test", html_content="<p>Content</p>")


class TestPerformanceAndTiming:
    """Test performance tracking and timing in mail tasks."""

    @patch("tasks.mail_register_task.get_email_i18n_service")
    @patch("tasks.mail_register_task.mail")
    @patch("tasks.mail_register_task.time")
    def test_mail_task_tracks_execution_time(
        self,
        mock_time: MagicMock,
        mock_mail: MagicMock,
        mock_email_service: MagicMock,
        caplog: pytest.LogCaptureFixture,
    ) -> None:
        """Test that mail tasks track and log execution time."""
        # Arrange
        mock_mail.is_inited.return_value = True
        mock_service = MagicMock()
        mock_email_service.return_value = mock_service

        # Simulate time progression
        mock_time.perf_counter.side_effect = [100.0, 100.5]  # 0.5 second execution

        # Act
        with caplog.at_level(logging.INFO, logger="tasks.mail_register_task"):
            send_email_register_mail_task(language="en-US", to="[email protected]", code="123456")

        # Assert
        latency_messages = [record.getMessage() for record in caplog.records if "latency:" in record.getMessage()]
        assert any("latency: 0.5" in message for message in latency_messages)


class TestEdgeCasesAndErrorHandling:
    """
    Test edge cases and error handling scenarios.

    This test class covers unusual inputs, boundary conditions,
    and various error scenarios to ensure robust error handling.
    """

    def test_mail_init_invalid_smtp_config_missing_server(self, config_overrides: Callable[..., None]) -> None:
        """
        Test mail initialization fails when SMTP server is missing.

        Validates that proper error is raised when required SMTP
        configuration parameters are not provided.
        """
        # Arrange
        config_overrides(MAIL_TYPE="smtp", SMTP_SERVER=None, SMTP_PORT=465)

        mail = Mail()
        mock_app = MagicMock()

        # Act & Assert
        with pytest.raises(ValueError, match="SMTP_SERVER and SMTP_PORT are required"):
            mail.init_app(mock_app)

    def test_mail_init_invalid_smtp_opportunistic_tls_without_tls(self, config_overrides: Callable[..., None]) -> None:
        """
        Test mail initialization fails with opportunistic TLS but TLS disabled.

        Opportunistic TLS (STARTTLS) requires TLS to be enabled.
        This test ensures the configuration is validated properly.
        """
        # Arrange
        config_overrides(
            MAIL_TYPE="smtp",
            SMTP_SERVER="smtp.example.com",
            SMTP_PORT=587,
            SMTP_USE_TLS=False,
            SMTP_OPPORTUNISTIC_TLS=True,
        )

        mail = Mail()
        mock_app = MagicMock()

        # Act & Assert
        with pytest.raises(ValueError, match="SMTP_OPPORTUNISTIC_TLS is not supported without enabling SMTP_USE_TLS"):
            mail.init_app(mock_app)

    def test_mail_init_unsupported_mail_type(self, config_overrides: Callable[..., None]) -> None:
        """
        Test mail initialization fails with unsupported mail type.

        Ensures that only supported mail providers (smtp, sendgrid, resend)
        are accepted and invalid types are rejected.
        """
        # Arrange
        config_overrides(MAIL_TYPE="unsupported_provider")

        mail = Mail()
        mock_app = MagicMock()

        # Act & Assert
        with pytest.raises(ValueError, match="Unsupported mail type"):
            mail.init_app(mock_app)

    @patch("libs.smtp.smtplib.SMTP_SSL")
    def test_smtp_send_with_empty_subject(self, mock_smtp_ssl: MagicMock) -> None:
        """
        Test SMTP client handles empty subject gracefully.

        While not ideal, the SMTP client should be able to send
        emails with empty subjects without crashing.
        """
        # Arrange
        mock_server = MagicMock()
        mock_smtp_ssl.return_value = mock_server

        client = SMTPClient(
            server="smtp.example.com",
            port=465,
            username="[email protected]",
            password="password123",
            _from="[email protected]",
            use_tls=True,
            opportunistic_tls=False,
        )

        # Email with empty subject
        mail_data = {"to": "[email protected]", "subject": "", "html": "<p>Content</p>"}

        # Act
        client.send(mail_data)

        # Assert - should still send successfully
        mock_server.sendmail.assert_called_once()

    @patch("libs.smtp.smtplib.SMTP_SSL")
    def test_smtp_send_with_unicode_characters(self, mock_smtp_ssl: MagicMock) -> None:
        """
        Test SMTP client handles Unicode characters in email content.

        Ensures proper handling of international characters in
        subject lines and email bodies.
        """
        # Arrange
        mock_server = MagicMock()
        mock_smtp_ssl.return_value = mock_server

        client = SMTPClient(
            server="smtp.example.com",
            port=465,
            username="[email protected]",
            password="password123",
            _from="[email protected]",
            use_tls=True,
            opportunistic_tls=False,
        )

        # Email with Unicode characters (Chinese, emoji, etc.)
        mail_data = {
            "to": "[email protected]",
            "subject": "测试邮件 🎉 Test Email",
            "html": "<p>你好世界 Hello World 🌍</p>",
        }

        # Act
        client.send(mail_data)

        # Assert
        mock_server.sendmail.assert_called_once()
        mock_server.quit.assert_called_once()

    @patch("tasks.mail_inner_task.get_email_i18n_service")
    @patch("tasks.mail_inner_task.mail")
    @patch("tasks.mail_inner_task._render_template_with_strategy")
    def test_inner_email_task_with_empty_recipient_list(
        self, mock_render: MagicMock, mock_mail: MagicMock, mock_email_service: MagicMock
    ) -> None:
        """
        Test inner email task handles empty recipient list.

        When no recipients are provided, the task should handle
        this gracefully without attempting to send emails.
        """
        # Arrange
        mock_mail.is_inited.return_value = True
        mock_render.return_value = "<p>Content</p>"
        mock_service = MagicMock()
        mock_email_service.return_value = mock_service

        # Act
        send_inner_email_task(to=[], subject="Test", body="Body", substitutions={})

        # Assert
        mock_service.send_raw_email.assert_called_once_with(to=[], subject="Test", html_content="<p>Content</p>")


class TestConcurrencyAndThreadSafety:
    """
    Test concurrent execution and thread safety scenarios.

    These tests ensure that mail tasks can handle concurrent
    execution without race conditions or resource conflicts.
    """

    @patch("tasks.mail_register_task.get_email_i18n_service")
    @patch("tasks.mail_register_task.mail")
    def test_multiple_mail_tasks_concurrent_execution(
        self, mock_mail: MagicMock, mock_email_service: MagicMock
    ) -> None:
        """
        Test multiple mail tasks can execute concurrently.

        Simulates concurrent execution of multiple mail tasks
        to ensure thread safety and proper resource handling.
        """
        # Arrange
        mock_mail.is_inited.return_value = True
        mock_service = MagicMock()
        mock_email_service.return_value = mock_service

        # Act - simulate concurrent task execution
        recipients = [f"user{i}@example.com" for i in range(5)]
        for recipient in recipients:
            send_email_register_mail_task(language="en-US", to=recipient, code="123456")

        # Assert - all tasks should complete successfully
        assert mock_service.send_email.call_count == 5


class TestResendIntegration:
    """
    Test Resend email service integration.

    Resend is an alternative email provider that can be used
    instead of SMTP or SendGrid.
    """

    @pytest.fixture(autouse=True)
    def _resend_config(self, config_overrides: Callable[..., None]) -> None:
        config_overrides(
            MAIL_TYPE="resend",
            RESEND_API_KEY="re_test_api_key",
            RESEND_API_URL=None,
            MAIL_DEFAULT_SEND_FROM="[email protected]",
        )

    @patch("builtins.__import__", side_effect=__import__)
    def test_mail_init_resend_configuration(self, mock_import: MagicMock) -> None:
        """
        Test mail extension initializes Resend client correctly.

        Validates that Resend API key is properly configured
        and the client is initialized.
        """
        # Arrange
        # Create mock resend module
        mock_resend = MagicMock()
        mock_emails = MagicMock()
        mock_resend.Emails = mock_emails

        # Override import for resend module
        original_import = __import__

        def custom_import(
            name: str,
            globals_: Mapping[str, object] | None = None,
            locals_: Mapping[str, object] | None = None,
            fromlist: Sequence[str] = (),
            level: int = 0,
        ) -> object:
            if name == "resend":
                return mock_resend
            return original_import(name, globals_, locals_, fromlist, level)

        mock_import.side_effect = custom_import

        mail = Mail()
        mock_app = MagicMock()

        # Act
        mail.init_app(mock_app)

        # Assert
        assert mail.is_inited() is True
        assert mock_resend.api_key == "re_test_api_key"

    @patch("builtins.__import__", side_effect=__import__)
    def test_mail_init_resend_with_custom_url(
        self, mock_import: MagicMock, config_overrides: Callable[..., None]
    ) -> None:
        """
        Test mail extension initializes Resend with custom API URL.

        Some deployments may use a custom Resend API endpoint.
        This test ensures custom URLs are properly configured.
        """
        # Arrange
        config_overrides(RESEND_API_URL="https://custom-resend.example.com")

        # Create mock resend module
        mock_resend = MagicMock()
        mock_emails = MagicMock()
        mock_resend.Emails = mock_emails

        # Override import for resend module
        original_import = __import__

        def custom_import(
            name: str,
            globals_: Mapping[str, object] | None = None,
            locals_: Mapping[str, object] | None = None,
            fromlist: Sequence[str] = (),
            level: int = 0,
        ) -> object:
            if name == "resend":
                return mock_resend
            return original_import(name, globals_, locals_, fromlist, level)

        mock_import.side_effect = custom_import

        mail = Mail()
        mock_app = MagicMock()

        # Act
        mail.init_app(mock_app)

        # Assert
        assert mail.is_inited() is True
        assert mock_resend.api_url == "https://custom-resend.example.com"

    def test_mail_init_resend_missing_api_key(self, config_overrides: Callable[..., None]) -> None:
        """
        Test mail initialization fails when Resend API key is missing.

        Resend requires an API key to function. This test ensures
        proper validation of required configuration.
        """
        # Arrange
        config_overrides(RESEND_API_KEY=None)

        mail = Mail()
        mock_app = MagicMock()

        # Act & Assert
        with pytest.raises(ValueError, match="RESEND_API_KEY is not set"):
            mail.init_app(mock_app)


class TestTemplateContextValidation:
    """
    Test template context validation and rendering.

    These tests ensure that template contexts are properly
    validated and rendered with correct variable substitution.
    """

    @patch("tasks.mail_register_task.get_email_i18n_service")
    @patch("tasks.mail_register_task.mail")
    def test_mail_task_template_context_includes_all_required_fields(
        self, mock_mail: MagicMock, mock_email_service: MagicMock
    ) -> None:
        """
        Test that mail tasks include all required fields in template context.

        Template rendering requires specific context variables.
        This test ensures all required fields are present.
        """
        # Arrange
        mock_mail.is_inited.return_value = True
        mock_service = MagicMock()
        mock_email_service.return_value = mock_service

        # Act
        send_email_register_mail_task(language="en-US", to="[email protected]", code="ABC123")

        # Assert
        call_args = mock_service.send_email.call_args
        context = call_args[1]["template_context"]

        # Verify all required fields are present
        assert "to" in context
        assert "code" in context
        assert context["to"] == "[email protected]"
        assert context["code"] == "ABC123"

    def test_render_template_with_complex_nested_data(self, config_overrides: Callable[..., None]) -> None:
        """
        Test template rendering with complex nested data structures.

        Templates may need to access nested dictionaries or lists.
        This test ensures complex data structures are handled correctly.
        """
        # Arrange
        body = (
            "User: {{ user.name }}, Items: "
            "{% for item in items %}{{ item }}{% if not loop.last %}, {% endif %}{% endfor %}"
        )
        substitutions = {"user": {"name": "John Doe"}, "items": ["apple", "banana", "cherry"]}

        # Act
        config_overrides(MAIL_TEMPLATING_MODE=TemplateMode.SANDBOX)
        result = _render_template_with_strategy(body, substitutions)

        # Assert
        assert "John Doe" in result
        assert "apple" in result
        assert "banana" in result
        assert "cherry" in result

    def test_render_template_with_conditional_logic(self, config_overrides: Callable[..., None]) -> None:
        """
        Test template rendering with conditional logic.

        Templates often use conditional statements to customize
        content based on context variables.
        """
        # Arrange
        body = "{% if is_premium %}Premium User{% else %}Free User{% endif %}"

        # Act - Test with premium user
        config_overrides(MAIL_TEMPLATING_MODE=TemplateMode.SANDBOX)
        result_premium = _render_template_with_strategy(body, {"is_premium": True})
        result_free = _render_template_with_strategy(body, {"is_premium": False})

        # Assert
        assert "Premium User" in result_premium
        assert "Free User" in result_free


class TestEmailValidation:
    """
    Test email address validation and sanitization.

    These tests ensure that email addresses are properly
    validated before sending to prevent errors.
    """

    def test_mail_send_with_invalid_email_format(self) -> None:
        """
        Test mail send with malformed email address.

        While the Mail class doesn't validate email format,
        this test documents the current behavior.
        """
        # Arrange
        mail = Mail()
        mock_client = MagicMock()
        mail._client = mock_client
        mail._default_send_from = "[email protected]"

        # Act - send to malformed email (no validation in Mail class)
        mail.send(to="not-an-email", subject="Test", html="<p>Content</p>")

        # Assert - Mail class passes through to client
        mock_client.send.assert_called_once()


class TestSMTPEdgeCases:
    """
    Test SMTP-specific edge cases and error conditions.

    These tests cover various SMTP-specific scenarios that
    may occur in production environments.
    """

    @patch("libs.smtp.smtplib.SMTP_SSL")
    def test_smtp_send_with_very_large_email_body(self, mock_smtp_ssl: MagicMock) -> None:
        """
        Test SMTP client handles large email bodies.

        Some emails may contain large HTML content with images
        or extensive formatting. This test ensures they're handled.
        """
        # Arrange
        mock_server = MagicMock()
        mock_smtp_ssl.return_value = mock_server

        client = SMTPClient(
            server="smtp.example.com",
            port=465,
            username="[email protected]",
            password="password123",
            _from="[email protected]",
            use_tls=True,
            opportunistic_tls=False,
        )

        # Create a large HTML body (simulating a newsletter)
        large_html = "<html><body>" + "<p>Content paragraph</p>" * 1000 + "</body></html>"
        mail_data = {"to": "[email protected]", "subject": "Large Email", "html": large_html}

        # Act
        client.send(mail_data)

        # Assert
        mock_server.sendmail.assert_called_once()
        # Verify the large content was included
        sent_message = mock_server.sendmail.call_args[0][2]
        assert len(sent_message) > 10000  # Should be a large message

    @patch("libs.smtp.smtplib.SMTP_SSL")
    def test_smtp_send_with_multiple_recipients_in_to_field(self, mock_smtp_ssl: MagicMock) -> None:
        """
        Test SMTP client with single recipient (current implementation).

        The current SMTPClient implementation sends to a single
        recipient per call. This test documents that behavior.
        """
        # Arrange
        mock_server = MagicMock()
        mock_smtp_ssl.return_value = mock_server

        client = SMTPClient(
            server="smtp.example.com",
            port=465,
            username="[email protected]",
            password="password123",
            _from="[email protected]",
            use_tls=True,
            opportunistic_tls=False,
        )

        mail_data = {"to": "[email protected]", "subject": "Test", "html": "<p>Content</p>"}

        # Act
        client.send(mail_data)

        # Assert - sends to single recipient
        call_args = mock_server.sendmail.call_args
        assert call_args[0][1] == "[email protected]"

    @patch("libs.smtp.smtplib.SMTP")
    def test_smtp_send_with_whitespace_in_credentials(self, mock_smtp: MagicMock) -> None:
        """
        Test SMTP client strips whitespace from credentials.

        The SMTPClient checks for non-empty credentials after stripping
        whitespace to avoid authentication with blank credentials.
        """
        # Arrange
        mock_server = MagicMock()
        mock_smtp.return_value = mock_server

        # Credentials with only whitespace
        client = SMTPClient(
            server="smtp.example.com",
            port=25,
            username="   ",  # Only whitespace
            password="   ",  # Only whitespace
            _from="[email protected]",
            use_tls=False,
            opportunistic_tls=False,
        )

        mail_data = {"to": "[email protected]", "subject": "Test", "html": "<p>Content</p>"}

        # Act
        client.send(mail_data)

        # Assert - should NOT attempt login with whitespace-only credentials
        mock_server.login.assert_not_called()


class TestLoggingAndMonitoring:
    """
    Test logging and monitoring functionality.

    These tests ensure that mail tasks properly log their
    execution for debugging and monitoring purposes.
    """

    @patch("tasks.mail_register_task.get_email_i18n_service")
    @patch("tasks.mail_register_task.mail")
    def test_mail_task_logs_recipient_information(
        self, mock_mail: MagicMock, mock_email_service: MagicMock, caplog: pytest.LogCaptureFixture
    ) -> None:
        """
        Test that mail tasks log recipient information for audit trails.

        Logging recipient information helps with debugging and
        tracking email delivery in production.
        """
        # Arrange
        mock_mail.is_inited.return_value = True
        mock_service = MagicMock()
        mock_email_service.return_value = mock_service

        # Act
        with caplog.at_level(logging.INFO, logger="tasks.mail_register_task"):
            send_email_register_mail_task(language="en-US", to="[email protected]", code="123456")

        # Assert
        # Check that recipient is logged in start message
        assert "[email protected]" in caplog.records[0].getMessage()

    @patch("tasks.mail_inner_task.get_email_i18n_service")
    @patch("tasks.mail_inner_task.mail")
    def test_inner_email_task_logs_subject_for_tracking(
        self, mock_mail: MagicMock, mock_email_service: MagicMock, caplog: pytest.LogCaptureFixture
    ) -> None:
        """
        Test that inner email task logs subject for tracking purposes.

        Logging email subjects helps identify which emails are being
        sent and aids in debugging delivery issues.
        """
        # Arrange
        mock_mail.is_inited.return_value = True
        mock_service = MagicMock()
        mock_email_service.return_value = mock_service

        # Act
        with caplog.at_level(logging.INFO, logger="tasks.mail_inner_task"):
            send_inner_email_task(
                to=["[email protected]"], subject="Important Notification", body="<p>Body</p>", substitutions={}
            )

        # Assert
        # Check that subject is logged
        assert "Important Notification" in caplog.records[0].getMessage()