"""Tests for VectorStore text construction, hashing, and hybrid search.""" import pytest from unittest.mock import patch, MagicMock from src.engine.vector_store import ( _build_internal_text, _build_baymard_text, _build_nng_text, VectorStore, ) from src.engine.retriever import Retriever # ─── Text construction tests ───────────────────────────────────────────────── class TestBuildInternalText: def test_basic_fields(self): item = { "metadata": { "리서치 제목": "숙소 예약 사용성 테스트", "태그": "숙소, 예약", "도메인": "숙소", "방법론": "UT", }, "상세 정보": { "주요 내용 요약": "숙소 예약 프로세스 개선 필요", }, } text = _build_internal_text(item, max_len=2000) assert "숙소 예약 사용성 테스트" in text assert "숙소, 예약" in text assert "UT" in text assert "개선 필요" in text def test_empty_fields(self): item = {"metadata": {}, "상세 정보": {}} text = _build_internal_text(item, max_len=2000) assert text == "" def test_truncation(self): item = { "metadata": {"리서치 제목": "A" * 3000}, "상세 정보": {}, } text = _build_internal_text(item, max_len=100) assert len(text) <= 100 class TestBuildBaymardText: def test_basic_fields(self): item = { "title": "Product Image Quality", "topic": "Product Page", "issue": "Users cannot assess product quality", "advice": "Use high-resolution images", } text = _build_baymard_text(item, max_len=2000) assert "Product Image Quality" in text assert "Product Page" in text assert "high-resolution" in text def test_truncation(self): item = {"title": "T", "topic": "", "issue": "X" * 3000, "advice": ""} text = _build_baymard_text(item, max_len=200) assert len(text) <= 200 class TestBuildNngText: def test_basic_fields(self): item = { "title": "Usability Heuristics", "description": "10 heuristics for UI design", "topics": ["Usability", "Heuristics"], "contents": ["Visibility of system status", "Match between system and real world"], } text = _build_nng_text(item, max_len=2000) assert "Usability Heuristics" in text assert "10 heuristics" in text assert "Visibility" in text def test_contents_as_string(self): item = { "title": "Test", "description": "", "topics": [], "contents": "Some string content", } text = _build_nng_text(item, max_len=2000) assert "Some string content" in text def test_truncation(self): item = { "title": "T", "description": "D" * 3000, "topics": [], "contents": [], } text = _build_nng_text(item, max_len=150) assert len(text) <= 150 # ─── Data hash tests ────────────────────────────────────────────────────────── class TestComputeDataHash: def _make_store(self, internal, baymard, nng): """Create a VectorStore without actually initializing ChromaDB.""" store = VectorStore.__new__(VectorStore) store.internal_data = internal store.baymard_data = baymard store.nng_data = nng return store def test_consistent_hash(self): data_i = [{"id": "RES-001"}, {"id": "RES-010"}] data_b = [{"id": 1}, {"id": 5}] data_n = [{"id": "article-1"}, {"id": "article-3"}] store = self._make_store(data_i, data_b, data_n) h1 = store._compute_data_hash() h2 = store._compute_data_hash() assert h1 == h2 def test_different_data_different_hash(self): store_a = self._make_store( [{"id": "RES-001"}], [{"id": 1}], [{"id": "a-1"}] ) store_b = self._make_store( [{"id": "RES-001"}, {"id": "RES-002"}], [{"id": 1}], [{"id": "a-1"}] ) assert store_a._compute_data_hash() != store_b._compute_data_hash() def test_empty_data(self): store = self._make_store([], [], []) h = store._compute_data_hash() assert isinstance(h, str) and len(h) == 64 # ─── Hybrid search integration test ────────────────────────────────────────── class TestHybridSearch: @pytest.fixture def retriever(self): """Create a Retriever with mock data and a mock VectorStore.""" with patch("src.engine.retriever.load_internal_research", return_value=[]), \ patch("src.engine.retriever.load_baymard_guidelines", return_value=[]), \ patch("src.engine.retriever.load_nng_articles", return_value=[]): r = Retriever.__new__(Retriever) r.internal_data = [ { "id": "RES-001", "metadata": { "리서치 제목": "숙소 예약 사용성 테스트", "태그": "숙소", "담당 리서처": "Shane", "방법론": "UT", "도메인": "숙소", "날짜": "2023-06", "결과 링크": "", }, "상세 정보": {"주요 내용 요약": "예약 프로세스 개선 필요"}, }, { "id": "RES-002", "metadata": { "리서치 제목": "펜션 이미지 품질 조사", "태그": "이미지", "담당 리서처": "Judy", "방법론": "Survey", "도메인": "숙소", "날짜": "2024-01", "결과 링크": "", }, "상세 정보": {"주요 내용 요약": "사진정보 부족 불만"}, }, ] r.baymard_data = [] r.nng_data = [] # Mock VectorStore mock_vs = MagicMock() mock_vs.semantic_search.return_value = [ {"doc_id": "RES-002", "source": "INTERNAL", "score": 0.85}, {"doc_id": "RES-001", "source": "INTERNAL", "score": 0.72}, ] r.vector_store = mock_vs return r def test_hybrid_returns_results(self, retriever): results = retriever.hybrid_search( keywords=["펜션"], query="펜션 사진정보 부족", k=5 ) assert len(results) > 0 assert all("match_type" in r for r in results) def test_hybrid_match_types(self, retriever): results = retriever.hybrid_search( keywords=["숙소"], query="숙소 예약 사용성", k=5 ) match_types = {r["match_type"] for r in results} # Should contain at least one hybrid or fuzzy match assert match_types & {"Hybrid Match", "Fuzzy Match", "Semantic Match"} def test_fallback_when_no_vector_store(self, retriever): retriever.vector_store = None results = retriever.hybrid_search( keywords=["숙소"], query="숙소 예약", k=5 ) # Should still return fuzzy results assert all(r.get("match_type") == "Fuzzy Match" for r in results) def test_source_filter(self, retriever): results = retriever.hybrid_search( keywords=["숙소"], query="숙소 예약", source="INTERNAL", k=5 ) assert all(r.get("source") == "INTERNAL" for r in results)