chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动
演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
60158935f4
commit
6519682885
15831 files changed
+3063428
No files matched your search
@@ -0,0 +1,51 @@
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from controllers.console.snippets.payloads import SnippetListQuery
|
||||
|
||||
|
||||
def test_snippet_list_query_accepts_tag_id_lists() -> None:
|
||||
first = "11111111-1111-1111-1111-111111111111"
|
||||
second = "22222222-2222-2222-2222-222222222222"
|
||||
|
||||
query = SnippetListQuery.model_validate({"tag_ids": [first, second]})
|
||||
|
||||
assert query.tag_ids == [first, second]
|
||||
|
||||
|
||||
def test_snippet_list_query_returns_none_for_blank_tag_ids() -> None:
|
||||
query = SnippetListQuery.model_validate({"tag_ids": ["", " "]})
|
||||
|
||||
assert query.tag_ids is None
|
||||
|
||||
|
||||
def test_snippet_list_query_rejects_invalid_tag_id() -> None:
|
||||
with pytest.raises(ValidationError, match="Invalid UUID format in tag_ids"):
|
||||
SnippetListQuery.model_validate({"tag_ids": ["not-a-uuid"]})
|
||||
|
||||
|
||||
def test_snippet_list_query_rejects_comma_separated_tag_ids() -> None:
|
||||
first = "11111111-1111-1111-1111-111111111111"
|
||||
second = "22222222-2222-2222-2222-222222222222"
|
||||
|
||||
with pytest.raises(ValidationError, match="Unsupported tag_ids type"):
|
||||
SnippetListQuery.model_validate({"tag_ids": f"{first},{second}"})
|
||||
|
||||
|
||||
def test_snippet_list_query_accepts_creator_id_alias() -> None:
|
||||
creator_id = "1886f96a-5bf0-42bf-961d-8d2129049076"
|
||||
|
||||
query = SnippetListQuery.model_validate({"creator_id": creator_id})
|
||||
|
||||
assert query.creators == [creator_id]
|
||||
|
||||
|
||||
def test_snippet_list_query_normalizes_creator_lists() -> None:
|
||||
query = SnippetListQuery.model_validate({"creators": ["account-1", "", " account-2 "]})
|
||||
|
||||
assert query.creators == ["account-1", "account-2"]
|
||||
|
||||
|
||||
def test_snippet_list_query_rejects_unsupported_list_value_type() -> None:
|
||||
with pytest.raises(ValidationError, match="Unsupported creators type"):
|
||||
SnippetListQuery.model_validate({"creators": {"bad": "value"}})
|
||||
+620
@@ -0,0 +1,620 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from inspect import unwrap
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
from flask import Flask
|
||||
from sqlalchemy.orm import Session
|
||||
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 models.workflow import Workflow
|
||||
from tests.helpers.unit.controllers.error_body import raised_error
|
||||
from tests.helpers.unit.model_factories import make_account
|
||||
|
||||
|
||||
def _account(account_id: str = "account-1") -> Account:
|
||||
return make_account(
|
||||
account_id=account_id,
|
||||
name="Test User",
|
||||
email=f"{account_id}@example.com",
|
||||
role=TenantAccountRole.EDITOR,
|
||||
)
|
||||
|
||||
|
||||
def _snippet(**overrides) -> CustomizedSnippet:
|
||||
data = {
|
||||
"id": "snippet-1",
|
||||
"tenant_id": "tenant-1",
|
||||
"name": "Snippet",
|
||||
"description": "Description",
|
||||
"type": "node",
|
||||
"created_by": "account-1",
|
||||
}
|
||||
data.update(overrides)
|
||||
return CustomizedSnippet(**data)
|
||||
|
||||
|
||||
def _workflow(**overrides) -> Workflow:
|
||||
workflow = Workflow.new(
|
||||
tenant_id="tenant-1",
|
||||
app_id="snippet-1",
|
||||
type="workflow",
|
||||
version="2024-01-01 00:00:00",
|
||||
graph=json.dumps({"nodes": [], "edges": []}),
|
||||
features="{}",
|
||||
created_by="account-1",
|
||||
environment_variables=[],
|
||||
conversation_variables=[],
|
||||
rag_pipeline_variables=[],
|
||||
)
|
||||
workflow.id = "workflow-1"
|
||||
for name, value in overrides.items():
|
||||
setattr(workflow, name, value)
|
||||
return workflow
|
||||
|
||||
|
||||
def test_get_snippet_requires_snippet_id(app):
|
||||
@snippet_workflow_module.get_snippet
|
||||
def view(**kwargs):
|
||||
return kwargs
|
||||
|
||||
with app.test_request_context("/snippets"):
|
||||
with pytest.raises(ValueError, match="missing snippet_id"):
|
||||
view()
|
||||
|
||||
|
||||
def test_get_snippet_injects_resolved_snippet(app: Flask, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
snippet = _snippet()
|
||||
|
||||
@snippet_workflow_module.get_snippet
|
||||
def view(**kwargs):
|
||||
return kwargs["snippet"]
|
||||
|
||||
monkeypatch.setattr(
|
||||
snippet_workflow_module,
|
||||
"current_account_with_tenant",
|
||||
lambda: (_account("account-1"), "tenant-1"),
|
||||
)
|
||||
monkeypatch.setattr(snippet_workflow_module.SnippetService, "get_snippet_by_id", Mock(return_value=snippet))
|
||||
|
||||
with app.test_request_context("/snippets/snippet-1"):
|
||||
result = view(snippet_id="snippet-1")
|
||||
|
||||
assert result is snippet
|
||||
|
||||
|
||||
def test_get_snippet_raises_not_found_when_snippet_missing(app: Flask, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
@snippet_workflow_module.get_snippet
|
||||
def view(**kwargs):
|
||||
return kwargs
|
||||
|
||||
monkeypatch.setattr(
|
||||
snippet_workflow_module,
|
||||
"current_account_with_tenant",
|
||||
lambda: (_account("account-1"), "tenant-1"),
|
||||
)
|
||||
monkeypatch.setattr(snippet_workflow_module.SnippetService, "get_snippet_by_id", Mock(return_value=None))
|
||||
|
||||
with app.test_request_context("/snippets/snippet-1"):
|
||||
with pytest.raises(NotFound, match="Snippet not found"):
|
||||
view(snippet_id="snippet-1")
|
||||
|
||||
|
||||
def test_draft_workflow_get_raises_when_missing(
|
||||
app: Flask, monkeypatch: pytest.MonkeyPatch, unbound_session: Session
|
||||
) -> None:
|
||||
snippet = _snippet()
|
||||
monkeypatch.setattr(snippet_workflow_module.SnippetService, "get_draft_workflow", Mock(return_value=None))
|
||||
|
||||
api = snippet_workflow_module.SnippetDraftWorkflowApi()
|
||||
handler = unwrap(api.get)
|
||||
|
||||
with app.test_request_context("/snippets/snippet-1/workflows/draft"):
|
||||
with pytest.raises(snippet_workflow_module.DraftWorkflowNotExist):
|
||||
handler(api, unbound_session, snippet=snippet)
|
||||
|
||||
|
||||
def test_draft_workflow_get_uses_session_aware_response_source(
|
||||
app: Flask, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
|
||||
) -> None:
|
||||
workflow = _workflow(updated_by="account-2")
|
||||
sqlite_session.add_all([_account(), _account("account-2")])
|
||||
sqlite_session.commit()
|
||||
snippet = _snippet()
|
||||
monkeypatch.setattr(snippet_workflow_module.SnippetService, "get_draft_workflow", Mock(return_value=workflow))
|
||||
monkeypatch.setattr(
|
||||
snippet_workflow_module.WorkflowAgentPublishService,
|
||||
"project_draft_bindings_to_graph",
|
||||
Mock(return_value=workflow.graph_dict),
|
||||
)
|
||||
|
||||
api = snippet_workflow_module.SnippetDraftWorkflowApi()
|
||||
handler = unwrap(api.get)
|
||||
|
||||
with app.test_request_context("/snippets/snippet-1/workflows/draft"):
|
||||
response = handler(api, sqlite_session, snippet=snippet)
|
||||
|
||||
assert response["id"] == "workflow-1"
|
||||
assert response["created_by"]["id"] == "account-1"
|
||||
assert response["updated_by"]["id"] == "account-2"
|
||||
assert response["tool_published"] is False
|
||||
|
||||
|
||||
def test_draft_workflow_post_returns_400_for_invalid_graph(app: Flask, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
user = _account("account-1")
|
||||
snippet = _snippet()
|
||||
sync_draft_workflow = Mock(side_effect=ValueError("invalid graph"))
|
||||
monkeypatch.setattr(snippet_workflow_module.SnippetService, "sync_draft_workflow", sync_draft_workflow)
|
||||
|
||||
api = snippet_workflow_module.SnippetDraftWorkflowApi()
|
||||
handler = unwrap(api.post)
|
||||
|
||||
with app.test_request_context(
|
||||
"/snippets/snippet-1/workflows/draft",
|
||||
method="POST",
|
||||
json={"graph": {"nodes": [], "edges": []}, "hash": "hash-1"},
|
||||
):
|
||||
response, status_code = raised_error(
|
||||
lambda: handler(
|
||||
api,
|
||||
snippet_workflow_module.SnippetDraftSyncPayload.model_validate(
|
||||
{"graph": {"nodes": [], "edges": []}, "hash": "hash-1"}
|
||||
),
|
||||
user,
|
||||
snippet,
|
||||
)
|
||||
)
|
||||
|
||||
assert status_code == 400
|
||||
assert response == {"code": "invalid_param", "message": "invalid graph"}
|
||||
|
||||
|
||||
def test_draft_config_returns_parallel_depth_limit(app) -> None:
|
||||
api = snippet_workflow_module.SnippetDraftConfigApi()
|
||||
handler = unwrap(api.get)
|
||||
|
||||
with app.test_request_context("/snippets/snippet-1/workflows/draft/config"):
|
||||
assert handler(api, snippet=_snippet()) == {"parallel_depth_limit": 3}
|
||||
|
||||
|
||||
def test_published_workflow_get_returns_none_when_not_published(app, unbound_session: Session) -> None:
|
||||
api = snippet_workflow_module.SnippetPublishedWorkflowApi()
|
||||
handler = unwrap(api.get)
|
||||
|
||||
with app.test_request_context("/snippets/snippet-1/workflows/publish"):
|
||||
assert handler(api, unbound_session, snippet=_snippet(is_published=False)) is None
|
||||
|
||||
|
||||
def test_published_workflow_get_uses_session_aware_response_source(
|
||||
app: Flask, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
|
||||
) -> None:
|
||||
workflow = _workflow(updated_by="account-2")
|
||||
sqlite_session.add_all([_account(), _account("account-2")])
|
||||
sqlite_session.commit()
|
||||
snippet = _snippet(is_published=True)
|
||||
monkeypatch.setattr(snippet_workflow_module.SnippetService, "get_published_workflow", Mock(return_value=workflow))
|
||||
|
||||
api = snippet_workflow_module.SnippetPublishedWorkflowApi()
|
||||
handler = unwrap(api.get)
|
||||
|
||||
with app.test_request_context("/snippets/snippet-1/workflows/publish"):
|
||||
response = handler(api, sqlite_session, snippet=snippet)
|
||||
|
||||
assert response["id"] == "workflow-1"
|
||||
assert response["created_by"]["id"] == "account-1"
|
||||
assert response["updated_by"]["id"] == "account-2"
|
||||
assert response["tool_published"] is False
|
||||
|
||||
|
||||
def test_published_workflow_post_returns_400_when_publish_fails(
|
||||
app: Flask,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sqlite_session: Session,
|
||||
) -> None:
|
||||
user = _account("account-1")
|
||||
snippet = _snippet()
|
||||
sqlite_session.add(snippet)
|
||||
sqlite_session.commit()
|
||||
|
||||
def fail_publish(*, session: Session, snippet: CustomizedSnippet, account: Account):
|
||||
snippet.name = "Uncommitted name"
|
||||
session.add(snippet)
|
||||
raise ValueError("No valid workflow found.")
|
||||
|
||||
monkeypatch.setattr(snippet_workflow_module.SnippetService, "publish_workflow", Mock(side_effect=fail_publish))
|
||||
|
||||
api = snippet_workflow_module.SnippetPublishedWorkflowApi()
|
||||
handler = unwrap(api.post)
|
||||
|
||||
with app.test_request_context("/snippets/snippet-1/workflows/publish", method="POST", json={}):
|
||||
response, status_code = raised_error(lambda: handler(api, sqlite_session, user, snippet))
|
||||
|
||||
assert status_code == 400
|
||||
assert response == {"code": "invalid_param", "message": "No valid workflow found."}
|
||||
sqlite_session.refresh(snippet)
|
||||
assert snippet.name == "Snippet"
|
||||
|
||||
|
||||
def test_published_workflow_post_returns_success(
|
||||
app: Flask,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sqlite_session: Session,
|
||||
) -> None:
|
||||
user = _account("account-1")
|
||||
snippet = _snippet()
|
||||
sqlite_session.add(snippet)
|
||||
sqlite_session.commit()
|
||||
workflow = _workflow()
|
||||
monkeypatch.setattr(snippet_workflow_module.SnippetService, "publish_workflow", Mock(return_value=workflow))
|
||||
|
||||
api = snippet_workflow_module.SnippetPublishedWorkflowApi()
|
||||
handler = unwrap(api.post)
|
||||
with app.test_request_context("/snippets/snippet-1/workflows/publish", method="POST", json={}):
|
||||
response = handler(api, sqlite_session, user, snippet)
|
||||
|
||||
assert response["result"] == "success"
|
||||
|
||||
|
||||
def test_default_block_configs_delegates_to_service(app: Flask, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
get_default_block_configs = Mock(return_value=[{"type": "llm"}])
|
||||
monkeypatch.setattr(snippet_workflow_module.SnippetService, "get_default_block_configs", get_default_block_configs)
|
||||
|
||||
api = snippet_workflow_module.SnippetDefaultBlockConfigsApi()
|
||||
handler = unwrap(api.get)
|
||||
|
||||
with app.test_request_context("/snippets/snippet-1/workflows/default-workflow-block-configs"):
|
||||
result = handler(api, snippet=_snippet())
|
||||
|
||||
assert result == [{"type": "llm"}]
|
||||
get_default_block_configs.assert_called_once()
|
||||
|
||||
|
||||
def test_list_published_snippet_workflows_includes_input_fields(
|
||||
app: Flask,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sqlite_session: Session,
|
||||
) -> None:
|
||||
workflow = _workflow()
|
||||
input_fields = [{"variable": "query", "type": "text"}]
|
||||
snippet = _snippet(input_fields=json.dumps(input_fields))
|
||||
|
||||
monkeypatch.setattr(
|
||||
snippet_workflow_module.SnippetService, "get_all_published_workflows", Mock(return_value=([workflow], False))
|
||||
)
|
||||
|
||||
api = snippet_workflow_module.SnippetPublishedAllWorkflowApi()
|
||||
handler = unwrap(api.get)
|
||||
|
||||
with app.test_request_context("/snippets/snippet-1/workflows?page=1&limit=20"):
|
||||
response = handler(
|
||||
api,
|
||||
snippet_workflow_module.SnippetWorkflowListQuery.model_validate({"page": 1, "limit": 20}),
|
||||
sqlite_session,
|
||||
snippet=snippet,
|
||||
)
|
||||
|
||||
assert response["items"][0]["input_fields"] == input_fields
|
||||
|
||||
|
||||
def test_restore_published_snippet_workflow_to_draft_success(app: Flask, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
workflow = _workflow(updated_at=None)
|
||||
user = _account("account-1")
|
||||
snippet = _snippet()
|
||||
|
||||
monkeypatch.setattr(
|
||||
snippet_workflow_module.SnippetService, "restore_published_workflow_to_draft", Mock(return_value=workflow)
|
||||
)
|
||||
|
||||
api = snippet_workflow_module.SnippetDraftWorkflowRestoreApi()
|
||||
handler = unwrap(api.post)
|
||||
|
||||
with app.test_request_context(
|
||||
"/snippets/snippet-1/workflows/published-workflow/restore",
|
||||
method="POST",
|
||||
):
|
||||
response = handler(api, user, snippet, workflow_id="published-workflow")
|
||||
|
||||
assert response["result"] == "success"
|
||||
assert response["hash"] == workflow.unique_hash
|
||||
|
||||
|
||||
def test_restore_published_snippet_workflow_to_draft_not_found(app: Flask, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
user = _account("account-1")
|
||||
snippet = _snippet()
|
||||
|
||||
monkeypatch.setattr(
|
||||
snippet_workflow_module.SnippetService,
|
||||
"restore_published_workflow_to_draft",
|
||||
Mock(side_effect=snippet_workflow_module.WorkflowNotFoundError("Workflow not found")),
|
||||
)
|
||||
|
||||
api = snippet_workflow_module.SnippetDraftWorkflowRestoreApi()
|
||||
handler = unwrap(api.post)
|
||||
|
||||
with app.test_request_context(
|
||||
"/snippets/snippet-1/workflows/published-workflow/restore",
|
||||
method="POST",
|
||||
):
|
||||
with pytest.raises(NotFound):
|
||||
handler(api, user, snippet, workflow_id="published-workflow")
|
||||
|
||||
|
||||
def test_restore_published_snippet_workflow_to_draft_returns_400_for_draft_source(
|
||||
app, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
user = _account("account-1")
|
||||
snippet = _snippet()
|
||||
|
||||
monkeypatch.setattr(
|
||||
snippet_workflow_module.SnippetService,
|
||||
"restore_published_workflow_to_draft",
|
||||
Mock(side_effect=snippet_workflow_module.IsDraftWorkflowError("source workflow must be published")),
|
||||
)
|
||||
|
||||
api = snippet_workflow_module.SnippetDraftWorkflowRestoreApi()
|
||||
handler = unwrap(api.post)
|
||||
|
||||
with app.test_request_context(
|
||||
"/snippets/snippet-1/workflows/draft-workflow/restore",
|
||||
method="POST",
|
||||
):
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
handler(api, user, snippet, workflow_id="draft-workflow")
|
||||
|
||||
assert exc.value.code == 400
|
||||
assert exc.value.description == snippet_workflow_module.RESTORE_SOURCE_WORKFLOW_MUST_BE_PUBLISHED_MESSAGE
|
||||
|
||||
|
||||
def test_restore_published_snippet_workflow_to_draft_returns_400_for_invalid_graph(
|
||||
app, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
user = _account("account-1")
|
||||
snippet = _snippet()
|
||||
|
||||
monkeypatch.setattr(
|
||||
snippet_workflow_module.SnippetService,
|
||||
"restore_published_workflow_to_draft",
|
||||
Mock(side_effect=ValueError("invalid snippet workflow graph")),
|
||||
)
|
||||
|
||||
api = snippet_workflow_module.SnippetDraftWorkflowRestoreApi()
|
||||
handler = unwrap(api.post)
|
||||
|
||||
with app.test_request_context(
|
||||
"/snippets/snippet-1/workflows/published-workflow/restore",
|
||||
method="POST",
|
||||
):
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
handler(api, user, snippet, workflow_id="published-workflow")
|
||||
|
||||
assert exc.value.code == 400
|
||||
assert exc.value.description == "invalid snippet workflow graph"
|
||||
|
||||
|
||||
def test_update_published_snippet_workflow_returns_updated_workflow(
|
||||
app: Flask,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sqlite_session: Session,
|
||||
) -> None:
|
||||
workflow = _workflow(marked_name="v1", marked_comment="first version")
|
||||
user = _account("account-1")
|
||||
input_fields = [{"variable": "query", "type": "text"}]
|
||||
snippet = _snippet(input_fields=json.dumps(input_fields))
|
||||
sqlite_session.add(snippet)
|
||||
sqlite_session.commit()
|
||||
|
||||
def update_persisted_snippet(*, session: Session, snippet: CustomizedSnippet, **_kwargs):
|
||||
merged_snippet = session.merge(snippet)
|
||||
merged_snippet.description = "Updated in transaction"
|
||||
return workflow
|
||||
|
||||
update_workflow = Mock(side_effect=update_persisted_snippet)
|
||||
monkeypatch.setattr(snippet_workflow_module.SnippetService, "update_workflow", update_workflow)
|
||||
|
||||
api = snippet_workflow_module.SnippetWorkflowByIdApi()
|
||||
handler = unwrap(api.patch)
|
||||
|
||||
with app.test_request_context(
|
||||
"/snippets/snippet-1/workflows/workflow-1",
|
||||
method="PATCH",
|
||||
json={"marked_name": "v1", "marked_comment": "first version"},
|
||||
):
|
||||
response = handler(
|
||||
api,
|
||||
snippet_workflow_module.WorkflowUpdatePayload.model_validate(
|
||||
{"marked_name": "v1", "marked_comment": "first version"}
|
||||
),
|
||||
sqlite_session,
|
||||
user,
|
||||
snippet,
|
||||
workflow_id="workflow-1",
|
||||
)
|
||||
|
||||
update_workflow.assert_called_once()
|
||||
update_call = update_workflow.call_args.kwargs
|
||||
assert isinstance(update_call["session"], Session)
|
||||
assert update_call["snippet"] is snippet
|
||||
assert update_call["workflow_id"] == "workflow-1"
|
||||
assert update_call["account"] is user
|
||||
assert update_call["data"] == {"marked_name": "v1", "marked_comment": "first version"}
|
||||
assert response["marked_name"] == "v1"
|
||||
assert response["marked_comment"] == "first version"
|
||||
assert response["input_fields"] == input_fields
|
||||
sqlite_session.refresh(snippet)
|
||||
assert snippet.description == "Updated in transaction"
|
||||
|
||||
|
||||
def test_update_published_snippet_workflow_returns_400_when_no_fields(app: Flask, unbound_session: Session) -> None:
|
||||
api = snippet_workflow_module.SnippetWorkflowByIdApi()
|
||||
handler = unwrap(api.patch)
|
||||
|
||||
with app.test_request_context("/snippets/snippet-1/workflows/workflow-1", method="PATCH", json={}):
|
||||
response, status_code = raised_error(
|
||||
lambda: handler(
|
||||
api,
|
||||
snippet_workflow_module.WorkflowUpdatePayload(),
|
||||
unbound_session,
|
||||
_account("account-1"),
|
||||
_snippet(),
|
||||
workflow_id="workflow-1",
|
||||
)
|
||||
)
|
||||
|
||||
assert status_code == 400
|
||||
assert response == {"code": "invalid_param", "message": "No valid fields to update"}
|
||||
|
||||
|
||||
def test_update_published_snippet_workflow_raises_not_found(
|
||||
app: Flask,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sqlite_session: Session,
|
||||
) -> None:
|
||||
user = _account("account-1")
|
||||
snippet = _snippet()
|
||||
sqlite_session.add(snippet)
|
||||
sqlite_session.commit()
|
||||
|
||||
def update_missing_workflow(*, session: Session, snippet: CustomizedSnippet, **_kwargs):
|
||||
merged_snippet = session.merge(snippet)
|
||||
merged_snippet.name = "Rolled back name"
|
||||
|
||||
monkeypatch.setattr(
|
||||
snippet_workflow_module.SnippetService, "update_workflow", Mock(side_effect=update_missing_workflow)
|
||||
)
|
||||
|
||||
api = snippet_workflow_module.SnippetWorkflowByIdApi()
|
||||
handler = unwrap(api.patch)
|
||||
|
||||
with app.test_request_context(
|
||||
"/snippets/snippet-1/workflows/missing-workflow",
|
||||
method="PATCH",
|
||||
json={"marked_name": "v1"},
|
||||
):
|
||||
with pytest.raises(NotFound, match="Workflow not found"):
|
||||
handler(
|
||||
api,
|
||||
snippet_workflow_module.WorkflowUpdatePayload.model_validate({"marked_name": "v1"}),
|
||||
sqlite_session,
|
||||
user,
|
||||
snippet,
|
||||
workflow_id="missing-workflow",
|
||||
)
|
||||
|
||||
sqlite_session.rollback()
|
||||
sqlite_session.refresh(snippet)
|
||||
assert snippet.name == "Snippet"
|
||||
|
||||
|
||||
def test_delete_published_snippet_workflow_succeeds(app: Flask, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
snippet = _snippet()
|
||||
delete_workflow = Mock(return_value=True)
|
||||
monkeypatch.setattr(snippet_workflow_module.SnippetService, "delete_workflow", delete_workflow)
|
||||
|
||||
api = snippet_workflow_module.SnippetWorkflowByIdApi()
|
||||
handler = unwrap(api.delete)
|
||||
|
||||
with app.test_request_context("/snippets/snippet-1/workflows/workflow-1", method="DELETE"):
|
||||
response, status_code = handler(api, snippet, workflow_id="workflow-1")
|
||||
|
||||
assert status_code == 204
|
||||
assert response is None
|
||||
delete_workflow.assert_called_once()
|
||||
delete_call = delete_workflow.call_args.kwargs
|
||||
assert isinstance(delete_call["session"], Session)
|
||||
assert delete_call["snippet"] is snippet
|
||||
assert delete_call["workflow_id"] == "workflow-1"
|
||||
|
||||
|
||||
def test_delete_published_snippet_workflow_raises_not_found(app: Flask, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
def delete_missing_workflow(**_kwargs):
|
||||
raise ValueError("Workflow with ID missing-workflow not found")
|
||||
|
||||
monkeypatch.setattr(
|
||||
snippet_workflow_module.SnippetService, "delete_workflow", Mock(side_effect=delete_missing_workflow)
|
||||
)
|
||||
|
||||
api = snippet_workflow_module.SnippetWorkflowByIdApi()
|
||||
handler = unwrap(api.delete)
|
||||
|
||||
with app.test_request_context("/snippets/snippet-1/workflows/missing-workflow", method="DELETE"):
|
||||
with pytest.raises(NotFound):
|
||||
handler(api, _snippet(), workflow_id="missing-workflow")
|
||||
|
||||
|
||||
def test_delete_published_snippet_workflow_raises_bad_request_when_in_use(
|
||||
app: Flask, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
def delete_active_workflow(**_kwargs):
|
||||
raise snippet_workflow_module.WorkflowInUseError("Cannot delete workflow that is currently in use")
|
||||
|
||||
monkeypatch.setattr(
|
||||
snippet_workflow_module.SnippetService, "delete_workflow", Mock(side_effect=delete_active_workflow)
|
||||
)
|
||||
|
||||
api = snippet_workflow_module.SnippetWorkflowByIdApi()
|
||||
handler = unwrap(api.delete)
|
||||
|
||||
with app.test_request_context("/snippets/snippet-1/workflows/workflow-1", method="DELETE"):
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
handler(api, _snippet(), workflow_id="workflow-1")
|
||||
|
||||
assert exc_info.value.code == 400
|
||||
|
||||
|
||||
def test_workflow_run_detail_raises_not_found_when_run_missing(
|
||||
app: Flask, monkeypatch: pytest.MonkeyPatch, sqlite_session: Session
|
||||
) -> None:
|
||||
snippet = _snippet()
|
||||
monkeypatch.setattr(snippet_workflow_module.SnippetService, "get_snippet_workflow_run", Mock(return_value=None))
|
||||
|
||||
api = snippet_workflow_module.SnippetWorkflowRunDetailApi()
|
||||
handler = unwrap(api.get)
|
||||
|
||||
with app.test_request_context("/snippets/snippet-1/workflow-runs/run-1"):
|
||||
with pytest.raises(NotFound, match="Workflow run not found"):
|
||||
handler(api, sqlite_session, snippet=snippet, run_id="run-1")
|
||||
|
||||
|
||||
def test_draft_node_last_run_raises_not_found_when_execution_missing(
|
||||
app: Flask, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
snippet = _snippet()
|
||||
draft_workflow = _workflow(version=Workflow.VERSION_DRAFT)
|
||||
monkeypatch.setattr(snippet_workflow_module.SnippetService, "get_draft_workflow", Mock(return_value=draft_workflow))
|
||||
monkeypatch.setattr(snippet_workflow_module.SnippetService, "get_snippet_node_last_run", Mock(return_value=None))
|
||||
|
||||
api = snippet_workflow_module.SnippetDraftNodeLastRunApi()
|
||||
handler = unwrap(api.get)
|
||||
|
||||
with app.test_request_context("/snippets/snippet-1/workflows/draft/nodes/llm-1/last-run"):
|
||||
with pytest.raises(NotFound, match="Node last run not found"):
|
||||
handler(api, snippet=snippet, node_id="llm-1")
|
||||
|
||||
|
||||
def test_workflow_task_stop_uses_snippet_owner_scope(app: Flask, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
stop_task = Mock()
|
||||
monkeypatch.setattr(
|
||||
snippet_workflow_module.AppTaskService,
|
||||
"stop_workflow_task",
|
||||
stop_task,
|
||||
)
|
||||
|
||||
api = snippet_workflow_module.SnippetWorkflowTaskStopApi()
|
||||
handler = unwrap(api.post)
|
||||
|
||||
with app.test_request_context("/snippets/snippet-1/workflow-runs/tasks/task-1/stop", method="POST"):
|
||||
result = handler(api, snippet=_snippet(), task_id="task-1")
|
||||
|
||||
assert result == {"result": "success"}
|
||||
stop_task.assert_called_once_with(
|
||||
tenant_id="tenant-1",
|
||||
app_id="snippet-1",
|
||||
task_id="task-1",
|
||||
app_mode=snippet_workflow_module.AppMode.WORKFLOW,
|
||||
owner=None,
|
||||
)
|
||||
+327
@@ -0,0 +1,327 @@
|
||||
import json
|
||||
from inspect import unwrap
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
from flask import Flask
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from controllers.console.snippets import snippet_workflow_draft_variable as module
|
||||
from graphon.variables import StringSegment, StringVariable
|
||||
from models.account import Account, AccountStatus
|
||||
from models.snippet import CustomizedSnippet
|
||||
from models.workflow import Workflow, WorkflowDraftVariable
|
||||
|
||||
|
||||
def _make_account() -> Account:
|
||||
account = Account(
|
||||
name="tester",
|
||||
email="tester@example.com",
|
||||
status=AccountStatus.ACTIVE,
|
||||
)
|
||||
account.id = "user-1" # type: ignore[assignment]
|
||||
return account
|
||||
|
||||
|
||||
def _make_snippet(snippet_id: str = "snippet-1") -> CustomizedSnippet:
|
||||
return CustomizedSnippet(
|
||||
id=snippet_id,
|
||||
tenant_id="tenant-1",
|
||||
name="Snippet",
|
||||
description="Description",
|
||||
type="node",
|
||||
created_by="user-1",
|
||||
)
|
||||
|
||||
|
||||
def _make_workflow(*, environment_variables: list[StringVariable] | None = None) -> Workflow:
|
||||
workflow = Workflow.new(
|
||||
tenant_id="tenant-1",
|
||||
app_id="snippet-1",
|
||||
type="workflow",
|
||||
version=Workflow.VERSION_DRAFT,
|
||||
graph=json.dumps({"nodes": [], "edges": []}),
|
||||
features="{}",
|
||||
created_by="user-1",
|
||||
environment_variables=environment_variables or [],
|
||||
conversation_variables=[],
|
||||
rag_pipeline_variables=[],
|
||||
)
|
||||
workflow.id = "workflow-1"
|
||||
return workflow
|
||||
|
||||
|
||||
def _make_node_variable(
|
||||
variable_id: str,
|
||||
*,
|
||||
app_id: str = "snippet-1",
|
||||
user_id: str = "user-1",
|
||||
node_id: str = "llm-1",
|
||||
name: str | None = None,
|
||||
node_execution_id: str | None = "execution-1",
|
||||
) -> WorkflowDraftVariable:
|
||||
"""Create a valid node variable for persisted controller tests."""
|
||||
variable = WorkflowDraftVariable.new_node_variable(
|
||||
app_id=app_id,
|
||||
user_id=user_id,
|
||||
node_id=node_id,
|
||||
name=name or variable_id,
|
||||
value=StringSegment(value=f"value-{variable_id}"),
|
||||
node_execution_id=node_execution_id or "execution-1",
|
||||
)
|
||||
variable.id = variable_id
|
||||
variable.node_execution_id = node_execution_id
|
||||
return variable
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app() -> Flask:
|
||||
app = Flask("test_snippet_workflow_draft_variable")
|
||||
app.config["TESTING"] = True
|
||||
return app
|
||||
|
||||
|
||||
def _persist_variables(sqlite_session: Session, *variables: WorkflowDraftVariable) -> None:
|
||||
sqlite_session.add_all(variables)
|
||||
sqlite_session.commit()
|
||||
|
||||
|
||||
def _variable_ids(session: Session) -> set[str]:
|
||||
return set(session.scalars(select(WorkflowDraftVariable.id)))
|
||||
|
||||
|
||||
def test_ensure_snippet_draft_variable_row_allowed_rejects_system_variable() -> None:
|
||||
variable = WorkflowDraftVariable.new_sys_variable(
|
||||
app_id="snippet-1",
|
||||
user_id="user-1",
|
||||
name="query",
|
||||
value=StringSegment(value="query"),
|
||||
node_execution_id="execution-1",
|
||||
editable=True,
|
||||
)
|
||||
|
||||
with pytest.raises(module.NotFoundError, match="variable not found"):
|
||||
module._ensure_snippet_draft_variable_row_allowed(variable=variable, variable_id="var-1")
|
||||
|
||||
|
||||
def test_ensure_snippet_draft_variable_row_allowed_rejects_conversation_variable() -> None:
|
||||
variable = WorkflowDraftVariable.new_conversation_variable(
|
||||
app_id="snippet-1",
|
||||
user_id="user-1",
|
||||
name="conversation-name",
|
||||
value=StringSegment(value="value"),
|
||||
)
|
||||
|
||||
with pytest.raises(module.NotFoundError, match="variable not found"):
|
||||
module._ensure_snippet_draft_variable_row_allowed(variable=variable, variable_id="var-1")
|
||||
|
||||
|
||||
def test_ensure_snippet_draft_variable_row_allowed_accepts_canvas_node_variable() -> None:
|
||||
variable = _make_node_variable("var-1")
|
||||
|
||||
module._ensure_snippet_draft_variable_row_allowed(variable=variable, variable_id="var-1")
|
||||
|
||||
|
||||
def test_conversation_variables_returns_empty_list(app: Flask) -> None:
|
||||
api = module.SnippetConversationVariableCollectionApi()
|
||||
handler = unwrap(api.get)
|
||||
|
||||
with app.test_request_context("/"):
|
||||
result = handler(api, _make_account(), snippet=_make_snippet())
|
||||
|
||||
assert result == {"items": []}
|
||||
|
||||
|
||||
def test_system_variables_returns_empty_list(app: Flask) -> None:
|
||||
api = module.SnippetSystemVariableCollectionApi()
|
||||
handler = unwrap(api.get)
|
||||
|
||||
with app.test_request_context("/"):
|
||||
result = handler(api, _make_account(), snippet=_make_snippet())
|
||||
|
||||
assert result == {"items": []}
|
||||
|
||||
|
||||
def test_delete_variable_collection_deletes_only_current_user_variables(
|
||||
app: Flask,
|
||||
sqlite_session: Session,
|
||||
) -> None:
|
||||
matching = _make_node_variable("matching", name="matching")
|
||||
matching_second = _make_node_variable("matching-second", node_id="tool-1", name="matching-second")
|
||||
other_user = _make_node_variable("other-user", user_id="user-2", name="other-user")
|
||||
other_snippet = _make_node_variable("other-snippet", app_id="snippet-2", name="other-snippet")
|
||||
_persist_variables(sqlite_session, matching, matching_second, other_user, other_snippet)
|
||||
api = module.SnippetWorkflowVariableCollectionApi()
|
||||
handler = unwrap(api.delete)
|
||||
|
||||
with app.test_request_context("/", method="DELETE"):
|
||||
response = handler(api, sqlite_session, _make_account(), snippet=_make_snippet())
|
||||
|
||||
assert response.status_code == 204
|
||||
assert _variable_ids(sqlite_session) == {other_user.id, other_snippet.id}
|
||||
|
||||
|
||||
def test_variable_collection_get_raises_when_draft_workflow_missing(
|
||||
app: Flask,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sqlite_session: Session,
|
||||
) -> None:
|
||||
monkeypatch.setattr(module.SnippetService, "get_draft_workflow", Mock(return_value=None))
|
||||
|
||||
api = module.SnippetWorkflowVariableCollectionApi()
|
||||
handler = unwrap(api.get)
|
||||
|
||||
with app.test_request_context("/"):
|
||||
with pytest.raises(module.DraftWorkflowNotExist):
|
||||
handler(
|
||||
api,
|
||||
sqlite_session,
|
||||
module.WorkflowDraftVariableListQuery(page=1, limit=20),
|
||||
_make_account(),
|
||||
snippet=_make_snippet(),
|
||||
)
|
||||
|
||||
|
||||
def test_node_variable_collection_get_lists_persisted_node_variables(
|
||||
app: Flask,
|
||||
sqlite_session: Session,
|
||||
) -> None:
|
||||
matching = _make_node_variable("matching", name="matching")
|
||||
other_node = _make_node_variable("other-node", node_id="tool-1", name="other-node")
|
||||
other_user = _make_node_variable("other-user", user_id="user-2", name="other-user")
|
||||
other_snippet = _make_node_variable("other-snippet", app_id="snippet-2", name="other-snippet")
|
||||
_persist_variables(sqlite_session, matching, other_node, other_user, other_snippet)
|
||||
api = module.SnippetNodeVariableCollectionApi()
|
||||
handler = unwrap(api.get)
|
||||
|
||||
with app.test_request_context("/"):
|
||||
result = handler(api, sqlite_session, _make_account(), snippet=_make_snippet(), node_id="llm-1")
|
||||
|
||||
assert [variable["id"] for variable in result["items"]] == [matching.id]
|
||||
|
||||
|
||||
def test_node_variable_collection_delete_deletes_only_requested_node_variables(
|
||||
app: Flask,
|
||||
sqlite_session: Session,
|
||||
) -> None:
|
||||
matching = _make_node_variable("matching", name="matching")
|
||||
matching_second = _make_node_variable("matching-second", name="matching-second")
|
||||
other_node = _make_node_variable("other-node", node_id="tool-1", name="other-node")
|
||||
other_user = _make_node_variable("other-user", user_id="user-2", name="other-user")
|
||||
_persist_variables(sqlite_session, matching, matching_second, other_node, other_user)
|
||||
api = module.SnippetNodeVariableCollectionApi()
|
||||
handler = unwrap(api.delete)
|
||||
|
||||
with app.test_request_context("/", method="DELETE"):
|
||||
response = handler(api, sqlite_session, _make_account(), snippet=_make_snippet(), node_id="llm-1")
|
||||
|
||||
assert response.status_code == 204
|
||||
assert _variable_ids(sqlite_session) == {other_node.id, other_user.id}
|
||||
|
||||
|
||||
def test_variable_patch_returns_persisted_variable_without_committing_when_no_changes(
|
||||
app: Flask,
|
||||
sqlite_session: Session,
|
||||
) -> None:
|
||||
variable = _make_node_variable("var-1")
|
||||
_persist_variables(sqlite_session, variable)
|
||||
api = module.SnippetVariableApi()
|
||||
handler = unwrap(api.patch)
|
||||
with app.test_request_context("/", method="PATCH", json={}):
|
||||
result = handler(
|
||||
api,
|
||||
module.WorkflowDraftVariableUpdatePayload(),
|
||||
sqlite_session,
|
||||
_make_account(),
|
||||
snippet=_make_snippet(),
|
||||
variable_id="var-1",
|
||||
)
|
||||
|
||||
assert result["id"] == variable.id
|
||||
|
||||
|
||||
def test_variable_delete_deletes_persisted_variable(
|
||||
app: Flask,
|
||||
sqlite_session: Session,
|
||||
) -> None:
|
||||
variable = _make_node_variable("var-1")
|
||||
retained = _make_node_variable("var-2", name="retained")
|
||||
_persist_variables(sqlite_session, variable, retained)
|
||||
api = module.SnippetVariableApi()
|
||||
handler = unwrap(api.delete)
|
||||
|
||||
with app.test_request_context("/", method="DELETE"):
|
||||
response = handler(
|
||||
api,
|
||||
sqlite_session,
|
||||
_make_account(),
|
||||
snippet=_make_snippet(),
|
||||
variable_id=variable.id,
|
||||
)
|
||||
|
||||
assert response.status_code == 204
|
||||
assert _variable_ids(sqlite_session) == {retained.id}
|
||||
|
||||
|
||||
def test_variable_reset_deletes_variable_without_node_execution(
|
||||
app: Flask,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sqlite_session: Session,
|
||||
) -> None:
|
||||
variable = _make_node_variable("var-1", node_execution_id=None)
|
||||
_persist_variables(sqlite_session, variable)
|
||||
monkeypatch.setattr(module.SnippetService, "get_draft_workflow", Mock(return_value=_make_workflow()))
|
||||
api = module.SnippetVariableResetApi()
|
||||
handler = unwrap(api.put)
|
||||
|
||||
with app.test_request_context("/", method="PUT"):
|
||||
response = handler(
|
||||
api,
|
||||
sqlite_session,
|
||||
_make_account(),
|
||||
snippet=_make_snippet(),
|
||||
variable_id=variable.id,
|
||||
)
|
||||
|
||||
assert response.status_code == 204
|
||||
assert _variable_ids(sqlite_session) == set()
|
||||
|
||||
|
||||
def test_environment_variables_returns_workflow_environment_variables(
|
||||
app: Flask,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
env_var = StringVariable(
|
||||
id="env-1",
|
||||
name="API_KEY",
|
||||
description="secret",
|
||||
selector=["env", "API_KEY"],
|
||||
value="sk-test",
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
module.SnippetService, "get_draft_workflow", Mock(return_value=_make_workflow(environment_variables=[env_var]))
|
||||
)
|
||||
|
||||
api = module.SnippetEnvironmentVariableCollectionApi()
|
||||
handler = unwrap(api.get)
|
||||
|
||||
with app.test_request_context("/"):
|
||||
result = handler(api, _make_account(), snippet=_make_snippet())
|
||||
|
||||
assert result == {
|
||||
"items": [
|
||||
{
|
||||
"id": "env-1",
|
||||
"type": "env",
|
||||
"name": "API_KEY",
|
||||
"description": "secret",
|
||||
"selector": ["env", "API_KEY"],
|
||||
"value_type": "string",
|
||||
"value": "sk-test",
|
||||
"edited": False,
|
||||
"visible": True,
|
||||
"editable": True,
|
||||
}
|
||||
]
|
||||
}
|
||||
Reference in new issue
Block a user