chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动

演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
wuzilongandCursor committed 2026-11-18 13:59:25 +08:00
1 parent 60158935f4
commit 6519682885
15831 files changed
+3063428

No files matched your search

@@ -0,0 +1,192 @@
"""
Integration tests for Account and Tenant model methods that interact with the database.
Migrated from unit_tests/models/test_account_models.py, replacing
@patch("models.account.db") mock patches with real PostgreSQL operations.
Also absorbs unit_tests/models/test_account.py role helper coverage.
Covers:
- Account.set_current_tenant_with_session (sets _current_tenant and role from TenantAccountJoin)
- Account.set_tenant_id_with_session (resolves tenant + role from real join row)
- Tenant.get_accounts (returns accounts linked via TenantAccountJoin)
"""
from collections.abc import Generator
from typing import cast
from uuid import uuid4
import pytest
from sqlalchemy import delete
from sqlalchemy.orm import Session
from models.account import Account, Tenant, TenantAccountJoin, TenantAccountRole
TrackedRow = Account | Tenant | TenantAccountJoin
def _cleanup_tracked_rows(db_session: Session, tracked: list[TrackedRow]) -> None:
"""Delete rows tracked during the test so committed state does not leak into the DB.
Rolls back any pending (uncommitted) session state first, then issues DELETE
statements by primary key for each tracked entity (in reverse creation order)
and commits. This cleans up rows created via either flush() or commit().
"""
db_session.rollback()
for entity in reversed(tracked):
db_session.execute(delete(type(entity)).where(type(entity).id == entity.id))
db_session.commit()
def _build_tenant() -> Tenant:
return Tenant(name=f"Tenant {uuid4()}")
def _build_account(email_prefix: str = "account") -> Account:
return Account(
name=f"Account {uuid4()}",
email=f"{email_prefix}_{uuid4()}@example.com",
password="hashed-password",
password_salt="salt",
interface_language="en-US",
timezone="UTC",
)
class _DBTrackingTestBase:
"""Base class providing a tracker list and shared row factories for account/tenant tests."""
_tracked: list[TrackedRow]
@pytest.fixture(autouse=True)
def _setup_cleanup(self, db_session_with_containers: Session) -> Generator[None]:
self._tracked = []
yield
_cleanup_tracked_rows(db_session_with_containers, self._tracked)
def _create_tenant(self, db_session: Session) -> Tenant:
tenant = _build_tenant()
db_session.add(tenant)
db_session.flush()
self._tracked.append(tenant)
return tenant
def _create_account(self, db_session: Session, email_prefix: str = "account") -> Account:
account = _build_account(email_prefix)
db_session.add(account)
db_session.flush()
self._tracked.append(account)
return account
def _create_join(
self, db_session: Session, tenant_id: str, account_id: str, role: TenantAccountRole, current: bool = True
) -> TenantAccountJoin:
join = TenantAccountJoin(tenant_id=tenant_id, account_id=account_id, role=role, current=current)
db_session.add(join)
db_session.flush()
self._tracked.append(join)
return join
class TestTenantAccountRole:
"""Tests for TenantAccountRole helper methods."""
def test_account_is_privileged_role(self) -> None:
assert TenantAccountRole.ADMIN == "admin"
assert TenantAccountRole.OWNER == "owner"
assert TenantAccountRole.EDITOR == "editor"
assert TenantAccountRole.NORMAL == "normal"
assert TenantAccountRole.is_privileged_role(TenantAccountRole.ADMIN)
assert TenantAccountRole.is_privileged_role(TenantAccountRole.OWNER)
assert not TenantAccountRole.is_privileged_role(TenantAccountRole.NORMAL)
assert not TenantAccountRole.is_privileged_role(TenantAccountRole.EDITOR)
assert not TenantAccountRole.is_privileged_role(cast(TenantAccountRole, ""))
class TestAccountSetCurrentTenant(_DBTrackingTestBase):
"""Integration tests for Account.current_tenant and set_current_tenant_with_session."""
def test_current_tenant_property_returns_cached_tenant(self, db_session_with_containers: Session) -> None:
"""current_tenant getter returns the in-memory _current_tenant without DB access."""
account = self._create_account(db_session_with_containers)
tenant = self._create_tenant(db_session_with_containers)
account._current_tenant = tenant
assert account.current_tenant is tenant
def test_set_current_tenant_with_session_sets_tenant_and_role_when_join_exists(
self, db_session_with_containers: Session
) -> None:
"""set_current_tenant_with_session loads the join row and assigns role when relationship exists."""
tenant = self._create_tenant(db_session_with_containers)
account = self._create_account(db_session_with_containers)
self._create_join(db_session_with_containers, tenant.id, account.id, TenantAccountRole.OWNER)
db_session_with_containers.commit()
account.set_current_tenant_with_session(tenant, session=db_session_with_containers)
assert account._current_tenant is not None
assert account._current_tenant.id == tenant.id
assert account.role == TenantAccountRole.OWNER
def test_set_current_tenant_with_session_sets_none_when_no_join_exists(
self, db_session_with_containers: Session
) -> None:
"""set_current_tenant_with_session results in _current_tenant=None when no join row exists."""
tenant = self._create_tenant(db_session_with_containers)
account = self._create_account(db_session_with_containers)
db_session_with_containers.commit()
account.set_current_tenant_with_session(tenant, session=db_session_with_containers)
assert account._current_tenant is None
class TestAccountSetTenantId(_DBTrackingTestBase):
"""Integration tests for Account.set_tenant_id_with_session method."""
def test_set_tenant_id_with_session_sets_tenant_and_role_when_relationship_exists(
self, db_session_with_containers: Session
) -> None:
"""set_tenant_id_with_session loads the tenant and assigns role when a join row exists."""
tenant = self._create_tenant(db_session_with_containers)
account = self._create_account(db_session_with_containers)
self._create_join(db_session_with_containers, tenant.id, account.id, TenantAccountRole.ADMIN)
db_session_with_containers.commit()
account.set_tenant_id_with_session(tenant.id, session=db_session_with_containers)
assert account._current_tenant is not None
assert account._current_tenant.id == tenant.id
assert account.role == TenantAccountRole.ADMIN
def test_set_tenant_id_with_session_does_not_set_tenant_when_no_relationship_exists(
self, db_session_with_containers: Session
) -> None:
"""set_tenant_id_with_session does nothing when no join row matches the tenant."""
tenant = self._create_tenant(db_session_with_containers)
account = self._create_account(db_session_with_containers)
db_session_with_containers.commit()
account.set_tenant_id_with_session(tenant.id, session=db_session_with_containers)
assert account._current_tenant is None
class TestTenantGetAccounts(_DBTrackingTestBase):
"""Integration tests for Tenant.get_accounts method."""
def test_get_accounts_returns_linked_accounts(self, db_session_with_containers: Session) -> None:
"""get_accounts returns all accounts linked to the tenant via TenantAccountJoin."""
tenant = self._create_tenant(db_session_with_containers)
account1 = self._create_account(db_session_with_containers, email_prefix="tenant_member")
account2 = self._create_account(db_session_with_containers, email_prefix="tenant_member")
self._create_join(db_session_with_containers, tenant.id, account1.id, TenantAccountRole.OWNER, current=False)
self._create_join(db_session_with_containers, tenant.id, account2.id, TenantAccountRole.NORMAL, current=False)
accounts = tenant.get_accounts(session=db_session_with_containers)
assert len(accounts) == 2
account_ids = {a.id for a in accounts}
assert account1.id in account_ids
assert account2.id in account_ids
@@ -0,0 +1,32 @@
"""
Integration tests for AppModelConfig using testcontainers.
These tests validate database-backed model behavior without mocking SQLAlchemy queries.
"""
from uuid import uuid4
from sqlalchemy.orm import Session
from models.model import AppModelConfig, load_annotation_reply_config
class TestAppModelConfig:
"""Integration tests for AppModelConfig."""
def test_load_annotation_reply_config_disabled_without_setting(self, db_session_with_containers: Session) -> None:
"""Return disabled annotation reply config when no AppAnnotationSetting exists."""
# Arrange
config = AppModelConfig(app_id=str(uuid4()))
db_session_with_containers.add(config)
db_session_with_containers.commit()
# Act
result = load_annotation_reply_config(db_session_with_containers, config.app_id)
# Assert
assert result == {"enabled": False}
# Cleanup
db_session_with_containers.delete(config)
db_session_with_containers.commit()
@@ -0,0 +1,149 @@
"""
Integration tests for Conversation.inputs and Message.inputs tenant resolution.
Migrated from unit_tests/models/test_model.py, replacing db.session.scalar monkeypatching
with a real App in PostgreSQL so the _resolve_app_tenant_id lookup executes against the DB.
"""
from collections.abc import Generator
from unittest.mock import patch
from uuid import uuid4
import pytest
from sqlalchemy.orm import Session
from core.workflow.file_reference import build_file_reference
from graphon.file import FILE_MODEL_IDENTITY, FileTransferMethod
from models.model import App, AppMode, Conversation, Message
def _build_local_file_mapping(record_id: str, *, tenant_id: str | None = None) -> dict:
mapping: dict = {
"dify_model_identity": FILE_MODEL_IDENTITY,
"transfer_method": FileTransferMethod.LOCAL_FILE,
"reference": build_file_reference(record_id=record_id),
"type": "document",
"filename": "example.txt",
"extension": ".txt",
"mime_type": "text/plain",
"size": 1,
}
if tenant_id is not None:
mapping["tenant_id"] = tenant_id
return mapping
class TestConversationMessageInputsTenantResolution:
"""Integration tests for Conversation/Message.inputs tenant resolution via real DB lookup."""
@pytest.fixture(autouse=True)
def _auto_rollback(self, db_session_with_containers: Session) -> Generator[None]:
"""Automatically rollback session changes after each test."""
yield
db_session_with_containers.rollback()
def _create_app(self, db_session: Session) -> App:
tenant_id = str(uuid4())
app = App(
tenant_id=tenant_id,
name=f"App {uuid4()}",
mode=AppMode.CHAT,
enable_site=False,
enable_api=True,
is_demo=False,
is_public=False,
is_universal=False,
created_by=str(uuid4()),
updated_by=str(uuid4()),
)
db_session.add(app)
db_session.flush()
return app
@pytest.mark.parametrize("owner_cls", [Conversation, Message])
def test_inputs_resolves_tenant_via_db_for_local_file(
self,
db_session_with_containers: Session,
owner_cls: type,
) -> None:
"""Inputs resolves tenant_id from real App row when file mapping has no tenant_id."""
app = self._create_app(db_session_with_containers)
build_calls: list[tuple[dict, str]] = []
def fake_build_from_mapping(
*, mapping, tenant_id, config=None, strict_type_validation=False, access_controller
):
build_calls.append((dict(mapping), tenant_id))
return {"tenant_id": tenant_id, "upload_file_id": mapping.get("upload_file_id")}
with patch("factories.file_factory.build_from_mapping", fake_build_from_mapping):
owner = owner_cls(app_id=app.id)
owner.inputs = {"file": _build_local_file_mapping("upload-1")}
restored_inputs = owner.inputs_with_session(session=db_session_with_containers)
# The tenant_id should come from the real App row in the DB
assert restored_inputs["file"] == {"tenant_id": app.tenant_id, "upload_file_id": "upload-1"}
assert len(build_calls) == 1
assert build_calls[0][1] == app.tenant_id
@pytest.mark.parametrize("owner_cls", [Conversation, Message])
def test_inputs_uses_serialized_tenant_id_skipping_db_lookup(
self,
db_session_with_containers: Session,
owner_cls: type,
) -> None:
"""Inputs uses tenant_id from the file mapping payload without hitting the DB."""
app = self._create_app(db_session_with_containers)
payload_tenant_id = "tenant-from-payload"
build_calls: list[tuple[dict, str]] = []
def fake_build_from_mapping(
*, mapping, tenant_id, config=None, strict_type_validation=False, access_controller
):
build_calls.append((dict(mapping), tenant_id))
return {"tenant_id": tenant_id, "upload_file_id": mapping.get("upload_file_id")}
with patch("factories.file_factory.build_from_mapping", fake_build_from_mapping):
owner = owner_cls(app_id=app.id)
owner.inputs = {"file": _build_local_file_mapping("upload-1", tenant_id=payload_tenant_id)}
restored_inputs = owner.inputs_with_session(session=db_session_with_containers)
assert restored_inputs["file"] == {"tenant_id": payload_tenant_id, "upload_file_id": "upload-1"}
assert len(build_calls) == 1
assert build_calls[0][1] == payload_tenant_id
@pytest.mark.parametrize("owner_cls", [Conversation, Message])
def test_inputs_resolves_tenant_for_file_list(
self,
db_session_with_containers: Session,
owner_cls: type,
) -> None:
"""Inputs resolves tenant_id for a list of file mappings."""
app = self._create_app(db_session_with_containers)
build_calls: list[tuple[dict, str]] = []
def fake_build_from_mapping(
*, mapping, tenant_id, config=None, strict_type_validation=False, access_controller
):
build_calls.append((dict(mapping), tenant_id))
return {"tenant_id": tenant_id, "upload_file_id": mapping.get("upload_file_id")}
with patch("factories.file_factory.build_from_mapping", fake_build_from_mapping):
owner = owner_cls(app_id=app.id)
owner.inputs = {
"files": [
_build_local_file_mapping("upload-1"),
_build_local_file_mapping("upload-2"),
]
}
restored_inputs = owner.inputs_with_session(session=db_session_with_containers)
assert len(build_calls) == 2
assert all(call[1] == app.tenant_id for call in build_calls)
assert restored_inputs["files"] == [
{"tenant_id": app.tenant_id, "upload_file_id": "upload-1"},
{"tenant_id": app.tenant_id, "upload_file_id": "upload-2"},
]
@@ -0,0 +1,315 @@
"""
Integration tests for Conversation.status_count_with_session and Site.generate_code.
Migrated from unit_tests/models/test_app_models.py TestConversationStatusCount and
test_site_generate_code, replacing db.session.scalars mocks with real PostgreSQL queries.
"""
from collections.abc import Generator
from decimal import Decimal
from uuid import uuid4
import pytest
from sqlalchemy.orm import Session
from graphon.enums import WorkflowExecutionStatus
from models.enums import ConversationFromSource, ConversationStatus, CreatorUserRole, CustomizeTokenStrategy, InvokeFrom
from models.model import App, AppMode, Conversation, Message, Site
from models.workflow import Workflow, WorkflowRun, WorkflowRunTriggeredFrom, WorkflowType
class TestConversationStatusCount:
"""Integration tests for Conversation.status_count_with_session."""
@pytest.fixture(autouse=True)
def _auto_rollback(self, db_session_with_containers: Session) -> Generator[None]:
"""Automatically rollback session changes after each test."""
yield
db_session_with_containers.rollback()
def _create_app(self, db_session: Session, tenant_id: str, created_by: str) -> App:
app = App(
tenant_id=tenant_id,
name=f"App {uuid4()}",
mode=AppMode.ADVANCED_CHAT,
enable_site=False,
enable_api=True,
is_demo=False,
is_public=False,
is_universal=False,
created_by=created_by,
updated_by=created_by,
)
db_session.add(app)
db_session.flush()
return app
def _create_conversation(self, db_session: Session, app: App) -> Conversation:
conversation = Conversation(
app_id=app.id,
mode=app.mode,
name=f"Conversation {uuid4()}",
summary="",
_inputs={},
introduction="",
system_instruction="",
system_instruction_tokens=0,
status=ConversationStatus.NORMAL,
invoke_from=InvokeFrom.WEB_APP,
from_source=ConversationFromSource.API,
dialogue_count=0,
is_deleted=False,
)
conversation.inputs = {}
db_session.add(conversation)
db_session.flush()
return conversation
def _create_workflow(self, db_session: Session, app: App, created_by: str) -> Workflow:
workflow = Workflow(
tenant_id=app.tenant_id,
app_id=app.id,
type=WorkflowType.CHAT,
version="draft",
graph="{}",
created_by=created_by,
)
workflow._features = "{}"
db_session.add(workflow)
db_session.flush()
return workflow
def _create_workflow_run(
self, db_session: Session, app: App, workflow: Workflow, status: WorkflowExecutionStatus, created_by: str
) -> WorkflowRun:
run = WorkflowRun(
tenant_id=app.tenant_id,
app_id=app.id,
workflow_id=workflow.id,
type=WorkflowType.CHAT,
triggered_from=WorkflowRunTriggeredFrom.APP_RUN,
version="draft",
status=status,
created_by_role=CreatorUserRole.ACCOUNT,
created_by=created_by,
)
db_session.add(run)
db_session.flush()
return run
def _create_message(
self, db_session: Session, app: App, conversation: Conversation, workflow_run_id: str | None = None
) -> Message:
message = Message(
app_id=app.id,
conversation_id=conversation.id,
_inputs={},
query="Test query",
message={"role": "user", "content": "Test query"},
answer="Test answer",
model_provider="openai",
model_id="gpt-4",
message_tokens=10,
message_unit_price=Decimal(0),
answer_tokens=10,
answer_unit_price=Decimal(0),
total_price=Decimal(0),
currency="USD",
from_source=ConversationFromSource.API,
invoke_from=InvokeFrom.WEB_APP,
workflow_run_id=workflow_run_id,
)
db_session.add(message)
db_session.flush()
return message
def test_status_count_returns_none_when_no_messages(self, db_session_with_containers: Session) -> None:
"""status_count returns None when conversation has no messages with workflow_run_id."""
tenant_id = str(uuid4())
created_by = str(uuid4())
app = self._create_app(db_session_with_containers, tenant_id, created_by)
conversation = self._create_conversation(db_session_with_containers, app)
result = conversation.status_count_with_session(session=db_session_with_containers)
assert result is None
def test_status_count_returns_none_when_messages_have_no_workflow_run_id(
self, db_session_with_containers: Session
) -> None:
"""status_count returns None when messages exist but none have workflow_run_id."""
tenant_id = str(uuid4())
created_by = str(uuid4())
app = self._create_app(db_session_with_containers, tenant_id, created_by)
conversation = self._create_conversation(db_session_with_containers, app)
self._create_message(db_session_with_containers, app, conversation, workflow_run_id=None)
result = conversation.status_count_with_session(session=db_session_with_containers)
assert result is None
def test_status_count_counts_succeeded_workflow_run(self, db_session_with_containers: Session) -> None:
"""status_count correctly counts succeeded workflow runs."""
tenant_id = str(uuid4())
created_by = str(uuid4())
app = self._create_app(db_session_with_containers, tenant_id, created_by)
conversation = self._create_conversation(db_session_with_containers, app)
workflow = self._create_workflow(db_session_with_containers, app, created_by)
run = self._create_workflow_run(
db_session_with_containers, app, workflow, WorkflowExecutionStatus.SUCCEEDED, created_by
)
self._create_message(db_session_with_containers, app, conversation, workflow_run_id=run.id)
result = conversation.status_count_with_session(session=db_session_with_containers)
assert result is not None
assert result["success"] == 1
assert result["failed"] == 0
assert result["partial_success"] == 0
assert result["paused"] == 0
def test_status_count_counts_failed_workflow_run(self, db_session_with_containers: Session) -> None:
"""status_count correctly counts failed workflow runs."""
tenant_id = str(uuid4())
created_by = str(uuid4())
app = self._create_app(db_session_with_containers, tenant_id, created_by)
conversation = self._create_conversation(db_session_with_containers, app)
workflow = self._create_workflow(db_session_with_containers, app, created_by)
run = self._create_workflow_run(
db_session_with_containers, app, workflow, WorkflowExecutionStatus.FAILED, created_by
)
self._create_message(db_session_with_containers, app, conversation, workflow_run_id=run.id)
result = conversation.status_count_with_session(session=db_session_with_containers)
assert result is not None
assert result["success"] == 0
assert result["failed"] == 1
assert result["partial_success"] == 0
assert result["paused"] == 0
def test_status_count_counts_paused_workflow_run(self, db_session_with_containers: Session) -> None:
"""status_count correctly counts paused workflow runs."""
tenant_id = str(uuid4())
created_by = str(uuid4())
app = self._create_app(db_session_with_containers, tenant_id, created_by)
conversation = self._create_conversation(db_session_with_containers, app)
workflow = self._create_workflow(db_session_with_containers, app, created_by)
run = self._create_workflow_run(
db_session_with_containers, app, workflow, WorkflowExecutionStatus.PAUSED, created_by
)
self._create_message(db_session_with_containers, app, conversation, workflow_run_id=run.id)
result = conversation.status_count_with_session(session=db_session_with_containers)
assert result is not None
assert result["success"] == 0
assert result["failed"] == 0
assert result["partial_success"] == 0
assert result["paused"] == 1
def test_status_count_multiple_statuses(self, db_session_with_containers: Session) -> None:
"""status_count counts multiple workflow runs with different statuses."""
tenant_id = str(uuid4())
created_by = str(uuid4())
app = self._create_app(db_session_with_containers, tenant_id, created_by)
conversation = self._create_conversation(db_session_with_containers, app)
workflow = self._create_workflow(db_session_with_containers, app, created_by)
for status in [
WorkflowExecutionStatus.SUCCEEDED,
WorkflowExecutionStatus.FAILED,
WorkflowExecutionStatus.PARTIAL_SUCCEEDED,
WorkflowExecutionStatus.PAUSED,
]:
run = self._create_workflow_run(db_session_with_containers, app, workflow, status, created_by)
self._create_message(db_session_with_containers, app, conversation, workflow_run_id=run.id)
result = conversation.status_count_with_session(session=db_session_with_containers)
assert result is not None
assert result["success"] == 1
assert result["failed"] == 1
assert result["partial_success"] == 1
assert result["paused"] == 1
def test_status_count_filters_workflow_runs_by_app_id(self, db_session_with_containers: Session) -> None:
"""status_count excludes workflow runs belonging to a different app."""
tenant_id = str(uuid4())
created_by = str(uuid4())
app = self._create_app(db_session_with_containers, tenant_id, created_by)
other_app = self._create_app(db_session_with_containers, tenant_id, created_by)
conversation = self._create_conversation(db_session_with_containers, app)
workflow = self._create_workflow(db_session_with_containers, other_app, created_by)
# Workflow run belongs to other_app, not app
other_run = self._create_workflow_run(
db_session_with_containers, other_app, workflow, WorkflowExecutionStatus.SUCCEEDED, created_by
)
# Message references that run but is in a conversation under app
self._create_message(db_session_with_containers, app, conversation, workflow_run_id=other_run.id)
result = conversation.status_count_with_session(session=db_session_with_containers)
# The run should be excluded because app_id filter doesn't match
assert result is not None
assert result["success"] == 0
class TestSiteGenerateCode:
"""Integration tests for Site.generate_code static method."""
@pytest.fixture(autouse=True)
def _auto_rollback(self, db_session_with_containers: Session) -> Generator[None]:
"""Automatically rollback session changes after each test."""
yield
db_session_with_containers.rollback()
def test_generate_code_returns_string_of_correct_length(self, db_session_with_containers: Session) -> None:
"""Site.generate_code returns a code string of the requested length."""
code = Site.generate_code(8, session=db_session_with_containers)
assert isinstance(code, str)
assert len(code) == 8
def test_generate_code_avoids_duplicates(self, db_session_with_containers: Session) -> None:
"""Site.generate_code returns a code not already in use."""
tenant_id = str(uuid4())
app = App(
tenant_id=tenant_id,
name="Test App",
mode=AppMode.CHAT,
enable_site=True,
enable_api=False,
is_demo=False,
is_public=False,
is_universal=False,
created_by=str(uuid4()),
updated_by=str(uuid4()),
)
db_session_with_containers.add(app)
db_session_with_containers.flush()
site = Site(
app_id=app.id,
title="Test Site",
default_language="en-US",
customize_token_strategy=CustomizeTokenStrategy.NOT_ALLOW,
)
# Set an explicit code so generate_code must avoid it
site.code = "AAAAAAAA"
db_session_with_containers.add(site)
db_session_with_containers.flush()
code = Site.generate_code(8, session=db_session_with_containers)
assert isinstance(code, str)
assert len(code) == 8
assert code != site.code
@@ -0,0 +1,502 @@
"""
Integration tests for Dataset and Document model properties using testcontainers.
These tests validate database-backed model properties (total_documents, word_count, etc.)
without mocking SQLAlchemy queries, ensuring real query behavior against PostgreSQL.
"""
from collections.abc import Generator
from uuid import uuid4
import pytest
from sqlalchemy.orm import Session
from models.dataset import Dataset, Document, DocumentSegment
from models.enums import DataSourceType, DocumentCreatedFrom, IndexingStatus, SegmentStatus
from repositories.knowledge.dataset_read_repository import (
get_dataset_available_document_count,
get_dataset_available_segment_count,
get_dataset_document_count,
get_dataset_word_count,
get_document_hit_count,
get_document_segment_count,
get_next_segment,
get_previous_segment,
get_segment_dataset,
get_segment_document,
)
class TestDatasetDocumentProperties:
"""Integration tests for Dataset and Document model properties."""
@pytest.fixture(autouse=True)
def _auto_rollback(self, db_session_with_containers: Session) -> Generator[None]:
"""Automatically rollback session changes after each test."""
yield
db_session_with_containers.rollback()
def test_dataset_with_documents_relationship(self, db_session_with_containers: Session) -> None:
"""Test dataset can track its documents."""
tenant_id = str(uuid4())
created_by = str(uuid4())
dataset = Dataset(
tenant_id=tenant_id, name="Test Dataset", data_source_type=DataSourceType.UPLOAD_FILE, created_by=created_by
)
db_session_with_containers.add(dataset)
db_session_with_containers.flush()
for i in range(3):
doc = Document(
tenant_id=tenant_id,
dataset_id=dataset.id,
position=i + 1,
data_source_type=DataSourceType.UPLOAD_FILE,
batch="batch_001",
name=f"doc_{i}.pdf",
created_from=DocumentCreatedFrom.WEB,
created_by=created_by,
)
db_session_with_containers.add(doc)
db_session_with_containers.flush()
assert get_dataset_document_count(dataset, session=db_session_with_containers) == 3
def test_dataset_available_documents_count(self, db_session_with_containers: Session) -> None:
"""Test dataset can count available documents."""
tenant_id = str(uuid4())
created_by = str(uuid4())
dataset = Dataset(
tenant_id=tenant_id, name="Test Dataset", data_source_type=DataSourceType.UPLOAD_FILE, created_by=created_by
)
db_session_with_containers.add(dataset)
db_session_with_containers.flush()
doc_available = Document(
tenant_id=tenant_id,
dataset_id=dataset.id,
position=1,
data_source_type=DataSourceType.UPLOAD_FILE,
batch="batch_001",
name="available.pdf",
created_from=DocumentCreatedFrom.WEB,
created_by=created_by,
indexing_status=IndexingStatus.COMPLETED,
enabled=True,
archived=False,
)
doc_pending = Document(
tenant_id=tenant_id,
dataset_id=dataset.id,
position=2,
data_source_type=DataSourceType.UPLOAD_FILE,
batch="batch_001",
name="pending.pdf",
created_from=DocumentCreatedFrom.WEB,
created_by=created_by,
indexing_status=IndexingStatus.WAITING,
enabled=True,
archived=False,
)
doc_disabled = Document(
tenant_id=tenant_id,
dataset_id=dataset.id,
position=3,
data_source_type=DataSourceType.UPLOAD_FILE,
batch="batch_001",
name="disabled.pdf",
created_from=DocumentCreatedFrom.WEB,
created_by=created_by,
indexing_status=IndexingStatus.COMPLETED,
enabled=False,
archived=False,
)
db_session_with_containers.add_all([doc_available, doc_pending, doc_disabled])
db_session_with_containers.flush()
assert get_dataset_available_document_count(dataset, session=db_session_with_containers) == 1
def test_dataset_word_count_aggregation(self, db_session_with_containers: Session) -> None:
"""Test dataset can aggregate word count from documents."""
tenant_id = str(uuid4())
created_by = str(uuid4())
dataset = Dataset(
tenant_id=tenant_id, name="Test Dataset", data_source_type=DataSourceType.UPLOAD_FILE, created_by=created_by
)
db_session_with_containers.add(dataset)
db_session_with_containers.flush()
for i, wc in enumerate([2000, 3000]):
doc = Document(
tenant_id=tenant_id,
dataset_id=dataset.id,
position=i + 1,
data_source_type=DataSourceType.UPLOAD_FILE,
batch="batch_001",
name=f"doc_{i}.pdf",
created_from=DocumentCreatedFrom.WEB,
created_by=created_by,
word_count=wc,
)
db_session_with_containers.add(doc)
db_session_with_containers.flush()
assert get_dataset_word_count(dataset, session=db_session_with_containers) == 5000
def test_dataset_available_segment_count(self, db_session_with_containers: Session) -> None:
"""Test Dataset.available_segment_count counts completed and enabled segments."""
tenant_id = str(uuid4())
created_by = str(uuid4())
dataset = Dataset(
tenant_id=tenant_id, name="Test Dataset", data_source_type=DataSourceType.UPLOAD_FILE, created_by=created_by
)
db_session_with_containers.add(dataset)
db_session_with_containers.flush()
doc = Document(
tenant_id=tenant_id,
dataset_id=dataset.id,
position=1,
data_source_type=DataSourceType.UPLOAD_FILE,
batch="batch_001",
name="doc.pdf",
created_from=DocumentCreatedFrom.WEB,
created_by=created_by,
)
db_session_with_containers.add(doc)
db_session_with_containers.flush()
for i in range(2):
seg = DocumentSegment(
tenant_id=tenant_id,
dataset_id=dataset.id,
document_id=doc.id,
position=i + 1,
content=f"segment {i}",
word_count=100,
tokens=50,
status=SegmentStatus.COMPLETED,
enabled=True,
created_by=created_by,
)
db_session_with_containers.add(seg)
seg_waiting = DocumentSegment(
tenant_id=tenant_id,
dataset_id=dataset.id,
document_id=doc.id,
position=3,
content="waiting segment",
word_count=100,
tokens=50,
status=SegmentStatus.WAITING,
enabled=True,
created_by=created_by,
)
db_session_with_containers.add(seg_waiting)
db_session_with_containers.flush()
assert get_dataset_available_segment_count(dataset, session=db_session_with_containers) == 2
def test_document_segment_count_property(self, db_session_with_containers: Session) -> None:
"""Test document can count its segments."""
tenant_id = str(uuid4())
created_by = str(uuid4())
dataset = Dataset(
tenant_id=tenant_id, name="Test Dataset", data_source_type=DataSourceType.UPLOAD_FILE, created_by=created_by
)
db_session_with_containers.add(dataset)
db_session_with_containers.flush()
doc = Document(
tenant_id=tenant_id,
dataset_id=dataset.id,
position=1,
data_source_type=DataSourceType.UPLOAD_FILE,
batch="batch_001",
name="doc.pdf",
created_from=DocumentCreatedFrom.WEB,
created_by=created_by,
)
db_session_with_containers.add(doc)
db_session_with_containers.flush()
for i in range(3):
seg = DocumentSegment(
tenant_id=tenant_id,
dataset_id=dataset.id,
document_id=doc.id,
position=i + 1,
content=f"segment {i}",
word_count=100,
tokens=50,
created_by=created_by,
)
db_session_with_containers.add(seg)
db_session_with_containers.flush()
assert get_document_segment_count(doc, session=db_session_with_containers) == 3
def test_document_hit_count_aggregation(self, db_session_with_containers: Session) -> None:
"""Test document can aggregate hit count from segments."""
tenant_id = str(uuid4())
created_by = str(uuid4())
dataset = Dataset(
tenant_id=tenant_id, name="Test Dataset", data_source_type=DataSourceType.UPLOAD_FILE, created_by=created_by
)
db_session_with_containers.add(dataset)
db_session_with_containers.flush()
doc = Document(
tenant_id=tenant_id,
dataset_id=dataset.id,
position=1,
data_source_type=DataSourceType.UPLOAD_FILE,
batch="batch_001",
name="doc.pdf",
created_from=DocumentCreatedFrom.WEB,
created_by=created_by,
)
db_session_with_containers.add(doc)
db_session_with_containers.flush()
for i, hits in enumerate([10, 15]):
seg = DocumentSegment(
tenant_id=tenant_id,
dataset_id=dataset.id,
document_id=doc.id,
position=i + 1,
content=f"segment {i}",
word_count=100,
tokens=50,
hit_count=hits,
created_by=created_by,
)
db_session_with_containers.add(seg)
db_session_with_containers.flush()
assert get_document_hit_count(doc, session=db_session_with_containers) == 25
class TestDocumentSegmentNavigationProperties:
"""Integration tests for DocumentSegment navigation properties."""
@pytest.fixture(autouse=True)
def _auto_rollback(self, db_session_with_containers: Session) -> Generator[None]:
"""Automatically rollback session changes after each test."""
yield
db_session_with_containers.rollback()
def test_document_segment_dataset_property(self, db_session_with_containers: Session) -> None:
"""Test segment can access its parent dataset."""
# Arrange
tenant_id = str(uuid4())
created_by = str(uuid4())
dataset = Dataset(
tenant_id=tenant_id,
name="Test Dataset",
data_source_type=DataSourceType.UPLOAD_FILE,
created_by=created_by,
)
db_session_with_containers.add(dataset)
db_session_with_containers.flush()
document = Document(
tenant_id=tenant_id,
dataset_id=dataset.id,
position=1,
data_source_type=DataSourceType.UPLOAD_FILE,
batch="batch_001",
name="test.pdf",
created_from=DocumentCreatedFrom.WEB,
created_by=created_by,
)
db_session_with_containers.add(document)
db_session_with_containers.flush()
segment = DocumentSegment(
tenant_id=tenant_id,
dataset_id=dataset.id,
document_id=document.id,
position=1,
content="Test",
word_count=1,
tokens=2,
created_by=created_by,
)
db_session_with_containers.add(segment)
db_session_with_containers.flush()
# Act
related_dataset = get_segment_dataset(segment, session=db_session_with_containers)
# Assert
assert related_dataset is not None
assert related_dataset.id == dataset.id
def test_document_segment_document_property(self, db_session_with_containers: Session) -> None:
"""Test segment can access its parent document."""
# Arrange
tenant_id = str(uuid4())
created_by = str(uuid4())
dataset = Dataset(
tenant_id=tenant_id,
name="Test Dataset",
data_source_type=DataSourceType.UPLOAD_FILE,
created_by=created_by,
)
db_session_with_containers.add(dataset)
db_session_with_containers.flush()
document = Document(
tenant_id=tenant_id,
dataset_id=dataset.id,
position=1,
data_source_type=DataSourceType.UPLOAD_FILE,
batch="batch_001",
name="test.pdf",
created_from=DocumentCreatedFrom.WEB,
created_by=created_by,
)
db_session_with_containers.add(document)
db_session_with_containers.flush()
segment = DocumentSegment(
tenant_id=tenant_id,
dataset_id=dataset.id,
document_id=document.id,
position=1,
content="Test",
word_count=1,
tokens=2,
created_by=created_by,
)
db_session_with_containers.add(segment)
db_session_with_containers.flush()
# Act
related_document = get_segment_document(segment, session=db_session_with_containers)
# Assert
assert related_document is not None
assert related_document.id == document.id
def test_document_segment_previous_segment(self, db_session_with_containers: Session) -> None:
"""Test segment can access previous segment."""
# Arrange
tenant_id = str(uuid4())
created_by = str(uuid4())
dataset = Dataset(
tenant_id=tenant_id,
name="Test Dataset",
data_source_type=DataSourceType.UPLOAD_FILE,
created_by=created_by,
)
db_session_with_containers.add(dataset)
db_session_with_containers.flush()
document = Document(
tenant_id=tenant_id,
dataset_id=dataset.id,
position=1,
data_source_type=DataSourceType.UPLOAD_FILE,
batch="batch_001",
name="test.pdf",
created_from=DocumentCreatedFrom.WEB,
created_by=created_by,
)
db_session_with_containers.add(document)
db_session_with_containers.flush()
previous_segment = DocumentSegment(
tenant_id=tenant_id,
dataset_id=dataset.id,
document_id=document.id,
position=1,
content="Previous",
word_count=1,
tokens=2,
created_by=created_by,
)
segment = DocumentSegment(
tenant_id=tenant_id,
dataset_id=dataset.id,
document_id=document.id,
position=2,
content="Current",
word_count=1,
tokens=2,
created_by=created_by,
)
db_session_with_containers.add_all([previous_segment, segment])
db_session_with_containers.flush()
# Act
prev_seg = get_previous_segment(segment, session=db_session_with_containers)
# Assert
assert prev_seg is not None
assert prev_seg.position == 1
def test_document_segment_next_segment(self, db_session_with_containers: Session) -> None:
"""Test segment can access next segment."""
# Arrange
tenant_id = str(uuid4())
created_by = str(uuid4())
dataset = Dataset(
tenant_id=tenant_id,
name="Test Dataset",
data_source_type=DataSourceType.UPLOAD_FILE,
created_by=created_by,
)
db_session_with_containers.add(dataset)
db_session_with_containers.flush()
document = Document(
tenant_id=tenant_id,
dataset_id=dataset.id,
position=1,
data_source_type=DataSourceType.UPLOAD_FILE,
batch="batch_001",
name="test.pdf",
created_from=DocumentCreatedFrom.WEB,
created_by=created_by,
)
db_session_with_containers.add(document)
db_session_with_containers.flush()
segment = DocumentSegment(
tenant_id=tenant_id,
dataset_id=dataset.id,
document_id=document.id,
position=1,
content="Current",
word_count=1,
tokens=2,
created_by=created_by,
)
next_segment = DocumentSegment(
tenant_id=tenant_id,
dataset_id=dataset.id,
document_id=document.id,
position=2,
content="Next",
word_count=1,
tokens=2,
created_by=created_by,
)
db_session_with_containers.add_all([segment, next_segment])
db_session_with_containers.flush()
# Act
next_seg = get_next_segment(segment, session=db_session_with_containers)
# Assert
assert next_seg is not None
assert next_seg.position == 2
@@ -0,0 +1,116 @@
from collections.abc import Iterator
from typing import Annotated, Literal
import pytest
import sqlalchemy as sa
from pydantic import BaseModel, ConfigDict, Field, TypeAdapter
from sqlalchemy import Engine, select
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column
from models.types import FrozenPydanticModelColumn
class _ConcretePayload(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True, strict=True, validate_default=True)
name: str
count: int
class _EmailDestination(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True, strict=True, validate_default=True)
channel: Literal["email"] = "email"
address: str
class _SlackDestination(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True, strict=True, validate_default=True)
channel: Literal["slack"] = "slack"
channel_id: str
type _Destination = Annotated[_EmailDestination | _SlackDestination, Field(discriminator="channel")]
class _Base(DeclarativeBase):
pass
class _PydanticJSONRecord(_Base):
__tablename__ = "integration_pydantic_json_records"
id: Mapped[int] = mapped_column(sa.Integer, primary_key=True, autoincrement=True)
concrete: Mapped[_ConcretePayload] = mapped_column(
FrozenPydanticModelColumn(
_ConcretePayload,
),
nullable=False,
)
destination: Mapped[_Destination] = mapped_column(
FrozenPydanticModelColumn(
TypeAdapter(_Destination),
model_types=(_EmailDestination, _SlackDestination),
),
nullable=False,
)
@pytest.fixture
def pydantic_json_engine(db_session_with_containers: Session) -> Engine:
bind = db_session_with_containers.get_bind()
assert isinstance(bind, Engine)
return bind
@pytest.fixture(autouse=True)
def _pydantic_json_schema(pydantic_json_engine: Engine) -> Iterator[None]:
_Base.metadata.create_all(pydantic_json_engine)
try:
yield
finally:
_Base.metadata.drop_all(pydantic_json_engine)
def test_real_database_stores_single_encoded_json_and_round_trips_a_concrete_model(
pydantic_json_engine: Engine,
) -> None:
with Session(pydantic_json_engine) as session:
record = _PydanticJSONRecord(
concrete=_ConcretePayload(name="container", count=3),
destination=_EmailDestination(address="reviewer@example.com"),
)
session.add(record)
session.commit()
record_id = record.id
with Session(pydantic_json_engine) as session:
stored_json = session.execute(
sa.text("SELECT concrete FROM integration_pydantic_json_records WHERE id = :record_id"),
{"record_id": record_id},
).scalar_one()
restored = session.scalar(select(_PydanticJSONRecord).where(_PydanticJSONRecord.id == record_id))
assert stored_json == '{"name":"container","count":3}'
assert restored is not None
assert restored.concrete == _ConcretePayload(name="container", count=3)
assert isinstance(restored.concrete, _ConcretePayload)
def test_real_database_restores_the_discriminated_union_subtype(pydantic_json_engine: Engine) -> None:
with Session(pydantic_json_engine) as session:
record = _PydanticJSONRecord(
concrete=_ConcretePayload(name="container", count=4),
destination=_SlackDestination(channel_id="C123"),
)
session.add(record)
session.commit()
record_id = record.id
with Session(pydantic_json_engine) as session:
restored = session.scalar(select(_PydanticJSONRecord).where(_PydanticJSONRecord.id == record_id))
assert restored is not None
assert restored.destination == _SlackDestination(channel_id="C123")
assert isinstance(restored.destination, _SlackDestination)
@@ -0,0 +1,230 @@
import re
from collections.abc import Callable, Iterable
from enum import StrEnum
from typing import Any, NamedTuple
import pytest
import sqlalchemy as sa
from sqlalchemy import exc as sa_exc
from sqlalchemy import insert, select
from sqlalchemy.engine import Connection, Engine
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column
from sqlalchemy.sql.sqltypes import VARCHAR
from graphon.model_runtime.entities.model_entities import ModelType
from models.types import EnumText
_USER_TABLE = "enum_text_users"
_COLUMN_TABLE = "enum_text_column_test"
_user_type_admin = "admin"
_user_type_normal = "normal"
class _Base(DeclarativeBase):
pass
class _UserType(StrEnum):
admin = _user_type_admin
normal = _user_type_normal
class _EnumWithLongValue(StrEnum):
unknown = "unknown"
a_really_long_enum_values = "a_really_long_enum_values"
class _User(_Base):
__tablename__ = _USER_TABLE
id: Mapped[int] = mapped_column(sa.Integer, primary_key=True)
name: Mapped[str] = mapped_column(sa.String(length=255), nullable=False)
user_type: Mapped[_UserType] = mapped_column(
EnumText(enum_class=_UserType), nullable=False, default=_UserType.normal
)
user_type_nullable: Mapped[_UserType | None] = mapped_column(EnumText(enum_class=_UserType), nullable=True)
class _ColumnTest(_Base):
__tablename__ = _COLUMN_TABLE
id: Mapped[int] = mapped_column(sa.Integer, primary_key=True)
user_type: Mapped[_UserType] = mapped_column(
EnumText(enum_class=_UserType), nullable=False, default=_UserType.normal
)
explicit_length: Mapped[_UserType | None] = mapped_column(
EnumText(_UserType, length=50), nullable=True, default=_UserType.normal
)
long_value: Mapped[_EnumWithLongValue] = mapped_column(EnumText(enum_class=_EnumWithLongValue), nullable=False)
class _LegacyModelTypeRecord(_Base):
__tablename__ = "enum_text_legacy_model_type_test"
id: Mapped[int] = mapped_column(sa.Integer, primary_key=True)
model_type: Mapped[ModelType] = mapped_column(EnumText(enum_class=ModelType), nullable=False)
def _first[T](it: Iterable[T]) -> T:
ls = list(it)
if not ls:
raise ValueError("List is empty")
return ls[0]
def _resolve_engine(bind: Engine | Connection) -> Engine:
if isinstance(bind, Engine):
return bind
return bind.engine
@pytest.fixture
def engine_with_containers(db_session_with_containers: Session) -> Engine:
return _resolve_engine(db_session_with_containers.get_bind())
@pytest.fixture(autouse=True)
def _enum_text_schema(engine_with_containers: Engine) -> Iterable[None]:
_Base.metadata.create_all(engine_with_containers)
try:
yield
finally:
_Base.metadata.drop_all(engine_with_containers)
class TestEnumText:
def test_column_impl(self, engine_with_containers: Engine):
inspector = sa.inspect(engine_with_containers)
columns = inspector.get_columns(_COLUMN_TABLE)
user_type_column = _first(c for c in columns if c["name"] == "user_type")
sql_type = user_type_column["type"]
assert isinstance(user_type_column["type"], VARCHAR)
assert sql_type.length == 20
assert user_type_column["nullable"] is False
explicit_length_column = _first(c for c in columns if c["name"] == "explicit_length")
sql_type = explicit_length_column["type"]
assert isinstance(sql_type, VARCHAR)
assert sql_type.length == 50
assert explicit_length_column["nullable"] is True
long_value_column = _first(c for c in columns if c["name"] == "long_value")
sql_type = long_value_column["type"]
assert isinstance(sql_type, VARCHAR)
assert sql_type.length == len(_EnumWithLongValue.a_really_long_enum_values)
def test_insert_and_select(self, engine_with_containers: Engine):
with Session(engine_with_containers) as session:
admin_user = _User(
name="admin",
user_type=_UserType.admin,
user_type_nullable=None,
)
session.add(admin_user)
session.flush()
admin_user_id = admin_user.id
normal_user = _User(
name="normal",
user_type=_UserType.normal.value,
user_type_nullable=_UserType.normal.value,
)
session.add(normal_user)
session.flush()
normal_user_id = normal_user.id
session.commit()
with Session(engine_with_containers) as session:
user = session.scalar(select(_User).where(_User.id == admin_user_id).limit(1))
assert user.user_type == _UserType.admin
assert user.user_type_nullable is None
with Session(engine_with_containers) as session:
user = session.scalar(select(_User).where(_User.id == normal_user_id).limit(1))
assert user.user_type == _UserType.normal
assert user.user_type_nullable == _UserType.normal
def test_insert_invalid_values(self, engine_with_containers: Engine):
def _session_insert_with_value(sess: Session, user_type: Any):
user = _User(name="test_user", user_type=user_type)
sess.add(user)
sess.flush()
def _insert_with_user(sess: Session, user_type: Any):
stmt = insert(_User).values(
{
"name": "test_user",
"user_type": user_type,
}
)
sess.execute(stmt)
class TestCase(NamedTuple):
name: str
action: Callable[[Session], None]
exc_type: type[Exception]
cases = [
TestCase(
name="session insert with invalid value",
action=lambda s: _session_insert_with_value(s, "invalid"),
exc_type=ValueError,
),
TestCase(
name="session insert with invalid type",
action=lambda s: _session_insert_with_value(s, 1),
exc_type=ValueError,
),
TestCase(
name="insert with invalid value",
action=lambda s: _insert_with_user(s, "invalid"),
exc_type=ValueError,
),
TestCase(
name="insert with invalid type",
action=lambda s: _insert_with_user(s, 1),
exc_type=ValueError,
),
]
for idx, c in enumerate(cases, 1):
with pytest.raises(sa_exc.StatementError) as exc:
with Session(engine_with_containers) as session:
c.action(session)
assert isinstance(exc.value.orig, c.exc_type), f"test case {idx} failed, name={c.name}"
def test_select_invalid_values(self, engine_with_containers: Engine):
insertion_sql = f"""
INSERT INTO {_USER_TABLE} (id, name, user_type) VALUES
(1, 'invalid_value', 'invalid');
"""
with Session(engine_with_containers) as session:
session.execute(sa.text(insertion_sql))
session.commit()
with pytest.raises(ValueError, match="'invalid' is not a valid _UserType") as exc:
with Session(engine_with_containers) as session:
_user = session.scalar(select(_User).where(_User.id == 1).limit(1))
assert str(exc.value) == "'invalid' is not a valid _UserType"
def test_select_rejects_legacy_model_type_values(self, engine_with_containers: Engine):
insertion_sql = """
INSERT INTO enum_text_legacy_model_type_test (id, model_type) VALUES
(1, 'text-generation'),
(2, 'embeddings'),
(3, 'reranking');
"""
with Session(engine_with_containers) as session:
session.execute(sa.text(insertion_sql))
session.commit()
for record_id, legacy_value in enumerate(("text-generation", "embeddings", "reranking"), 1):
with pytest.raises(ValueError, match=re.escape(f"'{legacy_value}' is not a valid ModelType")) as exc:
with Session(engine_with_containers) as session:
session.scalar(select(_LegacyModelTypeRecord).where(_LegacyModelTypeRecord.id == record_id))
assert str(exc.value) == f"'{legacy_value}' is not a valid ModelType"
@@ -0,0 +1,171 @@
"""
Integration tests for WorkflowNodeExecutionModel.created_by_account and .created_by_end_user.
Migrated from unit_tests/models/test_workflow_trigger_log.py, replacing
monkeypatch.setattr(db.session, "scalar", ...) with real Account/EndUser rows
persisted in PostgreSQL so the db.session.get() call executes against the DB.
"""
from collections.abc import Generator
from uuid import uuid4
import pytest
from sqlalchemy.orm import Session
from graphon.enums import WorkflowNodeExecutionStatus
from models.account import Account
from models.enums import CreatorUserRole, EndUserType
from models.model import App, AppMode, EndUser
from models.workflow import WorkflowNodeExecutionModel, WorkflowNodeExecutionTriggeredFrom
class TestWorkflowNodeExecutionModelCreatedBy:
"""Integration tests for WorkflowNodeExecutionModel creator lookup properties."""
@pytest.fixture(autouse=True)
def _auto_rollback(self, db_session_with_containers: Session) -> Generator[None]:
"""Automatically rollback session changes after each test."""
yield
db_session_with_containers.rollback()
def _create_account(self, db_session: Session) -> Account:
account = Account(
name="Test Account",
email=f"test_{uuid4()}@example.com",
password="hashed-password",
password_salt="salt",
interface_language="en-US",
timezone="UTC",
)
db_session.add(account)
db_session.flush()
return account
def _create_end_user(self, db_session: Session, tenant_id: str, app_id: str) -> EndUser:
end_user = EndUser(
tenant_id=tenant_id,
app_id=app_id,
type=EndUserType.SERVICE_API,
external_user_id=f"ext-{uuid4()}",
name="End User",
session_id=f"session-{uuid4()}",
)
end_user.is_anonymous = False
db_session.add(end_user)
db_session.flush()
return end_user
def _create_app(self, db_session: Session, tenant_id: str, created_by: str) -> App:
app = App(
tenant_id=tenant_id,
name=f"App {uuid4()}",
mode=AppMode.WORKFLOW,
enable_site=False,
enable_api=True,
is_demo=False,
is_public=False,
is_universal=False,
created_by=created_by,
updated_by=created_by,
)
db_session.add(app)
db_session.flush()
return app
def _make_execution(
self, tenant_id: str, app_id: str, created_by_role: CreatorUserRole, created_by: str
) -> WorkflowNodeExecutionModel:
return WorkflowNodeExecutionModel(
tenant_id=tenant_id,
app_id=app_id,
workflow_id=str(uuid4()),
triggered_from=WorkflowNodeExecutionTriggeredFrom.WORKFLOW_RUN,
workflow_run_id=None,
index=1,
predecessor_node_id=None,
node_execution_id=None,
node_id="n1",
node_type="start",
title="Start",
inputs=None,
process_data=None,
outputs=None,
status=WorkflowNodeExecutionStatus.SUCCEEDED,
error=None,
elapsed_time=0.0,
execution_metadata=None,
created_by_role=created_by_role,
created_by=created_by,
)
def test_created_by_account_returns_account_when_role_is_account(self, db_session_with_containers: Session) -> None:
"""created_by_account returns the Account row when role is ACCOUNT."""
account = self._create_account(db_session_with_containers)
app = self._create_app(db_session_with_containers, str(uuid4()), account.id)
execution = self._make_execution(
tenant_id=app.tenant_id,
app_id=app.id,
created_by_role=CreatorUserRole.ACCOUNT,
created_by=account.id,
)
result = execution.created_by_account(session=db_session_with_containers)
assert result is not None
assert result.id == account.id
def test_created_by_account_returns_none_when_role_is_end_user(self, db_session_with_containers: Session) -> None:
"""created_by_account returns None when role is END_USER, even if an Account exists."""
account = self._create_account(db_session_with_containers)
app = self._create_app(db_session_with_containers, str(uuid4()), account.id)
execution = self._make_execution(
tenant_id=app.tenant_id,
app_id=app.id,
created_by_role=CreatorUserRole.END_USER,
created_by=account.id,
)
result = execution.created_by_account(session=db_session_with_containers)
assert result is None
def test_created_by_end_user_returns_end_user_when_role_is_end_user(
self, db_session_with_containers: Session
) -> None:
"""created_by_end_user returns the EndUser row when role is END_USER."""
account = self._create_account(db_session_with_containers)
tenant_id = str(uuid4())
app = self._create_app(db_session_with_containers, tenant_id, account.id)
end_user = self._create_end_user(db_session_with_containers, tenant_id, app.id)
execution = self._make_execution(
tenant_id=tenant_id,
app_id=app.id,
created_by_role=CreatorUserRole.END_USER,
created_by=end_user.id,
)
result = execution.created_by_end_user(session=db_session_with_containers)
assert result is not None
assert result.id == end_user.id
def test_created_by_end_user_returns_none_when_role_is_account(self, db_session_with_containers: Session) -> None:
"""created_by_end_user returns None when role is ACCOUNT, even if an EndUser exists."""
account = self._create_account(db_session_with_containers)
tenant_id = str(uuid4())
app = self._create_app(db_session_with_containers, tenant_id, account.id)
end_user = self._create_end_user(db_session_with_containers, tenant_id, app.id)
execution = self._make_execution(
tenant_id=tenant_id,
app_id=app.id,
created_by_role=CreatorUserRole.ACCOUNT,
created_by=end_user.id,
)
result = execution.created_by_end_user(session=db_session_with_containers)
assert result is None