Skip to content

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

Add comprehensive tests for followup_research and API modules

LearningCircuitfa4d46d859e4
diff --git a/tests/api/__init__.py b/tests/api/__init__.py
new file mode 100644
index 0000000000..e920e9886b
--- /dev/null
+++ b/tests/api/__init__.py
@@ -0,0 +1 @@
+"""Tests for the programmatic API module."""
diff --git a/tests/api/test_settings_utils.py b/tests/api/test_settings_utils.py
new file mode 100644
index 0000000000..9b629c589b
--- /dev/null
+++ b/tests/api/test_settings_utils.py
@@ -0,0 +1,475 @@
+"""
+Tests for the API settings utilities.
+
+Tests cover:
+- InMemorySettingsManager class
+- get_default_settings_snapshot function
+- create_settings_snapshot function
+- extract_setting_value function
+"""
+
+
+class TestInMemorySettingsManager:
+ """Tests for InMemorySettingsManager class."""
+
+ def test_init_creates_empty_settings(self):
+ """InMemorySettingsManager initializes with settings."""
+ from src.local_deep_research.api.settings_utils import (
+ InMemorySettingsManager,
+ )
+
+ manager = InMemorySettingsManager()
+
+ # Should have loaded default settings
+ assert hasattr(manager, "_settings")
+ assert isinstance(manager._settings, dict)
+
+ def test_get_setting_returns_value(self):
+ """get_setting returns the setting value."""
+ from src.local_deep_research.api.settings_utils import (
+ InMemorySettingsManager,
+ )
+
+ manager = InMemorySettingsManager()
+
+ # Should have some default settings
+ settings = manager.get_all_settings()
+ if settings:
+ first_key = list(settings.keys())[0]
+ result = manager.get_setting(first_key)
+ assert result is not None
+
+ def test_get_setting_returns_default_for_unknown_key(self):
+ """get_setting returns default for unknown key."""
+ from src.local_deep_research.api.settings_utils import (
+ InMemorySettingsManager,
+ )
+
+ manager = InMemorySettingsManager()
+
+ result = manager.get_setting("nonexistent.key", default="default_value")
+
+ assert result == "default_value"
+
+ def test_set_setting_updates_value(self):
+ """set_setting updates the setting value."""
+ from src.local_deep_research.api.settings_utils import (
+ InMemorySettingsManager,
+ )
+
+ manager = InMemorySettingsManager()
+
+ # Get an existing key
+ settings = manager.get_all_settings()
+ if settings:
+ first_key = list(settings.keys())[0]
+
+ # Set a new value
+ result = manager.set_setting(first_key, "new_value")
+
+ assert result is True
+
+ def test_set_setting_returns_false_for_unknown_key(self):
+ """set_setting returns False for unknown key."""
+ from src.local_deep_research.api.settings_utils import (
+ InMemorySettingsManager,
+ )
+
+ manager = InMemorySettingsManager()
+
+ result = manager.set_setting("nonexistent.key", "value")
+
+ assert result is False
+
+ def test_get_all_settings_returns_dict(self):
+ """get_all_settings returns a dictionary."""
+ from src.local_deep_research.api.settings_utils import (
+ InMemorySettingsManager,
+ )
+
+ manager = InMemorySettingsManager()
+
+ result = manager.get_all_settings()
+
+ assert isinstance(result, dict)
+
+ def test_get_all_settings_returns_copy(self):
+ """get_all_settings returns a deep copy."""
+ from src.local_deep_research.api.settings_utils import (
+ InMemorySettingsManager,
+ )
+
+ manager = InMemorySettingsManager()
+
+ result1 = manager.get_all_settings()
+ result2 = manager.get_all_settings()
+
+ # Modifying one should not affect the other
+ if result1:
+ first_key = list(result1.keys())[0]
+ result1[first_key] = "modified"
+ assert result2[first_key] != "modified"
+
+ def test_delete_setting_removes_key(self):
+ """delete_setting removes the setting."""
+ from src.local_deep_research.api.settings_utils import (
+ InMemorySettingsManager,
+ )
+
+ manager = InMemorySettingsManager()
+
+ settings = manager.get_all_settings()
+ if settings:
+ first_key = list(settings.keys())[0]
+ result = manager.delete_setting(first_key)
+
+ assert result is True
+ assert manager.get_setting(first_key) is None
+
+ def test_delete_setting_returns_false_for_unknown_key(self):
+ """delete_setting returns False for unknown key."""
+ from src.local_deep_research.api.settings_utils import (
+ InMemorySettingsManager,
+ )
+
+ manager = InMemorySettingsManager()
+
+ result = manager.delete_setting("nonexistent.key")
+
+ assert result is False
+
+ def test_create_or_update_setting_with_dict(self):
+ """create_or_update_setting handles dict with key."""
+ from src.local_deep_research.api.settings_utils import (
+ InMemorySettingsManager,
+ )
+
+ manager = InMemorySettingsManager()
+
+ setting = {
+ "key": "test.setting",
+ "value": "test_value",
+ "ui_element": "text",
+ }
+
+ result = manager.create_or_update_setting(setting)
+
+ assert result is not None
+ assert manager.get_setting("test.setting") == "test_value"
+
+ def test_create_or_update_setting_returns_none_for_invalid(self):
+ """create_or_update_setting returns None for invalid input."""
+ from src.local_deep_research.api.settings_utils import (
+ InMemorySettingsManager,
+ )
+
+ manager = InMemorySettingsManager()
+
+ result = manager.create_or_update_setting("not a dict")
+
+ assert result is None
+
+ def test_import_settings_adds_settings(self):
+ """import_settings adds settings from dict."""
+ from src.local_deep_research.api.settings_utils import (
+ InMemorySettingsManager,
+ )
+
+ manager = InMemorySettingsManager()
+
+ settings_data = {
+ "new.setting1": {"value": "value1", "ui_element": "text"},
+ "new.setting2": {"value": 42, "ui_element": "number"},
+ }
+
+ manager.import_settings(settings_data)
+
+ assert manager.get_setting("new.setting1") == "value1"
+ assert manager.get_setting("new.setting2") == 42.0
+
+ def test_import_settings_with_delete_extra(self):
+ """import_settings with delete_extra clears existing."""
+ from src.local_deep_research.api.settings_utils import (
+ InMemorySettingsManager,
+ )
+
+ manager = InMemorySettingsManager()
+
+ settings_data = {
+ "only.setting": {"value": "only", "ui_element": "text"},
+ }
+
+ manager.import_settings(settings_data, delete_extra=True)
+
+ # Should only have the imported setting
+ assert len(manager.get_all_settings()) == 1
+
+ def test_get_typed_value_checkbox_string(self):
+ """_get_typed_value handles checkbox with string value."""
+ from src.local_deep_research.api.settings_utils import (
+ InMemorySettingsManager,
+ )
+
+ manager = InMemorySettingsManager()
+
+ setting_data = {"ui_element": "checkbox"}
+
+ assert manager._get_typed_value(setting_data, "true") is True
+ assert manager._get_typed_value(setting_data, "false") is False
+ assert manager._get_typed_value(setting_data, "1") is True
+ assert manager._get_typed_value(setting_data, "0") is False
+ assert manager._get_typed_value(setting_data, "yes") is True
+ assert manager._get_typed_value(setting_data, "no") is False
+
+ def test_get_typed_value_number(self):
+ """_get_typed_value handles number type."""
+ from src.local_deep_research.api.settings_utils import (
+ InMemorySettingsManager,
+ )
+
+ manager = InMemorySettingsManager()
+
+ setting_data = {"ui_element": "number"}
+
+ result = manager._get_typed_value(setting_data, "42")
+
+ assert result == 42.0
+ assert isinstance(result, float)
+
+
+class TestGetDefaultSettingsSnapshot:
+ """Tests for get_default_settings_snapshot function."""
+
+ def test_returns_dict(self):
+ """get_default_settings_snapshot returns a dictionary."""
+ from src.local_deep_research.api.settings_utils import (
+ get_default_settings_snapshot,
+ )
+
+ result = get_default_settings_snapshot()
+
+ assert isinstance(result, dict)
+
+ def test_contains_settings(self):
+ """get_default_settings_snapshot returns populated settings."""
+ from src.local_deep_research.api.settings_utils import (
+ get_default_settings_snapshot,
+ )
+
+ result = get_default_settings_snapshot()
+
+ # Should have some settings
+ assert len(result) > 0
+
+
+class TestCreateSettingsSnapshot:
+ """Tests for create_settings_snapshot function."""
+
+ def test_returns_dict(self):
+ """create_settings_snapshot returns a dictionary."""
+ from src.local_deep_research.api.settings_utils import (
+ create_settings_snapshot,
+ )
+
+ result = create_settings_snapshot()
+
+ assert isinstance(result, dict)
+
+ def test_applies_overrides(self):
+ """create_settings_snapshot applies overrides."""
+ from src.local_deep_research.api.settings_utils import (
+ create_settings_snapshot,
+ )
+
+ result = create_settings_snapshot(
+ overrides={"llm.provider": "test_provider"}
+ )
+
+ assert result["llm.provider"]["value"] == "test_provider"
+
+ def test_creates_new_settings_for_unknown_keys(self):
+ """create_settings_snapshot creates entries for unknown keys."""
+ from src.local_deep_research.api.settings_utils import (
+ create_settings_snapshot,
+ )
+
+ result = create_settings_snapshot(
+ overrides={"custom.new.setting": "custom_value"}
+ )
+
+ assert "custom.new.setting" in result
+ assert result["custom.new.setting"]["value"] == "custom_value"
+
+ def test_provider_kwarg(self):
+ """create_settings_snapshot handles provider kwarg."""
+ from src.local_deep_research.api.settings_utils import (
+ create_settings_snapshot,
+ )
+
+ result = create_settings_snapshot(provider="openai")
+
+ assert result["llm.provider"]["value"] == "openai"
+
+ def test_provider_and_api_key_kwargs(self):
+ """create_settings_snapshot handles provider and api_key kwargs."""
+ from src.local_deep_research.api.settings_utils import (
+ create_settings_snapshot,
+ )
+
+ result = create_settings_snapshot(provider="openai", api_key="test-key")
+
+ assert result["llm.provider"]["value"] == "openai"
+ assert "llm.openai.api_key" in result
+ assert result["llm.openai.api_key"]["value"] == "test-key"
+
+ def test_temperature_kwarg(self):
+ """create_settings_snapshot handles temperature kwarg."""
+ from src.local_deep_research.api.settings_utils import (
+ create_settings_snapshot,
+ )
+
+ result = create_settings_snapshot(temperature=0.5)
+
+ assert result["llm.temperature"]["value"] == 0.5
+
+ def test_max_search_results_kwarg(self):
+ """create_settings_snapshot handles max_search_results kwarg."""
+ from src.local_deep_research.api.settings_utils import (
+ create_settings_snapshot,
+ )
+
+ result = create_settings_snapshot(max_search_results=20)
+
+ assert result["search.max_results"]["value"] == 20
+
+ def test_custom_base_settings(self):
+ """create_settings_snapshot uses custom base settings."""
+ from src.local_deep_research.api.settings_utils import (
+ create_settings_snapshot,
+ )
+
+ base = {
+ "custom.setting": {"value": "base_value", "ui_element": "text"},
+ }
+
+ result = create_settings_snapshot(base_settings=base)
+
+ assert "custom.setting" in result
+ assert result["custom.setting"]["value"] == "base_value"
+
+ def test_overrides_on_custom_base(self):
+ """create_settings_snapshot applies overrides to custom base."""
+ from src.local_deep_research.api.settings_utils import (
+ create_settings_snapshot,
+ )
+
+ base = {
+ "custom.setting": {"value": "original", "ui_element": "text"},
+ }
+
+ result = create_settings_snapshot(
+ overrides={"custom.setting": "modified"},
+ base_settings=base,
+ )
+
+ assert result["custom.setting"]["value"] == "modified"
+
+ def test_infers_ui_element_for_bool(self):
+ """create_settings_snapshot infers checkbox for bool values."""
+ from src.local_deep_research.api.settings_utils import (
+ create_settings_snapshot,
+ )
+
+ result = create_settings_snapshot(overrides={"new.bool.setting": True})
+
+ assert result["new.bool.setting"]["ui_element"] == "checkbox"
+
+ def test_infers_ui_element_for_number(self):
+ """create_settings_snapshot infers number for numeric values."""
+ from src.local_deep_research.api.settings_utils import (
+ create_settings_snapshot,
+ )
+
+ result = create_settings_snapshot(overrides={"new.num.setting": 42})
+
+ assert result["new.num.setting"]["ui_element"] == "number"
+
+ def test_infers_ui_element_for_dict(self):
+ """create_settings_snapshot infers json for dict values."""
+ from src.local_deep_research.api.settings_utils import (
+ create_settings_snapshot,
+ )
+
+ result = create_settings_snapshot(
+ overrides={"new.dict.setting": {"key": "value"}}
+ )
+
+ assert result["new.dict.setting"]["ui_element"] == "json"
+
+
+class TestExtractSettingValue:
+ """Tests for extract_setting_value function."""
+
+ def test_extracts_value_from_dict_with_value_key(self):
+ """extract_setting_value extracts value from dict with 'value' key."""
+ from src.local_deep_research.api.settings_utils import (
+ extract_setting_value,
+ )
+
+ settings = {
+ "test.setting": {"value": "extracted_value", "ui_element": "text"},
+ }
+
+ result = extract_setting_value(settings, "test.setting")
+
+ assert result == "extracted_value"
+
+ def test_extracts_raw_value_from_simple_dict(self):
+ """extract_setting_value returns raw value if not nested."""
+ from src.local_deep_research.api.settings_utils import (
+ extract_setting_value,
+ )
+
+ settings = {
+ "test.setting": "simple_value",
+ }
+
+ result = extract_setting_value(settings, "test.setting")
+
+ assert result == "simple_value"
+
+ def test_returns_default_for_unknown_key(self):
+ """extract_setting_value returns default for unknown key."""
+ from src.local_deep_research.api.settings_utils import (
+ extract_setting_value,
+ )
+
+ settings = {"other.setting": {"value": "other"}}
+
+ result = extract_setting_value(
+ settings, "unknown.key", default="default"
+ )
+
+ assert result == "default"
+
+ def test_returns_default_for_none_snapshot(self):
+ """extract_setting_value returns default for None snapshot."""
+ from src.local_deep_research.api.settings_utils import (
+ extract_setting_value,
+ )
+
+ result = extract_setting_value(None, "any.key", default="default")
+
+ assert result == "default"
+
+ def test_returns_none_default_when_not_specified(self):
+ """extract_setting_value returns None when no default specified."""
+ from src.local_deep_research.api.settings_utils import (
+ extract_setting_value,
+ )
+
+ settings = {}
+
+ result = extract_setting_value(settings, "unknown.key")
+
+ assert result is None
diff --git a/tests/followup_research/__init__.py b/tests/followup_research/__init__.py
new file mode 100644
index 0000000000..b3952cab50
--- /dev/null
+++ b/tests/followup_research/__init__.py
@@ -0,0 +1 @@
+"""Tests for follow-up research functionality."""
diff --git a/tests/followup_research/test_models.py b/tests/followup_research/test_models.py
new file mode 100644
index 0000000000..bbe6f76d90
--- /dev/null
+++ b/tests/followup_research/test_models.py
@@ -0,0 +1,248 @@
+"""
+Tests for the follow-up research models.
+
+Tests cover:
+- FollowUpRequest initialization and defaults
+- FollowUpResponse initialization
+- to_dict serialization methods
+"""
+
+
+class TestFollowUpRequest:
+ """Tests for FollowUpRequest dataclass."""
+
+ def test_init_with_required_fields(self):
+ """FollowUpRequest initializes with required fields."""
+ from src.local_deep_research.followup_research.models import (
+ FollowUpRequest,
+ )
+
+ request = FollowUpRequest(
+ parent_research_id="test-id-123",
+ question="What is the follow-up question?",
+ )
+
+ assert request.parent_research_id == "test-id-123"
+ assert request.question == "What is the follow-up question?"
+
+ def test_init_default_strategy(self):
+ """FollowUpRequest has default strategy."""
+ from src.local_deep_research.followup_research.models import (
+ FollowUpRequest,
+ )
+
+ request = FollowUpRequest(
+ parent_research_id="test-id",
+ question="Question?",
+ )
+
+ assert request.strategy == "source-based"
+
+ def test_init_default_max_iterations(self):
+ """FollowUpRequest has default max_iterations."""
+ from src.local_deep_research.followup_research.models import (
+ FollowUpRequest,
+ )
+
+ request = FollowUpRequest(
+ parent_research_id="test-id",
+ question="Question?",
+ )
+
+ assert request.max_iterations == 1
+
+ def test_init_default_questions_per_iteration(self):
+ """FollowUpRequest has default questions_per_iteration."""
+ from src.local_deep_research.followup_research.models import (
+ FollowUpRequest,
+ )
+
+ request = FollowUpRequest(
+ parent_research_id="test-id",
+ question="Question?",
+ )
+
+ assert request.questions_per_iteration == 3
+
+ def test_init_custom_values(self):
+ """FollowUpRequest accepts custom values."""
+ from src.local_deep_research.followup_research.models import (
+ FollowUpRequest,
+ )
+
+ request = FollowUpRequest(
+ parent_research_id="custom-id",
+ question="Custom question?",
+ strategy="adaptive",
+ max_iterations=5,
+ questions_per_iteration=10,
+ )
+
+ assert request.parent_research_id == "custom-id"
+ assert request.question == "Custom question?"
+ assert request.strategy == "adaptive"
+ assert request.max_iterations == 5
+ assert request.questions_per_iteration == 10
+
+ def test_to_dict_contains_all_fields(self):
+ """to_dict returns dictionary with all fields."""
+ from src.local_deep_research.followup_research.models import (
+ FollowUpRequest,
+ )
+
+ request = FollowUpRequest(
+ parent_research_id="test-id",
+ question="Test question",
+ strategy="test-strategy",
+ max_iterations=3,
+ questions_per_iteration=5,
+ )
+
+ result = request.to_dict()
+
+ assert result["parent_research_id"] == "test-id"
+ assert result["question"] == "Test question"
+ assert result["strategy"] == "test-strategy"
+ assert result["max_iterations"] == 3
+ assert result["questions_per_iteration"] == 5
+
+ def test_to_dict_returns_dict_type(self):
+ """to_dict returns a dictionary."""
+ from src.local_deep_research.followup_research.models import (
+ FollowUpRequest,
+ )
+
+ request = FollowUpRequest(
+ parent_research_id="test-id",
+ question="Question?",
+ )
+
+ result = request.to_dict()
+
+ assert isinstance(result, dict)
+
+
+class TestFollowUpResponse:
+ """Tests for FollowUpResponse dataclass."""
+
+ def test_init_with_all_fields(self):
+ """FollowUpResponse initializes with all fields."""
+ from src.local_deep_research.followup_research.models import (
+ FollowUpResponse,
+ )
+
+ sources = [
+ {"title": "Source 1", "url": "https://example.com/1"},
+ {"title": "Source 2", "url": "https://example.com/2"},
+ ]
+
+ response = FollowUpResponse(
+ research_id="response-123",
+ question="What is the answer?",
+ answer="The answer is 42.",
+ sources_used=sources,
+ parent_context_used=True,
+ reused_links_count=5,
+ new_links_count=3,
+ )
+
+ assert response.research_id == "response-123"
+ assert response.question == "What is the answer?"
+ assert response.answer == "The answer is 42."
+ assert response.sources_used == sources
+ assert response.parent_context_used is True
+ assert response.reused_links_count == 5
+ assert response.new_links_count == 3
+
+ def test_init_empty_sources(self):
+ """FollowUpResponse handles empty sources list."""
+ from src.local_deep_research.followup_research.models import (
+ FollowUpResponse,
+ )
+
+ response = FollowUpResponse(
+ research_id="test-id",
+ question="Question?",
+ answer="Answer",
+ sources_used=[],
+ parent_context_used=False,
+ reused_links_count=0,
+ new_links_count=0,
+ )
+
+ assert response.sources_used == []
+
+ def test_to_dict_contains_all_fields(self):
+ """to_dict returns dictionary with all fields."""
+ from src.local_deep_research.followup_research.models import (
+ FollowUpResponse,
+ )
+
+ sources = [{"title": "Test", "url": "https://test.com"}]
+
+ response = FollowUpResponse(
+ research_id="test-id",
+ question="Test question",
+ answer="Test answer",
+ sources_used=sources,
+ parent_context_used=True,
+ reused_links_count=2,
+ new_links_count=1,
+ )
+
+ result = response.to_dict()
+
+ assert result["research_id"] == "test-id"
+ assert result["question"] == "Test question"
+ assert result["answer"] == "Test answer"
+ assert result["sources_used"] == sources
+ assert result["parent_context_used"] is True
+ assert result["reused_links_count"] == 2
+ assert result["new_links_count"] == 1
+
+ def test_to_dict_returns_dict_type(self):
+ """to_dict returns a dictionary."""
+ from src.local_deep_research.followup_research.models import (
+ FollowUpResponse,
+ )
+
+ response = FollowUpResponse(
+ research_id="id",
+ question="q",
+ answer="a",
+ sources_used=[],
+ parent_context_used=False,
+ reused_links_count=0,
+ new_links_count=0,
+ )
+
+ result = response.to_dict()
+
+ assert isinstance(result, dict)
+
+ def test_to_dict_preserves_sources_structure(self):
+ """to_dict preserves the structure of sources_used."""
+ from src.local_deep_research.followup_research.models import (
+ FollowUpResponse,
+ )
+
+ sources = [
+ {"title": "Source A", "url": "https://a.com", "snippet": "Text A"},
+ {"title": "Source B", "url": "https://b.com", "snippet": "Text B"},
+ ]
+
+ response = FollowUpResponse(
+ research_id="id",
+ question="q",
+ answer="a",
+ sources_used=sources,
+ parent_context_used=True,
+ reused_links_count=1,
+ new_links_count=1,
+ )
+
+ result = response.to_dict()
+
+ assert len(result["sources_used"]) == 2
+ assert result["sources_used"][0]["title"] == "Source A"
+ assert result["sources_used"][1]["url"] == "https://b.com"
diff --git a/tests/followup_research/test_service.py b/tests/followup_research/test_service.py
new file mode 100644
index 0000000000..22e18ac16e
--- /dev/null
+++ b/tests/followup_research/test_service.py
@@ -0,0 +1,357 @@
+"""
+Tests for the follow-up research service.
+
+Tests cover:
+- Service initialization
+- Loading parent research
+- Preparing research context
+- Performing follow-up research
+"""
+
+from unittest.mock import Mock, patch, MagicMock
+
+
+class TestFollowUpResearchServiceInit:
+ """Tests for FollowUpResearchService initialization."""
+
+ def test_init_without_username(self):
+ """Service initializes without username."""
+ from src.local_deep_research.followup_research.service import (
+ FollowUpResearchService,
+ )
+
+ service = FollowUpResearchService()
+
+ assert service.username is None
+
+ def test_init_with_username(self):
+ """Service initializes with username."""
+ from src.local_deep_research.followup_research.service import (
+ FollowUpResearchService,
+ )
+
+ service = FollowUpResearchService(username="testuser")
+
+ assert service.username == "testuser"
+
+
+class TestLoadParentResearch:
+ """Tests for load_parent_research method."""
+
+ def test_returns_empty_dict_when_research_not_found(self):
+ """Returns empty dict when parent research not found."""
+ from src.local_deep_research.followup_research.service import (
+ FollowUpResearchService,
+ )
+
+ service = FollowUpResearchService(username="testuser")
+
+ with patch(
+ "src.local_deep_research.followup_research.service.get_user_db_session"
+ ) as mock_session:
+ mock_ctx = MagicMock()
+ mock_session.return_value.__enter__ = Mock(return_value=mock_ctx)
+ mock_session.return_value.__exit__ = Mock(return_value=False)
+
+ mock_query = Mock()
+ mock_query.filter_by.return_value.first.return_value = None
+ mock_ctx.query.return_value = mock_query
+
+ result = service.load_parent_research("nonexistent-id")
+
+ assert result == {}
+
+ def test_returns_parent_data_when_found(self):
+ """Returns parent data when research is found."""
+ from src.local_deep_research.followup_research.service import (
+ FollowUpResearchService,
+ )
+
+ service = FollowUpResearchService(username="testuser")
+
+ mock_research = Mock()
+ mock_research.id = "parent-123"
+ mock_research.query = "Original query"
+ mock_research.report_content = "Research report content"
+ mock_research.research_meta = {
+ "formatted_findings": "Findings text",
+ "strategy_name": "source-based",
+ }
+
+ with patch(
+ "src.local_deep_research.followup_research.service.get_user_db_session"
+ ) as mock_session:
+ mock_ctx = MagicMock()
+ mock_session.return_value.__enter__ = Mock(return_value=mock_ctx)
+ mock_session.return_value.__exit__ = Mock(return_value=False)
+
+ mock_query = Mock()
+ mock_query.filter_by.return_value.first.return_value = mock_research
+ mock_ctx.query.return_value = mock_query
+
+ with patch(
+ "src.local_deep_research.followup_research.service.ResearchSourcesService"
+ ) as mock_sources_svc:
+ mock_svc_instance = Mock()
+ mock_svc_instance.get_research_sources.return_value = [
+ {"url": "https://example.com", "title": "Example"}
+ ]
+ mock_sources_svc.return_value = mock_svc_instance
+
+ result = service.load_parent_research("parent-123")
+
+ assert result["research_id"] == "parent-123"
+ assert result["query"] == "Original query"
+ assert result["report_content"] == "Research report content"
+
+ def test_returns_empty_dict_on_exception(self):
+ """Returns empty dict when exception occurs."""
+ from src.local_deep_research.followup_research.service import (
+ FollowUpResearchService,
+ )
+
+ service = FollowUpResearchService(username="testuser")
+
+ with patch(
+ "src.local_deep_research.followup_research.service.get_user_db_session"
+ ) as mock_session:
+ mock_session.return_value.__enter__ = Mock(
+ side_effect=Exception("DB Error")
+ )
+
+ result = service.load_parent_research("any-id")
+
+ assert result == {}
+
+
+class TestPrepareResearchContext:
+ """Tests for prepare_research_context method."""
+
+ def test_returns_empty_context_when_no_parent_data(self):
+ """Returns empty context when parent data not found."""
+ from src.local_deep_research.followup_research.service import (
+ FollowUpResearchService,
+ )
+
+ service = FollowUpResearchService(username="testuser")
+
+ with patch.object(service, "load_parent_research", return_value={}):
+ result = service.prepare_research_context("nonexistent-id")
+
+ assert result == {}
+
+ def test_returns_context_with_parent_data(self):
+ """Returns context when parent data exists."""
+ from src.local_deep_research.followup_research.service import (
+ FollowUpResearchService,
+ )
+
+ service = FollowUpResearchService(username="testuser")
+
+ parent_data = {
+ "all_links_of_system": [{"url": "https://test.com"}],
+ "formatted_findings": "Test findings",
+ "report_content": "Report content",
+ "resources": [{"url": "https://test.com"}],
+ "query": "Original query",
+ }
+
+ with patch.object(
+ service, "load_parent_research", return_value=parent_data
+ ):
+ result = service.prepare_research_context("parent-123")
+
+ assert result["parent_research_id"] == "parent-123"
+ assert result["past_links"] == [{"url": "https://test.com"}]
+ assert result["past_findings"] == "Test findings"
+ assert result["report_content"] == "Report content"
+ assert result["original_query"] == "Original query"
+
+ def test_context_contains_all_expected_keys(self):
+ """Context contains all expected keys."""
+ from src.local_deep_research.followup_research.service import (
+ FollowUpResearchService,
+ )
+
+ service = FollowUpResearchService(username="testuser")
+
+ parent_data = {
+ "all_links_of_system": [],
+ "formatted_findings": "",
+ "report_content": "",
+ "resources": [],
+ "query": "",
+ }
+
+ with patch.object(
+ service, "load_parent_research", return_value=parent_data
+ ):
+ result = service.prepare_research_context("parent-123")
+
+ expected_keys = [
+ "parent_research_id",
+ "past_links",
+ "past_findings",
+ "report_content",
+ "resources",
+ "all_links_of_system",
+ "original_query",
+ ]
+ for key in expected_keys:
+ assert key in result
+
+
+class TestPerformFollowup:
+ """Tests for perform_followup method."""
+
+ def test_returns_research_params(self):
+ """Returns research parameters for research system."""
+ from src.local_deep_research.followup_research.service import (
+ FollowUpResearchService,
+ )
+ from src.local_deep_research.followup_research.models import (
+ FollowUpRequest,
+ )
+
+ service = FollowUpResearchService(username="testuser")
+
+ request = FollowUpRequest(
+ parent_research_id="parent-123",
+ question="Follow-up question?",
+ strategy="source-based",
+ max_iterations=2,
+ questions_per_iteration=5,
+ )
+
+ mock_context = {
+ "parent_research_id": "parent-123",
+ "past_links": [],
+ "past_findings": "",
+ "report_content": "",
+ "resources": [],
+ "all_links_of_system": [],
+ "original_query": "",
+ }
+
+ with patch.object(
+ service, "prepare_research_context", return_value=mock_context
+ ):
+ result = service.perform_followup(request)
+
+ assert result["query"] == "Follow-up question?"
+ assert result["strategy"] == "contextual-followup"
+ assert result["delegate_strategy"] == "source-based"
+ assert result["max_iterations"] == 2
+ assert result["questions_per_iteration"] == 5
+ assert result["parent_research_id"] == "parent-123"
+
+ def test_uses_empty_context_when_parent_not_found(self):
+ """Uses empty context when parent research not found."""
+ from src.local_deep_research.followup_research.service import (
+ FollowUpResearchService,
+ )
+ from src.local_deep_research.followup_research.models import (
+ FollowUpRequest,
+ )
+
+ service = FollowUpResearchService(username="testuser")
+
+ request = FollowUpRequest(
+ parent_research_id="nonexistent",
+ question="Question?",
+ )
+
+ with patch.object(service, "prepare_research_context", return_value={}):
+ result = service.perform_followup(request)
+
+ # Should still return valid params with empty context
+ assert result["query"] == "Question?"
+ assert result["strategy"] == "contextual-followup"
+ assert "research_context" in result
+ assert result["research_context"]["past_links"] == []
+
+ def test_includes_research_context(self):
+ """Result includes research_context from parent."""
+ from src.local_deep_research.followup_research.service import (
+ FollowUpResearchService,
+ )
+ from src.local_deep_research.followup_research.models import (
+ FollowUpRequest,
+ )
+
+ service = FollowUpResearchService(username="testuser")
+
+ request = FollowUpRequest(
+ parent_research_id="parent-123",
+ question="Question?",
+ )
+
+ mock_context = {
+ "parent_research_id": "parent-123",
+ "past_links": [{"url": "https://test.com"}],
+ "past_findings": "Findings",
+ "report_content": "Report",
+ "resources": [{"url": "https://test.com"}],
+ "all_links_of_system": [{"url": "https://test.com"}],
+ "original_query": "Original",
+ }
+
+ with patch.object(
+ service, "prepare_research_context", return_value=mock_context
+ ):
+ result = service.perform_followup(request)
+
+ assert result["research_context"] == mock_context
+
+
+class TestFollowUpResearchServiceIntegration:
+ """Integration tests for FollowUpResearchService."""
+
+ def test_full_followup_workflow(self):
+ """Test complete follow-up workflow from request to params."""
+ from src.local_deep_research.followup_research.service import (
+ FollowUpResearchService,
+ )
+ from src.local_deep_research.followup_research.models import (
+ FollowUpRequest,
+ )
+
+ service = FollowUpResearchService(username="testuser")
+
+ request = FollowUpRequest(
+ parent_research_id="parent-id",
+ question="What are the implications?",
+ strategy="adaptive",
+ max_iterations=3,
+ questions_per_iteration=4,
+ )
+
+ # Mock the database/service calls
+ with patch.object(
+ service,
+ "load_parent_research",
+ return_value={
+ "research_id": "parent-id",
+ "query": "Original research topic",
+ "report_content": "Full research report...",
+ "formatted_findings": "Key findings...",
+ "resources": [
+ {"url": "https://source1.com", "title": "Source 1"},
+ {"url": "https://source2.com", "title": "Source 2"},
+ ],
+ "all_links_of_system": [
+ {"url": "https://source1.com"},
+ {"url": "https://source2.com"},
+ ],
+ },
+ ):
+ result = service.perform_followup(request)
+
+ # Verify the complete result
+ assert result["query"] == "What are the implications?"
+ assert result["strategy"] == "contextual-followup"
+ assert result["delegate_strategy"] == "adaptive"
+ assert result["max_iterations"] == 3
+ assert result["questions_per_iteration"] == 4
+ assert result["parent_research_id"] == "parent-id"
+ assert len(result["research_context"]["past_links"]) == 2