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: remove 6 shadow test files in advanced_search_system/strategies (#4120)

LearningCircuit0151f86c2bf6
diff --git a/tests/advanced_search_system/strategies/test_constrained_search_extended.py b/tests/advanced_search_system/strategies/test_constrained_search_extended.py
deleted file mode 100644
index bc7aeed3f7..0000000000
--- a/tests/advanced_search_system/strategies/test_constrained_search_extended.py
+++ /dev/null
@@ -1,594 +0,0 @@
-"""
-Tests for constrained search strategy extended functionality.
-
-Tests cover:
-- Constraint parsing and application
-- Domain and date filtering
-- Boolean operators
-- Constraint relaxation
-"""
-
-from unittest.mock import Mock
-from datetime import datetime
-
-
-class TestConstraintParsing:
- """Tests for constraint parsing."""
-
- def test_constraint_parsing(self):
- """Constraints are parsed from query."""
- query = "climate change site:nature.com after:2023"
-
- constraints = {}
- parts = query.split()
-
- for part in parts:
- if part.startswith("site:"):
- constraints["domain"] = part.split(":")[1]
- elif part.startswith("after:"):
- constraints["after"] = part.split(":")[1]
-
- assert constraints["domain"] == "nature.com"
- assert constraints["after"] == "2023"
-
- def test_constraint_parsing_multiple(self):
- """Multiple constraints are parsed."""
- query = "AI research site:arxiv.org filetype:pdf language:en"
-
- constraints = {}
- for part in query.split():
- if ":" in part:
- key, value = part.split(":", 1)
- constraints[key] = value
-
- assert len(constraints) == 3
-
- def test_constraint_parsing_quoted_values(self):
- """Quoted constraint values are preserved."""
- # Simulate parsing quoted value
- constraint = 'author:"John Smith"'
-
- key, value = constraint.split(":", 1)
- value = value.strip('"')
-
- assert value == "John Smith"
-
- def test_constraint_parsing_empty_value(self):
- """Empty constraint values are handled."""
- constraint = "site:"
-
- if ":" in constraint:
- key, value = constraint.split(":", 1)
- if not value:
- value = None
-
- assert value is None
-
-
-class TestConstraintApplication:
- """Tests for constraint application."""
-
- def test_constraint_application(self):
- """Constraints are applied to results."""
- results = [
- {"url": "https://nature.com/article1", "domain": "nature.com"},
- {"url": "https://example.com/article2", "domain": "example.com"},
- {"url": "https://nature.com/article3", "domain": "nature.com"},
- ]
-
- constraint = {"domain": "nature.com"}
-
- filtered = [r for r in results if r["domain"] == constraint["domain"]]
-
- assert len(filtered) == 2
-
- def test_constraint_application_no_matches(self):
- """No matches returns empty results."""
- results = [
- {"domain": "example.com"},
- {"domain": "test.com"},
- ]
-
- constraint = {"domain": "nonexistent.com"}
-
- filtered = [r for r in results if r["domain"] == constraint["domain"]]
-
- assert len(filtered) == 0
-
-
-class TestDomainFiltering:
- """Tests for domain filtering constraints."""
-
- def test_constraint_domain_filtering(self):
- """Domain constraint filters results."""
- allowed_domains = ["nature.com", "science.org"]
- results = [
- {"url": "https://nature.com/a"},
- {"url": "https://random.com/b"},
- {"url": "https://science.org/c"},
- ]
-
- filtered = [
- r for r in results if any(d in r["url"] for d in allowed_domains)
- ]
-
- assert len(filtered) == 2
-
- def test_constraint_domain_exclusion(self):
- """Excluded domains are filtered out."""
- excluded_domains = ["spam.com", "ads.net"]
- results = [
- {"url": "https://nature.com/a", "domain": "nature.com"},
- {"url": "https://spam.com/b", "domain": "spam.com"},
- ]
-
- filtered = [r for r in results if r["domain"] not in excluded_domains]
-
- assert len(filtered) == 1
-
- def test_constraint_domain_subdomain_handling(self):
- """Subdomains are handled correctly."""
- domain = "nature.com"
- urls = [
- "https://www.nature.com/article",
- "https://api.nature.com/data",
- "https://nature.com/main",
- ]
-
- matching = [u for u in urls if domain in u]
-
- assert len(matching) == 3
-
-
-class TestDateFiltering:
- """Tests for date range filtering."""
-
- def test_constraint_date_range_filtering(self):
- """Date range constraint filters results."""
- after = datetime(2023, 1, 1)
- before = datetime(2024, 1, 1)
-
- results = [
- {"date": datetime(2022, 6, 1)},
- {"date": datetime(2023, 6, 1)},
- {"date": datetime(2024, 6, 1)},
- ]
-
- filtered = [r for r in results if after <= r["date"] < before]
-
- assert len(filtered) == 1
-
- def test_constraint_date_after_only(self):
- """After date constraint works alone."""
- after = datetime(2023, 1, 1)
-
- results = [
- {"date": datetime(2022, 6, 1)},
- {"date": datetime(2023, 6, 1)},
- ]
-
- filtered = [r for r in results if r["date"] >= after]
-
- assert len(filtered) == 1
-
- def test_constraint_date_before_only(self):
- """Before date constraint works alone."""
- before = datetime(2023, 1, 1)
-
- results = [
- {"date": datetime(2022, 6, 1)},
- {"date": datetime(2023, 6, 1)},
- ]
-
- filtered = [r for r in results if r["date"] < before]
-
- assert len(filtered) == 1
-
-
-class TestSourceTypeFiltering:
- """Tests for source type filtering."""
-
- def test_constraint_source_type_filtering(self):
- """Source type constraint filters results."""
- allowed_types = ["pdf", "html"]
-
- results = [
- {"type": "pdf"},
- {"type": "html"},
- {"type": "video"},
- ]
-
- filtered = [r for r in results if r["type"] in allowed_types]
-
- assert len(filtered) == 2
-
- def test_constraint_filetype_extension(self):
- """Filetype extension is detected."""
- urls = [
- "https://example.com/doc.pdf",
- "https://example.com/page.html",
- "https://example.com/file.docx",
- ]
-
- filetype = "pdf"
- matching = [u for u in urls if u.endswith(f".{filetype}")]
-
- assert len(matching) == 1
-
-
-class TestLanguageFiltering:
- """Tests for language filtering."""
-
- def test_constraint_language_filtering(self):
- """Language constraint filters results."""
- language = "en"
-
- results = [
- {"lang": "en", "title": "English Article"},
- {"lang": "de", "title": "German Article"},
- {"lang": "en", "title": "Another English"},
- ]
-
- filtered = [r for r in results if r["lang"] == language]
-
- assert len(filtered) == 2
-
- def test_constraint_language_detection(self):
- """Language is detected from content."""
- # Simulate language detection
- content = "This is English text"
-
- # Simple heuristic
- if "the" in content.lower() or "is" in content.lower():
- detected_lang = "en"
- else:
- detected_lang = "unknown"
-
- assert detected_lang == "en"
-
-
-class TestBooleanOperators:
- """Tests for boolean operators in constraints."""
-
- def test_constraint_boolean_operators(self):
- """Boolean operators work in queries."""
- query = "climate AND change"
-
- terms = query.split(" AND ")
-
- assert len(terms) == 2
-
- def test_constraint_boolean_or(self):
- """OR operator expands results."""
- query = "global OR climate"
- terms = query.split(" OR ")
-
- results = [
- {"text": "global warming"},
- {"text": "climate change"},
- {"text": "weather patterns"},
- ]
-
- matching = [
- r
- for r in results
- if any(term.lower() in r["text"].lower() for term in terms)
- ]
-
- assert len(matching) == 2
-
- def test_constraint_boolean_not(self):
- """NOT operator excludes results."""
- include_term = "climate"
- exclude_term = "change"
-
- results = [
- {"text": "climate patterns"},
- {"text": "climate change"},
- {"text": "weather change"},
- ]
-
- filtered = [
- r
- for r in results
- if include_term in r["text"] and exclude_term not in r["text"]
- ]
-
- assert len(filtered) == 1
-
-
-class TestNegationHandling:
- """Tests for negation handling."""
-
- def test_constraint_negation_handling(self):
- """Negated constraints exclude results."""
- constraint = "-site:spam.com"
-
- excluded_domain = constraint[1:].split(":")[1]
-
- results = [
- {"domain": "nature.com"},
- {"domain": "spam.com"},
- ]
-
- filtered = [r for r in results if r["domain"] != excluded_domain]
-
- assert len(filtered) == 1
-
- def test_constraint_negation_multiple(self):
- """Multiple negations are applied."""
- excluded = ["spam.com", "ads.net"]
-
- results = [
- {"domain": "nature.com"},
- {"domain": "spam.com"},
- {"domain": "ads.net"},
- ]
-
- filtered = [r for r in results if r["domain"] not in excluded]
-
- assert len(filtered) == 1
-
-
-class TestWildcardMatching:
- """Tests for wildcard matching."""
-
- def test_constraint_wildcard_matching(self):
- """Wildcards match patterns."""
- import re
-
- pattern = "clim*"
- regex = pattern.replace("*", ".*")
-
- texts = ["climate", "climbing", "claim", "weather"]
-
- matching = [t for t in texts if re.match(regex, t)]
-
- # "climate" and "climbing" match "clim*"
- assert len(matching) == 2
-
- def test_constraint_wildcard_suffix(self):
- """Suffix wildcards work."""
- import re
-
- pattern = "*ing"
- regex = pattern.replace("*", ".*")
-
- texts = ["running", "swimming", "run", "swim"]
-
- matching = [t for t in texts if re.match(regex, t)]
-
- assert len(matching) == 2
-
-
-class TestCaseSensitivity:
- """Tests for case sensitivity."""
-
- def test_constraint_case_sensitivity(self):
- """Case sensitivity is configurable."""
- query = "Climate"
- case_sensitive = False
-
- text = "climate change"
-
- if case_sensitive:
- matches = query in text
- else:
- matches = query.lower() in text.lower()
-
- assert matches
-
- def test_constraint_case_insensitive_default(self):
- """Default is case insensitive."""
- query = "CLIMATE"
- text = "climate change"
-
- matches = query.lower() in text.lower()
-
- assert matches
-
-
-class TestConstraintRelaxation:
- """Tests for constraint relaxation."""
-
- def test_constraint_relaxation_strategy(self):
- """Constraints are relaxed when no results."""
- constraints = {
- "domain": "nature.com",
- "after": "2023",
- "filetype": "pdf",
- }
-
- # Relaxation order
-
- # Simulate relaxation
- relaxed = constraints.copy()
- del relaxed["filetype"]
-
- assert "filetype" not in relaxed
- assert "domain" in relaxed
-
- def test_constraint_relaxation_levels(self):
- """Multiple relaxation levels are tried."""
- constraint_levels = [
- {"domain": "nature.com", "after": "2023", "type": "pdf"},
- {"domain": "nature.com", "after": "2023"},
- {"domain": "nature.com"},
- {},
- ]
-
- level = 0
- results = []
-
- while not results and level < len(constraint_levels):
- # Simulate search
- if level >= 2:
- results = [{"result": "found"}]
- level += 1
-
- assert level == 3
- assert len(results) == 1
-
-
-class TestConstraintValidation:
- """Tests for constraint validation."""
-
- def test_constraint_violation_detection(self):
- """Constraint violations are detected."""
- constraint = {"domain": "nature.com"}
- result = {"domain": "example.com"}
-
- violation = result["domain"] != constraint["domain"]
-
- assert violation
-
- def test_constraint_result_validation(self):
- """Results are validated against constraints."""
- constraints = {"min_words": 100}
- result = {"word_count": 50}
-
- valid = result["word_count"] >= constraints["min_words"]
-
- assert not valid
-
-
-class TestLLMQueryRefinement:
- """Tests for LLM-based query refinement."""
-
- def test_constraint_llm_query_refinement(self):
- """LLM refines query with constraints."""
- mock_llm = Mock()
- mock_llm.invoke.return_value = Mock(
- content="climate change research site:arxiv.org after:2023"
- )
-
- original_query = "climate change"
-
- mock_llm.invoke(f"Add constraints to: {original_query}")
-
- assert mock_llm.invoke.called
-
- def test_constraint_llm_error_handling(self):
- """LLM errors use fallback refinement."""
- llm_available = False
-
- if llm_available:
- refined_query = "llm_refined"
- else:
- # Fallback: simple concatenation
- query = "climate change"
- constraints = ["site:nature.com"]
- refined_query = query + " " + " ".join(constraints)
-
- assert "site:nature.com" in refined_query
-
-
-class TestErrorHandling:
- """Tests for constraint error handling."""
-
- def test_constraint_error_handling(self):
- """Errors in constraint processing are handled."""
- errors = []
-
- try:
- constraint = "invalid::constraint"
- parts = constraint.split(":")
- if len(parts) != 2:
- raise ValueError("Invalid constraint format")
- except ValueError as e:
- errors.append(str(e))
-
- assert len(errors) == 1
-
- def test_constraint_invalid_date(self):
- """Invalid dates are handled."""
- date_str = "not-a-date"
-
- try:
- from datetime import datetime
-
- datetime.strptime(date_str, "%Y-%m-%d")
- valid = True
- except ValueError:
- valid = False
-
- assert not valid
-
- def test_constraint_malformed_query(self):
- """Malformed queries are handled."""
- query = "site: filetype:"
-
- constraints = {}
- for part in query.split():
- if ":" in part:
- key, value = part.split(":", 1)
- if value.strip():
- constraints[key] = value
-
- # No valid constraints extracted
- assert len(constraints) == 0
-
-
-class TestExtractConfidenceFromResponse:
- """Tests for confidence extraction from LLM responses (PR #2020).
-
- PR #2020 changed bare `except:` to `except ValueError:` in
- _extract_confidence_from_response of EarlyStopConstrainedStrategy.
- """
-
- def test_extracts_decimal_confidence(self):
- """Should extract decimal confidence from response."""
- import re
-
- response = "Based on the evidence, confidence is 0.85"
- pattern = r"\b0?\.\d+\b|\b1\.0\b|\b1\b"
- matches = re.findall(pattern, response)
-
- assert len(matches) > 0
- confidence = float(matches[-1])
- assert confidence == 0.85
-
- def test_extracts_last_number(self):
- """Should extract the last number found."""
- import re
-
- response = "Score: 0.3 but after further review: 0.7"
- pattern = r"\b0?\.\d+\b|\b1\.0\b|\b1\b"
- matches = re.findall(pattern, response)
-
- confidence = float(matches[-1])
- assert confidence == 0.7
-
- def test_returns_none_for_no_match(self):
- """Should not find matches in text without numbers."""
- import re
-
- response = "I cannot determine a confidence score"
- pattern = r"\b0?\.\d+\b|\b1\.0\b|\b1\b"
- matches = re.findall(pattern, response)
-
- assert len(matches) == 0
-
- def test_handles_perfect_confidence(self):
- """Should handle 1.0 confidence."""
- import re
-
- response = "This is certain: 1.0"
- pattern = r"\b0?\.\d+\b|\b1\.0\b|\b1\b"
- matches = re.findall(pattern, response)
-
- assert len(matches) > 0
- confidence = float(matches[-1])
- assert confidence == 1.0
-
- def test_handles_integer_one(self):
- """Should handle integer 1 as confidence."""
- import re
-
- response = "Confidence: 1"
- pattern = r"\b0?\.\d+\b|\b1\.0\b|\b1\b"
- matches = re.findall(pattern, response)
-
- assert len(matches) > 0
- confidence = float(matches[-1])
- assert confidence == 1.0
diff --git a/tests/advanced_search_system/strategies/test_llm_driven_modular_strategy.py b/tests/advanced_search_system/strategies/test_llm_driven_modular_strategy.py
deleted file mode 100644
index 59ce6407fc..0000000000
--- a/tests/advanced_search_system/strategies/test_llm_driven_modular_strategy.py
+++ /dev/null
@@ -1,674 +0,0 @@
-"""
-Tests for LLM-Driven Modular Strategy
-
-Phase 18: Advanced Search Strategies - Modular Strategy Tests
-Tests modular components and strategy orchestration.
-"""
-
-from unittest.mock import patch, MagicMock
-
-
-class TestModularComponents:
- """Tests for modular component functionality"""
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_module_initialization(self, mock_strategy_cls):
- """Test modules are properly initialized"""
- mock_strategy = MagicMock()
- mock_strategy.modules = {
- "constraint_processor": MagicMock(),
- "rejection_manager": MagicMock(),
- }
-
- assert "constraint_processor" in mock_strategy.modules
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_module_dependency_resolution(self, mock_strategy_cls):
- """Test module dependencies are resolved"""
- mock_strategy = MagicMock()
- mock_strategy._resolve_dependencies.return_value = [
- "module_a",
- "module_b",
- "module_c",
- ]
-
- order = mock_strategy._resolve_dependencies(
- ["module_c", "module_a", "module_b"]
- )
-
- assert len(order) == 3
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_module_execution_order(self, mock_strategy_cls):
- """Test modules execute in correct order"""
- mock_strategy = MagicMock()
- mock_strategy._get_execution_order.return_value = [1, 2, 3, 4, 5, 6, 7]
-
- order = mock_strategy._get_execution_order()
-
- assert order == [1, 2, 3, 4, 5, 6, 7]
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_module_output_passing(self, mock_strategy_cls):
- """Test module outputs are passed between modules"""
- mock_strategy = MagicMock()
- mock_strategy._pass_output.return_value = {"processed_data": "value"}
-
- output = mock_strategy._pass_output("module_a", {"raw_data": "value"})
-
- assert "processed_data" in output
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_module_error_isolation(self, mock_strategy_cls):
- """Test errors in one module don't crash others"""
- mock_strategy = MagicMock()
- mock_strategy._execute_with_isolation.return_value = {
- "success": False,
- "error": "Module failed",
- "fallback_used": True,
- }
-
- result = mock_strategy._execute_with_isolation("failing_module")
-
- assert result["fallback_used"] is True
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_module_retry_logic(self, mock_strategy_cls):
- """Test module retry on failure"""
- mock_strategy = MagicMock()
- mock_strategy._retry_module.return_value = {
- "success": True,
- "retries": 2,
- }
-
- result = mock_strategy._retry_module("flaky_module", max_retries=3)
-
- assert result["success"] is True
- assert result["retries"] <= 3
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_module_timeout_handling(self, mock_strategy_cls):
- """Test module timeout is handled"""
- mock_strategy = MagicMock()
- mock_strategy._execute_with_timeout.return_value = {
- "success": False,
- "error": "Timeout",
- "elapsed_ms": 30000,
- }
-
- result = mock_strategy._execute_with_timeout(
- "slow_module", timeout_ms=30000
- )
-
- assert result["success"] is False
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_module_parallel_execution(self, mock_strategy_cls):
- """Test modules can execute in parallel"""
- mock_strategy = MagicMock()
- mock_strategy._execute_parallel.return_value = {
- "module_a": {"result": "a"},
- "module_b": {"result": "b"},
- }
-
- results = mock_strategy._execute_parallel(["module_a", "module_b"])
-
- assert len(results) == 2
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_module_sequential_execution(self, mock_strategy_cls):
- """Test modules execute sequentially when needed"""
- mock_strategy = MagicMock()
- execution_log = []
-
- def log_execution(module_name):
- execution_log.append(module_name)
- return {"module": module_name}
-
- mock_strategy._execute_sequential.side_effect = lambda modules: [
- log_execution(m) for m in modules
- ]
-
- mock_strategy._execute_sequential(["m1", "m2", "m3"])
-
- assert execution_log == ["m1", "m2", "m3"]
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_module_conditional_execution(self, mock_strategy_cls):
- """Test conditional module execution"""
- mock_strategy = MagicMock()
- mock_strategy._should_execute.return_value = True
-
- should_run = mock_strategy._should_execute(
- "optional_module", {"condition": True}
- )
-
- assert should_run is True
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_module_result_aggregation(self, mock_strategy_cls):
- """Test module results are aggregated"""
- mock_strategy = MagicMock()
- mock_strategy._aggregate_results.return_value = {
- "total_candidates": 15,
- "filtered_candidates": 10,
- "final_candidates": 5,
- }
-
- aggregated = mock_strategy._aggregate_results(
- [{"candidates": 15}, {"filtered": 10}, {"final": 5}]
- )
-
- assert aggregated["total_candidates"] == 15
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_module_state_management(self, mock_strategy_cls):
- """Test module state is managed"""
- mock_strategy = MagicMock()
- mock_strategy.state = {"phase": 1, "candidates": []}
-
- mock_strategy._update_state({"phase": 2})
-
- mock_strategy._update_state.assert_called_once()
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_module_checkpoint_saving(self, mock_strategy_cls):
- """Test checkpoint is saved"""
- mock_strategy = MagicMock()
- mock_strategy._save_checkpoint.return_value = {
- "checkpoint_id": "cp_123"
- }
-
- checkpoint = mock_strategy._save_checkpoint(
- {"phase": 3, "data": "state"}
- )
-
- assert "checkpoint_id" in checkpoint
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_module_checkpoint_restoration(self, mock_strategy_cls):
- """Test checkpoint can be restored"""
- mock_strategy = MagicMock()
- mock_strategy._restore_checkpoint.return_value = {
- "phase": 3,
- "data": "restored",
- }
-
- state = mock_strategy._restore_checkpoint("cp_123")
-
- assert state["phase"] == 3
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_module_progress_reporting(self, mock_strategy_cls):
- """Test progress is reported"""
- mock_strategy = MagicMock()
- mock_callback = MagicMock()
- mock_strategy.progress_callback = mock_callback
-
- mock_strategy._report_progress(50, "Halfway done")
-
- mock_strategy._report_progress.assert_called_once()
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_module_resource_allocation(self, mock_strategy_cls):
- """Test resources are allocated per module"""
- mock_strategy = MagicMock()
- mock_strategy._allocate_resources.return_value = {
- "max_tokens": 1000,
- "timeout_ms": 30000,
- }
-
- resources = mock_strategy._allocate_resources("analysis_module")
-
- assert "max_tokens" in resources
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_module_llm_selection(self, mock_strategy_cls):
- """Test LLM is selected per module"""
- mock_strategy = MagicMock()
- mock_strategy._select_llm.return_value = "gpt-4"
-
- llm = mock_strategy._select_llm("complex_reasoning_module")
-
- assert llm is not None
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_module_prompt_templating(self, mock_strategy_cls):
- """Test prompt templates are used"""
- mock_strategy = MagicMock()
- mock_strategy._render_prompt.return_value = (
- "Analyze the following query: test"
- )
-
- prompt = mock_strategy._render_prompt(
- "analysis_template", {"query": "test"}
- )
-
- assert "test" in prompt
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_module_output_validation(self, mock_strategy_cls):
- """Test module output is validated"""
- mock_strategy = MagicMock()
- mock_strategy._validate_output.return_value = {
- "valid": True,
- "errors": [],
- }
-
- validation = mock_strategy._validate_output({"candidates": [1, 2, 3]})
-
- assert validation["valid"] is True
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_module_quality_assessment(self, mock_strategy_cls):
- """Test module output quality is assessed"""
- mock_strategy = MagicMock()
- mock_strategy._assess_quality.return_value = 0.85
-
- quality = mock_strategy._assess_quality(
- {"candidates": ["good", "quality"]}
- )
-
- assert quality >= 0.8
-
-
-class TestStrategyOrchestration:
- """Tests for strategy orchestration"""
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_strategy_configuration(self, mock_strategy_cls):
- """Test strategy is configurable"""
- mock_strategy = MagicMock()
- mock_strategy.config = {
- "max_iterations": 10,
- "confidence_threshold": 0.8,
- }
-
- assert mock_strategy.config["max_iterations"] == 10
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_strategy_execution_flow(self, mock_strategy_cls):
- """Test execution flows through all phases"""
- mock_strategy = MagicMock()
- mock_strategy.analyze_topic.return_value = {
- "phases_completed": [1, 2, 3, 4, 5, 6, 7],
- "answer": "Test answer",
- }
-
- result = mock_strategy.analyze_topic("test query")
-
- assert len(result["phases_completed"]) == 7
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_strategy_adaptation(self, mock_strategy_cls):
- """Test strategy adapts to query type"""
- mock_strategy = MagicMock()
- mock_strategy._adapt_strategy.return_value = {
- "search_depth": "deep",
- "parallel_searches": True,
- }
-
- adaptation = mock_strategy._adapt_strategy("complex research query")
-
- assert "search_depth" in adaptation
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_strategy_fallback_handling(self, mock_strategy_cls):
- """Test fallback is used on failure"""
- mock_strategy = MagicMock()
- mock_strategy._execute_with_fallback.return_value = {
- "success": True,
- "used_fallback": True,
- "fallback_type": "simplified_search",
- }
-
- result = mock_strategy._execute_with_fallback("main_search")
-
- assert result["used_fallback"] is True
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_strategy_quality_threshold(self, mock_strategy_cls):
- """Test quality threshold is enforced"""
- mock_strategy = MagicMock()
- mock_strategy._meets_quality_threshold.return_value = False
-
- meets_threshold = mock_strategy._meets_quality_threshold(
- {"confidence": 0.5}, threshold=0.8
- )
-
- assert meets_threshold is False
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_strategy_early_termination(self, mock_strategy_cls):
- """Test early termination on high confidence"""
- mock_strategy = MagicMock()
- mock_strategy._should_terminate_early.return_value = True
-
- should_stop = mock_strategy._should_terminate_early(
- {"confidence": 0.98}
- )
-
- assert should_stop is True
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_strategy_result_synthesis(self, mock_strategy_cls):
- """Test results are synthesized"""
- mock_strategy = MagicMock()
- mock_strategy._synthesize_results.return_value = {
- "answer": "Synthesized answer",
- "sources": ["source1", "source2"],
- }
-
- synthesis = mock_strategy._synthesize_results(
- [{"text": "result1"}, {"text": "result2"}]
- )
-
- assert "answer" in synthesis
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_strategy_cost_optimization(self, mock_strategy_cls):
- """Test cost optimization is applied"""
- mock_strategy = MagicMock()
- mock_strategy._optimize_for_cost.return_value = {
- "reduced_searches": True,
- "estimated_savings": 0.15,
- }
-
- optimization = mock_strategy._optimize_for_cost({"budget": 1.0})
-
- assert "reduced_searches" in optimization
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_strategy_latency_optimization(self, mock_strategy_cls):
- """Test latency optimization is applied"""
- mock_strategy = MagicMock()
- mock_strategy._optimize_for_latency.return_value = {
- "parallel_execution": True,
- "cached_results_used": True,
- }
-
- optimization = mock_strategy._optimize_for_latency(
- {"max_latency_ms": 5000}
- )
-
- assert optimization["parallel_execution"] is True
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_strategy_quality_optimization(self, mock_strategy_cls):
- """Test quality optimization is applied"""
- mock_strategy = MagicMock()
- mock_strategy._optimize_for_quality.return_value = {
- "deep_search": True,
- "verification_enabled": True,
- }
-
- optimization = mock_strategy._optimize_for_quality({"min_quality": 0.9})
-
- assert optimization["verification_enabled"] is True
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_strategy_multi_objective(self, mock_strategy_cls):
- """Test multi-objective optimization"""
- mock_strategy = MagicMock()
- mock_strategy._optimize_multi_objective.return_value = {
- "balance": "quality_first",
- "compromises": ["slightly_slower"],
- }
-
- optimization = mock_strategy._optimize_multi_objective(
- {"quality": 0.9, "cost": 0.5, "latency": 0.7}
- )
-
- assert "balance" in optimization
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_strategy_user_preference(self, mock_strategy_cls):
- """Test user preferences are respected"""
- mock_strategy = MagicMock()
- mock_strategy._apply_user_preferences.return_value = {
- "search_engines": ["google", "bing"],
- "max_sources": 10,
- }
-
- preferences = mock_strategy._apply_user_preferences(
- {"preferred_engines": ["google"]}
- )
-
- assert "search_engines" in preferences
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_strategy_context_awareness(self, mock_strategy_cls):
- """Test strategy is context-aware"""
- mock_strategy = MagicMock()
- mock_strategy._apply_context.return_value = {
- "previous_searches": ["search1"],
- "accumulated_knowledge": {"fact1": True},
- }
-
- context = mock_strategy._apply_context({"history": ["search1"]})
-
- assert "accumulated_knowledge" in context
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_strategy_learning_integration(self, mock_strategy_cls):
- """Test learning from past executions"""
- mock_strategy = MagicMock()
- mock_strategy._apply_learning.return_value = {
- "improved_patterns": True,
- "success_rate_improvement": 0.05,
- }
-
- learning = mock_strategy._apply_learning({"past_executions": 100})
-
- assert learning["improved_patterns"] is True
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMDrivenModularStrategy"
- )
- def test_strategy_feedback_incorporation(self, mock_strategy_cls):
- """Test feedback is incorporated"""
- mock_strategy = MagicMock()
- mock_strategy._incorporate_feedback.return_value = {
- "adjustments_made": ["increased_depth"],
- "feedback_applied": True,
- }
-
- feedback_result = mock_strategy._incorporate_feedback(
- {"rating": 3, "comment": "Need more depth"}
- )
-
- assert feedback_result["feedback_applied"] is True
-
-
-class TestLLMConstraintProcessor:
- """Tests for LLM constraint processor"""
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMConstraintProcessor"
- )
- def test_decompose_constraints_intelligently(self, mock_processor_cls):
- """Test intelligent constraint decomposition"""
- mock_processor = MagicMock()
- mock_processor.decompose_constraints_intelligently.return_value = {
- "atomic_elements": ["element1", "element2"],
- "variations": ["var1", "var2"],
- }
-
- result = mock_processor.decompose_constraints_intelligently(
- ["constraint1"]
- )
-
- assert "atomic_elements" in result
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMConstraintProcessor"
- )
- def test_generate_intelligent_combinations(self, mock_processor_cls):
- """Test generating search combinations"""
- mock_processor = MagicMock()
- mock_processor.generate_intelligent_combinations.return_value = [
- {"query": "combination1", "priority": "high"},
- {"query": "combination2", "priority": "medium"},
- ]
-
- combinations = mock_processor.generate_intelligent_combinations(
- {"elements": ["e1", "e2"]}
- )
-
- assert len(combinations) == 2
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMConstraintProcessor"
- )
- def test_generate_creative_search_angles(self, mock_processor_cls):
- """Test creative search angle generation"""
- mock_processor = MagicMock()
- mock_processor.generate_creative_search_angles.return_value = [
- "alternative perspective 1",
- "alternative perspective 2",
- ]
-
- angles = mock_processor.generate_creative_search_angles(
- "query", {"constraints": []}
- )
-
- assert len(angles) == 2
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.LLMConstraintProcessor"
- )
- def test_optimize_search_combinations(self, mock_processor_cls):
- """Test search combination optimization"""
- mock_processor = MagicMock()
- mock_processor.optimize_search_combinations.return_value = [
- {"query": "optimized1", "score": 0.9},
- {"query": "optimized2", "score": 0.8},
- ]
-
- optimized = mock_processor.optimize_search_combinations(
- [
- {"query": "q1", "score": 0.9},
- {"query": "q2", "score": 0.5},
- {"query": "q3", "score": 0.8},
- ]
- )
-
- # Should be sorted by score
- assert len(optimized) == 2
-
-
-class TestEarlyRejectionManager:
- """Tests for early rejection manager"""
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.EarlyRejectionManager"
- )
- def test_quick_confidence_check(self, mock_manager_cls):
- """Test quick confidence checking"""
- mock_manager = MagicMock()
- mock_manager.quick_confidence_check.return_value = {
- "positive_confidence": 0.8,
- "negative_confidence": 0.2,
- }
-
- check = mock_manager.quick_confidence_check(
- "candidate", ["constraint1"]
- )
-
- assert "positive_confidence" in check
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.EarlyRejectionManager"
- )
- def test_should_reject_early(self, mock_manager_cls):
- """Test early rejection decision"""
- mock_manager = MagicMock()
- mock_manager.should_reject_early.return_value = True
-
- should_reject = mock_manager.should_reject_early(
- {"positive_confidence": 0.1}
- )
-
- assert should_reject is True
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.llm_driven_modular_strategy.EarlyRejectionManager"
- )
- def test_should_continue_search(self, mock_manager_cls):
- """Test search continuation decision"""
- mock_manager = MagicMock()
- mock_manager.should_continue_search.return_value = False
-
- should_continue = mock_manager.should_continue_search(
- all_candidates=[{"confidence": 0.95}], high_confidence_count=1
- )
-
- assert should_continue is False
diff --git a/tests/advanced_search_system/strategies/test_rapid_search_strategy_extended.py b/tests/advanced_search_system/strategies/test_rapid_search_strategy_extended.py
deleted file mode 100644
index f5160f3eed..0000000000
--- a/tests/advanced_search_system/strategies/test_rapid_search_strategy_extended.py
+++ /dev/null
@@ -1,473 +0,0 @@
-"""
-Extended tests for RapidSearchStrategy - Optimized rapid search implementation.
-
-Tests cover:
-- Strategy initialization
-- Search execution flow
-- Snippet collection
-- Question generation
-- Final synthesis
-- Progress callback handling
-- Error handling
-"""
-
-
-class TestStrategyInitialization:
- """Tests for RapidSearchStrategy initialization."""
-
- def test_progress_callback_default_none(self):
- """Progress callback should default to None."""
- progress_callback = None
- assert progress_callback is None
-
- def test_questions_by_iteration_initialized(self):
- """Questions by iteration should be initialized."""
- questions_by_iteration = {}
- assert isinstance(questions_by_iteration, dict)
- assert len(questions_by_iteration) == 0
-
- def test_all_links_initialized(self):
- """All links list should be initialized."""
- all_links = []
- assert isinstance(all_links, list)
-
- def test_citation_handler_optional(self):
- """Citation handler should be optional."""
- citation_handler = None
- # Should use provided or create one
- if citation_handler is None:
- handler = "default_handler"
- else:
- handler = citation_handler
- assert handler == "default_handler"
-
-
-class TestSearchExecution:
- """Tests for search execution flow."""
-
- def test_initial_search_performed(self):
- """Should perform initial search for main query."""
- query = "What is machine learning?"
- # Simulated search execution
- search_performed = True
- assert search_performed is True
- assert len(query) > 0
-
- def test_results_collected(self):
- """Should collect search results."""
- results = [
- {"title": "Result 1", "snippet": "Snippet 1"},
- {"title": "Result 2", "snippet": "Snippet 2"},
- ]
- assert len(results) == 2
-
- def test_empty_results_handled(self):
- """Should handle empty search results."""
- results = []
- if not results:
- results = []
- assert results == []
-
-
-class TestSnippetCollection:
- """Tests for snippet collection."""
-
- def test_snippets_extracted_from_results(self):
- """Should extract snippets from search results."""
- results = [
- {
- "snippet": "Snippet text 1",
- "title": "Title 1",
- "link": "http://a.com",
- },
- {
- "snippet": "Snippet text 2",
- "title": "Title 2",
- "link": "http://b.com",
- },
- ]
-
- collected_snippets = []
- for result in results:
- if "snippet" in result:
- collected_snippets.append(
- {
- "text": result["snippet"],
- "source": result.get("title", "Unknown"),
- "link": result.get("link", ""),
- }
- )
-
- assert len(collected_snippets) == 2
- assert collected_snippets[0]["text"] == "Snippet text 1"
-
- def test_snippet_structure(self):
- """Snippet should have expected structure."""
- snippet = {
- "text": "Snippet text",
- "source": "Source title",
- "link": "http://example.com",
- "query": "original query",
- }
-
- assert "text" in snippet
- assert "source" in snippet
- assert "link" in snippet
- assert "query" in snippet
-
- def test_missing_snippet_skipped(self):
- """Results without snippet should be skipped."""
- results = [
- {"title": "Title 1", "link": "http://a.com"}, # No snippet
- {"snippet": "Snippet 2", "title": "Title 2"},
- ]
-
- collected = []
- for result in results:
- if "snippet" in result:
- collected.append(result["snippet"])
-
- assert len(collected) == 1
-
-
-class TestQuestionGeneration:
- """Tests for follow-up question generation."""
-
- def test_questions_generated(self):
- """Should generate follow-up questions."""
- questions = ["Q1?", "Q2?", "Q3?"]
- assert len(questions) == 3
-
- def test_fewer_questions_for_speed(self):
- """Should generate fewer questions for speed."""
- questions_per_iteration = 3 # Fewer than standard
- assert questions_per_iteration == 3
-
- def test_questions_stored_in_iteration(self):
- """Questions should be stored by iteration."""
- questions_by_iteration = {}
- questions = ["Q1?", "Q2?"]
- questions_by_iteration[0] = questions
-
- assert 0 in questions_by_iteration
- assert len(questions_by_iteration[0]) == 2
-
-
-class TestFinalSynthesis:
- """Tests for final synthesis."""
-
- def test_synthesis_performed_once(self):
- """Synthesis should be performed only once."""
- synthesis_count = 0
-
- # Simulated synthesis
- synthesis_count += 1
-
- assert synthesis_count == 1
-
- def test_synthesis_uses_all_snippets(self):
- """Synthesis should use all collected snippets."""
- collected_snippets = [
- {"text": "Snippet 1"},
- {"text": "Snippet 2"},
- {"text": "Snippet 3"},
- ]
-
- # All snippets should be available for synthesis
- snippets_for_synthesis = collected_snippets
- assert len(snippets_for_synthesis) == 3
-
- def test_synthesis_result_structure(self):
- """Synthesis result should have expected structure."""
- result = {
- "content": "Synthesized content",
- "documents": [{"title": "Doc 1"}],
- }
-
- assert "content" in result
- assert "documents" in result
-
-
-class TestProgressCallback:
- """Tests for progress callback handling."""
-
- def test_progress_initialization(self):
- """Should report initialization progress."""
- progress_updates = []
-
- def callback(msg, pct, data):
- progress_updates.append((msg, pct, data))
-
- callback("Initializing rapid research system", 5, {"phase": "init"})
-
- assert len(progress_updates) == 1
- assert progress_updates[0][1] == 5
-
- def test_progress_search_phase(self):
- """Should report search progress."""
- progress_updates = []
-
- def callback(msg, pct, data):
- progress_updates.append((msg, pct, data))
-
- callback("Performing initial search", 10, {"phase": "search"})
-
- assert progress_updates[0][2]["phase"] == "search"
-
- def test_progress_question_iteration(self):
- """Should report progress per question."""
- questions = ["Q1", "Q2", "Q3"]
- progress_values = []
-
- for q_idx, _question in enumerate(questions):
- question_progress = 30 + ((q_idx + 1) / len(questions) * 40)
- progress_values.append(int(question_progress))
-
- # Progress should increase with each question
- assert progress_values[2] > progress_values[0]
-
- def test_progress_synthesis_phase(self):
- """Should report synthesis progress."""
- progress_updates = []
-
- def callback(msg, pct, data):
- progress_updates.append((msg, pct, data))
-
- callback(
- "Synthesizing all collected information",
- 80,
- {"phase": "final_synthesis"},
- )
-
- assert progress_updates[0][1] == 80
-
- def test_progress_completion(self):
- """Should report 100% on completion."""
- progress_updates = []
-
- def callback(msg, pct, data):
- progress_updates.append((msg, pct, data))
-
- callback("Research complete", 100, {"phase": "complete"})
-
- assert progress_updates[0][1] == 100
-
-
-class TestReturnValue:
- """Tests for return value structure."""
-
- def test_return_has_findings(self):
- """Return should have findings key."""
- result = {
- "findings": [],
- "iterations": 1,
- }
- assert "findings" in result
-
- def test_return_has_iterations(self):
- """Return should have iterations key."""
- result = {
- "findings": [],
- "iterations": 1,
- }
- assert result["iterations"] == 1
-
- def test_iterations_always_one(self):
- """Rapid mode always has 1 iteration."""
- iterations = 1
- assert iterations == 1
-
- def test_return_has_questions(self):
- """Return should have questions key."""
- result = {
- "questions": {0: ["Q1", "Q2"]},
- }
- assert "questions" in result
-
- def test_return_has_formatted_findings(self):
- """Return should have formatted_findings key."""
- result = {
- "formatted_findings": "Formatted text...",
- }
- assert "formatted_findings" in result
-
- def test_return_has_current_knowledge(self):
- """Return should have current_knowledge key."""
- result = {
- "current_knowledge": "Synthesized knowledge...",
- }
- assert "current_knowledge" in result
-
-
-class TestFindingStructure:
- """Tests for finding structure."""
-
- def test_finding_has_phase(self):
- """Finding should have phase key."""
- finding = {
- "phase": "Final synthesis",
- "content": "Content",
- }
- assert finding["phase"] == "Final synthesis"
-
- def test_finding_has_content(self):
- """Finding should have content key."""
- finding = {
- "phase": "Final synthesis",
- "content": "Synthesized content here",
- }
- assert "content" in finding
-
- def test_finding_has_question(self):
- """Finding should have question key."""
- finding = {
- "phase": "Final synthesis",
- "content": "Content",
- "question": "Original query",
- }
- assert "question" in finding
-
- def test_finding_has_search_results(self):
- """Finding should have search_results key."""
- finding = {
- "phase": "Final synthesis",
- "content": "Content",
- "search_results": [{"title": "Result 1"}],
- }
- assert "search_results" in finding
-
- def test_finding_has_documents(self):
- """Finding should have documents key."""
- finding = {
- "phase": "Final synthesis",
- "content": "Content",
- "documents": [{"doc": "1"}],
- }
- assert "documents" in finding
-
-
-class TestSearchEngineValidation:
- """Tests for search engine validation."""
-
- def test_no_search_engine_error(self):
- """Should return error when no search engine."""
- search = None
-
- if not search:
- result = {
- "findings": [],
- "iterations": 0,
- "error": "No search engine available",
- "formatted_findings": "Error: Unable to conduct research without a search engine.",
- }
- else:
- result = {"findings": [{"content": "data"}]}
-
- assert "error" in result
- assert result["iterations"] == 0
-
-
-class TestLinkExtraction:
- """Tests for link extraction."""
-
- def test_links_extracted_from_results(self):
- """Should extract links from search results."""
- results = [
- {"title": "Title 1", "link": "http://example1.com"},
- {"title": "Title 2", "link": "http://example2.com"},
- ]
-
- links = []
- for result in results:
- if "link" in result:
- links.append(result["link"])
-
- assert len(links) == 2
-
- def test_links_accumulated(self):
- """Links should be accumulated across searches."""
- all_links = []
- initial_links = ["http://a.com"]
- followup_links = ["http://b.com", "http://c.com"]
-
- all_links.extend(initial_links)
- all_links.extend(followup_links)
-
- assert len(all_links) == 3
-
-
-class TestErrorHandling:
- """Tests for error handling."""
-
- def test_search_error_handled(self):
- """Should handle search errors gracefully."""
- try:
- raise Exception("Search error")
- except Exception:
- results = []
-
- assert results == []
-
- def test_synthesis_error_creates_error_finding(self):
- """Synthesis error should create error finding."""
- try:
- raise Exception("Synthesis error")
- except Exception as e:
- error_msg = f"Error synthesizing final answer: {e!s}"
- finding = {
- "phase": "Error",
- "content": error_msg,
- }
-
- assert finding["phase"] == "Error"
- assert "Synthesis error" in finding["content"]
-
- def test_error_progress_reported(self):
- """Errors should be reported via progress callback."""
- progress_updates = []
-
- def callback(msg, pct, data):
- progress_updates.append((msg, pct, data))
-
- callback(
- "Error during search",
- 15,
- {"phase": "search_error", "error": "Search error"},
- )
-
- assert progress_updates[0][2]["phase"] == "search_error"
-
-
-class TestResultCounts:
- """Tests for result count tracking."""
-
- def test_result_count_in_progress(self):
- """Result count should be in progress data."""
- results = [{"title": "R1"}, {"title": "R2"}, {"title": "R3"}]
- progress_data = {
- "phase": "search_complete",
- "result_count": len(results),
- }
-
- assert progress_data["result_count"] == 3
-
- def test_zero_results_reported(self):
- """Zero results should be reported."""
- results = []
- progress_data = {
- "phase": "search_complete",
- "result_count": len(results),
- }
-
- assert progress_data["result_count"] == 0
-
-
-class TestStrategyName:
- """Tests for strategy identification."""
-
- def test_strategy_name_rapid(self):
- """Strategy should be identified as rapid."""
- strategy_name = "rapid"
- progress_data = {"phase": "init", "strategy": strategy_name}
-
- assert progress_data["strategy"] == "rapid"
diff --git a/tests/advanced_search_system/strategies/test_smart_query_strategy.py b/tests/advanced_search_system/strategies/test_smart_query_strategy.py
deleted file mode 100644
index cdcb745c0b..0000000000
--- a/tests/advanced_search_system/strategies/test_smart_query_strategy.py
+++ /dev/null
@@ -1,330 +0,0 @@
-"""
-Tests for Smart Query Strategy.
-
-Phase 35: Complex Strategies - Tests for smart query generation and optimization.
-Tests query analysis, intent detection, and query expansion.
-"""
-
-from unittest.mock import MagicMock
-
-
-class TestSmartQueryStrategyInit:
- """Tests for smart query strategy initialization."""
-
- def test_initialization_basic(self):
- """Test basic initialization of smart query components."""
- # Test basic query generation setup
- query = "What is the capital of France?"
- assert len(query) > 0
-
- def test_initialization_with_model(self):
- """Test initialization with language model."""
- mock_model = MagicMock()
- mock_model.invoke.return_value = MagicMock(content="Paris")
-
- result = mock_model.invoke("Test query")
- assert result.content == "Paris"
-
-
-class TestQueryAnalysis:
- """Tests for query analysis functionality."""
-
- def test_analyze_simple_query(self):
- """Test analysis of simple query."""
- query = "What is AI?"
- words = query.split()
- assert len(words) >= 2
-
- def test_analyze_complex_query(self):
- """Test analysis of complex multi-part query."""
- query = "What are the economic impacts of climate change on agriculture in developing countries?"
- words = query.split()
- assert len(words) > 10
-
- def test_analyze_query_with_entities(self):
- """Test analysis of query with named entities."""
- query = "When did Microsoft acquire GitHub?"
- entities = ["Microsoft", "GitHub"]
- for entity in entities:
- assert entity in query
-
- def test_analyze_query_type(self):
- """Test query type detection."""
- queries = {
- "What is AI?": "definition",
- "How does it work?": "process",
- "When was it invented?": "temporal",
- "Where is it used?": "location",
- "Who invented it?": "person",
- "Why is it important?": "reason",
- }
- for query, expected_type in queries.items():
- # Basic type detection based on question word
- if query.startswith("What"):
- assert expected_type in ["definition", "explanation"] or True
- elif query.startswith("When"):
- assert expected_type == "temporal"
-
-
-class TestIntentDetection:
- """Tests for query intent detection."""
-
- def test_detect_informational_intent(self):
- """Test detection of informational intent."""
- queries = [
- "What is machine learning?",
- "How does photosynthesis work?",
- "Explain quantum computing",
- ]
- for query in queries:
- # Informational queries often start with question words or "explain"
- is_informational = any(
- query.lower().startswith(w) for w in ["what", "how", "explain"]
- )
- assert is_informational
-
- def test_detect_navigational_intent(self):
- """Test detection of navigational intent."""
- queries = [
- "Python documentation",
- "OpenAI website",
- "GitHub login",
- ]
- for query in queries:
- # Navigational queries often contain specific site/service names
- words = query.split()
- assert len(words) <= 3
-
- def test_detect_transactional_intent(self):
- """Test detection of transactional intent."""
- transactional_words = [
- "buy",
- "download",
- "sign up",
- "register",
- "order",
- ]
- query = "buy laptop"
- has_transactional = any(
- word in query.lower() for word in transactional_words
- )
- assert has_transactional
-
- def test_detect_comparison_intent(self):
- """Test detection of comparison intent."""
- comparison_words = ["vs", "versus", "compare", "better", "difference"]
- query = "Python vs JavaScript"
- has_comparison = any(word in query.lower() for word in comparison_words)
- assert has_comparison
-
-
-class TestQueryExpansion:
- """Tests for query expansion functionality."""
-
- def test_expand_query_with_synonyms(self):
- """Test query expansion with synonyms."""
- original = "fast cars"
- synonyms = ["quick", "speedy", "rapid"]
- expanded_queries = [f"{syn} cars" for syn in synonyms]
- expanded_queries.append(original)
-
- assert len(expanded_queries) == 4
-
- def test_expand_query_with_related_terms(self):
- """Test query expansion with related terms."""
- query = "machine learning"
- related = [
- "artificial intelligence",
- "deep learning",
- "neural networks",
- ]
- expanded = [f"{query} {term}" for term in related]
-
- assert len(expanded) == 3
-
- def test_expand_query_with_context(self):
- """Test query expansion with context."""
- query = "python"
- contexts = ["programming language", "snake", "data science"]
- expanded = [f"{query} {ctx}" for ctx in contexts]
-
- assert all("python" in q for q in expanded)
-
-
-class TestQueryReformulation:
- """Tests for query reformulation."""
-
- def test_reformulate_question_to_statement(self):
- """Test reformulating question to statement."""
- _question = "What is the capital of France?" # noqa: F841 - context
- # Simple reformulation
- statement = "capital of France"
- assert "capital" in statement
-
- def test_reformulate_with_specificity(self):
- """Test adding specificity to vague query."""
- vague = "weather"
- specific = "weather forecast today"
- assert len(specific) > len(vague)
-
- def test_reformulate_remove_stop_words(self):
- """Test removing stop words from query."""
- query = "what is the best way to learn programming"
- stop_words = {"what", "is", "the", "to"}
- words = query.split()
- filtered = [w for w in words if w not in stop_words]
-
- assert "best" in filtered
- assert "programming" in filtered
-
-
-class TestMultiQueryGeneration:
- """Tests for generating multiple query variations."""
-
- def test_generate_multiple_queries(self):
- """Test generating multiple query variations."""
- base_query = "machine learning applications"
- variations = [
- base_query,
- "ML use cases",
- "practical machine learning",
- "applications of ML",
- ]
-
- assert len(variations) >= 3
-
- def test_query_ranking(self):
- """Test ranking of generated queries."""
- queries = [
- {"query": "specific query", "score": 0.9},
- {"query": "vague query", "score": 0.5},
- {"query": "medium query", "score": 0.7},
- ]
- sorted_queries = sorted(queries, key=lambda x: x["score"], reverse=True)
-
- assert sorted_queries[0]["score"] == 0.9
-
-
-class TestResultAggregation:
- """Tests for result aggregation from multiple queries."""
-
- def test_aggregate_results_deduplication(self):
- """Test deduplication in result aggregation."""
- results = [
- {"url": "http://example.com/1", "title": "Result 1"},
- {"url": "http://example.com/1", "title": "Result 1"}, # Duplicate
- {"url": "http://example.com/2", "title": "Result 2"},
- ]
- unique = {r["url"]: r for r in results}
-
- assert len(unique) == 2
-
- def test_aggregate_results_scoring(self):
- """Test scoring in result aggregation."""
- results = [
- {"url": "url1", "score": 0.8, "sources": 1},
- {"url": "url2", "score": 0.6, "sources": 3},
- ]
- # Score could factor in number of sources
- for r in results:
- r["combined_score"] = r["score"] * (1 + 0.1 * r["sources"])
-
- assert results[1]["combined_score"] > results[1]["score"]
-
-
-class TestDiversityOptimization:
- """Tests for query diversity optimization."""
-
- def test_ensure_query_diversity(self):
- """Test ensuring diversity in query set."""
- queries = [
- "machine learning basics",
- "ML fundamentals",
- "intro to machine learning",
- ]
- # All queries are about the same topic - need diversity
- unique_words = set()
- for q in queries:
- unique_words.update(q.lower().split())
-
- assert len(unique_words) > 5 # Should have varied vocabulary
-
-
-class TestCoverageTracking:
- """Tests for coverage tracking."""
-
- def test_track_query_coverage(self):
- """Test tracking which aspects queries cover."""
- _aspects = ["definition", "applications", "history", "future"] # noqa: F841
- covered = {
- "definition": True,
- "applications": True,
- "history": False,
- "future": False,
- }
-
- coverage_rate = sum(covered.values()) / len(covered)
- assert coverage_rate == 0.5
-
-
-class TestLLMIntegration:
- """Tests for LLM integration in smart query."""
-
- def test_llm_query_generation(self):
- """Test using LLM to generate queries."""
- mock_model = MagicMock()
- mock_response = MagicMock()
- mock_response.content = "1. Query one\n2. Query two\n3. Query three"
- mock_model.invoke.return_value = mock_response
-
- result = mock_model.invoke("Generate search queries")
- assert "Query" in result.content
-
-
-class TestErrorHandling:
- """Tests for error handling in smart query strategy."""
-
- def test_handle_empty_query(self):
- """Test handling empty query."""
- query = ""
- is_valid = len(query.strip()) > 0
- assert not is_valid
-
- def test_handle_very_long_query(self):
- """Test handling very long query."""
- query = "word " * 1000
- # Should handle gracefully
- assert len(query) > 0
-
- def test_handle_special_characters(self):
- """Test handling queries with special characters."""
- query = "C++ vs C#"
- # Should not break
- assert "C++" in query
-
-
-class TestCaching:
- """Tests for query caching."""
-
- def test_cache_query_results(self):
- """Test caching of query results."""
- cache = {}
- query = "test query"
- cache[query] = {"results": ["r1", "r2"]}
-
- assert query in cache
- assert len(cache[query]["results"]) == 2
-
-
-class TestMetrics:
- """Tests for strategy metrics."""
-
- def test_track_query_metrics(self):
- """Test tracking query generation metrics."""
- metrics = {
- "queries_generated": 5,
- "unique_queries": 4,
- "avg_query_length": 15.5,
- }
-
- assert metrics["unique_queries"] <= metrics["queries_generated"]
diff --git a/tests/advanced_search_system/strategies/test_source_strategy_logic.py b/tests/advanced_search_system/strategies/test_source_strategy_logic.py
deleted file mode 100644
index 97a055b55b..0000000000
--- a/tests/advanced_search_system/strategies/test_source_strategy_logic.py
+++ /dev/null
@@ -1,228 +0,0 @@
-"""
-Tests for pure logic in SourceBasedSearchStrategy:
-- Long query detection (lines 250-264)
-- Question assembly deduplication (lines 281-286)
-- Progress percentage formula (lines 227-229)
-- Question context limiting (lines 317-324)
-
-Does NOT duplicate _format_search_results_as_context tests (already in test_strategy_pure_logic.py).
-"""
-
-from unittest.mock import Mock
-
-
-def _make_strategy(**overrides):
- """Build a minimal mock object with the attributes used by the logic under test."""
- s = Mock()
- s.search_original_query = overrides.get("search_original_query", True)
- s.questions_by_iteration = {}
- s.all_links_of_system = []
- s.progress_callback = overrides.get("progress_callback", None)
- s._settings_snapshot = overrides.get("settings_snapshot", {})
- s.question_generator = Mock()
- s.get_setting = overrides.get(
- "get_setting", lambda key, default=None: default
- )
- return s
-
-
-# ---------------------------------------------------------------------------
-# 2a. Long query detection
-# ---------------------------------------------------------------------------
-
-
-class TestLongQueryDetection:
- """Tests for long query detection (lines 250-264)."""
-
- def test_query_at_max_length_stays_true(self):
- """Query exactly at 300 chars → search_original_query stays True."""
- s = _make_strategy()
- query = "a" * 300
- max_len = 300
- # Simulate the logic
- if s.search_original_query and len(query.strip()) > max_len:
- s.search_original_query = False
- assert s.search_original_query is True
-
- def test_query_over_max_becomes_false(self):
- """Query at 301 chars → search_original_query becomes False."""
- s = _make_strategy()
- query = "a" * 301
- max_len = 300
- if s.search_original_query and len(query.strip()) > max_len:
- s.search_original_query = False
- assert s.search_original_query is False
-
- def test_whitespace_stripped_before_check(self):
- """Leading/trailing whitespace stripped before length check."""
- s = _make_strategy()
- query = " " + "a" * 299 + " " # 299 actual chars + whitespace
- max_len = 300
- if s.search_original_query and len(query.strip()) > max_len:
- s.search_original_query = False
- assert s.search_original_query is True # 299 < 300
-
- def test_custom_max_from_settings(self):
- """Custom max_query_length (500) from settings."""
- s = _make_strategy()
- query = "a" * 450
- max_len = 500
- if s.search_original_query and len(query.strip()) > max_len:
- s.search_original_query = False
- assert s.search_original_query is True # 450 < 500
-
- def test_search_original_query_false_skips_check(self):
- """search_original_query=False initially → length check skipped."""
- s = _make_strategy(search_original_query=False)
- query = "a" * 1000
- max_len = 300
- if s.search_original_query and len(query.strip()) > max_len:
- s.search_original_query = False
- # Still False — the check never ran because initial value was False
- assert s.search_original_query is False
-
- def test_empty_query_under_limit(self):
- """Empty query has 0 chars, under any limit."""
- s = _make_strategy()
- query = ""
- max_len = 300
- if s.search_original_query and len(query.strip()) > max_len:
- s.search_original_query = False
- assert s.search_original_query is True
-
-
-# ---------------------------------------------------------------------------
-# 2b. Question assembly deduplication
-# ---------------------------------------------------------------------------
-
-
-class TestQuestionAssembly:
- """Tests for question assembly deduplication (lines 281-286)."""
-
- def test_query_prepended_when_not_in_questions(self):
- """search_original_query=True, query NOT in questions → prepended."""
- query = "my query"
- questions = ["q1", "q2"]
- search_original_query = True
- all_questions = (
- [query] + questions
- if search_original_query and query not in questions
- else questions
- )
- assert all_questions == ["my query", "q1", "q2"]
-
- def test_query_not_duplicated_when_already_present(self):
- """search_original_query=True, query in questions → NOT duplicated."""
- query = "my query"
- questions = ["my query", "q2"]
- search_original_query = True
- all_questions = (
- [query] + questions
- if search_original_query and query not in questions
- else questions
- )
- assert all_questions == ["my query", "q2"]
-
- def test_query_skipped_when_flag_false(self):
- """search_original_query=False → questions returned without query."""
- query = "my query"
- questions = ["q1", "q2"]
- search_original_query = False
- all_questions = (
- [query] + questions
- if search_original_query and query not in questions
- else questions
- )
- assert all_questions == ["q1", "q2"]
-
- def test_empty_questions_with_flag_true(self):
- """Empty questions + flag=True → returns [query]."""
- query = "my query"
- questions = []
- search_original_query = True
- all_questions = (
- [query] + questions
- if search_original_query and query not in questions
- else questions
- )
- assert all_questions == ["my query"]
-
- def test_order_preserved_query_first(self):
- """Original query always first when included."""
- query = "original"
- questions = ["q1", "q2", "q3"]
- search_original_query = True
- all_questions = (
- [query] + questions
- if search_original_query and query not in questions
- else questions
- )
- assert all_questions[0] == "original"
- assert all_questions[1:] == ["q1", "q2", "q3"]
-
-
-# ---------------------------------------------------------------------------
-# 2c. Progress percentage formula
-# ---------------------------------------------------------------------------
-
-
-class TestProgressFormula:
- """Tests for iteration_progress_base formula (line 227-229)."""
-
- def _calc(self, iteration, iterations_to_run):
- return 5 + (iteration - 1) * (70 / iterations_to_run)
-
- def test_iter1_of_2(self):
- assert self._calc(1, 2) == 5.0
-
- def test_iter2_of_2(self):
- assert self._calc(2, 2) == 40.0
-
- def test_iter1_of_5(self):
- assert self._calc(1, 5) == 5.0
-
- def test_iter5_of_5(self):
- # 5 + 4*(70/5) = 5 + 56 = 61
- assert self._calc(5, 5) == 61.0
-
- def test_single_iteration_no_division_by_zero(self):
- """iterations_to_run=1 → safe, returns 5."""
- assert self._calc(1, 1) == 5.0
-
-
-# ---------------------------------------------------------------------------
-# 2d. Question context limiting
-# ---------------------------------------------------------------------------
-
-
-class TestQuestionContextLimiting:
- """Tests for question context limiting (lines 317-324)."""
-
- def test_50_results_limit_30_returns_last_30(self):
- results = list(range(50))
- limit = 30
- sliced = results[-limit:]
- assert len(sliced) == 30
- assert sliced[0] == 20 # last 30 of 0..49
-
- def test_10_results_limit_30_returns_all(self):
- results = list(range(10))
- limit = 30
- sliced = results[-limit:]
- assert len(sliced) == 10
-
- def test_default_limit_is_30(self):
- """get_setting returns 30 by default."""
- s = _make_strategy()
- val = int(s.get_setting("search.question_context_limit", 30))
- assert val == 30
-
- def test_custom_limit_from_settings(self):
- """Custom limit from settings snapshot."""
- s = _make_strategy(
- get_setting=lambda key, default=None: (
- 50 if key == "search.question_context_limit" else default
- )
- )
- val = int(s.get_setting("search.question_context_limit", 30))
- assert val == 50
diff --git a/tests/advanced_search_system/strategies/test_topic_organization_extended.py b/tests/advanced_search_system/strategies/test_topic_organization_extended.py
deleted file mode 100644
index 6dc06aa1bf..0000000000
--- a/tests/advanced_search_system/strategies/test_topic_organization_extended.py
+++ /dev/null
@@ -1,367 +0,0 @@
-"""
-Tests for topic organization strategy extended functionality.
-
-Tests cover:
-- Topic extraction and clustering
-- Topic hierarchy building
-- Topic relevance and coverage
-"""
-
-from unittest.mock import Mock
-
-
-class TestTopicExtraction:
- """Tests for topic extraction from queries."""
-
- def test_topic_extraction_from_query(self):
- """Topics are extracted from query."""
-
- # Simulate topic extraction
- topics = ["climate change", "agriculture", "food security"]
-
- assert len(topics) == 3
- assert "climate change" in topics
-
- def test_topic_extraction_single_topic(self):
- """Single topic queries are handled."""
-
- topics = ["quantum computing"]
-
- assert len(topics) == 1
-
- def test_topic_extraction_empty_query(self):
- """Empty queries return empty topics."""
- query = ""
-
- if not query.strip():
- topics = []
- else:
- topics = query.split()
-
- assert topics == []
-
- def test_topic_extraction_stop_words_removed(self):
- """Stop words are removed from topics."""
- query = "the effects of climate change on the environment"
- stop_words = {"the", "of", "on", "and", "a", "an"}
-
- words = query.lower().split()
- filtered = [w for w in words if w not in stop_words]
-
- assert "the" not in filtered
- assert "effects" in filtered
-
- def test_topic_extraction_compound_terms(self):
- """Compound terms are preserved."""
-
- # Preserve known compound terms
- compound_terms = ["machine learning", "artificial intelligence"]
- extracted = compound_terms
-
- assert "machine learning" in extracted
-
-
-class TestTopicClustering:
- """Tests for topic clustering."""
-
- def test_topic_clustering_algorithm(self):
- """Topics are clustered by similarity."""
-
- # Simple clustering by category
- clusters = {
- "AI": ["machine learning", "deep learning", "neural networks"],
- "Food": ["cooking recipes", "baking tips"],
- }
-
- assert len(clusters) == 2
- assert len(clusters["AI"]) == 3
-
- def test_topic_clustering_single_cluster(self):
- """Single topic goes to one cluster."""
- topics = ["python programming"]
-
- clusters = {"Programming": topics}
-
- assert len(clusters) == 1
-
- def test_topic_clustering_empty_input(self):
- """Empty topics return empty clusters."""
-
- clusters = {}
-
- assert clusters == {}
-
- def test_topic_clustering_overlapping_topics(self):
- """Overlapping topics are assigned to primary cluster."""
- topics = ["data science", "machine learning"]
-
- # Both could be AI, but primary assignment
- primary_cluster = {"AI/Data": topics}
-
- assert len(primary_cluster["AI/Data"]) == 2
-
-
-class TestTopicHierarchy:
- """Tests for topic hierarchy building."""
-
- def test_topic_hierarchy_building(self):
- """Topic hierarchy is built correctly."""
-
- hierarchy = {
- "AI": {
- "subtopics": ["Machine Learning"],
- "Machine Learning": {"subtopics": ["Deep Learning"]},
- }
- }
-
- assert "AI" in hierarchy
- assert "Machine Learning" in hierarchy["AI"]["subtopics"]
-
- def test_topic_hierarchy_depth_limiting(self):
- """Hierarchy depth is limited."""
- max_depth = 3
- current_depth = 0
-
- def build_hierarchy(depth):
- if depth >= max_depth:
- return {"leaf": True}
- return {"subtopics": [build_hierarchy(depth + 1)]}
-
- result = build_hierarchy(current_depth)
-
- # Check structure exists
- assert "subtopics" in result
-
- def test_topic_hierarchy_flat_topics(self):
- """Flat topics create shallow hierarchy."""
- topics = ["topic1", "topic2", "topic3"]
-
- hierarchy = {t: {"subtopics": []} for t in topics}
-
- for topic in topics:
- assert hierarchy[topic]["subtopics"] == []
-
- def test_topic_subtopic_generation(self):
- """Subtopics are generated for main topics."""
-
- subtopics = [
- "Global Warming",
- "Sea Level Rise",
- "Carbon Emissions",
- ]
-
- assert len(subtopics) == 3
-
-
-class TestTopicRelevance:
- """Tests for topic relevance scoring."""
-
- def test_topic_relevance_scoring(self):
- """Topics are scored for relevance."""
- topics = [
- {"name": "machine learning", "score": 0.9},
- {"name": "algorithms", "score": 0.8},
- {"name": "cooking", "score": 0.1},
- ]
-
- relevant = [t for t in topics if t["score"] > 0.5]
-
- assert len(relevant) == 2
-
- def test_topic_relevance_threshold(self):
- """Relevance threshold filters topics."""
- threshold = 0.7
- scores = [0.5, 0.6, 0.7, 0.8, 0.9]
-
- above_threshold = [s for s in scores if s >= threshold]
-
- assert len(above_threshold) == 3
-
- def test_topic_relevance_empty_scores(self):
- """Empty scores handled gracefully."""
- scores = []
-
- if not scores:
- avg_score = 0.0
- else:
- avg_score = sum(scores) / len(scores)
-
- assert avg_score == 0.0
-
-
-class TestTopicCoverage:
- """Tests for topic coverage analysis."""
-
- def test_topic_coverage_analysis(self):
- """Topic coverage is analyzed."""
- required_topics = {"A", "B", "C", "D"}
- covered_topics = {"A", "B", "C"}
-
- coverage = len(covered_topics & required_topics) / len(required_topics)
-
- assert coverage == 0.75
-
- def test_topic_gap_detection(self):
- """Gaps in topic coverage are detected."""
- required_topics = {"A", "B", "C", "D"}
- covered_topics = {"A", "C"}
-
- gaps = required_topics - covered_topics
-
- assert gaps == {"B", "D"}
-
- def test_topic_full_coverage(self):
- """Full coverage is detected."""
- required_topics = {"A", "B", "C"}
- covered_topics = {"A", "B", "C", "D"}
-
- fully_covered = required_topics.issubset(covered_topics)
-
- assert fully_covered
-
- def test_topic_deduplication(self):
- """Duplicate topics are removed."""
- topics = ["AI", "ai", "Artificial Intelligence", "AI"]
-
- # Normalize and deduplicate
- unique = list(set(t.lower() for t in topics))
-
- assert len(unique) == 2
-
-
-class TestTopicSearch:
- """Tests for topic-based search."""
-
- def test_topic_search_query_generation(self):
- """Search queries are generated from topics."""
- topic = "climate change"
- subtopics = ["effects", "solutions"]
-
- queries = [f"{topic} {subtopic}" for subtopic in subtopics]
-
- assert len(queries) == 2
- assert "climate change effects" in queries
-
- def test_topic_result_aggregation(self):
- """Results from topic searches are aggregated."""
- results = {
- "topic1": [{"url": "url1"}, {"url": "url2"}],
- "topic2": [{"url": "url3"}],
- }
-
- all_results = []
- for topic_results in results.values():
- all_results.extend(topic_results)
-
- assert len(all_results) == 3
-
- def test_topic_empty_results_handling(self):
- """Empty topic results are handled."""
- results = {"topic1": [], "topic2": []}
-
- has_results = any(r for r in results.values())
-
- assert not has_results
-
- def test_topic_error_recovery(self):
- """Errors in topic search are recovered."""
- topics = ["topic1", "topic2"]
- results = {}
- errors = []
-
- for topic in topics:
- try:
- if topic == "topic1":
- raise ConnectionError("Search failed")
- results[topic] = ["result"]
- except ConnectionError as e:
- errors.append(str(e))
-
- assert len(errors) == 1
- assert "topic2" in results
-
-
-class TestTopicSettings:
- """Tests for topic strategy settings."""
-
- def test_topic_settings_integration(self):
- """Settings are integrated into strategy."""
- settings = {
- "max_topics": 10,
- "min_relevance": 0.5,
- "max_depth": 3,
- }
-
- assert settings["max_topics"] == 10
-
- def test_topic_cache_utilization(self):
- """Topic cache is utilized."""
- cache = {}
- topic = "machine learning"
-
- if topic not in cache:
- cache[topic] = {"results": [], "timestamp": 0}
-
- cached = topic in cache
-
- assert cached
-
- def test_topic_rate_limit_handling(self):
- """Rate limits are handled."""
- rate_limited = True
-
- if rate_limited:
- action = "wait_and_retry"
- else:
- action = "continue"
-
- assert action == "wait_and_retry"
-
- def test_topic_progress_reporting(self):
- """Progress is reported during processing."""
- total_topics = 10
- processed = 0
- progress_reports = []
-
- for i in range(total_topics):
- processed += 1
- progress = processed / total_topics * 100
- progress_reports.append(progress)
-
- assert progress_reports[-1] == 100.0
-
-
-class TestTopicLLMIntegration:
- """Tests for LLM integration in topic strategy."""
-
- def test_topic_llm_integration(self):
- """LLM is used for topic analysis."""
- mock_llm = Mock()
- mock_llm.invoke.return_value = Mock(content="topic1, topic2, topic3")
-
- mock_llm.invoke("Extract topics from: test query")
-
- assert mock_llm.invoke.called
-
- def test_topic_llm_error_handling(self):
- """LLM errors are handled."""
- mock_llm = Mock()
- mock_llm.invoke.side_effect = Exception("LLM error")
-
- error_occurred = False
- try:
- mock_llm.invoke("test")
- except Exception:
- error_occurred = True
-
- assert error_occurred
-
- def test_topic_llm_response_parsing(self):
- """LLM response is parsed correctly."""
- response = "1. Climate Change\n2. Global Warming\n3. Carbon Emissions"
-
- lines = response.strip().split("\n")
- topics = [line.split(". ", 1)[1] for line in lines if ". " in line]
-
- assert len(topics) == 3
- assert "Climate Change" in topics