|
| 1 | +# Ensure the source directory is in the Python path for imports |
| 2 | +import sys |
| 3 | +from pathlib import Path |
| 4 | +from unittest.mock import MagicMock, mock_open, patch |
| 5 | + |
| 6 | +import pytest |
| 7 | + |
| 8 | +# Add the src directory to the path to ensure imports work from the root |
| 9 | +sys.path.insert(0, str(Path(__file__).parent.parent / "src")) |
| 10 | + |
| 11 | +# We need the Document class to create mock data for our tests |
| 12 | +from langchain_core.documents import Document |
| 13 | + |
| 14 | +from desi.query.query import RAGQueryEngine |
| 15 | + |
| 16 | +# --- Mocks and Fixtures --- |
| 17 | + |
| 18 | +# A fake prompt template to be used by the mock file system |
| 19 | +FAKE_PROMPT_TEMPLATE = "History: {history_str}\nContext: {context_str}\nQuery: {query}" |
| 20 | + |
| 21 | + |
| 22 | +@pytest.fixture |
| 23 | +def mock_docs_and_scores(): |
| 24 | + """Provides a list of mock (Document, score) tuples for mocking ChromaDB results.""" |
| 25 | + return [ |
| 26 | + ( |
| 27 | + Document( |
| 28 | + page_content="Content from openBIS doc.", metadata={"origin": "openbis"} |
| 29 | + ), |
| 30 | + 0.8, |
| 31 | + ), |
| 32 | + ( |
| 33 | + Document( |
| 34 | + page_content="Content from dswiki doc 1.", metadata={"origin": "dswiki"} |
| 35 | + ), |
| 36 | + 0.75, |
| 37 | + ), |
| 38 | + ( |
| 39 | + Document( |
| 40 | + page_content="Low relevance content.", metadata={"origin": "openbis"} |
| 41 | + ), |
| 42 | + 0.2, |
| 43 | + ), # This should be filtered out |
| 44 | + ( |
| 45 | + Document( |
| 46 | + page_content="Content from dswiki doc 2.", metadata={"origin": "dswiki"} |
| 47 | + ), |
| 48 | + 0.6, |
| 49 | + ), |
| 50 | + ( |
| 51 | + Document( |
| 52 | + page_content="More openBIS content.", metadata={"origin": "openbis"} |
| 53 | + ), |
| 54 | + 0.5, |
| 55 | + ), |
| 56 | + ] |
| 57 | + |
| 58 | + |
| 59 | +@pytest.fixture |
| 60 | +def rag_engine(mocker): |
| 61 | + """ |
| 62 | + Provides a fully initialized RAGQueryEngine instance with all external |
| 63 | + dependencies (Ollama, Chroma, file I/O) mocked out. |
| 64 | + """ |
| 65 | + # Mock the Ollama and ChromaDB components |
| 66 | + mocker.patch("desi.query.query.OllamaEmbeddings", return_value=MagicMock()) |
| 67 | + mock_chroma_instance = MagicMock() |
| 68 | + mocker.patch("desi.query.query.Chroma", return_value=mock_chroma_instance) |
| 69 | + |
| 70 | + mock_llm_instance = MagicMock() |
| 71 | + # Mock the .invoke() method on the LLM to return a mock response |
| 72 | + mock_llm_response = MagicMock() |
| 73 | + mock_llm_response.content = "This is the generated answer from the LLM." |
| 74 | + mock_llm_instance.invoke.return_value = mock_llm_response |
| 75 | + mocker.patch("desi.query.query.ChatOllama", return_value=mock_llm_instance) |
| 76 | + |
| 77 | + # Mock the file system to avoid needing a real prompt file |
| 78 | + mocker.patch("builtins.open", mock_open(read_data=FAKE_PROMPT_TEMPLATE)) |
| 79 | + |
| 80 | + # Mock the global availability flag to ensure the engine initializes |
| 81 | + mocker.patch("desi.query.query.OLLAMA_AVAILABLE", True) |
| 82 | + |
| 83 | + # Instantiate the class under test |
| 84 | + engine = RAGQueryEngine( |
| 85 | + chroma_persist_directory="/fake/dir", |
| 86 | + prompt_template_path="/fake/prompt.md", |
| 87 | + relevance_score_threshold=0.3, |
| 88 | + dswiki_boost=0.15, |
| 89 | + ) |
| 90 | + # Attach the mocks to the instance for easy access in tests |
| 91 | + engine.vector_store = mock_chroma_instance |
| 92 | + engine.llm = mock_llm_instance |
| 93 | + return engine |
| 94 | + |
| 95 | + |
| 96 | +# --- Unit Tests --- |
| 97 | + |
| 98 | + |
| 99 | +def test_initialization_no_ollama(mocker): |
| 100 | + """Tests that the engine handles initialization gracefully when Ollama is not available.""" |
| 101 | + mocker.patch("desi.query.query.OLLAMA_AVAILABLE", False) |
| 102 | + mocker.patch("builtins.open", mock_open(read_data=FAKE_PROMPT_TEMPLATE)) |
| 103 | + |
| 104 | + engine = RAGQueryEngine( |
| 105 | + chroma_persist_directory="/fake/dir", prompt_template_path="/fake/prompt.md" |
| 106 | + ) |
| 107 | + |
| 108 | + assert engine.vector_store is None |
| 109 | + assert engine.llm is None |
| 110 | + |
| 111 | + |
| 112 | +def test_retrieve_relevant_chunks_logic(rag_engine, mock_docs_and_scores): |
| 113 | + """ |
| 114 | + Tests the core logic of retrieving, filtering, boosting, and re-ranking chunks. |
| 115 | + """ |
| 116 | + # Configure the mock Chroma vector store to return our predefined docs and scores |
| 117 | + rag_engine.vector_store.similarity_search_with_relevance_scores.return_value = ( |
| 118 | + mock_docs_and_scores |
| 119 | + ) |
| 120 | + |
| 121 | + query = "test query" |
| 122 | + top_k = 3 |
| 123 | + final_chunks = rag_engine.retrieve_relevant_chunks(query, top_k=top_k) |
| 124 | + |
| 125 | + # 1. Check that the final list has the correct size (top_k) |
| 126 | + assert len(final_chunks) == top_k |
| 127 | + |
| 128 | + # 2. Check that the low-scoring doc was filtered out and is not in the final list |
| 129 | + assert "Low relevance content." not in [doc.page_content for doc in final_chunks] |
| 130 | + |
| 131 | + # 3. Check that the re-ranking worked as expected. |
| 132 | + # The first dswiki doc (score 0.75) should be boosted to 0.90 (0.75 + 0.15). |
| 133 | + # This should now be the highest-scoring document, even higher than the original 0.8 openBIS doc. |
| 134 | + assert final_chunks[0].page_content == "Content from dswiki doc 1." |
| 135 | + assert final_chunks[1].page_content == "Content from openBIS doc." |
| 136 | + |
| 137 | + # 4. The second dswiki doc (0.6) is boosted to 0.75, making it third. |
| 138 | + assert final_chunks[2].page_content == "Content from dswiki doc 2." |
| 139 | + |
| 140 | + |
| 141 | +def test_create_prompt_with_context_and_history(rag_engine, mock_docs_and_scores): |
| 142 | + """Tests that the prompt is formatted correctly with all components.""" |
| 143 | + # We only need the Document part of the tuple |
| 144 | + relevant_chunks = [doc for doc, score in mock_docs_and_scores[:2]] |
| 145 | + query = "What is openBIS?" |
| 146 | + history = [ |
| 147 | + {"role": "user", "content": "Hello"}, |
| 148 | + {"role": "assistant", "content": "Hi there!"}, |
| 149 | + ] |
| 150 | + |
| 151 | + prompt = rag_engine._create_prompt(query, relevant_chunks, history) |
| 152 | + |
| 153 | + # Check that all parts are present |
| 154 | + assert "History: User: Hello\nAssistant: Hi there!" in prompt |
| 155 | + assert "Context: --- Context Chunk 1" in prompt |
| 156 | + assert "Content from openBIS doc." in prompt |
| 157 | + assert "Content from dswiki doc 1." in prompt |
| 158 | + assert "Query: What is openBIS?" in prompt |
| 159 | + |
| 160 | + |
| 161 | +def test_generate_answer_cleans_think_tags(rag_engine): |
| 162 | + """Tests that the LLM response is correctly cleaned of <think> tags.""" |
| 163 | + # Configure the mock LLM to return a response with think tags |
| 164 | + rag_engine.llm.invoke.return_value.content = "<think>I should formulate the answer carefully.</think>The final answer is here." |
| 165 | + |
| 166 | + prompt = "test prompt" |
| 167 | + answer = rag_engine.generate_answer(prompt) |
| 168 | + |
| 169 | + assert answer == "The final answer is here." |
| 170 | + assert "<think>" not in answer |
| 171 | + |
| 172 | + |
| 173 | +def test_query_orchestration(mocker, rag_engine): |
| 174 | + """ |
| 175 | + Tests that the main `query` method correctly calls its helper methods in sequence. |
| 176 | + """ |
| 177 | + # Spy on the internal methods of the already-mocked rag_engine instance |
| 178 | + mocker.patch.object(rag_engine, "retrieve_relevant_chunks", return_value=[]) |
| 179 | + mocker.patch.object(rag_engine, "_create_prompt", return_value="final prompt") |
| 180 | + mocker.patch.object(rag_engine, "generate_answer", return_value="final answer") |
| 181 | + |
| 182 | + query = "test query" |
| 183 | + answer, chunks = rag_engine.query(query) |
| 184 | + |
| 185 | + # Assert that the main components of the pipeline were called |
| 186 | + rag_engine.retrieve_relevant_chunks.assert_called_once_with(query, top_k=5) |
| 187 | + rag_engine._create_prompt.assert_called_once() |
| 188 | + rag_engine.generate_answer.assert_called_once_with("final prompt") |
| 189 | + |
| 190 | + # Assert that the final output is correct |
| 191 | + assert answer == "final answer" |
0 commit comments