Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

Add comprehensive citation handler tests (127 tests)

LearningCircuit8c0f599e96d4
diff --git a/tests/citation_handlers/__init__.py b/tests/citation_handlers/__init__.py
new file mode 100644
index 0000000000..834e1b3643
--- /dev/null
+++ b/tests/citation_handlers/__init__.py
@@ -0,0 +1 @@
+"""Tests for citation handlers."""
diff --git a/tests/citation_handlers/conftest.py b/tests/citation_handlers/conftest.py
new file mode 100644
index 0000000000..94b195d163
--- /dev/null
+++ b/tests/citation_handlers/conftest.py
@@ -0,0 +1,154 @@
+"""Shared fixtures for citation handler tests."""
+
+import pytest
+from unittest.mock import Mock
+
+
+def mock_llm():
+ """Create a mock LLM that returns configurable responses."""
+ llm = Mock()
+ llm.invoke.return_value = Mock(content="Test response with citation [1].")
+ return llm
+
+
+def mock_llm_string_response():
+ """Create a mock LLM that returns string responses directly."""
+ llm = Mock()
+ llm.invoke.return_value = "Test string response with citation [1]."
+ return llm
+
+
+def sample_search_results():
+ """Sample search results for testing."""
+ return [
+ {
+ "title": "Test Article 1",
+ "link": "https://example.com/article1",
+ "snippet": "This is the first test article snippet.",
+ "full_content": "This is the full content of the first test article. It contains detailed information about the topic.",
+ },
+ {
+ "title": "Test Article 2",
+ "link": "https://example.org/article2",
+ "snippet": "Second article snippet with different information.",
+ "full_content": "Full content of the second article with more details and context.",
+ },
+ {
+ "title": "Test Article 3",
+ "link": "https://test.com/article3",
+ "snippet": "Third article providing additional context.",
+ "full_content": "The third article contains supplementary information relevant to the query.",
+ },
+ ]
+
+
+def empty_search_results():
+ """Empty search results."""
+ return []
+
+
+def string_search_results():
+ """Search results as a string (edge case)."""
+ return "No structured results available"
+
+
+def settings_with_fact_checking():
+ """Settings snapshot with fact-checking enabled."""
+ return {"general.enable_fact_checking": True}
+
+
+def settings_without_fact_checking():
+ """Settings snapshot with fact-checking disabled."""
+ return {"general.enable_fact_checking": False}
+
+
+def settings_with_output_instructions():
+ """Settings snapshot with custom output instructions."""
+ return {
+ "general.output_instructions": "Respond in formal academic English",
+ "general.enable_fact_checking": True,
+ }
+
+
+def settings_with_dict_value():
+ """Settings snapshot with dict-wrapped values (legacy format)."""
+ return {
+ "general.enable_fact_checking": {"value": True},
+ "general.output_instructions": {"value": "Be concise"},
+ }
+
+
+def sample_previous_knowledge():
+ """Sample previous knowledge for follow-up analysis."""
+ return """Based on previous research:
+- The topic was first studied in 1995 [1]
+- Key findings include improved performance metrics [2]
+- Recent developments show promising results [3]"""
+
+
+def name_search_results():
+ """Search results containing name information."""
+ return [
+ {
+ "title": "Biography of John Michael Smith",
+ "link": "https://example.com/bio",
+ "snippet": "John Smith was a renowned scientist.",
+ "full_content": "John Michael Smith (1950-2020) was a renowned scientist who contributed significantly to the field. His full name was John Michael William Smith.",
+ },
+ {
+ "title": "Awards and Recognition",
+ "link": "https://example.com/awards",
+ "snippet": "Dr. J. M. Smith received numerous awards.",
+ "full_content": "Dr. John M. Smith received numerous awards including the Nobel Prize. Smith's work influenced many researchers.",
+ },
+ ]
+
+
+def dimension_search_results():
+ """Search results containing dimension/measurement information."""
+ return [
+ {
+ "title": "Building Specifications",
+ "link": "https://example.com/building",
+ "snippet": "The tower stands at 324 meters tall.",
+ "full_content": "The Eiffel Tower stands at 324 meters (1,063 feet) tall. Its base is 125 meters wide. The structure weighs approximately 10,100 tons.",
+ },
+ ]
+
+
+def score_search_results():
+ """Search results containing score/game information."""
+ return [
+ {
+ "title": "Match Results",
+ "link": "https://example.com/match",
+ "snippet": "The final score was 3-2.",
+ "full_content": "In the championship final, Team A defeated Team B with a final score of 3-2. The halftime score was 1-1.",
+ },
+ ]
+
+
+def temporal_search_results():
+ """Search results containing date/year information."""
+ return [
+ {
+ "title": "Historical Timeline",
+ "link": "https://example.com/history",
+ "snippet": "The company was founded in 1998.",
+ "full_content": "The company was founded in 1998 by two engineers. It went public in 2004 and was acquired in 2015.",
+ },
+ ]
diff --git a/tests/citation_handlers/test_forced_answer_citation_handler.py b/tests/citation_handlers/test_forced_answer_citation_handler.py
new file mode 100644
index 0000000000..21a1f6d946
--- /dev/null
+++ b/tests/citation_handlers/test_forced_answer_citation_handler.py
@@ -0,0 +1,502 @@
+"""
+Comprehensive tests for ForcedAnswerCitationHandler.
+Tests initialization, analyze methods, hedging detection, and forced extraction.
+"""
+
+import pytest
+from unittest.mock import Mock
+
+
+class TestForcedAnswerCitationHandlerInit:
+ """Tests for ForcedAnswerCitationHandler initialization."""
+
+ def test_init_with_llm_only(self, mock_llm):
+ """Test initialization with just an LLM."""
+ from local_deep_research.citation_handlers.forced_answer_citation_handler import (
+ ForcedAnswerCitationHandler,
+ )
+
+ handler = ForcedAnswerCitationHandler(llm=mock_llm)
+
+ assert handler.llm == mock_llm
+ assert handler.settings_snapshot == {}
+
+ def test_init_with_settings_snapshot(
+ self, mock_llm, settings_with_fact_checking
+ ):
+ """Test initialization with settings snapshot."""
+ from local_deep_research.citation_handlers.forced_answer_citation_handler import (
+ ForcedAnswerCitationHandler,
+ )
+
+ handler = ForcedAnswerCitationHandler(
+ llm=mock_llm, settings_snapshot=settings_with_fact_checking
+ )
+
+ assert handler.settings_snapshot == settings_with_fact_checking
+
+
+class TestForcedAnswerNeedsAnswerExtraction:
+ """Tests for _needs_answer_extraction method."""
+
+ @pytest.fixture
+ def handler(self, mock_llm):
+ """Create a ForcedAnswerCitationHandler."""
+ from local_deep_research.citation_handlers.forced_answer_citation_handler import (
+ ForcedAnswerCitationHandler,
+ )
+
+ return ForcedAnswerCitationHandler(llm=mock_llm)
+
+ def test_detects_cannot_determine(self, handler):
+ """Test detection of 'cannot determine' hedging."""
+ content = "Based on the available information, I cannot determine the exact answer."
+ query = "What is the answer?"
+
+ assert handler._needs_answer_extraction(content, query) is True
+
+ def test_detects_unable_to_find(self, handler):
+ """Test detection of 'unable to find' hedging."""
+ content = "I was unable to find specific information about this topic."
+ query = "What is the answer?"
+
+ assert handler._needs_answer_extraction(content, query) is True
+
+ def test_detects_insufficient(self, handler):
+ """Test detection of 'insufficient' hedging."""
+ content = (
+ "There is insufficient evidence to provide a definitive answer."
+ )
+ query = "What happened?"
+
+ assert handler._needs_answer_extraction(content, query) is True
+
+ def test_detects_unclear(self, handler):
+ """Test detection of 'unclear' hedging."""
+ content = "The sources make it unclear what the actual outcome was."
+ query = "What was the result?"
+
+ assert handler._needs_answer_extraction(content, query) is True
+
+ def test_detects_not_enough(self, handler):
+ """Test detection of 'not enough' hedging."""
+ content = "There is not enough information in the sources."
+ query = "Who won?"
+
+ assert handler._needs_answer_extraction(content, query) is True
+
+ def test_detects_cannot_provide(self, handler):
+ """Test detection of 'cannot provide' hedging."""
+ content = "I cannot provide a specific answer based on the sources."
+ query = "What is the name?"
+
+ assert handler._needs_answer_extraction(content, query) is True
+
+ def test_detects_no_specific_answer(self, handler):
+ """Test detection of 'no specific answer' hedging."""
+ content = "The sources offer no specific answer to this question."
+ query = "Where did it happen?"
+
+ assert handler._needs_answer_extraction(content, query) is True
+
+ def test_detects_cannot_definitively(self, handler):
+ """Test detection of 'cannot definitively' hedging."""
+ content = "I cannot definitively state what the answer is."
+ query = "When did this occur?"
+
+ assert handler._needs_answer_extraction(content, query) is True
+
+ def test_accepts_confident_response(self, handler):
+ """Test acceptance of confident response without hedging."""
+ content = (
+ "The answer is John Smith. According to [1], he was the founder."
+ )
+ query = "What is the answer?"
+
+ assert handler._needs_answer_extraction(content, query) is False
+
+ def test_detects_direct_question_without_answer(self, handler):
+ """Test detection of direct question type without proper answer format."""
+ content = "The topic has been studied extensively by researchers."
+ query = "Who invented the telephone?"
+
+ assert handler._needs_answer_extraction(content, query) is True
+
+ def test_accepts_what_question_with_is_answer(self, handler):
+ """Test acceptance of 'what' question with 'is' in response."""
+ content = "It is the Eiffel Tower. The tower was built in 1889."
+ query = "What is the tallest structure in Paris?"
+
+ assert handler._needs_answer_extraction(content, query) is False
+
+ def test_accepts_who_question_with_was_answer(self, handler):
+ """Test acceptance of 'who' question with 'was' in response."""
+ content = "He was Albert Einstein. Einstein developed the theory."
+ query = "Who discovered relativity?"
+
+ assert handler._needs_answer_extraction(content, query) is False
+
+ def test_accepts_response_with_colon_format(self, handler):
+ """Test acceptance of response with colon format."""
+ content = "The answer: Paris is the capital of France."
+ query = "What is the capital of France?"
+
+ assert handler._needs_answer_extraction(content, query) is False
+
+ def test_case_insensitive_hedging_detection(self, handler):
+ """Test case-insensitive detection of hedging phrases."""
+ content = "CANNOT DETERMINE the answer from these sources."
+ query = "What is it?"
+
+ assert handler._needs_answer_extraction(content, query) is True
+
+
+class TestForcedAnswerExtractDirectAnswer:
+ """Tests for _extract_direct_answer method."""
+
+ @pytest.fixture
+ def handler(self, mock_llm):
+ """Create a ForcedAnswerCitationHandler."""
+ from local_deep_research.citation_handlers.forced_answer_citation_handler import (
+ ForcedAnswerCitationHandler,
+ )
+
+ return ForcedAnswerCitationHandler(llm=mock_llm)
+
+ def test_extract_direct_answer_calls_llm(self, handler, mock_llm):
+ """Test that _extract_direct_answer calls LLM."""
+ mock_llm.invoke.return_value = Mock(content="Extracted Answer")
+
+ handler._extract_direct_answer(
+ "Who is it?", "Some content", "Sources text"
+ )
+
+ mock_llm.invoke.assert_called_once()
+
+ def test_extract_direct_answer_formats_result(self, handler, mock_llm):
+ """Test that extracted answer is formatted correctly."""
+ mock_llm.invoke.return_value = Mock(content="John Smith")
+
+ result = handler._extract_direct_answer(
+ "Who is it?", "Original content", "Sources text"
+ )
+
+ assert result.startswith("John Smith.")
+ assert "Original content" in result
+
+ def test_extract_direct_answer_handles_exception(self, handler, mock_llm):
+ """Test graceful handling of extraction exceptions."""
+ mock_llm.invoke.side_effect = Exception("LLM error")
+
+ result = handler._extract_direct_answer(
+ "Who is it?", "Original content", "Sources text"
+ )
+
+ assert "most likely answer" in result
+ assert "Original content" in result
+
+ def test_extract_direct_answer_prompt_includes_query(
+ self, handler, mock_llm
+ ):
+ """Test that extraction prompt includes the query."""
+ mock_llm.invoke.return_value = Mock(content="Answer")
+
+ handler._extract_direct_answer(
+ "Who invented the telephone?", "Content", "Sources"
+ )
+
+ call_args = mock_llm.invoke.call_args[0][0]
+ assert "Who invented the telephone?" in call_args
+
+ def test_extract_direct_answer_truncates_long_content(
+ self, handler, mock_llm
+ ):
+ """Test that long content is truncated in prompt."""
+ mock_llm.invoke.return_value = Mock(content="Answer")
+ long_content = "x" * 3000
+
+ handler._extract_direct_answer("Query?", long_content, "Sources")
+
+ call_args = mock_llm.invoke.call_args[0][0]
+ # Content should be truncated to 1500 chars
+ assert len(call_args) < len(long_content)
+
+
+class TestForcedAnswerAnalyzeInitial:
+ """Tests for analyze_initial method."""
+
+ def test_analyze_initial_returns_content_and_documents(
+ self, mock_llm, sample_search_results
+ ):
+ """Test analyze_initial returns proper structure."""
+ from local_deep_research.citation_handlers.forced_answer_citation_handler import (
+ ForcedAnswerCitationHandler,
+ )
+
+ handler = ForcedAnswerCitationHandler(llm=mock_llm)
+
+ result = handler.analyze_initial(
+ "What is the answer?", sample_search_results
+ )
+
+ assert "content" in result
+ assert "documents" in result
+ assert len(result["documents"]) == 3
+
+ def test_analyze_initial_prompt_includes_forced_instructions(
+ self, mock_llm, sample_search_results
+ ):
+ """Test analyze_initial prompt includes forced answer instructions."""
+ from local_deep_research.citation_handlers.forced_answer_citation_handler import (
+ ForcedAnswerCitationHandler,
+ )
+
+ # Use response that won't trigger extraction
+ mock_llm.invoke.return_value = Mock(
+ content="The answer is X. According to [1], this is correct."
+ )
+
+ handler = ForcedAnswerCitationHandler(llm=mock_llm)
+
+ handler.analyze_initial("What is the answer?", sample_search_results)
+
+ # Check the first call (initial prompt, not extraction)
+ call_args = mock_llm.invoke.call_args_list[0][0][0]
+ assert "DIRECT answer" in call_args
+ assert "NEVER say" in call_args
+
+ def test_analyze_initial_triggers_extraction_on_hedging(
+ self, mock_llm, sample_search_results
+ ):
+ """Test analyze_initial triggers extraction when response hedges."""
+ from local_deep_research.citation_handlers.forced_answer_citation_handler import (
+ ForcedAnswerCitationHandler,
+ )
+
+ # First call returns hedging, second call returns extracted answer
+ mock_llm.invoke.side_effect = [
+ Mock(content="I cannot determine the answer from these sources."),
+ Mock(content="Extracted Answer"),
+ ]
+
+ handler = ForcedAnswerCitationHandler(llm=mock_llm)
+
+ result = handler.analyze_initial("Who is it?", sample_search_results)
+
+ # Should have called LLM twice (initial + extraction)
+ assert mock_llm.invoke.call_count == 2
+ assert "Extracted Answer" in result["content"]
+
+ def test_analyze_initial_no_extraction_on_confident_response(
+ self, mock_llm, sample_search_results
+ ):
+ """Test analyze_initial skips extraction on confident response."""
+ from local_deep_research.citation_handlers.forced_answer_citation_handler import (
+ ForcedAnswerCitationHandler,
+ )
+
+ mock_llm.invoke.return_value = Mock(
+ content="The answer is John Smith. According to [1]..."
+ )
+
+ handler = ForcedAnswerCitationHandler(llm=mock_llm)
+
+ handler.analyze_initial("Who is it?", sample_search_results)
+
+ # Should have called LLM only once
+ assert mock_llm.invoke.call_count == 1
+
+ def test_analyze_initial_handles_string_response(
+ self, mock_llm_string_response, sample_search_results
+ ):
+ """Test analyze_initial handles string LLM response."""
+ from local_deep_research.citation_handlers.forced_answer_citation_handler import (
+ ForcedAnswerCitationHandler,
+ )
+
+ handler = ForcedAnswerCitationHandler(llm=mock_llm_string_response)
+
+ result = handler.analyze_initial("What is it?", sample_search_results)
+
+ assert "content" in result
+
+
+class TestForcedAnswerAnalyzeFollowup:
+ """Tests for analyze_followup method."""
+
+ def test_analyze_followup_returns_content_and_documents(
+ self, mock_llm, sample_search_results, sample_previous_knowledge
+ ):
+ """Test analyze_followup returns proper structure."""
+ from local_deep_research.citation_handlers.forced_answer_citation_handler import (
+ ForcedAnswerCitationHandler,
+ )
+
+ handler = ForcedAnswerCitationHandler(llm=mock_llm)
+
+ result = handler.analyze_followup(
+ "Follow-up question?",
+ sample_search_results,
+ sample_previous_knowledge,
+ nr_of_links=3,
+ )
+
+ assert "content" in result
+ assert "documents" in result
+
+ def test_analyze_followup_with_fact_checking(
+ self, mock_llm, sample_search_results, sample_previous_knowledge
+ ):
+ """Test analyze_followup performs fact-checking when enabled."""
+ from local_deep_research.citation_handlers.forced_answer_citation_handler import (
+ ForcedAnswerCitationHandler,
+ )
+
+ handler = ForcedAnswerCitationHandler(
+ llm=mock_llm,
+ settings_snapshot={"general.enable_fact_checking": True},
+ )
+
+ handler.analyze_followup(
+ "Follow-up question?",
+ sample_search_results,
+ sample_previous_knowledge,
+ nr_of_links=0,
+ )
+
+ # Should call LLM at least twice (fact-check + main)
+ assert mock_llm.invoke.call_count >= 2
+
+ def test_analyze_followup_prompt_includes_critical_instructions(
+ self, mock_llm, sample_search_results, sample_previous_knowledge
+ ):
+ """Test analyze_followup prompt includes critical forced answer instructions."""
+ from local_deep_research.citation_handlers.forced_answer_citation_handler import (
+ ForcedAnswerCitationHandler,
+ )
+
+ # Use response that won't trigger extraction
+ mock_llm.invoke.return_value = Mock(
+ content="John Smith is the person. According to [1], he was the founder."
+ )
+
+ handler = ForcedAnswerCitationHandler(
+ llm=mock_llm,
+ settings_snapshot={"general.enable_fact_checking": False},
+ )
+
+ handler.analyze_followup(
+ "Who is the person?",
+ sample_search_results,
+ sample_previous_knowledge,
+ nr_of_links=0,
+ )
+
+ # Check the first call (main prompt, not extraction)
+ call_args = mock_llm.invoke.call_args_list[0][0][0]
+ assert "MUST start with a direct" in call_args
+ assert "wrong answer is better than no answer" in call_args
+
+ def test_analyze_followup_triggers_extraction_on_hedging(
+ self, mock_llm, sample_search_results, sample_previous_knowledge
+ ):
+ """Test analyze_followup triggers extraction when response hedges."""
+ from local_deep_research.citation_handlers.forced_answer_citation_handler import (
+ ForcedAnswerCitationHandler,
+ )
+
+ # Fact-check returns content, main response hedges, extraction returns answer
+ mock_llm.invoke.side_effect = [
+ Mock(content="No inconsistencies found."), # fact-check
+ Mock(content="I cannot determine who this person is."), # main
+ Mock(content="John Smith"), # extraction
+ ]
+
+ handler = ForcedAnswerCitationHandler(
+ llm=mock_llm,
+ settings_snapshot={"general.enable_fact_checking": True},
+ )
+
+ result = handler.analyze_followup(
+ "Who is the person?",
+ sample_search_results,
+ sample_previous_knowledge,
+ nr_of_links=0,
+ )
+
+ assert mock_llm.invoke.call_count == 3
+ assert "John Smith" in result["content"]
+
+
+class TestForcedAnswerEdgeCases:
+ """Tests for edge cases and error handling."""
+
+ def test_empty_search_results(self, mock_llm, empty_search_results):
+ """Test handling of empty search results."""
+ from local_deep_research.citation_handlers.forced_answer_citation_handler import (
+ ForcedAnswerCitationHandler,
+ )
+
+ handler = ForcedAnswerCitationHandler(llm=mock_llm)
+
+ result = handler.analyze_initial("What is it?", empty_search_results)
+
+ assert result["documents"] == []
+
+ def test_string_search_results(self, mock_llm, string_search_results):
+ """Test handling of string search results."""
+ from local_deep_research.citation_handlers.forced_answer_citation_handler import (
+ ForcedAnswerCitationHandler,
+ )
+
+ handler = ForcedAnswerCitationHandler(llm=mock_llm)
+
+ result = handler.analyze_initial("What is it?", string_search_results)
+
+ assert result["documents"] == []
+
+ def test_with_output_instructions(
+ self, mock_llm, sample_search_results, settings_with_output_instructions
+ ):
+ """Test that output instructions are included in prompts."""
+ from local_deep_research.citation_handlers.forced_answer_citation_handler import (
+ ForcedAnswerCitationHandler,
+ )
+
+ # Use response that won't trigger extraction
+ mock_llm.invoke.return_value = Mock(
+ content="The answer is X. According to [1], this is correct."
+ )
+
+ handler = ForcedAnswerCitationHandler(
+ llm=mock_llm, settings_snapshot=settings_with_output_instructions
+ )
+
+ handler.analyze_initial("What is it?", sample_search_results)
+
+ # Check the first call (initial prompt, not extraction)
+ call_args = mock_llm.invoke.call_args_list[0][0][0]
+ assert "formal academic English" in call_args
+
+ def test_nr_of_links_offset_applied(
+ self, mock_llm, sample_search_results, sample_previous_knowledge
+ ):
+ """Test that nr_of_links offset is correctly applied to document indices."""
+ from local_deep_research.citation_handlers.forced_answer_citation_handler import (
+ ForcedAnswerCitationHandler,
+ )
+
+ handler = ForcedAnswerCitationHandler(
+ llm=mock_llm,
+ settings_snapshot={"general.enable_fact_checking": False},
+ )
+
+ result = handler.analyze_followup(
+ "Question?",
+ sample_search_results,
+ sample_previous_knowledge,
+ nr_of_links=10,
+ )
+
+ # First document should have index 11 (10 + 1)
+ assert result["documents"][0].metadata["index"] == 11
diff --git a/tests/citation_handlers/test_precision_extraction_handler.py b/tests/citation_handlers/test_precision_extraction_handler.py
new file mode 100644
index 0000000000..fc6e3e4209
--- /dev/null
+++ b/tests/citation_handlers/test_precision_extraction_handler.py
@@ -0,0 +1,749 @@
+"""
+Comprehensive tests for PrecisionExtractionHandler.
+Tests question type detection, various extraction methods, and edge cases.
+"""
+
+import pytest
+from unittest.mock import Mock
+
+
+class TestPrecisionExtractionHandlerInit:
+ """Tests for PrecisionExtractionHandler initialization."""
+
+ def test_init_with_llm_only(self, mock_llm):
+ """Test initialization with just an LLM."""
+ from local_deep_research.citation_handlers.precision_extraction_handler import (
+ PrecisionExtractionHandler,
+ )
+
+ handler = PrecisionExtractionHandler(llm=mock_llm)
+
+ assert handler.llm == mock_llm
+ assert handler.settings_snapshot == {}
+
+ def test_init_creates_answer_patterns(self, mock_llm):
+ """Test initialization creates regex patterns."""
+ from local_deep_research.citation_handlers.precision_extraction_handler import (
+ PrecisionExtractionHandler,
+ )
+
+ handler = PrecisionExtractionHandler(llm=mock_llm)
+
+ assert "full_name" in handler.answer_patterns
+ assert "year" in handler.answer_patterns
+ assert "number" in handler.answer_patterns
+ assert "dimension" in handler.answer_patterns
+ assert "score" in handler.answer_patterns
+
+ def test_init_with_settings_snapshot(
+ self, mock_llm, settings_with_fact_checking
+ ):
+ """Test initialization with settings snapshot."""
+ from local_deep_research.citation_handlers.precision_extraction_handler import (
+ PrecisionExtractionHandler,
+ )
+
+ handler = PrecisionExtractionHandler(
+ llm=mock_llm, settings_snapshot=settings_with_fact_checking
+ )
+
+ assert handler.settings_snapshot == settings_with_fact_checking
+
+
+class TestPrecisionExtractionIdentifyQuestionType:
+ """Tests for _identify_question_type method."""
+
+ @pytest.fixture
+ def handler(self, mock_llm):
+ """Create a PrecisionExtractionHandler."""
+ from local_deep_research.citation_handlers.precision_extraction_handler import (
+ PrecisionExtractionHandler,
+ )
+
+ return PrecisionExtractionHandler(llm=mock_llm)
+
+ def test_identifies_full_name_question(self, handler):
+ """Test detection of full name questions."""
+ assert (
+ handler._identify_question_type(
+ "What is the full name of the founder?"
+ )
+ == "full_name"
+ )
+
+ def test_identifies_name_question_with_name_of(self, handler):
+ """Test detection of name questions with 'name of'."""
+ assert (
+ handler._identify_question_type("What is the name of the CEO?")
+ == "name"
+ )
+
+ def test_identifies_name_question_with_who_was(self, handler):
+ """Test detection of name questions with 'who was'."""
+ assert (
+ handler._identify_question_type("Who was the inventor?") == "name"
+ )
+
+ def test_identifies_name_question_with_who_is(self, handler):
+ """Test detection of name questions with 'who is'."""
+ assert (
+ handler._identify_question_type("Who is the current president?")
+ == "name"
+ )
+
+ def test_identifies_location_question_with_where(self, handler):
+ """Test detection of location questions with 'where'."""
+ assert (
+ handler._identify_question_type("Where did it happen?")
+ == "location"
+ )
+
+ def test_identifies_location_question_with_city(self, handler):
+ """Test detection of location questions mentioning city."""
+ assert (
+ handler._identify_question_type(
+ "In which city was the company founded?"
+ )
+ == "location"
+ )
+
+ def test_identifies_location_question_with_country(self, handler):
+ """Test detection of location questions mentioning country."""
+ assert (
+ handler._identify_question_type("What country is it located in?")
+ == "location"
+ )
+
+ def test_identifies_temporal_question_with_when(self, handler):
+ """Test detection of temporal questions with 'when'."""
+ assert (
+ handler._identify_question_type("When was the company founded?")
+ == "temporal"
+ )
+
+ def test_identifies_temporal_question_with_year(self, handler):
+ """Test detection of temporal questions with 'year'."""
+ assert (
+ handler._identify_question_type("In what year did the war begin?")
+ == "temporal"
+ )
+
+ def test_identifies_temporal_question_with_date(self, handler):
+ """Test detection of temporal questions with 'date'."""
+ assert (
+ handler._identify_question_type("What is the date of the event?")
+ == "temporal"
+ )
+
+ def test_identifies_number_question_with_how_many(self, handler):
+ """Test detection of number questions with 'how many'."""
+ assert (
+ handler._identify_question_type("How many employees work there?")
+ == "number"
+ )
+
+ def test_identifies_number_question_with_how_much(self, handler):
+ """Test detection of number questions with 'how much'."""
+ assert (
+ handler._identify_question_type("How much did it cost?") == "number"
+ )
+
+ def test_identifies_score_question(self, handler):
+ """Test detection of score questions."""
+ assert (
+ handler._identify_question_type("What was the final score?")
+ == "score"
+ )
+
+ def test_identifies_score_question_with_result(self, handler):
+ """Test detection of score questions with 'result'."""
+ assert (
+ handler._identify_question_type("What was the result of the match?")
+ == "score"
+ )
+
+ def test_identifies_dimension_question_with_height(self, handler):
+ """Test detection of dimension questions with 'height'."""
+ assert (
+ handler._identify_question_type(
+ "What is the height of the building?"
+ )
+ == "dimension"
+ )
+
+ def test_identifies_dimension_question_with_tall(self, handler):
+ """Test detection of dimension questions with 'tall'."""
+ assert (
+ handler._identify_question_type("How tall is the tower?")
+ == "dimension"
+ )
+
+ def test_identifies_dimension_question_with_length(self, handler):
+ """Test detection of dimension questions with 'length'."""
+ assert (
+ handler._identify_question_type("What is the length of the bridge?")
+ == "dimension"
+ )
+
+ def test_identifies_single_choice_question(self, handler):
+ """Test detection of single choice questions."""
+ assert (
+ handler._identify_question_type("Which one of these is correct?")
+ == "single_choice"
+ )
+
+ def test_returns_general_for_ambiguous_question(self, handler):
+ """Test that ambiguous questions return 'general'."""
+ assert (
+ handler._identify_question_type("What happened in the meeting?")
+ == "general"
+ )
+
+ def test_case_insensitive_detection(self, handler):
+ """Test case-insensitive question type detection."""
+ assert (
+ handler._identify_question_type("WHAT IS THE FULL NAME?")
+ == "full_name"
+ )
+ assert (
+ handler._identify_question_type("WHERE DID IT HAPPEN?")
+ == "location"
+ )
+
+
+class TestPrecisionExtractionRegexPatterns:
+ """Tests for regex pattern matching."""
+
+ @pytest.fixture
+ def handler(self, mock_llm):
+ """Create a PrecisionExtractionHandler."""
+ from local_deep_research.citation_handlers.precision_extraction_handler import (
+ PrecisionExtractionHandler,
+ )
+
+ return PrecisionExtractionHandler(llm=mock_llm)
+
+ def test_full_name_pattern_matches_two_words(self, handler):
+ """Test full name pattern matches two-word names."""
+ matches = handler.answer_patterns["full_name"].findall(
+ "John Smith went to the store."
+ )
+ assert "John Smith" in matches
+
+ def test_full_name_pattern_matches_three_words(self, handler):
+ """Test full name pattern matches three-word names."""
+ matches = handler.answer_patterns["full_name"].findall(
+ "John Michael Smith was born."
+ )
+ assert "John Michael Smith" in matches
+
+ def test_year_pattern_matches_1900s(self, handler):
+ """Test year pattern matches 1900s years."""
+ matches = handler.answer_patterns["year"].findall("Founded in 1995.")
+ assert "1995" in matches
+
+ def test_year_pattern_matches_2000s(self, handler):
+ """Test year pattern matches 2000s years."""
+ matches = handler.answer_patterns["year"].findall("Launched in 2024.")
+ assert "2024" in matches
+
+ def test_number_pattern_matches_integer(self, handler):
+ """Test number pattern matches integers."""
+ matches = handler.answer_patterns["number"].findall(
+ "There are 42 employees."
+ )
+ assert "42" in matches
+
+ def test_number_pattern_matches_decimal(self, handler):
+ """Test number pattern matches decimals."""
+ matches = handler.answer_patterns["number"].findall(
+ "The cost is 19.99 dollars."
+ )
+ assert "19.99" in matches
+
+ def test_dimension_pattern_matches_meters(self, handler):
+ """Test dimension pattern matches meters."""
+ matches = handler.answer_patterns["dimension"].findall(
+ "The tower is 324 meters tall."
+ )
+ assert ("324", "meters") in matches
+
+ def test_dimension_pattern_matches_feet(self, handler):
+ """Test dimension pattern matches feet."""
+ matches = handler.answer_patterns["dimension"].findall(
+ "It is 100 feet high."
+ )
+ assert ("100", "feet") in matches
+
+ def test_dimension_pattern_matches_kg(self, handler):
+ """Test dimension pattern matches kilograms."""
+ matches = handler.answer_patterns["dimension"].findall("Weighs 50 kg.")
+ assert ("50", "kg") in matches
+
+ def test_score_pattern_matches_hyphen_format(self, handler):
+ """Test score pattern matches X-Y format."""
+ matches = handler.answer_patterns["score"].findall(
+ "Final score was 3-2."
+ )
+ assert ("3", "2") in matches
+
+ def test_score_pattern_matches_dash_format(self, handler):
+ """Test score pattern matches X–Y format (en-dash)."""
+ matches = handler.answer_patterns["score"].findall(
+ "Final score was 3–2."
+ )
+ assert ("3", "2") in matches
+
+
+class TestPrecisionExtractionMethods:
+ """Tests for individual extraction methods."""
+
+ @pytest.fixture
+ def handler(self, mock_llm):
+ """Create a PrecisionExtractionHandler."""
+ from local_deep_research.citation_handlers.precision_extraction_handler import (
+ PrecisionExtractionHandler,
+ )
+
+ return PrecisionExtractionHandler(llm=mock_llm)
+
+ def test_extract_full_name_with_llm(self, handler, mock_llm):
+ """Test _extract_full_name calls LLM."""
+ mock_llm.invoke.return_value = Mock(
+ content="Full name: John Michael Smith"
+ )
+
+ result = handler._extract_full_name(
+ "John Smith was a scientist.", "Who is it?", "Sources"
+ )
+
+ mock_llm.invoke.assert_called_once()
+ assert "John Michael Smith" in result
+
+ def test_extract_full_name_fallback_to_longest(self, handler, mock_llm):
+ """Test _extract_full_name falls back to longest name when LLM doesn't identify."""
+ mock_llm.invoke.return_value = Mock(content="No full name identified")
+
+ content = "John Michael Smith and John Smith were scientists."
+ result = handler._extract_full_name(content, "Who is it?", "Sources")
+
+ # Should pick the longer name
+ assert "John Michael Smith" in result
+
+ def test_extract_full_name_handles_exception(self, handler, mock_llm):
+ """Test _extract_full_name handles exceptions gracefully."""
+ mock_llm.invoke.side_effect = Exception("LLM error")
+
+ result = handler._extract_full_name(
+ "John Smith content", "Who?", "Sources"
+ )
+
+ # Should return original content
+ assert "John Smith content" == result
+
+ def test_extract_best_name_returns_most_frequent(self, handler):
+ """Test _extract_best_name returns most frequent name."""
+ content = "John Smith said hello. Smith was happy. John Smith left."
+
+ result = handler._extract_best_name(content, "Who is it?", "Sources")
+
+ assert "John Smith" in result
+
+ def test_extract_dimension_with_llm(self, handler, mock_llm):
+ """Test _extract_dimension calls LLM."""
+ mock_llm.invoke.return_value = Mock(content="324 meters")
+
+ result = handler._extract_dimension(
+ "The tower is 324 meters tall.", "How tall?", "Sources"
+ )
+
+ mock_llm.invoke.assert_called_once()
+ assert "324" in result
+
+ def test_extract_dimension_fallback_to_pattern(self, handler, mock_llm):
+ """Test _extract_dimension falls back to regex pattern."""
+ mock_llm.invoke.return_value = Mock(content="No clear answer")
+
+ content = "The tower is 324 meters tall."
+ result = handler._extract_dimension(content, "How tall?", "Sources")
+
+ # Should still extract the measurement
+ assert "324" in result or "meters" in result or content == result
+
+ def test_extract_score_with_multiple_scores(self, handler, mock_llm):
+ """Test _extract_score when multiple scores present."""
+ mock_llm.invoke.return_value = Mock(content="3-2")
+
+ content = "Halftime was 1-1. Final score was 3-2."
+ result = handler._extract_score(
+ content, "What was the final score?", "Sources"
+ )
+
+ mock_llm.invoke.assert_called_once()
+ assert "3-2" in result
+
+ def test_extract_score_no_scores_returns_content(self, handler, mock_llm):
+ """Test _extract_score returns content when no scores found."""
+ content = "The game was exciting."
+ result = handler._extract_score(
+ content, "What was the score?", "Sources"
+ )
+
+ assert result == content
+
+ def test_extract_temporal_with_llm(self, handler, mock_llm):
+ """Test _extract_temporal calls LLM."""
+ mock_llm.invoke.return_value = Mock(content="1998")
+
+ content = "Founded in 1998, acquired in 2015."
+ result = handler._extract_temporal(
+ content, "When was it founded?", "Sources"
+ )
+
+ mock_llm.invoke.assert_called_once()
+ assert "1998" in result
+
+ def test_extract_temporal_no_years_returns_content(self, handler, mock_llm):
+ """Test _extract_temporal returns content when no years found."""
+ content = "It happened long ago."
+ result = handler._extract_temporal(content, "When?", "Sources")
+
+ assert result == content
+
+ def test_extract_number_with_llm(self, handler, mock_llm):
+ """Test _extract_number calls LLM."""
+ mock_llm.invoke.return_value = Mock(content="42")
+
+ content = "There are 42 employees and 10 managers."
+ result = handler._extract_number(
+ content, "How many employees?", "Sources"
+ )
+
+ mock_llm.invoke.assert_called_once()
+ assert "42" in result
+
+ def test_extract_single_answer_removes_alternatives(
+ self, handler, mock_llm
+ ):
+ """Test _extract_single_answer removes comma/and/or alternatives."""
+ mock_llm.invoke.return_value = Mock(
+ content="Option A, Option B, and Option C"
+ )
+
+ result = handler._extract_single_answer(
+ "Multiple options content", "Which one?", "Sources"
+ )
+
+ # Should only have first option
+ assert "Option A" in result
+ assert "Option B" not in result.split(".")[0]
+
+ def test_extract_key_facts_from_previous_knowledge(self, handler, mock_llm):
+ """Test _extract_key_facts extracts from previous knowledge."""
+ mock_llm.invoke.return_value = Mock(
+ content="Key facts: Founded 1998, Location: NYC"
+ )
+
+ result = handler._extract_key_facts(
+ "Previous knowledge about the company", "name"
+ )
+
+ mock_llm.invoke.assert_called_once()
+ assert len(result) <= 500
+
+ def test_extract_key_facts_handles_exception(self, handler, mock_llm):
+ """Test _extract_key_facts handles exception gracefully."""
+ mock_llm.invoke.side_effect = Exception("LLM error")
+
+ result = handler._extract_key_facts("Previous knowledge", "name")
+
+ # Should return truncated previous knowledge
+ assert "Previous knowledge" in result
+
+
+class TestPrecisionExtractionAnalyzeInitial:
+ """Tests for analyze_initial method."""
+
+ def test_analyze_initial_returns_content_and_documents(
+ self, mock_llm, sample_search_results
+ ):
+ """Test analyze_initial returns proper structure."""
+ from local_deep_research.citation_handlers.precision_extraction_handler import (
+ PrecisionExtractionHandler,
+ )
+
+ handler = PrecisionExtractionHandler(llm=mock_llm)
+
+ result = handler.analyze_initial(
+ "What is the topic?", sample_search_results
+ )
+
+ assert "content" in result
+ assert "documents" in result
+ assert len(result["documents"]) == 3
+
+ def test_analyze_initial_prompt_includes_question_type(
+ self, mock_llm, sample_search_results
+ ):
+ """Test analyze_initial prompt includes detected question type."""
+ from local_deep_research.citation_handlers.precision_extraction_handler import (
+ PrecisionExtractionHandler,
+ )
+
+ mock_llm.invoke.return_value = Mock(
+ content="The full name is John Smith. [1]"
+ )
+
+ handler = PrecisionExtractionHandler(llm=mock_llm)
+
+ handler.analyze_initial(
+ "What is the full name of the founder?", sample_search_results
+ )
+
+ call_args = mock_llm.invoke.call_args_list[0][0][0]
+ assert "full_name" in call_args
+
+ def test_analyze_initial_prompt_includes_precision_instructions(
+ self, mock_llm, sample_search_results
+ ):
+ """Test analyze_initial prompt includes precision extraction instructions."""
+ from local_deep_research.citation_handlers.precision_extraction_handler import (
+ PrecisionExtractionHandler,
+ )
+
+ mock_llm.invoke.return_value = Mock(content="Answer [1]")
+
+ handler = PrecisionExtractionHandler(llm=mock_llm)
+
+ handler.analyze_initial("What is it?", sample_search_results)
+
+ call_args = mock_llm.invoke.call_args_list[0][0][0]
+ assert "PRECISION" in call_args
+ assert "EXACT answer" in call_args
+
+ def test_analyze_initial_applies_extraction_for_full_name(
+ self, mock_llm, name_search_results
+ ):
+ """Test analyze_initial applies extraction for full_name questions."""
+ from local_deep_research.citation_handlers.precision_extraction_handler import (
+ PrecisionExtractionHandler,
+ )
+
+ # First call returns LLM response, second call extracts name
+ mock_llm.invoke.side_effect = [
+ Mock(content="The person is John Smith."),
+ Mock(content="Full name: John Michael William Smith"),
+ ]
+
+ handler = PrecisionExtractionHandler(llm=mock_llm)
+
+ handler.analyze_initial("What is the full name?", name_search_results)
+
+ # Should have called extraction
+ assert mock_llm.invoke.call_count >= 1
+
+ def test_analyze_initial_handles_string_response(
+ self, mock_llm_string_response, sample_search_results
+ ):
+ """Test analyze_initial handles string LLM response."""
+ from local_deep_research.citation_handlers.precision_extraction_handler import (
+ PrecisionExtractionHandler,
+ )
+
+ handler = PrecisionExtractionHandler(llm=mock_llm_string_response)
+
+ result = handler.analyze_initial("What is it?", sample_search_results)
+
+ assert "content" in result
+
+
+class TestPrecisionExtractionAnalyzeFollowup:
+ """Tests for analyze_followup method."""
+
+ def test_analyze_followup_returns_content_and_documents(
+ self, mock_llm, sample_search_results, sample_previous_knowledge
+ ):
+ """Test analyze_followup returns proper structure."""
+ from local_deep_research.citation_handlers.precision_extraction_handler import (
+ PrecisionExtractionHandler,
+ )
+
+ handler = PrecisionExtractionHandler(llm=mock_llm)
+
+ result = handler.analyze_followup(
+ "Follow-up question?",
+ sample_search_results,
+ sample_previous_knowledge,
+ nr_of_links=3,
+ )
+
+ assert "content" in result
+ assert "documents" in result
+
+ def test_analyze_followup_extracts_key_facts(
+ self, mock_llm, sample_search_results, sample_previous_knowledge
+ ):
+ """Test analyze_followup extracts key facts from previous knowledge."""
+ from local_deep_research.citation_handlers.precision_extraction_handler import (
+ PrecisionExtractionHandler,
+ )
+
+ mock_llm.invoke.return_value = Mock(content="Key facts extracted")
+
+ handler = PrecisionExtractionHandler(llm=mock_llm)
+
+ handler.analyze_followup(
+ "What year was it founded?",
+ sample_search_results,
+ sample_previous_knowledge,
+ nr_of_links=0,
+ )
+
+ # Should have called LLM for key facts extraction
+ first_call = mock_llm.invoke.call_args_list[0][0][0]
+ assert (
+ "key facts" in first_call.lower() or "extract" in first_call.lower()
+ )
+
+ def test_analyze_followup_applies_nr_of_links_offset(
+ self, mock_llm, sample_search_results, sample_previous_knowledge
+ ):
+ """Test analyze_followup applies nr_of_links offset to document indices."""
+ from local_deep_research.citation_handlers.precision_extraction_handler import (
+ PrecisionExtractionHandler,
+ )
+
+ handler = PrecisionExtractionHandler(llm=mock_llm)
+
+ result = handler.analyze_followup(
+ "Question?",
+ sample_search_results,
+ sample_previous_knowledge,
+ nr_of_links=10,
+ )
+
+ # First document should have index 11 (10 + 1)
+ assert result["documents"][0].metadata["index"] == 11
+
+
+class TestPrecisionExtractionEdgeCases:
+ """Tests for edge cases and error handling."""
+
+ def test_empty_search_results(self, mock_llm, empty_search_results):
+ """Test handling of empty search results."""
+ from local_deep_research.citation_handlers.precision_extraction_handler import (
+ PrecisionExtractionHandler,
+ )
+
+ handler = PrecisionExtractionHandler(llm=mock_llm)
+
+ result = handler.analyze_initial("What is it?", empty_search_results)
+
+ assert result["documents"] == []
+
+ def test_string_search_results(self, mock_llm, string_search_results):
+ """Test handling of string search results."""
+ from local_deep_research.citation_handlers.precision_extraction_handler import (
+ PrecisionExtractionHandler,
+ )
+
+ handler = PrecisionExtractionHandler(llm=mock_llm)
+
+ result = handler.analyze_initial("What is it?", string_search_results)
+
+ assert result["documents"] == []
+
+ def test_with_output_instructions(
+ self, mock_llm, sample_search_results, settings_with_output_instructions
+ ):
+ """Test that output instructions are included in prompts."""
+ from local_deep_research.citation_handlers.precision_extraction_handler import (
+ PrecisionExtractionHandler,
+ )
+
+ mock_llm.invoke.return_value = Mock(content="Response")
+
+ handler = PrecisionExtractionHandler(
+ llm=mock_llm, settings_snapshot=settings_with_output_instructions
+ )
+
+ handler.analyze_initial("What is it?", sample_search_results)
+
+ call_args = mock_llm.invoke.call_args_list[0][0][0]
+ assert "formal academic English" in call_args
+
+ def test_general_question_type_no_extraction(
+ self, mock_llm, sample_search_results
+ ):
+ """Test that general question type doesn't apply special extraction."""
+ from local_deep_research.citation_handlers.precision_extraction_handler import (
+ PrecisionExtractionHandler,
+ )
+
+ mock_llm.invoke.return_value = Mock(content="General response")
+
+ handler = PrecisionExtractionHandler(llm=mock_llm)
+
+ result = handler.analyze_initial(
+ "What happened?", sample_search_results
+ )
+
+ # Should just return the LLM response without extraction modifications
+ assert result["content"] == "General response"
+
+ def test_apply_precision_extraction_returns_content_for_unknown_type(
+ self, mock_llm
+ ):
+ """Test _apply_precision_extraction returns content for unknown question type."""
+ from local_deep_research.citation_handlers.precision_extraction_handler import (
+ PrecisionExtractionHandler,
+ )
+
+ handler = PrecisionExtractionHandler(llm=mock_llm)
+
+ result = handler._apply_precision_extraction(
+ "Original content", "Query?", "unknown_type", "Sources"
+ )
+
+ assert result == "Original content"
+
+
+class TestPrecisionExtractionDimensionContextAwareness:
+ """Tests for dimension extraction context awareness."""
+
+ @pytest.fixture
+ def handler(self, mock_llm):
+ """Create a PrecisionExtractionHandler."""
+ from local_deep_research.citation_handlers.precision_extraction_handler import (
+ PrecisionExtractionHandler,
+ )
+
+ return PrecisionExtractionHandler(llm=mock_llm)
+
+ def test_dimension_types_include_height(self, handler):
+ """Test dimension type detection includes height keywords."""
+ question_type = handler._identify_question_type(
+ "What is the height of the building?"
+ )
+ assert question_type == "dimension"
+
+ def test_dimension_types_include_size(self, handler):
+ """Test dimension type detection includes size keywords."""
+ question_type = handler._identify_question_type(
+ "What is the size of the building?"
+ )
+ assert question_type == "dimension"
+
+ def test_dimension_types_include_length(self, handler):
+ """Test dimension type detection includes length keywords."""
+ question_type = handler._identify_question_type(
+ "What is the length of the bridge?"
+ )
+ assert question_type == "dimension"
+
+ def test_dimension_types_include_width(self, handler):
+ """Test dimension type detection includes width keywords."""
+ question_type = handler._identify_question_type(
+ "How wide is the river?"
+ )
+ assert question_type == "dimension"
diff --git a/tests/citation_handlers/test_standard_citation_handler.py b/tests/citation_handlers/test_standard_citation_handler.py
new file mode 100644
index 0000000000..9c3aed2379
--- /dev/null
+++ b/tests/citation_handlers/test_standard_citation_handler.py
@@ -0,0 +1,517 @@
+"""
+Comprehensive tests for StandardCitationHandler.
+Tests initialization, analyze_initial, analyze_followup, and edge cases.
+"""
+
+from datetime import datetime, timezone
+
+
+class TestStandardCitationHandlerInit:
+ """Tests for StandardCitationHandler initialization."""
+
+ def test_init_with_llm_only(self, mock_llm):
+ """Test initialization with just an LLM."""
+ from local_deep_research.citation_handlers.standard_citation_handler import (
+ StandardCitationHandler,
+ )
+
+ handler = StandardCitationHandler(llm=mock_llm)
+
+ assert handler.llm == mock_llm
+ assert handler.settings_snapshot == {}
+
+ def test_init_with_settings_snapshot(
+ self, mock_llm, settings_with_fact_checking
+ ):
+ """Test initialization with settings snapshot."""
+ from local_deep_research.citation_handlers.standard_citation_handler import (
+ StandardCitationHandler,
+ )
+
+ handler = StandardCitationHandler(
+ llm=mock_llm, settings_snapshot=settings_with_fact_checking
+ )
+
+ assert handler.settings_snapshot == settings_with_fact_checking
+
+ def test_init_with_none_settings(self, mock_llm):
+ """Test initialization with None settings defaults to empty dict."""
+ from local_deep_research.citation_handlers.standard_citation_handler import (
+ StandardCitationHandler,
+ )
+
+ handler = StandardCitationHandler(llm=mock_llm, settings_snapshot=None)
+
+ assert handler.settings_snapshot == {}
+
+
+class TestStandardCitationHandlerGetSetting:
+ """Tests for get_setting method inherited from base."""
+
+ def test_get_setting_returns_value(
+ self, mock_llm, settings_with_fact_checking
+ ):
+ """Test get_setting returns correct value."""
+ from local_deep_research.citation_handlers.standard_citation_handler import (
+ StandardCitationHandler,
+ )
+
+ handler = StandardCitationHandler(
+ llm=mock_llm, settings_snapshot=settings_with_fact_checking
+ )
+
+ result = handler.get_setting("general.enable_fact_checking")
+
+ assert result is True
+
+ def test_get_setting_returns_default_for_missing_key(self, mock_llm):
+ """Test get_setting returns default for missing key."""
+ from local_deep_research.citation_handlers.standard_citation_handler import (
+ StandardCitationHandler,
+ )
+
+ handler = StandardCitationHandler(llm=mock_llm)
+
+ result = handler.get_setting("nonexistent.key", default="default_value")
+
+ assert result == "default_value"
+
+ def test_get_setting_extracts_value_from_dict(
+ self, mock_llm, settings_with_dict_value
+ ):
+ """Test get_setting extracts value from dict format."""
+ from local_deep_research.citation_handlers.standard_citation_handler import (
+ StandardCitationHandler,
+ )
+
+ handler = StandardCitationHandler(
+ llm=mock_llm, settings_snapshot=settings_with_dict_value
+ )
+
+ result = handler.get_setting("general.enable_fact_checking")
+
+ assert result is True
+
+
+class TestStandardCitationHandlerAnalyzeInitial:
+ """Tests for analyze_initial method."""
+
+ def test_analyze_initial_returns_content_and_documents(
+ self, mock_llm, sample_search_results
+ ):
+ """Test analyze_initial returns proper structure."""
+ from local_deep_research.citation_handlers.standard_citation_handler import (
+ StandardCitationHandler,
+ )
+
+ handler = StandardCitationHandler(llm=mock_llm)
+
+ result = handler.analyze_initial(
+ "What is the topic?", sample_search_results
+ )
+
+ assert "content" in result
+ assert "documents" in result
+ assert len(result["documents"]) == 3
+
+ def test_analyze_initial_calls_llm_invoke(
+ self, mock_llm, sample_search_results
+ ):
+ """Test analyze_initial calls LLM invoke."""
+ from local_deep_research.citation_handlers.standard_citation_handler import (
+ StandardCitationHandler,
+ )
+
+ handler = StandardCitationHandler(llm=mock_llm)
+
+ handler.analyze_initial("Test query", sample_search_results)
+
+ mock_llm.invoke.assert_called_once()
+
+ def test_analyze_initial_includes_query_in_prompt(
+ self, mock_llm, sample_search_results
+ ):
+ """Test analyze_initial includes query in LLM prompt."""
+ from local_deep_research.citation_handlers.standard_citation_handler import (
+ StandardCitationHandler,
+ )
+
+ handler = StandardCitationHandler(llm=mock_llm)
+
+ handler.analyze_initial("Specific test query", sample_search_results)
+
+ call_args = mock_llm.invoke.call_args[0][0]
+ assert "Specific test query" in call_args
+
+ def test_analyze_initial_includes_sources_in_prompt(
+ self, mock_llm, sample_search_results
+ ):
+ """Test analyze_initial includes formatted sources in prompt."""
+ from local_deep_research.citation_handlers.standard_citation_handler import (
+ StandardCitationHandler,
+ )
+
+ handler = StandardCitationHandler(llm=mock_llm)
+
+ handler.analyze_initial("Test query", sample_search_results)
+
+ call_args = mock_llm.invoke.call_args[0][0]
+ assert "[1]" in call_args
+ assert "full content of the first test article" in call_args
+
+ def test_analyze_initial_includes_timestamp(
+ self, mock_llm, sample_search_results
+ ):
+ """Test analyze_initial includes current timestamp."""
+ from local_deep_research.citation_handlers.standard_citation_handler import (
+ StandardCitationHandler,
+ )
+
+ handler = StandardCitationHandler(llm=mock_llm)
+
+ handler.analyze_initial("Test query", sample_search_results)
+
+ call_args = mock_llm.invoke.call_args[0][0]
+ assert "UTC" in call_args
+ # Should contain year
+ current_year = str(datetime.now(timezone.utc).year)
+ assert current_year in call_args
+
+ def test_analyze_initial_handles_string_response(
+ self, mock_llm_string_response, sample_search_results
+ ):
+ """Test analyze_initial handles string LLM response."""
+ from local_deep_research.citation_handlers.standard_citation_handler import (
+ StandardCitationHandler,
+ )
+
+ handler = StandardCitationHandler(llm=mock_llm_string_response)
+
+ result = handler.analyze_initial("Test query", sample_search_results)
+
+ assert result["content"] == "Test string response with citation [1]."
+
+ def test_analyze_initial_handles_object_response(
+ self, mock_llm, sample_search_results
+ ):
+ """Test analyze_initial handles object LLM response with .content."""
+ from local_deep_research.citation_handlers.standard_citation_handler import (
+ StandardCitationHandler,
+ )
+
+ handler = StandardCitationHandler(llm=mock_llm)
+
+ result = handler.analyze_initial("Test query", sample_search_results)
+
+ assert result["content"] == "Test response with citation [1]."
+
+ def test_analyze_initial_with_output_instructions(
+ self, mock_llm, sample_search_results, settings_with_output_instructions
+ ):
+ """Test analyze_initial includes output instructions in prompt."""
+ from local_deep_research.citation_handlers.standard_citation_handler import (
+ StandardCitationHandler,
+ )
+
+ handler = StandardCitationHandler(
+ llm=mock_llm, settings_snapshot=settings_with_output_instructions
+ )
+
+ handler.analyze_initial("Test query", sample_search_results)
+
+ call_args = mock_llm.invoke.call_args[0][0]
+ assert "formal academic English" in call_args
+
+ def test_analyze_initial_with_empty_results(
+ self, mock_llm, empty_search_results
+ ):
+ """Test analyze_initial with empty search results."""
+ from local_deep_research.citation_handlers.standard_citation_handler import (
+ StandardCitationHandler,
+ )
+
+ handler = StandardCitationHandler(llm=mock_llm)
+
+ result = handler.analyze_initial("Test query", empty_search_results)
+
+ assert result["documents"] == []
+
+ def test_analyze_initial_with_string_results(
+ self, mock_llm, string_search_results
+ ):
+ """Test analyze_initial with string search results (edge case)."""
+ from local_deep_research.citation_handlers.standard_citation_handler import (
+ StandardCitationHandler,
+ )
+
+ handler = StandardCitationHandler(llm=mock_llm)
+
+ result = handler.analyze_initial("Test query", string_search_results)
+
+ assert result["documents"] == []
+
+
+class TestStandardCitationHandlerAnalyzeFollowup:
+ """Tests for analyze_followup method."""
+
+ def test_analyze_followup_returns_content_and_documents(
+ self, mock_llm, sample_search_results, sample_previous_knowledge
+ ):
+ """Test analyze_followup returns proper structure."""
+ from local_deep_research.citation_handlers.standard_citation_handler import (
+ StandardCitationHandler,
+ )
+
+ handler = StandardCitationHandler(llm=mock_llm)
+
+ result = handler.analyze_followup(
+ "Follow-up question?",
+ sample_search_results,
+ sample_previous_knowledge,
+ nr_of_links=3,
+ )
+
+ assert "content" in result
+ assert "documents" in result
+
+ def test_analyze_followup_with_fact_checking_enabled(
+ self,
+ mock_llm,
+ sample_search_results,
+ sample_previous_knowledge,
+ settings_with_fact_checking,
+ ):
+ """Test analyze_followup calls LLM twice when fact-checking enabled."""
+ from local_deep_research.citation_handlers.standard_citation_handler import (
+ StandardCitationHandler,
+ )
+
+ handler = StandardCitationHandler(
+ llm=mock_llm, settings_snapshot=settings_with_fact_checking
+ )
+
+ handler.analyze_followup(
+ "Follow-up question?",
+ sample_search_results,
+ sample_previous_knowledge,
+ nr_of_links=0,
+ )
+
+ # Should call LLM twice: once for fact-checking, once for main response
+ assert mock_llm.invoke.call_count == 2
+
+ def test_analyze_followup_with_fact_checking_disabled(
+ self,
+ mock_llm,
+ sample_search_results,
+ sample_previous_knowledge,
+ settings_without_fact_checking,
+ ):
+ """Test analyze_followup calls LLM once when fact-checking disabled."""
+ from local_deep_research.citation_handlers.standard_citation_handler import (
+ StandardCitationHandler,
+ )
+
+ handler = StandardCitationHandler(
+ llm=mock_llm, settings_snapshot=settings_without_fact_checking
+ )
+
+ handler.analyze_followup(
+ "Follow-up question?",
+ sample_search_results,
+ sample_previous_knowledge,
+ nr_of_links=0,
+ )
+
+ # Should call LLM only once
+ assert mock_llm.invoke.call_count == 1
+
+ def test_analyze_followup_includes_previous_knowledge(
+ self, mock_llm, sample_search_results, sample_previous_knowledge
+ ):
+ """Test analyze_followup includes previous knowledge in prompt."""
+ from local_deep_research.citation_handlers.standard_citation_handler import (
+ StandardCitationHandler,
+ )
+
+ handler = StandardCitationHandler(
+ llm=mock_llm,
+ settings_snapshot={"general.enable_fact_checking": False},
+ )
+
+ handler.analyze_followup(
+ "Follow-up question?",
+ sample_search_results,
+ sample_previous_knowledge,
+ nr_of_links=0,
+ )
+
+ call_args = mock_llm.invoke.call_args[0][0]
+ assert "first studied in 1995" in call_args
+
+ def test_analyze_followup_uses_nr_of_links_offset(
+ self, mock_llm, sample_search_results, sample_previous_knowledge
+ ):
+ """Test analyze_followup applies nr_of_links offset to document indices."""
+ from local_deep_research.citation_handlers.standard_citation_handler import (
+ StandardCitationHandler,
+ )
+
+ handler = StandardCitationHandler(
+ llm=mock_llm,
+ settings_snapshot={"general.enable_fact_checking": False},
+ )
+
+ result = handler.analyze_followup(
+ "Follow-up question?",
+ sample_search_results,
+ sample_previous_knowledge,
+ nr_of_links=5,
+ )
+
+ # Documents should have indices starting at 6 (5 + 1)
+ assert result["documents"][0].metadata["index"] == 6
+ assert result["documents"][1].metadata["index"] == 7
+ assert result["documents"][2].metadata["index"] == 8
+
+ def test_analyze_followup_fact_check_prompt_structure(
+ self, mock_llm, sample_search_results, sample_previous_knowledge
+ ):
+ """Test fact-check prompt includes required elements."""
+ from local_deep_research.citation_handlers.standard_citation_handler import (
+ StandardCitationHandler,
+ )
+
+ handler = StandardCitationHandler(
+ llm=mock_llm,
+ settings_snapshot={"general.enable_fact_checking": True},
+ )
+
+ handler.analyze_followup(
+ "Follow-up question?",
+ sample_search_results,
+ sample_previous_knowledge,
+ nr_of_links=0,
+ )
+
+ # First call should be fact-check
+ first_call_args = mock_llm.invoke.call_args_list[0][0][0]
+ assert "Cross-reference" in first_call_args
+ assert "contradictions" in first_call_args
+
+
+class TestStandardCitationHandlerDocumentCreation:
+ """Tests for document creation functionality."""
+
+ def test_documents_have_correct_metadata(
+ self, mock_llm, sample_search_results
+ ):
+ """Test created documents have correct metadata."""
+ from local_deep_research.citation_handlers.standard_citation_handler import (
+ StandardCitationHandler,
+ )
+
+ handler = StandardCitationHandler(llm=mock_llm)
+
+ result = handler.analyze_initial("Test query", sample_search_results)
+
+ doc = result["documents"][0]
+ assert doc.metadata["source"] == "https://example.com/article1"
+ assert doc.metadata["title"] == "Test Article 1"
+ assert doc.metadata["index"] == 1
+
+ def test_documents_use_full_content_when_available(
+ self, mock_llm, sample_search_results
+ ):
+ """Test documents use full_content over snippet."""
+ from local_deep_research.citation_handlers.standard_citation_handler import (
+ StandardCitationHandler,
+ )
+
+ handler = StandardCitationHandler(llm=mock_llm)
+
+ result = handler.analyze_initial("Test query", sample_search_results)
+
+ # page_content should be the full content, not snippet
+ assert (
+ "full content of the first test article"
+ in result["documents"][0].page_content
+ )
+
+ def test_documents_fallback_to_snippet(self, mock_llm):
+ """Test documents fall back to snippet when full_content missing."""
+ from local_deep_research.citation_handlers.standard_citation_handler import (
+ StandardCitationHandler,
+ )
+
+ search_results = [
+ {
+ "title": "Test",
+ "link": "https://example.com",
+ "snippet": "Only snippet available",
+ }
+ ]
+
+ handler = StandardCitationHandler(llm=mock_llm)
+
+ result = handler.analyze_initial("Test query", search_results)
+
+ assert result["documents"][0].page_content == "Only snippet available"
+
+ def test_documents_preserve_existing_index(self, mock_llm):
+ """Test documents preserve pre-existing index."""
+ from local_deep_research.citation_handlers.standard_citation_handler import (
+ StandardCitationHandler,
+ )
+
+ search_results = [
+ {
+ "title": "Test",
+ "link": "https://example.com",
+ "snippet": "Test",
+ "index": "42", # Pre-existing index
+ }
+ ]
+
+ handler = StandardCitationHandler(llm=mock_llm)
+
+ result = handler.analyze_initial("Test query", search_results)
+
+ assert result["documents"][0].metadata["index"] == 42
+
+
+class TestStandardCitationHandlerSourceFormatting:
+ """Tests for source formatting functionality."""
+
+ def test_format_sources_includes_index(
+ self, mock_llm, sample_search_results
+ ):
+ """Test formatted sources include citation indices."""
+ from local_deep_research.citation_handlers.standard_citation_handler import (
+ StandardCitationHandler,
+ )
+
+ handler = StandardCitationHandler(llm=mock_llm)
+
+ handler.analyze_initial("Test query", sample_search_results)
+
+ call_args = mock_llm.invoke.call_args[0][0]
+ assert "[1]" in call_args
+ assert "[2]" in call_args
+ assert "[3]" in call_args
+
+ def test_format_sources_separates_with_newlines(
+ self, mock_llm, sample_search_results
+ ):
+ """Test formatted sources are separated by double newlines."""
+ from local_deep_research.citation_handlers.standard_citation_handler import (
+ StandardCitationHandler,
+ )
+
+ handler = StandardCitationHandler(llm=mock_llm)
+
+ handler.analyze_initial("Test query", sample_search_results)
+
+ call_args = mock_llm.invoke.call_args[0][0]
+ # Sources should be separated by \n\n
+ assert "\n\n" in call_args