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 libs test files (#44882)
Felix Shie9ba0f575a81
diff --git a/api/tests/unit_tests/libs/test_datetime_utils.py b/api/tests/unit_tests/libs/test_datetime_utils.pyindex b62c3585ce0..760bb5a93ac 100644--- a/api/tests/unit_tests/libs/test_datetime_utils.py+++ b/api/tests/unit_tests/libs/test_datetime_utils.py@@ -7,7 +7,7 @@ import pytzfrom libs.datetime_utils import Timing, measure_time, naive_utc_now, parse_time_range, to_utc_timestamp, utc_now-def test_utc_now(monkeypatch: pytest.MonkeyPatch):+def test_utc_now(monkeypatch: pytest.MonkeyPatch) -> None:expected = datetime.datetime(2026, 8, 26, 12, tzinfo=datetime.UTC)def _now_func(tz: datetime.timezone | None) -> datetime.datetime:@@ -19,7 +19,7 @@ def test_utc_now(monkeypatch: pytest.MonkeyPatch):assert utc_now().tzinfo is datetime.UTC-def test_naive_utc_now(monkeypatch: pytest.MonkeyPatch):+def test_naive_utc_now(monkeypatch: pytest.MonkeyPatch) -> None:tz_aware_utc_now = datetime.datetime.now(tz=datetime.UTC)def _now_func(tz: datetime.timezone | None) -> datetime.datetime:@@ -44,7 +44,7 @@ def test_naive_utc_now(monkeypatch: pytest.MonkeyPatch):datetime.datetime(2024, 1, 1, 9, tzinfo=datetime.timezone(datetime.timedelta(hours=9))),],)-def test_to_utc_timestamp(value: datetime.datetime):+def test_to_utc_timestamp(value: datetime.datetime) -> None:assert to_utc_timestamp(value) == 1704067200@@ -72,7 +72,7 @@ def test_measure_time_records_end_when_block_raises(monkeypatch: pytest.MonkeyPaclass TestParseTimeRange:"""Test cases for parse_time_range function."""- def test_parse_time_range_basic(self):+ def test_parse_time_range_basic(self) -> None:"""Test basic time range parsing."""start, end = parse_time_range("2024-01-01 10:00", "2024-01-01 18:00", "UTC")@@ -82,7 +82,7 @@ class TestParseTimeRange:assert start.tzinfo == pytz.UTCassert end.tzinfo == pytz.UTC- def test_parse_time_range_start_only(self):+ def test_parse_time_range_start_only(self) -> None:"""Test parsing with only start time."""start, end = parse_time_range("2024-01-01 10:00", None, "UTC")@@ -90,7 +90,7 @@ class TestParseTimeRange:assert end is Noneassert start.tzinfo == pytz.UTC- def test_parse_time_range_end_only(self):+ def test_parse_time_range_end_only(self) -> None:"""Test parsing with only end time."""start, end = parse_time_range(None, "2024-01-01 18:00", "UTC")@@ -98,14 +98,14 @@ class TestParseTimeRange:assert end is not Noneassert end.tzinfo == pytz.UTC- def test_parse_time_range_both_none(self):+ def test_parse_time_range_both_none(self) -> None:"""Test parsing with both times None."""start, end = parse_time_range(None, None, "UTC")assert start is Noneassert end is None- def test_parse_time_range_different_timezones(self):+ def test_parse_time_range_different_timezones(self) -> None:"""Test parsing with different timezones."""# Test with US/Eastern timezonestart, end = parse_time_range("2024-01-01 10:00", "2024-01-01 18:00", "US/Eastern")@@ -118,27 +118,27 @@ class TestParseTimeRange:assert start.hour == 15 # 10 AM EST = 3 PM UTC (in January)assert end.hour == 23 # 6 PM EST = 11 PM UTC (in January)- def test_parse_time_range_invalid_start_format(self):+ def test_parse_time_range_invalid_start_format(self) -> None:"""Test parsing with invalid start time format."""with pytest.raises(ValueError, match="time data.*does not match format"):parse_time_range("invalid-date", "2024-01-01 18:00", "UTC")- def test_parse_time_range_invalid_end_format(self):+ def test_parse_time_range_invalid_end_format(self) -> None:"""Test parsing with invalid end time format."""with pytest.raises(ValueError, match="time data.*does not match format"):parse_time_range("2024-01-01 10:00", "invalid-date", "UTC")- def test_parse_time_range_invalid_timezone(self):+ def test_parse_time_range_invalid_timezone(self) -> None:"""Test parsing with invalid timezone."""with pytest.raises(pytz.exceptions.UnknownTimeZoneError):parse_time_range("2024-01-01 10:00", "2024-01-01 18:00", "Invalid/Timezone")- def test_parse_time_range_start_after_end(self):+ def test_parse_time_range_start_after_end(self) -> None:"""Test parsing with start time after end time."""with pytest.raises(ValueError, match="start must be earlier than or equal to end"):parse_time_range("2024-01-01 18:00", "2024-01-01 10:00", "UTC")- def test_parse_time_range_start_equals_end(self):+ def test_parse_time_range_start_equals_end(self) -> None:"""Test parsing with start time equal to end time."""start, end = parse_time_range("2024-01-01 10:00", "2024-01-01 10:00", "UTC")@@ -146,7 +146,7 @@ class TestParseTimeRange:assert end is not Noneassert start == end- def test_parse_time_range_dst_ambiguous_time(self):+ def test_parse_time_range_dst_ambiguous_time(self) -> None:"""Test parsing during DST ambiguous time (fall back)."""# This test simulates DST fall back where 2:30 AM occurs twicewith patch("pytz.timezone", autospec=True) as mock_timezone:@@ -178,7 +178,7 @@ class TestParseTimeRange:assert start is not Noneassert end is not None- def test_parse_time_range_dst_nonexistent_time(self):+ def test_parse_time_range_dst_nonexistent_time(self) -> None:"""Test parsing during DST nonexistent time (spring forward)."""with patch("pytz.timezone", autospec=True) as mock_timezone:# Mock timezone that raises NonExistentTimeError@@ -209,7 +209,7 @@ class TestParseTimeRange:assert start is not Noneassert end is not None- def test_parse_time_range_edge_cases(self):+ def test_parse_time_range_edge_cases(self) -> None:"""Test edge cases for time parsing."""# Test with midnight timesstart, end = parse_time_range("2024-01-01 00:00", "2024-01-01 23:59", "UTC")@@ -220,7 +220,7 @@ class TestParseTimeRange:assert end.hour == 23assert end.minute == 59- def test_parse_time_range_different_dates(self):+ def test_parse_time_range_different_dates(self) -> None:"""Test parsing with different dates."""start, end = parse_time_range("2024-01-01 10:00", "2024-01-02 10:00", "UTC")assert start is not None@@ -228,7 +228,7 @@ class TestParseTimeRange:assert start.date() != end.date()assert (end - start).days == 1- def test_parse_time_range_seconds_handling(self):+ def test_parse_time_range_seconds_handling(self) -> None:"""Test that seconds are properly set to 0."""start, end = parse_time_range("2024-01-01 10:30", "2024-01-01 18:45", "UTC")assert start is not None@@ -236,7 +236,7 @@ class TestParseTimeRange:assert start.second == 0assert end.second == 0- def test_parse_time_range_timezone_conversion_accuracy(self):+ def test_parse_time_range_timezone_conversion_accuracy(self) -> None:"""Test accurate timezone conversion."""# Test with a known timezone conversionstart, end = parse_time_range("2024-01-01 12:00", "2024-01-01 12:00", "Asia/Tokyo")@@ -249,7 +249,7 @@ class TestParseTimeRange:assert start.hour == 3assert end.hour == 3- def test_parse_time_range_summer_time(self):+ def test_parse_time_range_summer_time(self) -> None:"""Test parsing during summer time (DST)."""# Test with US/Eastern during summer (EDT = UTC-4)start, end = parse_time_range("2024-07-01 12:00", "2024-07-01 12:00", "US/Eastern")@@ -262,7 +262,7 @@ class TestParseTimeRange:assert start.hour == 16assert end.hour == 16- def test_parse_time_range_winter_time(self):+ def test_parse_time_range_winter_time(self) -> None:"""Test parsing during winter time (standard time)."""# Test with US/Eastern during winter (EST = UTC-5)start, end = parse_time_range("2024-01-01 12:00", "2024-01-01 12:00", "US/Eastern")@@ -275,7 +275,7 @@ class TestParseTimeRange:assert start.hour == 17assert end.hour == 17- def test_parse_time_range_empty_strings(self):+ def test_parse_time_range_empty_strings(self) -> None:"""Test parsing with empty strings."""# Empty strings are treated as None, so they should not raise errorsstart, end = parse_time_range("", "2024-01-01 18:00", "UTC")@@ -286,7 +286,7 @@ class TestParseTimeRange:assert start is not Noneassert end is None- def test_parse_time_range_malformed_datetime(self):+ def test_parse_time_range_malformed_datetime(self) -> None:"""Test parsing with malformed datetime strings."""with pytest.raises(ValueError, match="time data.*does not match format"):parse_time_range("2024-13-01 10:00", "2024-01-01 18:00", "UTC")@@ -294,7 +294,7 @@ class TestParseTimeRange:with pytest.raises(ValueError, match="time data.*does not match format"):parse_time_range("2024-01-01 10:00", "2024-01-32 18:00", "UTC")- def test_parse_time_range_very_long_time_range(self):+ def test_parse_time_range_very_long_time_range(self) -> None:"""Test parsing with very long time range."""start, end = parse_time_range("2020-01-01 00:00", "2030-12-31 23:59", "UTC")@@ -303,7 +303,7 @@ class TestParseTimeRange:assert start < endassert (end - start).days > 3000 # More than 8 years- def test_parse_time_range_negative_timezone(self):+ def test_parse_time_range_negative_timezone(self) -> None:"""Test parsing with negative timezone offset."""start, end = parse_time_range("2024-01-01 12:00", "2024-01-01 12:00", "America/New_York")diff --git a/api/tests/unit_tests/libs/test_email_i18n.py b/api/tests/unit_tests/libs/test_email_i18n.pyindex 0a055cad513..a52b0ca0f72 100644--- a/api/tests/unit_tests/libs/test_email_i18n.py+++ b/api/tests/unit_tests/libs/test_email_i18n.py@@ -29,7 +29,7 @@ from services.entities.feature_entities import BrandingModelclass MockEmailRenderer:"""Mock implementation of EmailRenderer protocol"""- def __init__(self):+ def __init__(self) -> None:self.rendered_templates: list[tuple[str, dict[str, Any]]] = []def render_template(self, template_path: str, **context: Any) -> str:@@ -41,7 +41,7 @@ class MockEmailRenderer:class MockBrandingService:"""Mock implementation of BrandingService protocol"""- def __init__(self, enabled: bool = False, application_title: str = "Dify"):+ def __init__(self, enabled: bool = False, application_title: str = "Dify") -> None:self.enabled = enabledself.application_title = application_title@@ -53,10 +53,10 @@ class MockBrandingService:class MockEmailSender:"""Mock implementation of EmailSender protocol"""- def __init__(self):+ def __init__(self) -> None:self.sent_emails: list[dict[str, str]] = []- def send_email(self, to: str, subject: str, html_content: str):+ def send_email(self, to: str, subject: str, html_content: str) -> None:"""Mock send_email that records sent emails"""self.sent_emails.append({@@ -133,7 +133,7 @@ class TestEmailI18nService:email_service: EmailI18nService,mock_renderer: MockEmailRenderer,mock_sender: MockEmailSender,- ):+ ) -> None:"""Test sending email with English language"""email_service.send_email(email_type=EmailType.RESET_PASSWORD,@@ -161,7 +161,7 @@ class TestEmailI18nService:self,email_service: EmailI18nService,mock_sender: MockEmailSender,- ):+ ) -> None:"""Test sending email with Chinese language"""email_service.send_email(email_type=EmailType.RESET_PASSWORD,@@ -180,7 +180,7 @@ class TestEmailI18nService:email_config: EmailI18nConfig,mock_renderer: MockEmailRenderer,mock_sender: MockEmailSender,- ):+ ) -> None:"""Test sending email with branding enabled"""# Create branding service with branding enabledbranding_service = MockBrandingService(enabled=True, application_title="MyApp")@@ -214,7 +214,7 @@ class TestEmailI18nService:self,email_service: EmailI18nService,mock_sender: MockEmailSender,- ):+ ) -> None:"""Test language fallback to English when requested language not available"""# Request invite member in Chinese (not configured)email_service.send_email(@@ -232,7 +232,7 @@ class TestEmailI18nService:self,email_service: EmailI18nService,mock_sender: MockEmailSender,- ):+ ) -> None:"""Test unknown language code falls back to English"""email_service.send_email(email_type=EmailType.RESET_PASSWORD,@@ -249,7 +249,7 @@ class TestEmailI18nService:self,mock_renderer: MockEmailRenderer,mock_sender: MockEmailSender,- ):+ ) -> None:"""Trigger subject KeyError and cover except branch."""# Config with subject that references an unknown key (no {application_title} to avoid second format)config = EmailI18nConfig(@@ -288,7 +288,7 @@ class TestEmailI18nService:mock_renderer: MockEmailRenderer,mock_sender: MockEmailSender,mock_branding_service: MockBrandingService,- ):+ ) -> None:"""Test sending change email for old email verification"""# Add change email templates to configemail_config.templates[EmailType.CHANGE_EMAIL_OLD] = {@@ -326,7 +326,7 @@ class TestEmailI18nService:mock_renderer: MockEmailRenderer,mock_sender: MockEmailSender,mock_branding_service: MockBrandingService,- ):+ ) -> None:"""Test sending change email for new email verification"""# Add change email templates to configemail_config.templates[EmailType.CHANGE_EMAIL_NEW] = {@@ -361,7 +361,7 @@ class TestEmailI18nService:def test_send_change_email_invalid_phase(self,email_service: EmailI18nService,- ):+ ) -> None:"""Test sending change email with invalid phase raises error"""with pytest.raises(ValueError, match="Invalid phase: invalid_phase"):email_service.send_change_email(@@ -375,7 +375,7 @@ class TestEmailI18nService:self,email_service: EmailI18nService,mock_sender: MockEmailSender,- ):+ ) -> None:"""Test sending raw email to single recipient"""email_service.send_raw_email(to="[email protected]",@@ -393,7 +393,7 @@ class TestEmailI18nService:self,email_service: EmailI18nService,mock_sender: MockEmailSender,- ):+ ) -> None:"""Test sending raw email to multiple recipients"""@@ -414,7 +414,7 @@ class TestEmailI18nService:def test_get_template_missing_email_type(self,email_config: EmailI18nConfig,- ):+ ) -> None:"""Test getting template for missing email type raises error"""with pytest.raises(ValueError, match="No templates configured for email type"):email_config.get_template(EmailType.EMAIL_CODE_LOGIN, EmailLanguage.EN_US)@@ -422,7 +422,7 @@ class TestEmailI18nService:def test_get_template_missing_language_and_english(self,email_config: EmailI18nConfig,- ):+ ) -> None:"""Test error when neither requested language nor English fallback exists"""# Add template without English fallbackemail_config.templates[EmailType.EMAIL_CODE_LOGIN] = {@@ -443,7 +443,7 @@ class TestEmailI18nService:mock_renderer: MockEmailRenderer,mock_sender: MockEmailSender,mock_branding_service: MockBrandingService,- ):+ ) -> None:"""Test subject templating with custom variables"""# Add template with variable in subjectemail_config.templates[EmailType.OWNER_TRANSFER_NEW_NOTIFY] = {@@ -473,7 +473,7 @@ class TestEmailI18nService:sent_email = mock_sender.sent_emails[0]assert sent_email["subject"] == "You are now the owner of My Workspace"- def test_email_language_from_language_code(self):+ def test_email_language_from_language_code(self) -> None:"""Test EmailLanguage.from_language_code method"""assert EmailLanguage.from_language_code("zh-Hans") == EmailLanguage.ZH_HANSassert EmailLanguage.from_language_code("en-US") == EmailLanguage.EN_US@@ -484,7 +484,7 @@ class TestEmailI18nService:class TestEmailI18nIntegration:"""Integration tests for email i18n components"""- def test_create_default_email_config(self):+ def test_create_default_email_config(self) -> None:"""Test creating default email configuration"""config = create_default_email_config()@@ -513,7 +513,7 @@ class TestEmailI18nIntegration:assert EmailLanguage.ZH_HANS in config.templates[EmailType.RESET_PASSWORD]assert EmailLanguage.ZH_HANS in config.templates[EmailType.INVITE_MEMBER]- def test_get_email_i18n_service(self):+ def test_get_email_i18n_service(self) -> None:"""Test getting global email i18n service instance"""service1 = get_email_i18n_service()service2 = get_email_i18n_service()@@ -521,7 +521,7 @@ class TestEmailI18nIntegration:# Should return the same instanceassert service1 is service2- def test_flask_email_renderer(self):+ def test_flask_email_renderer(self) -> None:"""Test FlaskEmailRenderer implementation"""renderer = FlaskEmailRenderer()@@ -531,7 +531,7 @@ class TestEmailI18nIntegration:with pytest.raises(TemplateNotFound):renderer.render_template("test.html", foo="bar")- def test_flask_mail_sender_not_initialized(self):+ def test_flask_mail_sender_not_initialized(self) -> None:"""Test FlaskMailSender when mail is not initialized"""sender = FlaskMailSender()@@ -551,7 +551,7 @@ class TestEmailI18nIntegration:# Restore original maillibs.email_i18n.mail = original_mail- def test_flask_mail_sender_initialized(self):+ def test_flask_mail_sender_initialized(self) -> None:"""Test FlaskMailSender when mail is initialized"""sender = FlaskMailSender()@@ -577,7 +577,7 @@ class TestEmailI18nIntegration:@pytest.mark.parametrize("branding_enabled", [False, True])-def test_account_deletion_success_email_renders_chinese_template(branding_enabled: bool):+def test_account_deletion_success_email_renders_chinese_template(branding_enabled: bool) -> None:app = Flask(__name__, template_folder=str(Path(__file__).resolve().parents[3] / "templates"))sender = MockEmailSender()service = EmailI18nService(diff --git a/api/tests/unit_tests/libs/test_flask_utils.py b/api/tests/unit_tests/libs/test_flask_utils.pyindex a10a242d1f6..5d5fa682d6f 100644--- a/api/tests/unit_tests/libs/test_flask_utils.py+++ b/api/tests/unit_tests/libs/test_flask_utils.py@@ -1,6 +1,7 @@import contextvarsimport threadingfrom contextlib import nullcontext+from typing import overrideimport pytestfrom flask import Flask, current_app@@ -12,9 +13,10 @@ from libs.flask_utils import preserve_flask_contextsclass User(UserMixin):"""Simple User class for testing."""- def __init__(self, id: str):+ def __init__(self, id: str) -> None:self.id = id+ @overridedef get_id(self) -> str:return self.id@@ -43,7 +45,7 @@ def test_user() -> User:return User("test_user")-def test_current_user_not_accessible_across_threads(login_app: Flask, test_user: User):+def test_current_user_not_accessible_across_threads(login_app: Flask, test_user: User) -> None:"""Test that current_user is not accessible in a different thread without preserve_flask_contexts.@@ -57,10 +59,10 @@ def test_current_user_not_accessible_across_threads(login_app: Flask, test_user:assert current_user.id == "test_user"# Store the result of the thread execution- result = {"user_accessible": True, "error": None}+ result: dict[str, object] = {"user_accessible": True, "error": None}# Define a function to run in a separate thread- def check_user_in_thread():+ def check_user_in_thread() -> None:try:# Try to access current_user in a different thread with app_contextwith login_app.app_context():@@ -79,7 +81,7 @@ def test_current_user_not_accessible_across_threads(login_app: Flask, test_user:assert result["error"] is not None or (result["user_accessible"] is not None and not result["user_accessible"])-def test_current_user_accessible_with_preserve_flask_contexts(login_app: Flask, test_user: User):+def test_current_user_accessible_with_preserve_flask_contexts(login_app: Flask, test_user: User) -> None:"""Test that current_user is accessible in a different thread with preserve_flask_contexts.@@ -96,10 +98,10 @@ def test_current_user_accessible_with_preserve_flask_contexts(login_app: Flask,context_vars = contextvars.copy_context()# Store the result of the thread execution- result = {"user_accessible": False, "user_id": None, "error": None}+ result: dict[str, object] = {"user_accessible": False, "user_id": None, "error": None}# Define a function to run in a separate thread- def check_user_in_thread_with_manager():+ def check_user_in_thread_with_manager() -> None:try:# Use preserve_flask_contexts to access current_user in a different threadwith preserve_flask_contexts(login_app, context_vars):@@ -126,9 +128,11 @@ def test_current_user_accessible_with_preserve_flask_contexts(login_app: Flask,@pytest.mark.parametrize("caller_value", [None, "caller"])@pytest.mark.parametrize("failure_stage", [None, "body", "teardown"])-def test_preserve_flask_contexts_restores_bindings_after_teardown(caller_value, failure_stage):+def test_preserve_flask_contexts_restores_bindings_after_teardown(+ caller_value: str | None, failure_stage: str | None+) -> None:flask_app = Flask(__name__)- caller_app = current_app._get_current_object()+ caller_app = current_app._get_current_object() # pyrefly: ignore[missing-attribute]test_var = contextvars.ContextVar("preserved_var")captured = contextvars.copy_context()captured.run(test_var.set, "captured")@@ -136,7 +140,7 @@ def test_preserve_flask_contexts_restores_bindings_after_teardown(caller_value,teardown_values = []@flask_app.teardown_appcontext- def teardown(_error):+ def teardown(_error) -> None:teardown_values.append(test_var.get())if failure_stage == "teardown":raise ValueError("teardown failed")diff --git a/api/tests/unit_tests/libs/test_helper.py b/api/tests/unit_tests/libs/test_helper.pyindex 579f0475192..0b14b122a29 100644--- a/api/tests/unit_tests/libs/test_helper.py+++ b/api/tests/unit_tests/libs/test_helper.py@@ -124,7 +124,7 @@ def test_extract_remote_ip_preserves_trusted_rate_limit_buckets(class TestExtractTenantId:"""Test cases for the extract_tenant_id utility function."""- def test_extract_tenant_id_from_account_with_tenant(self):+ def test_extract_tenant_id_from_account_with_tenant(self) -> None:"""Test extracting tenant_id from Account with current_tenant_id."""# Create a mock Account objectaccount = Account(name="test", email="[email protected]")@@ -134,7 +134,7 @@ class TestExtractTenantId:tenant_id = extract_tenant_id(account)assert tenant_id == "account-tenant-123"- def test_extract_tenant_id_from_account_without_tenant(self):+ def test_extract_tenant_id_from_account_without_tenant(self) -> None:"""Test extracting tenant_id from Account without current_tenant_id."""# Create a mock Account objectaccount = Account(name="test", email="[email protected]")@@ -143,7 +143,7 @@ class TestExtractTenantId:tenant_id = extract_tenant_id(account)assert tenant_id is None- def test_extract_tenant_id_from_enduser_with_tenant(self):+ def test_extract_tenant_id_from_enduser_with_tenant(self) -> None:"""Test extracting tenant_id from EndUser with tenant_id."""# Create a mock EndUser objectend_user = EndUser()@@ -152,42 +152,42 @@ class TestExtractTenantId:tenant_id = extract_tenant_id(end_user)assert tenant_id == "enduser-tenant-456"- def test_extract_tenant_id_from_enduser_without_tenant(self):+ def test_extract_tenant_id_from_enduser_without_tenant(self) -> None:"""Test extracting tenant_id from EndUser without tenant_id."""# Create a mock EndUser objectend_user = EndUser()- end_user.tenant_id = None+ end_user.tenant_id = None # pyrefly: ignore[bad-argument-type]tenant_id = extract_tenant_id(end_user)assert tenant_id is None- def test_extract_tenant_id_with_invalid_user_type(self):+ def test_extract_tenant_id_with_invalid_user_type(self) -> None:"""Test extracting tenant_id with invalid user type raises ValueError."""invalid_user = "not_a_user_object"with pytest.raises(ValueError, match="Invalid user type.*Expected Account or EndUser"):- extract_tenant_id(invalid_user)+ extract_tenant_id(invalid_user) # pyrefly: ignore[bad-argument-type]- def test_extract_tenant_id_with_none_user(self):+ def test_extract_tenant_id_with_none_user(self) -> None:"""Test extracting tenant_id with None user raises ValueError."""with pytest.raises(ValueError, match="Invalid user type.*Expected Account or EndUser"):- extract_tenant_id(None)+ extract_tenant_id(None) # pyrefly: ignore[bad-argument-type]- def test_extract_tenant_id_with_dict_user(self):+ def test_extract_tenant_id_with_dict_user(self) -> None:"""Test extracting tenant_id with dict user raises ValueError."""dict_user = {"id": "123", "tenant_id": "456"}with pytest.raises(ValueError, match="Invalid user type.*Expected Account or EndUser"):- extract_tenant_id(dict_user)+ extract_tenant_id(dict_user) # pyrefly: ignore[bad-argument-type]class TestOptionalTimestampField:- def test_format_returns_none_for_none(self):+ def test_format_returns_none_for_none(self) -> None:field = OptionalTimestampField()assert field.format(None) is None- def test_format_returns_unix_timestamp_for_datetime(self):+ def test_format_returns_unix_timestamp_for_datetime(self) -> None:field = OptionalTimestampField()value = datetime(2024, 1, 2, 3, 4, 5)@@ -197,43 +197,43 @@ class TestOptionalTimestampField:class TestEscapeLikePattern:"""Test cases for the escape_like_pattern utility function."""- def test_escape_percent_character(self):+ def test_escape_percent_character(self) -> None:"""Test escaping percent character."""result = escape_like_pattern("50% discount")assert result == "50\\% discount"- def test_escape_underscore_character(self):+ def test_escape_underscore_character(self) -> None:"""Test escaping underscore character."""result = escape_like_pattern("test_data")assert result == "test\\_data"- def test_escape_backslash_character(self):+ def test_escape_backslash_character(self) -> None:"""Test escaping backslash character."""result = escape_like_pattern("path\\to\\file")assert result == "path\\\\to\\\\file"- def test_escape_combined_special_characters(self):+ def test_escape_combined_special_characters(self) -> None:"""Test escaping multiple special characters together."""result = escape_like_pattern("file_50%\\path")assert result == "file\\_50\\%\\\\path"- def test_escape_empty_string(self):+ def test_escape_empty_string(self) -> None:"""Test escaping empty string returns empty string."""result = escape_like_pattern("")assert result == ""- def test_escape_none_handling(self):+ def test_escape_none_handling(self) -> None:"""Test escaping None returns None (falsy check handles it)."""# The function checks `if not pattern`, so None is falsy and returns as-is- result = escape_like_pattern(None)+ result = escape_like_pattern(None) # pyrefly: ignore[bad-argument-type]assert result is None- def test_escape_normal_string_no_change(self):+ def test_escape_normal_string_no_change(self) -> None:"""Test that normal strings without special characters are unchanged."""result = escape_like_pattern("normal text")assert result == "normal text"- def test_escape_order_matters(self):+ def test_escape_order_matters(self) -> None:"""Test that backslash is escaped first to prevent double escaping."""# If we escape % first, then escape \, we might get wrong results# This test ensures the order is correct: \ first, then % and _@@ -245,26 +245,26 @@ class TestEscapeLikePattern:class TestEmailValidator:"""Tests for the email() validator — regression for #39234."""- def test_valid_email_accepted(self):+ def test_valid_email_accepted(self) -> None:assert email("[email protected]") == "[email protected]"- def test_trailing_newline_rejected(self):+ def test_trailing_newline_rejected(self) -> None:with pytest.raises(ValueError, match="not a valid email"):email("[email protected]\n")- def test_trailing_carriage_return_newline_rejected(self):+ def test_trailing_carriage_return_newline_rejected(self) -> None:with pytest.raises(ValueError, match="not a valid email"):email("[email protected]\r\n")- def test_multiple_newlines_rejected(self):+ def test_multiple_newlines_rejected(self) -> None:with pytest.raises(ValueError, match="not a valid email"):email("[email protected]\n\n")- def test_empty_string_rejected(self):+ def test_empty_string_rejected(self) -> None:with pytest.raises(ValueError, match="not a valid email"):email("")- def test_invalid_email_rejected(self):+ def test_invalid_email_rejected(self) -> None:with pytest.raises(ValueError, match="not a valid email"):email("not-an-email")@@ -272,39 +272,39 @@ class TestEmailValidator:class TestAlphanumericValidator:"""Tests for the alphanumeric() validator — regression for #39666."""- def test_valid_alphanumeric_accepted(self):+ def test_valid_alphanumeric_accepted(self) -> None:assert alphanumeric("tool_name") == "tool_name"assert alphanumeric("Tool123") == "Tool123"assert alphanumeric("_underscore_start") == "_underscore_start"assert alphanumeric("a") == "a"- def test_trailing_newline_rejected(self):+ def test_trailing_newline_rejected(self) -> None:# re.match with $ accepts a trailing \n in Python; re.fullmatch does not.# This was the pre-fix behaviour: alphanumeric("tool\n") returned "tool\n".with pytest.raises(ValueError, match="not a valid alphanumeric value"):alphanumeric("tool_name\n")- def test_trailing_carriage_return_rejected(self):+ def test_trailing_carriage_return_rejected(self) -> None:with pytest.raises(ValueError, match="not a valid alphanumeric value"):alphanumeric("tool_name\r")- def test_trailing_crlf_rejected(self):+ def test_trailing_crlf_rejected(self) -> None:with pytest.raises(ValueError, match="not a valid alphanumeric value"):alphanumeric("tool_name\r\n")- def test_leading_newline_rejected(self):+ def test_leading_newline_rejected(self) -> None:with pytest.raises(ValueError, match="not a valid alphanumeric value"):alphanumeric("\ntool_name")- def test_embedded_whitespace_rejected(self):+ def test_embedded_whitespace_rejected(self) -> None:with pytest.raises(ValueError, match="not a valid alphanumeric value"):alphanumeric("tool name")- def test_empty_string_rejected(self):+ def test_empty_string_rejected(self) -> None:with pytest.raises(ValueError, match="not a valid alphanumeric value"):alphanumeric("")- def test_special_characters_rejected(self):+ def test_special_characters_rejected(self) -> None:with pytest.raises(ValueError, match="not a valid alphanumeric value"):alphanumeric("tool-name")with pytest.raises(ValueError, match="not a valid alphanumeric value"):diff --git a/api/tests/unit_tests/libs/test_login.py b/api/tests/unit_tests/libs/test_login.pyindex c3e3205bf9e..1f98960f376 100644--- a/api/tests/unit_tests/libs/test_login.py+++ b/api/tests/unit_tests/libs/test_login.py@@ -1,3 +1,4 @@+from collections.abc import Callablefrom typing import castfrom unittest.mock import MagicMock@@ -15,11 +16,11 @@ from tests.helpers.unit.config_override import apply_config_overrides@pytest.fixture-def protected_view():+def protected_view() -> Callable[..., Response | str]:"""Build a small login-protected view that exercises the decorator logic."""@login_module.login_required- def _protected_view():+ def _protected_view() -> Response | str:return "Protected content"return _protected_view@@ -28,7 +29,7 @@ def protected_view():class MockUser:"""Mock user class for testing."""- def __init__(self, id: str, is_authenticated: bool = True):+ def __init__(self, id: str, is_authenticated: bool = True) -> None:self.id = idself._is_authenticated = is_authenticated@@ -60,13 +61,15 @@ def login_app(mocker: MockerFixture) -> Flask:login_manager = DifyLoginManager()login_manager.init_app(app)- login_manager.unauthorized = mocker.Mock(+ mocker.patch.object(+ login_manager,+ "unauthorized",name="unauthorized",return_value=Response("Unauthorized", status=401, content_type="application/json"),)@login_manager.user_loader- def load_user(_user_id: str):+ def load_user(_user_id: str) -> None:return Nonereturn app@@ -83,7 +86,7 @@ def csrf_check(mocker: MockerFixture) -> MagicMock:@pytest.fixture-def resolve_current_user(mocker: MockerFixture):+def resolve_current_user(mocker: MockerFixture) -> Callable[[MockUser | Account | None], MagicMock]:def _patch(user: MockUser | Account | None) -> MagicMock:return mocker.patch.object(login_module, "_resolve_current_user", return_value=user)@@ -96,10 +99,10 @@ class TestLoginRequired:def test_authenticated_user_can_access_protected_view(self,login_app: Flask,- protected_view,+ protected_view: Callable[..., Response | str],csrf_check: MagicMock,- resolve_current_user,- ):+ resolve_current_user: Callable[[MockUser | Account | None], MagicMock],+ ) -> None:"""Test that authenticated users can access protected views."""mock_user = MockUser("test_user", is_authenticated=True)@@ -125,12 +128,12 @@ class TestLoginRequired:def test_unauthorized_access_returns_login_manager_response(self,login_app: Flask,- protected_view,+ protected_view: Callable[..., Response | str],csrf_check: MagicMock,- resolve_current_user,+ resolve_current_user: Callable[[MockUser | Account | None], MagicMock],resolved_user: MockUser | None,description: str,- ):+ ) -> None:"""Test that missing or unauthenticated users return the manager response."""resolve_user = resolve_current_user(resolved_user)@@ -148,9 +151,9 @@ class TestLoginRequired:def test_unauthorized_access_propagates_response_object(self,login_app: Flask,- protected_view,+ protected_view: Callable[..., Response | str],csrf_check: MagicMock,- resolve_current_user,+ resolve_current_user: Callable[[MockUser | Account | None], MagicMock],mocker: MockerFixture,) -> None:"""Test that unauthorized responses are propagated as Flask Response objects."""@@ -176,13 +179,13 @@ class TestLoginRequired:def test_bypass_paths_skip_authentication_and_csrf(self,login_app: Flask,- protected_view,+ protected_view: Callable[..., Response | str],csrf_check: MagicMock,monkeypatch: pytest.MonkeyPatch,- resolve_current_user,+ resolve_current_user: Callable[[MockUser | Account | None], MagicMock],method: str,login_disabled: bool,- ):+ ) -> None:"""Test that bypass conditions skip auth lookup, CSRF, and unauthorized handling."""resolve_user = resolve_current_user(MockUser("test_user"))@@ -199,7 +202,7 @@ class TestLoginRequired:class TestGetUser:"""Test cases for _get_user function."""- def test_get_user_returns_user_from_g(self, login_app: Flask):+ def test_get_user_returns_user_from_g(self, login_app: Flask) -> None:"""Test that _get_user returns user from g._login_user."""mock_user = MockUser("test_user")@@ -210,7 +213,7 @@ class TestGetUser:assert user is not Noneassert user.id == "test_user"- def test_get_user_loads_user_if_not_in_g(self, login_app: Flask, mocker: MockerFixture):+ def test_get_user_loads_user_if_not_in_g(self, login_app: Flask, mocker: MockerFixture) -> None:"""Test that _get_user loads user if not already in g."""mock_user = MockUser("test_user")@@ -229,7 +232,7 @@ class TestGetUser:assert user == mock_userload_user.assert_called_once_with()- def test_get_user_returns_none_without_request_context(self):+ def test_get_user_returns_none_without_request_context(self) -> None:"""Test that _get_user returns None outside request context."""user = login_module._get_user()assert user is None@@ -238,7 +241,7 @@ class TestGetUser:class TestCurrentUser:"""Test cases for current_user proxy."""- def test_current_user_proxy_returns_authenticated_user(self, login_app: Flask, mocker: MockerFixture):+ def test_current_user_proxy_returns_authenticated_user(self, login_app: Flask, mocker: MockerFixture) -> None:"""Test that current_user proxy returns authenticated user."""mock_user = MockUser("test_user", is_authenticated=True)mocker.patch.object(login_module, "_get_user", return_value=mock_user)@@ -247,7 +250,9 @@ class TestCurrentUser:assert current_user.id == "test_user"assert current_user.is_authenticated is True- def test_current_user_proxy_raises_attribute_error_when_no_user(self, login_app: Flask, mocker: MockerFixture):+ def test_current_user_proxy_raises_attribute_error_when_no_user(+ self, login_app: Flask, mocker: MockerFixture+ ) -> None:"""Test that current_user proxy handles None user."""mocker.patch.object(login_module, "_get_user", return_value=None)@@ -259,7 +264,7 @@ class TestCurrentUser:class TestCurrentAccountWithTenant:"""Test cases for current_account_with_tenant helper."""- def test_returns_account_and_tenant_id(self, mocker: MockerFixture):+ def test_returns_account_and_tenant_id(self, mocker: MockerFixture) -> None:account = Account(name="Test User", email="[email protected]")tenant = Tenant(name="Test Tenant")tenant.id = "tenant-123"@@ -274,13 +279,13 @@ class TestCurrentAccountWithTenant:assert account_with_tenant.tenant_id == "tenant-123"current_user_proxy._get_current_object.assert_called_once_with()- def test_raises_when_current_user_is_not_account(self, mocker: MockerFixture):+ def test_raises_when_current_user_is_not_account(self, mocker: MockerFixture) -> None:mocker.patch.object(login_module, "current_user", new=MockUser("test_user"))with pytest.raises(ValueError, match="current_user must be an Account instance"):login_module.current_account_with_tenant()- def test_raises_when_account_has_no_tenant(self, mocker: MockerFixture):+ def test_raises_when_account_has_no_tenant(self, mocker: MockerFixture) -> None:account = Account(name="Test User", email="[email protected]")mocker.patch.object(login_module, "current_user", new=account)diff --git a/api/tests/unit_tests/libs/test_token.py b/api/tests/unit_tests/libs/test_token.pyindex e4ae2bf4128..db2f2e0e3cc 100644--- a/api/tests/unit_tests/libs/test_token.py+++ b/api/tests/unit_tests/libs/test_token.py@@ -1,3 +1,4 @@+from collections.abc import Callablefrom dataclasses import dataclassfrom typing import castfrom unittest.mock import MagicMock@@ -20,7 +21,7 @@ class MockRequest:path: str = "/console/api/test"-def test_extract_access_token():+def test_extract_access_token() -> None:def _mock_request(headers: dict[str, str], cookies: dict[str, str], args: dict[str, str]) -> Request:return cast(Request, MockRequest(headers, cookies, args))@@ -36,7 +37,7 @@ def test_extract_access_token():assert extract_webapp_access_token(request) == expected_webapp-def test_real_cookie_name_uses_host_prefix_without_domain(config_overrides):+def test_real_cookie_name_uses_host_prefix_without_domain(config_overrides: Callable[..., None]) -> None:config_overrides(CONSOLE_WEB_URL="https://console.example.com",CONSOLE_API_URL="https://api.example.com",@@ -46,7 +47,7 @@ def test_real_cookie_name_uses_host_prefix_without_domain(config_overrides):assert token._real_cookie_name("csrf_token") == "__Host-csrf_token"-def test_real_cookie_name_without_host_prefix_when_domain_present(config_overrides):+def test_real_cookie_name_without_host_prefix_when_domain_present(config_overrides: Callable[..., None]) -> None:config_overrides(CONSOLE_WEB_URL="https://console.example.com",CONSOLE_API_URL="https://api.example.com",@@ -56,7 +57,7 @@ def test_real_cookie_name_without_host_prefix_when_domain_present(config_overridassert token._real_cookie_name("csrf_token") == "csrf_token"-def test_set_csrf_cookie_includes_domain_when_configured(config_overrides):+def test_set_csrf_cookie_includes_domain_when_configured(config_overrides: Callable[..., None]) -> None:config_overrides(CONSOLE_WEB_URL="https://console.example.com",CONSOLE_API_URL="https://api.example.com",@@ -74,7 +75,7 @@ def test_set_csrf_cookie_includes_domain_when_configured(config_overrides):assert all("__Host-" not in c for c in cookies)-def test_workflow_run_archive_download_file_bypasses_csrf():+def test_workflow_run_archive_download_file_bypasses_csrf() -> None:request = cast(Request,MockRequest(@@ -88,14 +89,14 @@ def test_workflow_run_archive_download_file_bypasses_csrf():token.check_csrf_token(request, "account-1")-def test_non_whitelisted_path_requires_csrf():+def test_non_whitelisted_path_requires_csrf() -> None:request = cast(Request, MockRequest(headers={}, cookies={}, args={}, path="/console/api/test"))with pytest.raises(Unauthorized):token.check_csrf_token(request, "account-1")-def test_exact_workflow_draft_path_bypasses_csrf():+def test_exact_workflow_draft_path_bypasses_csrf() -> None:request = cast(Request,MockRequest(@@ -120,14 +121,16 @@ def test_exact_workflow_draft_path_bypasses_csrf():"/console/api/workflow-run-archives/downloads/5923ce20291444af45f0580fb49f1cc9/file/extra",],)-def test_whitelist_prefix_paths_still_require_csrf(path: str):+def test_whitelist_prefix_paths_still_require_csrf(path: str) -> None:request = cast(Request, MockRequest(headers={}, cookies={}, args={}, path=path))with pytest.raises(Unauthorized):token.check_csrf_token(request, "account-1")-def test_admin_api_key_header_bypasses_csrf_when_console_cookie_is_present(config_overrides):+def test_admin_api_key_header_bypasses_csrf_when_console_cookie_is_present(+ config_overrides: Callable[..., None],+) -> None:config_overrides(ADMIN_API_KEY_ENABLE=True,ADMIN_API_KEY="admin-key",diff --git a/api/tests/unit_tests/libs/test_validators.py b/api/tests/unit_tests/libs/test_validators.pyindex 962fb25b005..e27678d3dc4 100644--- a/api/tests/unit_tests/libs/test_validators.py+++ b/api/tests/unit_tests/libs/test_validators.py@@ -12,7 +12,7 @@ from tests.unit_tests.controllers.conftest import pipeline_application as pipeliclass TestDescriptionValidationUnit:"""Unit tests for the centralized description validation function."""- def test_validate_description_length_valid(self):+ def test_validate_description_length_valid(self) -> None:"""Test validation function with valid descriptions."""# Empty string should be validassert validate_description_length("") == ""@@ -32,7 +32,7 @@ class TestDescriptionValidationUnit:just_under = "x" * 399assert validate_description_length(just_under) == just_under- def test_validate_description_length_invalid(self):+ def test_validate_description_length_invalid(self) -> None:"""Test validation function with invalid descriptions."""# 401 characters should failjust_over = "x" * 401@@ -52,7 +52,7 @@ class TestDescriptionValidationUnit:validate_description_length(very_long)assert "Description cannot exceed 400 characters." in str(exc_info.value)- def test_boundary_values(self):+ def test_boundary_values(self) -> None:"""Test boundary values around the 400 character limit."""boundary_tests = [(0, True), # Empty@@ -75,7 +75,7 @@ class TestDescriptionValidationUnit:with pytest.raises(ValueError, match="Description cannot exceed 400 characters\\."):validate_description_length(test_desc)- def test_special_characters(self):+ def test_special_characters(self) -> None:"""Test validation with special characters, Unicode, etc."""# Unicode charactersunicode_desc = "测试描述" * 100 # Chinese characters@@ -95,7 +95,7 @@ class TestDescriptionValidationUnit:with pytest.raises(ValueError, match="Description cannot exceed 400 characters\\."):validate_description_length(mixed_desc)- def test_whitespace_handling(self):+ def test_whitespace_handling(self) -> None:"""Test validation with various whitespace scenarios."""# Leading/trailing whitespacewhitespace_desc = " Description with whitespace "diff --git a/api/tests/unit_tests/pyrefly.toml b/api/tests/unit_tests/pyrefly.tomlindex 730683f27ab..d4b8edd3487 100644--- a/api/tests/unit_tests/pyrefly.toml+++ b/api/tests/unit_tests/pyrefly.toml@@ -18,7 +18,6 @@ project-excludes = ["controllers/console/app/test_app.py","controllers/console/app/test_app_import.py","controllers/console/app/test_audio.py",- "libs/test_validators.py","controllers/console/app/test_generator.py","controllers/console/app/test_mcp_server.py","controllers/console/app/test_message.py",@@ -298,14 +297,8 @@ project-excludes = ["libs/broadcast_channel/redis/test_streams_channel.py","libs/test_archive_storage.py","libs/test_schedule_utils.py",- "libs/test_datetime_utils.py",- "libs/test_email_i18n.py","libs/test_external_api.py",- "libs/test_flask_utils.py",- "libs/test_helper.py",- "libs/test_login.py","../e2e_tests/contracts/libs/test_pandas.py",- "libs/test_token.py","migrations/versions/test_2025_07_02_2332-1c9ba48be8e4_add_uuidv7_function_in_sql.py","models/test_account.py","models/test_agent.py",