Skip to content

armgit / dify

Public Imported from GitHub
0

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

refactor(api): enable strict typing for top-level services tests (#43989)

Eddy ZHANG9a3deb80bf6c
diff --git a/api/tests/unit_tests/pyrefly.toml b/api/tests/unit_tests/pyrefly.toml
index 8be9641554d..58ea246b6f6 100644
--- a/api/tests/unit_tests/pyrefly.toml
+++ b/api/tests/unit_tests/pyrefly.toml
@@ -603,41 +603,29 @@ project-excludes = [
"services/test_api_token_service.py",
"services/test_app_generate_service.py",
"services/test_app_generate_service_streaming_integration.py",
- "services/test_app_model_config_service.py",
"services/test_app_service.py",
"services/test_app_task_service.py",
- "services/test_archive_workflow_run_logs.py",
"services/test_async_workflow_service.py",
"services/test_audio_service.py",
"services/test_billing_service.py",
"services/test_clear_free_plan_expired_workflow_run_logs.py",
"services/test_clear_free_plan_tenant_expired_logs.py",
- "services/test_code_based_extension_service.py",
"services/test_conversation_service.py",
"services/test_credit_pool_service.py",
"services/test_dataset_service_dataset.py",
"services/test_dataset_service_document.py",
- "services/test_dataset_service_lock_not_owned.py",
"services/test_dataset_service_segment.py",
"services/test_datasource_provider_service.py",
- "services/test_document_indexing_task_proxy.py",
- "services/test_duplicate_document_indexing_task_proxy.py",
"services/test_export_app_messages.py",
"services/test_external_dataset_service.py",
- "services/test_feature_service_human_input_email_delivery.py",
- "services/test_feature_service_vector_space.py",
"services/test_file_service.py",
"services/test_human_input_delivery_test_service.py",
"services/test_human_input_file_upload_service.py",
"services/test_knowledge_retrieval_inner_service.py",
"services/test_message_service.py",
"services/test_messages_clean_service.py",
- "services/test_metadata_nullable_bug.py",
"services/test_metadata_service_session_boundary.py",
- "services/test_model_load_balancing_service.py",
"services/test_model_provider_service.py",
- "services/test_model_provider_service_sanitization.py",
- "services/test_oauth_device_flow.py",
"services/test_operation_service.py",
"services/test_rag_pipeline_task_proxy.py",
"services/test_schedule_service.py",
diff --git a/api/tests/unit_tests/services/test_app_model_config_service.py b/api/tests/unit_tests/services/test_app_model_config_service.py
index 3d1d3c995c2..c424755c57a 100644
--- a/api/tests/unit_tests/services/test_app_model_config_service.py
+++ b/api/tests/unit_tests/services/test_app_model_config_service.py
@@ -1,4 +1,5 @@
-from unittest.mock import patch
+from collections.abc import Iterator
+from unittest.mock import MagicMock, patch
import pytest
from sqlalchemy.orm import Session
@@ -8,7 +9,7 @@ from services.app_model_config_service import AppModelConfigService
@pytest.fixture
-def mock_config_managers():
+def mock_config_managers() -> Iterator[dict[str, MagicMock]]:
"""Fixture that patches all app config manager validate methods.
Returns a dictionary containing the mocked config_validate methods for each manager.
@@ -41,8 +42,12 @@ class TestAppModelConfigService:
],
)
def test_should_route_validation_to_correct_manager_based_on_app_mode(
- self, app_mode, selected_manager, mock_config_managers, unbound_session: Session
- ):
+ self,
+ app_mode: AppMode,
+ selected_manager: str,
+ mock_config_managers: dict[str, MagicMock],
+ unbound_session: Session,
+ ) -> None:
"""Test configuration validation is delegated to the expected manager for each supported app mode."""
tenant_id = "tenant-123"
config = {"temperature": 0.5}
@@ -71,8 +76,8 @@ class TestAppModelConfigService:
mock_agent_validate.assert_not_called()
def test_should_raise_value_error_when_app_mode_is_not_supported(
- self, mock_config_managers, unbound_session: Session
- ):
+ self, mock_config_managers: dict[str, MagicMock], unbound_session: Session
+ ) -> None:
"""Test unsupported app modes raise ValueError with the invalid mode in the message."""
tenant_id = "tenant-123"
config = {"temperature": 0.5}
diff --git a/api/tests/unit_tests/services/test_archive_workflow_run_logs.py b/api/tests/unit_tests/services/test_archive_workflow_run_logs.py
index bf54be40405..ab6c23e16c3 100644
--- a/api/tests/unit_tests/services/test_archive_workflow_run_logs.py
+++ b/api/tests/unit_tests/services/test_archive_workflow_run_logs.py
@@ -6,6 +6,7 @@ This module contains tests for:
- Rollback service
"""
+from collections.abc import Callable
from datetime import datetime
from unittest.mock import MagicMock, patch
@@ -16,7 +17,7 @@ class TestWorkflowRunArchiver:
"""Tests for the WorkflowRunArchiver class."""
@patch("services.retention.workflow_run.archive_paid_plan_workflow_run.get_archive_storage", autospec=True)
- def test_archiver_initialization(self, mock_get_storage, config_overrides):
+ def test_archiver_initialization(self, mock_get_storage: MagicMock, config_overrides: Callable[..., None]) -> None:
"""Test archiver can be initialized with various options."""
from services.retention.workflow_run.archive_paid_plan_workflow_run import WorkflowRunArchiver
@@ -36,7 +37,7 @@ class TestWorkflowRunArchiver:
assert archiver.limit == 50
assert archiver.dry_run is True
- def test_get_bundle_manifest_key(self):
+ def test_get_bundle_manifest_key(self) -> None:
"""Test V2 bundle manifest key generation."""
from services.retention.workflow_run.archive_paid_plan_workflow_run import WorkflowRunArchiver
diff --git a/api/tests/unit_tests/services/test_code_based_extension_service.py b/api/tests/unit_tests/services/test_code_based_extension_service.py
index f6538a140aa..cd849bd8d52 100644
--- a/api/tests/unit_tests/services/test_code_based_extension_service.py
+++ b/api/tests/unit_tests/services/test_code_based_extension_service.py
@@ -7,7 +7,9 @@ from services.code_based_extension_service import CodeBasedExtensionService
class TestCodeBasedExtensionService:
- def test_should_return_only_non_builtin_extensions_with_public_fields(self, monkeypatch: pytest.MonkeyPatch):
+ def test_should_return_only_non_builtin_extensions_with_public_fields(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
"""Test service returns only non-builtin extensions with name/label/form_schema fields."""
moderation_extension = SimpleNamespace(
name="custom-moderation",
@@ -56,7 +58,7 @@ class TestCodeBasedExtensionService:
assert set(result[0].keys()) == {"name", "label", "form_schema"}
module_extensions_mock.assert_called_once_with("external_data_tool")
- def test_should_return_empty_list_when_all_extensions_are_builtin(self, monkeypatch: pytest.MonkeyPatch):
+ def test_should_return_empty_list_when_all_extensions_are_builtin(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""Test builtin extensions are filtered out completely."""
builtin_extension = SimpleNamespace(
name="builtin-moderation",
@@ -75,7 +77,7 @@ class TestCodeBasedExtensionService:
assert result == []
module_extensions_mock.assert_called_once_with("moderation")
- def test_should_propagate_error_when_module_extensions_lookup_fails(self, monkeypatch: pytest.MonkeyPatch):
+ def test_should_propagate_error_when_module_extensions_lookup_fails(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""Test ValueError from extension lookup bubbles up unchanged."""
module_extensions_mock = MagicMock(side_effect=ValueError("Extension Module invalid-module not found"))
monkeypatch.setattr(
diff --git a/api/tests/unit_tests/services/test_dataset_service_lock_not_owned.py b/api/tests/unit_tests/services/test_dataset_service_lock_not_owned.py
index d7236393504..0b0f8355051 100644
--- a/api/tests/unit_tests/services/test_dataset_service_lock_not_owned.py
+++ b/api/tests/unit_tests/services/test_dataset_service_lock_not_owned.py
@@ -11,6 +11,7 @@ from models.account import Account, Tenant
from models.dataset import Dataset, DatasetProcessRule, Document, DocumentSegment
from models.enums import ProcessRuleMode
from services.knowledge.dataset_service import DocumentService, SegmentService
+from services.knowledge.entities.knowledge_entities import DataSource, InfoList, KnowledgeConfig
from services.knowledge.segments.application import SegmentMutationService
TENANT_ID = "11111111-1111-1111-1111-111111111111"
@@ -22,16 +23,18 @@ DOCUMENT_ID = "44444444-4444-4444-4444-444444444444"
class FakeLock:
"""Lock that always fails on enter with LockNotOwnedError."""
- def __enter__(self):
+ def __enter__(self) -> None:
raise LockNotOwnedError("simulated")
- def __exit__(self, exc_type, exc, tb):
+ def __exit__(
+ self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None
+ ) -> bool:
# Normal contextmanager signature; return False so exceptions propagate
return False
@pytest.fixture
-def fake_current_user(monkeypatch: pytest.MonkeyPatch):
+def fake_current_user(monkeypatch: pytest.MonkeyPatch) -> Account:
tenant = Tenant(name="Test Tenant")
tenant.id = TENANT_ID
user = Account(name="Test User", email="[email protected]")
@@ -42,7 +45,7 @@ def fake_current_user(monkeypatch: pytest.MonkeyPatch):
@pytest.fixture
-def fake_features(monkeypatch: pytest.MonkeyPatch):
+def fake_features(monkeypatch: pytest.MonkeyPatch) -> types.SimpleNamespace:
features = types.SimpleNamespace(
billing=types.SimpleNamespace(subscription=types.SimpleNamespace(plan="ENTERPRISE")),
documents_upload_quota=types.SimpleNamespace(limit=10_000, size=0),
@@ -55,10 +58,10 @@ def fake_features(monkeypatch: pytest.MonkeyPatch):
@pytest.fixture
-def fake_lock(monkeypatch: pytest.MonkeyPatch):
+def fake_lock(monkeypatch: pytest.MonkeyPatch) -> None:
"""Patch redis_client.lock to always raise LockNotOwnedError on enter."""
- def _fake_lock(name, timeout=None, *args, **kwargs):
+ def _fake_lock(name: str, timeout: float | None = None, *args: object, **kwargs: object) -> FakeLock:
return FakeLock()
# DatasetService imports redis_client directly from extensions.ext_redis
@@ -73,11 +76,11 @@ def fake_lock(monkeypatch: pytest.MonkeyPatch):
@pytest.mark.parametrize("sqlite_session", [(Account, Tenant, Dataset, DatasetProcessRule, Document)], indirect=True)
def test_save_document_with_dataset_id_ignores_lock_not_owned(
monkeypatch: pytest.MonkeyPatch,
- fake_current_user,
- fake_features,
- fake_lock,
+ fake_current_user: Account,
+ fake_features: types.SimpleNamespace,
+ fake_lock: None,
sqlite_session: Session,
-):
+) -> None:
# Arrange
dataset = Dataset(
id=DATASET_ID,
@@ -97,18 +100,11 @@ def test_save_document_with_dataset_id_ignores_lock_not_owned(
sqlite_session.add_all([fake_current_user._current_tenant, fake_current_user, dataset, process_rule])
sqlite_session.commit()
- # Minimal knowledge_config stub that satisfies pre-lock code
- info_list = types.SimpleNamespace(data_source_type="upload_file")
- data_source = types.SimpleNamespace(info_list=info_list)
- knowledge_config = types.SimpleNamespace(
+ knowledge_config = KnowledgeConfig(
doc_form=IndexStructureType.QA_INDEX,
original_document_id=None, # go into "new document" branch
- data_source=data_source,
- indexing_technique=IndexTechniqueType.HIGH_QUALITY,
- embedding_model=None,
- embedding_model_provider=None,
- retrieval_model=None,
- process_rule=None,
+ data_source=DataSource(info_list=InfoList(data_source_type="upload_file")),
+ indexing_technique="high_quality",
duplicate=False,
doc_language="en",
)
@@ -152,10 +148,10 @@ def test_save_document_with_dataset_id_ignores_lock_not_owned(
@pytest.mark.parametrize("sqlite_session", [(Account, Tenant, Dataset, Document, DocumentSegment)], indirect=True)
def test_multi_create_segment_ignores_lock_not_owned(
monkeypatch: pytest.MonkeyPatch,
- fake_current_user,
- fake_lock,
+ fake_current_user: Account,
+ fake_lock: None,
sqlite_session: Session,
-):
+) -> None:
# Arrange
dataset = Dataset(
id=DATASET_ID,
diff --git a/api/tests/unit_tests/services/test_document_indexing_task_proxy.py b/api/tests/unit_tests/services/test_document_indexing_task_proxy.py
index f92d59181b1..b3c9bb019f2 100644
--- a/api/tests/unit_tests/services/test_document_indexing_task_proxy.py
+++ b/api/tests/unit_tests/services/test_document_indexing_task_proxy.py
@@ -33,7 +33,7 @@ class DocumentIndexingTaskProxyTestDataFactory:
class TestDocumentIndexingTaskProxy:
"""Test cases for DocumentIndexingTaskProxy class."""
- def test_initialization(self):
+ def test_initialization(self) -> None:
"""Test DocumentIndexingTaskProxy initialization."""
# Arrange
tenant_id = "tenant-123"
@@ -52,7 +52,7 @@ class TestDocumentIndexingTaskProxy:
assert proxy._tenant_isolated_task_queue._unique_key == "document_indexing"
@patch("services.document_indexing_proxy.base.FeatureService")
- def test_features_property(self, mock_feature_service):
+ def test_features_property(self, mock_feature_service: MagicMock) -> None:
"""Test cached_property features."""
# Arrange
mock_features = DocumentIndexingTaskProxyTestDataFactory.create_mock_features()
@@ -70,7 +70,7 @@ class TestDocumentIndexingTaskProxy:
mock_feature_service.get_features.assert_called_once_with("tenant-123", exclude_vector_space=True)
@patch("services.document_indexing_proxy.document_indexing_task_proxy.normal_document_indexing_task")
- def test_send_to_direct_queue(self, mock_task):
+ def test_send_to_direct_queue(self, mock_task: MagicMock) -> None:
"""Test _send_to_direct_queue method."""
# Arrange
proxy = DocumentIndexingTaskProxyTestDataFactory.create_document_task_proxy()
@@ -85,7 +85,9 @@ class TestDocumentIndexingTaskProxy:
)
@patch("services.document_indexing_proxy.document_indexing_task_proxy.normal_document_indexing_task")
- def test_send_to_tenant_queue_with_existing_task_key(self, mock_task, tenant_queue_commands: MagicMock):
+ def test_send_to_tenant_queue_with_existing_task_key(
+ self, mock_task: MagicMock, tenant_queue_commands: MagicMock
+ ) -> None:
"""Test _send_to_tenant_queue when task key exists."""
# Arrange
proxy = DocumentIndexingTaskProxyTestDataFactory.create_document_task_proxy()
@@ -108,7 +110,9 @@ class TestDocumentIndexingTaskProxy:
mock_task.delay.assert_not_called()
@patch("services.document_indexing_proxy.document_indexing_task_proxy.normal_document_indexing_task")
- def test_send_to_tenant_queue_without_task_key(self, mock_task, tenant_queue_commands: MagicMock):
+ def test_send_to_tenant_queue_without_task_key(
+ self, mock_task: MagicMock, tenant_queue_commands: MagicMock
+ ) -> None:
"""Test _send_to_tenant_queue when no task key exists."""
# Arrange
proxy = DocumentIndexingTaskProxyTestDataFactory.create_document_task_proxy()
@@ -132,7 +136,7 @@ class TestDocumentIndexingTaskProxy:
)
assert all(entry.args[0] != "LPUSH" for entry in tenant_queue_commands.call_args_list)
- def test_send_to_default_tenant_queue(self):
+ def test_send_to_default_tenant_queue(self) -> None:
"""Test _send_to_default_tenant_queue method."""
# Arrange
proxy = DocumentIndexingTaskProxyTestDataFactory.create_document_task_proxy()
@@ -144,7 +148,7 @@ class TestDocumentIndexingTaskProxy:
# Assert
proxy._send_to_tenant_queue.assert_called_once_with(proxy.NORMAL_TASK_FUNC)
- def test_send_to_priority_tenant_queue(self):
+ def test_send_to_priority_tenant_queue(self) -> None:
"""Test _send_to_priority_tenant_queue method."""
# Arrange
proxy = DocumentIndexingTaskProxyTestDataFactory.create_document_task_proxy()
@@ -156,7 +160,7 @@ class TestDocumentIndexingTaskProxy:
# Assert
proxy._send_to_tenant_queue.assert_called_once_with(proxy.PRIORITY_TASK_FUNC)
- def test_send_to_priority_direct_queue(self):
+ def test_send_to_priority_direct_queue(self) -> None:
"""Test _send_to_priority_direct_queue method."""
# Arrange
proxy = DocumentIndexingTaskProxyTestDataFactory.create_document_task_proxy()
@@ -170,7 +174,7 @@ class TestDocumentIndexingTaskProxy:
@config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
@patch("services.document_indexing_proxy.base.FeatureService")
- def test_dispatch_with_cloud_sandbox_plan(self, mock_feature_service):
+ def test_dispatch_with_cloud_sandbox_plan(self, mock_feature_service: MagicMock) -> None:
"""Test _dispatch method in Cloud with Sandbox plan."""
# Arrange
mock_features = DocumentIndexingTaskProxyTestDataFactory.create_mock_features(plan=CloudPlan.SANDBOX)
@@ -186,7 +190,7 @@ class TestDocumentIndexingTaskProxy:
@config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
@patch("services.document_indexing_proxy.base.FeatureService")
- def test_dispatch_with_cloud_paid_plan(self, mock_feature_service):
+ def test_dispatch_with_cloud_paid_plan(self, mock_feature_service: MagicMock) -> None:
"""Test _dispatch method in Cloud with a paid plan."""
# Arrange
mock_features = DocumentIndexingTaskProxyTestDataFactory.create_mock_features(plan=CloudPlan.TEAM)
@@ -202,7 +206,7 @@ class TestDocumentIndexingTaskProxy:
@config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
@patch("services.document_indexing_proxy.base.FeatureService")
- def test_dispatch_outside_cloud(self, mock_feature_service):
+ def test_dispatch_outside_cloud(self, mock_feature_service: MagicMock) -> None:
"""Test _dispatch method outside Cloud."""
# Arrange
mock_features = DocumentIndexingTaskProxyTestDataFactory.create_mock_features()
@@ -218,7 +222,7 @@ class TestDocumentIndexingTaskProxy:
@config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
@patch("services.document_indexing_proxy.base.FeatureService")
- def test_delay_method(self, mock_feature_service):
+ def test_delay_method(self, mock_feature_service: MagicMock) -> None:
"""Test delay method integration."""
# Arrange
mock_features = DocumentIndexingTaskProxyTestDataFactory.create_mock_features(plan=CloudPlan.SANDBOX)
@@ -233,7 +237,7 @@ class TestDocumentIndexingTaskProxy:
# If billing enabled with sandbox plan, should send to default tenant queue
proxy._send_to_default_tenant_queue.assert_called_once()
- def test_document_task_dataclass(self):
+ def test_document_task_dataclass(self) -> None:
"""Test DocumentTask dataclass."""
# Arrange
tenant_id = "tenant-123"
@@ -250,7 +254,7 @@ class TestDocumentIndexingTaskProxy:
@config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
@patch("services.document_indexing_proxy.base.FeatureService")
- def test_dispatch_edge_case_empty_plan(self, mock_feature_service):
+ def test_dispatch_edge_case_empty_plan(self, mock_feature_service: MagicMock) -> None:
"""Test _dispatch method with empty plan string."""
# Arrange
mock_features = DocumentIndexingTaskProxyTestDataFactory.create_mock_features(plan="")
@@ -266,7 +270,7 @@ class TestDocumentIndexingTaskProxy:
@config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
@patch("services.document_indexing_proxy.base.FeatureService")
- def test_dispatch_edge_case_none_plan(self, mock_feature_service):
+ def test_dispatch_edge_case_none_plan(self, mock_feature_service: MagicMock) -> None:
"""Test _dispatch method with None plan."""
# Arrange
mock_features = DocumentIndexingTaskProxyTestDataFactory.create_mock_features(plan=None)
@@ -280,7 +284,7 @@ class TestDocumentIndexingTaskProxy:
# Assert
proxy._send_to_priority_tenant_queue.assert_called_once()
- def test_initialization_with_empty_document_ids(self):
+ def test_initialization_with_empty_document_ids(self) -> None:
"""Test initialization with empty document_ids list."""
# Arrange
tenant_id = "tenant-123"
@@ -295,7 +299,7 @@ class TestDocumentIndexingTaskProxy:
assert proxy._dataset_id == dataset_id
assert proxy._document_ids == document_ids
- def test_initialization_with_single_document_id(self):
+ def test_initialization_with_single_document_id(self) -> None:
"""Test initialization with single document_id."""
# Arrange
tenant_id = "tenant-123"
diff --git a/api/tests/unit_tests/services/test_duplicate_document_indexing_task_proxy.py b/api/tests/unit_tests/services/test_duplicate_document_indexing_task_proxy.py
index 64077459cf6..c3a8979c19d 100644
--- a/api/tests/unit_tests/services/test_duplicate_document_indexing_task_proxy.py
+++ b/api/tests/unit_tests/services/test_duplicate_document_indexing_task_proxy.py
@@ -35,7 +35,7 @@ class DuplicateDocumentIndexingTaskProxyTestDataFactory:
class TestDuplicateDocumentIndexingTaskProxy:
"""Test cases for DuplicateDocumentIndexingTaskProxy class."""
- def test_initialization(self):
+ def test_initialization(self) -> None:
"""Test DuplicateDocumentIndexingTaskProxy initialization."""
# Arrange
tenant_id = "tenant-123"
@@ -53,7 +53,7 @@ class TestDuplicateDocumentIndexingTaskProxy:
assert proxy._tenant_isolated_task_queue._tenant_id == tenant_id
assert proxy._tenant_isolated_task_queue._unique_key == "duplicate_document_indexing"
- def test_queue_name(self):
+ def test_queue_name(self) -> None:
"""Test QUEUE_NAME class variable."""
# Arrange & Act
proxy = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_duplicate_document_task_proxy()
@@ -61,7 +61,7 @@ class TestDuplicateDocumentIndexingTaskProxy:
# Assert
assert proxy.QUEUE_NAME == "duplicate_document_indexing"
- def test_task_functions(self):
+ def test_task_functions(self) -> None:
"""Test NORMAL_TASK_FUNC and PRIORITY_TASK_FUNC class variables."""
# Arrange & Act
proxy = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_duplicate_document_task_proxy()
@@ -71,7 +71,7 @@ class TestDuplicateDocumentIndexingTaskProxy:
assert proxy.PRIORITY_TASK_FUNC.__name__ == "priority_duplicate_document_indexing_task"
@patch("services.document_indexing_proxy.base.FeatureService")
- def test_features_property(self, mock_feature_service):
+ def test_features_property(self, mock_feature_service: MagicMock) -> None:
"""Test cached_property features."""
# Arrange
mock_features = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_mock_features()
@@ -91,7 +91,7 @@ class TestDuplicateDocumentIndexingTaskProxy:
@patch(
"services.document_indexing_proxy.duplicate_document_indexing_task_proxy.normal_duplicate_document_indexing_task"
)
- def test_send_to_direct_queue(self, mock_task):
+ def test_send_to_direct_queue(self, mock_task: MagicMock) -> None:
"""Test _send_to_direct_queue method."""
# Arrange
proxy = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_duplicate_document_task_proxy()
@@ -108,7 +108,9 @@ class TestDuplicateDocumentIndexingTaskProxy:
@patch(
"services.document_indexing_proxy.duplicate_document_indexing_task_proxy.normal_duplicate_document_indexing_task"
)
- def test_send_to_tenant_queue_with_existing_task_key(self, mock_task, tenant_queue_commands: MagicMock):
+ def test_send_to_tenant_queue_with_existing_task_key(
+ self, mock_task: MagicMock, tenant_queue_commands: MagicMock
+ ) -> None:
"""Test _send_to_tenant_queue when task key exists."""
# Arrange
proxy = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_duplicate_document_task_proxy()
@@ -133,7 +135,9 @@ class TestDuplicateDocumentIndexingTaskProxy:
@patch(
"services.document_indexing_proxy.duplicate_document_indexing_task_proxy.normal_duplicate_document_indexing_task"
)
- def test_send_to_tenant_queue_without_task_key(self, mock_task, tenant_queue_commands: MagicMock):
+ def test_send_to_tenant_queue_without_task_key(
+ self, mock_task: MagicMock, tenant_queue_commands: MagicMock
+ ) -> None:
"""Test _send_to_tenant_queue when no task key exists."""
# Arrange
proxy = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_duplicate_document_task_proxy()
@@ -159,7 +163,7 @@ class TestDuplicateDocumentIndexingTaskProxy:
)
assert all(entry.args[0] != "LPUSH" for entry in tenant_queue_commands.call_args_list)
- def test_send_to_default_tenant_queue(self):
+ def test_send_to_default_tenant_queue(self) -> None:
"""Test _send_to_default_tenant_queue method."""
# Arrange
proxy = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_duplicate_document_task_proxy()
@@ -171,7 +175,7 @@ class TestDuplicateDocumentIndexingTaskProxy:
# Assert
proxy._send_to_tenant_queue.assert_called_once_with(proxy.NORMAL_TASK_FUNC)
- def test_send_to_priority_tenant_queue(self):
+ def test_send_to_priority_tenant_queue(self) -> None:
"""Test _send_to_priority_tenant_queue method."""
# Arrange
proxy = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_duplicate_document_task_proxy()
@@ -183,7 +187,7 @@ class TestDuplicateDocumentIndexingTaskProxy:
# Assert
proxy._send_to_tenant_queue.assert_called_once_with(proxy.PRIORITY_TASK_FUNC)
- def test_send_to_priority_direct_queue(self):
+ def test_send_to_priority_direct_queue(self) -> None:
"""Test _send_to_priority_direct_queue method."""
# Arrange
proxy = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_duplicate_document_task_proxy()
@@ -197,7 +201,7 @@ class TestDuplicateDocumentIndexingTaskProxy:
@config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
@patch("services.document_indexing_proxy.base.FeatureService")
- def test_dispatch_with_cloud_sandbox_plan(self, mock_feature_service):
+ def test_dispatch_with_cloud_sandbox_plan(self, mock_feature_service: MagicMock) -> None:
"""Test _dispatch method in Cloud with Sandbox plan."""
# Arrange
mock_features = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_mock_features(plan=CloudPlan.SANDBOX)
@@ -213,7 +217,7 @@ class TestDuplicateDocumentIndexingTaskProxy:
@config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
@patch("services.document_indexing_proxy.base.FeatureService")
- def test_dispatch_with_cloud_paid_plan(self, mock_feature_service):
+ def test_dispatch_with_cloud_paid_plan(self, mock_feature_service: MagicMock) -> None:
"""Test _dispatch method in Cloud with a paid plan."""
# Arrange
mock_features = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_mock_features(plan=CloudPlan.TEAM)
@@ -230,7 +234,7 @@ class TestDuplicateDocumentIndexingTaskProxy:
@config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
@patch("services.document_indexing_proxy.base.FeatureService")
- def test_dispatch_outside_cloud(self, mock_feature_service):
+ def test_dispatch_outside_cloud(self, mock_feature_service: MagicMock) -> None:
"""Test _dispatch method outside Cloud."""
# Arrange
mock_features = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_mock_features()
@@ -247,7 +251,7 @@ class TestDuplicateDocumentIndexingTaskProxy:
@config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
@patch("services.document_indexing_proxy.base.FeatureService")
- def test_delay_method(self, mock_feature_service):
+ def test_delay_method(self, mock_feature_service: MagicMock) -> None:
"""Test delay method integration."""
# Arrange
mock_features = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_mock_features(plan=CloudPlan.SANDBOX)
@@ -264,7 +268,7 @@ class TestDuplicateDocumentIndexingTaskProxy:
@config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
@patch("services.document_indexing_proxy.base.FeatureService")
- def test_dispatch_edge_case_empty_plan(self, mock_feature_service):
+ def test_dispatch_edge_case_empty_plan(self, mock_feature_service: MagicMock) -> None:
"""Test _dispatch method with empty plan string."""
# Arrange
mock_features = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_mock_features(plan="")
@@ -280,7 +284,7 @@ class TestDuplicateDocumentIndexingTaskProxy:
@config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
@patch("services.document_indexing_proxy.base.FeatureService")
- def test_dispatch_edge_case_none_plan(self, mock_feature_service):
+ def test_dispatch_edge_case_none_plan(self, mock_feature_service: MagicMock) -> None:
"""Test _dispatch method with None plan."""
# Arrange
mock_features = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_mock_features(plan=None)
@@ -294,7 +298,7 @@ class TestDuplicateDocumentIndexingTaskProxy:
# Assert
proxy._send_to_priority_tenant_queue.assert_called_once()
- def test_initialization_with_empty_document_ids(self):
+ def test_initialization_with_empty_document_ids(self) -> None:
"""Test initialization with empty document_ids list."""
# Arrange
tenant_id = "tenant-123"
@@ -309,7 +313,7 @@ class TestDuplicateDocumentIndexingTaskProxy:
assert proxy._dataset_id == dataset_id
assert proxy._document_ids == document_ids
- def test_initialization_with_single_document_id(self):
+ def test_initialization_with_single_document_id(self) -> None:
"""Test initialization with single document_id."""
# Arrange
tenant_id = "tenant-123"
@@ -324,7 +328,7 @@ class TestDuplicateDocumentIndexingTaskProxy:
assert proxy._dataset_id == dataset_id
assert proxy._document_ids == document_ids
- def test_initialization_with_large_batch(self):
+ def test_initialization_with_large_batch(self) -> None:
"""Test initialization with large batch of document IDs."""
# Arrange
tenant_id = "tenant-123"
@@ -342,7 +346,7 @@ class TestDuplicateDocumentIndexingTaskProxy:
@config_overrides_context(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
@patch("services.document_indexing_proxy.base.FeatureService")
- def test_dispatch_with_professional_plan(self, mock_feature_service):
+ def test_dispatch_with_professional_plan(self, mock_feature_service: MagicMock) -> None:
"""Test _dispatch method when billing is enabled with professional plan."""
# Arrange
mock_features = DuplicateDocumentIndexingTaskProxyTestDataFactory.create_mock_features(
diff --git a/api/tests/unit_tests/services/test_feature_service_human_input_email_delivery.py b/api/tests/unit_tests/services/test_feature_service_human_input_email_delivery.py
index cb16e88a8b0..26e58b67f65 100644
--- a/api/tests/unit_tests/services/test_feature_service_human_input_email_delivery.py
+++ b/api/tests/unit_tests/services/test_feature_service_human_input_email_delivery.py
@@ -14,7 +14,7 @@ class HumanInputEmailDeliveryCase:
name: str
deployment_edition: DeploymentEdition
tenant_id: str | None
- plan: str
+ plan: CloudPlan
expected: bool
@@ -68,7 +68,7 @@ CASES = [
def test_resolve_human_input_email_delivery_enabled_matrix(
config_overrides: Callable[..., None],
case: HumanInputEmailDeliveryCase,
-):
+) -> None:
config_overrides(DEPLOYMENT_EDITION=case.deployment_edition)
features = FeatureModel()
features.billing.subscription.plan = case.plan
@@ -83,7 +83,7 @@ def test_resolve_human_input_email_delivery_enabled_matrix(
def test_get_vector_space_converts_billing_float_size(
monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None]
-):
+) -> None:
config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
monkeypatch.setattr(
feature_service_module.BillingService,
@@ -100,7 +100,7 @@ def test_get_vector_space_converts_billing_float_size(
def test_get_vector_space_preserves_unknown_usage(
monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None]
-):
+) -> None:
config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
monkeypatch.setattr(
feature_service_module.BillingService,
diff --git a/api/tests/unit_tests/services/test_feature_service_vector_space.py b/api/tests/unit_tests/services/test_feature_service_vector_space.py
index 913a8526a95..4eada6740a6 100644
--- a/api/tests/unit_tests/services/test_feature_service_vector_space.py
+++ b/api/tests/unit_tests/services/test_feature_service_vector_space.py
@@ -1,3 +1,4 @@
+from collections.abc import Callable
from typing import cast
from unittest.mock import patch
@@ -7,7 +8,7 @@ from services.entities.feature_entities import LimitationModel
from services.feature_service import FeatureService
-def test_get_features_exclude_vector_space_sets_vector_space_to_none(config_overrides):
+def test_get_features_exclude_vector_space_sets_vector_space_to_none(config_overrides: Callable[..., None]) -> None:
tenant_id = "tenant-id"
billing_info = {
"subscription": {"plan": CloudPlan.PROFESSIONAL, "interval": "monthly", "education": False},
@@ -36,7 +37,7 @@ def test_get_features_exclude_vector_space_sets_vector_space_to_none(config_over
get_info.assert_called_once_with(tenant_id, exclude_vector_space=True)
-def test_full_features_keep_treating_unknown_vector_usage_as_zero():
+def test_full_features_keep_treating_unknown_vector_usage_as_zero() -> None:
vector_space = LimitationModel()
FeatureService._fulfill_vector_space_from_billing_info(
diff --git a/api/tests/unit_tests/services/test_metadata_nullable_bug.py b/api/tests/unit_tests/services/test_metadata_nullable_bug.py
index 0347cee0263..241a32bcb52 100644
--- a/api/tests/unit_tests/services/test_metadata_nullable_bug.py
+++ b/api/tests/unit_tests/services/test_metadata_nullable_bug.py
@@ -74,7 +74,7 @@ class TestMetadataNullableBug:
def test_api_layer_now_uses_pydantic_validation(self) -> None:
"""Verify that API layer relies on Pydantic validation instead of reqparse."""
- invalid_payload = {"type": None, "name": None}
+ invalid_payload: dict[str, object] = {"type": None, "name": None}
with pytest.raises((ValueError, TypeError)):
MetadataArgs.model_validate(invalid_payload)
diff --git a/api/tests/unit_tests/services/test_model_load_balancing_service.py b/api/tests/unit_tests/services/test_model_load_balancing_service.py
index 3d2c98102a0..98ffa1d3564 100644
--- a/api/tests/unit_tests/services/test_model_load_balancing_service.py
+++ b/api/tests/unit_tests/services/test_model_load_balancing_service.py
@@ -3,7 +3,7 @@
from __future__ import annotations
import json
-from collections.abc import Iterator
+from collections.abc import Generator
from contextlib import contextmanager
from typing import cast
from unittest.mock import MagicMock, patch
@@ -136,8 +136,8 @@ def _config(
@contextmanager
-def _raise_on_insert(engine: Engine) -> Iterator[None]:
- def raise_error(_conn, _cursor, statement, _parameters, _context, _executemany):
+def _raise_on_insert(engine: Engine) -> Generator[None]:
+ def raise_error(_conn, _cursor, statement: str, _parameters, _context, _executemany) -> None:
if statement.lstrip().upper().startswith("INSERT") and "load_balancing_model_configs" in statement:
raise RuntimeError("forced INSERT")
@@ -186,7 +186,7 @@ def test_enable_disable_persists_provider_model_setting(
def test_provider_missing_errors_use_runtime_boundary(service: ServiceFixture, sqlite_session: Session) -> None:
svc, manager, _ = service
- manager.get_configurations.return_value = {}
+ manager.get_configurations.return_value = dict[str, object]()
with pytest.raises(ValueError, match="Provider openai does not exist"):
svc.enable_model_load_balancing("tenant-1", "openai", "model", ModelType.LLM)
with pytest.raises(ValueError, match="Provider openai does not exist"):
@@ -329,7 +329,7 @@ def test_init_inherit_config_persists_and_sql_failure_rolls_back(
],
)
def test_update_configs_rejects_invalid_payloads(
- configs,
+ configs: object,
message: str,
service: ServiceFixture,
sqlite_session: Session,
@@ -337,7 +337,13 @@ def test_update_configs_rejects_invalid_payloads(
svc, _, _ = service
with pytest.raises(ValueError, match=message):
svc.update_load_balancing_configs(
- "tenant-1", "openai", "gpt-4o-mini", ModelType.LLM, configs, "custom-model", sqlite_session
+ "tenant-1",
+ "openai",
+ "gpt-4o-mini",
+ ModelType.LLM,
+ configs, # pyrefly: ignore[bad-argument-type]
+ "custom-model",
+ sqlite_session,
)
@@ -391,6 +397,7 @@ def test_update_configs_updates_creates_and_deletes_persisted_rows(
updated = sqlite_session.get(LoadBalancingModelConfig, keep.id)
assert updated is not None
assert updated.enabled is False
+ assert updated.encrypted_config is not None
assert json.loads(updated.encrypted_config) == {"api_key": "enc-new"}
diff --git a/api/tests/unit_tests/services/test_model_provider_service_sanitization.py b/api/tests/unit_tests/services/test_model_provider_service_sanitization.py
index 1c75b0e059b..392f068e86b 100644
--- a/api/tests/unit_tests/services/test_model_provider_service_sanitization.py
+++ b/api/tests/unit_tests/services/test_model_provider_service_sanitization.py
@@ -19,7 +19,7 @@ class _FakeConfigurations:
@pytest.fixture
-def service_with_fake_configurations():
+def service_with_fake_configurations(monkeypatch: pytest.MonkeyPatch) -> ModelProviderService:
# Build a fake provider schema with minimal fields used by ProviderResponse
fake_provider = types.SimpleNamespace(
provider="langgenius/openai_api_compatible/openai_api_compatible",
@@ -71,11 +71,11 @@ def service_with_fake_configurations():
return _FakeConfigurations(fake_provider_configuration)
svc = ModelProviderService()
- svc._get_provider_manager = lambda tenant_id: _FakeProviderManager()
+ monkeypatch.setattr(svc, "_get_provider_manager", lambda _tenant_id: _FakeProviderManager())
return svc
-def test_get_provider_list_strips_credentials(service_with_fake_configurations: ModelProviderService):
+def test_get_provider_list_strips_credentials(service_with_fake_configurations: ModelProviderService) -> None:
providers = service_with_fake_configurations.get_provider_list(tenant_id="tenant-1", model_type=None)
assert len(providers) == 1
diff --git a/api/tests/unit_tests/services/test_oauth_device_flow.py b/api/tests/unit_tests/services/test_oauth_device_flow.py
index 0d511d9c5b4..894f50b091a 100644
--- a/api/tests/unit_tests/services/test_oauth_device_flow.py
+++ b/api/tests/unit_tests/services/test_oauth_device_flow.py
@@ -1,4 +1,5 @@
import json
+from collections.abc import Callable, Sequence
from dataclasses import dataclass, field
from services.oauth_device_contracts import ApprovalTransitionConfirmation, DeviceFlowStatus, PollPayload
@@ -25,10 +26,10 @@ class _Redis:
def get(self, _name: str) -> str:
return self.response
- def register_script(self, script: str):
+ def register_script(self, script: str) -> Callable[..., str | int]:
self.script_sources.append(script)
- def execute(*, keys, args=()):
+ def execute(*, keys: Sequence[str], args: Sequence[object] = ()) -> str | int:
self.script_calls.append((script, tuple(keys), tuple(args or ())))
if "return raw" in script:
return self.response