mirror of
https://github.com/infiniflow/ragflow.git
synced 2026-08-15 05:04:27 +08:00
tests: improve RAGFlow coverage based on Codecov report (#13200)
### What problem does this PR solve? Codecov’s coverage report shows that several RAGFlow code paths are currently untested or under-tested. This makes it easier for regressions to slip in during refactors and feature work. This PR adds targeted automated tests to cover the files and branches highlighted by Codecov, improving confidence in core behavior while keeping runtime functionality unchanged. ### Type of change - [x] Other (please describe): Test coverage improvement (adds/extends unit and integration tests to address Codecov-reported gaps)
This commit is contained in:
@@ -71,6 +71,20 @@ Are you asking about the fruit itself, or its use in a specific context?
|
||||
assert message["agent_id"] == agent_id, message
|
||||
assert message["session_id"] == session_id, message
|
||||
|
||||
@pytest.mark.p2
|
||||
def test_add_message_invalid_memory_id(self, WebApiAuth):
|
||||
message_payload = {
|
||||
"memory_id": ["missing_memory_id"],
|
||||
"agent_id": uuid.uuid4().hex,
|
||||
"session_id": uuid.uuid4().hex,
|
||||
"user_id": "",
|
||||
"user_input": "what is pineapple?",
|
||||
"agent_response": "pineapple response",
|
||||
}
|
||||
res = add_message(WebApiAuth, message_payload)
|
||||
assert res["code"] == 500, res
|
||||
assert "Some messages failed to add" in res["message"], res
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("add_empty_multiple_type_memory")
|
||||
class TestAddMultipleTypeMessage:
|
||||
|
||||
@@ -15,8 +15,9 @@
|
||||
#
|
||||
import random
|
||||
import pytest
|
||||
import requests
|
||||
from test_web_api.common import forget_message, list_memory_message, get_message_content
|
||||
from configs import INVALID_API_TOKEN
|
||||
from configs import HOST_ADDRESS, INVALID_API_TOKEN, VERSION
|
||||
from libs.auth import RAGFlowWebApiAuth
|
||||
|
||||
|
||||
@@ -52,3 +53,17 @@ class TestForgetMessage:
|
||||
forgot_message_res = get_message_content(WebApiAuth, memory_id, message["message_id"])
|
||||
assert forgot_message_res["code"] == 0, forgot_message_res
|
||||
assert forgot_message_res["data"]["forget_at"] not in ["-", ""], forgot_message_res
|
||||
|
||||
@pytest.mark.p2
|
||||
def test_forget_message_invalid_memory_id(self, WebApiAuth):
|
||||
res = forget_message(WebApiAuth, "missing_memory_id", 1)
|
||||
assert res["code"] == 404, res
|
||||
assert "not found" in res["message"].lower(), res
|
||||
|
||||
@pytest.mark.p2
|
||||
def test_forget_message_invalid_message_id(self, WebApiAuth):
|
||||
memory_id = self.memory_id
|
||||
url = f"{HOST_ADDRESS}/api/{VERSION}/messages/{memory_id}:invalid_message_id"
|
||||
res = requests.delete(url=url, headers={"Content-Type": "application/json"}, auth=WebApiAuth).json()
|
||||
assert res["code"] == 500, res
|
||||
assert "Internal server error" in res["message"], res
|
||||
|
||||
@@ -49,3 +49,16 @@ class TestGetMessageContent:
|
||||
for field in ["content", "content_embed"]:
|
||||
assert field in content_res["data"]
|
||||
assert content_res["data"][field] is not None, content_res
|
||||
|
||||
@pytest.mark.p2
|
||||
def test_get_message_content_invalid_memory_id(self, WebApiAuth):
|
||||
res = get_message_content(WebApiAuth, "missing_memory_id", 1)
|
||||
assert res["code"] == 404, res
|
||||
assert "not found" in res["message"].lower(), res
|
||||
|
||||
@pytest.mark.p2
|
||||
def test_get_message_content_invalid_message_id(self, WebApiAuth):
|
||||
memory_id = self.memory_id
|
||||
res = get_message_content(WebApiAuth, memory_id, 999999999)
|
||||
assert res["code"] == 404, res
|
||||
assert "not found" in res["message"].lower(), res
|
||||
|
||||
@@ -66,3 +66,15 @@ class TestGetRecentMessage:
|
||||
for message in res["data"]:
|
||||
assert message["session_id"] == session_id, message
|
||||
|
||||
@pytest.mark.p2
|
||||
def test_get_recent_messages_missing_memory_id(self, WebApiAuth):
|
||||
res = get_recent_message(WebApiAuth, params={})
|
||||
assert res["code"] == 101, res
|
||||
assert "memory_ids is required" in res["message"], res
|
||||
|
||||
@pytest.mark.p2
|
||||
def test_get_recent_messages_csv_memory_ids(self, WebApiAuth):
|
||||
memory_id = self.memory_id
|
||||
res = get_recent_message(WebApiAuth, params={"memory_id": f"{memory_id},{memory_id}"})
|
||||
assert res["code"] == 0, res
|
||||
assert isinstance(res["data"], list), res
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
#
|
||||
# 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 asyncio
|
||||
import importlib.util
|
||||
import inspect
|
||||
import sys
|
||||
from copy import deepcopy
|
||||
from pathlib import Path
|
||||
from types import ModuleType, SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
class _DummyManager:
|
||||
def route(self, *_args, **_kwargs):
|
||||
def decorator(func):
|
||||
return func
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
class _AwaitableValue:
|
||||
def __init__(self, value):
|
||||
self._value = value
|
||||
|
||||
def __await__(self):
|
||||
async def _co():
|
||||
return self._value
|
||||
|
||||
return _co().__await__()
|
||||
|
||||
|
||||
class _DummyArgs(dict):
|
||||
def getlist(self, key):
|
||||
value = self.get(key)
|
||||
if value is None:
|
||||
return []
|
||||
if isinstance(value, list):
|
||||
return value
|
||||
return [value]
|
||||
|
||||
|
||||
class _DummyMemoryApiService:
|
||||
async def add_message(self, *_args, **_kwargs):
|
||||
return True, "ok"
|
||||
|
||||
async def get_messages(self, *_args, **_kwargs):
|
||||
return []
|
||||
|
||||
|
||||
def _run(coro):
|
||||
return asyncio.run(coro)
|
||||
|
||||
|
||||
def _load_memory_routes_module(monkeypatch):
|
||||
repo_root = Path(__file__).resolve().parents[4]
|
||||
|
||||
common_pkg = ModuleType("common")
|
||||
common_pkg.__path__ = [str(repo_root / "common")]
|
||||
monkeypatch.setitem(sys.modules, "common", common_pkg)
|
||||
|
||||
apps_mod = ModuleType("api.apps")
|
||||
apps_mod.__path__ = [str(repo_root / "api" / "apps")]
|
||||
apps_mod.current_user = SimpleNamespace(id="user-1")
|
||||
apps_mod.login_required = lambda func: func
|
||||
monkeypatch.setitem(sys.modules, "api.apps", apps_mod)
|
||||
|
||||
services_mod = ModuleType("api.apps.services")
|
||||
services_mod.memory_api_service = _DummyMemoryApiService()
|
||||
monkeypatch.setitem(sys.modules, "api.apps.services", services_mod)
|
||||
|
||||
module_name = "test_message_routes_unit_module"
|
||||
module_path = repo_root / "api" / "apps" / "restful_apis" / "memory_api.py"
|
||||
spec = importlib.util.spec_from_file_location(module_name, module_path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
module.manager = _DummyManager()
|
||||
monkeypatch.setitem(sys.modules, module_name, module)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def _set_request_json(monkeypatch, module, payload):
|
||||
monkeypatch.setattr(module, "get_request_json", lambda: _AwaitableValue(deepcopy(payload)))
|
||||
|
||||
|
||||
@pytest.mark.p2
|
||||
def test_add_message_partial_failure_branch(monkeypatch):
|
||||
module = _load_memory_routes_module(monkeypatch)
|
||||
|
||||
_set_request_json(
|
||||
monkeypatch,
|
||||
module,
|
||||
{
|
||||
"memory_id": ["memory-1"],
|
||||
"agent_id": "agent-1",
|
||||
"session_id": "session-1",
|
||||
"user_input": "hello",
|
||||
"agent_response": "world",
|
||||
},
|
||||
)
|
||||
|
||||
async def _add_message(_memory_ids, _message_dict):
|
||||
return False, "cannot enqueue"
|
||||
|
||||
monkeypatch.setattr(module.memory_api_service, "add_message", _add_message)
|
||||
|
||||
res = _run(inspect.unwrap(module.add_message)())
|
||||
assert res["code"] == module.RetCode.SERVER_ERROR, res
|
||||
assert "Some messages failed to add" in res["message"], res
|
||||
|
||||
|
||||
@pytest.mark.p2
|
||||
def test_get_messages_csv_and_missing_memory_ids(monkeypatch):
|
||||
module = _load_memory_routes_module(monkeypatch)
|
||||
|
||||
monkeypatch.setattr(module, "request", SimpleNamespace(args=_DummyArgs({})))
|
||||
res = _run(inspect.unwrap(module.get_messages)())
|
||||
assert res["code"] == module.RetCode.ARGUMENT_ERROR, res
|
||||
assert "memory_ids is required." in res["message"], res
|
||||
|
||||
monkeypatch.setattr(
|
||||
module,
|
||||
"request",
|
||||
SimpleNamespace(args=_DummyArgs({"memory_id": "m1,m2", "agent_id": "a1", "session_id": "s1", "limit": "5"})),
|
||||
)
|
||||
|
||||
async def _get_messages(memory_ids, agent_id, session_id, limit):
|
||||
assert memory_ids == ["m1", "m2"]
|
||||
assert agent_id == "a1"
|
||||
assert session_id == "s1"
|
||||
assert limit == 5
|
||||
return [{"message_id": 1}]
|
||||
|
||||
monkeypatch.setattr(module.memory_api_service, "get_messages", _get_messages)
|
||||
res = _run(inspect.unwrap(module.get_messages)())
|
||||
assert res["code"] == module.RetCode.SUCCESS, res
|
||||
assert isinstance(res["data"], list), res
|
||||
@@ -80,3 +80,23 @@ class TestSearchMessage:
|
||||
assert res["code"] == 0, res
|
||||
assert len(res["data"]) > 0
|
||||
assert len(res["data"]) <= params["top_n"]
|
||||
|
||||
@pytest.mark.p2
|
||||
def test_query_missing_query(self, WebApiAuth):
|
||||
memory_id = self.memory_id
|
||||
res = search_message(WebApiAuth, {"memory_id": memory_id})
|
||||
assert res["code"] in [100, 500], res
|
||||
|
||||
@pytest.mark.p2
|
||||
def test_query_missing_memory_id(self, WebApiAuth):
|
||||
res = search_message(WebApiAuth, {"query": "what is coriander"})
|
||||
assert res["code"] == 0, res
|
||||
assert isinstance(res["data"], list), res
|
||||
|
||||
@pytest.mark.p2
|
||||
def test_query_with_csv_memory_ids(self, WebApiAuth):
|
||||
memory_id = self.memory_id
|
||||
query = "Coriander is a versatile herb."
|
||||
res = search_message(WebApiAuth, {"memory_id": f"{memory_id},{memory_id}", "query": query})
|
||||
assert res["code"] == 0, res
|
||||
assert isinstance(res["data"], list), res
|
||||
|
||||
@@ -16,9 +16,11 @@
|
||||
import random
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
from test_web_api.common import update_message_status, list_memory_message, get_message_content
|
||||
from configs import INVALID_API_TOKEN
|
||||
from libs.auth import RAGFlowWebApiAuth
|
||||
from configs import HOST_ADDRESS, VERSION
|
||||
|
||||
|
||||
class TestAuthorization:
|
||||
@@ -73,3 +75,34 @@ class TestUpdateMessageStatus:
|
||||
res = get_message_content(WebApiAuth, memory_id, message["message_id"])
|
||||
assert res["code"] == 0, res
|
||||
assert res["data"]["status"], res
|
||||
|
||||
@pytest.mark.p2
|
||||
def test_update_invalid_status_type(self, WebApiAuth):
|
||||
memory_id = self.memory_id
|
||||
list_res = list_memory_message(WebApiAuth, memory_id)
|
||||
assert list_res["code"] == 0, list_res
|
||||
message_id = list_res["data"]["messages"]["message_list"][0]["message_id"]
|
||||
|
||||
url = f"{HOST_ADDRESS}/api/{VERSION}/messages/{memory_id}:{message_id}"
|
||||
res = requests.put(url=url, headers={"Content-Type": "application/json"}, auth=WebApiAuth, json={"status": "false"}).json()
|
||||
assert res["code"] == 101, res
|
||||
assert "Status must be a boolean." in res["message"], res
|
||||
|
||||
@pytest.mark.p2
|
||||
def test_update_invalid_memory_id(self, WebApiAuth):
|
||||
res = update_message_status(WebApiAuth, "missing_memory_id", 1, False)
|
||||
assert res["code"] == 404, res
|
||||
assert "not found" in res["message"].lower(), res
|
||||
|
||||
@pytest.mark.p2
|
||||
def test_update_invalid_message_id(self, WebApiAuth):
|
||||
memory_id = self.memory_id
|
||||
url = f"{HOST_ADDRESS}/api/{VERSION}/messages/{memory_id}:invalid_message_id"
|
||||
res = requests.put(
|
||||
url=url,
|
||||
headers={"Content-Type": "application/json"},
|
||||
auth=WebApiAuth,
|
||||
json={"status": True},
|
||||
).json()
|
||||
assert res["code"] == 500, res
|
||||
assert "Internal server error" in res["message"], res
|
||||
|
||||
Reference in New Issue
Block a user