Skip to content

armgit / dify

Public Imported from GitHub
0

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

refactor(api): merge duplicated model builders in unit tests (#41549)

Mesrop Harutyunyan104f3b239b2f
diff --git a/api/services/file_service.py b/api/services/file_service.py
index ded70111e3d..e06069c8cc2 100644
--- a/api/services/file_service.py
+++ b/api/services/file_service.py
@@ -1,6 +1,7 @@
import base64
import hashlib
import os
+import posixpath
import uuid
from collections.abc import Generator, Sequence # Changed Iterator to Generator
from contextlib import contextmanager, suppress
@@ -315,8 +316,9 @@ class FileService:
We keep this conservative: the upload flow already rejects `/` and `\\`, but older rows (or imported data)
could still contain unsafe names.
"""
- # Drop any directory components and prevent empty names.
- base = os.path.basename(name).strip() or "file"
+ # Drop any directory components and prevent empty names. ZIP names are always POSIX-style, so split on
+ # `/` explicitly rather than through `os.path`, whose separators differ on Windows hosts.
+ base = posixpath.basename(name).strip() or "file"
# ZIP uses forward slashes as separators; remove any residual separator characters.
return base.replace("/", "_").replace("\\", "_")
diff --git a/api/services/rag_pipeline/rag_pipeline_transform_service.py b/api/services/rag_pipeline/rag_pipeline_transform_service.py
index 90dd6e081bd..9304257de9a 100644
--- a/api/services/rag_pipeline/rag_pipeline_transform_service.py
+++ b/api/services/rag_pipeline/rag_pipeline_transform_service.py
@@ -123,29 +123,40 @@ class RagPipelineTransformService:
case DataSourceType.UPLOAD_FILE:
if indexing_technique == IndexTechniqueType.HIGH_QUALITY:
# get graph from transform.file-general-high-quality.yml
- with open(f"{Path(__file__).parent}/transform/file-general-high-quality.yml") as f:
+ with open(
+ f"{Path(__file__).parent}/transform/file-general-high-quality.yml", encoding="utf-8"
+ ) as f:
pipeline_yaml = yaml.safe_load(f)
if indexing_technique == IndexTechniqueType.ECONOMY:
# get graph from transform.file-general-economy.yml
- with open(f"{Path(__file__).parent}/transform/file-general-economy.yml") as f:
+ with open(f"{Path(__file__).parent}/transform/file-general-economy.yml", encoding="utf-8") as f:
pipeline_yaml = yaml.safe_load(f)
case DataSourceType.NOTION_IMPORT:
if indexing_technique == IndexTechniqueType.HIGH_QUALITY:
# get graph from transform.notion-general-high-quality.yml
- with open(f"{Path(__file__).parent}/transform/notion-general-high-quality.yml") as f:
+ with open(
+ f"{Path(__file__).parent}/transform/notion-general-high-quality.yml", encoding="utf-8"
+ ) as f:
pipeline_yaml = yaml.safe_load(f)
if indexing_technique == IndexTechniqueType.ECONOMY:
# get graph from transform.notion-general-economy.yml
- with open(f"{Path(__file__).parent}/transform/notion-general-economy.yml") as f:
+ with open(
+ f"{Path(__file__).parent}/transform/notion-general-economy.yml", encoding="utf-8"
+ ) as f:
pipeline_yaml = yaml.safe_load(f)
case DataSourceType.WEBSITE_CRAWL:
if indexing_technique == IndexTechniqueType.HIGH_QUALITY:
# get graph from transform.website-crawl-general-high-quality.yml
- with open(f"{Path(__file__).parent}/transform/website-crawl-general-high-quality.yml") as f:
+ with open(
+ f"{Path(__file__).parent}/transform/website-crawl-general-high-quality.yml",
+ encoding="utf-8",
+ ) as f:
pipeline_yaml = yaml.safe_load(f)
if indexing_technique == IndexTechniqueType.ECONOMY:
# get graph from transform.website-crawl-general-economy.yml
- with open(f"{Path(__file__).parent}/transform/website-crawl-general-economy.yml") as f:
+ with open(
+ f"{Path(__file__).parent}/transform/website-crawl-general-economy.yml", encoding="utf-8"
+ ) as f:
pipeline_yaml = yaml.safe_load(f)
case _:
raise ValueError("Unsupported datasource type")
@@ -153,15 +164,17 @@ class RagPipelineTransformService:
match datasource_type:
case DataSourceType.UPLOAD_FILE:
# get graph from transform.file-parentchild.yml
- with open(f"{Path(__file__).parent}/transform/file-parentchild.yml") as f:
+ with open(f"{Path(__file__).parent}/transform/file-parentchild.yml", encoding="utf-8") as f:
pipeline_yaml = yaml.safe_load(f)
case DataSourceType.NOTION_IMPORT:
# get graph from transform.notion-parentchild.yml
- with open(f"{Path(__file__).parent}/transform/notion-parentchild.yml") as f:
+ with open(f"{Path(__file__).parent}/transform/notion-parentchild.yml", encoding="utf-8") as f:
pipeline_yaml = yaml.safe_load(f)
case DataSourceType.WEBSITE_CRAWL:
# get graph from transform.website-crawl-parentchild.yml
- with open(f"{Path(__file__).parent}/transform/website-crawl-parentchild.yml") as f:
+ with open(
+ f"{Path(__file__).parent}/transform/website-crawl-parentchild.yml", encoding="utf-8"
+ ) as f:
pipeline_yaml = yaml.safe_load(f)
case _:
raise ValueError("Unsupported datasource type")
diff --git a/api/tests/unit_tests/commands/test_reset_encrypt_key_pair.py b/api/tests/unit_tests/commands/test_reset_encrypt_key_pair.py
index d8c47e2747e..bb3201bbdaa 100644
--- a/api/tests/unit_tests/commands/test_reset_encrypt_key_pair.py
+++ b/api/tests/unit_tests/commands/test_reset_encrypt_key_pair.py
@@ -22,6 +22,7 @@ from models import Tenant
from models.provider import Provider, ProviderModel, ProviderType
from models.tools import ApiToolProvider, BuiltinToolProvider, MCPToolProvider
from tests.unit_tests.config_override import apply_config_overrides
+from tests.unit_tests.model_factories import make_tenant
def _invoke_reset() -> int:
@@ -38,9 +39,7 @@ USER_ID = "22222222-2222-2222-2222-222222222222"
def _tenant(tenant_id: str, *, name: str = "Test tenant") -> Tenant:
- tenant = Tenant(name=name, encrypt_public_key="old-key")
- tenant.id = tenant_id
- return tenant
+ return make_tenant(tenant_id=tenant_id, name=name, encrypt_public_key="old-key")
def _encrypted_rows(tenant_id: str, *, suffix: str = "1") -> tuple[object, ...]:
diff --git a/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.py b/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.py
index ee10c5dc19f..d2af3b5fddc 100644
--- a/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.py
+++ b/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.py
@@ -75,6 +75,7 @@ from services.entities.agent_entities import (
WorkflowComposerCopyFromRosterPayload,
)
from tests.unit_tests.config_override import apply_config_overrides
+from tests.unit_tests.model_factories import make_account
def _persist_conversation_message(
@@ -228,12 +229,13 @@ def _app_detail_obj(**overrides) -> App:
def _account(*, account_id: str = "account-1", privileged: bool = False, timezone: str | None = None) -> Account:
- account = Account(name="Agent Controller Tester", email=f"{account_id}@example.com")
- account.id = account_id
- account.timezone = timezone
- if privileged:
- account.role = TenantAccountRole.OWNER
- return account
+ return make_account(
+ account_id=account_id,
+ name="Agent Controller Tester",
+ email=f"{account_id}@example.com",
+ timezone=timezone,
+ role=TenantAccountRole.OWNER if privileged else None,
+ )
def _candidates_response(variant: str) -> dict:
diff --git a/api/tests/unit_tests/controllers/console/agent/test_app_helpers.py b/api/tests/unit_tests/controllers/console/agent/test_app_helpers.py
index b797a2956ad..8ad20b6b84c 100644
--- a/api/tests/unit_tests/controllers/console/agent/test_app_helpers.py
+++ b/api/tests/unit_tests/controllers/console/agent/test_app_helpers.py
@@ -6,10 +6,11 @@ from sqlalchemy.orm import Session
from controllers.console.agent import app_helpers
from models.model import App, AppMode
+from tests.unit_tests.model_factories import make_app
def _app() -> App:
- return App(id="app-1", tenant_id="tenant-1", name="Agent App", mode=AppMode.AGENT)
+ return make_app(name="Agent App", mode=AppMode.AGENT, icon_type=None)
def test_resolve_agent_app_model_reuses_caller_session(
diff --git a/api/tests/unit_tests/controllers/console/app/test_agent_app_sandbox.py b/api/tests/unit_tests/controllers/console/app/test_agent_app_sandbox.py
index 0ce728baef9..077b166917f 100644
--- a/api/tests/unit_tests/controllers/console/app/test_agent_app_sandbox.py
+++ b/api/tests/unit_tests/controllers/console/app/test_agent_app_sandbox.py
@@ -12,6 +12,7 @@ from models.account import Account
from models.model import App, AppMode, IconType
from services.agent_app_sandbox_service import AgentSandboxDownload, AgentSandboxInfo, AgentSandboxInspectorError
from tests.unit_tests.controllers.rbac_introspection import rbac_checks
+from tests.unit_tests.model_factories import make_account
class _AgentAppService:
@@ -142,9 +143,7 @@ def _app_model(app_id: str = "app-1") -> App:
def _account() -> Account:
- account = Account(name="Sandbox Tester", email="[email protected]")
- account.id = "account-1"
- return account
+ return make_account(name="Sandbox Tester", email="[email protected]")
@pytest.mark.parametrize(
diff --git a/api/tests/unit_tests/controllers/console/app/test_annotation_api.py b/api/tests/unit_tests/controllers/console/app/test_annotation_api.py
index 38ae25284e1..5094bb1fab9 100644
--- a/api/tests/unit_tests/controllers/console/app/test_annotation_api.py
+++ b/api/tests/unit_tests/controllers/console/app/test_annotation_api.py
@@ -13,6 +13,7 @@ from controllers.console.app import annotation as annotation_module
from models.account import Account
from models.model import App, AppAnnotationHitHistory, AppMode, IconType, MessageAnnotation
from services.app_ref_service import AnnotationRef, AppRef
+from tests.unit_tests.model_factories import make_account
def _persist_app(session: Session) -> App:
@@ -33,9 +34,7 @@ def _persist_app(session: Session) -> App:
def _account() -> Account:
- account = Account(name="Owner", email="[email protected]")
- account.id = "account-1"
- return account
+ return make_account(name="Owner", email="[email protected]")
def _annotation_model(annotation_id: str = "ann-1") -> MessageAnnotation:
diff --git a/api/tests/unit_tests/controllers/console/app/test_annotation_security.py b/api/tests/unit_tests/controllers/console/app/test_annotation_security.py
index 0aa896337e3..9d0f6c33cc5 100644
--- a/api/tests/unit_tests/controllers/console/app/test_annotation_security.py
+++ b/api/tests/unit_tests/controllers/console/app/test_annotation_security.py
@@ -21,12 +21,11 @@ from models.model import App, AppMode, IconType
from services.annotation_service import AppAnnotationService
from tasks.annotation.batch_import_annotations_task import batch_import_annotations_task
from tests.unit_tests.config_override import config_overrides_context
+from tests.unit_tests.model_factories import make_account
def _account() -> Account:
- account = Account(name="Annotation Tester", email="[email protected]")
- account.id = "user_id"
- return account
+ return make_account(account_id="user_id", name="Annotation Tester", email="[email protected]")
def _persist_app(session: Session) -> App:
diff --git a/api/tests/unit_tests/controllers/console/app/test_audio.py b/api/tests/unit_tests/controllers/console/app/test_audio.py
index 1f8633923be..6e3efa6c985 100644
--- a/api/tests/unit_tests/controllers/console/app/test_audio.py
+++ b/api/tests/unit_tests/controllers/console/app/test_audio.py
@@ -50,6 +50,7 @@ from services.errors.audio import (
SpeechToTextDisabledServiceError,
UnsupportedAudioTypeServiceError,
)
+from tests.unit_tests.model_factories import make_account, make_app
def _file_data():
@@ -57,22 +58,11 @@ def _file_data():
def _app(*, app_id: str = "a1", tenant_id: str = "tenant-1") -> App:
- return App(
- id=app_id,
- tenant_id=tenant_id,
- name="Audio app",
- description="",
- mode=AppMode.CHAT,
- enable_site=True,
- enable_api=True,
- max_active_requests=0,
- )
+ return make_app(app_id=app_id, tenant_id=tenant_id, name="Audio app", icon_type=None, max_active_requests=0)
def _account(account_id: str = "account-1") -> Account:
- account = Account(name="Audio account", email=f"{account_id}@example.com")
- account.id = account_id
- return account
+ return make_account(account_id=account_id, name="Audio account", email=f"{account_id}@example.com")
def test_console_audio_api_success(app: Flask, monkeypatch: pytest.MonkeyPatch) -> None:
diff --git a/api/tests/unit_tests/controllers/console/app/test_conversation_api.py b/api/tests/unit_tests/controllers/console/app/test_conversation_api.py
index c43af0fde83..8425c9560de 100644
--- a/api/tests/unit_tests/controllers/console/app/test_conversation_api.py
+++ b/api/tests/unit_tests/controllers/console/app/test_conversation_api.py
@@ -23,9 +23,10 @@ from models.enums import (
FeedbackRating,
WorkflowRunTriggeredFrom,
)
-from models.model import AppMode, Conversation, IconType
+from models.model import AppMode, Conversation
from models.workflow import WorkflowRun, WorkflowType
from services.errors.conversation import ConversationNotExistsError
+from tests.unit_tests.model_factories import make_app, make_conversation
def _make_account() -> Account:
@@ -35,30 +36,13 @@ def _make_account() -> Account:
def _app(*, mode: AppMode = AppMode.CHAT) -> App:
- return App(
- id="app-1",
- tenant_id="tenant-1",
- name="Conversation app",
- description="",
- mode=mode,
- icon_type=IconType.EMOJI,
- icon="robot",
- icon_background="#FFFFFF",
- enable_site=True,
- enable_api=True,
- max_active_requests=None,
- )
+ return make_app(name="Conversation app", mode=mode)
def _conversation(*, conversation_id: str = "c1", app_id: str = "app-1") -> Conversation:
- conversation = Conversation(
+ return make_conversation(
+ conversation_id=conversation_id,
app_id=app_id,
- app_model_config_id=None,
- model_provider=None,
- override_model_configs=None,
- model_id=None,
- mode=AppMode.CHAT,
- name="Conversation",
inputs={},
introduction="",
system_instruction="",
@@ -66,11 +50,8 @@ def _conversation(*, conversation_id: str = "c1", app_id: str = "app-1") -> Conv
status="normal",
invoke_from=InvokeFrom.EXPLORE,
from_source=ConversationFromSource.CONSOLE,
- from_end_user_id=None,
from_account_id="u1",
)
- conversation.id = conversation_id
- return conversation
def test_completion_conversation_list_returns_paginated_result(
diff --git a/api/tests/unit_tests/controllers/console/app/test_conversation_variables_api.py b/api/tests/unit_tests/controllers/console/app/test_conversation_variables_api.py
index 07249da37c8..bfd030b2e7a 100644
--- a/api/tests/unit_tests/controllers/console/app/test_conversation_variables_api.py
+++ b/api/tests/unit_tests/controllers/console/app/test_conversation_variables_api.py
@@ -14,23 +14,11 @@ from controllers.console.app import conversation_variables as conversation_varia
from factories import variable_factory
from graphon.variables.types import SegmentType
from models import App, AppMode, ConversationVariable
-from models.model import IconType
+from tests.unit_tests.model_factories import make_app
def _app() -> App:
- return App(
- id="app-1",
- tenant_id="tenant-1",
- name="Conversation variables app",
- description="",
- mode=AppMode.ADVANCED_CHAT,
- icon_type=IconType.EMOJI,
- icon="robot",
- icon_background="#FFFFFF",
- enable_site=True,
- enable_api=True,
- max_active_requests=None,
- )
+ return make_app(name="Conversation variables app", mode=AppMode.ADVANCED_CHAT)
def test_get_conversation_variables_returns_paginated_response(
diff --git a/api/tests/unit_tests/controllers/console/app/test_generator_api.py b/api/tests/unit_tests/controllers/console/app/test_generator_api.py
index b028bd15761..184f0a3f988 100644
--- a/api/tests/unit_tests/controllers/console/app/test_generator_api.py
+++ b/api/tests/unit_tests/controllers/console/app/test_generator_api.py
@@ -20,7 +20,8 @@ from controllers.console.app.generator import (
)
from core.errors.error import ProviderTokenNotInitError
from models.model import App, AppMode
-from models.workflow import Workflow, WorkflowType
+from models.workflow import Workflow
+from tests.unit_tests.model_factories import make_workflow
def _persist_app(session: Session, *, tenant_id: str = "t1") -> App:
@@ -44,14 +45,7 @@ def _model_config_payload():
def _workflow(graph_dict: dict[str, object]) -> Workflow:
- return Workflow(
- id="workflow-1",
- tenant_id="t1",
- app_id="app-1",
- type=WorkflowType.WORKFLOW,
- version=Workflow.VERSION_DRAFT,
- graph=json.dumps(graph_dict),
- )
+ return make_workflow(workflow_id="workflow-1", tenant_id="t1", graph=graph_dict)
def _install_workflow_service(monkeypatch: pytest.MonkeyPatch, workflow):
diff --git a/api/tests/unit_tests/controllers/console/app/test_mcp_server_response.py b/api/tests/unit_tests/controllers/console/app/test_mcp_server_response.py
index 0f53d0de7d8..edac7a463c0 100644
--- a/api/tests/unit_tests/controllers/console/app/test_mcp_server_response.py
+++ b/api/tests/unit_tests/controllers/console/app/test_mcp_server_response.py
@@ -20,8 +20,9 @@ from controllers.console.wraps import RBACPermission, RBACResourceScope
from models import Account
from models.account import AccountStatus
from models.enums import AppMCPServerStatus
-from models.model import App, AppMCPServer, AppMode, IconType
+from models.model import App, AppMCPServer
from tests.unit_tests.config_override import config_overrides_context
+from tests.unit_tests.model_factories import make_app
def _app(
@@ -31,19 +32,7 @@ def _app(
name: str = "Demo App",
description: str = "App description",
) -> App:
- return App(
- id=app_id,
- tenant_id=tenant_id,
- name=name,
- description=description,
- mode=AppMode.CHAT,
- icon_type=IconType.EMOJI,
- icon="robot",
- icon_background="#FFFFFF",
- enable_site=True,
- enable_api=True,
- max_active_requests=None,
- )
+ return make_app(app_id=app_id, tenant_id=tenant_id, name=name, description=description)
def _server(
diff --git a/api/tests/unit_tests/controllers/console/app/test_workflow_convert_api.py b/api/tests/unit_tests/controllers/console/app/test_workflow_convert_api.py
index 54163d65448..f9a9bc80d06 100644
--- a/api/tests/unit_tests/controllers/console/app/test_workflow_convert_api.py
+++ b/api/tests/unit_tests/controllers/console/app/test_workflow_convert_api.py
@@ -9,24 +9,12 @@ from flask import Flask
from controllers.console.app import workflow as workflow_module
from controllers.console.app.workflow import ConvertToWorkflowApi
-from models import Account, App, AppMode
-from models.model import IconType
+from models import Account, App
+from tests.unit_tests.model_factories import make_app
def _app(app_id: str) -> App:
- return App(
- id=app_id,
- tenant_id="tenant-1",
- name=f"App {app_id}",
- description="",
- mode=AppMode.CHAT,
- icon_type=IconType.EMOJI,
- icon="robot",
- icon_background="#FFFFFF",
- enable_site=True,
- enable_api=True,
- max_active_requests=None,
- )
+ return make_app(app_id=app_id, name=f"App {app_id}")
class TestConvertToWorkflowApi:
diff --git a/api/tests/unit_tests/controllers/console/app/test_workflow_run_api.py b/api/tests/unit_tests/controllers/console/app/test_workflow_run_api.py
index 16c85e24f62..7457dae7d80 100644
--- a/api/tests/unit_tests/controllers/console/app/test_workflow_run_api.py
+++ b/api/tests/unit_tests/controllers/console/app/test_workflow_run_api.py
@@ -20,13 +20,13 @@ from graphon.enums import WorkflowExecutionStatus, WorkflowNodeExecutionStatus
from machinery.context import RequestContext
from models import Account, App, AppMode
from models.enums import CreatorUserRole, WorkflowRunTriggeredFrom
-from models.model import IconType
from models.workflow import (
WorkflowNodeExecutionModel,
WorkflowNodeExecutionTriggeredFrom,
WorkflowRun,
WorkflowType,
)
+from tests.unit_tests.model_factories import make_account, make_app
def _serialize_200_response(handler, payload: Any) -> Any:
@@ -41,27 +41,14 @@ def _serialize_200_response(handler, payload: Any) -> Any:
def _account(session: Session) -> Account:
- account = Account(name="Alice", email="[email protected]")
- account.id = "account-1"
+ account = make_account(name="Alice", email="[email protected]")
session.add(account)
session.commit()
return account
def _app() -> App:
- return App(
- id="app-1",
- tenant_id="tenant-1",
- name="Workflow run app",
- description="",
- mode=AppMode.WORKFLOW,
- icon_type=IconType.EMOJI,
- icon="robot",
- icon_background="#FFFFFF",
- enable_site=True,
- enable_api=True,
- max_active_requests=None,
- )
+ return make_app(name="Workflow run app", mode=AppMode.WORKFLOW)
def _request_context(*, workspace_id: str = "tenant-1") -> RequestContext:
diff --git a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_datasource_auth.py b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_datasource_auth.py
index 63a61586ef9..c1cbbaa8682 100644
--- a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_datasource_auth.py
+++ b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_datasource_auth.py
@@ -30,14 +30,13 @@ from graphon.model_runtime.errors.validate import CredentialsValidateFailedError
from models.account import Account
from services.datasource_provider_service import DatasourceProviderService
from services.plugin.oauth_service import OAuthProxyService
+from tests.unit_tests.model_factories import make_account
_PROVIDER_ID = "langgenius/notion_datasource/notion"
def _account() -> Account:
- account = Account(name="Datasource Auth Tester", email="[email protected]")
- account.id = "user-1"
- return account
+ return make_account(account_id="user-1", name="Datasource Auth Tester", email="[email protected]")
def _i18n(text: str) -> dict[str, str]:
diff --git a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline.py b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline.py
index 5ef83ea902f..53445379c5c 100644
--- a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline.py
+++ b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline.py
@@ -29,6 +29,7 @@ from services.errors.account import NoPermissionError
from services.errors.rag_pipeline import RagPipelineResourceNotFoundError
from tests.unit_tests.config_override import config_overrides_context
from tests.unit_tests.controllers.rbac_introspection import rbac_checks
+from tests.unit_tests.model_factories import make_account
def _template_item() -> dict[str, object]:
@@ -63,9 +64,7 @@ def _payload() -> dict[str, object]:
def _account() -> Account:
- account = Account(name="Test User", email="[email protected]")
- account.id = "account-1"
- return account
+ return make_account(name="Test User", email="[email protected]")
def _pipeline() -> Pipeline:
diff --git a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_datasets.py b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_datasets.py
index 3e2c9cefd04..a892ad820fb 100644
--- a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_datasets.py
+++ b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_datasets.py
@@ -19,12 +19,16 @@ from controllers.console.datasets.rag_pipeline.rag_pipeline_datasets import (
)
from models.account import Account, TenantAccountRole
from services.entities.dsl_entities import ImportStatus
+from tests.unit_tests.model_factories import make_account
def _account(*, editor: bool) -> Account:
- account = Account(name="RAG Pipeline Tester", email="[email protected]")
- account.role = TenantAccountRole.EDITOR if editor else TenantAccountRole.NORMAL
- return account
+ return make_account(
+ account_id=None,
+ name="RAG Pipeline Tester",
+ role=TenantAccountRole.EDITOR if editor else TenantAccountRole.NORMAL,
+ )
class TestCreateRagPipelineDatasetApi:
diff --git a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_draft_variable.py b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_draft_variable.py
index 33ff6a39a81..c5f43180cee 100644
--- a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_draft_variable.py
+++ b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_draft_variable.py
@@ -32,6 +32,7 @@ from models.account import Account, TenantAccountRole
from models.dataset import Pipeline
from models.workflow import Workflow, WorkflowDraftVariable, WorkflowType
from tests.unit_tests.controllers.rbac_introspection import rbac_checks
+from tests.unit_tests.model_factories import make_workflow
@pytest.fixture
@@ -48,17 +49,12 @@ def _pipeline(*, pipeline_id: str = "p1", tenant_id: str = "t1") -> Pipeline:
def _workflow(pipeline: Pipeline, environment_variables=()) -> Workflow:
- return Workflow.new(
+ return make_workflow(
tenant_id=pipeline.tenant_id,
app_id=pipeline.id,
- type=WorkflowType.RAG_PIPELINE,
- version=Workflow.VERSION_DRAFT,
+ workflow_type=WorkflowType.RAG_PIPELINE,
graph="{}",
- features="{}",
- created_by="account-1",
environment_variables=environment_variables,
- conversation_variables=[],
- rag_pipeline_variables=[],
)
diff --git a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_import.py b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_import.py
index c2e80c24bd5..9875ef27c1b 100644
--- a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_import.py
+++ b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_import.py
@@ -24,12 +24,11 @@ from models.dataset import Pipeline
from models.engine import db
from services.entities.dsl_entities import CheckDependenciesResult, ImportStatus
from services.rag_pipeline.rag_pipeline_dsl_service import RagPipelineImportInfo
+from tests.unit_tests.model_factories import make_account
def _account() -> Account:
- account = Account(name="RAG Import Tester", email="[email protected]")
- account.id = "account-1"
- return account
+ return make_account(name="RAG Import Tester", email="[email protected]")
@pytest.fixture
diff --git a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_workflow.py b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_workflow.py
index f6ab01e9cce..294e0c04f35 100644
--- a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_workflow.py
+++ b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_workflow.py
@@ -25,7 +25,7 @@ from controllers.console.datasets.rag_pipeline.rag_pipeline_workflow import (
WorkflowUpdatePayload,
)
from controllers.web.error import InvokeRateLimitError as InvokeRateLimitHttpError
-from models.account import Account, Tenant, TenantAccountRole
+from models.account import Account, TenantAccountRole
from models.dataset import Dataset, Pipeline
from models.engine import db
from models.enums import PermissionEnum
@@ -35,6 +35,7 @@ from services.errors.llm import InvokeRateLimitError
from services.errors.rag_pipeline import RagPipelineResourceNotFoundError
from services.rag_pipeline.rag_pipeline import RagPipelineService
from tests.unit_tests.config_override import config_overrides_context
+from tests.unit_tests.model_factories import make_account, make_dataset, make_tenant
DEFAULT_WORKFLOW_TENANT_ID = "00000000-0000-0000-0000-000000000001"
DEFAULT_WORKFLOW_APP_ID = "00000000-0000-0000-0000-000000000002"
@@ -68,13 +69,13 @@ def _make_workflow(**overrides: object) -> Workflow:
def _account() -> Account:
- account = Account(name="Alice", email="[email protected]")
- account.id = DEFAULT_WORKFLOW_CREATED_BY
- account.role = TenantAccountRole.EDITOR
- tenant = Tenant(name="Tenant")
- tenant.id = DEFAULT_WORKFLOW_TENANT_ID
- account._current_tenant = tenant
- return account
+ return make_account(
+ account_id=DEFAULT_WORKFLOW_CREATED_BY,
+ name="Alice",
+ role=TenantAccountRole.EDITOR,
+ tenant=make_tenant(tenant_id=DEFAULT_WORKFLOW_TENANT_ID, name="Tenant"),
+ )
def _pipeline() -> Pipeline:
@@ -84,10 +85,9 @@ def _pipeline() -> Pipeline:
def _dataset(*, tenant_id: str = DEFAULT_WORKFLOW_TENANT_ID, maintainer: str = DEFAULT_WORKFLOW_CREATED_BY) -> Dataset:
- return Dataset(
- id=DEFAULT_DATASET_ID,
+ return make_dataset(
+ dataset_id=DEFAULT_DATASET_ID,
tenant_id=tenant_id,
- name="Dataset",
created_by=maintainer,
maintainer=maintainer,
permission=PermissionEnum.ONLY_ME,
diff --git a/api/tests/unit_tests/controllers/console/datasets/test_data_source_notion_apis.py b/api/tests/unit_tests/controllers/console/datasets/test_data_source_notion_apis.py
index b96c09334b6..a0a7e37b3e3 100644
--- a/api/tests/unit_tests/controllers/console/datasets/test_data_source_notion_apis.py
+++ b/api/tests/unit_tests/controllers/console/datasets/test_data_source_notion_apis.py
@@ -20,23 +20,20 @@ from controllers.console.datasets.data_source import (
)
from core.rag.index_processor.constant.index_type import IndexStructureType
from models import Account, Dataset, Document
-from models.dataset import DataSourceType, DocumentCreatedFrom
+from models.dataset import DataSourceType
+from tests.unit_tests.model_factories import make_dataset, make_document
def _dataset() -> Dataset:
- return Dataset(id="ds-1", tenant_id="tenant-1", name="Dataset", created_by="u1")
+ return make_dataset(dataset_id="ds-1", created_by="u1")
def _document() -> Document:
- return Document(
- id="d1",
- tenant_id="tenant-1",
+ return make_document(
+ document_id="d1",
dataset_id="ds-1",
- position=1,
data_source_type=DataSourceType.NOTION_IMPORT,
- batch="batch-1",
name="Notion page",
- created_from=DocumentCreatedFrom.WEB,
created_by="u1",
)
diff --git a/api/tests/unit_tests/controllers/console/datasets/test_datasets_segments.py b/api/tests/unit_tests/controllers/console/datasets/test_datasets_segments.py
index 9b258aec8bc..00e4737228d 100644
--- a/api/tests/unit_tests/controllers/console/datasets/test_datasets_segments.py
+++ b/api/tests/unit_tests/controllers/console/datasets/test_datasets_segments.py
@@ -37,6 +37,7 @@ from models.enums import PermissionEnum, SegmentStatus, SegmentType
from models.model import UploadFile
from services.errors.chunk import ChildChunkDeleteIndexError as ChildChunkDeleteIndexServiceError
from services.errors.chunk import ChildChunkIndexingError as ChildChunkIndexingServiceError
+from tests.unit_tests.model_factories import make_account, make_dataset, make_document, make_upload_file
def _segment():
@@ -82,10 +83,9 @@ def _child_chunk():
def _account() -> Account:
- account = Account(name="Dataset Editor", email="[email protected]")
- account.id = "u1"
- account.role = TenantAccountRole.OWNER
- return account
+ return make_account(
+ account_id="u1", name="Dataset Editor", email="[email protected]", role=TenantAccountRole.OWNER
+ )
def _dataset(
@@ -96,10 +96,9 @@ def _dataset(
embedding_model_provider: str | None = None,
embedding_model: str | None = None,
) -> Dataset:
- return Dataset(
- id=dataset_id,
+ return make_dataset(
+ dataset_id=dataset_id,
tenant_id=tenant_id,
- name="Dataset",
description="",
provider="vendor",
permission=PermissionEnum.ONLY_ME,
@@ -117,14 +116,10 @@ def _document(
tenant_id: str = "tenant-1",
doc_form: IndexStructureType = IndexStructureType.PARAGRAPH_INDEX,
) -> Document:
- return Document(
- id=document_id,
+ return make_document(
+ document_id=document_id,
tenant_id=tenant_id,
dataset_id=dataset_id,
- position=1,
- data_source_type="upload_file",
- batch="batch-1",
- name="Document",
created_from="api",
created_by="u1",
doc_form=doc_form,
@@ -132,21 +127,17 @@ def _document(
def _upload_file(*, name: str = "test.csv", file_id: str = "test-file-id") -> UploadFile:
- upload_file = UploadFile(
- tenant_id="tenant-1",
+ return make_upload_file(
+ file_id=file_id,
storage_type="opendal",
key="test-key",
name=name,
size=0,
extension=name.rsplit(".", maxsplit=1)[-1],
mime_type="text/csv",
- created_by_role="account",
created_by="u1",
created_at=datetime.now(),
- used=False,
)
- upload_file.id = file_id
- return upload_file
class SQLiteControllerTest:
diff --git a/api/tests/unit_tests/controllers/console/explore/test_trial.py b/api/tests/unit_tests/controllers/console/explore/test_trial.py
index 03d93348382..dc7d3ac12c3 100644
--- a/api/tests/unit_tests/controllers/console/explore/test_trial.py
+++ b/api/tests/unit_tests/controllers/console/explore/test_trial.py
@@ -49,6 +49,7 @@ from services.app_ref_service import AppRef, MessageRef
from services.errors.audio import SpeechToTextDisabledServiceError
from services.errors.conversation import ConversationNotExistsError
from services.errors.llm import InvokeRateLimitError
+from tests.unit_tests.model_factories import make_app, make_upload_file
unwrap: Any = inspect_unwrap
@@ -80,32 +81,19 @@ def trial_app_usage(monkeypatch: pytest.MonkeyPatch) -> MagicMock:
def _app(*, app_id: str, mode: AppMode, tenant_id: str = "tenant-1") -> App:
- return App(
- id=app_id,
- tenant_id=tenant_id,
- name="Trial App",
- mode=mode,
- enable_site=True,
- enable_api=False,
- )
+ return make_app(app_id=app_id, tenant_id=tenant_id, name="Trial App", mode=mode, icon_type=None, enable_api=False)
def _upload_file(*, file_id: str = "upload-file-id", tenant_id: str = "app-tenant-id") -> UploadFile:
- upload_file = UploadFile(
+ return make_upload_file(
+ file_id=file_id,
tenant_id=tenant_id,
storage_type="opendal",
key="trial/file.txt",
name="file.txt",
size=1,
- extension="txt",
- mime_type="text/plain",
- created_by_role="account",
created_by="u1",
- created_at=datetime(2024, 1, 1),
- used=False,
)
- upload_file.id = file_id
- return upload_file
def _file_data() -> Any:
diff --git a/api/tests/unit_tests/controllers/console/explore/test_wraps.py b/api/tests/unit_tests/controllers/console/explore/test_wraps.py
index 53f87e22c5f..c3f104de1a6 100644
--- a/api/tests/unit_tests/controllers/console/explore/test_wraps.py
+++ b/api/tests/unit_tests/controllers/console/explore/test_wraps.py
@@ -21,7 +21,8 @@ from controllers.console.explore.wraps import (
trial_feature_enable,
user_allowed_to_access_app,
)
-from models import Account, AccountTrialAppRecord, App, AppMode, InstalledApp, TrialApp
+from models import Account, AccountTrialAppRecord, App, InstalledApp, TrialApp
+from tests.unit_tests.model_factories import make_account, make_app
def _bind_database(monkeypatch: pytest.MonkeyPatch, sqlite_session: Session) -> None:
@@ -31,22 +32,11 @@ def _bind_database(monkeypatch: pytest.MonkeyPatch, sqlite_session: Session) ->
def _account(*, account_id: str | None = None) -> Account:
- account = Account(name="Explore user", email="[email protected]")
- if account_id is not None:
- account.id = account_id
- return account
+ return make_account(account_id=account_id, name="Explore user", email="[email protected]")
def _app() -> App:
- app = App(
- tenant_id=str(uuid4()),
- name="Explore App",
- mode=AppMode.CHAT,
- enable_site=True,
- enable_api=True,
- )
- app.id = str(uuid4())
- return app
+ return make_app(app_id=str(uuid4()), tenant_id=str(uuid4()), name="Explore App", icon_type=None)
def _installed_app(*, app_id: str, tenant_id: str) -> InstalledApp:
diff --git a/api/tests/unit_tests/controllers/console/snippets/test_snippet_workflow.py b/api/tests/unit_tests/controllers/console/snippets/test_snippet_workflow.py
index 733ab1fb048..6d762791958 100644
--- a/api/tests/unit_tests/controllers/console/snippets/test_snippet_workflow.py
+++ b/api/tests/unit_tests/controllers/console/snippets/test_snippet_workflow.py
@@ -15,13 +15,16 @@ from werkzeug.exceptions import HTTPException, NotFound
from controllers.console.snippets import snippet_workflow as snippet_workflow_module
from models.account import Account, TenantAccountRole
from models.snippet import CustomizedSnippet
+from tests.unit_tests.model_factories import make_account
def _account(account_id: str = "account-1") -> Account:
- account = Account(name="Test User", email=f"{account_id}@example.com")
- account.id = account_id
- account.role = TenantAccountRole.EDITOR
- return account
+ return make_account(
+ account_id=account_id,
+ name="Test User",
+ email=f"{account_id}@example.com",
+ role=TenantAccountRole.EDITOR,
+ )
def _snippet(**overrides) -> CustomizedSnippet:
diff --git a/api/tests/unit_tests/controllers/console/tag/test_tags.py b/api/tests/unit_tests/controllers/console/tag/test_tags.py
index d40b84bd4dd..41aa923a471 100644
--- a/api/tests/unit_tests/controllers/console/tag/test_tags.py
+++ b/api/tests/unit_tests/controllers/console/tag/test_tags.py
@@ -20,7 +20,7 @@ from controllers.console.tag.tags import (
)
from machinery.context import RequestContext
from models import Account
-from models.account import AccountStatus, TenantAccountRole
+from models.account import TenantAccountRole
from models.enums import TagType
from services.tag_application_service import (
TagApplicationError,
@@ -32,6 +32,7 @@ from services.tag_application_service import (
UpdateTagInput,
)
from tests.unit_tests.config_override import config_overrides_context
+from tests.unit_tests.model_factories import make_account
def unwrap(func):
@@ -58,14 +59,7 @@ def request_context() -> RequestContext:
def _account(role: TenantAccountRole) -> Account:
- account = Account(
- name="Tag User",
- email=f"{role.value}@example.com",
- status=AccountStatus.ACTIVE,
- )
- account.id = "user-1"
- account.role = role
- return account
+ return make_account(account_id="user-1", name="Tag User", email=f"{role.value}@example.com", role=role)
@pytest.fixture
diff --git a/api/tests/unit_tests/controllers/console/test_files.py b/api/tests/unit_tests/controllers/console/test_files.py
index e5db1174b83..bf2b3da2671 100644
--- a/api/tests/unit_tests/controllers/console/test_files.py
+++ b/api/tests/unit_tests/controllers/console/test_files.py
@@ -1,5 +1,4 @@
import io
-from datetime import datetime
from unittest.mock import patch
import pytest
@@ -22,12 +21,11 @@ from controllers.console.files import (
FileSupportTypeApi,
upload_file_from_request,
)
-from extensions.storage.storage_type import StorageType
from machinery.context import RequestContext
from models import Account
from models.account import AccountStatus, TenantAccountRole
-from models.enums import CreatorUserRole
from models.model import UploadFile
+from tests.unit_tests.model_factories import make_upload_file
def unwrap(func):
@@ -40,21 +38,13 @@ def unwrap(func):
def _upload_file(*, file_id: str = "file-id-123", size: int = 1024) -> UploadFile:
- upload_file = UploadFile(
+ return make_upload_file(
+ file_id=file_id,
tenant_id="tenant-123",
- storage_type=StorageType.LOCAL,
key=f"upload/{file_id}/test.txt",
- name="test.txt",
size=size,
- extension="txt",
- mime_type="text/plain",
- created_by_role=CreatorUserRole.ACCOUNT,
created_by="user-123",
- created_at=datetime(2024, 1, 1),
- used=False,
)
- upload_file.id = file_id
- return upload_file
def _request_context(*, workspace_id: str = "tenant-1") -> RequestContext:
diff --git a/api/tests/unit_tests/controllers/console/test_human_input_form.py b/api/tests/unit_tests/controllers/console/test_human_input_form.py
index 39e8f089ce9..d799c634505 100644
--- a/api/tests/unit_tests/controllers/console/test_human_input_form.py
+++ b/api/tests/unit_tests/controllers/console/test_human_input_form.py
@@ -23,12 +23,12 @@ from controllers.console.human_input_form import (
from core.workflow.human_input_policy import HumanInputSurface
from graphon.enums import WorkflowExecutionStatus, WorkflowType
from models import Account
-from models.account import AccountStatus
from models.enums import CreatorUserRole, WorkflowRunTriggeredFrom
from models.human_input import RecipientType
from models.model import App, AppMode
from models.workflow import WorkflowRun
from tests.unit_tests.config_override import apply_config_overrides
+from tests.unit_tests.model_factories import make_account, make_app
@pytest.fixture(autouse=True)
@@ -38,20 +38,15 @@ def bind_console_human_input_database(sqlite_engine: Engine, monkeypatch: pytest
def _account(*, account_id: str = "user-1") -> Account:
- account = Account(name="Console User", email=f"{account_id}@example.com", status=AccountStatus.ACTIVE)
- account.id = account_id
- return account
+ return make_account(account_id=account_id, name="Console User", email=f"{account_id}@example.com")
def _app() -> App:
- return App(
- id="app-1",
+ return make_app(
tenant_id="t1",
name="Human Input App",
- description="",
mode=AppMode.WORKFLOW,
- enable_site=True,
- enable_api=True,
+ icon_type=None,
max_active_requests=0,
)
diff --git a/api/tests/unit_tests/controllers/console/test_workflow_run_archive.py b/api/tests/unit_tests/controllers/console/test_workflow_run_archive.py
index 6348a2f8ce9..5b13c907f2d 100644
--- a/api/tests/unit_tests/controllers/console/test_workflow_run_archive.py
+++ b/api/tests/unit_tests/controllers/console/test_workflow_run_archive.py
@@ -37,13 +37,11 @@ _ENDPOINTS = [
WorkflowRunArchiveDownloadFileApi.get,
]
from tests.unit_tests.config_override import apply_config_overrides
+from tests.unit_tests.model_factories import make_account
def _account(role: TenantAccountRole) -> Account:
- account = Account(name="Test User", email="[email protected]")
- account.id = "account-1"
- account.role = role
- return account
+ return make_account(name="Test User", email="[email protected]", role=role)
def _original(method):
diff --git a/api/tests/unit_tests/controllers/console/test_workspace_members.py b/api/tests/unit_tests/controllers/console/test_workspace_members.py
index 2528b387623..0be530a33d6 100644
--- a/api/tests/unit_tests/controllers/console/test_workspace_members.py
+++ b/api/tests/unit_tests/controllers/console/test_workspace_members.py
@@ -9,12 +9,11 @@ from controllers.console.workspace.error import InvalidMemberRoleError
from controllers.console.workspace.members import MemberInviteEmailApi
from enums import DeploymentEdition
from models.account import Account, Tenant, TenantAccountRole
+from tests.unit_tests.model_factories import make_tenant
def _tenant() -> Tenant:
- tenant = Tenant(name="Test Tenant")
- tenant.id = "tenant-1"
- return tenant
+ return make_tenant(name="Test Tenant")
@pytest.fixture
diff --git a/api/tests/unit_tests/controllers/console/workspace/test_agent_providers.py b/api/tests/unit_tests/controllers/console/workspace/test_agent_providers.py
index f62a0818333..462d0e3bb32 100644
--- a/api/tests/unit_tests/controllers/console/workspace/test_agent_providers.py
+++ b/api/tests/unit_tests/controllers/console/workspace/test_agent_providers.py
@@ -8,12 +8,11 @@ from controllers.console.workspace.agent_providers import (
AgentProviderListApi,
)
from models.account import Account
+from tests.unit_tests.model_factories import make_account
def _account() -> Account:
- account = Account(name="Agent Provider Tester", email="[email protected]")
- account.id = "user1"
- return account
+ return make_account(account_id="user1", name="Agent Provider Tester", email="[email protected]")
class TestAgentProviderListApi:
diff --git a/api/tests/unit_tests/controllers/console/workspace/test_load_balancing_config.py b/api/tests/unit_tests/controllers/console/workspace/test_load_balancing_config.py
index cdfdcb0ca8c..e436a4e6393 100644
--- a/api/tests/unit_tests/controllers/console/workspace/test_load_balancing_config.py
+++ b/api/tests/unit_tests/controllers/console/workspace/test_load_balancing_config.py
@@ -19,6 +19,7 @@ if not hasattr(builtins, "MethodView"):
builtins.MethodView = MethodView # type: ignore[attr-defined]
from models.account import Account, TenantAccountRole
+from tests.unit_tests.model_factories import make_account
@pytest.fixture
@@ -57,10 +58,7 @@ def load_balancing_module(monkeypatch: pytest.MonkeyPatch):
def _account(role: TenantAccountRole) -> Account:
- account = Account(name="Owner", email="[email protected]")
- account.id = "account-1"
- account.role = role
- return account
+ return make_account(name="Owner", email="[email protected]", role=role)
def _prepare_context(module, monkeypatch: pytest.MonkeyPatch, role=TenantAccountRole.OWNER):
diff --git a/api/tests/unit_tests/controllers/console/workspace/test_models.py b/api/tests/unit_tests/controllers/console/workspace/test_models.py
index 9f49e97d3d2..38f4d21db0d 100644
--- a/api/tests/unit_tests/controllers/console/workspace/test_models.py
+++ b/api/tests/unit_tests/controllers/console/workspace/test_models.py
@@ -28,12 +28,11 @@ from controllers.console.workspace.models import (
from graphon.model_runtime.entities.model_entities import ModelType
from graphon.model_runtime.errors.validate import CredentialsValidateFailedError
from models import Account
+from tests.unit_tests.model_factories import make_account
def _account() -> Account:
- account = Account(name="Model User", email="[email protected]")
- account.id = "u1"
- return account
+ return make_account(account_id="u1", name="Model User", email="[email protected]")
class TestDefaultModelApi:
diff --git a/api/tests/unit_tests/controllers/console/workspace/test_plugin.py b/api/tests/unit_tests/controllers/console/workspace/test_plugin.py
index ea0f79a851c..5424dc65634 100644
--- a/api/tests/unit_tests/controllers/console/workspace/test_plugin.py
+++ b/api/tests/unit_tests/controllers/console/workspace/test_plugin.py
@@ -83,6 +83,7 @@ from models.account import (
TenantPluginInstallPermission,
)
from tests.unit_tests.config_override import config_overrides_context
+from tests.unit_tests.model_factories import make_account
def _plugin_category_list_item(category: str = "tool") -> dict[str, Any]:
@@ -358,10 +359,7 @@ def _expected_dynamic_option_dump() -> dict[str, Any]:
def _account(role: TenantAccountRole = TenantAccountRole.OWNER) -> Account:
- account = Account(name="Test User", email="[email protected]")
- account.id = "u1"
- account.role = role
- return account
+ return make_account(account_id="u1", name="Test User", email="[email protected]", role=role)
@pytest.fixture
diff --git a/api/tests/unit_tests/controllers/console/workspace/test_rbac.py b/api/tests/unit_tests/controllers/console/workspace/test_rbac.py
index 15af9f1614d..3bbfe1e281c 100644
--- a/api/tests/unit_tests/controllers/console/workspace/test_rbac.py
+++ b/api/tests/unit_tests/controllers/console/workspace/test_rbac.py
@@ -28,6 +28,7 @@ from controllers.console.workspace import rbac as rbac_mod
from controllers.console.workspace.rbac import _RolesListQuery
from enums import DeploymentEdition
from models import Account
+from tests.unit_tests.model_factories import make_account
@pytest.fixture
@@ -47,9 +48,7 @@ def _rbac_config(config_overrides) -> None:
def _account() -> Account:
- account = Account(name="RBAC User", email="[email protected]")
- account.id = "acct-1"
- return account
+ return make_account(account_id="acct-1", name="RBAC User", email="[email protected]")
class TestCurrentIds:
diff --git a/api/tests/unit_tests/controllers/console/workspace/test_snippets.py b/api/tests/unit_tests/controllers/console/workspace/test_snippets.py
index 75dc6180e90..78943e87482 100644
--- a/api/tests/unit_tests/controllers/console/workspace/test_snippets.py
+++ b/api/tests/unit_tests/controllers/console/workspace/test_snippets.py
@@ -14,6 +14,7 @@ from controllers.console.workspace import snippets as snippets_module
from models.account import Account, TenantAccountRole
from models.snippet import CustomizedSnippet
from services.snippet_dsl_service import ImportStatus, SnippetImportInfo
+from tests.unit_tests.model_factories import make_account
@pytest.fixture(autouse=True)
@@ -33,10 +34,12 @@ def _patch_snippet_service_factory(
def _account(account_id: str = "account-1") -> Account:
- account = Account(name="Test User", email=f"{account_id}@example.com")
- account.id = account_id
- account.role = TenantAccountRole.EDITOR
- return account
+ return make_account(
+ account_id=account_id,
+ name="Test User",
+ email=f"{account_id}@example.com",
+ role=TenantAccountRole.EDITOR,
+ )
def _snippet(**overrides) -> CustomizedSnippet:
diff --git a/api/tests/unit_tests/controllers/inner_api/plugin/test_plugin.py b/api/tests/unit_tests/controllers/inner_api/plugin/test_plugin.py
index 3f8a6efde6b..c0e644e9c73 100644
--- a/api/tests/unit_tests/controllers/inner_api/plugin/test_plugin.py
+++ b/api/tests/unit_tests/controllers/inner_api/plugin/test_plugin.py
@@ -36,12 +36,11 @@ from controllers.inner_api.plugin.plugin import (
from core.workflow.file_reference import build_file_reference
from models import Account, Tenant
from tests.unit_tests.config_override import apply_config_overrides
+from tests.unit_tests.model_factories import make_tenant
def _tenant() -> Tenant:
- tenant = Tenant(name="Test Tenant")
- tenant.id = "tenant-id"
- return tenant
+ return make_tenant(tenant_id="tenant-id", name="Test Tenant")
def _user() -> Account:
diff --git a/api/tests/unit_tests/controllers/inner_api/test_agent_files.py b/api/tests/unit_tests/controllers/inner_api/test_agent_files.py
index f5bb418d76a..040a0f13abc 100644
--- a/api/tests/unit_tests/controllers/inner_api/test_agent_files.py
+++ b/api/tests/unit_tests/controllers/inner_api/test_agent_files.py
@@ -16,14 +16,13 @@ from core.workflow.file_reference import build_file_reference
from models.account import Account, Tenant
from services.file_request_service import DownloadFileRequestResult
from tests.unit_tests.config_override import apply_config_overrides
+from tests.unit_tests.model_factories import make_tenant
MODULE = "controllers.inner_api.agent.files"
def _tenant() -> Tenant:
- tenant = Tenant(name="Test Workspace")
- tenant.id = "tenant-1"
- return tenant
+ return make_tenant(name="Test Workspace")
def _raw[R](method: Callable[..., R]) -> Callable[..., R]:
diff --git a/api/tests/unit_tests/controllers/inner_api/test_agent_llm.py b/api/tests/unit_tests/controllers/inner_api/test_agent_llm.py
index f37e1acd971..f9eb3006bc5 100644
--- a/api/tests/unit_tests/controllers/inner_api/test_agent_llm.py
+++ b/api/tests/unit_tests/controllers/inner_api/test_agent_llm.py
@@ -50,7 +50,7 @@ def _agent_inner_auth() -> Generator[None]:
yield
-def _app() -> Flask:
+def _flask_app() -> Flask:
app = Flask(__name__)
app.config["TESTING"] = True
app.register_blueprint(inner_api_bp)
@@ -75,7 +75,7 @@ def test_post_streams_plugin_compatible_envelope() -> None:
patch("controllers.inner_api.agent.llm.AgentLLMInnerService.invoke", return_value=iter([chunk])),
):
response = (
- _app()
+ _flask_app()
.test_client()
.post(
"/inner/api/agent/llm/invoke",
@@ -134,7 +134,7 @@ def test_post_preserves_prompt_messages_without_transport_validation() -> None:
patch("controllers.inner_api.agent.llm.AgentLLMInnerService.invoke", return_value=iter([])),
):
response = (
- _app()
+ _flask_app()
.test_client()
.post(
"/inner/api/agent/llm/invoke",
@@ -150,7 +150,7 @@ def test_post_preserves_prompt_messages_without_transport_validation() -> None:
def test_post_rejects_invalid_body_before_model_resolution() -> None:
with _agent_inner_auth():
response = (
- _app()
+ _flask_app()
.test_client()
.post(
"/inner/api/agent/llm/invoke",
@@ -176,7 +176,7 @@ def test_post_preserves_preflight_quota_failure() -> None:
),
):
response = (
- _app()
+ _flask_app()
.test_client()
.post(
"/inner/api/agent/llm/invoke",
@@ -208,7 +208,7 @@ def test_post_preserves_stream_quota_failure() -> None:
),
):
response = (
- _app()
+ _flask_app()
.test_client()
.post(
"/inner/api/agent/llm/invoke",
diff --git a/api/tests/unit_tests/controllers/mcp/test_mcp.py b/api/tests/unit_tests/controllers/mcp/test_mcp.py
index 03679199403..0dd960de400 100644
--- a/api/tests/unit_tests/controllers/mcp/test_mcp.py
+++ b/api/tests/unit_tests/controllers/mcp/test_mcp.py
@@ -18,6 +18,7 @@ from models.engine import db
from models.enums import EndUserType
from models.model import App, AppAnnotationSetting, AppMCPServer, AppModelConfig, EndUser, IconType
from models.workflow import Workflow, WorkflowType
+from tests.unit_tests.model_factories import make_end_user
@pytest.fixture
@@ -127,14 +128,13 @@ def _app(
def _end_user() -> EndUser:
- end_user = EndUser(
+ return make_end_user(
+ end_user_id=str(uuid4()),
tenant_id=_TENANT_ID,
app_id=_APP_ID,
- type=EndUserType.MCP,
+ end_user_type=EndUserType.MCP,
session_id=_SERVER_ID,
)
- end_user.id = str(uuid4())
- return end_user
class DummyResult:
diff --git a/api/tests/unit_tests/controllers/openapi/auth/test_prepare.py b/api/tests/unit_tests/controllers/openapi/auth/test_prepare.py
index 96d823b178e..a9ae90a3463 100644
--- a/api/tests/unit_tests/controllers/openapi/auth/test_prepare.py
+++ b/api/tests/unit_tests/controllers/openapi/auth/test_prepare.py
@@ -21,10 +21,9 @@ from controllers.openapi.auth.prepare import (
from libs.oauth_bearer import TokenType
from models import Account, App, EndUser, Tenant, TenantAccountJoin
from models.account import AccountStatus, TenantAccountRole, TenantStatus
-from models.enums import AppStatus
-from models.model import AppMode, IconType
from services import end_user_service
from services.enterprise.enterprise_service import WebAppAccessMode
+from tests.unit_tests.model_factories import make_account, make_app, make_tenant
APP_ID = "00000000-0000-0000-0000-000000000001"
TENANT_ID = "00000000-0000-0000-0000-000000000002"
@@ -46,32 +45,15 @@ def _app(
tenant_id: str = TENANT_ID,
enable_api: bool = True,
) -> App:
- return App(
- id=app_id,
- tenant_id=tenant_id,
- name="OpenAPI app",
- description="",
- mode=AppMode.CHAT,
- icon_type=IconType.EMOJI,
- icon="robot",
- icon_background="#FFFFFF",
- status=AppStatus.NORMAL,
- enable_site=True,
- enable_api=enable_api,
- max_active_requests=None,
- )
+ return make_app(app_id=app_id, tenant_id=tenant_id, name="OpenAPI app", enable_api=enable_api)
def _tenant(*, tenant_id: str = TENANT_ID, status: TenantStatus = TenantStatus.NORMAL) -> Tenant:
- tenant = Tenant(name="OpenAPI tenant", status=status)
- tenant.id = tenant_id
- return tenant
+ return make_tenant(tenant_id=tenant_id, name="OpenAPI tenant", status=status)
def _account(*, status: AccountStatus = AccountStatus.ACTIVE) -> Account:
- account = Account(name="OpenAPI account", email="[email protected]", status=status)
- account.id = ACCOUNT_ID
- return account
+ return make_account(account_id=ACCOUNT_ID, name="OpenAPI account", email="[email protected]", status=status)
def _persist(session: Session, *models: object) -> None:
diff --git a/api/tests/unit_tests/controllers/openapi/test_app_payloads.py b/api/tests/unit_tests/controllers/openapi/test_app_payloads.py
index c73e6f3f454..2f548714484 100644
--- a/api/tests/unit_tests/controllers/openapi/test_app_payloads.py
+++ b/api/tests/unit_tests/controllers/openapi/test_app_payloads.py
@@ -13,23 +13,12 @@ from controllers.openapi.apps import ( # pyright: ignore[reportPrivateUsage]
parameters_payload,
)
from controllers.service_api.app.error import AppUnavailableError
-from models.model import App, AppMode, IconType
+from models.model import App, AppMode
+from tests.unit_tests.model_factories import make_app
def _app(*, mode: AppMode = AppMode.CHAT) -> App:
- return App(
- id="app1",
- tenant_id="tenant-1",
- name="X",
- description="d",
- mode=mode,
- icon_type=IconType.EMOJI,
- icon="robot",
- icon_background="#FFFFFF",
- enable_site=False,
- enable_api=True,
- max_active_requests=0,
- )
+ return make_app(app_id="app1", name="X", description="d", mode=mode, enable_site=False, max_active_requests=0)
def test_parameters_payload_raises_app_unavailable_when_no_config(unbound_session: Session):
diff --git a/api/tests/unit_tests/controllers/openapi/test_workspaces_members.py b/api/tests/unit_tests/controllers/openapi/test_workspaces_members.py
index 33a726e9c41..02398cbd2ad 100644
--- a/api/tests/unit_tests/controllers/openapi/test_workspaces_members.py
+++ b/api/tests/unit_tests/controllers/openapi/test_workspaces_members.py
@@ -45,7 +45,7 @@ from controllers.openapi.workspaces import (
from enums import DeploymentEdition
from libs.oauth_bearer import AuthContext, Scope, SubjectType, TokenType, reset_auth_ctx, set_auth_ctx
from models import Account, Tenant, TenantAccountJoin
-from models.account import AccountStatus, TenantAccountRole, TenantStatus
+from models.account import TenantAccountRole, TenantStatus
from services.account_service import TenantService as RealTenantService
from services.errors.account import (
AccountAlreadyInTenantError,
@@ -57,6 +57,7 @@ from services.errors.account import (
RoleAlreadyAssignedError,
)
from tests.unit_tests.config_override import config_overrides_context
+from tests.unit_tests.model_factories import make_account, make_tenant
if not hasattr(builtins, "MethodView"):
builtins.MethodView = MethodView # type: ignore[attr-defined]
@@ -130,14 +131,11 @@ def _auth_data(account_id: uuid.UUID) -> AuthData:
def _account(account_id: str = "acct-1", email: str = "[email protected]") -> Account:
- account = Account(name="User", email=email, status=AccountStatus.ACTIVE)
- account.id = account_id
- return account
+ return make_account(account_id=account_id, name="User", email=email)
def _tenant(tenant_id: str = "ws-1", *, status: TenantStatus = TenantStatus.NORMAL) -> Tenant:
- tenant = Tenant(name="WS", status=status)
- tenant.id = tenant_id
+ tenant = make_tenant(tenant_id=tenant_id, name="WS", status=status)
tenant.created_at = datetime(2026, 5, 18)
return tenant
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 9e51ffea837..325c5d33f77 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
@@ -34,7 +34,7 @@ from controllers.service_api.app.error import (
from core.errors.error import ModelCurrentlyNotSupportError, ProviderTokenNotInitError, QuotaExceededError
from graphon.model_runtime.errors.invoke import InvokeError
from models.enums import EndUserType
-from models.model import App, AppMode, EndUser
+from models.model import App, EndUser
from services.app_ref_service import AppRef, MessageRef
from services.audio_service import AudioService
from services.errors.app_model_config import AppModelConfigBrokenError
@@ -45,6 +45,7 @@ from services.errors.audio import (
SpeechToTextDisabledServiceError,
UnsupportedAudioTypeServiceError,
)
+from tests.unit_tests.model_factories import make_app, make_end_user
def _file_data():
@@ -52,24 +53,14 @@ def _file_data():
def _app(*, app_id: str = "a1", tenant_id: str = "tenant-1") -> App:
- return App(
- id=app_id,
- tenant_id=tenant_id,
- name="Audio app",
- description="",
- mode=AppMode.CHAT,
- enable_site=True,
- enable_api=True,
- max_active_requests=0,
- )
+ return make_app(app_id=app_id, tenant_id=tenant_id, name="Audio app", icon_type=None, max_active_requests=0)
def _end_user(*, end_user_id: str = "u1", external_user_id: str | None = None) -> EndUser:
- return EndUser(
- id=end_user_id,
- tenant_id="tenant-1",
+ return make_end_user(
+ end_user_id=end_user_id,
app_id="a1",
- type=EndUserType.SERVICE_API,
+ end_user_type=EndUserType.SERVICE_API,
external_user_id=external_user_id,
name="Audio user",
session_id=f"session-{end_user_id}",
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 093852d792f..efb2c2566e2 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
@@ -53,6 +53,7 @@ from services.errors.conversation import (
ConversationVariableNotExistsError,
ConversationVariableTypeMismatchError,
)
+from tests.unit_tests.model_factories import make_conversation
def _app(*, app_id: str = "app-1", mode: AppMode = AppMode.CHAT) -> App:
@@ -86,17 +87,15 @@ def _conversation(
app_id: str = "app-1",
end_user_id: str = "end-user-1",
) -> Conversation:
- conversation = Conversation(
+ return make_conversation(
+ conversation_id=conversation_id,
app_id=app_id,
- mode=AppMode.CHAT,
name="Original Name",
+ inputs={},
from_source=ConversationFromSource.API,
from_end_user_id=end_user_id,
invoke_from=InvokeFrom.SERVICE_API,
)
- conversation.id = conversation_id
- conversation.inputs = {}
- return conversation
class TestConversationListQuery:
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 ace817a4bf3..56aefeda1c7 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
@@ -43,6 +43,7 @@ from models.dataset import ChildChunk, Dataset, Document, DocumentSegment, Docum
from models.enums import IndexingStatus, SegmentType
from services.api_token_service import CachedApiToken
from services.dataset_service import DocumentService, SegmentService
+from tests.unit_tests.model_factories import make_account
def _segment_response_dict(summary: str | None = None):
@@ -85,9 +86,9 @@ def mock_tenant() -> Tenant:
def _account() -> Account:
- account = Account(name="Segment API User", email=f"segment-api-{uuid.uuid4()}@example.com")
- account.id = str(uuid.uuid4())
- return account
+ return make_account(
+ account_id=str(uuid.uuid4()), name="Segment API User", email=f"segment-api-{uuid.uuid4()}@example.com"
+ )
def _api_token(tenant_id: str) -> CachedApiToken:
diff --git a/api/tests/unit_tests/controllers/service_api/dataset/test_document.py b/api/tests/unit_tests/controllers/service_api/dataset/test_document.py
index efb38d0e340..8ea26e001f8 100644
--- a/api/tests/unit_tests/controllers/service_api/dataset/test_document.py
+++ b/api/tests/unit_tests/controllers/service_api/dataset/test_document.py
@@ -49,12 +49,10 @@ from controllers.service_api.dataset.document import (
from controllers.service_api.dataset.error import ArchivedDocumentImmutableError
from core.rag.index_processor.constant.index_type import IndexStructureType
from enums import DeploymentEdition
-from extensions.storage.storage_type import StorageType
from models.account import Account
from models.dataset import Dataset, Document, DocumentSegment
from models.enums import (
ApiTokenType,
- CreatorUserRole,
DataSourceType,
DocumentCreatedFrom,
DocumentDocType,
@@ -67,6 +65,7 @@ from services.dataset_service import DocumentService
from services.entities.knowledge_entities.knowledge_entities import ProcessRule, RetrievalModel
from services.errors.file import FileTooLargeError as FileTooLargeServiceError
from tests.unit_tests.config_override import config_overrides_context
+from tests.unit_tests.model_factories import make_account, make_upload_file
def _document_data_source_info() -> dict[str, str]:
@@ -74,27 +73,17 @@ def _document_data_source_info() -> dict[str, str]:
def _account() -> Account:
- account = Account(name="Document API User", email=f"document-api-{uuid.uuid4()}@example.com")
- account.id = "user-1"
- return account
+ return make_account(account_id="user-1", name="Document API User", email=f"document-api-{uuid.uuid4()}@example.com")
def _upload_file() -> UploadFile:
- upload_file = UploadFile(
- tenant_id="tenant-1",
- storage_type=StorageType.LOCAL,
+ return make_upload_file(
key="documents/file.txt",
name="file.txt",
- size=10,
- extension="txt",
- mime_type="text/plain",
- created_by_role=CreatorUserRole.ACCOUNT,
created_by="user-1",
created_at=datetime.now(UTC),
used=True,
)
- upload_file.id = str(uuid.uuid4())
- return upload_file
def _unwrap_non_wrapped_controller(view):
diff --git a/api/tests/unit_tests/controllers/service_api/dataset/test_rag_pipeline_file_upload_serialization.py b/api/tests/unit_tests/controllers/service_api/dataset/test_rag_pipeline_file_upload_serialization.py
index 9e09c8d8158..aa2b1f644af 100644
--- a/api/tests/unit_tests/controllers/service_api/dataset/test_rag_pipeline_file_upload_serialization.py
+++ b/api/tests/unit_tests/controllers/service_api/dataset/test_rag_pipeline_file_upload_serialization.py
@@ -5,28 +5,20 @@ Unit tests for Service API knowledge pipeline file-upload serialization.
from datetime import UTC, datetime
from controllers.service_api.dataset.rag_pipeline.rag_pipeline_workflow import PipelineUploadFileResponse
-from extensions.storage.storage_type import StorageType
from libs.helper import dump_response
-from models.enums import CreatorUserRole
from models.model import UploadFile
+from tests.unit_tests.model_factories import make_upload_file
def _upload_file(*, created_at: datetime) -> UploadFile:
- upload_file = UploadFile(
- tenant_id="tenant-1",
- storage_type=StorageType.LOCAL,
- key="uploads/file-1",
+ return make_upload_file(
+ file_id="file-1",
name="test.pdf",
size=123,
extension="pdf",
mime_type="application/pdf",
- created_by_role=CreatorUserRole.ACCOUNT,
- created_by="account-1",
created_at=created_at,
- used=False,
)
- upload_file.id = "file-1"
- return upload_file
def test_file_upload_created_at_is_isoformat_string():
diff --git a/api/tests/unit_tests/controllers/service_api/test_trace_session_id_parsing.py b/api/tests/unit_tests/controllers/service_api/test_trace_session_id_parsing.py
index 89766162a1d..05fcc5e400d 100644
--- a/api/tests/unit_tests/controllers/service_api/test_trace_session_id_parsing.py
+++ b/api/tests/unit_tests/controllers/service_api/test_trace_session_id_parsing.py
@@ -9,6 +9,7 @@ from controllers.service_api.app import workflow as workflow_module
from core.helper.trace_id_helper import get_trace_session_id
from models.enums import EndUserType
from models.model import App, AppMode, EndUser
+from tests.unit_tests.model_factories import make_app, make_end_user
class _Request:
@@ -41,16 +42,11 @@ def test_trace_session_id_invalid_highest_priority_raises_bad_request():
def _app(mode: AppMode) -> App:
- return App(id="app-1", mode=mode, tenant_id="tenant-1")
+ return make_app(mode=mode, icon_type=None)
def _end_user() -> EndUser:
- return EndUser(
- id="user-1",
- tenant_id="tenant-1",
- type=EndUserType.SERVICE_API,
- session_id="session-1",
- )
+ return make_end_user(end_user_id="user-1", end_user_type=EndUserType.SERVICE_API)
def _assert_generate_trace_session_id(mock_generate_service: MagicMock, expected: str) -> None:
diff --git a/api/tests/unit_tests/controllers/trigger/test_webhook.py b/api/tests/unit_tests/controllers/trigger/test_webhook.py
index 7cfd0306ff2..087922554ae 100644
--- a/api/tests/unit_tests/controllers/trigger/test_webhook.py
+++ b/api/tests/unit_tests/controllers/trigger/test_webhook.py
@@ -8,6 +8,7 @@ import controllers.trigger.webhook as module
from models.trigger import WorkflowWebhookTrigger
from models.workflow import Workflow
from services.errors.app import QuotaExceededError
+from tests.unit_tests.model_factories import make_workflow
@pytest.fixture(autouse=True)
@@ -35,7 +36,7 @@ def _webhook_trigger() -> WorkflowWebhookTrigger:
def _workflow() -> Workflow:
- return Workflow(id="workflow-1")
+ return make_workflow(workflow_id="workflow-1")
class TestPrepareWebhookExecution:
diff --git a/api/tests/unit_tests/controllers/web/test_audio.py b/api/tests/unit_tests/controllers/web/test_audio.py
index 10dc7a3429f..78f40d6dcb9 100644
--- a/api/tests/unit_tests/controllers/web/test_audio.py
+++ b/api/tests/unit_tests/controllers/web/test_audio.py
@@ -22,7 +22,6 @@ from controllers.web.error import (
)
from core.errors.error import ModelCurrentlyNotSupportError, ProviderTokenNotInitError, QuotaExceededError
from graphon.model_runtime.errors.invoke import InvokeError
-from models.enums import EndUserType
from models.model import App, AppMode, EndUser, IconType
from services.app_ref_service import AppRef, MessageRef
from services.errors.audio import (
@@ -32,6 +31,7 @@ from services.errors.audio import (
SpeechToTextDisabledServiceError,
UnsupportedAudioTypeServiceError,
)
+from tests.unit_tests.model_factories import make_end_user
def _app_model() -> App:
@@ -51,15 +51,7 @@ def _app_model() -> App:
def _end_user() -> EndUser:
- return EndUser(
- id="eu-1",
- tenant_id="tenant-1",
- app_id="app-1",
- type=EndUserType.BROWSER,
- external_user_id="ext-1",
- name="Web User",
- session_id="session-1",
- )
+ return make_end_user(end_user_id="eu-1", app_id="app-1", external_user_id="ext-1", name="Web User")
# ---------------------------------------------------------------------------
diff --git a/api/tests/unit_tests/controllers/web/test_completion.py b/api/tests/unit_tests/controllers/web/test_completion.py
index 6c7dce3c4ba..73f2ce6d20c 100644
--- a/api/tests/unit_tests/controllers/web/test_completion.py
+++ b/api/tests/unit_tests/controllers/web/test_completion.py
@@ -23,24 +23,12 @@ from controllers.web.error import (
from core.app.apps.agent_app.errors import AgentAppNotPublishedError
from core.errors.error import ModelCurrentlyNotSupportError, ProviderTokenNotInitError, QuotaExceededError
from graphon.model_runtime.errors.invoke import InvokeError
-from models.enums import EndUserType
-from models.model import App, AppMode, EndUser, IconType
+from models.model import App, AppMode, EndUser
+from tests.unit_tests.model_factories import make_app, make_end_user
def _app(mode: AppMode) -> App:
- return App(
- id="app-1",
- tenant_id="tenant-1",
- name="Web App",
- description="",
- mode=mode,
- icon_type=IconType.EMOJI,
- icon="robot",
- icon_background="#FFFFFF",
- enable_site=True,
- enable_api=False,
- max_active_requests=0,
- )
+ return make_app(name="Web App", mode=mode, enable_api=False, max_active_requests=0)
def _completion_app() -> App:
@@ -52,14 +40,7 @@ def _chat_app() -> App:
def _end_user() -> EndUser:
- return EndUser(
- id="eu-1",
- tenant_id="tenant-1",
- app_id="app-1",
- type=EndUserType.BROWSER,
- name="Web User",
- session_id="session-1",
- )
+ return make_end_user(end_user_id="eu-1", app_id="app-1", name="Web User")
# ---------------------------------------------------------------------------
diff --git a/api/tests/unit_tests/controllers/web/test_files.py b/api/tests/unit_tests/controllers/web/test_files.py
index 03d4241b62f..30c36a8af24 100644
--- a/api/tests/unit_tests/controllers/web/test_files.py
+++ b/api/tests/unit_tests/controllers/web/test_files.py
@@ -2,7 +2,6 @@
from __future__ import annotations
-from datetime import datetime
from io import BytesIO
from unittest.mock import MagicMock, patch
@@ -18,11 +17,11 @@ from controllers.common.errors import (
UnsupportedFileTypeError,
)
from controllers.web.files import FileApi
-from extensions.storage.storage_type import StorageType
from libs.exception import BaseHTTPException
-from models.enums import CreatorUserRole, EndUserType
+from models.enums import CreatorUserRole
from models.model import App, AppMode, EndUser, UploadFile
from services.errors import file as file_errors
+from tests.unit_tests.model_factories import make_end_user, make_upload_file
def _app_model() -> App:
@@ -39,31 +38,17 @@ def _app_model() -> App:
def _end_user() -> EndUser:
- return EndUser(
- id="eu-1",
- tenant_id="tenant-1",
- app_id="app-1",
- type=EndUserType.BROWSER,
- session_id="session-1",
- )
+ return make_end_user(end_user_id="eu-1", app_id="app-1")
def _upload_file() -> UploadFile:
- upload_file = UploadFile(
- tenant_id="tenant-1",
- storage_type=StorageType.LOCAL,
+ return make_upload_file(
+ file_id="file-1",
key="upload/test.txt",
- name="test.txt",
size=100,
- extension="txt",
- mime_type="text/plain",
created_by_role=CreatorUserRole.END_USER,
created_by="eu-1",
- created_at=datetime(2024, 1, 1),
- used=False,
)
- upload_file.id = "file-1"
- return upload_file
class TestFileApi:
diff --git a/api/tests/unit_tests/controllers/web/test_human_input_file_upload.py b/api/tests/unit_tests/controllers/web/test_human_input_file_upload.py
index a3d2c8d188a..9285a6c8fc2 100644
--- a/api/tests/unit_tests/controllers/web/test_human_input_file_upload.py
+++ b/api/tests/unit_tests/controllers/web/test_human_input_file_upload.py
@@ -28,10 +28,7 @@ from controllers.web.human_input_file_upload import (
InvalidUploadTokenForbiddenError,
InvalidUploadTokenUnauthorizedError,
)
-from extensions.storage.storage_type import StorageType
from models import Account
-from models.account import AccountStatus
-from models.enums import CreatorUserRole
from models.model import UploadFile
from services.errors.file import (
BlockedFileExtensionError as BlockedFileExtensionServiceError,
@@ -53,6 +50,7 @@ from services.remote_file_service import RemoteFileNotFoundError as RemoteFileNo
from services.remote_file_service import RemoteFileUnavailableError as RemoteFileUnavailableServiceError
from services.remote_file_service import RemoteFileUploadResult
from services.remote_file_service import RemoteFileUrlBlockedError as RemoteFileUrlBlockedServiceError
+from tests.unit_tests.model_factories import make_account, make_upload_file
@pytest.fixture
@@ -63,9 +61,7 @@ def app() -> Flask:
def _account() -> Account:
- account = Account(name="Form Owner", email="[email protected]", status=AccountStatus.ACTIVE)
- account.id = "owner-1"
- return account
+ return make_account(account_id="owner-1", name="Form Owner", email="[email protected]")
def _upload_context() -> HumanInputUploadContext:
@@ -80,22 +76,14 @@ def _upload_context() -> HumanInputUploadContext:
def _upload_file() -> UploadFile:
- upload_file = UploadFile(
- tenant_id="tenant-1",
- storage_type=StorageType.LOCAL,
+ return make_upload_file(
+ file_id="file-1",
key="upload/sample.txt",
name="sample.txt",
size=7,
- extension="txt",
- mime_type="text/plain",
- created_by_role=CreatorUserRole.ACCOUNT,
created_by="end-user-1",
- created_at=datetime(2024, 1, 1),
- used=False,
source_url="signed-source-url",
)
- upload_file.id = "file-1"
- return upload_file
def _remote_upload_file() -> RemoteFileUploadResult:
diff --git a/api/tests/unit_tests/controllers/web/test_message_endpoints.py b/api/tests/unit_tests/controllers/web/test_message_endpoints.py
index 5feea96596d..9fc9ad2fedc 100644
--- a/api/tests/unit_tests/controllers/web/test_message_endpoints.py
+++ b/api/tests/unit_tests/controllers/web/test_message_endpoints.py
@@ -22,10 +22,10 @@ from controllers.web.message import (
MessageMoreLikeThisQuery,
MessageSuggestedQuestionApi,
)
-from models.enums import EndUserType
from models.model import App, AppMode, EndUser
from services.errors.app import MoreLikeThisDisabledError
from services.errors.message import MessageNotExistsError
+from tests.unit_tests.model_factories import make_end_user
def _chat_app() -> App:
@@ -37,12 +37,7 @@ def _completion_app() -> App:
def _end_user() -> EndUser:
- return EndUser(
- id="eu-1",
- tenant_id="tenant-1",
- type=EndUserType.BROWSER,
- session_id="session-1",
- )
+ return make_end_user(end_user_id="eu-1")
# The @model_validate and @with_session decorators wrap the handlers; tests
diff --git a/api/tests/unit_tests/controllers/web/test_remote_files.py b/api/tests/unit_tests/controllers/web/test_remote_files.py
index 791ec2770fb..0ca69debd55 100644
--- a/api/tests/unit_tests/controllers/web/test_remote_files.py
+++ b/api/tests/unit_tests/controllers/web/test_remote_files.py
@@ -23,7 +23,6 @@ from controllers.common.errors import (
)
from controllers.web import remote_files as remote_files_module
from libs.exception import BaseHTTPException
-from models.enums import EndUserType
from models.model import App, AppMode, EndUser
from services.errors.file import (
BlockedFileExtensionError as ServiceBlockedFileExtensionError,
@@ -55,6 +54,7 @@ REMOTE_FILE_ERROR_CASES: tuple[tuple[type[RemoteFileError], type[BaseHTTPExcepti
502,
),
)
+from tests.unit_tests.model_factories import make_end_user
def _app_model() -> App:
@@ -71,13 +71,7 @@ def _app_model() -> App:
def _end_user() -> EndUser:
- return EndUser(
- id="eu-1",
- tenant_id="tenant-1",
- app_id="app-1",
- type=EndUserType.BROWSER,
- session_id="session-1",
- )
+ return make_end_user(end_user_id="eu-1", app_id="app-1")
def _upload_result() -> RemoteFileUploadResult:
diff --git a/api/tests/unit_tests/controllers/web/test_saved_message.py b/api/tests/unit_tests/controllers/web/test_saved_message.py
index 22ec43a5b47..11ef11da686 100644
--- a/api/tests/unit_tests/controllers/web/test_saved_message.py
+++ b/api/tests/unit_tests/controllers/web/test_saved_message.py
@@ -14,9 +14,9 @@ from werkzeug.exceptions import NotFound
from controllers.common.controller_schemas import SavedMessageCreatePayload, SavedMessageListQuery
from controllers.web.error import NotCompletionAppError
from controllers.web.saved_message import SavedMessageApi, SavedMessageListApi
-from models.enums import EndUserType
from models.model import App, AppMode, EndUser
from services.errors.message import MessageNotExistsError
+from tests.unit_tests.model_factories import make_end_user
def _completion_app() -> App:
@@ -28,12 +28,7 @@ def _chat_app() -> App:
def _end_user() -> EndUser:
- return EndUser(
- id="eu-1",
- tenant_id="tenant-1",
- type=EndUserType.BROWSER,
- session_id="session-1",
- )
+ return make_end_user(end_user_id="eu-1")
# The @with_session and @model_validate decorators wrap the handler; tests call
diff --git a/api/tests/unit_tests/controllers/web/test_workflow.py b/api/tests/unit_tests/controllers/web/test_workflow.py
index 711976ed441..49c6ad74c6b 100644
--- a/api/tests/unit_tests/controllers/web/test_workflow.py
+++ b/api/tests/unit_tests/controllers/web/test_workflow.py
@@ -15,11 +15,11 @@ from controllers.web.error import (
)
from controllers.web.workflow import WorkflowRunApi, WorkflowTaskStopApi
from core.errors.error import ProviderTokenNotInitError, QuotaExceededError
-from models.enums import EndUserType
from models.model import App, AppMode, EndUser
from services.errors.app import (
TriggerWorkflowServiceModeUnavailableError as TriggerWorkflowServiceModeUnavailableServiceError,
)
+from tests.unit_tests.model_factories import make_end_user
def _workflow_app() -> App:
@@ -31,12 +31,7 @@ def _chat_app() -> App:
def _end_user() -> EndUser:
- return EndUser(
- id="eu-1",
- tenant_id="tenant-1",
- type=EndUserType.BROWSER,
- session_id="session-1",
- )
+ return make_end_user(end_user_id="eu-1")
# ---------------------------------------------------------------------------
diff --git a/api/tests/unit_tests/controllers/web/test_workflow_events.py b/api/tests/unit_tests/controllers/web/test_workflow_events.py
index 049ab04cb4f..e6a4abf86df 100644
--- a/api/tests/unit_tests/controllers/web/test_workflow_events.py
+++ b/api/tests/unit_tests/controllers/web/test_workflow_events.py
@@ -11,9 +11,10 @@ from flask import Flask
from controllers.common.errors import NotFoundError
from controllers.web.workflow_events import WorkflowEventsApi
from graphon.enums import WorkflowExecutionStatus
-from models.enums import CreatorUserRole, EndUserType, WorkflowRunTriggeredFrom
+from models.enums import CreatorUserRole, WorkflowRunTriggeredFrom
from models.model import App, AppMode, EndUser
from models.workflow import WorkflowRun, WorkflowType
+from tests.unit_tests.model_factories import make_end_user
def _workflow_app() -> App:
@@ -21,12 +22,7 @@ def _workflow_app() -> App:
def _end_user() -> EndUser:
- return EndUser(
- id="eu-1",
- tenant_id="tenant-1",
- type=EndUserType.BROWSER,
- session_id="session-1",
- )
+ return make_end_user(end_user_id="eu-1")
def _workflow_run(
diff --git a/api/tests/unit_tests/core/app/apps/advanced_chat/test_app_config_manager.py b/api/tests/unit_tests/core/app/apps/advanced_chat/test_app_config_manager.py
index aaea73832ef..b2ebdb96318 100644
--- a/api/tests/unit_tests/core/app/apps/advanced_chat/test_app_config_manager.py
+++ b/api/tests/unit_tests/core/app/apps/advanced_chat/test_app_config_manager.py
@@ -1,26 +1,17 @@
-import json
from unittest.mock import patch
from core.app.apps.advanced_chat.app_config_manager import AdvancedChatAppConfigManager
from models.model import App, AppMode
from models.workflow import Workflow, WorkflowType
+from tests.unit_tests.model_factories import make_app, make_workflow
def _app() -> App:
- return App(id="app-1", tenant_id="tenant-1", name="Advanced Chat App", mode=AppMode.ADVANCED_CHAT)
+ return make_app(name="Advanced Chat App", mode=AppMode.ADVANCED_CHAT, icon_type=None)
def _workflow() -> Workflow:
- return Workflow(
- id="wf-1",
- tenant_id="tenant-1",
- app_id="app-1",
- type=WorkflowType.CHAT,
- version=Workflow.VERSION_DRAFT,
- graph="{}",
- features=json.dumps({}),
- created_by="account-1",
- )
+ return make_workflow(workflow_id="wf-1", workflow_type=WorkflowType.CHAT, graph="{}")
class TestAdvancedChatAppConfigManager:
diff --git a/api/tests/unit_tests/core/app/apps/agent_app/test_input_guards.py b/api/tests/unit_tests/core/app/apps/agent_app/test_input_guards.py
index 9445bc800d4..eaf50049612 100644
--- a/api/tests/unit_tests/core/app/apps/agent_app/test_input_guards.py
+++ b/api/tests/unit_tests/core/app/apps/agent_app/test_input_guards.py
@@ -23,6 +23,7 @@ from core.app.entities.queue_entities import (
)
from core.moderation.base import ModerationError
from models.model import App, AppMode, Message, MessageAnnotation
+from tests.unit_tests.model_factories import make_app, make_message
class _FakeQueueManager:
@@ -46,11 +47,11 @@ def _make_entity(query: str = "hello") -> SimpleNamespace:
def _app() -> App:
- return App(id="app-1", tenant_id="tenant-1", name="Agent App", mode=AppMode.AGENT_CHAT)
+ return make_app(name="Agent App", mode=AppMode.AGENT_CHAT, icon_type=None)
def _message() -> Message:
- return Message(id="msg-1", app_id="app-1", conversation_id="conversation-1")
+ return make_message(message_id="msg-1")
def _patch_moderation(monkeypatch: pytest.MonkeyPatch, *, returns=None, raises: Exception | None = None) -> None:
diff --git a/api/tests/unit_tests/core/app/apps/agent_app/test_resolve_agent.py b/api/tests/unit_tests/core/app/apps/agent_app/test_resolve_agent.py
index 17f5fcfd19a..9ed6f108680 100644
--- a/api/tests/unit_tests/core/app/apps/agent_app/test_resolve_agent.py
+++ b/api/tests/unit_tests/core/app/apps/agent_app/test_resolve_agent.py
@@ -34,6 +34,7 @@ from services.agent.workspace_service import (
AgentWorkspaceBindingGenerationMismatchError,
AgentWorkspaceService,
)
+from tests.unit_tests.model_factories import make_account, make_app, make_conversation
_SOUL_DICT = {
"model": {
@@ -84,24 +85,22 @@ def _snapshot(
def _app() -> App:
- return App(
- id="app-1",
+ return make_app(
tenant_id="t1",
name="Agent App",
mode=AppMode.AGENT_CHAT,
+ icon_type=None,
enable_site=False,
enable_api=False,
)
def _account() -> Account:
- account = Account(name="Agent User", email="[email protected]")
- account.id = "user-1"
- return account
+ return make_account(account_id="user-1", name="Agent User", email="[email protected]")
def _conversation(*, binding_id: str) -> Conversation:
- return Conversation(id="conversation-1", app_id="app-1", agent_workspace_binding_id=binding_id)
+ return make_conversation(agent_workspace_binding_id=binding_id)
def _binding(
diff --git a/api/tests/unit_tests/core/app/apps/chat/test_app_config_manager.py b/api/tests/unit_tests/core/app/apps/chat/test_app_config_manager.py
index 7df8a5d8e4e..00052feff1e 100644
--- a/api/tests/unit_tests/core/app/apps/chat/test_app_config_manager.py
+++ b/api/tests/unit_tests/core/app/apps/chat/test_app_config_manager.py
@@ -6,10 +6,11 @@ from sqlalchemy.orm import Session
from core.app.app_config.entities import EasyUIBasedAppModelConfigFrom, ModelConfigEntity, PromptTemplateEntity
from core.app.apps.chat.app_config_manager import ChatAppConfigManager
from models.model import App, AppMode, AppModelConfig
+from tests.unit_tests.model_factories import make_app
def _app() -> App:
- return App(id="app-1", tenant_id="tenant-1", name="Chat App", mode=AppMode.CHAT)
+ return make_app(name="Chat App", icon_type=None)
def _app_model_config() -> AppModelConfig:
diff --git a/api/tests/unit_tests/core/app/apps/pipeline/test_pipeline_runner.py b/api/tests/unit_tests/core/app/apps/pipeline/test_pipeline_runner.py
index 3e847f65d73..37e3912ba68 100644
--- a/api/tests/unit_tests/core/app/apps/pipeline/test_pipeline_runner.py
+++ b/api/tests/unit_tests/core/app/apps/pipeline/test_pipeline_runner.py
@@ -26,9 +26,10 @@ from core.app.apps.pipeline.pipeline_runner import PipelineRunner
from core.app.entities.app_invoke_entities import InvokeFrom, UserFrom
from graphon.graph_events import GraphRunFailedEvent
from models.dataset import Dataset, Document, Pipeline
-from models.enums import DataSourceType, DocumentCreatedFrom, EndUserType
+from models.enums import DocumentCreatedFrom
from models.model import EndUser
from models.workflow import Workflow, WorkflowType
+from tests.unit_tests.model_factories import make_dataset, make_document, make_end_user, make_workflow
def _pipeline(*, tenant_id: str = "tenant", pipeline_id: str = "pipe") -> Pipeline:
@@ -39,10 +40,9 @@ def _pipeline(*, tenant_id: str = "tenant", pipeline_id: str = "pipe") -> Pipeli
def _dataset(*, tenant_id: str = "tenant", dataset_id: str = "ds", pipeline_id: str = "pipe") -> Dataset:
- return Dataset(
- id=dataset_id,
+ return make_dataset(
+ dataset_id=dataset_id,
tenant_id=tenant_id,
- name="Dataset",
description="",
created_by="user",
pipeline_id=pipeline_id,
@@ -50,40 +50,26 @@ def _dataset(*, tenant_id: str = "tenant", dataset_id: str = "ds", pipeline_id:
def _workflow(*, tenant_id: str = "tenant", pipeline_id: str = "pipe", graph: dict | None = None) -> Workflow:
- return Workflow.new(
+ return make_workflow(
tenant_id=tenant_id,
app_id=pipeline_id,
- type=WorkflowType.RAG_PIPELINE.value,
+ workflow_type=WorkflowType.RAG_PIPELINE,
version="v1",
- graph=json.dumps(graph if graph is not None else {"nodes": [], "edges": []}),
- features="{}",
+ graph=graph,
created_by="user",
- environment_variables=[],
- conversation_variables=[],
- rag_pipeline_variables=[],
)
def _end_user() -> EndUser:
- return EndUser(
- id="user",
- tenant_id="tenant",
- app_id="pipe",
- type=EndUserType.BROWSER,
- name="User",
- session_id="sess",
- )
+ return make_end_user(end_user_id="user", tenant_id="tenant", app_id="pipe", name="User", session_id="sess")
def _document(*, document_id: str = "doc", dataset_id: str = "ds", tenant_id: str = "tenant") -> Document:
- return Document(
- id=document_id,
+ return make_document(
+ document_id=document_id,
tenant_id=tenant_id,
dataset_id=dataset_id,
- position=1,
- data_source_type=DataSourceType.UPLOAD_FILE,
batch="batch",
- name="Document",
created_from=DocumentCreatedFrom.API,
created_by="user",
)
diff --git a/api/tests/unit_tests/core/app/apps/test_message_based_app_generator.py b/api/tests/unit_tests/core/app/apps/test_message_based_app_generator.py
index 410ec9db8a9..fdd7b53c50a 100644
--- a/api/tests/unit_tests/core/app/apps/test_message_based_app_generator.py
+++ b/api/tests/unit_tests/core/app/apps/test_message_based_app_generator.py
@@ -18,6 +18,7 @@ from core.app.entities.app_invoke_entities import ChatAppGenerateEntity, InvokeF
from models.account import Account
from models.model import App, AppMode, Conversation, Message
from services.errors.app_model_config import AppModelConfigBrokenError
+from tests.unit_tests.model_factories import make_account, make_app
class DummyModelConf:
@@ -47,19 +48,11 @@ class DummyCompletionGenerateEntity:
def _app(*, app_id: str = "app") -> App:
- return App(
- id=app_id,
- tenant_id="tenant-id",
- name="Message App",
- mode=AppMode.CHAT,
- app_model_config_id=None,
- )
+ return make_app(app_id=app_id, tenant_id="tenant-id", name="Message App", icon_type=None)
def _account() -> Account:
- account = Account(name="Message User", email="[email protected]")
- account.id = "user-id"
- return account
+ return make_account(account_id="user-id", name="Message User", email="[email protected]")
def _make_app_config(app_mode: AppMode) -> EasyUIBasedAppConfig:
diff --git a/api/tests/unit_tests/core/app/apps/test_workflow_app_generator.py b/api/tests/unit_tests/core/app/apps/test_workflow_app_generator.py
index 43dcab8c241..c381fb1bbc4 100644
--- a/api/tests/unit_tests/core/app/apps/test_workflow_app_generator.py
+++ b/api/tests/unit_tests/core/app/apps/test_workflow_app_generator.py
@@ -1,7 +1,6 @@
"""SQLite-backed tests for workflow app generation and worker reload behavior."""
import contextlib
-import json
from types import SimpleNamespace
from unittest.mock import MagicMock
@@ -22,7 +21,8 @@ from graphon.runtime import GraphRuntimeState, VariablePool
from models.enums import CreatorUserRole, EndUserType, WorkflowRunTriggeredFrom
from models.model import App, AppMode, EndUser
from models.snippet import CustomizedSnippet
-from models.workflow import Workflow, WorkflowKind, WorkflowNodeExecutionTriggeredFrom, WorkflowRun, WorkflowType
+from models.workflow import Workflow, WorkflowKind, WorkflowNodeExecutionTriggeredFrom, WorkflowRun
+from tests.unit_tests.model_factories import make_workflow
def _workflow(
@@ -32,19 +32,13 @@ def _workflow(
tenant_id: str = "tenant",
kind: WorkflowKind = WorkflowKind.STANDARD,
) -> Workflow:
- return Workflow(
- id=workflow_id,
+ return make_workflow(
+ workflow_id=workflow_id,
tenant_id=tenant_id,
app_id=app_id,
- type=WorkflowType.WORKFLOW,
kind=kind,
version="1",
- graph=json.dumps({"nodes": [], "edges": []}),
- features="{}",
created_by="creator",
- environment_variables=[],
- conversation_variables=[],
- rag_pipeline_variables=[],
)
diff --git a/api/tests/unit_tests/core/app/apps/test_workflow_app_runner_core.py b/api/tests/unit_tests/core/app/apps/test_workflow_app_runner_core.py
index fbe5035d3fa..94dac233314 100644
--- a/api/tests/unit_tests/core/app/apps/test_workflow_app_runner_core.py
+++ b/api/tests/unit_tests/core/app/apps/test_workflow_app_runner_core.py
@@ -49,21 +49,16 @@ from graphon.node_events import NodeRunResult
from graphon.runtime import GraphRuntimeState, VariablePool
from graphon.variables.segments import StringSegment
from graphon.variables.variables import StringVariable
-from models.workflow import Workflow, WorkflowType
+from models.workflow import Workflow
+from tests.unit_tests.model_factories import make_workflow
def _workflow(graph: dict[str, object] | None = None) -> Workflow:
- return Workflow.new(
+ return make_workflow(
tenant_id="tenant",
app_id="app",
- type=WorkflowType.WORKFLOW,
- version=Workflow.VERSION_DRAFT,
graph=json.dumps(graph or {}, default=str),
- features="{}",
created_by="account",
- environment_variables=[],
- conversation_variables=[],
- rag_pipeline_variables=[],
)
diff --git a/api/tests/unit_tests/core/app/apps/workflow/test_app_config_manager.py b/api/tests/unit_tests/core/app/apps/workflow/test_app_config_manager.py
index 55911e1cedf..a443dbd4a29 100644
--- a/api/tests/unit_tests/core/app/apps/workflow/test_app_config_manager.py
+++ b/api/tests/unit_tests/core/app/apps/workflow/test_app_config_manager.py
@@ -1,26 +1,17 @@
-import json
from unittest.mock import patch
from core.app.apps.workflow.app_config_manager import WorkflowAppConfigManager
from models.model import App, AppMode
-from models.workflow import Workflow, WorkflowType
+from models.workflow import Workflow
+from tests.unit_tests.model_factories import make_app, make_workflow
def _app() -> App:
- return App(id="app-1", tenant_id="tenant-1", name="Workflow App", mode=AppMode.WORKFLOW)
+ return make_app(name="Workflow App", mode=AppMode.WORKFLOW, icon_type=None)
def _workflow() -> Workflow:
- return Workflow(
- id="wf-1",
- tenant_id="tenant-1",
- app_id="app-1",
- type=WorkflowType.WORKFLOW,
- version=Workflow.VERSION_DRAFT,
- graph="{}",
- features=json.dumps({}),
- created_by="account-1",
- )
+ return make_workflow(workflow_id="wf-1", graph="{}")
class TestWorkflowAppConfigManager:
diff --git a/api/tests/unit_tests/core/app/apps/workflow/test_generate_task_pipeline_core.py b/api/tests/unit_tests/core/app/apps/workflow/test_generate_task_pipeline_core.py
index b4d8dbde01f..14af58bae44 100644
--- a/api/tests/unit_tests/core/app/apps/workflow/test_generate_task_pipeline_core.py
+++ b/api/tests/unit_tests/core/app/apps/workflow/test_generate_task_pipeline_core.py
@@ -1,6 +1,5 @@
from __future__ import annotations
-import json
from types import SimpleNamespace
import pytest
@@ -53,33 +52,19 @@ from graphon.enums import BuiltinNodeTypes, WorkflowExecutionStatus
from graphon.model_runtime.entities.llm_entities import LLMUsage
from graphon.runtime import GraphRuntimeState, VariablePool
from libs.datetime_utils import naive_utc_now
-from models.enums import CreatorUserRole, EndUserType
+from models.enums import CreatorUserRole
from models.model import AppMode, EndUser
-from models.workflow import Workflow, WorkflowAppLog, WorkflowType
+from models.workflow import Workflow, WorkflowAppLog
+from tests.unit_tests.model_factories import make_end_user, make_workflow
from tests.workflow_test_utils import build_test_variable_pool
def _workflow() -> Workflow:
- return Workflow(
- id="workflow-id",
- tenant_id="tenant",
- app_id="app",
- type=WorkflowType.WORKFLOW,
- version=Workflow.VERSION_DRAFT,
- graph="{}",
- features=json.dumps({}),
- created_by="user",
- )
+ return make_workflow(workflow_id="workflow-id", tenant_id="tenant", app_id="app", graph="{}", created_by="user")
def _end_user(*, end_user_id: str = "user", session_id: str = "session") -> EndUser:
- return EndUser(
- id=end_user_id,
- tenant_id="tenant",
- app_id="app",
- type=EndUserType.BROWSER,
- session_id=session_id,
- )
+ return make_end_user(end_user_id=end_user_id, tenant_id="tenant", app_id="app", session_id=session_id)
def _make_pipeline():
diff --git a/api/tests/unit_tests/core/app/features/test_annotation_reply.py b/api/tests/unit_tests/core/app/features/test_annotation_reply.py
index a9ae870fabc..a9001c96c61 100644
--- a/api/tests/unit_tests/core/app/features/test_annotation_reply.py
+++ b/api/tests/unit_tests/core/app/features/test_annotation_reply.py
@@ -10,26 +10,18 @@ from core.app.entities.app_invoke_entities import InvokeFrom
from core.app.features.annotation_reply.annotation_reply import AnnotationReplyFeature
from models.dataset import DatasetCollectionBinding
from models.enums import CollectionBindingType, ConversationFromSource
-from models.model import App, AppAnnotationHitHistory, AppAnnotationSetting, AppMode, Message, MessageAnnotation
+from models.model import App, AppAnnotationHitHistory, AppAnnotationSetting, Message, MessageAnnotation
+from tests.unit_tests.model_factories import make_app, make_message
TABLES = (AppAnnotationSetting, DatasetCollectionBinding, MessageAnnotation, AppAnnotationHitHistory)
def _app() -> App:
- return App(
- id="app-1",
- tenant_id="tenant-1",
- name="Test App",
- description="",
- mode=AppMode.CHAT,
- enable_site=True,
- enable_api=True,
- max_active_requests=0,
- )
+ return make_app(icon_type=None, max_active_requests=0)
def _message() -> Message:
- return Message(id="msg-1")
+ return make_message(message_id="msg-1", app_id=None, conversation_id=None)
def _persist_binding(session: Session) -> DatasetCollectionBinding:
diff --git a/api/tests/unit_tests/core/app/task_pipeline/test_easy_ui_based_generate_task_pipeline_core.py b/api/tests/unit_tests/core/app/task_pipeline/test_easy_ui_based_generate_task_pipeline_core.py
index 7c696955c97..5ffb62a8a67 100644
--- a/api/tests/unit_tests/core/app/task_pipeline/test_easy_ui_based_generate_task_pipeline_core.py
+++ b/api/tests/unit_tests/core/app/task_pipeline/test_easy_ui_based_generate_task_pipeline_core.py
@@ -55,12 +55,12 @@ from core.app.task_pipeline.easy_ui_based_generate_task_pipeline import EasyUIBa
from core.base.tts import AppGeneratorTTSPublisher, AudioTrunk
from core.ops.entities.trace_entity import TraceTaskName
from core.ops.ops_trace_manager import TraceQueueManager
-from extensions.storage.storage_type import StorageType
from graphon.file import FileTransferMethod, FileType
from graphon.model_runtime.entities.llm_entities import LLMResult, LLMResultChunk, LLMResultChunkDelta, LLMUsage
from graphon.model_runtime.entities.message_entities import AssistantPromptMessage, TextPromptMessageContent
from models.enums import ConversationFromSource, CreatorUserRole
from models.model import AppMode, Conversation, Message, MessageAgentThought, MessageFile, UploadFile
+from tests.unit_tests.model_factories import make_upload_file
class _DummyModelConf:
@@ -212,21 +212,17 @@ def _message_file(
def _upload_file(*, file_id: str, name: str, mime_type: str, size: int, extension: str) -> UploadFile:
- upload_file = UploadFile(
+ return make_upload_file(
+ file_id=file_id,
tenant_id="tenant",
- storage_type=StorageType.LOCAL,
key=f"uploads/{file_id}",
name=name,
size=size,
extension=extension,
mime_type=mime_type,
- created_by_role=CreatorUserRole.ACCOUNT,
created_by="user",
created_at=datetime.now(UTC),
- used=False,
)
- upload_file.id = file_id
- return upload_file
def _agent_thought() -> MessageAgentThought:
diff --git a/api/tests/unit_tests/core/app/task_pipeline/test_message_cycle_manager_optimization.py b/api/tests/unit_tests/core/app/task_pipeline/test_message_cycle_manager_optimization.py
index 535bd04bcfa..1277d08699f 100644
--- a/api/tests/unit_tests/core/app/task_pipeline/test_message_cycle_manager_optimization.py
+++ b/api/tests/unit_tests/core/app/task_pipeline/test_message_cycle_manager_optimization.py
@@ -20,7 +20,8 @@ from graphon.file import FileTransferMethod, FileType
from models import model as model_module
from models.base import TypeBase
from models.enums import ConversationFromSource, CreatorUserRole, MessageFileBelongsTo
-from models.model import App, AppMode, Conversation, MessageAnnotation, MessageFile
+from models.model import App, Conversation, MessageAnnotation, MessageFile
+from tests.unit_tests.model_factories import make_app, make_conversation
@dataclass(frozen=True)
@@ -46,29 +47,18 @@ def cycle_db(sqlite_engine: Engine, monkeypatch: pytest.MonkeyPatch) -> Iterator
def _app(*, app_id: str = "app-id", tenant_id: str = "tenant-1") -> App:
- return App(
- id=app_id,
- tenant_id=tenant_id,
- name="Test App",
- description="",
- mode=AppMode.CHAT,
- enable_site=True,
- enable_api=True,
- max_active_requests=0,
- )
+ return make_app(app_id=app_id, tenant_id=tenant_id, icon_type=None, max_active_requests=0)
def _conversation(*, conversation_id: str = "conv-1", app_id: str = "app-id") -> Conversation:
- conversation = Conversation(
+ return make_conversation(
+ conversation_id=conversation_id,
app_id=app_id,
- mode=AppMode.CHAT,
name="",
status="normal",
from_source=ConversationFromSource.API,
inputs={},
)
- conversation.id = conversation_id
- return conversation
def _message_file(
diff --git a/api/tests/unit_tests/core/datasource/test_datasource_file_manager.py b/api/tests/unit_tests/core/datasource/test_datasource_file_manager.py
index c61b170eb0d..efd856dfbf9 100644
--- a/api/tests/unit_tests/core/datasource/test_datasource_file_manager.py
+++ b/api/tests/unit_tests/core/datasource/test_datasource_file_manager.py
@@ -6,28 +6,23 @@ import pytest
from sqlalchemy.orm import Session
from core.datasource.datasource_file_manager import DatasourceFileManager
-from extensions.storage.storage_type import StorageType
from models.enums import CreatorUserRole
from models.model import MessageFile, UploadFile
from models.tools import ToolFile
+from tests.unit_tests.model_factories import make_upload_file
def _upload_file(id: str, *, key: str, mime_type: str) -> UploadFile:
- upload_file = UploadFile(
- tenant_id="tenant-1",
- storage_type=StorageType.LOCAL,
+ return make_upload_file(
+ file_id=id,
key=key,
name="file.png",
size=4,
extension=".png",
mime_type=mime_type,
- created_by_role=CreatorUserRole.ACCOUNT,
created_by="user-1",
created_at=datetime.now(UTC).replace(tzinfo=None),
- used=False,
)
- upload_file.id = id
- return upload_file
def _tool_file(id: str, *, key: str = "tool_key", mimetype: str = "image/png") -> ToolFile:
diff --git a/api/tests/unit_tests/core/llm_generator/test_llm_generator_missing.py b/api/tests/unit_tests/core/llm_generator/test_llm_generator_missing.py
index 77c887fef8d..6fbf18afbbb 100644
--- a/api/tests/unit_tests/core/llm_generator/test_llm_generator_missing.py
+++ b/api/tests/unit_tests/core/llm_generator/test_llm_generator_missing.py
@@ -15,6 +15,7 @@ from graphon.model_runtime.entities.llm_entities import LLMResult, LLMUsage
from graphon.model_runtime.entities.message_entities import AssistantPromptMessage
from models.dataset import Dataset
from services.workflow_service import WorkflowService
+from tests.unit_tests.model_factories import make_dataset
@pytest.fixture
@@ -45,8 +46,8 @@ def _model_manager() -> tuple[MagicMock, MagicMock]:
def _dataset(*, dataset_id: str, tenant_id: str, name: str, created_at: datetime) -> Dataset:
- return Dataset(
- id=dataset_id,
+ return make_dataset(
+ dataset_id=dataset_id,
tenant_id=tenant_id,
name=name,
created_by="account-id",
diff --git a/api/tests/unit_tests/core/ops/test_ops_trace_manager.py b/api/tests/unit_tests/core/ops/test_ops_trace_manager.py
index b37553f8510..c0675a15900 100644
--- a/api/tests/unit_tests/core/ops/test_ops_trace_manager.py
+++ b/api/tests/unit_tests/core/ops/test_ops_trace_manager.py
@@ -26,6 +26,7 @@ from models.model import App, AppMode, AppModelConfig, Conversation, Message, Me
from models.workflow import WorkflowAppLog, WorkflowAppLogCreatedFrom, WorkflowRun, WorkflowType
from repositories.sqlalchemy_api_workflow_run_repository import DifyAPISQLAlchemyWorkflowRunRepository
from tests.unit_tests.config_override import apply_config_overrides
+from tests.unit_tests.model_factories import make_app
class DummyConfig:
@@ -183,20 +184,7 @@ def encryption_functions(
def _app(session: Session, *, app_id: str = "app-id", tracing: str | None = None) -> App:
- app = App(
- id=app_id,
- tenant_id="tenant-1",
- name="App",
- description="description",
- mode=AppMode.CHAT,
- icon_type=None,
- icon=None,
- icon_background=None,
- enable_site=True,
- enable_api=True,
- max_active_requests=None,
- tracing=tracing,
- )
+ app = make_app(app_id=app_id, name="App", description="description", icon_type=None, tracing=tracing)
session.add(app)
session.commit()
return app
diff --git a/api/tests/unit_tests/core/ops/test_utils.py b/api/tests/unit_tests/core/ops/test_utils.py
index 16fd87cfaa4..34752b2a447 100644
--- a/api/tests/unit_tests/core/ops/test_utils.py
+++ b/api/tests/unit_tests/core/ops/test_utils.py
@@ -19,6 +19,7 @@ from core.ops.utils import (
)
from models.enums import ConversationFromSource
from models.model import Message
+from tests.unit_tests.model_factories import make_message
class _DatabaseBinding:
@@ -39,10 +40,11 @@ def message_session(sqlite_session: Session, monkeypatch: pytest.MonkeyPatch) ->
def _message(message_id: str) -> Message:
- message = Message(
- id=message_id,
+ return make_message(
+ message_id=message_id,
app_id="app-id",
conversation_id="conversation-id",
+ inputs={},
query="question",
message={"role": "user", "content": "question"},
answer="answer",
@@ -51,8 +53,6 @@ def _message(message_id: str) -> Message:
currency="USD",
from_source=ConversationFromSource.API,
)
- message._inputs = {}
- return message
class TestValidateUrl:
diff --git a/api/tests/unit_tests/core/plugin/test_backwards_invocation_app.py b/api/tests/unit_tests/core/plugin/test_backwards_invocation_app.py
index 3716628927b..adfd4084b3e 100644
--- a/api/tests/unit_tests/core/plugin/test_backwards_invocation_app.py
+++ b/api/tests/unit_tests/core/plugin/test_backwards_invocation_app.py
@@ -13,7 +13,8 @@ from core.plugin.backwards_invocation.base import BaseBackwardsInvocation
from models import Account, Tenant, TenantAccountJoin
from models.enums import EndUserType
from models.model import App, AppMode, AppModelConfig, EndUser
-from models.workflow import Workflow, WorkflowType
+from models.workflow import Workflow
+from tests.unit_tests.model_factories import make_app, make_end_user, make_workflow
class _Chunk(BaseModel):
@@ -33,30 +34,21 @@ def _app(
workflow_id: str | None = None,
app_model_config_id: str | None = None,
) -> App:
- return App(
- id=app_id,
+ return make_app(
+ app_id=app_id,
tenant_id=tenant_id,
name="Plugin app",
- description="",
mode=mode,
- enable_site=False,
- enable_api=False,
+ icon_type=None,
workflow_id=workflow_id,
app_model_config_id=app_model_config_id,
+ enable_site=False,
+ enable_api=False,
)
def _workflow(*, workflow_id: str = "workflow-1", app_id: str = "app-1", tenant_id: str = "tenant-1") -> Workflow:
- return Workflow(
- id=workflow_id,
- tenant_id=tenant_id,
- app_id=app_id,
- type=WorkflowType.WORKFLOW,
- version=Workflow.VERSION_DRAFT,
- graph="{}",
- _features="{}",
- created_by="account-1",
- )
+ return make_workflow(workflow_id=workflow_id, tenant_id=tenant_id, app_id=app_id, graph="{}")
def _end_user(
@@ -66,14 +58,12 @@ def _end_user(
app_id: str = "app-1",
session_id: str = "browser-session",
) -> EndUser:
- return EndUser(
- id=user_id,
+ return make_end_user(
+ end_user_id=user_id,
tenant_id=tenant_id,
app_id=app_id,
- type=EndUserType.BROWSER,
session_id=session_id,
name="Browser user",
- is_anonymous=True,
)
diff --git a/api/tests/unit_tests/core/rag/datasource/keyword/jieba/test_jieba.py b/api/tests/unit_tests/core/rag/datasource/keyword/jieba/test_jieba.py
index 835e6b54e87..2cfbfd5db68 100644
--- a/api/tests/unit_tests/core/rag/datasource/keyword/jieba/test_jieba.py
+++ b/api/tests/unit_tests/core/rag/datasource/keyword/jieba/test_jieba.py
@@ -11,6 +11,7 @@ import core.rag.datasource.keyword.jieba.jieba as jieba_module
from core.rag.datasource.keyword.jieba.jieba import Jieba, dumps_with_sets, set_orjson_default
from core.rag.models.document import Document
from models.dataset import Dataset, DatasetKeywordTable, DocumentSegment
+from tests.unit_tests.model_factories import make_dataset
class _DummyLock:
@@ -34,11 +35,7 @@ def _dataset_keyword_table(
def _dataset(dataset_keyword_table: DatasetKeywordTable | None = None, keyword_number: int | None = None) -> Dataset:
- dataset = Dataset(
- id="dataset-1",
- tenant_id="tenant-1",
- keyword_number=keyword_number,
- )
+ dataset = make_dataset(keyword_number=keyword_number)
dataset.get_dataset_keyword_table = MagicMock(return_value=dataset_keyword_table)
return dataset
diff --git a/api/tests/unit_tests/core/rag/datasource/keyword/test_keyword_base.py b/api/tests/unit_tests/core/rag/datasource/keyword/test_keyword_base.py
index e96472699b9..e3b781d3168 100644
--- a/api/tests/unit_tests/core/rag/datasource/keyword/test_keyword_base.py
+++ b/api/tests/unit_tests/core/rag/datasource/keyword/test_keyword_base.py
@@ -7,10 +7,11 @@ from sqlalchemy.orm import Session
from core.rag.datasource.keyword.keyword_base import BaseKeyword
from core.rag.models.document import Document
from models import Dataset
+from tests.unit_tests.model_factories import make_dataset
def _dataset() -> Dataset:
- return Dataset(id="dataset-1", tenant_id="tenant-1", name="Dataset", created_by="account-1")
+ return make_dataset()
class _KeywordThatRaises(BaseKeyword):
diff --git a/api/tests/unit_tests/core/rag/docstore/test_dataset_docstore.py b/api/tests/unit_tests/core/rag/docstore/test_dataset_docstore.py
index 91e1ff4b391..07f7a87372a 100644
--- a/api/tests/unit_tests/core/rag/docstore/test_dataset_docstore.py
+++ b/api/tests/unit_tests/core/rag/docstore/test_dataset_docstore.py
@@ -14,6 +14,7 @@ from sqlalchemy.orm import Session
from core.rag.docstore.dataset_docstore import DatasetDocumentStore, DocumentSegment
from core.rag.models.document import AttachmentDocument, ChildDocument, Document
from models.dataset import ChildChunk, Dataset, SegmentAttachmentBinding
+from tests.unit_tests.model_factories import make_dataset
TENANT_ID = "00000000-0000-0000-0000-000000000001"
DATASET_ID = "00000000-0000-0000-0000-000000000002"
@@ -23,11 +24,7 @@ ATTACHMENT_ID = "00000000-0000-0000-0000-000000000005"
def _dataset() -> Dataset:
- dataset = Dataset(
- id=DATASET_ID,
- tenant_id=TENANT_ID,
- )
- return dataset
+ return make_dataset(dataset_id=DATASET_ID, tenant_id=TENANT_ID)
def _persist_segment(
diff --git a/api/tests/unit_tests/core/rag/extractor/test_extract_processor.py b/api/tests/unit_tests/core/rag/extractor/test_extract_processor.py
index 2f00fda06db..b065556125e 100644
--- a/api/tests/unit_tests/core/rag/extractor/test_extract_processor.py
+++ b/api/tests/unit_tests/core/rag/extractor/test_extract_processor.py
@@ -9,28 +9,23 @@ import core.rag.extractor.extract_processor as processor_module
from core.rag.extractor.entity.datasource_type import DatasourceType
from core.rag.extractor.extract_processor import ExtractProcessor
from core.rag.models.document import Document
-from extensions.storage.storage_type import StorageType
-from models.enums import CreatorUserRole
from models.model import UploadFile
from tests.unit_tests.config_override import apply_config_overrides
+from tests.unit_tests.model_factories import make_upload_file
def _upload_file(*, key: str, file_id: str = "upload-file-1") -> UploadFile:
- upload_file = UploadFile(
- tenant_id="tenant-1",
- storage_type=StorageType.LOCAL,
+ return make_upload_file(
+ file_id=file_id,
key=key,
name=Path(key).name,
size=1,
extension=Path(key).suffix.lstrip("."),
mime_type="application/octet-stream",
- created_by_role=CreatorUserRole.ACCOUNT,
created_by="user-1",
created_at=datetime(2025, 1, 1),
used=True,
)
- upload_file.id = file_id
- return upload_file
class _ExtractorFactory:
diff --git a/api/tests/unit_tests/core/repositories/test_sqlalchemy_workflow_node_execution_repository.py b/api/tests/unit_tests/core/repositories/test_sqlalchemy_workflow_node_execution_repository.py
index b437cdcf205..953529b4c55 100644
--- a/api/tests/unit_tests/core/repositories/test_sqlalchemy_workflow_node_execution_repository.py
+++ b/api/tests/unit_tests/core/repositories/test_sqlalchemy_workflow_node_execution_repository.py
@@ -26,21 +26,22 @@ from core.repositories.sqlalchemy_workflow_node_execution_repository import (
_find_first,
_replace_or_append_offload,
)
-from extensions.storage.storage_type import StorageType
from graphon.entities import WorkflowNodeExecution
from graphon.enums import BuiltinNodeTypes, WorkflowNodeExecutionMetadataKey, WorkflowNodeExecutionStatus
-from models import Account, EndUser, Tenant
+from models import Account, EndUser
from models.enums import CreatorUserRole, ExecutionOffLoadType
from models.model import UploadFile
from models.workflow import WorkflowNodeExecutionModel, WorkflowNodeExecutionOffload, WorkflowNodeExecutionTriggeredFrom
+from tests.unit_tests.model_factories import make_account, make_tenant, make_upload_file
def _account(*, tenant_id: str = "tenant-1", user_id: str = "user-1") -> Account:
- user = Account(name="Test Account", email="[email protected]")
- user.id = user_id
- user._current_tenant = Tenant(name="Test Tenant")
- user._current_tenant.id = tenant_id
- return user
+ return make_account(
+ account_id=user_id,
+ name="Test Account",
+ tenant=make_tenant(tenant_id=tenant_id, name="Test Tenant"),
+ )
def _end_user(*, tenant_id: str = "tenant-1", user_id: str = "end-user-1") -> EndUser:
@@ -48,18 +49,14 @@ def _end_user(*, tenant_id: str = "tenant-1", user_id: str = "end-user-1") -> En
def _upload_file(*, key: str = "storage-key") -> UploadFile:
- return UploadFile(
- tenant_id="tenant-1",
- storage_type=StorageType.LOCAL,
+ return make_upload_file(
key=key,
name="offload.json",
size=1,
extension="json",
mime_type="application/json",
- created_by_role=CreatorUserRole.ACCOUNT,
created_by="user-1",
created_at=datetime.now(UTC),
- used=False,
)
diff --git a/api/tests/unit_tests/core/repositories/test_workflow_node_execution_conflict_handling.py b/api/tests/unit_tests/core/repositories/test_workflow_node_execution_conflict_handling.py
index 0335bff634b..d9f39da073f 100644
--- a/api/tests/unit_tests/core/repositories/test_workflow_node_execution_conflict_handling.py
+++ b/api/tests/unit_tests/core/repositories/test_workflow_node_execution_conflict_handling.py
@@ -19,7 +19,8 @@ from graphon.entities.workflow_node_execution import (
)
from graphon.enums import BuiltinNodeTypes
from libs.datetime_utils import naive_utc_now
-from models import Account, Tenant, WorkflowNodeExecutionModel, WorkflowNodeExecutionTriggeredFrom
+from models import Account, WorkflowNodeExecutionModel, WorkflowNodeExecutionTriggeredFrom
+from tests.unit_tests.model_factories import make_account, make_tenant
@dataclass(frozen=True)
@@ -51,12 +52,12 @@ def conflict_database(
def _account() -> Account:
- tenant = Tenant(name="Conflict Tenant")
- tenant.id = "test-tenant-id"
- account = Account(name="Conflict User", email="[email protected]")
- account.id = "test-user-id"
- account._current_tenant = tenant
- return account
+ return make_account(
+ account_id="test-user-id",
+ name="Conflict User",
+ tenant=make_tenant(tenant_id="test-tenant-id", name="Conflict Tenant"),
+ )
@pytest.fixture
diff --git a/api/tests/unit_tests/core/tools/workflow_as_tool/test_provider.py b/api/tests/unit_tests/core/tools/workflow_as_tool/test_provider.py
index 45d9bdbf770..efac03fa7ae 100644
--- a/api/tests/unit_tests/core/tools/workflow_as_tool/test_provider.py
+++ b/api/tests/unit_tests/core/tools/workflow_as_tool/test_provider.py
@@ -29,9 +29,10 @@ from extensions.ext_database import db
from graphon.variables.input_entities import VariableEntity, VariableEntityType
from models.account import Account
from models.base import TypeBase
-from models.model import App, AppMode, IconType
+from models.model import App, AppMode
from models.tools import WorkflowToolProvider
-from models.workflow import Workflow, WorkflowType
+from models.workflow import Workflow
+from tests.unit_tests.model_factories import make_account, make_app, make_workflow
@pytest.fixture
@@ -64,35 +65,27 @@ def _controller(provider_id: str = "provider-1") -> WorkflowToolProviderControll
def _app(*, tenant_id: str | None = None) -> App:
- return App(
- id=str(uuid.uuid4()),
+ return make_app(
+ app_id=str(uuid.uuid4()),
tenant_id=tenant_id or str(uuid.uuid4()),
name="Workflow App",
mode=AppMode.WORKFLOW,
- icon_type=IconType.EMOJI,
icon="workflow",
- icon_background="#FFFFFF",
- enable_site=True,
enable_api=False,
)
def _account() -> Account:
- return Account(name="Alice", email="[email protected]")
+ return make_account(account_id=None, name="Alice", email="[email protected]")
def _workflow(app: App, account: Account | None = None) -> Workflow:
- return Workflow.new(
+ return make_workflow(
tenant_id=app.tenant_id,
app_id=app.id,
- type=WorkflowType.WORKFLOW.value,
version="1",
- graph=json.dumps({"nodes": []}),
- features="{}",
+ graph={"nodes": []},
created_by=account.id if account else str(uuid.uuid4()),
- environment_variables=[],
- conversation_variables=[],
- rag_pipeline_variables=[],
)
diff --git a/api/tests/unit_tests/core/trigger/debug/test_debug_event_selectors.py b/api/tests/unit_tests/core/trigger/debug/test_debug_event_selectors.py
index 616ec72dcaa..32f8a47ac41 100644
--- a/api/tests/unit_tests/core/trigger/debug/test_debug_event_selectors.py
+++ b/api/tests/unit_tests/core/trigger/debug/test_debug_event_selectors.py
@@ -32,6 +32,7 @@ from graphon.enums import BuiltinNodeTypes, NodeType, WorkflowType
from models.model import App, AppMode
from models.workflow import Workflow
from tests.unit_tests.core.trigger.conftest import VALID_PROVIDER_ID
+from tests.unit_tests.model_factories import make_app
def _make_poller_args(node_config: dict[str, Any] | None = None) -> dict[str, Any]:
@@ -75,14 +76,12 @@ def _workflow_with_node(node_type: NodeType | None) -> Workflow:
def _app() -> App:
- return App(
- id="a1",
+ return make_app(
+ app_id="a1",
tenant_id="t1",
name="Trigger App",
- description="",
mode=AppMode.WORKFLOW,
- enable_site=True,
- enable_api=True,
+ icon_type=None,
max_active_requests=0,
)
diff --git a/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_validators.py b/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_validators.py
index f5361f9cc71..a49468aeea2 100644
--- a/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_validators.py
+++ b/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_validators.py
@@ -1,4 +1,3 @@
-import json
from datetime import UTC, datetime
from unittest.mock import Mock
@@ -23,15 +22,11 @@ from models.agent_config_entities import AgentSoulConfig, AgentSoulModelConfig,
from models.enums import CreatorUserRole
from models.model import UploadFile
from models.workflow import Workflow
+from tests.unit_tests.model_factories import make_workflow
def _workflow(graph: dict) -> Workflow:
- return Workflow(
- id="workflow-1",
- tenant_id="tenant-1",
- app_id="app-1",
- graph=json.dumps(graph),
- )
+ return make_workflow(workflow_id="workflow-1", graph=graph)
def _binding(node_job: WorkflowNodeJobConfig) -> WorkflowAgentNodeBinding:
diff --git a/api/tests/unit_tests/core/workflow/test_workflow_entry_helpers.py b/api/tests/unit_tests/core/workflow/test_workflow_entry_helpers.py
index 938fe289b0a..384340c7d0b 100644
--- a/api/tests/unit_tests/core/workflow/test_workflow_entry_helpers.py
+++ b/api/tests/unit_tests/core/workflow/test_workflow_entry_helpers.py
@@ -1,4 +1,3 @@
-import json
from collections import UserString
from datetime import datetime
from types import SimpleNamespace
@@ -21,8 +20,9 @@ from graphon.node_events import NodeRunResult
from graphon.nodes import BuiltinNodeTypes
from graphon.runtime import VariablePool
from graphon.variables.variables import StringVariable
-from models.workflow import Workflow, WorkflowType
+from models.workflow import Workflow
from tests.unit_tests.config_override import config_overrides_context
+from tests.unit_tests.model_factories import make_workflow
def _build_typed_node_config(node_type: NodeType):
@@ -31,16 +31,7 @@ def _build_typed_node_config(node_type: NodeType):
def _workflow() -> Workflow:
"""Build a real transient workflow for single-step orchestration tests."""
- return Workflow(
- id="workflow-id",
- tenant_id="tenant-id",
- app_id="app-id",
- type=WorkflowType.WORKFLOW,
- version=Workflow.VERSION_DRAFT,
- graph=json.dumps({"nodes": [], "edges": []}),
- _features="{}",
- created_by="user-id",
- )
+ return make_workflow(workflow_id="workflow-id", tenant_id="tenant-id", app_id="app-id", created_by="user-id")
def _build_minimal_workflow_entry(
diff --git a/api/tests/unit_tests/events/event_handlers/test_queue_default_plugin_install_when_tenant_created.py b/api/tests/unit_tests/events/event_handlers/test_queue_default_plugin_install_when_tenant_created.py
index 14303aef5d9..21c64cdd2fb 100644
--- a/api/tests/unit_tests/events/event_handlers/test_queue_default_plugin_install_when_tenant_created.py
+++ b/api/tests/unit_tests/events/event_handlers/test_queue_default_plugin_install_when_tenant_created.py
@@ -6,12 +6,11 @@ import pytest
from events.event_handlers import queue_default_plugin_install_when_tenant_created as handler_module
from models.account import Tenant
from tests.unit_tests.config_override import apply_config_overrides
+from tests.unit_tests.model_factories import make_tenant
def _tenant() -> Tenant:
- tenant = Tenant(name="Test tenant")
- tenant.id = "tenant-1"
- return tenant
+ return make_tenant(name="Test tenant")
def test_handle_skips_when_no_default_plugins_are_configured(monkeypatch: pytest.MonkeyPatch) -> None:
diff --git a/api/tests/unit_tests/libs/test_workspace_member_helper.py b/api/tests/unit_tests/libs/test_workspace_member_helper.py
index 6a202e79fa4..af9acd9cf62 100644
--- a/api/tests/unit_tests/libs/test_workspace_member_helper.py
+++ b/api/tests/unit_tests/libs/test_workspace_member_helper.py
@@ -17,6 +17,7 @@ from libs import oauth_bearer
from libs.oauth_bearer import AuthContext, Scope, SubjectType, TokenType, require_workspace_member
from models.account import Account, AccountStatus, Tenant, TenantAccountJoin, TenantAccountRole
from tests.unit_tests.config_override import apply_config_overrides
+from tests.unit_tests.model_factories import make_account
pytestmark = pytest.mark.usefixtures("community_edition")
@@ -92,12 +93,12 @@ def _persist_membership(
def _account(account_id: uuid.UUID, *, status: AccountStatus = AccountStatus.ACTIVE) -> Account:
- account = Account(name="Workspace member", email=f"{account_id}@example.com", status=status)
# SQLite's StringUUID adapter binds UUID objects as compact hex, while
# PostgreSQL binds their dashed string form. Persist the SQLite-bound form
# so the production query can keep accepting the AuthContext UUID object.
- account.id = account_id.hex
- return account
+ return make_account(
+ account_id=account_id.hex, name="Workspace member", email=f"{account_id}@example.com", status=status
+ )
def test_skips_for_enterprise_edition(database: Database, monkeypatch: pytest.MonkeyPatch) -> None:
diff --git a/api/tests/unit_tests/model_factories.py b/api/tests/unit_tests/model_factories.py
new file mode 100644
index 00000000000..3aeb0f061b5
--- /dev/null
+++ b/api/tests/unit_tests/model_factories.py
@@ -0,0 +1,489 @@
+"""Builders for the model instances unit tests construct over and over.
+
+Every builder returns a transient (unpersisted) instance carrying the field set
+that most call sites need, so a test module only spells out the values it
+actually asserts on. Keyword arguments map one-to-one onto model columns.
+"""
+
+import json
+from collections.abc import Mapping, Sequence
+from datetime import datetime
+from decimal import Decimal
+
+from extensions.storage.storage_type import StorageType
+from graphon.variables import VariableBase
+from models.account import Account, AccountStatus, Tenant, TenantAccountRole, TenantStatus
+from models.dataset import Dataset, Document
+from models.enums import (
+ AppStatus,
+ CreatorUserRole,
+ DataSourceType,
+ DocumentCreatedFrom,
+ EndUserType,
+ PermissionEnum,
+)
+from models.model import (
+ App,
+ AppMode,
+ Conversation,
+ ConversationFromSource,
+ EndUser,
+ IconType,
+ Message,
+ UploadFile,
+)
+from models.workflow import Workflow, WorkflowKind, WorkflowType
+from services.entities.account_entities import AccountSnapshot
+
+
+def make_app(
+ *,
+ app_id: str = "app-1",
+ tenant_id: str = "tenant-1",
+ name: str = "Test App",
+ description: str = "",
+ mode: AppMode = AppMode.CHAT,
+ icon_type: IconType | None = IconType.EMOJI,
+ icon: str | None = "robot",
+ icon_background: str | None = "#FFFFFF",
+ status: AppStatus = AppStatus.NORMAL,
+ app_model_config_id: str | None = None,
+ workflow_id: str | None = None,
+ enable_site: bool = True,
+ enable_api: bool = True,
+ api_rpm: int = 0,
+ api_rph: int = 0,
+ is_demo: bool = False,
+ is_public: bool = False,
+ is_universal: bool = False,
+ max_active_requests: int | None = None,
+ tracing: str | None = None,
+ created_by: str | None = None,
+ maintainer: str | None = None,
+ use_icon_as_answer_icon: bool = False,
+) -> App:
+ """Build a transient ``App``.
+
+ ``app_id`` is spelled out instead of ``id`` so call sites never shadow the
+ builtin. ``icon_type=None`` clears ``icon`` and ``icon_background`` too, for
+ the tests that assert on an app without icon metadata.
+ """
+ if icon_type is None:
+ icon = None
+ icon_background = None
+ return App(
+ id=app_id,
+ tenant_id=tenant_id,
+ name=name,
+ description=description,
+ mode=mode,
+ icon_type=icon_type,
+ icon=icon,
+ icon_background=icon_background,
+ status=status,
+ app_model_config_id=app_model_config_id,
+ workflow_id=workflow_id,
+ enable_site=enable_site,
+ enable_api=enable_api,
+ api_rpm=api_rpm,
+ api_rph=api_rph,
+ is_demo=is_demo,
+ is_public=is_public,
+ is_universal=is_universal,
+ max_active_requests=max_active_requests,
+ tracing=tracing,
+ created_by=created_by,
+ maintainer=maintainer,
+ use_icon_as_answer_icon=use_icon_as_answer_icon,
+ )
+
+
+def make_account(
+ *,
+ account_id: str | None = "account-1",
+ name: str = "Test User",
+ email: str = "[email protected]",
+ status: AccountStatus = AccountStatus.ACTIVE,
+ interface_language: str | None = None,
+ timezone: str | None = None,
+ role: TenantAccountRole | None = None,
+ tenant: Tenant | None = None,
+) -> Account:
+ """Build a transient ``Account``.
+
+ ``id``, ``role`` and ``_current_tenant`` are ``init=False`` on the dataclass
+ model, so they are assigned after construction. Passing ``account_id=None``
+ keeps the generated identifier.
+ """
+ account = Account(
+ name=name,
+ email=email,
+ status=status,
+ interface_language=interface_language,
+ timezone=timezone,
+ )
+ if account_id is not None:
+ account.id = account_id
+ account.role = role
+ account._current_tenant = tenant
+ return account
+
+
+def make_tenant(
+ *,
+ tenant_id: str | None = "tenant-1",
+ name: str = "Test Tenant",
+ status: TenantStatus = TenantStatus.NORMAL,
+ encrypt_public_key: str | None = None,
+) -> Tenant:
+ """Build a transient ``Tenant``; ``tenant_id=None`` keeps the generated one."""
+ tenant = Tenant(name=name, status=status, encrypt_public_key=encrypt_public_key)
+ if tenant_id is not None:
+ tenant.id = tenant_id
+ return tenant
+
+
+def make_end_user(
+ *,
+ end_user_id: str = "end-user-1",
+ tenant_id: str = "tenant-1",
+ app_id: str | None = None,
+ end_user_type: EndUserType = EndUserType.BROWSER,
+ session_id: str = "session-1",
+ external_user_id: str | None = None,
+ name: str | None = None,
+ is_anonymous: bool = True,
+) -> EndUser:
+ """Build a transient ``EndUser``."""
+ return EndUser(
+ id=end_user_id,
+ tenant_id=tenant_id,
+ app_id=app_id,
+ type=end_user_type,
+ session_id=session_id,
+ external_user_id=external_user_id,
+ name=name,
+ is_anonymous=is_anonymous,
+ )
+
+
+def make_account_snapshot(
+ *,
+ account_id: str = "account-1",
+ name: str = "Account",
+ email: str = "[email protected]",
+ avatar: str | None = None,
+ is_password_set: bool = False,
+ interface_language: str | None = "en-US",
+ interface_theme: str | None = "light",
+ timezone: str | None = "UTC",
+ last_login_at: datetime | None = None,
+ last_login_ip: str | None = None,
+ status: str = "active",
+ initialized_at: datetime | None = None,
+ created_at: datetime = datetime(2026, 1, 1),
+) -> AccountSnapshot:
+ """Build the framework-neutral ``AccountSnapshot`` the account services return."""
+ return AccountSnapshot(
+ id=account_id,
+ name=name,
+ email=email,
+ avatar=avatar,
+ is_password_set=is_password_set,
+ interface_language=interface_language,
+ interface_theme=interface_theme,
+ timezone=timezone,
+ last_login_at=last_login_at,
+ last_login_ip=last_login_ip,
+ status=status,
+ initialized_at=initialized_at,
+ created_at=created_at,
+ )
+
+
+def make_workflow(
+ *,
+ workflow_id: str | None = None,
+ tenant_id: str = "tenant-1",
+ app_id: str = "app-1",
+ workflow_type: WorkflowType = WorkflowType.WORKFLOW,
+ kind: WorkflowKind = WorkflowKind.STANDARD,
+ version: str = Workflow.VERSION_DRAFT,
+ graph: str | Mapping[str, object] | None = None,
+ features: str | Mapping[str, object] = "{}",
+ created_by: str = "account-1",
+ environment_variables: Sequence[VariableBase] = (),
+ conversation_variables: Sequence[VariableBase] = (),
+ rag_pipeline_variables: list[dict[str, object]] | None = None,
+ marked_name: str = "",
+ marked_comment: str = "",
+ version_number: int | None = None,
+) -> Workflow:
+ """Build a transient ``Workflow`` through ``Workflow.new``.
+
+ ``graph`` and ``features`` accept either the serialized column value or the
+ mapping to serialize, since most call sites start from a graph literal.
+ ``workflow_id=None`` keeps the identifier ``Workflow.new`` generates.
+ """
+ workflow = Workflow.new(
+ tenant_id=tenant_id,
+ app_id=app_id,
+ type=workflow_type.value,
+ kind=kind.value,
+ version=version,
+ graph=graph if isinstance(graph, str) else json.dumps({"nodes": [], "edges": []} if graph is None else graph),
+ features=features if isinstance(features, str) else json.dumps(features),
+ created_by=created_by,
+ environment_variables=environment_variables,
+ conversation_variables=conversation_variables,
+ rag_pipeline_variables=rag_pipeline_variables or [],
+ marked_name=marked_name,
+ marked_comment=marked_comment,
+ version_number=version_number,
+ )
+ if workflow_id is not None:
+ workflow.id = workflow_id
+ return workflow
+
+
+def make_upload_file(
+ *,
+ file_id: str | None = None,
+ tenant_id: str = "tenant-1",
+ storage_type: StorageType = StorageType.LOCAL,
+ key: str = "uploads/file-1",
+ name: str = "test.txt",
+ size: int = 10,
+ extension: str = "txt",
+ mime_type: str = "text/plain",
+ created_by_role: CreatorUserRole = CreatorUserRole.ACCOUNT,
+ created_by: str = "account-1",
+ created_at: datetime | None = None,
+ used: bool = False,
+ source_url: str = "",
+) -> UploadFile:
+ """Build a transient ``UploadFile``; ``file_id=None`` keeps the generated one."""
+ upload_file = UploadFile(
+ tenant_id=tenant_id,
+ storage_type=storage_type,
+ key=key,
+ name=name,
+ size=size,
+ extension=extension,
+ mime_type=mime_type,
+ created_by_role=created_by_role,
+ created_by=created_by,
+ created_at=created_at if created_at is not None else datetime(2024, 1, 1),
+ used=used,
+ source_url=source_url,
+ )
+ if file_id is not None:
+ upload_file.id = file_id
+ return upload_file
+
+
+def make_dataset(
+ *,
+ dataset_id: str | None = "dataset-1",
+ tenant_id: str = "tenant-1",
+ name: str = "Dataset",
+ description: str | None = None,
+ provider: str | None = None,
+ permission: PermissionEnum | None = None,
+ data_source_type: DataSourceType | None = None,
+ indexing_technique: str | None = None,
+ index_struct: str | None = None,
+ created_by: str = "account-1",
+ maintainer: str | None = None,
+ created_at: datetime | None = None,
+ embedding_model: str | None = None,
+ embedding_model_provider: str | None = None,
+ keyword_number: int | None = None,
+ built_in_field_enabled: bool | None = None,
+ icon_info: dict[str, str] | None = None,
+ pipeline_id: str | None = None,
+ chunk_structure: str | None = None,
+ enable_api: bool | None = None,
+) -> Dataset:
+ """Build a transient ``Dataset``.
+
+ Optional columns default to ``None`` so an unset keyword leaves the column
+ unset, matching a bare ``Dataset(...)``. ``dataset_id=None`` keeps the
+ generated identifier.
+ """
+ values: dict[str, object] = {"tenant_id": tenant_id, "name": name, "created_by": created_by}
+ optional: dict[str, object | None] = {
+ "id": dataset_id,
+ "description": description,
+ "provider": provider,
+ "permission": permission,
+ "data_source_type": data_source_type,
+ "indexing_technique": indexing_technique,
+ "index_struct": index_struct,
+ "maintainer": maintainer,
+ "created_at": created_at,
+ "embedding_model": embedding_model,
+ "embedding_model_provider": embedding_model_provider,
+ "keyword_number": keyword_number,
+ "built_in_field_enabled": built_in_field_enabled,
+ "icon_info": icon_info,
+ "pipeline_id": pipeline_id,
+ "chunk_structure": chunk_structure,
+ "enable_api": enable_api,
+ }
+ values.update({key: value for key, value in optional.items() if value is not None})
+ return Dataset(**values)
+
+
+def make_conversation(
+ *,
+ conversation_id: str | None = "conversation-1",
+ app_id: str = "app-1",
+ mode: AppMode = AppMode.CHAT,
+ name: str = "Conversation",
+ inputs: Mapping[str, object] | None = None,
+ status: str | None = None,
+ from_source: ConversationFromSource | None = None,
+ from_account_id: str | None = None,
+ from_end_user_id: str | None = None,
+ invoke_from: str | None = None,
+ introduction: str | None = None,
+ system_instruction: str | None = None,
+ system_instruction_tokens: int | None = None,
+ override_model_configs: str | None = None,
+ summary: str | None = None,
+ dialogue_count: int | None = None,
+ is_deleted: bool | None = None,
+ agent_workspace_binding_id: str | None = None,
+) -> Conversation:
+ """Build a transient ``Conversation``; unset keywords leave their column unset."""
+ values: dict[str, object] = {"app_id": app_id, "mode": mode, "name": name}
+ optional: dict[str, object | None] = {
+ "id": conversation_id,
+ "inputs": inputs,
+ "status": status,
+ "from_source": from_source,
+ "from_account_id": from_account_id,
+ "from_end_user_id": from_end_user_id,
+ "invoke_from": invoke_from,
+ "introduction": introduction,
+ "system_instruction": system_instruction,
+ "system_instruction_tokens": system_instruction_tokens,
+ "override_model_configs": override_model_configs,
+ "summary": summary,
+ "dialogue_count": dialogue_count,
+ "is_deleted": is_deleted,
+ "agent_workspace_binding_id": agent_workspace_binding_id,
+ }
+ values.update({key: value for key, value in optional.items() if value is not None})
+ return Conversation(**values)
+
+
+def make_message(
+ *,
+ message_id: str | None = "message-1",
+ app_id: str | None = "app-1",
+ conversation_id: str | None = "conversation-1",
+ inputs: Mapping[str, object] | None = None,
+ query: str | None = None,
+ message: object | None = None,
+ answer: str | None = None,
+ status: str | None = None,
+ message_unit_price: Decimal | None = None,
+ answer_unit_price: Decimal | None = None,
+ total_price: Decimal | None = None,
+ currency: str | None = None,
+ from_source: ConversationFromSource | None = None,
+ from_account_id: str | None = None,
+ from_end_user_id: str | None = None,
+ invoke_from: str | None = None,
+ message_tokens: int | None = None,
+ answer_tokens: int | None = None,
+ provider_response_latency: float | None = None,
+ workflow_run_id: str | None = None,
+ created_at: datetime | None = None,
+ updated_at: datetime | None = None,
+) -> Message:
+ """Build a transient ``Message``; unset keywords leave their column unset."""
+ values: dict[str, object] = {}
+ optional: dict[str, object | None] = {
+ "id": message_id,
+ "app_id": app_id,
+ "conversation_id": conversation_id,
+ "inputs": inputs,
+ "query": query,
+ "message": message,
+ "answer": answer,
+ "status": status,
+ "message_unit_price": message_unit_price,
+ "answer_unit_price": answer_unit_price,
+ "total_price": total_price,
+ "currency": currency,
+ "from_source": from_source,
+ "from_account_id": from_account_id,
+ "from_end_user_id": from_end_user_id,
+ "invoke_from": invoke_from,
+ "message_tokens": message_tokens,
+ "answer_tokens": answer_tokens,
+ "provider_response_latency": provider_response_latency,
+ "workflow_run_id": workflow_run_id,
+ "created_at": created_at,
+ "updated_at": updated_at,
+ }
+ values.update({key: value for key, value in optional.items() if value is not None})
+ return Message(**values)
+
+
+def make_document(
+ *,
+ document_id: str | None = "document-1",
+ tenant_id: str = "tenant-1",
+ dataset_id: str = "dataset-1",
+ position: int = 1,
+ data_source_type: DataSourceType = DataSourceType.UPLOAD_FILE,
+ data_source_info: str | None = None,
+ batch: str = "batch-1",
+ name: str = "Document",
+ created_from: str = DocumentCreatedFrom.WEB,
+ created_by: str = "account-1",
+ doc_form: str | None = None,
+ doc_metadata: dict[str, object] | None = None,
+ created_at: datetime | None = None,
+ updated_at: datetime | None = None,
+) -> Document:
+ """Build a transient ``Document``; unset keywords leave their column unset."""
+ values: dict[str, object] = {
+ "tenant_id": tenant_id,
+ "dataset_id": dataset_id,
+ "position": position,
+ "data_source_type": data_source_type,
+ "batch": batch,
+ "name": name,
+ "created_from": created_from,
+ "created_by": created_by,
+ }
+ optional: dict[str, object | None] = {
+ "id": document_id,
+ "data_source_info": data_source_info,
+ "doc_form": doc_form,
+ "doc_metadata": doc_metadata,
+ "created_at": created_at,
+ "updated_at": updated_at,
+ }
+ values.update({key: value for key, value in optional.items() if value is not None})
+ return Document(**values)
+
+
+__all__ = [
+ "make_account",
+ "make_account_snapshot",
+ "make_app",
+ "make_conversation",
+ "make_dataset",
+ "make_document",
+ "make_end_user",
+ "make_message",
+ "make_tenant",
+ "make_upload_file",
+ "make_workflow",
+]
diff --git a/api/tests/unit_tests/models/test_comment_models.py b/api/tests/unit_tests/models/test_comment_models.py
index 480b6fadcc3..0dc1e3339d2 100644
--- a/api/tests/unit_tests/models/test_comment_models.py
+++ b/api/tests/unit_tests/models/test_comment_models.py
@@ -5,12 +5,11 @@ from sqlalchemy.orm import Session
from models.account import Account
from models.comment import WorkflowComment, WorkflowCommentMention, WorkflowCommentReply
+from tests.unit_tests.model_factories import make_account
def _account(name: str) -> Account:
- account = Account(name=name, email=f"{name.lower()}@example.com")
- account.id = str(uuid4())
- return account
+ return make_account(account_id=str(uuid4()), name=name, email=f"{name.lower()}@example.com")
def _comment(created_by: str, resolved_by: str | None = None) -> WorkflowComment:
diff --git a/api/tests/unit_tests/services/agent/test_agent_observability_service.py b/api/tests/unit_tests/services/agent/test_agent_observability_service.py
index 32a6e5a54d8..db6a8c19cc0 100644
--- a/api/tests/unit_tests/services/agent/test_agent_observability_service.py
+++ b/api/tests/unit_tests/services/agent/test_agent_observability_service.py
@@ -18,7 +18,7 @@ from models.enums import (
FeedbackRating,
MessageStatus,
)
-from models.model import App, AppMode, Conversation, IconType, Message, MessageFeedback
+from models.model import App, AppMode, Conversation, Message, MessageFeedback
from models.workflow import (
WorkflowExecutionStatus,
WorkflowNodeExecutionModel,
@@ -30,25 +30,16 @@ from models.workflow import (
from services.agent import observability_service as observability_service_module
from services.agent.observability_service import AgentLogQueryParams, AgentObservabilityService
from tests.unit_tests.config_override import apply_config_overrides
+from tests.unit_tests.model_factories import make_app, make_conversation, make_message
def _app(*, app_id: str = "app-1", name: str = "Iris", mode: AppMode = AppMode.AGENT_CHAT) -> App:
- return App(
- id=app_id,
- tenant_id="tenant-1",
- name=name,
- mode=mode,
- icon_type=IconType.EMOJI,
- icon="robot",
- icon_background="#fff",
- enable_site=False,
- enable_api=False,
- )
+ return make_app(app_id=app_id, name=name, mode=mode, icon_background="#fff", enable_site=False, enable_api=False)
def _conversation(*, conversation_id: str = "conversation-1", app_id: str = "app-1") -> Conversation:
- return Conversation(
- id=conversation_id,
+ return make_conversation(
+ conversation_id=conversation_id,
app_id=app_id,
mode=AppMode.AGENT_CHAT,
name="Debug conversation",
@@ -66,8 +57,8 @@ def _message(
created_at: datetime | None = None,
) -> Message:
timestamp = created_at or naive_utc_now()
- return Message(
- id=message_id,
+ return make_message(
+ message_id=message_id,
app_id=app_id,
conversation_id=conversation_id,
inputs={},
diff --git a/api/tests/unit_tests/services/agent/test_agent_services.py b/api/tests/unit_tests/services/agent/test_agent_services.py
index 7b1558e7999..ef219521c6b 100644
--- a/api/tests/unit_tests/services/agent/test_agent_services.py
+++ b/api/tests/unit_tests/services/agent/test_agent_services.py
@@ -37,11 +37,11 @@ from models.agent_config_entities import (
DeclaredOutputType,
WorkflowNodeJobConfig,
)
-from models.enums import AppStatus, ConversationFromSource, ConversationStatus
+from models.enums import ConversationFromSource, ConversationStatus
from models.model import App, AppMode, AppModelConfig, Conversation, IconType, Message
from models.skill import AgentSkillBindingSnapshot, Skill, SkillVersion, SkillVersionManifest
from models.tools import ToolFile
-from models.workflow import Workflow, WorkflowType
+from models.workflow import Workflow
from services.agent import composer_service, roster_service
from services.agent.agent_soul_state import agent_soul_has_model
from services.agent.composer_service import AgentComposerService
@@ -66,6 +66,7 @@ from services.entities.agent_entities import (
ComposerSaveStrategy,
ComposerVariant,
)
+from tests.unit_tests.model_factories import make_account, make_app, make_conversation, make_workflow
def _agent_soul_with_model() -> AgentSoulConfig:
@@ -124,14 +125,13 @@ def _snapshot(
def _conversation(*, conversation_id: str = "conversation-1", account_id: str = "account-1") -> Conversation:
- return Conversation(
- id=conversation_id,
- app_id="app-1",
- override_model_configs="{}",
+ return make_conversation(
+ conversation_id=conversation_id,
mode=AppMode.AGENT_CHAT,
name="Debug",
+ inputs={},
+ override_model_configs="{}",
summary="",
- _inputs={},
introduction="",
system_instruction="",
status=ConversationStatus.NORMAL,
@@ -142,19 +142,7 @@ def _conversation(*, conversation_id: str = "conversation-1", account_id: str =
def _workflow(*, workflow_id: str = "workflow-1", tenant_id: str = "tenant-1", app_id: str = "app-1") -> Workflow:
- return Workflow(
- id=workflow_id,
- tenant_id=tenant_id,
- app_id=app_id,
- type=WorkflowType.WORKFLOW,
- version=Workflow.VERSION_DRAFT,
- graph='{"nodes": [], "edges": []}',
- _features="{}",
- created_by="account-1",
- _environment_variables="{}",
- _conversation_variables="{}",
- _rag_pipeline_variables="{}",
- )
+ return make_workflow(workflow_id=workflow_id, tenant_id=tenant_id, app_id=app_id)
def _app(
@@ -164,27 +152,20 @@ def _app(
name: str = "Agent App",
mode: AppMode = AppMode.AGENT_CHAT,
) -> App:
- return App(
- id=app_id,
+ return make_app(
+ app_id=app_id,
tenant_id=tenant_id,
name=name,
- description="",
mode=mode,
- icon_type=IconType.EMOJI,
icon="🤖",
icon_background="#fff",
- status=AppStatus.NORMAL,
enable_site=False,
- enable_api=True,
- max_active_requests=None,
created_by="account-1",
)
def _account(*, account_id: str = "account-1") -> Account:
- account = Account(name="Agent Tester", email=f"{account_id}@example.com")
- account.id = account_id
- return account
+ return make_account(account_id=account_id, name="Agent Tester", email=f"{account_id}@example.com")
def test_agent_soul_has_model():
diff --git a/api/tests/unit_tests/services/agent/test_workflow_publish_service.py b/api/tests/unit_tests/services/agent/test_workflow_publish_service.py
index d50f3589b68..fa8eee4c361 100644
--- a/api/tests/unit_tests/services/agent/test_workflow_publish_service.py
+++ b/api/tests/unit_tests/services/agent/test_workflow_publish_service.py
@@ -17,24 +17,14 @@ from models.agent import (
from models.agent_config_entities import AgentSoulConfig
from models.enums import AppStatus
from models.model import App, AppMode
-from models.workflow import Workflow, WorkflowType
+from models.workflow import Workflow
from services.agent.dsl_service import AgentDslService
from services.agent.workflow_publish_service import WorkflowAgentPublishService
+from tests.unit_tests.model_factories import make_workflow
def _workflow(*, workflow_id: str = "workflow-1", version: str = Workflow.VERSION_DRAFT) -> Workflow:
- return Workflow(
- id=workflow_id,
- tenant_id="tenant-1",
- app_id="app-1",
- type=WorkflowType.WORKFLOW,
- version=version,
- graph={"nodes": [], "edges": []},
- features={},
- created_by="account-1",
- environment_variables=[],
- conversation_variables=[],
- )
+ return make_workflow(workflow_id=workflow_id, version=version)
def _inline_agent(
diff --git a/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline_dsl_service.py b/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline_dsl_service.py
index 44859fb7e2d..de56869d4a2 100644
--- a/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline_dsl_service.py
+++ b/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline_dsl_service.py
@@ -22,7 +22,7 @@ from sqlalchemy.orm import Session, sessionmaker
from core.workflow.llm_environment_variable import LLMEnvironmentVariable
from core.workflow.nodes.knowledge_index import KNOWLEDGE_INDEX_NODE_TYPE
from graphon.enums import BuiltinNodeTypes
-from models import Account, Tenant
+from models import Account
from models.dataset import (
Dataset,
Pipeline,
@@ -39,6 +39,7 @@ from services.rag_pipeline.rag_pipeline_dsl_service import (
RagPipelineDslService,
RagPipelinePendingData,
)
+from tests.unit_tests.model_factories import make_account, make_dataset, make_tenant, make_workflow
@pytest.fixture
@@ -47,12 +48,12 @@ def service(sqlite_session: Session) -> RagPipelineDslService:
def _account(*, tenant_id: str = "tenant-1", account_id: str = "account-1") -> Account:
- tenant = Tenant(name="Tenant")
- tenant.id = tenant_id
- account = Account(name="Account", email="[email protected]")
- account.id = account_id
- account._current_tenant = tenant
- return account
+ return make_account(
+ account_id=account_id,
+ name="Account",
+ tenant=make_tenant(tenant_id=tenant_id, name="Tenant"),
+ )
def _pipeline(
@@ -76,19 +77,12 @@ def _pipeline(
def _workflow(session: Session, pipeline: Pipeline, *, graph: dict[str, Any] | None = None) -> Workflow:
- workflow = Workflow(
- id=f"workflow-{pipeline.id}",
+ workflow = make_workflow(
+ workflow_id=f"workflow-{pipeline.id}",
tenant_id=pipeline.tenant_id,
app_id=pipeline.id,
- type=WorkflowType.RAG_PIPELINE,
- kind=WorkflowKind.STANDARD,
- version=Workflow.VERSION_DRAFT,
- graph=json.dumps(graph or {"nodes": [], "edges": []}),
- features="{}",
- created_by="account-1",
- environment_variables=[],
- conversation_variables=[],
- rag_pipeline_variables=[],
+ workflow_type=WorkflowType.RAG_PIPELINE,
+ graph=graph,
)
pipeline.workflow_id = workflow.id
session.add(workflow)
@@ -124,13 +118,13 @@ def _dataset(
name: str = "Dataset",
chunk_structure: str = "text_model",
) -> Dataset:
- dataset = Dataset(
+ dataset = make_dataset(
+ dataset_id=None,
tenant_id=pipeline.tenant_id,
name=name,
description="description",
data_source_type=DataSourceType.UPLOAD_FILE,
indexing_technique="high_quality",
- created_by="account-1",
maintainer="account-1",
chunk_structure=chunk_structure,
pipeline_id=pipeline.id,
diff --git a/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline_transform_service.py b/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline_transform_service.py
index be5728f396e..43cfb85a828 100644
--- a/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline_transform_service.py
+++ b/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline_transform_service.py
@@ -7,14 +7,14 @@ from pytest_mock import MockerFixture
from sqlalchemy import select
from sqlalchemy.orm import Session
-from extensions.storage.storage_type import StorageType
from models.dataset import Dataset, Document, DocumentPipelineExecutionLog, Pipeline
-from models.enums import CreatorUserRole, DataSourceType, DocumentCreatedFrom
+from models.enums import DataSourceType, DocumentCreatedFrom
from models.model import UploadFile
from services.entities.knowledge_entities.rag_pipeline_entities import KnowledgeConfiguration
from services.errors.rag_pipeline import RagPipelineResourceNotFoundError
from services.rag_pipeline.rag_pipeline_transform_service import RagPipelineTransformService
from tests.unit_tests.config_override import apply_config_overrides
+from tests.unit_tests.model_factories import make_upload_file
def _dataset(**overrides: object) -> Dataset:
@@ -60,21 +60,14 @@ def _pipeline(*, pipeline_id: str = "p-new", tenant_id: str = "t1") -> Pipeline:
def _upload_file(*, file_id: str = "file-1", tenant_id: str = "tenant-1") -> UploadFile:
- upload_file = UploadFile(
+ return make_upload_file(
+ file_id=file_id,
tenant_id=tenant_id,
- storage_type=StorageType.LOCAL,
key="files/f.txt",
name="f.txt",
- size=10,
- extension="txt",
- mime_type="text/plain",
- created_by_role=CreatorUserRole.ACCOUNT,
created_by="user-1",
created_at=datetime.now(UTC).replace(tzinfo=None),
- used=False,
)
- upload_file.id = file_id
- return upload_file
@pytest.mark.parametrize(
diff --git a/api/tests/unit_tests/services/test_account_change_email_service.py b/api/tests/unit_tests/services/test_account_change_email_service.py
index 3fb3e8d6837..1556657038e 100644
--- a/api/tests/unit_tests/services/test_account_change_email_service.py
+++ b/api/tests/unit_tests/services/test_account_change_email_service.py
@@ -33,6 +33,7 @@ from services.entities.account_entities import (
AccountEmailResetStatus,
AccountSnapshot,
)
+from tests.unit_tests.model_factories import make_account_snapshot
def _context() -> RequestContext:
@@ -45,21 +46,7 @@ def _context() -> RequestContext:
def _account(*, email: str = "[email protected]") -> AccountSnapshot:
- return AccountSnapshot(
- id="account-1",
- name="Account",
- email=email,
- avatar=None,
- is_password_set=True,
- interface_language="en-US",
- interface_theme="light",
- timezone="UTC",
- last_login_at=None,
- last_login_ip=None,
- status="active",
- initialized_at=datetime(2026, 1, 1),
- created_at=datetime(2026, 1, 1),
- )
+ return make_account_snapshot(email=email, is_password_set=True, initialized_at=datetime(2026, 1, 1))
def _service() -> tuple[AccountChangeEmailService, dict[str, Mock]]:
diff --git a/api/tests/unit_tests/services/test_account_deletion_service.py b/api/tests/unit_tests/services/test_account_deletion_service.py
index 0ba68d9d5f8..7d0f0e05ca6 100644
--- a/api/tests/unit_tests/services/test_account_deletion_service.py
+++ b/api/tests/unit_tests/services/test_account_deletion_service.py
@@ -17,6 +17,7 @@ from services.account_ports import (
AccountWorkspaceMembershipQuery,
)
from services.entities.account_entities import AccountDeletionChallenge, AccountSnapshot
+from tests.unit_tests.model_factories import make_account_snapshot
def _context() -> RequestContext:
@@ -29,21 +30,7 @@ def _context() -> RequestContext:
def _account() -> AccountSnapshot:
- return AccountSnapshot(
- id="account-1",
- name="Account",
- avatar=None,
- is_password_set=True,
- interface_language="en-US",
- interface_theme="light",
- timezone="UTC",
- last_login_at=None,
- last_login_ip=None,
- status="active",
- initialized_at=datetime(2026, 1, 1),
- created_at=datetime(2026, 1, 1),
- )
+ return make_account_snapshot(is_password_set=True, initialized_at=datetime(2026, 1, 1))
def _service(*, accounts: Mock | None = None) -> tuple[AccountDeletionService, dict[str, Mock]]:
diff --git a/api/tests/unit_tests/services/test_account_education_service.py b/api/tests/unit_tests/services/test_account_education_service.py
index 5f413eeee62..96194f44e31 100644
--- a/api/tests/unit_tests/services/test_account_education_service.py
+++ b/api/tests/unit_tests/services/test_account_education_service.py
@@ -20,6 +20,7 @@ from services.entities.account_entities import (
AccountEducationVerification,
AccountSnapshot,
)
+from tests.unit_tests.model_factories import make_account_snapshot
def _context() -> RequestContext:
@@ -32,20 +33,11 @@ def _context() -> RequestContext:
def _account() -> AccountSnapshot:
- return AccountSnapshot(
- id="account-1",
+ return make_account_snapshot(
name="Student",
- avatar=None,
is_password_set=True,
- interface_language="en-US",
- interface_theme="light",
- timezone="UTC",
- last_login_at=None,
- last_login_ip=None,
- status="active",
initialized_at=datetime(2026, 1, 1),
- created_at=datetime(2026, 1, 1),
)
diff --git a/api/tests/unit_tests/services/test_account_email_registration_service.py b/api/tests/unit_tests/services/test_account_email_registration_service.py
index b3091f51438..513b727e581 100644
--- a/api/tests/unit_tests/services/test_account_email_registration_service.py
+++ b/api/tests/unit_tests/services/test_account_email_registration_service.py
@@ -29,23 +29,15 @@ from services.entities.account_entities import (
AccountSessionTokens,
AccountSnapshot,
)
+from tests.unit_tests.model_factories import make_account_snapshot
def _account(*, email: str = "[email protected]") -> AccountSnapshot:
- return AccountSnapshot(
- id="account-1",
+ return make_account_snapshot(
name="Stored Account",
email=email,
- avatar=None,
is_password_set=True,
- interface_language="en-US",
- interface_theme="light",
- timezone="UTC",
- last_login_at=None,
- last_login_ip=None,
- status="active",
initialized_at=datetime(2026, 1, 1),
- created_at=datetime(2026, 1, 1),
)
diff --git a/api/tests/unit_tests/services/test_account_initialization_service.py b/api/tests/unit_tests/services/test_account_initialization_service.py
index e929e1ff11d..212fc61d149 100644
--- a/api/tests/unit_tests/services/test_account_initialization_service.py
+++ b/api/tests/unit_tests/services/test_account_initialization_service.py
@@ -19,6 +19,7 @@ from services.entities.account_entities import (
AccountInitializationStatus,
AccountSnapshot,
)
+from tests.unit_tests.model_factories import make_account_snapshot
def _context() -> RequestContext:
@@ -31,21 +32,7 @@ def _context() -> RequestContext:
def _account(*, status: str = "uninitialized") -> AccountSnapshot:
- return AccountSnapshot(
- id="account-1",
- name="Account",
- avatar=None,
- is_password_set=False,
- interface_language="en-US",
- interface_theme="light",
- timezone="UTC",
- last_login_at=None,
- last_login_ip=None,
- status=status,
- initialized_at=None,
- created_at=datetime(2026, 1, 1),
- )
+ return make_account_snapshot(status=status)
def test_cloud_initialization_consumes_invitation_and_updates_account_atomically() -> None:
diff --git a/api/tests/unit_tests/services/test_account_password_service.py b/api/tests/unit_tests/services/test_account_password_service.py
index d4b9f7c2050..19ccad4125e 100644
--- a/api/tests/unit_tests/services/test_account_password_service.py
+++ b/api/tests/unit_tests/services/test_account_password_service.py
@@ -1,6 +1,5 @@
from __future__ import annotations
-from datetime import datetime
from unittest.mock import Mock
import pytest
@@ -10,6 +9,7 @@ from services.account_errors import AccountNotFoundError, CurrentAccountPassword
from services.account_password_service import AccountPasswordService
from services.account_ports import AccountPasswordHasher, AccountRepository
from services.entities.account_entities import AccountCredentials, AccountPasswordDigest, AccountSnapshot
+from tests.unit_tests.model_factories import make_account_snapshot
def _context() -> RequestContext:
@@ -22,21 +22,7 @@ def _context() -> RequestContext:
def _account() -> AccountSnapshot:
- return AccountSnapshot(
- id="account-1",
- name="Account",
- avatar=None,
- is_password_set=True,
- interface_language="en-US",
- interface_theme="light",
- timezone="UTC",
- last_login_at=None,
- last_login_ip=None,
- status="active",
- initialized_at=None,
- created_at=datetime(2026, 1, 1),
- )
+ return make_account_snapshot(is_password_set=True)
def test_change_verifies_current_password_and_updates_digest() -> None:
diff --git a/api/tests/unit_tests/services/test_account_profile_service.py b/api/tests/unit_tests/services/test_account_profile_service.py
index 018cd45fc59..76837a88a3c 100644
--- a/api/tests/unit_tests/services/test_account_profile_service.py
+++ b/api/tests/unit_tests/services/test_account_profile_service.py
@@ -1,6 +1,5 @@
from __future__ import annotations
-from datetime import datetime
from unittest.mock import Mock
import pytest
@@ -10,6 +9,7 @@ from services.account_errors import AccountNotFoundError
from services.account_ports import AccountRepository
from services.account_profile_service import AccountProfileService
from services.entities.account_entities import AccountProfileChanges, AccountSnapshot
+from tests.unit_tests.model_factories import make_account_snapshot
def _context() -> RequestContext:
@@ -22,21 +22,7 @@ def _context() -> RequestContext:
def _account() -> AccountSnapshot:
- return AccountSnapshot(
- id="account-1",
- name="Account",
- avatar=None,
- is_password_set=False,
- interface_language="en-US",
- interface_theme="light",
- timezone="UTC",
- last_login_at=None,
- last_login_ip=None,
- status="active",
- initialized_at=None,
- created_at=datetime(2026, 1, 1),
- )
+ return make_account_snapshot()
def test_get_returns_framework_neutral_account_snapshot() -> None:
diff --git a/api/tests/unit_tests/services/test_account_service.py b/api/tests/unit_tests/services/test_account_service.py
index 9bd00353a90..83e83929725 100644
--- a/api/tests/unit_tests/services/test_account_service.py
+++ b/api/tests/unit_tests/services/test_account_service.py
@@ -37,6 +37,7 @@ from services.errors.account import (
NoPermissionError,
)
from tests.unit_tests.config_override import config_overrides_context
+from tests.unit_tests.model_factories import make_tenant
type _MockDependencies = dict[str, MagicMock]
@@ -75,7 +76,7 @@ class TestAccountAssociatedDataFactory:
def _tenant(session: Session | None = None) -> Tenant:
- tenant = Tenant(name="Test Workspace")
+ tenant = make_tenant(tenant_id=None, name="Test Workspace")
if session is not None:
session.add(tenant)
return tenant
diff --git a/api/tests/unit_tests/services/test_app_dsl_service.py b/api/tests/unit_tests/services/test_app_dsl_service.py
index b7d84895d04..e4c1554f62c 100644
--- a/api/tests/unit_tests/services/test_app_dsl_service.py
+++ b/api/tests/unit_tests/services/test_app_dsl_service.py
@@ -1,4 +1,3 @@
-import json
from collections.abc import Callable
from types import SimpleNamespace
from typing import cast
@@ -12,9 +11,9 @@ from sqlalchemy.orm import Session, sessionmaker
from constants.dsl_version import CURRENT_APP_DSL_VERSION
from core.rbac import RBACPermission, RBACResourceScope
from core.workflow.llm_environment_variable import LLMEnvironmentVariable
-from models import Account, App, AppMode, Tenant
+from models import Account, App, AppMode
from models.model import AppModelConfig, AppModelConfigDict, IconType
-from models.workflow import Workflow, WorkflowType
+from models.workflow import Workflow
from services.agent.dsl_entities import AgentPackage
from services.app_dsl_service import AppDslService, Import, PendingData
from services.enterprise.enterprise_service import EnterpriseService
@@ -23,6 +22,7 @@ from services.errors.account import NoPermissionError
from services.errors.app import WorkflowNotFoundError
from services.system_feature_service import SystemFeatureService
from tests.unit_tests.config_override import apply_config_overrides
+from tests.unit_tests.model_factories import make_account, make_app, make_tenant, make_workflow
_OVERWRITE_APP_ID = "11111111-1111-4111-8111-111111111111"
_TENANT_ID = "22222222-2222-4222-8222-222222222222"
@@ -60,12 +60,12 @@ def _persist_overwrite_target(session: Session, *, maintainer: str = _OTHER_ACCO
def _account(*, account_id: str = "account-1", tenant_id: str = "tenant-1") -> Account:
- account = Account(name="DSL author", email=f"{account_id}@example.com")
- account.id = account_id
- tenant = Tenant(name="DSL workspace")
- tenant.id = tenant_id
- account._current_tenant = tenant
- return account
+ return make_account(
+ account_id=account_id,
+ name="DSL author",
+ email=f"{account_id}@example.com",
+ tenant=make_tenant(tenant_id=tenant_id, name="DSL workspace"),
+ )
def _app(
@@ -75,38 +75,20 @@ def _app(
mode: AppMode = AppMode.CHAT,
app_model_config_id: str | None = None,
) -> App:
- return App(
- id=app_id,
+ return make_app(
+ app_id=app_id,
tenant_id=tenant_id,
app_model_config_id=app_model_config_id,
name="Existing app",
- description="",
mode=mode,
- icon_type=IconType.EMOJI,
- icon="robot",
- icon_background="#FFFFFF",
- enable_site=True,
- enable_api=True,
max_active_requests=0,
- use_icon_as_answer_icon=False,
)
def _workflow(
*, graph: dict[str, object], environment_variables: list[LLMEnvironmentVariable] | None = None
) -> Workflow:
- workflow = Workflow(
- id="workflow-1",
- tenant_id="tenant-1",
- app_id="app-1",
- type=WorkflowType.WORKFLOW,
- version="draft",
- graph=json.dumps(graph),
- _features="{}",
- created_by="account-1",
- )
- workflow.environment_variables = environment_variables or []
- return workflow
+ return make_workflow(workflow_id="workflow-1", graph=graph, environment_variables=environment_variables or [])
@pytest.mark.parametrize("status", [ImportStatus.FAILED, ImportStatus.PENDING])
diff --git a/api/tests/unit_tests/services/test_audio_service.py b/api/tests/unit_tests/services/test_audio_service.py
index 82568916445..88c4fe20964 100644
--- a/api/tests/unit_tests/services/test_audio_service.py
+++ b/api/tests/unit_tests/services/test_audio_service.py
@@ -81,6 +81,7 @@ from services.errors.audio import (
SpeechToTextDisabledServiceError,
UnsupportedAudioTypeServiceError,
)
+from tests.unit_tests.model_factories import make_message
APP_ID = "11111111-1111-1111-1111-111111111111"
TENANT_ID = "22222222-2222-2222-2222-222222222222"
@@ -92,10 +93,11 @@ OTHER_ID = "77777777-7777-7777-7777-777777777777"
def _message(*, answer: str = "Message answer") -> Message:
- message = Message(
- id=MESSAGE_ID,
+ return make_message(
+ message_id=MESSAGE_ID,
app_id=APP_ID,
conversation_id=CONVERSATION_ID,
+ inputs={},
query="Question",
message={"role": "user", "content": "Question"},
answer=answer,
@@ -107,8 +109,6 @@ def _message(*, answer: str = "Message answer") -> Message:
from_end_user_id=END_USER_ID,
from_account_id=ACCOUNT_ID,
)
- message._inputs = {}
- return message
class AudioServiceTestDataFactory:
diff --git a/api/tests/unit_tests/services/test_billing_portal_service.py b/api/tests/unit_tests/services/test_billing_portal_service.py
index 676d0686629..9af98ed8368 100644
--- a/api/tests/unit_tests/services/test_billing_portal_service.py
+++ b/api/tests/unit_tests/services/test_billing_portal_service.py
@@ -1,4 +1,3 @@
-from datetime import datetime
from unittest.mock import MagicMock, Mock
import pytest
@@ -8,6 +7,7 @@ from services.account_errors import AccountNotFoundError
from services.account_ports import AccountRepository
from services.billing_portal_service import BillingPortalService
from services.entities.account_entities import AccountSnapshot
+from tests.unit_tests.model_factories import make_account_snapshot
def _context() -> RequestContext:
@@ -20,21 +20,7 @@ def _context() -> RequestContext:
def _account() -> AccountSnapshot:
- return AccountSnapshot(
- id="account-1",
- name="Account",
- avatar=None,
- is_password_set=False,
- interface_language="en-US",
- interface_theme="light",
- timezone="UTC",
- last_login_at=None,
- last_login_ip=None,
- status="active",
- initialized_at=None,
- created_at=datetime(2026, 1, 1),
- )
+ return make_account_snapshot(email="[email protected]")
@pytest.fixture
diff --git a/api/tests/unit_tests/services/test_billing_service.py b/api/tests/unit_tests/services/test_billing_service.py
index 0e10220635b..f2acba94932 100644
--- a/api/tests/unit_tests/services/test_billing_service.py
+++ b/api/tests/unit_tests/services/test_billing_service.py
@@ -22,7 +22,6 @@ import pytest
from werkzeug.exceptions import InternalServerError
from enums import CloudPlan
-from models import Account, Tenant
from services.billing_service import BillingService, _BillingHTTPStatusError
from services.errors.billing import (
BillingUpstreamInvalidResponseError,
@@ -33,15 +32,6 @@ TENANT_ID = "11111111-1111-1111-1111-111111111111"
ACCOUNT_ID = "33333333-3333-3333-3333-333333333333"
-def _account(*, account_id: str = ACCOUNT_ID, email: str = "[email protected]", tenant_id: str = TENANT_ID) -> Account:
- tenant = Tenant(name="Test Tenant")
- tenant.id = tenant_id
- account = Account(name="Test User", email=email)
- account.id = account_id
- account._current_tenant = tenant
- return account
-
-
class TestBillingServiceSendRequest:
"""Unit tests for BillingService._send_request method.
diff --git a/api/tests/unit_tests/services/test_dataset_service_dataset.py b/api/tests/unit_tests/services/test_dataset_service_dataset.py
index f20946f4e91..18a833afb55 100644
--- a/api/tests/unit_tests/services/test_dataset_service_dataset.py
+++ b/api/tests/unit_tests/services/test_dataset_service_dataset.py
@@ -19,7 +19,6 @@ from core.errors.error import LLMBadRequestError, ProviderTokenNotInitError
from core.rag.index_processor.constant.index_type import IndexTechniqueType
from graphon.model_runtime.entities.model_entities import ModelFeature, ModelType
from models import Account
-from models.account import Tenant
from models.dataset import (
Dataset,
DatasetCollectionBinding,
@@ -36,6 +35,7 @@ from services.entities.knowledge_entities.rag_pipeline_entities import (
)
from services.errors.account import NoPermissionError
from services.errors.dataset import DatasetNameDuplicateError
+from tests.unit_tests.model_factories import make_account, make_dataset, make_tenant
from .dataset_service_test_helpers import (
MagicMock,
@@ -51,13 +51,13 @@ def _account(
tenant_id: str = "tenant-1",
role: TenantAccountRole = TenantAccountRole.OWNER,
) -> Account:
- account = Account(name=f"User {account_id}", email=f"{account_id}@example.com")
- account.id = account_id
- account.role = role
- tenant = Tenant(name=f"Tenant {tenant_id}")
- tenant.id = tenant_id
- account._current_tenant = tenant
- return account
+ return make_account(
+ account_id=account_id,
+ name=f"User {account_id}",
+ email=f"{account_id}@example.com",
+ role=role,
+ tenant=make_tenant(tenant_id=tenant_id, name=f"Tenant {tenant_id}"),
+ )
def _dataset(
@@ -71,8 +71,8 @@ def _dataset(
indexing_technique: str = IndexTechniqueType.ECONOMY,
chunk_structure: str | None = "text_model",
) -> Dataset:
- return Dataset(
- id=dataset_id,
+ return make_dataset(
+ dataset_id=dataset_id,
tenant_id=tenant_id,
name=name,
description="",
diff --git a/api/tests/unit_tests/services/test_dataset_service_document.py b/api/tests/unit_tests/services/test_dataset_service_document.py
index c70468e5f65..a450560d231 100644
--- a/api/tests/unit_tests/services/test_dataset_service_document.py
+++ b/api/tests/unit_tests/services/test_dataset_service_document.py
@@ -7,13 +7,13 @@ from sqlalchemy import event, select
from sqlalchemy.orm import Session
from enums import DeploymentEdition
-from models.account import Tenant
from models.dataset import Dataset, DatasetCollectionBinding, DocumentSegment
from models.enums import DataSourceType, DocumentCreatedFrom, IndexingStatus
from models.model import UploadFile
from models.source import DataSourceOauthBinding
from services.dataset_ref_service import DatasetRefService
from tests.unit_tests.config_override import config_overrides_context
+from tests.unit_tests.model_factories import make_account, make_tenant, make_upload_file
from .dataset_service_test_helpers import (
Account,
@@ -53,12 +53,12 @@ from .dataset_service_test_helpers import (
def _account(*, account_id: str = "user-1", tenant_id: str = "tenant-1") -> Account:
- account = Account(name="User", email=f"{account_id}@example.com")
- account.id = account_id
- tenant = Tenant(name="Tenant")
- tenant.id = tenant_id
- account._current_tenant = tenant
- return account
+ return make_account(
+ account_id=account_id,
+ name="User",
+ email=f"{account_id}@example.com",
+ tenant=make_tenant(tenant_id=tenant_id, name="Tenant"),
+ )
def _dataset_row(
@@ -121,21 +121,16 @@ def _document_row(
def _upload_file(*, file_id: str, tenant_id: str = "tenant-1", name: str = "upload.txt") -> UploadFile:
- upload_file = UploadFile(
+ return make_upload_file(
+ file_id=file_id,
tenant_id=tenant_id,
storage_type="opendal",
key=f"key-{file_id}",
name=name,
size=1,
- extension="txt",
- mime_type="text/plain",
- created_by_role="account",
created_by="user-1",
created_at=datetime(2026, 1, 1),
- used=False,
)
- upload_file.id = file_id
- return upload_file
def _process_rule(
diff --git a/api/tests/unit_tests/services/test_file_service.py b/api/tests/unit_tests/services/test_file_service.py
index a807bc6aa41..22106b85cc1 100644
--- a/api/tests/unit_tests/services/test_file_service.py
+++ b/api/tests/unit_tests/services/test_file_service.py
@@ -22,12 +22,11 @@ from services.errors.file import (
UnsupportedFileTypeError,
)
from services.file_service import FileService
+from tests.unit_tests.model_factories import make_account
def _account() -> Account:
- account = Account(name="Test Account", email="[email protected]")
- account.id = "user_id"
- return account
+ return make_account(account_id="user_id", name="Test Account", email="[email protected]")
class TestFileService:
diff --git a/api/tests/unit_tests/services/test_knowledge_fs_proxy.py b/api/tests/unit_tests/services/test_knowledge_fs_proxy.py
index 51cd56b7bfd..1f7f2d6a2a0 100644
--- a/api/tests/unit_tests/services/test_knowledge_fs_proxy.py
+++ b/api/tests/unit_tests/services/test_knowledge_fs_proxy.py
@@ -31,15 +31,13 @@ from services.knowledge_fs_proxy import (
from services.knowledge_fs_proxy import (
_forward_knowledge_fs_request as forward_knowledge_fs_request,
)
+from tests.unit_tests.model_factories import make_account
_JWT_SECRET = "production-secret-with-at-least-32-bytes"
def _account(*, role: TenantAccountRole = TenantAccountRole.DATASET_OPERATOR) -> Account:
- account = Account(name="Knowledge User", email="[email protected]")
- account.id = "account-1"
- account.role = role
- return account
+ return make_account(name="Knowledge User", email="[email protected]", role=role)
def _account_for_legacy_role(role: str) -> Account:
diff --git a/api/tests/unit_tests/services/test_knowledge_retrieval_inner_service.py b/api/tests/unit_tests/services/test_knowledge_retrieval_inner_service.py
index 4a5511396d7..66a289d24fa 100644
--- a/api/tests/unit_tests/services/test_knowledge_retrieval_inner_service.py
+++ b/api/tests/unit_tests/services/test_knowledge_retrieval_inner_service.py
@@ -7,7 +7,6 @@ from sqlalchemy.orm import Session
from core.workflow.nodes.knowledge_retrieval.retrieval import Source, SourceMetadata
from models.dataset import Dataset
-from models.enums import AppStatus
from models.model import App, AppMode
from services.entities.knowledge_retrieval_inner import InnerKnowledgeRetrieveRequest
from services.errors.knowledge_retrieval import (
@@ -17,6 +16,7 @@ from services.errors.knowledge_retrieval import (
InnerKnowledgeRetrieveDatasetTenantMismatchError,
)
from services.knowledge_retrieval_inner_service import InnerKnowledgeRetrievalService
+from tests.unit_tests.model_factories import make_app, make_dataset
TENANT_ID = "11111111-1111-1111-1111-111111111111"
OTHER_TENANT_ID = "22222222-2222-2222-2222-222222222222"
@@ -27,22 +27,19 @@ DATASET_2_ID = "66666666-6666-6666-6666-666666666666"
def _app(*, tenant_id: str = TENANT_ID) -> App:
- return App(
- id=APP_ID,
+ return make_app(
+ app_id=APP_ID,
tenant_id=tenant_id,
- name="Test App",
- description="",
mode=AppMode.WORKFLOW,
- status=AppStatus.NORMAL,
+ icon_type=None,
enable_site=False,
enable_api=False,
- max_active_requests=None,
)
def _dataset(*, dataset_id: str, tenant_id: str = TENANT_ID, enable_api: bool = True) -> Dataset:
- return Dataset(
- id=dataset_id,
+ return make_dataset(
+ dataset_id=dataset_id,
tenant_id=tenant_id,
name=f"Dataset {dataset_id[-1]}",
description="",
diff --git a/api/tests/unit_tests/services/test_metadata_service_session_boundary.py b/api/tests/unit_tests/services/test_metadata_service_session_boundary.py
index 3414a1b0d10..eea773da175 100644
--- a/api/tests/unit_tests/services/test_metadata_service_session_boundary.py
+++ b/api/tests/unit_tests/services/test_metadata_service_session_boundary.py
@@ -8,7 +8,7 @@ from sqlalchemy.orm import Session, sessionmaker
from core.rag.index_processor.constant.built_in_field import BuiltInField
from models import Account
from models.dataset import Dataset, DatasetMetadata, DatasetMetadataBinding, Document
-from models.enums import DataSourceType, DocumentCreatedFrom
+from models.enums import DocumentCreatedFrom
from services.dataset_service import DocumentService
from services.entities.knowledge_entities.knowledge_entities import (
DocumentMetadataOperation,
@@ -18,6 +18,7 @@ from services.entities.knowledge_entities.knowledge_entities import (
)
from services.errors.metadata import MetadataResourceNotFoundError
from services.metadata_service import MetadataService
+from tests.unit_tests.model_factories import make_account, make_dataset, make_document
DOCUMENT_ID = "11111111-1111-1111-1111-111111111111"
FOREIGN_DOCUMENT_ID = "22222222-2222-2222-2222-222222222222"
@@ -26,9 +27,7 @@ FOREIGN_METADATA_ID = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"
def _account() -> Account:
- account = Account(name="User", email="[email protected]")
- account.id = "account-1"
- return account
+ return make_account(name="User", email="[email protected]")
def test_create_metadata_flushes_without_committing_caller_session(sqlite_session: Session) -> None:
@@ -50,28 +49,17 @@ def test_create_metadata_flushes_without_committing_caller_session(sqlite_sessio
def _dataset(*, built_in_field_enabled: bool) -> Dataset:
- return Dataset(
- id="dataset-1",
- tenant_id="tenant-1",
- name="Dataset",
+ return make_dataset(
description="",
provider="vendor",
- created_by="account-1",
built_in_field_enabled=built_in_field_enabled,
)
def _document() -> Document:
- return Document(
- id=DOCUMENT_ID,
- tenant_id="tenant-1",
- dataset_id="dataset-1",
- position=1,
- data_source_type=DataSourceType.UPLOAD_FILE,
- batch="batch-1",
- name="Document",
+ return make_document(
+ document_id=DOCUMENT_ID,
created_from=DocumentCreatedFrom.API,
- created_by="account-1",
created_at=datetime(2026, 1, 1),
updated_at=datetime(2026, 1, 2),
doc_metadata={},
diff --git a/api/tests/unit_tests/services/test_schedule_service.py b/api/tests/unit_tests/services/test_schedule_service.py
index 4f5df2f8c8a..40f1801c561 100644
--- a/api/tests/unit_tests/services/test_schedule_service.py
+++ b/api/tests/unit_tests/services/test_schedule_service.py
@@ -10,8 +10,9 @@ from core.trigger.constants import TRIGGER_SCHEDULE_NODE_TYPE
from core.workflow.nodes.trigger_schedule.entities import VisualConfig
from core.workflow.nodes.trigger_schedule.exc import ScheduleConfigError
from libs.schedule_utils import calculate_next_run_at, convert_12h_to_24h
-from models.workflow import Workflow, WorkflowType
+from models.workflow import Workflow
from services.trigger.schedule_service import ScheduleService
+from tests.unit_tests.model_factories import make_workflow
class TestScheduleService(unittest.TestCase):
@@ -507,18 +508,7 @@ class TestScheduleWithTimezone(unittest.TestCase):
def _workflow(*, graph_dict: dict[str, Any]) -> Workflow:
- return Workflow.new(
- tenant_id="tenant-1",
- app_id="app-1",
- type=WorkflowType.WORKFLOW,
- version="draft",
- graph=json.dumps(graph_dict),
- features="{}",
- created_by="account-1",
- environment_variables=[],
- conversation_variables=[],
- rag_pipeline_variables=[],
- )
+ return make_workflow(graph=graph_dict)
def test_to_schedule_config_should_build_from_cron_mode() -> None:
diff --git a/api/tests/unit_tests/services/test_snippet_dsl_service.py b/api/tests/unit_tests/services/test_snippet_dsl_service.py
index 900f321c43b..bd06fe98613 100644
--- a/api/tests/unit_tests/services/test_snippet_dsl_service.py
+++ b/api/tests/unit_tests/services/test_snippet_dsl_service.py
@@ -8,9 +8,9 @@ from sqlalchemy import event
from sqlalchemy.orm import Session
from graphon.nodes import BuiltinNodeTypes
-from models import Account, Tenant
+from models import Account
from models.snippet import CustomizedSnippet, SnippetType
-from models.workflow import Workflow, WorkflowType
+from models.workflow import Workflow
from services.snippet_dsl_service import (
ImportMode,
ImportStatus,
@@ -18,6 +18,7 @@ from services.snippet_dsl_service import (
SnippetPendingData,
_check_version_compatibility,
)
+from tests.unit_tests.model_factories import make_account, make_tenant, make_workflow
SQLITE_MODELS = (CustomizedSnippet,)
pytestmark = [
@@ -33,12 +34,12 @@ def service(sqlite_session: Session) -> SnippetDslService:
def _account(*, account_id: str = "account-1", tenant_id: str = "tenant-1") -> Account:
- account = Account(name="Snippet author", email=f"{account_id}@example.com")
- account.id = account_id
- tenant = Tenant(name="Snippet workspace")
- tenant.id = tenant_id
- account._current_tenant = tenant
- return account
+ return make_account(
+ account_id=account_id,
+ name="Snippet author",
+ email=f"{account_id}@example.com",
+ tenant=make_tenant(tenant_id=tenant_id, name="Snippet workspace"),
+ )
def _snippet(
@@ -64,16 +65,7 @@ def _snippet(
def _workflow(*, graph: dict | None = None) -> Workflow:
- return Workflow(
- id="workflow-1",
- tenant_id="tenant-1",
- app_id="snippet-1",
- type=WorkflowType.WORKFLOW,
- version="draft",
- graph=json.dumps(graph or {"nodes": [], "edges": []}),
- _features="{}",
- created_by="account-1",
- )
+ return make_workflow(workflow_id="workflow-1", app_id="snippet-1", graph=graph)
@pytest.mark.parametrize(
diff --git a/api/tests/unit_tests/services/test_snippet_generate_service.py b/api/tests/unit_tests/services/test_snippet_generate_service.py
index d1b3f428c7b..cc2a81ecdc4 100644
--- a/api/tests/unit_tests/services/test_snippet_generate_service.py
+++ b/api/tests/unit_tests/services/test_snippet_generate_service.py
@@ -8,25 +8,13 @@ from sqlalchemy.orm import Session, sessionmaker
from core.workflow.snippet_start import SNIPPET_VIRTUAL_START_NODE_ID
from models.account import Account
from models.snippet import CustomizedSnippet, SnippetType
-from models.workflow import Workflow, WorkflowKind, WorkflowNodeExecutionModel, WorkflowType
+from models.workflow import Workflow, WorkflowKind, WorkflowNodeExecutionModel
from services.snippet_generate_service import SnippetGenerateService
+from tests.unit_tests.model_factories import make_account, make_workflow
def _workflow(graph: dict) -> Workflow:
- return Workflow(
- id="workflow-1",
- tenant_id="tenant-1",
- app_id="snippet-1",
- type=WorkflowType.WORKFLOW,
- kind=WorkflowKind.SNIPPET,
- version=Workflow.VERSION_DRAFT,
- graph=json.dumps(graph),
- features="{}",
- created_by="account-1",
- environment_variables=[],
- conversation_variables=[],
- rag_pipeline_variables=[],
- )
+ return make_workflow(workflow_id="workflow-1", app_id="snippet-1", kind=WorkflowKind.SNIPPET, graph=graph)
def _snippet(*, input_fields: list[dict] | None = None) -> CustomizedSnippet:
@@ -42,9 +30,7 @@ def _snippet(*, input_fields: list[dict] | None = None) -> CustomizedSnippet:
def _account(account_id: str = "user-1") -> Account:
- account = Account(name="Test User", email=f"{account_id}@example.com")
- account.id = account_id
- return account
+ return make_account(account_id=account_id, name="Test User", email=f"{account_id}@example.com")
def test_filter_virtual_start_events_keeps_blocking_response_unchanged():
diff --git a/api/tests/unit_tests/services/test_snippet_service.py b/api/tests/unit_tests/services/test_snippet_service.py
index ea2d83c810a..843c1857a81 100644
--- a/api/tests/unit_tests/services/test_snippet_service.py
+++ b/api/tests/unit_tests/services/test_snippet_service.py
@@ -37,6 +37,7 @@ from models.workflow import (
from services.errors.app import IsDraftWorkflowError, WorkflowHashNotEqualError, WorkflowNotFoundError
from services.errors.workflow_service import DraftWorkflowDeletionError, WorkflowInUseError
from services.snippet_service import SnippetService
+from tests.unit_tests.model_factories import make_account
def _create_workflow(*, workflow_id: str, version: str, graph: dict, features: dict) -> Workflow:
@@ -70,9 +71,7 @@ def _snippet(**overrides) -> CustomizedSnippet:
def _account(account_id: str = "account-1") -> Account:
- account = Account(name="Test User", email=f"{account_id}@example.com")
- account.id = account_id
- return account
+ return make_account(account_id=account_id, name="Test User", email=f"{account_id}@example.com")
def test_create_snippet_allows_duplicate_names(
diff --git a/api/tests/unit_tests/services/test_step_by_step_tour_service.py b/api/tests/unit_tests/services/test_step_by_step_tour_service.py
index 1290987ffce..25413aa3449 100644
--- a/api/tests/unit_tests/services/test_step_by_step_tour_service.py
+++ b/api/tests/unit_tests/services/test_step_by_step_tour_service.py
@@ -12,6 +12,7 @@ from services.account_ports import AccountRepository
from services.entities.account_entities import AccountSnapshot
from services.entities.onboarding_entities import StepByStepTourPatch, StepByStepTourResult, StepByStepTourState
from services.step_by_step_tour_service import StepByStepTourService
+from tests.unit_tests.model_factories import make_account_snapshot
def _context(*, workspace_id: str = "workspace-1") -> RequestContext:
@@ -55,21 +56,7 @@ class StateRepositoryStub:
def _account(*, started_at: datetime = datetime(2026, 6, 28)) -> AccountSnapshot:
- return AccountSnapshot(
- id="account-1",
- name="Account",
- avatar=None,
- is_password_set=False,
- interface_language="en-US",
- interface_theme="light",
- timezone="UTC",
- last_login_at=None,
- last_login_ip=None,
- status="active",
- initialized_at=started_at,
- created_at=started_at,
- )
+ return make_account_snapshot(initialized_at=started_at, created_at=started_at)
def _accounts(account: AccountSnapshot | None) -> Mock:
diff --git a/api/tests/unit_tests/services/test_vector_service.py b/api/tests/unit_tests/services/test_vector_service.py
index 50b0d2c58c4..a8914f41f1c 100644
--- a/api/tests/unit_tests/services/test_vector_service.py
+++ b/api/tests/unit_tests/services/test_vector_service.py
@@ -14,12 +14,12 @@ from sqlalchemy.orm import Session
import services.vector_service as vector_service_module
from core.rag.index_processor.constant.index_type import IndexStructureType, IndexTechniqueType
-from extensions.storage.storage_type import StorageType
from models import UploadFile
from models.dataset import ChildChunk, Dataset, DatasetProcessRule, DocumentSegment, SegmentAttachmentBinding
from models.dataset import Document as DatasetDocument
-from models.enums import CreatorUserRole, DataSourceType, DocumentCreatedFrom, ProcessRuleMode
+from models.enums import DataSourceType, DocumentCreatedFrom, ProcessRuleMode
from services.vector_service import VectorService
+from tests.unit_tests.model_factories import make_upload_file
@dataclass(frozen=True)
@@ -107,21 +107,15 @@ def _make_segment(
def _upload_file(*, file_id: str = "file-1", name: str = "img.png", tenant_id: str = "tenant-1") -> UploadFile:
- upload_file = UploadFile(
+ return make_upload_file(
+ file_id=file_id,
tenant_id=tenant_id,
- storage_type=StorageType.LOCAL,
key=f"uploads/{file_id}",
name=name,
- size=10,
extension="png",
mime_type="image/png",
- created_by_role=CreatorUserRole.ACCOUNT,
- created_by="account-1",
created_at=datetime(2026, 1, 1),
- used=False,
)
- upload_file.id = file_id
- return upload_file
def _make_child_chunk(
diff --git a/api/tests/unit_tests/services/test_vector_space_admission_service.py b/api/tests/unit_tests/services/test_vector_space_admission_service.py
index 267d35f7757..db66f40ec66 100644
--- a/api/tests/unit_tests/services/test_vector_space_admission_service.py
+++ b/api/tests/unit_tests/services/test_vector_space_admission_service.py
@@ -26,6 +26,7 @@ from services.vector_space_admission_service import (
get_vector_space_admission_error_fields,
parse_vector_space_estimate_limits,
)
+from tests.unit_tests.model_factories import make_dataset
_MEBIBYTE = 1024 * 1024
_ESTIMATE_LIMITS = "sandbox:60,professional:6400,team:25600"
@@ -74,10 +75,8 @@ class _FakeRedis:
def _dataset(session: Session) -> Dataset:
- dataset = Dataset(
- id=str(uuid4()),
- tenant_id="tenant-1",
- name="Dataset",
+ dataset = make_dataset(
+ dataset_id=str(uuid4()),
created_by=str(uuid4()),
indexing_technique=IndexTechniqueType.HIGH_QUALITY,
embedding_model_provider="provider",
diff --git a/api/tests/unit_tests/services/test_webhook_service.py b/api/tests/unit_tests/services/test_webhook_service.py
index f52541d3506..301997252cf 100644
--- a/api/tests/unit_tests/services/test_webhook_service.py
+++ b/api/tests/unit_tests/services/test_webhook_service.py
@@ -10,7 +10,6 @@ from sqlalchemy.engine import Engine
from sqlalchemy.orm import Session
from werkzeug.datastructures import FileStorage
-from graphon.enums import WorkflowType
from models.enums import AppTriggerStatus, AppTriggerType, EndUserType
from models.model import App, AppMode, EndUser
from models.tools import ToolFile
@@ -19,6 +18,7 @@ from models.workflow import Workflow
from services.errors.app import QuotaExceededError
from services.trigger import webhook_service as webhook_service_module
from services.trigger.webhook_service import WebhookService
+from tests.unit_tests.model_factories import make_app, make_end_user, make_workflow
def _webhook_trigger(
@@ -59,31 +59,22 @@ def _workflow(
app_id: str = "app-123",
version: str = Workflow.VERSION_DRAFT,
) -> Workflow:
- workflow = Workflow.new(
+ return make_workflow(
+ workflow_id=workflow_id,
tenant_id=tenant_id,
app_id=app_id,
- type=WorkflowType.WORKFLOW.value,
version=version,
- graph='{"nodes": [], "edges": []}',
- features="{}",
created_by="account-123",
- environment_variables=[],
- conversation_variables=[],
- rag_pipeline_variables=[],
)
- workflow.id = workflow_id
- return workflow
def _app(*, tenant_id: str = "tenant-123", app_id: str = "app-123") -> App:
- return App(
- id=app_id,
+ return make_app(
+ app_id=app_id,
tenant_id=tenant_id,
name="Webhook App",
- description="",
mode=AppMode.WORKFLOW,
- enable_site=True,
- enable_api=True,
+ icon_type=None,
max_active_requests=0,
)
@@ -100,11 +91,11 @@ def _app_trigger(*, status: AppTriggerStatus = AppTriggerStatus.ENABLED) -> AppT
def _end_user() -> EndUser:
- return EndUser(
- id="end-user-123",
+ return make_end_user(
+ end_user_id="end-user-123",
tenant_id="tenant-123",
app_id="app-123",
- type=EndUserType.TRIGGER,
+ end_user_type=EndUserType.TRIGGER,
session_id="webhook-session",
)
diff --git a/api/tests/unit_tests/services/test_workflow_collaboration_service.py b/api/tests/unit_tests/services/test_workflow_collaboration_service.py
index 943677502f7..c1cbe203d63 100644
--- a/api/tests/unit_tests/services/test_workflow_collaboration_service.py
+++ b/api/tests/unit_tests/services/test_workflow_collaboration_service.py
@@ -11,10 +11,11 @@ from sqlalchemy.orm import Session
from core.rbac import RBACPermission, RBACResourceScope
from models.account import Account, Tenant
from models.base import TypeBase
-from models.model import App, AppMode, IconType
+from models.model import App, AppMode
from repositories.workflow_collaboration_repository import WorkflowCollaborationRepository
from services.workflow_collaboration_service import SYNC_REQUEST_TIMEOUT_SECONDS, WorkflowCollaborationService
from tests.unit_tests.config_override import config_overrides_context
+from tests.unit_tests.model_factories import make_app
@pytest.fixture
@@ -27,25 +28,15 @@ def db_session(sqlite_engine: Engine) -> Iterator[Session]:
def _app(*, app_id: str, tenant_id: str, maintainer: str | None = None) -> App:
- return App(
- id=app_id,
+ return make_app(
+ app_id=app_id,
tenant_id=tenant_id,
name="Workflow app",
- description="",
mode=AppMode.WORKFLOW,
- icon_type=IconType.EMOJI,
- icon="robot",
icon_background="#ffffff",
enable_site=False,
enable_api=False,
- api_rpm=0,
- api_rph=0,
- is_demo=False,
- is_public=False,
- is_universal=False,
- max_active_requests=None,
maintainer=maintainer,
- use_icon_as_answer_icon=False,
)
diff --git a/api/tests/unit_tests/services/test_workflow_comment_service.py b/api/tests/unit_tests/services/test_workflow_comment_service.py
index f850169d09d..31b428ac1ab 100644
--- a/api/tests/unit_tests/services/test_workflow_comment_service.py
+++ b/api/tests/unit_tests/services/test_workflow_comment_service.py
@@ -19,6 +19,7 @@ from models.account import Account, TenantAccountRole
from models.model import AppMode
from services import workflow_comment_service as service_module
from services.workflow_comment_service import WorkflowCommentService
+from tests.unit_tests.model_factories import make_account, make_app
TENANT_ID = "11111111-1111-1111-1111-111111111111"
OTHER_TENANT_ID = "11111111-1111-1111-1111-111111111112"
@@ -55,22 +56,20 @@ def _account(
email: str = "[email protected]",
interface_language: str | None = "en-US",
) -> Account:
- account = Account(name=name, email=email, interface_language=interface_language)
- account.id = account_id
- return account
+ return make_account(account_id=account_id, name=name, email=email, interface_language=interface_language)
def _app(*, app_id: str = APP_ID, tenant_id: str = TENANT_ID, name: str = "My App") -> App:
- app = App(
+ return make_app(
+ app_id=app_id,
tenant_id=tenant_id,
name=name,
mode=AppMode.WORKFLOW,
+ icon_type=None,
enable_site=False,
enable_api=False,
created_by=OWNER_ID,
)
- app.id = app_id
- return app
def _comment(
diff --git a/api/tests/unit_tests/services/workflow/test_workflow_human_input_delivery.py b/api/tests/unit_tests/services/workflow/test_workflow_human_input_delivery.py
index 62c4b456c63..1f75c576b78 100644
--- a/api/tests/unit_tests/services/workflow/test_workflow_human_input_delivery.py
+++ b/api/tests/unit_tests/services/workflow/test_workflow_human_input_delivery.py
@@ -17,11 +17,11 @@ from core.workflow.human_input_adapter import (
from core.workflow.nodes.human_input.entities import HumanInputNodeData
from graphon.enums import BuiltinNodeTypes
from models import Account
-from models.enums import AppStatus
from models.model import App, AppMode
from models.workflow import Workflow, WorkflowType
from services import workflow_service as workflow_service_module
from services.workflow_service import WorkflowService
+from tests.unit_tests.model_factories import make_account, make_app
TENANT_ID = "11111111-1111-1111-1111-111111111111"
APP_ID = "22222222-2222-2222-2222-222222222222"
@@ -35,23 +35,18 @@ def _make_service(sqlite_session: Session) -> WorkflowService:
def _app() -> App:
- return App(
- id=APP_ID,
+ return make_app(
+ app_id=APP_ID,
tenant_id=TENANT_ID,
- name="Test App",
- description="",
mode=AppMode.WORKFLOW,
- status=AppStatus.NORMAL,
+ icon_type=None,
enable_site=False,
enable_api=False,
- max_active_requests=None,
)
def _account() -> Account:
- account = Account(name="Test User", email="[email protected]")
- account.id = ACCOUNT_ID
- return account
+ return make_account(account_id=ACCOUNT_ID, name="Test User", email="[email protected]")
def _build_node_config(delivery_methods: list[EmailDeliveryMethod]) -> dict[str, object]:
diff --git a/api/tests/unit_tests/tasks/test_clean_document_task.py b/api/tests/unit_tests/tasks/test_clean_document_task.py
index 4aef0581933..259dfd6e6a1 100644
--- a/api/tests/unit_tests/tasks/test_clean_document_task.py
+++ b/api/tests/unit_tests/tasks/test_clean_document_task.py
@@ -20,9 +20,10 @@ from models.dataset import (
DocumentSegment,
SegmentAttachmentBinding,
)
-from models.enums import DataSourceType, DocumentCreatedFrom
+from models.enums import DataSourceType
from models.model import UploadFile
from tasks.clean_document_task import clean_document_task
+from tests.unit_tests.model_factories import make_document
SQLITE_MODELS = (
Dataset,
@@ -87,15 +88,11 @@ def mock_index_processor_factory():
def _document(*, document_id: str, dataset_id: str, tenant_id: str, created_by: str) -> Document:
- return Document(
- id=document_id,
+ return make_document(
+ document_id=document_id,
tenant_id=tenant_id,
dataset_id=dataset_id,
- position=1,
- data_source_type=DataSourceType.UPLOAD_FILE,
- batch="batch-1",
name=f"{document_id}.txt",
- created_from=DocumentCreatedFrom.WEB,
created_by=created_by,
)
diff --git a/api/tests/unit_tests/tasks/test_delete_conversation_task.py b/api/tests/unit_tests/tasks/test_delete_conversation_task.py
index e3e5d84488c..aa86ac156a0 100644
--- a/api/tests/unit_tests/tasks/test_delete_conversation_task.py
+++ b/api/tests/unit_tests/tasks/test_delete_conversation_task.py
@@ -12,7 +12,6 @@ from core.workflow.nodes.human_input.enums import HumanInputFormKind, HumanInput
from graphon.file import FileTransferMethod, FileType
from models import (
AgentDebugConversation,
- AppMode,
Conversation,
ConversationVariable,
HumanInputForm,
@@ -39,6 +38,7 @@ from models.enums import (
from models.human_input import HumanInputDelivery, HumanInputFormRecipient, RecipientType
from models.tools import ToolConversationVariables, ToolFile
from tasks.delete_conversation_task import _cleanup_conversation_related_data, sweep_deleted_conversations
+from tests.unit_tests.model_factories import make_conversation, make_message
TENANT_ID = "11111111-1111-1111-1111-111111111111"
APP_ID = "22222222-2222-2222-2222-222222222222"
@@ -50,10 +50,9 @@ AGENT_ID = "77777777-7777-7777-7777-777777777777"
def _conversation(conversation_id: str, *, deleted: bool) -> Conversation:
- return Conversation(
- id=conversation_id,
+ return make_conversation(
+ conversation_id=conversation_id,
app_id=APP_ID,
- mode=AppMode.CHAT,
name="Test conversation",
inputs={},
status=ConversationStatus.NORMAL,
@@ -64,8 +63,8 @@ def _conversation(conversation_id: str, *, deleted: bool) -> Conversation:
def _message() -> Message:
- return Message(
- id=MESSAGE_ID,
+ return make_message(
+ message_id=MESSAGE_ID,
app_id=APP_ID,
conversation_id=CONVERSATION_ID,
inputs={},
diff --git a/api/tests/unit_tests/tasks/test_resume_agent_app_task.py b/api/tests/unit_tests/tasks/test_resume_agent_app_task.py
index c9d20849af7..ce063d3a6bb 100644
--- a/api/tests/unit_tests/tasks/test_resume_agent_app_task.py
+++ b/api/tests/unit_tests/tasks/test_resume_agent_app_task.py
@@ -18,6 +18,7 @@ from models.enums import InvokeFrom as StoredInvokeFrom
from models.human_input import HumanInputForm
from models.model import App, AppMode, Conversation, EndUser
from tasks.app_generate import resume_agent_app_task as mod
+from tests.unit_tests.model_factories import make_app, make_conversation
MODULE = "tasks.app_generate.resume_agent_app_task"
@@ -33,15 +34,12 @@ def task_session(mocker: MockerFixture, sqlite_session_factory: sessionmaker[Ses
def _app(*, app_id: str, tenant_id: str) -> App:
- return App(
- id=app_id,
+ return make_app(
+ app_id=app_id,
tenant_id=tenant_id,
name="Agent app",
- description="",
mode=AppMode.AGENT_CHAT,
icon_type=None,
- icon=None,
- icon_background=None,
enable_site=False,
enable_api=False,
)
@@ -55,8 +53,8 @@ def _conversation(
end_user_id: str | None = None,
invoke_from: StoredInvokeFrom = StoredInvokeFrom.WEB_APP,
) -> Conversation:
- return Conversation(
- id=conversation_id,
+ return make_conversation(
+ conversation_id=conversation_id,
app_id=app_id,
mode=AppMode.AGENT_CHAT,
name="Agent conversation",
diff --git a/api/tests/unit_tests/tasks/test_sync_website_document_indexing_task.py b/api/tests/unit_tests/tasks/test_sync_website_document_indexing_task.py
index 041e9ba55e5..594c4295305 100644
--- a/api/tests/unit_tests/tasks/test_sync_website_document_indexing_task.py
+++ b/api/tests/unit_tests/tasks/test_sync_website_document_indexing_task.py
@@ -7,14 +7,15 @@ from sqlalchemy.orm import Session
from core.rag.index_processor.constant.index_type import IndexStructureType
from enums import DeploymentEdition
from models.dataset import Dataset, Document, DocumentSegment
-from models.enums import DataSourceType, DocumentCreatedFrom
+from models.enums import DataSourceType
from tasks.sync_website_document_indexing_task import sync_website_document_indexing_task
from tests.unit_tests.config_override import config_overrides_context
+from tests.unit_tests.model_factories import make_dataset, make_document
def _dataset(tenant_id: str) -> Dataset:
- return Dataset(
- id=str(uuid.uuid4()),
+ return make_dataset(
+ dataset_id=str(uuid.uuid4()),
tenant_id=tenant_id,
name="Website dataset",
data_source_type=DataSourceType.WEBSITE_CRAWL,
@@ -23,15 +24,12 @@ def _dataset(tenant_id: str) -> Dataset:
def _document(dataset: Dataset) -> Document:
- return Document(
- id=str(uuid.uuid4()),
+ return make_document(
+ document_id=str(uuid.uuid4()),
tenant_id=dataset.tenant_id,
dataset_id=dataset.id,
- position=1,
data_source_type=DataSourceType.WEBSITE_CRAWL,
- batch="batch-1",
name="Website document",
- created_from=DocumentCreatedFrom.WEB,
created_by=str(uuid.uuid4()),
doc_form=IndexStructureType.PARAGRAPH_INDEX,
)
diff --git a/api/tests/unit_tests/tasks/test_trigger_processing_tasks.py b/api/tests/unit_tests/tasks/test_trigger_processing_tasks.py
index 6609633a9cb..ecb320b5a9d 100644
--- a/api/tests/unit_tests/tasks/test_trigger_processing_tasks.py
+++ b/api/tests/unit_tests/tasks/test_trigger_processing_tasks.py
@@ -1,52 +1,43 @@
-import json
from unittest.mock import MagicMock, patch
import pytest
import tasks.trigger_processing_tasks as trigger_processing_tasks_module
from core.plugin.entities.plugin_daemon import CredentialType
-from graphon.enums import WorkflowType
from models.enums import EndUserType
from models.model import EndUser
from models.trigger import TriggerSubscription, WorkflowPluginTrigger
from models.workflow import Workflow
from services.errors.app import QuotaExceededError
from tasks.trigger_processing_tasks import dispatch_triggered_workflow
+from tests.unit_tests.model_factories import make_end_user, make_workflow
def _workflow(*, app_id: str = "app-123") -> Workflow:
- workflow = Workflow.new(
+ return make_workflow(
+ workflow_id="workflow-123",
tenant_id="tenant-123",
app_id=app_id,
- type=WorkflowType.WORKFLOW.value,
version="published",
- graph=json.dumps(
- {
- "nodes": [
- {
- "id": "node-123",
- "data": {"type": trigger_processing_tasks_module.TRIGGER_PLUGIN_NODE_TYPE},
- }
- ],
- "edges": [],
- }
- ),
- features="{}",
+ graph={
+ "nodes": [
+ {
+ "id": "node-123",
+ "data": {"type": trigger_processing_tasks_module.TRIGGER_PLUGIN_NODE_TYPE},
+ }
+ ],
+ "edges": [],
+ },
created_by="user-123",
- environment_variables=[],
- conversation_variables=[],
- rag_pipeline_variables=[],
)
- workflow.id = "workflow-123"
- return workflow
def _end_user() -> EndUser:
- return EndUser(
- id="end-user-123",
+ return make_end_user(
+ end_user_id="end-user-123",
tenant_id="tenant-123",
app_id="app-123",
- type=EndUserType.TRIGGER,
+ end_user_type=EndUserType.TRIGGER,
session_id="trigger-session",
)