Merge branch 'main' into feat/dify-builder

This commit is contained in:
twwu committed 2026-09-17 17:01:34 +08:00
commit 782688563d
266 files changed
+9891 -3597

No files matched your search

@@ -0,0 +1,39 @@
"""Regression coverage for the ``db.session``→session-parameter refactor on
``AppMCPServer.generate_server_code``.
The static method reached for the global ``db.session`` internally and has been converted to
take an explicit ``session: Session`` (per the pattern established in #40370/#40797/#41394,
tracked in #40372).
"""
from unittest.mock import patch
from uuid import uuid4
from sqlalchemy.orm import Session
from models.enums import AppMCPServerStatus
from models.model import AppMCPServer
def _persist_server(session: Session, *, server_code: str) -> AppMCPServer:
server = AppMCPServer(
tenant_id=str(uuid4()),
app_id=str(uuid4()),
name="Test MCP Server",
description="Test server",
server_code=server_code,
status=AppMCPServerStatus.ACTIVE,
parameters="{}",
)
session.add(server)
session.flush()
return server
def test_generate_server_code_retries_a_taken_code_through_the_given_session(sqlite_session: Session) -> None:
_persist_server(sqlite_session, server_code="taken-code")
with patch("models.model.generate_string", side_effect=["taken-code", "fresh-code"]):
result = AppMCPServer.generate_server_code(16, session=sqlite_session)
assert result == "fresh-code"
+129 -9
View File
@@ -33,6 +33,7 @@ from models.model import (
Site,
load_annotation_reply_config,
)
from models.workflow import Workflow, WorkflowType
class TestAppModelValidation:
@@ -122,8 +123,9 @@ class TestAppModelValidation:
# Assert
assert {t.value for t in IconType} == {"image", "emoji", "link"}
def test_app_desc_or_prompt_with_description(self):
"""Test desc_or_prompt property when description exists."""
@pytest.mark.parametrize("sqlite_session", [(App, AppModelConfig)], indirect=True)
def test_app_desc_or_prompt_with_description(self, sqlite_session: Session):
"""Test desc_or_prompt_with_session when description exists."""
# Arrange
app = App(
tenant_id=str(uuid4()),
@@ -136,7 +138,7 @@ class TestAppModelValidation:
)
# Act
result = app.desc_or_prompt
result = app.desc_or_prompt_with_session(session=sqlite_session)
# Assert
assert result == "App description"
@@ -267,6 +269,110 @@ class TestAppModelValidation:
# Assert
assert result == AppMode.AGENT_CHAT
@pytest.mark.parametrize("sqlite_session", [(App, AppModelConfig)], indirect=True)
def test_app_model_config_with_session_reads_through_the_caller_session(self, sqlite_session: Session):
"""`app_model_config_with_session` resolves the linked config through the caller's session."""
# Arrange
app = App(
tenant_id=str(uuid4()),
name="Test App",
mode=AppMode.CHAT,
enable_site=True,
enable_api=False,
created_by=str(uuid4()),
)
sqlite_session.add(app)
sqlite_session.flush()
model_config = AppModelConfig(app_id=app.id, agent_mode=json.dumps({"enabled": False}))
sqlite_session.add(model_config)
sqlite_session.flush()
app.app_model_config_id = model_config.id
sqlite_session.commit()
# Act: a session the model never owns, proving the lookup does not reach for a global one
with Session(sqlite_session.get_bind(), expire_on_commit=False) as caller_session:
result = app.app_model_config_with_session(session=caller_session)
# Assert
assert result is not None
assert result.id == model_config.id
assert result in caller_session
@pytest.mark.parametrize("sqlite_session", [(App, AppModelConfig)], indirect=True)
def test_app_model_config_with_session_returns_none_when_unlinked(self, sqlite_session: Session):
"""An app without `app_model_config_id` resolves to None without querying."""
# Arrange
app = App(
tenant_id=str(uuid4()),
name="Test App",
mode=AppMode.CHAT,
enable_site=True,
enable_api=False,
created_by=str(uuid4()),
)
sqlite_session.add(app)
sqlite_session.flush()
# Act / Assert: an unbound session would raise if the guard were dropped
with Session(expire_on_commit=False) as unbound_session:
assert app.app_model_config_with_session(session=unbound_session) is None
@pytest.mark.parametrize("sqlite_session", [(App, AppModelConfig)], indirect=True)
def test_workflow_with_session_reads_through_the_caller_session(self, sqlite_session: Session):
"""`workflow_with_session` resolves the published workflow through the caller's session."""
# Arrange
app = App(
tenant_id=str(uuid4()),
name="Test App",
mode=AppMode.WORKFLOW,
enable_site=True,
enable_api=False,
created_by=str(uuid4()),
)
sqlite_session.add(app)
sqlite_session.flush()
workflow = Workflow(
tenant_id=app.tenant_id,
app_id=app.id,
type=WorkflowType.WORKFLOW,
version="1",
graph=json.dumps({"nodes": [], "edges": []}),
created_by=app.created_by,
)
workflow._features = "{}"
sqlite_session.add(workflow)
sqlite_session.flush()
app.workflow_id = workflow.id
sqlite_session.commit()
# Act: a session the model never owns, proving the lookup does not reach for a global one
with Session(sqlite_session.get_bind(), expire_on_commit=False) as caller_session:
result = app.workflow_with_session(session=caller_session)
# Assert
assert result is not None
assert result.id == workflow.id
assert result in caller_session
@pytest.mark.parametrize("sqlite_session", [(App, AppModelConfig)], indirect=True)
def test_workflow_with_session_returns_none_when_unpublished(self, sqlite_session: Session):
"""An app without `workflow_id` resolves to None without querying."""
# Arrange
app = App(
tenant_id=str(uuid4()),
name="Test App",
mode=AppMode.WORKFLOW,
enable_site=True,
enable_api=False,
created_by=str(uuid4()),
)
sqlite_session.add(app)
sqlite_session.flush()
# Act / Assert: an unbound session would raise if the guard were dropped
with Session(expire_on_commit=False) as unbound_session:
assert app.workflow_with_session(session=unbound_session) is None
@pytest.mark.parametrize("sqlite_session", [(App, AppModelConfig)], indirect=True)
def test_deleted_tools_checks_plugin_builtin_providers_through_core_plugin_service(self, sqlite_session: Session):
"""Plugin-backed built-in tools are checked through core PluginService."""
@@ -528,8 +634,8 @@ class TestConversationModel:
assert conversation.from_source == "api"
assert conversation.from_end_user_id == from_end_user_id
def test_conversation_with_inputs(self):
"""Test conversation inputs property."""
def test_conversation_with_inputs(self, sqlite_session: Session):
"""Test conversation inputs round-trip through the session-aware accessor."""
# Arrange
inputs = {"query": "Hello", "context": "test"}
conversation = Conversation(
@@ -543,11 +649,18 @@ class TestConversationModel:
conversation._inputs = inputs
# Act
result = conversation.inputs
result = conversation.inputs_with_session(session=sqlite_session)
# Assert
assert result == inputs
def test_conversation_inputs_is_write_only(self):
"""Reading conversation.inputs must fail loudly; reads go through inputs_with_session."""
conversation = Conversation(app_id=str(uuid4()), _inputs={})
with pytest.raises(AttributeError, match="no getter"):
_ = conversation.inputs
def test_conversation_inputs_setter(self):
"""Test conversation inputs setter."""
# Arrange
@@ -772,8 +885,8 @@ class TestMessageModel:
assert message.currency == "USD"
assert message.from_source == "api"
def test_message_with_inputs(self):
"""Test message inputs property."""
def test_message_with_inputs(self, sqlite_session: Session):
"""Test message inputs round-trip through the session-aware accessor."""
# Arrange
inputs = {"query": "Hello", "context": "test"}
message = Message(
@@ -790,11 +903,18 @@ class TestMessageModel:
)
# Act
result = message.inputs
result = message.inputs_with_session(session=sqlite_session)
# Assert
assert result == inputs
def test_message_inputs_is_write_only(self):
"""Reading message.inputs must fail loudly; reads go through inputs_with_session."""
message = Message(app_id=str(uuid4()), _inputs={})
with pytest.raises(AttributeError, match="no getter"):
_ = message.inputs
def test_message_inputs_setter(self):
"""Test message inputs setter."""
# Arrange
@@ -17,12 +17,11 @@ from urllib.parse import parse_qs, urlparse
from uuid import uuid4
import pytest
from sqlalchemy.orm import Session, scoped_session, sessionmaker
from sqlalchemy.orm import Session
from core.rag.entities import ParentMode
from core.rag.index_processor.constant.index_type import IndexStructureType, IndexTechniqueType
from extensions.storage.storage_type import StorageType
from models import dataset as dataset_module
from models.account import Account
from models.dataset import (
AppDatasetJoin,
@@ -821,59 +820,6 @@ class TestDocumentModelRelationships:
assert document.get_dataset(session=sqlite_session) is dataset
@pytest.mark.parametrize("sqlite_session", [(Document, DocumentSegment)], indirect=True)
def test_document_average_segment_length(
self,
sqlite_session: Session,
sqlite_session_factory: sessionmaker[Session],
monkeypatch: pytest.MonkeyPatch,
):
"""Test average_segment_length property calculation."""
# Arrange
document = Document(
tenant_id=str(uuid4()),
dataset_id=str(uuid4()),
position=1,
data_source_type=DataSourceType.UPLOAD_FILE,
batch="batch_001",
name="test.pdf",
created_from=DocumentCreatedFrom.WEB,
created_by=str(uuid4()),
word_count=1000,
)
sqlite_session.add(document)
sqlite_session.flush()
sqlite_session.add_all(_make_segments(document, [0] * 10))
sqlite_session.commit()
monkeypatch.setattr(dataset_module.db, "session", scoped_session(sqlite_session_factory))
# Act
result = document.average_segment_length
# Assert
assert result == 100
def test_document_average_segment_length_zero(self):
"""Test average_segment_length property when word_count is zero."""
# Arrange
document = Document(
tenant_id=str(uuid4()),
dataset_id=str(uuid4()),
position=1,
data_source_type=DataSourceType.UPLOAD_FILE,
batch="batch_001",
name="test.pdf",
created_from=DocumentCreatedFrom.WEB,
created_by=str(uuid4()),
word_count=0,
)
# Act
result = document.average_segment_length
# Assert
assert result == 0
class TestDocumentSegmentIndexing:
"""Test suite for DocumentSegment model indexing and operations."""
@@ -1573,49 +1519,6 @@ class TestModelIntegration:
assert document.word_count == 100
assert segment.status == SegmentStatus.COMPLETED
@pytest.mark.parametrize("sqlite_session", [(Document, DocumentSegment)], indirect=True)
def test_document_to_dict_serialization(
self,
sqlite_session: Session,
sqlite_session_factory: sessionmaker[Session],
monkeypatch: pytest.MonkeyPatch,
):
"""Test document to_dict method for serialization."""
# Arrange
tenant_id = str(uuid4())
dataset_id = str(uuid4())
created_by = str(uuid4())
document = Document(
tenant_id=tenant_id,
dataset_id=dataset_id,
position=1,
data_source_type=DataSourceType.UPLOAD_FILE,
batch="batch_001",
name="test.pdf",
created_from=DocumentCreatedFrom.WEB,
created_by=created_by,
word_count=100,
indexing_status=IndexingStatus.COMPLETED,
)
sqlite_session.add(document)
sqlite_session.flush()
sqlite_session.add_all(_make_segments(document, [2, 2, 2, 2, 2]))
sqlite_session.commit()
monkeypatch.setattr(dataset_module.db, "session", scoped_session(sqlite_session_factory))
# Act
result = document.to_dict()
# Assert
assert result["tenant_id"] == tenant_id
assert result["dataset_id"] == dataset_id
assert result["name"] == "test.pdf"
assert result["word_count"] == 100
assert result["indexing_status"] == IndexingStatus.COMPLETED
assert result["segment_count"] == 5
assert result["hit_count"] == 10
class TestChildChunkSessionAccessors:
"""Regression coverage for the ``ChildChunk`` accessors refactored to take a caller-provided session.
+4 -2
View File
@@ -104,7 +104,9 @@ def _build_local_file_mapping(record_id: str, *, tenant_id: str | None = None) -
@pytest.mark.parametrize("owner_cls", [Conversation, Message])
def test_inputs_restore_external_remote_url_file_mappings(owner_cls: type[Conversation] | type[Message]) -> None:
def test_inputs_restore_external_remote_url_file_mappings(
owner_cls: type[Conversation] | type[Message], sqlite_session: Session
) -> None:
owner = owner_cls(app_id="app-1")
owner.inputs = {
"file": {
@@ -119,7 +121,7 @@ def test_inputs_restore_external_remote_url_file_mappings(owner_cls: type[Conver
}
}
restored_file = owner.inputs["file"]
restored_file = owner.inputs_with_session(session=sqlite_session)["file"]
assert restored_file.transfer_method == FileTransferMethod.REMOTE_URL
assert restored_file.remote_url == "https://example.com/report.pdf"
@@ -0,0 +1,102 @@
"""Regression coverage for the ``@property``→session-parameter refactor on
``RecommendedApp`` and ``AccountTrialAppRecord``.
The legacy ``@property`` accessors reached for the global ``db.session`` internally and have
been converted to plain methods taking an explicit ``session: Session`` (per the pattern
established in #40370/#41394/#41830/#42000, tracked in #40372).
"""
from uuid import uuid4
from sqlalchemy.orm import Session
from models.account import Account
from models.model import AccountTrialAppRecord, App, AppMode, RecommendedApp
def _persist_app(session: Session) -> App:
app = App(
tenant_id=str(uuid4()),
name="Test App",
mode=AppMode.CHAT,
enable_site=True,
enable_api=False,
created_by=str(uuid4()),
description="App description",
)
session.add(app)
session.flush()
return app
def _persist_recommended_app(session: Session, *, app_id: str) -> RecommendedApp:
recommended_app = RecommendedApp(
app_id=app_id,
description={"en_US": "A recommended app"},
copyright="Dify",
privacy_policy="https://dify.ai/privacy",
category="Assistant",
)
session.add(recommended_app)
session.flush()
return recommended_app
def _persist_account(session: Session) -> Account:
account = Account(name="Test User", email=f"user-{uuid4()}@example.com")
session.add(account)
session.flush()
return account
def _persist_trial_record(session: Session, *, account_id: str, app_id: str) -> AccountTrialAppRecord:
record = AccountTrialAppRecord(account_id=account_id, app_id=app_id, count=1)
session.add(record)
session.flush()
return record
class TestRecommendedAppApp:
def test_returns_the_matching_app(self, sqlite_session: Session) -> None:
app = _persist_app(sqlite_session)
recommended_app = _persist_recommended_app(sqlite_session, app_id=app.id)
result = recommended_app.app(session=sqlite_session)
assert result is not None
assert result.id == app.id
def test_returns_none_when_app_missing(self, sqlite_session: Session) -> None:
recommended_app = _persist_recommended_app(sqlite_session, app_id=str(uuid4()))
assert recommended_app.app(session=sqlite_session) is None
class TestAccountTrialAppRecordAccessors:
def test_app_returns_the_matching_app(self, sqlite_session: Session) -> None:
app = _persist_app(sqlite_session)
record = _persist_trial_record(sqlite_session, account_id=str(uuid4()), app_id=app.id)
result = record.app(session=sqlite_session)
assert result is not None
assert result.id == app.id
def test_app_returns_none_when_app_missing(self, sqlite_session: Session) -> None:
record = _persist_trial_record(sqlite_session, account_id=str(uuid4()), app_id=str(uuid4()))
assert record.app(session=sqlite_session) is None
def test_user_returns_the_matching_account(self, sqlite_session: Session) -> None:
account = _persist_account(sqlite_session)
record = _persist_trial_record(sqlite_session, account_id=account.id, app_id=str(uuid4()))
result = record.user(session=sqlite_session)
assert result is not None
assert result.id == account.id
def test_user_returns_none_when_account_missing(self, sqlite_session: Session) -> None:
record = _persist_trial_record(sqlite_session, account_id=str(uuid4()), app_id=str(uuid4()))
assert record.user(session=sqlite_session) is None