Skip to content

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

test(sdk): audit session management tests (#21665)

Sbaaoui Idriss3e005cb0b3ef
diff --git a/test/testcases/test_sdk_api/test_session_management/conftest.py b/test/testcases/test_sdk_api/test_session_management/conftest.py
index 351dfcf4ad..06f3fc1215 100644
--- a/test/testcases/test_sdk_api/test_session_management/conftest.py
+++ b/test/testcases/test_sdk_api/test_session_management/conftest.py
@@ -1,5 +1,5 @@
#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
+# 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.
@@ -13,37 +13,59 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
+import os
+from uuid import uuid4
+
import pytest
-from common import batch_add_sessions_with_chat_assistant, delete_all_sessions
-from pytest import FixtureRequest
-from ragflow_sdk import Chat, DataSet, Document, Session
+import requests
+from ragflow_sdk import RAGFlow
+
+
[email protected](scope="session", autouse=True)
+def set_tenant_info():
+ # Session CRUD needs no models; override the ancestor's live model configuration.
+ return None
+
+
[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"Service-free test attempted HTTP: {method} {url}")
+ kwargs.setdefault("timeout", 30)
+ return original(session, method, url, **kwargs)
[email protected](scope="class")
-def add_sessions_with_chat_assistant(request: FixtureRequest, add_chat_assistants: tuple[DataSet, Document, list[Chat]]) -> tuple[Chat, list[Session]]:
- def cleanup():
- for chat_assistant in chat_assistants:
- try:
- delete_all_sessions(chat_assistant)
- except Exception:
- pass
+ monkeypatch.setattr(requests.sessions.Session, "request", guarded)
- request.addfinalizer(cleanup)
- _, _, chat_assistants = add_chat_assistants
- return chat_assistants[0], batch_add_sessions_with_chat_assistant(chat_assistants[0], 5)
+def client():
+ 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 not client.list_chats(page_size=1), "Dedicated tenant must start without chats"
+ assert not client.list_datasets(page_size=1), "Dedicated tenant must start without datasets"
+ return client
[email protected](scope="function")
-def add_sessions_with_chat_assistant_func(request: FixtureRequest, add_chat_assistants: tuple[DataSet, Document, list[Chat]]) -> tuple[Chat, list[Session]]:
- def cleanup():
- for chat_assistant in chat_assistants:
- try:
- delete_all_sessions(chat_assistant)
- except Exception:
- pass
+def chat(client):
+ chat = client.create_chat(name=f"sdk-session-{uuid4().hex}", prompt_config={"prologue": "session audit greeting"})
+ try:
+ yield chat
+ finally:
+ if client.list_chats(id=chat.id):
+ sessions = chat.list_sessions(page_size=-1)
+ if sessions:
+ chat.delete_sessions(ids=[session.id for session in sessions])
+ assert chat.list_sessions(page_size=-1) == [], "Test-owned session cleanup did not persist"
+ client.delete_chats(ids=[chat.id])
+ assert not client.list_chats(id=chat.id), "Test-owned chat cleanup did not persist"
- request.addfinalizer(cleanup)
- _, _, chat_assistants = add_chat_assistants
- return chat_assistants[0], batch_add_sessions_with_chat_assistant(chat_assistants[0], 5)
+def add_sessions_with_chat_assistant(chat):
+ return chat, [chat.create_session(name=f"session_with_chat_assistant_{i}") for i in range(5)]
diff --git a/test/testcases/test_sdk_api/test_session_management/pytest.ini b/test/testcases/test_sdk_api/test_session_management/pytest.ini
new file mode 100644
index 0000000000..de540b5360
--- /dev/null
+++ b/test/testcases/test_sdk_api/test_session_management/pytest.ini
@@ -0,0 +1,8 @@
+[pytest]
+pythonpath = ../../../../sdk/python
+addopts = --strict-markers
+markers =
+ integration: requires disposable Go backend and dedicated empty tenant
+ p1: high priority
+ p2: medium priority
+ p3: low priority
diff --git a/test/testcases/test_sdk_api/test_session_management/test_create_session_with_chat_assistant.py b/test/testcases/test_sdk_api/test_session_management/test_create_session_with_chat_assistant.py
index 08fb241162..fad0b581c0 100644
--- a/test/testcases/test_sdk_api/test_session_management/test_create_session_with_chat_assistant.py
+++ b/test/testcases/test_sdk_api/test_session_management/test_create_session_with_chat_assistant.py
@@ -1,5 +1,5 @@
#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
+# 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.
@@ -13,11 +13,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-from concurrent.futures import ThreadPoolExecutor, as_completed
+from concurrent.futures import ThreadPoolExecutor
import pytest
-from common import list_all_sessions
-from configs import HOST_ADDRESS, SESSION_WITH_CHAT_NAME_LIMIT
from ragflow_sdk import RAGFlow
from ragflow_sdk.modules.session import Session
@@ -40,66 +38,73 @@ class _DummyJsonResponse:
return self._payload
[email protected]("clear_session_with_chat_assistants")
class TestSessionWithChatAssistantCreate:
- @pytest.mark.p3
@pytest.mark.parametrize(
- "name, expected_message",
+ "name, expected",
[
- ("valid_name", ""),
- pytest.param("a" * (SESSION_WITH_CHAT_NAME_LIMIT + 1), "", marks=pytest.mark.skip(reason="issues/")),
- pytest.param(1, "", marks=pytest.mark.skip(reason="issues/")),
- ("", "`name` can not be empty"),
- ("duplicated_name", ""),
- ("case insensitive", ""),
+ ("valid_name", "valid_name"),
+ ("a" * 256, "a" * 255),
+ ("会" * 256, "会" * 255),
+ ("", None),
+ (" ", None),
+ (1, None),
+ (None, None),
+ (True, None),
+ ([], None),
+ (" trimmed name ", "trimmed name"),
+ ("duplicated_name", "duplicated_name"),
+ ("case insensitive", "case insensitive"),
],
)
- def test_name(self, add_chat_assistants, name, expected_message):
- _, _, chat_assistants = add_chat_assistants
- chat_assistant = chat_assistants[0]
-
- if name == "duplicated_name":
- chat_assistant.create_session(name=name)
- elif name == "case insensitive":
- chat_assistant.create_session(name=name.upper())
-
- if expected_message:
- with pytest.raises(Exception) as exception_info:
- chat_assistant.create_session(name=name)
- assert expected_message in str(exception_info.value)
+ def test_name(self, chat, name, expected):
+ previous = None
+ if name in ("duplicated_name", "case insensitive"):
+ previous = chat.create_session(name=name.upper() if name == "case insensitive" else name)
+ if expected is None:
+ with pytest.raises(Exception, match="`name` can not be empty"):
+ chat.create_session(name=name)
+ assert chat.list_sessions() == []
else:
- session = chat_assistant.create_session(name=name)
- assert session.name == name, str(session)
- assert session.chat_id == chat_assistant.id, str(session)
-
- @pytest.mark.p3
- def test_concurrent_create_session(self, add_chat_assistants):
+ session = chat.create_session(name=name)
+ assert session.id
+ assert session.name == expected
+ assert session.chat_id == chat.id
+ persisted = chat.list_sessions(id=session.id)
+ assert len(persisted) == 1
+ assert persisted[0].name == expected
+ if previous:
+ assert session.id != previous.id
+ assert {item.id for item in chat.list_sessions()} == {session.id, previous.id}
+
+ def test_default_name(self, chat):
+ session = chat.create_session()
+ assert session.name == "New session"
+ assert session.chat_id == chat.id
+ assert session.messages[0]["role"] == "assistant"
+ assert session.messages[0]["content"] == "session audit greeting"
+ assert [item.id for item in chat.list_sessions()] == [session.id]
+
+ def test_concurrent_create_session(self, chat):
count = 1000
- _, _, chat_assistants = add_chat_assistants
- chat_assistant = chat_assistants[0]
-
with ThreadPoolExecutor(max_workers=5) as executor:
- futures = [executor.submit(chat_assistant.create_session, name=f"session with chat assistant test {i}") for i in range(count)]
- responses = list(as_completed(futures))
- assert len(responses) == count, responses
-
- updated_sessions = list_all_sessions(chat_assistant, limit=count + 1)
- assert len(updated_sessions) == count
+ futures = [executor.submit(chat.create_session, name=f"session-{i}") for i in range(count)]
+ sessions = [future.result() for future in futures]
+ assert len({session.id for session in sessions}) == count
+ assert {session.name for session in sessions} == {f"session-{i}" for i in range(count)}
+ assert all(session.chat_id == chat.id for session in sessions)
+ persisted = chat.list_sessions(page_size=count + 1)
+ assert {session.id for session in persisted} == {session.id for session in sessions}
- @pytest.mark.p3
- def test_add_session_to_deleted_chat_assistant(self, client, add_chat_assistants):
- _, _, chat_assistants = add_chat_assistants
- chat_assistant = chat_assistants[0]
-
- client.delete_chats(ids=[chat_assistant.id])
- with pytest.raises(Exception) as exception_info:
- chat_assistant.create_session(name="valid_name")
- assert "no authorization" in str(exception_info.value)
+ def test_add_session_to_deleted_chat_assistant(self, client, chat):
+ client.delete_chats(ids=[chat.id])
+ with pytest.raises(Exception, match="^Resource not found$"):
+ chat.create_session(name="valid_name")
@pytest.mark.p2
def test_session_module_streaming_and_helper_paths_unit(monkeypatch):
- client = RAGFlow("token", HOST_ADDRESS)
+ client = RAGFlow("token", "http://unit.invalid")
chat_session = Session(client, {"id": "session-chat", "chat_id": "chat-1"})
chat_done_session = Session(client, {"id": "session-chat-done", "chat_id": "chat-1"})
agent_session = Session(client, {"id": "session-agent", "agent_id": "agent-1"})
@@ -215,3 +220,123 @@ def test_agent_session_streams_all_message_references_without_duplicate_content(
assert "".join(message.content for message in messages) == "first answersecond answer"
assert [message.reference for message in messages if message.reference] == [[first_chunk], [second_chunk]]
+
+
[email protected]("session_type", ["chat", "agent"])
[email protected]("stream", [False, True])
+def test_session_ask_forwards_request_and_message_identity(monkeypatch, session_type, stream):
+ session = Session(None, {"id": "saved-session", f"{session_type}_id": "parent"})
+ calls = []
+ answer = {"content": "answer", "reference": {"chunks": [{"id": "source"}]}}
+ event = {"event": "message", "message_id": "message-id", "data": answer}
+ if session_type == "chat":
+ event = {"data": {"id": "message-id", "answer": "answer", "reference": answer["reference"]}}
+ if stream:
+ import json
+
+ response = _DummyStreamResponse(["data: " + json.dumps(event), "data:[DONE]"])
+ else:
+ response = _DummyJsonResponse({"code": 0, "data": event if session_type == "agent" else event["data"]})
+
+ def post(path, payload, stream=False):
+ calls.append((path, payload, stream))
+ return response
+
+ monkeypatch.setattr(session, "post", post)
+ options = {"files": [{"id": "file-id"}], "user_id": "external-user", "session_id": "override-session"}
+ if session_type == "agent":
+ options.update(inputs={"topic": {"value": "SDK"}}, release=False, return_trace=True)
+ messages = list(session.ask("question", stream=stream, **options))
+ assert len(messages) == 1
+ assert messages[0].id == "message-id"
+ assert messages[0].content == "answer"
+ assert messages[0].role == "assistant"
+ assert messages[0].reference == [{"id": "source"}]
+ path, payload, transport_stream = calls[0]
+ expected = {"stream": stream, **options}
+ if session_type == "chat":
+ expected["question"] = "question"
+ assert path == "/chats/parent/completions"
+ else:
+ expected.update(agent_id="parent", query="question", **{"openai-compatible": False})
+ assert path == "/agents/chat/completions"
+ assert payload == expected
+ assert transport_stream is stream
+
+
[email protected]("session_type", ["chat", "agent"])
[email protected]("terminator", ["data: [DONE]", "data:[DONE]"])
+def test_session_stream_stops_before_trailing_messages(monkeypatch, session_type, terminator):
+ session = Session(None, {"id": "session", f"{session_type}_id": "parent"})
+ if session_type == "chat":
+ frame = 'data:{"event":"message","data":{"id":"answer-id","answer":"answer"}}'
+ else:
+ frame = 'data:{"event":"message","message_id":"answer-id","data":{"content":"answer"}}'
+ response = _DummyStreamResponse(["", ": keepalive", "event: message", "data: {invalid json}", 'data:{"event":"node_finished","data":{}}', frame, terminator, frame])
+ monkeypatch.setattr(session, "post", lambda *_args, **_kwargs: response)
+ messages = list(session.ask("question", stream=True))
+ assert [(message.id, message.content) for message in messages] == [("answer-id", "answer")]
+
+
+def test_chat_stream_preserves_runtime_error_answer(monkeypatch):
+ session = Session(None, {"id": "session", "chat_id": "parent"})
+ response = _DummyStreamResponse(['data:{"code":500,"message":"Session not found!","data":{"answer":"**ERROR**: Session not found!","reference":[]}}'])
+ monkeypatch.setattr(session, "post", lambda *_args, **_kwargs: response)
+ messages = list(session.ask("question", stream=True))
+ assert len(messages) == 1
+ assert messages[0].content == "**ERROR**: Session not found!"
+ assert messages[0].reference is None
+
+
[email protected]("session_type", ["chat", "agent"])
[email protected]("stream", [False, True])
[email protected](reason="Python SDK Session.ask ignores nonzero response codes: Go validation errors lose their message in KeyError('data') instead of raising the API error")
+def test_session_ask_preserves_api_error_message(monkeypatch, session_type, stream):
+ session = Session(None, {"id": "session", f"{session_type}_id": "parent"})
+ error = {"code": 102, "message": "Session not found!"}
+ response = _DummyJsonResponse(error)
+ if stream:
+ response = _DummyStreamResponse(['{"code":102,"message":"Session not found!"}'])
+ monkeypatch.setattr(session, "post", lambda *_args, **_kwargs: response)
+ with pytest.raises(Exception, match="Session not found!"):
+ list(session.ask("question", stream=stream))
+
+
[email protected]("session_type", ["chat", "agent"])
+def test_session_non_stream_rejects_malformed_json(monkeypatch, session_type):
+ session = Session(None, {"id": "session", f"{session_type}_id": "parent"})
+
+ class InvalidResponse:
+ def json(self):
+ raise ValueError("invalid JSON")
+
+ def __str__(self):
+ return "malformed response"
+
+ monkeypatch.setattr(session, "post", lambda *_args, **_kwargs: InvalidResponse())
+ with pytest.raises(Exception, match="Invalid response malformed response"):
+ list(session.ask("question", stream=False))
+
+
+def test_chat_stream_true_terminator_ignores_trailing_messages(monkeypatch):
+ session = Session(None, {"id": "session", "chat_id": "parent"})
+ frame = 'data:{"data":{"answer":"answer"}}'
+ monkeypatch.setattr(session, "post", lambda *_args, **_kwargs: _DummyStreamResponse([frame, 'data:{"data":true}', frame]))
+ assert [message.content for message in session.ask("question", stream=True)] == ["answer"]
+
+
[email protected]("session_type", ["chat", "agent"])
+def test_session_stream_eof_returns_received_messages(monkeypatch, session_type):
+ session = Session(None, {"id": "session", f"{session_type}_id": "parent"})
+ frame = 'data:{"data":{"answer":"answer"}}'
+ if session_type == "agent":
+ frame = 'data:{"event":"message","data":{"content":"answer"}}'
+ monkeypatch.setattr(session, "post", lambda *_args, **_kwargs: _DummyStreamResponse([frame]))
+ assert [message.content for message in session.ask("question", stream=True)] == ["answer"]
diff --git a/test/testcases/test_sdk_api/test_session_management/test_delete_sessions_with_chat_assistant.py b/test/testcases/test_sdk_api/test_session_management/test_delete_sessions_with_chat_assistant.py
index ae996dc659..d4baf84ef6 100644
--- a/test/testcases/test_sdk_api/test_session_management/test_delete_sessions_with_chat_assistant.py
+++ b/test/testcases/test_sdk_api/test_session_management/test_delete_sessions_with_chat_assistant.py
@@ -1,5 +1,5 @@
#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
+# 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.
@@ -15,97 +15,128 @@
#
from concurrent.futures import ThreadPoolExecutor, as_completed
+from unittest.mock import Mock
import pytest
-from common import batch_add_sessions_with_chat_assistant
+from ragflow_sdk.modules.chat import Chat
class TestSessionWithChatAssistantDelete:
- @pytest.mark.parametrize(
- "payload",
- [
- pytest.param(lambda r: {"ids": ["invalid_id"] + r}, marks=pytest.mark.p3),
- pytest.param(lambda r: {"ids": r[:1] + ["invalid_id"] + r[1:5]}, marks=pytest.mark.p3),
- pytest.param(lambda r: {"ids": r + ["invalid_id"]}, marks=pytest.mark.p3),
- ],
- )
- def test_delete_partial_invalid_id(self, add_sessions_with_chat_assistant_func, payload):
- chat_assistant, sessions = add_sessions_with_chat_assistant_func
- if callable(payload):
- payload = payload([session.id for session in sessions])
-
- chat_assistant.delete_sessions(**payload)
-
- sessions = chat_assistant.list_sessions()
- assert len(sessions) == 0
-
@pytest.mark.p3
- def test_repeated_deletion(self, add_sessions_with_chat_assistant_func):
- chat_assistant, sessions = add_sessions_with_chat_assistant_func
- session_ids = {"ids": [session.id for session in sessions]}
-
- chat_assistant.delete_sessions(**session_ids)
-
- with pytest.raises(Exception) as exception_info:
- chat_assistant.delete_sessions(**session_ids)
- assert "The chat doesn't own the session" in str(exception_info.value)
+ @pytest.mark.parametrize("invalid_index", [0, 1, 5])
+ def test_delete_partial_invalid_id(self, add_sessions_with_chat_assistant, invalid_index):
+ chat, sessions = add_sessions_with_chat_assistant
+ ids = [session.id for session in sessions]
+ ids.insert(invalid_index, "invalid_id")
+ assert chat.delete_sessions(ids=ids) is None
+ assert chat.list_sessions() == []
@pytest.mark.p3
- def test_duplicate_deletion(self, add_sessions_with_chat_assistant_func):
- chat_assistant, sessions = add_sessions_with_chat_assistant_func
- session_ids = {"ids": [session.id for session in sessions] * 2}
- chat_assistant.delete_sessions(**session_ids)
- sessions = chat_assistant.list_sessions()
- assert len(sessions) == 0
+ def test_repeated_deletion(self, add_sessions_with_chat_assistant):
+ chat, sessions = add_sessions_with_chat_assistant
+ ids = [session.id for session in sessions]
+ chat.delete_sessions(ids=ids)
+ with pytest.raises(Exception, match="The chat doesn't own the session"):
+ chat.delete_sessions(ids=ids)
+ assert chat.list_sessions() == []
@pytest.mark.p3
- def test_concurrent_deletion(self, add_chat_assistants):
- count = 100
- _, _, chat_assistants = add_chat_assistants
- chat_assistant = chat_assistants[0]
- sessions = batch_add_sessions_with_chat_assistant(chat_assistant, count)
+ def test_duplicate_deletion(self, add_sessions_with_chat_assistant):
+ chat, sessions = add_sessions_with_chat_assistant
+ assert chat.delete_sessions(ids=[session.id for session in sessions] * 2) is None
+ assert chat.list_sessions() == []
+ @pytest.mark.p3
+ def test_concurrent_deletion(self, chat):
+ sessions = [chat.create_session(name=f"concurrent-delete-{i}") for i in range(100)]
with ThreadPoolExecutor(max_workers=5) as executor:
- futures = [executor.submit(chat_assistant.delete_sessions, ids=[sessions[i].id]) for i in range(count)]
- responses = list(as_completed(futures))
- assert len(responses) == count, responses
+ futures = [executor.submit(chat.delete_sessions, ids=[session.id]) for session in sessions]
+ for future in as_completed(futures):
+ assert future.result() is None
+ assert chat.list_sessions() == []
@pytest.mark.p3
- def test_delete_1k(self, add_chat_assistants):
- count = 1_000
- _, _, chat_assistants = add_chat_assistants
- chat_assistant = chat_assistants[0]
- ssessions = batch_add_sessions_with_chat_assistant(chat_assistant, count)
- chat_assistant.delete_sessions(ids=[ssession.id for ssession in ssessions])
-
- sessions = chat_assistant.list_sessions()
- assert len(sessions) == 0
+ def test_delete_1k(self, chat):
+ sessions = [chat.create_session(name=f"bulk-delete-{i}") for i in range(1_000)]
+ assert len({session.id for session in sessions}) == 1_000
+ chat.delete_sessions(ids=[session.id for session in sessions])
+ assert chat.list_sessions() == []
+ @pytest.mark.p3
@pytest.mark.parametrize(
- "payload, expected_message, remaining",
+ "mode, remaining",
[
- pytest.param(None, "", 5, marks=pytest.mark.p3),
- pytest.param({"ids": ["invalid_id"]}, "The chat doesn't own the session invalid_id", 5, marks=pytest.mark.p3),
- pytest.param("not json", """AttributeError("\'str\' object has no attribute \'get\'")""", 5, marks=pytest.mark.skip),
- pytest.param(lambda r: {"ids": r[:1]}, "", 4, marks=pytest.mark.p3),
- pytest.param(lambda r: {"ids": r}, "", 0, marks=pytest.mark.p3),
- pytest.param({"ids": []}, "", 5, marks=pytest.mark.p3),
+ ("omitted", 5),
+ ("invalid", 5),
+ ("one", 4),
+ ("all_ids", 0),
+ ("empty", 5),
+ ("null", 5),
+ ("delete_all", 0),
+ ("empty_delete_all", 0),
+ ("ids_with_delete_all", 4),
],
)
- def test_basic_scenarios(self, add_sessions_with_chat_assistant_func, payload, expected_message, remaining):
- chat_assistant, sessions = add_sessions_with_chat_assistant_func
- if callable(payload):
- payload = payload([session.id for session in sessions])
-
- if expected_message:
- with pytest.raises(Exception) as exception_info:
- chat_assistant.delete_sessions(**payload)
- assert expected_message in str(exception_info.value)
+ def test_basic_scenarios(self, add_sessions_with_chat_assistant, mode, remaining):
+ chat, sessions = add_sessions_with_chat_assistant
+ ids = [session.id for session in sessions]
+ payload = {
+ "omitted": {},
+ "invalid": {"ids": ["invalid_id"]},
+ "one": {"ids": ids[:1]},
+ "all_ids": {"ids": ids},
+ "empty": {"ids": []},
+ "null": {"ids": None},
+ "delete_all": {"delete_all": True},
+ "empty_delete_all": {"ids": [], "delete_all": True},
+ "ids_with_delete_all": {"ids": ids[:1], "delete_all": True},
+ }[mode]
+ if mode == "invalid":
+ with pytest.raises(Exception, match="The chat doesn't own the session invalid_id"):
+ chat.delete_sessions(**payload)
else:
- if payload is None:
- chat_assistant.delete_sessions()
- else:
- chat_assistant.delete_sessions(**payload)
-
- sessions = chat_assistant.list_sessions()
- assert len(sessions) == remaining
+ assert chat.delete_sessions(**payload) is None
+ expected = set(ids if remaining == 5 else ids[1:] if remaining == 4 else [])
+ assert {session.id for session in chat.list_sessions()} == expected
+
+ def test_delete_cannot_target_another_chat(self, client, add_sessions_with_chat_assistant):
+ chat, sessions = add_sessions_with_chat_assistant
+ other_chat = client.create_chat(name="other-delete-owner")
+ other_session = None
+ try:
+ other_session = other_chat.create_session(name="must survive")
+ with pytest.raises(Exception, match="The chat doesn't own the session"):
+ chat.delete_sessions(ids=[other_session.id])
+ assert {session.id for session in chat.list_sessions()} == {session.id for session in sessions}
+ assert [session.id for session in other_chat.list_sessions()] == [other_session.id]
+ finally:
+ if other_session is not None:
+ other_chat.delete_sessions(ids=[other_session.id])
+ assert other_chat.list_sessions() == []
+ client.delete_chats(ids=[other_chat.id])
+ assert client.list_chats(id=other_chat.id) == []
+
+
+ "payload, expected",
+ [
+ ({}, {"ids": None, "delete_all": False}),
+ ({"ids": []}, {"ids": [], "delete_all": False}),
+ ({"ids": ["s"]}, {"ids": ["s"], "delete_all": False}),
+ ({"delete_all": True}, {"ids": None, "delete_all": True}),
+ ],
+)
+def test_delete_sessions_sdk_payload(payload, expected):
+ rag = Mock()
+ rag.delete.return_value.json.return_value = {"code": 0}
+ chat = Chat(rag, {"id": "chat"})
+ assert chat.delete_sessions(**payload) is None
+ rag.delete.assert_called_once_with("/chats/chat/sessions", expected)
+
+
+def test_delete_sessions_invalid_keyword_payload():
+ rag = Mock()
+ with pytest.raises(TypeError):
+ Chat(rag, {"id": "chat"}).delete_sessions(**"not json")
+ rag.delete.assert_not_called()
diff --git a/test/testcases/test_sdk_api/test_session_management/test_list_sessions_with_chat_assistant.py b/test/testcases/test_sdk_api/test_session_management/test_list_sessions_with_chat_assistant.py
index 21b6fea9f9..f2660c9688 100644
--- a/test/testcases/test_sdk_api/test_session_management/test_list_sessions_with_chat_assistant.py
+++ b/test/testcases/test_sdk_api/test_session_management/test_list_sessions_with_chat_assistant.py
@@ -1,5 +1,5 @@
#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
+# 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.
@@ -14,225 +14,134 @@
# limitations under the License.
#
import pytest
-from concurrent.futures import ThreadPoolExecutor, as_completed
-from configs import HOST_ADDRESS
+from concurrent.futures import ThreadPoolExecutor
from ragflow_sdk import RAGFlow
from ragflow_sdk.modules.session import Message, Session
[email protected](scope="session")
-def auth():
- return "unit-auth"
-
-
[email protected](scope="session", autouse=True)
-def set_tenant_info():
- return None
-
-
class TestSessionsWithChatAssistantList:
- @pytest.mark.p3
- def test_list_sessions_raises_on_nonzero_response(self, add_sessions_with_chat_assistant, monkeypatch):
- chat_assistant, _ = add_sessions_with_chat_assistant
-
- class _DummyResponse:
- def json(self):
- return {"code": 1, "message": "boom"}
-
- monkeypatch.setattr(chat_assistant, "get", lambda *_args, **_kwargs: _DummyResponse())
-
- with pytest.raises(Exception) as exception_info:
- chat_assistant.list_sessions()
- assert "boom" in str(exception_info.value)
+ @pytest.mark.parametrize("page, offset", [(None, 0), (0, 0), (2, 2), (3, 4), ("3", 4), (-1, 0), ("a", 0)])
+ def test_page(self, add_sessions_with_chat_assistant, page, offset):
+ chat, sessions = add_sessions_with_chat_assistant
+ ordered = sorted(sessions, key=lambda item: item.name)
+ result = chat.list_sessions(page=page, page_size=2, orderby="name", desc=False)
+ assert [item.id for item in result] == [item.id for item in ordered[offset : offset + 2]]
+
+ @pytest.mark.parametrize("page_size, count", [(None, 5), (0, 0), (1, 1), (6, 5), ("1", 1), (-1, 5), ("a", 5)])
+ def test_page_size(self, add_sessions_with_chat_assistant, page_size, count):
+ chat, sessions = add_sessions_with_chat_assistant
+ result = chat.list_sessions(page_size=page_size, orderby="name", desc=False)
+ assert [item.id for item in result] == [item.id for item in sessions[:count]]
+
+ @pytest.mark.parametrize("orderby, desc", [(None, True), ("create_time", True), ("update_time", True), ("name", "False"), ("unknown", True)])
+ def test_orderby(self, add_sessions_with_chat_assistant, orderby, desc):
+ chat, sessions = add_sessions_with_chat_assistant
+ if orderby == "unknown":
+ with pytest.raises(Exception, match="invalid orderby field: unknown"):
+ chat.list_sessions(orderby=orderby)
+ return
+ result = chat.list_sessions(orderby=orderby, desc=desc)
+ assert {item.id for item in result} == {item.id for item in sessions}
+ key = orderby or "create_time"
+ values = [getattr(item, key) for item in result]
+ assert values == sorted(values, reverse=desc != "False")
- @pytest.mark.p1
@pytest.mark.parametrize(
- "params, expected_page_size, expected_message",
+ "desc, descending, orderby",
[
- ({"page": None, "page_size": 2}, 0, "not instance of"),
- pytest.param({"page": 0, "page_size": 2}, 0, "ValueError('Search does not support negative slicing.')", marks=pytest.mark.skip),
- ({"page": 2, "page_size": 2}, 2, ""),
- ({"page": 3, "page_size": 2}, 1, ""),
- ({"page": "3", "page_size": 2}, 0, "not instance of"),
- pytest.param({"page": -1, "page_size": 2}, 0, "ValueError('Search does not support negative slicing.')", marks=pytest.mark.skip),
- pytest.param({"page": "a", "page_size": 2}, 0, """ValueError("invalid literal for int() with base 10: \'a\'")""", marks=pytest.mark.skip),
+ (None, True, "name"),
+ ("true", True, "name"),
+ ("True", True, "name"),
+ (True, True, "name"),
+ ("false", False, "name"),
+ ("False", False, "name"),
+ (False, False, "name"),
+ ("False", False, "update_time"),
+ ("unknown", True, "name"),
],
)
- def test_page(self, add_sessions_with_chat_assistant, params, expected_page_size, expected_message):
- chat_assistant, _ = add_sessions_with_chat_assistant
- if expected_message:
- with pytest.raises(Exception) as exception_info:
- chat_assistant.list_sessions(**params)
- assert expected_message in str(exception_info.value)
- else:
- sessions = chat_assistant.list_sessions(**params)
- assert len(sessions) == expected_page_size
-
- @pytest.mark.p1
- @pytest.mark.parametrize(
- "params, expected_page_size, expected_message",
- [
- ({"page_size": None}, 0, "not instance of"),
- ({"page_size": 0}, 5, ""),
- ({"page_size": 1}, 1, ""),
- ({"page_size": 6}, 5, ""),
- ({"page_size": "1"}, 0, "not instance of"),
- pytest.param({"page_size": -1}, 5, "", marks=pytest.mark.skip),
- pytest.param({"page_size": "a"}, 0, """ValueError("invalid literal for int() with base 10: \'a\'")""", marks=pytest.mark.skip),
- ],
- )
- def test_page_size(self, add_sessions_with_chat_assistant, params, expected_page_size, expected_message):
- chat_assistant, _ = add_sessions_with_chat_assistant
- if expected_message:
- with pytest.raises(Exception) as exception_info:
- chat_assistant.list_sessions(**params)
- assert expected_message in str(exception_info.value)
- else:
- sessions = chat_assistant.list_sessions(**params)
- assert len(sessions) == expected_page_size
+ def test_desc(self, add_sessions_with_chat_assistant, desc, descending, orderby):
+ chat, sessions = add_sessions_with_chat_assistant
+ result = chat.list_sessions(orderby=orderby, desc=desc)
+ assert {item.id for item in result} == {item.id for item in sessions}
+ values = [getattr(item, orderby) for item in result]
+ assert values == sorted(values, reverse=descending)
+
+ @pytest.mark.parametrize("name", [None, "", "session_with_chat_assistant_1", "unknown"])
+ def test_name(self, add_sessions_with_chat_assistant, name):
+ chat, sessions = add_sessions_with_chat_assistant
+ result = chat.list_sessions(name=name)
+ expected = [item for item in sessions if not name or item.name == name]
+ assert {item.id for item in result} == {item.id for item in expected}
+ assert all(not name or item.name == name for item in result)
+
+ @pytest.mark.parametrize("session_id", [None, "", "existing", "unknown"])
+ def test_id(self, add_sessions_with_chat_assistant, session_id):
+ chat, sessions = add_sessions_with_chat_assistant
+ if session_id == "existing":
+ session_id = sessions[0].id
+ result = chat.list_sessions(id=session_id)
+ assert {item.id for item in result} == {item.id for item in sessions if not session_id or item.id == session_id}
+
+ @pytest.mark.parametrize("existing_id, name", [(True, "session_with_chat_assistant_0"), (True, "session_with_chat_assistant_100"), (True, "unknown"), (False, "session_with_chat_assistant_0")])
+ def test_name_and_id(self, add_sessions_with_chat_assistant, existing_id, name):
+ chat, sessions = add_sessions_with_chat_assistant
+ session_id = sessions[0].id if existing_id else "unknown"
+ result = chat.list_sessions(id=session_id, name=name)
+ assert {item.id for item in result} == {item.id for item in sessions if item.id == session_id and item.name == name}
- @pytest.mark.p3
- @pytest.mark.parametrize(
- "params, expected_message",
- [
- ({"orderby": None}, "not instance of"),
- ({"orderby": "create_time"}, ""),
- ({"orderby": "update_time"}, ""),
- ({"orderby": "name", "desc": "False"}, "not instance of"),
- pytest.param({"orderby": "unknown"}, "orderby should be create_time or update_time", marks=pytest.mark.skip(reason="issues/")),
- ],
- )
- def test_orderby(self, add_sessions_with_chat_assistant, params, expected_message):
- chat_assistant, _ = add_sessions_with_chat_assistant
- if expected_message:
- with pytest.raises(Exception) as exception_info:
- chat_assistant.list_sessions(**params)
- assert expected_message in str(exception_info.value)
- else:
- chat_assistant.list_sessions(**params)
-
- @pytest.mark.p3
- @pytest.mark.parametrize(
- "params, expected_message",
- [
- ({"desc": None}, "not instance of"),
- ({"desc": "true"}, "not instance of"),
- ({"desc": "True"}, "not instance of"),
- ({"desc": True}, ""),
- ({"desc": "false"}, "not instance of"),
- ({"desc": "False"}, "not instance of"),
- ({"desc": False}, ""),
- ({"desc": "False", "orderby": "update_time"}, "not instance of"),
- pytest.param({"desc": "unknown"}, "desc should be true or false", marks=pytest.mark.skip(reason="issues/")),
- ],
- )
- def test_desc(self, add_sessions_with_chat_assistant, params, expected_message):
- chat_assistant, _ = add_sessions_with_chat_assistant
- if expected_message:
- with pytest.raises(Exception) as exception_info:
- chat_assistant.list_sessions(**params)
- assert expected_message in str(exception_info.value)
- else:
- chat_assistant.list_sessions(**params)
-
- @pytest.mark.p1
- @pytest.mark.parametrize(
- "params, expected_num, expected_message",
- [
- ({"name": None}, 0, "not instance of"),
- ({"name": ""}, 5, ""),
- ({"name": "session_with_chat_assistant_1"}, 1, ""),
- ({"name": "unknown"}, 0, ""),
- ],
- )
- def test_name(self, add_sessions_with_chat_assistant, params, expected_num, expected_message):
- chat_assistant, _ = add_sessions_with_chat_assistant
- if expected_message:
- with pytest.raises(Exception) as exception_info:
- chat_assistant.list_sessions(**params)
- assert expected_message in str(exception_info.value)
- else:
- sessions = chat_assistant.list_sessions(**params)
- if params["name"] == "session_with_chat_assistant_1":
- assert sessions[0].name == params["name"]
- else:
- assert len(sessions) == expected_num
+ def test_concurrent_list(self, add_sessions_with_chat_assistant):
+ chat, sessions = add_sessions_with_chat_assistant
+ expected = {item.id for item in sessions}
+ with ThreadPoolExecutor(max_workers=5) as executor:
+ futures = [executor.submit(chat.list_sessions) for _ in range(100)]
+ for future in futures:
+ assert {item.id for item in future.result()} == expected
- @pytest.mark.p1
- @pytest.mark.parametrize(
- "session_id, expected_num, expected_message",
- [
- (None, 0, "not instance of"),
- ("", 5, ""),
- (lambda r: r[0], 1, ""),
- ("unknown", 0, ""),
- ],
+ def test_list_chats_after_deleting_associated_chat_assistant(self, client, add_sessions_with_chat_assistant):
+ chat, _ = add_sessions_with_chat_assistant
+ client.delete_chats(ids=[chat.id])
+ with pytest.raises(Exception, match="^Resource not found$"):
+ chat.list_sessions()
+
+ @pytest.mark.skip(reason="Go ListChatSessions never reads user_id or filters by it (internal/handler/chat_session.go); remove when documented user_id filtering is implemented")
+ @pytest.mark.parametrize("combined", [False, True])
+ def test_user_id(self, add_sessions_with_chat_assistant, combined):
+ chat, sessions = add_sessions_with_chat_assistant
+ filters = {"id": sessions[0].id, "name": sessions[0].name} if combined else {}
+ assert chat.list_sessions(user_id="nonexistent-session-user", **filters) == []
+
+ @pytest.mark.skip(
+ reason="Go list serializes entity.ChatSession as dialog_id/message, but SDK Session requires chat_id/messages (internal/handler/chat_session.go and sdk/python/ragflow_sdk/modules/session.py); remove when list returns SDK session schema"
)
- def test_id(self, add_sessions_with_chat_assistant, session_id, expected_num, expected_message):
- chat_assistant, sessions = add_sessions_with_chat_assistant
- if callable(session_id):
- params = {"id": session_id([s.id for s in sessions])}
- else:
- params = {"id": session_id}
+ def test_list_response_session_contract(self, chat):
+ created = chat.create_session()
+ listed = chat.list_sessions(id=created.id)
+ assert len(listed) == 1
+ assert listed[0].chat_id == chat.id
+ assert listed[0].messages == created.messages
+ listed[0].update({"name": "updated from listed session"})
+ assert chat.list_sessions(id=created.id)[0].name == "updated from listed session"
- if expected_message:
- with pytest.raises(Exception) as exception_info:
- chat_assistant.list_sessions(**params)
- assert expected_message in str(exception_info.value)
- else:
- list_sessions = chat_assistant.list_sessions(**params)
- if "id" in params and params["id"] == sessions[0].id:
- assert list_sessions[0].id == params["id"]
- else:
- assert len(list_sessions) == expected_num
- @pytest.mark.p3
- @pytest.mark.parametrize(
- "session_id, name, expected_num, expected_message",
- [
- (lambda r: r[0], "session_with_chat_assistant_0", 1, ""),
- (lambda r: r[0], "session_with_chat_assistant_100", 0, ""),
- (lambda r: r[0], "unknown", 0, ""),
- ("id", "session_with_chat_assistant_0", 0, ""),
- ],
- )
- def test_name_and_id(self, add_sessions_with_chat_assistant, session_id, name, expected_num, expected_message):
- chat_assistant, sessions = add_sessions_with_chat_assistant
- if callable(session_id):
- params = {"id": session_id([s.id for s in sessions]), "name": name}
- else:
- params = {"id": session_id, "name": name}
+def test_list_sessions_raises_on_nonzero_response(monkeypatch):
+ from ragflow_sdk import Chat
- if expected_message:
- with pytest.raises(Exception) as exception_info:
- chat_assistant.list_sessions(**params)
- assert expected_message in str(exception_info.value)
- else:
- list_sessions = chat_assistant.list_sessions(**params)
- assert len(list_sessions) == expected_num
-
- @pytest.mark.p3
- def test_concurrent_list(self, add_sessions_with_chat_assistant):
- count = 100
- chat_assistant, _ = add_sessions_with_chat_assistant
- with ThreadPoolExecutor(max_workers=5) as executor:
- futures = [executor.submit(chat_assistant.list_sessions) for _ in range(count)]
- responses = list(as_completed(futures))
- assert len(responses) == count, responses
+ chat = Chat(None, {"id": "chat-1"})
- @pytest.mark.p3
- def test_list_chats_after_deleting_associated_chat_assistant(self, client, add_sessions_with_chat_assistant):
- chat_assistant, _ = add_sessions_with_chat_assistant
- client.delete_chats(ids=[chat_assistant.id])
+ class Response:
+ def json(self):
+ return {"code": 1, "message": "boom"}
- with pytest.raises(Exception) as exception_info:
- chat_assistant.list_sessions()
- assert "no authorization" in str(exception_info.value)
+ monkeypatch.setattr(chat, "get", lambda *_args, **_kwargs: Response())
+ with pytest.raises(Exception, match="boom"):
+ chat.list_sessions()
@pytest.mark.p2
def test_session_module_error_paths_unit(monkeypatch):
- client = RAGFlow("token", HOST_ADDRESS)
+ client = RAGFlow("token", "http://unit.invalid")
unknown_session = Session(client, {"id": "session-unknown", "chat_id": "chat-1"})
unknown_session._Session__session_type = "unknown" # noqa: SLF001
@@ -279,3 +188,72 @@ def test_session_module_error_paths_unit(monkeypatch):
assert message.role == "assistant"
assert message.prompt is None
assert message.id is None
+
+
[email protected]("operation", ["create", "list", "update", "delete"])
+def test_sdk_crud_http_contract(monkeypatch, operation):
+ import requests
+ from ragflow_sdk import Chat
+
+ client = RAGFlow("unit-token", "http://unit.invalid")
+ chat = Chat(client, {"id": "chat-1"})
+ row = {"id": "session-1", "chat_id": "chat-1", "name": "session name", "messages": []}
+ calls = []
+
+ def request(_session, method, url, **kwargs):
+ calls.append((method, url, kwargs))
+ response = requests.Response()
+ response.status_code = 200
+ import json
+
+ response._content = json.dumps({"code": 0, "data": [row] if operation == "list" else row}).encode()
+ return response
+
+ monkeypatch.setattr(requests.sessions.Session, "request", request)
+ if operation == "create":
+ result = chat.create_session()
+ method, path, payload_key, payload = "post", "/chats/chat-1/sessions", "json", {"name": "New session"}
+ assert isinstance(result, Session)
+ assert result.chat_id == chat.id
+ elif operation == "list":
+ result = chat.list_sessions(page=2, page_size=7, orderby="name", desc=False, id="session-1", name="session name", user_id="external-user")
+ method, path, payload_key = "get", "/chats/chat-1/sessions", "params"
+ payload = {"page": 2, "page_size": 7, "orderby": "name", "desc": False, "id": "session-1", "name": "session name", "user_id": "external-user"}
+ assert len(result) == 1
+ assert result[0].id == row["id"]
+ assert result[0].messages == []
+ elif operation == "update":
+ session = Session(client, row)
+ assert session.update({"name": "updated"}) is None
+ method, path, payload_key, payload = "patch", "/chats/chat-1/sessions/session-1", "json", {"name": "updated"}
+ else:
+ assert chat.delete_sessions(ids=["session-1"]) is None
+ method, path, payload_key, payload = "delete", "/chats/chat-1/sessions", "json", {"ids": ["session-1"], "delete_all": False}
+ assert len(calls) == 1
+ actual_method, url, kwargs = calls[0]
+ assert actual_method.lower() == method
+ assert url == "http://unit.invalid/api/v1" + path
+ assert kwargs[payload_key] == payload
+ assert kwargs["headers"] == {"Authorization": "Bearer unit-token"}
+
+
[email protected]("operation", ["create", "update", "delete"])
+def test_sdk_crud_api_errors(monkeypatch, operation):
+ from ragflow_sdk import Chat
+
+ class Response:
+ def json(self):
+ return {"code": 102, "message": "session contract error"}
+
+ chat = Chat(None, {"id": "chat-1"})
+ session = Session(None, {"id": "session-1", "chat_id": "chat-1"})
+ monkeypatch.setattr(chat, "post", lambda *_args, **_kwargs: Response())
+ monkeypatch.setattr(chat, "rm", lambda *_args, **_kwargs: Response())
+ monkeypatch.setattr(session, "patch", lambda *_args, **_kwargs: Response())
+ with pytest.raises(Exception, match="session contract error"):
+ if operation == "create":
+ chat.create_session()
+ elif operation == "update":
+ session.update({"name": "new"})
+ else:
+ chat.delete_sessions(ids=[session.id])
diff --git a/test/testcases/test_sdk_api/test_session_management/test_update_session_with_chat_assistant.py b/test/testcases/test_sdk_api/test_session_management/test_update_session_with_chat_assistant.py
index b92cc11eb9..e0b981c12c 100644
--- a/test/testcases/test_sdk_api/test_session_management/test_update_session_with_chat_assistant.py
+++ b/test/testcases/test_sdk_api/test_session_management/test_update_session_with_chat_assistant.py
@@ -1,5 +1,5 @@
#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
+# 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.
@@ -13,86 +13,98 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
+
from concurrent.futures import ThreadPoolExecutor, as_completed
-from random import randint
import pytest
-from configs import SESSION_WITH_CHAT_NAME_LIMIT
class TestSessionWithChatAssistantUpdate:
+ @pytest.mark.p3
@pytest.mark.parametrize(
- "payload, expected_message",
+ "name, expected_name, error",
[
- pytest.param({"name": "valid_name"}, "", marks=pytest.mark.p3),
- pytest.param({"name": "a" * (SESSION_WITH_CHAT_NAME_LIMIT + 1)}, "", marks=pytest.mark.skip(reason="issues/")),
- pytest.param({"name": 1}, "", marks=pytest.mark.skip(reason="issues/")),
- pytest.param({"name": ""}, "`name` can not be empty", marks=pytest.mark.p3),
- pytest.param({"name": "duplicated_name"}, "", marks=pytest.mark.p3),
- pytest.param({"name": "case insensitive"}, "", marks=pytest.mark.p3),
+ ("valid_name", "valid_name", None),
+ ("a" * 256, "a" * 255, None),
+ (1, None, "`name` can not be empty"),
+ ("", None, "`name` can not be empty"),
+ ("duplicated_name", "duplicated_name", None),
+ ("case insensitive", "case insensitive", None),
+ (" trimmed name ", "trimmed name", None),
+ (" ", None, "`name` can not be empty"),
+ ("会" * 256, "会" * 255, None),
],
)
- def test_name(self, add_sessions_with_chat_assistant_func, payload, expected_message):
- chat_assistant, sessions = add_sessions_with_chat_assistant_func
+ def test_name(self, add_sessions_with_chat_assistant, name, expected_name, error):
+ chat, sessions = add_sessions_with_chat_assistant
session = sessions[0]
-
- if payload["name"] == "duplicated_name":
- session.update(payload)
- elif payload["name"] == "case insensitive":
- session.update({"name": payload["name"].upper()})
-
- if expected_message:
- with pytest.raises(Exception) as exception_info:
- session.update(payload)
- assert expected_message in str(exception_info.value)
+ if name == "duplicated_name":
+ sessions[1].update({"name": name})
+ elif name == "case insensitive":
+ session.update({"name": name.upper()})
+ original = chat.list_sessions(id=session.id)[0].name
+ if error:
+ with pytest.raises(Exception, match=error):
+ session.update({"name": name})
else:
- session.update(payload)
- updated_session = chat_assistant.list_sessions(id=session.id)[0]
- assert updated_session.name == payload["name"]
+ assert session.update({"name": name}) is None
+ persisted = chat.list_sessions(id=session.id)
+ assert len(persisted) == 1
+ assert persisted[0].name == (original if error else expected_name)
+ if name == "duplicated_name":
+ assert chat.list_sessions(id=sessions[1].id)[0].name == name
@pytest.mark.p3
- def test_repeated_update_session(self, add_sessions_with_chat_assistant_func):
- _, sessions = add_sessions_with_chat_assistant_func
+ def test_repeated_update_session(self, add_sessions_with_chat_assistant):
+ chat, sessions = add_sessions_with_chat_assistant
session = sessions[0]
-
- session.update({"name": "valid_name_1"})
- session.update({"name": "valid_name_2"})
+ for name in ("valid_name_1", "valid_name_2", "valid_name_2"):
+ assert session.update({"name": name}) is None
+ assert chat.list_sessions(id=session.id)[0].name == name
@pytest.mark.p3
@pytest.mark.parametrize(
- "payload, expected_message",
+ "payload, error",
[
- pytest.param({"unknown_key": "unknown_value"}, "ValueError", marks=pytest.mark.skip),
- ({}, ""),
- pytest.param(None, "TypeError", marks=pytest.mark.skip),
+ pytest.param({}, None, id="empty-noop"),
+ pytest.param(None, None, id="absent-body-noop"),
+ pytest.param({"id": "other", "dialog_id": "other", "chat_id": "other", "user_id": "other"}, None, id="protected-identifiers"),
+ pytest.param({"messages": []}, "`messages` cannot be changed", id="messages"),
+ pytest.param({"message": []}, "`messages` cannot be changed", id="message"),
+ pytest.param({"reference": []}, "`reference` cannot be changed", id="reference"),
],
)
- def test_invalid_params(self, add_sessions_with_chat_assistant_func, payload, expected_message):
- _, sessions = add_sessions_with_chat_assistant_func
+ def test_invalid_params(self, add_sessions_with_chat_assistant, payload, error):
+ chat, sessions = add_sessions_with_chat_assistant
session = sessions[0]
-
- if expected_message:
- with pytest.raises(Exception) as exception_info:
+ before = chat.list_sessions(id=session.id)[0].to_json()
+ if error:
+ with pytest.raises(Exception) as exc:
session.update(payload)
- assert expected_message in str(exception_info.value)
+ assert str(exc.value) == error
else:
- session.update(payload)
+ assert session.update(payload) is None
+ after = chat.list_sessions(id=session.id)[0].to_json()
+ assert after == before
@pytest.mark.p3
- def test_concurrent_update_session(self, add_sessions_with_chat_assistant_func):
- count = 50
- _, sessions = add_sessions_with_chat_assistant_func
-
+ def test_concurrent_update_session(self, add_sessions_with_chat_assistant):
+ chat, sessions = add_sessions_with_chat_assistant
+ names = {session.id: {f"update {session.id} {i}" for i in range(10)} for session in sessions}
with ThreadPoolExecutor(max_workers=5) as executor:
- futures = [executor.submit(sessions[randint(0, 4)].update, {"name": f"update session test {i}"}) for i in range(count)]
- responses = list(as_completed(futures))
- assert len(responses) == count, responses
+ futures = [executor.submit(session.update, {"name": name}) for session in sessions for name in names[session.id]]
+ for future in as_completed(futures):
+ assert future.result() is None
+ persisted = chat.list_sessions()
+ assert {session.id for session in persisted} == set(names)
+ for session in persisted:
+ assert session.name in names[session.id]
@pytest.mark.p3
- def test_update_session_to_deleted_chat_assistant(self, client, add_sessions_with_chat_assistant_func):
- chat_assistant, sessions = add_sessions_with_chat_assistant_func
- client.delete_chats(ids=[chat_assistant.id])
-
- with pytest.raises(Exception) as exception_info:
+ def test_update_session_to_deleted_chat_assistant(self, client, add_sessions_with_chat_assistant):
+ chat, sessions = add_sessions_with_chat_assistant
+ client.delete_chats(ids=[chat.id])
+ with pytest.raises(Exception) as exc:
sessions[0].update({"name": "valid_name"})
- assert "no authorization" in str(exception_info.value)
+ assert str(exc.value) == "Resource not found"