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 162 high-value unit tests covering untested functions and edge cases (#2345)

LearningCircuit6bd80569cd33
diff --git a/tests/benchmarks/test_metrics_calculation_extended.py b/tests/benchmarks/test_metrics_calculation_extended.py
new file mode 100644
index 0000000000..a85b1bebe5
--- /dev/null
+++ b/tests/benchmarks/test_metrics_calculation_extended.py
@@ -0,0 +1,429 @@
+"""Extended tests for benchmarks/metrics/calculation.py - covering edge cases
+in calculate_metrics and calculate_combined_score."""
+
+import json
+import tempfile
+
+import pytest
+
+
+class TestCalculateMetricsEdgeCases:
+ """Tests for calculate_metrics edge cases."""
+
+ def test_nonexistent_file_returns_error(self):
+ """Non-existent file should return error dict."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_metrics,
+ )
+
+ result = calculate_metrics("/nonexistent/path/results.jsonl")
+
+ assert "error" in result
+
+ def test_empty_file_returns_error(self):
+ """Empty file should return error about no results."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_metrics,
+ )
+
+ with tempfile.NamedTemporaryFile(
+ mode="w", suffix=".jsonl", delete=False
+ ) as f:
+ f.write("")
+ f.flush()
+
+ result = calculate_metrics(f.name)
+
+ assert result["error"] == "No results found"
+
+ def test_malformed_json_lines_returns_error(self):
+ """File with malformed JSON should return error."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_metrics,
+ )
+
+ with tempfile.NamedTemporaryFile(
+ mode="w", suffix=".jsonl", delete=False
+ ) as f:
+ f.write("not valid json\n")
+ f.flush()
+
+ result = calculate_metrics(f.name)
+
+ assert "error" in result
+
+ def test_file_with_only_whitespace_lines(self):
+ """File with only whitespace lines should return no results error."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_metrics,
+ )
+
+ with tempfile.NamedTemporaryFile(
+ mode="w", suffix=".jsonl", delete=False
+ ) as f:
+ f.write("\n\n\n")
+ f.flush()
+
+ result = calculate_metrics(f.name)
+
+ assert result["error"] == "No results found"
+
+ def test_all_correct_results(self):
+ """All correct results should give accuracy of 1.0."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_metrics,
+ )
+
+ with tempfile.NamedTemporaryFile(
+ mode="w", suffix=".jsonl", delete=False
+ ) as f:
+ for i in range(5):
+ f.write(
+ json.dumps({"is_correct": True, "processing_time": 1.0})
+ + "\n"
+ )
+ f.flush()
+
+ result = calculate_metrics(f.name)
+
+ assert result["accuracy"] == 1.0
+ assert result["correct"] == 5
+ assert result["graded_examples"] == 5
+
+ def test_all_incorrect_results(self):
+ """All incorrect results should give accuracy of 0.0."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_metrics,
+ )
+
+ with tempfile.NamedTemporaryFile(
+ mode="w", suffix=".jsonl", delete=False
+ ) as f:
+ for i in range(3):
+ f.write(json.dumps({"is_correct": False}) + "\n")
+ f.flush()
+
+ result = calculate_metrics(f.name)
+
+ assert result["accuracy"] == 0.0
+ assert result["correct"] == 0
+
+ def test_mixed_graded_and_ungraded(self):
+ """Mixed graded and ungraded results should only use graded for accuracy."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_metrics,
+ )
+
+ with tempfile.NamedTemporaryFile(
+ mode="w", suffix=".jsonl", delete=False
+ ) as f:
+ f.write(json.dumps({"is_correct": True}) + "\n")
+ f.write(json.dumps({"is_correct": False}) + "\n")
+ f.write(json.dumps({"answer": "no grading"}) + "\n") # Ungraded
+ f.flush()
+
+ result = calculate_metrics(f.name)
+
+ assert result["total_examples"] == 3
+ assert result["graded_examples"] == 2
+ assert result["accuracy"] == 0.5
+
+ def test_results_with_errors(self):
+ """Results with errors should be counted in error_rate."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_metrics,
+ )
+
+ with tempfile.NamedTemporaryFile(
+ mode="w", suffix=".jsonl", delete=False
+ ) as f:
+ f.write(json.dumps({"is_correct": True}) + "\n")
+ f.write(json.dumps({"error": "timeout"}) + "\n")
+ f.write(json.dumps({"error": "API error"}) + "\n")
+ f.flush()
+
+ result = calculate_metrics(f.name)
+
+ assert result["error_count"] == 2
+ assert result["error_rate"] == pytest.approx(2 / 3)
+
+ def test_processing_time_calculation(self):
+ """Average processing time should be calculated correctly."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_metrics,
+ )
+
+ with tempfile.NamedTemporaryFile(
+ mode="w", suffix=".jsonl", delete=False
+ ) as f:
+ f.write(
+ json.dumps({"processing_time": 10.0, "is_correct": True}) + "\n"
+ )
+ f.write(
+ json.dumps({"processing_time": 20.0, "is_correct": True}) + "\n"
+ )
+ f.write(
+ json.dumps({"processing_time": 30.0, "is_correct": True}) + "\n"
+ )
+ f.flush()
+
+ result = calculate_metrics(f.name)
+
+ assert result["average_processing_time"] == pytest.approx(20.0)
+
+ def test_confidence_parsing(self):
+ """Confidence values should be parsed and averaged."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_metrics,
+ )
+
+ with tempfile.NamedTemporaryFile(
+ mode="w", suffix=".jsonl", delete=False
+ ) as f:
+ f.write(json.dumps({"confidence": "80", "is_correct": True}) + "\n")
+ f.write(json.dumps({"confidence": "60", "is_correct": True}) + "\n")
+ f.flush()
+
+ result = calculate_metrics(f.name)
+
+ assert result["average_confidence"] == 70.0
+
+ def test_invalid_confidence_values_skipped(self):
+ """Invalid confidence values should be skipped."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_metrics,
+ )
+
+ with tempfile.NamedTemporaryFile(
+ mode="w", suffix=".jsonl", delete=False
+ ) as f:
+ f.write(
+ json.dumps({"confidence": "not_a_number", "is_correct": True})
+ + "\n"
+ )
+ f.write(json.dumps({"confidence": "90", "is_correct": True}) + "\n")
+ f.flush()
+
+ result = calculate_metrics(f.name)
+
+ assert result["average_confidence"] == 90.0
+
+ def test_per_category_metrics(self):
+ """Per-category metrics should be calculated correctly."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_metrics,
+ )
+
+ with tempfile.NamedTemporaryFile(
+ mode="w", suffix=".jsonl", delete=False
+ ) as f:
+ f.write(json.dumps({"is_correct": True, "category": "math"}) + "\n")
+ f.write(
+ json.dumps({"is_correct": False, "category": "math"}) + "\n"
+ )
+ f.write(
+ json.dumps({"is_correct": True, "category": "science"}) + "\n"
+ )
+ f.flush()
+
+ result = calculate_metrics(f.name)
+
+ assert "categories" in result
+ assert result["categories"]["math"]["accuracy"] == 0.5
+ assert result["categories"]["math"]["total"] == 2
+ assert result["categories"]["science"]["accuracy"] == 1.0
+
+ def test_no_processing_times(self):
+ """Results without processing_time should give avg_time of 0."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_metrics,
+ )
+
+ with tempfile.NamedTemporaryFile(
+ mode="w", suffix=".jsonl", delete=False
+ ) as f:
+ f.write(json.dumps({"is_correct": True}) + "\n")
+ f.flush()
+
+ result = calculate_metrics(f.name)
+
+ assert result["average_processing_time"] == 0
+
+ def test_no_graded_results_accuracy_zero(self):
+ """Results with no is_correct field should give accuracy 0."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_metrics,
+ )
+
+ with tempfile.NamedTemporaryFile(
+ mode="w", suffix=".jsonl", delete=False
+ ) as f:
+ f.write(json.dumps({"answer": "something"}) + "\n")
+ f.flush()
+
+ result = calculate_metrics(f.name)
+
+ assert result["accuracy"] == 0
+ assert result["graded_examples"] == 0
+
+ def test_timestamp_included(self):
+ """Result should include a timestamp."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_metrics,
+ )
+
+ with tempfile.NamedTemporaryFile(
+ mode="w", suffix=".jsonl", delete=False
+ ) as f:
+ f.write(json.dumps({"is_correct": True}) + "\n")
+ f.flush()
+
+ result = calculate_metrics(f.name)
+
+ assert "timestamp" in result
+ assert isinstance(result["timestamp"], str)
+
+
+class TestCalculateCombinedScoreEdgeCases:
+ """Tests for calculate_combined_score edge cases."""
+
+ def test_default_weights(self):
+ """Default weights should be quality=0.6, speed=0.3, resource=0.1."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_combined_score,
+ )
+
+ metrics = {
+ "quality": {"quality_score": 1.0},
+ "speed": {"speed_score": 1.0},
+ "resource": {"resource_score": 1.0},
+ }
+
+ score = calculate_combined_score(metrics)
+ assert score == pytest.approx(1.0)
+
+ def test_zero_weights_returns_zero(self):
+ """All zero weights should return 0.0."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_combined_score,
+ )
+
+ metrics = {"quality": {"quality_score": 1.0}}
+ weights = {"quality": 0.0, "speed": 0.0, "resource": 0.0}
+
+ score = calculate_combined_score(metrics, weights)
+ assert score == 0.0
+
+ def test_missing_metric_categories(self):
+ """Missing metric categories should be skipped."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_combined_score,
+ )
+
+ metrics = {
+ "quality": {"quality_score": 0.8},
+ # No speed or resource
+ }
+
+ score = calculate_combined_score(metrics)
+ # Only quality contributes: 0.8 * (0.6/1.0) = 0.48
+ assert score == pytest.approx(0.8 * 0.6)
+
+ def test_custom_weights(self):
+ """Custom weights should be used instead of defaults."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_combined_score,
+ )
+
+ metrics = {
+ "quality": {"quality_score": 1.0},
+ "speed": {"speed_score": 0.5},
+ }
+ weights = {"quality": 1.0, "speed": 1.0}
+
+ score = calculate_combined_score(metrics, weights)
+ # Normalized: quality=0.5, speed=0.5
+ # Score: 1.0*0.5 + 0.5*0.5 = 0.75
+ assert score == pytest.approx(0.75)
+
+ def test_empty_metrics(self):
+ """Empty metrics should return 0."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_combined_score,
+ )
+
+ score = calculate_combined_score({})
+ assert score == 0.0
+
+ def test_missing_score_keys_in_metrics(self):
+ """Missing score keys within metric dicts should default to 0."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_combined_score,
+ )
+
+ metrics = {
+ "quality": {}, # No quality_score key
+ "speed": {"speed_score": 0.8},
+ }
+
+ score = calculate_combined_score(metrics)
+ # quality_score defaults to 0.0, speed_score=0.8
+ assert score == pytest.approx(0.0 * 0.6 + 0.8 * 0.3)
+
+
+class TestCalculateResourceMetrics:
+ """Tests for calculate_resource_metrics."""
+
+ def test_basic_resource_calculation(self):
+ """Basic resource metrics with default config."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_resource_metrics,
+ )
+
+ config = {
+ "iterations": 2,
+ "questions_per_iteration": 2,
+ "max_results": 50,
+ }
+ result = calculate_resource_metrics(config)
+
+ assert "resource_score" in result
+ assert "estimated_complexity" in result
+ assert 0 <= result["resource_score"] <= 1
+
+ def test_higher_config_means_more_resources(self):
+ """Higher config values should give lower resource score (more resources used)."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_resource_metrics,
+ )
+
+ low_config = {
+ "iterations": 1,
+ "questions_per_iteration": 1,
+ "max_results": 10,
+ }
+ high_config = {
+ "iterations": 10,
+ "questions_per_iteration": 10,
+ "max_results": 100,
+ }
+
+ low_result = calculate_resource_metrics(low_config)
+ high_result = calculate_resource_metrics(high_config)
+
+ assert low_result["resource_score"] > high_result["resource_score"]
+ assert (
+ low_result["estimated_complexity"]
+ < high_result["estimated_complexity"]
+ )
+
+ def test_default_values_used_when_missing(self):
+ """Default values should be used when config keys are missing."""
+ from local_deep_research.benchmarks.metrics.calculation import (
+ calculate_resource_metrics,
+ )
+
+ result = calculate_resource_metrics({}) # Empty config
+
+ assert "resource_score" in result
+ assert result["estimated_complexity"] > 0
diff --git a/tests/config/test_paths_extended.py b/tests/config/test_paths_extended.py
new file mode 100644
index 0000000000..9e09939595
--- /dev/null
+++ b/tests/config/test_paths_extended.py
@@ -0,0 +1,122 @@
+"""Extended tests for paths module - covering untested directory functions."""
+
+from pathlib import Path
+
+from local_deep_research.config.paths import (
+ get_library_directory,
+ get_config_directory,
+ get_models_directory,
+ get_research_outputs_directory,
+)
+
+
+class TestGetLibraryDirectory:
+ """Tests for get_library_directory function."""
+
+ def test_returns_library_subdirectory(self, mock_env_data_dir):
+ """Should return library subdirectory of data dir."""
+ result = get_library_directory()
+ assert result.name == "library"
+ assert result.parent == mock_env_data_dir
+
+ def test_creates_directory(self, mock_env_data_dir):
+ """Should create directory if it doesn't exist."""
+ result = get_library_directory()
+ assert result.exists()
+ assert result.is_dir()
+
+ def test_returns_path_object(self, mock_env_data_dir):
+ """Should return Path object."""
+ result = get_library_directory()
+ assert isinstance(result, Path)
+
+ def test_idempotent_when_directory_exists(self, mock_env_data_dir):
+ """Calling twice should work fine when directory already exists."""
+ result1 = get_library_directory()
+ result2 = get_library_directory()
+ assert result1 == result2
+ assert result1.exists()
+
+
+class TestGetConfigDirectory:
+ """Tests for get_config_directory function."""
+
+ def test_returns_config_subdirectory(self, mock_env_data_dir):
+ """Should return config subdirectory of data dir."""
+ result = get_config_directory()
+ assert result.name == "config"
+ assert result.parent == mock_env_data_dir
+
+ def test_creates_directory(self, mock_env_data_dir):
+ """Should create directory if it doesn't exist."""
+ result = get_config_directory()
+ assert result.exists()
+ assert result.is_dir()
+
+ def test_returns_path_object(self, mock_env_data_dir):
+ """Should return Path object."""
+ result = get_config_directory()
+ assert isinstance(result, Path)
+
+
+class TestGetModelsDirectory:
+ """Tests for get_models_directory function."""
+
+ def test_returns_models_subdirectory(self, mock_env_data_dir):
+ """Should return models subdirectory of data dir."""
+ result = get_models_directory()
+ assert result.name == "models"
+ assert result.parent == mock_env_data_dir
+
+ def test_creates_directory(self, mock_env_data_dir):
+ """Should create directory if it doesn't exist."""
+ result = get_models_directory()
+ assert result.exists()
+ assert result.is_dir()
+
+ def test_returns_path_object(self, mock_env_data_dir):
+ """Should return Path object."""
+ result = get_models_directory()
+ assert isinstance(result, Path)
+
+
+class TestAllDirectoriesUseDataDir:
+ """Verify all directory functions consistently use get_data_directory as base."""
+
+ def test_all_subdirectories_share_same_parent(self, mock_env_data_dir):
+ """All subdirectory functions should use the same data directory."""
+ library = get_library_directory()
+ config = get_config_directory()
+ models = get_models_directory()
+ outputs = get_research_outputs_directory()
+
+ assert library.parent == mock_env_data_dir
+ assert config.parent == mock_env_data_dir
+ assert models.parent == mock_env_data_dir
+ assert outputs.parent == mock_env_data_dir
+
+ def test_env_var_override_affects_all_directories(
+ self, tmp_path, monkeypatch
+ ):
+ """LDR_DATA_DIR override should affect all directory functions."""
+ custom_dir = tmp_path / "custom_data"
+ custom_dir.mkdir()
+ monkeypatch.setenv("LDR_DATA_DIR", str(custom_dir))
+
+ library = get_library_directory()
+ config = get_config_directory()
+ models = get_models_directory()
+
+ assert library.parent == custom_dir
+ assert config.parent == custom_dir
+ assert models.parent == custom_dir
+
+ def test_all_directories_are_distinct(self, mock_env_data_dir):
+ """All directory functions should return different paths."""
+ library = get_library_directory()
+ config = get_config_directory()
+ models = get_models_directory()
+ outputs = get_research_outputs_directory()
+
+ paths = {library, config, models, outputs}
+ assert len(paths) == 4, "All directory paths should be unique"
diff --git a/tests/core/test_search_system_extended.py b/tests/core/test_search_system_extended.py
new file mode 100644
index 0000000000..1c1b343653
--- /dev/null
+++ b/tests/core/test_search_system_extended.py
@@ -0,0 +1,415 @@
+"""Extended tests for search_system.py - covering settings processing, programmatic mode,
+strategy selection, and result processing."""
+
+from unittest.mock import Mock, patch
+
+
+def _make_strategy_mock():
+ """Create a mock strategy with required attributes."""
+ mock_strategy = Mock()
+ mock_strategy.questions_by_iteration = []
+ mock_strategy.all_links_of_system = []
+ return mock_strategy
+
+
+def _patch_system():
+ """Return nested context managers for search system patching.
+
+ Usage:
+ with _create_patched():
+ ...
+
+ Returns a helper that patches both create_strategy and StandardCitationHandler.
+ """
+
+ class PatchContext:
+ def __init__(self):
+ self.strategy = _make_strategy_mock()
+ self._p1 = patch(
+ "local_deep_research.search_system_factory.create_strategy",
+ return_value=self.strategy,
+ )
+ self._p2 = patch(
+ "local_deep_research.citation_handlers.standard_citation_handler.StandardCitationHandler",
+ return_value=Mock(
+ _create_documents=Mock(), _format_sources=Mock()
+ ),
+ )
+
+ def __enter__(self):
+ self.mock_create = self._p1.__enter__()
+ self.mock_citation = self._p2.__enter__()
+ return self
+
+ def __exit__(self, *args):
+ self._p2.__exit__(*args)
+ self._p1.__exit__(*args)
+
+ return PatchContext()
+
+
+class TestAdvancedSearchSystemSettingsProcessing:
+ """Tests for settings snapshot processing in AdvancedSearchSystem.__init__."""
+
+ def test_max_iterations_from_dict_settings(self):
+ """max_iterations should be extracted from dict-wrapped settings."""
+ settings = {
+ "search.iterations": {"value": 5, "ui_element": "number"},
+ "search.questions_per_iteration": {
+ "value": 4,
+ "ui_element": "number",
+ },
+ }
+
+ with _patch_system():
+ from local_deep_research.search_system import AdvancedSearchSystem
+
+ system = AdvancedSearchSystem(
+ llm=Mock(), search=Mock(), settings_snapshot=settings
+ )
+
+ assert system.max_iterations == 5
+ assert system.questions_per_iteration == 4
+
+ def test_max_iterations_from_direct_value_settings(self):
+ """max_iterations should work with direct (non-dict) settings values."""
+ settings = {
+ "search.iterations": 3,
+ "search.questions_per_iteration": 2,
+ }
+
+ with _patch_system():
+ from local_deep_research.search_system import AdvancedSearchSystem
+
+ system = AdvancedSearchSystem(
+ llm=Mock(), search=Mock(), settings_snapshot=settings
+ )
+
+ assert system.max_iterations == 3
+ assert system.questions_per_iteration == 2
+
+ def test_max_iterations_defaults_when_missing(self):
+ """max_iterations should default to 1 when not in settings."""
+ with _patch_system():
+ from local_deep_research.search_system import AdvancedSearchSystem
+
+ system = AdvancedSearchSystem(
+ llm=Mock(), search=Mock(), settings_snapshot={}
+ )
+
+ assert system.max_iterations == 1
+ assert system.questions_per_iteration == 3
+
+ def test_explicit_max_iterations_overrides_settings(self):
+ """Explicit max_iterations parameter should override settings snapshot."""
+ settings = {"search.iterations": {"value": 10}}
+
+ with _patch_system():
+ from local_deep_research.search_system import AdvancedSearchSystem
+
+ system = AdvancedSearchSystem(
+ llm=Mock(),
+ search=Mock(),
+ max_iterations=7,
+ settings_snapshot=settings,
+ )
+
+ assert system.max_iterations == 7
+
+
+class TestAdvancedSearchSystemProgrammaticMode:
+ """Tests for programmatic mode behavior."""
+
+ def test_programmatic_mode_sets_flag(self):
+ """programmatic_mode flag should be stored."""
+ with _patch_system():
+ from local_deep_research.search_system import AdvancedSearchSystem
+
+ system = AdvancedSearchSystem(
+ llm=Mock(), search=Mock(), programmatic_mode=True
+ )
+
+ assert system.programmatic_mode is True
+
+ def test_non_programmatic_mode_default(self):
+ """programmatic_mode should default to False."""
+ with _patch_system():
+ from local_deep_research.search_system import AdvancedSearchSystem
+
+ system = AdvancedSearchSystem(llm=Mock(), search=Mock())
+
+ assert system.programmatic_mode is False
+
+
+class TestAdvancedSearchSystemResearchContext:
+ """Tests for research context handling."""
+
+ def test_stores_research_context(self):
+ """research_context should be stored on the system."""
+ context = {"delegate_strategy": "rapid", "some_key": "some_value"}
+
+ with _patch_system():
+ from local_deep_research.search_system import AdvancedSearchSystem
+
+ system = AdvancedSearchSystem(
+ llm=Mock(), search=Mock(), research_context=context
+ )
+
+ assert system.research_context == context
+
+ def test_none_research_context(self):
+ """None research_context should not cause errors."""
+ with _patch_system():
+ from local_deep_research.search_system import AdvancedSearchSystem
+
+ system = AdvancedSearchSystem(
+ llm=Mock(), search=Mock(), research_context=None
+ )
+
+ assert system.research_context is None
+
+ def test_research_id_stored(self):
+ """research_id should be stored on the system."""
+ with _patch_system():
+ from local_deep_research.search_system import AdvancedSearchSystem
+
+ system = AdvancedSearchSystem(
+ llm=Mock(), search=Mock(), research_id="test-123"
+ )
+
+ assert system.research_id == "test-123"
+
+
+class TestAdvancedSearchSystemContextualFollowUp:
+ """Tests for contextual follow-up strategy initialization."""
+
+ def test_contextual_followup_uses_delegate(self):
+ """Contextual follow-up strategy should create a delegate strategy."""
+ context = {"delegate_strategy": "rapid"}
+
+ with _patch_system() as ctx:
+ with patch(
+ "local_deep_research.search_system.EnhancedContextualFollowUpStrategy"
+ ) as mock_followup_cls:
+ mock_followup_cls.return_value = Mock()
+
+ from local_deep_research.search_system import (
+ AdvancedSearchSystem,
+ )
+
+ AdvancedSearchSystem(
+ llm=Mock(),
+ search=Mock(),
+ strategy_name="enhanced-contextual-followup",
+ research_context=context,
+ )
+
+ # Verify delegate strategy was created with rapid
+ ctx.mock_create.assert_called()
+ call_kwargs = ctx.mock_create.call_args
+ assert call_kwargs.kwargs.get("strategy_name") == "rapid" or (
+ call_kwargs[1].get("strategy_name") == "rapid"
+ )
+
+ def test_contextual_followup_defaults_delegate_to_source_based(self):
+ """Contextual follow-up without delegate_strategy should default to source-based."""
+ with _patch_system() as ctx:
+ with patch(
+ "local_deep_research.search_system.EnhancedContextualFollowUpStrategy"
+ ) as mock_followup_cls:
+ mock_followup_cls.return_value = Mock()
+
+ from local_deep_research.search_system import (
+ AdvancedSearchSystem,
+ )
+
+ AdvancedSearchSystem(
+ llm=Mock(),
+ search=Mock(),
+ strategy_name="contextual-followup",
+ research_context={},
+ )
+
+ call_kwargs = ctx.mock_create.call_args
+ strategy_name = call_kwargs.kwargs.get(
+ "strategy_name"
+ ) or call_kwargs[1].get("strategy_name")
+ assert strategy_name == "source-based"
+
+ def test_contextual_followup_name_variants(self):
+ """All contextual follow-up name variants should be recognized."""
+ variants = [
+ "enhanced-contextual-followup",
+ "enhanced_contextual_followup",
+ "contextual-followup",
+ "contextual_followup",
+ ]
+
+ for variant in variants:
+ with _patch_system():
+ with patch(
+ "local_deep_research.search_system.EnhancedContextualFollowUpStrategy"
+ ) as mock_followup_cls:
+ mock_followup_cls.return_value = Mock()
+
+ from local_deep_research.search_system import (
+ AdvancedSearchSystem,
+ )
+
+ AdvancedSearchSystem(
+ llm=Mock(),
+ search=Mock(),
+ strategy_name=variant,
+ )
+ # Should use EnhancedContextualFollowUpStrategy
+ mock_followup_cls.assert_called_once()
+
+
+class TestAdvancedSearchSystemSearchOriginalQuery:
+ """Tests for search_original_query parameter."""
+
+ def test_search_original_query_default_true(self):
+ """search_original_query should default to True."""
+ with _patch_system():
+ from local_deep_research.search_system import AdvancedSearchSystem
+
+ system = AdvancedSearchSystem(llm=Mock(), search=Mock())
+
+ assert system.search_original_query is True
+
+ def test_search_original_query_can_be_disabled(self):
+ """search_original_query can be set to False for news searches."""
+ with _patch_system():
+ from local_deep_research.search_system import AdvancedSearchSystem
+
+ system = AdvancedSearchSystem(
+ llm=Mock(), search=Mock(), search_original_query=False
+ )
+
+ assert system.search_original_query is False
+
+
+class TestAdvancedSearchSystemPerformSearch:
+ """Tests for _perform_search result processing."""
+
+ def test_result_includes_query(self):
+ """Result should include the query if not returned by strategy."""
+ with _patch_system() as ctx:
+ ctx.strategy.analyze_topic.return_value = {
+ "current_knowledge": "some results"
+ }
+ ctx.strategy.questions_by_iteration = {1: ["q1"]}
+
+ from local_deep_research.search_system import AdvancedSearchSystem
+
+ system = AdvancedSearchSystem(llm=Mock(), search=Mock())
+
+ with patch(
+ "local_deep_research.news.core.search_integration.NewsSearchCallback"
+ ):
+ result = system.analyze_topic("test query")
+
+ assert result["query"] == "test query"
+
+ def test_result_includes_search_system_reference(self):
+ """Result should include reference to the search system."""
+ with _patch_system() as ctx:
+ ctx.strategy.analyze_topic.return_value = {
+ "current_knowledge": "results"
+ }
+ ctx.strategy.questions_by_iteration = {}
+
+ from local_deep_research.search_system import AdvancedSearchSystem
+
+ system = AdvancedSearchSystem(llm=Mock(), search=Mock())
+
+ with patch(
+ "local_deep_research.news.core.search_integration.NewsSearchCallback"
+ ):
+ result = system.analyze_topic("test query")
+
+ assert result["search_system"] is system
+
+ def test_settings_snapshot_extraction_in_perform_search(self):
+ """_perform_search should extract LLM/search info from settings snapshot."""
+ settings = {
+ "llm.provider": {"value": "openai"},
+ "llm.model": {"value": "gpt-4"},
+ "search.tool": {"value": "searxng"},
+ }
+
+ progress_calls = []
+
+ def capture_progress(msg, progress, metadata):
+ progress_calls.append((msg, progress, metadata))
+
+ with _patch_system() as ctx:
+ ctx.strategy.analyze_topic.return_value = {"current_knowledge": "r"}
+ ctx.strategy.questions_by_iteration = {}
+
+ from local_deep_research.search_system import AdvancedSearchSystem
+
+ system = AdvancedSearchSystem(
+ llm=Mock(), search=Mock(), settings_snapshot=settings
+ )
+ system.set_progress_callback(capture_progress)
+
+ with patch(
+ "local_deep_research.news.core.search_integration.NewsSearchCallback"
+ ):
+ system.analyze_topic("test")
+
+ # Should have progress callbacks with LLM and search info
+ assert len(progress_calls) >= 2
+ assert "openai" in progress_calls[0][0]
+ assert "gpt-4" in progress_calls[0][0]
+
+ def test_links_deduplication(self):
+ """all_links_of_system should not be duplicated when same object."""
+ shared_links = [{"title": "link1", "url": "http://example.com"}]
+
+ with _patch_system() as ctx:
+ ctx.strategy.analyze_topic.return_value = {"current_knowledge": "r"}
+ ctx.strategy.questions_by_iteration = {}
+ ctx.strategy.all_links_of_system = shared_links
+
+ from local_deep_research.search_system import AdvancedSearchSystem
+
+ system = AdvancedSearchSystem(llm=Mock(), search=Mock())
+ system.all_links_of_system = shared_links
+
+ with patch(
+ "local_deep_research.news.core.search_integration.NewsSearchCallback"
+ ):
+ system.analyze_topic("test")
+
+ # Should NOT have duplicated the links
+ assert len(system.all_links_of_system) == 1
+
+
+class TestAdvancedSearchSystemProgressCallback:
+ """Tests for progress callback mechanism."""
+
+ def test_set_progress_callback_propagates_to_strategy(self):
+ """set_progress_callback should propagate to the strategy."""
+ with _patch_system() as ctx:
+ from local_deep_research.search_system import AdvancedSearchSystem
+
+ system = AdvancedSearchSystem(llm=Mock(), search=Mock())
+
+ def noop_callback(msg, pct, meta):
+ return None
+
+ system.set_progress_callback(noop_callback)
+
+ ctx.strategy.set_progress_callback.assert_called_with(noop_callback)
+
+ def test_progress_callback_before_strategy_exists(self):
+ """Setting callback before strategy is created should not crash."""
+ with _patch_system():
+ from local_deep_research.search_system import AdvancedSearchSystem
+
+ system = AdvancedSearchSystem(llm=Mock(), search=Mock())
+
+ # Default callback should be a no-op lambda
+ system.progress_callback("test", 50, {})
diff --git a/tests/core/test_search_system_factory_extended.py b/tests/core/test_search_system_factory_extended.py
new file mode 100644
index 0000000000..7b07384bde
--- /dev/null
+++ b/tests/core/test_search_system_factory_extended.py
@@ -0,0 +1,351 @@
+"""Extended tests for search_system_factory.py - covering _get_setting helper,
+strategy creation edge cases, and unknown strategy fallback."""
+
+from unittest.mock import Mock, patch
+
+
+class TestGetSettingHelper:
+ """Tests for _get_setting utility function."""
+
+ def test_returns_default_when_no_snapshot(self):
+ """Should return default when settings_snapshot is None."""
+ from local_deep_research.search_system_factory import _get_setting
+
+ result = _get_setting(None, "key", "default_value")
+ assert result == "default_value"
+
+ def test_returns_default_when_empty_snapshot(self):
+ """Should return default when settings_snapshot is empty dict."""
+ from local_deep_research.search_system_factory import _get_setting
+
+ result = _get_setting({}, "key", "default_value")
+ assert result == "default_value"
+
+ def test_returns_default_when_key_missing(self):
+ """Should return default when key is not in snapshot."""
+ from local_deep_research.search_system_factory import _get_setting
+
+ result = _get_setting({"other_key": "value"}, "key", "default_value")
+ assert result == "default_value"
+
+ def test_extracts_value_from_dict(self):
+ """Should extract value from dict-wrapped setting."""
+ from local_deep_research.search_system_factory import _get_setting
+
+ snapshot = {"key": {"value": 42, "ui_element": "number"}}
+ result = _get_setting(snapshot, "key", 0)
+ assert result == 42
+
+ def test_returns_direct_value(self):
+ """Should return direct (non-dict) value."""
+ from local_deep_research.search_system_factory import _get_setting
+
+ snapshot = {"key": "direct_string"}
+ result = _get_setting(snapshot, "key", "default")
+ assert result == "direct_string"
+
+ def test_returns_dict_without_value_key_as_is(self):
+ """Dict without 'value' key should be returned as-is."""
+ from local_deep_research.search_system_factory import _get_setting
+
+ snapshot = {"key": {"other": "data"}}
+ result = _get_setting(snapshot, "key", "default")
+ assert result == {"other": "data"}
+
+ def test_handles_boolean_values(self):
+ """Should handle boolean values in settings."""
+ from local_deep_research.search_system_factory import _get_setting
+
+ snapshot = {"key": {"value": True}}
+ result = _get_setting(snapshot, "key", False)
+ assert result is True
+
+ def test_handles_none_value_in_dict(self):
+ """Should handle None as value in dict-wrapped setting."""
+ from local_deep_research.search_system_factory import _get_setting
+
+ snapshot = {"key": {"value": None}}
+ result = _get_setting(snapshot, "key", "default")
+ assert result is None
+
+ def test_handles_zero_value(self):
+ """Should handle 0 value correctly (not confuse with None)."""
+ from local_deep_research.search_system_factory import _get_setting
+
+ snapshot = {"key": {"value": 0}}
+ result = _get_setting(snapshot, "key", 5)
+ assert result == 0
+
+ def test_handles_empty_string_value(self):
+ """Should handle empty string value."""
+ from local_deep_research.search_system_factory import _get_setting
+
+ snapshot = {"key": {"value": ""}}
+ result = _get_setting(snapshot, "key", "default")
+ assert result == ""
+
+
+class TestCreateStrategyNames:
+ """Tests for strategy name handling in create_strategy."""
+
+ def test_source_based_variants(self):
+ """All source-based name variants should create SourceBasedSearchStrategy."""
+ from local_deep_research.search_system_factory import create_strategy
+
+ variants = ["source-based", "source_based", "source_based_search"]
+
+ for variant in variants:
+ strategy = create_strategy(
+ strategy_name=variant,
+ model=Mock(),
+ search=Mock(),
+ )
+ assert type(strategy).__name__ == "SourceBasedSearchStrategy", (
+ f"Variant '{variant}' did not create SourceBasedSearchStrategy"
+ )
+
+ def test_iterdrag_creates_correct_strategy(self):
+ """iterdrag name should create IterDRAGStrategy."""
+ from local_deep_research.search_system_factory import create_strategy
+
+ strategy = create_strategy(
+ strategy_name="iterdrag",
+ model=Mock(),
+ search=Mock(),
+ )
+ assert type(strategy).__name__ == "IterDRAGStrategy"
+
+ def test_rapid_creates_correct_strategy(self):
+ """rapid name should create RapidSearchStrategy."""
+ from local_deep_research.search_system_factory import create_strategy
+
+ strategy = create_strategy(
+ strategy_name="rapid",
+ model=Mock(),
+ search=Mock(),
+ )
+ assert type(strategy).__name__ == "RapidSearchStrategy"
+
+ def test_parallel_creates_correct_strategy(self):
+ """parallel name should create ParallelSearchStrategy."""
+ from local_deep_research.search_system_factory import create_strategy
+
+ strategy = create_strategy(
+ strategy_name="parallel",
+ model=Mock(),
+ search=Mock(),
+ )
+ assert type(strategy).__name__ == "ParallelSearchStrategy"
+
+ def test_standard_creates_correct_strategy(self):
+ """standard name should create StandardSearchStrategy."""
+ from local_deep_research.search_system_factory import create_strategy
+
+ settings = {
+ "search.iterations": {"value": 3},
+ "search.questions_per_iteration": {"value": 3},
+ "general.knowledge_accumulation_context_limit": {"value": 50000},
+ }
+
+ with patch(
+ "local_deep_research.citation_handlers.standard_citation_handler.StandardCitationHandler"
+ ):
+ strategy = create_strategy(
+ strategy_name="standard",
+ model=Mock(),
+ search=Mock(),
+ settings_snapshot=settings,
+ )
+ assert type(strategy).__name__ == "StandardSearchStrategy"
+
+
+class TestCreateStrategyUnknown:
+ """Tests for unknown strategy name handling."""
+
+ def test_unknown_strategy_falls_back_to_source_based(self):
+ """Unknown strategy name should fall back to SourceBasedSearchStrategy."""
+ from local_deep_research.search_system_factory import create_strategy
+
+ strategy = create_strategy(
+ strategy_name="nonexistent_strategy_xyz",
+ model=Mock(),
+ search=Mock(),
+ )
+ assert type(strategy).__name__ == "SourceBasedSearchStrategy"
+
+ def test_empty_string_strategy_falls_back(self):
+ """Empty string strategy should fall back to source-based."""
+ from local_deep_research.search_system_factory import create_strategy
+
+ strategy = create_strategy(
+ strategy_name="",
+ model=Mock(),
+ search=Mock(),
+ )
+ assert type(strategy).__name__ == "SourceBasedSearchStrategy"
+
+
+class TestCreateStrategyKwargsPassthrough:
+ """Tests for kwargs passthrough to strategies."""
+
+ def test_source_based_receives_kwargs(self):
+ """Source-based strategy should receive kwargs."""
+ from local_deep_research.search_system_factory import create_strategy
+
+ strategy = create_strategy(
+ strategy_name="source-based",
+ model=Mock(),
+ search=Mock(),
+ include_text_content=False,
+ use_cross_engine_filter=False,
+ use_atomic_facts=True,
+ )
+
+ assert strategy.include_text_content is False
+ assert strategy.use_cross_engine_filter is False
+
+ def test_iterative_strategy_receives_iteration_settings(self):
+ """Iterative strategy should receive iteration settings from kwargs."""
+ from local_deep_research.search_system_factory import create_strategy
+
+ strategy = create_strategy(
+ strategy_name="iterative",
+ model=Mock(),
+ search=Mock(),
+ max_iterations=15,
+ questions_per_iteration=5,
+ confidence_threshold=0.85,
+ )
+
+ assert strategy.max_iterations == 15
+ assert strategy.confidence_threshold == 0.85
+
+
+class TestCreateStrategySettingsSnapshot:
+ """Tests for settings snapshot integration in create_strategy."""
+
+ def test_all_links_initialized_when_none(self):
+ """all_links_of_system should be initialized to empty list when None."""
+ from local_deep_research.search_system_factory import create_strategy
+
+ strategy = create_strategy(
+ strategy_name="rapid",
+ model=Mock(),
+ search=Mock(),
+ all_links_of_system=None,
+ )
+
+ assert strategy.all_links_of_system == []
+
+ def test_all_links_passed_through(self):
+ """Provided all_links_of_system should be passed to strategy."""
+ from local_deep_research.search_system_factory import create_strategy
+
+ existing_links = [{"url": "http://example.com", "title": "Test"}]
+
+ strategy = create_strategy(
+ strategy_name="rapid",
+ model=Mock(),
+ search=Mock(),
+ all_links_of_system=existing_links,
+ )
+
+ assert strategy.all_links_of_system is existing_links
+
+ def test_settings_snapshot_passed_to_strategy(self):
+ """Settings snapshot should be passed to strategy."""
+ from local_deep_research.search_system_factory import create_strategy
+
+ settings = {"some.setting": "value"}
+
+ strategy = create_strategy(
+ strategy_name="source-based",
+ model=Mock(),
+ search=Mock(),
+ settings_snapshot=settings,
+ )
+
+ assert strategy.settings_snapshot is settings
+
+
+class TestCreateStrategyFocusedIteration:
+ """Tests for focused-iteration strategy creation with settings."""
+
+ def test_focused_iteration_reads_settings(self):
+ """Focused iteration should read settings from snapshot."""
+ from local_deep_research.search_system_factory import create_strategy
+
+ settings = {
+ "focused_iteration.adaptive_questions": {"value": 1},
+ "focused_iteration.knowledge_summary_limit": {"value": 5},
+ "focused_iteration.snippet_truncate": {"value": 100},
+ }
+
+ strategy = create_strategy(
+ strategy_name="focused-iteration",
+ model=Mock(),
+ search=Mock(),
+ settings_snapshot=settings,
+ )
+
+ assert strategy.enable_adaptive_questions is True
+ assert strategy.knowledge_summary_limit == 5
+ assert strategy.knowledge_snippet_truncate == 100
+
+ def test_focused_iteration_zero_converts_to_none(self):
+ """Knowledge limit of 0 should be converted to None (unlimited)."""
+ from local_deep_research.search_system_factory import create_strategy
+
+ settings = {
+ "focused_iteration.knowledge_summary_limit": {"value": 0},
+ "focused_iteration.snippet_truncate": {"value": 0},
+ }
+
+ strategy = create_strategy(
+ strategy_name="focused-iteration",
+ model=Mock(),
+ search=Mock(),
+ settings_snapshot=settings,
+ )
+
+ assert strategy.knowledge_summary_limit is None
+ assert strategy.knowledge_snippet_truncate is None
+
+ def test_focused_iteration_name_variants(self):
+ """Both focused-iteration name variants should work."""
+ from local_deep_research.search_system_factory import create_strategy
+
+ for variant in ["focused-iteration", "focused_iteration"]:
+ strategy = create_strategy(
+ strategy_name=variant,
+ model=Mock(),
+ search=Mock(),
+ )
+ assert type(strategy).__name__ == "FocusedIterationStrategy"
+
+
+class TestCreateStrategyCaseInsensitivity:
+ """Tests for case handling in strategy names."""
+
+ def test_lowercase_matching(self):
+ """Strategy names should be matched case-insensitively."""
+ from local_deep_research.search_system_factory import create_strategy
+
+ # The function calls .lower() on strategy_name
+ strategy = create_strategy(
+ strategy_name="RAPID",
+ model=Mock(),
+ search=Mock(),
+ )
+ assert type(strategy).__name__ == "RapidSearchStrategy"
+
+ def test_mixed_case_matching(self):
+ """Mixed case strategy names should work."""
+ from local_deep_research.search_system_factory import create_strategy
+
+ strategy = create_strategy(
+ strategy_name="Source-Based",
+ model=Mock(),
+ search=Mock(),
+ )
+ assert type(strategy).__name__ == "SourceBasedSearchStrategy"
diff --git a/tests/metrics/test_token_counter_callback.py b/tests/metrics/test_token_counter_callback.py
new file mode 100644
index 0000000000..48a5806d0e
--- /dev/null
+++ b/tests/metrics/test_token_counter_callback.py
@@ -0,0 +1,733 @@
+"""Tests for TokenCountingCallback real behavior - covering token extraction,
+model detection, provider detection, context overflow, and error handling."""
+
+import time
+from unittest.mock import Mock
+
+from langchain_core.outputs import LLMResult
+
+from local_deep_research.metrics.token_counter import (
+ TokenCountingCallback,
+ TokenCounter,
+)
+
+
+class TestTokenCountingCallbackModelDetection:
+ """Tests for model name detection from various sources."""
+
+ def test_preset_model_takes_priority(self):
+ """Preset model name should override all other detection."""
+ callback = TokenCountingCallback()
+ callback.preset_model = "my-preset-model"
+ callback.preset_provider = "openai"
+
+ serialized = {"name": "different-model", "_type": "ChatOpenAI"}
+ callback.on_llm_start(serialized, ["test prompt"])
+
+ assert callback.current_model == "my-preset-model"
+
+ def test_model_from_invocation_params(self):
+ """Model should be extracted from invocation_params."""
+ callback = TokenCountingCallback()
+
+ serialized = {}
+ kwargs = {"invocation_params": {"model": "gpt-4-turbo"}}
+ callback.on_llm_start(serialized, ["test"], **kwargs)
+
+ assert callback.current_model == "gpt-4-turbo"
+
+ def test_model_from_serialized_kwargs(self):
+ """Model should be extracted from serialized kwargs."""
+ callback = TokenCountingCallback()
+
+ serialized = {"kwargs": {"model": "claude-3-opus"}}
+ callback.on_llm_start(serialized, ["test"])
+
+ assert callback.current_model == "claude-3-opus"
+
+ def test_model_from_serialized_name(self):
+ """Model should be extracted from serialized name."""
+ callback = TokenCountingCallback()
+
+ serialized = {"name": "my-model"}
+ callback.on_llm_start(serialized, ["test"])
+
+ assert callback.current_model == "my-model"
+
+ def test_ollama_model_extraction(self):
+ """Ollama model should be extracted from serialized type and kwargs."""
+ callback = TokenCountingCallback()
+
+ serialized = {
+ "_type": "ChatOllama",
+ "kwargs": {"model": "llama3:8b"},
+ }
+ callback.on_llm_start(serialized, ["test"])
+
+ assert callback.current_model == "llama3:8b"
+
+ def test_ollama_type_without_model_name(self):
+ """Ollama type without model name should default to 'ollama'."""
+ callback = TokenCountingCallback()
+
+ serialized = {"_type": "ChatOllama"}
+ callback.on_llm_start(serialized, ["test"])
+
+ assert callback.current_model == "ollama"
+
+ def test_unknown_model_fallback(self):
+ """Unknown model should fall back to 'unknown'."""
+ callback = TokenCountingCallback()
+
+ serialized = {}
+ callback.on_llm_start(serialized, ["test"])
+
+ assert callback.current_model == "unknown"
+
+ def test_type_as_model_fallback(self):
+ """_type should be used as model name if no other source found."""
+ callback = TokenCountingCallback()
+
+ serialized = {"_type": "CustomLLM"}
+ callback.on_llm_start(serialized, ["test"])
+
+ assert callback.current_model == "CustomLLM"
+
+
+class TestTokenCountingCallbackProviderDetection:
+ """Tests for provider detection from various sources."""
+
+ def test_preset_provider_takes_priority(self):
+ """Preset provider should override detection."""
+ callback = TokenCountingCallback()
+ callback.preset_provider = "anthropic"
+
+ serialized = {"_type": "ChatOpenAI"}
+ callback.on_llm_start(serialized, ["test"])
+
+ assert callback.current_provider == "anthropic"
+
+ def test_openai_provider_detection(self):
+ """ChatOpenAI type should detect 'openai' provider."""
+ callback = TokenCountingCallback()
+
+ serialized = {"_type": "ChatOpenAI", "kwargs": {"model": "gpt-4"}}
+ callback.on_llm_start(serialized, ["test"])
+
+ assert callback.current_provider == "openai"
+
+ def test_anthropic_provider_detection(self):
+ """ChatAnthropic type should detect 'anthropic' provider."""
+ callback = TokenCountingCallback()
+
+ serialized = {
+ "_type": "ChatAnthropic",
+ "kwargs": {"model": "claude-3-opus"},
+ }
+ callback.on_llm_start(serialized, ["test"])
+
+ assert callback.current_provider == "anthropic"
+
+ def test_ollama_provider_detection(self):
+ """ChatOllama type should detect 'ollama' provider."""
+ callback = TokenCountingCallback()
+
+ serialized = {
+ "_type": "ChatOllama",
+ "kwargs": {"model": "llama3"},
+ }
+ callback.on_llm_start(serialized, ["test"])
+
+ assert callback.current_provider == "ollama"
+
+ def test_unknown_provider_fallback(self):
+ """Unknown type should fall back to 'unknown' provider."""
+ callback = TokenCountingCallback()
+
+ serialized = {}
+ callback.on_llm_start(serialized, ["test"])
+
+ assert callback.current_provider == "unknown"
+
+
+class TestTokenCountingCallbackTokenExtraction:
+ """Tests for token extraction from LLM responses."""
+
+ def test_token_extraction_from_llm_output(self):
+ """Tokens should be extracted from response.llm_output."""
+ callback = TokenCountingCallback()
+ callback.current_model = "gpt-4"
+ callback.counts["by_model"]["gpt-4"] = {
+ "prompt_tokens": 0,
+ "completion_tokens": 0,
+ "total_tokens": 0,
+ "calls": 1,
+ "provider": "openai",
+ }
+
+ response = Mock(spec=LLMResult)
+ response.llm_output = {
+ "token_usage": {
+ "prompt_tokens": 100,
+ "completion_tokens": 50,
+ "total_tokens": 150,
+ }
+ }
+ response.generations = []
+
+ callback.on_llm_end(response)
+
+ assert callback.counts["total_prompt_tokens"] == 100
+ assert callback.counts["total_completion_tokens"] == 50
+ assert callback.counts["total_tokens"] == 150
+
+ def test_token_extraction_from_usage_metadata(self):
+ """Tokens should be extracted from generation.message.usage_metadata."""
+ callback = TokenCountingCallback()
+ callback.current_model = "llama3"
+ callback.counts["by_model"]["llama3"] = {
+ "prompt_tokens": 0,
+ "completion_tokens": 0,
+ "total_tokens": 0,
+ "calls": 1,
+ "provider": "ollama",
+ }
+
+ # Create mock generation with usage_metadata
+ mock_message = Mock()
+ mock_message.usage_metadata = {
+ "input_tokens": 200,
+ "output_tokens": 80,
+ "total_tokens": 280,
+ }
+ mock_message.response_metadata = {}
+
+ mock_generation = Mock()
+ mock_generation.message = mock_message
+
+ response = Mock(spec=LLMResult)
+ response.llm_output = None
+ response.generations = [[mock_generation]]
+
+ callback.on_llm_end(response)
+
+ assert callback.counts["total_prompt_tokens"] == 200
+ assert callback.counts["total_completion_tokens"] == 80
+ assert callback.counts["total_tokens"] == 280
+
+ def test_token_extraction_from_response_metadata_ollama(self):
+ """Tokens should be extracted from Ollama response_metadata."""
+ callback = TokenCountingCallback()
+ callback.current_model = "llama3"
+ callback.counts["by_model"]["llama3"] = {
+ "prompt_tokens": 0,
+ "completion_tokens": 0,
+ "total_tokens": 0,
+ "calls": 1,
+ "provider": "ollama",
+ }
+
+ mock_message = Mock()
+ mock_message.usage_metadata = None
+ mock_message.response_metadata = {
+ "prompt_eval_count": 300,
+ "eval_count": 120,
+ "total_duration": 5000000000,
+ "load_duration": 100000000,
+ "prompt_eval_duration": 2000000000,
+ "eval_duration": 2900000000,
+ }
+
+ mock_generation = Mock()
+ mock_generation.message = mock_message
+
+ response = Mock(spec=LLMResult)
+ response.llm_output = None
+ response.generations = [[mock_generation]]
+
+ callback.on_llm_end(response)
+
+ assert callback.counts["total_prompt_tokens"] == 300
+ assert callback.counts["total_completion_tokens"] == 120
+ assert callback.counts["total_tokens"] == 420
+
+ def test_no_token_usage_available(self):
+ """No token usage data should not crash and not update counts."""
+ callback = TokenCountingCallback()
+ callback.current_model = "test"
+ callback.counts["by_model"]["test"] = {
+ "prompt_tokens": 0,
+ "completion_tokens": 0,
+ "total_tokens": 0,
+ "calls": 1,
+ "provider": "unknown",
+ }
+
+ response = Mock(spec=LLMResult)
+ response.llm_output = None
+ response.generations = []
+
+ callback.on_llm_end(response)
+
+ assert callback.counts["total_tokens"] == 0
+
+ def test_cumulative_token_counting(self):
+ """Multiple on_llm_end calls should accumulate token counts."""
+ callback = TokenCountingCallback()
+ callback.current_model = "gpt-4"
+ callback.counts["by_model"]["gpt-4"] = {
+ "prompt_tokens": 0,
+ "completion_tokens": 0,
+ "total_tokens": 0,
+ "calls": 1,
+ "provider": "openai",
+ }
+
+ for i in range(3):
+ response = Mock(spec=LLMResult)
+ response.llm_output = {
+ "token_usage": {
+ "prompt_tokens": 10,
+ "completion_tokens": 5,
+ "total_tokens": 15,
+ }
+ }
+ response.generations = []
+ callback.on_llm_end(response)
+
+ assert callback.counts["total_tokens"] == 45
+ assert callback.counts["total_prompt_tokens"] == 30
+ assert callback.counts["total_completion_tokens"] == 15
+
+
+class TestTokenCountingCallbackContextOverflow:
+ """Tests for context overflow detection."""
+
+ def test_context_overflow_detected(self):
+ """Context overflow should be detected when near context limit."""
+ callback = TokenCountingCallback(
+ research_context={"context_limit": 4096}
+ )
+ callback.current_model = "llama3"
+ callback.counts["by_model"]["llama3"] = {
+ "prompt_tokens": 0,
+ "completion_tokens": 0,
+ "total_tokens": 0,
+ "calls": 1,
+ "provider": "ollama",
+ }
+
+ # Estimate original prompt is much larger
+ callback.original_prompt_estimate = 5000
+
+ # Simulate start to set context limit
+ callback.on_llm_start({"_type": "ChatOllama"}, ["x" * 20000])
+
+ mock_message = Mock()
+ mock_message.usage_metadata = None
+ mock_message.response_metadata = {
+ "prompt_eval_count": 3900, # 95% of 4096
+ "eval_count": 100,
+ }
+ mock_generation = Mock()
+ mock_generation.message = mock_message
+
+ response = Mock(spec=LLMResult)
+ response.llm_output = None
+ response.generations = [[mock_generation]]
+
+ callback.on_llm_end(response)
+
+ assert callback.context_truncated is True
+ assert callback.tokens_truncated > 0
+
+ def test_no_overflow_when_below_threshold(self):
+ """No overflow when prompt tokens are below 95% of context limit."""
+ callback = TokenCountingCallback(
+ research_context={"context_limit": 4096}
+ )
+ callback.current_model = "llama3"
+ callback.counts["by_model"]["llama3"] = {
+ "prompt_tokens": 0,
+ "completion_tokens": 0,
+ "total_tokens": 0,
+ "calls": 1,
+ "provider": "ollama",
+ }
+
+ callback.on_llm_start({"_type": "ChatOllama"}, ["x" * 4000])
+
+ mock_message = Mock()
+ mock_message.usage_metadata = None
+ mock_message.response_metadata = {
+ "prompt_eval_count": 2000, # Well below 95% of 4096
+ "eval_count": 100,
+ }
+ mock_generation = Mock()
+ mock_generation.message = mock_message
+
+ response = Mock(spec=LLMResult)
+ response.llm_output = None
+ response.generations = [[mock_generation]]
+
+ callback.on_llm_end(response)
+
+ assert callback.context_truncated is False
+
+ def test_no_overflow_without_context_limit(self):
+ """No overflow detection when context_limit is not set."""
+ callback = TokenCountingCallback()
+ callback.current_model = "gpt-4"
+ callback.counts["by_model"]["gpt-4"] = {
+ "prompt_tokens": 0,
+ "completion_tokens": 0,
+ "total_tokens": 0,
+ "calls": 1,
+ "provider": "openai",
+ }
+
+ mock_message = Mock()
+ mock_message.usage_metadata = None
+ mock_message.response_metadata = {
+ "prompt_eval_count": 100000,
+ "eval_count": 100,
+ }
+ mock_generation = Mock()
+ mock_generation.message = mock_message
+
+ response = Mock(spec=LLMResult)
+ response.llm_output = None
+ response.generations = [[mock_generation]]
+
+ callback.on_llm_end(response)
+
+ assert callback.context_truncated is False
+
+
+class TestTokenCountingCallbackErrorHandling:
+ """Tests for error tracking in callback."""
+
+ def test_error_sets_status_and_type(self):
+ """on_llm_error should set error status and type."""
+ callback = TokenCountingCallback()
+ callback.start_time = time.time()
+
+ error = ValueError("test error")
+ callback.on_llm_error(error)
+
+ assert callback.success_status == "error"
+ assert callback.error_type == "ValueError"
+
+ def test_error_calculates_response_time(self):
+ """on_llm_error should calculate response time."""
+ callback = TokenCountingCallback()
+ callback.start_time = time.time() - 0.5 # 500ms ago
+
+ callback.on_llm_error(RuntimeError("test"))
+
+ assert callback.response_time_ms is not None
+ assert callback.response_time_ms >= 400 # At least 400ms
+
+ def test_error_without_start_time(self):
+ """on_llm_error without start_time should not crash."""
+ callback = TokenCountingCallback()
+
+ callback.on_llm_error(RuntimeError("test"))
+
+ assert callback.success_status == "error"
+ assert callback.response_time_ms is None
+
+
+class TestTokenCountingCallbackTimingAndCallStack:
+ """Tests for timing and call stack tracking."""
+
+ def test_start_time_set_on_llm_start(self):
+ """on_llm_start should record start time."""
+ callback = TokenCountingCallback()
+
+ before = time.time()
+ callback.on_llm_start({}, ["test"])
+ after = time.time()
+
+ assert before <= callback.start_time <= after
+
+ def test_response_time_calculated_on_end(self):
+ """on_llm_end should calculate response time in ms."""
+ callback = TokenCountingCallback()
+ callback.current_model = "test"
+ callback.counts["by_model"]["test"] = {
+ "prompt_tokens": 0,
+ "completion_tokens": 0,
+ "total_tokens": 0,
+ "calls": 1,
+ "provider": "unknown",
+ }
+ callback.start_time = time.time() - 0.1 # 100ms ago
+
+ response = Mock(spec=LLMResult)
+ response.llm_output = None
+ response.generations = []
+
+ callback.on_llm_end(response)
+
+ assert callback.response_time_ms is not None
+ assert callback.response_time_ms >= 50 # At least 50ms
+
+ def test_prompt_estimate_from_prompts(self):
+ """original_prompt_estimate should be set from prompt length."""
+ callback = TokenCountingCallback()
+
+ callback.on_llm_start({}, ["Hello world!"]) # 12 chars ~ 3 tokens
+
+ assert callback.original_prompt_estimate == 3 # 12 // 4
+
+ def test_prompt_estimate_multiple_prompts(self):
+ """Multiple prompts should sum their character counts for estimate."""
+ callback = TokenCountingCallback()
+
+ callback.on_llm_start({}, ["aaaa", "bbbb", "cccc"]) # 12 chars total
+
+ assert callback.original_prompt_estimate == 3 # 12 // 4
+
+ def test_call_count_incremented(self):
+ """Call count should increment on each on_llm_start."""
+ callback = TokenCountingCallback()
+
+ callback.on_llm_start(
+ {"_type": "ChatOpenAI", "kwargs": {"model": "gpt-4"}}, ["test"]
+ )
+ callback.on_llm_start(
+ {"_type": "ChatOpenAI", "kwargs": {"model": "gpt-4"}}, ["test"]
+ )
+
+ assert callback.counts["by_model"]["gpt-4"]["calls"] == 2
+
+
+class TestTokenCountingCallbackGetContextOverflowFields:
+ """Tests for _get_context_overflow_fields helper."""
+
+ def test_fields_when_no_overflow(self):
+ """Fields should indicate no overflow when not truncated."""
+ callback = TokenCountingCallback()
+
+ fields = callback._get_context_overflow_fields()
+
+ assert fields["context_truncated"] is False
+ assert fields["tokens_truncated"] is None
+ assert fields["truncation_ratio"] is None
+
+ def test_fields_when_overflow(self):
+ """Fields should contain overflow data when truncated."""
+ callback = TokenCountingCallback()
+ callback.context_limit = 4096
+ callback.context_truncated = True
+ callback.tokens_truncated = 500
+ callback.truncation_ratio = 0.12
+ callback.ollama_metrics = {
+ "prompt_eval_count": 3900,
+ "eval_count": 100,
+ }
+
+ fields = callback._get_context_overflow_fields()
+
+ assert fields["context_truncated"] is True
+ assert fields["tokens_truncated"] == 500
+ assert fields["truncation_ratio"] == 0.12
+ assert fields["context_limit"] == 4096
+ assert fields["ollama_prompt_eval_count"] == 3900
+
+
+class TestTokenCounterManager:
+ """Tests for TokenCounter manager class."""
+
+ def test_create_callback_returns_callback(self):
+ """create_callback should return a TokenCountingCallback instance."""
+ counter = TokenCounter()
+ callback = counter.create_callback(
+ research_id="test-123",
+ research_context={"key": "value"},
+ )
+
+ assert isinstance(callback, TokenCountingCallback)
+ assert callback.research_id == "test-123"
+ assert callback.research_context == {"key": "value"}
+
+ def test_create_callback_without_args(self):
+ """create_callback without args should work."""
+ counter = TokenCounter()
+ callback = counter.create_callback()
+
+ assert isinstance(callback, TokenCountingCallback)
+ assert callback.research_id is None
+
+ def test_empty_metrics_structure(self):
+ """_get_empty_metrics should return proper structure."""
+ counter = TokenCounter()
+ metrics = counter._get_empty_metrics()
+
+ assert metrics["total_tokens"] == 0
+ assert metrics["total_researches"] == 0
+ assert metrics["by_model"] == []
+ assert metrics["recent_researches"] == []
+ assert "token_breakdown" in metrics
+
+ def test_merge_metrics_combines_totals(self):
+ """_merge_metrics should combine totals from both sources."""
+ counter = TokenCounter()
+
+ encrypted = {
+ "total_tokens": 1000,
+ "total_researches": 5,
+ "by_model": [
+ {
+ "model": "gpt-4",
+ "provider": "openai",
+ "tokens": 800,
+ "calls": 3,
+ "prompt_tokens": 500,
+ "completion_tokens": 300,
+ }
+ ],
+ "recent_researches": [{"id": "r1"}],
+ "token_breakdown": {
+ "total_input_tokens": 600,
+ "total_output_tokens": 400,
+ "avg_input_tokens": 200,
+ "avg_output_tokens": 133,
+ "avg_total_tokens": 333,
+ },
+ }
+ thread = {
+ "total_tokens": 500,
+ "total_researches": 3,
+ "by_model": [
+ {
+ "model": "gpt-4",
+ "provider": "openai",
+ "tokens": 500,
+ "calls": 2,
+ "prompt_tokens": 300,
+ "completion_tokens": 200,
+ }
+ ],
+ "recent_researches": [],
+ "token_breakdown": {
+ "total_input_tokens": 300,
+ "total_output_tokens": 200,
+ "avg_input_tokens": 0,
+ "avg_output_tokens": 0,
+ "avg_total_tokens": 0,
+ },
+ }
+
+ result = counter._merge_metrics(encrypted, thread)
+
+ assert result["total_tokens"] == 1500
+ assert result["total_researches"] == 5 # max(5, 3)
+ assert len(result["by_model"]) == 1
+ assert result["by_model"][0]["tokens"] == 1300 # 800 + 500
+ assert result["by_model"][0]["calls"] == 5 # 3 + 2
+ assert result["token_breakdown"]["total_input_tokens"] == 900
+
+ def test_merge_metrics_different_models(self):
+ """_merge_metrics should keep separate models distinct."""
+ counter = TokenCounter()
+
+ encrypted = {
+ "total_tokens": 100,
+ "total_researches": 1,
+ "by_model": [
+ {
+ "model": "gpt-4",
+ "provider": "openai",
+ "tokens": 100,
+ "calls": 1,
+ "prompt_tokens": 60,
+ "completion_tokens": 40,
+ }
+ ],
+ "recent_researches": [],
+ "token_breakdown": {
+ "total_input_tokens": 60,
+ "total_output_tokens": 40,
+ "avg_input_tokens": 60,
+ "avg_output_tokens": 40,
+ "avg_total_tokens": 100,
+ },
+ }
+ thread = {
+ "total_tokens": 200,
+ "total_researches": 1,
+ "by_model": [
+ {
+ "model": "llama3",
+ "provider": "ollama",
+ "tokens": 200,
+ "calls": 2,
+ "prompt_tokens": 120,
+ "completion_tokens": 80,
+ }
+ ],
+ "recent_researches": [],
+ "token_breakdown": {
+ "total_input_tokens": 120,
+ "total_output_tokens": 80,
+ "avg_input_tokens": 0,
+ "avg_output_tokens": 0,
+ "avg_total_tokens": 0,
+ },
+ }
+
+ result = counter._merge_metrics(encrypted, thread)
+
+ assert len(result["by_model"]) == 2
+ models = {m["model"] for m in result["by_model"]}
+ assert models == {"gpt-4", "llama3"}
+
+ def test_merge_metrics_sorted_by_tokens(self):
+ """Merged by_model should be sorted by tokens descending."""
+ counter = TokenCounter()
+
+ encrypted = {
+ "total_tokens": 100,
+ "total_researches": 1,
+ "by_model": [
+ {
+ "model": "small-model",
+ "provider": "x",
+ "tokens": 100,
+ "calls": 1,
+ "prompt_tokens": 50,
+ "completion_tokens": 50,
+ }
+ ],
+ "recent_researches": [],
+ "token_breakdown": {
+ "total_input_tokens": 50,
+ "total_output_tokens": 50,
+ },
+ }
+ thread = {
+ "total_tokens": 1000,
+ "total_researches": 1,
+ "by_model": [
+ {
+ "model": "big-model",
+ "provider": "y",
+ "tokens": 1000,
+ "calls": 5,
+ "prompt_tokens": 600,
+ "completion_tokens": 400,
+ }
+ ],
+ "recent_researches": [],
+ "token_breakdown": {
+ "total_input_tokens": 600,
+ "total_output_tokens": 400,
+ },
+ }
+
+ result = counter._merge_metrics(encrypted, thread)
+
+ # Big model should be first (more tokens)
+ assert result["by_model"][0]["model"] == "big-model"
diff --git a/tests/report/test_report_generator_extended.py b/tests/report/test_report_generator_extended.py
new file mode 100644
index 0000000000..d1b087cc13
--- /dev/null
+++ b/tests/report/test_report_generator_extended.py
@@ -0,0 +1,469 @@
+"""Extended tests for report_generator.py - covering factory function,
+structure parsing edge cases, and source section removal."""
+
+from unittest.mock import Mock, patch
+
+
+class TestGetReportGenerator:
+ """Tests for get_report_generator factory function."""
+
+ def test_returns_integrated_report_generator(self):
+ """get_report_generator should return IntegratedReportGenerator."""
+ from local_deep_research.report_generator import (
+ get_report_generator,
+ IntegratedReportGenerator,
+ )
+
+ mock_search_system = Mock()
+ mock_search_system.model = Mock()
+
+ result = get_report_generator(search_system=mock_search_system)
+
+ assert isinstance(result, IntegratedReportGenerator)
+
+ def test_passes_search_system_through(self):
+ """get_report_generator should pass search_system to constructor."""
+ from local_deep_research.report_generator import get_report_generator
+
+ mock_search_system = Mock()
+ mock_search_system.model = Mock()
+
+ result = get_report_generator(search_system=mock_search_system)
+
+ assert result.search_system is mock_search_system
+
+ def test_none_search_system_uses_fallback(self):
+ """get_report_generator with None should use fallback initialization."""
+ from local_deep_research.report_generator import get_report_generator
+
+ with patch(
+ "local_deep_research.report_generator.get_llm"
+ ) as mock_get_llm:
+ mock_llm = Mock()
+ mock_get_llm.return_value = mock_llm
+
+ with patch(
+ "local_deep_research.report_generator.AdvancedSearchSystem"
+ ) as mock_system_cls:
+ mock_system_cls.return_value = Mock()
+ result = get_report_generator(search_system=None)
+
+ assert result is not None
+
+
+class TestDetermineReportStructureParsing:
+ """Tests for structure parsing in _determine_report_structure."""
+
+ def _create_generator(self, llm_response):
+ """Helper to create a generator with mocked LLM."""
+ from local_deep_research.report_generator import (
+ IntegratedReportGenerator,
+ )
+
+ mock_llm = Mock()
+ mock_llm.invoke.return_value = Mock(content=llm_response)
+ mock_search_system = Mock()
+ mock_search_system.model = mock_llm
+
+ gen = IntegratedReportGenerator(search_system=mock_search_system)
+ gen.model = mock_llm
+ return gen
+
+ def test_parses_well_formed_structure(self):
+ """Well-formed STRUCTURE response should be parsed correctly."""
+ llm_response = """
+STRUCTURE
+1. Introduction
+ - Overview | Provide project overview
+ - Background | Historical context
+2. Technical Details
+ - Architecture | System architecture
+END_STRUCTURE
+"""
+ gen = self._create_generator(llm_response)
+ structure = gen._determine_report_structure(
+ {"current_knowledge": "test content"}, "test query"
+ )
+
+ assert len(structure) == 2
+ assert structure[0]["name"] == "Introduction"
+ assert len(structure[0]["subsections"]) == 2
+ assert structure[0]["subsections"][0]["name"] == "Overview"
+ assert (
+ structure[0]["subsections"][0]["purpose"]
+ == "Provide project overview"
+ )
+
+ def test_subsection_without_purpose_gets_default(self):
+ """Subsection without pipe separator should get default purpose."""
+ llm_response = """
+STRUCTURE
+1. Main Section
+ - Subsection Without Purpose
+END_STRUCTURE
+"""
+ gen = self._create_generator(llm_response)
+ structure = gen._determine_report_structure(
+ {"current_knowledge": "test"}, "test query"
+ )
+
+ assert len(structure[0]["subsections"]) == 1
+ assert (
+ "Provide detailed information"
+ in structure[0]["subsections"][0]["purpose"]
+ )
+
+ def test_removes_source_section_at_end(self):
+ """Source-related last section should be removed."""
+ llm_response = """
+STRUCTURE
+1. Content Section
+ - Details | Main details
+2. Sources and References
+ - Bibliography | Citation list
+END_STRUCTURE
+"""
+ gen = self._create_generator(llm_response)
+ structure = gen._determine_report_structure(
+ {"current_knowledge": "test"}, "test query"
+ )
+
+ assert len(structure) == 1
+ assert structure[0]["name"] == "Content Section"
+
+ def test_keeps_source_keyword_in_middle_section(self):
+ """Source keyword in non-last section should be kept."""
+ llm_response = """
+STRUCTURE
+1. Open Source Software
+ - Overview | Open source overview
+2. Conclusion
+ - Summary | Final summary
+END_STRUCTURE
+"""
+ gen = self._create_generator(llm_response)
+ structure = gen._determine_report_structure(
+ {"current_knowledge": "test"}, "test query"
+ )
+
+ # "Open Source Software" is not the last section, so it should be kept
+ assert len(structure) == 2
+ assert structure[0]["name"] == "Open Source Software"
+
+ def test_removes_bibliography_section(self):
+ """Bibliography section at end should be removed."""
+ llm_response = """
+STRUCTURE
+1. Analysis
+ - Details | Analysis details
+2. Bibliography
+ - References | All references
+END_STRUCTURE
+"""
+ gen = self._create_generator(llm_response)
+ structure = gen._determine_report_structure(
+ {"current_knowledge": "test"}, "test query"
+ )
+
+ assert len(structure) == 1
+ assert structure[0]["name"] == "Analysis"
+
+ def test_removes_citation_section(self):
+ """Citation section at end should be removed."""
+ llm_response = """
+STRUCTURE
+1. Content
+ - Main | Main content
+2. Citations
+ - List | Citation list
+END_STRUCTURE
+"""
+ gen = self._create_generator(llm_response)
+ structure = gen._determine_report_structure(
+ {"current_knowledge": "test"}, "test query"
+ )
+
+ assert len(structure) == 1
+
+ def test_empty_response_returns_empty_structure(self):
+ """Empty LLM response should return empty structure."""
+ gen = self._create_generator("")
+ structure = gen._determine_report_structure(
+ {"current_knowledge": "test"}, "test query"
+ )
+
+ assert structure == []
+
+ def test_response_without_markers(self):
+ """Response without STRUCTURE/END_STRUCTURE markers should still parse."""
+ llm_response = """
+1. First Section
+ - Sub A | Purpose A
+2. Second Section
+ - Sub B | Purpose B
+"""
+ gen = self._create_generator(llm_response)
+ structure = gen._determine_report_structure(
+ {"current_knowledge": "test"}, "test query"
+ )
+
+ assert len(structure) == 2
+
+ def test_subsection_with_multiple_pipes(self):
+ """Subsection with multiple | characters should only split on first."""
+ llm_response = """
+STRUCTURE
+1. Section
+ - Sub | Purpose with | pipes | in it
+END_STRUCTURE
+"""
+ gen = self._create_generator(llm_response)
+ structure = gen._determine_report_structure(
+ {"current_knowledge": "test"}, "test query"
+ )
+
+ assert structure[0]["subsections"][0]["name"] == "Sub"
+ assert "pipes" in structure[0]["subsections"][0]["purpose"]
+
+ def test_strips_think_tags_from_response(self):
+ """Think tags in LLM response should be stripped."""
+ llm_response = """<think>Let me think about this...</think>
+STRUCTURE
+1. Real Content
+ - Overview | Content overview
+END_STRUCTURE
+"""
+ gen = self._create_generator(llm_response)
+ structure = gen._determine_report_structure(
+ {"current_knowledge": "test"}, "test query"
+ )
+
+ assert len(structure) == 1
+ assert structure[0]["name"] == "Real Content"
+
+
+class TestTruncateAtSentenceBoundary:
+ """Tests for _truncate_at_sentence_boundary."""
+
+ def _create_generator(self):
+ from local_deep_research.report_generator import (
+ IntegratedReportGenerator,
+ )
+
+ mock_search_system = Mock()
+ mock_search_system.model = Mock()
+ return IntegratedReportGenerator(search_system=mock_search_system)
+
+ def test_no_truncation_when_under_limit(self):
+ """Text under the limit should not be truncated."""
+ gen = self._create_generator()
+ text = "Short text."
+ result = gen._truncate_at_sentence_boundary(text, 100)
+ assert result == text
+
+ def test_truncates_at_period(self):
+ """Should truncate at last period before limit."""
+ gen = self._create_generator()
+ text = (
+ "First sentence. Second sentence. Third sentence that is very long."
+ )
+ result = gen._truncate_at_sentence_boundary(text, 35)
+ assert result.startswith("First sentence. Second sentence.")
+ assert "[...truncated]" in result
+
+ def test_truncates_at_exclamation(self):
+ """Should truncate at exclamation mark."""
+ gen = self._create_generator()
+ text = (
+ "Amazing! This is great! But this part is too long for the limit."
+ )
+ result = gen._truncate_at_sentence_boundary(text, 25)
+ assert "!" in result.split("[...truncated]")[0]
+
+ def test_truncates_at_question_mark(self):
+ """Should truncate at question mark."""
+ gen = self._create_generator()
+ text = "What happened? Then more text that goes past the boundary by a lot."
+ result = gen._truncate_at_sentence_boundary(text, 20)
+ assert "?" in result.split("[...truncated]")[0]
+
+ def test_hard_truncation_fallback(self):
+ """Should hard-truncate when no sentence boundary preserves 80%."""
+ gen = self._create_generator()
+ text = "A" * 100 # No sentence boundaries
+ result = gen._truncate_at_sentence_boundary(text, 50)
+ assert len(result.split("\n")[0]) == 50
+ assert "[...truncated]" in result
+
+
+class TestBuildPreviousContext:
+ """Tests for _build_previous_context."""
+
+ def _create_generator(self):
+ from local_deep_research.report_generator import (
+ IntegratedReportGenerator,
+ )
+
+ mock_search_system = Mock()
+ mock_search_system.model = Mock()
+ return IntegratedReportGenerator(search_system=mock_search_system)
+
+ def test_empty_findings_returns_empty(self):
+ """Empty accumulated findings should return empty string."""
+ gen = self._create_generator()
+ result = gen._build_previous_context([])
+ assert result == ""
+
+ def test_limits_to_max_context_sections(self):
+ """Should only include last max_context_sections findings."""
+ gen = self._create_generator()
+ gen.max_context_sections = 2
+
+ findings = [f"Finding {i}" for i in range(5)]
+ result = gen._build_previous_context(findings)
+
+ assert "Finding 3" in result
+ assert "Finding 4" in result
+ assert "Finding 0" not in result
+
+ def test_includes_do_not_repeat_instruction(self):
+ """Context should include DO NOT REPEAT instruction."""
+ gen = self._create_generator()
+ result = gen._build_previous_context(["Some finding"])
+
+ assert "DO NOT REPEAT" in result
+ assert "CRITICAL" in result
+
+ def test_truncation_for_long_context(self):
+ """Very long context should be truncated."""
+ gen = self._create_generator()
+ gen.max_context_chars = 100
+
+ long_finding = "A" * 200
+ result = gen._build_previous_context([long_finding])
+
+ assert "[...truncated]" in result
+
+
+class TestGenerateErrorReport:
+ """Tests for _generate_error_report."""
+
+ def test_error_report_format(self):
+ """Error report should contain query and error message."""
+ from local_deep_research.report_generator import (
+ IntegratedReportGenerator,
+ )
+
+ mock_search_system = Mock()
+ mock_search_system.model = Mock()
+ gen = IntegratedReportGenerator(search_system=mock_search_system)
+
+ result = gen._generate_error_report("test query", "Something failed")
+
+ assert "test query" in result
+ assert "Something failed" in result
+ assert "ERROR REPORT" in result
+
+ def test_error_report_with_special_characters(self):
+ """Error report should handle special characters."""
+ from local_deep_research.report_generator import (
+ IntegratedReportGenerator,
+ )
+
+ mock_search_system = Mock()
+ mock_search_system.model = Mock()
+ gen = IntegratedReportGenerator(search_system=mock_search_system)
+
+ result = gen._generate_error_report(
+ "query with <html> & special chars", "Error: 'unexpected' \"token\""
+ )
+
+ assert "<html>" in result
+ assert "unexpected" in result
+
+
+class TestIntegratedReportGeneratorInit:
+ """Tests for constructor edge cases."""
+
+ def test_init_with_llm_only(self):
+ """Constructor with only LLM should create search system."""
+ from local_deep_research.report_generator import (
+ IntegratedReportGenerator,
+ )
+
+ mock_llm = Mock()
+
+ with patch(
+ "local_deep_research.report_generator.AdvancedSearchSystem"
+ ) as mock_system_cls:
+ mock_system_cls.return_value = Mock()
+ gen = IntegratedReportGenerator(llm=mock_llm)
+
+ assert gen.model is mock_llm
+ mock_system_cls.assert_called_once()
+
+ def test_init_with_search_system_uses_system_llm(self):
+ """Constructor with search_system should use system's LLM."""
+ from local_deep_research.report_generator import (
+ IntegratedReportGenerator,
+ )
+
+ mock_llm = Mock()
+ mock_search_system = Mock()
+ mock_search_system.model = mock_llm
+
+ gen = IntegratedReportGenerator(search_system=mock_search_system)
+
+ assert gen.model is mock_llm
+
+ def test_init_with_custom_searches_per_section(self):
+ """Custom searches_per_section should be stored."""
+ from local_deep_research.report_generator import (
+ IntegratedReportGenerator,
+ )
+
+ mock_search_system = Mock()
+ mock_search_system.model = Mock()
+
+ gen = IntegratedReportGenerator(
+ search_system=mock_search_system,
+ searches_per_section=5,
+ )
+
+ assert gen.searches_per_section == 5
+
+ def test_context_settings_from_snapshot(self):
+ """Settings snapshot should override default context settings."""
+ from local_deep_research.report_generator import (
+ IntegratedReportGenerator,
+ )
+
+ mock_search_system = Mock()
+ mock_search_system.model = Mock()
+
+ settings = {
+ "report.max_context_sections": 5,
+ "report.max_context_chars": 8000,
+ }
+
+ gen = IntegratedReportGenerator(
+ search_system=mock_search_system,
+ settings_snapshot=settings,
+ )
+
+ assert gen.max_context_sections == 5
+ assert gen.max_context_chars == 8000
+
+ def test_default_context_settings(self):
+ """Without settings snapshot, defaults should be used."""
+ from local_deep_research.report_generator import (
+ IntegratedReportGenerator,
+ )
+
+ mock_search_system = Mock()
+ mock_search_system.model = Mock()
+
+ gen = IntegratedReportGenerator(search_system=mock_search_system)
+
+ assert gen.max_context_sections == 3
+ assert gen.max_context_chars == 4000
diff --git a/tests/utilities/test_url_utils_extended.py b/tests/utilities/test_url_utils_extended.py
new file mode 100644
index 0000000000..b5553504d7
--- /dev/null
+++ b/tests/utilities/test_url_utils_extended.py
@@ -0,0 +1,126 @@
+"""Extended tests for url_utils.py - covering IPv6, fragments, and edge cases."""
+
+import pytest
+from unittest.mock import patch
+
+
+class TestNormalizeUrlIPv6:
+ """Tests for IPv6 address handling in normalize_url."""
+
+ def test_ipv6_loopback_gets_http(self):
+ """IPv6 loopback [::1] should get http:// scheme."""
+ from local_deep_research.utilities.url_utils import normalize_url
+
+ with patch(
+ "local_deep_research.utilities.url_utils.is_private_ip",
+ return_value=True,
+ ):
+ result = normalize_url("[::1]:8080")
+ assert result == "http://[::1]:8080"
+
+ def test_ipv6_address_with_brackets(self):
+ """IPv6 address with brackets should be handled correctly."""
+ from local_deep_research.utilities.url_utils import normalize_url
+
+ with patch(
+ "local_deep_research.utilities.url_utils.is_private_ip",
+ return_value=False,
+ ):
+ result = normalize_url("[2001:db8::1]:443")
+ assert result == "https://[2001:db8::1]:443"
+
+ def test_ipv6_address_already_has_scheme(self):
+ """IPv6 URL with existing scheme should be returned unchanged."""
+ from local_deep_research.utilities.url_utils import normalize_url
+
+ result = normalize_url("http://[::1]:11434")
+ assert result == "http://[::1]:11434"
+
+
+class TestNormalizeUrlFragments:
+ """Tests for URL fragment/anchor handling."""
+
+ def test_preserves_fragment(self):
+ """URL with # fragment should be preserved."""
+ from local_deep_research.utilities.url_utils import normalize_url
+
+ result = normalize_url("http://example.com/page#section")
+ assert result == "http://example.com/page#section"
+
+ def test_preserves_query_and_fragment(self):
+ """URL with both query string and fragment should be preserved."""
+ from local_deep_research.utilities.url_utils import normalize_url
+
+ result = normalize_url("http://example.com/page?q=test#section")
+ assert result == "http://example.com/page?q=test#section"
+
+
+class TestNormalizeUrlEdgeCases:
+ """Additional edge cases for normalize_url."""
+
+ def test_url_with_path_and_no_scheme(self):
+ """URL with path but no scheme should get appropriate scheme."""
+ from local_deep_research.utilities.url_utils import normalize_url
+
+ with patch(
+ "local_deep_research.utilities.url_utils.is_private_ip",
+ return_value=False,
+ ):
+ result = normalize_url("example.com/api/v1/search")
+ assert result == "https://example.com/api/v1/search"
+
+ def test_url_with_encoded_characters(self):
+ """URL with percent-encoded characters should be preserved."""
+ from local_deep_research.utilities.url_utils import normalize_url
+
+ result = normalize_url("http://example.com/path%20with%20spaces")
+ assert result == "http://example.com/path%20with%20spaces"
+
+ def test_none_url_raises_error(self):
+ """None URL should raise a TypeError or ValueError."""
+ from local_deep_research.utilities.url_utils import normalize_url
+
+ with pytest.raises((ValueError, TypeError)):
+ normalize_url(None)
+
+ def test_whitespace_only_url_raises_error(self):
+ """Whitespace-only URL should raise ValueError after strip."""
+ from local_deep_research.utilities.url_utils import normalize_url
+
+ # After stripping whitespace, the URL becomes empty which should raise
+ # However, the function may handle this differently
+ try:
+ result = normalize_url(" ")
+ # If it doesn't raise, it should at least produce some output
+ assert isinstance(result, str)
+ except (ValueError, TypeError):
+ pass # Expected behavior
+
+ def test_url_with_port_no_scheme_external(self):
+ """External hostname with port and no scheme should get https."""
+ from local_deep_research.utilities.url_utils import normalize_url
+
+ with patch(
+ "local_deep_research.utilities.url_utils.is_private_ip",
+ return_value=False,
+ ):
+ result = normalize_url("api.example.com:8443")
+ assert result == "https://api.example.com:8443"
+
+ def test_double_slash_with_private_ip(self):
+ """// prefix with private IP should resolve to http."""
+ from local_deep_research.utilities.url_utils import normalize_url
+
+ with patch(
+ "local_deep_research.utilities.url_utils.is_private_ip",
+ return_value=True,
+ ):
+ result = normalize_url("//192.168.1.1:8080")
+ assert result == "http://192.168.1.1:8080"
+
+ def test_url_with_userinfo(self):
+ """URL with user info (user:pass@host) should be preserved."""
+ from local_deep_research.utilities.url_utils import normalize_url
+
+ result = normalize_url("http://user:[email protected]:8080/path")
+ assert result == "http://user:[email protected]:8080/path"