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.

5.4 KB
Raw Blame
from __future__ import annotations

from pathlib import Path
import shutil
import subprocess
import textwrap

import pytest


def test_client_public_exports_work_with_default_dependencies_only(tmp_path: Path) -> None:
    """Install the package without extras and verify client-facing imports work."""
    uv = shutil.which("uv")
    if uv is None:
        pytest.skip("uv is required to verify default-dependency imports in an isolated environment")

    project_root = Path(__file__).resolve().parents[3]
    venv_path = tmp_path / "client-default-venv"
    python_path = venv_path / "bin" / "python"

    subprocess.run([uv, "venv", str(venv_path)], cwd=project_root, check=True)
    subprocess.run(
        [uv, "pip", "install", "--python", str(python_path), "."],
        cwd=project_root,
        check=True,
    )

    script = textwrap.dedent(
        """
        from __future__ import annotations

        import importlib
        from importlib.metadata import PackageNotFoundError, distribution
        from pathlib import Path
        import re
        import sys
        import tomllib


        def requirement_name(requirement: str) -> str:
            match = re.match(r"\\s*([A-Za-z0-9_.-]+)", requirement)
            if match is None:
                raise AssertionError(f"Cannot parse requirement name: {requirement!r}")
            return match.group(1).lower().replace("_", "-")


        project_root = Path(sys.argv[1])
        pyproject = tomllib.loads((project_root / "pyproject.toml").read_text())
        default_dependency_names = {
            requirement_name(requirement)
            for requirement in pyproject["project"].get("dependencies", [])
        }
        server_dependency_names = {
            requirement_name(requirement)
            for requirement in pyproject["project"].get("optional-dependencies", {}).get("server", [])
        }
        server_only_dependency_names = server_dependency_names - default_dependency_names

        dify_agent = importlib.import_module("dify_agent")
        client_module = importlib.import_module("dify_agent.client")
        protocol_module = importlib.import_module("dify_agent.protocol")
        agent_stub_protocol_module = importlib.import_module("dify_agent.agent_stub.protocol")
        agent_cli_help_module = importlib.import_module("dify_agent.layers._agent_cli_help")
        agent_stub_shell_env_module = importlib.import_module("dify_agent.agent_stub.shell_env")
        shell_module = importlib.import_module("dify_agent.layers.shell")
        execution_context_module = importlib.import_module("dify_agent.layers.execution_context")
        plugin_module = importlib.import_module("dify_agent.layers.dify_plugin")
        output_module = importlib.import_module("dify_agent.layers.output")
        user_prompt_module = importlib.import_module("dify_agent.layers.user_prompt")

        assert dify_agent.Client is client_module.Client
        assert protocol_module.CreateRunRequest is not None
        assert protocol_module.RunComposition is not None
        assert protocol_module.RunLayerSpec is not None
        assert agent_stub_protocol_module.AgentStubConnectRequest is not None
        assert agent_cli_help_module.render_agent_stub_cli_help is not None
        # Exercises the generated JSON snapshot to confirm it ships in the wheel.
        assert "Usage:" in agent_cli_help_module.render_agent_stub_cli_help(("config",))
        assert agent_stub_shell_env_module.build_shell_agent_stub_env is not None
        assert shell_module.DifyShellLayerConfig is not None
        assert execution_context_module.DifyExecutionContextLayerConfig is not None
        tracing = execution_context_module.ApplicationTracingContext(
            run_id="11111111-1111-4111-8111-111111111111",
            invocation_id="22222222-2222-4222-8222-222222222222",
            trace_id="1" * 32,
            parent_span_id="2" * 16,
            session_id="client-session",
            capture_content=False,
        )
        assert execution_context_module.ApplicationTracingContext.model_validate_json(tracing.model_dump_json()) == tracing
        assert plugin_module.DifyPluginLLMLayerConfig is not None
        assert output_module.DifyOutputLayerConfig is not None
        assert user_prompt_module.DifyUserPromptLayerConfig is not None
        assert user_prompt_module.DifyUserPromptFileConfig is not None
        download = user_prompt_module.DifyUserPromptDownloadConfig(
            type="image", transfer_method="local_file", reference="file-1"
        )
        image = user_prompt_module.DifyUserPromptImageConfig(
            filename="image.png", mime_type="image/png", format="png", url="https://example.com/image.png"
        )
        config = user_prompt_module.DifyUserPromptLayerConfig(text="Inspect it.", files=[download, image])
        assert user_prompt_module.DifyUserPromptLayerConfig.model_validate_json(config.model_dump_json()) == config
        assert [file.delivery for file in config.files] == ["download", "multimodal"]

        unexpectedly_installed = []
        for dependency_name in sorted(server_only_dependency_names):
            try:
                distribution(dependency_name)
            except PackageNotFoundError:
                continue
            unexpectedly_installed.append(dependency_name)
        assert unexpectedly_installed == []
        """
    )
    subprocess.run([str(python_path), "-c", script, str(project_root)], cwd=project_root, check=True)