Files
akyldash/backend/test_rag_review.py
codex 1d0719b101
CI / tests-and-images (pull_request) Successful in 4m0s
Runner smoke test / runner-smoke (pull_request) Successful in 5s
Connect review to local RAG via subscription Codex CLI
2026-11-24 21:53:43 +00:00

113 lines
6.1 KiB
Python

import json
from pathlib import Path
import sqlite3
import tempfile
import unittest
from unittest.mock import Mock, patch
from search.api import Api, ApiError
from search.rag_review import RagError, ReviewRag, decode_search
FRAGMENT = "document:1:edition:2:lang:ru:fragment:3:part:1"
ACCOUNT = {"username": "reader", "must_change_password": False}
def events(ids, suggestions, hits=None):
output = {"ids": ids, "clarifications": suggestions}
if hits is None:
hits = [{"id": FRAGMENT, "text": "Закон"}]
item = {
"type": "mcp_tool_call", "server": "akyldash_rag", "tool": "search_laws", "status": "completed",
"result": {"content": [{"type": "text", "text": json.dumps(hits)}]},
}
lines = [
{"type": "item.completed", "item": item},
{"type": "item.completed", "item": {"type": "agent_message", "text": json.dumps(output)}},
{"type": "turn.completed"},
]
return "\n".join(json.dumps(line) for line in lines)
class ReviewRagTest(unittest.TestCase):
def test_only_issued_candidates_and_distinct_options_are_accepted(self):
ids, options, _ = decode_search(events([FRAGMENT, FRAGMENT], ["Условие", "условие", "Срок"]), 10, "Срок")
self.assertEqual(ids, [FRAGMENT])
self.assertEqual(options, ["Условие"])
self.assertEqual(decode_search(events([], [], []), 10, "")[:2], ([], []))
with self.assertRaisesRegex(RagError, "rag_invalid_response"):
decode_search(events(["made-up"], []), 10, "")
with self.assertRaisesRegex(RagError, "rag_invalid_response"):
decode_search(events([FRAGMENT], []).replace("search_laws", "other_tool"), 10, "")
def test_lookup_rejects_wrong_language_or_replaced_passage(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
index = root / "rag.sqlite"
db = sqlite3.connect(index)
with db:
db.execute("CREATE TABLE chunks (id, code, edition, title, article, status, edition_label, text, language)")
db.execute("INSERT INTO chunks VALUES (?,?,?,?,?,?,?,?,?)",
(FRAGMENT, "1", "2", "Кодекс", "Статья 1", "Действует", "2026", "Закон", "ru"))
db.close()
rag = ReviewRag(index, root, "codex")
with patch("search.rag_review.subprocess.run") as run:
run.return_value = Mock(returncode=0, stdout=events([FRAGMENT], []))
rows, _ = rag.search("Вопрос", "ru", "", 10)
self.assertEqual(rows[0]["article"], "Статья 1")
command = run.call_args.args[0]
self.assertIn('forced_login_method="chatgpt"', command)
self.assertIn('features.shell_tool=false', command)
self.assertNotIn("Вопрос", " ".join(command))
self.assertEqual(json.loads(run.call_args.kwargs["input"])["question"], "Вопрос")
with self.assertRaisesRegex(RagError, "rag_invalid_response"):
rag.search("Суроо", "ky", "", 10)
run.return_value = Mock(returncode=0, stdout=events([FRAGMENT], [], [{"id": FRAGMENT, "text": "Другой текст"}]))
with self.assertRaisesRegex(RagError, "rag_invalid_response"):
rag.search("Вопрос", "ru", "", 10)
class ReviewSearchRouteTest(unittest.TestCase):
def setUp(self):
self.rag = Mock()
self.rag.index.name = "laws-v1.sqlite3"
self.rag.search.return_value = ([{"code": "1", "edition": "2", "fragment_id": FRAGMENT}], ["Тактоо"])
self.api = Api("http://127.0.0.1:1", "unreachable", Path("missing"), rag=self.rag)
self.addCleanup(self.api.review_store.connection.close)
def test_search_and_snapshot_without_opensearch(self):
for language, question, detail in (("ru", "Вопрос", ""), ("ky", "Суроо", "Сыноо өттү")):
with self.subTest(language=language):
with patch.object(self.api, "query_opensearch", side_effect=AssertionError("OpenSearch was contacted")):
status, result = self.api.handle("POST", "/review/search", {
"q": question, "language": language, "clarification": detail}, ACCOUNT)
self.assertEqual(status, 200)
self.rag.search.assert_called_with(question, language, detail, 10)
self.assertEqual(result["clarifications"], ["Тактоо"])
payload = {"review_token": result["review_token"], "results": [{"rank": 1, "code": "1"}]}
self.assertEqual(self.api.handle("POST", "/search-reviews", payload, ACCOUNT)[0], 201)
with self.assertRaises(ApiError) as error:
self.api.handle("POST", "/search-reviews", payload, {"username": "someone-else"})
self.assertEqual(error.exception.status, 403)
def test_auth_input_and_service_errors(self):
for user, body, expected in (
(None, {"q": "query"}, 401),
({**ACCOUNT, "must_change_password": True}, {"q": "query"}, 403),
(ACCOUNT, {"q": "query", "clarification": "x" * 301}, 400),
):
with self.assertRaises(ApiError) as error:
self.api.handle("POST", "/review/search", body, user)
self.assertEqual(error.exception.status, expected)
self.rag.search.assert_not_called()
for code, status in (("rag_timeout", 504), ("rag_limit", 429), ("rag_invalid_response", 502), ("rag_busy", 503)):
self.rag.search.side_effect = RagError(code)
self.assertEqual(self.api.handle("POST", "/review/search", {"q": "query"}, ACCOUNT),
(status, {"api_version": "v1", "error": code}))
def test_rag_is_selected_only_when_worker_is_configured(self):
self.assertIn('data-review-engine="codex-rag"', self.api.review_page())
self.api.rag = None
self.assertIn('data-review-engine="standard"', self.api.review_page())
self.assertEqual(self.api.handle("POST", "/review/search", {"q": "query"}, ACCOUNT)[0], 503)