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 remaining libs unit tests (#44388)
Eddy ZHANG7baaf3f9179f
diff --git a/api/tests/unit_tests/.ruff.toml b/api/tests/unit_tests/.ruff.tomlindex bc2dc76e53b..978433b0006 100644--- a/api/tests/unit_tests/.ruff.toml+++ b/api/tests/unit_tests/.ruff.toml@@ -249,7 +249,6 @@ extend-select = ["ANN401", "ARG"]"libs/test_cron_compatibility.py" = ["S110"]"libs/test_email_i18n.py" = ["ANN401", "TID251"]"libs/test_schedule_utils_enhanced.py" = ["S110"]-"libs/test_sendgrid_client.py" = ["ARG001", "TID251"]"models/test_dataset_models.py" = ["ARG005"]"oss/__mock/aliyun_oss.py" = ["ARG002"]"oss/__mock/baidu_obs.py" = ["ARG002"]diff --git a/api/tests/unit_tests/libs/test_file_utils.py b/api/tests/unit_tests/libs/test_file_utils.pyindex b2abc0fafa8..0dab1c7c56d 100644--- a/api/tests/unit_tests/libs/test_file_utils.py+++ b/api/tests/unit_tests/libs/test_file_utils.py@@ -6,7 +6,7 @@ import pytestfrom libs.file_utils import search_file_upwards-def test_search_file_upwards_found_in_parent(tmp_path: Path):+def test_search_file_upwards_found_in_parent(tmp_path: Path) -> None:base = tmp_path / "a" / "b" / "c"base.mkdir(parents=True)@@ -17,7 +17,7 @@ def test_search_file_upwards_found_in_parent(tmp_path: Path):assert found == target-def test_search_file_upwards_found_in_current(tmp_path: Path):+def test_search_file_upwards_found_in_current(tmp_path: Path) -> None:base = tmp_path / "x"base.mkdir()target = base / "here.txt"@@ -27,7 +27,7 @@ def test_search_file_upwards_found_in_current(tmp_path: Path):assert found == target-def test_search_file_upwards_not_found_raises(tmp_path: Path):+def test_search_file_upwards_not_found_raises(tmp_path: Path) -> None:base = tmp_path / "m" / "n"base.mkdir(parents=True)with pytest.raises(@@ -43,7 +43,7 @@ def test_search_file_upwards_not_found_raises(tmp_path: Path):assert str(base) in msg-def test_search_file_upwards_root_breaks_and_raises():+def test_search_file_upwards_root_breaks_and_raises() -> None:# Using filesystem root triggers the 'break' branch (parent == current)with pytest.raises(ValueError,@@ -55,7 +55,7 @@ def test_search_file_upwards_root_breaks_and_raises():search_file_upwards(Path("/"), "__definitely_not_exists__.txt", max_search_parent_depth=1)-def test_search_file_upwards_depth_limit_raises(tmp_path: Path):+def test_search_file_upwards_depth_limit_raises(tmp_path: Path) -> None:base = tmp_path / "a" / "b" / "c"base.mkdir(parents=True)target = tmp_path / "a" / "target.txt"diff --git a/api/tests/unit_tests/libs/test_password.py b/api/tests/unit_tests/libs/test_password.pyindex 5cfaf73b4ee..6a2bc28cd7c 100644--- a/api/tests/unit_tests/libs/test_password.py+++ b/api/tests/unit_tests/libs/test_password.py@@ -13,13 +13,13 @@ from libs.password import compare_password, hash_password, valid_passwordclass TestValidPassword:"""Test password format validation"""- def test_should_accept_valid_passwords(self):+ def test_should_accept_valid_passwords(self) -> None:"""Test accepting valid password formats"""assert valid_password("password123") == "password123"assert valid_password("test1234") == "test1234"assert valid_password("Test123456") == "Test123456"- def test_should_reject_invalid_passwords(self):+ def test_should_reject_invalid_passwords(self) -> None:"""Test rejecting invalid password formats"""# Too shortwith pytest.raises(@@ -50,7 +50,7 @@ class TestValidPassword:):valid_password("")- def test_should_reject_password_shorter_than_minimum_length(self):+ def test_should_reject_password_shorter_than_minimum_length(self) -> None:"""A 7-character password with letters and numbers is rejected for length."""with pytest.raises(ValueError,@@ -64,7 +64,7 @@ class TestValidPassword:class TestPasswordHashing:"""Test password hashing and comparison"""- def setup_method(self):+ def setup_method(self) -> None:"""Setup test data"""self.password = "test123password"self.salt = os.urandom(16)@@ -73,17 +73,17 @@ class TestPasswordHashing:password_hash = hash_password(self.password, self.salt)self.password_hash_base64 = base64.b64encode(password_hash).decode()- def test_should_verify_correct_password(self):+ def test_should_verify_correct_password(self) -> None:"""Test correct password verification"""result = compare_password(self.password, self.password_hash_base64, self.salt_base64)assert result is True- def test_should_reject_wrong_password(self):+ def test_should_reject_wrong_password(self) -> None:"""Test rejection of incorrect passwords"""result = compare_password("wrongpassword", self.password_hash_base64, self.salt_base64)assert result is False- def test_should_handle_invalid_base64(self):+ def test_should_handle_invalid_base64(self) -> None:"""Test handling of invalid base64 data"""# Invalid base64 hashwith pytest.raises(binascii.Error):@@ -93,7 +93,7 @@ class TestPasswordHashing:with pytest.raises(binascii.Error):compare_password(self.password, self.password_hash_base64, "invalid_base64!")- def test_should_be_case_sensitive(self):+ def test_should_be_case_sensitive(self) -> None:"""Test password case sensitivity"""result = compare_password(self.password.upper(), self.password_hash_base64, self.salt_base64)assert result is False@@ -109,20 +109,20 @@ class TestPasswordPepper:def _encode(password_hash: bytes) -> str:return base64.b64encode(password_hash).decode()- def test_empty_pepper_keeps_legacy_hash(self, config_overrides: Callable[..., None]):+ def test_empty_pepper_keeps_legacy_hash(self, config_overrides: Callable[..., None]) -> None:config_overrides(PASSWORD_PEPPER="")legacy = binascii.hexlify(hashlib.pbkdf2_hmac("sha256", self.password.encode(), self.salt, 10000))assert hash_password(self.password, self.salt) == legacy- def test_pepper_wraps_legacy_digest(self, config_overrides: Callable[..., None]):+ def test_pepper_wraps_legacy_digest(self, config_overrides: Callable[..., None]) -> None:config_overrides(PASSWORD_PEPPER="pepper-a")legacy_digest = hashlib.pbkdf2_hmac("sha256", self.password.encode(), self.salt, 10000)expected = binascii.hexlify(hmac.new(b"pepper-a", legacy_digest, hashlib.sha256).digest())assert hash_password(self.password, self.salt) == expected- def test_peppered_hash_verifies_with_same_pepper(self, config_overrides: Callable[..., None]):+ def test_peppered_hash_verifies_with_same_pepper(self, config_overrides: Callable[..., None]) -> None:config_overrides(PASSWORD_PEPPER="pepper-a")password_hash = self._encode(hash_password(self.password, self.salt))@@ -132,7 +132,7 @@ class TestPasswordPepper:@pytest.mark.parametrize(("hash_pepper", "verify_pepper"), [("", "pepper-a"), ("pepper-a", ""), ("pepper-a", "b")])def test_changing_pepper_invalidates_existing_hash(self, config_overrides: Callable[..., None], hash_pepper: str, verify_pepper: str- ):+ ) -> None:config_overrides(PASSWORD_PEPPER=hash_pepper)password_hash = self._encode(hash_password(self.password, self.salt))diff --git a/api/tests/unit_tests/libs/test_sendgrid_client.py b/api/tests/unit_tests/libs/test_sendgrid_client.pyindex 05bcd7b01e1..18bd3bb02b0 100644--- a/api/tests/unit_tests/libs/test_sendgrid_client.py+++ b/api/tests/unit_tests/libs/test_sendgrid_client.py@@ -1,4 +1,4 @@-from typing import Any+from email.message import Messagefrom unittest.mock import MagicMock, patchimport pytest@@ -7,12 +7,12 @@ from python_http_client.exceptions import UnauthorizedErrorfrom libs.sendgrid import SendGridClient-def _mail(to: str = "[email protected]") -> dict[str, Any]:+def _mail(to: str = "[email protected]") -> dict[str, object]:return {"to": to, "subject": "Hi", "html": "<b>Hi</b>"}@patch("libs.sendgrid.sendgrid.SendGridAPIClient")-def test_sendgrid_success(mock_client_cls: MagicMock):+def test_sendgrid_success(mock_client_cls: MagicMock) -> None:mock_client = MagicMock()mock_client_cls.return_value = mock_client# nested attribute access: client.mail.send.post@@ -26,17 +26,18 @@ def test_sendgrid_success(mock_client_cls: MagicMock):@patch("libs.sendgrid.sendgrid.SendGridAPIClient")-def test_sendgrid_missing_to_raises(mock_client_cls: MagicMock):+def test_sendgrid_missing_to_raises(mock_client_cls: MagicMock) -> None:sg = SendGridClient(sendgrid_api_key="key", _from="[email protected]")with pytest.raises(ValueError, match="SendGridClient: Cannot send email: recipient address is missing\\."):sg.send(_mail(to=""))+ mock_client_cls.assert_not_called()@patch("libs.sendgrid.sendgrid.SendGridAPIClient")-def test_sendgrid_auth_errors_reraise(mock_client_cls: MagicMock):+def test_sendgrid_auth_errors_reraise(mock_client_cls: MagicMock) -> None:mock_client = MagicMock()mock_client_cls.return_value = mock_client- mock_client.client.mail.send.post.side_effect = UnauthorizedError(401, "Unauthorized", b"{}", {})+ mock_client.client.mail.send.post.side_effect = UnauthorizedError(401, "Unauthorized", b"{}", Message())sg = SendGridClient(sendgrid_api_key="key", _from="[email protected]")with pytest.raises(UnauthorizedError):@@ -44,7 +45,7 @@ def test_sendgrid_auth_errors_reraise(mock_client_cls: MagicMock):@patch("libs.sendgrid.sendgrid.SendGridAPIClient")-def test_sendgrid_timeout_reraise(mock_client_cls: MagicMock):+def test_sendgrid_timeout_reraise(mock_client_cls: MagicMock) -> None:mock_client = MagicMock()mock_client_cls.return_value = mock_clientmock_client.client.mail.send.post.side_effect = TimeoutError("timeout")diff --git a/api/tests/unit_tests/libs/test_time_parser.py b/api/tests/unit_tests/libs/test_time_parser.pyindex 8319cb1cc67..7e31119393c 100644--- a/api/tests/unit_tests/libs/test_time_parser.py+++ b/api/tests/unit_tests/libs/test_time_parser.py@@ -8,32 +8,32 @@ from libs.time_parser import get_time_threshold, parse_time_durationclass TestParseTimeDuration:"""Test parse_time_duration function."""- def test_parse_days(self):+ def test_parse_days(self) -> None:"""Test parsing days."""result = parse_time_duration("7d")assert result == timedelta(days=7)- def test_parse_hours(self):+ def test_parse_hours(self) -> None:"""Test parsing hours."""result = parse_time_duration("4h")assert result == timedelta(hours=4)- def test_parse_minutes(self):+ def test_parse_minutes(self) -> None:"""Test parsing minutes."""result = parse_time_duration("30m")assert result == timedelta(minutes=30)- def test_parse_seconds(self):+ def test_parse_seconds(self) -> None:"""Test parsing seconds."""result = parse_time_duration("30s")assert result == timedelta(seconds=30)- def test_parse_uppercase(self):+ def test_parse_uppercase(self) -> None:"""Test parsing uppercase units."""result = parse_time_duration("7D")assert result == timedelta(days=7)- def test_parse_invalid_format(self):+ def test_parse_invalid_format(self) -> None:"""Test parsing invalid format."""result = parse_time_duration("7days")assert result is None@@ -44,21 +44,21 @@ class TestParseTimeDuration:result = parse_time_duration("7")assert result is None- def test_parse_empty_string(self):+ def test_parse_empty_string(self) -> None:"""Test parsing empty string."""result = parse_time_duration("")assert result is None- def test_parse_none(self):+ def test_parse_none(self) -> None:"""Test parsing None."""- result = parse_time_duration(None)+ result = parse_time_duration(None) # pyrefly: ignore[bad-argument-type]assert result is Noneclass TestGetTimeThreshold:"""Test get_time_threshold function."""- def test_get_threshold_days(self):+ def test_get_threshold_days(self) -> None:"""Test getting threshold for days."""before = datetime.now(UTC)result = get_time_threshold("7d")@@ -69,7 +69,7 @@ class TestGetTimeThreshold:# Allow 1 second tolerance for test execution timeassert abs((result - expected).total_seconds()) < 1- def test_get_threshold_hours(self):+ def test_get_threshold_hours(self) -> None:"""Test getting threshold for hours."""before = datetime.now(UTC)result = get_time_threshold("4h")@@ -78,12 +78,12 @@ class TestGetTimeThreshold:expected = before - timedelta(hours=4)assert abs((result - expected).total_seconds()) < 1- def test_get_threshold_invalid(self):+ def test_get_threshold_invalid(self) -> None:"""Test getting threshold with invalid duration."""result = get_time_threshold("invalid")assert result is None- def test_get_threshold_none(self):+ def test_get_threshold_none(self) -> None:"""Test getting threshold with None."""result = get_time_threshold(None)assert result is Nonediff --git a/api/tests/unit_tests/libs/test_uuid_utils.py b/api/tests/unit_tests/libs/test_uuid_utils.pyindex 688d4663638..c715f02598a 100644--- a/api/tests/unit_tests/libs/test_uuid_utils.py+++ b/api/tests/unit_tests/libs/test_uuid_utils.py@@ -11,7 +11,7 @@ from libs.uuid_utils import _create_uuidv7_bytes, uuidv7, uuidv7_boundary, uuidv# Tests for private helper function _create_uuidv7_bytes-def test_create_uuidv7_bytes_basic_structure():+def test_create_uuidv7_bytes_basic_structure() -> None:"""Test basic byte structure creation."""timestamp_ms = 1609459200000 # 2021-01-01 00:00:00 UTC in millisecondsrandom_bytes = b"\x12\x34\x56\x78\x9a\xbc\xde\xf0\x11\x22"@@ -27,7 +27,7 @@ def test_create_uuidv7_bytes_basic_structure():assert uuid_obj.version == 7-def test_create_uuidv7_bytes_timestamp_encoding():+def test_create_uuidv7_bytes_timestamp_encoding() -> None:"""Test timestamp is correctly encoded in first 48 bits."""timestamp_ms = 1609459200000 # 2021-01-01 00:00:00 UTC in millisecondsrandom_bytes = b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"@@ -41,7 +41,7 @@ def test_create_uuidv7_bytes_timestamp_encoding():assert extracted_timestamp == timestamp_ms-def test_create_uuidv7_bytes_version_bits():+def test_create_uuidv7_bytes_version_bits() -> None:"""Test version bits are set to 7."""timestamp_ms = 1609459200000random_bytes = b"\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00" # Set first 2 bytes to all 1s@@ -55,7 +55,7 @@ def test_create_uuidv7_bytes_version_bits():assert version == 7-def test_create_uuidv7_bytes_variant_bits():+def test_create_uuidv7_bytes_variant_bits() -> None:"""Test variant bits are set correctly."""timestamp_ms = 1609459200000random_bytes = b"\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00" # Set byte 8 to all 1s@@ -69,7 +69,7 @@ def test_create_uuidv7_bytes_variant_bits():assert variant_bits == 0b10 # Should be binary 10-def test_create_uuidv7_bytes_random_data():+def test_create_uuidv7_bytes_random_data() -> None:"""Test random bytes are placed correctly."""timestamp_ms = 1609459200000random_bytes = b"\x12\x34\x56\x78\x9a\xbc\xde\xf0\x11\x22"@@ -91,7 +91,7 @@ def test_create_uuidv7_bytes_random_data():assert result[9:16] == random_bytes[3:10]-def test_create_uuidv7_bytes_zero_random():+def test_create_uuidv7_bytes_zero_random() -> None:"""Test with zero random bytes (boundary case)."""timestamp_ms = 1609459200000zero_random_bytes = b"\x00" * 10@@ -113,7 +113,7 @@ def test_create_uuidv7_bytes_zero_random():assert result[9:16] == b"\x00" * 7-def test_uuidv7_basic_generation():+def test_uuidv7_basic_generation() -> None:"""Test basic UUID generation produces valid UUIDv7."""result = uuidv7()@@ -129,7 +129,7 @@ def test_uuidv7_basic_generation():assert (variant_byte >> 6) == 0b10-def test_uuidv7_with_custom_timestamp():+def test_uuidv7_with_custom_timestamp() -> None:"""Test UUID generation with custom timestamp."""custom_timestamp = 1609459200000 # 2021-01-01 00:00:00 UTC in millisecondsresult = uuidv7(custom_timestamp)@@ -143,7 +143,7 @@ def test_uuidv7_with_custom_timestamp():assert extracted_timestamp == custom_timestamp # Exact match for integer milliseconds-def test_uuidv7_with_none_timestamp(monkeypatch: pytest.MonkeyPatch):+def test_uuidv7_with_none_timestamp(monkeypatch: pytest.MonkeyPatch) -> None:"""Test UUID generation with None timestamp uses current time."""mock_time = 1609459200mock_time_func = mock.Mock(return_value=mock_time)@@ -159,7 +159,7 @@ def test_uuidv7_with_none_timestamp(monkeypatch: pytest.MonkeyPatch):assert extracted_timestamp == mock_time * 1000 # 1609459200.0 * 1000-def test_uuidv7_time_ordering():+def test_uuidv7_time_ordering() -> None:"""Test that sequential UUIDs have increasing timestamps."""# Generate UUIDs with incrementing timestamps (in milliseconds)timestamp1 = 1609459200000 # 2021-01-01 00:00:00 UTC@@ -184,7 +184,7 @@ def test_uuidv7_time_ordering():assert uuid_strings == sorted(uuid_strings)-def test_uuidv7_uniqueness():+def test_uuidv7_uniqueness() -> None:"""Test that multiple calls generate different UUIDs."""# Generate multiple UUIDs with the same timestamp (in milliseconds)timestamp = 1609459200000@@ -199,7 +199,7 @@ def test_uuidv7_uniqueness():assert extracted_ts == timestamp-def test_uuidv7_timestamp_error_handling_wrong_version():+def test_uuidv7_timestamp_error_handling_wrong_version() -> None:"""Test error handling for non-UUIDv7 inputs."""uuid_v4 = uuid.uuid4()@@ -210,7 +210,7 @@ def test_uuidv7_timestamp_error_handling_wrong_version():@given(st.integers(max_value=2**48 - 1, min_value=0))-def test_uuidv7_timestamp_round_trip(timestamp_ms):+def test_uuidv7_timestamp_round_trip(timestamp_ms: int) -> None:# Generate UUID with timestampuuid_obj = uuidv7(timestamp_ms)@@ -221,7 +221,7 @@ def test_uuidv7_timestamp_round_trip(timestamp_ms):assert extracted_timestamp == timestamp_ms-def test_uuidv7_timestamp_edge_cases():+def test_uuidv7_timestamp_edge_cases() -> None:"""Test timestamp extraction with edge case values."""# Test with very small timestampsmall_timestamp = 1 # 1ms after epoch@@ -236,7 +236,7 @@ def test_uuidv7_timestamp_edge_cases():assert extracted_large == large_timestamp-def test_uuidv7_boundary_basic_generation():+def test_uuidv7_boundary_basic_generation() -> None:"""Test basic boundary UUID generation with a known timestamp."""timestamp = 1609459200000 # 2021-01-01 00:00:00 UTC in millisecondsresult = uuidv7_boundary(timestamp)@@ -253,7 +253,7 @@ def test_uuidv7_boundary_basic_generation():assert (variant_byte >> 6) == 0b10-def test_uuidv7_boundary_timestamp_extraction():+def test_uuidv7_boundary_timestamp_extraction() -> None:"""Test that boundary UUID timestamp can be extracted correctly."""timestamp = 1609459200000 # 2021-01-01 00:00:00 UTC in millisecondsboundary_uuid = uuidv7_boundary(timestamp)@@ -265,7 +265,7 @@ def test_uuidv7_boundary_timestamp_extraction():assert extracted_timestamp == timestamp-def test_uuidv7_boundary_deterministic():+def test_uuidv7_boundary_deterministic() -> None:"""Test that boundary UUIDs are deterministic for same timestamp."""timestamp = 1609459200000 # 2021-01-01 00:00:00 UTC in milliseconds@@ -279,7 +279,7 @@ def test_uuidv7_boundary_deterministic():assert str(uuid1) == str(uuid2) == str(uuid3)-def test_uuidv7_boundary_is_minimum():+def test_uuidv7_boundary_is_minimum() -> None:"""Test that boundary UUID is lexicographically smaller than regular UUIDs."""timestamp = 1609459200000 # 2021-01-01 00:00:00 UTC in milliseconds@@ -302,7 +302,7 @@ def test_uuidv7_boundary_is_minimum():assert boundary_bytes < regular_bytes-def test_uuidv7_boundary_different_timestamps():+def test_uuidv7_boundary_different_timestamps() -> None:"""Test that boundary UUIDs with different timestamps are ordered correctly."""timestamp1 = 1609459200000 # 2021-01-01 00:00:00 UTCtimestamp2 = 1609459201000 # 2021-01-01 00:00:01 UTC@@ -328,7 +328,7 @@ def test_uuidv7_boundary_different_timestamps():assert uuid1.bytes < uuid2.bytes < uuid3.bytes-def test_uuidv7_boundary_edge_cases():+def test_uuidv7_boundary_edge_cases() -> None:"""Test boundary UUID generation with edge case timestamp values."""# Test with timestamp 0 (Unix epoch)epoch_uuid = uuidv7_boundary(0)diff --git a/api/tests/unit_tests/libs/test_yarl.py b/api/tests/unit_tests/libs/test_yarl.pyindex 7bb98fb35cc..03ab6168653 100644--- a/api/tests/unit_tests/libs/test_yarl.py+++ b/api/tests/unit_tests/libs/test_yarl.py@@ -2,7 +2,7 @@ import pytestfrom yarl import URL-def test_yarl_urls():+def test_yarl_urls() -> None:expected_1 = "https://dify.ai/api"assert str(URL("https://dify.ai") / "api") == expected_1assert str(URL("https://dify.ai/") / "api") == expected_1diff --git a/api/tests/unit_tests/pyrefly.toml b/api/tests/unit_tests/pyrefly.tomlindex daf7db1444f..652fefbadf5 100644--- a/api/tests/unit_tests/pyrefly.toml+++ b/api/tests/unit_tests/pyrefly.toml@@ -475,7 +475,6 @@ project-excludes = ["libs/test_datetime_utils.py","libs/test_email_i18n.py","libs/test_external_api.py",- "libs/test_file_utils.py","libs/test_flask_utils.py","libs/test_helper.py","libs/test_json_in_md_parser.py",@@ -484,14 +483,9 @@ project-excludes = ["libs/test_orjson.py","libs/test_pagination.py","libs/test_pandas.py",- "libs/test_password.py","libs/test_rate_limiter.py","libs/test_schedule_utils_enhanced.py",- "libs/test_sendgrid_client.py",- "libs/test_time_parser.py","libs/test_token.py",- "libs/test_uuid_utils.py",- "libs/test_yarl.py","migrations/test_uuidv7_pg18_migration.py","models/test_account_models.py","models/test_agent.py",