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.

test: use real ORM models in app and API tests (#40020)

Asuka Minato123f128ccc93
diff --git a/api/tests/unit_tests/controllers/openapi/auth/test_verify.py b/api/tests/unit_tests/controllers/openapi/auth/test_verify.py
index 012b9880a12..af6515ea7a4 100644
--- a/api/tests/unit_tests/controllers/openapi/auth/test_verify.py
+++ b/api/tests/unit_tests/controllers/openapi/auth/test_verify.py
@@ -1,5 +1,5 @@
import uuid
-from unittest.mock import MagicMock, patch
+from unittest.mock import patch
import pytest
from flask import Flask
@@ -61,7 +61,7 @@ def test_check_app_access_passes_when_tenant_none():
def test_check_app_access_passes_when_member():
- tenant = MagicMock(spec=Tenant)
+ tenant = Tenant(name="Test Tenant")
tenant.id = "t1"
data = _data(account_id=uuid.uuid4(), tenant=tenant)
with patch("controllers.openapi.auth.verify.TenantService.account_belongs_to_tenant", return_value=True):
@@ -69,7 +69,7 @@ def test_check_app_access_passes_when_member():
def test_check_app_access_raises_when_not_member():
- tenant = MagicMock(spec=Tenant)
+ tenant = Tenant(name="Test Tenant")
tenant.id = "t1"
data = _data(account_id=uuid.uuid4(), tenant=tenant)
with patch("controllers.openapi.auth.verify.TenantService.account_belongs_to_tenant", return_value=False):
@@ -113,7 +113,7 @@ def test_check_rbac_raises_when_context_missing():
def test_check_rbac_enforces_for_account_caller():
- tenant = MagicMock(spec=Tenant)
+ tenant = Tenant(name="Test Tenant")
tenant.id = "t1"
account_id = uuid.uuid4()
data = _data(
@@ -144,13 +144,13 @@ def test_check_acl_raises_when_app_or_mode_missing():
def test_check_acl_account_allowed_for_public():
- app = MagicMock(spec=App)
+ app = App()
data = _data(token_type=TokenType.OAUTH_ACCOUNT, app=app, app_access_mode=WebAppAccessMode.PUBLIC)
check_acl(data)
def test_check_acl_external_sso_blocked_for_private():
- app = MagicMock(spec=App)
+ app = App()
data = _data(
token_type=TokenType.OAUTH_EXTERNAL_SSO,
app=app,
@@ -161,7 +161,7 @@ def test_check_acl_external_sso_blocked_for_private():
def test_check_acl_external_sso_allowed_for_sso_verified():
- app = MagicMock(spec=App)
+ app = App()
data = _data(
token_type=TokenType.OAUTH_EXTERNAL_SSO,
app=app,
@@ -176,8 +176,9 @@ def test_check_private_app_permission_raises_when_app_none():
def test_check_private_app_permission_raises_when_user_not_allowed():
- app = MagicMock(spec=App)
- app.id = "app-1"
+ app = App(
+ id="app-1",
+ )
data = _data(account_id=uuid.uuid4(), app=app)
target = "controllers.openapi.auth.verify.EnterpriseService.WebAppAuth.is_user_allowed_to_access_webapp"
with patch(target, return_value=False):
@@ -186,8 +187,9 @@ def test_check_private_app_permission_raises_when_user_not_allowed():
def test_check_private_app_permission_passes_when_allowed():
- app = MagicMock(spec=App)
- app.id = "app-1"
+ app = App(
+ id="app-1",
+ )
data = _data(account_id=uuid.uuid4(), app=app)
target = "controllers.openapi.auth.verify.EnterpriseService.WebAppAuth.is_user_allowed_to_access_webapp"
with patch(target, return_value=True):
@@ -208,7 +210,7 @@ def test_check_workspace_mismatch_passes_when_tenant_none(flask_app):
def test_check_workspace_mismatch_passes_when_ids_match(flask_app):
- tenant = MagicMock(spec=Tenant)
+ tenant = Tenant(name="Test Tenant")
tid = uuid.uuid4()
tenant.id = tid
with flask_app.test_request_context(f"/test?workspace_id={tid}"):
@@ -218,7 +220,7 @@ def test_check_workspace_mismatch_passes_when_ids_match(flask_app):
def test_check_workspace_mismatch_raises_422_on_mismatch(flask_app):
from werkzeug.exceptions import UnprocessableEntity
- tenant = MagicMock(spec=Tenant)
+ tenant = Tenant(name="Test Tenant")
tenant.id = uuid.uuid4()
other_id = uuid.uuid4()
with flask_app.test_request_context(f"/test?workspace_id={other_id}"):
@@ -227,7 +229,7 @@ def test_check_workspace_mismatch_raises_422_on_mismatch(flask_app):
def test_check_workspace_mismatch_passes_when_no_request_workspace_id(flask_app):
- tenant = MagicMock(spec=Tenant)
+ tenant = Tenant(name="Test Tenant")
tenant.id = uuid.uuid4()
with flask_app.test_request_context("/test"):
check_workspace_mismatch(_data(tenant=tenant, path_params={}))
@@ -267,14 +269,16 @@ def test_check_workspace_role_passes_when_role_allowed():
def test_check_app_api_enabled_passes_when_enabled():
- app = MagicMock(spec=App)
- app.enable_api = True
+ app = App(
+ enable_api=True,
+ )
check_app_api_enabled(_data(app=app))
def test_check_app_api_enabled_raises_forbidden_when_disabled():
- app = MagicMock(spec=App)
- app.enable_api = False
+ app = App(
+ enable_api=False,
+ )
with pytest.raises(Forbidden, match="service_api_disabled"):
check_app_api_enabled(_data(app=app))
diff --git a/api/tests/unit_tests/controllers/service_api/app/test_annotation.py b/api/tests/unit_tests/controllers/service_api/app/test_annotation.py
index 6d60af54e2e..866018bd49d 100644
--- a/api/tests/unit_tests/controllers/service_api/app/test_annotation.py
+++ b/api/tests/unit_tests/controllers/service_api/app/test_annotation.py
@@ -110,25 +110,28 @@ class TestAppModelPatterns:
def test_app_model_has_required_fields(self):
"""Test App model has required fields for annotation operations."""
- app = Mock(spec=App)
- app.id = str(uuid.uuid4())
- app.status = "normal"
- app.enable_api = True
+ app = App(
+ id=str(uuid.uuid4()),
+ status="normal",
+ enable_api=True,
+ )
assert app.id is not None
assert app.status == "normal"
assert app.enable_api
def test_app_model_disabled_api(self):
"""Test app with disabled API access."""
- app = Mock(spec=App)
- app.enable_api = False
+ app = App(
+ enable_api=False,
+ )
assert not app.enable_api
def test_app_model_archived_status(self):
"""Test app with archived status."""
- app = Mock(spec=App)
- app.status = "archived"
+ app = App(
+ status="archived",
+ )
assert app.status == "archived"
diff --git a/api/tests/unit_tests/controllers/service_api/app/test_audio.py b/api/tests/unit_tests/controllers/service_api/app/test_audio.py
index 2019891d281..d41bfc69109 100644
--- a/api/tests/unit_tests/controllers/service_api/app/test_audio.py
+++ b/api/tests/unit_tests/controllers/service_api/app/test_audio.py
@@ -143,11 +143,12 @@ class TestAudioServiceMockedBehavior:
@pytest.fixture
def mock_app(self):
- """Create mock app model."""
+ """Create an app model."""
from models.model import App
- app = Mock(spec=App)
- app.id = str(uuid.uuid4())
+ app = App(
+ id=str(uuid.uuid4()),
+ )
return app
@pytest.fixture
diff --git a/api/tests/unit_tests/controllers/service_api/app/test_conversation.py b/api/tests/unit_tests/controllers/service_api/app/test_conversation.py
index 09f0d430eff..537e9cda7fe 100644
--- a/api/tests/unit_tests/controllers/service_api/app/test_conversation.py
+++ b/api/tests/unit_tests/controllers/service_api/app/test_conversation.py
@@ -56,8 +56,9 @@ from services.errors.conversation import (
def _end_user(user_id: str = "end-user-1") -> EndUser:
- end_user = EndUser()
- end_user.id = user_id
+ end_user = EndUser(
+ id=user_id,
+ )
return end_user
@@ -375,8 +376,9 @@ class TestConversationAppModeValidation:
Verifies that CHAT, AGENT_CHAT, AGENT, and ADVANCED_CHAT modes pass
validation without raising NotChatAppError.
"""
- app = Mock(spec=App)
- app.mode = mode
+ app = App(
+ mode=mode,
+ )
# Validation should pass without raising for chat modes
app_mode = AppMode.value_of(app.mode)
@@ -388,8 +390,9 @@ class TestConversationAppModeValidation:
Verifies that calling a conversation endpoint with a COMPLETION mode
app raises NotChatAppError.
"""
- app = Mock(spec=App)
- app.mode = AppMode.COMPLETION
+ app = App(
+ mode=AppMode.COMPLETION,
+ )
app_mode = AppMode.value_of(app.mode)
assert app_mode not in {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT}
@@ -402,8 +405,9 @@ class TestConversationAppModeValidation:
Verifies that calling a conversation endpoint with a WORKFLOW mode
app raises NotChatAppError.
"""
- app = Mock(spec=App)
- app.mode = AppMode.WORKFLOW
+ app = App(
+ mode=AppMode.WORKFLOW,
+ )
app_mode = AppMode.value_of(app.mode)
assert app_mode not in {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT}
@@ -478,8 +482,8 @@ class TestConversationService:
mock_pagination.return_value = mock_result
result = ConversationService.pagination_by_last_id(
- app_model=Mock(spec=App),
- user=Mock(spec=EndUser),
+ app_model=App(),
+ user=EndUser(),
last_id=None,
limit=20,
invoke_from=Mock(),
@@ -498,8 +502,9 @@ class TestConversationService:
sqlite_session.add(conversation)
sqlite_session.commit()
- app_model = App()
- app_model.id = "app-1"
+ app_model = App(
+ id="app-1",
+ )
end_user = _end_user()
result = ConversationService.rename(
diff --git a/api/tests/unit_tests/controllers/service_api/app/test_file.py b/api/tests/unit_tests/controllers/service_api/app/test_file.py
index 184723a06ae..2a714600be9 100644
--- a/api/tests/unit_tests/controllers/service_api/app/test_file.py
+++ b/api/tests/unit_tests/controllers/service_api/app/test_file.py
@@ -210,9 +210,10 @@ from inspect import unwrap
def mock_app_model():
from models import App
- app = Mock(spec=App)
- app.id = str(uuid.uuid4())
- app.tenant_id = str(uuid.uuid4())
+ app = App(
+ id=str(uuid.uuid4()),
+ tenant_id=str(uuid.uuid4()),
+ )
return app
@@ -220,8 +221,9 @@ def mock_app_model():
def mock_end_user():
from models import EndUser
- user = Mock(spec=EndUser)
- user.id = str(uuid.uuid4())
+ user = EndUser(
+ id=str(uuid.uuid4()),
+ )
return user
diff --git a/api/tests/unit_tests/controllers/service_api/app/test_hitl_service_api.py b/api/tests/unit_tests/controllers/service_api/app/test_hitl_service_api.py
index 005d1ea7502..6b6581d86f3 100644
--- a/api/tests/unit_tests/controllers/service_api/app/test_hitl_service_api.py
+++ b/api/tests/unit_tests/controllers/service_api/app/test_hitl_service_api.py
@@ -117,10 +117,8 @@ def _build_service_api_pause_converter() -> WorkflowResponseConverter:
workflow_id="workflow-id",
workflow_execution_id="run-id",
)
- user = MagicMock(spec=Account)
+ user = Account(name="Tester", email="[email protected]")
user.id = "account-id"
- user.name = "Tester"
- user.email = "[email protected]"
return WorkflowResponseConverter(
application_generate_entity=application_generate_entity,
user=user,
diff --git a/api/tests/unit_tests/controllers/service_api/app/test_message.py b/api/tests/unit_tests/controllers/service_api/app/test_message.py
index 14bd2672d60..2920e6565ad 100644
--- a/api/tests/unit_tests/controllers/service_api/app/test_message.py
+++ b/api/tests/unit_tests/controllers/service_api/app/test_message.py
@@ -273,8 +273,8 @@ class TestMessageService:
mock_pagination.return_value = mock_result
result = MessageService.pagination_by_first_id(
- app_model=Mock(spec=App),
- user=Mock(spec=EndUser),
+ app_model=App(),
+ user=EndUser(),
conversation_id=str(uuid.uuid4()),
first_id=None,
limit=20,
@@ -294,8 +294,8 @@ class TestMessageService:
with pytest.raises(services.errors.conversation.ConversationNotExistsError):
MessageService.pagination_by_first_id(
- app_model=Mock(spec=App),
- user=Mock(spec=EndUser),
+ app_model=App(),
+ user=EndUser(),
conversation_id="invalid_id",
first_id=None,
limit=20,
@@ -309,8 +309,8 @@ class TestMessageService:
with pytest.raises(FirstMessageNotExistsError):
MessageService.pagination_by_first_id(
- app_model=Mock(spec=App),
- user=Mock(spec=EndUser),
+ app_model=App(),
+ user=EndUser(),
conversation_id=str(uuid.uuid4()),
first_id="invalid_first_id",
limit=20,
@@ -323,9 +323,9 @@ class TestMessageService:
mock_create_feedback.return_value = None
MessageService.create_feedback(
- app_model=Mock(spec=App),
+ app_model=App(),
message_id=str(uuid.uuid4()),
- user=Mock(spec=EndUser),
+ user=EndUser(),
rating=FeedbackRating.LIKE,
content="Great response!",
session=orm_session,
@@ -340,9 +340,9 @@ class TestMessageService:
with pytest.raises(MessageNotExistsError):
MessageService.create_feedback(
- app_model=Mock(spec=App),
+ app_model=App(),
message_id="invalid_message_id",
- user=Mock(spec=EndUser),
+ user=EndUser(),
rating=FeedbackRating.LIKE,
content=None,
session=orm_session,
@@ -357,9 +357,7 @@ class TestMessageService:
]
mock_get_feedbacks.return_value = mock_feedbacks
- result = MessageService.get_all_messages_feedbacks(
- app_model=Mock(spec=App), page=1, limit=20, session=orm_session
- )
+ result = MessageService.get_all_messages_feedbacks(app_model=App(), page=1, limit=20, session=orm_session)
assert len(result) == 2
assert result[0]["rating"] == "like"
@@ -371,8 +369,8 @@ class TestMessageService:
mock_get_questions.return_value = mock_questions
result = MessageService.get_suggested_questions_after_answer(
- app_model=Mock(spec=App),
- user=Mock(spec=EndUser),
+ app_model=App(),
+ user=EndUser(),
message_id=str(uuid.uuid4()),
invoke_from=Mock(),
session=orm_session,
@@ -388,8 +386,8 @@ class TestMessageService:
with pytest.raises(SuggestedQuestionsAfterAnswerDisabledError):
MessageService.get_suggested_questions_after_answer(
- app_model=Mock(spec=App),
- user=Mock(spec=EndUser),
+ app_model=App(),
+ user=EndUser(),
message_id=str(uuid.uuid4()),
invoke_from=Mock(),
session=orm_session,
@@ -402,8 +400,8 @@ class TestMessageService:
with pytest.raises(MessageNotExistsError):
MessageService.get_suggested_questions_after_answer(
- app_model=Mock(spec=App),
- user=Mock(spec=EndUser),
+ app_model=App(),
+ user=EndUser(),
message_id="invalid_message_id",
invoke_from=Mock(),
session=orm_session,
diff --git a/api/tests/unit_tests/controllers/service_api/conftest.py b/api/tests/unit_tests/controllers/service_api/conftest.py
index bede4d75850..126ac8e8763 100644
--- a/api/tests/unit_tests/controllers/service_api/conftest.py
+++ b/api/tests/unit_tests/controllers/service_api/conftest.py
@@ -83,25 +83,27 @@ def mock_app_id():
@pytest.fixture
def mock_end_user(mock_tenant_id):
"""Create a mock EndUser model with required attributes."""
- user = Mock(spec=EndUser)
- user.id = str(uuid.uuid4())
- user.external_user_id = f"external_{uuid.uuid4().hex[:8]}"
- user.tenant_id = mock_tenant_id
+ user = EndUser(
+ id=str(uuid.uuid4()),
+ external_user_id=f"external_{uuid.uuid4().hex[:8]}",
+ tenant_id=mock_tenant_id,
+ )
return user
@pytest.fixture
def mock_app_model(mock_app_id, mock_tenant_id):
- """Create a mock App model with all required attributes for API testing."""
- app = Mock(spec=App)
- app.id = mock_app_id
- app.tenant_id = mock_tenant_id
- app.name = "Test App"
- app.description = "A test application"
- app.mode = AppMode.CHAT
+ """Create an App model with all required attributes for API testing."""
+ app = App(
+ id=mock_app_id,
+ tenant_id=mock_tenant_id,
+ name="Test App",
+ description="A test application",
+ mode=AppMode.CHAT,
+ status="normal",
+ enable_api=True,
+ )
app.author_name = "Test Author"
- app.status = "normal"
- app.enable_api = True
app.tags = []
# Mock workflow for workflow apps
@@ -113,7 +115,7 @@ def mock_app_model(mock_app_id, mock_tenant_id):
@pytest.fixture
def mock_tenant(mock_tenant_id):
- """Create a mock Tenant model."""
+ """Create a Tenant model."""
tenant = Mock()
tenant.id = mock_tenant_id
tenant.status = TenantStatus.NORMAL
@@ -122,7 +124,7 @@ def mock_tenant(mock_tenant_id):
@pytest.fixture
def mock_account():
- """Create a mock Account model."""
+ """Create an Account model."""
account = Mock()
account.id = str(uuid.uuid4())
return account
@@ -151,50 +153,55 @@ def mock_dataset_api_token(mock_tenant_id):
@pytest.fixture
def mock_dataset():
- """Create a mock Dataset model."""
+ """Create a Dataset model."""
from models.dataset import Dataset
- dataset = Mock(spec=Dataset)
- dataset.id = str(uuid.uuid4())
- dataset.tenant_id = str(uuid.uuid4())
- dataset.name = "Test Dataset"
- dataset.indexing_technique = "economy"
- dataset.embedding_model = None
- dataset.embedding_model_provider = None
+ dataset = Dataset(
+ id=str(uuid.uuid4()),
+ tenant_id=str(uuid.uuid4()),
+ name="Test Dataset",
+ indexing_technique="economy",
+ embedding_model=None,
+ embedding_model_provider=None,
+ )
return dataset
@pytest.fixture
def mock_document():
- """Create a mock Document model."""
+ """Create a Document model."""
from models.dataset import Document
- document = Mock(spec=Document)
- document.id = str(uuid.uuid4())
- document.dataset_id = str(uuid.uuid4())
- document.tenant_id = str(uuid.uuid4())
- document.name = "test_document.txt"
- document.indexing_status = "completed"
- document.enabled = True
- document.doc_form = IndexStructureType.PARAGRAPH_INDEX
+ document = Document(
+ id=str(uuid.uuid4()),
+ dataset_id=str(uuid.uuid4()),
+ tenant_id=str(uuid.uuid4()),
+ name="test_document.txt",
+ indexing_status="completed",
+ enabled=True,
+ doc_form=IndexStructureType.PARAGRAPH_INDEX,
+ )
return document
@pytest.fixture
def mock_segment():
- """Create a mock DocumentSegment model."""
+ """Create a DocumentSegment model."""
from models.dataset import DocumentSegment
- segment = Mock(spec=DocumentSegment)
+ segment = DocumentSegment(
+ tenant_id=str(uuid.uuid4()),
+ dataset_id=str(uuid.uuid4()),
+ document_id=str(uuid.uuid4()),
+ position=1,
+ content="Test segment content",
+ word_count=3,
+ tokens=0,
+ created_by="account-id",
+ enabled=True,
+ status="completed",
+ )
segment.id = str(uuid.uuid4())
- segment.document_id = str(uuid.uuid4())
- segment.dataset_id = str(uuid.uuid4())
- segment.tenant_id = str(uuid.uuid4())
- segment.content = "Test segment content"
- segment.word_count = 3
- segment.position = 1
- segment.enabled = True
- segment.status = "completed"
return segment
@@ -203,9 +210,15 @@ def mock_child_chunk():
"""Create a mock ChildChunk model."""
from models.dataset import ChildChunk
- child_chunk = Mock(spec=ChildChunk)
+ child_chunk = ChildChunk(
+ tenant_id=str(uuid.uuid4()),
+ dataset_id="dataset-id",
+ document_id="document-id",
+ segment_id=str(uuid.uuid4()),
+ position=1,
+ content="Test child chunk content",
+ word_count=0,
+ created_by="account-id",
+ )
child_chunk.id = str(uuid.uuid4())
- child_chunk.segment_id = str(uuid.uuid4())
- child_chunk.tenant_id = str(uuid.uuid4())
- child_chunk.content = "Test child chunk content"
return child_chunk
diff --git a/api/tests/unit_tests/controllers/service_api/dataset/rag_pipeline/test_rag_pipeline_workflow.py b/api/tests/unit_tests/controllers/service_api/dataset/rag_pipeline/test_rag_pipeline_workflow.py
index a55e3b8cbaa..92018a8c233 100644
--- a/api/tests/unit_tests/controllers/service_api/dataset/rag_pipeline/test_rag_pipeline_workflow.py
+++ b/api/tests/unit_tests/controllers/service_api/dataset/rag_pipeline/test_rag_pipeline_workflow.py
@@ -494,7 +494,7 @@ class TestDatasourceNodeRunApiPost:
@patch("controllers.service_api.dataset.rag_pipeline.rag_pipeline_workflow.PipelineGenerator")
@patch(
"controllers.service_api.dataset.rag_pipeline.rag_pipeline_workflow.current_user",
- new_callable=lambda: Mock(spec=Account),
+ new_callable=lambda: Account(name="Test Account", email="[email protected]"),
)
@patch("controllers.service_api.dataset.rag_pipeline.rag_pipeline_workflow.RagPipelineService")
@patch("controllers.service_api.dataset.rag_pipeline.rag_pipeline_workflow.db")
@@ -570,7 +570,7 @@ class TestPipelineRunApiPost:
@patch("controllers.service_api.dataset.rag_pipeline.rag_pipeline_workflow.PipelineGenerateService")
@patch(
"controllers.service_api.dataset.rag_pipeline.rag_pipeline_workflow.current_user",
- new_callable=lambda: Mock(spec=Account),
+ new_callable=lambda: Account(name="Test Account", email="[email protected]"),
)
@patch("controllers.service_api.dataset.rag_pipeline.rag_pipeline_workflow.RagPipelineService")
@patch("controllers.service_api.dataset.rag_pipeline.rag_pipeline_workflow.service_api_ns")
diff --git a/api/tests/unit_tests/controllers/service_api/dataset/test_dataset_segment.py b/api/tests/unit_tests/controllers/service_api/dataset/test_dataset_segment.py
index c7bac28b694..9fae95edcfc 100644
--- a/api/tests/unit_tests/controllers/service_api/dataset/test_dataset_segment.py
+++ b/api/tests/unit_tests/controllers/service_api/dataset/test_dataset_segment.py
@@ -100,9 +100,9 @@ def _child_chunk() -> ChildChunk:
content="child chunk content",
word_count=3,
created_by="account-1",
+ type=SegmentType.CUSTOMIZED,
)
child_chunk.id = "child-1"
- child_chunk.type = SegmentType.CUSTOMIZED
child_chunk.created_at = naive_utc_now()
child_chunk.updated_at = naive_utc_now()
return child_chunk
@@ -358,34 +358,64 @@ class TestSegmentServiceMockedBehavior:
@pytest.fixture
def mock_dataset(self):
"""Create mock dataset."""
- dataset = Mock(spec=Dataset)
- dataset.id = str(uuid.uuid4())
- dataset.tenant_id = str(uuid.uuid4())
+ dataset = Dataset(
+ id=str(uuid.uuid4()),
+ tenant_id=str(uuid.uuid4()),
+ )
return dataset
@pytest.fixture
def mock_document(self):
"""Create mock document."""
- document = Mock(spec=Document)
- document.id = str(uuid.uuid4())
- document.dataset_id = str(uuid.uuid4())
- document.indexing_status = "completed"
- document.enabled = True
+ document = Document(
+ id=str(uuid.uuid4()),
+ dataset_id=str(uuid.uuid4()),
+ indexing_status="completed",
+ enabled=True,
+ )
return document
@pytest.fixture
def mock_segment(self):
"""Create mock segment."""
- segment = Mock(spec=DocumentSegment)
+ segment = DocumentSegment(
+ tenant_id="tenant-id",
+ dataset_id="dataset-id",
+ document_id=str(uuid.uuid4()),
+ position=1,
+ content="Test content",
+ word_count=0,
+ tokens=0,
+ created_by="account-id",
+ )
segment.id = str(uuid.uuid4())
- segment.document_id = str(uuid.uuid4())
- segment.content = "Test content"
return segment
@patch.object(SegmentService, "multi_create_segment")
def test_create_segments_returns_list(self, mock_create, mock_dataset, mock_document):
"""Test segment creation returns list of segments."""
- mock_segments = [Mock(spec=DocumentSegment), Mock(spec=DocumentSegment)]
+ mock_segments = [
+ DocumentSegment(
+ tenant_id="tenant-id",
+ dataset_id="dataset-id",
+ document_id="document-id",
+ position=1,
+ content="",
+ word_count=0,
+ tokens=0,
+ created_by="account-id",
+ ),
+ DocumentSegment(
+ tenant_id="tenant-id",
+ dataset_id="dataset-id",
+ document_id="document-id",
+ position=1,
+ content="",
+ word_count=0,
+ tokens=0,
+ created_by="account-id",
+ ),
+ ]
mock_create.return_value = mock_segments
session = Mock()
@@ -459,17 +489,33 @@ class TestChildChunkServiceMockedBehavior:
@pytest.fixture
def mock_segment(self):
"""Create mock segment."""
- segment = Mock(spec=DocumentSegment)
+ segment = DocumentSegment(
+ tenant_id="tenant-id",
+ dataset_id="dataset-id",
+ document_id="document-id",
+ position=1,
+ content="",
+ word_count=0,
+ tokens=0,
+ created_by="account-id",
+ )
segment.id = str(uuid.uuid4())
return segment
@pytest.fixture
def mock_child_chunk(self):
"""Create mock child chunk."""
- chunk = Mock(spec=ChildChunk)
+ chunk = ChildChunk(
+ tenant_id="tenant-id",
+ dataset_id="dataset-id",
+ document_id="document-id",
+ segment_id=str(uuid.uuid4()),
+ position=1,
+ content="Child chunk content",
+ word_count=0,
+ created_by="account-id",
+ )
chunk.id = str(uuid.uuid4())
- chunk.segment_id = str(uuid.uuid4())
- chunk.content = "Child chunk content"
return chunk
@patch.object(SegmentService, "create_child_chunk")
@@ -480,8 +526,8 @@ class TestChildChunkServiceMockedBehavior:
result = SegmentService.create_child_chunk(
content="New chunk content",
segment=mock_segment,
- document=Mock(spec=Document),
- dataset=Mock(spec=Dataset),
+ document=Document(),
+ dataset=Dataset(),
session=Mock(),
)
@@ -524,16 +570,33 @@ class TestChildChunkServiceMockedBehavior:
@patch.object(SegmentService, "update_child_chunk")
def test_update_child_chunk_returns_updated_chunk(self, mock_update, mock_child_chunk):
"""Test update_child_chunk returns updated chunk."""
- updated_chunk = Mock(spec=ChildChunk)
- updated_chunk.content = "Updated content"
+ updated_chunk = ChildChunk(
+ tenant_id="tenant-id",
+ dataset_id="dataset-id",
+ document_id="document-id",
+ segment_id="segment-id",
+ position=1,
+ content="Updated content",
+ word_count=0,
+ created_by="account-id",
+ )
mock_update.return_value = updated_chunk
result = SegmentService.update_child_chunk(
content="Updated content",
child_chunk=mock_child_chunk,
- segment=Mock(spec=DocumentSegment),
- document=Mock(spec=Document),
- dataset=Mock(spec=Dataset),
+ segment=DocumentSegment(
+ tenant_id="tenant-id",
+ dataset_id="dataset-id",
+ document_id="document-id",
+ position=1,
+ content="",
+ word_count=0,
+ tokens=0,
+ created_by="account-id",
+ ),
+ document=Document(),
+ dataset=Dataset(),
session=Mock(),
)
@@ -545,26 +608,30 @@ class TestDocumentValidation:
def test_document_indexing_status_completed_is_valid(self):
"""Test that completed indexing status is valid."""
- document = Mock(spec=Document)
- document.indexing_status = "completed"
+ document = Document(
+ indexing_status="completed",
+ )
assert document.indexing_status == "completed"
def test_document_indexing_status_indexing_is_invalid(self):
"""Test that indexing status is invalid for segment operations."""
- document = Mock(spec=Document)
- document.indexing_status = "indexing"
+ document = Document(
+ indexing_status="indexing",
+ )
assert document.indexing_status != "completed"
def test_document_enabled_true_is_valid(self):
"""Test that enabled=True is valid."""
- document = Mock(spec=Document)
- document.enabled = True
+ document = Document(
+ enabled=True,
+ )
assert document.enabled
def test_document_enabled_false_is_invalid(self):
"""Test that enabled=False is invalid for segment operations."""
- document = Mock(spec=Document)
- document.enabled = False
+ document = Document(
+ enabled=False,
+ )
assert not document.enabled
@@ -573,10 +640,11 @@ class TestDatasetModels:
def test_dataset_has_required_fields(self):
"""Test Dataset model has required fields."""
- dataset = Mock(spec=Dataset)
- dataset.id = str(uuid.uuid4())
- dataset.tenant_id = str(uuid.uuid4())
- dataset.indexing_technique = "economy"
+ dataset = Dataset(
+ id=str(uuid.uuid4()),
+ tenant_id=str(uuid.uuid4()),
+ indexing_technique="economy",
+ )
assert dataset.id is not None
assert dataset.tenant_id is not None
@@ -584,11 +652,17 @@ class TestDatasetModels:
def test_document_segment_has_required_fields(self):
"""Test DocumentSegment model has required fields."""
- segment = Mock(spec=DocumentSegment)
+ segment = DocumentSegment(
+ tenant_id="tenant-id",
+ dataset_id="dataset-id",
+ document_id=str(uuid.uuid4()),
+ position=1,
+ content="Test content",
+ word_count=0,
+ tokens=0,
+ created_by="account-id",
+ )
segment.id = str(uuid.uuid4())
- segment.document_id = str(uuid.uuid4())
- segment.content = "Test content"
- segment.position = 1
assert segment.id is not None
assert segment.document_id is not None
@@ -596,10 +670,17 @@ class TestDatasetModels:
def test_child_chunk_has_required_fields(self):
"""Test ChildChunk model has required fields."""
- chunk = Mock(spec=ChildChunk)
+ chunk = ChildChunk(
+ tenant_id="tenant-id",
+ dataset_id="dataset-id",
+ document_id="document-id",
+ segment_id=str(uuid.uuid4()),
+ position=1,
+ content="Chunk content",
+ word_count=0,
+ created_by="account-id",
+ )
chunk.id = str(uuid.uuid4())
- chunk.segment_id = str(uuid.uuid4())
- chunk.content = "Chunk content"
assert chunk.id is not None
assert chunk.segment_id is not None
@@ -787,8 +868,9 @@ class TestSegmentIndexingRequirements:
@pytest.mark.parametrize("technique", ["high_quality", "economy"])
def test_indexing_technique_values(self, technique):
"""Test valid indexing technique values."""
- dataset = Mock(spec=Dataset)
- dataset.indexing_technique = technique
+ dataset = Dataset(
+ indexing_technique=technique,
+ )
assert dataset.indexing_technique in ["high_quality", "economy"]
@pytest.mark.parametrize(
@@ -803,8 +885,9 @@ class TestSegmentIndexingRequirements:
)
def test_valid_indexing_statuses(self, status):
"""Test valid document indexing statuses."""
- document = Mock(spec=Document)
- document.indexing_status = status
+ document = Document(
+ indexing_status=status,
+ )
assert document.indexing_status in {
IndexingStatus.WAITING,
IndexingStatus.PARSING,
@@ -815,9 +898,10 @@ class TestSegmentIndexingRequirements:
def test_completed_status_required_for_segments(self):
"""Test that completed status is required for segment operations."""
- document = Mock(spec=Document)
- document.indexing_status = "completed"
- document.enabled = True
+ document = Document(
+ indexing_status="completed",
+ enabled=True,
+ )
# Both conditions must be true
assert document.indexing_status == "completed"
diff --git a/api/tests/unit_tests/controllers/service_api/end_user/test_end_user.py b/api/tests/unit_tests/controllers/service_api/end_user/test_end_user.py
index 687c1a67b1a..30449f4b6b3 100644
--- a/api/tests/unit_tests/controllers/service_api/end_user/test_end_user.py
+++ b/api/tests/unit_tests/controllers/service_api/end_user/test_end_user.py
@@ -1,5 +1,4 @@
from datetime import UTC, datetime
-from unittest.mock import Mock
from uuid import UUID, uuid4
import pytest
@@ -18,25 +17,27 @@ class TestEndUserApi:
@pytest.fixture
def app_model(self) -> App:
- app = Mock(spec=App)
- app.id = str(uuid4())
- app.tenant_id = str(uuid4())
+ app = App(
+ id=str(uuid4()),
+ tenant_id=str(uuid4()),
+ )
return app
def test_get_end_user_returns_all_attributes(
self, mocker: MockerFixture, resource: EndUserApi, app_model: App
) -> None:
- end_user = Mock(spec=EndUser)
- end_user.id = str(uuid4())
- end_user.tenant_id = app_model.tenant_id
- end_user.app_id = app_model.id
- end_user.type = EndUserType.SERVICE_API
- end_user.external_user_id = "external-123"
- end_user.name = "Alice"
- end_user._is_anonymous = True
- end_user.session_id = "session-xyz"
- end_user.created_at = datetime(2024, 1, 1, tzinfo=UTC)
- end_user.updated_at = datetime(2024, 1, 2, tzinfo=UTC)
+ end_user = EndUser(
+ id=str(uuid4()),
+ tenant_id=app_model.tenant_id,
+ app_id=app_model.id,
+ type=EndUserType.SERVICE_API,
+ external_user_id="external-123",
+ name="Alice",
+ _is_anonymous=True,
+ session_id="session-xyz",
+ created_at=datetime(2024, 1, 1, tzinfo=UTC),
+ updated_at=datetime(2024, 1, 2, tzinfo=UTC),
+ )
get_end_user_by_id = mocker.patch(
"controllers.service_api.end_user.end_user.EndUserService.get_end_user_by_id", return_value=end_user
diff --git a/api/tests/unit_tests/controllers/web/test_site.py b/api/tests/unit_tests/controllers/web/test_site.py
index f7a44afad6a..8253933937d 100644
--- a/api/tests/unit_tests/controllers/web/test_site.py
+++ b/api/tests/unit_tests/controllers/web/test_site.py
@@ -14,7 +14,7 @@ def test_app_site_api_returns_legacy_agent_compatible_mode() -> None:
app_model.tenant = MagicMock(id="tenant-id", status="normal")
app_model.mode_compatible_with_agent_with_session.return_value = AppMode.AGENT_CHAT
end_user = MagicMock(id="end-user-id")
- site = MagicMock(spec=Site)
+ site = Site()
response = MagicMock()
response.model_dump.return_value = {"mode": AppMode.AGENT_CHAT}
@@ -42,9 +42,10 @@ def test_app_site_api_returns_legacy_agent_compatible_mode() -> None:
def test_build_site_icon_url_uses_s3_presigned_url() -> None:
- site = MagicMock(spec=Site)
- site.icon_type = IconType.IMAGE
- site.icon = "11111111-1111-4111-8111-111111111111"
+ site = Site(
+ icon_type=IconType.IMAGE,
+ icon="11111111-1111-4111-8111-111111111111",
+ )
with (
patch.object(dify_config, "EDITION", "CLOUD"),
@@ -69,9 +70,10 @@ def test_build_site_icon_url_uses_s3_presigned_url() -> None:
def test_build_site_icon_url_keeps_preview_url_for_self_hosted_s3() -> None:
- site = MagicMock(spec=Site)
- site.icon_type = IconType.IMAGE
- site.icon = "11111111-1111-4111-8111-111111111111"
+ site = Site(
+ icon_type=IconType.IMAGE,
+ icon="11111111-1111-4111-8111-111111111111",
+ )
with (
patch.object(dify_config, "EDITION", "SELF_HOSTED"),
@@ -86,9 +88,10 @@ def test_build_site_icon_url_keeps_preview_url_for_self_hosted_s3() -> None:
def test_build_site_icon_url_keeps_preview_url_for_non_s3_storage() -> None:
- site = MagicMock(spec=Site)
- site.icon_type = IconType.IMAGE
- site.icon = "11111111-1111-4111-8111-111111111111"
+ site = Site(
+ icon_type=IconType.IMAGE,
+ icon="11111111-1111-4111-8111-111111111111",
+ )
with (
patch.object(dify_config, "EDITION", "CLOUD"),
diff --git a/api/tests/unit_tests/core/app/apps/agent_app/test_app_generator.py b/api/tests/unit_tests/core/app/apps/agent_app/test_app_generator.py
index d193231b96e..d346dfe9601 100644
--- a/api/tests/unit_tests/core/app/apps/agent_app/test_app_generator.py
+++ b/api/tests/unit_tests/core/app/apps/agent_app/test_app_generator.py
@@ -512,7 +512,7 @@ class TestResumeAfterFormSubmission:
conversation = mocker.MagicMock(id="conv", invoke_from=InvokeFrom.DEBUGGER)
mocker.patch(f"{MODULE}.ConversationService.get_conversation", return_value=conversation)
generator._resolve_resume_draft.return_value = ("debug_build", "draft-build-1")
- account_user = mocker.MagicMock(spec=Account)
+ account_user = Account(name="Test Account", email="[email protected]")
account_user.id = "user"
app_model = mocker.MagicMock(id="app1", tenant_id="tenant", mode="agent")
app_model.app_model_config_id = "config-1"
diff --git a/api/tests/unit_tests/core/app/apps/common/test_workflow_response_converter_truncation.py b/api/tests/unit_tests/core/app/apps/common/test_workflow_response_converter_truncation.py
index b3c0eb74faa..ecf58070655 100644
--- a/api/tests/unit_tests/core/app/apps/common/test_workflow_response_converter_truncation.py
+++ b/api/tests/unit_tests/core/app/apps/common/test_workflow_response_converter_truncation.py
@@ -49,10 +49,11 @@ class TestWorkflowResponseConverter:
"""Create a WorkflowResponseConverter for testing."""
mock_entity = self.create_mock_generate_entity()
- mock_user = Mock(spec=Account)
+ mock_user = Account(
+ name="Test User",
+ )
mock_user.id = "test-user-id"
- mock_user.name = "Test User"
- mock_user.email = "[email protected]"
system_variables = build_system_variables(workflow_id="wf-id", workflow_execution_id="initial-run-id")
return WorkflowResponseConverter(
diff --git a/api/tests/unit_tests/extensions/otel/test_retrieval_tracing.py b/api/tests/unit_tests/extensions/otel/test_retrieval_tracing.py
index 586d39f8f60..79273d07019 100644
--- a/api/tests/unit_tests/extensions/otel/test_retrieval_tracing.py
+++ b/api/tests/unit_tests/extensions/otel/test_retrieval_tracing.py
@@ -51,11 +51,12 @@ def test_multiple_retrieve_preserves_otel_context_in_dataset_thread(
) -> None:
"""Per-dataset retrieval spans must remain in the workflow node trace."""
retrieval = DatasetRetrieval()
- dataset = MagicMock(spec=Dataset)
- dataset.id = str(uuid4())
- dataset.indexing_technique = "high_quality"
- dataset.embedding_model = "text-embedding-3-small"
- dataset.embedding_model_provider = "openai"
+ dataset = Dataset(
+ id=str(uuid4()),
+ indexing_technique="high_quality",
+ embedding_model="text-embedding-3-small",
+ embedding_model_provider="openai",
+ )
observed_trace_ids: list[int] = []
def record_active_trace(**_kwargs: object) -> None:
diff --git a/api/tests/unit_tests/extensions/test_ext_login.py b/api/tests/unit_tests/extensions/test_ext_login.py
index feb4930292f..bcf182c180e 100644
--- a/api/tests/unit_tests/extensions/test_ext_login.py
+++ b/api/tests/unit_tests/extensions/test_ext_login.py
@@ -9,6 +9,7 @@ from constants import COOKIE_NAME_ACCESS_TOKEN
from core.logging.context import clear_request_context, get_identity_context
from extensions import ext_login
from extensions.ext_login import unauthorized_handler
+from models.account import TenantAccountRole
@pytest.fixture(autouse=True)
@@ -31,9 +32,10 @@ def test_unauthorized_handler_returns_json_response() -> None:
def test_on_user_logged_in_sets_account_logging_identity() -> None:
- account = mock.Mock(spec=ext_login.Account)
+ account = ext_login.Account(name="Test Account", email="[email protected]")
account.id = "account-id"
- account.current_tenant_id = "tenant-id"
+ account._current_tenant = ext_login.Tenant(name="Test Tenant")
+ account._current_tenant.id = "tenant-id"
clear_request_context()
ext_login.on_user_logged_in(None, account)
@@ -42,10 +44,11 @@ def test_on_user_logged_in_sets_account_logging_identity() -> None:
def test_on_user_logged_in_sets_end_user_logging_identity() -> None:
- end_user = mock.Mock(spec=ext_login.EndUser)
- end_user.id = "end-user-id"
- end_user.tenant_id = "tenant-id"
- end_user.type = "browser"
+ end_user = ext_login.EndUser(
+ id="end-user-id",
+ tenant_id="tenant-id",
+ type="browser",
+ )
clear_request_context()
ext_login.on_user_logged_in(None, end_user)
@@ -54,12 +57,19 @@ def test_on_user_logged_in_sets_end_user_logging_identity() -> None:
def test_on_user_logged_in_does_not_break_auth_when_identity_is_unavailable(caplog: pytest.LogCaptureFixture) -> None:
- account = mock.Mock(spec=ext_login.Account)
- type(account).current_tenant_id = mock.PropertyMock(side_effect=RuntimeError("unavailable"))
+ account = ext_login.Account(name="Test Account", email="[email protected]")
account.id = "account-id"
clear_request_context()
- with caplog.at_level("ERROR", logger=ext_login.logger.name):
+ with (
+ mock.patch.object(
+ ext_login.Account,
+ "current_tenant_id",
+ new_callable=mock.PropertyMock,
+ side_effect=RuntimeError("unavailable"),
+ ),
+ caplog.at_level("ERROR", logger=ext_login.logger.name),
+ ):
ext_login.on_user_logged_in(None, account)
assert get_identity_context() == ("", "", "")
@@ -80,11 +90,16 @@ def test_on_user_logged_in_logs_unsupported_user_type(caplog: pytest.LogCaptureF
def test_admin_api_key_header_takes_precedence_over_console_cookie(monkeypatch: pytest.MonkeyPatch) -> None:
app = Flask(__name__)
session = mock.Mock(spec=ext_login.Session)
- tenant = mock.Mock(spec=ext_login.Tenant)
- tenant_account_join = mock.Mock(spec=ext_login.TenantAccountJoin)
- account = mock.Mock(spec=ext_login.Account)
+ tenant = ext_login.Tenant(name="Test Tenant")
+ tenant_account_join = ext_login.TenantAccountJoin(
+ tenant_id="tenant-id",
+ account_id="account-id",
+ role=TenantAccountRole.NORMAL,
+ )
+ account = ext_login.Account(name="Test Account", email="[email protected]")
session.execute.return_value.one_or_none.return_value = (tenant, tenant_account_join)
- session.scalar.return_value = account
+ session.scalar.side_effect = [account, tenant_account_join]
+ session.scalars.return_value.one.return_value = tenant
monkeypatch.setattr(ext_login.dify_config, "ADMIN_API_KEY_ENABLE", True)
monkeypatch.setattr(ext_login.dify_config, "ADMIN_API_KEY", "admin-key")
monkeypatch.setattr(ext_login.dify_config, "CONSOLE_WEB_URL", "http://console.example.com")
@@ -102,4 +117,4 @@ def test_admin_api_key_header_takes_precedence_over_console_cookie(monkeypatch:
result = ext_login._load_user_from_request(request, session)
assert result is account
- account.set_current_tenant_with_session.assert_called_once_with(tenant, session=session)
+ assert account.current_tenant is tenant
diff --git a/api/tests/unit_tests/models/test_app_models.py b/api/tests/unit_tests/models/test_app_models.py
index 5ef0f52d3d8..c90c8d72fc8 100644
--- a/api/tests/unit_tests/models/test_app_models.py
+++ b/api/tests/unit_tests/models/test_app_models.py
@@ -191,11 +191,12 @@ class TestAppModelValidation:
enable_site=True,
enable_api=False,
created_by=str(uuid4()),
+ app_model_config_id="config-1",
+ )
+ app_model_config = AppModelConfig(
+ app_id="app-id",
+ agent_mode=json.dumps({"enabled": True, "strategy": "react"}),
)
- app.app_model_config_id = "config-1"
- app_model_config = MagicMock(spec=AppModelConfig)
- app_model_config.agent_mode = "agent"
- app_model_config.agent_mode_dict = {"enabled": True, "strategy": "react"}
session = MagicMock()
session.get.return_value = app_model_config
@@ -582,18 +583,19 @@ class TestConversationModel:
model_id="model-1",
model_provider="provider-1",
)
- app_model_config = MagicMock(spec=AppModelConfig)
- app_model_config.app_id = "app-1"
- app_model_config.to_dict.return_value = {}
+ app_model_config = AppModelConfig(app_id="app-1")
session = MagicMock()
session.scalar.return_value = app_model_config
annotation_reply = {"enabled": False}
- with patch("models.model.load_annotation_reply_config", return_value=annotation_reply) as load_config:
+ with (
+ patch.object(AppModelConfig, "to_dict", return_value={}) as to_dict,
+ patch("models.model.load_annotation_reply_config", return_value=annotation_reply) as load_config,
+ ):
result = conversation.model_config_with_session(session=session)
load_config.assert_called_once_with(session, "app-1")
- app_model_config.to_dict.assert_called_once_with(annotation_reply=annotation_reply)
+ to_dict.assert_called_once_with(annotation_reply=annotation_reply)
assert result["model_id"] == "model-1"
assert result["provider"] == "provider-1"
@@ -607,20 +609,19 @@ class TestConversationModel:
from_end_user_id=str(uuid4()),
override_model_configs=json.dumps({"model": {}}),
)
- app_model_config = MagicMock(spec=AppModelConfig)
- app_model_config.app_id = "app-1"
- app_model_config.to_dict.return_value = {}
+ app_model_config = AppModelConfig(app_id="app-1")
session = MagicMock()
annotation_reply = {"enabled": False}
with (
patch.object(AppModelConfig, "from_model_config_dict", return_value=app_model_config),
+ patch.object(AppModelConfig, "to_dict", return_value={}) as to_dict,
patch("models.model.load_annotation_reply_config", return_value=annotation_reply) as load_config,
):
conversation.model_config_with_session(session=session)
load_config.assert_called_once_with(session, "app-1")
- app_model_config.to_dict.assert_called_once_with(annotation_reply=annotation_reply)
+ to_dict.assert_called_once_with(annotation_reply=annotation_reply)
session.scalar.assert_not_called()
def test_conversation_in_debug_mode(self):
@@ -718,8 +719,8 @@ class TestMessageModel:
answer_unit_price=Decimal("0.0002"),
currency="USD",
from_source=ConversationFromSource.API,
+ _inputs=inputs,
)
- message._inputs = inputs
# Act
result = message.inputs
@@ -835,11 +836,11 @@ class TestMessageModel:
currency="USD",
from_source=ConversationFromSource.API,
status="normal",
+ id=str(uuid4()),
+ _inputs={"query": "test"},
+ created_at=now,
+ updated_at=now,
)
- message.id = str(uuid4())
- message._inputs = {"query": "test"}
- message.created_at = now
- message.updated_at = now
# Act
result = message.to_dict()
@@ -1178,8 +1179,8 @@ class TestModelIntegration:
enable_site=True,
enable_api=True,
created_by=created_by,
+ id=app_id,
)
- app.id = app_id
# Create conversation
conversation = Conversation(
@@ -1203,8 +1204,8 @@ class TestModelIntegration:
answer_unit_price=Decimal("0.0002"),
currency="USD",
from_source=ConversationFromSource.API,
+ id=message_id,
)
- message.id = message_id
# Assert
assert app.id == app_id
@@ -1229,8 +1230,8 @@ class TestModelIntegration:
enable_site=True,
enable_api=True,
created_by=created_user_id,
+ id=app_id,
)
- app.id = app_id
# Create annotation setting
setting = AppAnnotationSetting(
@@ -1264,8 +1265,8 @@ class TestModelIntegration:
answer_unit_price=Decimal("0.0002"),
currency="USD",
from_source=ConversationFromSource.API,
+ id=message_id,
)
- message.id = message_id
# Create annotation
annotation = MessageAnnotation(
@@ -1332,8 +1333,8 @@ class TestModelIntegration:
enable_site=True,
enable_api=True,
created_by=str(uuid4()),
+ id=app_id,
)
- app.id = app_id
# Create site
site = Site(
diff --git a/api/tests/unit_tests/services/test_account_service.py b/api/tests/unit_tests/services/test_account_service.py
index 5be118b669a..d82ee5dbfc8 100644
--- a/api/tests/unit_tests/services/test_account_service.py
+++ b/api/tests/unit_tests/services/test_account_service.py
@@ -42,27 +42,28 @@ class TestAccountAssociatedDataFactory:
account_id: str = "user-123",
email: str = "[email protected]",
name: str = "Test User",
- status: str = "active",
+ status: AccountStatus | str = AccountStatus.ACTIVE,
password: str = "hashed_password",
password_salt: str = "salt",
interface_language: str = "en-US",
interface_theme: str = "light",
timezone: str = "UTC",
- ) -> MagicMock:
- """Create a mock account with specified attributes."""
- account = MagicMock(spec=Account)
+ ) -> Account:
+ """Create an account with specified attributes."""
+ account = Account(
+ name=name,
+ email=email,
+ password=password,
+ password_salt=password_salt,
+ interface_language=interface_language,
+ interface_theme=interface_theme,
+ timezone=timezone,
+ status=AccountStatus(status),
+ initialized_at=None,
+ )
account.id = account_id
- account.email = email
- account.name = name
- account.status = status
- account.password = password
- account.password_salt = password_salt
- account.interface_language = interface_language
- account.interface_theme = interface_theme
- account.timezone = timezone
# Set last_active_at to a datetime object that's older than 10 minutes
account.last_active_at = datetime.now() - timedelta(minutes=15)
- account.initialized_at = None
return account
@@ -809,10 +810,7 @@ class TestTenantService:
tenant = service_session.scalar(select(Tenant).where(Tenant.name == "Test User's Workspace"))
assert tenant is not None
tenant_id = tenant.id
- mock_account.set_current_tenant_with_session.assert_called_once_with(
- tenant,
- session=service_session,
- )
+ assert mock_account.current_tenant_id == tenant.id
mock_tenant_was_created.assert_called_once_with(tenant)
mock_rsa_dependencies.assert_called_once_with(tenant_id)
@@ -1095,14 +1093,14 @@ class TestTenantService:
"feature_service"
].get_license.return_value.workspaces.is_available.return_value = True
- mock_tenant = MagicMock()
+ mock_tenant = Tenant(name="RBAC User's Workspace")
mock_tenant.id = "tenant-rbac"
- mock_tenant.name = "RBAC User's Workspace"
+ sqlite_session.add(mock_tenant)
+ sqlite_session.flush()
with (
patch("services.account_service.dify_config.RBAC_ENABLED", True),
patch("services.account_service.TenantService.create_tenant", return_value=mock_tenant),
- patch("services.account_service.TenantService.create_tenant_member"),
patch(
"services.account_service.AccountService._resolve_legacy_role_id",
return_value="rbac-owner-id",
@@ -1509,7 +1507,7 @@ class TestRegisterService:
assert result == mock_account
mock_create_workspace.assert_called_once_with(account=mock_account, session=sqlite_session)
- mock_join_default_workspace.assert_called_once_with(str(mock_account.id))
+ mock_join_default_workspace.assert_called_once_with(mock_account.id)
def test_create_account_and_tenant_does_not_call_default_workspace_join_when_enterprise_disabled(
self,
@@ -1579,7 +1577,7 @@ class TestRegisterService:
session=sqlite_session,
)
- mock_join_default_workspace.assert_called_once_with(str(mock_account.id))
+ mock_join_default_workspace.assert_called_once_with(mock_account.id)
def test_register_success(
self, sqlite_session: Session, mock_external_service_dependencies: _MockDependencies
@@ -1657,7 +1655,7 @@ class TestRegisterService:
)
assert result == mock_account
- mock_join_default_workspace.assert_called_once_with(str(mock_account.id))
+ mock_join_default_workspace.assert_called_once_with(mock_account.id)
def test_register_does_not_call_default_workspace_join_when_enterprise_disabled(
self,
@@ -1730,7 +1728,7 @@ class TestRegisterService:
session=sqlite_session,
)
- mock_join_default_workspace.assert_called_once_with(str(mock_account.id))
+ mock_join_default_workspace.assert_called_once_with(mock_account.id)
def test_register_still_calls_default_workspace_join_when_workspace_limit_exceeded(
self,
@@ -1770,7 +1768,7 @@ class TestRegisterService:
session=sqlite_session,
)
- mock_join_default_workspace.assert_called_once_with(str(mock_account.id))
+ mock_join_default_workspace.assert_called_once_with(mock_account.id)
def test_register_with_oauth(
self, sqlite_session: Session, mock_external_service_dependencies: _MockDependencies
@@ -1798,8 +1796,17 @@ class TestRegisterService:
patch("services.account_service.TenantService.create_tenant_member") as mock_create_member,
patch("services.account_service.tenant_was_created") as mock_event,
):
- mock_tenant = MagicMock()
+ mock_tenant = Tenant(name="Test User's Workspace")
+ sqlite_session.add(mock_tenant)
+ sqlite_session.flush()
mock_create_tenant.return_value = mock_tenant
+ mock_create_member.side_effect = lambda tenant, account, session, role: session.add(
+ TenantAccountJoin(
+ tenant_id=tenant.id,
+ account_id=account.id,
+ role=TenantAccountRole(role),
+ )
+ )
# Execute test
result = RegisterService.register(
@@ -1839,8 +1846,17 @@ class TestRegisterService:
patch("services.account_service.TenantService.create_tenant_member") as mock_create_member,
patch("services.account_service.tenant_was_created") as mock_event,
):
- mock_tenant = MagicMock()
+ mock_tenant = Tenant(name="Test User's Workspace")
+ sqlite_session.add(mock_tenant)
+ sqlite_session.flush()
mock_create_tenant.return_value = mock_tenant
+ mock_create_member.side_effect = lambda tenant, account, session, role: session.add(
+ TenantAccountJoin(
+ tenant_id=tenant.id,
+ account_id=account.id,
+ role=TenantAccountRole(role),
+ )
+ )
# Execute test with pending status
from models.account import AccountStatus
diff --git a/api/tests/unit_tests/services/test_annotation_service.py b/api/tests/unit_tests/services/test_annotation_service.py
index d729b1c5a80..4814490c9d5 100644
--- a/api/tests/unit_tests/services/test_annotation_service.py
+++ b/api/tests/unit_tests/services/test_annotation_service.py
@@ -19,19 +19,20 @@ from services.annotation_service import AppAnnotationService
from services.app_ref_service import AnnotationRef, AppRef
-def _make_app(app_id: str = "app-1", tenant_id: str = "tenant-1") -> MagicMock:
- app = MagicMock(spec=App)
- app.id = app_id
- app.tenant_id = tenant_id
- app.status = "normal"
+def _make_app(app_id: str = "app-1", tenant_id: str = "tenant-1") -> App:
+ app = App(
+ id=app_id,
+ tenant_id=tenant_id,
+ status="normal",
+ )
return app
-def _make_app_ref(app: MagicMock) -> AppRef:
+def _make_app_ref(app: App) -> AppRef:
return AppRef(tenant_id=app.tenant_id, app_id=app.id)
-def _make_annotation_ref(app: MagicMock, annotation_id: str = "ann-1") -> AnnotationRef:
+def _make_annotation_ref(app: App, annotation_id: str = "ann-1") -> AnnotationRef:
return AnnotationRef(app=AppRef(tenant_id=app.tenant_id, app_id=app.id), annotation_id=annotation_id)
@@ -41,35 +42,36 @@ def _make_user(user_id: str = "user-1") -> MagicMock:
return user
-def _make_message(message_id: str = "msg-1", app_id: str = "app-1") -> MagicMock:
- message = MagicMock(spec=Message)
- message.id = message_id
- message.app_id = app_id
- message.conversation_id = "conv-1"
- message.query = "default-question"
- message.annotation = None
+def _make_message(message_id: str = "msg-1", app_id: str = "app-1") -> Message:
+ message = Message(
+ id=message_id,
+ app_id=app_id,
+ conversation_id="conv-1",
+ query="default-question",
+ )
return message
-def _make_annotation(annotation_id: str = "ann-1", app_id: str = "app-1") -> MagicMock:
- annotation = MagicMock(spec=MessageAnnotation)
+def _make_annotation(annotation_id: str = "ann-1", app_id: str = "app-1") -> MessageAnnotation:
+ annotation = MessageAnnotation(
+ app_id=app_id,
+ question="",
+ content="",
+ account_id="account-id",
+ )
annotation.id = annotation_id
- annotation.app_id = app_id
- annotation.content = ""
- annotation.question = ""
- annotation.question_text = ""
return annotation
-def _make_setting(setting_id: str = "setting-1", with_detail: bool = True) -> MagicMock:
- setting = MagicMock(spec=AppAnnotationSetting)
+def _make_setting(setting_id: str = "setting-1") -> AppAnnotationSetting:
+ setting = AppAnnotationSetting(
+ app_id="app-id",
+ score_threshold=0.5,
+ collection_binding_id="collection-1",
+ created_user_id="account-id",
+ updated_user_id="account-id",
+ )
setting.id = setting_id
- setting.score_threshold = 0.5
- setting.collection_binding_id = "collection-1"
- if with_detail:
- setting.collection_binding_detail = SimpleNamespace(provider_name="provider-a", model_name="model-a")
- else:
- setting.collection_binding_detail = None
return setting
@@ -188,7 +190,6 @@ class TestAppAnnotationServiceUpInsert:
tenant_id = "tenant-1"
app = _make_app()
message = _make_message(message_id="msg-1", app_id=app.id)
- message.annotation = None
with (
patch("services.annotation_service.current_account_with_tenant", return_value=(current_user, tenant_id)),
@@ -595,7 +596,7 @@ class TestAppAnnotationServiceDirectManipulation:
tenant_id = "tenant-1"
app = _make_app()
annotation = _make_annotation("ann-1")
- annotation.question_text = "q1"
+ annotation.question = "q1"
setting = _make_setting()
with (
@@ -631,8 +632,28 @@ class TestAppAnnotationServiceDirectManipulation:
tenant_id = "tenant-1"
app = _make_app()
annotation = _make_annotation("ann-1")
- history1 = MagicMock(spec=AppAnnotationHitHistory)
- history2 = MagicMock(spec=AppAnnotationHitHistory)
+ history1 = AppAnnotationHitHistory(
+ app_id="app-id",
+ annotation_id="annotation-id",
+ source="hit-testing",
+ question="question",
+ account_id="account-id",
+ score=0.0,
+ message_id="message-id",
+ annotation_question="question",
+ annotation_content="content",
+ )
+ history2 = AppAnnotationHitHistory(
+ app_id="app-id",
+ annotation_id="annotation-id",
+ source="hit-testing",
+ question="question",
+ account_id="account-id",
+ score=0.0,
+ message_id="message-id",
+ annotation_question="question",
+ annotation_content="content",
+ )
setting = _make_setting()
with (
@@ -1183,9 +1204,8 @@ class TestAppAnnotationServiceHitHistoryAndSettings:
# Arrange
tenant_id = "tenant-1"
app = _make_app()
- setting = _make_setting(with_detail=True)
- detail = setting.collection_binding_detail
- setting.collection_binding_detail = None
+ setting = _make_setting()
+ detail = SimpleNamespace(provider_name="provider-a", model_name="model-a")
with (
patch("services.annotation_service.current_account_with_tenant", return_value=(_make_user(), tenant_id)),
@@ -1224,8 +1244,7 @@ class TestAppAnnotationServiceHitHistoryAndSettings:
# Arrange
tenant_id = "tenant-1"
app = _make_app()
- setting = _make_setting(with_detail=False)
- setting.collection_binding_detail = SimpleNamespace(provider_name="wrong", model_name="wrong")
+ setting = _make_setting()
with (
patch("services.annotation_service.current_account_with_tenant", return_value=(_make_user(), tenant_id)),
@@ -1266,9 +1285,8 @@ class TestAppAnnotationServiceHitHistoryAndSettings:
tenant_id = "tenant-1"
current_user = _make_user("user-1")
app = _make_app()
- setting = _make_setting(with_detail=True)
- detail = setting.collection_binding_detail
- setting.collection_binding_detail = None
+ setting = _make_setting()
+ detail = SimpleNamespace(provider_name="provider-a", model_name="model-a")
args = {"score_threshold": 0.8}
with (
@@ -1297,8 +1315,7 @@ class TestAppAnnotationServiceHitHistoryAndSettings:
tenant_id = "tenant-1"
current_user = _make_user("user-1")
app = _make_app()
- setting = _make_setting(with_detail=False)
- setting.collection_binding_detail = SimpleNamespace(provider_name="wrong", model_name="wrong")
+ setting = _make_setting()
args = {"score_threshold": 0.7}
with (
@@ -1365,7 +1382,17 @@ class TestAppAnnotationServiceClearAll:
setting = _make_setting()
annotation1 = _make_annotation("ann-1")
annotation2 = _make_annotation("ann-2")
- history = MagicMock(spec=AppAnnotationHitHistory)
+ history = AppAnnotationHitHistory(
+ app_id="app-id",
+ annotation_id="annotation-id",
+ source="hit-testing",
+ question="question",
+ account_id="account-id",
+ score=0.0,
+ message_id="message-id",
+ annotation_question="question",
+ annotation_content="content",
+ )
with (
patch("services.annotation_service.current_account_with_tenant", return_value=(_make_user(), tenant_id)),
diff --git a/api/tests/unit_tests/services/test_app_service.py b/api/tests/unit_tests/services/test_app_service.py
index c7911534d6c..66ae199a067 100644
--- a/api/tests/unit_tests/services/test_app_service.py
+++ b/api/tests/unit_tests/services/test_app_service.py
@@ -13,7 +13,7 @@ from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from graphon.model_runtime.entities.model_entities import ModelType
-from models import Account
+from models import Account, Tenant
from models.model import App, AppMode, AppModelConfig, IconType
from models.workflow import Workflow
from services.agent.errors import AgentNameConflictError
@@ -23,7 +23,10 @@ from services.app_service import AppListParams, AppService, CreateAppParams
class TestCreateAppTransactionBoundary:
def test_commits_database_state_before_external_side_effects(self) -> None:
session = MagicMock()
- account = MagicMock(spec=Account, id="account-1", current_tenant_id="tenant-1")
+ account = Account(name="Test Account", email="[email protected]")
+ account.id = "account-1"
+ account._current_tenant = Tenant(name="Test Tenant")
+ account._current_tenant.id = "tenant-1"
phase_events: list[str] = []
session.commit.side_effect = lambda: phase_events.append("commit")
@@ -53,7 +56,10 @@ class TestCreateAppTransactionBoundary:
def test_falls_back_when_default_model_schema_is_unavailable(self) -> None:
session = MagicMock()
- account = MagicMock(spec=Account, id="account-1", current_tenant_id="tenant-1")
+ account = Account(name="Test Account", email="[email protected]")
+ account.id = "account-1"
+ account._current_tenant = Tenant(name="Test Tenant")
+ account._current_tenant.id = "tenant-1"
model_type_instance = MagicMock()
model_type_instance.get_model_schema.side_effect = ValueError("Base model unknown-model not found")
model_instance = SimpleNamespace(
@@ -131,8 +137,9 @@ class TestOpenapiVisibilityHelpers:
signal if the helper coalesced both into ``None``.
"""
mock_session = MagicMock()
- sentinel_app = MagicMock(spec=App)
- sentinel_app.status = "archived" # explicitly NOT "normal"
+ sentinel_app = App(
+ status="archived",
+ ) # explicitly NOT "normal"
mock_session.get.return_value = sentinel_app
assert AppService.get_app_by_id("app-uuid", mock_session) is sentinel_app
@@ -146,8 +153,9 @@ class TestOpenapiVisibilityHelpers:
def test_get_visible_app_by_id_returns_app_when_visible(self):
mock_session = MagicMock()
- app = MagicMock(spec=App)
- app.status = "normal"
+ app = App(
+ status="normal",
+ )
mock_session.get.return_value = app
with patch("services.app_service.is_openapi_visible", return_value=True):
@@ -166,8 +174,9 @@ class TestOpenapiVisibilityHelpers:
surface — the helper hides them by returning ``None``.
"""
mock_session = MagicMock()
- app = MagicMock(spec=App)
- app.status = "archived"
+ app = App(
+ status="archived",
+ )
mock_session.get.return_value = app
with patch("services.app_service.is_openapi_visible", return_value=True):
@@ -179,8 +188,9 @@ class TestOpenapiVisibilityHelpers:
treat the row as invisible (not "found but unauthorized").
"""
mock_session = MagicMock()
- app = MagicMock(spec=App)
- app.status = "normal"
+ app = App(
+ status="normal",
+ )
mock_session.get.return_value = app
with patch("services.app_service.is_openapi_visible", return_value=False):
@@ -192,7 +202,7 @@ class TestOpenapiVisibilityHelpers:
so the controller can branch on length (404 / single / 409).
"""
mock_session = MagicMock()
- rows = [MagicMock(spec=App), MagicMock(spec=App)]
+ rows = [App(), App()]
mock_session.execute.return_value.scalars.return_value = iter(rows)
with patch("services.app_service.apply_openapi_gate", side_effect=lambda q: q) as gate:
@@ -229,7 +239,7 @@ class TestOpenapiVisibilityHelpers:
non-normal hits in Python so its page count stays anchored.
"""
mock_session = MagicMock()
- rows = [MagicMock(spec=App), MagicMock(spec=App)]
+ rows = [App(), App()]
mock_session.execute.return_value.scalars.return_value.all.return_value = rows
with patch("services.app_service.apply_openapi_gate", side_effect=lambda q: q) as gate:
@@ -249,27 +259,30 @@ def test_get_recent_apps_uses_one_tenant_scoped_projection_query(sqlite_session:
sqlite_session.flush()
def create_app(*, name: str, tenant_id: str, updated_at: datetime, mode: AppMode = AppMode.CHAT) -> App:
- app = App()
- app.id = str(uuid4())
- app.tenant_id = tenant_id
- app.name = name
- app.description = ""
- app.mode = mode
- app.icon_type = IconType.EMOJI
- app.icon = "🚀"
- app.icon_background = "#FFFFFF"
- app.enable_site = False
- app.enable_api = False
- app.created_by = account.id
- app.maintainer = account.id
- app.created_at = updated_at
- app.updated_at = updated_at
- app.use_icon_as_answer_icon = False
+ app = App(
+ id=str(uuid4()),
+ tenant_id=tenant_id,
+ name=name,
+ description="",
+ mode=mode,
+ icon_type=IconType.EMOJI,
+ icon="🚀",
+ icon_background="#FFFFFF",
+ enable_site=False,
+ enable_api=False,
+ created_by=account.id,
+ maintainer=account.id,
+ created_at=updated_at,
+ updated_at=updated_at,
+ use_icon_as_answer_icon=False,
+ )
return app
newest = create_app(name="Newest", tenant_id=tenant_id, updated_at=datetime(2026, 7, 3))
- legacy_agent = AppModelConfig(app_id=newest.id)
- legacy_agent.agent_mode = '{"enabled": true, "strategy": "react"}'
+ legacy_agent = AppModelConfig(
+ app_id=newest.id,
+ agent_mode='{"enabled": true, "strategy": "react"}',
+ )
newest.app_model_config_id = legacy_agent.id
second = create_app(
name="Second",
@@ -349,31 +362,41 @@ class TestAppMeta:
class TestGetApp:
def test_legacy_agent_detection_uses_caller_session(self):
session = MagicMock()
- app = MagicMock(spec=App)
- app.mode = AppMode.CHAT
- app.is_agent_with_session.return_value = False
- account = MagicMock(spec=Account)
- account.current_tenant_id = "tenant-1"
+ app = App(
+ mode=AppMode.CHAT,
+ )
+ account = Account(name="Test Account", email="[email protected]")
+ account._current_tenant = Tenant(name="Test Tenant")
+ account._current_tenant.id = "tenant-1"
- with patch("services.app_service.current_user", account):
+ with (
+ patch.object(App, "is_agent_with_session", return_value=False) as is_agent,
+ patch.object(App, "app_model_config_with_session") as get_model_config,
+ patch("services.app_service.current_user", account),
+ ):
assert AppService().get_app(app, session=session) is app
- app.is_agent_with_session.assert_called_once_with(session=session)
- app.app_model_config_with_session.assert_not_called()
+ is_agent.assert_called_once_with(session=session)
+ get_model_config.assert_not_called()
def test_agent_model_config_uses_caller_session(self):
session = MagicMock()
- app = MagicMock(spec=App)
- app.mode = AppMode.AGENT_CHAT
- app.app_model_config_with_session.return_value = None
- account = MagicMock(spec=Account)
- account.current_tenant_id = "tenant-1"
+ app = App(
+ mode=AppMode.AGENT_CHAT,
+ )
+ account = Account(name="Test Account", email="[email protected]")
+ account._current_tenant = Tenant(name="Test Tenant")
+ account._current_tenant.id = "tenant-1"
- with patch("services.app_service.current_user", account):
+ with (
+ patch.object(App, "is_agent_with_session") as is_agent,
+ patch.object(App, "app_model_config_with_session", return_value=None) as get_model_config,
+ patch("services.app_service.current_user", account),
+ ):
assert AppService().get_app(app, session=session) is app
- app.is_agent_with_session.assert_not_called()
- app.app_model_config_with_session.assert_called_once_with(session=session)
+ is_agent.assert_not_called()
+ get_model_config.assert_called_once_with(session=session)
class TestAgentAppType:
@@ -399,8 +422,9 @@ class TestAgentAppType:
"""Non-agent apps short-circuit without touching the DB."""
from models.model import App, AppMode
- app = App()
- app.mode = AppMode.CHAT
+ app = App(
+ mode=AppMode.CHAT,
+ )
assert app.bound_agent_id is None
def test_update_agent_app_syncs_backing_agent_identity(self):
diff --git a/api/tests/unit_tests/services/test_file_service.py b/api/tests/unit_tests/services/test_file_service.py
index 172aa909100..0994abecf65 100644
--- a/api/tests/unit_tests/services/test_file_service.py
+++ b/api/tests/unit_tests/services/test_file_service.py
@@ -86,7 +86,7 @@ class TestFileService:
mock_now.return_value = datetime(2024, 1, 1, tzinfo=UTC)
mock_get_url.return_value = "http://signed-url"
- user = MagicMock(spec=Account)
+ user = Account(name="Test Account", email="[email protected]")
user.id = "user_id"
content = b"file content"
filename = "test.jpg"
@@ -127,7 +127,7 @@ class TestFileService:
mock_storage.save.assert_called_once_with(result.key, expected_content)
def test_upload_file_uses_explicit_resource_tenant(self, file_service: FileService):
- user = MagicMock(spec=Account)
+ user = Account(name="Test Account", email="[email protected]")
user.id = "user-id"
with (
@@ -154,7 +154,7 @@ class TestFileService:
def test_upload_file_long_filename(self, file_service: FileService, db_session: Session):
# Setup
long_name = "a" * 210 + ".txt"
- user = MagicMock(spec=Account)
+ user = Account(name="Test Account", email="[email protected]")
user.id = "user_id"
with (
@@ -189,8 +189,9 @@ class TestFileService:
file_service.upload_file(filename="test.jpg", content=content, mimetype="image/jpeg", user=MagicMock())
def test_upload_file_end_user(self, file_service: FileService, db_session: Session):
- user = MagicMock(spec=EndUser)
- user.id = "end_user_id"
+ user = EndUser(
+ id="end_user_id",
+ )
with (
patch("services.file_service.storage"),
diff --git a/api/tests/unit_tests/services/tools/test_mcp_tools_transform.py b/api/tests/unit_tests/services/tools/test_mcp_tools_transform.py
index 9537d207f01..aa5f28c0535 100644
--- a/api/tests/unit_tests/services/tools/test_mcp_tools_transform.py
+++ b/api/tests/unit_tests/services/tools/test_mcp_tools_transform.py
@@ -3,6 +3,7 @@
from unittest.mock import Mock
import pytest
+from pytest_mock import MockerFixture
from core.mcp.types import Tool as MCPTool
from core.tools.entities.api_entities import ToolApiEntity, ToolProviderApiEntity
@@ -21,33 +22,55 @@ def mock_user():
@pytest.fixture
-def mock_provider(mock_user):
+def mock_provider(mock_user, mocker: MockerFixture):
"""Provides a mock MCPToolProvider with a loaded user."""
- provider = Mock(spec=MCPToolProvider)
- provider.load_user.return_value = mock_user
+ provider = MCPToolProvider(
+ name="Test Provider",
+ server_identifier="test-provider",
+ server_url="https://example.com",
+ server_url_hash="hash",
+ icon="icon",
+ tenant_id="tenant-id",
+ user_id="user-id",
+ )
+ mocker.patch.object(provider, "load_user", return_value=mock_user)
return provider
@pytest.fixture
-def mock_provider_no_user():
+def mock_provider_no_user(mocker: MockerFixture):
"""Provides a mock MCPToolProvider with no user."""
- provider = Mock(spec=MCPToolProvider)
- provider.load_user.return_value = None
+ provider = MCPToolProvider(
+ name="Test Provider",
+ server_identifier="test-provider",
+ server_url="https://example.com",
+ server_url_hash="hash",
+ icon="icon",
+ tenant_id="tenant-id",
+ user_id="user-id",
+ )
+ mocker.patch.object(provider, "load_user", return_value=None)
return provider
@pytest.fixture
-def mock_provider_full(mock_user):
+def mock_provider_full(mock_user, mocker: MockerFixture):
"""Provides a fully configured mock MCPToolProvider for detailed tests."""
- provider = Mock(spec=MCPToolProvider)
+ provider = MCPToolProvider(
+ name="Test MCP Provider",
+ server_identifier="server-identifier-456",
+ server_url="https://example.com",
+ server_url_hash="hash",
+ icon="icon",
+ tenant_id="tenant-id",
+ user_id="user-id",
+ authed=True,
+ timeout=30,
+ sse_read_timeout=300,
+ )
provider.id = "provider-id-123"
- provider.server_identifier = "server-identifier-456"
- provider.name = "Test MCP Provider"
provider.provider_icon = "icon.png"
- provider.authed = True
provider.masked_server_url = "https://*****.com/mcp"
- provider.timeout = 30
- provider.sse_read_timeout = 300
provider.masked_headers = {"Authorization": "Bearer *****"}
provider.decrypted_headers = {"Authorization": "Bearer secret-token"}
@@ -56,7 +79,7 @@ def mock_provider_full(mock_user):
mock_updated_at.timestamp.return_value = 1234567890
provider.updated_at = mock_updated_at
- provider.load_user.return_value = mock_user
+ mocker.patch.object(provider, "load_user", return_value=mock_user)
return provider
@@ -306,7 +329,7 @@ class TestMCPToolTransform:
assert result[0].type == ToolParameter.ToolParameterType.STRING
assert result[0].input_schema is None
- def test_mcp_provider_to_user_provider_for_list(self, mock_provider_full):
+ def test_mcp_provider_to_user_provider_for_list(self, mock_provider_full, mocker: MockerFixture):
"""Test mcp_provider_to_user_provider with for_list=True."""
# Set tools data with null description
mock_provider_full.tools = '[{"name": "tool1", "description": null, "inputSchema": {}}]'
@@ -328,7 +351,7 @@ class TestMCPToolTransform:
"label": I18nObject(en_US="Test MCP Provider", zh_Hans="Test MCP Provider"),
"masked_credentials": {},
}
- mock_provider_full.to_entity.return_value = mock_entity
+ mocker.patch.object(mock_provider_full, "to_entity", return_value=mock_entity)
# Call the method with for_list=True
result = ToolTransformService.mcp_provider_to_user_provider(mock_provider_full, for_list=True)
@@ -343,7 +366,7 @@ class TestMCPToolTransform:
assert len(result.tools) == 1
assert result.tools[0].description.en_US == "" # Should handle None description
- def test_mcp_provider_to_user_provider_not_for_list(self, mock_provider_full):
+ def test_mcp_provider_to_user_provider_not_for_list(self, mock_provider_full, mocker: MockerFixture):
"""Test mcp_provider_to_user_provider with for_list=False."""
# Set tools data with description
mock_provider_full.tools = '[{"name": "tool1", "description": "Tool description", "inputSchema": {}}]'
@@ -367,7 +390,7 @@ class TestMCPToolTransform:
"label": I18nObject(en_US="Test MCP Provider", zh_Hans="Test MCP Provider"),
"masked_credentials": {},
}
- mock_provider_full.to_entity.return_value = mock_entity
+ mocker.patch.object(mock_provider_full, "to_entity", return_value=mock_entity)
# Call the method with for_list=False
result = ToolTransformService.mcp_provider_to_user_provider(mock_provider_full, for_list=False)