Spaces:
Runtime error
Runtime error
File size: 15,254 Bytes
197a96c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 | """
Pipeline tests โ covers every public function in the project.
Modules tested:
- core.file_service._chunk
- core.file_service.extract_text (.txt, .pdf, unsupported)
- core.ai_service.stream_response
- core.vector_store.embed_and_store / retrieve
- core.pii_guard.redact_pii
"""
import io
import sys
import os
import unittest
from unittest.mock import patch, MagicMock
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 1. core.file_service._chunk
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestChunk(unittest.TestCase):
def setUp(self):
from core.file_service import _chunk
self.chunk = _chunk
def test_short_text_single_chunk(self):
text = "Hello world"
result = self.chunk(text, size=500, overlap=50)
self.assertEqual(result, "Hello world")
def test_multiple_chunks_separator(self):
text = "A" * 600
result = self.chunk(text, size=500, overlap=50)
self.assertIn("---", result, "Chunks must be separated by ---")
parts = result.split("\n\n---\n\n")
self.assertEqual(len(parts), 2)
def test_overlap_produces_shared_content(self):
text = "X" * 100
result = self.chunk(text, size=60, overlap=20)
parts = result.split("\n\n---\n\n")
self.assertGreater(len(parts), 1)
def test_empty_string(self):
result = self.chunk("", size=500, overlap=50)
self.assertEqual(result, "")
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 2. core.file_service.extract_text โ .txt path
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestExtractTxt(unittest.TestCase):
def setUp(self):
from core.file_service import extract_text
self.extract_text = extract_text
def _make_file(self, name: str, content: bytes):
f = io.BytesIO(content)
f.name = name
return f
def test_txt_extraction(self):
content = b"Hello from a text file."
f = self._make_file("sample.txt", content)
result = self.extract_text(f)
self.assertIn("Hello from a text file.", result)
def test_txt_long_content_is_chunked(self):
content = ("word " * 300).encode("utf-8") # ~1500 chars โ multiple chunks
f = self._make_file("long.txt", content)
result = self.extract_text(f)
self.assertIn("---", result)
def test_unsupported_type_raises(self):
f = self._make_file("doc.docx", b"binary data")
with self.assertRaises(ValueError):
self.extract_text(f)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 3. core.file_service.extract_text โ .pdf path (mocked via fitz)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestExtractPdf(unittest.TestCase):
def setUp(self):
from core.file_service import extract_text
self.extract_text = extract_text
def test_pdf_extraction(self):
fake_page = MagicMock()
fake_page.get_text.return_value = "PDF page text here."
fake_doc = MagicMock()
fake_doc.__iter__ = MagicMock(return_value=iter([fake_page]))
f = io.BytesIO(b"%PDF-1.4 fake")
f.name = "document.pdf"
with patch("core.file_service.fitz.open", return_value=fake_doc):
result = self.extract_text(f)
self.assertIn("PDF page text here.", result)
def test_pdf_empty_pages(self):
fake_page = MagicMock()
fake_page.get_text.return_value = "" # fitz returns "" for blank pages
fake_doc = MagicMock()
fake_doc.__iter__ = MagicMock(return_value=iter([fake_page]))
f = io.BytesIO(b"%PDF-1.4 fake")
f.name = "empty.pdf"
with patch("core.file_service.fitz.open", return_value=fake_doc):
result = self.extract_text(f)
self.assertEqual(result, "")
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 4. core.ai_service.stream_response
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestStreamResponse(unittest.TestCase):
def _make_chunk(self, text):
chunk = MagicMock()
chunk.choices[0].delta.content = text
return chunk
def test_yields_content_tokens(self):
from core.ai_service import stream_response
fake_chunks = [self._make_chunk("Hello"), self._make_chunk(" world")]
mock_stream = MagicMock()
mock_stream.__iter__ = MagicMock(return_value=iter(fake_chunks))
mock_client = MagicMock()
mock_client.chat.completions.create.return_value = mock_stream
with patch("core.ai_service.OpenAI", return_value=mock_client):
tokens = list(stream_response("hi"))
self.assertEqual(tokens, ["Hello", " world"])
def test_none_content_skipped(self):
"""Chunks where delta.content is None must not be yielded."""
from core.ai_service import stream_response
chunk_none = MagicMock()
chunk_none.choices[0].delta.content = None
chunk_real = self._make_chunk("data")
mock_stream = MagicMock()
mock_stream.__iter__ = MagicMock(return_value=iter([chunk_none, chunk_real]))
mock_client = MagicMock()
mock_client.chat.completions.create.return_value = mock_stream
with patch("core.ai_service.OpenAI", return_value=mock_client):
tokens = list(stream_response("hi"))
self.assertEqual(tokens, ["data"])
def test_context_becomes_second_system_message(self):
"""Context must appear as a second system message, after SYSTEM_PROMPT."""
from core.ai_service import stream_response
mock_stream = MagicMock()
mock_stream.__iter__ = MagicMock(return_value=iter([self._make_chunk("ok")]))
mock_client = MagicMock()
mock_client.chat.completions.create.return_value = mock_stream
with patch("core.ai_service.OpenAI", return_value=mock_client):
list(stream_response("hello", context="some law context"))
call_kwargs = mock_client.chat.completions.create.call_args[1]
messages = call_kwargs["messages"]
self.assertEqual(messages[0]["role"], "system")
self.assertIn("some law context", messages[1]["content"])
self.assertEqual(messages[2]["role"], "user")
self.assertEqual(messages[2]["content"], "hello")
def test_no_context_sends_system_and_user(self):
"""Without context, exactly system prompt + user message are sent."""
from core.ai_service import stream_response
mock_stream = MagicMock()
mock_stream.__iter__ = MagicMock(return_value=iter([self._make_chunk("ok")]))
mock_client = MagicMock()
mock_client.chat.completions.create.return_value = mock_stream
with patch("core.ai_service.OpenAI", return_value=mock_client):
list(stream_response("hello"))
call_kwargs = mock_client.chat.completions.create.call_args[1]
messages = call_kwargs["messages"]
self.assertEqual(len(messages), 2)
self.assertEqual(messages[0]["role"], "system")
self.assertEqual(messages[1]["role"], "user")
self.assertEqual(messages[1]["content"], "hello")
def test_stream_flag_is_true(self):
"""The OpenAI call must always use stream=True."""
from core.ai_service import stream_response
mock_stream = MagicMock()
mock_stream.__iter__ = MagicMock(return_value=iter([]))
mock_client = MagicMock()
mock_client.chat.completions.create.return_value = mock_stream
with patch("core.ai_service.OpenAI", return_value=mock_client):
list(stream_response("test"))
call_kwargs = mock_client.chat.completions.create.call_args[1]
self.assertTrue(call_kwargs.get("stream"), "stream must be True")
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 5. core.vector_store.embed_and_store + retrieve
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestVectorStore(unittest.TestCase):
def _fake_embed(self, texts, is_query=False):
"""Returns deterministic unit vectors without loading the real model."""
import numpy as np
rng = np.random.default_rng(seed=42)
vecs = rng.random((len(texts), 1024)).astype("float32")
norms = np.linalg.norm(vecs, axis=1, keepdims=True)
return vecs / norms
def test_embed_and_store_then_retrieve_returns_strings(self):
import core.vector_store as vs
chunks = ["cats are mammals", "dogs bark loudly", "fish live in water"]
with patch("core.vector_store._embed", side_effect=self._fake_embed):
vs.embed_and_store(chunks)
results = vs.retrieve("mammals", k=2)
self.assertIsInstance(results, list)
self.assertEqual(len(results), 2)
self.assertTrue(all(isinstance(r, str) for r in results))
self.assertTrue(all(r in chunks for r in results))
def test_retrieve_k_capped_to_index_size(self):
import core.vector_store as vs
chunks = ["only one chunk"]
with patch("core.vector_store._embed", side_effect=self._fake_embed):
vs.embed_and_store(chunks)
results = vs.retrieve("query", k=10)
self.assertEqual(len(results), 1)
def test_retrieve_before_store_returns_empty(self):
import core.vector_store as vs
vs._index = None
vs._chunks = []
results = vs.retrieve("anything")
self.assertEqual(results, [])
def test_embed_and_store_resets_previous_index(self):
import core.vector_store as vs
with patch("core.vector_store._embed", side_effect=self._fake_embed):
vs.embed_and_store(["first batch"])
vs.embed_and_store(["second batch A", "second batch B"])
results = vs.retrieve("query", k=5)
self.assertEqual(len(results), 2)
self.assertTrue(all("second" in r for r in results))
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 6. core.pii_guard.redact_pii
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestPiiGuard(unittest.TestCase):
def setUp(self):
from core.pii_guard import redact_pii
self.redact_pii = redact_pii
def test_saudi_id_redacted(self):
text = "ุฑูู
ุงููููุฉ: 1234567890"
result, count = self.redact_pii(text)
self.assertNotIn("1234567890", result)
self.assertIn("[ุฑูู
ูููุฉ]", result)
self.assertEqual(count, 1)
def test_iqama_id_redacted(self):
text = "ุฑูู
ุงูุฅูุงู
ุฉ: 2987654321"
result, count = self.redact_pii(text)
self.assertNotIn("2987654321", result)
self.assertIn("[ุฑูู
ูููุฉ]", result)
self.assertEqual(count, 1)
def test_iban_redacted(self):
text = "ุฑูู
IBAN: SA1234567890123456789012"
result, count = self.redact_pii(text)
self.assertNotIn("SA1234567890123456789012", result)
self.assertIn("[ุฑูู
IBAN]", result)
self.assertEqual(count, 1)
def test_no_pii_returns_unchanged(self):
text = "ูุฐุง ูุต ุนุงุฏู ุจุฏูู ุจูุงูุงุช ุญุณุงุณุฉ"
result, count = self.redact_pii(text)
self.assertEqual(result, text)
self.assertEqual(count, 0)
def test_multiple_pii_all_redacted(self):
text = "ูููุฉ: 1234567890 ูIBAN: SA0987654321098765432109"
result, count = self.redact_pii(text)
self.assertEqual(count, 2)
self.assertNotIn("1234567890", result)
self.assertNotIn("SA0987654321098765432109", result)
def test_id_inside_longer_number_not_matched(self):
"""An 11-digit number must not be treated as a Saudi ID."""
text = "ุงูุฑูู
: 12345678901"
result, count = self.redact_pii(text)
self.assertEqual(count, 0)
self.assertEqual(result, text)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# 6. app.py โ show_sources widget keys must stay unique across messages
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestShowSourcesUniqueKeys(unittest.TestCase):
"""Regression test for StreamlitDuplicateElementId when two chat
turns share the same uploaded file or the same retrieved article."""
def test_overlapping_sources_across_messages_do_not_crash(self):
from streamlit.testing.v1 import AppTest
app_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "app.py")
at = AppTest.from_file(app_path)
same_chunk = ("ูุต ุงูู
ุงุฏุฉ ุงูุฃููู ู
ู ูุธุงู
ุงูุนู
ู", 0.91)
same_file_text = "ูุต ู
ูู ุงูุนูุฏ ุงูู
ุฑููุน ููุงุฎุชุจุงุฑ"
at.session_state["messages"] = [
{"role": "user", "content": "ุณุคุงู 1"},
{"role": "assistant", "content": "ุฌูุงุจ 1", "scored_chunks": [same_chunk], "file_text": same_file_text},
{"role": "user", "content": "ุณุคุงู 2"},
{"role": "assistant", "content": "ุฌูุงุจ 2", "scored_chunks": [same_chunk], "file_text": same_file_text},
]
at.run(timeout=60)
self.assertEqual(at.exception, [], f"App crashed: {[e.value for e in at.exception]}")
if __name__ == "__main__":
unittest.main(verbosity=2)
|