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.

10.1 KB
Raw Blame
"""
Comprehensive unit tests for ConversationService.

This file provides complete test coverage for all ConversationService methods.
Tests are organized by functionality and include edge cases, error handling,
and both positive and negative test scenarios. Database paths use isolated
in-memory SQLite sessions with persisted ORM rows.
"""

from dataclasses import replace
from unittest.mock import MagicMock

import pytest
from sqlalchemy.orm import Session

from libs.datetime_utils import naive_utc_now
from models import Account
from models.agent import (
    AgentConfigVersionKind,
    AgentWorkingResourceStatus,
    AgentWorkspace,
    AgentWorkspaceBinding,
    AgentWorkspaceOwnerType,
)
from models.enums import AppStatus, ConversationFromSource, ConversationStatus
from models.model import App, AppMode, Conversation
from repositories.conversation_lifecycle import retire_conversation
from services import conversation_service
from services.agent.workspace_service import AgentWorkspaceNotFoundError, WorkspaceOwnerScope
from services.conversation_service import ConversationService

TENANT_ID = "11111111-1111-1111-1111-111111111111"
APP_ID = "22222222-2222-2222-2222-222222222222"
ACCOUNT_ID = "33333333-3333-3333-3333-333333333333"
CONVERSATION_ID = "44444444-4444-4444-4444-444444444444"
OTHER_APP_ID = "77777777-7777-7777-7777-777777777777"
OTHER_CONVERSATION_ID = "88888888-8888-8888-8888-888888888888"


def _workspace_binding(binding_id: str) -> AgentWorkspaceBinding:
    return AgentWorkspaceBinding(
        id=binding_id,
        tenant_id=TENANT_ID,
        app_id=APP_ID,
        workspace_id="workspace-1",
        agent_id="agent-1",
        base_home_snapshot_id=None,
        agent_config_version_id="config-1",
        agent_config_version_kind=AgentConfigVersionKind.SNAPSHOT,
        backend_binding_ref="backend-binding-1",
        status=AgentWorkingResourceStatus.ACTIVE,
    )


class ConversationServiceTestDataFactory:
    """
    Factory for creating test ORM objects.

    Provides reusable methods to create consistent model objects for testing
    conversation-related operations.
    """

    @staticmethod
    def create_account(account_id: str = ACCOUNT_ID, **kwargs) -> Account:  # pyrefly: ignore[implicit-any-parameter]
        """
        Create an Account object.

        Args:
            account_id: Unique identifier for the account
            **kwargs: Additional attributes to set on the model

        Returns:
            Account object with specified attributes
        """
        account = Account(name="Test User", email="[email protected]")
        account.id = account_id
        for key, value in kwargs.items():
            setattr(account, key, value)
        return account

    @staticmethod
    def create_app(
        app_id: str = APP_ID,
        tenant_id: str = TENANT_ID,
        name: str = "Test App",
        mode: AppMode = AppMode.CHAT,
        status: AppStatus = AppStatus.NORMAL,
    ) -> App:
        """
        Create an App object.

        Args:
            app_id: Unique identifier for the app
            tenant_id: Tenant/workspace identifier
            name: Display name of the app
            mode: App mode
            status: App lifecycle status

        Returns:
            App object with specified attributes
        """
        return App(
            id=app_id,
            tenant_id=tenant_id,
            name=name,
            mode=mode,
            status=status,
            description="",
            enable_site=False,
            enable_api=False,
            max_active_requests=None,
        )

    @staticmethod
    def create_conversation(
        conversation_id: str = CONVERSATION_ID,
        app_id: str = APP_ID,
        from_source: ConversationFromSource = ConversationFromSource.CONSOLE,
        **kwargs,  # pyrefly: ignore[implicit-any-parameter]
    ) -> Conversation:
        """
        Create a Conversation object.

        Args:
            conversation_id: Unique identifier for the conversation
            app_id: Associated app identifier
            from_source: Source of conversation ('console' or 'api')
            **kwargs: Additional attributes to set on the model

        Returns:
            Conversation object with specified attributes
        """
        conversation = Conversation(
            id=conversation_id,
            app_id=app_id,
            mode=AppMode.CHAT,
            name=kwargs.get("name", "Test Conversation"),
            status=kwargs.get("status", ConversationStatus.NORMAL),
            from_source=from_source,
            from_end_user_id=kwargs.get("from_end_user_id"),
            from_account_id=kwargs.get("from_account_id", ACCOUNT_ID),
            is_deleted=kwargs.get("is_deleted", False),
        )
        conversation._inputs = {}
        conversation.created_at = kwargs.get("created_at", naive_utc_now())
        conversation.updated_at = kwargs.get("updated_at", naive_utc_now())
        for key, value in kwargs.items():
            setattr(conversation, key, value)
        return conversation


@pytest.fixture
def conversation_workspace(sqlite_session: Session) -> tuple[AgentWorkspace, AgentWorkspaceBinding]:
    workspace = AgentWorkspace(
        id="workspace-1",
        tenant_id=TENANT_ID,
        app_id=APP_ID,
        owner_type=AgentWorkspaceOwnerType.CONVERSATION,
        owner_id=CONVERSATION_ID,
        owner_scope_key="root",
        backend_workspace_ref="backend-workspace-1",
        status=AgentWorkingResourceStatus.ACTIVE,
        active_guard=1,
    )
    binding = _workspace_binding("binding-1")
    sqlite_session.add_all([workspace, binding])
    sqlite_session.flush()
    return workspace, binding


def test_retire_leaves_commit_and_cleanup_to_the_caller(
    monkeypatch: pytest.MonkeyPatch,
    sqlite_session: Session,
    conversation_workspace: tuple[AgentWorkspace, AgentWorkspaceBinding],
) -> None:
    workspace, binding = conversation_workspace
    app = ConversationServiceTestDataFactory.create_app()
    conversation = ConversationServiceTestDataFactory.create_conversation()
    conversation.agent_workspace_binding_id = binding.id
    sqlite_session.add(conversation)
    sqlite_session.commit()
    enqueue_collection = MagicMock()
    delete_related = MagicMock()
    monkeypatch.setattr(conversation_service, "enqueue_agent_resource_collection", enqueue_collection)
    monkeypatch.setattr(conversation_service.delete_conversation_related_data, "delay", delete_related)

    retired_workspace_ids = retire_conversation(app_model=app, conversation=conversation, session=sqlite_session)
    sqlite_session.flush()

    assert retired_workspace_ids == (workspace.id,)
    assert conversation.is_deleted is True
    assert binding.status == workspace.status == AgentWorkingResourceStatus.RETIRED
    enqueue_collection.assert_not_called()
    delete_related.assert_not_called()
    sqlite_session.rollback()
    restored = sqlite_session.get(Conversation, CONVERSATION_ID)
    assert restored is not None
    assert restored.is_deleted is False
    assert binding.status == workspace.status == AgentWorkingResourceStatus.ACTIVE


_CONVERSATION_OWNER = WorkspaceOwnerScope(
    tenant_id=TENANT_ID,
    app_id=APP_ID,
    owner_type=AgentWorkspaceOwnerType.CONVERSATION,
    owner_id=CONVERSATION_ID,
)


@pytest.mark.parametrize(
    "scope",
    [
        replace(_CONVERSATION_OWNER, tenant_id="bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"),
        replace(_CONVERSATION_OWNER, app_id=OTHER_APP_ID),
        replace(_CONVERSATION_OWNER, owner_type=AgentWorkspaceOwnerType.WORKFLOW_RUN),
        replace(_CONVERSATION_OWNER, owner_id=OTHER_CONVERSATION_ID),
        replace(_CONVERSATION_OWNER, owner_scope_key="other"),
    ],
    ids=["tenant", "app", "owner type", "owner id", "owner scope"],
)
def test_retire_rejects_participants_owned_by_another_scope(
    scope: WorkspaceOwnerScope,
    sqlite_session: Session,
    conversation_workspace: tuple[AgentWorkspace, AgentWorkspaceBinding],
) -> None:
    workspace, binding = conversation_workspace
    workspace.tenant_id = scope.tenant_id
    workspace.app_id = scope.app_id
    workspace.owner_type = scope.owner_type
    workspace.owner_id = scope.owner_id
    workspace.owner_scope_key = scope.owner_scope_key
    app = ConversationServiceTestDataFactory.create_app()
    conversation = ConversationServiceTestDataFactory.create_conversation()
    conversation.agent_workspace_binding_id = binding.id
    sqlite_session.add(conversation)
    sqlite_session.commit()

    with pytest.raises(AgentWorkspaceNotFoundError, match="participant Binding is unavailable"):
        retire_conversation(app_model=app, conversation=conversation, session=sqlite_session)

    assert conversation.is_deleted is False
    assert binding.status == workspace.status == AgentWorkingResourceStatus.ACTIVE


def test_cleanup_propagates_agent_enqueue_failure_before_conversation_enqueue(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(
        conversation_service, "enqueue_agent_resource_collection", MagicMock(side_effect=RuntimeError("unavailable"))
    )
    delete_related = MagicMock()
    monkeypatch.setattr(conversation_service.delete_conversation_related_data, "delay", delete_related)

    with pytest.raises(RuntimeError, match="unavailable"):
        ConversationService.enqueue_delete_cleanup(
            tenant_id=TENANT_ID, conversation_id=CONVERSATION_ID, retired_workspace_ids=("workspace-1",)
        )

    delete_related.assert_not_called()


def test_cleanup_keeps_soft_deleted_marker_when_dispatch_fails(
    monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
) -> None:
    conversation = ConversationServiceTestDataFactory.create_conversation(is_deleted=True)
    sqlite_session.add(conversation)
    sqlite_session.commit()
    monkeypatch.setattr(
        conversation_service.delete_conversation_related_data,
        "delay",
        MagicMock(side_effect=RuntimeError("broker unavailable")),
    )

    ConversationService.enqueue_delete_cleanup(
        tenant_id=TENANT_ID, conversation_id=conversation.id, retired_workspace_ids=()
    )

    persisted = sqlite_session.get(Conversation, conversation.id)
    assert persisted is not None
    assert persisted.is_deleted is True