Files
Ai/rag/tests/test_chat_context.py
T

56 lines
2.1 KiB
Python
Raw Normal View History

2026-04-24 02:50:27 +03:30
from unittest.mock import patch
from django.test import SimpleTestCase
2026-04-24 03:02:22 +03:30
from rag.chat import build_rag_context
2026-04-24 02:50:27 +03:30
class ChatContextTests(SimpleTestCase):
2026-04-24 03:02:22 +03:30
@patch("rag.chat.search_with_texts")
2026-04-24 02:50:27 +03:30
@patch("rag.chat.chunk_text")
2026-04-24 03:02:22 +03:30
def test_build_rag_context_includes_full_farm_and_kb_results(
2026-04-24 02:50:27 +03:30
self,
mock_chunk_text,
2026-04-24 03:02:22 +03:30
mock_search_with_texts,
2026-04-24 02:50:27 +03:30
):
2026-04-24 03:02:22 +03:30
mock_chunk_text.return_value = ["farm chunk 1", "farm chunk 2"]
mock_search_with_texts.return_value = [
{"id": "kb-1", "score": 0.8, "text": "kb text 1", "metadata": {}},
{"id": "kb-2", "score": 0.7, "text": "kb text 2", "metadata": {}},
2026-04-24 02:50:27 +03:30
]
2026-04-24 03:02:22 +03:30
context = build_rag_context(
2026-04-24 02:50:27 +03:30
query="وضعیت مزرعه چطور است؟",
2026-04-24 03:02:22 +03:30
sensor_uuid="farm-123",
service_id="chat",
2026-04-24 02:50:27 +03:30
farm_details={"sensor_payload": {"sensor-7-1": {"soil_moisture": 30}}},
)
2026-04-24 03:02:22 +03:30
self.assertIn("[اطلاعات کامل مزرعه]", context)
self.assertIn("soil_moisture", context)
self.assertIn("[متن‌های مرجع]", context)
2026-04-24 02:50:27 +03:30
self.assertIn("kb text 1", context)
self.assertIn("kb text 2", context)
2026-04-24 03:02:22 +03:30
mock_search_with_texts.assert_called_once()
sent_texts = mock_search_with_texts.call_args.kwargs["texts"]
self.assertEqual(sent_texts[0], "وضعیت مزرعه چطور است؟")
self.assertIn("farm chunk 1", sent_texts)
self.assertIn("farm chunk 2", sent_texts)
2026-04-24 02:50:27 +03:30
2026-04-24 03:02:22 +03:30
@patch("rag.chat.search_with_texts", return_value=[])
2026-04-24 02:50:27 +03:30
@patch("rag.chat.chunk_text", return_value=["farm chunk"])
2026-04-24 03:02:22 +03:30
def test_build_rag_context_returns_full_farm_when_kb_empty(
2026-04-24 02:50:27 +03:30
self,
_mock_chunk_text,
2026-04-24 03:02:22 +03:30
_mock_search_with_texts,
2026-04-24 02:50:27 +03:30
):
2026-04-24 03:02:22 +03:30
context = build_rag_context(
2026-04-24 02:50:27 +03:30
query="رطوبت چقدر است؟",
2026-04-24 03:02:22 +03:30
sensor_uuid="farm-123",
service_id="chat",
2026-04-24 02:50:27 +03:30
farm_details={"sensor_payload": {"sensor-7-1": {"soil_moisture": 30}}},
)
2026-04-24 03:02:22 +03:30
self.assertIn("[اطلاعات کامل مزرعه]", context)
self.assertIn("soil_moisture", context)