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.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
refactor(api): enable strict typing for tasks unit tests (#44255)
Eddy ZHANGeec9f8260d29
diff --git a/api/tests/unit_tests/.ruff.toml b/api/tests/unit_tests/.ruff.tomlindex 64a6a75118e..d3394476cc4 100644--- a/api/tests/unit_tests/.ruff.toml+++ b/api/tests/unit_tests/.ruff.toml@@ -323,11 +323,9 @@ extend-select = ["ANN401", "ARG"]"tasks/test_document_indexing_sync_task.py" = ["ARG002"]"tasks/test_human_input_timeout_tasks.py" = ["ARG001", "ARG002", "ARG005", "TID251"]"tasks/test_initialize_created_app_rbac_access_task.py" = ["ARG005"]-"tasks/test_mail_send_task.py" = ["ARG002"]"tasks/test_ops_trace_task.py" = ["ARG004"]"tasks/test_process_tenant_plugin_autoupgrade_check_task.py" = ["ARG001"]"tasks/test_remove_app_and_related_data_task.py" = ["ARG002"]-"tasks/test_trigger_processing_tasks.py" = ["ARG002"]"tasks/test_workflow_execute_task.py" = ["ARG005"]"test_app_factory.py" = ["ARG001"]"test_pytest_dify.py" = ["ARG001"]diff --git a/api/tests/unit_tests/pyrefly.toml b/api/tests/unit_tests/pyrefly.tomlindex 1bc723da324..3cae02945cc 100644--- a/api/tests/unit_tests/pyrefly.toml+++ b/api/tests/unit_tests/pyrefly.toml@@ -640,19 +640,13 @@ project-excludes = ["tasks/test_document_indexing_sync_task.py","tasks/test_document_indexing_update_task.py","tasks/test_enable_segment_index_tasks.py",- "tasks/test_enterprise_telemetry_task.py","tasks/test_human_input_timeout_tasks.py","tasks/test_initialize_created_app_rbac_access_task.py",- "tasks/test_install_default_plugins_task.py",- "tasks/test_mail_human_input_delivery_task.py",- "tasks/test_mail_send_task.py","tasks/test_ops_trace_task.py","tasks/test_process_tenant_plugin_autoupgrade_check_task.py",- "tasks/test_refresh_billing_vector_space_task.py","tasks/test_remove_app_and_related_data_task.py","tasks/test_resume_agent_app_task.py","tasks/test_summary_queue_isolation.py",- "tasks/test_trigger_processing_tasks.py","tasks/test_workflow_execute_task.py","test_app_factory.py","test_makefile_backend_tests.py",diff --git a/api/tests/unit_tests/tasks/test_enterprise_telemetry_task.py b/api/tests/unit_tests/tasks/test_enterprise_telemetry_task.pyindex 02131445eb6..e7434ea7984 100644--- a/api/tests/unit_tests/tasks/test_enterprise_telemetry_task.py+++ b/api/tests/unit_tests/tasks/test_enterprise_telemetry_task.py@@ -10,7 +10,7 @@ from tasks.enterprise_telemetry_task import process_enterprise_telemetry@pytest.fixture-def sample_envelope_json():+def sample_envelope_json() -> str:envelope = TelemetryEnvelope(case=TelemetryCase.APP_CREATED,tenant_id="test-tenant",@@ -20,7 +20,7 @@ def sample_envelope_json():return envelope.model_dump_json()-def test_process_enterprise_telemetry_success(sample_envelope_json):+def test_process_enterprise_telemetry_success(sample_envelope_json: str) -> None:with patch("tasks.enterprise_telemetry_task.EnterpriseMetricHandler") as mock_handler_class:mock_handler = MagicMock()mock_handler_class.return_value = mock_handler@@ -35,7 +35,7 @@ def test_process_enterprise_telemetry_success(sample_envelope_json):assert call_args.event_id == "test-event-123"-def test_process_enterprise_telemetry_invalid_json(caplog: pytest.LogCaptureFixture):+def test_process_enterprise_telemetry_invalid_json(caplog: pytest.LogCaptureFixture) -> None:invalid_json = "not valid json"process_enterprise_telemetry(invalid_json)@@ -43,7 +43,9 @@ def test_process_enterprise_telemetry_invalid_json(caplog: pytest.LogCaptureFixtassert "Failed to process enterprise telemetry envelope" in caplog.text-def test_process_enterprise_telemetry_handler_exception(sample_envelope_json, caplog: pytest.LogCaptureFixture):+def test_process_enterprise_telemetry_handler_exception(+ sample_envelope_json: str, caplog: pytest.LogCaptureFixture+) -> None:with patch("tasks.enterprise_telemetry_task.EnterpriseMetricHandler") as mock_handler_class:mock_handler = MagicMock()mock_handler.handle.side_effect = Exception("Handler error")@@ -54,7 +56,7 @@ def test_process_enterprise_telemetry_handler_exception(sample_envelope_json, caassert "Failed to process enterprise telemetry envelope" in caplog.text-def test_process_enterprise_telemetry_validation_error(caplog: pytest.LogCaptureFixture):+def test_process_enterprise_telemetry_validation_error(caplog: pytest.LogCaptureFixture) -> None:invalid_envelope = json.dumps({"case": "INVALID_CASE",diff --git a/api/tests/unit_tests/tasks/test_install_default_plugins_task.py b/api/tests/unit_tests/tasks/test_install_default_plugins_task.pyindex f7e44be1a50..e44f75ea497 100644--- a/api/tests/unit_tests/tasks/test_install_default_plugins_task.py+++ b/api/tests/unit_tests/tasks/test_install_default_plugins_task.py@@ -1,5 +1,6 @@import loggingfrom types import SimpleNamespace+from typing import Protocol, castfrom unittest.mock import MagicMock, callimport pytest@@ -8,16 +9,20 @@ from celery.exceptions import Retryfrom tests.unit_tests.config_override import apply_config_overrides+class _TaskWithQueue(Protocol):+ queue: str++def test_install_default_plugins_task_uses_plugin_queue() -> None:from tasks.install_default_plugins_task import install_default_plugins_task- assert install_default_plugins_task.queue == "plugin"+ assert cast(_TaskWithQueue, install_default_plugins_task).queue == "plugin"def test_configure_default_models_task_uses_plugin_queue() -> None:from tasks.install_default_plugins_task import configure_default_models_task- assert configure_default_models_task.queue == "plugin"+ assert cast(_TaskWithQueue, configure_default_models_task).queue == "plugin"def test_install_default_plugins_task_installs_latest_identifiers(monkeypatch: pytest.MonkeyPatch) -> None:diff --git a/api/tests/unit_tests/tasks/test_mail_human_input_delivery_task.py b/api/tests/unit_tests/tasks/test_mail_human_input_delivery_task.pyindex 739db0d5877..709e6314c33 100644--- a/api/tests/unit_tests/tasks/test_mail_human_input_delivery_task.py+++ b/api/tests/unit_tests/tasks/test_mail_human_input_delivery_task.py@@ -13,14 +13,14 @@ from tasks import mail_human_input_delivery_task as task_moduleclass _DummyMail:- def __init__(self):+ def __init__(self) -> None:self.sent: list[dict[str, str]] = []self._inited = Truedef is_inited(self) -> bool:return self._inited- def send(self, *, to: str, subject: str, html: str):+ def send(self, *, to: str, subject: str, html: str) -> None:self.sent.append({"to": to, "subject": subject, "html": html})@@ -54,7 +54,7 @@ def _build_job(recipient_count: int = 1) -> task_module._EmailDeliveryJob:@pytest.mark.parametrize("sqlite_session", [(HumanInputForm,)], indirect=True)def test_dispatch_human_input_email_task_sends_to_each_recipient(monkeypatch: pytest.MonkeyPatch, sqlite_engine: Engine, sqlite_session: Session-):+) -> None:mail = _DummyMail()form = _form()sqlite_session.add(form)@@ -83,7 +83,7 @@ def test_dispatch_human_input_email_task_sends_to_each_recipient(@pytest.mark.parametrize("sqlite_session", [(HumanInputForm,)], indirect=True)def test_dispatch_human_input_email_task_skips_when_feature_disabled(monkeypatch: pytest.MonkeyPatch, sqlite_engine: Engine, sqlite_session: Session-):+) -> None:mail = _DummyMail()form = _form()sqlite_session.add(form)@@ -109,7 +109,7 @@ def test_dispatch_human_input_email_task_skips_when_feature_disabled(@pytest.mark.parametrize("sqlite_session", [(HumanInputForm,)], indirect=True)def test_dispatch_human_input_email_task_replaces_body_variables(monkeypatch: pytest.MonkeyPatch, sqlite_engine: Engine, sqlite_session: Session-):+) -> None:mail = _DummyMail()form = _form(workflow_run_id=str(uuid4()))sqlite_session.add(form)@@ -150,7 +150,7 @@ def test_dispatch_human_input_email_task_sanitizes_subject(line_break: str,sqlite_engine: Engine,sqlite_session: Session,-):+) -> None:mail = _DummyMail()form = _form()sqlite_session.add(form)@@ -181,7 +181,7 @@ def test_dispatch_human_input_email_task_sanitizes_subject(assert mail.sent[0]["subject"] == "Notice BCC:[email protected] Alert"-def test_parse_recipient_payload_reads_email_and_type():+def test_parse_recipient_payload_reads_email_and_type() -> None:payload = json.dumps({"email": "[email protected]", "TYPE": RecipientType.EMAIL_MEMBER})assert task_module._parse_recipient_payload(payload) == ("[email protected]", RecipientType.EMAIL_MEMBER)@@ -196,6 +196,6 @@ def test_parse_recipient_payload_reads_email_and_type():json.dumps({"email": 42, "TYPE": RecipientType.EMAIL_MEMBER}),],)-def test_parse_recipient_payload_rejects_unusable_payloads(payload: str):+def test_parse_recipient_payload_rejects_unusable_payloads(payload: str) -> None:"""Payloads the recipients layer cannot produce must degrade to a skipped recipient."""assert task_module._parse_recipient_payload(payload) == (None, None)diff --git a/api/tests/unit_tests/tasks/test_mail_send_task.py b/api/tests/unit_tests/tasks/test_mail_send_task.pyindex e14c0a3a0de..d1d3714c3ca 100644--- a/api/tests/unit_tests/tasks/test_mail_send_task.py+++ b/api/tests/unit_tests/tasks/test_mail_send_task.py@@ -10,6 +10,8 @@ This module tests the mail sending functionality including:import loggingimport smtplib+from collections.abc import Callable, Mapping, Sequence+from email.message import Messagefrom unittest.mock import ANY, MagicMock, patchimport pytest@@ -35,7 +37,7 @@ from tasks.mail_reset_password_task import (class TestEmailTemplateRendering:"""Test email template rendering with various scenarios."""- def test_render_template_unsafe_mode(self, config_overrides):+ def test_render_template_unsafe_mode(self, config_overrides: Callable[..., None]) -> None:"""Test template rendering in unsafe mode with Jinja2 syntax."""# Arrangebody = "Hello {{ name }}, your code is {{ code }}"@@ -48,7 +50,7 @@ class TestEmailTemplateRendering:# Assertassert result == "Hello John, your code is 123456"- def test_render_template_sandbox_mode(self, config_overrides):+ def test_render_template_sandbox_mode(self, config_overrides: Callable[..., None]) -> None:"""Test template rendering in sandbox mode for security."""# Arrangebody = "Hello {{ name }}, your code is {{ code }}"@@ -61,7 +63,7 @@ class TestEmailTemplateRendering:# Assertassert result == "Hello Alice, your code is 654321"- def test_render_template_disabled_mode(self, config_overrides):+ def test_render_template_disabled_mode(self, config_overrides: Callable[..., None]) -> None:"""Test template rendering when templating is disabled."""# Arrangebody = "Hello {{ name }}, your code is {{ code }}"@@ -74,7 +76,7 @@ class TestEmailTemplateRendering:# Assert - should return body unchangedassert result == "Hello {{ name }}, your code is {{ code }}"- def test_render_template_sandbox_timeout(self, config_overrides):+ 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 %}"@@ -85,7 +87,7 @@ class TestEmailTemplateRendering:with pytest.raises((TimeoutError, RuntimeError, OverflowError)):_render_template_with_strategy(body, substitutions)- def test_render_template_invalid_mode(self, config_overrides):+ def test_render_template_invalid_mode(self, config_overrides: Callable[..., None]) -> None:"""Test that invalid template mode raises ValueError."""# Arrangebody = "Test"@@ -96,7 +98,7 @@ class TestEmailTemplateRendering: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):+ def test_render_template_with_special_characters(self, config_overrides: Callable[..., None]) -> None:"""Test template rendering with special characters and HTML."""# Arrangebody = "<h1>Hello {{ name }}</h1><p>Code: {{ code }}</p>"@@ -110,7 +112,7 @@ class TestEmailTemplateRendering:assert "Test<User>" in resultassert "ABC&123" in result- def test_render_template_missing_variable_sandbox(self, config_overrides):+ def test_render_template_missing_variable_sandbox(self, config_overrides: Callable[..., None]) -> None:"""Test sandbox mode handles missing variables gracefully."""# Arrangebody = "Hello {{ name }}, your code is {{ missing_var }}"@@ -129,7 +131,7 @@ 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):+ def test_smtp_send_with_tls_ssl(self, mock_smtp_ssl: MagicMock) -> None:"""Test SMTP send with TLS using SMTP_SSL."""# Arrangemock_server = MagicMock()@@ -157,7 +159,7 @@ class TestSMTPIntegration:mock_server.quit.assert_called_once()@patch("libs.smtp.smtplib.SMTP")- def test_smtp_send_with_opportunistic_tls(self, mock_smtp):+ def test_smtp_send_with_opportunistic_tls(self, mock_smtp: MagicMock) -> None:"""Test SMTP send with opportunistic TLS (STARTTLS)."""# Arrangemock_server = MagicMock()@@ -187,7 +189,7 @@ class TestSMTPIntegration:mock_server.quit.assert_called_once()@patch("libs.smtp.smtplib.SMTP")- def test_smtp_send_without_tls(self, mock_smtp):+ def test_smtp_send_without_tls(self, mock_smtp: MagicMock) -> None:"""Test SMTP send without TLS encryption."""# Arrangemock_server = MagicMock()@@ -215,7 +217,7 @@ class TestSMTPIntegration:mock_server.quit.assert_called_once()@patch("libs.smtp.smtplib.SMTP")- def test_smtp_send_without_authentication(self, mock_smtp):+ def test_smtp_send_without_authentication(self, mock_smtp: MagicMock) -> None:"""Test SMTP send without authentication (empty credentials)."""# Arrangemock_server = MagicMock()@@ -242,7 +244,7 @@ class TestSMTPIntegration:mock_server.quit.assert_called_once()@patch("libs.smtp.smtplib.SMTP_SSL")- def test_smtp_send_authentication_failure(self, mock_smtp_ssl):+ def test_smtp_send_authentication_failure(self, mock_smtp_ssl: MagicMock) -> None:"""Test SMTP send handles authentication failure."""# Arrangemock_server = MagicMock()@@ -268,7 +270,7 @@ class TestSMTPIntegration: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):+ def test_smtp_send_timeout_error(self, mock_smtp_ssl: MagicMock) -> None:"""Test SMTP send handles timeout errors."""# Arrangemock_smtp_ssl.side_effect = TimeoutError("Connection timeout")@@ -290,7 +292,7 @@ class TestSMTPIntegration:client.send(mail_data)@patch("libs.smtp.smtplib.SMTP_SSL")- def test_smtp_send_connection_refused(self, mock_smtp_ssl):+ def test_smtp_send_connection_refused(self, mock_smtp_ssl: MagicMock) -> None:"""Test SMTP send handles connection refused errors."""# Arrangemock_smtp_ssl.side_effect = ConnectionRefusedError("Connection refused")@@ -312,7 +314,7 @@ class TestSMTPIntegration:client.send(mail_data)@patch("libs.smtp.smtplib.SMTP_SSL")- def test_smtp_send_ensures_cleanup_on_error(self, mock_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."""# Arrangemock_server = MagicMock()@@ -343,7 +345,7 @@ 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):+ def test_mail_task_skips_when_not_initialized(self, mock_mail: MagicMock) -> None:"""Test that mail tasks skip execution when mail is not initialized."""# Arrangemock_mail.is_inited.return_value = False@@ -357,7 +359,9 @@ class TestMailTaskRetryLogic:@patch("tasks.mail_register_task.get_email_i18n_service")@patch("tasks.mail_register_task.mail")- def test_mail_task_logs_success(self, mock_mail, mock_email_service, caplog: pytest.LogCaptureFixture):+ 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."""# Arrangemock_mail.is_inited.return_value = True@@ -383,7 +387,9 @@ class TestMailTaskRetryLogic:@patch("tasks.mail_register_task.get_email_i18n_service")@patch("tasks.mail_register_task.mail")- def test_mail_task_logs_failure(self, mock_mail, mock_email_service, caplog: pytest.LogCaptureFixture):+ 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."""# Arrangemock_mail.is_inited.return_value = True@@ -402,7 +408,7 @@ class TestMailTaskRetryLogic:@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, mock_email_service):+ def test_reset_password_task_success(self, mock_mail: MagicMock, mock_email_service: MagicMock) -> None:"""Test reset password task sends email successfully."""# Arrangemock_mail.is_inited.return_value = True@@ -422,7 +428,9 @@ class TestMailTaskRetryLogic:@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, mock_email_service, config_overrides):+ 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."""# Arrangemock_mail.is_inited.return_value = True@@ -444,7 +452,9 @@ class TestMailTaskRetryLogic:@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, mock_email_service):+ 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."""# Arrangemock_mail.is_inited.return_value = True@@ -467,7 +477,7 @@ class TestMailTaskInternationalization:@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, mock_email_service):+ def test_mail_task_with_english_language(self, mock_mail: MagicMock, mock_email_service: MagicMock) -> None:"""Test mail task with English language code."""# Arrangemock_mail.is_inited.return_value = True@@ -483,7 +493,7 @@ class TestMailTaskInternationalization:@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, mock_email_service):+ def test_mail_task_with_chinese_language(self, mock_mail: MagicMock, mock_email_service: MagicMock) -> None:"""Test mail task with Chinese language code."""# Arrangemock_mail.is_inited.return_value = True@@ -499,7 +509,9 @@ class TestMailTaskInternationalization:@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, mock_email_service, config_overrides):+ 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."""# Arrangemock_mail.is_inited.return_value = True@@ -526,7 +538,9 @@ class TestInnerEmailTask:@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, mock_mail, mock_email_service):+ 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."""# Arrangemock_mail.is_inited.return_value = True@@ -549,7 +563,7 @@ class TestInnerEmailTask:)@patch("tasks.mail_inner_task.mail")- def test_inner_email_task_skips_when_not_initialized(self, mock_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."""# Arrangemock_mail.is_inited.return_value = False@@ -564,8 +578,12 @@ class TestInnerEmailTask:@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, mock_mail, mock_email_service, caplog: pytest.LogCaptureFixture- ):+ self,+ mock_render: MagicMock,+ mock_mail: MagicMock,+ mock_email_service: MagicMock,+ caplog: pytest.LogCaptureFixture,+ ) -> None:"""Test inner email task logs failures properly."""# Arrangemock_mail.is_inited.return_value = True@@ -590,7 +608,7 @@ class TestSendGridIntegration:"""Test SendGrid client integration."""@patch("libs.sendgrid.sendgrid.SendGridAPIClient")- def test_sendgrid_send_success(self, mock_sg_client):+ def test_sendgrid_send_success(self, mock_sg_client: MagicMock) -> None:"""Test SendGrid client sends email successfully."""# Arrangemock_client_instance = MagicMock()@@ -611,7 +629,7 @@ class TestSendGridIntegration: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):+ def test_sendgrid_send_missing_recipient(self, mock_sg_client: MagicMock) -> None:"""Test SendGrid client raises error when recipient is missing."""# Arrangeclient = SendGridClient(sendgrid_api_key="test_api_key", _from="[email protected]")@@ -621,43 +639,44 @@ class TestSendGridIntegration:# Act & Assertwith 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):+ def test_sendgrid_send_unauthorized_error(self, mock_sg_client: MagicMock) -> None:"""Test SendGrid client handles unauthorized errors."""# Arrangemock_client_instance = MagicMock()mock_sg_client.return_value = mock_client_instance- mock_client_instance.client.mail.send.post.side_effect = UnauthorizedError(- MagicMock(status_code=401), "Unauthorized"- )+ 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):+ 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):+ def test_sendgrid_send_forbidden_error(self, mock_sg_client: MagicMock) -> None:"""Test SendGrid client handles forbidden errors."""# Arrangemock_client_instance = MagicMock()mock_sg_client.return_value = mock_client_instance- mock_client_instance.client.mail.send.post.side_effect = ForbiddenError(MagicMock(status_code=403), "Forbidden")+ 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):+ 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):+ def test_sendgrid_send_timeout_error(self, mock_sg_client: MagicMock) -> None:"""Test SendGrid client handles timeout errors."""# Arrangemock_client_instance = MagicMock()@@ -677,7 +696,7 @@ class TestMailExtension:"""Test mail extension initialization and configuration."""@pytest.fixture(autouse=True)- def _smtp_config(self, config_overrides) -> None:+ def _smtp_config(self, config_overrides: Callable[..., None]) -> None:config_overrides(MAIL_TYPE="smtp",SMTP_SERVER="smtp.example.com",@@ -689,7 +708,7 @@ class TestMailExtension:MAIL_DEFAULT_SEND_FROM="[email protected]",)- def test_mail_init_smtp_configuration(self):+ def test_mail_init_smtp_configuration(self) -> None:"""Test mail extension initializes SMTP client correctly."""# Arrangemail = Mail()@@ -702,7 +721,7 @@ class TestMailExtension:assert mail.is_inited() is Trueassert mail._client is not None- def test_mail_init_without_mail_type(self, config_overrides):+ def test_mail_init_without_mail_type(self, config_overrides: Callable[..., None]) -> None:"""Test mail extension skips initialization when MAIL_TYPE is not set."""# Arrangeconfig_overrides(MAIL_TYPE=None)@@ -716,7 +735,7 @@ class TestMailExtension:# Assertassert mail.is_inited() is False- def test_mail_send_validates_parameters(self):+ def test_mail_send_validates_parameters(self) -> None:"""Test mail send validates required parameters."""# Arrangemail = Mail()@@ -735,7 +754,7 @@ class TestMailExtension: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):+ def test_mail_send_uses_default_from(self) -> None:"""Test mail send uses default from address when not provided."""# Arrangemail = Mail()@@ -758,7 +777,9 @@ class TestEmailI18nService:@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, mock_branding_class, mock_sender_class):+ 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."""# Arrangemock_renderer = MagicMock()@@ -803,7 +824,7 @@ class TestEmailI18nService:)@patch("libs.email_i18n.FlaskMailSender")- def test_email_service_send_raw_email_single_recipient(self, mock_sender_class):+ def test_email_service_send_raw_email_single_recipient(self, mock_sender_class: MagicMock) -> None:"""Test email service sends raw email to single recipient."""# Arrangemock_sender = MagicMock()@@ -825,7 +846,7 @@ class TestEmailI18nService:)@patch("libs.email_i18n.FlaskMailSender")- def test_email_service_send_raw_email_multiple_recipients(self, mock_sender_class):+ def test_email_service_send_raw_email_multiple_recipients(self, mock_sender_class: MagicMock) -> None:"""Test email service sends raw email to multiple recipients."""# Arrangemock_sender = MagicMock()@@ -856,8 +877,12 @@ class TestPerformanceAndTiming:@patch("tasks.mail_register_task.mail")@patch("tasks.mail_register_task.time")def test_mail_task_tracks_execution_time(- self, mock_time, mock_mail, mock_email_service, caplog: pytest.LogCaptureFixture- ):+ self,+ mock_time: MagicMock,+ mock_mail: MagicMock,+ mock_email_service: MagicMock,+ caplog: pytest.LogCaptureFixture,+ ) -> None:"""Test that mail tasks track and log execution time."""# Arrangemock_mail.is_inited.return_value = True@@ -886,7 +911,7 @@ class TestEdgeCasesAndErrorHandling:and various error scenarios to ensure robust error handling."""- def test_mail_init_invalid_smtp_config_missing_server(self, config_overrides):+ def test_mail_init_invalid_smtp_config_missing_server(self, config_overrides: Callable[..., None]) -> None:"""Test mail initialization fails when SMTP server is missing.@@ -903,7 +928,7 @@ class TestEdgeCasesAndErrorHandling: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):+ 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.@@ -926,7 +951,7 @@ class TestEdgeCasesAndErrorHandling: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):+ def test_mail_init_unsupported_mail_type(self, config_overrides: Callable[..., None]) -> None:"""Test mail initialization fails with unsupported mail type.@@ -944,7 +969,7 @@ class TestEdgeCasesAndErrorHandling:mail.init_app(mock_app)@patch("libs.smtp.smtplib.SMTP_SSL")- def test_smtp_send_with_empty_subject(self, mock_smtp_ssl):+ def test_smtp_send_with_empty_subject(self, mock_smtp_ssl: MagicMock) -> None:"""Test SMTP client handles empty subject gracefully.@@ -975,7 +1000,7 @@ class TestEdgeCasesAndErrorHandling:mock_server.sendmail.assert_called_once()@patch("libs.smtp.smtplib.SMTP_SSL")- def test_smtp_send_with_unicode_characters(self, mock_smtp_ssl):+ def test_smtp_send_with_unicode_characters(self, mock_smtp_ssl: MagicMock) -> None:"""Test SMTP client handles Unicode characters in email content.@@ -1013,7 +1038,9 @@ class TestEdgeCasesAndErrorHandling:@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, mock_mail, mock_email_service):+ 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.@@ -1043,7 +1070,9 @@ class TestConcurrencyAndThreadSafety:@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, mock_email_service):+ def test_multiple_mail_tasks_concurrent_execution(+ self, mock_mail: MagicMock, mock_email_service: MagicMock+ ) -> None:"""Test multiple mail tasks can execute concurrently.@@ -1073,7 +1102,7 @@ class TestResendIntegration:"""@pytest.fixture(autouse=True)- def _resend_config(self, config_overrides) -> None:+ def _resend_config(self, config_overrides: Callable[..., None]) -> None:config_overrides(MAIL_TYPE="resend",RESEND_API_KEY="re_test_api_key",@@ -1082,7 +1111,7 @@ class TestResendIntegration:)@patch("builtins.__import__", side_effect=__import__)- def test_mail_init_resend_configuration(self, mock_import):+ def test_mail_init_resend_configuration(self, mock_import: MagicMock) -> None:"""Test mail extension initializes Resend client correctly.@@ -1098,10 +1127,16 @@ class TestResendIntegration:# Override import for resend moduleoriginal_import = __import__- def custom_import(name, *args, **kwargs):+ 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, *args, **kwargs)+ return original_import(name, globals_, locals_, fromlist, level)mock_import.side_effect = custom_import@@ -1116,7 +1151,9 @@ class TestResendIntegration: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, config_overrides):+ 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.@@ -1134,10 +1171,16 @@ class TestResendIntegration:# Override import for resend moduleoriginal_import = __import__- def custom_import(name, *args, **kwargs):+ 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, *args, **kwargs)+ return original_import(name, globals_, locals_, fromlist, level)mock_import.side_effect = custom_import@@ -1151,7 +1194,7 @@ class TestResendIntegration:assert mail.is_inited() is Trueassert mock_resend.api_url == "https://custom-resend.example.com"- def test_mail_init_resend_missing_api_key(self, config_overrides):+ def test_mail_init_resend_missing_api_key(self, config_overrides: Callable[..., None]) -> None:"""Test mail initialization fails when Resend API key is missing.@@ -1179,7 +1222,9 @@ class TestTemplateContextValidation:@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, mock_email_service):+ 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.@@ -1204,7 +1249,7 @@ class TestTemplateContextValidation:assert context["to"] == "[email protected]"assert context["code"] == "ABC123"- def test_render_template_with_complex_nested_data(self, config_overrides):+ def test_render_template_with_complex_nested_data(self, config_overrides: Callable[..., None]) -> None:"""Test template rendering with complex nested data structures.@@ -1228,7 +1273,7 @@ class TestTemplateContextValidation:assert "banana" in resultassert "cherry" in result- def test_render_template_with_conditional_logic(self, config_overrides):+ def test_render_template_with_conditional_logic(self, config_overrides: Callable[..., None]) -> None:"""Test template rendering with conditional logic.@@ -1256,7 +1301,7 @@ class TestEmailValidation:validated before sending to prevent errors."""- def test_mail_send_with_invalid_email_format(self):+ def test_mail_send_with_invalid_email_format(self) -> None:"""Test mail send with malformed email address.@@ -1285,7 +1330,7 @@ class TestSMTPEdgeCases:"""@patch("libs.smtp.smtplib.SMTP_SSL")- def test_smtp_send_with_very_large_email_body(self, mock_smtp_ssl):+ def test_smtp_send_with_very_large_email_body(self, mock_smtp_ssl: MagicMock) -> None:"""Test SMTP client handles large email bodies.@@ -1320,7 +1365,7 @@ class TestSMTPEdgeCases: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):+ def test_smtp_send_with_multiple_recipients_in_to_field(self, mock_smtp_ssl: MagicMock) -> None:"""Test SMTP client with single recipient (current implementation).@@ -1351,7 +1396,7 @@ class TestSMTPEdgeCases:assert call_args[0][1] == "[email protected]"@patch("libs.smtp.smtplib.SMTP")- def test_smtp_send_with_whitespace_in_credentials(self, mock_smtp):+ def test_smtp_send_with_whitespace_in_credentials(self, mock_smtp: MagicMock) -> None:"""Test SMTP client strips whitespace from credentials.@@ -1393,8 +1438,8 @@ class TestLoggingAndMonitoring:@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, mock_email_service, caplog: pytest.LogCaptureFixture- ):+ self, mock_mail: MagicMock, mock_email_service: MagicMock, caplog: pytest.LogCaptureFixture+ ) -> None:"""Test that mail tasks log recipient information for audit trails.@@ -1417,8 +1462,8 @@ class TestLoggingAndMonitoring:@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, mock_email_service, caplog: pytest.LogCaptureFixture- ):+ self, mock_mail: MagicMock, mock_email_service: MagicMock, caplog: pytest.LogCaptureFixture+ ) -> None:"""Test that inner email task logs subject for tracking purposes.diff --git a/api/tests/unit_tests/tasks/test_refresh_billing_vector_space_task.py b/api/tests/unit_tests/tasks/test_refresh_billing_vector_space_task.pyindex 93136228da3..2e533f63e0c 100644--- a/api/tests/unit_tests/tasks/test_refresh_billing_vector_space_task.py+++ b/api/tests/unit_tests/tasks/test_refresh_billing_vector_space_task.py@@ -15,7 +15,7 @@ def _cloud_edition(config_overrides: Callable[..., None]) -> None:config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)-def test_refresh_invalidates_vector_space_cache():+def test_refresh_invalidates_vector_space_cache() -> None:with (patch("tasks.refresh_billing_vector_space_task.BillingService.invalidate_vector_space_cache"@@ -26,7 +26,7 @@ def test_refresh_invalidates_vector_space_cache():invalidate_cache.assert_called_once_with("tenant-1")-def test_refresh_failure_schedules_retry():+def test_refresh_failure_schedules_retry() -> None:error = RuntimeError("billing unavailable")with (@@ -42,7 +42,7 @@ def test_refresh_failure_schedules_retry():retry.assert_called_once_with(exc=error, countdown=30)-def test_dispatch_failure_does_not_propagate():+def test_dispatch_failure_does_not_propagate() -> None:with (patch.object(refresh_billing_vector_space_task, "delay", side_effect=RuntimeError("broker unavailable")),):diff --git a/api/tests/unit_tests/tasks/test_trigger_processing_tasks.py b/api/tests/unit_tests/tasks/test_trigger_processing_tasks.pyindex 2e96619116f..f8ba6ad57fe 100644--- a/api/tests/unit_tests/tasks/test_trigger_processing_tasks.py+++ b/api/tests/unit_tests/tasks/test_trigger_processing_tasks.py@@ -1,7 +1,8 @@-from collections.abc import Mapping+from collections.abc import Generator, Mappingfrom unittest.mock import MagicMock, patchimport pytest+from typing_extensions import TypedDictimport tasks.trigger_processing_tasks as trigger_processing_tasks_modulefrom core.plugin.entities.plugin_daemon import CredentialType@@ -59,6 +60,17 @@ class _EndUserServiceStub:return self.result+class _DispatchMocks(TypedDict, closed=True):+ get_workflows: MagicMock+ reserve: MagicMock+ quota_charge: MagicMock+ mark_rate_limited: MagicMock+ invoke_trigger_event: MagicMock+ invoke_response: MagicMock+ end_users: _EndUserServiceStub+ trigger_workflow_async: MagicMock++class TestDispatchTriggeredWorkflow:"""Unit tests covering branch behaviours of ``dispatch_triggered_workflow``.@@ -71,7 +83,7 @@ class TestDispatchTriggeredWorkflow:"""@pytest.fixture- def subscription(self):+ def subscription(self) -> TriggerSubscription:subscription = TriggerSubscription(tenant_id="tenant-123",user_id="user-123",@@ -87,7 +99,7 @@ class TestDispatchTriggeredWorkflow:return subscription@pytest.fixture- def plugin_trigger(self):+ def plugin_trigger(self) -> WorkflowPluginTrigger:trigger = WorkflowPluginTrigger(app_id="app-123",node_id="node-123",@@ -100,7 +112,7 @@ class TestDispatchTriggeredWorkflow:return trigger@pytest.fixture- def provider_controller(self):+ def provider_controller(self) -> MagicMock:controller = MagicMock()controller.plugin_unique_identifier = "langgenius/test_plugin:0.0.1"controller.entity.identity.name = "Test Plugin"@@ -109,7 +121,9 @@ class TestDispatchTriggeredWorkflow:return controller@pytest.fixture- def dispatch_mocks(self, subscription, plugin_trigger, provider_controller):+ def dispatch_mocks(+ self, plugin_trigger: WorkflowPluginTrigger, provider_controller: MagicMock+ ) -> Generator[_DispatchMocks]:"""Patch all external dependencies reached by ``dispatch_triggered_workflow``.Defaults are configured so the code flow can reach the final async@@ -119,7 +133,7 @@ class TestDispatchTriggeredWorkflow:"""invoke_response = MagicMock()invoke_response.cancelled = False- invoke_response.variables = {}+ invoke_response.variables = dict[str, object]()quota_charge = MagicMock()end_users = _EndUserServiceStub()@@ -184,9 +198,11 @@ class TestDispatchTriggeredWorkflow:"trigger_workflow_async": trigger_workflow_async,}- def test_dispatch_skips_when_workflow_missing(self, subscription, dispatch_mocks):+ def test_dispatch_skips_when_workflow_missing(+ self, subscription: TriggerSubscription, dispatch_mocks: _DispatchMocks+ ) -> None:"""Covers missing workflow → log + ``continue``."""- dispatch_mocks["get_workflows"].return_value = {}+ dispatch_mocks["get_workflows"].return_value = dict[str, object]()dispatched = dispatch_triggered_workflow(user_id="user-123",@@ -201,7 +217,9 @@ class TestDispatchTriggeredWorkflow:dispatch_mocks["invoke_trigger_event"].assert_not_called()dispatch_mocks["mark_rate_limited"].assert_not_called()- def test_dispatch_marks_rate_limited_when_quota_exceeded(self, subscription, plugin_trigger, dispatch_mocks):+ def test_dispatch_marks_rate_limited_when_quota_exceeded(+ self, subscription: TriggerSubscription, plugin_trigger: WorkflowPluginTrigger, dispatch_mocks: _DispatchMocks+ ) -> None:"""Covers QuotaExceededError → mark rate-limited + early return."""workflow = _workflow()dispatch_mocks["get_workflows"].return_value = {plugin_trigger.app_id: workflow}@@ -223,8 +241,8 @@ class TestDispatchTriggeredWorkflow:dispatch_mocks["invoke_trigger_event"].assert_not_called()def test_dispatch_commits_quota_and_counts_when_workflow_triggered(- self, subscription, plugin_trigger, dispatch_mocks- ):+ self, subscription: TriggerSubscription, plugin_trigger: WorkflowPluginTrigger, dispatch_mocks: _DispatchMocks+ ) -> None:"""Happy path: end user exists and async trigger succeeds."""workflow = _workflow()dispatch_mocks["get_workflows"].return_value = {plugin_trigger.app_id: workflow}