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.

chore(api): clear ruff debt in strict services unit tests (#44041)

Eddy ZHANGa408d1d031b3
diff --git a/api/tests/unit_tests/.ruff.toml b/api/tests/unit_tests/.ruff.toml
index 1be93700804..5ef92bfb6a8 100644
--- a/api/tests/unit_tests/.ruff.toml
+++ b/api/tests/unit_tests/.ruff.toml
@@ -296,7 +296,6 @@ extend-select = ["ANN401", "ARG"]
"oss/volcengine_tos/test_volcengine_tos.py" = ["ARG002"]
"services/agent/test_agent_observability_service.py" = ["ARG002", "ARG005"]
"services/agent/test_agent_services.py" = ["ARG001", "ARG002", "ARG003", "ARG005"]
-"services/agent/test_composer_candidates.py" = ["ARG005"]
"services/agent/test_prompt_mentions.py" = ["ARG005"]
"services/controller_api.py" = ["ARG002"]
"services/data_migration/test_import_service.py" = ["ARG002", "ARG005"]
@@ -319,7 +318,6 @@ extend-select = ["ANN401", "ARG"]
"services/test_app_generate_service.py" = ["ARG001", "ARG002", "ARG004"]
"services/test_app_generate_service_streaming_integration.py" = ["ARG002", "TID251"]
"services/test_audio_service.py" = ["ARG002", "TID251"]
-"services/test_batch_indexing_base.py" = ["ANN401", "TID251"]
"services/test_billing_service.py" = ["ARG001", "ARG002"]
"services/test_clear_free_plan_expired_workflow_run_logs.py" = ["ANN401", "ARG002", "ARG005", "TID251"]
"services/test_clear_free_plan_tenant_expired_logs.py" = ["ARG002", "ARG003"]
@@ -336,16 +334,13 @@ extend-select = ["ANN401", "ARG"]
"services/test_schedule_service.py" = ["ANN401", "TID251"]
"services/test_snippet_service.py" = ["ARG001", "ARG002"]
"services/test_summary_index_service.py" = ["ARG001"]
-"services/test_telemetry_service.py" = ["ARG001", "ARG005"]
"services/test_variable_truncator.py" = ["ARG002", "TID251"]
-"services/test_variable_truncator_additional.py" = ["ANN401", "TID251"]
"services/test_webhook_service_additional.py" = ["ANN401", "ARG002", "TID251"]
"services/test_website_service.py" = ["TID251"]
"services/test_workflow_run_service.py" = ["ANN401", "ARG002", "TID251"]
"services/test_workflow_service.py" = ["ANN401", "ARG002", "TID251"]
"services/tools/test_builtin_tools_manage_service.py" = ["ARG001", "ARG002"]
"services/tools/test_tools_manage_service.py" = ["ARG002"]
-"services/workflow/test_inspector_events.py" = ["ANN401", "TID251"]
"services/workflow/test_node_output_inspector_service.py" = ["TID251"]
"services/workflow/test_workflow_converter_additional.py" = ["ANN401", "ARG001", "ARG005", "TID251"]
"services/workflow/test_workflow_event_snapshot_service.py" = ["ANN401", "ARG002", "ARG005", "TID251"]
diff --git a/api/tests/unit_tests/services/agent/test_composer_candidates.py b/api/tests/unit_tests/services/agent/test_composer_candidates.py
index ac91b5ce404..a30c0dfad81 100644
--- a/api/tests/unit_tests/services/agent/test_composer_candidates.py
+++ b/api/tests/unit_tests/services/agent/test_composer_candidates.py
@@ -150,8 +150,8 @@ def test_previous_outputs_capped_and_flagged() -> None:
entries, truncated = previous_node_output_candidates(
graph=graph,
node_id="t",
- declared_outputs_loader=lambda nid: None,
- draft_variables_loader=lambda nid: [],
+ declared_outputs_loader=lambda _nid: None,
+ draft_variables_loader=lambda _nid: [],
system_variables_loader=lambda: many,
)
assert len(entries) == MAX_CANDIDATES_PER_LIST
@@ -194,7 +194,7 @@ def test_soul_candidates_lists_configured_items_only() -> None:
)
lists, truncated = soul_candidates(
agent_soul=_soul(),
- dataset_lookup=lambda ids: {"ds-1": dataset},
+ dataset_lookup=lambda _ids: {"ds-1": dataset},
workspace_tools_loader=lambda: [
{"id": "tavily/tavily_search", "name": "tavily_search", "provider": "tavily", "plugin_id": "lg/tavily"}
],
@@ -236,7 +236,7 @@ def test_candidates_response_omits_legacy_skill_file_candidates() -> None:
def test_soul_candidates_empty_config_yields_empty_lists() -> None:
lists, truncated = soul_candidates(
agent_soul=None,
- dataset_lookup=lambda ids: {},
+ dataset_lookup=lambda _ids: {},
workspace_tools_loader=lambda: [],
)
assert truncated is False
@@ -246,7 +246,7 @@ def test_soul_candidates_empty_config_yields_empty_lists() -> None:
def test_soul_candidates_caps_lists() -> None:
lists, truncated = soul_candidates(
agent_soul=None,
- dataset_lookup=lambda ids: {},
+ dataset_lookup=lambda _ids: {},
workspace_tools_loader=lambda: [{"id": str(i)} for i in range(MAX_CANDIDATES_PER_LIST + 1)],
)
assert len(lists["dify_tools"]) == MAX_CANDIDATES_PER_LIST
diff --git a/api/tests/unit_tests/services/test_batch_indexing_base.py b/api/tests/unit_tests/services/test_batch_indexing_base.py
index 929cd6251db..06f610ac8a0 100644
--- a/api/tests/unit_tests/services/test_batch_indexing_base.py
+++ b/api/tests/unit_tests/services/test_batch_indexing_base.py
@@ -1,5 +1,5 @@
from dataclasses import asdict
-from typing import Any, ClassVar, cast
+from typing import ClassVar, cast
from unittest.mock import MagicMock, patch
import pytest
@@ -18,8 +18,8 @@ class ConcreteBatchProxy(BatchDocumentIndexingProxy):
"""Minimal concrete implementation that provides the required class-level vars."""
QUEUE_NAME: ClassVar[str] = "test_queue"
- NORMAL_TASK_FUNC: ClassVar[Any] = MagicMock(name="NORMAL_TASK_FUNC")
- PRIORITY_TASK_FUNC: ClassVar[Any] = MagicMock(name="PRIORITY_TASK_FUNC")
+ NORMAL_TASK_FUNC = MagicMock(name="NORMAL_TASK_FUNC")
+ PRIORITY_TASK_FUNC = MagicMock(name="PRIORITY_TASK_FUNC")
# ---------------------------------------------------------------------------
@@ -31,13 +31,15 @@ DATASET_ID = "dataset-xyz"
DOC_IDS: list[str] = ["doc-1", "doc-2", "doc-3"]
-def make_proxy(**kwargs: Any) -> ConcreteBatchProxy:
+def make_proxy(
+ *, tenant_id: str = TENANT_ID, dataset_id: str = DATASET_ID, document_ids: list[str] | None = None
+) -> ConcreteBatchProxy:
"""Factory: returns a ConcreteBatchProxy with TenantIsolatedTaskQueue mocked out."""
with patch("services.document_indexing_proxy.batch_indexing_base.TenantIsolatedTaskQueue") as MockQueue:
proxy = ConcreteBatchProxy(
- tenant_id=kwargs.get("tenant_id", TENANT_ID),
- dataset_id=kwargs.get("dataset_id", DATASET_ID),
- document_ids=kwargs.get("document_ids", DOC_IDS),
+ tenant_id=tenant_id,
+ dataset_id=dataset_id,
+ document_ids=document_ids if document_ids is not None else DOC_IDS,
)
# Expose the mock queue on the proxy so tests can assert on it
proxy._tenant_isolated_task_queue = MockQueue.return_value
@@ -256,7 +258,7 @@ class TestSendToTenantQueue:
mock_queue.push_tasks.assert_not_called()
@pytest.mark.parametrize("falsy_key", [None, "", 0, False])
- def test_should_init_task_when_key_is_any_falsy_value(self, falsy_key: Any) -> None:
+ def test_should_init_task_when_key_is_any_falsy_value(self, falsy_key: object) -> None:
"""Verify that any falsy return from get_task_key() triggers the init branch."""
# Arrange
proxy = make_proxy()
diff --git a/api/tests/unit_tests/services/test_telemetry_service.py b/api/tests/unit_tests/services/test_telemetry_service.py
index e14c1278b0d..e55f2c6a2dc 100644
--- a/api/tests/unit_tests/services/test_telemetry_service.py
+++ b/api/tests/unit_tests/services/test_telemetry_service.py
@@ -43,8 +43,9 @@ def test_telemetry_is_disabled_for_enterprise(config_overrides: Callable[..., No
("TELEMETRY_ENDPOINT", ""),
],
)
[email protected]("telemetry_enabled")
def test_telemetry_is_disabled_when_a_required_condition_is_not_met(
- telemetry_enabled: None, config_overrides: Callable[..., None], setting: str, value: str | bool
+ config_overrides: Callable[..., None], setting: str, value: str | bool
) -> None:
config_overrides(**{setting: value})
@@ -52,15 +53,16 @@ def test_telemetry_is_disabled_when_a_required_condition_is_not_met(
@pytest.mark.parametrize("sqlite_session", [(DifySetup,)], indirect=True)
-def test_reporting_without_setup_is_skipped(sqlite_session: Session, telemetry_enabled: None) -> None:
[email protected]("telemetry_enabled")
+def test_reporting_without_setup_is_skipped(sqlite_session: Session) -> None:
assert CommunityTelemetryService.report_install(session=sqlite_session) is False
assert CommunityTelemetryService.report_heartbeat(session=sqlite_session) is False
@pytest.mark.parametrize("sqlite_session", [(DifySetup,)], indirect=True)
[email protected]("telemetry_enabled")
def test_report_install_marks_reported_at(
sqlite_session: Session,
- telemetry_enabled: None,
monkeypatch: pytest.MonkeyPatch,
config_overrides: Callable[..., None],
) -> None:
@@ -71,7 +73,7 @@ def test_report_install_marks_reported_at(
sent_payloads: list[dict[str, str | int]] = []
- def fake_post(url: str, json: dict[str, str | int], timeout: int) -> httpx.Response:
+ def fake_post(url: str, json: dict[str, str | int], **_kwargs: object) -> httpx.Response:
sent_payloads.append(json)
return httpx.Response(204, request=httpx.Request("POST", url))
@@ -89,16 +91,15 @@ def test_report_install_marks_reported_at(
@pytest.mark.parametrize("sqlite_session", [(DifySetup,)], indirect=True)
-def test_report_install_generates_missing_instance_id(
- sqlite_session: Session, telemetry_enabled: None, monkeypatch: pytest.MonkeyPatch
-) -> None:
[email protected]("telemetry_enabled")
+def test_report_install_generates_missing_instance_id(sqlite_session: Session, monkeypatch: pytest.MonkeyPatch) -> None:
setup = DifySetup(version="installed-version")
sqlite_session.add(setup)
sqlite_session.commit()
monkeypatch.setattr(
telemetry_service.httpx,
"post",
- lambda url, json, timeout: httpx.Response(204, request=httpx.Request("POST", url)),
+ lambda url, **_kwargs: httpx.Response(204, request=httpx.Request("POST", url)),
)
assert CommunityTelemetryService.report_install(session=sqlite_session) is True
@@ -108,8 +109,9 @@ def test_report_install_generates_missing_instance_id(
@pytest.mark.parametrize("sqlite_session", [(DifySetup,)], indirect=True)
[email protected]("telemetry_enabled")
def test_report_heartbeat_generates_missing_instance_id(
- sqlite_session: Session, telemetry_enabled: None, monkeypatch: pytest.MonkeyPatch
+ sqlite_session: Session, monkeypatch: pytest.MonkeyPatch
) -> None:
setup = DifySetup(version="1.0.0", install_reported_at=datetime(2026, 7, 12, 8, 0, 0))
sqlite_session.add(setup)
@@ -117,7 +119,7 @@ def test_report_heartbeat_generates_missing_instance_id(
monkeypatch.setattr(
telemetry_service.httpx,
"post",
- lambda url, json, timeout: httpx.Response(204, request=httpx.Request("POST", url)),
+ lambda url, **_kwargs: httpx.Response(204, request=httpx.Request("POST", url)),
)
assert (
@@ -129,14 +131,13 @@ def test_report_heartbeat_generates_missing_instance_id(
@pytest.mark.parametrize("sqlite_session", [(DifySetup,)], indirect=True)
-def test_report_install_failure_keeps_install_pending(
- sqlite_session: Session, telemetry_enabled: None, monkeypatch: pytest.MonkeyPatch
-) -> None:
[email protected]("telemetry_enabled")
+def test_report_install_failure_keeps_install_pending(sqlite_session: Session, monkeypatch: pytest.MonkeyPatch) -> None:
setup = DifySetup(version="1.0.0", instance_id="d246c3a1-350b-406c-92c7-6043df680758")
sqlite_session.add(setup)
sqlite_session.commit()
- def fake_post(url: str, json: dict[str, str | int], timeout: int) -> httpx.Response:
+ def fake_post(url: str, **_kwargs: object) -> httpx.Response:
raise httpx.ConnectError("offline", request=httpx.Request("POST", url))
monkeypatch.setattr(telemetry_service.httpx, "post", fake_post)
@@ -149,8 +150,9 @@ def test_report_install_failure_keeps_install_pending(
@pytest.mark.parametrize("sqlite_session", [(DifySetup,)], indirect=True)
[email protected]("telemetry_enabled")
def test_report_install_uses_fallback_endpoint_after_network_failure(
- sqlite_session: Session, telemetry_enabled: None, monkeypatch: pytest.MonkeyPatch
+ sqlite_session: Session, monkeypatch: pytest.MonkeyPatch
) -> None:
setup = DifySetup(version="1.0.0", instance_id="d246c3a1-350b-406c-92c7-6043df680758")
sqlite_session.add(setup)
@@ -158,7 +160,7 @@ def test_report_install_uses_fallback_endpoint_after_network_failure(
urls: list[str] = []
- def fake_post(url: str, json: dict[str, str | int], timeout: int) -> httpx.Response:
+ def fake_post(url: str, **_kwargs: object) -> httpx.Response:
urls.append(url)
if url == telemetry_service.dify_config.TELEMETRY_ENDPOINT:
raise httpx.ConnectError("offline", request=httpx.Request("POST", url))
@@ -174,8 +176,9 @@ def test_report_install_uses_fallback_endpoint_after_network_failure(
@pytest.mark.parametrize("sqlite_session", [(DifySetup,)], indirect=True)
[email protected]("telemetry_enabled")
def test_report_install_does_not_use_fallback_endpoint_after_http_error(
- sqlite_session: Session, telemetry_enabled: None, monkeypatch: pytest.MonkeyPatch
+ sqlite_session: Session, monkeypatch: pytest.MonkeyPatch
) -> None:
setup = DifySetup(version="1.0.0", instance_id="d246c3a1-350b-406c-92c7-6043df680758")
sqlite_session.add(setup)
@@ -194,9 +197,9 @@ def test_report_install_does_not_use_fallback_endpoint_after_http_error(
@pytest.mark.parametrize("sqlite_session", [(DifySetup,)], indirect=True)
[email protected]("telemetry_enabled")
def test_report_heartbeat_retries_pending_install_before_heartbeat(
sqlite_session: Session,
- telemetry_enabled: None,
monkeypatch: pytest.MonkeyPatch,
config_overrides: Callable[..., None],
) -> None:
@@ -207,7 +210,7 @@ def test_report_heartbeat_retries_pending_install_before_heartbeat(
sent_payloads: list[dict[str, str | int]] = []
- def fake_post(url: str, json: dict[str, str | int], timeout: int) -> httpx.Response:
+ def fake_post(url: str, json: dict[str, str | int], **_kwargs: object) -> httpx.Response:
sent_payloads.append(json)
return httpx.Response(204, request=httpx.Request("POST", url))
@@ -226,8 +229,9 @@ def test_report_heartbeat_retries_pending_install_before_heartbeat(
@pytest.mark.parametrize("sqlite_session", [(DifySetup,)], indirect=True)
[email protected]("telemetry_enabled")
def test_report_heartbeat_skips_when_already_sent_today(
- sqlite_session: Session, telemetry_enabled: None, monkeypatch: pytest.MonkeyPatch
+ sqlite_session: Session, monkeypatch: pytest.MonkeyPatch
) -> None:
setup = DifySetup(
version="1.0.0",
@@ -248,8 +252,9 @@ def test_report_heartbeat_skips_when_already_sent_today(
@pytest.mark.parametrize("sqlite_session", [(DifySetup,)], indirect=True)
[email protected]("telemetry_enabled")
def test_report_heartbeat_failure_does_not_mark_the_day_reported(
- sqlite_session: Session, telemetry_enabled: None, monkeypatch: pytest.MonkeyPatch
+ sqlite_session: Session, monkeypatch: pytest.MonkeyPatch
) -> None:
setup = DifySetup(
version="1.0.0",
@@ -259,7 +264,7 @@ def test_report_heartbeat_failure_does_not_mark_the_day_reported(
sqlite_session.add(setup)
sqlite_session.commit()
- def fake_post(url: str, json: dict[str, str | int], timeout: int) -> httpx.Response:
+ def fake_post(url: str, **_kwargs: object) -> httpx.Response:
raise httpx.ConnectError("offline", request=httpx.Request("POST", url))
monkeypatch.setattr(telemetry_service.httpx, "post", fake_post)
@@ -281,12 +286,13 @@ def test_send_event_skips_when_telemetry_is_disabled(
post_mock.assert_not_called()
[email protected]("telemetry_enabled")
def test_send_event_skips_an_empty_fallback_endpoint(
- telemetry_enabled: None, monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None]
+ monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None]
) -> None:
config_overrides(TELEMETRY_FALLBACK_ENDPOINT="")
- def fake_post(url: str, json: dict[str, str], timeout: int) -> httpx.Response:
+ def fake_post(url: str, **_kwargs: object) -> httpx.Response:
raise httpx.ConnectError("offline", request=httpx.Request("POST", url))
monkeypatch.setattr(telemetry_service.httpx, "post", fake_post)
@@ -294,8 +300,9 @@ def test_send_event_skips_an_empty_fallback_endpoint(
assert CommunityTelemetryService._send_event({"event": "heartbeat"}) is False
[email protected]("telemetry_enabled")
def test_send_event_does_not_retry_the_same_endpoint(
- telemetry_enabled: None, monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None]
+ monkeypatch: pytest.MonkeyPatch, config_overrides: Callable[..., None]
) -> None:
config_overrides(TELEMETRY_FALLBACK_ENDPOINT=telemetry_service.dify_config.TELEMETRY_ENDPOINT)
post_mock = Mock(
diff --git a/api/tests/unit_tests/services/test_variable_truncator_additional.py b/api/tests/unit_tests/services/test_variable_truncator_additional.py
index 7e08ca75474..3678e985673 100644
--- a/api/tests/unit_tests/services/test_variable_truncator_additional.py
+++ b/api/tests/unit_tests/services/test_variable_truncator_additional.py
@@ -1,5 +1,3 @@
-from typing import Any
-
import pytest
from graphon.nodes.variable_assigner.common.helpers import UpdatedVariable
@@ -57,7 +55,7 @@ class TestVariableTruncatorAdditionalBehavior:
)
def test_json_value_needs_truncation_should_match_expected_rules(
self,
- value: Any,
+ value: object,
expected: bool,
) -> None:
result = VariableTruncator._json_value_needs_truncation(value)
diff --git a/api/tests/unit_tests/services/workflow/test_inspector_events.py b/api/tests/unit_tests/services/workflow/test_inspector_events.py
index 32451654e1f..16ce1247eb2 100644
--- a/api/tests/unit_tests/services/workflow/test_inspector_events.py
+++ b/api/tests/unit_tests/services/workflow/test_inspector_events.py
@@ -15,7 +15,6 @@ from __future__ import annotations
import json
from collections.abc import Generator, Iterator
-from typing import Any
from unittest.mock import MagicMock, patch
from services.workflow import inspector_events
@@ -104,7 +103,7 @@ def test_publish_swallows_redis_errors() -> None:
"""Persistence must not crash if redis blows up — we publish best-effort."""
class _BrokenRedis:
- def publish(self, *_args: Any, **_kwargs: Any) -> None:
+ def publish(self, *_args: object, **_kwargs: object) -> None:
raise RuntimeError("redis offline")
with patch.object(inspector_events, "redis_client", _BrokenRedis()):
@@ -117,10 +116,10 @@ def test_publish_swallows_redis_errors() -> None:
# ──────────────────────────────────────────────────────────────────────────────
-def _make_fake_pubsub(messages: list[dict[str, Any] | None]) -> MagicMock:
+def _make_fake_pubsub(messages: list[dict[str, object] | None]) -> MagicMock:
"""Build a redis pubsub stub that replays ``messages`` then raises StopIteration."""
pubsub = MagicMock()
- it: Iterator[dict[str, Any] | None] = iter(messages)
+ it: Iterator[dict[str, object] | None] = iter(messages)
pubsub.get_message.side_effect = lambda **_kwargs: next(it, None)
return pubsub
@@ -206,7 +205,7 @@ def test_subscribe_skips_non_string_data_payloads() -> None:
"""``raw["data"]`` can be ``None`` / int / bytes — only str is decodable
and the rest are silently skipped."""
fake_pubsub = MagicMock()
- msgs: list[dict[str, Any] | None] = [
+ msgs: list[dict[str, object] | None] = [
{"data": None}, # missing payload
{"data": 12345}, # int payload (shouldn't happen, defensive)
{