Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

test(sdk): audit agent management tests (#21668)

Sbaaoui Idrisse997b94fc35b
diff --git a/test/testcases/test_sdk_api/test_agent_management/conftest.py b/test/testcases/test_sdk_api/test_agent_management/conftest.py
new file mode 100644
index 0000000000..838750b014
--- /dev/null
+++ b/test/testcases/test_sdk_api/test_agent_management/conftest.py
@@ -0,0 +1,109 @@
+#
+# Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import copy
+import os
+
+import pytest
+import requests
+from ragflow_sdk import RAGFlow
+
+
[email protected](autouse=True)
+def network_boundary(request, monkeypatch):
+ original = requests.sessions.Session.request
+
+ def guarded(session, method, url, **kwargs):
+ if request.node.get_closest_marker("integration") is None:
+ pytest.fail(f"Mocked SDK test attempted HTTP: {method} {url}")
+ kwargs.setdefault("timeout", 30)
+ return original(session, method, url, **kwargs)
+
+ monkeypatch.setattr(requests.sessions.Session, "request", guarded)
+
+
+def dsl():
+ # A model-free draft with no dangling component references.
+ return {
+ "components": {"begin": {"obj": {"component_name": "Begin", "params": {}}, "downstream": [], "upstream": []}},
+ "graph": {"nodes": [{"id": "begin", "type": "beginNode", "data": {"label": "Begin", "name": "begin"}, "position": {"x": 0, "y": 0}}], "edges": []},
+ }
+
+
+def client():
+ return RAGFlow("unit-token", "http://sdk.invalid")
+
+
+def wire(monkeypatch):
+ calls = []
+ reply = {"code": 0, "data": True, "message": "success"}
+
+ def request(_session, method, url, **kwargs):
+ calls.append((method, url, kwargs))
+ response = requests.Response()
+ response.status_code = 200
+ response.json = lambda: copy.deepcopy(reply)
+ return response
+
+ monkeypatch.setattr(requests.sessions.Session, "request", request)
+ return calls, reply
+
+
+def live_client(monkeypatch):
+ required = ("RAGFLOW_SDK_BASE_URL", "RAGFLOW_SDK_API_KEY")
+ if os.environ.get("RAGFLOW_SDK_ISOLATED") != "1" or not all(os.environ.get(key) for key in required):
+ pytest.fail("Environment blocked: requires RAGFLOW_SDK_ISOLATED=1, RAGFLOW_SDK_BASE_URL and RAGFLOW_SDK_API_KEY for a disposable Go backend and dedicated empty tenant")
+ client = RAGFlow(os.environ["RAGFLOW_SDK_API_KEY"], os.environ["RAGFLOW_SDK_BASE_URL"])
+ assert client.list_agents(page_size=1) == [], "Dedicated tenant must start without agents"
+ created = set()
+ sessions = set()
+ post = client.post
+
+ def track(path, *args, **kwargs):
+ response = post(path, *args, **kwargs)
+ body = response.json()
+ if path == "/agents" and body.get("code") == 0:
+ created.add(body["data"]["id"])
+ if path.startswith("/agents/") and path.endswith("/sessions") and body.get("code") == 0:
+ sessions.add((path, body["data"]["id"]))
+ return response
+
+ monkeypatch.setattr(client, "post", track)
+ try:
+ yield client
+ finally:
+ errors = []
+ # Single-item HTTP deletion works; batch SDK deletion currently ignores IDs.
+ for path, session_id in sessions:
+ try:
+ assert client.delete(f"{path}/{session_id}", {}).json()["code"] == 0
+ assert client.get(f"{path}/{session_id}").json()["code"] == 404
+ except Exception as error:
+ errors.append(f"Session {session_id}: {error}")
+ for agent_id in created:
+ try:
+ remaining = client.get(f"/agents/{agent_id}").json()
+ if remaining["code"] == 0:
+ assert client.get(f"/agents/{agent_id}/sessions").json()["data"] == []
+ client.delete_agent(agent_id)
+ assert client.get(f"/agents/{agent_id}").json()["code"] == 103
+ except Exception as error:
+ errors.append(f"Agent {agent_id}: {error}")
+ assert not errors, "Cleanup failed: " + "; ".join(errors)
diff --git a/test/testcases/test_sdk_api/test_agent_management/pytest.ini b/test/testcases/test_sdk_api/test_agent_management/pytest.ini
new file mode 100644
index 0000000000..6ad4fab78f
--- /dev/null
+++ b/test/testcases/test_sdk_api/test_agent_management/pytest.ini
@@ -0,0 +1,6 @@
+[pytest]
+pythonpath = ../../../../sdk/python
+addopts = --strict-markers
+markers =
+ integration: requires disposable Go backend and dedicated empty tenant
+ p2: core SDK contract
diff --git a/test/testcases/test_sdk_api/test_agent_management/test_agent_crud_integration.py b/test/testcases/test_sdk_api/test_agent_management/test_agent_crud_integration.py
new file mode 100644
index 0000000000..6f79487131
--- /dev/null
+++ b/test/testcases/test_sdk_api/test_agent_management/test_agent_crud_integration.py
@@ -0,0 +1,181 @@
+#
+# Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import time
+from uuid import uuid4
+
+import pytest
+from ragflow_sdk import RAGFlow
+
+pytestmark = [pytest.mark.p2, pytest.mark.integration]
+
+
+def create_agent(client, dsl, **options):
+ title = f"sdk-agent-{uuid4().hex}"
+ assert client.create_agent(title, dsl, **options) is None
+ matches = [agent for agent in client.list_agents(page_size=100) if agent.title == title]
+ assert len(matches) == 1
+ return client.get_agent(matches[0].id)
+
+
+def test_agent_crud_persistence(live_client, dsl):
+ agent = create_agent(live_client, dsl, description="description", canvas_type="Agent")
+ assert agent.description == "description"
+ assert agent.canvas_type == "Agent"
+ assert agent.permission == "me"
+ assert agent.canvas_category == "agent_canvas"
+ assert agent.dsl.to_json() == dsl
+ assert live_client.delete_agent(agent.id) is None
+ assert agent.id not in {row.id for row in live_client.list_agents()}
+ with pytest.raises(Exception):
+ live_client.get_agent(agent.id)
+ with pytest.raises(Exception):
+ live_client.delete_agent(agent.id)
+
+
[email protected]("patch", [{}, {"title": " Renamed "}, {"description": "changed"}, {"description": ""}, {"canvas_type": "Marketing"}, {"dsl": {}}])
+def test_agent_partial_updates_persist(live_client, dsl, patch):
+ agent = create_agent(live_client, dsl, description="original", canvas_type="Agent")
+ assert live_client.update_agent(agent.id, **patch) is None
+ fresh = live_client.get_agent(agent.id)
+ assert fresh.title == patch.get("title", agent.title).strip()
+ assert fresh.description == patch.get("description", "original")
+ assert fresh.canvas_type == patch.get("canvas_type", "Agent")
+ if "dsl" not in patch:
+ assert fresh.dsl.to_json() == dsl
+ else:
+ # Go omits an empty DSL map from the detail response (json omitempty).
+ assert fresh.dsl is None
+ assert "dsl" not in live_client.get(f"/agents/{agent.id}").json()["data"]
+
+
+def test_agent_dsl_update_persists(live_client, dsl):
+ agent = create_agent(live_client, dsl)
+ dsl["graph"]["nodes"][0]["position"]["x"] = 90
+ live_client.update_agent(agent.id, dsl=dsl)
+ assert live_client.get_agent(agent.id).dsl.to_json() == dsl
+
+
+ "title,dsl_value,options",
+ [
+ ("", {}, {}),
+ (" ", {}, {}),
+ (None, {}, {}),
+ (42, {}, {}),
+ ("Title", None, {}),
+ ("Title", [], {}),
+ ("Title", "invalid", {}),
+ ("Title", {}, {"description": []}),
+ ("Title", {}, {"canvas_type": []}),
+ ],
+)
+def test_agent_create_invalid_values(live_client, title, dsl_value, options):
+ # Raw HTTP reaches the Go decoder even when optional SDK type checking is installed.
+ response = live_client.post("/agents", {"title": title, "dsl": dsl_value} | options).json()
+ assert response["code"] == 101, response
+ assert live_client.list_agents() == []
+
+
[email protected]("value", [[], "invalid", 42])
+def test_agent_update_rejects_nonobject_dsl(live_client, dsl, value):
+ agent = create_agent(live_client, dsl)
+ response = live_client.put(f"/agents/{agent.id}", {"dsl": value}).json()
+ assert response["code"] != 0, response
+ assert "dsl must be an object" in response["message"]
+ assert live_client.get_agent(agent.id).dsl.to_json() == dsl
+
+
+def test_agent_duplicate_title_contract(live_client, dsl):
+ agent = create_agent(live_client, dsl)
+ live_client.create_agent(agent.title, dsl)
+ rows = live_client.list_agents()
+ assert {row.title for row in rows} == {agent.title, agent.title + "(1)"}
+ second = next(row for row in rows if row.id != agent.id)
+ with pytest.raises(Exception, match="already exists"):
+ live_client.update_agent(second.id, title=agent.title)
+ assert live_client.get_agent(second.id).title == second.title
+
+
+def test_agent_listing_pages(live_client, dsl):
+ agents = [create_agent(live_client, dsl) for _ in range(3)]
+ pages = [live_client.list_agents(page=page, page_size=1) for page in (1, 2, 3)]
+ assert all(len(page) == 1 for page in pages)
+ assert {page[0].id for page in pages} == {agent.id for agent in agents}
+ assert live_client.list_agents(page=4, page_size=1) == []
+ rows = live_client.list_agents(orderby="update_time", desc=False)
+ assert [row.update_time for row in rows] == sorted(row.update_time for row in rows)
+
+
[email protected](reason="Go AgentService.mergeAgentsAndGroups sorts only update_time even when SDK orderby=create_time; remove when the requested column is respected")
+def test_agent_creation_order_after_update(live_client, dsl):
+ first = create_agent(live_client, dsl)
+ time.sleep(0.02)
+ second = create_agent(live_client, dsl)
+ assert first.create_time < second.create_time
+ time.sleep(0.02)
+ live_client.update_agent(first.id, description="updated oldest")
+ assert live_client.get_agent(first.id).update_time > second.update_time
+ assert [agent.id for agent in live_client.list_agents(orderby="create_time", desc=False)] == [first.id, second.id]
+
+
[email protected]("method,options", [("get_agent", {}), ("update_agent", {"description": "no"}), ("delete_agent", {})])
+def test_agent_missing_id(live_client, method, options):
+ with pytest.raises(Exception):
+ getattr(live_client, method)(uuid4().hex, **options)
+
+
+def test_agent_invalid_credentials_cannot_delete(live_client, dsl):
+ agent = create_agent(live_client, dsl)
+ denied = RAGFlow("invalid-audit-token", live_client.api_url.removesuffix("/api/v1"))
+ with pytest.raises(Exception):
+ denied.delete_agent(agent.id)
+ assert live_client.get_agent(agent.id).id == agent.id
+
+
+def test_agent_session_creation_and_listing(live_client, dsl):
+ agent = create_agent(live_client, dsl)
+ first = agent.create_session(name=" first ", source="sdk")
+ second = agent.create_session()
+ assert (first.name, first.source) == ("first", "sdk")
+ assert second.name == "session"
+ sessions = agent.list_sessions()
+ assert {session.id for session in sessions} == {first.id, second.id}
+ assert all(session.agent_id == agent.id and session.message == [] for session in sessions)
+ filtered = agent.list_sessions(page_size=1, id=first.id, orderby="create_time", desc=False)
+ assert [session.id for session in filtered] == [first.id]
+ assert agent.list_sessions(page=3, page_size=1) == []
+
+
[email protected]("delete_all", [False, True])
[email protected](reason="Go AgentHandler.DeleteAgentSession ignores documented JSON ids/delete_all sent by Agent.delete_sessions; it reads query parameters and silently deletes nothing")
+def test_agent_session_deletion_persists(live_client, dsl, delete_all):
+ agent = create_agent(live_client, dsl)
+ first = agent.create_session(name="delete")
+ second = agent.create_session(name="survivor")
+ if delete_all:
+ agent.delete_sessions(delete_all=True)
+ else:
+ agent.delete_sessions(ids=[first.id])
+ expected = set() if delete_all else {second.id}
+ assert {session.id for session in agent.list_sessions()} == expected
+
+
[email protected](reason="Go CreateAgentSession serializes dialog_id instead of documented agent_id; SDK Session.__init__ cannot bind agent sessions for ask(); remove when response uses agent_id")
+def test_created_agent_session_binding(live_client, dsl):
+ agent = create_agent(live_client, dsl)
+ session = agent.create_session()
+ assert session.agent_id == agent.id
diff --git a/test/testcases/test_sdk_api/test_agent_management/test_agent_crud_unit.py b/test/testcases/test_sdk_api/test_agent_management/test_agent_crud_unit.py
index c54095d7f1..1b122536fe 100644
--- a/test/testcases/test_sdk_api/test_agent_management/test_agent_crud_unit.py
+++ b/test/testcases/test_sdk_api/test_agent_management/test_agent_crud_unit.py
@@ -15,207 +15,196 @@
#
import pytest
-from configs import HOST_ADDRESS
-from ragflow_sdk import RAGFlow
+import requests
from ragflow_sdk.modules.agent import Agent
from ragflow_sdk.modules.session import Session
+pytestmark = pytest.mark.p2
+
+
+def assert_call(wire, method, path, payload=None, params=None):
+ calls, _ = wire
+ actual_method, url, kwargs = calls[-1]
+ assert actual_method == method
+ assert url == f"http://sdk.invalid/api/v1{path}"
+ assert kwargs["headers"] == {"Authorization": "Bearer unit-token"}
+ assert kwargs.get("json") == payload
+ assert kwargs.get("params") == params
+
+
[email protected]("options", [{}, {"page": 2, "page_size": 5, "orderby": "create_time", "desc": False}])
+def test_list_agents_pagination_and_deserialization(client, wire, dsl, options):
+ wire[1]["data"] = {"canvas": [{"id": "a1", "title": "One", "dsl": dsl}, {"id": "a2", "title": "Two"}], "total": 8}
+ agents = client.list_agents(**options)
+ assert_call(wire, "get", "/agents", params={"page": 1, "page_size": 30, "orderby": "update_time", "desc": True} | options)
+ assert all(isinstance(agent, Agent) and agent.rag is client for agent in agents)
+ assert [(agent.id, agent.title) for agent in agents] == [("a1", "One"), ("a2", "Two")]
+ assert agents[0].dsl.to_json() == dsl
+
+
+def test_list_agents_empty(client, wire):
+ wire[1]["data"] = {"canvas": [], "total": 0}
+ assert client.list_agents() == []
+
+
+def test_get_agent_detail(client, wire, dsl):
+ wire[1]["data"] = {"id": "a1", "title": "One", "description": "details", "canvas_type": "Agent", "dsl": dsl, "tenant_id": "t1", "last_publish_time": 123}
+ agent = client.get_agent("a1")
+ assert_call(wire, "get", "/agents/a1")
+ assert isinstance(agent, Agent) and agent.rag is client
+ assert (agent.id, agent.title, agent.description, agent.canvas_type) == ("a1", "One", "details", "Agent")
+ assert agent.dsl.to_json() == dsl
+ assert (agent.tenant_id, agent.last_publish_time) == ("t1", 123)
+
+
[email protected]("options", [{}, {"description": None, "canvas_type": None}, {"description": "desc"}, {"canvas_type": "Marketing"}, {"description": "", "canvas_type": ""}])
+def test_create_agent_payload_and_return(client, wire, dsl, options):
+ wire[1]["data"] = {"id": "a1", "title": "Title", "dsl": dsl}
+ assert client.create_agent("Title", dsl, **options) is None
+ assert_call(wire, "post", "/agents", {"title": "Title", "dsl": dsl} | {key: value for key, value in options.items() if value is not None})
+
+
[email protected]("kwargs", [{}, {"title": "only-title"}, {"dsl": {}}])
+def test_create_agent_required_arguments(client, wire, kwargs):
+ with pytest.raises(TypeError):
+ client.create_agent(**kwargs)
+ assert wire[0] == []
+
+
+ "patch",
+ [
+ {},
+ {"title": None, "description": None, "dsl": None, "canvas_type": None},
+ {"title": "New"},
+ {"description": "New description"},
+ {"description": ""},
+ {"dsl": {}},
+ {"canvas_type": "Agent"},
+ {"title": "New", "description": "desc", "canvas_type": "Marketing"},
+ ],
+)
+def test_update_agent_partial_payload(client, wire, patch):
+ wire[1]["data"] = {"update_time": 123}
+ assert client.update_agent("a1", **patch) is None
+ assert_call(wire, "put", "/agents/a1", {key: value for key, value in patch.items() if value is not None})
-class _DummyResponse:
- def __init__(self, payload):
- self._payload = payload
- def json(self):
- return self._payload
+def test_update_agent_dsl_payload(client, wire, dsl):
+ assert client.update_agent("a1", dsl=dsl) is None
+ assert_call(wire, "put", "/agents/a1", {"dsl": dsl})
+
+
+def test_delete_agent_success(client, wire):
+ assert client.delete_agent("a1") is None
+ assert_call(wire, "delete", "/agents/a1", {})
+
+
+ "method,kwargs,verb,path,code,message",
+ [
+ ("list_agents", {}, "get", "/agents", 100, "Unauthenticated"),
+ ("get_agent", {"agent_id": "missing"}, "get", "/agents/missing", 103, "Make sure you have permission to access the agent."),
+ ("create_agent", {"title": "", "dsl": {}}, "post", "/agents", 101, "no title in request"),
+ ("update_agent", {"agent_id": "a1", "title": "duplicate"}, "put", "/agents/a1", 102, "duplicate already exists."),
+ ("delete_agent", {"agent_id": "missing"}, "delete", "/agents/missing", 103, "Only the owner of the agent is authorized for this operation."),
+ ("delete_agent", {"agent_id": "a1"}, "delete", "/agents/a1", 100, "Unauthenticated"),
+ ],
+)
+def test_agent_api_errors_propagate(client, wire, method, kwargs, verb, path, code, message):
+ # This proves SDK propagation, not server-side validation of mocked inputs.
+ wire[1].update(code=code, message=message, data=None)
+ with pytest.raises(Exception) as error:
+ getattr(client, method)(**kwargs)
+ assert str(error.value) == message
+ assert wire[0][-1][:2] == (verb, f"http://sdk.invalid/api/v1{path}")
+
+
+def test_agent_optional_fields(client):
+ agent = Agent(client, {"id": "a1", "title": "One"})
+ assert (agent.id, agent.title) == ("a1", "One")
+ assert all(getattr(agent, field) is None for field in ("avatar", "canvas_type", "description", "dsl"))
+
+
+def test_explicit_dsl_round_trip(client, dsl):
+ result = Agent.Dsl(client, dsl).to_json()
+ assert result["components"] == dsl["components"]
+ assert result["graph"] == dsl["graph"]
+
+
[email protected](reason="SDK Agent.Dsl.__init__ hardcodes missing Answer:China downstream; remove when the default graph has no dangling references")
+def test_default_dsl_references_existing_components(client):
+ dsl = Agent.Dsl(client, {}).to_json()
+ for component in dsl["components"].values():
+ assert set(component["downstream"]) <= dsl["components"].keys()
+ assert set(component["upstream"]) <= dsl["components"].keys()
+ assert {node["id"] for node in dsl["graph"]["nodes"]} == dsl["components"].keys()
+
+
[email protected]("options", [{}, {"name": "Session", "source": "sdk"}])
+def test_agent_create_session_request(client, wire, options):
+ wire[1]["data"] = {"id": "s1", "agent_id": "a1", "name": "session", "message": []}
+ session = Agent(client, {"id": "a1"}).create_session(**options)
+ assert_call(wire, "post", "/agents/a1/sessions", options)
+ assert isinstance(session, Session) and session.rag is client
+ assert (session.id, session.name, session.agent_id) == ("s1", "session", "a1")
+
+
[email protected]("options", [{}, {"page": 2, "page_size": 5, "orderby": "update_time", "desc": False, "id": "s1"}])
+def test_agent_list_sessions(client, wire, options):
+ wire[1].update(data=[{"id": "s1", "agent_id": "a1", "name": "one", "message": []}], total=1)
+ sessions = Agent(client, {"id": "a1"}).list_sessions(**options)
+ assert_call(wire, "get", "/agents/a1/sessions", params={"page": 1, "page_size": 30, "orderby": "create_time", "desc": True, "id": None} | options)
+ assert len(sessions) == 1 and isinstance(sessions[0], Session)
+ assert (sessions[0].id, sessions[0].agent_id, sessions[0].name) == ("s1", "a1", "one")
+
+
+def test_agent_list_sessions_empty(client, wire):
+ wire[1].update(data=[], total=0)
+ assert Agent(client, {"id": "a1"}).list_sessions() == []
+
+
+def test_listed_agent_session_history(client, wire):
+ history = [{"role": "user", "content": "stored question"}]
+ wire[1].update(data=[{"id": "s1", "agent_id": "a1", "message": history}], total=1)
+ assert Agent(client, {"id": "a1"}).list_sessions()[0].message == history
+
+
[email protected]("options,payload", [({"ids": ["s1", "s2"]}, {"ids": ["s1", "s2"]}), ({"delete_all": True}, {"ids": None, "delete_all": True})])
+def test_agent_delete_sessions_payload(client, wire, options, payload):
+ assert Agent(client, {"id": "a1"}).delete_sessions(**options) is None
+ assert_call(wire, "delete", "/agents/a1/sessions", payload)
+
+
[email protected]("ids", [None, []])
+def test_agent_delete_sessions_noop(client, wire, ids):
+ assert Agent(client, {"id": "a1"}).delete_sessions(ids=ids) is None
+ assert_call(wire, "delete", "/agents/a1/sessions", {"ids": ids})
+
[email protected]("method,options,verb", [("create_session", {"name": "bad"}, "post"), ("list_sessions", {}, "get"), ("delete_sessions", {"ids": ["missing"]}, "delete")])
+def test_agent_session_errors(client, wire, method, options, verb):
+ wire[1].update(code=103, message="agent not found or no permission", data=None)
+ with pytest.raises(Exception, match="^agent not found or no permission$"):
+ getattr(Agent(client, {"id": "missing"}), method)(**options)
+ assert wire[0][-1][:2] == (verb, "http://sdk.invalid/api/v1/agents/missing/sessions")
[email protected](scope="session")
-def auth():
- return "unit-auth"
+ "method,options",
+ [("list_agents", {}), ("get_agent", {"agent_id": "a1"}), ("create_agent", {"title": "Title", "dsl": {}}), ("update_agent", {"agent_id": "a1"}), ("delete_agent", {"agent_id": "a1"})],
+)
+def test_agent_transport_errors_propagate(client, monkeypatch, method, options):
+ def unavailable(*args, **kwargs):
+ raise requests.ConnectionError("offline")
[email protected](scope="session", autouse=True)
-def set_tenant_info():
- return None
-
-
-def test_list_agents_success_and_error(monkeypatch):
- client = RAGFlow("token", HOST_ADDRESS)
- captured = {}
-
- def _ok_get(path, params=None, json=None):
- captured["path"] = path
- captured["params"] = params
- captured["json"] = json
- return _DummyResponse({"code": 0, "data": {"canvas": [{"id": "agent-1", "title": "Agent One"}], "total": 1}})
-
- monkeypatch.setattr(client, "get", _ok_get)
- agents = client.list_agents()
- assert captured["path"] == "/agents"
- assert captured["params"] == {"page": 1, "page_size": 30, "orderby": "update_time", "desc": True}
- assert isinstance(agents[0], Agent), str(agents)
- assert agents[0].id == "agent-1", str(agents[0])
- assert agents[0].title == "Agent One", str(agents[0])
-
- monkeypatch.setattr(client, "get", lambda *_args, **_kwargs: _DummyResponse({"code": 1, "message": "list boom"}))
- with pytest.raises(Exception) as exception_info:
- client.list_agents()
- assert "list boom" in str(exception_info.value), str(exception_info.value)
-
-
-def test_create_agent_payload_and_error(monkeypatch):
- client = RAGFlow("token", HOST_ADDRESS)
- calls = []
-
- def _ok_post(path, json=None, stream=False, files=None):
- calls.append((path, json, stream, files))
- return _DummyResponse({"code": 0, "message": "ok"})
-
- monkeypatch.setattr(client, "post", _ok_post)
- client.create_agent("agent-title", {"graph": {}}, description=None)
- assert calls[-1][0] == "/agents"
- assert calls[-1][1] == {"title": "agent-title", "dsl": {"graph": {}}}
-
- client.create_agent("agent-title", {"graph": {}}, description="desc")
- assert calls[-1][1] == {"title": "agent-title", "dsl": {"graph": {}}, "description": "desc"}
-
- client.create_agent("agent-title", {"graph": {}}, canvas_type="Marketing")
- assert calls[-1][1] == {"title": "agent-title", "dsl": {"graph": {}}, "canvas_type": "Marketing"}
-
- monkeypatch.setattr(client, "post", lambda *_args, **_kwargs: _DummyResponse({"code": 1, "message": "create boom"}))
- with pytest.raises(Exception) as exception_info:
- client.create_agent("agent-title", {"graph": {}})
- assert "create boom" in str(exception_info.value), str(exception_info.value)
-
-
-def test_update_agent_payload_matrix_and_error(monkeypatch):
- client = RAGFlow("token", HOST_ADDRESS)
- calls = []
-
- def _ok_put(path, json):
- calls.append((path, json))
- return _DummyResponse({"code": 0, "message": "ok"})
-
- monkeypatch.setattr(client, "put", _ok_put)
- cases = [
- ({"title": "new-title"}, {"title": "new-title"}),
- ({"description": "new-description"}, {"description": "new-description"}),
- ({"dsl": {"nodes": []}}, {"dsl": {"nodes": []}}),
- (
- {"title": "new-title", "description": "new-description", "dsl": {"nodes": []}},
- {"title": "new-title", "description": "new-description", "dsl": {"nodes": []}},
- ),
- ({"canvas_type": "Agent"}, {"canvas_type": "Agent"}),
- ]
- for kwargs, expected_payload in cases:
- client.update_agent("agent-1", **kwargs)
- assert calls[-1][0] == "/agents/agent-1"
- assert calls[-1][1] == expected_payload
-
- monkeypatch.setattr(client, "put", lambda *_args, **_kwargs: _DummyResponse({"code": 1, "message": "update boom"}))
- with pytest.raises(Exception) as exception_info:
- client.update_agent("agent-1", title="bad")
- assert "update boom" in str(exception_info.value), str(exception_info.value)
-
-
-def test_delete_agent_success_and_error(monkeypatch):
- client = RAGFlow("token", HOST_ADDRESS)
- calls = []
-
- def _ok_delete(path, json):
- calls.append((path, json))
- return _DummyResponse({"code": 0, "message": "ok"})
-
- monkeypatch.setattr(client, "delete", _ok_delete)
- client.delete_agent("agent-1")
- assert calls[-1] == ("/agents/agent-1", {})
-
- monkeypatch.setattr(client, "delete", lambda *_args, **_kwargs: _DummyResponse({"code": 1, "message": "delete boom"}))
- with pytest.raises(Exception) as exception_info:
- client.delete_agent("agent-1")
- assert "delete boom" in str(exception_info.value), str(exception_info.value)
-
-
-def test_agent_and_dsl_default_initialization():
- client = RAGFlow("token", HOST_ADDRESS)
-
- agent = Agent(client, {"id": "agent-1", "title": "Agent One"})
- assert agent.id == "agent-1"
- assert agent.avatar is None
- assert agent.canvas_type is None
- assert agent.description is None
- assert agent.dsl is None
-
- dsl = Agent.Dsl(client, {})
- assert dsl.answer == []
- assert "begin" in dsl.components
- assert dsl.components["begin"]["obj"]["component_name"] == "Begin"
- assert dsl.graph["nodes"][0]["id"] == "begin"
- assert dsl.history == []
- assert dsl.messages == []
- assert dsl.path == []
- assert dsl.reference == []
-
-
-def test_agent_session_methods_success_and_error_paths(monkeypatch):
- client = RAGFlow("token", HOST_ADDRESS)
- agent = Agent(client, {"id": "agent-1"})
- calls = {"post": [], "get": [], "rm": []}
-
- def _ok_post(path, json=None, stream=False, files=None):
- calls["post"].append((path, json, stream, files))
- return _DummyResponse({"code": 0, "data": {"id": "session-1", "agent_id": "agent-1", "name": "one"}})
-
- def _ok_get(path, params=None):
- calls["get"].append((path, params))
- return _DummyResponse(
- {
- "code": 0,
- "data": [
- {"id": "session-1", "agent_id": "agent-1", "name": "one"},
- {"id": "session-2", "agent_id": "agent-1", "name": "two"},
- ],
- }
- )
-
- def _ok_rm(path, payload):
- calls["rm"].append((path, payload))
- return _DummyResponse({"code": 0, "message": "ok"})
-
- monkeypatch.setattr(agent, "post", _ok_post)
- monkeypatch.setattr(agent, "get", _ok_get)
- monkeypatch.setattr(agent, "rm", _ok_rm)
-
- session = agent.create_session(name="session-name")
- assert isinstance(session, Session), str(session)
- assert session.id == "session-1", str(session)
- assert calls["post"][-1][0] == "/agents/agent-1/sessions"
- assert calls["post"][-1][1] == {"name": "session-name"}
-
- sessions = agent.list_sessions(page=2, page_size=5, orderby="create_time", desc=False, id="session-1")
- assert len(sessions) == 2, str(sessions)
- assert all(isinstance(item, Session) for item in sessions), str(sessions)
- assert calls["get"][-1][0] == "/agents/agent-1/sessions"
- assert calls["get"][-1][1]["page"] == 2
- assert calls["get"][-1][1]["id"] == "session-1"
-
- agent.delete_sessions(ids=["session-1", "session-2"])
- assert calls["rm"][-1] == ("/agents/agent-1/sessions", {"ids": ["session-1", "session-2"]})
-
- monkeypatch.setattr(agent, "post", lambda *_args, **_kwargs: _DummyResponse({"code": 1, "message": "create failed"}))
- with pytest.raises(Exception, match="create failed"):
- agent.create_session(name="bad")
-
- monkeypatch.setattr(agent, "get", lambda *_args, **_kwargs: _DummyResponse({"code": 2, "message": "list failed"}))
- with pytest.raises(Exception, match="list failed"):
- agent.list_sessions()
-
- monkeypatch.setattr(agent, "rm", lambda *_args, **_kwargs: _DummyResponse({"code": 3, "message": "delete failed"}))
- with pytest.raises(Exception, match="delete failed"):
- agent.delete_sessions(ids=["session-1"])
+ monkeypatch.setattr(requests.sessions.Session, "request", unavailable)
+ with pytest.raises(requests.ConnectionError, match="^offline$"):
+ getattr(client, method)(**options)
+
+
+def test_agent_create_session_custom_dsl(client, wire, dsl):
+ wire[1]["data"] = {"id": "s1", "dialog_id": "a1", "dsl": dsl}
+ session = Agent(client, {"id": "a1"}).create_session(dsl=dsl)
+ assert_call(wire, "post", "/agents/a1/sessions", {"dsl": dsl})
+ assert session.dsl.to_json() == dsl