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.

test: add tests to improve code coverage

LearningCircuit9ab0f9b8d274
diff --git a/tests/benchmarks/__init__.py b/tests/benchmarks/__init__.py
new file mode 100644
index 0000000000..7017caeb32
--- /dev/null
+++ b/tests/benchmarks/__init__.py
@@ -0,0 +1 @@
+"""Tests for the benchmarks module."""
diff --git a/tests/benchmarks/test_graders.py b/tests/benchmarks/test_graders.py
new file mode 100644
index 0000000000..2d25166bc2
--- /dev/null
+++ b/tests/benchmarks/test_graders.py
@@ -0,0 +1,280 @@
+"""
+Tests for benchmarks/graders.py
+
+Tests cover:
+- extract_answer_from_response function
+- grade_single_result with mocked LLM
+- get_evaluation_llm configuration
+"""
+
+from unittest.mock import Mock, patch, MagicMock
+
+
+class TestExtractAnswerFromResponse:
+ """Tests for the extract_answer_from_response function."""
+
+ def test_browsecomp_extracts_exact_answer(self):
+ """Test extraction of exact answer from BrowseComp response."""
+ from local_deep_research.benchmarks.graders import (
+ extract_answer_from_response,
+ )
+
+ response = """
+Based on my research, I found the following information.
+
+Exact Answer: 42
+Confidence: 95%
+"""
+ result = extract_answer_from_response(
+ response, dataset_type="browsecomp"
+ )
+
+ assert result["extracted_answer"] == "42"
+ assert result["confidence"] == "95"
+
+ def test_browsecomp_missing_answer_returns_none(self):
+ """Test handling of missing answer in BrowseComp response."""
+ from local_deep_research.benchmarks.graders import (
+ extract_answer_from_response,
+ )
+
+ response = "Some response without the expected format"
+ result = extract_answer_from_response(
+ response, dataset_type="browsecomp"
+ )
+
+ assert result["extracted_answer"] == "None"
+ assert result["confidence"] == "100"
+
+ def test_browsecomp_missing_confidence_defaults(self):
+ """Test that missing confidence defaults to 100."""
+ from local_deep_research.benchmarks.graders import (
+ extract_answer_from_response,
+ )
+
+ response = "Exact Answer: Paris"
+ result = extract_answer_from_response(
+ response, dataset_type="browsecomp"
+ )
+
+ assert result["extracted_answer"] == "Paris"
+ assert result["confidence"] == "100"
+
+ def test_simpleqa_returns_full_response(self):
+ """Test that SimpleQA returns the full response as the answer."""
+ from local_deep_research.benchmarks.graders import (
+ extract_answer_from_response,
+ )
+
+ response = "The capital of France is Paris."
+ result = extract_answer_from_response(response, dataset_type="simpleqa")
+
+ assert result["extracted_answer"] == response
+ assert result["confidence"] == "100"
+
+ def test_removes_citations_from_response(self):
+ """Test that citations are removed from the response."""
+ from local_deep_research.benchmarks.graders import (
+ extract_answer_from_response,
+ )
+
+ response = "The answer is 42 [1] according to the source [2][3]."
+ result = extract_answer_from_response(response, dataset_type="simpleqa")
+
+ assert "[1]" not in result["extracted_answer"]
+ assert "[2]" not in result["extracted_answer"]
+ assert "[3]" not in result["extracted_answer"]
+ assert "42" in result["extracted_answer"]
+
+ def test_browsecomp_case_insensitive(self):
+ """Test that dataset type matching is case insensitive."""
+ from local_deep_research.benchmarks.graders import (
+ extract_answer_from_response,
+ )
+
+ response = "Exact Answer: test\nConfidence: 80%"
+ result = extract_answer_from_response(
+ response, dataset_type="BROWSECOMP"
+ )
+
+ assert result["extracted_answer"] == "test"
+ assert result["confidence"] == "80"
+
+
+class TestGetEvaluationLLM:
+ """Tests for the get_evaluation_llm function."""
+
+ @patch("local_deep_research.benchmarks.graders.get_llm")
+ def test_uses_default_config(self, mock_get_llm):
+ """Test that default config is used."""
+ from local_deep_research.benchmarks.graders import (
+ get_evaluation_llm,
+ DEFAULT_EVALUATION_CONFIG,
+ )
+
+ mock_get_llm.return_value = Mock()
+
+ get_evaluation_llm()
+
+ mock_get_llm.assert_called_once()
+ call_kwargs = mock_get_llm.call_args[1]
+ assert (
+ call_kwargs["model_name"] == DEFAULT_EVALUATION_CONFIG["model_name"]
+ )
+ assert (
+ call_kwargs["temperature"]
+ == DEFAULT_EVALUATION_CONFIG["temperature"]
+ )
+
+ @patch("local_deep_research.benchmarks.graders.get_llm")
+ def test_custom_config_overrides_defaults(self, mock_get_llm):
+ """Test that custom config overrides defaults."""
+ from local_deep_research.benchmarks.graders import get_evaluation_llm
+
+ mock_get_llm.return_value = Mock()
+
+ custom_config = {
+ "model_name": "custom-model",
+ "temperature": 0.5,
+ }
+ get_evaluation_llm(custom_config=custom_config)
+
+ call_kwargs = mock_get_llm.call_args[1]
+ assert call_kwargs["model_name"] == "custom-model"
+ assert call_kwargs["temperature"] == 0.5
+
+ @patch("local_deep_research.benchmarks.graders.get_llm")
+ def test_filters_unsupported_params(self, mock_get_llm):
+ """Test that unsupported parameters are filtered out."""
+ from local_deep_research.benchmarks.graders import get_evaluation_llm
+
+ mock_get_llm.return_value = Mock()
+
+ custom_config = {
+ "model_name": "test-model",
+ "unsupported_param": "value",
+ "max_tokens": 1000, # Not supported by LDR's get_llm
+ }
+ get_evaluation_llm(custom_config=custom_config)
+
+ call_kwargs = mock_get_llm.call_args[1]
+ assert "unsupported_param" not in call_kwargs
+ assert "max_tokens" not in call_kwargs
+
+ @patch("local_deep_research.benchmarks.graders.get_llm")
+ def test_extracts_api_key_from_settings_snapshot(self, mock_get_llm):
+ """Test that API key is extracted from settings snapshot."""
+ from local_deep_research.benchmarks.graders import get_evaluation_llm
+
+ mock_get_llm.return_value = Mock()
+
+ settings_snapshot = {
+ "llm.openai_endpoint.api_key": {"value": "test-api-key"}
+ }
+ get_evaluation_llm(settings_snapshot=settings_snapshot)
+
+ # Should not raise and should call get_llm
+ mock_get_llm.assert_called_once()
+
+
+class TestGradeSingleResult:
+ """Tests for the grade_single_result function."""
+
+ @patch("local_deep_research.benchmarks.graders.get_evaluation_llm")
+ def test_grades_correctly(self, mock_get_eval_llm):
+ """Test that grade_single_result grades correctly."""
+ from local_deep_research.benchmarks.graders import grade_single_result
+
+ # Mock the LLM response
+ mock_llm = MagicMock()
+ mock_response = MagicMock()
+ mock_response.content = """
+Extracted Answer: Paris
+Reasoning: The model correctly identified Paris as the capital of France.
+Correct: yes
+"""
+ mock_llm.invoke.return_value = mock_response
+ mock_get_eval_llm.return_value = mock_llm
+
+ result_data = {
+ "problem": "What is the capital of France?",
+ "correct_answer": "Paris",
+ "response": "The capital of France is Paris.",
+ }
+
+ graded = grade_single_result(result_data, dataset_type="simpleqa")
+
+ assert graded["is_correct"] is True
+ assert "Paris" in graded["extracted_by_grader"]
+
+ @patch("local_deep_research.benchmarks.graders.get_evaluation_llm")
+ def test_handles_grading_error(self, mock_get_eval_llm):
+ """Test that grade_single_result handles errors gracefully."""
+ from local_deep_research.benchmarks.graders import grade_single_result
+
+ # Mock the LLM to raise an error during invoke (inside the try block)
+ mock_llm = MagicMock()
+ mock_llm.invoke.side_effect = Exception("LLM invoke error")
+ mock_get_eval_llm.return_value = mock_llm
+
+ result_data = {
+ "problem": "test",
+ "correct_answer": "answer",
+ "response": "response",
+ }
+
+ graded = grade_single_result(result_data)
+
+ assert graded["is_correct"] is False
+ assert "grading_error" in graded
+
+ @patch("local_deep_research.benchmarks.graders.get_evaluation_llm")
+ def test_browsecomp_grading_format(self, mock_get_eval_llm):
+ """Test BrowseComp-specific grading format extraction."""
+ from local_deep_research.benchmarks.graders import grade_single_result
+
+ mock_llm = MagicMock()
+ mock_response = MagicMock()
+ mock_response.content = """
+extracted_final_answer: 42
+reasoning: The model found the correct answer by analyzing the data.
+correct: yes
+confidence: 95
+"""
+ mock_llm.invoke.return_value = mock_response
+ mock_get_eval_llm.return_value = mock_llm
+
+ result_data = {
+ "problem": "What is the answer?",
+ "correct_answer": "42",
+ "response": "The answer is 42.",
+ }
+
+ graded = grade_single_result(result_data, dataset_type="browsecomp")
+
+ assert graded["is_correct"] is True
+ assert graded["extracted_by_grader"] == "42"
+ assert graded["graded_confidence"] == "95"
+
+ @patch("local_deep_research.benchmarks.graders.get_evaluation_llm")
+ def test_grading_with_no_judgment(self, mock_get_eval_llm):
+ """Test grading when LLM doesn't provide clear judgment."""
+ from local_deep_research.benchmarks.graders import grade_single_result
+
+ mock_llm = MagicMock()
+ mock_response = MagicMock()
+ mock_response.content = "Some response without proper format"
+ mock_llm.invoke.return_value = mock_response
+ mock_get_eval_llm.return_value = mock_llm
+
+ result_data = {
+ "problem": "test",
+ "correct_answer": "answer",
+ "response": "response",
+ }
+
+ graded = grade_single_result(result_data, dataset_type="simpleqa")
+
+ # Should default to False when no clear judgment
+ assert graded["is_correct"] is False
+ assert graded["extracted_by_grader"] == "None"
diff --git a/tests/news/test_headline_generator.py b/tests/news/test_headline_generator.py
new file mode 100644
index 0000000000..c02b471f71
--- /dev/null
+++ b/tests/news/test_headline_generator.py
@@ -0,0 +1,178 @@
+"""
+Tests for news/utils/headline_generator.py
+
+Tests cover:
+- Headline generation with mocked LLM
+- Fallback behavior when LLM fails
+- Edge cases: empty findings, long queries
+"""
+
+from unittest.mock import patch, MagicMock
+
+
+class TestGenerateHeadline:
+ """Tests for the generate_headline function."""
+
+ @patch("local_deep_research.config.llm_config.get_llm")
+ def test_successful_headline_generation(self, mock_get_llm):
+ """Test that headline is generated when LLM succeeds."""
+ from local_deep_research.news.utils.headline_generator import (
+ generate_headline,
+ )
+
+ # Setup mock LLM
+ mock_llm = MagicMock()
+ mock_response = MagicMock()
+ mock_response.content = "Major Tech Company Announces New Product"
+ mock_llm.invoke.return_value = mock_response
+ mock_get_llm.return_value = mock_llm
+
+ result = generate_headline(
+ query="technology news",
+ findings="A major tech company announced a new smartphone today.",
+ )
+
+ assert result == "Major Tech Company Announces New Product"
+ mock_llm.invoke.assert_called_once()
+
+ @patch("local_deep_research.config.llm_config.get_llm")
+ def test_headline_strips_quotes(self, mock_get_llm):
+ """Test that quotes are stripped from generated headline."""
+ from local_deep_research.news.utils.headline_generator import (
+ generate_headline,
+ )
+
+ mock_llm = MagicMock()
+ mock_response = MagicMock()
+ mock_response.content = '"Breaking News: Event Occurs"'
+ mock_llm.invoke.return_value = mock_response
+ mock_get_llm.return_value = mock_llm
+
+ result = generate_headline(query="news", findings="Something happened")
+
+ assert not result.startswith('"')
+ assert not result.endswith('"')
+
+ @patch("local_deep_research.config.llm_config.get_llm")
+ def test_empty_findings_returns_failure_message(self, mock_get_llm):
+ """Test that empty findings returns failure message."""
+ from local_deep_research.news.utils.headline_generator import (
+ generate_headline,
+ )
+
+ # Mock LLM to prevent actual calls
+ mock_llm = MagicMock()
+ mock_get_llm.return_value = mock_llm
+
+ result = generate_headline(query="test query", findings="")
+
+ assert result == "[Headline generation failed]"
+ # LLM invoke should not be called without findings
+ mock_llm.invoke.assert_not_called()
+
+ @patch("local_deep_research.config.llm_config.get_llm")
+ def test_llm_exception_returns_failure_message(self, mock_get_llm):
+ """Test that LLM exception results in failure message."""
+ from local_deep_research.news.utils.headline_generator import (
+ generate_headline,
+ )
+
+ mock_get_llm.side_effect = Exception("LLM error")
+
+ result = generate_headline(query="test", findings="Some findings")
+
+ assert result == "[Headline generation failed]"
+
+ @patch("local_deep_research.config.llm_config.get_llm")
+ def test_llm_empty_response_returns_failure(self, mock_get_llm):
+ """Test that empty LLM response returns failure message."""
+ from local_deep_research.news.utils.headline_generator import (
+ generate_headline,
+ )
+
+ mock_llm = MagicMock()
+ mock_response = MagicMock()
+ mock_response.content = ""
+ mock_llm.invoke.return_value = mock_response
+ mock_get_llm.return_value = mock_llm
+
+ result = generate_headline(query="test", findings="Some findings")
+
+ assert result == "[Headline generation failed]"
+
+
+class TestGenerateWithLLM:
+ """Tests for the internal _generate_with_llm function."""
+
+ @patch("local_deep_research.config.llm_config.get_llm")
+ def test_uses_low_temperature(self, mock_get_llm):
+ """Test that LLM is called with low temperature for consistency."""
+ from local_deep_research.news.utils.headline_generator import (
+ _generate_with_llm,
+ )
+
+ mock_llm = MagicMock()
+ mock_response = MagicMock()
+ mock_response.content = "Test Headline"
+ mock_llm.invoke.return_value = mock_response
+ mock_get_llm.return_value = mock_llm
+
+ _generate_with_llm("query", "findings", 100)
+
+ mock_get_llm.assert_called_once_with(temperature=0.3)
+
+ @patch("local_deep_research.config.llm_config.get_llm")
+ def test_prompt_includes_findings(self, mock_get_llm):
+ """Test that prompt includes the findings content."""
+ from local_deep_research.news.utils.headline_generator import (
+ _generate_with_llm,
+ )
+
+ mock_llm = MagicMock()
+ mock_response = MagicMock()
+ mock_response.content = "Test Headline"
+ mock_llm.invoke.return_value = mock_response
+ mock_get_llm.return_value = mock_llm
+
+ _generate_with_llm("query", "Important findings about topic", 100)
+
+ # Check that invoke was called with prompt containing findings
+ call_args = mock_llm.invoke.call_args
+ prompt = call_args[0][0]
+ assert "Important findings about topic" in prompt
+
+ @patch("local_deep_research.config.llm_config.get_llm")
+ def test_no_findings_returns_none(self, mock_get_llm):
+ """Test that missing findings returns None."""
+ from local_deep_research.news.utils.headline_generator import (
+ _generate_with_llm,
+ )
+
+ # Mock LLM to prevent actual calls
+ mock_llm = MagicMock()
+ mock_get_llm.return_value = mock_llm
+
+ result = _generate_with_llm("query", "", 100)
+
+ assert result is None
+ # LLM invoke should not be called without findings
+ mock_llm.invoke.assert_not_called()
+
+ @patch("local_deep_research.config.llm_config.get_llm")
+ def test_strips_punctuation_from_ends(self, mock_get_llm):
+ """Test that punctuation is stripped from headline ends."""
+ from local_deep_research.news.utils.headline_generator import (
+ _generate_with_llm,
+ )
+
+ mock_llm = MagicMock()
+ mock_response = MagicMock()
+ mock_response.content = "...Headline With Punctuation!!?"
+ mock_llm.invoke.return_value = mock_response
+ mock_get_llm.return_value = mock_llm
+
+ result = _generate_with_llm("query", "findings", 100)
+
+ assert not result.startswith(".")
+ assert not result.endswith("!")
+ assert not result.endswith("?")
diff --git a/tests/news/test_topic_generator.py b/tests/news/test_topic_generator.py
new file mode 100644
index 0000000000..c7f63b833e
--- /dev/null
+++ b/tests/news/test_topic_generator.py
@@ -0,0 +1,311 @@
+"""
+Tests for news/utils/topic_generator.py
+
+Tests cover:
+- Topic generation with mocked LLM
+- Topic validation and cleaning
+- Edge cases: empty input, duplicates, invalid topics
+"""
+
+from unittest.mock import patch, MagicMock
+
+
+class TestValidateTopics:
+ """Tests for the _validate_topics function."""
+
+ def test_removes_empty_topics(self):
+ """Test that empty topics are removed."""
+ from local_deep_research.news.utils.topic_generator import (
+ _validate_topics,
+ )
+
+ topics = ["valid", "", " ", "another", None]
+ # Filter out None before passing
+ topics = [t for t in topics if t is not None]
+ result = _validate_topics(topics, 5)
+
+ assert "valid" in result
+ assert "another" in result
+ assert "" not in result
+
+ def test_removes_short_topics(self):
+ """Test that topics shorter than 2 chars are removed."""
+ from local_deep_research.news.utils.topic_generator import (
+ _validate_topics,
+ )
+
+ topics = ["a", "ab", "abc", "valid topic"]
+ result = _validate_topics(topics, 5)
+
+ assert "a" not in result
+ assert "ab" in result
+ assert "abc" in result
+ assert "valid topic" in result
+
+ def test_removes_long_topics(self):
+ """Test that topics longer than 30 chars are removed."""
+ from local_deep_research.news.utils.topic_generator import (
+ _validate_topics,
+ )
+
+ long_topic = "x" * 31
+ short_topic = "x" * 30
+
+ topics = [long_topic, short_topic, "normal"]
+ result = _validate_topics(topics, 5)
+
+ assert long_topic not in result
+ assert "x" * 30 in result
+ assert "normal" in result
+
+ def test_removes_case_insensitive_duplicates(self):
+ """Test that duplicates are removed case-insensitively."""
+ from local_deep_research.news.utils.topic_generator import (
+ _validate_topics,
+ )
+
+ topics = ["Technology", "technology", "TECHNOLOGY", "Other"]
+ result = _validate_topics(topics, 5)
+
+ # Should only have one version of technology
+ tech_count = sum(1 for t in result if "technolog" in t.lower())
+ assert tech_count == 1
+ assert "other" in result
+
+ def test_respects_max_topics_limit(self):
+ """Test that max_topics limit is enforced."""
+ from local_deep_research.news.utils.topic_generator import (
+ _validate_topics,
+ )
+
+ topics = ["one", "two", "three", "four", "five", "six"]
+ result = _validate_topics(topics, 3)
+
+ assert len(result) <= 3
+
+ def test_converts_to_lowercase(self):
+ """Test that topics are converted to lowercase."""
+ from local_deep_research.news.utils.topic_generator import (
+ _validate_topics,
+ )
+
+ topics = ["UPPERCASE", "MixedCase", "lowercase"]
+ result = _validate_topics(topics, 5)
+
+ for topic in result:
+ assert topic == topic.lower()
+
+ def test_strips_whitespace(self):
+ """Test that whitespace is stripped from topics."""
+ from local_deep_research.news.utils.topic_generator import (
+ _validate_topics,
+ )
+
+ topics = [" spaced ", "\ttabbed\t", "normal"]
+ result = _validate_topics(topics, 5)
+
+ for topic in result:
+ assert topic == topic.strip()
+
+ def test_empty_input_returns_no_valid_topics_message(self):
+ """Test that empty input returns failure indicator."""
+ from local_deep_research.news.utils.topic_generator import (
+ _validate_topics,
+ )
+
+ result = _validate_topics([], 5)
+
+ assert result == ["[No valid topics]"]
+
+ def test_all_invalid_returns_failure_message(self):
+ """Test that all invalid topics returns failure indicator."""
+ from local_deep_research.news.utils.topic_generator import (
+ _validate_topics,
+ )
+
+ # All topics are too short
+ topics = ["a", "b", "c"]
+ result = _validate_topics(topics, 5)
+
+ assert result == ["[No valid topics]"]
+
+
+class TestGenerateTopics:
+ """Tests for the generate_topics function."""
+
+ @patch("local_deep_research.news.utils.topic_generator._generate_with_llm")
+ def test_returns_llm_topics_when_successful(self, mock_llm_gen):
+ """Test that LLM topics are returned when generation succeeds."""
+ from local_deep_research.news.utils.topic_generator import (
+ generate_topics,
+ )
+
+ mock_llm_gen.return_value = ["tech", "innovation", "startup"]
+
+ result = generate_topics(
+ query="tech news", findings="A startup launched a new product"
+ )
+
+ assert "tech" in result
+ assert "innovation" in result
+ assert "startup" in result
+
+ @patch("local_deep_research.news.utils.topic_generator._generate_with_llm")
+ def test_returns_failure_message_when_llm_fails(self, mock_llm_gen):
+ """Test that failure message is returned when LLM fails."""
+ from local_deep_research.news.utils.topic_generator import (
+ generate_topics,
+ )
+
+ mock_llm_gen.return_value = []
+
+ result = generate_topics(query="test", findings="test")
+
+ assert "[topic generation failed]" in result
+
+
+class TestGenerateWithLLM:
+ """Tests for the _generate_with_llm function."""
+
+ @patch("local_deep_research.config.llm_config.get_llm")
+ def test_parses_json_array_response(self, mock_get_llm):
+ """Test parsing of JSON array from LLM."""
+ from local_deep_research.news.utils.topic_generator import (
+ _generate_with_llm,
+ )
+
+ mock_llm = MagicMock()
+ mock_response = MagicMock()
+ mock_response.content = '["topic1", "topic2", "topic3"]'
+ mock_llm.invoke.return_value = mock_response
+ mock_get_llm.return_value = mock_llm
+
+ result = _generate_with_llm("query", "findings", "category", 5)
+
+ assert "topic1" in result
+ assert "topic2" in result
+ assert "topic3" in result
+
+ @patch("local_deep_research.config.llm_config.get_llm")
+ def test_handles_json_with_markdown_code_block(self, mock_get_llm):
+ """Test handling of JSON wrapped in markdown code block."""
+ from local_deep_research.news.utils.topic_generator import (
+ _generate_with_llm,
+ )
+
+ mock_llm = MagicMock()
+ mock_response = MagicMock()
+ mock_response.content = '```json\n["topic1", "topic2"]\n```'
+ mock_llm.invoke.return_value = mock_response
+ mock_get_llm.return_value = mock_llm
+
+ result = _generate_with_llm("query", "findings", "category", 5)
+
+ assert "topic1" in result
+ assert "topic2" in result
+
+ @patch("local_deep_research.config.llm_config.get_llm")
+ def test_handles_comma_separated_fallback(self, mock_get_llm):
+ """Test fallback parsing of comma-separated topics."""
+ from local_deep_research.news.utils.topic_generator import (
+ _generate_with_llm,
+ )
+
+ mock_llm = MagicMock()
+ mock_response = MagicMock()
+ mock_response.content = "topic one, topic two, topic three"
+ mock_llm.invoke.return_value = mock_response
+ mock_get_llm.return_value = mock_llm
+
+ result = _generate_with_llm("query", "findings", "category", 5)
+
+ assert "topic one" in result
+ assert "topic two" in result
+
+ @patch("local_deep_research.config.llm_config.get_llm")
+ def test_respects_max_topics(self, mock_get_llm):
+ """Test that max_topics limit is respected."""
+ from local_deep_research.news.utils.topic_generator import (
+ _generate_with_llm,
+ )
+
+ mock_llm = MagicMock()
+ mock_response = MagicMock()
+ mock_response.content = '["t1", "t2", "t3", "t4", "t5", "t6", "t7"]'
+ mock_llm.invoke.return_value = mock_response
+ mock_get_llm.return_value = mock_llm
+
+ result = _generate_with_llm("query", "findings", "category", 3)
+
+ assert len(result) <= 3
+
+ @patch("local_deep_research.config.llm_config.get_llm")
+ def test_filters_long_topics(self, mock_get_llm):
+ """Test that topics longer than 30 chars are filtered."""
+ from local_deep_research.news.utils.topic_generator import (
+ _generate_with_llm,
+ )
+
+ long_topic = "x" * 35
+ mock_llm = MagicMock()
+ mock_response = MagicMock()
+ mock_response.content = f'["short", "{long_topic}"]'
+ mock_llm.invoke.return_value = mock_response
+ mock_get_llm.return_value = mock_llm
+
+ result = _generate_with_llm("query", "findings", "category", 5)
+
+ assert "short" in result
+ assert long_topic not in result
+
+ @patch("local_deep_research.config.llm_config.get_llm")
+ def test_handles_llm_exception(self, mock_get_llm):
+ """Test graceful handling of LLM exceptions."""
+ from local_deep_research.news.utils.topic_generator import (
+ _generate_with_llm,
+ )
+
+ mock_get_llm.side_effect = Exception("LLM error")
+
+ result = _generate_with_llm("query", "findings", "category", 5)
+
+ assert result == []
+
+ @patch("local_deep_research.config.llm_config.get_llm")
+ def test_uses_medium_temperature(self, mock_get_llm):
+ """Test that medium temperature is used for topic diversity."""
+ from local_deep_research.news.utils.topic_generator import (
+ _generate_with_llm,
+ )
+
+ mock_llm = MagicMock()
+ mock_response = MagicMock()
+ mock_response.content = '["topic"]'
+ mock_llm.invoke.return_value = mock_response
+ mock_get_llm.return_value = mock_llm
+
+ _generate_with_llm("query", "findings", "category", 5)
+
+ mock_get_llm.assert_called_once_with(temperature=0.5)
+
+ @patch("local_deep_research.config.llm_config.get_llm")
+ def test_truncates_long_query_in_prompt(self, mock_get_llm):
+ """Test that long queries are truncated in prompt."""
+ from local_deep_research.news.utils.topic_generator import (
+ _generate_with_llm,
+ )
+
+ mock_llm = MagicMock()
+ mock_response = MagicMock()
+ mock_response.content = '["topic"]'
+ mock_llm.invoke.return_value = mock_response
+ mock_get_llm.return_value = mock_llm
+
+ long_query = "x" * 1000
+ _generate_with_llm(long_query, "findings", "category", 5)
+
+ # The prompt should be invoked with truncated query
+ call_args = mock_llm.invoke.call_args
+ prompt = call_args[0][0]
+ # Query should be truncated to 500 chars
+ assert "x" * 501 not in prompt
diff --git a/tests/search_engines/test_search_engine_ddg.py b/tests/search_engines/test_search_engine_ddg.py
index 4ccf3473af..737caa209f 100644
--- a/tests/search_engines/test_search_engine_ddg.py
+++ b/tests/search_engines/test_search_engine_ddg.py
@@ -6,8 +6,9 @@ Note: These tests require the 'ddgs' package to be installed.
"""
import pytest
+from unittest.mock import Mock, patch
-# Check if ddgs package is available
+# Check if ddgs package is available (required by langchain DuckDuckGoSearchAPIWrapper)
import importlib.util
DDGS_AVAILABLE = importlib.util.find_spec("ddgs") is not None
@@ -142,3 +143,231 @@ class TestDDGResponseFixtures:
"""Test that URLs in mock response are valid."""
for result in mock_ddg_response:
assert result["href"].startswith("http")
+
+
[email protected](not DDGS_AVAILABLE, reason="ddgs package not installed")
+class TestDuckDuckGoGetPreviews:
+ """Tests for the _get_previews method and error handling."""
+
+ @pytest.fixture
+ def ddg_engine(self):
+ """Create a DuckDuckGo engine instance."""
+ from local_deep_research.web_search_engines.engines.search_engine_ddg import (
+ DuckDuckGoSearchEngine,
+ )
+
+ return DuckDuckGoSearchEngine(max_results=10)
+
+ def test_get_previews_returns_correct_format(self, ddg_engine):
+ """Test that _get_previews returns properly formatted previews."""
+ with patch.object(ddg_engine.engine, "results") as mock_results:
+ mock_results.return_value = [
+ {
+ "title": "Test Title",
+ "link": "https://example.com",
+ "snippet": "Test snippet",
+ },
+ {
+ "title": "Title 2",
+ "link": "https://example2.com",
+ "snippet": "Snippet 2",
+ },
+ ]
+
+ previews = ddg_engine._get_previews("test query")
+
+ assert len(previews) == 2
+ assert previews[0]["title"] == "Test Title"
+ assert previews[0]["link"] == "https://example.com"
+ assert previews[0]["snippet"] == "Test snippet"
+ assert previews[0]["id"] == "https://example.com"
+
+ def test_get_previews_handles_empty_results(self, ddg_engine):
+ """Test that _get_previews handles empty results list."""
+ with patch.object(ddg_engine.engine, "results") as mock_results:
+ mock_results.return_value = []
+
+ previews = ddg_engine._get_previews("test query")
+
+ assert previews == []
+
+ def test_get_previews_handles_non_list_results(self, ddg_engine):
+ """Test that _get_previews handles non-list results."""
+ with patch.object(ddg_engine.engine, "results") as mock_results:
+ mock_results.return_value = None
+
+ previews = ddg_engine._get_previews("test query")
+
+ assert previews == []
+
+ def test_get_previews_rate_limit_202_raises_error(self, ddg_engine):
+ """Test that 202 Ratelimit error raises RateLimitError."""
+ from local_deep_research.web_search_engines.rate_limiting import (
+ RateLimitError,
+ )
+
+ with patch.object(ddg_engine.engine, "results") as mock_results:
+ mock_results.side_effect = Exception("202 Ratelimit hit")
+
+ with pytest.raises(RateLimitError) as exc_info:
+ ddg_engine._get_previews("test query")
+
+ assert "rate limit" in str(exc_info.value).lower()
+
+ def test_get_previews_403_forbidden_raises_error(self, ddg_engine):
+ """Test that 403 forbidden error raises RateLimitError."""
+ from local_deep_research.web_search_engines.rate_limiting import (
+ RateLimitError,
+ )
+
+ with patch.object(ddg_engine.engine, "results") as mock_results:
+ mock_results.side_effect = Exception("403 Forbidden response")
+
+ with pytest.raises(RateLimitError) as exc_info:
+ ddg_engine._get_previews("test query")
+
+ assert "forbidden" in str(exc_info.value).lower()
+
+ def test_get_previews_timeout_raises_error(self, ddg_engine):
+ """Test that timeout error raises RateLimitError."""
+ from local_deep_research.web_search_engines.rate_limiting import (
+ RateLimitError,
+ )
+
+ with patch.object(ddg_engine.engine, "results") as mock_results:
+ mock_results.side_effect = Exception("Connection timeout")
+
+ with pytest.raises(RateLimitError) as exc_info:
+ ddg_engine._get_previews("test query")
+
+ assert "timeout" in str(exc_info.value).lower()
+
+ def test_get_previews_generic_exception_returns_empty(self, ddg_engine):
+ """Test that generic exceptions return empty list."""
+ with patch.object(ddg_engine.engine, "results") as mock_results:
+ mock_results.side_effect = ValueError("Some generic error")
+
+ previews = ddg_engine._get_previews("test query")
+
+ assert previews == []
+
+ def test_get_previews_handles_missing_fields(self, ddg_engine):
+ """Test that _get_previews handles results with missing fields."""
+ with patch.object(ddg_engine.engine, "results") as mock_results:
+ mock_results.return_value = [
+ {"title": "Title Only"}, # Missing link and snippet
+ {"link": "https://example.com"}, # Missing title and snippet
+ ]
+
+ previews = ddg_engine._get_previews("test query")
+
+ assert len(previews) == 2
+ assert previews[0]["title"] == "Title Only"
+ assert previews[0]["snippet"] == ""
+ assert previews[1]["title"] == ""
+
+
[email protected](not DDGS_AVAILABLE, reason="ddgs package not installed")
+class TestDuckDuckGoGetFullContent:
+ """Tests for the _get_full_content method."""
+
+ @pytest.fixture
+ def ddg_engine_with_full_content(self):
+ """Create a DuckDuckGo engine with full content enabled."""
+ from local_deep_research.web_search_engines.engines.search_engine_ddg import (
+ DuckDuckGoSearchEngine,
+ )
+
+ mock_llm = Mock()
+ return DuckDuckGoSearchEngine(
+ max_results=10,
+ llm=mock_llm,
+ include_full_content=True,
+ )
+
+ @pytest.fixture
+ def ddg_engine_snippets_only(self):
+ """Create a DuckDuckGo engine without full content."""
+ from local_deep_research.web_search_engines.engines.search_engine_ddg import (
+ DuckDuckGoSearchEngine,
+ )
+
+ return DuckDuckGoSearchEngine(
+ max_results=10,
+ include_full_content=False,
+ )
+
+ def test_get_full_content_without_full_search(
+ self, ddg_engine_snippets_only
+ ):
+ """Test that _get_full_content returns items as-is when no full_search."""
+ items = [
+ {"title": "Test", "snippet": "Snippet"},
+ ]
+
+ result = ddg_engine_snippets_only._get_full_content(items)
+
+ assert result == items
+
+ def test_get_full_content_with_full_search_delegates(
+ self, ddg_engine_with_full_content
+ ):
+ """Test that _get_full_content delegates to full_search when available."""
+ items = [{"title": "Test", "snippet": "Snippet"}]
+
+ # Mock the full_search._get_full_content method
+ with patch.object(
+ ddg_engine_with_full_content.full_search, "_get_full_content"
+ ) as mock_full:
+ mock_full.return_value = [
+ {"title": "Test", "content": "Full content"}
+ ]
+
+ result = ddg_engine_with_full_content._get_full_content(items)
+
+ mock_full.assert_called_once_with(items)
+ assert result[0]["content"] == "Full content"
+
+
[email protected](not DDGS_AVAILABLE, reason="ddgs package not installed")
+class TestDuckDuckGoRunMethod:
+ """Tests for the run() method which uses the two-phase approach."""
+
+ @pytest.fixture
+ def ddg_engine(self):
+ """Create a DuckDuckGo engine instance."""
+ from local_deep_research.web_search_engines.engines.search_engine_ddg import (
+ DuckDuckGoSearchEngine,
+ )
+
+ return DuckDuckGoSearchEngine(max_results=5)
+
+ def test_run_returns_results(self, ddg_engine):
+ """Test that run() returns search results."""
+ with patch.object(ddg_engine, "_get_previews") as mock_previews:
+ mock_previews.return_value = [
+ {
+ "id": "1",
+ "title": "Test",
+ "snippet": "Test snippet",
+ "link": "https://example.com",
+ },
+ ]
+
+ results = ddg_engine.run("test query")
+
+ # Should return filtered results (or all if no filtering)
+ assert isinstance(results, list)
+
+ def test_run_accepts_research_context(self, ddg_engine):
+ """Test that run() accepts research_context parameter."""
+ with patch.object(ddg_engine, "_get_previews") as mock_previews:
+ mock_previews.return_value = []
+
+ # Should not raise
+ results = ddg_engine.run(
+ "test query",
+ research_context={"previous_findings": "some info"},
+ )
+
+ assert isinstance(results, list)
diff --git a/tests/web/__init__.py b/tests/web/__init__.py
new file mode 100644
index 0000000000..84836a2cf3
--- /dev/null
+++ b/tests/web/__init__.py
@@ -0,0 +1 @@
+"""Tests for the web module."""
diff --git a/tests/web/test_formatters.py b/tests/web/test_formatters.py
new file mode 100644
index 0000000000..9cdcb7b3fd
--- /dev/null
+++ b/tests/web/test_formatters.py
@@ -0,0 +1,151 @@
+"""
+Tests for web/utils/formatters.py
+
+Tests cover:
+- convert_debug_to_markdown function
+- Edge cases: None, empty, no findings section
+- Standard conversion with divider removal
+"""
+
+
+class TestConvertDebugToMarkdown:
+ """Tests for the convert_debug_to_markdown function."""
+
+ def test_empty_input_returns_message(self):
+ """Test that empty input returns informative message."""
+ from local_deep_research.web.utils.formatters import (
+ convert_debug_to_markdown,
+ )
+
+ result = convert_debug_to_markdown("", "test query")
+ assert "No detailed findings available" in result
+ assert "test query" in result
+
+ def test_none_input_returns_message(self):
+ """Test that None input returns informative message."""
+ from local_deep_research.web.utils.formatters import (
+ convert_debug_to_markdown,
+ )
+
+ result = convert_debug_to_markdown(None, "my research")
+ assert "No detailed findings available" in result
+ assert "my research" in result
+
+ def test_extracts_detailed_findings_section(self):
+ """Test extraction of content after DETAILED FINDINGS marker."""
+ from local_deep_research.web.utils.formatters import (
+ convert_debug_to_markdown,
+ )
+
+ raw_text = """Some header content
+DETAILED FINDINGS:
+This is the actual content
+that should be extracted."""
+
+ result = convert_debug_to_markdown(raw_text, "query")
+
+ assert "This is the actual content" in result
+ assert "that should be extracted" in result
+ assert "Some header content" not in result
+
+ def test_removes_divider_lines_with_equals(self):
+ """Test that === divider lines are removed."""
+ from local_deep_research.web.utils.formatters import (
+ convert_debug_to_markdown,
+ )
+
+ raw_text = """DETAILED FINDINGS:
+=== Section 1 ===
+Actual content here
+================================================================================
+More content"""
+
+ result = convert_debug_to_markdown(raw_text, "query")
+
+ assert "===" not in result
+ assert "Actual content here" in result
+ assert "More content" in result
+
+ def test_no_detailed_findings_uses_full_text(self):
+ """Test that full text is used when no DETAILED FINDINGS marker."""
+ from local_deep_research.web.utils.formatters import (
+ convert_debug_to_markdown,
+ )
+
+ raw_text = """This is research content
+with multiple lines
+and no special markers."""
+
+ result = convert_debug_to_markdown(raw_text, "query")
+
+ assert "This is research content" in result
+ assert "with multiple lines" in result
+
+ def test_returns_stripped_result(self):
+ """Test that result is properly stripped of whitespace."""
+ from local_deep_research.web.utils.formatters import (
+ convert_debug_to_markdown,
+ )
+
+ raw_text = """DETAILED FINDINGS:
+
+ Content with whitespace
+
+"""
+ result = convert_debug_to_markdown(raw_text, "query")
+
+ assert not result.startswith(" ")
+ assert not result.endswith(" ")
+ assert "Content with whitespace" in result
+
+ def test_handles_only_divider_lines(self):
+ """Test handling of text that contains only dividers."""
+ from local_deep_research.web.utils.formatters import (
+ convert_debug_to_markdown,
+ )
+
+ raw_text = """DETAILED FINDINGS:
+================================================================================
+=== Only Dividers ===
+================================================================================"""
+
+ result = convert_debug_to_markdown(raw_text, "query")
+
+ # Should return empty or minimal content after removing dividers
+ assert "===" not in result
+
+ def test_preserves_markdown_formatting(self):
+ """Test that markdown formatting is preserved."""
+ from local_deep_research.web.utils.formatters import (
+ convert_debug_to_markdown,
+ )
+
+ raw_text = """DETAILED FINDINGS:
+# Header
+
+- Bullet point
+- Another bullet
+
+**Bold text** and *italic*"""
+
+ result = convert_debug_to_markdown(raw_text, "query")
+
+ assert "# Header" in result
+ assert "- Bullet point" in result
+ assert "**Bold text**" in result
+ assert "*italic*" in result
+
+ def test_handles_unicode_content(self):
+ """Test proper handling of unicode characters."""
+ from local_deep_research.web.utils.formatters import (
+ convert_debug_to_markdown,
+ )
+
+ raw_text = """DETAILED FINDINGS:
+Émojis 🌍 and spëcial çharacters
+日本語テキスト"""
+
+ result = convert_debug_to_markdown(raw_text, "日本語クエリ")
+
+ assert "🌍" in result
+ assert "日本語テキスト" in result